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