@opendata-ai/openchart-vanilla 8.0.0-rc.8 → 8.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 (147) hide show
  1. package/dist/{chunk-W34KN7FD.js → chunk-2NAQRP66.js} +2 -2
  2. package/dist/{chunk-UZ7J3NOF.js → chunk-6BUCYCLD.js} +7314 -5605
  3. package/dist/chunk-6BUCYCLD.js.map +1 -0
  4. package/dist/chunk-DCODCLWI.js +234 -0
  5. package/dist/chunk-DCODCLWI.js.map +1 -0
  6. package/dist/{chunk-5EOV5JQZ.js → chunk-EKAUQAAX.js} +50 -46
  7. package/dist/chunk-EKAUQAAX.js.map +1 -0
  8. package/dist/chunk-RM5XS6NR.js +113 -0
  9. package/dist/chunk-RM5XS6NR.js.map +1 -0
  10. package/dist/chunk-T32UHMZA.js +282 -0
  11. package/dist/chunk-T32UHMZA.js.map +1 -0
  12. package/dist/export-gif.d.ts +113 -0
  13. package/dist/export-gif.js +21 -0
  14. package/dist/export-gif.js.map +1 -0
  15. package/dist/index.d.ts +309 -27
  16. package/dist/index.js +2020 -836
  17. package/dist/index.js.map +1 -1
  18. package/dist/{mount-CUKQLeqD.d.ts → mount-CL-nA0f-.d.ts} +85 -2
  19. package/dist/simulation-worker.js +83 -2
  20. package/dist/static.d.ts +2 -0
  21. package/dist/static.js +8 -69
  22. package/dist/static.js.map +1 -1
  23. package/dist/story/index.d.ts +25 -9
  24. package/dist/story/index.js +9 -7
  25. package/dist/story/index.js.map +1 -1
  26. package/dist/styles.css +1 -1
  27. package/dist/styles.css.map +1 -1
  28. package/package.json +14 -6
  29. package/dist/chunk-5EOV5JQZ.js.map +0 -1
  30. package/dist/chunk-UZ7J3NOF.js.map +0 -1
  31. package/src/__test-fixtures__/dom.ts +0 -70
  32. package/src/__test-fixtures__/specs.ts +0 -214
  33. package/src/__tests__/animation.test.ts +0 -358
  34. package/src/__tests__/annotations-render.test.ts +0 -201
  35. package/src/__tests__/compound-labels.test.ts +0 -122
  36. package/src/__tests__/continuous-legend.test.ts +0 -91
  37. package/src/__tests__/crosshair.test.ts +0 -130
  38. package/src/__tests__/edit-events.test.ts +0 -950
  39. package/src/__tests__/events.test.ts +0 -387
  40. package/src/__tests__/export.test.ts +0 -241
  41. package/src/__tests__/font-race.test.ts +0 -199
  42. package/src/__tests__/gradient-ids.test.ts +0 -159
  43. package/src/__tests__/gradient-utils.test.ts +0 -125
  44. package/src/__tests__/known-bugs-render.test.ts +0 -183
  45. package/src/__tests__/map.test.ts +0 -636
  46. package/src/__tests__/mount.test.ts +0 -357
  47. package/src/__tests__/pattern-fills.test.ts +0 -105
  48. package/src/__tests__/resize-timing.test.ts +0 -218
  49. package/src/__tests__/sankey.test.ts +0 -133
  50. package/src/__tests__/selection-events.test.ts +0 -869
  51. package/src/__tests__/series-search.test.ts +0 -311
  52. package/src/__tests__/static.test.ts +0 -141
  53. package/src/__tests__/svg-renderer.test.ts +0 -895
  54. package/src/__tests__/table-keyboard.test.ts +0 -361
  55. package/src/__tests__/table-mount.test.ts +0 -639
  56. package/src/__tests__/tilemap.test.ts +0 -158
  57. package/src/__tests__/tooltip.test.ts +0 -337
  58. package/src/__tests__/transition.test.ts +0 -1792
  59. package/src/__tests__/update-scrolly-matrix.test.ts +0 -563
  60. package/src/__tests__/you-draw-it.test.ts +0 -273
  61. package/src/animation-vars.ts +0 -42
  62. package/src/animation.ts +0 -76
  63. package/src/barlist-mount.ts +0 -383
  64. package/src/barlist-renderer.ts +0 -267
  65. package/src/dom-helpers.ts +0 -17
  66. package/src/export.ts +0 -482
  67. package/src/gradient-utils.ts +0 -138
  68. package/src/graph/__tests__/canvas-renderer.test.ts +0 -713
  69. package/src/graph/__tests__/graph-mount.test.ts +0 -213
  70. package/src/graph/__tests__/interaction.test.ts +0 -205
  71. package/src/graph/__tests__/keyboard.test.ts +0 -653
  72. package/src/graph/__tests__/search.test.ts +0 -88
  73. package/src/graph/__tests__/simulation.test.ts +0 -233
  74. package/src/graph/__tests__/spatial-index.test.ts +0 -142
  75. package/src/graph/__tests__/zoom.test.ts +0 -203
  76. package/src/graph/canvas-renderer.ts +0 -747
  77. package/src/graph/interaction.ts +0 -367
  78. package/src/graph/keyboard.ts +0 -208
  79. package/src/graph/search.ts +0 -50
  80. package/src/graph/simulation-worker-url.ts +0 -12
  81. package/src/graph/simulation-worker.ts +0 -278
  82. package/src/graph/simulation.ts +0 -422
  83. package/src/graph/spatial-index.ts +0 -121
  84. package/src/graph/types.ts +0 -47
  85. package/src/graph/worker-protocol.ts +0 -70
  86. package/src/graph/zoom.ts +0 -134
  87. package/src/graph-mount.ts +0 -888
  88. package/src/index.ts +0 -76
  89. package/src/interactions/chart-events.ts +0 -139
  90. package/src/interactions/crosshair.ts +0 -233
  91. package/src/interactions/drag-handler.ts +0 -175
  92. package/src/interactions/editing-drags.ts +0 -515
  93. package/src/interactions/index.ts +0 -25
  94. package/src/interactions/keyboard-nav.ts +0 -111
  95. package/src/interactions/legend-interaction.ts +0 -46
  96. package/src/interactions/selection.ts +0 -280
  97. package/src/interactions/tooltip-events.ts +0 -72
  98. package/src/map-camera.ts +0 -111
  99. package/src/map-mount.ts +0 -792
  100. package/src/map-renderer.ts +0 -460
  101. package/src/map-transition.ts +0 -99
  102. package/src/measure-text.ts +0 -134
  103. package/src/mount.ts +0 -1382
  104. package/src/pattern-utils.ts +0 -110
  105. package/src/renderers/annotations.ts +0 -388
  106. package/src/renderers/axes.ts +0 -351
  107. package/src/renderers/brand.ts +0 -87
  108. package/src/renderers/chrome.ts +0 -196
  109. package/src/renderers/endpoint-labels.ts +0 -150
  110. package/src/renderers/legend.ts +0 -311
  111. package/src/renderers/marks.ts +0 -561
  112. package/src/renderers/metrics.ts +0 -63
  113. package/src/renderers/svg-dom.ts +0 -40
  114. package/src/renderers/table-cells.ts +0 -446
  115. package/src/resize-observer.ts +0 -46
  116. package/src/sankey-mount.ts +0 -622
  117. package/src/sankey-renderer.ts +0 -614
  118. package/src/series-search.ts +0 -392
  119. package/src/static.ts +0 -251
  120. package/src/story/__tests__/camera-math.test.ts +0 -145
  121. package/src/story/__tests__/create-chart-story.test.ts +0 -317
  122. package/src/story/__tests__/progress-math.test.ts +0 -95
  123. package/src/story/__tests__/scroll-driver.test.ts +0 -130
  124. package/src/story/__tests__/tween.test.ts +0 -159
  125. package/src/story/camera-math.ts +0 -125
  126. package/src/story/create-chart-story.ts +0 -353
  127. package/src/story/crossfade.ts +0 -70
  128. package/src/story/index.ts +0 -39
  129. package/src/story/progress-math.ts +0 -85
  130. package/src/story/resolve-camera-target.ts +0 -119
  131. package/src/story/scroll-driver.ts +0 -206
  132. package/src/story/story-camera.ts +0 -49
  133. package/src/story/tween.ts +0 -112
  134. package/src/story/types.ts +0 -76
  135. package/src/svg-ids.ts +0 -23
  136. package/src/svg-renderer.ts +0 -383
  137. package/src/table-keyboard.ts +0 -266
  138. package/src/table-mount.ts +0 -567
  139. package/src/table-renderer.ts +0 -414
  140. package/src/text-edit-overlay.ts +0 -255
  141. package/src/theme-tokens.ts +0 -51
  142. package/src/tilemap-mount.ts +0 -511
  143. package/src/tilemap-renderer.ts +0 -396
  144. package/src/tooltip.ts +0 -177
  145. package/src/transition.ts +0 -2816
  146. package/src/you-draw-it.ts +0 -480
  147. /package/dist/{chunk-W34KN7FD.js.map → chunk-2NAQRP66.js.map} +0 -0
