@dudousxd/nestjs-catalog-react 0.8.0 → 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 (47) hide show
  1. package/README.md +41 -5
  2. package/dist/DashboardBoard.d.ts +22 -0
  3. package/dist/DashboardBoard.js +88 -67
  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/context.d.ts +71 -0
  12. package/dist/context.js +20 -3
  13. package/dist/embed/EmbeddedChart.d.ts +41 -0
  14. package/dist/embed/EmbeddedChart.js +25 -0
  15. package/dist/embed/EmbeddedDashboard.d.ts +32 -0
  16. package/dist/embed/EmbeddedDashboard.js +38 -0
  17. package/dist/embed/actions.d.ts +75 -0
  18. package/dist/embed/actions.js +64 -0
  19. package/dist/embed/chart-card.d.ts +20 -0
  20. package/dist/embed/chart-card.js +89 -0
  21. package/dist/embed/index.d.ts +12 -0
  22. package/dist/embed/index.js +11 -0
  23. package/dist/embed/payload.d.ts +78 -0
  24. package/dist/embed/payload.js +42 -0
  25. package/dist/embed/slots.d.ts +52 -0
  26. package/dist/embed/slots.js +44 -0
  27. package/dist/export/css-variables.d.ts +60 -0
  28. package/dist/export/css-variables.js +137 -0
  29. package/dist/export/index.d.ts +21 -0
  30. package/dist/export/index.js +21 -0
  31. package/dist/export/pdf.d.ts +136 -0
  32. package/dist/export/pdf.js +97 -0
  33. package/dist/export/png.d.ts +88 -0
  34. package/dist/export/png.js +125 -0
  35. package/dist/export/serialize.d.ts +92 -0
  36. package/dist/export/serialize.js +298 -0
  37. package/dist/export/use-pdf-export.d.ts +66 -0
  38. package/dist/export/use-pdf-export.js +63 -0
  39. package/dist/export/use-png-export.d.ts +82 -0
  40. package/dist/export/use-png-export.js +126 -0
  41. package/dist/index.d.ts +3 -1
  42. package/dist/index.js +21 -1
  43. package/dist/routes.d.ts +25 -1
  44. package/dist/routes.js +25 -1
  45. package/dist/sharing.d.ts +81 -0
  46. package/dist/sharing.js +72 -0
  47. package/package.json +2 -2
