Repository navigation
Expand file tree
/
Copy pathstack.js
More file actions
610 lines (575 loc) · 25.8 KB
/
Copy pathstack.js
File metadata and controls
610 lines (575 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// The hero stacks, drawn like the SQLStack mark: a column of dot-shaded discs on the mark's swoosh
// brim. The discs turn slowly; the swoosh keeps its shape, and its dots flow along it at the same
// speed. Each layer has a real link laid over it, clipped to the shapes it draws, so hover, click
// and keyboard focus all come from the links; the canvas only draws. A tool in both stacks lights
// up in both. Links marked data-brim are the brim's strips, top first; the rest are discs, top first.
(() => {
const TILT = 0.47; // camera elevation in radians
const SIN = Math.sin(TILT);
const COS = Math.cos(TILT);
const TAU = Math.PI * 2;
// In units of the column's radius. Heights are measured up from the column's base.
const COLUMN_HEIGHT = 0.95;
const LAYER_GAP = 0.09;
const BRIM_INNER = 1.1;
const BRIM_WIDTH = 0.62;
const BRIM_THICK = 0.09;
const STRIP_GAP = 0.1;
const STRIP_GROWTH = 0.28; // a lower strip reaches further out, so its lip shows
const T0 = (-100 * Math.PI) / 180; // the swoosh's left tip; 0 is the front
const T1 = (118 * Math.PI) / 180; // its back-right tip
const BRIM_LIFT = 0.02;
// The brim dips at the front and rises on the right, like the mark; the whole hat turns a little left.
const ROTATE_Z = [Math.cos(0.34), Math.sin(0.34)];
const ROTATE_X = [Math.cos(0.1), Math.sin(0.1)];
const ROTATE_Y = [Math.cos(-0.15), Math.sin(-0.15)];
const TURN_SECONDS = 48;
// The discs turn together, like a planet's body. The brim's strips circle like its rings: the top
// one keeps the discs' pace and each one below lags a little, so nothing moves faster than the discs.
const RING_SPEEDS = [1, 0.85, 0.7];
const SPOKES = 96;
const ROWS = 3;
const RINGS = 5;
const FLOW_STEPS = 72;
const LANE_SPACING = 0.15;
const SEGMENTS = 96;
const LIGHT = (() => {
const v = [-0.62, 0.55, 0.56];
const n = Math.hypot(...v);
return v.map((c) => c / n);
})();
const CAP_LIGHT = 0.25 + 0.75 * Math.max(0, LIGHT[1]);
const wallLight = (nx, nz) => 0.2 + 0.8 * Math.max(0, nx * LIGHT[0] + nz * LIGHT[2]);
function hexToRgb(value) {
const hex = value.trim().replace('#', '');
const full = hex.length === 3 ? hex.split('').map((c) => c + c).join('') : hex;
const n = parseInt(full, 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function mix(a, b, t) {
return a.map((c, i) => Math.round(c + (b[i] - c) * t));
}
// The swoosh: tapers to a point at both tips, widest at the front left.
const tAt = (u) => T0 + (T1 - T0) * u;
const widthAt = (u, strip) => (1 + STRIP_GROWTH * strip) * BRIM_WIDTH * Math.sin(Math.PI * u ** 0.7) ** 0.85;
function rotate([x, y, z]) {
[x, y] = [x * ROTATE_Z[0] - y * ROTATE_Z[1], x * ROTATE_Z[1] + y * ROTATE_Z[0]];
[y, z] = [y * ROTATE_X[0] - z * ROTATE_X[1], y * ROTATE_X[1] + z * ROTATE_X[0]];
[x, z] = [x * ROTATE_Y[0] + z * ROTATE_Y[1], -x * ROTATE_Y[1] + z * ROTATE_Y[0]];
return [x, y, z];
}
// A point on brim strip `strip` (0 is the top one), at distance r from the axis and height y on it.
function brimPoint(strip, u, r, y) {
const t = tAt(u);
const p = rotate([Math.sin(t) * r, y - strip * (BRIM_THICK + STRIP_GAP), Math.cos(t) * r]);
p[1] += BRIM_LIFT;
return p;
}
// Where each strip is in front of the column and where behind it, as runs of segments.
function brimRuns(strip) {
const runs = [];
for (let i = 0; i < SEGMENTS; i += 1) {
const u = (i + 0.5) / SEGMENTS;
const front = brimPoint(strip, u, BRIM_INNER + widthAt(u, strip) / 2, 0)[2] >= 0;
const last = runs[runs.length - 1];
if (last && last.front === front) last.to = i + 1;
else runs.push({ front, from: i, to: i + 1 });
}
return runs;
}
// Projected extent of a stack with this many strips, at scale 1 around the origin.
function extent(strips) {
const box = [Infinity, -Infinity, Infinity, -Infinity];
const add = ([x, y, z]) => {
const sx = x;
const sy = z * SIN - y * COS;
box[0] = Math.min(box[0], sx); box[1] = Math.max(box[1], sx);
box[2] = Math.min(box[2], sy); box[3] = Math.max(box[3], sy);
};
for (let s = 0; s < 64; s += 1) {
const t = (s / 64) * TAU;
add([Math.sin(t), COLUMN_HEIGHT, Math.cos(t)]);
add([Math.sin(t), 0, Math.cos(t)]);
}
for (let strip = 0; strip < strips; strip += 1) {
for (let i = 0; i <= SEGMENTS; i += 1) {
const u = i / SEGMENTS;
for (const r of [BRIM_INNER, BRIM_INNER + widthAt(u, strip)]) {
add(brimPoint(strip, u, r, 0));
add(brimPoint(strip, u, r, -BRIM_THICK));
}
}
}
return box;
}
// Every stack is fitted as if it had two strips, so the columns match in size and place.
const REFERENCE = extent(2);
function init(root) {
const canvas = root.querySelector('canvas');
const links = [...root.querySelectorAll('[data-layer]')];
const ctx = canvas.getContext('2d');
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)');
const discs = links.filter((link) => !link.hasAttribute('data-brim'));
const strips = links.filter((link) => link.hasAttribute('data-brim'));
const own = extent(strips.length);
const height = (COLUMN_HEIGHT - (discs.length - 1) * LAYER_GAP) / discs.length;
const hit = (link) => {
const span = document.createElement('span');
span.className = 'hit';
link.prepend(span);
return span;
};
const layers = links.map((link) => ({ link, glow: 0, target: 0 }));
const layerOf = new Map(layers.map((layer) => [layer.link, layer]));
const discParts = discs.map((link, i) => ({
layer: layerOf.get(link),
top: COLUMN_HEIGHT - i * (height + LAYER_GAP),
span: hit(link),
}));
const stripParts = strips.map((link, strip) => ({
layer: layerOf.get(link),
strip,
runs: brimRuns(strip).map((run) => ({ ...run, span: hit(link) })),
dots: flowDots(strip),
}));
// In the tool section (data-labels-beside) the mark behaves like a tower of tools: the picked
// layer's neighbours move apart to make room for it, and a click knocks the layer it hits, the
// push running on through the others. Both are moves on screen, so each layer is drawn shifted.
const order = [...discParts.map((part) => part.layer), ...stripParts.map((part) => part.layer)]; // top to bottom
const OPEN = 0.14; // extra room above and below the picked layer, in column radii
const kicks = [];
let bouncing = false;
for (const layer of layers) Object.assign(layer, { o: { x: 0, y: 0, vx: 0, vy: 0 }, tx: 0, ty: 0, spans: [] });
for (const part of discParts) part.layer.spans.push(part.span);
for (const part of stripParts) part.layer.spans.push(...part.runs.map((run) => run.span));
let width = 0;
let scale = 0;
let cx = 0;
let cy = 0;
let dpr = 1;
let ink = [23, 26, 31];
let background = [255, 255, 255];
let line = [200, 200, 200];
// With data-labels-beside, every layer's name sits in a column to the right of the mark, joined to
// its layer by a dotted leader, instead of under the stack while it is pointed at.
const beside = root.hasAttribute('data-labels-beside');
let leaders = [];
let angle = 0.6;
let last = 0;
let frame = 0;
let onScreen = true;
const project = ([x, y, z]) => [cx + scale * x, cy + scale * (z * SIN - y * COS)];
function readColours() {
const style = getComputedStyle(document.documentElement);
ink = hexToRgb(style.getPropertyValue('--ink'));
background = hexToRgb(style.getPropertyValue('--background'));
line = hexToRgb(style.getPropertyValue('--line'));
for (const layer of layers) {
layer.accent = hexToRgb(getComputedStyle(layer.link).getPropertyValue('--accent'));
}
}
// Quads with the same winding, so their union fills under the nonzero rule.
function quad(points) {
let area = 0;
points.forEach(([x1, y1], i) => {
const [x2, y2] = points[(i + 1) % points.length];
area += x1 * y2 - x2 * y1;
});
if (area < 0) points.reverse();
return `M${points.map(([x, y]) => `${x.toFixed(1)} ${y.toFixed(1)}`).join('L')}Z`;
}
function discOutline(part) {
const r = scale;
const ry = r * SIN;
const topY = cy - scale * part.top * COS;
const bottomY = cy - scale * (part.top - height) * COS;
const f = (n) => n.toFixed(1);
return `M${f(cx - r)} ${f(topY)}A${f(r)} ${f(ry)} 0 0 1 ${f(cx + r)} ${f(topY)}L${f(cx + r)} ${f(bottomY)}`
+ `A${f(r)} ${f(ry)} 0 0 1 ${f(cx - r)} ${f(bottomY)}Z`;
}
function runOutline(strip, run) {
let d = '';
for (let i = run.from; i < run.to; i += 1) {
const ua = i / SEGMENTS;
const ub = (i + 1) / SEGMENTS;
const ra = BRIM_INNER + widthAt(ua, strip);
const rb = BRIM_INNER + widthAt(ub, strip);
const p = (u, r, y) => project(brimPoint(strip, u, r, y));
const [iA, iB, oA, oB] = [p(ua, BRIM_INNER, 0), p(ub, BRIM_INNER, 0), p(ua, ra, 0), p(ub, rb, 0)];
const [jA, jB, qA, qB] = [p(ua, BRIM_INNER, -BRIM_THICK), p(ub, BRIM_INNER, -BRIM_THICK), p(ua, ra, -BRIM_THICK), p(ub, rb, -BRIM_THICK)];
d += quad([iA, oA, oB, iB]) + quad([oA, qA, qB, oB]) + quad([iA, jA, jB, iB]);
}
return d;
}
function layout() {
width = root.clientWidth;
if (!width) return;
dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(root.clientHeight * dpr);
const floor = width * 0.86;
let room = 0;
if (beside) {
room = width - Math.max(0, ...links.map((link) => link.querySelector('.label').offsetWidth)) - 44;
const tall = root.clientHeight;
// Inset, so a layer knocked left isn't cut off at the canvas edge.
scale = Math.min((room - 32) / (own[1] - own[0]), (tall * 0.94) / (own[3] - own[2]));
cx = room / 2 - (scale * (own[0] + own[1])) / 2;
cy = tall / 2 - (scale * (own[2] + own[3])) / 2;
} else {
scale = Math.min((width * 0.94) / (REFERENCE[1] - REFERENCE[0]), (width * 0.8) / (REFERENCE[3] - REFERENCE[2]));
cx = width / 2 - (scale * (REFERENCE[0] + REFERENCE[1])) / 2;
// Stand every stack on the same floor, whatever its height.
cy = floor - scale * own[3];
}
const caption = floor + 14;
root.style.setProperty('--caption-y', `${caption}px`);
for (const link of links) {
link.style.setProperty('--label-x', `${width / 2}px`);
link.style.setProperty('--label-y', `${caption}px`);
}
// Each shape gets a hit area in the order it is painted, so the one on top takes the pointer.
let order = 0;
const place = (span, d) => {
span.style.clipPath = `path('${d}')`;
span.style.zIndex = String((order += 1));
return new Path2D(d);
};
const runs = (front) => [...stripParts].reverse().flatMap((part) => part.runs.filter((run) => run.front === front).map((run) => [part, run]));
for (const [part, run] of runs(false)) run.path = place(run.span, runOutline(part.strip, run));
for (const part of [...discParts].reverse()) part.path = place(part.span, discOutline(part));
for (const [part, run] of runs(true)) run.path = place(run.span, runOutline(part.strip, run));
if (beside) placeBeside(room);
}
// Each layer's anchor is its right-hand edge. The names keep the stack's order, top disc to
// bottom strip, at least a line apart, in one column past the widest anchor.
function placeBeside(room) {
const anchors = [
...discParts.map((part) => {
const y = cy - scale * (part.top - height / 2) * COS;
part.layer.centre = [cx, y];
return { layer: part.layer, x: cx + scale, y };
}),
...stripParts.map((part) => {
let best = null;
for (let i = 0; i <= SEGMENTS; i += 1) {
const u = i / SEGMENTS;
const [x, y] = project(brimPoint(part.strip, u, BRIM_INNER + widthAt(u, part.strip), -BRIM_THICK / 2));
if (!best || x > best.x) best = { layer: part.layer, x, y };
}
part.layer.centre = project(brimPoint(part.strip, 0.5, BRIM_INNER + widthAt(0.5, part.strip) / 2, -BRIM_THICK / 2));
return best;
}),
];
const column = Math.max(room, ...anchors.map((a) => a.x)) + 28;
const gap = 30;
let previous = -Infinity;
for (const anchor of anchors) {
anchor.labelY = Math.max(anchor.y, previous + gap);
previous = anchor.labelY;
}
// Centre the names on their anchors as a group, so pushing some down doesn't drag them all.
const drift = anchors.reduce((sum, a) => sum + a.labelY - a.y, 0) / anchors.length;
for (const anchor of anchors) {
anchor.labelY -= drift;
anchor.labelX = column;
anchor.layer.link.style.setProperty('--label-x', `${column}px`);
anchor.layer.link.style.setProperty('--label-y', `${anchor.labelY + anchor.layer.ty}px`);
anchor.layer.labelY = anchor.labelY;
// A knock towards the names eases to a stop within a few pixels, so no layer reaches the leaders.
anchor.layer.room = 8;
}
leaders = anchors;
}
function paintLeaders() {
ctx.setLineDash([1, 3]);
ctx.lineWidth = 1;
for (const { layer, x, y, labelX, labelY } of leaders) {
ctx.beginPath();
ctx.moveTo(x + 8 + layer.tx, y + layer.ty);
ctx.lineTo(labelX - 8, labelY + layer.ty);
ctx.strokeStyle = `rgb(${mix(line, layer.accent, layer.glow)})`;
ctx.stroke();
}
ctx.setLineDash([]);
}
// Dots on one strip. The swoosh holds still; each dot slides along it by `phase`, a fraction of
// its length, so the brim seems to turn with the discs. Lanes thin out where the swoosh narrows.
function flowDots(strip) {
const lanes = Math.ceil(((1 + STRIP_GROWTH * strip) * BRIM_WIDTH) / LANE_SPACING);
const items = [];
for (let i = 0; i < FLOW_STEPS; i += 1) {
const u = i / FLOW_STEPS;
for (let lane = 0; lane < lanes; lane += 1) items.push({ u, lane });
items.push({ u, edge: true });
for (let row = 0; row < 2; row += 1) items.push({ u, row });
}
const clamp = (x) => Math.max(0, Math.min(1, x));
return (phase) => items.map((item) => {
const u = (((item.u + phase) % 1) + 1) % 1;
const w = widthAt(u, strip);
if (item.lane !== undefined) {
const visible = clamp((w - (item.lane + 0.5) * LANE_SPACING) / 0.015);
const point = brimPoint(strip, u, BRIM_INNER + item.lane * LANE_SPACING, 0);
return { point, light: CAP_LIGHT * (0.85 + (0.15 * item.lane) / lanes), visible };
}
if (item.edge) return { point: brimPoint(strip, u, BRIM_INNER + w, 0), light: CAP_LIGHT, visible: clamp(w / 0.02) };
const t = tAt(u);
const [nx, ny, nz] = rotate([Math.sin(t), 0, Math.cos(t)]);
// The outer wall shows only where it faces the camera.
const facing = ny * SIN + nz * COS > -0.05;
const point = brimPoint(strip, u, BRIM_INNER + w, -((item.row + 0.5) / 2) * BRIM_THICK);
return { point, light: wallLight(nx, nz), visible: facing ? clamp(w / 0.05) : 0 };
});
}
function paintDots(layer, points, lit) {
const colour = mix(ink, layer.accent, layer.glow);
const fade = 1 - 0.55 * (lit - layer.glow);
const dot = (width * 0.4) / 165;
const buckets = [[], [], [], [], []];
for (const { at, light, visible } of points) {
if (visible > 0.01) buckets[Math.min(4, Math.floor(light * 5))].push(at, visible);
}
buckets.forEach((items, b) => {
if (!items.length) return;
const light = (b + 0.5) / 5;
const radius = dot * (0.45 + 1.1 * light) * (1 + 0.25 * layer.glow);
ctx.beginPath();
for (let i = 0; i < items.length; i += 2) {
const [x, y] = items[i];
const r = radius * items[i + 1];
ctx.moveTo(x + r, y);
ctx.arc(x, y, r, 0, TAU);
}
ctx.globalAlpha = Math.min(1, (0.3 + 0.7 * light) * fade);
ctx.fillStyle = `rgb(${colour})`;
ctx.fill();
});
ctx.globalAlpha = 1;
}
function paintDisc(part, lit) {
const points = [];
for (let s = 0; s < SPOKES; s += 1) {
const theta = (s / SPOKES) * TAU + angle;
const nx = Math.sin(theta);
const nz = Math.cos(theta);
if (nz < -0.05) continue;
const light = wallLight(nx, nz);
for (let row = 0; row < ROWS; row += 1) {
const y = part.top - ((row + 0.5) / ROWS) * height;
points.push({ at: project([nx, y, nz]), light, visible: 1 });
}
}
for (let ring = 1; ring <= RINGS; ring += 1) {
const rho = ring / RINGS;
const spokes = Math.round(SPOKES * rho);
for (let s = 0; s < spokes; s += 1) {
const theta = (s / spokes) * TAU + angle;
const nx = Math.sin(theta);
const nz = Math.cos(theta);
// A little shading towards the light keeps the cap from reading flat.
const light = CAP_LIGHT * (0.75 + (0.25 * rho * (nx * LIGHT[0] + nz * LIGHT[2] + 1)) / 2);
points.push({ at: project([rho * nx, part.top, rho * nz]), light, visible: 1 });
}
}
paintDots(part.layer, points, lit);
}
function draw() {
if (!width) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, canvas.height);
const lit = Math.max(...layers.map((layer) => layer.glow));
const phase = angle / (T1 - T0);
const flows = stripParts.map((part) => part.dots(phase * RING_SPEEDS[Math.min(part.strip, RING_SPEEDS.length - 1)]));
// Back to front: the brim behind the column, the column from its base up, then the brim in front.
// Each shape first hides whatever it covers.
const paintStrips = (front) => {
for (let k = stripParts.length - 1; k >= 0; k -= 1) {
const part = stripParts[k];
ctx.save();
ctx.translate(part.layer.tx, part.layer.ty);
ctx.fillStyle = `rgb(${background})`;
for (const run of part.runs) if (run.front === front) ctx.fill(run.path);
const points = flows[k]
.filter(({ point }) => (point[2] >= 0) === front)
.map(({ point, light, visible }) => ({ at: project(point), light, visible }));
paintDots(part.layer, points, lit);
ctx.restore();
}
};
paintStrips(false);
for (let i = discParts.length - 1; i >= 0; i -= 1) {
ctx.save();
ctx.translate(discParts[i].layer.tx, discParts[i].layer.ty);
ctx.fillStyle = `rgb(${background})`;
ctx.fill(discParts[i].path);
paintDisc(discParts[i], lit);
ctx.restore();
}
paintStrips(true);
if (beside) paintLeaders();
}
function moving() {
return !reduced.matches && onScreen && !document.hidden;
}
function settling() {
return layers.some((layer) => Math.abs(layer.glow - layer.target) > 0.01);
}
function tick(now) {
frame = 0;
const elapsed = last ? Math.min(now - last, 100) : 0;
// Thirty frames a second is plenty for a slow turn; a knock gets sixty.
if (last && elapsed < (bouncing ? 15 : 32)) {
frame = requestAnimationFrame(tick);
return;
}
last = now;
if (moving()) angle += (elapsed / 1000) * (TAU / TURN_SECONDS);
const step = reduced.matches ? 1 : Math.min(1, elapsed / 160) || 0.2;
for (const layer of layers) layer.glow += (layer.target - layer.glow) * step;
if (beside) bouncing = move(now, elapsed);
draw();
if (moving() || settling() || bouncing) frame = requestAnimationFrame(tick);
else last = 0;
}
// Knocked layers spring back with a little overshoot; the rest open around the picked one.
function move(now, elapsed) {
while (kicks.length && kicks[0].at <= now) {
const k = kicks.shift();
k.o.vx += k.vx;
k.o.vy += k.vy;
}
let still = kicks.length === 0;
const sub = elapsed / 1000 / 4;
for (const { o } of order) {
for (let i = 0; i < 4; i += 1) {
o.vx += (-90 * o.x - 6 * o.vx) * sub;
o.vy += (-90 * o.y - 6 * o.vy) * sub;
o.x += o.vx * sub;
o.y += o.vy * sub;
}
if (Math.abs(o.x) + Math.abs(o.y) + (Math.abs(o.vx) + Math.abs(o.vy)) / 20 > 0.05) still = false;
else o.x = o.y = o.vx = o.vy = 0;
}
order.forEach((layer, i) => {
const shift = order.reduce((sum, other, j) => sum + (j === i ? 0 : (j > i ? 1 : -1) * OPEN * other.glow), 0);
const room = layer.room ?? 12;
layer.tx = layer.o.x > 0 ? room * Math.tanh(layer.o.x / room) : layer.o.x;
layer.ty = layer.o.y - scale * shift * COS;
const transform = `translate(${layer.tx.toFixed(1)}px, ${layer.ty.toFixed(1)}px)`;
for (const span of layer.spans) span.style.transform = transform;
if (layer.labelY !== undefined) layer.link.style.setProperty('--label-y', `${layer.labelY + layer.ty}px`);
});
return !still;
}
// The clicked layer is pushed away from the click, and the push runs on through the others.
function knock(clicked, event) {
const box = root.getBoundingClientRect();
const x = event.clientX - box.left;
const y = event.clientY - box.top;
const near = order.indexOf(clicked);
const [mx, my] = [clicked.centre[0] + clicked.tx, clicked.centre[1] + clicked.ty];
const reach = Math.max(0.35, 1 - Math.max(0, Math.hypot(x - mx, y - my) - scale * 1.1) / (scale * 2));
const dx = mx - x;
const dy = (my - y) * 0.5;
const len = Math.hypot(dx, dy) || 1;
const at = performance.now();
const speed = scale * 3;
order.forEach((layer, i) => {
const f = reach * 0.55 ** Math.abs(i - near);
kicks.push({ o: layer.o, at: at + 60 * Math.abs(i - near), vx: (dx / len) * speed * f, vy: (dy / len) * speed * f });
});
kicks.sort((a, b) => a.at - b.at);
bouncing = true;
wake();
}
function wake() {
if (!frame) frame = requestAnimationFrame(tick);
}
// The tool being pointed at, in this stack or the other one, or else the one picked for this
// stack with a stack:pick event on it.
let hovered = null;
let picked = null;
const retarget = () => {
// In the tool section only the picked tool lights, so the pointer passing over the mark on its
// way to the card doesn't flash other layers.
const tool = beside ? picked : hovered ?? picked;
for (const layer of layers) {
layer.target = layer.link.dataset.layer === tool ? 1 : 0;
layer.link.classList.toggle('is-on', layer.link.dataset.layer === tool);
}
wake();
};
document.addEventListener('stack:active', ({ detail }) => {
hovered = detail.tool;
for (const layer of layers) layer.link.classList.toggle('is-active', layer.link === detail.link);
retarget();
});
root.addEventListener('stack:pick', ({ detail }) => {
picked = detail;
retarget();
});
document.fonts?.ready.then(() => {
layout();
draw();
});
const announce = (link) => {
document.dispatchEvent(new CustomEvent('stack:active', { detail: { tool: link?.dataset.layer ?? null, link } }));
};
// On a touch screen a tap picks a layer instead of opening its site: the layer lights up and
// the tool card below switches to it, and the card links to the site. Tapping anywhere else
// puts the layer out. A mouse click, Enter or a screen reader's activation still opens it.
let tapped = null;
for (const layer of layers) {
layer.link.addEventListener('pointerenter', (event) => { if (event.pointerType !== 'touch') announce(layer.link); });
layer.link.addEventListener('pointerleave', (event) => { if (event.pointerType !== 'touch') announce(null); });
layer.link.addEventListener('pointerdown', (event) => {
tapped = event.pointerType === 'touch' ? layer.link : null;
});
layer.link.addEventListener('click', (event) => {
const tap = tapped;
tapped = null;
// In the tool section a click on a layer picks its tool and knocks it; its name opens the site.
if (beside && event.target.classList?.contains('hit')) {
event.preventDefault();
root.dispatchEvent(new CustomEvent('stack:choose', { detail: layer.link.dataset.layer }));
if (!reduced.matches) knock(layer, event);
return;
}
if (tap !== layer.link) return;
event.preventDefault();
// Safari doesn't focus a tapped link; the tool cards pick a focused layer straight away.
layer.link.focus({ preventScroll: true });
announce(layer.link);
});
layer.link.addEventListener('focus', () => announce(layer.link));
layer.link.addEventListener('blur', () => announce(null));
}
document.addEventListener('pointerdown', (event) => {
if (event.pointerType !== 'touch' || event.target.closest?.('.stack-labels a')) return;
if (layers.some((layer) => layer.link.classList.contains('is-active'))) announce(null);
});
new ResizeObserver(() => {
layout();
draw();
}).observe(root);
new IntersectionObserver(([entry]) => {
onScreen = entry.isIntersecting;
wake();
}).observe(root);
new MutationObserver(() => {
readColours();
draw();
}).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
document.addEventListener('visibilitychange', wake);
reduced.addEventListener('change', wake);
readColours();
layout();
draw();
wake();
}
window.SQLStackMark = init;
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('[data-stack]').forEach(init);
});
})();