@jsb188/gfx 1.1.2 → 1.1.11

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 (56) hide show
  1. package/README.md +54 -248
  2. package/libs/dotGrid.ts +77 -480
  3. package/libs/effects/effectQuad.ts +2 -8
  4. package/libs/pointer.ts +0 -6
  5. package/libs/runtime.ts +4 -6
  6. package/libs/types.ts +1 -8
  7. package/main.ts +0 -2
  8. package/modules/Carousel.helpers.ts +0 -234
  9. package/modules/Carousel.tsx +29 -135
  10. package/modules/DotsArea.tsx +120 -0
  11. package/modules/GfxCanvas.tsx +2 -10
  12. package/modules/ScrollSteps.tsx +52 -7
  13. package/modules/VisionBoard.helpers.ts +561 -0
  14. package/modules/VisionBoard.tsx +358 -0
  15. package/modules/VisionBoard.types.ts +88 -0
  16. package/package.json +5 -15
  17. package/scenes/Carousel.ts +18 -99
  18. package/scenes/DotsArea.ts +208 -0
  19. package/tsconfig.json +1 -1
  20. package/utils/color.ts +2 -64
  21. package/utils/dotGridSpecs.ts +46 -304
  22. package/elements/Shapes.helpers.ts +0 -204
  23. package/elements/Shapes.hooks.ts +0 -171
  24. package/elements/Shapes.tsx +0 -505
  25. package/elements/Shapes.types.ts +0 -81
  26. package/elements/Stack.helpers.ts +0 -42
  27. package/elements/Stack.tsx +0 -143
  28. package/elements/Text.helpers.ts +0 -45
  29. package/elements/Text.hooks.ts +0 -197
  30. package/elements/Text.tsx +0 -98
  31. package/libs/dotGrid.helpers.ts +0 -53
  32. package/libs/effects/dotEffects.ts +0 -136
  33. package/modules/Carousel.hooks.ts +0 -520
  34. package/modules/Dots.tsx +0 -269
  35. package/modules/DotsBoard.helpers.ts +0 -388
  36. package/modules/DotsBoard.hooks.ts +0 -144
  37. package/modules/DotsBoard.strings.ts +0 -649
  38. package/modules/DotsBoard.types.ts +0 -240
  39. package/modules/DotsBoardCanvas.hooks.ts +0 -49
  40. package/modules/DotsBoardCanvas.tsx +0 -190
  41. package/modules/DotsBoardElements.tsx +0 -330
  42. package/modules/Gallery.helpers.ts +0 -32
  43. package/modules/Gallery.hooks.ts +0 -149
  44. package/modules/Gallery.tsx +0 -194
  45. package/modules/KineticHeader.helpers.ts +0 -44
  46. package/modules/KineticHeader.hooks.ts +0 -206
  47. package/modules/KineticHeader.tsx +0 -305
  48. package/modules/KineticHeader.types.ts +0 -56
  49. package/modules/ScrollSteps.hooks.ts +0 -138
  50. package/scenes/DotsBoard.helpers.ts +0 -12
  51. package/scenes/DotsBoard.ts +0 -245
  52. package/utils/align.ts +0 -18
  53. package/utils/dotEffectSpecs.ts +0 -79
  54. package/utils/motion.ts +0 -88
  55. package/utils/random.ts +0 -22
  56. package/utils/strings.ts +0 -116
