@openshift-migration-advisor/shared-components 0.24.0 → 0.25.0-1c27267d2ea6

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 (143) hide show
  1. package/README.md +31 -0
  2. package/dist/charts/index.d.ts +1 -1
  3. package/dist/charts/index.d.ts.map +1 -1
  4. package/dist/forms/RadioButtonFormGroup.d.ts.map +1 -1
  5. package/dist/forms/RadioButtonFormGroup.js +2 -2
  6. package/dist/report/ChartDownloadButton.d.ts +11 -0
  7. package/dist/report/ChartDownloadButton.d.ts.map +1 -0
  8. package/dist/report/ChartDownloadButton.js +24 -0
  9. package/dist/report/ChartExportProvider.d.ts +22 -0
  10. package/dist/report/ChartExportProvider.d.ts.map +1 -0
  11. package/dist/report/ChartExportProvider.js +222 -0
  12. package/dist/report/ChartExportSurface.d.ts +12 -0
  13. package/dist/report/ChartExportSurface.d.ts.map +1 -0
  14. package/dist/report/ChartExportSurface.js +32 -0
  15. package/dist/report/ErrorTable.d.ts +18 -0
  16. package/dist/report/ErrorTable.d.ts.map +1 -0
  17. package/dist/report/ErrorTable.js +20 -0
  18. package/dist/report/FeatureStatusBadge.d.ts +7 -0
  19. package/dist/report/FeatureStatusBadge.d.ts.map +1 -0
  20. package/dist/report/FeatureStatusBadge.js +13 -0
  21. package/dist/report/HostPowerStates.d.ts +8 -0
  22. package/dist/report/HostPowerStates.d.ts.map +1 -0
  23. package/dist/report/HostPowerStates.js +11 -0
  24. package/dist/report/InfrastructureSummary.d.ts +7 -0
  25. package/dist/report/InfrastructureSummary.d.ts.map +1 -0
  26. package/dist/report/InfrastructureSummary.js +9 -0
  27. package/dist/report/NetworkOverview.d.ts +31 -0
  28. package/dist/report/NetworkOverview.d.ts.map +1 -0
  29. package/dist/report/NetworkOverview.js +201 -0
  30. package/dist/report/OSDistribution.d.ts +0 -2
  31. package/dist/report/OSDistribution.d.ts.map +1 -1
  32. package/dist/report/OSDistribution.js +10 -15
  33. package/dist/report/OsSupportTiersHelpPopover.d.ts.map +1 -1
  34. package/dist/report/OsSupportTiersHelpPopover.js +2 -31
  35. package/dist/report/OsUpgradeNotice.d.ts.map +1 -1
  36. package/dist/report/OsUpgradeNotice.js +1 -5
  37. package/dist/report/OsUpgradeRecommendationPopover.d.ts +0 -1
  38. package/dist/report/OsUpgradeRecommendationPopover.d.ts.map +1 -1
  39. package/dist/report/OsUpgradeRecommendationPopover.js +4 -3
  40. package/dist/report/PowerStateCard.d.ts +16 -0
  41. package/dist/report/PowerStateCard.d.ts.map +1 -0
  42. package/dist/report/PowerStateCard.js +9 -0
  43. package/dist/report/ReportExportMenu.d.ts +19 -0
  44. package/dist/report/ReportExportMenu.d.ts.map +1 -0
  45. package/dist/report/ReportExportMenu.js +31 -0
  46. package/dist/report/ReportTable.d.ts +14 -0
  47. package/dist/report/ReportTable.d.ts.map +1 -0
  48. package/dist/report/ReportTable.js +23 -0
  49. package/dist/report/SupportTierBadge.d.ts +0 -1
  50. package/dist/report/SupportTierBadge.d.ts.map +1 -1
  51. package/dist/report/SupportTierBadge.js +1 -19
  52. package/dist/report/VCenterClusterDetails.d.ts +9 -0
  53. package/dist/report/VCenterClusterDetails.d.ts.map +1 -0
  54. package/dist/report/VCenterClusterDetails.js +31 -0
  55. package/dist/report/VmPowerStates.d.ts +8 -0
  56. package/dist/report/VmPowerStates.d.ts.map +1 -0
  57. package/dist/report/VmPowerStates.js +11 -0
  58. package/dist/report/captureChartElement.d.ts +8 -0
  59. package/dist/report/captureChartElement.d.ts.map +1 -0
  60. package/dist/report/captureChartElement.js +284 -0
  61. package/dist/report/chartExport.d.ts +57 -0
  62. package/dist/report/chartExport.d.ts.map +1 -0
  63. package/dist/report/chartExport.js +162 -0
  64. package/dist/report/chartExportContext.d.ts +28 -0
  65. package/dist/report/chartExportContext.d.ts.map +1 -0
  66. package/dist/report/chartExportContext.js +36 -0
  67. package/dist/report/chartExportFilenames.d.ts +4 -0
  68. package/dist/report/chartExportFilenames.d.ts.map +1 -0
  69. package/dist/report/chartExportFilenames.js +16 -0
  70. package/dist/report/constants.d.ts +3 -0
  71. package/dist/report/constants.d.ts.map +1 -1
  72. package/dist/report/constants.js +3 -0
  73. package/dist/report/dashboardStyles.d.ts +0 -4
  74. package/dist/report/dashboardStyles.d.ts.map +1 -1
  75. package/dist/report/dashboardStyles.js +0 -19
  76. package/dist/report/htmlExport.d.ts +9 -0
  77. package/dist/report/htmlExport.d.ts.map +1 -0
  78. package/dist/report/htmlExport.js +65 -0
  79. package/dist/report/index.d.ts +26 -0
  80. package/dist/report/index.d.ts.map +1 -1
  81. package/dist/report/index.js +24 -0
  82. package/dist/report/infrastructureSummaryModel.d.ts +82 -0
  83. package/dist/report/infrastructureSummaryModel.d.ts.map +1 -0
  84. package/dist/report/infrastructureSummaryModel.js +139 -0
  85. package/dist/report/pdfExport.d.ts +3 -0
  86. package/dist/report/pdfExport.d.ts.map +1 -0
  87. package/dist/report/pdfExport.js +82 -0
  88. package/dist/report/pdfPage.d.ts +15 -0
  89. package/dist/report/pdfPage.d.ts.map +1 -0
  90. package/dist/report/pdfPage.js +44 -0
  91. package/dist/report/powerStates.d.ts +11 -0
  92. package/dist/report/powerStates.d.ts.map +1 -0
  93. package/dist/report/powerStates.js +113 -0
  94. package/dist/report/reportExportOptions.d.ts +17 -0
  95. package/dist/report/reportExportOptions.d.ts.map +1 -0
  96. package/dist/report/reportExportOptions.js +31 -0
  97. package/dist/report/zipChartPngs.d.ts +3 -0
  98. package/dist/report/zipChartPngs.d.ts.map +1 -0
  99. package/dist/report/zipChartPngs.js +8 -0
  100. package/package.json +7 -2
  101. package/src/charts/index.ts +1 -0
  102. package/src/forms/RadioButtonFormGroup.tsx +10 -3
  103. package/src/report/ChartDownloadButton.tsx +59 -0
  104. package/src/report/ChartExportProvider.tsx +384 -0
  105. package/src/report/ChartExportSurface.tsx +60 -0
  106. package/src/report/ErrorTable.tsx +85 -0
  107. package/src/report/FeatureStatusBadge.tsx +30 -0
  108. package/src/report/HostPowerStates.tsx +38 -0
  109. package/src/report/InfrastructureSummary.tsx +73 -0
  110. package/src/report/NetworkOverview.tsx +405 -0
  111. package/src/report/OSDistribution.tsx +96 -99
  112. package/src/report/OsSupportTiersHelpPopover.tsx +32 -62
  113. package/src/report/OsUpgradeNotice.tsx +1 -7
  114. package/src/report/OsUpgradeRecommendationPopover.tsx +3 -4
  115. package/src/report/PowerStateCard.tsx +86 -0
  116. package/src/report/ReportExportMenu.tsx +119 -0
  117. package/src/report/ReportTable.tsx +81 -0
  118. package/src/report/SupportTierBadge.tsx +12 -38
  119. package/src/report/VCenterClusterDetails.tsx +233 -0
  120. package/src/report/VmPowerStates.tsx +38 -0
  121. package/src/report/__tests__/ChartExportProvider.test.tsx +474 -0
  122. package/src/report/__tests__/HostPowerStates.test.tsx +47 -0
  123. package/src/report/__tests__/InfrastructureSummary.test.tsx +126 -0
  124. package/src/report/__tests__/NetworkOverview.test.tsx +269 -0
  125. package/src/report/__tests__/OSDistribution.test.tsx +10 -11
  126. package/src/report/__tests__/captureChartElement.test.ts +132 -0
  127. package/src/report/__tests__/chartExportPackagers.test.ts +224 -0
  128. package/src/report/__tests__/infrastructureSummaryModel.test.ts +224 -0
  129. package/src/report/__tests__/powerStates.test.ts +70 -0
  130. package/src/report/captureChartElement.ts +368 -0
  131. package/src/report/chartExport.ts +237 -0
  132. package/src/report/chartExportContext.tsx +84 -0
  133. package/src/report/chartExportFilenames.ts +21 -0
  134. package/src/report/constants.ts +3 -0
  135. package/src/report/dashboardStyles.ts +0 -23
  136. package/src/report/htmlExport.ts +83 -0
  137. package/src/report/index.ts +142 -0
  138. package/src/report/infrastructureSummaryModel.ts +281 -0
  139. package/src/report/pdfExport.ts +154 -0
  140. package/src/report/pdfPage.ts +83 -0
  141. package/src/report/powerStates.ts +169 -0
  142. package/src/report/reportExportOptions.ts +53 -0
  143. package/src/report/zipChartPngs.ts +10 -0
