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
@@ -0,0 +1,366 @@
1
+ import { glLayer, program, rgba } from '../gl.js';
2
+ // Canvas fills a ribbon at a time, and from about here a hover takes longer than a frame.
3
+ const GL_FROM = 1000;
4
+ const SEGMENTS = 24;
5
+ const programs = new WeakMap();
6
+ // An instance is a ribbon from (e.x, e.z) to (e.y, e.w), h tall, bent as the canvas bezier is. Each
7
+ // pixel is as strong as the share of it the ribbon covers. Under an eighth of a pixel that is too
8
+ // faint for the canvas to add up, so such a ribbon is drawn an eighth thick or not at all, as
9
+ // often as keeps the whole as strong; one on the path pointed at is always drawn.
10
+ function ribbonProgram(gl) {
11
+ const p = program(gl, `layout(location=0) in vec4 e;layout(location=1) in float h;layout(location=2) in vec4 c;layout(location=3) in float s;layout(location=4) in vec4 c2;uniform vec2 size;uniform float lit;out vec4 col;out vec2 v;void main(){float t=float(gl_VertexID>>1)/${SEGMENTS}.0;float side=float(gl_VertexID&1)*2.0-1.0;float w=1.0-t;float x=e.x*w*w*w+(e.x+e.y)*1.5*w*t+e.y*t*t*t;uint z=uint(gl_InstanceID)*2654435761u;z^=z>>15;float d=h;if(h>0.0&&h<0.125)d=s>=lit||float(z&65535u)/65536.0<h*8.0?0.125:0.0;float r=d*0.5+0.5;float y=mix(e.z,e.w,t*t*(3.0-2.0*t))+d*0.5+side*r;gl_Position=d>0.0?vec4(x/size.x*2.0-1.0,1.0-y/size.y*2.0,0,1):vec4(2,2,2,1);vec4 k=mix(c,c2,t);col=vec4(k.rgb,1)*k.a*s;v=vec2(side*r,d*0.5);}`, 'precision highp float;in vec4 col;in vec2 v;out vec4 o;void main(){o=col*clamp(min(v.y,v.x+0.5)-max(-v.y,v.x-0.5),0.0,1.0);}');
12
+ return { p, size: gl.getUniformLocation(p, 'size'), lit: gl.getUniformLocation(p, 'lit') };
13
+ }
14
+ /** The columns sankey() takes, from links that name their ends. Nodes are listed as first met. */
15
+ export function fromLinks(links) {
16
+ const place = new Map();
17
+ const at = (name) => {
18
+ if (!place.has(name))
19
+ place.set(name, place.size);
20
+ return place.get(name);
21
+ };
22
+ const [source, target, value] = [[], [], []];
23
+ for (const link of links) {
24
+ source.push(at(link.source));
25
+ target.push(at(link.target));
26
+ value.push(link.value);
27
+ }
28
+ return { nodes: [...place.keys()], source: source, target: target, value: value };
29
+ }
30
+ export function sankey(o) {
31
+ const { nodes, source, target, colors, alpha = 1 } = o;
32
+ const [n, links] = [nodes.length, source.length];
33
+ const named = (i) => nodes[i] ?? `#${i}`;
34
+ for (let i = 0; i < links; i++) {
35
+ for (const end of [source[i], target[i]]) {
36
+ if (!Number.isInteger(end) || end < 0 || end >= n)
37
+ throw new Error(`sankey: link ${i} names node ${end}, and there are ${n}`);
38
+ }
39
+ if (source[i] === target[i])
40
+ throw new Error(`sankey: ${named(source[i])} links to itself`);
41
+ }
42
+ // Values are taken as shares of the largest, so that sums of them cannot overflow.
43
+ let most = 0;
44
+ const worth = (i) => (o.value[i] > 0 && Number.isFinite(o.value[i]) ? o.value[i] : 0);
45
+ for (let i = 0; i < links; i++)
46
+ most = Math.max(most, worth(i));
47
+ const value = Float64Array.from({ length: links }, (_, i) => worth(i) / (most || 1));
48
+ // Each node's links, listed once, so that nothing below looks through all links per node.
49
+ const [into, outOf] = [nodes.map(() => []), nodes.map(() => [])];
50
+ for (let i = 0; i < links; i++) {
51
+ outOf[source[i]].push(i);
52
+ into[target[i]].push(i);
53
+ }
54
+ // A column for each node: one after its furthest source. What is left when no node is free of
55
+ // unplaced sources is fed by a cycle.
56
+ const column = new Int32Array(n);
57
+ const waiting = Int32Array.from(into, list => list.length);
58
+ const ready = Array.from({ length: n }, (_, i) => i).filter(i => !waiting[i]);
59
+ for (let done = 0; done < ready.length; done++) {
60
+ const from = ready[done];
61
+ for (const i of outOf[from]) {
62
+ const to = target[i];
63
+ column[to] = Math.max(column[to], column[from] + 1);
64
+ if (!--waiting[to])
65
+ ready.push(to);
66
+ }
67
+ }
68
+ if (ready.length < n) {
69
+ // Every unplaced node has an unplaced source; walking back along those must come round.
70
+ const back = (node) => source[into[node].find(i => waiting[source[i]])];
71
+ const seen = new Set();
72
+ let node = waiting.findIndex(w => w > 0);
73
+ while (!seen.has(node)) {
74
+ seen.add(node);
75
+ node = back(node);
76
+ }
77
+ const circle = [node];
78
+ for (let next = back(node); next !== node; next = back(next))
79
+ circle.unshift(next);
80
+ throw new Error(`sankey: the links go round in a circle through ${circle.map(named).join(', ')}`);
81
+ }
82
+ const size = new Float64Array(n);
83
+ for (let i = 0; i < n; i++) {
84
+ const total = (list) => list.reduce((sum, link) => sum + value[link], 0);
85
+ size[i] = Math.max(total(into[i]), total(outOf[i]));
86
+ }
87
+ const columns = [];
88
+ for (let i = 0; i < n; i++)
89
+ (columns[column[i]] ??= []).push(i);
90
+ // Order within a column: by where a node's neighbours on one side sit, weighted by the flow.
91
+ const place = new Float64Array(n);
92
+ const settle = (c) => c.forEach((node, k) => (place[node] = k));
93
+ const order = (c, near, far) => {
94
+ const pull = (node) => {
95
+ let [sum, weight] = [0, 0];
96
+ for (const i of near[node]) {
97
+ sum += place[far[i]] * value[i];
98
+ weight += value[i];
99
+ }
100
+ return weight ? sum / weight : place[node];
101
+ };
102
+ const pulls = new Map(c.map(node => [node, pull(node)]));
103
+ c.sort((a, b) => pulls.get(a) - pulls.get(b) || a - b);
104
+ settle(c);
105
+ };
106
+ columns.forEach(settle);
107
+ for (const c of columns)
108
+ order(c, into, source);
109
+ for (const c of [...columns].reverse())
110
+ order(c, outOf, target);
111
+ const shade = (i) => colors[i % colors.length] ?? '#888';
112
+ const holds = new WeakMap();
113
+ // What lights up with a row: all that flows into it and all that flows out of it, however
114
+ // many nodes away. For a link that is what feeds its source and what its target feeds.
115
+ let lit = { rows: new Set() };
116
+ const along = (row) => {
117
+ if (lit.row === row)
118
+ return lit.rows;
119
+ const rows = new Set([row]);
120
+ const walk = (from, near, far) => {
121
+ const todo = [from];
122
+ rows.add(from);
123
+ for (let node = todo.pop(); node !== undefined; node = todo.pop()) {
124
+ for (const i of near[node]) {
125
+ if (!value[i])
126
+ continue;
127
+ rows.add(n + i);
128
+ if (!rows.has(far[i]))
129
+ todo.push(far[i]);
130
+ rows.add(far[i]);
131
+ }
132
+ }
133
+ };
134
+ walk(row < n ? row : source[row - n], into, source);
135
+ walk(row < n ? row : target[row - n], outOf, target);
136
+ lit = { row, rows };
137
+ return rows;
138
+ };
139
+ const strength = (k, row, rest, mine) => alpha * k * (row === undefined || along(row).has(mine) ? 1 : rest);
140
+ // Where everything sits in a view: what both the canvas and the WebGL painting draw and hit.
141
+ const lay = ({ ctx, dpr, left, top, width, height }) => {
142
+ // Nodes and the gaps between them give way before they crowd out the flows: a node is at
143
+ // most half its column's share of the width, and the gaps in the fullest column a third
144
+ // of the height.
145
+ const fullest = columns.reduce((most, c) => Math.max(most, c.length), 1);
146
+ const thick = Math.min(12 * dpr, width / (2 * Math.max(columns.length, 1)));
147
+ const gap = Math.min(10 * dpr, height / 3 / Math.max(fullest - 1, 1));
148
+ // One scale for every column: the tightest column decides it.
149
+ let scale = Infinity;
150
+ for (const c of columns) {
151
+ const total = c.reduce((sum, node) => sum + size[node], 0);
152
+ if (total)
153
+ scale = Math.min(scale, Math.max(0, height - gap * (c.length - 1)) / total);
154
+ }
155
+ if (!Number.isFinite(scale))
156
+ scale = 0;
157
+ const step = columns.length > 1 ? (width - thick) / (columns.length - 1) : 0;
158
+ const [x, y] = [new Float64Array(n), new Float64Array(n)];
159
+ for (const [k, c] of columns.entries()) {
160
+ const used = c.reduce((sum, node) => sum + size[node] * scale, 0) + gap * (c.length - 1);
161
+ let at = top + (height - used) / 2;
162
+ for (const node of c) {
163
+ [x[node], y[node]] = [left + k * step, at];
164
+ at += size[node] * scale + gap;
165
+ }
166
+ }
167
+ // A node's links leave and arrive stacked in the order of the nodes at their other end.
168
+ const [leaves, arrives] = [new Float64Array(n), new Float64Array(n)];
169
+ const byEnds = Array.from({ length: links }, (_, i) => i).sort((a, b) => y[source[a]] - y[source[b]] || y[target[a]] - y[target[b]] || a - b);
170
+ // The top of each link's ribbon where it leaves and where it arrives.
171
+ const tops = new Float64Array(links * 2);
172
+ for (const i of byEnds) {
173
+ const [s, t, h] = [source[i], target[i], value[i] * scale];
174
+ tops.set([y[s] + leaves[s], y[t] + arrives[t]], i * 2);
175
+ leaves[s] += h;
176
+ arrives[t] += h;
177
+ }
178
+ const trace = (i) => {
179
+ const [x0, x1, h] = [x[source[i]] + thick, x[target[i]], value[i] * scale];
180
+ const [y0, y1, bend] = [tops[i * 2], tops[i * 2 + 1], (x0 + x1) / 2];
181
+ if (!h)
182
+ return undefined;
183
+ const path = new Path2D();
184
+ path.moveTo(x0, y0);
185
+ path.bezierCurveTo(bend, y0, bend, y1, x1, y1);
186
+ path.lineTo(x1, y1 + h);
187
+ path.bezierCurveTo(bend, y1 + h, bend, y0 + h, x0, y0 + h);
188
+ path.closePath();
189
+ return path;
190
+ };
191
+ const labels = [];
192
+ for (let i = 0; o.text !== false && i < n; i++) {
193
+ const last = column[i] === columns.length - 1 && columns.length > 1;
194
+ labels.push({
195
+ x: last ? x[i] - 6 * dpr : x[i] + thick + 6 * dpr,
196
+ y: y[i] + (size[i] * scale) / 2,
197
+ text: named(i),
198
+ align: last ? 'end' : 'start',
199
+ priority: size[i],
200
+ });
201
+ }
202
+ // A node with any flow keeps a pixel of height, and is drawn and hit as the same rectangle.
203
+ const tall = (i) => (size[i] ? Math.max(size[i] * scale, 1) : 0);
204
+ const frac = (px, py) => ({ x: (px - left) / width, y: 1 - (py - top) / height });
205
+ // A node before a link; a link the pointer is in before one it is only near. A thin link
206
+ // answers from 3 px either side, since its true width may be less than a pixel.
207
+ const hit = (shape) => (px, py, reach) => {
208
+ const [hx, hy] = [px * dpr, py * dpr];
209
+ if (hx < left || hx > left + width || hy < top || hy > top + height)
210
+ return null;
211
+ for (let i = n - 1; i >= 0; i--) {
212
+ if (hx >= x[i] && hx < x[i] + thick && hy >= y[i] && hy < y[i] + tall(i)) {
213
+ return {
214
+ ...frac(x[i] + thick / 2, y[i] + (size[i] * scale) / 2),
215
+ distance: reach,
216
+ row: i,
217
+ color: shade(i),
218
+ };
219
+ }
220
+ }
221
+ ctx.lineWidth = 6 * dpr;
222
+ for (const near of [0, 3 * dpr]) {
223
+ for (let i = links - 1; i >= 0; i--) {
224
+ // Only a ribbon whose bounds hold the pointer has its shape asked, which costs far more.
225
+ const [x0, x1, h] = [x[source[i]] + thick, x[target[i]], value[i] * scale];
226
+ const [y0, y1] = [tops[i * 2], tops[i * 2 + 1]];
227
+ if (!h || hx < x0 - near || hx > x1 + near)
228
+ continue;
229
+ if (hy < Math.min(y0, y1) - near || hy > Math.max(y0, y1) + h + near)
230
+ continue;
231
+ const path = shape(i);
232
+ if (!(near ? ctx.isPointInStroke(path, hx, hy) : ctx.isPointInPath(path, hx, hy)))
233
+ continue;
234
+ return {
235
+ ...frac((x0 + x1) / 2, (y0 + y1 + h) / 2),
236
+ distance: reach,
237
+ row: n + i,
238
+ color: shade(source[i]),
239
+ };
240
+ }
241
+ }
242
+ return null;
243
+ };
244
+ return { x, y, thick, scale, tops, labels, tall, trace, hit };
245
+ };
246
+ // Every ribbon and node is one instance of a strip whose curve the vertex shader works out,
247
+ // so a view costs one small upload and a hover one float per instance.
248
+ const prepareGl = (view, { gl }) => {
249
+ const { x, y, thick, scale, tops, labels, tall, trace, hit } = lay(view);
250
+ const u = programs.get(gl) ?? ribbonProgram(gl);
251
+ programs.set(gl, u);
252
+ const count = links + n;
253
+ const place = new Float32Array(count * 5);
254
+ const tone = new Uint8Array(count * 8);
255
+ const tones = (colors.length ? colors : ['#888']).map(c => rgba(view.ctx, c).map(v => Math.round(v * 255)));
256
+ for (let i = 0; i < links; i++) {
257
+ place.set([x[source[i]] + thick, x[target[i]], tops[i * 2], tops[i * 2 + 1], value[i] * scale], i * 5);
258
+ tone.set(tones[source[i] % tones.length], i * 8);
259
+ tone.set(tones[(o.blend ? target[i] : source[i]) % tones.length], i * 8 + 4);
260
+ }
261
+ for (let i = 0; i < n; i++) {
262
+ place.set([x[i], x[i] + thick, y[i], y[i], tall(i)], (links + i) * 5);
263
+ tone.set(tones[i % tones.length], (links + i) * 8);
264
+ tone.set(tones[i % tones.length], (links + i) * 8 + 4);
265
+ }
266
+ let held = holds.get(gl);
267
+ if (!held)
268
+ holds.set(gl, (held = { vao: gl.createVertexArray(), buffers: [0, 1, 2].map(() => gl.createBuffer()) }));
269
+ gl.bindVertexArray(held.vao);
270
+ const column = (at, buffer, data, parts) => {
271
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
272
+ gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);
273
+ const float = data instanceof Float32Array;
274
+ const stride = parts.reduce((sum, p) => sum + p[1], 0) * (float ? 4 : 1);
275
+ for (const [slot, length, offset] of parts) {
276
+ gl.enableVertexAttribArray(at + slot);
277
+ gl.vertexAttribPointer(at + slot, length, float ? gl.FLOAT : gl.UNSIGNED_BYTE, !float, stride, offset);
278
+ gl.vertexAttribDivisor(at + slot, 1);
279
+ }
280
+ };
281
+ column(0, held.buffers[0], place, [
282
+ [0, 4, 0],
283
+ [1, 1, 16],
284
+ ]);
285
+ column(2, held.buffers[1], tone, [
286
+ [0, 4, 0],
287
+ [2, 4, 4],
288
+ ]);
289
+ const strengths = new Float32Array(count);
290
+ column(3, held.buffers[2], strengths, [[0, 1, 0]]);
291
+ gl.bindVertexArray(null);
292
+ let drawn = '';
293
+ return {
294
+ labels,
295
+ paint(k, row, rest = 1) {
296
+ const { vao, buffers } = held;
297
+ if (drawn !== (drawn = `${k} ${row} ${rest}`)) {
298
+ for (let i = 0; i < links; i++)
299
+ strengths[i] = strength(k, row, rest, n + i) * 0.45;
300
+ for (let i = 0; i < n; i++)
301
+ strengths[links + i] = strength(k, row, rest, i);
302
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffers[2]);
303
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, strengths);
304
+ }
305
+ gl.useProgram(u.p);
306
+ gl.uniform2f(u.size, gl.canvas.width, gl.canvas.height);
307
+ gl.uniform1f(u.lit, row === undefined ? 2 : alpha * k * 0.45 * 0.999);
308
+ gl.bindVertexArray(vao);
309
+ gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 2 * (SEGMENTS + 1), count);
310
+ gl.bindVertexArray(null);
311
+ },
312
+ hit: hit(trace),
313
+ };
314
+ };
315
+ return {
316
+ type: 'sankey',
317
+ key: o.key,
318
+ label: o.label,
319
+ group: o.group ?? o.label,
320
+ color: shade(0),
321
+ options: o,
322
+ points: n + links,
323
+ channels: { x: [], y: [] },
324
+ prepare(view) {
325
+ const { ctx } = view;
326
+ const { x, y, thick, labels, tall, trace, hit } = lay(view);
327
+ const ribbons = Array.from({ length: links }, (_, i) => trace(i));
328
+ const inks = !o.blend
329
+ ? undefined
330
+ : ribbons.map((_, i) => {
331
+ const across = ctx.createLinearGradient(x[source[i]] + thick, 0, x[target[i]], 0);
332
+ across.addColorStop(0, shade(source[i]));
333
+ across.addColorStop(1, shade(target[i]));
334
+ return across;
335
+ });
336
+ return {
337
+ labels,
338
+ paint(k, row, rest = 1) {
339
+ ribbons.forEach((path, i) => {
340
+ if (!path)
341
+ return;
342
+ ctx.globalAlpha = strength(k, row, rest, n + i) * 0.45;
343
+ ctx.fillStyle = inks?.[i] ?? shade(source[i]);
344
+ ctx.fill(path);
345
+ });
346
+ for (let i = 0; i < n; i++) {
347
+ ctx.globalAlpha = strength(k, row, rest, i);
348
+ ctx.fillStyle = shade(i);
349
+ ctx.fillRect(x[i], y[i], thick, tall(i));
350
+ }
351
+ },
352
+ hit: hit(i => ribbons[i]),
353
+ };
354
+ },
355
+ gl: { layer: glLayer, from: GL_FROM, prepare: prepareGl },
356
+ release(layer) {
357
+ const held = layer && holds.get(layer.gl);
358
+ if (!held)
359
+ return;
360
+ layer.gl.deleteVertexArray(held.vao);
361
+ for (const buffer of held.buffers)
362
+ layer.gl.deleteBuffer(buffer);
363
+ holds.delete(layer.gl);
364
+ },
365
+ };
366
+ }
@@ -0,0 +1,26 @@
1
+ import type { Mark } from '../types.js';
2
+ import { type TreeColumns } from './tree.js';
3
+ /**
4
+ * A tree as rings round a centre, for a polar frame: the roots innermost, each node's children
5
+ * in the next ring out, sharing its part of the turn by their sizes. A single root is a disc in
6
+ * the middle. See TreeColumns for the input and fromTree() for nested objects. Each root has a
7
+ * colour, or each child of a single root, and what is below it is the same colour, lighter ring
8
+ * by ring. A hit's row is the node's place in `nodes`; pointing at a node also picks out, more
9
+ * faintly, the nodes it sits under.
10
+ * ponytail: at most the 200 largest nodes ask for a label, as in treemap().
11
+ */
12
+ export type SunburstOptions = TreeColumns & {
13
+ colors: string[];
14
+ /** Text on each node that has room: its name by default, your own, or none. */
15
+ text?: false | ((row: number) => string);
16
+ /**
17
+ * Each branch runs smoothly from its full colour at the centre to this opacity at the rim, in
18
+ * place of a lighter step for each ring.
19
+ */
20
+ shade?: number;
21
+ alpha?: number;
22
+ key?: string;
23
+ label?: string;
24
+ group?: string;
25
+ };
26
+ export declare function sunburst(o: SunburstOptions): Mark;
@@ -0,0 +1,185 @@
1
+ import { rgba } from '../gl.js';
2
+ import { inRing, TURN, turnAt } from './common.js';
3
+ import { first, grow } from './tree.js';
4
+ export function sunburst(o) {
5
+ const { colors, parent, alpha = 1 } = o;
6
+ const { n, kids, roots, order, depth, tint, size, named } = grow(o, 'sunburst');
7
+ const shade = (i) => (tint[i] < 0 ? '#999' : (colors[tint[i] % colors.length] ?? '#888'));
8
+ // Where each node starts and ends, as shares of the turn: parents before their children.
9
+ const [from, to] = [new Float64Array(n), new Float64Array(n)];
10
+ const share = (list, start, span) => {
11
+ const total = list.reduce((sum, i) => sum + size[i], 0);
12
+ // The last one with any size ends exactly where its parent does, whatever the sums round
13
+ // to, and none ends beyond it; one of no size has no part of the turn.
14
+ const last = list.findLast(i => size[i] > 0);
15
+ let at = start;
16
+ for (const i of list) {
17
+ from[i] = at;
18
+ to[i] = at =
19
+ i === last ? start + span : Math.min(start + span, at + (total ? (size[i] / total) * span : 0));
20
+ }
21
+ };
22
+ share(roots, 0, 1);
23
+ for (const node of order)
24
+ share(kids[node], from[node], to[node] - from[node]);
25
+ const drawn = order.filter(i => to[i] > from[i]);
26
+ // Rings are counted over what is drawn: a branch of no size takes no room, however deep.
27
+ const rings = drawn.reduce((most, i) => Math.max(most, depth[i] + 1), 0);
28
+ const largest = first(drawn, 200, (a, b) => size[b] / 2 ** depth[b] - size[a] / 2 ** depth[a] || a - b);
29
+ let above = { rows: new Set() };
30
+ const over = (row) => {
31
+ if (above.row !== row) {
32
+ const rows = new Set();
33
+ for (let p = parent[row]; p >= 0; p = parent[p])
34
+ rows.add(p);
35
+ above = { row, rows };
36
+ }
37
+ return above.rows;
38
+ };
39
+ return {
40
+ type: 'sunburst',
41
+ key: o.key,
42
+ label: o.label,
43
+ group: o.group ?? o.label,
44
+ color: colors[0] ?? '#888',
45
+ options: o,
46
+ points: n,
47
+ channels: { x: [], y: [] },
48
+ prepare({ ctx, dpr, left, top, width, height }) {
49
+ const [cx, cy] = [left + width / 2, top + height / 2];
50
+ const outer = Math.max(0, Math.min(width, height) / 2);
51
+ const thick = outer / (rings || 1);
52
+ // A ring starts a pixel out from the one inside it; the innermost starts at the centre.
53
+ const reach = (i) => {
54
+ const d = depth[i];
55
+ return [d * thick + (d ? Math.min(dpr, thick / 4) : 0), (d + 1) * thick];
56
+ };
57
+ const whole = (i) => to[i] - from[i] >= 1;
58
+ // Siblings are gathered until they are a device pixel wide at their rim, and drawn as one in
59
+ // the colour of the widest among them: more shapes than pixels cost time and show nothing.
60
+ // ponytail: each parent with a size still has a shape of its own children, however thin;
61
+ // skip what lies under a gathered node when trees of millions of branches matter.
62
+ const shapes = [];
63
+ const part = new Int32Array(n).fill(-1);
64
+ const gather = (list) => {
65
+ let [lead, start, open] = [-1, 0, false];
66
+ const last = list.findLast(i => to[i] > from[i]);
67
+ for (const i of list) {
68
+ if (!(to[i] > from[i]))
69
+ continue;
70
+ if (!open)
71
+ [lead, start, open] = [i, from[i], true];
72
+ if (to[i] - from[i] > to[lead] - from[lead])
73
+ lead = i;
74
+ part[i] = shapes.length;
75
+ const [near, far] = reach(i);
76
+ const span = to[i] - start;
77
+ if (span * TURN * far < 1 && i !== last)
78
+ continue;
79
+ const gap = span >= 1 || !outer ? 0 : Math.min(0.5 / far, (span * TURN) / 4);
80
+ const [a, b] = [start * TURN - TURN / 4 + gap, to[i] * TURN - TURN / 4 - gap];
81
+ const path = new Path2D();
82
+ path.arc(cx, cy, far, a, b);
83
+ path.arc(cx, cy, near, b, a, true);
84
+ path.closePath();
85
+ shapes.push({ path, lead });
86
+ open = false;
87
+ }
88
+ };
89
+ gather(roots);
90
+ for (const node of order)
91
+ if (to[node] > from[node])
92
+ gather(kids[node]);
93
+ const faded = (ring) => 0.4 + 0.6 * (1 - ring / rings);
94
+ const inks = new Map();
95
+ for (const { lead } of o.shade === undefined ? [] : shapes) {
96
+ if (inks.has(shade(lead)))
97
+ continue;
98
+ const [red, green, blue, a = 1] = rgba(ctx, shade(lead)).map((v, at) => at < 3 ? Math.round(v * 255) : v);
99
+ const out = ctx.createRadialGradient(cx, cy, 0, cx, cy, outer || 1);
100
+ out.addColorStop(0, `rgba(${red},${green},${blue},${a})`);
101
+ out.addColorStop(1, `rgba(${red},${green},${blue},${a * o.shade})`);
102
+ inks.set(shade(lead), out);
103
+ }
104
+ // Half-way round the node and half-way out; a disc is named at its centre.
105
+ const anchor = (i) => {
106
+ const [near, far] = reach(i);
107
+ if (whole(i) && !near)
108
+ return [cx, cy];
109
+ const middle = ((from[i] + to[i]) / 2) * TURN - TURN / 4;
110
+ return [
111
+ cx + (Math.cos(middle) * (near + far)) / 2,
112
+ cy + (Math.sin(middle) * (near + far)) / 2,
113
+ ];
114
+ };
115
+ const labels = [];
116
+ for (const i of o.text === false || !outer ? [] : largest) {
117
+ const text = o.text ? o.text(i) : named(i);
118
+ const [x, y] = anchor(i);
119
+ if (!text || !inRing([cx, cy, ...reach(i), from[i], to[i]], x, y, text.length * 7 * dpr, 16 * dpr))
120
+ continue;
121
+ labels.push({ x, y, text, color: '#fff', priority: size[i] / 2 ** depth[i] });
122
+ }
123
+ return {
124
+ labels,
125
+ paint(k, row, rest = 1) {
126
+ const lit = new Map();
127
+ if (row !== undefined && row < n) {
128
+ for (const above of over(row))
129
+ lit.set(part[above], (1 + rest) / 2);
130
+ lit.set(part[row], 1);
131
+ }
132
+ shapes.forEach(({ path, lead }, at) => {
133
+ ctx.globalAlpha =
134
+ alpha *
135
+ k *
136
+ (row === undefined ? 1 : (lit.get(at) ?? rest)) *
137
+ (inks.size ? 1 : faded(depth[lead]));
138
+ ctx.fillStyle = inks.get(shade(lead)) ?? shade(lead);
139
+ ctx.fill(path);
140
+ });
141
+ },
142
+ // The ring from the distance, then down from the roots by the share of the turn, and
143
+ // last the painted shape itself, which leaves out the gaps between neighbours.
144
+ hit(px, py, max) {
145
+ const [hx, hy] = [px * dpr, py * dpr];
146
+ const ring = Math.floor(Math.hypot(hx - cx, hy - cy) / (thick || 1));
147
+ if (!thick || ring >= rings)
148
+ return null;
149
+ const at = turnAt(hx - cx, hy - cy);
150
+ // Siblings start in ascending order, so the one holding the pointer is the last to
151
+ // start at or before it.
152
+ const holding = (list) => {
153
+ let [lo, hi] = [0, list.length];
154
+ while (lo < hi) {
155
+ const mid = (lo + hi) >> 1;
156
+ if (from[list[mid]] <= at)
157
+ lo = mid + 1;
158
+ else
159
+ hi = mid;
160
+ }
161
+ return lo ? list[lo - 1] : undefined;
162
+ };
163
+ let node = holding(roots);
164
+ while (node !== undefined && depth[node] < ring)
165
+ node = holding(kids[node]);
166
+ const shape = node === undefined ? undefined : shapes[part[node]];
167
+ if (node === undefined || !shape)
168
+ return null;
169
+ // A node gathered with its neighbours answers from the gaps round them too.
170
+ const wide = (to[node] - from[node]) * TURN * reach(node)[1] >= 1;
171
+ if (wide && !ctx.isPointInPath(shape.path, hx, hy))
172
+ return null;
173
+ const [x, y] = anchor(node);
174
+ return {
175
+ x: (x - left) / width,
176
+ y: 1 - (y - top) / height,
177
+ distance: max,
178
+ row: node,
179
+ color: shade(node),
180
+ };
181
+ },
182
+ };
183
+ },
184
+ };
185
+ }
@@ -0,0 +1,9 @@
1
+ import type { Col, Mark } from '../types.js';
2
+ import type { Common } from './common.js';
3
+ /** A vertical tick of `size` CSS pixels above and below each point. */
4
+ export type TicksOptions = Common & {
5
+ x: Col;
6
+ y: Col;
7
+ size: number;
8
+ };
9
+ export declare function ticks(o: TicksOptions): Mark;
@@ -0,0 +1,26 @@
1
+ import { base } from './common.js';
2
+ export function ticks(o) {
3
+ const { x, y, color, size, alpha = 1 } = o;
4
+ return {
5
+ ...base('ticks', o, [x], [y]),
6
+ oneShape: true,
7
+ prepare({ ctx, dpr, ox, kx, oy, ky }) {
8
+ const h = size * dpr;
9
+ const path = new Path2D();
10
+ for (let i = 0; i < x.length; i++) {
11
+ const px = ox + x[i] * kx;
12
+ const py = oy - y[i] * ky;
13
+ path.moveTo(px, py - h);
14
+ path.lineTo(px, py + h);
15
+ }
16
+ return {
17
+ paint(a) {
18
+ ctx.globalAlpha = alpha * a;
19
+ ctx.lineWidth = dpr;
20
+ ctx.strokeStyle = color;
21
+ ctx.stroke(path);
22
+ },
23
+ };
24
+ },
25
+ };
26
+ }
@@ -0,0 +1,41 @@
1
+ import type { Col } from '../types.js';
2
+ /**
3
+ * A hierarchy in columns: `parent` holds the place in `nodes` of each node's parent, negative
4
+ * for a root. Only the values of nodes without children count; a node with children is as large
5
+ * as they are together, so a parent's own share needs a child of its own. A value that is
6
+ * negative or not a number counts as 0.
7
+ */
8
+ export type TreeColumns = {
9
+ nodes: string[];
10
+ parent: Col;
11
+ value: Col;
12
+ };
13
+ export type Nested = {
14
+ name: string;
15
+ value?: number;
16
+ children?: Nested[];
17
+ };
18
+ /** The columns of a nested tree, or of several. Nodes that share a name stay separate nodes. */
19
+ export declare function fromTree(tree: Nested | Nested[]): {
20
+ nodes: string[];
21
+ parent: number[];
22
+ value: number[];
23
+ };
24
+ /** The `count` first of `list` in the order `before` gives, without sorting all of it. */
25
+ export declare function first(list: number[], count: number, before: (a: number, b: number) => number): number[];
26
+ /**
27
+ * What both tree marks lay out. Sizes are shares of the largest value, so that sums of them
28
+ * cannot overflow. `tint` numbers the branches that get a colour each: the roots, or the
29
+ * children of a single root, which itself has -1. Nothing here recurses, so a tree may be as
30
+ * deep as it likes. A parent out of range, a node that is its own parent and a cycle throw.
31
+ */
32
+ export declare function grow({ nodes, parent, value }: TreeColumns, who: string): {
33
+ n: number;
34
+ kids: number[][];
35
+ roots: number[];
36
+ order: number[];
37
+ depth: Int32Array<ArrayBuffer>;
38
+ tint: Int32Array<ArrayBuffer>;
39
+ size: Float64Array<ArrayBuffer>;
40
+ named: (i: number) => string;
41
+ };