@@ -0,0 +1,298 @@
1
+ import { THEME_CUSTOM_PROPERTIES, collectCustomProperties, resolveCssVariables, } from './css-variables';
2
+ /**
3
+ * Turning a live chart `<svg>` into standalone markup that renders the same.
4
+ *
5
+ * WHAT THE PROBLEM ACTUALLY IS
6
+ * ----------------------------
7
+ * `new XMLSerializer().serializeToString(chartSvg)` is one line and produces
8
+ * something that looks right in a text editor and renders as a black shape on
9
+ * a transparent ground in an `<img>`. Three separate reasons, and each has to
10
+ * be fixed here because none of them is visible in the serialised string:
11
+ *
12
+ * 1. **The cascade does not travel.** Every colour in these charts comes from
13
+ * a Tailwind class or a theme custom property. The markup keeps the
14
+ * `class` attribute and loses the stylesheet that gave it meaning, so
15
+ * every `fill` falls back to its initial value, which is black.
16
+ * 2. **Size is not in the markup.** The responsive renderers size themselves
17
+ * from their container and emit `width="100%"`, so the standalone document
18
+ * has no intrinsic size and rasterises to whatever the canvas guesses.
19
+ * 3. **There is no background.** SVG has no page colour. A dark-theme chart
20
+ * serialised faithfully is light-on-transparent, which is invisible the
21
+ * moment it lands in a light document.
22
+ *
23
+ * So this module clones the element, walks the clone against the live tree
24
+ * copying resolved presentation styles onto it, stamps an explicit size, and
25
+ * paints a background. The source element is never touched — an export must not
26
+ * be observable in the page it exported.
27
+ */
28
+ /**
29
+ * Presentation properties copied from the live tree onto the clone.
30
+ *
31
+ * These are the inherited ones, which is why they are separate: an inherited
32
+ * property whose resolved value equals the parent's is not written at all,
33
+ * because the clone inherits it too. That is not a micro-optimisation. A
34
+ * recharts surface is several hundred elements and writing sixteen inherited
35
+ * declarations onto every one of them produced markup large enough to matter
36
+ * for the data URI the rasteriser then has to parse.
37
+ */
38
+ const INHERITED_PROPERTIES = [
39
+ 'color',
40
+ 'fill',
41
+ 'fill-opacity',
42
+ 'fill-rule',
43
+ 'stroke',
44
+ 'stroke-width',
45
+ 'stroke-opacity',
46
+ 'stroke-linecap',
47
+ 'stroke-linejoin',
48
+ 'stroke-dasharray',
49
+ 'stroke-dashoffset',
50
+ 'font-family',
51
+ 'font-size',
52
+ 'font-weight',
53
+ 'font-style',
54
+ 'letter-spacing',
55
+ 'text-anchor',
56
+ 'paint-order',
57
+ 'visibility',
58
+ ];
59
+ /**
60
+ * Non-inherited properties, each with the initial value that means "skip it".
61
+ *
62
+ * `clip-path`, `filter` and `mask` are here because they hold `url(#id)`
63
+ * references. The clone carries its own `<defs>` with the same ids, so the
64
+ * reference keeps working — dropping these is how a recharts plot area stops
65
+ * being clipped and the line runs out over the axis.
66
+ */
67
+ const NON_INHERITED_PROPERTIES = new Map([
68
+ ['opacity', '1'],
69
+ ['display', 'inline'],
70
+ ['dominant-baseline', 'auto'],
71
+ ['mix-blend-mode', 'normal'],
72
+ ['shape-rendering', 'auto'],
73
+ ['clip-path', 'none'],
74
+ ['filter', 'none'],
75
+ ['mask', 'none'],
76
+ ]);
77
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
78
+ const XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink';
79
+ /**
80
+ * The namespace a namespace declaration itself lives in.
81
+ *
82
+ * `setAttribute('xmlns', …)` looks equivalent and is not: it creates a plain
83
+ * attribute that happens to be spelled `xmlns`, and `XMLSerializer` then adds
84
+ * the real declaration as well. Two `xmlns` attributes on one element is not
85
+ * well-formed XML, and an `<img>` pointed at it fails to load with no useful
86
+ * message — the export appears to hang and then produce nothing.
87
+ */
88
+ const XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/';
89
+ /** Values that mean "there is nothing painted here". */
90
+ const TRANSPARENT = new Set(['', 'transparent', 'rgba(0, 0, 0, 0)', 'rgba(0,0,0,0)']);
91
+ /** A length that is a real number of pixels, or null for `100%`, `auto`, `em`… */
92
+ function parseLength(value) {
93
+ if (!value)
94
+ return null;
95
+ const match = /^\s*(-?[\d.]+)(px)?\s*$/.exec(value);
96
+ if (!match)
97
+ return null;
98
+ const parsed = Number.parseFloat(match[1]);
99
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
100
+ }
101
+ function parseViewBox(value) {
102
+ if (!value)
103
+ return null;
104
+ const parts = value
105
+ .trim()
106
+ .split(/[\s,]+/)
107
+ .map(Number);
108
+ if (parts.length !== 4)
109
+ return null;
110
+ const [, , width, height] = parts;
111
+ if (!Number.isFinite(width) || !Number.isFinite(height))
112
+ return null;
113
+ if (width <= 0 || height <= 0)
114
+ return null;
115
+ return { width, height };
116
+ }
117
+ /**
118
+ * How big the exported image should be, in CSS pixels.
119
+ *
120
+ * The laid-out box first, because that is what the reader is looking at. The
121
+ * `width`/`height` attributes second, and the `viewBox` last — those two only
122
+ * come up when the element has never been laid out, which is the case under
123
+ * jsdom and for an element that was built but not mounted.
124
+ */
125
+ export function resolveSvgSize(svg) {
126
+ const rect = svg.getBoundingClientRect();
127
+ if (rect.width > 0 && rect.height > 0)
128
+ return { width: rect.width, height: rect.height };
129
+ const attributeWidth = parseLength(svg.getAttribute('width'));
130
+ const attributeHeight = parseLength(svg.getAttribute('height'));
131
+ if (attributeWidth !== null && attributeHeight !== null) {
132
+ return { width: attributeWidth, height: attributeHeight };
133
+ }
134
+ const viewBox = parseViewBox(svg.getAttribute('viewBox'));
135
+ if (viewBox)
136
+ return viewBox;
137
+ throw new Error('Cannot export this chart: the <svg> has no laid-out size, no numeric width/height and no ' +
138
+ 'viewBox, so there is no honest size to rasterise it at. Export it after it has rendered, ' +
139
+ 'or pass an explicit width and height.');
140
+ }
141
+ /**
142
+ * The first painted background colour at or above `element`.
143
+ *
144
+ * Stops at `<html>`. Returns null rather than guessing so the caller can apply
145
+ * its own documented fallback instead of this function inventing white.
146
+ */
147
+ export function resolveAncestorBackground(element, read = (target) => window.getComputedStyle(target)) {
148
+ let current = element;
149
+ while (current) {
150
+ const color = read(current).getPropertyValue('background-color').trim();
151
+ if (!TRANSPARENT.has(color))
152
+ return color;
153
+ current = current.parentElement;
154
+ }
155
+ return null;
156
+ }
157
+ /**
158
+ * The declarations one element needs, and what its children will inherit.
159
+ *
160
+ * Takes a lookup rather than an `Element` so the rule that decides how much
161
+ * markup an export produces — skip an inherited value the parent already
162
+ * declared, skip a non-inherited value that equals its initial — can be checked
163
+ * against known inputs. Reading it out of a live tree instead would put it at
164
+ * the mercy of whether the DOM under test implements CSS inheritance, and the
165
+ * one these tests run against does not: every child would report no value at
166
+ * all, the skip would never fire, and a test over a real tree would pass
167
+ * whether or not this function did anything.
168
+ */
169
+ export function inlineDeclarationsFor(read, variables, inherited) {
170
+ const inheritedByChildren = new Map(inherited);
171
+ const declarations = [];
172
+ for (const property of INHERITED_PROPERTIES) {
173
+ const value = resolveCssVariables(read(property), variables);
174
+ if (!value)
175
+ continue;
176
+ inheritedByChildren.set(property, value);
177
+ if (inherited.get(property) === value)
178
+ continue;
179
+ declarations.push(`${property}:${value}`);
180
+ }
181
+ for (const [property, initial] of NON_INHERITED_PROPERTIES) {
182
+ const value = resolveCssVariables(read(property), variables);
183
+ if (!value || value === initial)
184
+ continue;
185
+ declarations.push(`${property}:${value}`);
186
+ }
187
+ return { declarations, inheritedByChildren };
188
+ }
189
+ /**
190
+ * Copy resolved presentation styles from `source` onto `clone`, depth-first.
191
+ *
192
+ * The two trees are walked in lockstep by index, which is sound because `clone`
193
+ * is a deep clone of `source` and nothing has touched either since. Reading
194
+ * from the source and writing to the clone is the whole point: the source is
195
+ * in the document and has a cascade, the clone is detached and has none.
196
+ */
197
+ function inlineStyles(source, clone, context, inherited) {
198
+ const computed = context.read(source);
199
+ const { declarations, inheritedByChildren } = inlineDeclarationsFor((property) => computed.getPropertyValue(property).trim(), context.variables, inherited);
200
+ if (declarations.length > 0) {
201
+ // Anything already inline on the clone goes last, so it still wins. It is
202
+ // also already folded into the computed value we just read, so this is
203
+ // belt and braces rather than a correction.
204
+ const existing = clone.getAttribute('style');
205
+ const own = declarations.join(';');
206
+ clone.setAttribute('style', existing ? `${own};${existing}` : own);
207
+ }
208
+ const sourceChildren = source.children;
209
+ const cloneChildren = clone.children;
210
+ for (let index = 0; index < sourceChildren.length && index < cloneChildren.length; index++) {
211
+ inlineStyles(sourceChildren[index], cloneChildren[index], context, inheritedByChildren);
212
+ }
213
+ }
214
+ function cloneSvgRoot(svg) {
215
+ const clone = svg.cloneNode(true);
216
+ if (!(clone instanceof SVGSVGElement)) {
217
+ throw new Error('Cloning the chart <svg> did not produce an <svg>; refusing to export it.');
218
+ }
219
+ return clone;
220
+ }
221
+ /**
222
+ * Serialise a live chart `<svg>` into a standalone, self-contained document.
223
+ *
224
+ * Returns the markup plus the size it was measured at, because the rasteriser
225
+ * needs the same number and re-measuring after the clone is detached would give
226
+ * a different one.
227
+ */
228
+ export function serializeSvg(svg, options = {}) {
229
+ const read = (target) => window.getComputedStyle(target);
230
+ const measured = resolveSvgSize(svg);
231
+ const width = typeof options.width === 'number' && typeof options.height === 'number'
232
+ ? options.width
233
+ : measured.width;
234
+ const height = typeof options.width === 'number' && typeof options.height === 'number'
235
+ ? options.height
236
+ : measured.height;
237
+ const names = options.customProperties
238
+ ? [...THEME_CUSTOM_PROPERTIES, ...options.customProperties]
239
+ : THEME_CUSTOM_PROPERTIES;
240
+ const variables = collectCustomProperties(svg, names, read);
241
+ const clone = cloneSvgRoot(svg);
242
+ inlineStyles(svg, clone, { variables, read }, new Map());
243
+ clone.setAttributeNS(XMLNS_NAMESPACE, 'xmlns', SVG_NAMESPACE);
244
+ clone.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:xlink', XLINK_NAMESPACE);
245
+ clone.setAttribute('width', String(width));
246
+ clone.setAttribute('height', String(height));
247
+ if (!clone.getAttribute('viewBox')) {
248
+ clone.setAttribute('viewBox', `0 0 ${width} ${height}`);
249
+ }
250
+ // The variables themselves ride along too. Every declaration we wrote is
251
+ // already substituted, so this is only for markup that carried its own
252
+ // `<style>` block — a renderer is allowed to, and dropping its variables
253
+ // would be the same black-chart failure one level down.
254
+ //
255
+ // Written into the style attribute as text rather than through
256
+ // `style.setProperty`, which is the obvious call and silently does nothing
257
+ // for custom properties in some CSSOM implementations — including the one the
258
+ // tests run against, which is how that was found.
259
+ if (variables.size > 0) {
260
+ const declared = [...variables].map(([name, value]) => `${name}:${value}`).join(';');
261
+ const existing = clone.getAttribute('style');
262
+ clone.setAttribute('style', existing ? `${declared};${existing}` : declared);
263
+ }
264
+ const background = resolveBackgroundColor(svg, options, read);
265
+ if (background) {
266
+ const rect = clone.ownerDocument.createElementNS(SVG_NAMESPACE, 'rect');
267
+ rect.setAttribute('x', '0');
268
+ rect.setAttribute('y', '0');
269
+ rect.setAttribute('width', '100%');
270
+ rect.setAttribute('height', '100%');
271
+ rect.setAttribute('fill', background);
272
+ clone.insertBefore(rect, clone.firstChild);
273
+ }
274
+ if (options.fontFaceCss) {
275
+ const style = clone.ownerDocument.createElementNS(SVG_NAMESPACE, 'style');
276
+ style.textContent = options.fontFaceCss;
277
+ clone.insertBefore(style, clone.firstChild);
278
+ }
279
+ return { markup: new XMLSerializer().serializeToString(clone), width, height };
280
+ }
281
+ function resolveBackgroundColor(svg, options, read) {
282
+ const requested = options.background ?? 'auto';
283
+ if (requested === 'transparent')
284
+ return null;
285
+ if (requested !== 'auto')
286
+ return requested;
287
+ return resolveAncestorBackground(svg, read) ?? options.fallbackBackground ?? '#ffffff';
288
+ }
289
+ /**
290
+ * The serialised document as a `data:` URI an `<img>` can load.
291
+ *
292
+ * `encodeURIComponent` rather than `btoa`: base64 needs Latin-1 and a chart
293
+ * with a `µ`, a `—` or any non-Latin label throws `InvalidCharacterError` in
294
+ * the middle of an export that had nothing to do with encoding.
295
+ */
296
+ export function svgToDataUri(markup) {
297
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;
298
+ }
@@ -0,0 +1,66 @@
1
+ import { type ChartPdfSource, type PdfSourceOptions } from './pdf';
2
+ import { type PngExportTarget } from './use-png-export';
3
+ /**
4
+ * The PDF action, as a toolbar actually needs it.
5
+ *
6
+ * The one thing this hook exists to get right is {@link PdfExport.available}.
7
+ * Everything else — pending, error, a promise that resolves rather than rejects
8
+ * — it does the same way `usePngExport` does, and for the same reasons.
9
+ *
10
+ * `available` is false unless ALL THREE of these hold, because each of them is
11
+ * a way for a rendered button to be a lie:
12
+ *
13
+ * 1. **A host registered an exporter.** This package ships no PDF renderer
14
+ * (see `pdf.ts`), so with nothing registered there is no PDF to make.
15
+ * 2. **The card has an `<svg>`.** `CssBarChart` — the no-dependency fallback —
16
+ * is a stack of `<div>`s, so `findExportableSvg` returns null and there is
17
+ * nothing to serialise or rasterise.
18
+ * 3. **The browser can rasterise.** False during SSR, and false wherever
19
+ * there is no canvas.
20
+ *
21
+ * WHY THE TARGET IS AN ARGUMENT HERE AND NOT ON THE CALL
22
+ * -----------------------------------------------------
23
+ * `usePngExport` takes the target when the export runs, and reports only the
24
+ * browser capability up front — a card with no `<svg>` finds out by clicking and
25
+ * getting an error. That was a reasonable line to draw there and it is the wrong
26
+ * one here: condition 2 has to be answered BEFORE anything is drawn, so the hook
27
+ * has to be holding the target while it renders, not when it is clicked.
28
+ *
29
+ * Which means reading the DOM, which means after the commit — so `available`
30
+ * is false for one paint and then becomes true. Unavoidable: the `<svg>` does
31
+ * not exist until the renderer has mounted, and asking earlier would just be
32
+ * guessing. It also means watching for changes, because a chart library that
33
+ * measures its container before drawing (recharts does) inserts its `<svg>`
34
+ * from its own state, with no re-render of the component holding this hook and
35
+ * therefore nothing at all to prompt a second look.
36
+ */
37
+ export interface UsePdfExportOptions extends PdfSourceOptions {
38
+ /** Called after the host's exporter resolves, e.g. to show a toast. */
39
+ onExported?: (source: ChartPdfSource) => void;
40
+ /** Called instead of the error being swallowed. The error is also returned in `error`. */
41
+ onError?: (error: Error) => void;
42
+ }
43
+ export interface PdfExport {
44
+ /**
45
+ * Whether to render the action AT ALL.
46
+ *
47
+ * Not "whether to disable it". A disabled PDF button on every card of a
48
+ * console whose host never wired an exporter advertises a feature that does
49
+ * not exist and cannot be made to exist by the person looking at it.
50
+ */
51
+ available: boolean;
52
+ /** The host's name for its own document, when it gave one. */
53
+ label: string | undefined;
54
+ /**
55
+ * Build the payload and hand it to the host's exporter.
56
+ *
57
+ * Resolves to the payload on success and to null on failure — it does not
58
+ * reject, because the caller is an `onClick` and an unhandled rejection in one
59
+ * is a console error nobody sees. `error` holds what went wrong, including
60
+ * anything the host's own exporter threw.
61
+ */
62
+ exportPdf: (overrides?: PdfSourceOptions) => Promise<ChartPdfSource | null>;
63
+ exporting: boolean;
64
+ error: Error | null;
65
+ }
66
+ export declare function usePdfExport(target: PngExportTarget, options?: UsePdfExportOptions): PdfExport;
@@ -0,0 +1,63 @@
1
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
2
+ import { exportSvgAsPdf, getPdfExporter, subscribeToPdfExporter, } from './pdf';
3
+ import { findExportableSvg } from './png';
4
+ import { canRasterise, toExportError, unwrapExportTarget, useHasExportableSvg, } from './use-png-export';
5
+ export function usePdfExport(target, options = {}) {
6
+ const [exporting, setExporting] = useState(false);
7
+ const [error, setError] = useState(null);
8
+ // The exporter object itself is the snapshot: it only changes when somebody
9
+ // registers, so the reference is stable between renders and
10
+ // `useSyncExternalStore` will not loop on it.
11
+ const exporter = useSyncExternalStore(subscribeToPdfExporter, getPdfExporter, () => undefined);
12
+ // Target and options both read through a ref inside the callback, so
13
+ // `exportPdf` keeps its identity when the caller passes an inline object —
14
+ // which is every caller — and a memoised toolbar does not re-render with its
15
+ // parent.
16
+ const latest = useRef({ target, options });
17
+ latest.current = { target, options };
18
+ const mounted = useRef(true);
19
+ useEffect(() => {
20
+ mounted.current = true;
21
+ return () => {
22
+ mounted.current = false;
23
+ };
24
+ }, []);
25
+ // One implementation of "is there an `<svg>` here yet", shared with the
26
+ // toolbar that decides whether a PNG action exists — including the
27
+ // MutationObserver, which is what makes it true for recharts.
28
+ const hasSvg = useHasExportableSvg(target);
29
+ const exportPdf = useCallback(async (overrides) => {
30
+ const { target: current, options: settings } = latest.current;
31
+ const { onExported, onError, ...base } = settings;
32
+ setExporting(true);
33
+ setError(null);
34
+ try {
35
+ const svg = findExportableSvg(unwrapExportTarget(current));
36
+ if (!svg) {
37
+ throw new Error('Nothing to export: no <svg> was found in this card. The built-in CSS chart draws with ' +
38
+ 'elements that cannot be serialised; register a chart library to export it.');
39
+ }
40
+ const source = await exportSvgAsPdf(svg, { ...base, ...overrides });
41
+ onExported?.(source);
42
+ return source;
43
+ }
44
+ catch (thrown) {
45
+ const failure = toExportError(thrown);
46
+ if (mounted.current)
47
+ setError(failure);
48
+ onError?.(failure);
49
+ return null;
50
+ }
51
+ finally {
52
+ if (mounted.current)
53
+ setExporting(false);
54
+ }
55
+ }, []);
56
+ return {
57
+ available: exporter !== undefined && hasSvg && canRasterise(),
58
+ label: exporter?.label,
59
+ exportPdf,
60
+ exporting,
61
+ error,
62
+ };
63
+ }
@@ -0,0 +1,82 @@
1
+ import { type PngExportOptions } from './png';
2
+ /**
3
+ * The export action, as a component actually needs it.
4
+ *
5
+ * Three things a toolbar button has to know and none of which the plain
6
+ * functions can tell it: whether the action is possible at all, whether one is
7
+ * in flight, and what went wrong. Rasterising is asynchronous — a chart of any
8
+ * size takes long enough that a button with no pending state gets clicked three
9
+ * times and produces three files.
10
+ *
11
+ * `supported` is the one that changes what gets rendered rather than how. A
12
+ * card drawn by the CSS fallback renderer has no `<svg>` to serialise, so the
13
+ * honest thing is for no export control to appear on it, exactly as the chart
14
+ * library picker offers only the libraries somebody registered. It is
15
+ * deliberately a value the caller reads, not something this hook enforces by
16
+ * throwing when clicked.
17
+ */
18
+ /** A DOM element, or a ref to one. Structural rather than `RefObject` so React's typings can move. */
19
+ export type PngExportTarget = Element | {
20
+ current: Element | null;
21
+ } | null | undefined;
22
+ export interface UsePngExportOptions extends PngExportOptions {
23
+ /** Fixed name, or one computed per export. Defaults to a timestamped `chart-….png`. */
24
+ filename?: string | (() => string);
25
+ /** Called after a successful export, e.g. to show a toast. */
26
+ onExported?: (blob: Blob, filename: string) => void;
27
+ /** Called instead of the error being swallowed. The error is also returned in `error`. */
28
+ onError?: (error: Error) => void;
29
+ }
30
+ export interface PngExport {
31
+ /**
32
+ * Rasterise the chart inside `target` and download it.
33
+ *
34
+ * Resolves to the blob on success and to null on failure — it does not
35
+ * reject, because the caller is an `onClick` and an unhandled rejection in
36
+ * one is a console error nobody sees. `error` holds what went wrong.
37
+ */
38
+ exportPng: (target: PngExportTarget, overrides?: PngExportOptions) => Promise<Blob | null>;
39
+ /** The same render, returned rather than downloaded. For a clipboard copy or an upload. */
40
+ renderPng: (target: PngExportTarget, overrides?: PngExportOptions) => Promise<Blob | null>;
41
+ exporting: boolean;
42
+ error: Error | null;
43
+ /** Whether this browser can rasterise at all. False during SSR. */
44
+ supported: boolean;
45
+ }
46
+ /**
47
+ * The element behind a target, whichever of the two forms it came in.
48
+ *
49
+ * Exported for `use-pdf-export.ts`, which has the same job and must resolve a
50
+ * target exactly the same way — the two hooks disagreeing about what counts as
51
+ * a target would mean one action appearing on a card and the other not.
52
+ */
53
+ export declare function unwrapExportTarget(target: PngExportTarget): Element | null;
54
+ /** Whatever was thrown, as an `Error`. Shared with the PDF hook for the same reason. */
55
+ export declare function toExportError(thrown: unknown): Error;
56
+ /**
57
+ * Whether the browser has the two things the pipeline cannot be written without.
58
+ *
59
+ * Cached, because it is read on every render of every card that offers the
60
+ * action and the check allocates a canvas to ask.
61
+ */
62
+ export declare function canRasterise(): boolean;
63
+ export declare function usePngExport(options?: UsePngExportOptions): PngExport;
64
+ /**
65
+ * Whether this target has an `<svg>` that can be exported, right now.
66
+ *
67
+ * A hook rather than a function because the answer changes after mount and the
68
+ * caller needs to re-render when it does. Two things make that true, and both
69
+ * were learned the hard way:
70
+ *
71
+ * - The element is only knowable after a commit, so on the first render there
72
+ * is nothing to look at. Hence no dependency array — keying on the null the
73
+ * first render sees would mean never looking again.
74
+ * - Recharts measures its container and then inserts its `<svg>` from its own
75
+ * state, with no React render to prompt a second look. Without the observer,
76
+ * the answer stays `false` forever on exactly the renderer that most needs it.
77
+ *
78
+ * The built-in CSS bar chart draws with divs, so this is permanently `false`
79
+ * there — which is the point: a caller uses it to offer no action rather than
80
+ * one that fails on click.
81
+ */
82
+ export declare function useHasExportableSvg(target: PngExportTarget): boolean;
@@ -0,0 +1,126 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { defaultPngFilename, downloadSvgAsPng, findExportableSvg, svgToPngBlob, } from './png';
3
+ /**
4
+ * The element behind a target, whichever of the two forms it came in.
5
+ *
6
+ * Exported for `use-pdf-export.ts`, which has the same job and must resolve a
7
+ * target exactly the same way — the two hooks disagreeing about what counts as
8
+ * a target would mean one action appearing on a card and the other not.
9
+ */
10
+ export function unwrapExportTarget(target) {
11
+ if (!target)
12
+ return null;
13
+ if (target instanceof Element)
14
+ return target;
15
+ const current = target.current;
16
+ return current instanceof Element ? current : null;
17
+ }
18
+ /** Whatever was thrown, as an `Error`. Shared with the PDF hook for the same reason. */
19
+ export function toExportError(thrown) {
20
+ return thrown instanceof Error ? thrown : new Error(String(thrown));
21
+ }
22
+ let rasteriseSupport = null;
23
+ /**
24
+ * Whether the browser has the two things the pipeline cannot be written without.
25
+ *
26
+ * Cached, because it is read on every render of every card that offers the
27
+ * action and the check allocates a canvas to ask.
28
+ */
29
+ export function canRasterise() {
30
+ if (rasteriseSupport !== null)
31
+ return rasteriseSupport;
32
+ if (typeof window === 'undefined' || typeof document === 'undefined')
33
+ return false;
34
+ const supported = typeof XMLSerializer === 'function' &&
35
+ typeof document.createElement('canvas').toBlob === 'function';
36
+ rasteriseSupport = supported;
37
+ return supported;
38
+ }
39
+ export function usePngExport(options = {}) {
40
+ const [exporting, setExporting] = useState(false);
41
+ const [error, setError] = useState(null);
42
+ // Every option, read through a ref inside the callbacks. Without it the
43
+ // callbacks change identity whenever the caller passes an inline object —
44
+ // which is every caller — and a memoised toolbar re-renders on each parent
45
+ // render for no reason.
46
+ const latest = useRef(options);
47
+ latest.current = options;
48
+ const mounted = useRef(true);
49
+ useEffect(() => {
50
+ mounted.current = true;
51
+ return () => {
52
+ mounted.current = false;
53
+ };
54
+ }, []);
55
+ const run = useCallback(async (target, overrides, download) => {
56
+ const { filename, onExported, onError, ...base } = latest.current;
57
+ const settings = { ...base, ...overrides };
58
+ setExporting(true);
59
+ setError(null);
60
+ try {
61
+ const svg = findExportableSvg(unwrapExportTarget(target));
62
+ if (!svg) {
63
+ throw new Error('Nothing to export: no <svg> was found in this card. The built-in CSS chart draws with ' +
64
+ 'elements a canvas cannot rasterise; register a chart library to export it.');
65
+ }
66
+ const name = typeof filename === 'function' ? filename() : (filename ?? defaultPngFilename());
67
+ const blob = download
68
+ ? await downloadSvgAsPng(svg, name, settings)
69
+ : await svgToPngBlob(svg, settings);
70
+ onExported?.(blob, name);
71
+ return blob;
72
+ }
73
+ catch (thrown) {
74
+ const failure = toExportError(thrown);
75
+ if (mounted.current)
76
+ setError(failure);
77
+ onError?.(failure);
78
+ return null;
79
+ }
80
+ finally {
81
+ if (mounted.current)
82
+ setExporting(false);
83
+ }
84
+ }, []);
85
+ const exportPng = useCallback((target, overrides) => run(target, overrides, true), [run]);
86
+ const renderPng = useCallback((target, overrides) => run(target, overrides, false), [run]);
87
+ return { exportPng, renderPng, exporting, error, supported: canRasterise() };
88
+ }
89
+ /**
90
+ * Whether this target has an `<svg>` that can be exported, right now.
91
+ *
92
+ * A hook rather than a function because the answer changes after mount and the
93
+ * caller needs to re-render when it does. Two things make that true, and both
94
+ * were learned the hard way:
95
+ *
96
+ * - The element is only knowable after a commit, so on the first render there
97
+ * is nothing to look at. Hence no dependency array — keying on the null the
98
+ * first render sees would mean never looking again.
99
+ * - Recharts measures its container and then inserts its `<svg>` from its own
100
+ * state, with no React render to prompt a second look. Without the observer,
101
+ * the answer stays `false` forever on exactly the renderer that most needs it.
102
+ *
103
+ * The built-in CSS bar chart draws with divs, so this is permanently `false`
104
+ * there — which is the point: a caller uses it to offer no action rather than
105
+ * one that fails on click.
106
+ */
107
+ export function useHasExportableSvg(target) {
108
+ const [hasSvg, setHasSvg] = useState(false);
109
+ const latest = useRef(target);
110
+ latest.current = target;
111
+ useEffect(() => {
112
+ const element = unwrapExportTarget(latest.current);
113
+ const check = () => {
114
+ const found = findExportableSvg(element) !== null;
115
+ // Guarded, so this does not feed itself through the missing dep array.
116
+ setHasSvg((current) => (current === found ? current : found));
117
+ };
118
+ check();
119
+ if (!element || typeof MutationObserver !== 'function')
120
+ return;
121
+ const observer = new MutationObserver(check);
122
+ observer.observe(element, { childList: true, subtree: true });
123
+ return () => observer.disconnect();
124
+ });
125
+ return hasSvg;
126
+ }
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export { DashboardBoard } from './DashboardBoard';
7
7
  export { CHART_COLORS, type ChartRenderer, type ChartRendererProps, getChartRenderer, registerChartRenderer, registeredChartLibraries, seriesFrom, } from './charts/registry';
