@opendata-ai/openchart-vanilla 8.0.0-rc.2 → 8.0.0-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/{chunk-W34KN7FD.js → chunk-2NAQRP66.js} +2 -2
  2. package/dist/chunk-DCODCLWI.js +234 -0
  3. package/dist/chunk-DCODCLWI.js.map +1 -0
  4. package/dist/{chunk-5EOV5JQZ.js → chunk-EKAUQAAX.js} +50 -46
  5. package/dist/chunk-EKAUQAAX.js.map +1 -0
  6. package/dist/{chunk-ENXSUXC5.js → chunk-KNT5AZ2O.js} +7309 -5490
  7. package/dist/chunk-KNT5AZ2O.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 +283 -24
  16. package/dist/index.js +2012 -763
  17. package/dist/index.js.map +1 -1
  18. package/dist/{mount-CUKQLeqD.d.ts → mount-Dvv8NYIv.d.ts} +117 -3
  19. package/dist/simulation-worker.js +83 -2
  20. package/dist/static.js +7 -69
  21. package/dist/static.js.map +1 -1
  22. package/dist/story/index.d.ts +3 -2
  23. package/dist/story/index.js +5 -3
  24. package/dist/story/index.js.map +1 -1
  25. package/dist/styles.css +1 -1
  26. package/dist/styles.css.map +1 -1
  27. package/package.json +14 -6
  28. package/dist/chunk-5EOV5JQZ.js.map +0 -1
  29. package/dist/chunk-ENXSUXC5.js.map +0 -1
  30. package/src/__test-fixtures__/dom.ts +0 -70
  31. package/src/__test-fixtures__/specs.ts +0 -214
  32. package/src/__tests__/animation.test.ts +0 -358
  33. package/src/__tests__/annotations-render.test.ts +0 -201
  34. package/src/__tests__/compound-labels.test.ts +0 -122
  35. package/src/__tests__/continuous-legend.test.ts +0 -91
  36. package/src/__tests__/crosshair.test.ts +0 -130
  37. package/src/__tests__/edit-events.test.ts +0 -902
  38. package/src/__tests__/events.test.ts +0 -387
  39. package/src/__tests__/export.test.ts +0 -241
  40. package/src/__tests__/font-race.test.ts +0 -199
  41. package/src/__tests__/gradient-ids.test.ts +0 -159
  42. package/src/__tests__/gradient-utils.test.ts +0 -125
  43. package/src/__tests__/known-bugs-render.test.ts +0 -183
  44. package/src/__tests__/map.test.ts +0 -293
  45. package/src/__tests__/mount.test.ts +0 -357
  46. package/src/__tests__/pattern-fills.test.ts +0 -105
  47. package/src/__tests__/resize-timing.test.ts +0 -218
  48. package/src/__tests__/sankey.test.ts +0 -133
  49. package/src/__tests__/selection-events.test.ts +0 -869
  50. package/src/__tests__/series-search.test.ts +0 -311
  51. package/src/__tests__/static.test.ts +0 -141
  52. package/src/__tests__/svg-renderer.test.ts +0 -895
  53. package/src/__tests__/table-keyboard.test.ts +0 -361
  54. package/src/__tests__/table-mount.test.ts +0 -639
  55. package/src/__tests__/tilemap.test.ts +0 -158
  56. package/src/__tests__/tooltip.test.ts +0 -337
  57. package/src/__tests__/transition.test.ts +0 -1777
  58. package/src/__tests__/you-draw-it.test.ts +0 -273
  59. package/src/animation-vars.ts +0 -42
  60. package/src/animation.ts +0 -76
  61. package/src/barlist-mount.ts +0 -383
  62. package/src/barlist-renderer.ts +0 -267
  63. package/src/dom-helpers.ts +0 -17
  64. package/src/export.ts +0 -482
  65. package/src/gradient-utils.ts +0 -138
  66. package/src/graph/__tests__/canvas-renderer.test.ts +0 -713
  67. package/src/graph/__tests__/graph-mount.test.ts +0 -213
  68. package/src/graph/__tests__/interaction.test.ts +0 -205
  69. package/src/graph/__tests__/keyboard.test.ts +0 -653
  70. package/src/graph/__tests__/search.test.ts +0 -88
  71. package/src/graph/__tests__/simulation.test.ts +0 -233
  72. package/src/graph/__tests__/spatial-index.test.ts +0 -142
  73. package/src/graph/__tests__/zoom.test.ts +0 -203
  74. package/src/graph/canvas-renderer.ts +0 -747
  75. package/src/graph/interaction.ts +0 -367
  76. package/src/graph/keyboard.ts +0 -208
  77. package/src/graph/search.ts +0 -50
  78. package/src/graph/simulation-worker-url.ts +0 -12
  79. package/src/graph/simulation-worker.ts +0 -278
  80. package/src/graph/simulation.ts +0 -422
  81. package/src/graph/spatial-index.ts +0 -121
  82. package/src/graph/types.ts +0 -47
  83. package/src/graph/worker-protocol.ts +0 -70
  84. package/src/graph/zoom.ts +0 -134
  85. package/src/graph-mount.ts +0 -888
  86. package/src/index.ts +0 -76
  87. package/src/interactions/chart-events.ts +0 -139
  88. package/src/interactions/crosshair.ts +0 -233
  89. package/src/interactions/drag-handler.ts +0 -175
  90. package/src/interactions/editing-drags.ts +0 -515
  91. package/src/interactions/index.ts +0 -25
  92. package/src/interactions/keyboard-nav.ts +0 -111
  93. package/src/interactions/legend-interaction.ts +0 -46
  94. package/src/interactions/selection.ts +0 -280
  95. package/src/interactions/tooltip-events.ts +0 -72
  96. package/src/map-camera.ts +0 -88
  97. package/src/map-mount.ts +0 -701
  98. package/src/map-renderer.ts +0 -338
  99. package/src/map-transition.ts +0 -83
  100. package/src/measure-text.ts +0 -134
  101. package/src/mount.ts +0 -1382
  102. package/src/pattern-utils.ts +0 -110
  103. package/src/renderers/annotations.ts +0 -388
  104. package/src/renderers/axes.ts +0 -351
  105. package/src/renderers/brand.ts +0 -87
  106. package/src/renderers/chrome.ts +0 -196
  107. package/src/renderers/endpoint-labels.ts +0 -150
  108. package/src/renderers/legend.ts +0 -311
  109. package/src/renderers/marks.ts +0 -561
  110. package/src/renderers/metrics.ts +0 -63
  111. package/src/renderers/svg-dom.ts +0 -40
  112. package/src/renderers/table-cells.ts +0 -446
  113. package/src/resize-observer.ts +0 -46
  114. package/src/sankey-mount.ts +0 -622
  115. package/src/sankey-renderer.ts +0 -614
  116. package/src/series-search.ts +0 -392
  117. package/src/static.ts +0 -251
  118. package/src/story/__tests__/camera-math.test.ts +0 -145
  119. package/src/story/__tests__/create-chart-story.test.ts +0 -317
  120. package/src/story/__tests__/progress-math.test.ts +0 -95
  121. package/src/story/__tests__/scroll-driver.test.ts +0 -130
  122. package/src/story/__tests__/tween.test.ts +0 -159
  123. package/src/story/camera-math.ts +0 -125
  124. package/src/story/create-chart-story.ts +0 -353
  125. package/src/story/crossfade.ts +0 -70
  126. package/src/story/index.ts +0 -39
  127. package/src/story/progress-math.ts +0 -85
  128. package/src/story/resolve-camera-target.ts +0 -119
  129. package/src/story/scroll-driver.ts +0 -206
  130. package/src/story/story-camera.ts +0 -49
  131. package/src/story/tween.ts +0 -112
  132. package/src/story/types.ts +0 -76
  133. package/src/svg-ids.ts +0 -23
  134. package/src/svg-renderer.ts +0 -383
  135. package/src/table-keyboard.ts +0 -266
  136. package/src/table-mount.ts +0 -567
  137. package/src/table-renderer.ts +0 -414
  138. package/src/text-edit-overlay.ts +0 -255
  139. package/src/theme-tokens.ts +0 -51
  140. package/src/tilemap-mount.ts +0 -511
  141. package/src/tilemap-renderer.ts +0 -396
  142. package/src/tooltip.ts +0 -177
  143. package/src/transition.ts +0 -2816
  144. package/src/you-draw-it.ts +0 -480
  145. /package/dist/{chunk-W34KN7FD.js.map → chunk-2NAQRP66.js.map} +0 -0
