swiftplot 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +327 -2
  3. package/dist/chart.d.ts +3 -0
  4. package/dist/chart.js +1226 -0
  5. package/dist/charts/controller.d.ts +32 -0
  6. package/dist/charts/controller.js +231 -0
  7. package/dist/charts/defaults.d.ts +12 -0
  8. package/dist/charts/defaults.js +60 -0
  9. package/dist/charts/fields.d.ts +34 -0
  10. package/dist/charts/fields.js +167 -0
  11. package/dist/charts/index.d.ts +6 -0
  12. package/dist/charts/index.js +3 -0
  13. package/dist/charts/mount.d.ts +5 -0
  14. package/dist/charts/mount.js +21 -0
  15. package/dist/charts/source.d.ts +24 -0
  16. package/dist/charts/source.js +225 -0
  17. package/dist/charts/types.d.ts +104 -0
  18. package/dist/charts/types.js +1 -0
  19. package/dist/charts/xy.d.ts +36 -0
  20. package/dist/charts/xy.js +220 -0
  21. package/dist/features/animate.d.ts +11 -0
  22. package/dist/features/animate.js +118 -0
  23. package/dist/features/brush.d.ts +13 -0
  24. package/dist/features/brush.js +127 -0
  25. package/dist/features/legend.d.ts +15 -0
  26. package/dist/features/legend.js +237 -0
  27. package/dist/features/pointer.d.ts +29 -0
  28. package/dist/features/pointer.js +23 -0
  29. package/dist/features/tooltip.d.ts +14 -0
  30. package/dist/features/tooltip.js +190 -0
  31. package/dist/features/zoom.d.ts +13 -0
  32. package/dist/features/zoom.js +228 -0
  33. package/dist/gl.d.ts +5 -0
  34. package/dist/gl.js +52 -0
  35. package/dist/index.d.ts +60 -0
  36. package/dist/index.js +31 -0
  37. package/dist/marks/arcs.d.ts +25 -0
  38. package/dist/marks/arcs.js +124 -0
  39. package/dist/marks/area.d.ts +24 -0
  40. package/dist/marks/area.js +106 -0
  41. package/dist/marks/bar.d.ts +44 -0
  42. package/dist/marks/bar.js +243 -0
  43. package/dist/marks/box.d.ts +27 -0
  44. package/dist/marks/box.js +188 -0
  45. package/dist/marks/common.d.ts +84 -0
  46. package/dist/marks/common.js +236 -0
  47. package/dist/marks/dots.d.ts +15 -0
  48. package/dist/marks/dots.js +156 -0
  49. package/dist/marks/errorBars.d.ts +19 -0
  50. package/dist/marks/errorBars.js +79 -0
  51. package/dist/marks/funnel.d.ts +25 -0
  52. package/dist/marks/funnel.js +121 -0
  53. package/dist/marks/heatmap.d.ts +19 -0
  54. package/dist/marks/heatmap.js +139 -0
  55. package/dist/marks/line.d.ts +19 -0
  56. package/dist/marks/line.js +75 -0
  57. package/dist/marks/radar.d.ts +22 -0
  58. package/dist/marks/radar.js +155 -0
  59. package/dist/marks/radialBars.d.ts +27 -0
  60. package/dist/marks/radialBars.js +111 -0
  61. package/dist/marks/rects.d.ts +43 -0
  62. package/dist/marks/rects.js +120 -0
  63. package/dist/marks/rule.d.ts +28 -0
  64. package/dist/marks/rule.js +80 -0
  65. package/dist/marks/sankey.d.ts +41 -0
  66. package/dist/marks/sankey.js +366 -0
  67. package/dist/marks/sunburst.d.ts +26 -0
  68. package/dist/marks/sunburst.js +185 -0
  69. package/dist/marks/ticks.d.ts +9 -0
  70. package/dist/marks/ticks.js +26 -0
  71. package/dist/marks/tree.d.ts +41 -0
  72. package/dist/marks/tree.js +110 -0
  73. package/dist/marks/treemap.d.ts +25 -0
  74. package/dist/marks/treemap.js +159 -0
  75. package/dist/paint.d.ts +30 -0
  76. package/dist/paint.js +66 -0
  77. package/dist/scale.d.ts +16 -0
  78. package/dist/scale.js +96 -0
  79. package/dist/scales/band.d.ts +9 -0
  80. package/dist/scales/band.js +23 -0
  81. package/dist/scales/bare.d.ts +3 -0
  82. package/dist/scales/bare.js +7 -0
  83. package/dist/scales/color.d.ts +18 -0
  84. package/dist/scales/color.js +21 -0
  85. package/dist/scales/log.d.ts +20 -0
  86. package/dist/scales/log.js +97 -0
  87. package/dist/scales/time.d.ts +30 -0
  88. package/dist/scales/time.js +181 -0
  89. package/dist/theme.d.ts +10 -0
  90. package/dist/theme.js +8 -0
  91. package/dist/transforms.d.ts +43 -0
  92. package/dist/transforms.js +118 -0
  93. package/dist/types.d.ts +434 -0
  94. package/dist/types.js +1 -0
  95. package/package.json +39 -3
