@opendata-ai/openchart-vanilla 9.0.0-rc.2 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +10 -0
  2. package/dist/{chunk-RY5JEGFM.js → chunk-42WVDS3V.js} +161 -26
  3. package/dist/chunk-42WVDS3V.js.map +1 -0
  4. package/dist/{chunk-46E3QB6O.js → chunk-6GRMMSQA.js} +2 -2
  5. package/dist/{chunk-A5C4VCUO.js → chunk-7XFFPRQ7.js} +13 -4
  6. package/dist/chunk-7XFFPRQ7.js.map +1 -0
  7. package/dist/chunk-E3ETKTJQ.js +130 -0
  8. package/dist/chunk-E3ETKTJQ.js.map +1 -0
  9. package/dist/{chunk-5ZLSMZRM.js → chunk-HQ5GADZ4.js} +9 -8
  10. package/dist/{chunk-5ZLSMZRM.js.map → chunk-HQ5GADZ4.js.map} +1 -1
  11. package/dist/{chunk-5OQZRGUL.js → chunk-NGNHQOXO.js} +1064 -971
  12. package/dist/chunk-NGNHQOXO.js.map +1 -0
  13. package/dist/{chunk-RBXIZJPE.js → chunk-OEJHSKFZ.js} +2 -2
  14. package/dist/{chunk-CMIJA63X.js → chunk-RWP23N4D.js} +3 -3
  15. package/dist/chunk-SKQAAHHR.js +533 -0
  16. package/dist/chunk-SKQAAHHR.js.map +1 -0
  17. package/dist/{chunk-NLKQ5AOA.js → chunk-XR4B3SPC.js} +70 -30
  18. package/dist/chunk-XR4B3SPC.js.map +1 -0
  19. package/dist/export-gif.js +4 -4
  20. package/dist/graph-3d/index.js +4 -4
  21. package/dist/index.d.ts +41 -51
  22. package/dist/index.js +85 -216
  23. package/dist/index.js.map +1 -1
  24. package/dist/static.d.ts +10 -21
  25. package/dist/static.js +417 -118
  26. package/dist/static.js.map +1 -1
  27. package/dist/story/index.js +7 -7
  28. package/dist/styles.css.map +1 -1
  29. package/package.json +4 -7
  30. package/dist/chunk-5OQZRGUL.js.map +0 -1
  31. package/dist/chunk-A5C4VCUO.js.map +0 -1
  32. package/dist/chunk-FFP5GXIP.js +0 -45
  33. package/dist/chunk-FFP5GXIP.js.map +0 -1
  34. package/dist/chunk-LDSPJFOU.js +0 -297
  35. package/dist/chunk-LDSPJFOU.js.map +0 -1
  36. package/dist/chunk-NLKQ5AOA.js.map +0 -1
  37. package/dist/chunk-RY5JEGFM.js.map +0 -1
  38. /package/dist/{chunk-46E3QB6O.js.map → chunk-6GRMMSQA.js.map} +0 -0
  39. /package/dist/{chunk-RBXIZJPE.js.map → chunk-OEJHSKFZ.js.map} +0 -0
  40. /package/dist/{chunk-CMIJA63X.js.map → chunk-RWP23N4D.js.map} +0 -0
package/dist/static.d.ts CHANGED
@@ -1,33 +1,22 @@
1
- import { ThemeConfig, DarkMode, ChartSpec, LayerSpec, TileMapSpec, GeoMapSpec } from '@opendata-ai/openchart-core';
1
+ import { ThemeConfig, DarkMode, CompileOptions, ChartSpec, LayerSpec, TileMapSpec, GeoMapSpec, BarListSpec } from '@opendata-ai/openchart-core';
2
2
 
