@opendata-ai/openchart-vanilla 8.9.1 → 9.0.0-rc.1

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 (51) hide show
  1. package/README.md +4 -4
  2. package/dist/{chunk-REH5UQCL.js → chunk-46E3QB6O.js} +6 -20
  3. package/dist/chunk-46E3QB6O.js.map +1 -0
  4. package/dist/{chunk-GX6BWMJD.js → chunk-5ZLSMZRM.js} +466 -330
  5. package/dist/chunk-5ZLSMZRM.js.map +1 -0
  6. package/dist/{chunk-Q7YEEF2X.js → chunk-6YPRYQKD.js} +16 -50
  7. package/dist/chunk-6YPRYQKD.js.map +1 -0
  8. package/dist/{chunk-SDJHUELU.js → chunk-A5C4VCUO.js} +26 -45
  9. package/dist/chunk-A5C4VCUO.js.map +1 -0
  10. package/dist/{chunk-MGFXAROR.js → chunk-CMIJA63X.js} +5 -3
  11. package/dist/chunk-CMIJA63X.js.map +1 -0
  12. package/dist/{chunk-APMUBW72.js → chunk-ERPYVYFW.js} +1565 -294
  13. package/dist/chunk-ERPYVYFW.js.map +1 -0
  14. package/dist/chunk-FFP5GXIP.js +45 -0
  15. package/dist/chunk-FFP5GXIP.js.map +1 -0
  16. package/dist/chunk-NLKQ5AOA.js +448 -0
  17. package/dist/chunk-NLKQ5AOA.js.map +1 -0
  18. package/dist/{chunk-R5TZHNTG.js → chunk-RBXIZJPE.js} +17 -5
  19. package/dist/chunk-RBXIZJPE.js.map +1 -0
  20. package/dist/{chunk-CCRFYGHU.js → chunk-T6IPHUN4.js} +2354 -2338
  21. package/dist/chunk-T6IPHUN4.js.map +1 -0
  22. package/dist/export-gif.d.ts +2 -2
  23. package/dist/export-gif.js +4 -3
  24. package/dist/graph-3d/index.d.ts +28 -1
  25. package/dist/graph-3d/index.js +26 -12
  26. package/dist/graph-3d/index.js.map +1 -1
  27. package/dist/index.d.ts +155 -29
  28. package/dist/index.js +1774 -186
  29. package/dist/index.js.map +1 -1
  30. package/dist/{mount-TEjIdF0m.d.ts → mount-types-DeUCa2hy.d.ts} +34 -21
  31. package/dist/{renderer-registry-Cng76n8F.d.ts → renderer-registry-Bu22Roek.d.ts} +5 -22
  32. package/dist/simulation-worker.js +1 -0
  33. package/dist/static.d.ts +4 -2
  34. package/dist/static.js +34 -10
  35. package/dist/static.js.map +1 -1
  36. package/dist/story/index.d.ts +8 -6
  37. package/dist/story/index.js +15 -12
  38. package/dist/story/index.js.map +1 -1
  39. package/dist/styles.css +1 -1
  40. package/dist/styles.css.map +1 -1
  41. package/package.json +3 -3
  42. package/dist/chunk-APMUBW72.js.map +0 -1
  43. package/dist/chunk-CCRFYGHU.js.map +0 -1
  44. package/dist/chunk-GX6BWMJD.js.map +0 -1
  45. package/dist/chunk-MGFXAROR.js.map +0 -1
  46. package/dist/chunk-Q7YEEF2X.js.map +0 -1
  47. package/dist/chunk-R5TZHNTG.js.map +0 -1
  48. package/dist/chunk-REH5UQCL.js.map +0 -1
  49. package/dist/chunk-SDJHUELU.js.map +0 -1
  50. package/dist/chunk-UC4IHEUO.js +0 -73
  51. package/dist/chunk-UC4IHEUO.js.map +0 -1
@@ -1,14 +1,16 @@
1
1
  import {
2
2
  nextSvgId,
3
- renderChromeElement,
4
3
  renderLegend,
5
4
  stampAnimationVars
6
- } from "./chunk-APMUBW72.js";
5
+ } from "./chunk-ERPYVYFW.js";
6
+ import {
7
+ renderAttributionBrand,
8
+ renderChromeElement,
9
+ stampThemeProperties
10
+ } from "./chunk-NLKQ5AOA.js";
7
11
 
8
12
  // src/tilemap-renderer.ts
9
13
  var SVG_NS = "http://www.w3.org/2000/svg";
10
- var XLINK_NS = "http://www.w3.org/1999/xlink";
11
- var BRAND_URL = "https://tryopendata.ai";
12
14
  function createSVGElement(tag) {
13
15
  return document.createElementNS(SVG_NS, tag);
14
16
  }
@@ -21,7 +23,7 @@ function renderChrome(parent, layout) {
21
23
  const g = createSVGElement("g");
22
24
  g.setAttribute("class", "oc-chrome");
23
25
  const { chrome, measureText } = layout;
24
- const bottomOffset = layout.area.y + layout.area.height;
26
+ const bottomOffset = chrome.bottomAnchorY ?? layout.area.y + layout.area.height;
25
27
  if (chrome.title) {
26
28
  renderChromeElement(g, chrome.title, "oc-title", "title", measureText);
27
29
  }
@@ -57,46 +59,6 @@ function renderChrome(parent, layout) {
57
59
  }
58
60
  parent.appendChild(g);
59
61
  }
