@openshift-migration-advisor/shared-components 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/report/ChartExportProvider.d.ts +3 -2
  2. package/dist/report/ChartExportProvider.d.ts.map +1 -1
  3. package/dist/report/ChartExportProvider.js +3 -3
  4. package/dist/report/ClustersOverview.d.ts +24 -0
  5. package/dist/report/ClustersOverview.d.ts.map +1 -0
  6. package/dist/report/ClustersOverview.js +228 -0
  7. package/dist/report/ClustersOverviewStyles.d.ts +12 -0
  8. package/dist/report/ClustersOverviewStyles.d.ts.map +1 -0
  9. package/dist/report/ClustersOverviewStyles.js +101 -0
  10. package/dist/report/CpuAndMemoryOverview.d.ts +19 -0
  11. package/dist/report/CpuAndMemoryOverview.d.ts.map +1 -0
  12. package/dist/report/CpuAndMemoryOverview.js +112 -0
  13. package/dist/report/captureChartElement.d.ts.map +1 -1
  14. package/dist/report/captureChartElement.js +28 -8
  15. package/dist/report/chartExport.d.ts +23 -0
  16. package/dist/report/chartExport.d.ts.map +1 -1
  17. package/dist/report/chartExport.js +20 -0
  18. package/dist/report/chartExportContext.d.ts +6 -2
  19. package/dist/report/chartExportContext.d.ts.map +1 -1
  20. package/dist/report/index.d.ts +4 -2
  21. package/dist/report/index.d.ts.map +1 -1
  22. package/dist/report/index.js +2 -0
  23. package/dist/report/pdfExport.d.ts +2 -2
  24. package/dist/report/pdfExport.d.ts.map +1 -1
  25. package/dist/report/pdfExport.js +52 -3
  26. package/package.json +2 -2
  27. package/src/report/ChartExportProvider.tsx +13 -5
  28. package/src/report/ClustersOverview.tsx +451 -0
  29. package/src/report/ClustersOverviewStyles.ts +110 -0
  30. package/src/report/CpuAndMemoryOverview.tsx +277 -0
  31. package/src/report/__tests__/ChartExportProvider.test.tsx +110 -2
  32. package/src/report/__tests__/ClustersOverview.test.tsx +241 -0
  33. package/src/report/__tests__/CpuAndMemoryOverview.test.tsx +200 -0
  34. package/src/report/__tests__/captureChartElement.test.ts +73 -0
  35. package/src/report/__tests__/chartExportPackagers.test.ts +75 -0
  36. package/src/report/captureChartElement.ts +37 -7
  37. package/src/report/chartExport.ts +40 -0
  38. package/src/report/chartExportContext.tsx +9 -1
  39. package/src/report/index.ts +12 -0
  40. package/src/report/pdfExport.ts +81 -2