3
3
  interface StaticRenderOptions {
4
- /** Stable XML-safe prefix. Use distinct prefixes for figures sharing one document. */
4
+ /** Stable XML-safe prefix, unique for figures sharing one document. Defaults to `ocs-<hash of spec and options>`. */
5
5
  idPrefix?: string;
6
6
  width?: number;
7
7
  height?: number;
8
8
  theme?: ThemeConfig;
9
- /**
10
- * Dark mode setting. In static rendering `'auto'` resolves to light mode
11
- * since there is no `matchMedia` to query. Use `'force'` for dark output.
12
- */
9
+ /** `auto` resolves to light without a browser. */
13
10
  darkMode?: DarkMode;
14
- /** Rendering backend for point marks; see `MountOptions.renderer`. */
15
11
  renderer?: 'auto' | 'svg' | 'canvas';
16
12
  watermark?: boolean;
13
+ measureText?: CompileOptions['measureText'];
14
+ /** Geometry decimal places; null preserves raw doubles. Default 3. */
15
+ precision?: number | null;
17
16
  }
18
- /**
19
- * Render a chart spec to a standalone SVG string without a browser DOM.
20
- *
21
- * Requires `happy-dom` as a peer dependency (`bun add happy-dom`).
22
- *
23
- * Not safe for concurrent invocation: the render pipeline relies on a global
24
- * SVG ID counter and a temporary global `document` swap, both of which are
25
- * single-threaded. In a server handling parallel requests, serialize calls
26
- * through a queue or mutex.
27
- *
28
- * The entire render pipeline is synchronous; the global swap is safe as long
29
- * as no code schedules microtasks that outlive the call.
30
- */
31
- declare function renderStaticSVG(spec: ChartSpec | LayerSpec | TileMapSpec | GeoMapSpec, options?: StaticRenderOptions): string;
17
+ type StaticSpec = ChartSpec | LayerSpec | TileMapSpec | GeoMapSpec | BarListSpec;
18
+
19
+ /** Render standalone SVG using a per-call element tree and id scope. */
20
+ declare function renderStaticSVG(spec: StaticSpec, options?: StaticRenderOptions): string;
32
21
 
33
22
  export { type StaticRenderOptions, renderStaticSVG };
package/dist/static.js CHANGED
@@ -1,155 +1,454 @@
1
1
  import {
2
+ renderBarListSVG,
2
3
  renderTileMapSVG
3
- } from "./chunk-LDSPJFOU.js";
4
+ } from "./chunk-SKQAAHHR.js";
4
5
  import {
5
6
  applyMapCamera,
6
7
  cameraForTarget,
7
- captureSvgIdState,
8
8
  renderChartSVG,
9
- renderMapSVG,
10
- resetSvgIdCounter,
11
- restoreSvgIdState
12
- } from "./chunk-5OQZRGUL.js";
9
+ renderMapSVG
10
+ } from "./chunk-NGNHQOXO.js";
13
11
  import {
14
12
  buildThemeStyleBlock
15
- } from "./chunk-A5C4VCUO.js";
16
- import "./chunk-NLKQ5AOA.js";
13
+ } from "./chunk-7XFFPRQ7.js";
17
14
  import {
18
- SVG_NS
19
- } from "./chunk-FFP5GXIP.js";
15
+ createIdScope,
16
+ createRenderContext
17
+ } from "./chunk-XR4B3SPC.js";
18
+ import {
19
+ SVG_NS,
20
+ XLINK_NS,
21
+ applyRoleStyle
22
+ } from "./chunk-E3ETKTJQ.js";
20
23
 
21
- // src/static.ts
22
- import { createRequire } from "module";
23
- import { isGeoMapSpec, isLayerSpec, isTileMapSpec } from "@opendata-ai/openchart-core";
24
+ // src/static-render.ts
25
+ import {
26
+ isBarListSpec,
27
+ isGeoMapSpec,
28
+ isLayerSpec,
29
+ isTileMapSpec
30
+ } from "@opendata-ai/openchart-core";
24
31
  import {
32
+ compileBarList,
25
33
  compileChart,
26
34
  compileGeoMap,
27
35
  compileLayer,
28
36
  compileTileMap
29
37
  } from "@opendata-ai/openchart-engine";
