@dudousxd/nestjs-catalog-react 0.7.2 → 0.9.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 (49) hide show
  1. package/README.md +41 -5
  2. package/dist/DashboardBoard.d.ts +22 -0
  3. package/dist/DashboardBoard.js +134 -69
  4. package/dist/GovernanceTimeline.js +11 -1
  5. package/dist/SavedQueryPanel.d.ts +0 -8
  6. package/dist/SavedQueryPanel.js +48 -9
  7. package/dist/charts/body.d.ts +39 -0
  8. package/dist/charts/body.js +53 -0
  9. package/dist/charts/grid.d.ts +23 -0
  10. package/dist/charts/grid.js +39 -0
  11. package/dist/charts/registry.d.ts +19 -0
  12. package/dist/charts/registry.js +22 -0
  13. package/dist/context.d.ts +71 -0
  14. package/dist/context.js +20 -3
  15. package/dist/embed/EmbeddedChart.d.ts +41 -0
  16. package/dist/embed/EmbeddedChart.js +25 -0
  17. package/dist/embed/EmbeddedDashboard.d.ts +32 -0
  18. package/dist/embed/EmbeddedDashboard.js +38 -0
  19. package/dist/embed/actions.d.ts +75 -0
  20. package/dist/embed/actions.js +64 -0
  21. package/dist/embed/chart-card.d.ts +20 -0
  22. package/dist/embed/chart-card.js +89 -0
  23. package/dist/embed/index.d.ts +12 -0
  24. package/dist/embed/index.js +11 -0
  25. package/dist/embed/payload.d.ts +78 -0
  26. package/dist/embed/payload.js +42 -0
  27. package/dist/embed/slots.d.ts +52 -0
  28. package/dist/embed/slots.js +44 -0
  29. package/dist/export/css-variables.d.ts +60 -0
  30. package/dist/export/css-variables.js +137 -0
  31. package/dist/export/index.d.ts +21 -0
  32. package/dist/export/index.js +21 -0
  33. package/dist/export/pdf.d.ts +136 -0
  34. package/dist/export/pdf.js +97 -0
  35. package/dist/export/png.d.ts +88 -0
  36. package/dist/export/png.js +125 -0
  37. package/dist/export/serialize.d.ts +92 -0
  38. package/dist/export/serialize.js +298 -0
  39. package/dist/export/use-pdf-export.d.ts +66 -0
  40. package/dist/export/use-pdf-export.js +63 -0
  41. package/dist/export/use-png-export.d.ts +82 -0
  42. package/dist/export/use-png-export.js +126 -0
  43. package/dist/index.d.ts +3 -1
  44. package/dist/index.js +21 -1
  45. package/dist/routes.d.ts +25 -1
  46. package/dist/routes.js +25 -1
  47. package/dist/sharing.d.ts +81 -0
  48. package/dist/sharing.js +72 -0
  49. package/package.json +2 -2