@@ -0,0 +1,277 @@
1
+ import { css } from "@emotion/css";
2
+ import {
3
+ Card,
4
+ CardBody,
5
+ CardTitle,
6
+ Dropdown,
7
+ DropdownItem,
8
+ DropdownList,
9
+ Flex,
10
+ FlexItem,
11
+ MenuToggle,
12
+ type MenuToggleElement,
13
+ } from "@patternfly/react-core";
14
+ import { DataProcessorIcon } from "@patternfly/react-icons";
15
+ import type { FC, Ref } from "react";
16
+ import { useMemo, useState } from "react";
17
+ import {
18
+ MigrationDonutChart,
19
+ type MigrationDonutChartDatum,
20
+ type MigrationDonutChartLegendVariant,
21
+ } from "../charts/MigrationDonutChart.js";
22
+ import { CardEmptyState } from "./CardEmptyState.js";
23
+ import { ChartHeaderActions } from "./ChartDownloadButton.js";
24
+ import { ChartExportSurface } from "./ChartExportSurface.js";
25
+ import { chartExportViewsFromLabels } from "./chartExport.js";
26
+ import { REPORT_CARD_EMPTY_STATE_TITLES } from "./constants.js";
27
+ import { dashboardStyles } from "./dashboardStyles.js";
28
+
29
+ export interface CpuAndMemoryOverviewProps {
30
+ cpuTierDistribution?: Record<string, number>;
31
+ memoryTierDistribution?: Record<string, number>;
32
+ memoryTotalGB?: number;
33
+ cpuTotalCores?: number;
34
+ /**
35
+ * Memory-tier slice click. The argument is the distribution key.
36
+ * Agent-ui maps it to a VM memory filter; ui-app omits it.
37
+ */
38
+ onTierSelect?: (tierLabel: string) => void;
39
+ /** Center-title click. Agent-ui opens the VM list with no extra filters. */
40
+ onTitleClick?: () => void;
41
+ /** `"html"` in agent-ui; ui-app passes `"chart"`. */
42
+ legendVariant?: MigrationDonutChartLegendVariant;
43
+ }
44
+
45
+ type ViewMode = "memoryTiers" | "vcpuTiers";
46
+
47
+ const VIEW_MODE_LABELS: Record<ViewMode, string> = {
48
+ memoryTiers: "VM distribution by memory size tier",
49
+ vcpuTiers: "VM distribution by vCPU count tier",
50
+ };
51
+
52
+ const VIEW_SUBTITLES: Record<ViewMode, string> = {
53
+ memoryTiers: "Memory size tiers",
54
+ vcpuTiers: "vCPU count tiers",
55
+ };
56
+
57
+ /**
58
+ * Categorical order shared by the agent-ui and ui-app CPU/memory donuts.
59
+ */
60
+ const TIER_COLORS = [
61
+ "#0066cc",
62
+ "#5e40be",
63
+ "#b6a6e9",
64
+ "#73c5c5",
65
+ "#b98412",
66
+ "#28a745",
67
+ "#f0ad4e",
68
+ "#d9534f",
69
+ "#009596",
70
+ "#6a6e73",
71
+ ];
72
+
73
+ const CHART_ID = "cpu-memory-overview";
74
+ const CHART_TITLE = "CPU & memory";
75
+
76
+ const cardSubtitle = css`
77
+ color: var(--pf-t--global--text--color--subtle);
78
+ font-size: 0.85rem;
79
+ `;
80
+
81
+ const menuToggleMinWidth = css`
82
+ min-width: 290px;
83
+ `;
84
+
85
+ const titleRow = css`
86
+ width: 100%;
87
+ `;
88
+
89
+ const isViewMode = (value: string | number | undefined): value is ViewMode =>
90
+ value === "memoryTiers" || value === "vcpuTiers";
91
+
92
+ const tierSortKey = (label: string): number => {
93
+ const value = Number.parseInt(label.trim(), 10);
94
+ return Number.isFinite(value) ? value : Number.MAX_SAFE_INTEGER;
95
+ };
96
+
97
+ const hasUnit = (label: string, unit: "GB" | "cores"): boolean =>
98
+ unit === "GB" ? /gb$/i.test(label) : /cores?$/i.test(label);
99
+
100
+ const slicesFromDistribution = (
101
+ distribution: Record<string, number> | undefined,
102
+ unit: "GB" | "cores",
103
+ ): MigrationDonutChartDatum[] =>
104
+ Object.entries(distribution ?? {})
105
+ .filter(([, count]) => Number(count) > 0)
106
+ .sort(([left], [right]) => tierSortKey(left) - tierSortKey(right))
107
+ .map(([tier, count]) => {
108
+ const trimmed = tier.trim();
109
+ const name = hasUnit(trimmed, unit) ? trimmed : `${trimmed} ${unit}`;
110
+ const vmCount = Number(count);
111
+ return {
112
+ name,
113
+ count: vmCount,
114
+ countDisplay: `${vmCount} VMs`,
115
+ legendCategory: tier,
116
+ };
117
+ });
118
+
119
+ const legendFor = (categories: string[]): Record<string, string> => {
120
+ const legend: Record<string, string> = {};
121
+ categories.forEach((category, index) => {
122
+ const color = TIER_COLORS[index % TIER_COLORS.length];
123
+ if (color) {
124
+ legend[category] = color;
125
+ }
126
+ });
127
+ return legend;
128
+ };
129
+
130
+ export const CpuAndMemoryOverview: FC<CpuAndMemoryOverviewProps> = ({
131
+ cpuTierDistribution,
132
+ memoryTierDistribution,
133
+ memoryTotalGB,
134
+ cpuTotalCores,
135
+ onTierSelect,
136
+ onTitleClick,
137
+ legendVariant = "html",
138
+ }) => {
139
+ const [viewMode, setViewMode] = useState<ViewMode>("memoryTiers");
140
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
141
+
142
+ const memorySlices = useMemo(
143
+ () => slicesFromDistribution(memoryTierDistribution, "GB"),
144
+ [memoryTierDistribution],
145
+ );
146
+ const vcpuSlices = useMemo(
147
+ () => slicesFromDistribution(cpuTierDistribution, "cores"),
148
+ [cpuTierDistribution],
149
+ );
150
+
151
+ const activeSlices = viewMode === "memoryTiers" ? memorySlices : vcpuSlices;
152
+ const legend = useMemo(
153
+ () => legendFor(activeSlices.map((slice) => slice.legendCategory)),
154
+ [activeSlices],
155
+ );
156
+ const totalVMs = useMemo(
157
+ () => activeSlices.reduce((sum, slice) => sum + slice.count, 0),
158
+ [activeSlices],
159
+ );
160
+
161
+ const chartTitle = `${CHART_TITLE} — ${VIEW_MODE_LABELS[viewMode]}`;
162
+ const subTitle =
163
+ viewMode === "memoryTiers"
164
+ ? typeof memoryTotalGB === "number"
165
+ ? `${memoryTotalGB.toLocaleString()} GB`
166
+ : undefined
167
+ : typeof cpuTotalCores === "number"
168
+ ? `${cpuTotalCores.toLocaleString()} Cores`
169
+ : undefined;
170
+ const emptyTitle =
171
+ viewMode === "memoryTiers"
172
+ ? REPORT_CARD_EMPTY_STATE_TITLES.memory
173
+ : REPORT_CARD_EMPTY_STATE_TITLES.cpu;
174
+
175
+ return (
176
+ <ChartExportSurface
177
+ id={CHART_ID}
178
+ title={chartTitle}
179
+ exportViews={chartExportViewsFromLabels(CHART_TITLE, VIEW_MODE_LABELS)}
180
+ activeExportViewId={viewMode}
181
+ onExportViewChange={(viewId) => {
182
+ if (isViewMode(viewId)) {
183
+ setViewMode(viewId);
184
+ }
185
+ }}
186
+ >
187
+ <Card className={dashboardStyles.card}>
188
+ <CardTitle>
189
+ <Flex
190
+ className={titleRow}
191
+ justifyContent={{ default: "justifyContentSpaceBetween" }}
192
+ alignItems={{ default: "alignItemsCenter" }}
193
+ >
194
+ <FlexItem>
195
+ <div>
196
+ <div>
197
+ <DataProcessorIcon /> {CHART_TITLE}
198
+ </div>
199
+ <div className={cardSubtitle}>{VIEW_SUBTITLES[viewMode]}</div>
200
+ </div>
201
+ </FlexItem>
202
+ <ChartHeaderActions chartId={CHART_ID} title={chartTitle}>
203
+ <Dropdown
204
+ isOpen={isDropdownOpen}
205
+ onSelect={(_event, value) => {
206
+ if (isViewMode(value)) {
207
+ setViewMode(value);
208
+ }
209
+ setIsDropdownOpen(false);
210
+ }}
211
+ onOpenChange={setIsDropdownOpen}
212
+ toggle={(toggleRef: Ref<MenuToggleElement>) => (
213
+ <MenuToggle
214
+ ref={toggleRef}
215
+ onClick={() => setIsDropdownOpen((open) => !open)}
216
+ isExpanded={isDropdownOpen}
217
+ className={menuToggleMinWidth}
218
+ >
219
+ {VIEW_MODE_LABELS[viewMode]}
220
+ </MenuToggle>
221
+ )}
222
+ >
223
+ <DropdownList>
224
+ <DropdownItem value="memoryTiers" key="memoryTiers">
225
+ {VIEW_MODE_LABELS.memoryTiers}
226
+ </DropdownItem>
227
+ <DropdownItem value="vcpuTiers" key="vcpuTiers">
228
+ {VIEW_MODE_LABELS.vcpuTiers}
229
+ </DropdownItem>
230
+ </DropdownList>
231
+ </Dropdown>
232
+ </ChartHeaderActions>
233
+ </Flex>
234
+ </CardTitle>
235
+ <CardBody className={dashboardStyles.cardBodyScrollable}>
236
+ {activeSlices.length === 0 ? (
237
+ <CardEmptyState title={emptyTitle} />
238
+ ) : (
239
+ <MigrationDonutChart
240
+ legendVariant={legendVariant}
241
+ data={activeSlices}
242
+ legend={legend}
243
+ height={300}
244
+ width={420}
245
+ donutThickness={18}
246
+ titleFontSize={34}
247
+ title={`${totalVMs} VMs`}
248
+ subTitle={subTitle}
249
+ subTitleColor="var(--pf-t--global--text--color--subtle)"
250
+ legendLabelFormatter={({ x, countDisplay }) =>
251
+ `${x} (${countDisplay})`
252
+ }
253
+ tooltipLabelFormatter={({ datum, percent }) =>
254
+ `${datum.countDisplay}\n${percent.toFixed(1)}%`
255
+ }
256
+ itemsPerRow={
257
+ legendVariant === "chart"
258
+ ? Math.ceil(activeSlices.length / 2)
259
+ : undefined
260
+ }
261
+ labelFontSize={legendVariant === "chart" ? 18 : undefined}
262
+ marginLeft={legendVariant === "chart" ? "52%" : undefined}
263
+ onItemClick={
264
+ viewMode === "memoryTiers" && onTierSelect
265
+ ? (item) => onTierSelect(item.legendCategory)
266
+ : undefined
267
+ }
268
+ onTitleClick={onTitleClick}
269
+ />
270
+ )}
271
+ </CardBody>
272
+ </Card>
273
+ </ChartExportSurface>
274
+ );
275
+ };
276
+
277
+ CpuAndMemoryOverview.displayName = "CpuAndMemoryOverview";
@@ -101,12 +101,18 @@ function DownloadChartButton({ id }: { id: string }): JSX.Element {
101
101
  );