@@ -1,480 +0,0 @@
1
- /**
2
- * "You draw it" interaction layer: the DOM/SVG overlay for the `youDrawIt`
3
- * spec option (NYT-style draw-then-reveal engagement format).
4
- *
5
- * SVG-space elements (hatched drawing region, reader's guess path, reveal
6
- * clip rect, pointer-capture overlay) render inside the chart's own SVG so
7
- * they clip and scale with it. The prompt text and skip-to-reveal button are
8
- * a small HTML overlay positioned over the drawing region, following the
9
- * series-search precedent (`series-search.ts`): a native `<button>` gets
10
- * keyboard semantics for free instead of hand-rolling SVG focus handling.
11
- *
12
- * State (the reader's in-progress guess) lives in this module's closure,
13
- * matching mount.ts's per-instance-closure convention (StrictMode double-
14
- * mount safe): a fresh `createYouDrawIt()` call gets a fresh closure.
15
- */
16
-
17
- import type { Point, ResolvedYouDrawIt } from '@opendata-ai/openchart-core';
18
- import { createSVGElement, SVG_NS, setAttrs } from './renderers/svg-dom';
19
- import { nextSvgId } from './svg-ids';
20
-
21
- export interface YouDrawItOptions {
22
- /** The chart container (`.oc-root`). Must be position: relative. */
23
- container: HTMLElement;
24
- /** Fired once the drawing is revealed, with the guess in data coordinates ordered by x. */
25
- onReveal?: (guess: Array<{ x: string | number; y: number }>) => void;
26
- }
27
-
28
- export interface YouDrawItController {
29
- /** Reposition, resync geometry, and (re)wire pointer capture against a freshly rendered layout + SVG. */
30
- update(config: ResolvedYouDrawIt, svg: SVGSVGElement): void;
31
- /** Hide (spec no longer wants youDrawIt on this render, e.g. mark type changed). */
32
- hide(): void;
33
- /** Reveal the real line and fire onReveal, without requiring reader interaction (skip-to-reveal). */
34
- reveal(): void;
35
- /** Clear the reader's guess and return to the drawing state. */
36
- reset(): void;
37
- /** Whether the drawing has been revealed. */
38
- readonly isRevealed: boolean;
39
- /** Remove all DOM elements. */
40
- destroy(): void;
41
- }
42
-
43
- /** Minimum touch target size (effective hit area), per WCAG 2.5.5 / mobile a11y conventions. */
44
- const MIN_TOUCH_TARGET = 24;
45
-
46
- /** Build the "M x,y L x,y ..." path string for a straight-segment line through points, sorted by x. */
47
- function buildLinearPath(points: Point[]): string {
48
- if (points.length === 0) return '';
49
- const sorted = [...points].sort((a, b) => a.x - b.x);
50
- return sorted.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ');
51
- }
52
-
53
- /**
54
- * Create the you-draw-it control. Mounted once per chart instance and kept
55
- * across re-renders so the in-progress drawing survives; `update()` re-syncs
56
- * geometry and re-wires pointer capture after each render.
57
- */
58
- export function createYouDrawIt(options: YouDrawItOptions): YouDrawItController {
59
- const { container, onReveal } = options;
60
-
61
- let destroyed = false;
62
- let revealed = false;
63
- let config: ResolvedYouDrawIt | null = null;
64
- let svgEl: SVGSVGElement | null = null;
65
- /** Reader's guess: pixel y keyed by pixel x sample. */
66
- const guessByX = new Map<number, number>();
67
- let cleanupPointerEvents: (() => void) | null = null;
68
-
69
- // ---------------------------------------------------------------------------
70
- // SVG elements (rebuilt each update() since the SVG itself is rebuilt on render)
71
- // ---------------------------------------------------------------------------
72
-
73
- function buildHatchPattern(id: string, color: string): SVGElement {
74
- const pattern = document.createElementNS(SVG_NS, 'pattern');
75
- pattern.setAttribute('id', id);
76
- pattern.setAttribute('patternUnits', 'userSpaceOnUse');
77
- pattern.setAttribute('width', '8');
78
- pattern.setAttribute('height', '8');
79
- pattern.setAttribute('patternTransform', 'rotate(45)');
80
- const line = document.createElementNS(SVG_NS, 'line');
81
- setAttrs(line, { x1: 0, y1: 0, x2: 0, y2: 8, stroke: color, 'stroke-width': 1 });
82
- line.setAttribute('stroke-opacity', '0.5');
83
- pattern.appendChild(line);
84
- return pattern;
85
- }
86
-
87
- /** Locate the target line's <path> in the freshly rendered SVG. */
88
- function findTargetLinePath(svg: SVGSVGElement, seriesKey?: string): SVGPathElement | null {
89
- // Line marks render as <g data-mark-id="line-{seriesKey ?? index}"> with a
90
- // single <path> child (see renderers/marks.ts). Prefer the seriesKey match;
91
- // fall back to the first line mark for single-series charts (no color enc).
92
- if (seriesKey) {
93
- const escaped =
94
- typeof CSS !== 'undefined' && typeof CSS.escape === 'function'
95
- ? CSS.escape(seriesKey)
96
- : seriesKey.replace(/"/g, '\\"');
97
- const byKey = svg.querySelector<SVGPathElement>(`[data-mark-id="line-${escaped}"] path`);
98
- if (byKey) return byKey;
99
- }
100
- return svg.querySelector<SVGPathElement>('.oc-mark-line path');
101
- }
102
-
103
- function render(cfg: ResolvedYouDrawIt, svg: SVGSVGElement): void {
104
- // Remove any previous you-draw-it group (SVG is rebuilt each render, but
105
- // defensive against re-entrant calls).
106
- svg.querySelector('[data-you-draw-it]')?.remove();
107
-
108
- const group = createSVGElement('g') as SVGGElement;
109
- group.setAttribute('data-you-draw-it', 'true');
110
- group.setAttribute('class', 'oc-ydi');
111
-
112
- const { area, fromX } = cfg;
113
- const regionWidth = Math.max(0, area.x + area.width - fromX);
114
-
115
- // Hatch pattern + reveal clip defs.
116
- const defs = createSVGElement('defs');
117
- const patternId = nextSvgId('oc-ydi-hatch');
118
- defs.appendChild(buildHatchPattern(patternId, cfg.lineColor));
119
-
120
- // Reveal clip: masks the real line's post-from segment until reveal.
121
- // Applied to the target line path element itself (not a <g>), matching
122
- // the SVG clip-path gotcha in .claude/rules/svg-animation.md.
123
- const clipId = nextSvgId('oc-ydi-clip');
124
- const clipPath = createSVGElement('clipPath');
125
- clipPath.setAttribute('id', clipId);
126
- const clipRect = createSVGElement('rect');
127
- setAttrs(clipRect, {
128
- x: area.x,
129
- y: area.y,
130
- width: revealed ? area.width : Math.max(0, fromX - area.x),
131
- height: area.height,
132
- });
133
- clipRect.setAttribute('data-ydi-clip-rect', 'true');
134
- clipRect.setAttribute('class', 'oc-ydi-clip-rect');
135
- clipPath.appendChild(clipRect);
136
- defs.appendChild(clipPath);
137
- group.appendChild(defs);
138
-
139
- // Hatched "draw here" region.
140
- const region = createSVGElement('rect');
141
- setAttrs(region, {
142
- x: fromX,
143
- y: area.y,
144
- width: regionWidth,
145
- height: area.height,
146
- fill: `url(#${patternId})`,
147
- });
148
- region.setAttribute('class', 'oc-ydi-region');
149
- region.setAttribute('data-ydi-region', 'true');
150
- region.setAttribute('pointer-events', 'none');
151
- if (revealed) region.setAttribute('data-ydi-hidden', 'true');
152
- group.appendChild(region);
153
-
154
- // "from" boundary marker: a thin dashed rule where drawing begins.
155
- const boundary = createSVGElement('line');
156
- setAttrs(boundary, { x1: fromX, y1: area.y, x2: fromX, y2: area.y + area.height });
157
- boundary.setAttribute('class', 'oc-ydi-boundary');
158
- boundary.setAttribute('pointer-events', 'none');
159
- group.appendChild(boundary);
160
-
161
- const targetLineEl = findTargetLinePath(svg, cfg.targetSeriesKey);
162
- if (targetLineEl) {
163
- targetLineEl.setAttribute('clip-path', `url(#${clipId})`);
164
- }
165
-
166
- // Optional comparison line (host-supplied "everyone else's guess").
167
- if (cfg.comparisonPoints && cfg.comparisonPoints.length > 0) {
168
- const compPath = createSVGElement('path');
169
- setAttrs(compPath, { d: buildLinearPath(cfg.comparisonPoints), fill: 'none' });
170
- compPath.setAttribute('class', 'oc-ydi-comparison');
171
- compPath.setAttribute('pointer-events', 'none');
172
- group.appendChild(compPath);
173
- }
174
-
175
- // Reader's guess path (pen style), populated as the reader draws.
176
- const guessPath = createSVGElement('path');
177
- setAttrs(guessPath, { d: '', fill: 'none' });
178
- guessPath.setAttribute('class', 'oc-ydi-guess');
179
- guessPath.setAttribute('data-ydi-guess-path', 'true');
180
- guessPath.setAttribute('pointer-events', 'none');
181
- group.appendChild(guessPath);
182
-
183
- // Pointer-capture overlay over the drawing region only.
184
- if (!revealed) {
185
- const overlay = createSVGElement('rect');
186
- setAttrs(overlay, {
187
- x: fromX,
188
- y: area.y,
189
- width: regionWidth,
190
- height: area.height,
191
- fill: 'transparent',
192
- });
193
- overlay.setAttribute('class', 'oc-ydi-overlay');
194
- overlay.setAttribute('data-ydi-overlay', 'true');
195
- overlay.setAttribute('role', 'img');
196
- overlay.setAttribute(
197
- 'aria-label',
198
- 'Drawing area: drag to sketch your guess of the trend, or use the reveal button to skip.',
199
- );
200
- overlay.style.touchAction = 'none';
201
- overlay.style.cursor = 'crosshair';
202
- group.appendChild(overlay);
203
- }
204
-
205
- svg.appendChild(group);
206
- }
207
-
208
- function redrawGuessPath(): void {
209
- if (!svgEl) return;
210
- const path = svgEl.querySelector<SVGPathElement>('[data-ydi-guess-path]');
211
- if (!path) return;
212
- const points: Point[] = Array.from(guessByX.entries()).map(([x, y]) => ({ x, y }));
213
- path.setAttribute('d', buildLinearPath(points));
214
- }
215
-
216
- function snapToNearestSample(px: number): number | null {
217
- if (!config || config.samples.length === 0) return null;
218
- let nearestPx = config.samples[0].px;
219
- let best = Math.abs(nearestPx - px);
220
- for (const s of config.samples) {
221
- const d = Math.abs(s.px - px);
222
- if (d < best) {
223
- best = d;
224
- nearestPx = s.px;
225
- }
226
- }
227
- return nearestPx;
228
- }
229
-
230
- function clampY(py: number): number {
231
- if (!config) return py;
232
- return Math.min(config.area.y + config.area.height, Math.max(config.area.y, py));
233
- }
234
-
235
- // ---------------------------------------------------------------------------
236
- // Pointer capture (mouse + touch), following the crosshair toSvgCoords pattern
237
- // ---------------------------------------------------------------------------
238
-
239
- function wirePointerEvents(svg: SVGSVGElement): () => void {
240
- const overlay = svg.querySelector('[data-ydi-overlay]');
241
- if (!overlay) return () => {};
242
-
243
- let dragging = false;
244
-
245
- const toSvgCoords = (clientX: number, clientY: number) => {
246
- const svgRect = svg.getBoundingClientRect();
247
- const viewBox = svg.viewBox?.baseVal;
248
- const scaleX = viewBox?.width && svgRect.width ? viewBox.width / svgRect.width : 1;
249
- const scaleY = viewBox?.height && svgRect.height ? viewBox.height / svgRect.height : 1;
250
- return {
251
- svgX: (clientX - svgRect.left) * scaleX,
252
- svgY: (clientY - svgRect.top) * scaleY,
253
- };
254
- };
255
-
256
- const paintAt = (clientX: number, clientY: number) => {
257
- const { svgX, svgY } = toSvgCoords(clientX, clientY);
258
- const snapped = snapToNearestSample(svgX);
259
- if (snapped === null) return;
260
- guessByX.set(snapped, clampY(svgY));
261
- redrawGuessPath();
262
- };
263
-
264
- const handleMouseDown = (e: Event) => {
265
- const me = e as MouseEvent;
266
- dragging = true;
267
- paintAt(me.clientX, me.clientY);
268
- };
269
- const handleMouseMove = (e: Event) => {
270
- if (!dragging) return;
271
- const me = e as MouseEvent;
272
- paintAt(me.clientX, me.clientY);
273
- };
274
- const handleMouseUp = () => {
275
- dragging = false;
276
- };
277
-
278
- const handleTouchStart = (e: Event) => {
279
- const te = e as TouchEvent;
280
- if (te.touches.length === 0) return;
281
- if (te.cancelable) te.preventDefault();
282
- dragging = true;
283
- paintAt(te.touches[0].clientX, te.touches[0].clientY);
284
- };
285
- const handleTouchMove = (e: Event) => {
286
- if (!dragging) return;
287
- const te = e as TouchEvent;
288
- if (te.touches.length === 0) return;
289
- if (te.cancelable) te.preventDefault();
290
- paintAt(te.touches[0].clientX, te.touches[0].clientY);
291
- };
292
- const handleTouchEnd = () => {
293
- dragging = false;
294
- };
295
-
296
- overlay.addEventListener('mousedown', handleMouseDown);
297
- document.addEventListener('mousemove', handleMouseMove);
298
- document.addEventListener('mouseup', handleMouseUp);
299
- overlay.addEventListener('touchstart', handleTouchStart, { passive: false });
300
- overlay.addEventListener('touchmove', handleTouchMove, { passive: false });
301
- overlay.addEventListener('touchend', handleTouchEnd);
302
- overlay.addEventListener('touchcancel', handleTouchEnd);
303
-
304
- return () => {
305
- overlay.removeEventListener('mousedown', handleMouseDown);
306
- document.removeEventListener('mousemove', handleMouseMove);
307
- document.removeEventListener('mouseup', handleMouseUp);
308
- overlay.removeEventListener('touchstart', handleTouchStart);
309
- overlay.removeEventListener('touchmove', handleTouchMove);
310
- overlay.removeEventListener('touchend', handleTouchEnd);
311
- overlay.removeEventListener('touchcancel', handleTouchEnd);
312
- };
313
- }
314
-
315
- // ---------------------------------------------------------------------------
316
- // Prompt + reveal button (HTML overlay, positioned over the drawing region)
317
- // ---------------------------------------------------------------------------
318
-
319
- const root = document.createElement('div');
320
- root.className = 'oc-ydi-controls';
321
- root.style.display = 'none';
322
- root.style.position = 'absolute';
323
-
324
- const prompt = document.createElement('div');
325
- prompt.className = 'oc-ydi-prompt';
326
-
327
- const revealButton = document.createElement('button');
328
- revealButton.type = 'button';
329
- revealButton.className = 'oc-ydi-reveal-button';
330
-
331
- root.append(prompt, revealButton);
332
- container.style.position = container.style.position || 'relative';
333
- container.appendChild(root);
334
-
335
- function reduceMotion(): boolean {
336
- return (
337
- typeof window !== 'undefined' &&
338
- !!window.matchMedia &&
339
- window.matchMedia('(prefers-reduced-motion: reduce)').matches
340
- );
341
- }
342
-
343
- /**
344
- * Map a drawn pixel y back to a data value via the linear yInvert anchors.
345
- *
346
- * This interpolates linearly in pixel space between the top and bottom
347
- * anchors. For a linear y-scale that is exact. For a log or pow scale it is
348
- * an approximation: the true inverse is curved, so a guess drawn halfway up
349
- * the plot reads back as the arithmetic midpoint of the domain rather than
350
- * the geometric (log) or power midpoint. The you-draw-it guess is a rough
351
- * "where did the reader think the line went" signal, not a precise readout,
352
- * so the linear approximation is acceptable here; revisit if a non-linear
353
- * scale ever needs an exact guess value.
354
- */
355
- function pixelYToData(py: number): number {
356
- if (!config) return py;
357
- const inv = config.yInvert;
358
- if (!inv) {
359
- // No invertible scale: report the pixel y normalized to the area (1 at
360
- // top, 0 at bottom) so callers still get relative shape.
361
- const area = config.area;
362
- return 1 - (py - area.y) / (area.height || 1);
363
- }
364
- const span = inv.bottomPixel - inv.topPixel;
365
- if (span === 0) return inv.topData;
366
- const t = (py - inv.topPixel) / span;
367
- return inv.topData + t * (inv.bottomData - inv.topData);
368
- }
369
-
370
- function getGuessData(): Array<{ x: string | number; y: number }> {
371
- if (!config) return [];
372
- const valueByPx = new Map(config.samples.map((s) => [s.px, s.xValue]));
373
- return Array.from(guessByX.entries())
374
- .sort((a, b) => a[0] - b[0])
375
- .map(([px, py]) => ({ x: valueByPx.get(px) ?? px, y: pixelYToData(py) }));
376
- }
377
-
378
- function doReveal(): void {
379
- if (destroyed || revealed || !svgEl || !config) return;
380
- revealed = true;
381
-
382
- const clipRect = svgEl.querySelector<SVGRectElement>('[data-ydi-clip-rect]');
383
- if (clipRect) {
384
- if (reduceMotion()) {
385
- clipRect.setAttribute('width', String(config.area.width));
386
- } else {
387
- clipRect.classList.add('oc-ydi-clip-animate');
388
- // Force layout so the transition on the width change is observed. The
389
- // update-transition rAF driver only tracks marks, so a scoped CSS
390
- // transition on the clip rect is the plan's accepted fallback.
391
- void clipRect.getBoundingClientRect();
392
- clipRect.setAttribute('width', String(config.area.width));
393
- }
394
- }
395
- const region = svgEl.querySelector<SVGRectElement>('[data-ydi-region]');
396
- region?.setAttribute('data-ydi-hidden', 'true');
397
- svgEl.querySelector('[data-ydi-overlay]')?.remove();
398
- cleanupPointerEvents?.();
399
- cleanupPointerEvents = null;
400
- root.classList.add('oc-ydi-revealed');
401
- prompt.textContent = '';
402
- revealButton.disabled = true;
403
-
404
- onReveal?.(getGuessData());
405
- }
406
-
407
- revealButton.addEventListener('click', doReveal);
408
-
409
- return {
410
- update(cfg: ResolvedYouDrawIt, svg: SVGSVGElement): void {
411
- if (destroyed) return;
412
- cleanupPointerEvents?.();
413
- cleanupPointerEvents = null;
414
-
415
- config = cfg;
416
- svgEl = svg;
417
-
418
- render(cfg, svg);
419
- redrawGuessPath();
420
-
421
- prompt.textContent = revealed ? '' : cfg.prompt;
422
- revealButton.textContent = cfg.revealLabel;
423
- revealButton.setAttribute('aria-label', cfg.revealLabel);
424
- revealButton.style.minHeight = `${MIN_TOUCH_TARGET}px`;
425
- revealButton.disabled = revealed;
426
- if (revealed) root.classList.add('oc-ydi-revealed');
427
- else root.classList.remove('oc-ydi-revealed');
428
-
429
- // Position the HTML controls over the drawing region. Same viewBox-scale
430
- // approach as series-search / the text edit overlay.
431
- const viewBox = svg.viewBox?.baseVal;
432
- const svgRect = svg.getBoundingClientRect();
433
- const containerRect = container.getBoundingClientRect();
434
- const scaleX = viewBox?.width && svgRect.width ? svgRect.width / viewBox.width : 1;
435
- const scaleY = viewBox?.height && svgRect.height ? svgRect.height / viewBox.height : 1;
436
- const regionWidth = Math.max(0, cfg.area.x + cfg.area.width - cfg.fromX);
437
- root.style.left = `${cfg.fromX * scaleX + (svgRect.left - containerRect.left)}px`;
438
- root.style.top = `${cfg.area.y * scaleY + (svgRect.top - containerRect.top)}px`;
439
- root.style.width = `${regionWidth * scaleX}px`;
440
- root.style.height = `${cfg.area.height * scaleY}px`;
441
- root.style.display = 'flex';
442
-
443
- if (!revealed) {
444
- cleanupPointerEvents = wirePointerEvents(svg);
445
- }
446
- },
447
- hide(): void {
448
- root.style.display = 'none';
449
- svgEl?.querySelector('[data-you-draw-it]')?.remove();
450
- cleanupPointerEvents?.();
451
- cleanupPointerEvents = null;
452
- },
453
- reveal(): void {
454
- doReveal();
455
- },
456
- reset(): void {
457
- if (destroyed) return;
458
- revealed = false;
459
- guessByX.clear();
460
- revealButton.disabled = false;
461
- root.classList.remove('oc-ydi-revealed');
462
- if (config && svgEl) {
463
- render(config, svgEl);
464
- prompt.textContent = config.prompt;
465
- cleanupPointerEvents?.();
466
- cleanupPointerEvents = wirePointerEvents(svgEl);
467
- }
468
- },
469
- get isRevealed(): boolean {
470
- return revealed;
471
- },
472
- destroy(): void {
473
- if (destroyed) return;
474
- destroyed = true;
475
- cleanupPointerEvents?.();
476
- cleanupPointerEvents = null;
477
- root.remove();
478
- },
479
- };
480
- }