8
8
  export { ChartEmpty, ChartFailed, ChartSkeleton, type ChartSkeletonProps, } from './charts/skeleton';
9
9
  export { CssBarChart, looksLikeTimeSeries } from './charts/css';
10
+ export { EMBED_ACTIONS, type EmbedAction, type EmbedActions, EmbeddedChart, type EmbeddedChartPayload, type EmbeddedChartProps, EmbeddedDashboard, type EmbeddedDashboardPayload, type EmbeddedDashboardProps, type EmbedFailureSlot, type EmbedLoadingSlot, chartsInLayoutOrder, resolveEmbedActions, } from './embed';
10
11
  export { FlowView } from './FlowView';
11
12
  export { GovernanceTimeline } from './GovernanceTimeline';
12
13
  export { QueryConsole, type QueryConsoleProps } from './QueryConsole';
@@ -20,7 +21,7 @@ export { type CatalogWorkflow, describeDurability, isWorkflowNodeKind, newLocalI
20
21
  export { WORKFLOW_NAME } from './workflow/name';
21
22
  export { canConnect, type ConnectionVerdict, edgeId, hasBlockingProblem, problemsByNode, validateWorkflow, type WorkflowProblem, type WorkflowProblemCode, wouldCycle, } from './workflow/validate';
22
23
  export { type CatalogClient, type CatalogIdentity, type CatalogPersonRole, type CatalogPersonSummary, type CatalogPrincipalSummary, CatalogProvider, type CatalogProviderProps, type CatalogTransport, type ConnectionInput, type ConnectorInput, catalogQueryKeys, type PersonInput, type PersonUpsertResult, type PipelineCapabilities, type TransformInput, useCatalogClient, } from './context';
23
- export { type AccessRoutes, accessRoutes, DEFAULT_ACCESS_BASE_PATH, DEFAULT_PIPELINE_BASE_PATH, type PipelineRoutes, pipelineRoutes, } from './routes';
24
+ export { type AccessRoutes, accessRoutes, DEFAULT_ACCESS_BASE_PATH, DEFAULT_PIPELINE_BASE_PATH, embedRoutes, type PipelineRoutes, pipelineRoutes, } from './routes';
24
25
  export { ConfirmDialog } from './ui/dialog';
25
26
  export { FieldGroup, TextAreaField, TextField } from './ui/field';
26
27
  export { Select, SelectField, type SelectOption } from './ui/select';
@@ -31,3 +32,4 @@ export { RichTextField, RichTextView, type RichTextFieldProps, } from './ui/rich
31
32
  export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './ui/button';
32
33
  export { Tabs, TabsList, TabsPanel, TabsTab } from './ui/tabs';
33
34
  export { Tooltip, TooltipProvider } from './ui/tooltip';
35
+ export { buildChartPdfSource, canRasterise, type ChartPdfExporter, type ChartPdfSource, defaultPngFilename, downloadSvgAsPng, type ExportBackground, exportSvgAsPdf, findExportableSvg, getPdfExporter, type PdfExport, type PdfSourceOptions, type PngExport, type PngExportOptions, type PngExportTarget, rasteriseSerializedSvg, registerPdfExporter, serializeSvg, subscribeToPdfExporter, type SvgRasteriser, svgToPngBlob, useHasExportableSvg, usePdfExport, usePngExport, } from './export';