package/src/map-mount.ts DELETED
@@ -1,792 +0,0 @@
1
- /**
2
- * Map mount API: the main entry point for vanilla JS map usage.
3
- *
4
- * createMap() takes a container, MapSpec, and options, compiles the
5
- * map, renders it as SVG, sets up responsive resizing, tooltip interaction,
6
- * and returns a MapInstance with update/resize/export/destroy.
7
- */
8
-
9
- import type {
10
- CompileOptions,
11
- DarkMode,
12
- MapLayout,
13
- MapSpec,
14
- ThemeConfig,
15
- } from '@opendata-ai/openchart-core';
16
- import { compileMap } from '@opendata-ai/openchart-engine';
17
- import { cancelAnimations, setupAnimationCleanup } from './animation';
18
- import {
19
- exportJPG,
20
- exportPNG,
21
- exportSVG,
22
- exportSVGWithFonts,
23
- type JPGExportOptions,
24
- type SVGExportOptions,
25
- } from './export';
26
- import {
27
- applyMapCamera,
28
- cameraForTarget,
29
- FOCUS_DIM_OPACITY,
30
- focusTargetForFeatures,
31
- type MapCameraOptions,
32
- } from './map-camera';
33
- import { renderMapSVG } from './map-renderer';
34
- import { captureFeatureFills, runMapFillTransition } from './map-transition';
35
- import { createMeasureText, resolveFontFamily, scheduleFontReload } from './measure-text';
36
- import { observeResize } from './resize-observer';
37
- import type { Camera } from './story/camera-math';
38
- import { interpolateCamera } from './story/camera-math';
39
- import type { Tween } from './story/tween';
40
- import { createTween, easingFns, storyMotion } from './story/tween';
41
- import { createTooltipManager, type TooltipManager } from './tooltip';
42
-
43
- /**
44
- * A stable string for a resolved focus, used to detect focus changes between
45
- * `update()` calls. Includes the target rect (rounded) so a points focus
46
- * (which has empty ids) still re-fits when the fitted cluster moves; ids alone
47
- * would miss that. `null` focus -> null (no camera target).
48
- */
49
- function focusSignature(focus: MapLayout['focus']): string | null {
50
- if (!focus) return null;
51
- const t = focus.target;
52
- const ids = focus.ids.map(String).sort().join(',');
53
- return `${ids}|${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)},${Math.round(t.height)},${t.padding}`;
54
- }
55
-
56
- // ---------------------------------------------------------------------------
57
- // Types
58
- // ---------------------------------------------------------------------------
59
-
60
- export type MapMarkEvent = {
61
- kind: 'feature' | 'point';
62
- id: string | number;
63
- name?: string;
64
- data: Record<string, unknown> | null;
65
- };
66
-
67
- export interface MapMountOptions {
68
- /** Theme overrides. */
69
- theme?: ThemeConfig;
70
- /** Dark mode setting: "auto" (system pref), "force", or "off". */
71
- darkMode?: DarkMode;
72
- /** Enable responsive resizing. Defaults to true. */
73
- responsive?: boolean;
74
- /** Show the tryOpenData.ai watermark. Defaults to true. */
75
- watermark?: boolean;
76
- /** Show tooltips on hover. Defaults to true. */
77
- tooltip?: boolean;
78
- /** Callback when a feature or point is clicked. */
79
- onMarkClick?: (event: MapMarkEvent) => void;
80
- /** Callback when a feature or point is hovered (null on mouse leave). */
81
- onMarkHover?: (event: MapMarkEvent | null) => void;
82
- }
83
-
84
- export interface MapInstance {
85
- /** Re-compile and re-render with a new spec. */
86
- update(spec: MapSpec): void;
87
- /** Re-compile at current container dimensions. */
88
- resize(): void;
89
- /** Export the map. */
90
- export(
91
- format: 'svg' | 'svg-with-fonts' | 'png' | 'jpg',
92
- options?: JPGExportOptions | SVGExportOptions,
93
- ): string | Promise<Blob> | Promise<string>;
94
- /** Remove all DOM elements and disconnect observers. */
95
- destroy(): void;
96
- /** The current compiled layout. */
97
- readonly layout: MapLayout;
98
- /** Zoom to one or more features by ID. */
99
- zoomTo(featureId: string | number | Array<string | number>, opts?: MapCameraOptions): void;
100
- /** Pan to a feature keeping the current zoom level. */
101
- panTo(featureId: string | number, opts?: MapCameraOptions): void;
102
- /** Fit the camera to an arbitrary bounding box, or reset to full view if no target. */
103
- fitBounds(
104
- target?: { x: number; y: number; width: number; height: number; padding?: number },
105
- opts?: MapCameraOptions,
106
- ): void;
107
- /** Reset the camera to the full map view. */
108
- resetView(opts?: MapCameraOptions): void;
109
- /** Get a snapshot of the current camera state. */
110
- getCamera(): Camera;
111
- /** Set the camera to an exact state (no animation). */
112
- setCamera(camera: Camera): void;
113
- }
114
-
115
- // ---------------------------------------------------------------------------
116
- // Dark mode resolution
117
- // ---------------------------------------------------------------------------
118
-
119
- function prefersReducedMotion(): boolean {
120
- if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;
121
- try {
122
- return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
123
- } catch {
124
- return false;
125
- }
126
- }
127
-
128
- function resolveDarkMode(mode?: DarkMode): boolean {
129
- if (mode === 'force') return true;
130
- if (mode === 'off' || mode === undefined) return false;
131
- if (typeof window !== 'undefined' && window.matchMedia) {
132
- return window.matchMedia('(prefers-color-scheme: dark)').matches;
133
- }
134
- return false;
135
- }
136
-
137
- // ---------------------------------------------------------------------------
138
- // Main API
139
- // ---------------------------------------------------------------------------
140
-
141
- /**
142
- * Create a map instance from a spec and mount it into a container.
143
- */
144
- export function createMap(
145
- container: HTMLElement,
146
- spec: MapSpec,
147
- options?: MapMountOptions,
148
- ): MapInstance {
149
- let currentSpec = spec;
150
- let currentLayout: MapLayout;
151
- let destroyed = false;
152
-
153
- // DOM
154
- let svgElement: SVGSVGElement | null = null;
155
-
156
- // Subsystems
157
- let tooltipManager: TooltipManager | null = null;
158
- let cleanupTooltipEvents: (() => void) | null = null;
159
- let disconnectResize: (() => void) | null = null;
160
-
161
- // Animation state
162
- let animationCleanup: (() => void) | null = null;
163
- let fillTransitionHandle: { cancel: () => void } | null = null;
164
- let pendingResize = false;
165
-
166
- // Camera state
167
- let currentCamera: Camera = { cx: 0, cy: 0, k: 1 };
168
- let currentFocusIds: Array<string | number> | null = null;
169
- let cameraTween: Tween<Camera> | null = null;
170
-
171
- // Track whether this is the first render (for snap-to-focus).
172
- let isFirstRender = true;
173
-
174
- // Set when webfonts have loaded and a recompile is owed.
175
- let fontsReloadPending = false;
176
-
177
- // Apply the root class up front so getComputedStyle sees --oc-font-family
178
- container.classList.add('oc-map-root');
179
-
180
- // Resolve the effective font the same way compile() will.
181
- function resolveEffectiveFont(): string {
182
- return (
183
- options?.theme?.fonts?.family ??
184
- currentSpec.theme?.fonts?.family ??
185
- resolveFontFamily(container)
186
- );
187
- }
188
- let fontFamily = resolveEffectiveFont();
189
- let measureText = createMeasureText(fontFamily);
190
- let renderGen = 0;
191
-
192
- // ---------------------------------------------------------------------------
193
- // Helpers
194
- // ---------------------------------------------------------------------------
195
-
196
- let isAutoHeight: boolean | null = null;
197
-
198
- function getContainerDimensions(): { width: number; height: number } {
199
- const rect = container.getBoundingClientRect();
200
- const width = Math.max(rect.width || 600, 100);
201
-
202
- if (isAutoHeight === null && (rect.width > 0 || rect.height > 0)) {
203
- isAutoHeight = rect.height === 0 && rect.width > 0;
204
- }
205
-
206
- // Explicit host height is a hard budget: return it as-is so the
207
- // compiler keeps the SVG inside its box.
208
- if (isAutoHeight === false && rect.height > 0) {
209
- return { width, height: Math.max(rect.height, 100) };
210
- }
211
-
212
- // Auto-height host: pick our own budget.
213
- return { width, height: Math.round(width * 0.625) };
214
- }
215
-
216
- function compile(): MapLayout {
217
- const { width, height } = getContainerDimensions();
218
- const darkMode = resolveDarkMode(options?.darkMode);
219
-
220
- const compileOpts: CompileOptions = {
221
- width,
222
- height,
223
- theme: options?.theme,
224
- darkMode,
225
- watermark: options?.watermark,
226
- measureText,
227
- };
228
-
229
- return compileMap(currentSpec, compileOpts);
230
- }
231
-
232
- // ---------------------------------------------------------------------------
233
- // Tooltip and interaction wiring
234
- // ---------------------------------------------------------------------------
235
-
236
- function wireTooltipAndInteraction(svg: SVGSVGElement, layout: MapLayout): () => void {
237
- const cleanups: Array<() => void> = [];
238
-
239
- const featureElements = svg.querySelectorAll('.oc-map-feature');
240
- for (const el of featureElements) {
241
- const featureId = el.getAttribute('data-feature-id');
242
- if (!featureId) continue;
243
-
244
- const content = layout.tooltipDescriptors.get(featureId);
245
- const feature = layout.features.find((f) => String(f.id) === featureId);
246
-
247
- const handleMouseEnter = (e: Event) => {
248
- const mouseEvent = e as MouseEvent;
249
- (el as SVGElement & ElementCSSInlineStyle).style.setProperty('cursor', 'pointer');
250
- (el as SVGElement & ElementCSSInlineStyle).style.setProperty('filter', 'brightness(1.1)');
251
- if (content && tooltipManager && options?.tooltip !== false) {
252
- const svgRect = svg.getBoundingClientRect();
253
- const x = mouseEvent.clientX - svgRect.left;
254
- const y = mouseEvent.clientY - svgRect.top;
255
- tooltipManager.show(content, x, y);
256
- }
257
- if (feature) {
258
- options?.onMarkHover?.({
259
- kind: 'feature',
260
- id: feature.id,
261
- name: feature.name,
262
- data: feature.data,
263
- });
264
- }
265
- };
266
-
267
- const handleMouseMove = (e: Event) => {
268
- if (content && tooltipManager && options?.tooltip !== false) {
269
- const mouseEvent = e as MouseEvent;
270
- const svgRect = svg.getBoundingClientRect();
271
- const x = mouseEvent.clientX - svgRect.left;
272
- const y = mouseEvent.clientY - svgRect.top;
273
- tooltipManager.show(content, x, y);
274
- }
275
- };
276
-
277
- const handleMouseLeave = () => {
278
- (el as SVGElement & ElementCSSInlineStyle).style.removeProperty('cursor');
279
- (el as SVGElement & ElementCSSInlineStyle).style.removeProperty('filter');
280
- tooltipManager?.hide();
281
- options?.onMarkHover?.(null);
282
- };
283
-
284
- const handleClick = () => {
285
- if (feature) {
286
- options?.onMarkClick?.({
287
- kind: 'feature',
288
- id: feature.id,
289
- name: feature.name,
290
- data: feature.data,
291
- });
292
- }
293
- };
294
-
295
- el.addEventListener('mouseenter', handleMouseEnter);
296
- el.addEventListener('mousemove', handleMouseMove);
297
- el.addEventListener('mouseleave', handleMouseLeave);
298
- el.addEventListener('click', handleClick);
299
-
300
- cleanups.push(() => {
301
- el.removeEventListener('mouseenter', handleMouseEnter);
302
- el.removeEventListener('mousemove', handleMouseMove);
303
- el.removeEventListener('mouseleave', handleMouseLeave);
304
- el.removeEventListener('click', handleClick);
305
- });
306
- }
307
-
308
- // Wire point interactions
309
- const pointMarksByKey = new Map(layout.pointMarks.map((p) => [p.key, p]));
310
- const pointElements = svg.querySelectorAll('.oc-map-point');
311
- for (const el of pointElements) {
312
- const pointKey = el.getAttribute('data-point-key');
313
- if (!pointKey) continue;
314
-
315
- const content = layout.tooltipDescriptors.get(`point:${pointKey}`);
316
- const pointMark = pointMarksByKey.get(pointKey);
317
-
318
- const handlePointMouseEnter = (e: Event) => {
319
- const mouseEvent = e as MouseEvent;
320
- (el as SVGElement & ElementCSSInlineStyle).style.setProperty('cursor', 'pointer');
321
- (el as SVGElement & ElementCSSInlineStyle).style.setProperty('filter', 'brightness(1.15)');
322
- if (content && tooltipManager && options?.tooltip !== false) {
323
- const svgRect = svg.getBoundingClientRect();
324
- const x = mouseEvent.clientX - svgRect.left;
325
- const y = mouseEvent.clientY - svgRect.top;
326
- tooltipManager.show(content, x, y);
327
- }
328
- if (pointMark) {
329
- options?.onMarkHover?.({
330
- kind: 'point',
331
- id: pointKey,
332
- data: pointMark.data,
333
- });
334
- }
335
- };
336
-
337
- const handlePointMouseMove = (e: Event) => {
338
- if (content && tooltipManager && options?.tooltip !== false) {
339
- const mouseEvent = e as MouseEvent;
340
- const svgRect = svg.getBoundingClientRect();
341
- const x = mouseEvent.clientX - svgRect.left;
342
- const y = mouseEvent.clientY - svgRect.top;
343
- tooltipManager.show(content, x, y);
344
- }
345
- };
346
-
347
- const handlePointMouseLeave = () => {
348
- (el as SVGElement & ElementCSSInlineStyle).style.removeProperty('cursor');
349
- (el as SVGElement & ElementCSSInlineStyle).style.removeProperty('filter');
350
- tooltipManager?.hide();
351
- options?.onMarkHover?.(null);
352
- };
353
-
354
- const handlePointClick = () => {
355
- if (pointMark) {
356
- options?.onMarkClick?.({
357
- kind: 'point',
358
- id: pointKey,
359
- data: pointMark.data,
360
- });
361
- }
362
- };
363
-
364
- el.addEventListener('mouseenter', handlePointMouseEnter);
365
- el.addEventListener('mousemove', handlePointMouseMove);
366
- el.addEventListener('mouseleave', handlePointMouseLeave);
367
- el.addEventListener('click', handlePointClick);
368
-
369
- cleanups.push(() => {
370
- el.removeEventListener('mouseenter', handlePointMouseEnter);
371
- el.removeEventListener('mousemove', handlePointMouseMove);
372
- el.removeEventListener('mouseleave', handlePointMouseLeave);
373
- el.removeEventListener('click', handlePointClick);
374
- });
375
- }
376
-
377
- return () => {
378
- for (const cleanup of cleanups) {
379
- cleanup();
380
- }
381
- };
382
- }
383
-
384
- // ---------------------------------------------------------------------------
385
- // Camera helpers
386
- // ---------------------------------------------------------------------------
387
-
388
- function resolveCamera(): Camera {
389
- if (currentFocusIds && currentFocusIds.length > 0) {
390
- const target = focusTargetForFeatures(currentLayout, currentFocusIds);
391
- return cameraForTarget(currentLayout, target);
392
- }
393
- return cameraForTarget(currentLayout, null);
394
- }
395
-
396
- function animateCamera(target: Camera, duration: number): void {
397
- if (cameraTween) cameraTween.cancel();
398
- cameraTween = createTween<Camera>({
399
- initial: currentCamera,
400
- lerp: interpolateCamera,
401
- duration,
402
- ease: easingFns.easeInOutCubic,
403
- onFrame(cam) {
404
- currentCamera = cam;
405
- if (svgElement) applyMapCamera(svgElement, cam, currentLayout);
406
- },
407
- });
408
- cameraTween.to(target);
409
- }
410
-
411
- function driveCamera(cam: Camera, duration: number): void {
412
- if (duration === 0 || prefersReducedMotion()) {
413
- currentCamera = cam;
414
- if (svgElement) applyMapCamera(svgElement, cam, currentLayout);
415
- } else {
416
- animateCamera(cam, duration);
417
- }
418
- }
419
-
420
- function updateA11yLive(ids: Array<string | number> | null): void {
421
- let liveEl = container.querySelector('.oc-map-live') as HTMLElement | null;
422
- if (!liveEl) {
423
- liveEl = document.createElement('div');
424
- liveEl.className = 'oc-map-live oc-sr-only';
425
- liveEl.setAttribute('aria-live', 'polite');
426
- container.appendChild(liveEl);
427
- }
428
- if (!ids || ids.length === 0) {
429
- liveEl.textContent = 'Showing full map';
430
- return;
431
- }
432
- const names = ids.map((id) => {
433
- const f = currentLayout.features.find((feat) => String(feat.id) === String(id));
434
- return f?.name ?? String(id);
435
- });
436
- liveEl.textContent = `Zoomed to ${names.join(', ')}`;
437
- }
438
-
439
- function applyFocusDim(ids: Array<string | number> | null): void {
440
- if (!svgElement) return;
441
- const features = svgElement.querySelectorAll('.oc-map-feature');
442
- if (!ids || ids.length === 0) {
443
- for (const el of features) {
444
- (el as SVGElement & ElementCSSInlineStyle).style.removeProperty('opacity');
445
- }
446
- return;
447
- }
448
- const focusSet = new Set(ids.map(String));
449
- for (const el of features) {
450
- const fid = el.getAttribute('data-feature-id');
451
- (el as SVGElement & ElementCSSInlineStyle).style.setProperty(
452
- 'opacity',
453
- fid && focusSet.has(fid) ? '1' : String(FOCUS_DIM_OPACITY),
454
- );
455
- }
456
- }
457
-
458
- // ---------------------------------------------------------------------------
459
- // Render + update
460
- // ---------------------------------------------------------------------------
461
-
462
- function render(animate = false): void {
463
- // Cancel running animations
464
- if (animationCleanup) {
465
- animationCleanup();
466
- animationCleanup = null;
467
- }
468
- if (fillTransitionHandle) {
469
- fillTransitionHandle.cancel();
470
- fillTransitionHandle = null;
471
- }
472
-
473
- // Render new SVG before removing old to avoid a paint gap
474
- const oldSvg = svgElement;
475
- const newSvg = renderMapSVG(currentLayout, { animate });
476
-
477
- if (oldSvg) {
478
- if (cleanupTooltipEvents) {
479
- cleanupTooltipEvents();
480
- cleanupTooltipEvents = null;
481
- }
482
- container.replaceChild(newSvg, oldSvg);
483
- } else {
484
- container.appendChild(newSvg);
485
- }
486
- svgElement = newSvg;
487
-
488
- // Wire interactions
489
- cleanupTooltipEvents = wireTooltipAndInteraction(newSvg, currentLayout);
490
-
491
- // Setup tooltips if enabled
492
- if (options?.tooltip !== false) {
493
- if (!tooltipManager) {
494
- tooltipManager = createTooltipManager(container);
495
- }
496
- }
497
-
498
- // Setup animation cleanup only when actually animating
499
- const isAnimating = animate && !!currentLayout.animation?.enter;
500
- if (isAnimating) {
501
- animationCleanup = setupAnimationCleanup(newSvg, () => {
502
- if (pendingResize && !destroyed) {
503
- pendingResize = false;
504
- resize();
505
- }
506
- // Apply deferred focus dim after animation completes
507
- if (currentFocusIds && currentFocusIds.length > 0) {
508
- applyFocusDim(currentFocusIds);
509
- }
510
- });
511
- }
512
-
513
- // Re-apply camera transform after render if zoomed or focused
514
- if (currentCamera.k > 1 + 1e-3 || (currentFocusIds && currentFocusIds.length > 0)) {
515
- applyMapCamera(newSvg, currentCamera, currentLayout);
516
- }
517
-
518
- renderGen += 1;
519
- container.dataset.ocRenderGen = String(renderGen);
520
-
521
- if (fontsReloadPending) {
522
- fontsReloadPending = false;
523
- container.dataset.ocFontsState = 'ready';
524
- }
525
-
526
- // On first render, snap to declarative focus if present
527
- if (isFirstRender && currentLayout.focus) {
528
- const target = currentLayout.focus.target;
529
- currentFocusIds = [...currentLayout.focus.ids];
530
- const cam = cameraForTarget(currentLayout, target);
531
- currentCamera = cam;
532
- if (svgElement) applyMapCamera(svgElement, cam, currentLayout);
533
- if (!isAnimating) applyFocusDim(currentFocusIds);
534
- }
535
- isFirstRender = false;
536
- }
537
-
538
- function update(newSpec: MapSpec): void {
539
- currentSpec = newSpec;
540
- const nextFont = resolveEffectiveFont();
541
- if (nextFont !== fontFamily) {
542
- fontFamily = nextFont;
543
- measureText = createMeasureText(fontFamily);
544
- }
545
-
546
- // Capture fills optimistically; gate the tween on the *new* layout's animation config after compile
547
- const canAnimate = !animationCleanup && !prefersReducedMotion();
548
- const prevFills = canAnimate ? captureFeatureFills(svgElement) : null;
549
-
550
- // Remember previous focus to detect changes. The signature includes the
551
- // target rect, not just ids+padding, so a points-focus ({ points: true },
552
- // which resolves to empty ids) still re-fits the camera when the fitted
553
- // cluster moves between steps.
554
- const prevFocusIds = currentFocusIds ? currentFocusIds.map(String).sort().join(',') : null;
555
- const prevFocusSig = focusSignature(currentLayout.focus);
556
-
557
- currentLayout = compile();
558
- render();
559
-
560
- // Run fill tween if the *new* layout enables update animation
561
- if (
562
- canAnimate &&
563
- prevFills &&
564
- prevFills.size > 0 &&
565
- svgElement &&
566
- currentLayout.animation?.update
567
- ) {
568
- fillTransitionHandle = runMapFillTransition(svgElement, prevFills, {
569
- duration: currentLayout.animation.update.duration,
570
- });
571
- }
572
-
573
- // Declarative focus from spec: tween camera if focus changed
574
- const nextFocus = currentLayout.focus;
575
- const nextFocusSig = focusSignature(nextFocus);
576
-
577
- if (nextFocusSig !== prevFocusSig) {
578
- if (nextFocus) {
579
- currentFocusIds = [...nextFocus.ids];
580
- const cam = cameraForTarget(currentLayout, nextFocus.target);
581
- driveCamera(cam, prefersReducedMotion() ? 0 : storyMotion.camera);
582
- applyFocusDim(currentFocusIds);
583
- } else if (prevFocusIds !== null) {
584
- currentFocusIds = null;
585
- const cam = cameraForTarget(currentLayout, null);
586
- driveCamera(cam, prefersReducedMotion() ? 0 : storyMotion.camera);
587
- applyFocusDim(null);
588
- }
589
- }
590
- }
591
-
592
- function resize(): void {
593
- if (destroyed) return;
594
- // If animation is running, queue the resize for after it completes
595
- if (animationCleanup) {
596
- pendingResize = true;
597
- return;
598
- }
599
-
600
- // Cancel any running camera tween: the resize recomputes the camera for the
601
- // new dimensions, and a stale tween would overwrite it on the next frame.
602
- if (cameraTween) {
603
- cameraTween.cancel();
604
- cameraTween = null;
605
- }
606
-
607
- currentLayout = compile();
608
- render();
609
-
610
- // Re-resolve camera against new layout dimensions.
611
- // Imperative focus (set via zoomTo/panTo) takes precedence over declarative.
612
- if (currentFocusIds && currentFocusIds.length > 0) {
613
- currentCamera = resolveCamera();
614
- if (svgElement) applyMapCamera(svgElement, currentCamera, currentLayout);
615
- } else if (currentLayout.focus) {
616
- currentFocusIds = [...currentLayout.focus.ids];
617
- currentCamera = cameraForTarget(currentLayout, currentLayout.focus.target);
618
- if (svgElement) applyMapCamera(svgElement, currentCamera, currentLayout);
619
- }
620
- applyFocusDim(currentFocusIds);
621
- }
622
-
623
- // ---------------------------------------------------------------------------
624
- // Export
625
- // ---------------------------------------------------------------------------
626
-
627
- function exportChart(
628
- format: 'svg' | 'svg-with-fonts' | 'png' | 'jpg',
629
- options_?: JPGExportOptions | SVGExportOptions,
630
- ): string | Promise<Blob> | Promise<string> {
631
- if (!svgElement) return '';
632
-
633
- switch (format) {
634
- case 'svg':
635
- return exportSVG(svgElement);
636
- case 'svg-with-fonts':
637
- return exportSVGWithFonts(svgElement);
638
- case 'png':
639
- return exportPNG(svgElement, options_ as JPGExportOptions);
640
- case 'jpg':
641
- return exportJPG(svgElement, options_ as JPGExportOptions);
642
- default:
643
- return '';
644
- }
645
- }
646
-
647
- // ---------------------------------------------------------------------------
648
- // Destroy
649
- // ---------------------------------------------------------------------------
650
-
651
- function destroy(): void {
652
- if (destroyed) return;
653
- destroyed = true;
654
-
655
- // Cancel running animations
656
- if (animationCleanup) {
657
- cancelAnimations(svgElement);
658
- animationCleanup();
659
- animationCleanup = null;
660
- }
661
- if (fillTransitionHandle) {
662
- fillTransitionHandle.cancel();
663
- fillTransitionHandle = null;
664
- }
665
- if (cameraTween) {
666
- cameraTween.cancel();
667
- cameraTween = null;
668
- }
669
-
670
- // Clean up events
671
- if (cleanupTooltipEvents) {
672
- cleanupTooltipEvents();
673
- cleanupTooltipEvents = null;
674
- }
675
-
676
- // Remove SVG
677
- if (svgElement) {
678
- svgElement.remove();
679
- svgElement = null;
680
- }
681
-
682
- // Remove a11y live region
683
- const liveEl = container.querySelector('.oc-map-live');
684
- if (liveEl) liveEl.remove();
685
-
686
- // Unmount tooltip manager
687
- if (tooltipManager) {
688
- tooltipManager.destroy();
689
- tooltipManager = null;
690
- }
691
-
692
- // Disconnect resize observer
693
- if (disconnectResize) {
694
- disconnectResize();
695
- disconnectResize = null;
696
- }
697
-
698
- // Remove root classes
699
- container.classList.remove('oc-map-root', 'oc-dark');
700
- }
701
-
702
- // ---------------------------------------------------------------------------
703
- // Initialize
704
- // ---------------------------------------------------------------------------
705
-
706
- if (resolveDarkMode(options?.darkMode)) {
707
- container.classList.add('oc-dark');
708
- }
709
-
710
- // Initial compile and render (animate on first mount)
711
- currentLayout = compile();
712
- render(true);
713
-
714
- // Recompile once after webfonts load
715
- const fontsPending = scheduleFontReload(
716
- fontFamily,
717
- () => !destroyed,
718
- () => {
719
- fontsReloadPending = true;
720
- resize();
721
- },
722
- );
723
- container.dataset.ocFontsState = fontsPending ? 'pending' : 'ready';
724
-
725
- // Setup responsive resizing
726
- if (options?.responsive !== false) {
727
- disconnectResize = observeResize(container, () => {
728
- resize();
729
- });
730
- }
731
-
732
- return {
733
- update,
734
- resize,
735
- export: exportChart,
736
- destroy,
737
- get layout(): MapLayout {
738
- return currentLayout;
739
- },
740
- zoomTo(featureId: string | number | Array<string | number>, opts?: MapCameraOptions): void {
741
- const ids = Array.isArray(featureId) ? featureId : [featureId];
742
- const target = focusTargetForFeatures(currentLayout, ids, opts?.padding ?? 16);
743
- if (!target) {
744
- console.warn(`[openchart] zoomTo: no features found for ids: ${ids.join(', ')}`);
745
- return;
746
- }
747
- currentFocusIds = ids;
748
- const cam = cameraForTarget(currentLayout, target);
749
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
750
- applyFocusDim(ids);
751
- updateA11yLive(ids);
752
- },
753
- panTo(featureId: string | number, opts?: MapCameraOptions): void {
754
- const target = focusTargetForFeatures(currentLayout, [featureId], opts?.padding ?? 16);
755
- if (!target) {
756
- console.warn(`[openchart] panTo: no feature found for id: ${featureId}`);
757
- return;
758
- }
759
- const cam: Camera = {
760
- cx: target.x + target.width / 2,
761
- cy: target.y + target.height / 2,
762
- k: currentCamera.k,
763
- };
764
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
765
- updateA11yLive([featureId]);
766
- },
767
- fitBounds(
768
- target?: { x: number; y: number; width: number; height: number; padding?: number },
769
- opts?: MapCameraOptions,
770
- ): void {
771
- currentFocusIds = null;
772
- const cam = cameraForTarget(currentLayout, target ?? null);
773
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
774
- applyFocusDim(null);
775
- },
776
- resetView(opts?: MapCameraOptions): void {
777
- currentFocusIds = null;
778
- const cam = cameraForTarget(currentLayout, null);
779
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
780
- applyFocusDim(null);
781
- updateA11yLive(null);
782
- },
783
- getCamera(): Camera {
784
- return { ...currentCamera };
785
- },
786
- setCamera(camera: Camera): void {
787
- currentCamera = camera;
788
- currentFocusIds = null;
789
- if (svgElement) applyMapCamera(svgElement, camera, currentLayout);
790
- },
791
- };
792
- }