@@ -1,649 +0,0 @@
1
- import { SPRING_PHYSICS, prefersReducedMotion, snapSpring, springBodyAt, stepSpring } from '../utils/motion.ts';
2
- import type { SpringBody } from '../utils/motion.ts';
3
- import {
4
- buildStringPath,
5
- getNearestStringPoint,
6
- getQuadraticPoint,
7
- getStringCrossing,
8
- getStringRestControl,
9
- lerpPoint,
10
- } from '../utils/strings.ts';
11
- import type { Point } from '../utils/strings.ts';
12
- import { DOTS_STRING_DEFAULTS } from './DotsBoard.helpers.ts';
13
- import type { DotsBoardStringOptions, DotsBoardStringSpec, Offset } from './DotsBoard.types.ts';
14
-
15
- /**
16
- * Types
17
- */
18
-
19
- /** A point the string is pinned at: a spring body that follows its item's dot. */
20
- interface Knot extends SpringBody {
21
- item: string;
22
- }
23
-
24
- /**
25
- * Where strings draw: the board's own `<svg>`s, or a pinned layer's. Each has its own groups,
26
- * translated so board-pixel paths draw in its pixels, and its own pointer host.
27
- */
28
- interface StringSurface {
29
- root: SVGGElement;
30
- hitRoot: SVGGElement;
31
- svgs: StringSvgs | null;
32
- /** Where the surface's top-left corner rests in the board. */
33
- offset: Offset;
34
- /** The element the pointer is followed on: the parent of the surface's `<svg>`. */
35
- host: HTMLElement | null;
36
- /** Where the pointer last was over the host, in board pixels; null once it has left. */
37
- pointer: Point | null;
38
- onPointerMove: (event: PointerEvent) => void;
39
- onPointerLeave: () => void;
40
- }
41
-
42
- interface StringState {
43
- spec: DotsBoardStringSpec;
44
- /** The surface the string draws on: its items' layer's, or the board's. */
45
- surface: StringSurface;
46
- el: SVGPathElement;
47
- /** An unpainted, wider copy of the path that takes the pointer, so the string can be grabbed. */
48
- hit: SVGPathElement;
49
- /** The knots the string runs through, in order, and the bend between each pair (`bends[i]` joins `knots[i]` to `knots[i + 1]`). */
50
- knots: Knot[];
51
- bends: SpringBody[];
52
- /** The knots have been put on their dots at least once. */
53
- placed: boolean;
54
- /** The path last written, so a still string writes nothing. */
55
- path: string;
56
- /** The fade-out under way once the string's connection is gone; null while it belongs to one. */
57
- leaving: Animation | null;
58
- }
59
-
60
- /** The `<svg>`s of a board or layer that the strings draw in: the paths beneath the children, the hit paths above them. */
61
- export interface StringSvgs {
62
- paths: SVGSVGElement;
63
- hits: SVGSVGElement;
64
- }
65
-
66
- /** A string held by the pointer. */
67
- interface Grip {
68
- string: StringState;
69
- /** The piece grabbed (`bends[piece]`), and where along it. */
70
- piece: number;
71
- t: number;
72
- /** Where the pointer took hold, in board pixels. */
73
- origin: Point;
74
- /** How far the pointer has pulled from there. */
75
- pull: Point;
76
- pointerId: number;
77
- }
78
-
79
- /**
80
- * Constants
81
- */
82
-
83
- const SVG_NS = 'http://www.w3.org/2000/svg';
84
- const ORIGIN: Offset = { left: 0, top: 0 };
85
- /** A tug never leaves a bend moving faster than this many times the tug's own speed, however often the pointer crosses back and forth. */
86
- const TUG_MAX_SPEED_FACTOR = 2;
87
- /** The least width, in board pixels, of the stroke that takes the pointer for a string, so a thin one is still easy to grab. */
88
- const HIT_MIN_WIDTH = 16;
89
- /** However near a knot a string is held, its bend is never moved more than this many times the pull, since a pinned end cannot follow anyway. */
90
- const PULL_MAX_REACH = 4;
91
-
92
- /*
93
- * Draws the strings between a board's items outside React, from the dots the items report in
94
- * board pixels. A string is one continuous stroke through its knots, one knot per item it is
95
- * pinned to, with a bend between neighbours that sags as if hung. Every knot and bend is a
96
- * spring body: a knot follows its item's dot (so a resize is followed) and a bend rests on
97
- * the sag between its knots. A new string is placed taut on its dots and fades in as it drops
98
- * into its sag; when a connection keeps its key but changes its items, the string is re-pinned
99
- * in place (kept items keep their knots, a new item's knot is born on the string where the pin
100
- * catches it, and where an item was dropped the string relaxes from where it hung); a string
101
- * whose connection goes fades out and is removed. A pointer crossing a string tugs its bend
102
- * along with it (`tug`), so the string swings and springs back; a string can also be grabbed
103
- * and dragged, its bend following the pointer, until the pointer lets go or has pulled
104
- * `pull` pixels, when the string slips from it and springs back. Frames run only while
105
- * something moves. Reduced motion, or no spring, puts everything straight in place, and then
106
- * nothing tugs or pulls.
107
- *
108
- * Each string draws on the surface its items live on: the board's `<svg>`s, or a pinned
109
- * layer's (`setLayerSvg`) for the items reported from inside it, translated by the layer's
110
- * rest offset so the same board-pixel paths draw in the layer's pixels. A string's surface is
111
- * its first item's, so a string should not run between a layer and the rest of the board. On
112
- * each surface the paths live in one `<g>` and the hit paths in a second `<g>` in the matching
113
- * `hit` svg, which the board puts above its children so the strings can be grabbed where
114
- * content covers them, while the strings themselves draw beneath it.
115
- */
116
- export class DotsStringEngine {
117
- /** Null on the server, where nothing is drawn. */
118
- private readonly board: StringSurface | null;
119
- private readonly layer: StringSurface | null;
120
- private readonly dots = new Map<string, Point>();
121
- /** The items whose dots were reported from inside the pinned layer. */
122
- private readonly layeredDots = new Set<string>();
123
- private readonly strings = new Map<string, StringState>();
124
- private options: DotsBoardStringOptions = {
125
- spring: DOTS_STRING_DEFAULTS.spring,
126
- fadeMs: DOTS_STRING_DEFAULTS.fadeMs,
127
- tug: DOTS_STRING_DEFAULTS.tug,
128
- pull: DOTS_STRING_DEFAULTS.pull,
129
- };
130
- private grip: Grip | null = null;
131
- private rafId = 0;
132
- private lastTime = 0;
133
-
134
- constructor() {
135
- const canDraw = typeof document !== 'undefined';
136
- this.board = canDraw ? this.createSurface() : null;
137
- this.layer = canDraw ? this.createSurface() : null;
138
- }
139
-
140
- /*
141
- * The board's own `<svg>`s, where the strings of items outside a pinned layer draw.
142
- */
143
- setBoardSvg(svgs: StringSvgs | null) {
144
- if (this.board) this.mount(this.board, svgs, ORIGIN);
145
- }
146
-
147
- /*
148
- * The pinned layer's `<svg>`s, whose top-left corner rests `offset` pixels into the board,
149
- * where the strings of the items inside it draw; null gives them back to the board.
150
- */
151
- setLayerSvg(svgs: StringSvgs | null, offset: Offset = ORIGIN) {
152
- if (this.layer) this.mount(this.layer, svgs, offset);
153
- this.wake();
154
- }
155
-
156
- /*
157
- * Where an item's dot is, in board pixels (null when it leaves the board), and whether it was
158
- * reported from inside the pinned layer; its strings follow.
159
- */
160
- setDot(id: string, point: Point | null, layered = false) {
161
- if (point) this.dots.set(id, point);
162
- else this.dots.delete(id);
163
- if (point && layered) this.layeredDots.add(id);
164
- else this.layeredDots.delete(id);
165
- this.wake();
166
- }
167
-
168
- /*
169
- * Change the springs and fade; takes effect from the next frame (and the next fade).
170
- */
171
- setOptions(options: DotsBoardStringOptions) {
172
- const grabbable = options.pull > 0;
173
- if (grabbable !== this.options.pull > 0) for (const string of this.strings.values()) this.styleHit(string, grabbable);
174
- this.options = options;
175
- if (!grabbable) this.release();
176
- this.wake();
177
- }
178
-
179
- /*
180
- * Replace the set of strings: existing keys are restyled and re-pinned in place (a leaving
181
- * string that comes back fades back in), new keys are added for the frame loop to place and
182
- * fade in, and keys no longer present fade out.
183
- */
184
- setStrings(specs: DotsBoardStringSpec[]) {
185
- const keep = new Set<string>();
186
- for (const spec of specs) {
187
- keep.add(spec.key);
188
- const string = this.strings.get(spec.key);
189
- if (string) this.update(string, spec);
190
- else this.create(spec);
191
- }
192
- for (const string of this.strings.values()) {
193
- if (!keep.has(string.spec.key) && !string.leaving) this.leave(string);
194
- }
195
- this.wake();
196
- }
197
-
198
- /*
199
- * Stop the loop and let go of any grip. Nothing else is torn down: the paths and the
200
- * pointer listeners leave with the `<svg>`s (`setBoardSvg` / `setLayerSvg(null)`) and the
201
- * items take their dots away themselves, each in its own effect's cleanup. So an engine
202
- * kept across a Fast Refresh, which runs this after those effects have set everything up
203
- * again, keeps drawing its strings instead of losing them, or drawing them twice.
204
- */
205
- dispose() {
206
- if (this.rafId) cancelAnimationFrame(this.rafId);
207
- this.rafId = 0;
208
- this.lastTime = 0;
209
- this.release();
210
- }
211
-
212
- /*
213
- * A surface with its groups made and nowhere to draw yet.
214
- */
215
- private createSurface(): StringSurface {
216
- const surface: StringSurface = {
217
- root: document.createElementNS(SVG_NS, 'g'),
218
- hitRoot: document.createElementNS(SVG_NS, 'g'),
219
- svgs: null,
220
- offset: ORIGIN,
221
- host: null,
222
- pointer: null,
223
- onPointerMove: (event) => this.onPointerMove(surface, event),
224
- onPointerLeave: () => {
225
- surface.pointer = null;
226
- },
227
- };
228
- return surface;
229
- }
230
-
231
- /*
232
- * Put a surface's groups in its `<svg>`s, translated into their pixels.
233
- */
234
- private mount(surface: StringSurface, svgs: StringSvgs | null, offset: Offset) {
235
- surface.svgs = svgs;
236
- surface.offset = offset;
237
- const transform = `translate(${-offset.left} ${-offset.top})`;
238
- const place = (g: SVGGElement, svg: SVGSVGElement | undefined) => {
239
- g.setAttribute('transform', transform);
240
- if (!svg) g.remove();
241
- else if (g.parentNode !== svg) svg.appendChild(g);
242
- };
243
- place(surface.root, svgs?.paths);
244
- place(surface.hitRoot, svgs?.hits);
245
- this.listen(surface, svgs?.paths.parentElement ?? null);
246
- }
247
-
248
- /*
249
- * Follow the pointer over a surface's host, so a crossing can tug its strings. The `<svg>`
250
- * itself takes no pointer events, so its parent, the layer element, is listened on.
251
- */
252
- private listen(surface: StringSurface, host: HTMLElement | null) {
253
- if (host === surface.host) return;
254
- surface.host?.removeEventListener('pointermove', surface.onPointerMove);
255
- surface.host?.removeEventListener('pointerleave', surface.onPointerLeave);
256
- surface.host = host;
257
- surface.pointer = null;
258
- host?.addEventListener('pointermove', surface.onPointerMove);
259
- host?.addEventListener('pointerleave', surface.onPointerLeave);
260
- }
261
-
262
- /*
263
- * The pointer moved over a surface's host: taken into board pixels, and if it came from
264
- * somewhere over the host, every string of the surface its move crossed is tugged. Touches do not cross.
265
- */
266
- private onPointerMove(surface: StringSurface, event: PointerEvent) {
267
- if (event.pointerType === 'touch' || !surface.host) return;
268
- const point = this.toBoardPoint(surface, event);
269
- if (surface.pointer) this.tug(surface, surface.pointer, point);
270
- surface.pointer = point;
271
- }
272
-
273
- /*
274
- * A pointer event's position in board pixels: the surface host's own pixels plus where the
275
- * host rests in the board, which holds for a pinned layer too.
276
- */
277
- private toBoardPoint(surface: StringSurface, event: PointerEvent): Point {
278
- const rect = surface.host?.getBoundingClientRect();
279
- const { offset } = surface;
280
- return { x: event.clientX - (rect?.left ?? 0) + offset.left, y: event.clientY - (rect?.top ?? 0) + offset.top };
281
- }
282
-
283
- /*
284
- * The surface a string belongs on: the pinned layer's while it is mounted and holds the
285
- * string's first item, the board's otherwise.
286
- */
287
- private surfaceFor(string: StringState): StringSurface {
288
- const { board, layer } = this;
289
- return layer?.svgs && this.layeredDots.has(string.spec.items[0]) ? layer : (board ?? string.surface);
290
- }
291
-
292
- /*
293
- * Move a string (and, unless it is leaving, its hit path) onto another surface.
294
- */
295
- private moveTo(string: StringState, surface: StringSurface) {
296
- if (string.surface === surface) return;
297
- if (string === this.grip?.string) this.release();
298
- string.surface = surface;
299
- surface.root.appendChild(string.el);
300
- if (!string.leaving) surface.hitRoot.appendChild(string.hit);
301
- }
302
-
303
- /*
304
- * The pointer took hold of a string (on its hit path): the piece nearest the pointer is
305
- * gripped where the pointer is on it, and the pointer is captured so the drag continues
306
- * off the string. Not while another grip holds, and not without a spring to pull against.
307
- */
308
- private readonly onGrab = (event: PointerEvent) => {
309
- const { spring, pull } = this.options;
310
- if (this.grip || !spring || pull <= 0 || prefersReducedMotion() || !event.isPrimary) return;
311
- let string: StringState | undefined;
312
- for (const candidate of this.strings.values()) if (candidate.hit === event.target) string = candidate;
313
- if (!string || string.leaving || !string.placed) return;
314
- const point = this.toBoardPoint(string.surface, event);
315
- const { knots, bends } = string;
316
- let piece = -1;
317
- let t = 0;
318
- let distance = Number.POSITIVE_INFINITY;
319
- for (let i = 0; i < bends.length; i++) {
320
- const nearest = getNearestStringPoint(knots[i], bends[i], knots[i + 1], point);
321
- if (nearest.distance < distance) {
322
- ({ t, distance } = nearest);
323
- piece = i;
324
- }
325
- }
326
- if (piece < 0) return;
327
- event.preventDefault();
328
- const { hit } = string;
329
- hit.setPointerCapture(event.pointerId);
330
- hit.style.cursor = 'grabbing';
331
- hit.addEventListener('pointermove', this.onDrag);
332
- hit.addEventListener('pointerup', this.onLetGo);
333
- hit.addEventListener('pointercancel', this.onLetGo);
334
- this.grip = { string, piece, t, origin: point, pull: { x: 0, y: 0 }, pointerId: event.pointerId };
335
- this.wake();
336
- };
337
-
338
- /*
339
- * The pointer moved while holding a string: the string follows it exactly, until the
340
- * pointer is further than `pull` pixels from where it took hold, when the string slips out
341
- * of the grip and springs back, whether or not the button is still down.
342
- */
343
- private readonly onDrag = (event: PointerEvent) => {
344
- const { grip } = this;
345
- if (!grip || event.pointerId !== grip.pointerId) return;
346
- const point = this.toBoardPoint(grip.string.surface, event);
347
- grip.pull = { x: point.x - grip.origin.x, y: point.y - grip.origin.y };
348
- if (Math.hypot(grip.pull.x, grip.pull.y) > this.options.pull) this.release();
349
- this.wake();
350
- };
351
-
352
- private readonly onLetGo = (event: PointerEvent) => {
353
- if (this.grip && event.pointerId === this.grip.pointerId) this.release();
354
- };
355
-
356
- /*
357
- * Let go of the held string, if any: its bend springs back to rest from where it was held.
358
- */
359
- private release() {
360
- const { grip } = this;
361
- if (!grip) return;
362
- const { hit } = grip.string;
363
- hit.removeEventListener('pointermove', this.onDrag);
364
- hit.removeEventListener('pointerup', this.onLetGo);
365
- hit.removeEventListener('pointercancel', this.onLetGo);
366
- if (hit.hasPointerCapture(grip.pointerId)) hit.releasePointerCapture(grip.pointerId);
367
- hit.style.cursor = 'grab';
368
- this.grip = null;
369
- this.wake();
370
- }
371
-
372
- /*
373
- * Tug every string of a surface a pointer move from `from` to `to` crosses: the bend of the crossed
374
- * piece gets a push along the move, strongest at the middle of the piece and fading to
375
- * nothing at its knots, sized so the string swings about `tug` pixels (the bend twice that,
376
- * as the curve follows its control point halfway). Nothing without a spring to swing back on.
377
- */
378
- private tug(surface: StringSurface, from: Point, to: Point) {
379
- const { spring, tug } = this.options;
380
- if (!spring || tug <= 0 || prefersReducedMotion()) return;
381
- const length = Math.hypot(to.x - from.x, to.y - from.y);
382
- if (!length) return;
383
- // A spring released from rest with speed v swings out about v / √stiffness.
384
- const speed = 2 * tug * Math.sqrt(spring.stiffness);
385
- const maxSpeed = speed * TUG_MAX_SPEED_FACTOR;
386
- let tugged = false;
387
- for (const string of this.strings.values()) {
388
- // A held string is under the pointer already; it is pulled, not tugged.
389
- if (string.surface !== surface || string.leaving || !string.placed || string === this.grip?.string) continue;
390
- const { knots, bends } = string;
391
- for (let i = 0; i < bends.length; i++) {
392
- const t = getStringCrossing(knots[i], bends[i], knots[i + 1], from, to);
393
- if (t === null) continue;
394
- const push = (speed * Math.sin(Math.PI * t)) / length;
395
- const bend = bends[i];
396
- bend.vx += (to.x - from.x) * push;
397
- bend.vy += (to.y - from.y) * push;
398
- const total = Math.hypot(bend.vx, bend.vy);
399
- if (total > maxSpeed) {
400
- bend.vx *= maxSpeed / total;
401
- bend.vy *= maxSpeed / total;
402
- }
403
- tugged = true;
404
- }
405
- }
406
- if (tugged) this.wake();
407
- }
408
-
409
- /*
410
- * Run the loop if it is not already scheduled.
411
- */
412
- private wake() {
413
- if (!this.rafId && typeof requestAnimationFrame === 'function') this.rafId = requestAnimationFrame(this.frame);
414
- }
415
-
416
- /*
417
- * A new string, appended with no path: the frame loop draws it once every dot it needs is known.
418
- */
419
- private create(spec: DotsBoardStringSpec) {
420
- const { board } = this;
421
- if (!board) return;
422
- const el = document.createElementNS(SVG_NS, 'path');
423
- el.setAttribute('fill', 'none');
424
- el.setAttribute('stroke-linecap', 'round');
425
- el.setAttribute('stroke-linejoin', 'round');
426
- // The hit path takes the pointer on its stroke alone, whatever it is (not) painted with.
427
- const hit = document.createElementNS(SVG_NS, 'path');
428
- hit.setAttribute('fill', 'none');
429
- hit.setAttribute('stroke', 'none');
430
- hit.setAttribute('stroke-linecap', 'round');
431
- hit.addEventListener('pointerdown', this.onGrab);
432
- const string: StringState = {
433
- spec,
434
- surface: board,
435
- el,
436
- hit,
437
- knots: spec.items.map((item) => ({ ...springBodyAt(0, 0), item })),
438
- bends: spec.items.slice(1).map(() => springBodyAt(0, 0)),
439
- placed: false,
440
- path: '',
441
- leaving: null,
442
- };
443
- this.style(string);
444
- this.styleHit(string, this.options.pull > 0);
445
- board.root.appendChild(el);
446
- board.hitRoot.appendChild(hit);
447
- this.strings.set(spec.key, string);
448
- }
449
-
450
- /*
451
- * A string whose connection is still there: restyle and re-pin it as its spec changed.
452
- */
453
- private update(string: StringState, spec: DotsBoardStringSpec) {
454
- const previous = string.spec;
455
- string.spec = spec;
456
- if (spec.color !== previous.color || spec.width !== previous.width || spec.dashed !== previous.dashed) this.style(string);
457
- if (spec.items.length !== previous.items.length || spec.items.some((item, i) => item !== previous.items[i])) this.repin(string);
458
- this.stay(string);
459
- }
460
-
461
- /*
462
- * A leaving string whose connection came back before it was gone: it stops fading out and
463
- * fades back in from as far as it had got, and its hit path, taken away when it began to
464
- * leave, goes back so it can be grabbed again.
465
- */
466
- private stay(string: StringState) {
467
- const { leaving, el, hit } = string;
468
- if (!leaving) return;
469
- const faded = leaving.effect?.getComputedTiming().progress ?? 0;
470
- leaving.onfinish = null;
471
- leaving.cancel();
472
- string.leaving = null;
473
- string.surface.hitRoot.appendChild(hit);
474
- const { fadeMs } = this.options;
475
- if (faded > 0 && fadeMs > 0) el.animate([{ opacity: 1 - faded }, { opacity: 1 }], { duration: fadeMs * faded });
476
- }
477
-
478
- /*
479
- * Fade a string out and remove it; at once where fading is not possible.
480
- */
481
- private leave(string: StringState) {
482
- const { el, hit, spec } = string;
483
- if (string === this.grip?.string) this.release();
484
- hit.remove();
485
- const remove = () => {
486
- el.remove();
487
- this.strings.delete(spec.key);
488
- };
489
- const { fadeMs } = this.options;
490
- if (!string.placed || fadeMs <= 0 || typeof el.animate !== 'function') {
491
- remove();
492
- return;
493
- }
494
- string.leaving = el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: fadeMs, fill: 'forwards' });
495
- string.leaving.onfinish = remove;
496
- }
497
-
498
- /*
499
- * A string's stroke, as style (not presentation attributes) so a `var()` color resolves.
500
- */
501
- private style({ el, hit, spec }: StringState) {
502
- el.style.stroke = spec.color;
503
- el.style.strokeWidth = `${spec.width}px`;
504
- if (spec.dashed) el.setAttribute('stroke-dasharray', `${spec.width * 2} ${spec.width * 4}`);
505
- else el.removeAttribute('stroke-dasharray');
506
- hit.style.strokeWidth = `${Math.max(spec.width * 3, HIT_MIN_WIDTH)}px`;
507
- }
508
-
509
- /*
510
- * Whether a string's hit path takes the pointer (and offers a grab) or lets it through.
511
- */
512
- private styleHit({ hit }: StringState, grabbable: boolean) {
513
- hit.style.pointerEvents = grabbable ? 'stroke' : 'none';
514
- hit.style.cursor = grabbable ? 'grab' : '';
515
- }
516
-
517
- /*
518
- * Snap a string's knots onto their dots and pull it taut between them, so it drops into its
519
- * sag as it fades in.
520
- */
521
- private place(string: StringState, targets: Point[]) {
522
- const { knots, bends, el } = string;
523
- for (let i = 0; i < knots.length; i++) snapSpring(knots[i], targets[i].x, targets[i].y);
524
- for (let i = 0; i < bends.length; i++) {
525
- const middle = lerpPoint(knots[i], knots[i + 1], 0.5);
526
- snapSpring(bends[i], middle.x, middle.y);
527
- }
528
- string.placed = true;
529
- const { fadeMs } = this.options;
530
- if (fadeMs > 0 && typeof el.animate === 'function') el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: fadeMs });
531
- }
532
-
533
- /*
534
- * Re-pin a string to its spec's new run of items, keeping the string itself. Items it
535
- * already had keep their knots, and a bend between two knots that were already neighbours
536
- * is kept; a new item's knot is born where the string passes between its nearest kept
537
- * neighbours (on the piece that hung between them, or on the chord), for the pin to pull up;
538
- * where items were dropped between two kept ones, the new bend starts on the middle dropped
539
- * knot, so the string relaxes from where it hung instead of snapping straight.
540
- */
541
- private repin(string: StringState) {
542
- const { items } = string.spec;
543
- const { knots: old, bends: oldBends } = string;
544
- const oldIndex = new Map(old.map((knot, i) => [knot.item, i] as const));
545
- const knots = items.map((item, i) => {
546
- const at = oldIndex.get(item);
547
- return at === undefined ? this.bornKnot(string, i, oldIndex) : old[at];
548
- });
549
- const bends = knots.slice(1).map((knot, i) => {
550
- const a = oldIndex.get(knots[i].item);
551
- const b = oldIndex.get(knot.item);
552
- if (a !== undefined && b === a + 1) return oldBends[a];
553
- const dropped = a !== undefined && b !== undefined && b > a + 1 ? old[Math.floor((a + b) / 2)] : null;
554
- const start = dropped ?? lerpPoint(knots[i], knot, 0.5);
555
- return springBodyAt(start.x, start.y);
556
- });
557
- string.knots = knots;
558
- string.bends = bends;
559
- }
560
-
561
- /*
562
- * A knot for the new item at `index` of the string's items: on the string between its
563
- * nearest kept neighbours at its rank among the new items there, or, with only one side
564
- * kept or none, on its dot (or its kept neighbour, or the origin).
565
- */
566
- private bornKnot(string: StringState, index: number, oldIndex: Map<string, number>): Knot {
567
- const { items } = string.spec;
568
- const item = items[index];
569
- let prev = index - 1;
570
- while (prev >= 0 && !oldIndex.has(items[prev])) prev--;
571
- let next = index + 1;
572
- while (next < items.length && !oldIndex.has(items[next])) next++;
573
- const a = prev >= 0 ? oldIndex.get(items[prev]) : undefined;
574
- const b = next < items.length ? oldIndex.get(items[next]) : undefined;
575
- let at: Point | undefined;
576
- if (a !== undefined && b !== undefined) {
577
- const t = (index - prev) / (next - prev);
578
- at =
579
- b === a + 1
580
- ? getQuadraticPoint(string.knots[a], string.bends[a], string.knots[b], t)
581
- : lerpPoint(string.knots[a], string.knots[b], t);
582
- } else {
583
- at = this.dots.get(item) ?? (a !== undefined ? string.knots[a] : b !== undefined ? string.knots[b] : undefined);
584
- }
585
- return { ...springBodyAt(at?.x ?? 0, at?.y ?? 0), item };
586
- }
587
-
588
- /*
589
- * One frame: place new strings, advance every spring that is not at rest (or snap them, with
590
- * no spring or reduced motion), write the paths that changed, and reschedule only if
591
- * something is still moving. A string missing a dot draws nothing until it is back.
592
- */
593
- private readonly frame = (time: number) => {
594
- this.rafId = 0;
595
- const dt = this.lastTime ? Math.min((time - this.lastTime) / 1000, SPRING_PHYSICS.maxDt) : 0;
596
- this.lastTime = time;
597
- const spring = this.options.spring && !prefersReducedMotion() ? this.options.spring : null;
598
- if (!spring) this.release();
599
- const { grip } = this;
600
- const step = (body: SpringBody, target: Point) => {
601
- if (spring) return stepSpring(body, target.x, target.y, dt, spring);
602
- snapSpring(body, target.x, target.y);
603
- return true;
604
- };
605
- let active = false;
606
-
607
- for (const string of this.strings.values()) {
608
- if (string.leaving) continue;
609
- const { knots, bends, spec } = string;
610
- const targets: Point[] = [];
611
- for (const knot of knots) {
612
- const dot = this.dots.get(knot.item);
613
- if (dot) targets.push(dot);
614
- }
615
- let path = '';
616
- if (targets.length === knots.length && knots.length >= 2) {
617
- this.moveTo(string, this.surfaceFor(string));
618
- if (!string.placed) this.place(string, targets);
619
- let settled = true;
620
- for (let i = 0; i < knots.length; i++) if (!step(knots[i], targets[i])) settled = false;
621
- for (let i = 0; i < bends.length; i++) {
622
- const target = getStringRestControl(knots[i], knots[i + 1], spec.slack, spec.maxSag);
623
- if (grip?.string === string && grip.piece === i) {
624
- // The held piece follows the pointer: a quadratic's curve moves `2t(1 - t)` of what its
625
- // control does, so the control takes the pull divided by that, which puts the point held
626
- // under the pointer. Held near a knot that factor runs away, so the reach is capped.
627
- const { t } = grip;
628
- const reach = Math.min(1 / (2 * t * (1 - t)), PULL_MAX_REACH);
629
- // Snapped, not sprung, so the string sits exactly where the pointer has it; it keeps the
630
- // spring for the way back, from rest at the pulled shape.
631
- snapSpring(bends[i], target.x + grip.pull.x * reach, target.y + grip.pull.y * reach);
632
- continue;
633
- }
634
- if (!step(bends[i], target)) settled = false;
635
- }
636
- if (!settled) active = true;
637
- path = buildStringPath(knots, bends);
638
- }
639
- if (path !== string.path) {
640
- string.path = path;
641
- string.el.setAttribute('d', path);
642
- string.hit.setAttribute('d', path);
643
- }
644
- }
645
-
646
- if (active) this.wake();
647
- else this.lastTime = 0;
648
- };
649
- }