102
102
  }
103
103
 
104
- function DownloadPdfButton(): JSX.Element {
104
+ function DownloadPdfButton({
105
+ extraPages,
106
+ }: {
107
+ extraPages?: Parameters<
108
+ NonNullable<ReturnType<typeof useChartExport>>["downloadPdf"]
109
+ >[1];
110
+ }): JSX.Element {
105
111
  const exportApi = useChartExport();
106
112
  return (
107
113
  <button
108
114
  type="button"
109
- onClick={() => void exportApi?.downloadPdf("Overview")}
115
+ onClick={() => void exportApi?.downloadPdf("Overview", extraPages)}
110
116
  >
111
117
  Download pdf
112
118
  </button>
@@ -181,6 +187,46 @@ describe("ChartExportProvider", () => {
181
187
  expect(downloadFile).toHaveBeenCalledWith(expect.any(Blob), "disks.png");
182
188
  });
183
189
 
190
+ it("does not change the live theme while exporting", async () => {
191
+ const user = userEvent.setup();
192
+ document.documentElement.classList.add("pf-v6-theme-dark");
193
+ const capture = vi.fn(async () => {
194
+ expect(
195
+ document.documentElement.classList.contains("pf-v6-theme-dark"),
196
+ ).toBe(true);
197
+ return fakeCanvas();
198
+ });
199
+ const downloadFile = vi.fn();
200
+
201
+ render(
202
+ <ChartExportProvider
203
+ capture={capture}
204
+ encodePng={async () => new Blob(["png"])}
205
+ zipFiles={async () => new Blob(["zip"])}
206
+ downloadFile={downloadFile}
207
+ getZipFilename={() => "charts.zip"}
208
+ >
209
+ <RegisteredChart id="storage" title="Disks" />
210
+ <DownloadChartButton id="storage" />
211
+ <DownloadAllButton />
212
+ </ChartExportProvider>,
213
+ );
214
+
215
+ await user.click(screen.getByRole("button", { name: "Download storage" }));
216
+ await waitFor(() =>
217
+ expect(downloadFile).toHaveBeenCalledWith(expect.any(Blob), "disks.png"),
218
+ );
219
+ await user.click(screen.getByRole("button", { name: "Download all" }));
220
+ await waitFor(() =>
221
+ expect(downloadFile).toHaveBeenCalledWith(expect.any(Blob), "charts.zip"),
222
+ );
223
+
224
+ expect(
225
+ document.documentElement.classList.contains("pf-v6-theme-dark"),
226
+ ).toBe(true);
227
+ document.documentElement.classList.remove("pf-v6-theme-dark");
228
+ });
229
+
184
230
  it("re-registers charts after React Strict Mode's extra effect cycle", async () => {
185
231
  const user = userEvent.setup();
186
232
  const capture = vi.fn(async () => fakeCanvas());
@@ -236,6 +282,68 @@ describe("ChartExportProvider", () => {
236
282
  expect(downloadFile).toHaveBeenCalledWith(expect.any(Blob), "report.pdf");
237
283
  });
238
284
 
285
+ it("forwards extra text pages (e.g. cluster sizing recommendations) to the pdf builder", async () => {
286
+ const user = userEvent.setup();
287
+ const capture = vi.fn(async () => fakeCanvas());
288
+ const buildPdf = vi.fn(async () => new Blob(["pdf"]));
289
+ const downloadFile = vi.fn();
290
+ const extraPages = [
291
+ {
292
+ title: "Cluster sizing recommendations",
293
+ items: [
294
+ { label: "Cluster name", value: "cluster-1" },
295
+ { label: "Target platform", value: "Bare metal" },
296
+ ],
297
+ footer: "Note: estimates only.",
298
+ },
299
+ ];
300
+
301
+ render(
302
+ <ChartExportProvider
303
+ capture={capture}
304
+ zipFiles={vi.fn()}
305
+ buildPdf={buildPdf}
306
+ downloadFile={downloadFile}
307
+ getPdfFilename={() => "report.pdf"}
308
+ >
309
+ <RegisteredChart id="storage" title="Disks" />
310
+ <DownloadPdfButton extraPages={extraPages} />
311
+ </ChartExportProvider>,
312
+ );
313
+
314
+ await user.click(screen.getByRole("button", { name: "Download pdf" }));
315
+
316
+ expect(buildPdf).toHaveBeenCalledTimes(1);
317
+ expect(buildPdf.mock.calls[0]?.[2]).toEqual(extraPages);
318
+ expect(downloadFile).toHaveBeenCalledWith(expect.any(Blob), "report.pdf");
319
+ });
320
+
321
+ it("builds a PDF from extra text pages alone when no charts are registered", async () => {
322
+ const user = userEvent.setup();
323
+ const buildPdf = vi.fn(async () => new Blob(["pdf"]));
324
+ const downloadFile = vi.fn();
325
+ const extraPages = [{ title: "Cluster sizing recommendations", items: [] }];
326
+
327
+ render(
328
+ <ChartExportProvider
329
+ capture={vi.fn()}
330
+ zipFiles={vi.fn()}
331
+ buildPdf={buildPdf}
332
+ downloadFile={downloadFile}
333
+ getPdfFilename={() => "report.pdf"}
334
+ >
335
+ <DownloadPdfButton extraPages={extraPages} />
336
+ </ChartExportProvider>,
337
+ );
338
+
339
+ await user.click(screen.getByRole("button", { name: "Download pdf" }));
340
+
341
+ expect(buildPdf).toHaveBeenCalledTimes(1);
342
+ expect(buildPdf.mock.calls[0]?.[0]).toEqual([]);
343
+ expect(buildPdf.mock.calls[0]?.[2]).toEqual(extraPages);
344
+ expect(downloadFile).toHaveBeenCalledWith(expect.any(Blob), "report.pdf");
345
+ });
346
+
239
347
  it("builds HTML from the same captured canvases", async () => {
240
348
  const user = userEvent.setup();
241
349
  const capture = vi.fn(async () => fakeCanvas());
@@ -0,0 +1,241 @@
1
+ import "@testing-library/jest-dom";
2
+ import {
3
+ chart_color_blue_300,
4
+ chart_color_purple_100,
5
+ chart_color_purple_300,
6
+ chart_color_teal_200,
7
+ chart_color_yellow_400,
8
+ } from "@patternfly/react-tokens";
9
+ import { cleanup, render, screen } from "@testing-library/react";
10
+ import userEvent from "@testing-library/user-event";
11
+ import { afterEach, describe, expect, it, vi } from "vitest";
12
+ import type { MigrationDonutChartProps } from "../../charts/MigrationDonutChart.js";
13
+ import {
14
+ ClustersOverview,
15
+ type InventoryDataLike,
16
+ } from "../ClustersOverview.js";
17
+
18
+ const donutProps = vi.hoisted(() => ({
19
+ current: null as MigrationDonutChartProps | null,
20
+ }));
21
+
22
+ vi.mock("../../charts/MigrationDonutChart.js", () => ({
23
+ MigrationDonutChart: (props: MigrationDonutChartProps): JSX.Element => {
24
+ donutProps.current = props;
25
+ return (
26
+ <div data-testid="clusters-donut">
27
+ {props.title} {props.subTitle}
28
+ </div>
29
+ );
30
+ },
31
+ }));
32
+
33
+ afterEach(() => {
34
+ donutProps.current = null;
35
+ cleanup();
36
+ });
37
+
38
+ const renderedDonut = (): MigrationDonutChartProps => {
39
+ const props = donutProps.current;
40
+ if (!props) {
41
+ throw new Error("expected a clusters donut to render");
42
+ }
43
+ return props;
44
+ };
45
+
46
+ const selectView = async (name: string): Promise<void> => {
47
+ const user = userEvent.setup();
48
+ await user.click(
49
+ screen.getByRole("button", { name: "VM distribution by cluster" }),
50
+ );
51
+ await user.click(screen.getByRole("menuitem", { name }));
52
+ };
53
+
54
+ describe("ClustersOverview", () => {
55
+ it("shows the cluster empty state when no clusters were collected", () => {
56
+ render(<ClustersOverview />);
57
+
58
+ expect(screen.getByText("Clusters")).toBeInTheDocument();
59
+ expect(screen.getByText("Top 5 clusters")).toBeInTheDocument();
60
+ expect(screen.getByText("Cluster data not collected")).toBeInTheDocument();
61
+ expect(screen.queryByTestId("clusters-donut")).not.toBeInTheDocument();
62
+ });
63
+
64
+ it("keeps the top 4 clusters and rolls the rest into one slice", () => {
65
+ render(
66
+ <ClustersOverview
67
+ clusters={{
68
+ a: { vms: { total: 10 } },
69
+ b: { vms: { total: 8 } },
70
+ c: { vms: { total: 6 } },
71
+ d: { vms: { total: 4 } },
72
+ e: { vms: { total: 3 } },
73
+ f: {},
74
+ g: { vms: { total: Number.NaN } },
75
+ h: { vms: { total: -2 } },
76
+ }}
77
+ />,
78
+ );
79
+
80
+ expect(screen.getByTestId("clusters-donut")).toHaveTextContent("31 VMs");
81
+
82
+ const props = renderedDonut();
83
+ expect(props.data.map((slice) => [slice.name, slice.count])).toEqual([
84
+ ["Cluster 1", 10],
85
+ ["Cluster 2", 8],
86
+ ["Cluster 3", 6],
87
+ ["Cluster 4", 4],
88
+ ["Rest of clusters", 3],
89
+ ]);
90
+ expect(props.data[0]?.countDisplay).toBe("10 VMs");
91
+ expect(props.legend).toEqual({
92
+ "Cluster 1": chart_color_blue_300.value,
93
+ "Cluster 2": chart_color_purple_300.value,
94
+ "Cluster 3": chart_color_purple_100.value,
95
+ "Cluster 4": chart_color_teal_200.value,
96
+ "Rest of clusters": chart_color_yellow_400.value,
97
+ });
98
+ expect(props.legendVariant).toBe("html");
99
+ expect(props.height).toBe(300);
100
+ expect(props.width).toBe(420);
101
+ expect(props.donutThickness).toBe(18);
102
+ expect(props.titleFontSize).toBe(34);
103
+ expect(props.subTitleColor).toBe(
104
+ "var(--pf-t--global--text--color--subtle)",
105
+ );
106
+ expect(
107
+ props.tooltipLabelFormatter?.({
108
+ datum: {
109
+ x: "Cluster 1",
110
+ y: 10,
111
+ countDisplay: "10 VMs",
112
+ legendCategory: "Cluster 1",
113
+ },
114
+ percent: 32.258,
115
+ total: 31,
116
+ }),
117
+ ).toBe("10 VMs\n32.3%");
118
+ });
119
+
120
+ it("passes the chart legend variant through", () => {
121
+ render(
122
+ <ClustersOverview
123
+ legendVariant="chart"
124
+ clusters={{ a: { vms: { total: 2 } } }}
125
+ />,
126
+ );
127
+
128
+ expect(renderedDonut().legendVariant).toBe("chart");
129
+ });
130
+
131
+ it("plots cluster counts per data center and ignores non-numeric entries", async () => {
132
+ render(
133
+ <ClustersOverview
134
+ clustersPerDatacenter={
135
+ [1, 5, Number.NaN, 2, 4, 3, -1, "3"] as unknown as number[]
136
+ }
137
+ clusters={{ a: { vms: { total: 1 } } }}
138
+ />,
139
+ );
140
+
141
+ await selectView("Cluster distribution by data center");
142
+
143
+ expect(screen.getByText("Top 5 datacenters")).toBeInTheDocument();
144
+ expect(screen.getByTestId("clusters-donut")).toHaveTextContent(
145
+ "15 Clusters",
146
+ );
147
+
148
+ const props = renderedDonut();
149
+ expect(props.data.map((slice) => [slice.name, slice.count])).toEqual([
150
+ ["Data center 1", 5],
151
+ ["Data center 2", 4],
152
+ ["Data center 3", 3],
153
+ ["Data center 4", 2],
154
+ ["Rest of datacenters", 1],
155
+ ]);
156
+ expect(props.data[4]?.countDisplay).toBe("1 clusters");
157
+ expect(props.subTitle).toBe("Clusters");
158
+ });
159
+
160
+ it("shows the cluster empty state when datacenter counts are unusable", async () => {
161
+ render(
162
+ <ClustersOverview
163
+ clustersPerDatacenter={"nope" as unknown as number[]}
164
+ clusters={{ a: { vms: { total: 1 } } }}
165
+ />,
166
+ );
167
+
168
+ await selectView("Cluster distribution by data center");
169
+
170
+ expect(screen.getByText("Cluster data not collected")).toBeInTheDocument();
171
+ expect(screen.queryByTestId("clusters-donut")).not.toBeInTheDocument();
172
+ });
173
+
174
+ it("renders the top 5 CPU overcommitment ratios as boxes and a legend", async () => {
175
+ render(
176
+ <ClustersOverview
177
+ clusters={{
178
+ low: { infra: { cpuOverCommitment: 0.5 } },
179
+ high: { infra: { cpuOverCommitment: 8 } },
180
+ ratio: { infra: { cpuOverCommitment: " 1 : 4.25 " } },
181
+ numericString: { infra: { cpuOverCommitment: "3.5" } },
182
+ integer: { infra: { cpuOverCommitment: 2 } },
183
+ sixth: { infra: { cpuOverCommitment: 1 } },
184
+ }}
185
+ />,
186
+ );
187
+
188
+ await selectView("Cluster CPU over commitment");
189
+
190
+ expect(screen.queryByTestId("clusters-donut")).not.toBeInTheDocument();
191
+ expect(screen.getByText("8")).toHaveStyle({
192
+ background: chart_color_blue_300.value,
193
+ });
194
+ expect(screen.getByText("4.25")).toHaveStyle({
195
+ background: chart_color_purple_300.value,
196
+ });
197
+ expect(screen.getByText("3.5")).toHaveStyle({
198
+ background: chart_color_purple_100.value,
199
+ });
200
+ expect(screen.getByText("2")).toHaveStyle({
201
+ background: chart_color_teal_200.value,
202
+ });
203
+ expect(screen.getByText("1")).toHaveStyle({
204
+ background: chart_color_yellow_400.value,
205
+ });
206
+ expect(screen.queryByText("0.5")).not.toBeInTheDocument();
207
+ expect(screen.getByText("Cluster 1 (8)")).toBeInTheDocument();
208
+ expect(screen.getByText("Cluster 5 (1)")).toBeInTheDocument();
209
+ expect(screen.queryByText("Cluster 6 (0.5)")).not.toBeInTheDocument();
210
+ });
211
+
212
+ it("does not crash when cpuOverCommitment is missing or an unexpected shape", async () => {
213
+ const clusters: Record<string, InventoryDataLike> = {
214
+ missing: {},
215
+ blank: { infra: { cpuOverCommitment: " " } },
216
+ garbage: { infra: { cpuOverCommitment: "lots" } },
217
+ negative: { infra: { cpuOverCommitment: -2 } },
218
+ objectRatio: { infra: { cpuOverCommitment: { ratio: 4 } } },
219
+ nonObject: "cluster" as unknown as InventoryDataLike,
220
+ };
221
+
222
+ render(
223
+ <ClustersOverview
224
+ clusters={{
225
+ ...clusters,
226
+ stringInfra: {
227
+ infra: "nope" as unknown as InventoryDataLike["infra"],
228
+ },
229
+ arrayClusters: ["1:4"] as unknown as InventoryDataLike,
230
+ }}
231
+ />,
232
+ );
233
+
234
+ await selectView("Cluster CPU over commitment");
235
+
236
+ expect(
237
+ screen.getByText("CPU overcommitment data not collected"),
238
+ ).toBeInTheDocument();
239
+ expect(screen.queryByTestId("clusters-donut")).not.toBeInTheDocument();
240
+ });
241
+ });