@@ -0,0 +1,113 @@
1
+ const HOST_POWER_CATEGORIES = [
2
+ "Powered on",
3
+ "Powered off",
4
+ "Standby",
5
+ "Not responding",
6
+ "Maintenance",
7
+ ];
8
+ const HOST_POWER_KEY_ALIASES = {
9
+ poweredon: "Powered on",
10
+ powered_on: "Powered on",
11
+ green: "Powered on",
12
+ poweredoff: "Powered off",
13
+ powered_off: "Powered off",
14
+ standby: "Standby",
15
+ stand_by: "Standby",
16
+ notresponding: "Not responding",
17
+ not_responding: "Not responding",
18
+ gray: "Not responding",
19
+ grey: "Not responding",
20
+ red: "Not responding",
21
+ maintenance: "Maintenance",
22
+ inmaintenance: "Maintenance",
23
+ inmaintenancemode: "Maintenance",
24
+ };
25
+ export const HOST_POWER_COLORS = {
26
+ "Powered on": "#0066cc",
27
+ "Powered off": "#dca614",
28
+ Standby: "#f0ab00",
29
+ "Not responding": "#c9190b",
30
+ Maintenance: "#002f5d",
31
+ };
32
+ const VM_POWER_CATEGORIES = ["Powered off", "Powered on", "Suspended"];
33
+ const VM_POWER_KEY_ALIASES = {
34
+ poweredoff: "Powered off",
35
+ powered_off: "Powered off",
36
+ poweredon: "Powered on",
37
+ powered_on: "Powered on",
38
+ suspended: "Suspended",
39
+ };
40
+ export const VM_POWER_COLORS = {
41
+ "Powered off": "#0066cc",
42
+ "Powered on": "#dca614",
43
+ Suspended: "#5e40be",
44
+ };
45
+ const OTHER_COLOR = "#6a6e73";
46
+ const normalizeKey = (key) => key
47
+ .trim()
48
+ .toLowerCase()
49
+ .replace(/[\s-]+/g, "");
50
+ const formatUnknownLabel = (key) => {
51
+ const spaced = key
52
+ .replace(/[_-]+/g, " ")
53
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
54
+ .trim();
55
+ if (!spaced) {
56
+ return "Unknown";
57
+ }
58
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
59
+ };
60
+ const toSlice = (name, count, unit) => ({
61
+ name,
62
+ count,
63
+ legendCategory: name,
64
+ countDisplay: `${count} ${count === 1 ? unit.replace(/s$/, "") : unit}`,
65
+ });
66
+ const sumCounts = (counts) => Object.values(counts).reduce((total, count) => total + (count || 0), 0);
67
+ export const buildHostPowerStateChart = (hostPowerStates) => {
68
+ const counts = Object.fromEntries(HOST_POWER_CATEGORIES.map((category) => [category, 0]));
69
+ for (const [key, count] of Object.entries(hostPowerStates ?? {})) {
70
+ const mapped = HOST_POWER_KEY_ALIASES[normalizeKey(key)];
71
+ const label = mapped ?? formatUnknownLabel(key);
72
+ counts[label] = (counts[label] ?? 0) + (count || 0);
73
+ }
74
+ const orderedLabels = [
75
+ ...HOST_POWER_CATEGORIES,
76
+ ...Object.keys(counts).filter((label) => !HOST_POWER_CATEGORIES.includes(label)),
77
+ ];
78
+ const slices = orderedLabels.map((label) => toSlice(label, counts[label] ?? 0, "hosts"));
79
+ const legend = {};
80
+ for (const label of orderedLabels) {
81
+ legend[label] = HOST_POWER_COLORS[label] ?? OTHER_COLOR;
82
+ }
83
+ return {
84
+ slices,
85
+ legend,
86
+ total: sumCounts(counts),
87
+ };
88
+ };
89
+ export const buildVmPowerStateChart = (powerStates) => {
90
+ const counts = {
91
+ "Powered off": 0,
92
+ "Powered on": 0,
93
+ };
94
+ for (const [key, count] of Object.entries(powerStates ?? {})) {
95
+ const mapped = VM_POWER_KEY_ALIASES[normalizeKey(key)];
96
+ const label = mapped ?? formatUnknownLabel(key);
97
+ counts[label] = (counts[label] ?? 0) + (count || 0);
98
+ }
99
+ const orderedLabels = [
100
+ ...VM_POWER_CATEGORIES.filter((category) => category !== "Suspended" || (counts[category] ?? 0) > 0),
101
+ ...Object.keys(counts).filter((label) => !VM_POWER_CATEGORIES.includes(label)),
102
+ ];
103
+ const slices = orderedLabels.map((label) => toSlice(label, counts[label] ?? 0, "VMs"));
104
+ const legend = {};
105
+ for (const label of orderedLabels) {
106
+ legend[label] = VM_POWER_COLORS[label] ?? OTHER_COLOR;
107
+ }
108
+ return {
109
+ slices,
110
+ legend,
111
+ total: sumCounts(counts),
112
+ };
113
+ };
@@ -0,0 +1,17 @@
1
+ export interface ReportExportOption {
2
+ key: string;
3
+ label: string;
4
+ description?: string;
5
+ onSelect: () => void;
6
+ isDisabled?: boolean;
7
+ }
8
+ export interface StandardReportExportHandlers {
9
+ onExportPdf?: () => void;
10
+ onExportPng?: () => void;
11
+ onExportHtml?: () => void;
12
+ }
13
+ /**
14
+ * Standard report-download actions. Omit a handler to hide that format.
15
+ */
16
+ export declare const standardReportExportOptions: ({ onExportPdf, onExportPng, onExportHtml, }: StandardReportExportHandlers) => ReportExportOption[];
17
+ //# sourceMappingURL=reportExportOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reportExportOptions.d.ts","sourceRoot":"","sources":["../../src/report/reportExportOptions.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,MAAM,WAAW,4BAA4B;IAC3C,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;CAC3B;AAED;;GAEG;AACH,eAAO,MAAM,2BAA2B,GAAI,6CAIzC,4BAA4B,KAAG,kBAAkB,EA+BnD,CAAC"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Standard report-download actions. Omit a handler to hide that format.
3
+ */
4
+ export const standardReportExportOptions = ({ onExportPdf, onExportPng, onExportHtml, }) => {
5
+ const options = [];
6
+ if (onExportPdf) {
7
+ options.push({
8
+ key: "pdf",
9
+ label: "PDF",
10
+ description: "Export the report as a PDF",
11
+ onSelect: onExportPdf,
12
+ });
13
+ }
14
+ if (onExportHtml) {
15
+ options.push({
16
+ key: "html",
17
+ label: "HTML",
18
+ description: "Export the report as HTML",
19
+ onSelect: onExportHtml,
20
+ });
21
+ }
22
+ if (onExportPng) {
23
+ options.push({
24
+ key: "png",
25
+ label: "PNG",
26
+ description: "Download all charts as PNG files",
27
+ onSelect: onExportPng,
28
+ });
29
+ }
30
+ return options;
31
+ };
@@ -0,0 +1,3 @@
1
+ import type { ChartExportFile } from "./chartExport.js";
2
+ export declare function zipChartPngs(files: ChartExportFile[]): Promise<Blob>;
3
+ //# sourceMappingURL=zipChartPngs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zipChartPngs.d.ts","sourceRoot":"","sources":["../../src/report/zipChartPngs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,wBAAsB,YAAY,CAAC,KAAK,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1E"}
@@ -0,0 +1,8 @@
1
+ import JSZip from "jszip";
2
+ export async function zipChartPngs(files) {
3
+ const zip = new JSZip();
4
+ for (const file of files) {
5
+ zip.file(file.filename, file.blob);
6
+ }
7
+ return zip.generateAsync({ type: "blob", compression: "STORE" });
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openshift-migration-advisor/shared-components",
3
- "version": "0.24.0",
3
+ "version": "0.25.0-1c27267d2ea6",
4
4
  "description": "Shared React UI components for Migration Advisor apps (report charts, forms, OS support tiers)",
5
5
  "author": "Montse Ortega <mortegag@redhat.com>",
6
6
  "license": "Apache-2.0",
@@ -44,5 +44,10 @@
44
44
  "src",
45
45
  "LICENSE",
46
46
  "README.md"
47
- ]
47
+ ],
48
+ "dependencies": {
49
+ "html2canvas-pro": "^2.4.5",
50
+ "jspdf": "^4.2.1",
51
+ "jszip": "^3.10.2"
52
+ }
48
53
  }
