@opendata-ai/openchart-vanilla 8.0.0-rc.9 → 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 (150) hide show
  1. package/dist/{chunk-SPILUE5S.js → chunk-2NAQRP66.js} +2 -2
  2. package/dist/{chunk-IZQBT6QM.js → chunk-6BUCYCLD.js} +7283 -5881
  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-QW7ZB6NE.js → chunk-EKAUQAAX.js} +49 -45
  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-IZQBT6QM.js.map +0 -1
  30. package/dist/chunk-QW7ZB6NE.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 -1477
  39. package/src/__tests__/editable-prop.test.ts +0 -174
  40. package/src/__tests__/events.test.ts +0 -387
  41. package/src/__tests__/export.test.ts +0 -241
  42. package/src/__tests__/font-race.test.ts +0 -199
  43. package/src/__tests__/gradient-ids.test.ts +0 -159
  44. package/src/__tests__/gradient-utils.test.ts +0 -125
  45. package/src/__tests__/invert.test.ts +0 -187
  46. package/src/__tests__/known-bugs-render.test.ts +0 -183
  47. package/src/__tests__/map.test.ts +0 -636
  48. package/src/__tests__/mount.test.ts +0 -357
  49. package/src/__tests__/pattern-fills.test.ts +0 -105
  50. package/src/__tests__/resize-timing.test.ts +0 -218
  51. package/src/__tests__/sankey.test.ts +0 -133
  52. package/src/__tests__/selection-events.test.ts +0 -1062
  53. package/src/__tests__/series-search.test.ts +0 -311
  54. package/src/__tests__/static.test.ts +0 -141
  55. package/src/__tests__/svg-renderer.test.ts +0 -895
  56. package/src/__tests__/table-keyboard.test.ts +0 -361
  57. package/src/__tests__/table-mount.test.ts +0 -639
  58. package/src/__tests__/tilemap.test.ts +0 -158
  59. package/src/__tests__/tooltip.test.ts +0 -337
  60. package/src/__tests__/transition.test.ts +0 -1792
  61. package/src/__tests__/update-scrolly-matrix.test.ts +0 -563
  62. package/src/__tests__/you-draw-it.test.ts +0 -273
  63. package/src/animation-vars.ts +0 -42
  64. package/src/animation.ts +0 -76
  65. package/src/barlist-mount.ts +0 -383
  66. package/src/barlist-renderer.ts +0 -267
  67. package/src/dom-helpers.ts +0 -17
  68. package/src/export.ts +0 -482
  69. package/src/gradient-utils.ts +0 -138
  70. package/src/graph/__tests__/canvas-renderer.test.ts +0 -713
  71. package/src/graph/__tests__/graph-mount.test.ts +0 -213
  72. package/src/graph/__tests__/interaction.test.ts +0 -205
  73. package/src/graph/__tests__/keyboard.test.ts +0 -653
  74. package/src/graph/__tests__/search.test.ts +0 -88
  75. package/src/graph/__tests__/simulation.test.ts +0 -233
  76. package/src/graph/__tests__/spatial-index.test.ts +0 -142
  77. package/src/graph/__tests__/zoom.test.ts +0 -203
  78. package/src/graph/canvas-renderer.ts +0 -747
  79. package/src/graph/interaction.ts +0 -367
  80. package/src/graph/keyboard.ts +0 -208
  81. package/src/graph/search.ts +0 -50
  82. package/src/graph/simulation-worker-url.ts +0 -12
  83. package/src/graph/simulation-worker.ts +0 -278
  84. package/src/graph/simulation.ts +0 -422
  85. package/src/graph/spatial-index.ts +0 -121
  86. package/src/graph/types.ts +0 -47
  87. package/src/graph/worker-protocol.ts +0 -70
  88. package/src/graph/zoom.ts +0 -134
  89. package/src/graph-mount.ts +0 -888
  90. package/src/index.ts +0 -76
  91. package/src/interactions/chart-events.ts +0 -139
  92. package/src/interactions/crosshair.ts +0 -233
  93. package/src/interactions/drag-handler.ts +0 -175
  94. package/src/interactions/editing-drags.ts +0 -649
  95. package/src/interactions/index.ts +0 -27
  96. package/src/interactions/invert.ts +0 -54
  97. package/src/interactions/keyboard-nav.ts +0 -111
  98. package/src/interactions/legend-interaction.ts +0 -46
  99. package/src/interactions/selection.ts +0 -286
  100. package/src/interactions/tooltip-events.ts +0 -72
  101. package/src/map-camera.ts +0 -111
  102. package/src/map-mount.ts +0 -797
  103. package/src/map-renderer.ts +0 -476
  104. package/src/map-transition.ts +0 -99
  105. package/src/measure-text.ts +0 -134
  106. package/src/mount.ts +0 -1434
  107. package/src/pattern-utils.ts +0 -110
  108. package/src/renderers/annotations.ts +0 -388
  109. package/src/renderers/axes.ts +0 -351
  110. package/src/renderers/brand.ts +0 -87
  111. package/src/renderers/chrome.ts +0 -196
  112. package/src/renderers/endpoint-labels.ts +0 -150
  113. package/src/renderers/legend.ts +0 -312
  114. package/src/renderers/marks.ts +0 -561
  115. package/src/renderers/metrics.ts +0 -63
  116. package/src/renderers/svg-dom.ts +0 -40
  117. package/src/renderers/table-cells.ts +0 -446
  118. package/src/resize-observer.ts +0 -46
  119. package/src/sankey-mount.ts +0 -622
  120. package/src/sankey-renderer.ts +0 -614
  121. package/src/series-search.ts +0 -392
  122. package/src/static.ts +0 -251
  123. package/src/story/__tests__/camera-math.test.ts +0 -145
  124. package/src/story/__tests__/create-chart-story.test.ts +0 -317
  125. package/src/story/__tests__/progress-math.test.ts +0 -95
  126. package/src/story/__tests__/scroll-driver.test.ts +0 -130
  127. package/src/story/__tests__/tween.test.ts +0 -159
  128. package/src/story/camera-math.ts +0 -125
  129. package/src/story/create-chart-story.ts +0 -353
  130. package/src/story/crossfade.ts +0 -70
  131. package/src/story/index.ts +0 -39
  132. package/src/story/progress-math.ts +0 -85
  133. package/src/story/resolve-camera-target.ts +0 -119
  134. package/src/story/scroll-driver.ts +0 -206
  135. package/src/story/story-camera.ts +0 -49
  136. package/src/story/tween.ts +0 -112
  137. package/src/story/types.ts +0 -76
  138. package/src/svg-ids.ts +0 -23
  139. package/src/svg-renderer.ts +0 -383
  140. package/src/table-keyboard.ts +0 -266
  141. package/src/table-mount.ts +0 -567
  142. package/src/table-renderer.ts +0 -414
  143. package/src/text-edit-overlay.ts +0 -389
  144. package/src/theme-tokens.ts +0 -51
  145. package/src/tilemap-mount.ts +0 -511
  146. package/src/tilemap-renderer.ts +0 -396
  147. package/src/tooltip.ts +0 -177
  148. package/src/transition.ts +0 -2816
  149. package/src/you-draw-it.ts +0 -480
  150. /package/dist/{chunk-SPILUE5S.js.map → chunk-2NAQRP66.js.map} +0 -0