@@ -0,0 +1,136 @@
1
+ import { type PngExportOptions } from './png';
2
+ import { type SerializedSvg } from './serialize';
3
+ /**
4
+ * PDF export, as a seam the host fills rather than a dependency this package takes.
5
+ *
6
+ * WHY THERE IS NO PDF RENDERER IN HERE
7
+ * ------------------------------------
8
+ * The same argument `charts/registry.tsx` makes about recharts and bklit, with
9
+ * the numbers on the other side of it. A client-side PDF means `jspdf` (109KB
10
+ * gzipped) plus `svg2pdf.js` (19KB) — ~128KB that every consumer of this
11
+ * library downloads so that some of them can export a chart. Meanwhile the
12
+ * applications that actually want this already generate PDFs server-side, with
13
+ * their own fonts, header, page furniture and pipeline; a PDF produced here
14
+ * would match none of it and would have to be styled back out again.
15
+ *
16
+ * So the host registers something that turns an exported chart into a PDF:
17
+ *
18
+ * ```ts
19
+ * import { registerPdfExporter } from "@dudousxd/nestjs-catalog-react";
20
+ *
21
+ * registerPdfExporter({
22
+ * label: "Save as report",
23
+ * async export({ png, width, height, title }) {
24
+ * const body = new FormData();
25
+ * body.append("chart", png, "chart.png");
26
+ * body.append("meta", JSON.stringify({ width, height, title }));
27
+ * await fetch("/reports/chart", { method: "POST", body });
28
+ * },
29
+ * });
30
+ * ```
31
+ *
32
+ * WHY BOTH THE RASTER AND THE MARKUP
33
+ * ----------------------------------
34
+ * A host on `@react-pdf/renderer` takes `png`, because that library draws
35
+ * images and not arbitrary SVG. A host with a vector pipeline takes `svg` and
36
+ * gets text that is still selectable and still sharp at print size. Handing
37
+ * over only the raster forecloses the second; handing over only the markup
38
+ * makes the common case do work it should not have to. Both are produced from
39
+ * ONE serialisation, so the two always describe the same chart at the same
40
+ * size — see {@link rasteriseSerializedSvg}.
41
+ *
42
+ * WHERE NOBODY REGISTERED ONE, THERE IS NO ACTION
43
+ * -----------------------------------------------
44
+ * Not a disabled button, not one that fails when clicked: absent. That is the
45
+ * rule `registeredChartLibraries()` already follows, and it is the rule
46
+ * `usePdfExport` implements — a control that claims something the code does not
47
+ * do is a bug report filed against whoever shipped the control.
48
+ */
49
+ /**
50
+ * What the host is handed. One chart, in the two forms this package can produce.
51
+ */
52
+ export interface ChartPdfSource {
53
+ /** The rasterised chart. What an image-drawing PDF library wants. */
54
+ png: Blob;
55
+ /** The same chart as a standalone, self-contained SVG document, styles inlined. */
56
+ svg: string;
57
+ /** CSS pixels, so the host can size a page honestly. Describes both `png` and `svg`. */
58
+ width: number;
59
+ height: number;
60
+ /** The card's title, when it has one. */
61
+ title?: string;
62
+ /** The SQL behind the chart, for a host that prints it as a caption. */
63
+ query?: string;
64
+ }
65
+ export interface ChartPdfExporter {
66
+ /**
67
+ * Shown on the action, so the host names its own document.
68
+ *
69
+ * Absent means the caller draws whatever it calls this by default. It is here
70
+ * because the host is the one producing the artefact: "Save as PDF" is wrong
71
+ * for something that lands in a quarterly report template, and the component
72
+ * offering the button cannot know which it is.
73
+ */
74
+ label?: string;
75
+ export(chart: ChartPdfSource): Promise<void>;
76
+ }
77
+ /**
78
+ * Register the host's exporter. Returns a function that removes it again.
79
+ *
80
+ * The disposer is deliberately not a plain `exporter = undefined`: it clears the
81
+ * slot only if this exporter is still the one in it. A host that swaps
82
+ * implementations — or a test that registers a second — would otherwise have
83
+ * the older disposer wipe the newer registration, and the symptom is the action
84
+ * silently disappearing long after the call that caused it.
85
+ */
86
+ export declare function registerPdfExporter(next: ChartPdfExporter): () => void;
87
+ /** The registered exporter, or undefined when the host wired none. */
88
+ export declare function getPdfExporter(): ChartPdfExporter | undefined;
89
+ /**
90
+ * Subscribe to registration changes.
91
+ *
92
+ * `getChartRenderer` has no equivalent and does not need one: it is read while
93
+ * rendering a card that re-renders whenever its query result does. This is read
94
+ * to decide whether a control EXISTS, and the whole premise above is that a
95
+ * host's PDF pipeline is heavy — so it is very often behind a dynamic import
96
+ * that resolves after the console has already mounted. Without this, those
97
+ * cards would sit there actionless until something unrelated re-rendered them.
98
+ */
99
+ export declare function subscribeToPdfExporter(listener: () => void): () => void;
100
+ export interface PdfSourceOptions extends PngExportOptions {
101
+ /** The card's title, passed through to the exporter. */
102
+ title?: string;
103
+ /** The query behind the chart, passed through to the exporter. */
104
+ query?: string;
105
+ }
106
+ /**
107
+ * How the raster is produced. A parameter so a test can substitute it.
108
+ *
109
+ * jsdom cannot rasterise — `canvas.getContext('2d')` returns null — so a test
110
+ * that wants to check what reaches the exporter has no other way in. The
111
+ * substitution stops at the raster: `serializeSvg` still runs for real, so the
112
+ * markup and the dimensions a test observes are the ones a browser would see.
113
+ */
114
+ export type SvgRasteriser = (serialized: SerializedSvg, options: PngExportOptions) => Promise<Blob>;
115
+ /**
116
+ * Everything the host needs, from one serialisation of one chart.
117
+ *
118
+ * Separate from {@link exportSvgAsPdf} because it is the whole contract of the
119
+ * seam and nothing about it is React: a host with its own toolbar can build the
120
+ * payload and route it wherever it likes.
121
+ */
122
+ export declare function buildChartPdfSource(svg: SVGSVGElement, options?: PdfSourceOptions, rasterise?: SvgRasteriser): Promise<ChartPdfSource>;
123
+ /**
124
+ * Build the payload and hand it to the registered exporter.
125
+ *
126
+ * Throws when nobody registered one. That is not the path a user can reach —
127
+ * `usePdfExport` reports no action at all in that case — so reaching it means a
128
+ * caller offered the export without checking, and a thrown error naming the
129
+ * missing registration is far more use than a silent no-op that looks like the
130
+ * PDF pipeline failing.
131
+ *
132
+ * A rejection from the host's own exporter propagates untouched. Swallowing it
133
+ * would leave a user who clicked "export" watching nothing happen, with the
134
+ * only evidence in a console they are not looking at.
135
+ */
136
+ export declare function exportSvgAsPdf(svg: SVGSVGElement, options?: PdfSourceOptions, rasterise?: SvgRasteriser): Promise<ChartPdfSource>;
@@ -0,0 +1,97 @@
1
+ import { rasteriseSerializedSvg } from './png';
2
+ import { serializeSvg } from './serialize';
3
+ /**
4
+ * One slot, not a map by name.
5
+ *
6
+ * Chart renderers are keyed because a saved query names the library it wants
7
+ * and several can be live at once. A PDF pipeline is not chosen per chart — the
8
+ * host has one document story, and a second registration is a replacement
9
+ * rather than an addition.
10
+ */
11
+ let exporter;
12
+ /** Notified when the slot changes, so a mounted card can grow or lose the action. */
13
+ const listeners = new Set();
14
+ /**
15
+ * Register the host's exporter. Returns a function that removes it again.
16
+ *
17
+ * The disposer is deliberately not a plain `exporter = undefined`: it clears the
18
+ * slot only if this exporter is still the one in it. A host that swaps
19
+ * implementations — or a test that registers a second — would otherwise have
20
+ * the older disposer wipe the newer registration, and the symptom is the action
21
+ * silently disappearing long after the call that caused it.
22
+ */
23
+ export function registerPdfExporter(next) {
24
+ exporter = next;
25
+ for (const listener of listeners)
26
+ listener();
27
+ return () => {
28
+ if (exporter !== next)
29
+ return;
30
+ exporter = undefined;
31
+ for (const listener of listeners)
32
+ listener();
33
+ };
34
+ }
35
+ /** The registered exporter, or undefined when the host wired none. */
36
+ export function getPdfExporter() {
37
+ return exporter;
38
+ }
39
+ /**
40
+ * Subscribe to registration changes.
41
+ *
42
+ * `getChartRenderer` has no equivalent and does not need one: it is read while
43
+ * rendering a card that re-renders whenever its query result does. This is read
44
+ * to decide whether a control EXISTS, and the whole premise above is that a
45
+ * host's PDF pipeline is heavy — so it is very often behind a dynamic import
46
+ * that resolves after the console has already mounted. Without this, those
47
+ * cards would sit there actionless until something unrelated re-rendered them.
48
+ */
49
+ export function subscribeToPdfExporter(listener) {
50
+ listeners.add(listener);
51
+ return () => {
52
+ listeners.delete(listener);
53
+ };
54
+ }
55
+ /**
56
+ * Everything the host needs, from one serialisation of one chart.
57
+ *
58
+ * Separate from {@link exportSvgAsPdf} because it is the whole contract of the
59
+ * seam and nothing about it is React: a host with its own toolbar can build the
60
+ * payload and route it wherever it likes.
61
+ */
62
+ export async function buildChartPdfSource(svg, options = {}, rasterise = rasteriseSerializedSvg) {
63
+ const serialized = serializeSvg(svg, options);
64
+ const png = await rasterise(serialized, options);
65
+ return {
66
+ png,
67
+ svg: serialized.markup,
68
+ width: serialized.width,
69
+ height: serialized.height,
70
+ title: options.title,
71
+ query: options.query,
72
+ };
73
+ }
74
+ /**
75
+ * Build the payload and hand it to the registered exporter.
76
+ *
77
+ * Throws when nobody registered one. That is not the path a user can reach —
78
+ * `usePdfExport` reports no action at all in that case — so reaching it means a
79
+ * caller offered the export without checking, and a thrown error naming the
80
+ * missing registration is far more use than a silent no-op that looks like the
81
+ * PDF pipeline failing.
82
+ *
83
+ * A rejection from the host's own exporter propagates untouched. Swallowing it
84
+ * would leave a user who clicked "export" watching nothing happen, with the
85
+ * only evidence in a console they are not looking at.
86
+ */
87
+ export async function exportSvgAsPdf(svg, options = {}, rasterise = rasteriseSerializedSvg) {
88
+ const target = exporter;
89
+ if (!target) {
90
+ throw new Error('No PDF exporter is registered, so this chart cannot be exported as a PDF. This package ' +
91
+ 'ships no PDF renderer by design; call registerPdfExporter() with one backed by your own ' +
92
+ 'document pipeline.');
93
+ }
94
+ const source = await buildChartPdfSource(svg, options, rasterise);
95
+ await target.export(source);
96
+ return source;
97
+ }
@@ -0,0 +1,88 @@
1
+ import { type SerializeSvgOptions, type SerializedSvg } from './serialize';
2
+ /**
3
+ * SVG chart → PNG, in the browser, with no dependency.
4
+ *
5
+ * The pipeline is: serialise the live `<svg>` with its styles inlined (see
6
+ * `serialize.ts`, which is where the hard part is), load that as an image,
7
+ * draw it into a canvas at a real pixel ratio, and `toBlob`. Nothing here is
8
+ * novel; what makes it worth writing down is the list of things that silently
9
+ * do not work, all of which are properties of `<img src="data:image/svg+xml,…">`
10
+ * rather than of this code:
11
+ *
12
+ * **Fonts do not load.** An SVG loaded through `<img>` renders in what the spec
13
+ * calls secure static mode: it fetches nothing. No stylesheet, no image, no
14
+ * `@font-face` — including the Google Fonts link the console uses for
15
+ * `Space Grotesk` and `JetBrains Mono`. Those are web fonts, not system fonts,
16
+ * so the rasteriser cannot find them by name either. The exported PNG therefore
17
+ * renders labels in the next family in the stack (`ui-sans-serif`/`system-ui`,
18
+ * and `ui-monospace` for values), which is why `serialize.ts` inlines the whole
19
+ * `font-family` stack rather than just the first entry: with the full stack the
20
+ * text lands in a fallback face, without it the text could vanish. The fallback
21
+ * face has different metrics, so a long axis label can end up a few pixels
22
+ * wider or narrower than it is on screen. Text is present and legible; it is
23
+ * not pixel-identical to the page. A host that needs the real faces can pass
24
+ * `fontFaceCss` with the fonts base64'd into `data:` URIs — that is the only
25
+ * fix, and it is the host's to make because only the host knows whether it is
26
+ * licensed to embed them.
27
+ *
28
+ * **A raster image inside the chart taints the canvas.** If a renderer embeds
29
+ * an `<image href="https://…">`, `toBlob` throws a `SecurityError` and no
30
+ * amount of retrying helps. None of the shipped renderers do this; a custom one
31
+ * might, and the error below says so rather than surfacing as "export failed".
32
+ *
33
+ * **`<foreignObject>` is not portable.** HTML inside an SVG rasterises in
34
+ * Chromium and does not in every browser. The shipped renderers use it only for
35
+ * hover tooltips, which are not present in a static export anyway.
36
+ *
37
+ * **Only SVG renderers can be exported.** `CssBarChart` — the no-dependency
38
+ * fallback — is a stack of `<div>`s, not an `<svg>`, so there is nothing here
39
+ * to serialise. `findExportableSvg` returns null for it and the caller is
40
+ * expected to hide the action rather than offer one that fails.
41
+ */
42
+ export interface PngExportOptions extends SerializeSvgOptions {
43
+ /**
44
+ * Pixels per CSS pixel.
45
+ *
46
+ * Defaults to `max(devicePixelRatio, 2)`. Not plain `devicePixelRatio`: a 1x
47
+ * PNG is soft on every modern display and unusable the moment it is scaled up
48
+ * in a document, and the person exporting a chart is almost always about to
49
+ * put it in one. 2x is the floor, a Retina screen gets its own ratio, and a
50
+ * caller who wants a specific size passes a number.
51
+ */
52
+ scale?: number;
53
+ /** @default 'image/png' */
54
+ mimeType?: string;
55
+ }
56
+ /** The effective scale, honouring the request but never overflowing the canvas. */
57
+ export declare function resolveScale(requested: number | undefined, width: number, height: number, devicePixelRatio?: number): number;
58
+ /**
59
+ * The `<svg>` inside `element` that can be exported, or null if there is none.
60
+ *
61
+ * Null is a real answer, not a failure: the CSS fallback chart has no SVG, and
62
+ * a toolbar should read that and not offer the action.
63
+ */
64
+ export declare function findExportableSvg(element: Element | null | undefined): SVGSVGElement | null;
65
+ /**
66
+ * A PNG from markup that has ALREADY been serialised.
67
+ *
68
+ * Split out of `svgToPngBlob` for the one caller that needs the serialised
69
+ * document as well as the raster — the PDF seam in `pdf.ts` hands a host both.
70
+ * Serialising twice would work and would be wrong in a way that only shows up
71
+ * later: the size is measured during serialisation, so two passes over a chart
72
+ * that resized in between produce a `width`/`height` that describes one of them
73
+ * and a PNG that is the other. A host sizing a PDF page from those numbers then
74
+ * gets a stretched image, and nothing in either call reported a problem.
75
+ *
76
+ * It is also the seam a test can stand in for. jsdom cannot rasterise at all,
77
+ * so a test that wants to check what a caller does with the blob substitutes
78
+ * this and leaves the serialisation real.
79
+ */
80
+ export declare function rasteriseSerializedSvg(serialized: SerializedSvg, options?: PngExportOptions): Promise<Blob>;
81
+ /** A PNG of the given chart `<svg>`, at `scale` times its on-screen size. */
82
+ export declare function svgToPngBlob(svg: SVGSVGElement, options?: PngExportOptions): Promise<Blob>;
83
+ /** `chart-2026-08-04T12-30-00.png` — sortable, and unique enough for a downloads folder. */
84
+ export declare function defaultPngFilename(now?: Date): string;
85
+ /** Hand a blob to the browser as a download. Separate so the blob path stays testable. */
86
+ export declare function triggerDownload(blob: Blob, filename: string): void;
87
+ /** Rasterise the chart and download it. The whole feature, for a caller who wants one call. */
88
+ export declare function downloadSvgAsPng(svg: SVGSVGElement, filename?: string, options?: PngExportOptions): Promise<Blob>;
@@ -0,0 +1,125 @@
1
+ import { serializeSvg, svgToDataUri, } from './serialize';
2
+ /**
3
+ * The per-side limit every current browser enforces on a canvas.
4
+ *
5
+ * Chromium and Firefox both cap a dimension at 16384px (Safari caps total area
6
+ * lower still). Past the cap `drawImage` silently produces a blank canvas — no
7
+ * exception — so the scale is clamped instead of discovering it as an empty
8
+ * PNG.
9
+ */
10
+ const MAX_CANVAS_SIDE = 16384;
11
+ /** The effective scale, honouring the request but never overflowing the canvas. */
12
+ export function resolveScale(requested, width, height, devicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio ?? 1)) {
13
+ const wanted = typeof requested === 'number' && Number.isFinite(requested) && requested > 0
14
+ ? requested
15
+ : Math.max(devicePixelRatio, 2);
16
+ const largest = Math.max(width, height);
17
+ if (!Number.isFinite(largest) || largest <= 0)
18
+ return wanted;
19
+ return Math.min(wanted, MAX_CANVAS_SIDE / largest);
20
+ }
21
+ /**
22
+ * The `<svg>` inside `element` that can be exported, or null if there is none.
23
+ *
24
+ * Null is a real answer, not a failure: the CSS fallback chart has no SVG, and
25
+ * a toolbar should read that and not offer the action.
26
+ */
27
+ export function findExportableSvg(element) {
28
+ if (!element)
29
+ return null;
30
+ if (element instanceof SVGSVGElement)
31
+ return element;
32
+ const found = element.querySelector('svg');
33
+ return found instanceof SVGSVGElement ? found : null;
34
+ }
35
+ function decodeImage(dataUri) {
36
+ return new Promise((resolve, reject) => {
37
+ const image = new Image();
38
+ image.onload = () => resolve(image);
39
+ image.onerror = () => reject(new Error('The browser refused to load the serialised chart as an image. This usually means the ' +
40
+ 'SVG is not well-formed XML — a renderer emitting raw HTML into the chart is the ' +
41
+ 'common cause.'));
42
+ image.src = dataUri;
43
+ });
44
+ }
45
+ function canvasToBlob(canvas, mimeType) {
46
+ return new Promise((resolve, reject) => {
47
+ canvas.toBlob((blob) => {
48
+ if (blob) {
49
+ resolve(blob);
50
+ return;
51
+ }
52
+ reject(new Error(`The canvas produced no ${mimeType} data.`));
53
+ }, mimeType);
54
+ });
55
+ }
56
+ /**
57
+ * A PNG from markup that has ALREADY been serialised.
58
+ *
59
+ * Split out of `svgToPngBlob` for the one caller that needs the serialised
60
+ * document as well as the raster — the PDF seam in `pdf.ts` hands a host both.
61
+ * Serialising twice would work and would be wrong in a way that only shows up
62
+ * later: the size is measured during serialisation, so two passes over a chart
63
+ * that resized in between produce a `width`/`height` that describes one of them
64
+ * and a PNG that is the other. A host sizing a PDF page from those numbers then
65
+ * gets a stretched image, and nothing in either call reported a problem.
66
+ *
67
+ * It is also the seam a test can stand in for. jsdom cannot rasterise at all,
68
+ * so a test that wants to check what a caller does with the blob substitutes
69
+ * this and leaves the serialisation real.
70
+ */
71
+ export async function rasteriseSerializedSvg(serialized, options = {}) {
72
+ const { markup, width, height } = serialized;
73
+ const scale = resolveScale(options.scale, width, height);
74
+ const canvas = document.createElement('canvas');
75
+ canvas.width = Math.max(1, Math.round(width * scale));
76
+ canvas.height = Math.max(1, Math.round(height * scale));
77
+ const context = canvas.getContext('2d');
78
+ if (!context) {
79
+ throw new Error('No 2D canvas context is available, so the chart cannot be rasterised. PNG export needs a ' +
80
+ 'real browser canvas; there is no fallback that produces a correct image.');
81
+ }
82
+ const image = await decodeImage(svgToDataUri(markup));
83
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
84
+ try {
85
+ return await canvasToBlob(canvas, options.mimeType ?? 'image/png');
86
+ }
87
+ catch (error) {
88
+ if (error instanceof DOMException && error.name === 'SecurityError') {
89
+ throw new Error('The chart contains an image loaded from another origin, which taints the canvas and ' +
90
+ 'makes the PNG unreadable to the page. Inline that image as a data: URI to export it.');
91
+ }
92
+ throw error;
93
+ }
94
+ }
95
+ /** A PNG of the given chart `<svg>`, at `scale` times its on-screen size. */
96
+ export async function svgToPngBlob(svg, options = {}) {
97
+ return rasteriseSerializedSvg(serializeSvg(svg, options), options);
98
+ }
99
+ /** `chart-2026-08-04T12-30-00.png` — sortable, and unique enough for a downloads folder. */
100
+ export function defaultPngFilename(now = new Date()) {
101
+ return `chart-${now.toISOString().slice(0, 19).replace(/[:T]/g, '-')}.png`;
102
+ }
103
+ /** Hand a blob to the browser as a download. Separate so the blob path stays testable. */
104
+ export function triggerDownload(blob, filename) {
105
+ if (typeof URL.createObjectURL !== 'function') {
106
+ throw new Error('URL.createObjectURL is unavailable, so the PNG cannot be handed to the user.');
107
+ }
108
+ const href = URL.createObjectURL(blob);
109
+ const anchor = document.createElement('a');
110
+ anchor.href = href;
111
+ anchor.download = filename;
112
+ anchor.rel = 'noopener';
113
+ document.body.appendChild(anchor);
114
+ anchor.click();
115
+ anchor.remove();
116
+ // Deferred: revoking synchronously after `click()` races the download in
117
+ // Safari, which has not read the blob yet and ends up saving nothing.
118
+ setTimeout(() => URL.revokeObjectURL(href), 10_000);
119
+ }
120
+ /** Rasterise the chart and download it. The whole feature, for a caller who wants one call. */
121
+ export async function downloadSvgAsPng(svg, filename = defaultPngFilename(), options = {}) {
122
+ const blob = await svgToPngBlob(svg, options);
123
+ triggerDownload(blob, filename);
124
+ return blob;
125
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * What to paint behind the chart.
3
+ *
4
+ * `'auto'` walks up from the chart for the first ancestor with a background
5
+ * colour that is actually painted, which is the card, and falls back to white
6
+ * when nothing in the tree paints one. `'transparent'` is available and is
7
+ * never the default: a transparent PNG of a dark-theme chart is unreadable in
8
+ * any light document, and that failure happens after the file has left, in
9
+ * someone else's slide deck, where nobody can connect it back to an export
10
+ * option. Any other CSS colour string is used as given.
11
+ */
12
+ export type ExportBackground = string;
13
+ export interface SerializeSvgOptions {
14
+ /** @default 'auto' */
15
+ background?: ExportBackground;
16
+ /** Used when `background` is `'auto'` and nothing in the tree paints one. @default '#ffffff' */
17
+ fallbackBackground?: string;
18
+ /** Custom properties to resolve, beyond the console theme's own. */
19
+ customProperties?: readonly string[];
20
+ /**
21
+ * `@font-face` CSS injected into the serialised document.
22
+ *
23
+ * The escape hatch for the font problem described on `svgToPngBlob`. Rules
24
+ * here must carry their font data as `data:` URIs — the rasteriser will not
25
+ * fetch anything.
26
+ */
27
+ fontFaceCss?: string;
28
+ /** Override the measured size. Both must be given for either to apply. */
29
+ width?: number;
30
+ height?: number;
31
+ }
32
+ export interface SerializedSvg {
33
+ markup: string;
34
+ width: number;
35
+ height: number;
36
+ }
37
+ /**
38
+ * How big the exported image should be, in CSS pixels.
39
+ *
40
+ * The laid-out box first, because that is what the reader is looking at. The
41
+ * `width`/`height` attributes second, and the `viewBox` last — those two only
42
+ * come up when the element has never been laid out, which is the case under
43
+ * jsdom and for an element that was built but not mounted.
44
+ */
45
+ export declare function resolveSvgSize(svg: SVGSVGElement): {
46
+ width: number;
47
+ height: number;
48
+ };
49
+ /**
50
+ * The first painted background colour at or above `element`.
51
+ *
52
+ * Stops at `<html>`. Returns null rather than guessing so the caller can apply
53
+ * its own documented fallback instead of this function inventing white.
54
+ */
55
+ export declare function resolveAncestorBackground(element: Element, read?: (target: Element) => CSSStyleDeclaration): string | null;
56
+ /** Resolved inherited values so far, so a child can skip what it would inherit anyway. */
57
+ type Inherited = ReadonlyMap<string, string>;
58
+ /** One element's resolved value for a property, already trimmed. */
59
+ export type StyleLookup = (property: string) => string;
60
+ /**
61
+ * The declarations one element needs, and what its children will inherit.
62
+ *
63
+ * Takes a lookup rather than an `Element` so the rule that decides how much
64
+ * markup an export produces — skip an inherited value the parent already
65
+ * declared, skip a non-inherited value that equals its initial — can be checked
66
+ * against known inputs. Reading it out of a live tree instead would put it at
67
+ * the mercy of whether the DOM under test implements CSS inheritance, and the
68
+ * one these tests run against does not: every child would report no value at
69
+ * all, the skip would never fire, and a test over a real tree would pass
70
+ * whether or not this function did anything.
71
+ */
72
+ export declare function inlineDeclarationsFor(read: StyleLookup, variables: ReadonlyMap<string, string>, inherited: Inherited): {
73
+ declarations: string[];
74
+ inheritedByChildren: Map<string, string>;
75
+ };
76
+ /**
77
+ * Serialise a live chart `<svg>` into a standalone, self-contained document.
78
+ *
79
+ * Returns the markup plus the size it was measured at, because the rasteriser
80
+ * needs the same number and re-measuring after the clone is detached would give
81
+ * a different one.
82
+ */
83
+ export declare function serializeSvg(svg: SVGSVGElement, options?: SerializeSvgOptions): SerializedSvg;
84
+ /**
85
+ * The serialised document as a `data:` URI an `<img>` can load.
86
+ *
87
+ * `encodeURIComponent` rather than `btoa`: base64 needs Latin-1 and a chart
88
+ * with a `µ`, a `—` or any non-Latin label throws `InvalidCharacterError` in
89
+ * the middle of an export that had nothing to do with encoding.
90
+ */
91
+ export declare function svgToDataUri(markup: string): string;
92
+ export {};