@@ -1,5 +1,6 @@
1
1
  export {
2
2
  MigrationDonutChart,
3
3
  type MigrationDonutChartDatum,
4
+ type MigrationDonutChartLegendVariant,
4
5
  type MigrationDonutChartProps,
5
6
  } from "./MigrationDonutChart.js";
@@ -33,12 +33,19 @@ export default function RadioButtonFormGroup({
33
33
  const showError = error && (isTouched || isSubmitted);
34
34
 
35
35
  return (
36
- <FormGroup label={label} isRequired={isRequired} fieldId={id} {...props}>
36
+ <FormGroup
37
+ label={label}
38
+ isRequired={isRequired}
39
+ fieldId={id}
40
+ role="radiogroup"
41
+ isInline
42
+ {...props}
43
+ >
37
44
  <Controller
38
45
  name={name}
39
46
  control={methods.control}
40
47
  render={({ field }) => (
41
- <div style={{ display: "flex", gap: "16px" }} role="radiogroup">
48
+ <>
42
49
  {options.map((option) => (
43
50
  <Radio
44
51
  key={option.value}
@@ -50,7 +57,7 @@ export default function RadioButtonFormGroup({
50
57
  onBlur={field.onBlur}
51
58
  />
52
59
  ))}
53
- </div>
60
+ </>
54
61
  )}
55
62
  />
56
63
  <FormFieldHelperText
@@ -0,0 +1,59 @@
1
+ import { Button, Flex, FlexItem } from "@patternfly/react-core";
2
+ import { DownloadIcon } from "@patternfly/react-icons";
3
+ import type { FC, ReactNode } from "react";
4
+ import { chartExportHideProps } from "./chartExport.js";
5
+ import { useChartExport } from "./chartExportContext.js";
6
+
7
+ export const ChartDownloadButton: FC<{
8
+ chartId: string;
9
+ title?: string;
10
+ }> = ({ chartId, title }) => {
11
+ const exportApi = useChartExport();
12
+ if (!exportApi) {
13
+ return null;
14
+ }
15
+
16
+ const label = title ? `Download ${title} as PNG` : "Download chart as PNG";
17
+
18
+ return (
19
+ <Button
20
+ variant="plain"
21
+ icon={<DownloadIcon />}
22
+ aria-label={label}
23
+ isLoading={exportApi.downloadingChartId === chartId}
24
+ isDisabled={exportApi.isBusy}
25
+ onClick={() => {
26
+ void exportApi.downloadChart(chartId);
27
+ }}
28
+ />
29
+ );
30
+ };
31
+
32
+ ChartDownloadButton.displayName = "ChartDownloadButton";
33
+
34
+ export const ChartHeaderActions: FC<{
35
+ chartId: string;
36
+ title?: string;
37
+ children?: ReactNode;
38
+ }> = ({ chartId, title, children }) => {
39
+ const exportApi = useChartExport();
40
+ if (!exportApi && !children) {
41
+ return null;
42
+ }
43
+
44
+ return (
45
+ <FlexItem {...chartExportHideProps}>
46
+ <Flex
47
+ alignItems={{ default: "alignItemsCenter" }}
48
+ spaceItems={{ default: "spaceItemsSm" }}
49
+ >
50
+ {children}
51
+ {exportApi ? (
52
+ <ChartDownloadButton chartId={chartId} title={title} />
53
+ ) : null}
54
+ </Flex>
55
+ </FlexItem>
56
+ );
57
+ };
58
+
59
+ ChartHeaderActions.displayName = "ChartHeaderActions";
@@ -0,0 +1,384 @@
1
+ import {
2
+ type FC,
3
+ type ReactNode,
4
+ useCallback,
5
+ useMemo,
6
+ useRef,
7
+ useState,
8
+ } from "react";
9
+ import {
10
+ type ChartCaptureSource,
11
+ type ChartExportFile,
12
+ canvasToBlob,
13
+ downloadBlob,
14
+ type RegisteredChart,
15
+ releaseCanvas,
16
+ restoreChartExportViews,
17
+ sortRegisteredChartsByDocumentOrder,
18
+ toBulkChartCaptureSources,
19
+ } from "./chartExport.js";
20
+ import {
21
+ type ChartExportApi,
22
+ ChartExportApiContext,
23
+ type ChartExportFormat,
24
+ type ChartExportRegistry,
25
+ ChartExportRegistryContext,
26
+ } from "./chartExportContext.js";
27
+ import { getChartExportFilename } from "./chartExportFilenames.js";
28
+
29
+ export type CaptureChartElement = (
30
+ element: HTMLElement,
31
+ ) => Promise<HTMLCanvasElement>;
32
+ export type ZipChartFiles = (files: ChartExportFile[]) => Promise<Blob>;
33
+ export type EncodeChartPng = (canvas: HTMLCanvasElement) => Promise<Blob>;
34
+ export type BuildChartDocument = (
35
+ charts: ChartCaptureSource[],
36
+ documentTitle: string,
37
+ ) => Promise<Blob>;
38
+
39
+ export type {
40
+ ChartExportApi,
41
+ ChartExportFormat,
42
+ } from "./chartExportContext.js";
43
+ export { useChartExport, useRegisterChart } from "./chartExportContext.js";
44
+
45
+ export interface ChartExportProviderProps {
46
+ children: ReactNode;
47
+ capture?: CaptureChartElement;
48
+ zipFiles?: ZipChartFiles;
49
+ encodePng?: EncodeChartPng;
50
+ buildPdf?: BuildChartDocument;
51
+ buildHtml?: BuildChartDocument;
52
+ downloadFile?: (blob: Blob, filename: string) => void;
53
+ getZipFilename?: () => string;
54
+ getPdfFilename?: () => string;
55
+ getHtmlFilename?: () => string;
56
+ }
57
+
58
+ const EXPORT_LOADING_LABELS: Record<ChartExportFormat, string> = {
59
+ pdf: "Generating PDF...",
60
+ png: "Generating PNG...",
61
+ html: "Generating HTML...",
62
+ };
63
+
64
+ const defaultZipFilename = (): string => getChartExportFilename("zip");
65
+ const defaultPdfFilename = (): string => getChartExportFilename("pdf");
66
+ const defaultHtmlFilename = (): string => getChartExportFilename("html");
67
+
68
+ async function resolveCapture(
69
+ override?: CaptureChartElement,
70
+ ): Promise<CaptureChartElement> {
71
+ if (override) {
72
+ return override;
73
+ }
74
+ const { captureChartElement } = await import("./captureChartElement.js");
75
+ return captureChartElement;
76
+ }
77
+
78
+ async function resolvePrepareElement(
79
+ overrideCapture?: CaptureChartElement,
80
+ ): Promise<((element: HTMLElement) => () => void) | undefined> {
81
+ if (overrideCapture) {
82
+ return undefined;
83
+ }
84
+ const { revealHiddenChartAncestors } = await import(
85
+ "./captureChartElement.js"
86
+ );
87
+ return revealHiddenChartAncestors;
88
+ }
89
+
90
+ async function resolveZip(override?: ZipChartFiles): Promise<ZipChartFiles> {
91
+ if (override) {
92
+ return override;
93
+ }
94
+ const { zipChartPngs } = await import("./zipChartPngs.js");
95
+ return zipChartPngs;
96
+ }
97
+
98
+ async function resolvePdf(
99
+ override?: BuildChartDocument,
100
+ ): Promise<BuildChartDocument> {
101
+ if (override) {
102
+ return override;
103
+ }
104
+ const { buildPdfFromCharts } = await import("./pdfExport.js");
105
+ return buildPdfFromCharts;
106
+ }
107
+
108
+ async function resolveHtml(
109
+ override?: BuildChartDocument,
110
+ ): Promise<BuildChartDocument> {
111
+ if (override) {
112
+ return override;
113
+ }
114
+ const { buildHtmlFromCharts } = await import("./htmlExport.js");
115
+ return buildHtmlFromCharts;
116
+ }
117
+
118
+ function toCaptureSources(
119
+ charts: RegisteredChart[],
120
+ capture: CaptureChartElement,
121
+ prepareElement?: (element: HTMLElement) => () => void,
122
+ ): ChartCaptureSource[] {
123
+ return toBulkChartCaptureSources(charts, capture, prepareElement);
124
+ }
125
+
126
+ export const ChartExportProvider: FC<ChartExportProviderProps> = ({
127
+ children,
128
+ capture,
129
+ zipFiles,
130
+ encodePng = canvasToBlob,
131
+ buildPdf,
132
+ buildHtml,
133
+ downloadFile = downloadBlob,
134
+ getZipFilename = defaultZipFilename,
135
+ getPdfFilename = defaultPdfFilename,
136
+ getHtmlFilename = defaultHtmlFilename,
137
+ }) => {
138
+ const chartsRef = useRef(new Map<string, RegisteredChart>());
139
+ const isBusyRef = useRef(false);
140
+ const [downloadingChartId, setDownloadingChartId] = useState<string | null>(
141
+ null,
142
+ );
143
+ const [exportingFormat, setExportingFormat] =
144
+ useState<ChartExportFormat | null>(null);
145
+ const [exportError, setExportError] = useState<string | null>(null);
146
+
147
+ const registry = useMemo<ChartExportRegistry>(
148
+ () => ({
149
+ register(chart) {
150
+ const existing = chartsRef.current.get(chart.id);
151
+ if (
152
+ existing &&
153
+ existing.element !== chart.element &&
154
+ existing.element.isConnected
155
+ ) {
156
+ console.warn(
157
+ `Duplicate chart export id "${chart.id}". The previous chart will not be exported.`,
158
+ );
159
+ }
160
+ chartsRef.current.set(chart.id, chart);
161
+ return () => {
162
+ const current = chartsRef.current.get(chart.id);
163
+ if (current?.element === chart.element) {
164
+ chartsRef.current.delete(chart.id);
165
+ }
166
+ };
167
+ },
168
+ }),
169
+ [],
170
+ );
171
+
172
+ const listCharts = useCallback((): RegisteredChart[] => {
173
+ return sortRegisteredChartsByDocumentOrder(
174
+ Array.from(chartsRef.current.values()).filter(
175
+ (chart) => chart.element.isConnected,
176
+ ),
177
+ );
178
+ }, []);
179
+
180
+ const runCapture = useCallback(
181
+ async (
182
+ work: () => Promise<void>,
183
+ chartId: string | null,
184
+ format: ChartExportFormat,
185
+ ) => {
186
+ if (isBusyRef.current) {
187
+ return;
188
+ }
189
+
190
+ isBusyRef.current = true;
191
+ setExportError(null);
192
+ if (chartId) {
193
+ setDownloadingChartId(chartId);
194
+ } else {
195
+ setExportingFormat(format);
196
+ }
197
+
198
+ try {
199
+ await work();
200
+ } catch (error) {
201
+ console.error(`Error exporting ${format}:`, error);
202
+ setExportError(
203
+ `Failed to export ${format.toUpperCase()}. Please try again.`,
204
+ );
205
+ } finally {
206
+ isBusyRef.current = false;
207
+ setDownloadingChartId(null);
208
+ setExportingFormat(null);
209
+ }
210
+ },
211
+ [],
212
+ );
213
+
214
+ const downloadChart = useCallback(
215
+ async (id: string) => {
216
+ await runCapture(
217
+ async () => {
218
+ const chart = chartsRef.current.get(id);
219
+ if (!chart?.element.isConnected) {
220
+ throw new Error("The chart is not ready to export yet.");
221
+ }
222
+ const captureFn = await resolveCapture(capture);
223
+ const canvas = await captureFn(chart.element);
224
+ try {
225
+ downloadFile(await encodePng(canvas), chart.filename);
226
+ } finally {
227
+ releaseCanvas(canvas);
228
+ }
229
+ },
230
+ id,
231
+ "png",
232
+ );
233
+ },
234
+ [capture, downloadFile, encodePng, runCapture],
235
+ );
236
+
237
+ const downloadAll = useCallback(async () => {
238
+ await runCapture(
239
+ async () => {
240
+ const charts = listCharts();
241
+ if (charts.length === 0) {
242
+ throw new Error("The report is not ready to export yet.");
243
+ }
244
+ const captureFn = await resolveCapture(capture);
245
+ const prepareElement = await resolvePrepareElement(capture);
246
+ const zipFn = await resolveZip(zipFiles);
247
+ const files: ChartExportFile[] = [];
248
+ const sources = toBulkChartCaptureSources(
249
+ charts,
250
+ captureFn,
251
+ prepareElement,
252
+ );
253
+ try {
254
+ for (const [index, source] of sources.entries()) {
255
+ const canvas = await source.capture();
256
+ try {
257
+ files.push({
258
+ filename: `${String(index + 1).padStart(2, "0")}-${source.filename}`,
259
+ blob: await encodePng(canvas),
260
+ });
261
+ } finally {
262
+ releaseCanvas(canvas);
263
+ }
264
+ }
265
+ } finally {
266
+ await restoreChartExportViews(charts);
267
+ }
268
+ downloadFile(await zipFn(files), getZipFilename());
269
+ },
270
+ null,
271
+ "png",
272
+ );
273
+ }, [
274
+ capture,
275
+ downloadFile,
276
+ encodePng,
277
+ getZipFilename,
278
+ listCharts,
279
+ runCapture,
280
+ zipFiles,
281
+ ]);
282
+
283
+ const downloadPdf = useCallback(
284
+ async (documentTitle: string) => {
285
+ await runCapture(
286
+ async () => {
287
+ const charts = listCharts();
288
+ if (charts.length === 0) {
289
+ throw new Error("The report is not ready to export yet.");
290
+ }
291
+ const captureFn = await resolveCapture(capture);
292
+ const prepareElement = await resolvePrepareElement(capture);
293
+ const build = await resolvePdf(buildPdf);
294
+ try {
295
+ downloadFile(
296
+ await build(
297
+ toCaptureSources(charts, captureFn, prepareElement),
298
+ documentTitle,
299
+ ),
300
+ getPdfFilename(),
301
+ );
302
+ } finally {
303
+ await restoreChartExportViews(charts);
304
+ }
305
+ },
306
+ null,
307
+ "pdf",
308
+ );
309
+ },
310
+ [buildPdf, capture, downloadFile, getPdfFilename, listCharts, runCapture],
311
+ );
312
+
313
+ const downloadHtml = useCallback(
314
+ async (documentTitle: string) => {
315
+ await runCapture(
316
+ async () => {
317
+ const charts = listCharts();
318
+ if (charts.length === 0) {
319
+ throw new Error("The report is not ready to export yet.");
320
+ }
321
+ const captureFn = await resolveCapture(capture);
322
+ const prepareElement = await resolvePrepareElement(capture);
323
+ const build = await resolveHtml(buildHtml);
324
+ try {
325
+ downloadFile(
326
+ await build(
327
+ toCaptureSources(charts, captureFn, prepareElement),
328
+ documentTitle,
329
+ ),
330
+ getHtmlFilename(),
331
+ );
332
+ } finally {
333
+ await restoreChartExportViews(charts);
334
+ }
335
+ },
336
+ null,
337
+ "html",
338
+ );
339
+ },
340
+ [buildHtml, capture, downloadFile, getHtmlFilename, listCharts, runCapture],
341
+ );
342
+
343
+ const clearExportError = useCallback(() => {
344
+ setExportError(null);
345
+ }, []);
346
+
347
+ const api = useMemo<ChartExportApi>(
348
+ () => ({
349
+ downloadChart,
350
+ downloadAll,
351
+ downloadPdf,
352
+ downloadHtml,
353
+ downloadingChartId,
354
+ exportingFormat,
355
+ exportLoadingLabel: exportingFormat
356
+ ? EXPORT_LOADING_LABELS[exportingFormat]
357
+ : null,
358
+ isExportingAll: exportingFormat !== null,
359
+ isBusy: downloadingChartId !== null || exportingFormat !== null,
360
+ exportError,
361
+ clearExportError,
362
+ }),
363
+ [
364
+ clearExportError,
365
+ downloadAll,
366
+ downloadChart,
367
+ downloadHtml,
368
+ downloadPdf,
369
+ downloadingChartId,
370
+ exportError,
371
+ exportingFormat,
372
+ ],
373
+ );
374
+
375
+ return (
376
+ <ChartExportRegistryContext.Provider value={registry}>
377
+ <ChartExportApiContext.Provider value={api}>
378
+ {children}
379
+ </ChartExportApiContext.Provider>
380
+ </ChartExportRegistryContext.Provider>
381
+ );
382
+ };
383
+
384
+ ChartExportProvider.displayName = "ChartExportProvider";