@opendata-ai/openchart-vanilla 8.0.0-rc.2 → 8.0.0-rc.21
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.
- package/dist/{chunk-W34KN7FD.js → chunk-2NAQRP66.js} +2 -2
- package/dist/chunk-DCODCLWI.js +234 -0
- package/dist/chunk-DCODCLWI.js.map +1 -0
- package/dist/{chunk-5EOV5JQZ.js → chunk-EKAUQAAX.js} +50 -46
- package/dist/chunk-EKAUQAAX.js.map +1 -0
- package/dist/{chunk-ENXSUXC5.js → chunk-KNT5AZ2O.js} +7309 -5490
- package/dist/chunk-KNT5AZ2O.js.map +1 -0
- package/dist/chunk-RM5XS6NR.js +113 -0
- package/dist/chunk-RM5XS6NR.js.map +1 -0
- package/dist/chunk-T32UHMZA.js +282 -0
- package/dist/chunk-T32UHMZA.js.map +1 -0
- package/dist/export-gif.d.ts +113 -0
- package/dist/export-gif.js +21 -0
- package/dist/export-gif.js.map +1 -0
- package/dist/index.d.ts +283 -24
- package/dist/index.js +2012 -763
- package/dist/index.js.map +1 -1
- package/dist/{mount-CUKQLeqD.d.ts → mount-Dvv8NYIv.d.ts} +117 -3
- package/dist/simulation-worker.js +83 -2
- package/dist/static.js +7 -69
- package/dist/static.js.map +1 -1
- package/dist/story/index.d.ts +3 -2
- package/dist/story/index.js +5 -3
- package/dist/story/index.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/styles.css.map +1 -1
- package/package.json +14 -6
- package/dist/chunk-5EOV5JQZ.js.map +0 -1
- package/dist/chunk-ENXSUXC5.js.map +0 -1
- package/src/__test-fixtures__/dom.ts +0 -70
- package/src/__test-fixtures__/specs.ts +0 -214
- package/src/__tests__/animation.test.ts +0 -358
- package/src/__tests__/annotations-render.test.ts +0 -201
- package/src/__tests__/compound-labels.test.ts +0 -122
- package/src/__tests__/continuous-legend.test.ts +0 -91
- package/src/__tests__/crosshair.test.ts +0 -130
- package/src/__tests__/edit-events.test.ts +0 -902
- package/src/__tests__/events.test.ts +0 -387
- package/src/__tests__/export.test.ts +0 -241
- package/src/__tests__/font-race.test.ts +0 -199
- package/src/__tests__/gradient-ids.test.ts +0 -159
- package/src/__tests__/gradient-utils.test.ts +0 -125
- package/src/__tests__/known-bugs-render.test.ts +0 -183
- package/src/__tests__/map.test.ts +0 -293
- package/src/__tests__/mount.test.ts +0 -357
- package/src/__tests__/pattern-fills.test.ts +0 -105
- package/src/__tests__/resize-timing.test.ts +0 -218
- package/src/__tests__/sankey.test.ts +0 -133
- package/src/__tests__/selection-events.test.ts +0 -869
- package/src/__tests__/series-search.test.ts +0 -311
- package/src/__tests__/static.test.ts +0 -141
- package/src/__tests__/svg-renderer.test.ts +0 -895
- package/src/__tests__/table-keyboard.test.ts +0 -361
- package/src/__tests__/table-mount.test.ts +0 -639
- package/src/__tests__/tilemap.test.ts +0 -158
- package/src/__tests__/tooltip.test.ts +0 -337
- package/src/__tests__/transition.test.ts +0 -1777
- package/src/__tests__/you-draw-it.test.ts +0 -273
- package/src/animation-vars.ts +0 -42
- package/src/animation.ts +0 -76
- package/src/barlist-mount.ts +0 -383
- package/src/barlist-renderer.ts +0 -267
- package/src/dom-helpers.ts +0 -17
- package/src/export.ts +0 -482
- package/src/gradient-utils.ts +0 -138
- package/src/graph/__tests__/canvas-renderer.test.ts +0 -713
- package/src/graph/__tests__/graph-mount.test.ts +0 -213
- package/src/graph/__tests__/interaction.test.ts +0 -205
- package/src/graph/__tests__/keyboard.test.ts +0 -653
- package/src/graph/__tests__/search.test.ts +0 -88
- package/src/graph/__tests__/simulation.test.ts +0 -233
- package/src/graph/__tests__/spatial-index.test.ts +0 -142
- package/src/graph/__tests__/zoom.test.ts +0 -203
- package/src/graph/canvas-renderer.ts +0 -747
- package/src/graph/interaction.ts +0 -367
- package/src/graph/keyboard.ts +0 -208
- package/src/graph/search.ts +0 -50
- package/src/graph/simulation-worker-url.ts +0 -12
- package/src/graph/simulation-worker.ts +0 -278
- package/src/graph/simulation.ts +0 -422
- package/src/graph/spatial-index.ts +0 -121
- package/src/graph/types.ts +0 -47
- package/src/graph/worker-protocol.ts +0 -70
- package/src/graph/zoom.ts +0 -134
- package/src/graph-mount.ts +0 -888
- package/src/index.ts +0 -76
- package/src/interactions/chart-events.ts +0 -139
- package/src/interactions/crosshair.ts +0 -233
- package/src/interactions/drag-handler.ts +0 -175
- package/src/interactions/editing-drags.ts +0 -515
- package/src/interactions/index.ts +0 -25
- package/src/interactions/keyboard-nav.ts +0 -111
- package/src/interactions/legend-interaction.ts +0 -46
- package/src/interactions/selection.ts +0 -280
- package/src/interactions/tooltip-events.ts +0 -72
- package/src/map-camera.ts +0 -88
- package/src/map-mount.ts +0 -701
- package/src/map-renderer.ts +0 -338
- package/src/map-transition.ts +0 -83
- package/src/measure-text.ts +0 -134
- package/src/mount.ts +0 -1382
- package/src/pattern-utils.ts +0 -110
- package/src/renderers/annotations.ts +0 -388
- package/src/renderers/axes.ts +0 -351
- package/src/renderers/brand.ts +0 -87
- package/src/renderers/chrome.ts +0 -196
- package/src/renderers/endpoint-labels.ts +0 -150
- package/src/renderers/legend.ts +0 -311
- package/src/renderers/marks.ts +0 -561
- package/src/renderers/metrics.ts +0 -63
- package/src/renderers/svg-dom.ts +0 -40
- package/src/renderers/table-cells.ts +0 -446
- package/src/resize-observer.ts +0 -46
- package/src/sankey-mount.ts +0 -622
- package/src/sankey-renderer.ts +0 -614
- package/src/series-search.ts +0 -392
- package/src/static.ts +0 -251
- package/src/story/__tests__/camera-math.test.ts +0 -145
- package/src/story/__tests__/create-chart-story.test.ts +0 -317
- package/src/story/__tests__/progress-math.test.ts +0 -95
- package/src/story/__tests__/scroll-driver.test.ts +0 -130
- package/src/story/__tests__/tween.test.ts +0 -159
- package/src/story/camera-math.ts +0 -125
- package/src/story/create-chart-story.ts +0 -353
- package/src/story/crossfade.ts +0 -70
- package/src/story/index.ts +0 -39
- package/src/story/progress-math.ts +0 -85
- package/src/story/resolve-camera-target.ts +0 -119
- package/src/story/scroll-driver.ts +0 -206
- package/src/story/story-camera.ts +0 -49
- package/src/story/tween.ts +0 -112
- package/src/story/types.ts +0 -76
- package/src/svg-ids.ts +0 -23
- package/src/svg-renderer.ts +0 -383
- package/src/table-keyboard.ts +0 -266
- package/src/table-mount.ts +0 -567
- package/src/table-renderer.ts +0 -414
- package/src/text-edit-overlay.ts +0 -255
- package/src/theme-tokens.ts +0 -51
- package/src/tilemap-mount.ts +0 -511
- package/src/tilemap-renderer.ts +0 -396
- package/src/tooltip.ts +0 -177
- package/src/transition.ts +0 -2816
- package/src/you-draw-it.ts +0 -480
- /package/dist/{chunk-W34KN7FD.js.map → chunk-2NAQRP66.js.map} +0 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// src/renderers/svg-dom.ts
|
|
2
|
+
var SVG_NS = "http://www.w3.org/2000/svg";
|
|
3
|
+
var XLINK_NS = "http://www.w3.org/1999/xlink";
|
|
4
|
+
function createSVGElement(tag) {
|
|
5
|
+
return document.createElementNS(SVG_NS, tag);
|
|
6
|
+
}
|
|
7
|
+
function setAttrs(el, attrs) {
|
|
8
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
9
|
+
el.setAttribute(key, String(value));
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function applyTextStyle(el, style) {
|
|
13
|
+
const inline = el.style;
|
|
14
|
+
inline.setProperty("fill", style.fill);
|
|
15
|
+
inline.setProperty("font-size", `${style.fontSize}px`);
|
|
16
|
+
inline.setProperty("font-weight", String(style.fontWeight));
|
|
17
|
+
inline.setProperty("font-family", style.fontFamily);
|
|
18
|
+
if (style.textAnchor) {
|
|
19
|
+
el.setAttribute("text-anchor", style.textAnchor);
|
|
20
|
+
}
|
|
21
|
+
if (style.dominantBaseline) {
|
|
22
|
+
el.setAttribute("dominant-baseline", style.dominantBaseline);
|
|
23
|
+
}
|
|
24
|
+
if (style.fontVariant) {
|
|
25
|
+
el.setAttribute("font-variant", style.fontVariant);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/theme-style-block.ts
|
|
30
|
+
import { adaptForLightLineStroke, cssTokenDefault } from "@opendata-ai/openchart-core";
|
|
31
|
+
function buildThemeStyleBlock(theme) {
|
|
32
|
+
const accent = theme.colors.categorical[0] ?? cssTokenDefault("--oc-accent", "light");
|
|
33
|
+
const bg = theme.colors.background === "transparent" ? theme.isDark ? cssTokenDefault("--oc-bg", "dark") : cssTokenDefault("--oc-bg", "light") : theme.colors.background;
|
|
34
|
+
const props = [
|
|
35
|
+
`--oc-font-family: ${theme.fonts.family}`,
|
|
36
|
+
`--oc-font-mono: ${theme.fonts.mono}`,
|
|
37
|
+
`--oc-title-size: ${theme.chrome.title.fontSize}px`,
|
|
38
|
+
`--oc-title-weight: ${theme.chrome.title.fontWeight}`,
|
|
39
|
+
`--oc-title-tracking: ${cssTokenDefault("--oc-title-tracking", "light")}`,
|
|
40
|
+
`--oc-subtitle-size: ${theme.chrome.subtitle.fontSize}px`,
|
|
41
|
+
`--oc-subtitle-weight: ${theme.chrome.subtitle.fontWeight}`,
|
|
42
|
+
`--oc-source-size: ${theme.chrome.source.fontSize}px`,
|
|
43
|
+
`--oc-source-weight: ${theme.chrome.source.fontWeight}`,
|
|
44
|
+
`--oc-body-size: ${theme.fonts.sizes.body}px`,
|
|
45
|
+
`--oc-eyebrow-size: ${theme.chrome.eyebrow.fontSize}px`,
|
|
46
|
+
`--oc-eyebrow-weight: ${theme.chrome.eyebrow.fontWeight}`,
|
|
47
|
+
`--oc-eyebrow-tracking: ${cssTokenDefault("--oc-eyebrow-tracking", "light")}`,
|
|
48
|
+
`--oc-bg: ${bg}`,
|
|
49
|
+
`--oc-text: ${theme.colors.text}`,
|
|
50
|
+
`--oc-text-muted: ${theme.colors.axis}`,
|
|
51
|
+
`--oc-text-faint: ${theme.isDark ? cssTokenDefault("--oc-text-faint", "dark") : cssTokenDefault("--oc-text-faint", "light")}`,
|
|
52
|
+
`--oc-gridline: ${theme.colors.gridline}`,
|
|
53
|
+
`--oc-axis: ${theme.colors.axis}`,
|
|
54
|
+
`--oc-border-radius: ${theme.borderRadius}px`,
|
|
55
|
+
`--oc-accent: ${accent}`,
|
|
56
|
+
`--oc-accent-strong: ${adaptForLightLineStroke(accent)}`,
|
|
57
|
+
`--oc-positive: ${theme.colors.positive}`,
|
|
58
|
+
`--oc-negative: ${theme.colors.negative}`,
|
|
59
|
+
`--oc-legend-text: ${theme.isDark ? cssTokenDefault("--oc-legend-text", "dark") : cssTokenDefault("--oc-legend-text", "light")}`,
|
|
60
|
+
`--oc-space-2: ${theme.spacing.chromeGap * 2}px`,
|
|
61
|
+
`--oc-space-4: ${theme.spacing.padding}px`
|
|
62
|
+
];
|
|
63
|
+
const rules = [
|
|
64
|
+
`svg.oc-chart { ${props.join("; ")}; }`,
|
|
65
|
+
`.oc-chrome { font-family: var(--oc-font-family); }`,
|
|
66
|
+
`.oc-eyebrow { font-size: var(--oc-eyebrow-size); font-weight: var(--oc-eyebrow-weight); letter-spacing: var(--oc-eyebrow-tracking); text-transform: uppercase; fill: var(--oc-accent); }`,
|
|
67
|
+
`.oc-title { font-size: var(--oc-title-size); font-weight: var(--oc-title-weight); letter-spacing: var(--oc-title-tracking); fill: var(--oc-text); }`,
|
|
68
|
+
`.oc-subtitle { font-size: var(--oc-subtitle-size); font-weight: var(--oc-subtitle-weight); fill: var(--oc-text-muted); }`,
|
|
69
|
+
`.oc-source, .oc-byline, .oc-footer { font-size: var(--oc-source-size); font-weight: var(--oc-source-weight); fill: var(--oc-text-muted); }`,
|
|
70
|
+
`.oc-brand { font-size: 11px; font-weight: 510; letter-spacing: 0.02em; fill: var(--oc-text-faint); }`,
|
|
71
|
+
`.oc-brand-dot { fill: var(--oc-accent); }`,
|
|
72
|
+
`.oc-eyebrow-dot { fill: var(--oc-accent); }`,
|
|
73
|
+
`.oc-metrics { font-family: var(--oc-font-family); }`,
|
|
74
|
+
`.oc-metric-label { font-size: 10px; font-weight: 510; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--oc-text-muted); }`,
|
|
75
|
+
`.oc-metric-value { font-size: 22px; font-weight: 510; letter-spacing: -0.01em; fill: var(--oc-text); font-variant-numeric: tabular-nums; }`,
|
|
76
|
+
`.oc-metric-delta-up { fill: var(--oc-positive); font-size: 12px; font-weight: 510; }`,
|
|
77
|
+
`.oc-metric-delta-down { fill: var(--oc-negative); font-size: 12px; font-weight: 510; }`,
|
|
78
|
+
`.oc-axis-tick-inline { font-size: 11px; font-weight: 400; fill: var(--oc-text-muted); }`,
|
|
79
|
+
`.oc-endpoint-labels { font-family: var(--oc-font-family); }`,
|
|
80
|
+
`.oc-endpoint-label { fill: var(--oc-endpoint-label-color, var(--oc-text)); }`,
|
|
81
|
+
`.oc-endpoint-value { fill: var(--oc-endpoint-value-color, var(--oc-text-muted)); }`,
|
|
82
|
+
`.oc-endpoint-leader { stroke: var(--oc-endpoint-leader-color, currentColor); }`,
|
|
83
|
+
`.oc-annotation-subtitle { fill: var(--oc-annotation-subtitle-color, var(--oc-text-muted)); }`,
|
|
84
|
+
`.oc-metric-secondary { fill: var(--oc-positive); font-size: 12px; font-weight: 400; }`,
|
|
85
|
+
`.oc-legend { font-family: var(--oc-font-family); font-size: var(--oc-body-size); }`,
|
|
86
|
+
`.oc-legend-entry { cursor: default; }`,
|
|
87
|
+
`.oc-legend text { fill: var(--oc-legend-text); }`
|
|
88
|
+
];
|
|
89
|
+
return rules.join("\n");
|
|
90
|
+
}
|
|
91
|
+
function injectThemeStyleBlock(svg, theme) {
|
|
92
|
+
if (!theme) return;
|
|
93
|
+
let defs = svg.querySelector("defs");
|
|
94
|
+
if (!defs) {
|
|
95
|
+
defs = document.createElementNS(SVG_NS, "defs");
|
|
96
|
+
svg.insertBefore(defs, svg.firstChild);
|
|
97
|
+
}
|
|
98
|
+
const style = document.createElementNS(SVG_NS, "style");
|
|
99
|
+
style.setAttribute("data-oc-theme", "");
|
|
100
|
+
style.textContent = buildThemeStyleBlock(theme);
|
|
101
|
+
defs.insertBefore(style, defs.firstChild);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export {
|
|
105
|
+
SVG_NS,
|
|
106
|
+
XLINK_NS,
|
|
107
|
+
createSVGElement,
|
|
108
|
+
setAttrs,
|
|
109
|
+
applyTextStyle,
|
|
110
|
+
buildThemeStyleBlock,
|
|
111
|
+
injectThemeStyleBlock
|
|
112
|
+
};
|
|
113
|
+
//# sourceMappingURL=chunk-RM5XS6NR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/renderers/svg-dom.ts","../src/theme-style-block.ts"],"sourcesContent":["/**\n * Shared SVG DOM helpers used across the per-concern renderers.\n *\n * Pure, stateless utilities. No layout/theme knowledge.\n */\n\nimport type { TextStyle } from '@opendata-ai/openchart-core';\n\nexport const SVG_NS = 'http://www.w3.org/2000/svg';\nexport const XLINK_NS = 'http://www.w3.org/1999/xlink';\n\nexport function createSVGElement(tag: string): SVGElement {\n return document.createElementNS(SVG_NS, tag);\n}\n\nexport function setAttrs(el: SVGElement, attrs: Record<string, string | number>): void {\n for (const [key, value] of Object.entries(attrs)) {\n el.setAttribute(key, String(value));\n }\n}\n\nexport function applyTextStyle(el: SVGElement, style: TextStyle): void {\n // Use inline styles so engine-computed values take priority over CSS class\n // defaults (e.g. .oc-title { font-size: var(--oc-title-size) } would otherwise\n // override the responsive scaling applied by the chrome layout).\n const inline = (el as SVGElement & ElementCSSInlineStyle).style;\n inline.setProperty('fill', style.fill);\n inline.setProperty('font-size', `${style.fontSize}px`);\n inline.setProperty('font-weight', String(style.fontWeight));\n inline.setProperty('font-family', style.fontFamily);\n if (style.textAnchor) {\n el.setAttribute('text-anchor', style.textAnchor);\n }\n if (style.dominantBaseline) {\n el.setAttribute('dominant-baseline', style.dominantBaseline);\n }\n if (style.fontVariant) {\n el.setAttribute('font-variant', style.fontVariant);\n }\n}\n","/**\n * Theme `<style>` block for self-contained SVG export.\n *\n * Charts render most fills as inline SVG attributes, but a handful of chrome\n * elements (metric cells, the brand watermark dot, legend text, endpoint labels)\n * take their fill from CSS classes in `chrome.css` via `--oc-*` variables. That\n * works on-screen because the live SVG inherits the page stylesheet — but a\n * serialized/rasterized export (PNG/JPG/GIF) is detached from the page, so those\n * class-based fills vanish. This module builds a `<style>` block that resolves\n * every such rule against a concrete `ResolvedTheme`, so injecting it into an\n * export clone makes the SVG fully self-contained.\n *\n * Both the headless renderer (`static.ts`) and the browser export path use this,\n * so class-based styling round-trips identically no matter which path produced\n * the SVG. Browser-safe (no Node imports) so the browser exporters can import it.\n */\n\nimport type { ResolvedTheme } from '@opendata-ai/openchart-core';\nimport { adaptForLightLineStroke, cssTokenDefault } from '@opendata-ai/openchart-core';\nimport { SVG_NS } from './renderers/svg-dom';\n\n/**\n * Build the theme `<style>` block CSS text for a resolved theme. Sets the\n * `--oc-*` custom properties on `svg.oc-chart` and defines every class-based\n * chrome rule against them.\n */\nexport function buildThemeStyleBlock(theme: ResolvedTheme): string {\n const accent = theme.colors.categorical[0] ?? cssTokenDefault('--oc-accent', 'light');\n const bg =\n theme.colors.background === 'transparent'\n ? theme.isDark\n ? cssTokenDefault('--oc-bg', 'dark')\n : cssTokenDefault('--oc-bg', 'light')\n : theme.colors.background;\n\n const props = [\n `--oc-font-family: ${theme.fonts.family}`,\n `--oc-font-mono: ${theme.fonts.mono}`,\n `--oc-title-size: ${theme.chrome.title.fontSize}px`,\n `--oc-title-weight: ${theme.chrome.title.fontWeight}`,\n `--oc-title-tracking: ${cssTokenDefault('--oc-title-tracking', 'light')}`,\n `--oc-subtitle-size: ${theme.chrome.subtitle.fontSize}px`,\n `--oc-subtitle-weight: ${theme.chrome.subtitle.fontWeight}`,\n `--oc-source-size: ${theme.chrome.source.fontSize}px`,\n `--oc-source-weight: ${theme.chrome.source.fontWeight}`,\n `--oc-body-size: ${theme.fonts.sizes.body}px`,\n `--oc-eyebrow-size: ${theme.chrome.eyebrow.fontSize}px`,\n `--oc-eyebrow-weight: ${theme.chrome.eyebrow.fontWeight}`,\n `--oc-eyebrow-tracking: ${cssTokenDefault('--oc-eyebrow-tracking', 'light')}`,\n `--oc-bg: ${bg}`,\n `--oc-text: ${theme.colors.text}`,\n `--oc-text-muted: ${theme.colors.axis}`,\n `--oc-text-faint: ${theme.isDark ? cssTokenDefault('--oc-text-faint', 'dark') : cssTokenDefault('--oc-text-faint', 'light')}`,\n `--oc-gridline: ${theme.colors.gridline}`,\n `--oc-axis: ${theme.colors.axis}`,\n `--oc-border-radius: ${theme.borderRadius}px`,\n `--oc-accent: ${accent}`,\n `--oc-accent-strong: ${adaptForLightLineStroke(accent)}`,\n `--oc-positive: ${theme.colors.positive}`,\n `--oc-negative: ${theme.colors.negative}`,\n `--oc-legend-text: ${theme.isDark ? cssTokenDefault('--oc-legend-text', 'dark') : cssTokenDefault('--oc-legend-text', 'light')}`,\n `--oc-space-2: ${theme.spacing.chromeGap * 2}px`,\n `--oc-space-4: ${theme.spacing.padding}px`,\n ];\n\n const rules = [\n `svg.oc-chart { ${props.join('; ')}; }`,\n `.oc-chrome { font-family: var(--oc-font-family); }`,\n `.oc-eyebrow { font-size: var(--oc-eyebrow-size); font-weight: var(--oc-eyebrow-weight); letter-spacing: var(--oc-eyebrow-tracking); text-transform: uppercase; fill: var(--oc-accent); }`,\n `.oc-title { font-size: var(--oc-title-size); font-weight: var(--oc-title-weight); letter-spacing: var(--oc-title-tracking); fill: var(--oc-text); }`,\n `.oc-subtitle { font-size: var(--oc-subtitle-size); font-weight: var(--oc-subtitle-weight); fill: var(--oc-text-muted); }`,\n `.oc-source, .oc-byline, .oc-footer { font-size: var(--oc-source-size); font-weight: var(--oc-source-weight); fill: var(--oc-text-muted); }`,\n `.oc-brand { font-size: 11px; font-weight: 510; letter-spacing: 0.02em; fill: var(--oc-text-faint); }`,\n `.oc-brand-dot { fill: var(--oc-accent); }`,\n `.oc-eyebrow-dot { fill: var(--oc-accent); }`,\n `.oc-metrics { font-family: var(--oc-font-family); }`,\n `.oc-metric-label { font-size: 10px; font-weight: 510; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--oc-text-muted); }`,\n `.oc-metric-value { font-size: 22px; font-weight: 510; letter-spacing: -0.01em; fill: var(--oc-text); font-variant-numeric: tabular-nums; }`,\n `.oc-metric-delta-up { fill: var(--oc-positive); font-size: 12px; font-weight: 510; }`,\n `.oc-metric-delta-down { fill: var(--oc-negative); font-size: 12px; font-weight: 510; }`,\n `.oc-axis-tick-inline { font-size: 11px; font-weight: 400; fill: var(--oc-text-muted); }`,\n `.oc-endpoint-labels { font-family: var(--oc-font-family); }`,\n `.oc-endpoint-label { fill: var(--oc-endpoint-label-color, var(--oc-text)); }`,\n `.oc-endpoint-value { fill: var(--oc-endpoint-value-color, var(--oc-text-muted)); }`,\n `.oc-endpoint-leader { stroke: var(--oc-endpoint-leader-color, currentColor); }`,\n `.oc-annotation-subtitle { fill: var(--oc-annotation-subtitle-color, var(--oc-text-muted)); }`,\n `.oc-metric-secondary { fill: var(--oc-positive); font-size: 12px; font-weight: 400; }`,\n `.oc-legend { font-family: var(--oc-font-family); font-size: var(--oc-body-size); }`,\n `.oc-legend-entry { cursor: default; }`,\n `.oc-legend text { fill: var(--oc-legend-text); }`,\n ];\n\n return rules.join('\\n');\n}\n\n/**\n * Inject the theme style block into an SVG clone's `<defs>` so class-based fills\n * survive serialization. Idempotent-ish: adds one `<style data-oc-theme>` at the\n * front of `<defs>`; call once per clone before serializing. No-op if `theme` is\n * undefined (nothing to resolve against).\n */\nexport function injectThemeStyleBlock(svg: SVGElement, theme: ResolvedTheme | undefined): void {\n if (!theme) return;\n let defs = svg.querySelector('defs');\n if (!defs) {\n defs = document.createElementNS(SVG_NS, 'defs');\n svg.insertBefore(defs, svg.firstChild);\n }\n const style = document.createElementNS(SVG_NS, 'style');\n style.setAttribute('data-oc-theme', '');\n style.textContent = buildThemeStyleBlock(theme);\n defs.insertBefore(style, defs.firstChild);\n}\n"],"mappings":";AAQO,IAAM,SAAS;AACf,IAAM,WAAW;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A;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;AAQO,SAAS,sBAAsB,KAAiB,OAAwC;AAC7F,MAAI,CAAC,MAAO;AACZ,MAAI,OAAO,IAAI,cAAc,MAAM;AACnC,MAAI,CAAC,MAAM;AACT,WAAO,SAAS,gBAAgB,QAAQ,MAAM;AAC9C,QAAI,aAAa,MAAM,IAAI,UAAU;AAAA,EACvC;AACA,QAAM,QAAQ,SAAS,gBAAgB,QAAQ,OAAO;AACtD,QAAM,aAAa,iBAAiB,EAAE;AACtC,QAAM,cAAc,qBAAqB,KAAK;AAC9C,OAAK,aAAa,OAAO,KAAK,UAAU;AAC1C;","names":[]}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import {
|
|
2
|
+
injectThemeStyleBlock
|
|
3
|
+
} from "./chunk-RM5XS6NR.js";
|
|
4
|
+
|
|
5
|
+
// src/export.ts
|
|
6
|
+
function getSVGDimensions(svg) {
|
|
7
|
+
const w = parseFloat(svg.getAttribute("width") || "");
|
|
8
|
+
const h = parseFloat(svg.getAttribute("height") || "");
|
|
9
|
+
if (w && h) return { width: w, height: h };
|
|
10
|
+
const vb = svg.getAttribute("viewBox");
|
|
11
|
+
if (vb) {
|
|
12
|
+
const parts = vb.split(/[\s,]+/).map(Number);
|
|
13
|
+
if (parts.length >= 4 && parts[2] && parts[3]) {
|
|
14
|
+
return { width: parts[2], height: parts[3] };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return { width: 600, height: 400 };
|
|
18
|
+
}
|
|
19
|
+
function ensureSVGDimensions(svgString, width, height) {
|
|
20
|
+
if (/^<svg[^>]*\swidth\s*=/.test(svgString)) return svgString;
|
|
21
|
+
return svgString.replace(/^(<svg)/, `$1 width="${width}" height="${height}"`);
|
|
22
|
+
}
|
|
23
|
+
function collectUsedFonts(svgElement) {
|
|
24
|
+
const fonts = /* @__PURE__ */ new Map();
|
|
25
|
+
const textElements = svgElement.querySelectorAll("text");
|
|
26
|
+
for (const el of textElements) {
|
|
27
|
+
const family = el.getAttribute("font-family");
|
|
28
|
+
const weight = el.getAttribute("font-weight") || "400";
|
|
29
|
+
if (family) {
|
|
30
|
+
const primary = family.split(",")[0].trim().replace(/["']/g, "");
|
|
31
|
+
if (!fonts.has(primary)) fonts.set(primary, /* @__PURE__ */ new Set());
|
|
32
|
+
fonts.get(primary).add(String(weight));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return fonts;
|
|
36
|
+
}
|
|
37
|
+
function findFontFaceRules(usedFonts) {
|
|
38
|
+
const results = [];
|
|
39
|
+
try {
|
|
40
|
+
for (const sheet of document.styleSheets) {
|
|
41
|
+
let rules;
|
|
42
|
+
try {
|
|
43
|
+
rules = sheet.cssRules;
|
|
44
|
+
} catch {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
for (const rule of rules) {
|
|
48
|
+
if (!(rule instanceof CSSFontFaceRule)) continue;
|
|
49
|
+
const familyRaw = rule.style.getPropertyValue("font-family").replace(/["']/g, "").trim();
|
|
50
|
+
const weight = rule.style.getPropertyValue("font-weight") || "400";
|
|
51
|
+
const style = rule.style.getPropertyValue("font-style") || "normal";
|
|
52
|
+
const src = rule.style.getPropertyValue("src");
|
|
53
|
+
const weights = usedFonts.get(familyRaw);
|
|
54
|
+
if (!weights) continue;
|
|
55
|
+
const weightMatch = weights.has(weight) || weight.includes(" ");
|
|
56
|
+
if (!weightMatch) continue;
|
|
57
|
+
const woff2Match = src.match(/url\(["']?([^"')]+\.woff2[^"')]*?)["']?\)/);
|
|
58
|
+
if (woff2Match) {
|
|
59
|
+
results.push({
|
|
60
|
+
family: familyRaw,
|
|
61
|
+
weight,
|
|
62
|
+
style,
|
|
63
|
+
url: woff2Match[1],
|
|
64
|
+
format: "woff2"
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
}
|
|
71
|
+
return results;
|
|
72
|
+
}
|
|
73
|
+
async function fetchFontsAsBase64(fontRules) {
|
|
74
|
+
const results = [];
|
|
75
|
+
const fetches = fontRules.map(async (rule) => {
|
|
76
|
+
try {
|
|
77
|
+
const response = await fetch(rule.url);
|
|
78
|
+
if (!response.ok) return;
|
|
79
|
+
const buffer = await response.arrayBuffer();
|
|
80
|
+
const base64 = arrayBufferToBase64(buffer);
|
|
81
|
+
results.push({
|
|
82
|
+
family: rule.family,
|
|
83
|
+
weight: rule.weight,
|
|
84
|
+
style: rule.style,
|
|
85
|
+
base64,
|
|
86
|
+
format: rule.format
|
|
87
|
+
});
|
|
88
|
+
} catch {
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
await Promise.all(fetches);
|
|
92
|
+
return results;
|
|
93
|
+
}
|
|
94
|
+
function arrayBufferToBase64(buffer) {
|
|
95
|
+
let binary = "";
|
|
96
|
+
const bytes = new Uint8Array(buffer);
|
|
97
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
98
|
+
binary += String.fromCharCode(bytes[i]);
|
|
99
|
+
}
|
|
100
|
+
return btoa(binary);
|
|
101
|
+
}
|
|
102
|
+
function injectFontsIntoSVG(svgElement, fonts) {
|
|
103
|
+
if (fonts.length === 0) return;
|
|
104
|
+
const cssRules = fonts.map(
|
|
105
|
+
(f) => `@font-face { font-family: '${f.family}'; font-weight: ${f.weight}; font-style: ${f.style}; src: url(data:font/${f.format};base64,${f.base64}) format('${f.format}'); }`
|
|
106
|
+
).join("\n");
|
|
107
|
+
const ns = "http://www.w3.org/2000/svg";
|
|
108
|
+
let defs = svgElement.querySelector("defs");
|
|
109
|
+
if (!defs) {
|
|
110
|
+
defs = document.createElementNS(ns, "defs");
|
|
111
|
+
svgElement.insertBefore(defs, svgElement.firstChild);
|
|
112
|
+
}
|
|
113
|
+
const styleEl = document.createElementNS(ns, "style");
|
|
114
|
+
styleEl.textContent = cssRules;
|
|
115
|
+
defs.insertBefore(styleEl, defs.firstChild);
|
|
116
|
+
}
|
|
117
|
+
async function embedFonts(svgElement) {
|
|
118
|
+
const usedFonts = collectUsedFonts(svgElement);
|
|
119
|
+
if (usedFonts.size === 0) return;
|
|
120
|
+
const fontRules = findFontFaceRules(usedFonts);
|
|
121
|
+
if (fontRules.length === 0) return;
|
|
122
|
+
const fontData = await fetchFontsAsBase64(fontRules);
|
|
123
|
+
injectFontsIntoSVG(svgElement, fontData);
|
|
124
|
+
}
|
|
125
|
+
function getSVGBackgroundColor(svgElement, fallback) {
|
|
126
|
+
const firstRect = svgElement.querySelector("rect");
|
|
127
|
+
const fill = firstRect?.getAttribute("fill");
|
|
128
|
+
if (!fill || fill === "none" || fill === "transparent") return fallback ?? "#ffffff";
|
|
129
|
+
return fill;
|
|
130
|
+
}
|
|
131
|
+
function exportSVG(svgElement) {
|
|
132
|
+
if (!svgElement.getAttribute("xmlns")) {
|
|
133
|
+
svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
|
134
|
+
}
|
|
135
|
+
const serializer = new XMLSerializer();
|
|
136
|
+
return serializer.serializeToString(svgElement);
|
|
137
|
+
}
|
|
138
|
+
async function exportSVGWithFonts(svgElement, options) {
|
|
139
|
+
const clone = svgElement.cloneNode(true);
|
|
140
|
+
const shouldEmbed = options?.embedFonts ?? true;
|
|
141
|
+
injectThemeStyleBlock(clone, options?.theme);
|
|
142
|
+
if (shouldEmbed) {
|
|
143
|
+
await embedFonts(clone);
|
|
144
|
+
}
|
|
145
|
+
return exportSVG(clone);
|
|
146
|
+
}
|
|
147
|
+
var p3Supported;
|
|
148
|
+
function supportsDisplayP3() {
|
|
149
|
+
if (p3Supported !== void 0) return p3Supported;
|
|
150
|
+
try {
|
|
151
|
+
const probe = document.createElement("canvas");
|
|
152
|
+
const ctx = probe.getContext("2d", { colorSpace: "display-p3" });
|
|
153
|
+
p3Supported = !!ctx && ctx.getContextAttributes?.().colorSpace === "display-p3";
|
|
154
|
+
} catch {
|
|
155
|
+
p3Supported = false;
|
|
156
|
+
}
|
|
157
|
+
return p3Supported;
|
|
158
|
+
}
|
|
159
|
+
function getExportContext(canvas) {
|
|
160
|
+
const ctx = supportsDisplayP3() ? canvas.getContext("2d", { colorSpace: "display-p3" }) : canvas.getContext("2d");
|
|
161
|
+
if (!ctx) {
|
|
162
|
+
throw new Error("Canvas 2D context not available");
|
|
163
|
+
}
|
|
164
|
+
return ctx;
|
|
165
|
+
}
|
|
166
|
+
function rasterizeSVGToCanvas(svgString, width, height, dpi, prepare) {
|
|
167
|
+
if (!width || !height) {
|
|
168
|
+
throw new Error(`SVG has zero dimensions (width=${width}, height=${height})`);
|
|
169
|
+
}
|
|
170
|
+
const canvas = document.createElement("canvas");
|
|
171
|
+
canvas.width = width * dpi;
|
|
172
|
+
canvas.height = height * dpi;
|
|
173
|
+
const ctx = getExportContext(canvas);
|
|
174
|
+
prepare?.(ctx, canvas);
|
|
175
|
+
ctx.scale(dpi, dpi);
|
|
176
|
+
const img = new Image();
|
|
177
|
+
const blob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
|
|
178
|
+
const url = URL.createObjectURL(blob);
|
|
179
|
+
return new Promise((resolve, reject) => {
|
|
180
|
+
img.onload = () => {
|
|
181
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
182
|
+
URL.revokeObjectURL(url);
|
|
183
|
+
resolve(canvas);
|
|
184
|
+
};
|
|
185
|
+
img.onerror = () => {
|
|
186
|
+
URL.revokeObjectURL(url);
|
|
187
|
+
reject(
|
|
188
|
+
new Error(
|
|
189
|
+
`Failed to load SVG as image (width=${width}, height=${height}, svgLength=${svgString.length})`
|
|
190
|
+
)
|
|
191
|
+
);
|
|
192
|
+
};
|
|
193
|
+
img.src = url;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async function prepareRasterSVG(svgElement, shouldEmbed, theme) {
|
|
197
|
+
const { width, height } = getSVGDimensions(svgElement);
|
|
198
|
+
const clone = svgElement.cloneNode(true);
|
|
199
|
+
injectThemeStyleBlock(clone, theme);
|
|
200
|
+
if (shouldEmbed) {
|
|
201
|
+
await embedFonts(clone);
|
|
202
|
+
}
|
|
203
|
+
const svgString = ensureSVGDimensions(exportSVG(clone), width, height);
|
|
204
|
+
return { svgString, width, height };
|
|
205
|
+
}
|
|
206
|
+
async function exportPNG(svgElement, options) {
|
|
207
|
+
const dpi = options?.dpi ?? 2;
|
|
208
|
+
const shouldEmbed = options?.embedFonts ?? true;
|
|
209
|
+
const { svgString, width, height } = await prepareRasterSVG(
|
|
210
|
+
svgElement,
|
|
211
|
+
shouldEmbed,
|
|
212
|
+
options?.theme
|
|
213
|
+
);
|
|
214
|
+
const canvas = await rasterizeSVGToCanvas(svgString, width, height, dpi);
|
|
215
|
+
return new Promise((resolve, reject) => {
|
|
216
|
+
canvas.toBlob((result) => {
|
|
217
|
+
if (result) {
|
|
218
|
+
resolve(result);
|
|
219
|
+
} else {
|
|
220
|
+
reject(new Error("Canvas toBlob returned null"));
|
|
221
|
+
}
|
|
222
|
+
}, "image/png");
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
async function exportJPG(svgElement, options) {
|
|
226
|
+
const dpi = options?.dpi ?? 2;
|
|
227
|
+
const quality = options?.quality ?? 0.92;
|
|
228
|
+
const shouldEmbed = options?.embedFonts ?? true;
|
|
229
|
+
const backgroundColor = getSVGBackgroundColor(svgElement);
|
|
230
|
+
const { svgString, width, height } = await prepareRasterSVG(
|
|
231
|
+
svgElement,
|
|
232
|
+
shouldEmbed,
|
|
233
|
+
options?.theme
|
|
234
|
+
);
|
|
235
|
+
const canvas = await rasterizeSVGToCanvas(svgString, width, height, dpi, (ctx, cv) => {
|
|
236
|
+
ctx.fillStyle = backgroundColor;
|
|
237
|
+
ctx.fillRect(0, 0, cv.width, cv.height);
|
|
238
|
+
});
|
|
239
|
+
return new Promise((resolve, reject) => {
|
|
240
|
+
canvas.toBlob(
|
|
241
|
+
(result) => {
|
|
242
|
+
if (result) {
|
|
243
|
+
resolve(result);
|
|
244
|
+
} else {
|
|
245
|
+
reject(new Error("Canvas toBlob returned null"));
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
"image/jpeg",
|
|
249
|
+
quality
|
|
250
|
+
);
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function exportCSV(data) {
|
|
254
|
+
if (data.length === 0) return "";
|
|
255
|
+
const headers = Object.keys(data[0]);
|
|
256
|
+
const rows = [headers.map(csvEscape).join(",")];
|
|
257
|
+
for (const row of data) {
|
|
258
|
+
const values = headers.map((h) => csvEscape(String(row[h] ?? "")));
|
|
259
|
+
rows.push(values.join(","));
|
|
260
|
+
}
|
|
261
|
+
return rows.join("\n");
|
|
262
|
+
}
|
|
263
|
+
function csvEscape(value) {
|
|
264
|
+
if (value.includes(",") || value.includes('"') || value.includes("\n") || value.includes("\r")) {
|
|
265
|
+
return `"${value.replace(/"/g, '""')}"`;
|
|
266
|
+
}
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export {
|
|
271
|
+
getSVGDimensions,
|
|
272
|
+
ensureSVGDimensions,
|
|
273
|
+
embedFonts,
|
|
274
|
+
getSVGBackgroundColor,
|
|
275
|
+
exportSVG,
|
|
276
|
+
exportSVGWithFonts,
|
|
277
|
+
rasterizeSVGToCanvas,
|
|
278
|
+
exportPNG,
|
|
279
|
+
exportJPG,
|
|
280
|
+
exportCSV
|
|
281
|
+
};
|
|
282
|
+
//# sourceMappingURL=chunk-T32UHMZA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/export.ts"],"sourcesContent":["/**\n * Export utilities: serialize charts to SVG, PNG, JPG, or CSV.\n *\n * - SVG: serializes the rendered DOM element via XMLSerializer\n * - SVG with fonts: async version that embeds @font-face data URIs\n * - PNG: renders SVG to canvas, then extracts as Blob\n * - JPG: same as PNG but with JPEG compression and background fill\n * - CSV: converts a data array to comma-separated text\n */\n\nimport type { ResolvedTheme } from '@opendata-ai/openchart-core';\nimport { injectThemeStyleBlock } from './theme-style-block';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SVGExportOptions {\n /** Embed fonts as base64 data URIs in the SVG. Defaults to true. */\n embedFonts?: boolean;\n /**\n * Resolved theme to inline as a `<style>` block, so class-based fills (metric\n * cells, brand watermark dot, legend text, endpoint labels) survive\n * serialization away from the page stylesheet. Omit to skip — a chart whose\n * chrome is all inline-filled exports fine without it.\n */\n theme?: ResolvedTheme;\n}\n\nexport interface PNGExportOptions extends SVGExportOptions {\n /** DPI scaling factor. Defaults to 2 for retina-quality output. */\n dpi?: number;\n}\n\nexport interface JPGExportOptions extends PNGExportOptions {\n /** JPEG quality from 0 to 1. Defaults to 0.92. */\n quality?: number;\n}\n\ninterface FontFaceData {\n family: string;\n weight: string;\n style: string;\n base64: string;\n format: string;\n}\n\n// ---------------------------------------------------------------------------\n// Dimension parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Extract dimensions from an SVG element, trying width/height attributes\n * first, then falling back to viewBox.\n */\nexport function getSVGDimensions(svg: SVGElement): { width: number; height: number } {\n const w = parseFloat(svg.getAttribute('width') || '');\n const h = parseFloat(svg.getAttribute('height') || '');\n if (w && h) return { width: w, height: h };\n\n const vb = svg.getAttribute('viewBox');\n if (vb) {\n const parts = vb.split(/[\\s,]+/).map(Number);\n if (parts.length >= 4 && parts[2] && parts[3]) {\n return { width: parts[2], height: parts[3] };\n }\n }\n\n return { width: 600, height: 400 };\n}\n\n/**\n * Ensure an SVG string has explicit width/height attributes.\n *\n * When an SVG only has a viewBox (no width/height), browsers loading it as\n * an Image blob may use 300x150 as the intrinsic size instead of the viewBox\n * dimensions. This causes clipping at non-1x DPI scaling. Injecting explicit\n * width/height into the root <svg> tag fixes the intrinsic size.\n */\nexport function ensureSVGDimensions(svgString: string, width: number, height: number): string {\n // If the <svg> already has a width attribute, leave it alone\n if (/^<svg[^>]*\\swidth\\s*=/.test(svgString)) return svgString;\n // Inject width and height right after <svg\n return svgString.replace(/^(<svg)/, `$1 width=\"${width}\" height=\"${height}\"`);\n}\n\n// ---------------------------------------------------------------------------\n// Font embedding\n// ---------------------------------------------------------------------------\n\n/**\n * Collect unique font-family + font-weight combos from all <text> elements.\n */\nfunction collectUsedFonts(svgElement: SVGElement): Map<string, Set<string>> {\n const fonts = new Map<string, Set<string>>();\n const textElements = svgElement.querySelectorAll('text');\n\n for (const el of textElements) {\n const family = el.getAttribute('font-family');\n const weight = el.getAttribute('font-weight') || '400';\n if (family) {\n // Take the first font in the stack (e.g., \"Inter, sans-serif\" → \"Inter\")\n const primary = family.split(',')[0].trim().replace(/[\"']/g, '');\n if (!fonts.has(primary)) fonts.set(primary, new Set());\n fonts.get(primary)!.add(String(weight));\n }\n }\n\n return fonts;\n}\n\n/**\n * Find @font-face rules in document stylesheets that match the requested fonts.\n * Returns the src URLs for .woff2 files.\n */\nfunction findFontFaceRules(\n usedFonts: Map<string, Set<string>>,\n): Array<{ family: string; weight: string; style: string; url: string; format: string }> {\n const results: Array<{\n family: string;\n weight: string;\n style: string;\n url: string;\n format: string;\n }> = [];\n\n try {\n for (const sheet of document.styleSheets) {\n let rules: CSSRuleList;\n try {\n rules = sheet.cssRules;\n } catch {\n // Cross-origin stylesheet, skip\n continue;\n }\n\n for (const rule of rules) {\n if (!(rule instanceof CSSFontFaceRule)) continue;\n\n const familyRaw = rule.style.getPropertyValue('font-family').replace(/[\"']/g, '').trim();\n const weight = rule.style.getPropertyValue('font-weight') || '400';\n const style = rule.style.getPropertyValue('font-style') || 'normal';\n const src = rule.style.getPropertyValue('src');\n\n const weights = usedFonts.get(familyRaw);\n if (!weights) continue;\n\n // Check if this weight is used (handle ranges like \"100 900\")\n const weightMatch = weights.has(weight) || weight.includes(' ');\n if (!weightMatch) continue;\n\n // Extract woff2 URL from src descriptor\n const woff2Match = src.match(/url\\([\"']?([^\"')]+\\.woff2[^\"')]*?)[\"']?\\)/);\n if (woff2Match) {\n results.push({\n family: familyRaw,\n weight,\n style,\n url: woff2Match[1],\n format: 'woff2',\n });\n }\n }\n }\n } catch {\n // Stylesheet access failed entirely, return empty\n }\n\n return results;\n}\n\n/**\n * Fetch font files and convert to base64 data URIs.\n */\nasync function fetchFontsAsBase64(\n fontRules: Array<{ family: string; weight: string; style: string; url: string; format: string }>,\n): Promise<FontFaceData[]> {\n const results: FontFaceData[] = [];\n\n const fetches = fontRules.map(async (rule) => {\n try {\n const response = await fetch(rule.url);\n if (!response.ok) return;\n const buffer = await response.arrayBuffer();\n const base64 = arrayBufferToBase64(buffer);\n results.push({\n family: rule.family,\n weight: rule.weight,\n style: rule.style,\n base64,\n format: rule.format,\n });\n } catch {\n // Font fetch failed (CORS, network, etc.) - skip this font\n }\n });\n\n await Promise.all(fetches);\n return results;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Inject @font-face rules with base64 data URIs into the SVG's <defs>.\n */\nfunction injectFontsIntoSVG(svgElement: SVGElement, fonts: FontFaceData[]): void {\n if (fonts.length === 0) return;\n\n const cssRules = fonts\n .map(\n (f) =>\n `@font-face { font-family: '${f.family}'; font-weight: ${f.weight}; font-style: ${f.style}; src: url(data:font/${f.format};base64,${f.base64}) format('${f.format}'); }`,\n )\n .join('\\n');\n\n const ns = 'http://www.w3.org/2000/svg';\n let defs = svgElement.querySelector('defs');\n if (!defs) {\n defs = document.createElementNS(ns, 'defs');\n svgElement.insertBefore(defs, svgElement.firstChild);\n }\n\n const styleEl = document.createElementNS(ns, 'style');\n styleEl.textContent = cssRules;\n defs.insertBefore(styleEl, defs.firstChild);\n}\n\n/**\n * Embed fonts into an SVG element by finding matching @font-face rules\n * in the page's stylesheets, fetching the font files, and injecting\n * them as base64 data URIs.\n *\n * Modifies the SVG element in place. Call this before serialization.\n * If font fetching fails for any font, that font is silently skipped\n * and the export proceeds with system font fallback for that face.\n */\nexport async function embedFonts(svgElement: SVGElement): Promise<void> {\n const usedFonts = collectUsedFonts(svgElement);\n if (usedFonts.size === 0) return;\n\n const fontRules = findFontFaceRules(usedFonts);\n if (fontRules.length === 0) return;\n\n const fontData = await fetchFontsAsBase64(fontRules);\n injectFontsIntoSVG(svgElement, fontData);\n}\n\n// ---------------------------------------------------------------------------\n// SVG background color\n// ---------------------------------------------------------------------------\n\n/**\n * Read the chart's background color from its first rect element. Falls back to\n * `fallback` (white when omitted) when the chart has no opaque background,\n * which matters for formats that can't carry alpha (JPEG, GIF).\n *\n * Pass the resolved theme's `colors.background` as `fallback` when the caller\n * has one: canvas mark mode suppresses the SVG background rect (the canvas\n * paints it), so without it a dark chart would flood-fill white.\n */\nexport function getSVGBackgroundColor(svgElement: SVGElement, fallback?: string): string {\n const firstRect = svgElement.querySelector('rect');\n const fill = firstRect?.getAttribute('fill');\n if (!fill || fill === 'none' || fill === 'transparent') return fallback ?? '#ffffff';\n return fill;\n}\n\n// ---------------------------------------------------------------------------\n// SVG export\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize an SVG element to an XML string.\n *\n * @param svgElement - The rendered SVG element to serialize.\n * @returns The SVG markup as a string.\n */\nexport function exportSVG(svgElement: SVGElement): string {\n if (!svgElement.getAttribute('xmlns')) {\n svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n }\n const serializer = new XMLSerializer();\n return serializer.serializeToString(svgElement);\n}\n\n/**\n * Serialize an SVG element with embedded fonts to an XML string.\n *\n * Collects font-family declarations from the SVG's text elements,\n * finds matching @font-face rules in the page's stylesheets, fetches\n * the font files, and embeds them as base64 data URIs. The resulting\n * SVG is self-contained and renders correctly without external fonts.\n *\n * @param svgElement - The rendered SVG element to serialize.\n * @param options - Export options.\n * @returns A Promise resolving to the SVG markup as a string.\n */\nexport async function exportSVGWithFonts(\n svgElement: SVGElement,\n options?: SVGExportOptions,\n): Promise<string> {\n const clone = svgElement.cloneNode(true) as SVGElement;\n const shouldEmbed = options?.embedFonts ?? true;\n injectThemeStyleBlock(clone, options?.theme);\n if (shouldEmbed) {\n await embedFonts(clone);\n }\n return exportSVG(clone);\n}\n\n// ---------------------------------------------------------------------------\n// Raster export (PNG / JPG)\n// ---------------------------------------------------------------------------\n\n/**\n * Cache the one-time probe for Display P3 canvas support. Rendering raster\n * exports into a display-p3 canvas makes toBlob embed a wide-gamut color profile\n * (verified: an sRGB PNG has no iCCP chunk; a display-p3 PNG does — and JPEG\n * upgrades from an sRGB to a P3 profile), so the export matches the on-screen\n * chart instead of reading as an untagged/sRGB image that looks washed out on\n * P3 displays.\n */\nlet p3Supported: boolean | undefined;\n\nfunction supportsDisplayP3(): boolean {\n if (p3Supported !== undefined) return p3Supported;\n try {\n const probe = document.createElement('canvas');\n const ctx = probe.getContext('2d', { colorSpace: 'display-p3' }) as\n | (CanvasRenderingContext2D & { getContextAttributes?: () => { colorSpace?: string } })\n | null;\n p3Supported = !!ctx && ctx.getContextAttributes?.().colorSpace === 'display-p3';\n } catch {\n p3Supported = false;\n }\n return p3Supported;\n}\n\n/**\n * Create a 2D context in the widest color space the runtime supports. A\n * display-p3 canvas is what makes toBlob embed the profile. Callers that read\n * pixels back for a non-color-managed sink (GIF quantization) must NOT rely on\n * this — they must read back in sRGB explicitly.\n */\nfunction getExportContext(canvas: HTMLCanvasElement): CanvasRenderingContext2D {\n const ctx = supportsDisplayP3()\n ? canvas.getContext('2d', { colorSpace: 'display-p3' })\n : canvas.getContext('2d');\n if (!ctx) {\n throw new Error('Canvas 2D context not available');\n }\n return ctx;\n}\n\n/**\n * Draw a serialized SVG string onto a canvas at DPI scaling.\n *\n * Shared by PNG/JPG export and per-frame GIF rendering: loads the SVG string\n * as an Image via an object URL, draws it into a `width*dpi × height*dpi`\n * canvas, and hands the canvas back once painted. The caller decides how to\n * read the result (toBlob for PNG/JPG, getImageData for GIF frames).\n *\n * An optional `prepare` hook runs before drawing the image, used by JPG export\n * to fill an opaque background so transparency doesn't render as black.\n *\n * @param svgString - Serialized SVG markup (should already carry width/height).\n * @param width - Logical width in CSS pixels.\n * @param height - Logical height in CSS pixels.\n * @param dpi - Device pixel ratio scaling factor.\n * @param prepare - Optional pre-draw hook receiving the scaled 2D context.\n * @returns A Promise resolving to the painted canvas.\n */\nexport function rasterizeSVGToCanvas(\n svgString: string,\n width: number,\n height: number,\n dpi: number,\n prepare?: (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => void,\n): Promise<HTMLCanvasElement> {\n if (!width || !height) {\n throw new Error(`SVG has zero dimensions (width=${width}, height=${height})`);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = width * dpi;\n canvas.height = height * dpi;\n\n const ctx = getExportContext(canvas);\n\n prepare?.(ctx, canvas);\n ctx.scale(dpi, dpi);\n\n const img = new Image();\n const blob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });\n const url = URL.createObjectURL(blob);\n\n return new Promise<HTMLCanvasElement>((resolve, reject) => {\n img.onload = () => {\n ctx.drawImage(img, 0, 0, width, height);\n URL.revokeObjectURL(url);\n resolve(canvas);\n };\n\n img.onerror = () => {\n URL.revokeObjectURL(url);\n reject(\n new Error(\n `Failed to load SVG as image (width=${width}, height=${height}, svgLength=${svgString.length})`,\n ),\n );\n };\n\n img.src = url;\n });\n}\n\n/**\n * Serialize an SVG element (optionally embedding fonts) into a canvas-ready\n * string with explicit width/height. Shared by the raster exporters.\n */\nasync function prepareRasterSVG(\n svgElement: SVGElement,\n shouldEmbed: boolean,\n theme?: ResolvedTheme,\n): Promise<{ svgString: string; width: number; height: number }> {\n const { width, height } = getSVGDimensions(svgElement);\n const clone = svgElement.cloneNode(true) as SVGElement;\n // Inline the theme style block so class-based fills survive the detach from\n // the page stylesheet. No-op when theme is undefined.\n injectThemeStyleBlock(clone, theme);\n if (shouldEmbed) {\n await embedFonts(clone);\n }\n const svgString = ensureSVGDimensions(exportSVG(clone), width, height);\n return { svgString, width, height };\n}\n\n/**\n * Render an SVG element to a PNG Blob via a canvas.\n *\n * Embeds fonts by default so the exported image matches on-screen rendering.\n * Set `embedFonts: false` to skip font embedding for faster exports.\n *\n * @param svgElement - The rendered SVG element.\n * @param options - Optional DPI scaling and font embedding.\n * @returns A Promise resolving to the PNG Blob.\n */\nexport async function exportPNG(svgElement: SVGElement, options?: PNGExportOptions): Promise<Blob> {\n const dpi = options?.dpi ?? 2;\n const shouldEmbed = options?.embedFonts ?? true;\n const { svgString, width, height } = await prepareRasterSVG(\n svgElement,\n shouldEmbed,\n options?.theme,\n );\n const canvas = await rasterizeSVGToCanvas(svgString, width, height, dpi);\n\n return new Promise<Blob>((resolve, reject) => {\n canvas.toBlob((result) => {\n if (result) {\n resolve(result);\n } else {\n reject(new Error('Canvas toBlob returned null'));\n }\n }, 'image/png');\n });\n}\n\n/**\n * Render an SVG element to a JPEG Blob via a canvas.\n *\n * Same pipeline as exportPNG but outputs JPEG with configurable quality.\n * The canvas is filled with the chart's background color before drawing\n * to avoid transparent backgrounds rendering as black in JPEG format.\n *\n * @param svgElement - The rendered SVG element.\n * @param options - Optional DPI scaling, JPEG quality, and font embedding.\n * @returns A Promise resolving to the JPEG Blob.\n */\nexport async function exportJPG(svgElement: SVGElement, options?: JPGExportOptions): Promise<Blob> {\n const dpi = options?.dpi ?? 2;\n const quality = options?.quality ?? 0.92;\n const shouldEmbed = options?.embedFonts ?? true;\n const backgroundColor = getSVGBackgroundColor(svgElement);\n const { svgString, width, height } = await prepareRasterSVG(\n svgElement,\n shouldEmbed,\n options?.theme,\n );\n\n // Fill an opaque background before drawing so transparency doesn't render\n // as black in the JPEG. Runs before ctx.scale, so use the raw canvas size.\n const canvas = await rasterizeSVGToCanvas(svgString, width, height, dpi, (ctx, cv) => {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, cv.width, cv.height);\n });\n\n return new Promise<Blob>((resolve, reject) => {\n canvas.toBlob(\n (result) => {\n if (result) {\n resolve(result);\n } else {\n reject(new Error('Canvas toBlob returned null'));\n }\n },\n 'image/jpeg',\n quality,\n );\n });\n}\n\n// ---------------------------------------------------------------------------\n// CSV export\n// ---------------------------------------------------------------------------\n\n/**\n * Convert an array of data objects to a CSV string.\n *\n * Uses the keys from the first row as column headers.\n * Values are quoted if they contain commas, quotes, or newlines.\n *\n * @param data - Array of row objects.\n * @returns CSV-formatted string.\n */\nexport function exportCSV(data: Record<string, unknown>[]): string {\n if (data.length === 0) return '';\n\n const headers = Object.keys(data[0]);\n const rows = [headers.map(csvEscape).join(',')];\n\n for (const row of data) {\n const values = headers.map((h) => csvEscape(String(row[h] ?? '')));\n rows.push(values.join(','));\n }\n\n return rows.join('\\n');\n}\n\nfunction csvEscape(value: string): string {\n if (value.includes(',') || value.includes('\"') || value.includes('\\n') || value.includes('\\r')) {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n }\n return value;\n}\n"],"mappings":";;;;;AAuDO,SAAS,iBAAiB,KAAoD;AACnF,QAAM,IAAI,WAAW,IAAI,aAAa,OAAO,KAAK,EAAE;AACpD,QAAM,IAAI,WAAW,IAAI,aAAa,QAAQ,KAAK,EAAE;AACrD,MAAI,KAAK,EAAG,QAAO,EAAE,OAAO,GAAG,QAAQ,EAAE;AAEzC,QAAM,KAAK,IAAI,aAAa,SAAS;AACrC,MAAI,IAAI;AACN,UAAM,QAAQ,GAAG,MAAM,QAAQ,EAAE,IAAI,MAAM;AAC3C,QAAI,MAAM,UAAU,KAAK,MAAM,CAAC,KAAK,MAAM,CAAC,GAAG;AAC7C,aAAO,EAAE,OAAO,MAAM,CAAC,GAAG,QAAQ,MAAM,CAAC,EAAE;AAAA,IAC7C;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,KAAK,QAAQ,IAAI;AACnC;AAUO,SAAS,oBAAoB,WAAmB,OAAe,QAAwB;AAE5F,MAAI,wBAAwB,KAAK,SAAS,EAAG,QAAO;AAEpD,SAAO,UAAU,QAAQ,WAAW,aAAa,KAAK,aAAa,MAAM,GAAG;AAC9E;AASA,SAAS,iBAA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;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAeO,SAAS,UAAU,MAAyC;AACjE,MAAI,KAAK,WAAW,EAAG,QAAO;AAE9B,QAAM,UAAU,OAAO,KAAK,KAAK,CAAC,CAAC;AACnC,QAAM,OAAO,CAAC,QAAQ,IAAI,SAAS,EAAE,KAAK,GAAG,CAAC;AAE9C,aAAW,OAAO,MAAM;AACtB,UAAM,SAAS,QAAQ,IAAI,CAAC,MAAM,UAAU,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;AACjE,SAAK,KAAK,OAAO,KAAK,GAAG,CAAC;AAAA,EAC5B;AAEA,SAAO,KAAK,KAAK,IAAI;AACvB;AAEA,SAAS,UAAU,OAAuB;AACxC,MAAI,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,SAAS,IAAI,GAAG;AAC9F,WAAO,IAAI,MAAM,QAAQ,MAAM,IAAI,CAAC;AAAA,EACtC;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { ResolvedTheme, AnimationEase, ResolvedAnimation } from '@opendata-ai/openchart-core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Animated GIF export.
|
|
5
|
+
*
|
|
6
|
+
* Unlike PNG/JPG (single static frame), GIF export must reproduce the chart's
|
|
7
|
+
* entrance animation across many frames. OpenChart entrance animations are pure
|
|
8
|
+
* CSS keyframes that mutate `clip-path`/`opacity`/`transform` in *computed*
|
|
9
|
+
* style, which `XMLSerializer` does not capture — so serializing the live,
|
|
10
|
+
* mid-animation SVG yields the base markup on every frame (a static GIF).
|
|
11
|
+
*
|
|
12
|
+
* This module sidesteps that by *synthesizing* frames deterministically: it
|
|
13
|
+
* takes the settled, final-state SVG plus the resolved animation config,
|
|
14
|
+
* computes each animated element's value at time `t` in JS, stamps
|
|
15
|
+
* `clip-path`/`opacity` as INLINE attributes on a clone (inline values DO
|
|
16
|
+
* serialize), rasterizes that clone, and encodes each frame with gifenc.
|
|
17
|
+
*
|
|
18
|
+
* This mirrors the entrance keyframes in `packages/core/src/styles/*.css`:
|
|
19
|
+
* bars clip bottom-up / left-right, line/area clip left-right, arcs and points
|
|
20
|
+
* fade. Only the entrance is reproduced; the on-screen CSS animation is
|
|
21
|
+
* untouched. `gifenc` is an optional peer dependency, loaded dynamically.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
interface GIFExportOptions {
|
|
25
|
+
/** Frames per second to capture. Defaults to 25. */
|
|
26
|
+
fps?: number;
|
|
27
|
+
/** DPI scaling factor, matching PNG export. Defaults to 2. */
|
|
28
|
+
dpi?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Loop behavior. Defaults to play-once (hold the final frame):
|
|
31
|
+
* - `false` / omitted: play once, then hold the final frame
|
|
32
|
+
* - `true`: loop forever
|
|
33
|
+
* - a number: loop that many times, then hold
|
|
34
|
+
*/
|
|
35
|
+
loop?: boolean | number;
|
|
36
|
+
/**
|
|
37
|
+
* Explicit capture duration in ms. Defaults to the resolved animation total
|
|
38
|
+
* (enter duration + last element's stagger delay + a small tail).
|
|
39
|
+
*/
|
|
40
|
+
durationMs?: number;
|
|
41
|
+
/** Embed fonts as base64 data URIs so text matches on-screen. Defaults to true. */
|
|
42
|
+
embedFonts?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Opaque background fill. GIF can't carry partial alpha, so a transparent
|
|
45
|
+
* chart would composite onto black. Defaults to the chart's own background
|
|
46
|
+
* color (or white if the chart is transparent).
|
|
47
|
+
*/
|
|
48
|
+
backgroundColor?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Resolved theme to inline as a `<style>` block so class-based fills (metric
|
|
51
|
+
* cells, brand watermark dot, legend text) survive serialization. Omit to skip.
|
|
52
|
+
*/
|
|
53
|
+
theme?: ResolvedTheme;
|
|
54
|
+
}
|
|
55
|
+
/** Which visual property an element's entrance keyframe animates. */
|
|
56
|
+
type AnimationKind = 'bar-vertical' | 'bar-horizontal' | 'line-area' | 'fade';
|
|
57
|
+
interface AnimatedTarget {
|
|
58
|
+
/** The element in the CLONE that receives per-frame inline styles. */
|
|
59
|
+
el: SVGElement;
|
|
60
|
+
kind: AnimationKind;
|
|
61
|
+
/** Start offset in ms (stagger * mark index). */
|
|
62
|
+
startMs: number;
|
|
63
|
+
/** Duration of this element's own animation in ms. */
|
|
64
|
+
durationMs: number;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Sample points of the `--oc-ease-smooth` token (see tokens.css). CSS
|
|
68
|
+
* `linear()` interpolates piecewise-linearly between evenly-spaced samples, so
|
|
69
|
+
* we reproduce it exactly rather than approximating with a cubic-bezier.
|
|
70
|
+
*/
|
|
71
|
+
declare const EASE_SMOOTH_SAMPLES: number[];
|
|
72
|
+
/** Piecewise-linear evaluation of a CSS linear() sample array at t in [0,1]. */
|
|
73
|
+
declare function evalLinearSamples(samples: number[], t: number): number;
|
|
74
|
+
/**
|
|
75
|
+
* Classify an animated element (identified by `data-animation-index`) into the
|
|
76
|
+
* keyframe it plays, and return the element that should receive inline styles.
|
|
77
|
+
* Returns null only when a bar group has no shape child to clip. Unrecognized
|
|
78
|
+
* mark types (map/tilemap/table/text) fall back to a plain opacity fade rather
|
|
79
|
+
* than a hard pop-in — see the generic case at the end.
|
|
80
|
+
*/
|
|
81
|
+
declare function classifyTarget(groupOrEl: SVGElement): {
|
|
82
|
+
el: SVGElement;
|
|
83
|
+
kind: AnimationKind;
|
|
84
|
+
} | null;
|
|
85
|
+
/**
|
|
86
|
+
* Distinguish "the optional gifenc peer isn't installed" from a real error
|
|
87
|
+
* thrown while loading it. Node/bundlers use ERR_MODULE_NOT_FOUND /
|
|
88
|
+
* MODULE_NOT_FOUND / "Cannot find module" for the former.
|
|
89
|
+
*/
|
|
90
|
+
declare function isModuleNotFound(err: unknown): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Map the `loop` option to gifenc's `repeat` value:
|
|
93
|
+
* `true` → 0 (loop forever), a number → that count, otherwise → -1 (play once,
|
|
94
|
+
* hold the final frame — the default and the common editorial case).
|
|
95
|
+
*/
|
|
96
|
+
declare function resolveRepeat(loop: boolean | number | undefined): number;
|
|
97
|
+
/**
|
|
98
|
+
* Apply the interpolated entrance state for a target at absolute time `nowMs`,
|
|
99
|
+
* writing inline `clip-path`/`opacity` so it survives serialization.
|
|
100
|
+
*/
|
|
101
|
+
declare function applyFrameState(target: AnimatedTarget, nowMs: number, easeKind: AnimationEase): void;
|
|
102
|
+
/**
|
|
103
|
+
* Render a chart's entrance animation to an animated GIF Blob.
|
|
104
|
+
*
|
|
105
|
+
* @param svgElement - The settled, fully-rendered chart SVG (animation complete).
|
|
106
|
+
* @param animation - The chart's resolved animation config (for exact timing).
|
|
107
|
+
* When undefined, timing falls back to sensible defaults.
|
|
108
|
+
* @param options - fps, dpi, loop, duration, font-embedding overrides.
|
|
109
|
+
* @returns A Promise resolving to the GIF Blob.
|
|
110
|
+
*/
|
|
111
|
+
declare function exportGIF(svgElement: SVGElement, animation: ResolvedAnimation | undefined, options?: GIFExportOptions): Promise<Blob>;
|
|
112
|
+
|
|
113
|
+
export { type AnimatedTarget, type AnimationKind, EASE_SMOOTH_SAMPLES, type GIFExportOptions, applyFrameState, classifyTarget, evalLinearSamples, exportGIF, isModuleNotFound, resolveRepeat };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EASE_SMOOTH_SAMPLES,
|
|
3
|
+
applyFrameState,
|
|
4
|
+
classifyTarget,
|
|
5
|
+
evalLinearSamples,
|
|
6
|
+
exportGIF,
|
|
7
|
+
isModuleNotFound,
|
|
8
|
+
resolveRepeat
|
|
9
|
+
} from "./chunk-DCODCLWI.js";
|
|
10
|
+
import "./chunk-T32UHMZA.js";
|
|
11
|
+
import "./chunk-RM5XS6NR.js";
|
|
12
|
+
export {
|
|
13
|
+
EASE_SMOOTH_SAMPLES,
|
|
14
|
+
applyFrameState,
|
|
15
|
+
classifyTarget,
|
|
16
|
+
evalLinearSamples,
|
|
17
|
+
exportGIF,
|
|
18
|
+
isModuleNotFound,
|
|
19
|
+
resolveRepeat
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=export-gif.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|