30
- var esmRequire = createRequire(import.meta.url);
31
- var cachedWindow;
32
- function getHappyDomWindow() {
33
- if (cachedWindow) return cachedWindow;
34
- try {
35
- ({ Window: cachedWindow } = esmRequire("happy-dom"));
36
- } catch {
37
- throw new Error(
38
- "renderStaticSVG requires 'happy-dom' as a peer dependency. Install it with: npm add happy-dom"
38
+
39
+ // src/static-dom.ts
40
+ var StaticText = class {
41
+ constructor(data) {
42
+ this.data = data;
43
+ }
44
+ nodeType = 3;
45
+ parentNode = null;
46
+ get textContent() {
47
+ return this.data;
48
+ }
49
+ set textContent(value) {
50
+ this.data = value;
51
+ }
52
+ remove() {
53
+ this.parentNode?.removeChild(this);
54
+ }
55
+ };
56
+ function cssName(name) {
57
+ return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
58
+ }
59
+ function createStyle(element) {
60
+ const declarations = () => new Map(
61
+ (element.getAttribute("style") ?? "").split(";").flatMap((part) => {
62
+ const colon = part.indexOf(":");
63
+ return colon < 0 ? [] : [[part.slice(0, colon).trim(), part.slice(colon + 1).trim()]];
64
+ })
65
+ );
66
+ const write = (values) => {
67
+ if (values.size)
68
+ element.setAttribute(
69
+ "style",
70
+ [...values].map(([name, value]) => `${name}: ${value};`).join(" ")
71
+ );
72
+ else element.removeAttribute("style");
73
+ };
74
+ const api = {
75
+ setProperty(name, value, priority = "") {
76
+ const values = declarations();
77
+ if (value === "") values.delete(name);
78
+ else values.set(name, `${String(value)}${priority ? " !important" : ""}`);
79
+ write(values);
80
+ },
81
+ removeProperty(name) {
82
+ const values = declarations();
83
+ const previous = values.get(name) ?? "";
84
+ values.delete(name);
85
+ write(values);
86
+ return previous;
87
+ },
88
+ getPropertyValue(name) {
89
+ return (declarations().get(name) ?? "").replace(/\s*!important\s*$/, "");
90
+ },
91
+ getPropertyPriority(name) {
92
+ return /!important\s*$/.test(declarations().get(name) ?? "") ? "important" : "";
93
+ },
94
+ get cssText() {
95
+ return element.getAttribute("style") ?? "";
96
+ },
97
+ set cssText(value) {
98
+ element.setAttribute("style", value);
99
+ write(declarations());
100
+ }
101
+ };
102
+ return new Proxy(api, {
103
+ get(target, key) {
104
+ return key in target ? Reflect.get(target, key) : typeof key === "string" ? target.getPropertyValue(cssName(key)) : void 0;
105
+ },
106
+ set(target, key, value) {
107
+ if (key === "cssText") target.cssText = String(value);
108
+ else if (typeof key === "string") target.setProperty(cssName(key), String(value));
109
+ return true;
110
+ }
111
+ });
112
+ }
113
+ var StaticElement = class _StaticElement {
114
+ constructor(tagName, namespaceURI = SVG_NS) {
115
+ this.tagName = tagName;
116
+ this.namespaceURI = namespaceURI;
117
+ }
118
+ nodeType = 1;
119
+ attributes = /* @__PURE__ */ new Map();
120
+ childNodes = [];
121
+ parentNode = null;
122
+ style = createStyle(this);
123
+ classList = {
124
+ add: (...tokens) => {
125
+ this.setAttribute("class", [.../* @__PURE__ */ new Set([...this.classes(), ...tokens])].join(" "));
126
+ },
127
+ remove: (...tokens) => {
128
+ this.setAttribute(
129
+ "class",
130
+ this.classes().filter((token) => !tokens.includes(token)).join(" ")
131
+ );
132
+ },
133
+ contains: (token) => this.classes().includes(token),
134
+ toggle: (token, force) => {
135
+ const include = force ?? !this.classList.contains(token);
136
+ if (include) this.classList.add(token);
137
+ else this.classList.remove(token);
138
+ return include;
139
+ },
140
+ [Symbol.iterator]: () => this.classes()[Symbol.iterator]()
141
+ };
142
+ classes() {
143
+ return (this.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
144
+ }
145
+ get id() {
146
+ return this.getAttribute("id") ?? "";
147
+ }
148
+ set id(value) {
149
+ this.setAttribute("id", value);
150
+ }
151
+ get children() {
152
+ return this.childNodes.filter((node) => node instanceof _StaticElement);
153
+ }
154
+ get firstElementChild() {
155
+ return this.children[0] ?? null;
156
+ }
157
+ get firstChild() {
158
+ return this.childNodes[0] ?? null;
159
+ }
160
+ get nextSibling() {
161
+ if (!this.parentNode) return null;
162
+ return this.parentNode.childNodes[this.parentNode.childNodes.indexOf(this) + 1] ?? null;
163
+ }
164
+ get textContent() {
165
+ return this.childNodes.map((node) => node.textContent).join("");
166
+ }
167
+ set textContent(value) {
168
+ for (const child of this.childNodes) child.parentNode = null;
169
+ this.childNodes.length = 0;
170
+ if (value) this.appendChild(new StaticText(String(value)));
171
+ }
172
+ setAttribute(name, value) {
173
+ this.attributes.set(name, String(value));
174
+ }
175
+ setAttributeNS(_namespace, name, value) {
176
+ this.setAttribute(name, value);
177
+ }
178
+ getAttribute(name) {
179
+ return this.attributes.get(name) ?? null;
180
+ }
181
+ hasAttribute(name) {
182
+ return this.attributes.has(name);
183
+ }
184
+ removeAttribute(name) {
185
+ this.attributes.delete(name);
186
+ }
187
+ appendChild(child) {
188
+ return this.insertBefore(child, null);
189
+ }
190
+ append(...nodes) {
191
+ for (const node of nodes)
192
+ this.appendChild(typeof node === "string" ? new StaticText(node) : node);
193
+ }
194
+ insertBefore(child, before) {
195
+ if (child === before) return child;
196
+ child.parentNode?.removeChild(child);
197
+ const index = before === null ? this.childNodes.length : this.childNodes.indexOf(before);
198
+ if (index < 0) throw new Error("insertBefore reference is not a child");
199
+ this.childNodes.splice(index, 0, child);
200
+ child.parentNode = this;
201
+ return child;
202
+ }
203
+ removeChild(child) {
204
+ const index = this.childNodes.indexOf(child);
205
+ if (index < 0) throw new Error("removeChild target is not a child");
206
+ this.childNodes.splice(index, 1);
207
+ child.parentNode = null;
208
+ return child;
209
+ }
210
+ remove() {
211
+ this.parentNode?.removeChild(this);
212
+ }
213
+ insertAdjacentElement(position, element) {
214
+ if (position === "afterend" && this.parentNode)
215
+ return this.parentNode.insertBefore(element, this.nextSibling);
216
+ if (position === "beforebegin" && this.parentNode)
217
+ return this.parentNode.insertBefore(element, this);
218
+ if (position === "afterbegin") return this.insertBefore(element, this.firstChild);
219
+ if (position === "beforeend") return this.appendChild(element);
220
+ return null;
221
+ }
222
+ matches(selector) {
223
+ return selector.split(",").some(
224
+ (part) => matchesChain(
225
+ this,
226
+ part.replace(/\s*>\s*(?![^[]*\])/g, " > ").trim().split(/\s+(?![^[]*\])/)
227
+ )
39
228
  );
40
229
  }
41
- return cachedWindow;
230
+ closest(selector) {
231
+ for (let node = this; node; node = node.parentNode)
232
+ if (node.matches(selector)) return node;
233
+ return null;
234
+ }
235
+ querySelectorAll(selector) {
236
+ const found = [];
237
+ const visit = (node) => {
238
+ for (const child of node.children) {
239
+ if (child.matches(selector)) found.push(child);
240
+ visit(child);
241
+ }
242
+ };
243
+ visit(this);
244
+ return found;
245
+ }
246
+ querySelector(selector) {
247
+ return this.querySelectorAll(selector)[0] ?? null;
248
+ }
249
+ };
250
+ function matchesSimple(element, selector) {
251
+ const tag = /^[\w*:-]+/.exec(selector)?.[0];
252
+ if (tag && tag !== "*" && element.tagName.toLowerCase() !== tag.toLowerCase()) return false;
253
+ for (const match of selector.matchAll(
254
+ /([.#])([\w-]+)|\[([^\]=\s]+)(?:\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\]]+)))?\]/g
255
+ )) {
256
+ if (match[1] === "." && !element.classList.contains(match[2])) return false;
257
+ if (match[1] === "#" && element.id !== match[2]) return false;
258
+ if (match[3]) {
259
+ if (!element.hasAttribute(match[3])) return false;
260
+ const value = match[4] ?? match[5] ?? match[6];
261
+ if (value !== void 0 && element.getAttribute(match[3]) !== value) return false;
262
+ }
263
+ }
264
+ return true;
42
265
  }
43
- var rendering = false;
44
- function resolveStaticDarkMode(mode) {
45
- if (mode === "force") return true;
266
+ function matchesChain(element, parts) {
267
+ const last = parts[parts.length - 1];
268
+ if (!last || last === ">" || /^[+~]$/.test(last))
269
+ throw new Error(`Unsupported static selector: ${parts.join(" ")}`);
270
+ if (/[+~]/.test(last.replace(/\[[^\]]*\]/g, "")))
271
+ throw new Error(`Unsupported static selector combinator in ${last}`);
272
+ if (!matchesSimple(element, last)) return false;
273
+ if (parts.length === 1) return true;
274
+ if (parts[parts.length - 2] === ">")
275
+ return !!element.parentNode && matchesChain(element.parentNode, parts.slice(0, -2));
276
+ for (let parent = element.parentNode; parent; parent = parent.parentNode)
277
+ if (matchesChain(parent, parts.slice(0, -1))) return true;
46
278
  return false;
47
279
  }
48
- function stripInteractiveElements(svg) {
49
- const selectors = ["[data-voronoi-overlay]", "[data-crosshair]", "[data-snap-dots]"];
50
- for (const selector of selectors) {
51
- const els = svg.querySelectorAll(selector);
52
- for (const el of els) {
53
- el.parentNode?.removeChild(el);
280
+ var staticFactory = {
281
+ svg: (tag) => new StaticElement(tag),
282
+ html: (tag) => new StaticElement(tag, "http://www.w3.org/1999/xhtml"),
283
+ text: (data) => new StaticText(data)
284
+ };
285
+ var GEOMETRY_ATTRIBUTES = new Set(
286
+ "x y x1 y1 x2 y2 width height r rx ry cx cy dx dy d points transform viewBox".split(" ")
287
+ );
288
+ var NUMBER_TOKEN = /[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/g;
289
+ var UNIT_SUFFIX = /^(?:%|em|ex|ch|rem|px|pt|pc|cm|mm|in|vw|vh|vmin|vmax)/;
290
+ function roundGeometryValue(value, precision) {
291
+ if (precision === null) return value;
292
+ let previousEnd = -1;
293
+ return value.replace(NUMBER_TOKEN, (token, offset) => {
294
+ const separator = offset === previousEnd ? " " : "";
295
+ previousEnd = offset + token.length;
296
+ if (UNIT_SUFFIX.test(value.slice(previousEnd))) return separator + token;
297
+ return separator + String(Number(Number(token).toFixed(precision)));
298
+ });
299
+ }
300
+ function escapeText(value) {
301
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
302
+ }
303
+ function escapeAttribute(value) {
304
+ return escapeText(value).replace(/"/g, "&quot;").replace(/\t/g, "&#9;").replace(/\n/g, "&#10;").replace(/\r/g, "&#13;");
305
+ }
306
+ function serialize(node, options = {}) {
307
+ const precision = options.precision === void 0 ? 3 : options.precision;
308
+ if (precision !== null && (!Number.isInteger(precision) || precision < 0 || precision > 15))
309
+ throw new Error("precision must be an integer between 0 and 15, or null.");
310
+ const hasXlink = (element) => [...element.attributes.keys()].some((name) => name.startsWith("xlink:")) || element.children.some(hasXlink);
311
+ const write = (current, root = false, inheritedNamespace = SVG_NS) => {
312
+ if (current instanceof StaticText) return escapeText(current.data);
313
+ const attributes = new Map(current.attributes);
314
+ let head = `<${current.tagName}`;
315
+ if (root) {
316
+ head += ` xmlns="${escapeAttribute(attributes.get("xmlns") ?? current.namespaceURI)}"`;
317
+ attributes.delete("xmlns");
318
+ if (attributes.has("xmlns:xlink") || hasXlink(current)) {
319
+ head += ` xmlns:xlink="${XLINK_NS}"`;
320
+ attributes.delete("xmlns:xlink");
321
+ }
54
322
  }
55
- }
323
+ if (!root && current.namespaceURI !== inheritedNamespace) {
324
+ head += ` xmlns="${escapeAttribute(current.namespaceURI)}"`;
325
+ attributes.delete("xmlns");
326
+ }
327
+ for (const [name, original] of attributes) {
328
+ const value = GEOMETRY_ATTRIBUTES.has(name) ? roundGeometryValue(original, precision) : original;
329
+ head += ` ${name}="${escapeAttribute(value)}"`;
330
+ }
331
+ return current.childNodes.length ? `${head}>${current.childNodes.map((child) => write(child, false, current.namespaceURI)).join("")}</${current.tagName}>` : `${head}/>`;
332
+ };
333
+ return write(node, true);
56
334
  }
57
- function renderStaticSVG(spec, options) {
58
- if (options?.idPrefix !== void 0 && !/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(options.idPrefix))
335
+
336
+ // src/static-render.ts
337
+ var XMLNS_NS = "http://www.w3.org/2000/xmlns/";
338
+ function renderStaticParts(spec, options = {}, factory = staticFactory) {
339
+ if (options.idPrefix !== void 0 && !/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(options.idPrefix))
59
340
  throw new Error(
60
341
  "idPrefix must start with a letter or underscore and contain only letters, digits, underscores, periods or hyphens."
61
342
  );
62
- if (rendering) {
63
- throw new Error("renderStaticSVG is not reentrant \u2014 serialize calls through a queue or mutex");
64
- }
65
- rendering = true;
66
- const Window = getHappyDomWindow();
67
- const win = new Window({ url: "about:blank" });
68
- const svgIdState = captureSvgIdState();
69
- const prevDocument = globalThis.document;
70
- const prevWindow = globalThis.window;
71
- try {
72
- globalThis.document = win.document;
73
- globalThis.window = win;
74
- resetSvgIdCounter(options?.idPrefix);
75
- const width = options?.width ?? 640;
76
- const height = options?.height ?? 420;
77
- const darkMode = resolveStaticDarkMode(options?.darkMode);
78
- const compileOpts = {
79
- width,
80
- height,
81
- theme: options?.theme,
82
- darkMode,
83
- renderer: options?.renderer,
84
- watermark: options?.watermark
85
- };
86
- let svg;
87
- let themeForStyle;
88
- if (isGeoMapSpec(spec)) {
89
- const mapLayout = compileGeoMap(spec, compileOpts);
90
- svg = renderMapSVG(mapLayout, { animate: false });
91
- if (!mapLayout.views)
92
- applyMapCamera(svg, cameraForTarget(mapLayout, mapLayout.focus?.target), mapLayout);
93
- themeForStyle = mapLayout.theme;
94
- } else if (isTileMapSpec(spec)) {
95
- const tileMapLayout = compileTileMap(spec, compileOpts);
96
- svg = renderTileMapSVG(tileMapLayout, { animate: false });
97
- themeForStyle = tileMapLayout.theme;
98
- } else {
99
- let layout;
100
- if (isLayerSpec(spec)) {
101
- layout = compileLayer(spec, compileOpts);
102
- } else {
103
- layout = compileChart(spec, compileOpts);
104
- }
105
- const container = win.document.createElement("div");
106
- Object.defineProperty(container, "getBoundingClientRect", {
107
- value: () => ({
108
- width,
109
- height,
110
- top: 0,
111
- left: 0,
112
- right: width,
113
- bottom: height,
114
- x: 0,
115
- y: 0,
116
- toJSON: () => ({})
117
- })
118
- });
119
- svg = renderChartSVG(layout, container, {
120
- animate: false,
121
- crosshair: false
122
- });
123
- stripInteractiveElements(svg);
124
- themeForStyle = layout.theme;
343
+ const precision = options.precision === void 0 ? 3 : options.precision;
344
+ if (precision !== null && (!Number.isInteger(precision) || precision < 0 || precision > 15))
345
+ throw new Error("precision must be an integer between 0 and 15, or null.");
346
+ const type = spec.type;
347
+ if (type && !["chart", "layer", "barlist", "tilemap", "map", "geomap"].includes(type))
348
+ throw new Error(
349
+ `renderStaticSVG does not render "${type}"; supported: chart, layer, barlist, tilemap, geomap`
350
+ );
351
+ const ctx = createRenderContext({
352
+ factory,
353
+ ids: createIdScope(options.idPrefix ?? defaultIdPrefix(spec, options)),
354
+ interactive: false,
355
+ precision
356
+ });
357
+ const compileOpts = {
358
+ width: options.width ?? 640,
359
+ height: options.height ?? 420,
360
+ theme: options.theme,
361
+ darkMode: options.darkMode === "force",
362
+ renderer: options.renderer,
363
+ watermark: options.watermark,
364
+ measureText: options.measureText,
365
+ onWarn: () => {
125
366
  }
126
- const doc = win.document;
367
+ };
368
+ let svg;
369
+ let theme;
370
+ const map = isGeoMapSpec(spec), tilemap = isTileMapSpec(spec);
371
+ if (map) {
372
+ const layout = compileGeoMap(spec, compileOpts);
373
+ svg = renderMapSVG(layout, { animate: false, context: ctx });
374
+ if (!layout.views) applyMapCamera(svg, cameraForTarget(layout, layout.focus?.target), layout);
375
+ theme = layout.theme;
376
+ } else if (tilemap) {
377
+ const layout = compileTileMap(spec, compileOpts);
378
+ svg = renderTileMapSVG(layout, { animate: false, context: ctx });
379
+ theme = layout.theme;
380
+ } else if (isBarListSpec(spec)) {
381
+ const layout = compileBarList(
382
+ { ...spec, height: options.height ?? spec.height ?? "auto" },
383
+ compileOpts
384
+ );
385
+ svg = renderBarListSVG(layout, { animate: false, context: ctx });
386
+ theme = layout.theme;
387
+ } else {
388
+ const layout = isLayerSpec(spec) ? compileLayer(spec, compileOpts) : compileChart(spec, compileOpts);
389
+ svg = renderChartSVG(layout, factory.html("div"), {
390
+ animate: false,
391
+ crosshair: false,
392
+ context: ctx
393
+ });
394
+ theme = layout.theme;
395
+ }
396
+ if ([svg, ...svg.querySelectorAll("*")].some((el) => el.hasAttribute("xlink:href"))) {
397
+ if (!svg.hasAttribute("xmlns")) svg.setAttributeNS(XMLNS_NS, "xmlns", SVG_NS);
398
+ svg.setAttributeNS(XMLNS_NS, "xmlns:xlink", XLINK_NS);
399
+ }
400
+ svg.setAttribute("data-theme", theme.isDark ? "dark" : "light");
401
+ if (options.idPrefix) svg.setAttribute("id", `${options.idPrefix}-oc-root`);
402
+ if (map || tilemap) {
127
403
  let defs = svg.querySelector("defs");
128
404
  if (!defs) {
129
- defs = doc.createElementNS(SVG_NS, "defs");
405
+ defs = factory.svg("defs");
130
406
  svg.insertBefore(defs, svg.firstChild);
131
407
  }
132
- const styleEl = doc.createElementNS(SVG_NS, "style");
133
- styleEl.textContent = buildThemeStyleBlock(themeForStyle);
134
- defs.insertBefore(styleEl, defs.firstChild);
135
- const serializer = new win.XMLSerializer();
136
- return serializer.serializeToString(svg);
137
- } finally {
138
- restoreSvgIdState(svgIdState);
139
- rendering = false;
140
- if (prevDocument !== void 0) {
141
- globalThis.document = prevDocument;
142
- } else {
143
- delete globalThis.document;
144
- }
145
- if (prevWindow !== void 0) {
146
- globalThis.window = prevWindow;
147
- } else {
148
- delete globalThis.window;
408
+ const style = factory.svg("style");
409
+ style.textContent = buildThemeStyleBlock(
410
+ theme,
411
+ options.idPrefix ? `${options.idPrefix}-oc-root` : void 0
412
+ );
413
+ defs.insertBefore(style, defs.firstChild);
414
+ } else inlineStaticStyles(svg, theme);
415
+ return { svg, serialize: () => serialize(svg, { precision }) };
416
+ }
417
+ function defaultIdPrefix(spec, options) {
418
+ const input = JSON.stringify([spec, { ...options, measureText: void 0 }]);
419
+ let hash = 2166136261;
420
+ for (let i = 0; i < input.length; i++) hash = Math.imul(hash ^ input.charCodeAt(i), 16777619);
421
+ return `ocs-${(hash >>> 0).toString(36)}`;
422
+ }
423
+ function inlineStaticStyles(svg, theme) {
424
+ const roleContext = { theme };
425
+ const roleAttributes = /* @__PURE__ */ new Map();
426
+ const applyRule = (el, role) => {
427
+ let names = roleAttributes.get(role);
428
+ if (!names) {
429
+ const probe = new StaticElement("g");
430
+ applyRoleStyle(roleContext, probe, role);
431
+ names = [...probe.attributes.keys()];
432
+ roleAttributes.set(role, names);
149
433
  }
150
- win.close();
434
+ for (const name of names)
435
+ if (name !== "style" && !el.style.getPropertyValue(name)) el.removeAttribute(name);
436
+ applyRoleStyle(roleContext, el, role);
437
+ };
438
+ svg.setAttribute("font-family", theme.fonts.family);
439
+ svg.style.setProperty("font-variant-numeric", "tabular-nums");
440
+ for (const el of [svg, ...svg.querySelectorAll("*")]) {
441
+ for (const role of (el.getAttribute("class") ?? "").split(/\s+/))
442
+ applyRule(el, role);
443
+ if (el.tagName.toLowerCase() === "text" && el.closest(".oc-legend"))
444
+ applyRule(el, "oc-legend-text");
151
445
  }
152
446
  }
447
+
448
+ // src/static.ts
449
+ function renderStaticSVG(spec, options) {
450
+ return renderStaticParts(spec, options).serialize();
451
+ }
153
452
  export {
154
453
  renderStaticSVG
155
454
  };