60
- function renderWatermark(parent, layout) {
61
- if (layout.width < 480) return;
62
- const { width, height } = layout;
63
- const { theme } = layout;
64
- const padding = theme.spacing.padding;
65
- const rightEdge = width - padding;
66
- const bottomEdge = height - padding;
67
- const fill = theme.colors.axis;
68
- const a = createSVGElement("a");
69
- a.setAttribute("href", BRAND_URL);
70
- a.setAttributeNS(XLINK_NS, "xlink:href", BRAND_URL);
71
- a.setAttribute("target", "_blank");
72
- a.setAttribute("rel", "noopener");
73
- a.setAttribute("class", "oc-chrome-ref");
74
- const text = createSVGElement("text");
75
- setAttrs(text, {
76
- x: rightEdge,
77
- y: bottomEdge,
78
- "dominant-baseline": "alphabetic",
79
- "text-anchor": "end",
80
- "font-family": theme.fonts.family,
81
- "font-size": 12,
82
- "fill-opacity": 0.55
83
- });
84
- text.style.setProperty("fill", fill);
85
- const trySpan = createSVGElement("tspan");
86
- setAttrs(trySpan, { "font-weight": 500 });
87
- trySpan.textContent = "try";
88
- const openDataSpan = createSVGElement("tspan");
89
- setAttrs(openDataSpan, { "font-weight": 600, "font-size": 16 });
90
- openDataSpan.textContent = "OpenData";
91
- const aiSpan = createSVGElement("tspan");
92
- setAttrs(aiSpan, { "font-weight": 500 });
93
- aiSpan.textContent = ".ai";
94
- text.appendChild(trySpan);
95
- text.appendChild(openDataSpan);
96
- text.appendChild(aiSpan);
97
- a.appendChild(text);
98
- parent.appendChild(a);
99
- }
100
62
  function renderTiles(parent, tiles, animation) {
101
63
  const g = createSVGElement("g");
102
64
  g.setAttribute("class", "oc-tilemap-tiles");
@@ -290,7 +252,7 @@ function renderGradientLegend(parent, layout) {
290
252
  parent.appendChild(g);
291
253
  }
292
254
  function renderTileMapSVG(layout, opts) {
293
- const { width, height, tiles, a11y, watermark, animation } = layout;
255
+ const { width, height, tiles, a11y, animation } = layout;
294
256
  const animate = opts?.animate && !!animation?.enter;
295
257
  const svg = createSVGElement("svg");
296
258
  svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
@@ -300,6 +262,7 @@ function renderTileMapSVG(layout, opts) {
300
262
  }
301
263
  const classes = animate ? "oc-tilemap oc-animate" : "oc-tilemap";
302
264
  svg.setAttribute("class", classes);
265
+ stampThemeProperties(svg, layout.theme);
303
266
  if (animate && animation?.enter) {
304
267
  const stagger = Math.max(5, Math.round(800 / Math.max(tiles.length, 1)));
305
268
  stampAnimationVars(svg, {
@@ -319,13 +282,16 @@ function renderTileMapSVG(layout, opts) {
319
282
  } else {
320
283
  renderGradientLegend(svg, layout);
321
284
  }
322
- if (watermark) {
323
- renderWatermark(svg, layout);
324
- }
285
+ renderAttributionBrand(
286
+ svg,
287
+ layout.chrome,
288
+ layout.chrome.bottomAnchorY ?? layout.area.y + layout.area.height,
289
+ layout.measureText
290
+ );
325
291
  return svg;
326
292
  }
327
293
 
328
294
  export {
329
295
  renderTileMapSVG
330
296
  };
331
- //# sourceMappingURL=chunk-Q7YEEF2X.js.map
297
+ //# sourceMappingURL=chunk-6YPRYQKD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tilemap-renderer.ts"],"sourcesContent":["/**\n * TileMap SVG renderer: converts a TileMapLayout into SVG DOM elements.\n *\n * Creates an <svg> with tile rectangles, state code labels, value labels,\n * gradient legend, and chrome. All styling via inline SVG attributes from\n * layout data. Animation is pure CSS, driven by data attributes.\n */\n\nimport type {\n ResolvedAnimation,\n TileMapLayout,\n TileMapTileMark,\n} from '@opendata-ai/openchart-core';\nimport { stampAnimationVars } from './animation-vars';\nimport { renderAttributionBrand } from './renderers/brand';\nimport { renderChromeElement } from './renderers/chrome';\nimport { renderLegend } from './renderers/legend';\nimport { nextSvgId } from './svg-ids';\nimport { stampThemeProperties } from './theme-tokens';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction createSVGElement(tag: string): SVGElement {\n return document.createElementNS(SVG_NS, tag);\n}\n\nfunction 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\n// ---------------------------------------------------------------------------\n// Chrome rendering (delegates to the shared helper for text wrapping)\n// ---------------------------------------------------------------------------\n\nfunction renderChrome(parent: SVGElement, layout: TileMapLayout): void {\n const g = createSVGElement('g');\n g.setAttribute('class', 'oc-chrome');\n\n const { chrome, measureText } = layout;\n const bottomOffset = chrome.bottomAnchorY ?? layout.area.y + layout.area.height;\n\n if (chrome.title) {\n renderChromeElement(g, chrome.title, 'oc-title', 'title', measureText);\n }\n if (chrome.subtitle) {\n renderChromeElement(g, chrome.subtitle, 'oc-subtitle', 'subtitle', measureText);\n }\n if (chrome.source) {\n renderChromeElement(\n g,\n { ...chrome.source, y: bottomOffset + chrome.source.y },\n 'oc-source',\n 'source',\n measureText,\n );\n }\n if (chrome.byline) {\n renderChromeElement(\n g,\n { ...chrome.byline, y: bottomOffset + chrome.byline.y },\n 'oc-byline',\n 'byline',\n measureText,\n );\n }\n if (chrome.footer) {\n renderChromeElement(\n g,\n { ...chrome.footer, y: bottomOffset + chrome.footer.y },\n 'oc-footer',\n 'footer',\n measureText,\n );\n }\n\n parent.appendChild(g);\n}\n\n// ---------------------------------------------------------------------------\n// Watermark rendering\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Tiles rendering\n// ---------------------------------------------------------------------------\n\nfunction renderTiles(\n parent: SVGElement,\n tiles: TileMapTileMark[],\n animation?: ResolvedAnimation,\n): void {\n const g = createSVGElement('g');\n g.setAttribute('class', 'oc-tilemap-tiles');\n g.setAttribute('role', 'list');\n\n // Compute per-tile delays with jitter for organic feel.\n // Base delay spreads tiles across ~800ms window, jitter adds +-40% variation\n // so some tiles pop in clusters while others have longer gaps.\n const tileDelays: number[] = [];\n if (animation?.enter) {\n const baseStagger = 800 / Math.max(tiles.length, 1);\n let seed = 17;\n for (let i = 0; i < tiles.length; i++) {\n const idx = tiles[i].animationIndex ?? i;\n seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n const jitter = ((seed % 1000) / 1000 - 0.5) * 0.8;\n tileDelays.push(Math.max(0, Math.round(idx * baseStagger * (1 + jitter))));\n }\n }\n\n for (let i = 0; i < tiles.length; i++) {\n const tile = tiles[i];\n const tileGroup = createSVGElement('g');\n tileGroup.setAttribute('class', 'oc-tilemap-tile');\n tileGroup.setAttribute('data-state', tile.stateCode);\n tileGroup.setAttribute('role', 'listitem');\n if (tile.aria?.label) {\n tileGroup.setAttribute('aria-label', tile.aria.label);\n }\n\n if (animation?.enter) {\n const idx = tile.animationIndex ?? i;\n tileGroup.setAttribute('data-animation-index', String(idx));\n (tileGroup as SVGElement & ElementCSSInlineStyle).style.setProperty(\n '--oc-mark-index',\n String(idx),\n );\n (tileGroup as SVGElement & ElementCSSInlineStyle).style.setProperty(\n '--oc-tile-delay',\n `${tileDelays[i]}ms`,\n );\n }\n\n // Tile background rect\n const rect = createSVGElement('rect');\n setAttrs(rect, {\n x: tile.x,\n y: tile.y,\n width: tile.size,\n height: tile.size,\n rx: tile.cornerRadius,\n fill: tile.fill,\n 'fill-opacity': tile.fillOpacity ?? 1,\n stroke: tile.stroke,\n 'stroke-width': tile.strokeWidth,\n });\n tileGroup.appendChild(rect);\n\n // State code label\n const codeLabel = createSVGElement('text');\n setAttrs(codeLabel, {\n x: tile.label.x,\n y: tile.label.y,\n 'text-anchor': 'middle',\n 'dominant-baseline': 'central',\n 'font-family': tile.label.style.fontFamily,\n 'font-size': tile.label.style.fontSize,\n 'font-weight': tile.label.style.fontWeight,\n // A hair of tracking is what keeps a two-letter code legible at 8px now\n // that it is set at 600 instead of 700.\n 'letter-spacing': '0.02em',\n });\n (codeLabel as SVGElement & ElementCSSInlineStyle).style.setProperty(\n 'fill',\n tile.label.style.fill,\n );\n codeLabel.textContent = tile.label.text;\n tileGroup.appendChild(codeLabel);\n\n // Value label (if visible)\n if (tile.valueLabel.visible && tile.valueLabel.text) {\n const valueLabel = createSVGElement('text');\n setAttrs(valueLabel, {\n x: tile.valueLabel.x,\n y: tile.valueLabel.y,\n 'text-anchor': 'middle',\n 'dominant-baseline': 'central',\n 'font-family': tile.valueLabel.style.fontFamily,\n 'font-size': tile.valueLabel.style.fontSize,\n 'font-weight': tile.valueLabel.style.fontWeight,\n });\n (valueLabel as SVGElement & ElementCSSInlineStyle).style.setProperty(\n 'fill',\n tile.valueLabel.style.fill,\n );\n valueLabel.textContent = tile.valueLabel.text;\n tileGroup.appendChild(valueLabel);\n }\n\n g.appendChild(tileGroup);\n }\n\n parent.appendChild(g);\n}\n\n// ---------------------------------------------------------------------------\n// Gradient legend rendering\n// ---------------------------------------------------------------------------\n\nfunction renderGradientLegend(parent: SVGElement, layout: TileMapLayout): void {\n if (!layout.gradientLegend) return;\n\n const { gradientLegend } = layout;\n const g = createSVGElement('g');\n g.setAttribute('class', 'oc-tilemap-legend');\n\n // Build linear gradient in defs\n const defs = parent.querySelector('defs') || createSVGElement('defs');\n const exists = parent.querySelector('defs');\n if (!exists) {\n parent.insertBefore(defs, parent.firstChild);\n }\n\n const gradientId = nextSvgId('oc-tilemap-legend-gradient');\n const grad = createSVGElement('linearGradient');\n grad.id = gradientId;\n grad.setAttribute('x1', '0%');\n grad.setAttribute('y1', '0%');\n grad.setAttribute('x2', '100%');\n grad.setAttribute('y2', '0%');\n\n for (const stop of gradientLegend.colorStops) {\n const s = createSVGElement('stop');\n const attrs: Record<string, string | number> = {\n offset: `${stop.offset * 100}%`,\n 'stop-color': stop.color,\n };\n if (stop.opacity !== undefined) {\n attrs['stop-opacity'] = stop.opacity;\n }\n setAttrs(s, attrs);\n grad.appendChild(s);\n }\n\n (defs as SVGElement).appendChild(grad);\n\n // Gradient bar: square-cornered, so it reads as a color scale rather than a\n // pill-shaped UI control.\n const barHeight = gradientLegend.bounds.height;\n const bar = createSVGElement('rect');\n setAttrs(bar, {\n x: gradientLegend.bounds.x,\n y: gradientLegend.bounds.y,\n width: gradientLegend.bounds.width,\n height: barHeight,\n fill: `url(#${gradientId})`,\n 'shape-rendering': 'crispEdges',\n });\n g.appendChild(bar);\n\n // Min label\n const minText = createSVGElement('text');\n setAttrs(minText, {\n x: gradientLegend.bounds.x,\n y: gradientLegend.bounds.y + gradientLegend.bounds.height + 14,\n 'text-anchor': 'start',\n 'font-family': gradientLegend.labelStyle.fontFamily,\n 'font-size': gradientLegend.labelStyle.fontSize,\n 'font-weight': gradientLegend.labelStyle.fontWeight,\n });\n (minText as SVGElement & ElementCSSInlineStyle).style.setProperty(\n 'fill',\n gradientLegend.labelStyle.fill,\n );\n minText.textContent = gradientLegend.minLabel;\n g.appendChild(minText);\n\n // Max label\n const maxText = createSVGElement('text');\n setAttrs(maxText, {\n x: gradientLegend.bounds.x + gradientLegend.bounds.width,\n y: gradientLegend.bounds.y + gradientLegend.bounds.height + 14,\n 'text-anchor': 'end',\n 'font-family': gradientLegend.labelStyle.fontFamily,\n 'font-size': gradientLegend.labelStyle.fontSize,\n 'font-weight': gradientLegend.labelStyle.fontWeight,\n });\n (maxText as SVGElement & ElementCSSInlineStyle).style.setProperty(\n 'fill',\n gradientLegend.labelStyle.fill,\n );\n maxText.textContent = gradientLegend.maxLabel;\n g.appendChild(maxText);\n\n // Detached \"no data\" swatch, keyed beside the ramp rather than at its low end.\n if (gradientLegend.noData) {\n const nd = gradientLegend.noData;\n const swatch = createSVGElement('rect');\n swatch.setAttribute('class', 'oc-legend-nodata');\n setAttrs(swatch, {\n x: nd.x,\n y: nd.y,\n width: nd.size,\n height: nd.size,\n fill: nd.fill,\n 'shape-rendering': 'crispEdges',\n });\n g.appendChild(swatch);\n\n const ndLabel = createSVGElement('text');\n setAttrs(ndLabel, {\n x: nd.labelX,\n y: nd.labelY,\n 'text-anchor': 'start',\n 'font-family': gradientLegend.labelStyle.fontFamily,\n 'font-size': gradientLegend.labelStyle.fontSize,\n 'font-weight': gradientLegend.labelStyle.fontWeight,\n });\n (ndLabel as SVGElement & ElementCSSInlineStyle).style.setProperty(\n 'fill',\n gradientLegend.labelStyle.fill,\n );\n ndLabel.textContent = nd.label;\n g.appendChild(ndLabel);\n }\n\n parent.appendChild(g);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Render a TileMapLayout to an SVG element.\n */\nexport function renderTileMapSVG(\n layout: TileMapLayout,\n opts?: { animate?: boolean },\n): SVGSVGElement {\n const { width, height, tiles, a11y, animation } = layout;\n const animate = opts?.animate && !!animation?.enter;\n\n const svg = createSVGElement('svg') as SVGSVGElement;\n svg.setAttribute('viewBox', `0 0 ${width} ${height}`);\n svg.setAttribute('role', 'img');\n if (a11y.altText) {\n svg.setAttribute('aria-label', a11y.altText);\n }\n\n const classes = animate ? 'oc-tilemap oc-animate' : 'oc-tilemap';\n svg.setAttribute('class', classes);\n stampThemeProperties(svg, layout.theme);\n\n if (animate && animation?.enter) {\n // Target ~1s total: stagger window ~800ms + per-tile pop ~200ms\n const stagger = Math.max(5, Math.round(800 / Math.max(tiles.length, 1)));\n stampAnimationVars(svg, {\n duration: animation.enter.duration,\n spring: animation.enter.spring,\n stagger,\n annotationDelay: animation.annotationDelay,\n ease: animation.enter.ease,\n });\n }\n\n // Empty defs element (will be filled by gradient legend)\n const defs = createSVGElement('defs');\n svg.appendChild(defs);\n\n // Render chrome\n renderChrome(svg, layout);\n\n // Render tiles\n renderTiles(svg, tiles, animate ? animation : undefined);\n\n // Render legend (gradient for quantitative, categorical for nominal)\n if (layout.categoricalLegend) {\n renderLegend(svg, layout.categoricalLegend);\n } else {\n renderGradientLegend(svg, layout);\n }\n\n // Render watermark\n renderAttributionBrand(\n svg,\n layout.chrome,\n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 @@
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 applyKnockoutHalo(el, color, fontSize) {
13
- setAttrs(el, {
14
- stroke: color,
15
- "stroke-width": Math.round(fontSize * 0.3),
16
- "stroke-linejoin": "round",
17
- "paint-order": "stroke"
18
- });
19
- }
20
- function applyTextStyle(el, style) {
21
- const inline = el.style;
22
- inline.setProperty("fill", style.fill);
23
- inline.setProperty("font-size", `${style.fontSize}px`);
24
- inline.setProperty("font-weight", String(style.fontWeight));
25
- inline.setProperty("font-family", style.fontFamily);
26
- if (style.textAnchor) {
27
- el.setAttribute("text-anchor", style.textAnchor);
28
- }
29
- if (style.dominantBaseline) {
30
- el.setAttribute("dominant-baseline", style.dominantBaseline);
31
- }
32
- if (style.fontVariant) {
33
- el.setAttribute("font-variant", style.fontVariant);
34
- }
35
- }
1
+ import {
2
+ SVG_NS
3
+ } from "./chunk-FFP5GXIP.js";
36
4
 
37
5
  // src/theme-style-block.ts
38
- import { adaptForLightLineStroke, cssTokenDefault } from "@opendata-ai/openchart-core";
6
+ import { adaptForLightLineStroke, CSS_TOKENS, cssTokenDefault } from "@opendata-ai/openchart-core";
39
7
  function buildThemeStyleBlock(theme) {
40
8
  const accent = theme.colors.categorical[0] ?? cssTokenDefault("--oc-accent", "light");
41
9
  const bg = theme.colors.neutral.surface;
@@ -74,7 +42,7 @@ function buildThemeStyleBlock(theme) {
74
42
  const rules = [
75
43
  // Tabular figures everywhere in the chart's own text: axis ticks, value
76
44
  // labels and legend entries all line up column-wise.
77
- `svg.oc-chart { ${props.join("; ")}; font-variant-numeric: tabular-nums; }`,
45
+ `svg.oc-chart, svg.oc-map, svg.oc-tilemap, svg.oc-barlist { ${props.join("; ")}; font-variant-numeric: tabular-nums; }`,
78
46
  `.oc-chrome { font-family: var(--oc-font-family); }`,
79
47
  `.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); }`,
80
48
  `.oc-title { font-size: var(--oc-title-size); font-weight: var(--oc-title-weight); letter-spacing: var(--oc-title-tracking); fill: var(--oc-text); }`,
@@ -102,6 +70,7 @@ function buildThemeStyleBlock(theme) {
102
70
  }
103
71
  function injectThemeStyleBlock(svg, theme) {
104
72
  if (!theme) return;
73
+ for (const previous of svg.querySelectorAll("style[data-oc-theme]")) previous.remove();
105
74
  let defs = svg.querySelector("defs");
106
75
  if (!defs) {
107
76
  defs = document.createElementNS(SVG_NS, "defs");
@@ -112,15 +81,27 @@ function injectThemeStyleBlock(svg, theme) {
112
81
  style.textContent = buildThemeStyleBlock(theme);
113
82
  defs.insertBefore(style, defs.firstChild);
114
83
  }
84
+ function copyComputedThemeProperties(source, clone) {
85
+ if (!source.isConnected) return;
86
+ const computed = getComputedStyle(source);
87
+ for (const { name } of CSS_TOKENS) {
88
+ const value = computed.getPropertyValue(name).trim();
89
+ if (value) clone.style.setProperty(name, value);
90
+ }
91
+ }
92
+ function prepareSettledExportTheme(source, settled, theme, explicitTheme = false) {
93
+ if (explicitTheme) {
94
+ for (const { name } of CSS_TOKENS) settled.style.removeProperty(name);
95
+ } else {
96
+ copyComputedThemeProperties(source, settled);
97
+ }
98
+ injectThemeStyleBlock(settled, theme);
99
+ }
115
100
 
116
101
  export {
117
- SVG_NS,
118
- XLINK_NS,
119
- createSVGElement,
120
- setAttrs,
121
- applyKnockoutHalo,
122
- applyTextStyle,
123
102
  buildThemeStyleBlock,
124
- injectThemeStyleBlock
103
+ injectThemeStyleBlock,
104
+ copyComputedThemeProperties,
105
+ prepareSettledExportTheme
125
106
  };
126
- //# sourceMappingURL=chunk-SDJHUELU.js.map
107
+ //# sourceMappingURL=chunk-A5C4VCUO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/theme-style-block.ts"],"sourcesContent":["/**\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 eyebrow 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, CSS_TOKENS, 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 each supported SVG root 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 = theme.colors.neutral.surface;\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-secondary: ${theme.colors.neutral.secondary}`,\n `--oc-text-faint: ${theme.colors.neutral.faint}`,\n `--oc-border: ${theme.colors.neutral.border}`,\n `--oc-gridline: ${theme.colors.gridline}`,\n // Hairline, not the tick-label ink.\n `--oc-axis: ${theme.colors.hairline}`,\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 // Tabular figures everywhere in the chart's own text: axis ticks, value\n // labels and legend entries all line up column-wise.\n `svg.oc-chart, svg.oc-map, svg.oc-tilemap, svg.oc-barlist { ${props.join('; ')}; font-variant-numeric: tabular-nums; }`,\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: 500; letter-spacing: 0.02em; fill: var(--oc-text-faint); }`,\n `.oc-eyebrow-dot { fill: var(--oc-accent); }`,\n `.oc-metrics { font-family: var(--oc-font-family); }`,\n `.oc-metric-label { font-size: 11px; font-weight: 500; letter-spacing: 0.06em; text-transform: uppercase; fill: var(--oc-text-muted); }`,\n `.oc-metric-value { font-size: 22px; font-weight: 600; letter-spacing: -0.02em; fill: var(--oc-text); font-variant-numeric: tabular-nums; }`,\n `.oc-metric-delta-up { fill: var(--oc-positive); font-size: 12px; font-weight: 500; }`,\n `.oc-metric-delta-down { fill: var(--oc-negative); font-size: 12px; font-weight: 500; }`,\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-text-muted); 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. Replaces any prior export theme block, so repeated\n * preparation produces one block. 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 for (const previous of svg.querySelectorAll('style[data-oc-theme]')) previous.remove();\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\n/** Preserve the live host CSS tokens when an export leaves its document. */\nexport function copyComputedThemeProperties(source: SVGElement, clone: SVGElement): void {\n if (!source.isConnected) return;\n const computed = getComputedStyle(source);\n for (const { name } of CSS_TOKENS) {\n const value = computed.getPropertyValue(name).trim();\n if (value) clone.style.setProperty(name, value);\n }\n}\n\n/** Prepare detached settled geometry with its live cascade or an export override. */\nexport function prepareSettledExportTheme(\n source: SVGElement,\n settled: SVGElement,\n theme: ResolvedTheme | undefined,\n explicitTheme = false,\n): void {\n if (explicitTheme) {\n // A re-render may stamp authored mount values inline. They would beat the\n // export theme's stylesheet even when copying the live cascade is skipped.\n for (const { name } of CSS_TOKENS) settled.style.removeProperty(name);\n } else {\n copyComputedThemeProperties(source, settled);\n }\n injectThemeStyleBlock(settled, theme);\n}\n"],"mappings":";;;;;AAkBA,SAAS,yBAAyB,YAAY,uBAAuB;AAQ9D,SAAS,qBAAqB,OAA8B;AACjE,QAAM,SAAS,MAAM,OAAO,YAAY,CAAC,KAAK,gBAAgB,eAAe,OAAO;AACpF,QAAM,KAAK,MAAM,OAAO,QAAQ;AAEhC,QAAM,QAAQ;AAAA,IACZ,qBAAqB,MAAM,MAAM,MAAM;AAAA,IACvC,mBAAmB,MAAM,MAAM,IAAI;AAAA,IACnC,oBAAoB,MAAM,OAAO,MAAM,QAAQ;AAAA,IAC/C,sBAAsB,MAAM,OAAO,MAAM,UAAU;AAAA,IACnD,wBAAwB,gBAAgB,uBAAuB,OAAO,CAAC;AAAA,IACvE,uBAAuB,MAAM,OAAO,SAAS,QAAQ;AAAA,IACrD,yBAAyB,MAAM,OAAO,SAAS,UAAU;AAAA,IACzD,qBAAqB,MAAM,OAAO,OAAO,QAAQ;AAAA,I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A;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;AAQO,SAAS,sBAAsB,KAAiB,OAAwC;AAC7F,MAAI,CAAC,MAAO;AACZ,aAAW,YAAY,IAAI,iBAAiB,sBAAsB,EAAG,UAAS,OAAO;AACrF,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;AAGO,SAAS,4BAA4B,QAAoB,OAAyB;AACvF,MAAI,CAAC,OAAO,YAAa;AACzB,QAAM,WAAW,iBAAiB,MAAM;AACxC,aAAW,EAAE,KAAK,KAAK,YAAY;AACjC,UAAM,QAAQ,SAAS,iBAAiB,IAAI,EAAE,KAAK;AACnD,QAAI,MAAO,OAAM,MAAM,YAAY,MAAM,KAAK;AAAA,EAChD;AACF;AAGO,SAAS,0BACd,QACA,SACA,OACA,gBAAgB,OACV;AACN,MAAI,eAAe;AAGjB,eAAW,EAAE,KAAK,KAAK,WAAY,SAAQ,MAAM,eAAe,IAAI;AAAA,EACtE,OAAO;AACL,gCAA4B,QAAQ,OAAO;AAAA,EAC7C;AACA,wBAAsB,SAAS,KAAK;AACtC;","names":[]}
@@ -5,10 +5,10 @@ import {
5
5
  getSVGBackgroundColor,
6
6
  getSVGDimensions,
7
7
  rasterizeSVGToCanvas
8
- } from "./chunk-R5TZHNTG.js";
8
+ } from "./chunk-RBXIZJPE.js";
9
9
  import {
10
10
  injectThemeStyleBlock
11
- } from "./chunk-SDJHUELU.js";
11
+ } from "./chunk-A5C4VCUO.js";
12
12
 
13
13
  // src/export-gif.ts
14
14
  import {
@@ -144,6 +144,8 @@ function applyFrameState(target, nowMs, easeKind, phase) {
144
144
  style.opacity = String(eased);
145
145
  break;
146
146
  }
147
+ default:
148
+ target.kind;
147
149
  }
148
150
  }
149
151
  function clearFrameState(target) {
@@ -243,4 +245,4 @@ export {
243
245
  applyFrameState,
244
246
  exportGIF
245
247
  };
246
- //# sourceMappingURL=chunk-MGFXAROR.js.map
248
+ //# sourceMappingURL=chunk-CMIJA63X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/export-gif.ts","../src/gif-encode.ts"],"sourcesContent":["/**\n * Animated GIF export.\n *\n * Unlike PNG/JPG (single static frame), GIF export must reproduce the chart's\n * entrance animation across many frames. OpenChart entrance animations are pure\n * CSS keyframes that mutate `clip-path`/`opacity`/`transform` in *computed*\n * style, which `XMLSerializer` does not capture — so serializing the live,\n * mid-animation SVG yields the base markup on every frame (a static GIF).\n *\n * This module sidesteps that by *synthesizing* frames deterministically: it\n * takes the settled, final-state SVG plus the resolved animation config,\n * computes each animated element's value at time `t` in JS, stamps\n * `clip-path`/`opacity` as INLINE attributes on a clone (inline values DO\n * serialize), rasterizes that clone, and encodes each frame with gifenc.\n *\n * This mirrors the entrance keyframes in `packages/core/src/styles/*.css`:\n * bars clip bottom-up / left-right, line/area clip left-right, arcs and points\n * fade. Only the entrance is reproduced; the on-screen CSS animation is\n * untouched. `gifenc` is an optional peer dependency, loaded dynamically.\n */\n\nimport {\n type AnimationEase,\n type MotionPhase,\n type ResolvedAnimation,\n type ResolvedTheme,\n sampleMotion,\n} from '@opendata-ai/openchart-core';\nimport {\n embedFonts,\n ensureSVGDimensions,\n exportSVG,\n getSVGBackgroundColor,\n getSVGDimensions,\n rasterizeSVGToCanvas,\n} from './export';\nimport { readCanvasSRGB } from './gif-encode';\nimport { injectThemeStyleBlock } from './theme-style-block';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface GIFExportOptions {\n /** Frames per second to capture. Defaults to 25. */\n fps?: number;\n /** DPI scaling factor, matching PNG export. Defaults to 2. */\n dpi?: number;\n /**\n * Loop behavior. Defaults to play-once (hold the final frame):\n * - `false` / omitted: play once, then hold the final frame\n * - `true`: loop forever\n * - a number: loop that many times, then hold\n */\n loop?: boolean | number;\n /**\n * Explicit capture duration in ms. Defaults to the resolved animation total\n * (enter duration + last element's stagger delay + a small tail).\n */\n durationMs?: number;\n /** Embed fonts as base64 data URIs so text matches on-screen. Defaults to true. */\n embedFonts?: boolean;\n /**\n * Opaque background fill. GIF can't carry partial alpha, so a transparent\n * chart would composite onto black. Defaults to the chart's own background\n * color (or white if the chart is transparent).\n */\n backgroundColor?: string;\n /**\n * Resolved theme to inline as a `<style>` block so class-based fills (metric\n * cells, eyebrow dot, legend text) survive serialization. Omit to skip.\n */\n theme?: ResolvedTheme;\n}\n\n/** Which visual property an element's entrance keyframe animates. */\nexport type AnimationKind = 'bar-vertical' | 'bar-horizontal' | 'line-area' | 'fade';\n\nexport interface AnimatedTarget {\n /** The element in the CLONE that receives per-frame inline styles. */\n el: SVGElement;\n kind: AnimationKind;\n /** Start offset in ms (stagger * mark index). */\n startMs: number;\n /** Duration of this element's own animation in ms. */\n durationMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Easing — replicate --oc-ease-smooth (CSS linear() sample points)\n// ---------------------------------------------------------------------------\n\n/**\n * Sample points of the `--oc-ease-smooth` token (see tokens.css). CSS\n * `linear()` interpolates piecewise-linearly between evenly-spaced samples, so\n * we reproduce it exactly rather than approximating with a cubic-bezier.\n */\nexport const EASE_SMOOTH_SAMPLES: readonly number[] = [\n 0, 0.157, 0.438, 0.64, 0.766, 0.85, 0.906, 0.941, 0.964, 0.978, 0.988, 0.994, 0.998, 1,\n];\n\n/** Piecewise-linear evaluation of a CSS linear() sample array at t in [0,1]. */\nexport function evalLinearSamples(samples: readonly number[], t: number): number {\n if (t <= 0) return samples[0];\n if (t >= 1) return samples[samples.length - 1];\n const scaled = t * (samples.length - 1);\n const i = Math.floor(scaled);\n const frac = scaled - i;\n return samples[i] + (samples[i + 1] - samples[i]) * frac;\n}\n\n/** Ease a normalized progress value. Only 'smooth' is sample-accurate today. */\nfunction ease(p: number, _kind: AnimationEase): number {\n // The entrance rules use --oc-ease-smooth (or fall back to it) in all cases\n // GIF export handles today. Snappy/others could add their own samples later.\n return evalLinearSamples(EASE_SMOOTH_SAMPLES, p);\n}\n\n// ---------------------------------------------------------------------------\n// Target discovery\n// ---------------------------------------------------------------------------\n\n/**\n * Classify an animated element (identified by `data-animation-index`) into the\n * keyframe it plays, and return the element that should receive inline styles.\n * Returns null only when a bar group has no shape child to clip. Unrecognized\n * mark types (map/tilemap/table/text) fall back to a plain opacity fade rather\n * than a hard pop-in — see the generic case at the end.\n */\nexport function classifyTarget(\n groupOrEl: SVGElement,\n): { el: SVGElement; kind: AnimationKind } | null {\n const cls = groupOrEl.getAttribute('class') ?? '';\n\n if (cls.includes('oc-stack-reveal'))\n return {\n el: groupOrEl,\n kind:\n groupOrEl.getAttribute('data-orient') === 'horizontal' ? 'bar-horizontal' : 'bar-vertical',\n };\n\n // Bars: CSS animates the child <rect>; clip + fade. Orient on the group.\n if (cls.includes('oc-mark-rect') || cls.includes('oc-mark-bar')) {\n const rect = groupOrEl.querySelector('rect') ?? groupOrEl.querySelector('path');\n if (!rect) return null;\n const horizontal = groupOrEl.getAttribute('data-orient') === 'horizontal';\n return { el: rect as SVGElement, kind: horizontal ? 'bar-horizontal' : 'bar-vertical' };\n }\n\n // Line/area: the whole group clips left-to-right + fades.\n if (cls.includes('oc-mark-line') || cls.includes('oc-mark-area')) {\n return { el: groupOrEl, kind: 'line-area' };\n }\n\n // Arcs and points: fade only (scale breaks arc/point positioning, so the CSS\n // uses a plain opacity fade too).\n if (\n cls.includes('oc-mark-arc') ||\n cls.includes('oc-mark-point') ||\n cls.includes('oc-mark-circle')\n ) {\n return { el: groupOrEl, kind: 'fade' };\n }\n\n // Everything else (text labels, rules, ticks, map/tilemap/table marks) is a\n // plain fade; treat generically so the frame isn't a hard pop-in.\n return { el: groupOrEl, kind: 'fade' };\n}\n\n/**\n * Build the list of animated targets from a cloned SVG, pairing each element\n * with its timing. Elements carry `data-animation-index` (the mark index that\n * drives stagger) stamped by the renderer.\n */\nfunction collectTargets(\n clone: SVGElement,\n enterDurationMs: number,\n staggerMs: number,\n): AnimatedTarget[] {\n const els = clone.querySelectorAll<SVGElement>('[data-animation-index]');\n const targets: AnimatedTarget[] = [];\n\n for (const el of els) {\n if (!el.classList.contains('oc-stack-reveal') && el.closest('.oc-stack-reveal')) continue;\n const classified = classifyTarget(el);\n if (!classified) continue;\n const idx = parseInt(el.getAttribute('data-animation-index') ?? '0', 10) || 0;\n // Points animate at 40% of the base duration (matches animation.css).\n const isPoint =\n classified.kind === 'fade' && /oc-mark-(point|circle)/.test(el.getAttribute('class') ?? '');\n // Points on line/area charts start 35% of a duration in, so they pop as the\n // line draws through them (the `.oc-mark-line ~ circle.oc-mark-point` rule).\n const lineOffset = isPoint && hasLineAreaSibling(el) ? enterDurationMs * 0.35 : 0;\n targets.push({\n el: classified.el,\n kind: classified.kind,\n startMs: staggerMs * idx + lineOffset,\n durationMs: isPoint ? enterDurationMs * 0.4 : enterDurationMs,\n });\n }\n\n return targets;\n}\n\n/**\n * Replicate the CSS sibling combinator `.oc-mark-line ~ circle.oc-mark-point`:\n * true when a line or area mark precedes this point among its siblings.\n */\nfunction hasLineAreaSibling(point: SVGElement): boolean {\n let sib = point.previousElementSibling;\n while (sib) {\n const cls = sib.getAttribute('class') ?? '';\n if (cls.includes('oc-mark-line') || cls.includes('oc-mark-area')) return true;\n sib = sib.previousElementSibling;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Per-frame interpolation\n// ---------------------------------------------------------------------------\n\nconst clamp01 = (v: number): number => (v < 0 ? 0 : v > 1 ? 1 : v);\n\n/**\n * Distinguish \"the optional gifenc peer isn't installed\" from a real error\n * thrown while loading it. Node/bundlers use ERR_MODULE_NOT_FOUND /\n * MODULE_NOT_FOUND / \"Cannot find module\" for the former.\n */\nexport function isModuleNotFound(err: unknown): boolean {\n const code = (err as { code?: string })?.code;\n if (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') return true;\n const message = (err as { message?: string })?.message ?? '';\n return /cannot find (module|package)|failed to (resolve|fetch)/i.test(message);\n}\n\n/**\n * Map the `loop` option to gifenc's `repeat` value:\n * `true` → 0 (loop forever), a number → that count, otherwise → -1 (play once,\n * hold the final frame — the default and the common editorial case).\n */\nexport function resolveRepeat(loop: boolean | number | undefined): number {\n if (loop === true) return 0;\n if (typeof loop === 'number') return loop;\n return -1;\n}\n\n/**\n * Apply the interpolated entrance state for a target at absolute time `nowMs`,\n * writing inline `clip-path`/`opacity` so it survives serialization.\n */\nexport function applyFrameState(\n target: AnimatedTarget,\n nowMs: number,\n easeKind: AnimationEase,\n phase?: MotionPhase,\n): void {\n const p = clamp01((nowMs - target.startMs) / target.durationMs);\n const progress = (fraction: number) =>\n phase?.spring\n ? sampleMotion(phase, clamp01(fraction) * phase.duration).position\n : ease(clamp01(fraction), easeKind);\n const eased = progress(p);\n const style = target.el.style;\n\n switch (target.kind) {\n case 'bar-vertical': {\n // oc-enter-bar: clip-path inset(100%→0 from top) + opacity (full by 75%).\n const inset = (1 - eased) * 100;\n style.clipPath = `inset(${inset}% 0 0 0)`;\n style.opacity = String(progress(p / 0.75));\n break;\n }\n case 'bar-horizontal': {\n // oc-enter-bar-h: clip-path inset(0 100%→0 from right) + opacity.\n const inset = (1 - eased) * 100;\n style.clipPath = `inset(0 ${inset}% 0 0)`;\n style.opacity = String(progress(p / 0.75));\n break;\n }\n case 'line-area': {\n // oc-enter-line: clip-path inset(0 100%→0 from right); opacity full by 15%.\n const inset = (1 - eased) * 100;\n style.clipPath = `inset(0 ${inset}% 0 0)`;\n style.opacity = String(progress(p / 0.15));\n break;\n }\n case 'fade': {\n // oc-enter-fade-only: opacity 0→1.\n style.opacity = String(eased);\n break;\n }\n default:\n target.kind satisfies never;\n }\n}\n\n/** Clear any inline entrance styles so the settled frame renders at rest. */\nfunction clearFrameState(target: AnimatedTarget): void {\n const style = target.el.style;\n style.clipPath = '';\n style.opacity = '';\n}\n\n// ---------------------------------------------------------------------------\n// Export\n// ---------------------------------------------------------------------------\n\n/**\n * Render a chart's entrance animation to an animated GIF Blob.\n *\n * @param svgElement - The settled, fully-rendered chart SVG (animation complete).\n * @param animation - The chart's resolved animation config (for exact timing).\n * When undefined, timing falls back to sensible defaults.\n * @param options - fps, dpi, loop, duration, font-embedding overrides.\n * @returns A Promise resolving to the GIF Blob.\n */\nexport async function exportGIF(\n svgElement: SVGElement,\n animation: ResolvedAnimation | undefined,\n options?: GIFExportOptions,\n): Promise<Blob> {\n let gifenc: typeof import('gifenc');\n try {\n gifenc = await import('gifenc');\n } catch (err) {\n // Only a genuine \"module not found\" means the optional peer is absent. Any\n // other failure (a real bug in gifenc's module eval, a corrupt install) must\n // surface with its context, not the misleading install hint.\n if (isModuleNotFound(err)) {\n throw new Error(\n \"GIF export requires the optional 'gifenc' peer dependency. Install it: npm install gifenc\",\n );\n }\n throw new Error('GIF export failed to load the gifenc encoder', { cause: err });\n }\n const { GIFEncoder, quantize, applyPalette } = gifenc;\n\n const fps = options?.fps ?? 25;\n const dpi = options?.dpi ?? 2;\n const shouldEmbed = options?.embedFonts ?? true;\n const { width, height } = getSVGDimensions(svgElement);\n if (!width || !height) {\n throw new Error(`SVG has zero dimensions (width=${width}, height=${height})`);\n }\n\n // Resolve timing from the config (exact) with defaults as a fallback.\n const enter = animation?.enter;\n const enterDurationMs = enter?.duration ?? 600;\n const staggerMs = enter?.staggerDelay ?? 0;\n const easeKind: AnimationEase = enter?.ease ?? 'smooth';\n\n // Build one font-embedded clone that represents the FINAL frame; every frame\n // derives from it, so fonts are embedded exactly once.\n const clone = svgElement.cloneNode(true) as SVGElement;\n // Inline the theme style block so class-based chrome fills survive the detach\n // from the page stylesheet (metrics, eyebrow dot, legend). No-op when undefined.\n injectThemeStyleBlock(clone, options?.theme);\n if (shouldEmbed) {\n await embedFonts(clone);\n }\n const targets = collectTargets(clone, enterDurationMs, staggerMs);\n\n // Total capture window: explicit override, else the animation total. Mirrors\n // computeAnimationDuration (animation.ts): the window must cover the last\n // mark's stagger + its own duration AND the annotation reveal, which animates\n // at enterDuration + annotationDelay. Without the annotationDelay term, charts\n // with annotations get cut off before the annotations finish fading in.\n const annotationDelay = animation?.annotationDelay ?? 0;\n const lastMarkEnd = targets.reduce(\n (m, t) => Math.max(m, t.startMs + t.durationMs),\n enterDurationMs,\n );\n const lastEnd = Math.max(lastMarkEnd, enterDurationMs + annotationDelay);\n const totalMs = options?.durationMs ?? lastEnd + 300;\n const frameDelay = Math.round(1000 / fps);\n const totalFrames = Math.max(1, Math.round((totalMs / 1000) * fps));\n\n // Loop → gifenc repeat: play-once (-1), forever (0), or explicit count.\n const repeat = resolveRepeat(options?.loop);\n\n // GIF can't carry partial alpha, so fill an opaque background before drawing\n // each frame (else a transparent chart composites onto black). Runs before\n // ctx.scale, so paint the raw device-pixel canvas size.\n // The theme background is the fallback: canvas mark mode suppresses the SVG\n // background rect, so there's nothing in the markup to read it from.\n const bgColor =\n options?.backgroundColor ??\n getSVGBackgroundColor(svgElement, options?.theme?.colors.background);\n const fillBackground = (ctx: CanvasRenderingContext2D, cv: HTMLCanvasElement): void => {\n ctx.fillStyle = bgColor;\n ctx.fillRect(0, 0, cv.width, cv.height);\n };\n\n const gif = GIFEncoder();\n\n // Derive ONE global palette from the settled frame (most complete colors)\n // and reuse it for every frame, so colors stay stable and the file stays\n // small. gifenc writes the global color table from the palette on the first\n // frame; later frames reuse it.\n let globalPalette: number[][] = [];\n await seedPalette(clone, targets, width, height, dpi, fillBackground, (data) => {\n globalPalette = quantize(data, 256);\n });\n\n let frameWritten = 0;\n const writeFrame = async (nowMs: number | null): Promise<void> => {\n if (nowMs === null) {\n for (const t of targets) clearFrameState(t);\n } else {\n for (const t of targets) applyFrameState(t, nowMs, easeKind, enter || undefined);\n }\n const svgString = ensureSVGDimensions(exportSVG(clone), width, height);\n const canvas = await rasterizeSVGToCanvas(svgString, width, height, dpi, fillBackground);\n const index = applyPalette(readCanvasSRGB(canvas), globalPalette);\n // `repeat` is only meaningful on the first frame (it writes the loop\n // extension); passing it later is ignored by gifenc.\n gif.writeFrame(index, canvas.width, canvas.height, {\n palette: globalPalette,\n delay: frameDelay,\n ...(frameWritten === 0 ? { repeat } : {}),\n });\n frameWritten++;\n };\n\n for (let i = 0; i < totalFrames; i++) {\n await writeFrame((i / fps) * 1000);\n }\n // Final settled frame the GIF holds on.\n await writeFrame(null);\n\n gif.finish();\n // gifenc types bytes() as Uint8Array<ArrayBufferLike>; BlobPart wants a view\n // over a plain ArrayBuffer. The runtime value is a valid BufferSource, so the\n // cast is safe — it only bridges the ArrayBufferLike/ArrayBuffer lib mismatch.\n return new Blob([gif.bytes() as BlobPart], { type: 'image/gif' });\n}\n\n/**\n * Render the settled clone once (no per-frame state) to derive the palette\n * source, without writing a frame. Restores frame state afterward.\n */\nasync function seedPalette(\n clone: SVGElement,\n targets: AnimatedTarget[],\n width: number,\n height: number,\n dpi: number,\n prepare: (ctx: CanvasRenderingContext2D, cv: HTMLCanvasElement) => void,\n use: (data: Uint8ClampedArray) => void,\n): Promise<void> {\n for (const t of targets) clearFrameState(t);\n const svgString = ensureSVGDimensions(exportSVG(clone), width, height);\n const canvas = await rasterizeSVGToCanvas(svgString, width, height, dpi, prepare);\n use(readCanvasSRGB(canvas));\n}\n","/**\n * Shared gifenc frame-encoding primitives.\n *\n * Both GIF exporters (`export-gif.ts`, entrance animation; `export-sequence.ts`,\n * spec-swap keyframes) need the same low-level steps: read a canvas back in\n * sRGB (the export canvas may be display-p3, but gifenc's quantizer assumes sRGB\n * bytes), quantize a shared palette, and write indexed frames. They differ only\n * in how they PRODUCE canvases — synthesized per time-step vs. one per spec — so\n * that stays in each caller; only these primitives are shared, which keeps the\n * sRGB-readback subtlety in exactly one place.\n */\n\n/**\n * Read a canvas's pixels back in sRGB. The export canvas may be display-p3 (so\n * PNG/JPG can embed a wide-gamut profile), but GIF is sRGB-only and gifenc's\n * quantizer assumes sRGB bytes — feeding it P3-encoded data would shift and\n * desaturate the GIF. The browser converts P3→sRGB on readback.\n */\nexport function readCanvasSRGB(canvas: HTMLCanvasElement): Uint8ClampedArray {\n const ctx = canvas.getContext('2d');\n if (!ctx) throw new Error('Canvas 2D context not available');\n return ctx.getImageData(0, 0, canvas.width, canvas.height, {\n colorSpace: 'srgb',\n }).data;\n}\n\n/** Quantize a 256-color palette from a canvas's sRGB pixels. */\nexport function paletteFromCanvas(\n canvas: HTMLCanvasElement,\n quantize: (data: Uint8ClampedArray, maxColors: number) => number[][],\n): number[][] {\n return quantize(readCanvasSRGB(canvas), 256);\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA;AAAA,EAKE;AAAA,OACK;;;ACTA,SAAS,eAAe,QAA8C;AAC3E,QAAM,MAAM,OAAO,WAAW,IAAI;AAClC,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,iCAAiC;AAC3D,SAAO,IAAI,aAAa,GAAG,GAAG,OAAO,OAAO,OAAO,QAAQ;AAAA,IACzD,YAAY;AAAA,EACd,CAAC,EAAE;AACL;AAGO,SAAS,kBACd,QACA,UACY;AACZ,SAAO,SAAS,eAAe,MAAM,GAAG,GAAG;AAC7C;;;ADiEO,IAAM,sBAAyC;AAAA,EACpD;AAAA,EAAG;AAAA,EAAO;AAAA,EAAO;AAAA,EAAM;AAAA,EAAO;AAAA,EAAM;AAAA,EAAO;AAAA,EAAO;AAAA,EAAO;AAAA,EAAO;AAAA,EAAO;AAAA,EAAO;AAAA,EAAO;AACvF;AAGO,SAAS,kBAAkB,SAA4B,GAAmB;AAC/E,MAAI,KAAK,EAAG,QAAO,QAAQ,CAAC;AAC5B,MAAI,KAAK,EAAG,QAAO,QAAQ,QAAQ,SAAS,CAAC;AAC7C,QAAM,SAAS,KAAK,QAAQ,SAAS;AACrC,QAAM,IAAI,KAAK,MAAM,MAAM;AAC3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