package/src/map-mount.ts DELETED
@@ -1,797 +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, initialize the camera so subsequent tweens start
527
- // from the correct position (not the {0,0,1} default).
528
- if (isFirstRender) {
529
- if (currentLayout.focus) {
530
- const target = currentLayout.focus.target;
531
- currentFocusIds = [...currentLayout.focus.ids];
532
- const cam = cameraForTarget(currentLayout, target);
533
- currentCamera = cam;
534
- if (svgElement) applyMapCamera(svgElement, cam, currentLayout);
535
- if (!isAnimating) applyFocusDim(currentFocusIds);
536
- } else {
537
- currentCamera = cameraForTarget(currentLayout, null);
538
- }
539
- }
540
- isFirstRender = false;
541
- }
542
-
543
- function update(newSpec: MapSpec): void {
544
- currentSpec = newSpec;
545
- const nextFont = resolveEffectiveFont();
546
- if (nextFont !== fontFamily) {
547
- fontFamily = nextFont;
548
- measureText = createMeasureText(fontFamily);
549
- }
550
-
551
- // Capture fills optimistically; gate the tween on the *new* layout's animation config after compile
552
- const canAnimate = !animationCleanup && !prefersReducedMotion();
553
- const prevFills = canAnimate ? captureFeatureFills(svgElement) : null;
554
-
555
- // Remember previous focus to detect changes. The signature includes the
556
- // target rect, not just ids+padding, so a points-focus ({ points: true },
557
- // which resolves to empty ids) still re-fits the camera when the fitted
558
- // cluster moves between steps.
559
- const prevFocusIds = currentFocusIds ? currentFocusIds.map(String).sort().join(',') : null;
560
- const prevFocusSig = focusSignature(currentLayout.focus);
561
-
562
- currentLayout = compile();
563
- render();
564
-
565
- // Run fill tween if the *new* layout enables update animation
566
- if (
567
- canAnimate &&
568
- prevFills &&
569
- prevFills.size > 0 &&
570
- svgElement &&
571
- currentLayout.animation?.update
572
- ) {
573
- fillTransitionHandle = runMapFillTransition(svgElement, prevFills, {
574
- duration: currentLayout.animation.update.duration,
575
- });
576
- }
577
-
578
- // Declarative focus from spec: tween camera if focus changed
579
- const nextFocus = currentLayout.focus;
580
- const nextFocusSig = focusSignature(nextFocus);
581
-
582
- if (nextFocusSig !== prevFocusSig) {
583
- if (nextFocus) {
584
- currentFocusIds = [...nextFocus.ids];
585
- const cam = cameraForTarget(currentLayout, nextFocus.target);
586
- driveCamera(cam, prefersReducedMotion() ? 0 : storyMotion.camera);
587
- applyFocusDim(currentFocusIds);
588
- } else if (prevFocusIds !== null) {
589
- currentFocusIds = null;
590
- const cam = cameraForTarget(currentLayout, null);
591
- driveCamera(cam, prefersReducedMotion() ? 0 : storyMotion.camera);
592
- applyFocusDim(null);
593
- }
594
- }
595
- }
596
-
597
- function resize(): void {
598
- if (destroyed) return;
599
- // If animation is running, queue the resize for after it completes
600
- if (animationCleanup) {
601
- pendingResize = true;
602
- return;
603
- }
604
-
605
- // Cancel any running camera tween: the resize recomputes the camera for the
606
- // new dimensions, and a stale tween would overwrite it on the next frame.
607
- if (cameraTween) {
608
- cameraTween.cancel();
609
- cameraTween = null;
610
- }
611
-
612
- currentLayout = compile();
613
- render();
614
-
615
- // Re-resolve camera against new layout dimensions.
616
- // Imperative focus (set via zoomTo/panTo) takes precedence over declarative.
617
- if (currentFocusIds && currentFocusIds.length > 0) {
618
- currentCamera = resolveCamera();
619
- if (svgElement) applyMapCamera(svgElement, currentCamera, currentLayout);
620
- } else if (currentLayout.focus) {
621
- currentFocusIds = [...currentLayout.focus.ids];
622
- currentCamera = cameraForTarget(currentLayout, currentLayout.focus.target);
623
- if (svgElement) applyMapCamera(svgElement, currentCamera, currentLayout);
624
- }
625
- applyFocusDim(currentFocusIds);
626
- }
627
-
628
- // ---------------------------------------------------------------------------
629
- // Export
630
- // ---------------------------------------------------------------------------
631
-
632
- function exportChart(
633
- format: 'svg' | 'svg-with-fonts' | 'png' | 'jpg',
634
- options_?: JPGExportOptions | SVGExportOptions,
635
- ): string | Promise<Blob> | Promise<string> {
636
- if (!svgElement) return '';
637
-
638
- switch (format) {
639
- case 'svg':
640
- return exportSVG(svgElement);
641
- case 'svg-with-fonts':
642
- return exportSVGWithFonts(svgElement);
643
- case 'png':
644
- return exportPNG(svgElement, options_ as JPGExportOptions);
645
- case 'jpg':
646
- return exportJPG(svgElement, options_ as JPGExportOptions);
647
- default:
648
- return '';
649
- }
650
- }
651
-
652
- // ---------------------------------------------------------------------------
653
- // Destroy
654
- // ---------------------------------------------------------------------------
655
-
656
- function destroy(): void {
657
- if (destroyed) return;
658
- destroyed = true;
659
-
660
- // Cancel running animations
661
- if (animationCleanup) {
662
- cancelAnimations(svgElement);
663
- animationCleanup();
664
- animationCleanup = null;
665
- }
666
- if (fillTransitionHandle) {
667
- fillTransitionHandle.cancel();
668
- fillTransitionHandle = null;
669
- }
670
- if (cameraTween) {
671
- cameraTween.cancel();
672
- cameraTween = null;
673
- }
674
-
675
- // Clean up events
676
- if (cleanupTooltipEvents) {
677
- cleanupTooltipEvents();
678
- cleanupTooltipEvents = null;
679
- }
680
-
681
- // Remove SVG
682
- if (svgElement) {
683
- svgElement.remove();
684
- svgElement = null;
685
- }
686
-
687
- // Remove a11y live region
688
- const liveEl = container.querySelector('.oc-map-live');
689
- if (liveEl) liveEl.remove();
690
-
691
- // Unmount tooltip manager
692
- if (tooltipManager) {
693
- tooltipManager.destroy();
694
- tooltipManager = null;
695
- }
696
-
697
- // Disconnect resize observer
698
- if (disconnectResize) {
699
- disconnectResize();
700
- disconnectResize = null;
701
- }
702
-
703
- // Remove root classes
704
- container.classList.remove('oc-map-root', 'oc-dark');
705
- }
706
-
707
- // ---------------------------------------------------------------------------
708
- // Initialize
709
- // ---------------------------------------------------------------------------
710
-
711
- if (resolveDarkMode(options?.darkMode)) {
712
- container.classList.add('oc-dark');
713
- }
714
-
715
- // Initial compile and render (animate on first mount)
716
- currentLayout = compile();
717
- render(true);
718
-
719
- // Recompile once after webfonts load
720
- const fontsPending = scheduleFontReload(
721
- fontFamily,
722
- () => !destroyed,
723
- () => {
724
- fontsReloadPending = true;
725
- resize();
726
- },
727
- );
728
- container.dataset.ocFontsState = fontsPending ? 'pending' : 'ready';
729
-
730
- // Setup responsive resizing
731
- if (options?.responsive !== false) {
732
- disconnectResize = observeResize(container, () => {
733
- resize();
734
- });
735
- }
736
-
737
- return {
738
- update,
739
- resize,
740
- export: exportChart,
741
- destroy,
742
- get layout(): MapLayout {
743
- return currentLayout;
744
- },
745
- zoomTo(featureId: string | number | Array<string | number>, opts?: MapCameraOptions): void {
746
- const ids = Array.isArray(featureId) ? featureId : [featureId];
747
- const target = focusTargetForFeatures(currentLayout, ids, opts?.padding ?? 16);
748
- if (!target) {
749
- console.warn(`[openchart] zoomTo: no features found for ids: ${ids.join(', ')}`);
750
- return;
751
- }
752
- currentFocusIds = ids;
753
- const cam = cameraForTarget(currentLayout, target);
754
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
755
- applyFocusDim(ids);
756
- updateA11yLive(ids);
757
- },
758
- panTo(featureId: string | number, opts?: MapCameraOptions): void {
759
- const target = focusTargetForFeatures(currentLayout, [featureId], opts?.padding ?? 16);
760
- if (!target) {
761
- console.warn(`[openchart] panTo: no feature found for id: ${featureId}`);
762
- return;
763
- }
764
- const cam: Camera = {
765
- cx: target.x + target.width / 2,
766
- cy: target.y + target.height / 2,
767
- k: currentCamera.k,
768
- };
769
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
770
- updateA11yLive([featureId]);
771
- },
772
- fitBounds(
773
- target?: { x: number; y: number; width: number; height: number; padding?: number },
774
- opts?: MapCameraOptions,
775
- ): void {
776
- currentFocusIds = null;
777
- const cam = cameraForTarget(currentLayout, target ?? null);
778
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
779
- applyFocusDim(null);
780
- },
781
- resetView(opts?: MapCameraOptions): void {
782
- currentFocusIds = null;
783
- const cam = cameraForTarget(currentLayout, null);
784
- driveCamera(cam, opts?.duration ?? storyMotion.camera);
785
- applyFocusDim(null);
786
- updateA11yLive(null);
787
- },
788
- getCamera(): Camera {
789
- return { ...currentCamera };
790
- },
791
- setCamera(camera: Camera): void {
792
- currentCamera = camera;
793
- currentFocusIds = null;
794
- if (svgElement) applyMapCamera(svgElement, camera, currentLayout);
795
- },
796
- };
797
- }