package/dist/chart.js ADDED
@@ -0,0 +1,1226 @@
1
+ import { locate, position } from './features/pointer.js';
2
+ import { upTo } from './marks/common.js';
3
+ import { extent, scale } from './scale.js';
4
+ import { light } from './theme.js';
5
+ export const NEAREST_PX = 20;
6
+ // What an update of these alone leaves alone: a tip held by a tap stays.
7
+ const LIGHT = new Set(['pointer', 'onClick', 'onPointerChange', 'onViewChange', 'onHiddenChange']);
8
+ // ponytail: measured crossover is somewhere between 10k and 100k points; tune per device if it matters.
9
+ const GL_FROM = 10_000;
10
+ const same = (a, b) => {
11
+ const keys = Object.keys(a);
12
+ return (keys.length === Object.keys(b).length &&
13
+ keys.every(k => Object.hasOwn(b, k) && a[k] === b[k]));
14
+ };
15
+ const resolve = (a, of, room) => {
16
+ if (a.scale)
17
+ return a.scale(a, of, room);
18
+ const s = scale(a.domain, typeof a.domain === 'string' ? of() : a.domain, room, a);
19
+ return { ...s, ticks: s.ticks.map(value => ({ value, label: (a.format ?? String)(value) })) };
20
+ };
21
+ const AUTO = { domain: 'nice', label: '' };
22
+ const NONE = { domain: [0, 1], label: '', scale: () => ({ lo: 0, hi: 1, ticks: [] }) };
23
+ const bare = (o) => o.frame === 'polar' || o.frame === 'blank';
24
+ const axisOf = (o, which) => (bare(o) ? NONE : (o[which] ?? AUTO));
25
+ const sameAxis = (a, b) => same({ ...a, domain: String(a.domain) }, { ...b, domain: String(b.domain) });
26
+ const within = (want, [lo, hi], least = (hi - lo) * 1e-6) => {
27
+ if (!want)
28
+ return undefined;
29
+ let [a, b] = want;
30
+ if (!(a <= b) || !Number.isFinite(a) || !Number.isFinite(b))
31
+ return undefined;
32
+ const w = Math.max(b - a, least);
33
+ if (w >= hi - lo)
34
+ return [lo, hi];
35
+ const narrow = b - a < least;
36
+ if (narrow)
37
+ a = (a + b) / 2 - w / 2;
38
+ const s = !(a >= lo) ? [lo, lo + w] : a + w > hi ? [hi - w, hi] : narrow ? [a, a + w] : [a, b];
39
+ // Far from zero the floor can be below one float step, so the edges round together.
40
+ const step = Math.max(-lo, hi) * Number.EPSILON * 4;
41
+ return s[0] < s[1] || least >= step ? s : within(want, [lo, hi], step);
42
+ };
43
+ const clamp = (want, [p, q]) => {
44
+ if (p <= q)
45
+ return within(want, [p, q]);
46
+ const s = within(want && [Math.min(...want), Math.max(...want)], [q, p]);
47
+ return s && [s[1], s[0]];
48
+ };
49
+ export function plot(el, options) {
50
+ let o = options;
51
+ let dpr = devicePixelRatio;
52
+ const root = document.createElement('div');
53
+ const font = '12px system-ui,sans-serif';
54
+ root.style.cssText = `position:relative;font:${font};pointer-events:auto`;
55
+ const widths = new Map();
56
+ let pen;
57
+ const textWidth = (s) => {
58
+ let w = widths.get(s);
59
+ if (w === undefined) {
60
+ pen ??= Object.assign(document.createElement('canvas').getContext('2d'), { font });
61
+ widths.set(s, (w = pen.measureText(s).width));
62
+ }
63
+ return w;
64
+ };
65
+ const layer = (tag, css = '') => {
66
+ const e = document.createElement(tag);
67
+ e.style.cssText = `position:absolute;pointer-events:none;${css}`;
68
+ return root.appendChild(e);
69
+ };
70
+ const canvas = layer('canvas', 'left:0;top:0');
71
+ const ctx = canvas.getContext('2d');
72
+ const axes = layer('div', 'inset:0');
73
+ canvas.setAttribute('role', 'img');
74
+ axes.ariaHidden = 'true';
75
+ let glCanvas;
76
+ let gl;
77
+ let makeGl;
78
+ let W = -1;
79
+ let H = -1;
80
+ let marks = o.marks;
81
+ const idOf = (k) => k.group ?? k.label;
82
+ const sameIds = (a = [], b = []) => {
83
+ const of = new Set(a);
84
+ const to = new Set(b);
85
+ return of.size === to.size && [...of].every(id => to.has(id));
86
+ };
87
+ let hiddenIds = [...(o.hidden ?? [])];
88
+ // What arranged marks are drawn as, kept while the shown members of their key stay the same.
89
+ let laid = new Map();
90
+ let declared = new Map();
91
+ const arrange = (shown, kept = new Map()) => {
92
+ const next = new Map();
93
+ for (const k of shown) {
94
+ if (!k.arrange)
95
+ continue;
96
+ const g = next.get(k.arrange.key);
97
+ if (g)
98
+ g.members.push(k);
99
+ else
100
+ next.set(k.arrange.key, { members: [k], drawn: [] });
101
+ }
102
+ for (const [key, g] of next) {
103
+ const was = kept.get(key);
104
+ g.drawn =
105
+ was && was.members.length === g.members.length && was.members.every((k, i) => k === g.members[i])
106
+ ? was.drawn
107
+ : g.members[0].arrange.lay(g.members);
108
+ }
109
+ const taken = new Map();
110
+ const list = shown.map(k => {
111
+ const g = k.arrange && next.get(k.arrange.key);
112
+ if (!g)
113
+ return k;
114
+ const i = taken.get(k.arrange.key) ?? 0;
115
+ taken.set(k.arrange.key, i + 1);
116
+ return g.drawn[i];
117
+ });
118
+ return { list, next };
119
+ };
120
+ const showing = () => {
121
+ const hidden = new Set(hiddenIds);
122
+ const shown = hidden.size ? marks.filter(k => !hidden.has(idOf(k))) : marks;
123
+ const { list, next } = arrange(shown, laid);
124
+ let relaid = false;
125
+ const drawn = new Set([...next.values()].flatMap(g => g.drawn));
126
+ for (const [key, g] of laid) {
127
+ const now = next.get(key);
128
+ g.drawn.forEach((d, i) => {
129
+ if (drawn.has(d))
130
+ return;
131
+ relaid = true;
132
+ drop(d);
133
+ // The mark that now draws the same member, or the member its update replaced, moves from this one.
134
+ const member = g.members[i];
135
+ let nth = g.members.slice(0, i).filter(k => k === member).length;
136
+ const j = now?.members.findIndex(k => (k === member || replaced.get(k) === member) && nth-- === 0) ?? -1;
137
+ const to = j < 0 ? undefined : now.drawn[j];
138
+ if (!to)
139
+ return;
140
+ replaced.set(to, d);
141
+ if (focusedRow?.mark === d)
142
+ focusedRow = { ...focusedRow, mark: to };
143
+ });
144
+ }
145
+ laid = next;
146
+ declared = new Map([...next.values()].flatMap(g => g.drawn.map((d, i) => [d, g.members[i]])));
147
+ visible = list;
148
+ return relaid;
149
+ };
150
+ let visible = [];
151
+ // Every arranged mark laid out with none hidden, for an axis that fits them all.
152
+ let everyLaid;
153
+ const every = () => (everyLaid ??= marks.some(k => k.arrange) ? arrange(marks, laid).list : marks);
154
+ const reshow = () => {
155
+ const relaid = showing();
156
+ delete extents.x;
157
+ delete extents.y;
158
+ scanned = undefined;
159
+ return relaid;
160
+ };
161
+ let xs;
162
+ let ys;
163
+ let view;
164
+ let viewKey = '';
165
+ let axesKey = '';
166
+ let cache = new Map();
167
+ let flat = [];
168
+ let onGl = [];
169
+ // What holds buffers on the layer: a mark keeps them while hidden or moved to the canvas, until released.
170
+ const placed = new Set();
171
+ let focused = null;
172
+ let m = { top: 0, right: 0, bottom: 0, left: 0 };
173
+ let above;
174
+ let replaced = new Map();
175
+ let paired = true;
176
+ let morphs = [];
177
+ // A kept mark may be part-way through a move that the next list of morphs no longer covers.
178
+ const settle = () => {
179
+ for (const p of morphs)
180
+ p.morph(1);
181
+ morphs = [];
182
+ };
183
+ const drop = (k) => {
184
+ // Before any release: finishing a move may still need what release() frees.
185
+ settle();
186
+ cache.delete(k);
187
+ k.release?.(gl ?? null);
188
+ placed.delete(k);
189
+ };
190
+ let drawable = false;
191
+ const fit = (c) => {
192
+ c.width = Math.round(W * dpr);
193
+ c.height = Math.round(H * dpr);
194
+ c.style.width = `${W}px`;
195
+ c.style.height = `${H}px`;
196
+ };
197
+ const measure = () => {
198
+ root.style.width = o.width === undefined ? '100%' : `${o.width}px`;
199
+ root.style.height = o.height === undefined ? '100%' : `${o.height}px`;
200
+ const w = o.width ?? root.clientWidth;
201
+ const h = o.height ?? root.clientHeight;
202
+ if (w === W && h === H)
203
+ return false;
204
+ W = w;
205
+ H = h;
206
+ fit(canvas);
207
+ if (glCanvas)
208
+ fit(glCanvas);
209
+ return true;
210
+ };
211
+ // What a reveal has uncovered at a progress, in CSS pixels: the one shape the canvas clip, the
212
+ // WebGL clip and the labels all follow.
213
+ const overhang = () => visible.reduce((most, k) => Math.max(most, k.overhang ?? 0), 0);
214
+ const revealed = (t, over = overhang()) => {
215
+ const [l, top, w, h] = [m.left, m.top, W - m.left - m.right, H - m.top - m.bottom];
216
+ if (t >= 1 || o.frame !== 'polar') {
217
+ const [across, down] = visible.some(k => k.reveal === 'down')
218
+ ? [1, Math.min(t, 1)]
219
+ : [Math.min(t, 1), 1];
220
+ // The edge a reveal is moving stays where it is; the others let a mark overhang them.
221
+ const [x0, y0] = [Math.max(l - over, 0), Math.max(top - over, 0)];
222
+ const x1 = across < 1 ? l + w * across : Math.min(l + w + over, W);
223
+ const y1 = down < 1 ? top + h * down : Math.min(top + h + over, H);
224
+ return [
225
+ [x0, y0],
226
+ [x1, y0],
227
+ [x1, y1],
228
+ [x0, y1],
229
+ ];
230
+ }
231
+ // The centre, twelve o'clock, each corner of the rectangle the sweep has passed, and where
232
+ // its leading ray leaves the rectangle.
233
+ const [cx, cy] = [l + w / 2, top + h / 2];
234
+ const ray = (turn) => {
235
+ const [dx, dy] = [Math.sin(turn * 2 * Math.PI), -Math.cos(turn * 2 * Math.PI)];
236
+ const far = Math.min(w / 2 / Math.abs(dx || 1e-9), h / 2 / Math.abs(dy || 1e-9));
237
+ return [cx + dx * far, cy + dy * far];
238
+ };
239
+ const corner = Math.atan2(w, h) / (2 * Math.PI);
240
+ const passed = [corner, 0.5 - corner, 0.5 + corner, 1 - corner].filter(turn => turn < t);
241
+ return [[cx, cy], ray(0), ...passed.map(ray), ray(t)];
242
+ };
243
+ const inside = (shape, x, y) => {
244
+ let within = false;
245
+ for (let i = 0, j = shape.length - 1; i < shape.length; j = i++) {
246
+ const [[xi, yi], [xj, yj]] = [shape[i], shape[j]];
247
+ if (yi > y !== yj > y && x < xi + ((xj - xi) * (y - yi)) / (yj - yi))
248
+ within = !within;
249
+ }
250
+ return within;
251
+ };
252
+ const cross = (a, b, c, d) => {
253
+ const side = (p, q, r) => Math.sign((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]));
254
+ return side(a, b, c) !== side(a, b, d) && side(c, d, a) !== side(c, d, b);
255
+ };
256
+ // The whole of a box is uncovered when its corners are and no edge of the outline cuts through
257
+ // it; the corners alone miss a wedge still to come that passes between them. The box is taken a
258
+ // little smaller, so that one touching the edge of the plot counts as inside it.
259
+ const uncovered = (shape, k) => {
260
+ const [l, t, r, b] = [k.l + 0.5, k.t + 0.5, k.r - 0.5, k.b - 0.5];
261
+ const corners = [
262
+ [l, t],
263
+ [r, t],
264
+ [r, b],
265
+ [l, b],
266
+ ];
267
+ return (corners.every(([x, y]) => inside(shape, x, y)) &&
268
+ !shape.some((p, i) => corners.some((q, j) => cross(p, shape[(i + 1) % shape.length], q, corners[(j + 1) % 4]))));
269
+ };
270
+ let notes;
271
+ let noted = '[]';
272
+ let boxes = [];
273
+ const annotate = () => {
274
+ // In the order of the marks, whichever layer each is drawn on: that order settles a tie.
275
+ const wanted = [...new Set(visible)].flatMap(k => cache.get(k)?.p.labels ?? []);
276
+ const kept = [];
277
+ for (const label of wanted.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))) {
278
+ const [x, y, w] = [label.x / dpr, label.y / dpr, label.text.length * 7];
279
+ const l = label.align === 'start' ? x : label.align === 'end' ? x - w : x - w / 2;
280
+ const box = { l, t: y - 8, r: l + w, b: y + 8, text: label.text, color: label.color };
281
+ if (box.l < 0 || box.t < 0 || box.r > W || box.b > H)
282
+ continue;
283
+ if (kept.some(k => box.l < k.r && k.l < box.r && box.t < k.b && k.t < box.b))
284
+ continue;
285
+ kept.push(box);
286
+ }
287
+ const key = JSON.stringify(kept);
288
+ if (key === noted)
289
+ return;
290
+ noted = key;
291
+ boxes = kept.map(k => {
292
+ const el = document.createElement('div');
293
+ el.textContent = k.text;
294
+ el.style.cssText = `position:absolute;white-space:nowrap;line-height:16px;left:${k.l}px;top:${k.t}px;width:${k.r - k.l}px;text-align:center`;
295
+ if (k.color)
296
+ el.style.color = k.color;
297
+ return { ...k, el };
298
+ });
299
+ notes ??= layer('div', `inset:0;color:${theme().text}`);
300
+ notes.replaceChildren(...boxes.map(k => k.el));
301
+ uncover();
302
+ };
303
+ // The marks' rules, as DOM between the canvases and the axis text, in a layer made when the first one is asked for.
304
+ let lines;
305
+ let ruled = '[]';
306
+ const rule = () => {
307
+ const { left, top, width, height } = view;
308
+ const wanted = [...new Set(visible)].flatMap(k => cache.get(k)?.p.rules ?? []);
309
+ const key = JSON.stringify(wanted.length ? [wanted, left, top, width, height] : []);
310
+ if (key === ruled)
311
+ return;
312
+ ruled = key;
313
+ if (!lines) {
314
+ axes.before((lines = layer('div', 'inset:0')));
315
+ clipped = '';
316
+ }
317
+ lines.replaceChildren(...wanted.map(r => {
318
+ const e = document.createElement('div');
319
+ const w = Number(r.width) / dpr;
320
+ const along = (at, lo, size) => Math.min(Math.max(Math.round(at - r.width / 2) / dpr, lo / dpr), (lo + size) / dpr - w);
321
+ e.style.cssText =
322
+ r.y === undefined
323
+ ? `position:absolute;top:${top / dpr}px;height:${height / dpr}px;width:0;left:${along(r.x, left, width)}px`
324
+ : `position:absolute;left:${left / dpr}px;width:${width / dpr}px;height:0;top:${along(r.y, top, height)}px`;
325
+ const side = r.y === undefined ? 'Left' : 'Top';
326
+ e.style[`border${side}Width`] = `${w}px`;
327
+ e.style[`border${side}Style`] = r.dashed ? 'dashed' : 'solid';
328
+ e.style[`border${side}Color`] = r.color;
329
+ return e;
330
+ }));
331
+ uncover();
332
+ };
333
+ // An entrance uncovers the chart up to `shown`, or raises it from an opacity of `faded`. Layout
334
+ // calls this with no argument, which must undo neither.
335
+ let shown = 1;
336
+ let faded = 1;
337
+ let clipped = '';
338
+ const uncover = (reveal = shown, opacity = faded) => {
339
+ [shown, faded] = [reveal, opacity];
340
+ const shape = reveal < 1 ? revealed(reveal) : undefined;
341
+ if (notes) {
342
+ notes.style.opacity = opacity === 1 ? '' : String(opacity);
343
+ // A label shows once the whole of its box is uncovered, so it never names what is not there yet.
344
+ for (const k of boxes)
345
+ k.el.style.visibility = !shape || uncovered(shape, k) ? '' : 'hidden';
346
+ }
347
+ if (!glCanvas && !lines)
348
+ return;
349
+ const css = shape
350
+ ? `polygon(${shape.map(([x, y]) => `${x}px ${y}px`).join()})`
351
+ : `inset(${[m.top, m.right, m.bottom, m.left].map(side => `${Math.max(side - overhang(), 0)}px`).join(' ')})`;
352
+ for (const e of [glCanvas, lines]) {
353
+ if (!e)
354
+ continue;
355
+ if (css !== clipped)
356
+ e.style.clipPath = css;
357
+ e.style.opacity = opacity === 1 ? '' : String(opacity);
358
+ }
359
+ clipped = css;
360
+ };
361
+ // A column set is scanned at most once per list of marks, and only if its axis asks.
362
+ let extents = {};
363
+ // With every series hidden an axis keeps the extent it last had.
364
+ const last = {};
365
+ const limits = { x: [0, 1], y: [0, 1] };
366
+ const wholes = {};
367
+ // A proposal's scan is kept for the display of the same window that follows it.
368
+ let scanned;
369
+ let lastWindowFit;
370
+ let yFitted = false;
371
+ let yFit;
372
+ // The y extent of the shown marks between a and b on x, if any shows there. A connected mark's x
373
+ // is ascending, so its rows are found by binary search, and its values at the two edges count too.
374
+ // A row counts only where every value of it is a number, as a mark draws nothing of it otherwise.
375
+ const scan = (a, b) => {
376
+ let lo = Infinity;
377
+ let hi = -Infinity;
378
+ let seen = false;
379
+ const add = (v) => {
380
+ if (!Number.isFinite(v))
381
+ return;
382
+ seen = true;
383
+ if (v < lo)
384
+ lo = v;
385
+ if (v > hi)
386
+ hi = v;
387
+ };
388
+ for (const k of visible) {
389
+ const n = k.points;
390
+ const { x: X, y: Y } = k.channels;
391
+ const rows = Y.filter(c => c.length === n);
392
+ // A mark with no y per row, such as a heatmap, is given by its bounds and shows whole where it reaches into the window.
393
+ if (!rows.length) {
394
+ const [p, q] = X.length ? extent(X) : [a, b];
395
+ if (p <= b && q >= a)
396
+ for (const c of Y)
397
+ for (let i = 0; i < c.length; i++)
398
+ add(c[i]);
399
+ continue;
400
+ }
401
+ const [only] = rows;
402
+ const take = rows.length === 1
403
+ ? (i) => add(only[i])
404
+ : (i) => {
405
+ for (const c of rows)
406
+ if (!Number.isFinite(c[i]))
407
+ return;
408
+ for (const c of rows)
409
+ add(c[i]);
410
+ };
411
+ seen = false;
412
+ if (!X.some(c => c.length === n)) {
413
+ for (let i = 0; i < n; i++)
414
+ take(i);
415
+ }
416
+ else if (k.sampleAtX && X.length === 1) {
417
+ const x = X[0];
418
+ let from = upTo(x, a);
419
+ while (from > 0 && x[from - 1] === a)
420
+ from--;
421
+ for (let i = from, to = upTo(x, b); i < to; i++)
422
+ take(i);
423
+ for (const v of [a, b]) {
424
+ if (!(v <= x[n - 1]))
425
+ continue;
426
+ // Which of the two a smooth curve draws depends on the pixel columns, so both count.
427
+ for (const s of [k.sampleAtX(v), k.sampleAtX(v, true)]) {
428
+ if (typeof s === 'number')
429
+ add(s);
430
+ else if (s) {
431
+ add(s.y1);
432
+ add(s.y2);
433
+ }
434
+ }
435
+ }
436
+ }
437
+ else {
438
+ const across = X.filter(c => c.length === n || c.length === 1);
439
+ for (let i = 0; i < n; i++) {
440
+ let p = Infinity;
441
+ let q = -Infinity;
442
+ for (const c of across) {
443
+ const v = c[c.length === 1 ? 0 : i];
444
+ p = Math.min(p, v);
445
+ q = Math.max(q, v);
446
+ }
447
+ if (p <= b && q >= a)
448
+ take(i);
449
+ }
450
+ }
451
+ // A column shorter than the rows, such as a bar's zero baseline, counts whole once the mark shows.
452
+ if (seen)
453
+ for (const c of Y)
454
+ if (c.length !== n)
455
+ for (let i = 0; i < c.length; i++)
456
+ add(c[i]);
457
+ }
458
+ return lo <= hi ? [lo, hi] : undefined;
459
+ };
460
+ const sorted = ([a, b]) => [Math.min(a, b), Math.max(a, b)];
461
+ const fitsWindow = (axis) => axis.fit === 'window' && typeof axis.domain === 'string';
462
+ const scanOnce = (a, b) => {
463
+ const key = `${a},${b}`;
464
+ if (scanned?.key !== key)
465
+ scanned = { key, span: scan(a, b) };
466
+ return scanned.span;
467
+ };
468
+ const windowExtent = (whole) => {
469
+ const [a, b] = sorted([xs.lo, xs.hi]);
470
+ lastWindowFit = scanOnce(a, b) ?? lastWindowFit;
471
+ return lastWindowFit ?? whole();
472
+ };
473
+ const fitted = (which, room) => {
474
+ const of = () => axisOf(o, which).fit === 'all'
475
+ ? (extents[`${which}All`] ??= extent(every().flatMap(k => k.channels[which])))
476
+ : (extents[which] ??=
477
+ visible.some(k => !k.backdrop) || !marks.length
478
+ ? (last[which] = extent(visible.flatMap(k => k.channels[which])))
479
+ : (last[which] ??= extent(every().flatMap(k => k.channels[which]))));
480
+ const whole = (wholes[which] = resolve(axisOf(o, which), of, room));
481
+ limits[which] = [whole.lo, whole.hi];
482
+ const w = bare(o) ? undefined : clamp(into(which, o.view?.[which]), limits[which]);
483
+ if (which === 'y') {
484
+ yFitted = false;
485
+ yFit = { of, room };
486
+ }
487
+ if (!w) {
488
+ const axis = axisOf(o, which);
489
+ if (which === 'x' || !fitsWindow(axis))
490
+ return whole;
491
+ yFitted = true;
492
+ if (xs !== wholes.x)
493
+ return resolve(axis, () => windowExtent(of), room);
494
+ lastWindowFit = of();
495
+ return whole;
496
+ }
497
+ if (w[0] === whole.lo && w[1] === whole.hi)
498
+ return whole;
499
+ // The window's own bounds, not the scale's: a band scale keeps the bounds of all its categories.
500
+ const { ticks } = resolve({ ...axisOf(o, which), domain: w }, of, room);
501
+ return {
502
+ lo: w[0],
503
+ hi: w[1],
504
+ ticks: ticks.filter(t => t.value >= Math.min(...w) && t.value <= Math.max(...w)),
505
+ };
506
+ };
507
+ // Before the first layout the room is judged from the margins as given; after it, from the real
508
+ // ones, which is what catches a legend or a wide label taking the room away.
509
+ const rescale = (laidOut) => {
510
+ const g = o.margin ?? {};
511
+ const bottom = g.bottom ?? (axisOf(o, 'x').label ? 44 : 26);
512
+ const [w, h] = laidOut
513
+ ? [W - m.left - m.right, H - m.top - m.bottom]
514
+ : [W - (g.left ?? 44) - (g.right ?? 16), H - (g.top ?? 12) - bottom];
515
+ xs = fitted('x', { length: w, horizontal: true });
516
+ ys = fitted('y', { length: h, horizontal: false });
517
+ };
518
+ const theme = () => o.theme ?? light;
519
+ const real = (k, v) => {
520
+ const a = axisOf(o, k);
521
+ return a.from ? a.from(v, a) : v;
522
+ };
523
+ // A window a gesture wrote is read back as the span it was made from, which a round trip through real values can miss by a float step.
524
+ const exact = new WeakMap();
525
+ const inward = (k, v) => {
526
+ const a = axisOf(o, k);
527
+ return a.to ? a.to(v, a) : v;
528
+ };
529
+ const into = (k, s) => {
530
+ const a = axisOf(o, k);
531
+ if (!s || !a.to)
532
+ return s;
533
+ const e = exact.get(s);
534
+ if (e && sameAxis(e.axis, a))
535
+ return e.span;
536
+ const r = [inward(k, s[0]), inward(k, s[1])];
537
+ // A decreasing transform, such as a log base below 1, turns the window round; either order means the same window.
538
+ return (s[0] - s[1]) * (r[0] - r[1]) < 0 ? sorted(r) : r;
539
+ };
540
+ const out = (k, s) => {
541
+ const r = [real(k, s[0]), real(k, s[1])];
542
+ exact.set(r, { axis: axisOf(o, k), span: s });
543
+ return r;
544
+ };
545
+ const xPx = (v) => (view.ox + v * view.kx) / dpr;
546
+ const yPx = (v) => (view.oy - v * view.ky) / dpr;
547
+ const layout = () => {
548
+ // ponytail: tick labels are taken as 7 px a character, not measured, because measuring text
549
+ // forces a layout before the first paint. Set the margin when labels are wider than that.
550
+ const [xLabel, yLabel] = [axisOf(o, 'x').label, axisOf(o, 'y').label];
551
+ const given = o.margin ?? {};
552
+ let widest = 0;
553
+ if (given.left === undefined)
554
+ for (const t of [...ys.ticks, ...wholes.y.ticks])
555
+ widest = Math.max(widest, t.label.length);
556
+ m = bare(o)
557
+ ? { top: given.top ?? 8, right: given.right ?? 8, bottom: given.bottom ?? 8, left: given.left ?? 8 }
558
+ : {
559
+ top: given.top ?? 12,
560
+ right: given.right ?? 16,
561
+ bottom: given.bottom ?? (xLabel ? 44 : 26),
562
+ left: given.left ?? 14 + widest * 7 + (yLabel ? 20 : 0),
563
+ };
564
+ // x tick labels are centred on their ticks, so the first and the last may reach past the chart.
565
+ // A tick at fraction u of the axis sits at (1 - u) * left + u * (W - right). Each side is first
566
+ // made the least that keeps its own label inside; if growing the right has pushed the first
567
+ // label out again, both bind at once and the two equations are solved together. Under a window
568
+ // this is done for the whole domain's ticks, so the margins hold still as the window moves.
569
+ const wx = wholes.x;
570
+ const span = wx.hi - wx.lo || 1;
571
+ const half = (label) => label.length * 3.5 + 4;
572
+ const edge = (t) => t && { u: (t.value - wx.lo) / span, half: half(t.label) };
573
+ const [a, b] = [edge(wx.ticks[0]), edge(wx.ticks.at(-1))];
574
+ const [freeLeft, freeRight] = [given.left === undefined, given.right === undefined];
575
+ const leftFor = (right) => (a && a.u < 1 ? (a.half - a.u * (W - right)) / (1 - a.u) : 0);
576
+ if (freeLeft)
577
+ m.left = Math.max(m.left, leftFor(m.right));
578
+ if (freeRight && b && b.u > 0) {
579
+ m.right = Math.max(m.right, W - (W - b.half - (1 - b.u) * m.left) / b.u);
580
+ if (freeLeft && a && a.u !== b.u && leftFor(m.right) > m.left) {
581
+ const p = a.half - a.u * W;
582
+ const q = (1 - b.u) * W - b.half;
583
+ m.left = (a.u * q - b.u * p) / (a.u - b.u);
584
+ m.right = ((1 - a.u) * q - (1 - b.u) * p) / (a.u - b.u);
585
+ }
586
+ }
587
+ m.top += above?.(m.left, W - m.left - m.right) ?? 0;
588
+ const left = m.left * dpr;
589
+ const top = m.top * dpr;
590
+ const width = (W - m.left - m.right) * dpr;
591
+ const height = (H - m.top - m.bottom) * dpr;
592
+ const kx = width / (xs.hi - xs.lo);
593
+ const ky = height / (ys.hi - ys.lo);
594
+ view = {
595
+ kx,
596
+ ox: left - xs.lo * kx,
597
+ ky,
598
+ oy: top + height + ys.lo * ky,
599
+ left,
600
+ top,
601
+ width,
602
+ height,
603
+ dpr,
604
+ ctx,
605
+ theme: theme(),
606
+ };
607
+ axes.style.color = theme().text;
608
+ if (notes)
609
+ notes.style.color = theme().text;
610
+ uncover();
611
+ const key = JSON.stringify([W, H, m, xs, ys, xLabel, yLabel, xs !== wx]);
612
+ if (key !== axesKey) {
613
+ axesKey = key;
614
+ // Axis text is DOM, not fillText: the first text drawn on a canvas cost ~20 ms at 4x CPU slowdown.
615
+ const labels = document.createDocumentFragment();
616
+ const text = (s, x, y, transform) => {
617
+ const e = document.createElement('div');
618
+ e.textContent = s;
619
+ e.style.cssText = `position:absolute;white-space:nowrap;left:${x}px;top:${y}px;transform:${transform}`;
620
+ labels.appendChild(e);
621
+ };
622
+ for (const t of xs.ticks) {
623
+ const x = xPx(t.value);
624
+ if (xs !== wx && (x < textWidth(t.label) / 2 || x > W - textWidth(t.label) / 2))
625
+ continue;
626
+ text(t.label, x, H - m.bottom + 8, 'translate(-50%,0)');
627
+ }
628
+ for (const t of ys.ticks)
629
+ text(t.label, m.left - 8, yPx(t.value), 'translate(-100%,-50%)');
630
+ text(xLabel, m.left + width / dpr / 2, H - 2, 'translate(-50%,-100%)');
631
+ text(yLabel, 10, m.top + height / dpr / 2, 'translate(-50%,-50%) rotate(-90deg)');
632
+ axes.replaceChildren(labels);
633
+ }
634
+ const described = () => {
635
+ const names = [...new Set(marks.flatMap(k => k.label ?? []))].join(', ');
636
+ const axesNamed = yLabel && xLabel ? `${yLabel} by ${xLabel}` : yLabel || xLabel;
637
+ return [axesNamed, names].filter(Boolean).join(': ') || 'Chart';
638
+ };
639
+ canvas.ariaLabel = o.description ?? described();
640
+ viewKey = [kx, view.ox, ky, view.oy, left, top, width, height].join();
641
+ };
642
+ // The browser takes a context away when too many are open, so a lost layer gives its marks back to the canvas.
643
+ const dropLost = () => {
644
+ if (!gl?.gl.isContextLost())
645
+ return false;
646
+ for (const k of placed)
647
+ k.release?.(gl);
648
+ placed.clear();
649
+ gl.destroy();
650
+ gl = null;
651
+ return true;
652
+ };
653
+ const onLost = () => {
654
+ if (dropLost() && drawable) {
655
+ prepare(false);
656
+ paint('size');
657
+ }
658
+ };
659
+ const prepare = (viewChanged) => {
660
+ // A backdrop stays on the canvas: the WebGL layer is dimmed as one when a group is focused.
661
+ const make = makeGl ?? visible.find(k => k.gl && !k.backdrop)?.gl?.layer;
662
+ const on = visible.map(k => !!k.gl && !k.backdrop && k.gl.layer === make);
663
+ // The layer lies over the canvas, so a mark that belongs under those after it stays on the
664
+ // canvas unless they are all on the layer too. A backdrop is painted under both.
665
+ for (let at = visible.length - 1, clear = true; at >= 0; at--) {
666
+ if (visible[at].backdrop)
667
+ continue;
668
+ if (visible[at].gl?.under && !clear)
669
+ on[at] = false;
670
+ clear &&= on[at];
671
+ }
672
+ const layered = new Map();
673
+ visible.forEach((k, i) => layered.has(k) || layered.set(k, on[i]));
674
+ const onLayer = (k) => layered.get(k);
675
+ // ponytail: WebGL positions are 32-bit, a pixel off past ~4096x, so deeper zoom draws on the
676
+ // canvas; 64-bit positions in the shader (a high and a low float) would lift this ceiling.
677
+ const deep = [xs, ys].some((s, i) => {
678
+ const whole = i ? wholes.y : wholes.x;
679
+ return (whole.hi - whole.lo) / (s.hi - s.lo) > 4096;
680
+ });
681
+ // Each mark fills its own share of the threshold, so a mark may ask for the layer sooner or later.
682
+ let useGl = !deep &&
683
+ visible.reduce((sum, k) => sum + (onLayer(k) ? k.points / (k.gl.from ?? GL_FROM) : 0), 0) >= 1;
684
+ if (useGl && gl === undefined) {
685
+ makeGl = make;
686
+ glCanvas = layer('canvas', 'left:0;top:0');
687
+ glCanvas.ariaHidden = 'true';
688
+ canvas.after(glCanvas);
689
+ fit(glCanvas);
690
+ clipped = '';
691
+ uncover();
692
+ gl = makeGl(glCanvas);
693
+ glCanvas.addEventListener('webglcontextlost', onLost);
694
+ }
695
+ dropLost();
696
+ useGl &&= !!gl;
697
+ if (glCanvas)
698
+ glCanvas.style.display = useGl ? '' : 'none';
699
+ const old = cache;
700
+ cache = new Map();
701
+ flat = [];
702
+ onGl = [];
703
+ settle();
704
+ several = new Set(visible.map(k => k.group).filter(g => g !== undefined)).size > 1;
705
+ let all = paired;
706
+ for (const k of visible) {
707
+ const g = useGl && onLayer(k);
708
+ let e = old.get(k);
709
+ const changed = !e;
710
+ if (!e || viewChanged || e.gl !== g) {
711
+ e = { p: g ? k.gl.prepare(view, gl) : k.prepare(view, replaced.get(k)), gl: g };
712
+ if (g)
713
+ placed.add(k);
714
+ }
715
+ if (changed && e.p.morph && replaced.has(k))
716
+ morphs.push(e.p);
717
+ else if (changed)
718
+ all = false;
719
+ cache.set(k, e);
720
+ (g ? onGl : flat).push([k, e.p]);
721
+ }
722
+ flat = [...flat.filter(([k]) => k.backdrop), ...flat.filter(([k]) => !k.backdrop)];
723
+ if (!all)
724
+ morphs = [];
725
+ replaced.clear();
726
+ paired = true;
727
+ annotate();
728
+ rule();
729
+ };
730
+ const grid = () => {
731
+ const { left, top, width, height, ox, kx, oy, ky } = view;
732
+ ctx.lineWidth = dpr;
733
+ ctx.strokeStyle = view.theme.grid;
734
+ ctx.beginPath();
735
+ for (const t of ys.ticks) {
736
+ const y = Math.round(oy - t.value * ky) + dpr / 2;
737
+ ctx.moveTo(left, y);
738
+ ctx.lineTo(left + width, y);
739
+ }
740
+ ctx.stroke();
741
+ ctx.strokeStyle = view.theme.muted;
742
+ ctx.beginPath();
743
+ for (const t of xs.ticks) {
744
+ const x = Math.round(ox + t.value * kx) + dpr / 2;
745
+ ctx.moveTo(x, top + height);
746
+ ctx.lineTo(x, top + height + 5 * dpr);
747
+ }
748
+ ctx.stroke();
749
+ };
750
+ let focusedRow;
751
+ let several = false;
752
+ // One row is picked out where there is no other series to set the hovered one against, or where
753
+ // the row is a named part of its mark, such as a slice, which is then the thing pointed at.
754
+ const drawnRow = () => (o.dim ?? 1) !== 1 && focusedRow && !focusedRow.mark.rowsAlike && (!several || focusedRow.mark.entries)
755
+ ? focusedRow
756
+ : undefined;
757
+ const chosen = () => {
758
+ if (!o.selected?.length)
759
+ return undefined;
760
+ const rows = new Map();
761
+ for (const k of visible) {
762
+ const of = new Set(o.selected
763
+ .flatMap(s => (s.id === idOf(k) ? s.rows : []))
764
+ .filter(r => Number.isInteger(r) && r >= 0 && r < k.points));
765
+ if (of.size)
766
+ rows.set(k, [...of]);
767
+ }
768
+ return rows.size ? rows : undefined;
769
+ };
770
+ const drawnFocus = () => ((o.dim ?? 1) === 1 || drawnRow() ? null : focused);
771
+ const hovered = () => focused !== null || focusedRow !== undefined;
772
+ const render = (reveal = 1) => {
773
+ const dim = o.dim ?? 1;
774
+ const lit = drawnFocus();
775
+ const only = drawnRow();
776
+ uncover(reveal, 1);
777
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
778
+ grid();
779
+ if (!reveal)
780
+ return;
781
+ if (onGl.length && dropLost())
782
+ prepare(false);
783
+ // Each mark is cut to the plot area and its own overhang, so a bar beside a point keeps its edge.
784
+ const cut = (k, draw) => {
785
+ ctx.save();
786
+ ctx.beginPath();
787
+ for (const [x, y] of revealed(reveal, k.overhang ?? 0))
788
+ ctx.lineTo(x * dpr, y * dpr);
789
+ ctx.clip();
790
+ draw();
791
+ ctx.restore();
792
+ };
793
+ const picked = hovered() ? undefined : chosen();
794
+ const pick = (k, p, rows) => {
795
+ if (p.select)
796
+ p.select(rows, view.theme.text);
797
+ else if (k.oneShape)
798
+ p.paint(1);
799
+ else
800
+ for (const row of rows)
801
+ p.paint(1, row, 0);
802
+ };
803
+ // Beside a focused row the other marks keep their strength, unless they are other series.
804
+ const others = lit !== null || (only && several) || picked ? dim : 1;
805
+ const [under, over] = [flat.filter(([k]) => k.backdrop), flat.filter(([k]) => !k.backdrop)];
806
+ for (const [k, p] of under)
807
+ cut(k, () => p.paint(1));
808
+ for (const [k, p] of over) {
809
+ if (k === only?.mark)
810
+ cut(k, () => p.paint(1, only.row, dim));
811
+ else if (k.group !== lit)
812
+ cut(k, () => p.paint(others));
813
+ }
814
+ for (const [k, p] of over)
815
+ if (k.group === lit)
816
+ cut(k, () => p.paint(1));
817
+ for (const [k, p] of over) {
818
+ const rows = picked?.get(k);
819
+ if (rows)
820
+ cut(k, () => pick(k, p, rows));
821
+ }
822
+ if (!onGl.length)
823
+ return;
824
+ gl.clear();
825
+ // What is to be dimmed is drawn first and faded as one, then what is focused goes on top.
826
+ for (const [k, p] of onGl)
827
+ if (k !== only?.mark && k.group !== lit)
828
+ p.paint(1);
829
+ if (others !== 1)
830
+ gl.fade(dim);
831
+ for (const [k, p] of onGl) {
832
+ if (k === only?.mark)
833
+ p.paint(1, only.row, dim);
834
+ else if (lit !== null && k.group === lit)
835
+ p.paint(1);
836
+ else if (picked?.has(k))
837
+ pick(k, p, picked.get(k));
838
+ }
839
+ };
840
+ let painter;
841
+ const paint = (why) => (painter ? painter(render, why) : render());
842
+ const refresh = (data, also, restyled = false, asked = false) => {
843
+ const before = viewKey;
844
+ const shown = () => [xs.lo, xs.hi, ys.lo, ys.hi].join();
845
+ const was = asked && shown();
846
+ rescale(false);
847
+ layout();
848
+ // The scales were resolved for a guessed room; resolved again for the real one, their ticks or
849
+ // bounds may differ, and then so may the margins. Once more is enough to be right in all but contrived cases.
850
+ const guessed = JSON.stringify([xs, ys, wholes]);
851
+ rescale(true);
852
+ if (JSON.stringify([xs, ys, wholes]) !== guessed)
853
+ layout();
854
+ if (asked && shown() !== was)
855
+ also = 'size';
856
+ const viewChanged = viewKey !== before || restyled;
857
+ drawable = W > m.left + m.right && H > m.top + m.bottom;
858
+ root.style.visibility = drawable ? '' : 'hidden';
859
+ // Growing back always changes the view, so marks replaced while hidden are prepared then.
860
+ if (!drawable) {
861
+ flat = [];
862
+ onGl = [];
863
+ cache.clear();
864
+ settle();
865
+ annotate();
866
+ return false;
867
+ }
868
+ if (data || viewChanged)
869
+ prepare(viewChanged);
870
+ // A resize has already cleared the canvas, so it is 'size' even when the data changed too.
871
+ if (data || viewChanged || also)
872
+ paint(also === 'size' || !data ? (also ?? 'size') : 'data');
873
+ return true;
874
+ };
875
+ const unfocusGone = () => {
876
+ const gone = focusedRow !== undefined && !visible.includes(focusedRow.mark);
877
+ if (gone)
878
+ focusedRow = undefined;
879
+ const lost = gone || (focused !== null && !visible.some(k => k.group === focused));
880
+ if (lost)
881
+ focused = null;
882
+ return lost;
883
+ };
884
+ const focus = (group, row) => {
885
+ const [was, wasRow, wasHovered] = [drawnFocus(), drawnRow(), hovered()];
886
+ focused = group;
887
+ focusedRow = row && { mark: row.mark, row: row.row };
888
+ // Only what is drawn counts: a new row inside a focused series changes nothing on screen.
889
+ const now = drawnRow();
890
+ const same = drawnFocus() === was && now?.mark === wasRow?.mark && now?.row === wasRow?.row;
891
+ if (same && (hovered() === wasHovered || !chosen()))
892
+ return;
893
+ if (drawable)
894
+ paint('focus');
895
+ };
896
+ // In the marks' space, or with `stored` as o.view keeps it: in real values, a side not proposed as the app gave it.
897
+ const wanted = (want, stored = false) => {
898
+ const next = {};
899
+ for (const k of ['x', 'y']) {
900
+ if (!want)
901
+ continue;
902
+ const given = o.view?.[k];
903
+ const w = k in want ? clamp(want[k], limits[k]) : stored ? given : into(k, given);
904
+ if (w)
905
+ next[k] = stored && k in want ? out(k, w) : w;
906
+ }
907
+ return next;
908
+ };
909
+ const internals = {
910
+ root,
911
+ canvas,
912
+ layer,
913
+ onPaint(p) {
914
+ painter = p;
915
+ },
916
+ morph(t) {
917
+ for (const p of morphs)
918
+ p.morph(t);
919
+ return morphs.length > 0;
920
+ },
921
+ revealed,
922
+ reveal: uncover,
923
+ reserve(space) {
924
+ above = space;
925
+ },
926
+ marks: () => visible,
927
+ listed: () => marks,
928
+ hidden: () => hiddenIds,
929
+ hide(ids) {
930
+ if (sameIds(hiddenIds, ids))
931
+ return;
932
+ letGo();
933
+ hiddenIds = [...ids];
934
+ const relaid = reshow();
935
+ unfocusGone();
936
+ if (refresh(true, relaid ? undefined : 'size'))
937
+ sync();
938
+ o.onHiddenChange?.(ids);
939
+ },
940
+ size: () => ({ width: W, height: H }),
941
+ margin: () => m,
942
+ theme,
943
+ xPx,
944
+ yPx,
945
+ xValue: px => (px * dpr - view.ox) / view.kx,
946
+ yValue: px => (view.oy - px * dpr) / view.ky,
947
+ view: () => ({ x: [xs.lo, xs.hi], y: [ys.lo, ys.hi] }),
948
+ domain: () => ({ ...limits }),
949
+ fit(want) {
950
+ if (bare(o))
951
+ return internals.view();
952
+ const next = wanted(want);
953
+ const x = clamp(next.x, limits.x) ?? limits.x;
954
+ const derived = () => {
955
+ const whole = x[0] === limits.x[0] && x[1] === limits.x[1];
956
+ if (whole || !yFit || !fitsWindow(axisOf(o, 'y')))
957
+ return limits.y;
958
+ const fit = resolve(axisOf(o, 'y'), () => scanOnce(...sorted(x)) ?? lastWindowFit ?? yFit.of(), yFit.room);
959
+ return [fit.lo, fit.hi];
960
+ };
961
+ const y = clamp(next.y, limits.y) ?? derived();
962
+ return { x: [...x], y: [...y] };
963
+ },
964
+ propose(want) {
965
+ if (bare(o))
966
+ return false;
967
+ const [shown, will] = [internals.view(), internals.fit(want)];
968
+ if (['x', 'y'].every(k => String(will[k]) === String(shown[k])))
969
+ return false;
970
+ letGo();
971
+ o = { ...o, view: want ? wanted(want, true) : undefined };
972
+ if (refresh(false, 'size'))
973
+ sync();
974
+ o.onViewChange?.({
975
+ x: [real('x', xs.lo), real('x', xs.hi)],
976
+ ...(!yFitted && { y: [real('y', ys.lo), real('y', ys.hi)] }),
977
+ });
978
+ return true;
979
+ },
980
+ real,
981
+ frame: () => o.frame ?? 'axes',
982
+ drag: { brush: false, pan: false, active: false },
983
+ sync: () => sync(),
984
+ // Topmost first, the reverse of render(): a hit that is no nearer never replaces one above it.
985
+ hit(px, py, max) {
986
+ const lit = drawnFocus();
987
+ let best = null;
988
+ for (const list of [onGl, flat]) {
989
+ for (const top of [true, false]) {
990
+ for (let i = list.length - 1; i >= 0; i--) {
991
+ const [mark, p] = list[i];
992
+ if ((mark.group === lit && !mark.backdrop) !== top)
993
+ continue;
994
+ const h = p.hit?.(px, py, best ? best.distance : max);
995
+ if (h && (!best || h.distance < best.distance))
996
+ best = { ...h, mark };
997
+ }
998
+ }
999
+ }
1000
+ return best;
1001
+ },
1002
+ pointer() {
1003
+ const p = o.pointer;
1004
+ if (!p || bare(o) || !drawable)
1005
+ return null;
1006
+ const x = xPx(inward('x', p.x));
1007
+ if (!(x >= m.left && x <= W - m.right))
1008
+ return null;
1009
+ if (p.y === undefined)
1010
+ return { x };
1011
+ const y = yPx(inward('y', p.y));
1012
+ return !(y >= m.top && y <= H - m.bottom) ? { x } : { x, y };
1013
+ },
1014
+ focus,
1015
+ };
1016
+ let pointed = false;
1017
+ const tell = (p) => {
1018
+ if (!p && !pointed)
1019
+ return;
1020
+ pointed = !!p;
1021
+ o.onPointerChange?.(p);
1022
+ };
1023
+ let at;
1024
+ const aim = () => {
1025
+ root.style.cursor = o.onClick && at && clicked(at)?.hit ? 'pointer' : '';
1026
+ };
1027
+ const point = (e) => {
1028
+ at = e;
1029
+ aim();
1030
+ if (internals.drag.active)
1031
+ return tell(null);
1032
+ const { px, py, over } = locate(internals, e);
1033
+ tell(over ? { x: real('x', internals.xValue(px)), y: real('y', internals.yValue(py)) } : null);
1034
+ };
1035
+ const unpoint = () => {
1036
+ at = undefined;
1037
+ root.style.cursor = '';
1038
+ tell(null);
1039
+ };
1040
+ root.addEventListener('pointerdown', point);
1041
+ root.addEventListener('pointermove', point);
1042
+ root.addEventListener('pointerleave', unpoint);
1043
+ root.addEventListener('pointercancel', unpoint);
1044
+ const clicked = (e) => {
1045
+ if (internals.drag.active || e.target !== root)
1046
+ return undefined;
1047
+ const { px, py, inside } = position(internals, e.clientX, e.clientY);
1048
+ if (!inside)
1049
+ return undefined;
1050
+ return { px, py, hit: internals.hit(px, py, NEAREST_PX) };
1051
+ };
1052
+ root.addEventListener('click', e => {
1053
+ const c = o.onClick && clicked(e);
1054
+ if (!c)
1055
+ return;
1056
+ const { px, py, hit } = c;
1057
+ o.onClick(hit && {
1058
+ ...hit,
1059
+ mark: declared.get(hit.mark) ?? hit.mark,
1060
+ x: real('x', hit.x),
1061
+ y: real('y', hit.y),
1062
+ ...(hit.value !== undefined && { value: real('y', hit.value) }),
1063
+ }, {
1064
+ x: real('x', internals.xValue(px)),
1065
+ y: real('y', internals.yValue(py)),
1066
+ });
1067
+ });
1068
+ showing();
1069
+ const features = [];
1070
+ const sync = () => {
1071
+ for (const f of features)
1072
+ f.update?.();
1073
+ aim();
1074
+ };
1075
+ const letGo = () => {
1076
+ for (const f of features)
1077
+ f.letGo?.();
1078
+ };
1079
+ let observer;
1080
+ let observing = false;
1081
+ const observe = () => {
1082
+ const auto = o.width === undefined || o.height === undefined;
1083
+ if (auto === observing)
1084
+ return;
1085
+ observing = auto;
1086
+ if (auto)
1087
+ observer.observe(root);
1088
+ else
1089
+ observer.disconnect();
1090
+ };
1091
+ // A density query matches one value only, so each change is listened for once and asked for again.
1092
+ let density;
1093
+ const redensify = () => {
1094
+ dpr = devicePixelRatio;
1095
+ fit(canvas);
1096
+ if (glCanvas)
1097
+ fit(glCanvas);
1098
+ watch();
1099
+ letGo();
1100
+ if (refresh(false, 'size'))
1101
+ sync();
1102
+ };
1103
+ const watch = () => {
1104
+ density = matchMedia(`(resolution: ${dpr}dppx)`);
1105
+ density.addEventListener('change', redensify, { once: true });
1106
+ };
1107
+ const teardown = () => {
1108
+ let failed;
1109
+ const run = (f) => {
1110
+ try {
1111
+ f();
1112
+ }
1113
+ catch (e) {
1114
+ failed ??= { e };
1115
+ }
1116
+ };
1117
+ run(() => observer?.disconnect());
1118
+ run(() => density?.removeEventListener('change', redensify));
1119
+ for (const f of features)
1120
+ run(() => f.destroy());
1121
+ for (const k of new Set([...marks, ...declared.keys()]))
1122
+ run(() => k.release?.(gl ?? null));
1123
+ run(() => glCanvas?.removeEventListener('webglcontextlost', onLost));
1124
+ run(() => gl?.destroy());
1125
+ root.remove();
1126
+ if (failed)
1127
+ throw failed.e;
1128
+ };
1129
+ el.appendChild(root);
1130
+ try {
1131
+ measure();
1132
+ for (const feature of o.use ?? [])
1133
+ features.push(feature(internals));
1134
+ if (refresh(true))
1135
+ sync();
1136
+ observer = new ResizeObserver(() => {
1137
+ letGo();
1138
+ if (refresh(false, measure() ? 'size' : undefined))
1139
+ sync();
1140
+ });
1141
+ observe();
1142
+ watch();
1143
+ }
1144
+ catch (e) {
1145
+ try {
1146
+ teardown();
1147
+ }
1148
+ catch { }
1149
+ throw e;
1150
+ }
1151
+ return {
1152
+ update(partial) {
1153
+ const keys = Object.keys(partial);
1154
+ if (!keys.length || !keys.every(k => LIGHT.has(k)))
1155
+ letGo();
1156
+ const prev = o;
1157
+ o = { ...o, ...partial };
1158
+ const hid = 'hidden' in partial && !sameIds(partial.hidden, hiddenIds);
1159
+ if (hid)
1160
+ hiddenIds = [...(partial.hidden ?? [])];
1161
+ let data = !sameAxis(axisOf(o, 'x'), axisOf(prev, 'x')) || !sameAxis(axisOf(o, 'y'), axisOf(prev, 'y'));
1162
+ replaced = new Map();
1163
+ paired = true;
1164
+ let relaid = false;
1165
+ let reshown = false;
1166
+ if (partial.marks) {
1167
+ const before = marks;
1168
+ const byKey = new Map(before.map((k, i) => [k.key ?? i, k]));
1169
+ marks = partial.marks.map((k, i) => {
1170
+ const was = byKey.get(k.key ?? i);
1171
+ if (was?.type !== k.type)
1172
+ return k;
1173
+ if (same(was.options, k.options))
1174
+ return was;
1175
+ replaced.set(k, was);
1176
+ return k;
1177
+ });
1178
+ if (marks.length !== before.length || marks.some((k, i) => k !== before[i])) {
1179
+ data = true;
1180
+ extents = {};
1181
+ everyLaid = undefined;
1182
+ lastWindowFit = undefined;
1183
+ relaid = reshow();
1184
+ reshown = true;
1185
+ }
1186
+ const kept = new Set(marks);
1187
+ // Every old listing must be matched by exactly one new one, kept or paired: a mark may be
1188
+ // listed more than once, so this counts listings, not marks.
1189
+ const unmatched = new Map();
1190
+ for (const k of before)
1191
+ unmatched.set(k, (unmatched.get(k) ?? 0) + 1);
1192
+ for (const k of marks) {
1193
+ const was = replaced.get(k) ?? k;
1194
+ unmatched.set(was, (unmatched.get(was) ?? 0) - 1);
1195
+ }
1196
+ paired = [...unmatched.values()].every(n => n === 0);
1197
+ for (const k of new Set(before))
1198
+ if (!kept.has(k))
1199
+ drop(k);
1200
+ }
1201
+ // The focused row follows its mark into the mark that replaced it, so a pointer at rest
1202
+ // on a bar asks for no new focus and does not cut the bar's move short.
1203
+ for (const [k, was] of replaced)
1204
+ if (was === focusedRow?.mark)
1205
+ focusedRow = { ...focusedRow, mark: k };
1206
+ if (hid && !reshown)
1207
+ relaid = reshow();
1208
+ data ||= hid;
1209
+ const lost = unfocusGone();
1210
+ observe();
1211
+ const resized = measure();
1212
+ const restyled = theme() !== (prev.theme ?? light);
1213
+ // Ticks are DOM and change at once, so a new window must not cross-fade with new marks.
1214
+ const moved = ['x', 'y'].some(k => String(o.view?.[k]) !== String(prev.view?.[k]));
1215
+ if (refresh(data, resized || restyled || (hid && !relaid)
1216
+ ? 'size'
1217
+ : lost || o.dim !== prev.dim || o.selected !== prev.selected
1218
+ ? 'focus'
1219
+ : undefined, restyled, moved))
1220
+ sync();
1221
+ else
1222
+ aim();
1223
+ },
1224
+ destroy: teardown,
1225
+ };
1226
+ }