gooee 0.47.0 → 0.50.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.
@@ -0,0 +1,676 @@
1
+ import { boxPath, boxRing, clamp01, lerp, polyPath, sdBox, seg, trace, type Box, type Pt, type Sdf } from '../liquidPath'
2
+ import { frames, layer, morphEase, motionFor } from './liquidMatter'
3
+
4
+ // Liquid matter for Checkbox (a cup that fills), the fields (an edge that flows round), CopyButton (a
5
+ // drop that fills the icon and turns into the check) and the menus (a bead that follows the pointer).
6
+ // Same contract as liquidMatter.ts: the SVG exists only while the part moves, and its last frame is
7
+ // the part's own CSS shape.
8
+
9
+ const NS = 'http://www.w3.org/2000/svg'
10
+ let ids = 0
11
+
12
+ function clipOf(svg: SVGSVGElement) {
13
+ const defs = svg.insertBefore(document.createElementNS(NS, 'defs'), svg.firstChild)
14
+ const clip = defs.appendChild(document.createElementNS(NS, 'clipPath'))
15
+ clip.id = `gooee-liquid-clip-${++ids}`
16
+ const path = clip.appendChild(document.createElementNS(NS, 'path'))
17
+ return { path, url: `url(#${clip.id})` }
18
+ }
19
+
20
+ // ---------- cup ----------
21
+
22
+ /** A container's inner walls, floor and rim, and how much the surface tips and curves. */
23
+ export type Cup = { x0: number; x1: number; top: number; bot: number; tilt: number; men: number }
24
+
25
+ /**
26
+ * The surface at fill `f` (0 on the floor, 1 over the rim), poured from side `s` (-1 left, 1 right,
27
+ * 0 evenly from below): high on the poured side at first, then it rises and levels, with a meniscus.
28
+ */
29
+ export function cupLevel(f: number, s: number, cup: Cup) {
30
+ const cx = (cup.x0 + cup.x1) / 2
31
+ const hw = (cup.x1 - cup.x0) / 2
32
+ const T = cup.tilt * (1 - f) * (1 - f)
33
+ const M = cup.men * (0.4 + 0.6 * (1 - f))
34
+ const L = lerp(cup.bot + cup.tilt * Math.abs(s) + cup.men, cup.top - 1, f)
35
+ return (x: number) => {
36
+ const q = (x - cx) / hw
37
+ return L - s * T * q - M * q * q
38
+ }
39
+ }
40
+
41
+ /** The liquid under `y` from x0 to x1, closed along `floor`. */
42
+ export function cupPath(y: (x: number) => number, x0: number, x1: number, floor: number) {
43
+ const pts: Pt[] = []
44
+ for (let x = x0; x <= x1 + 1e-6; x += 0.5) pts.push([x, y(x)])
45
+ pts.push([x1, floor], [x0, floor])
46
+ return polyPath(pts)
47
+ }
48
+
49
+ const cupAttr = (c: Cup) => `${c.x0} ${c.x1} ${c.top} ${c.bot}`
50
+
51
+ // ---------- Checkbox ----------
52
+
53
+ export type Pour = { u: number; side: number; done: boolean; stop: () => void }
54
+
55
+ /**
56
+ * Checkbox: ink pours into `box` from `side` (the side tapped; 0 fills evenly from below), rises with
57
+ * a meniscus and levels, then `mark` draws. Emptying runs it back. While it pours the box carries
58
+ * data-pouring, so its CSS fill stands down. A pour caught half way turns from where it is.
59
+ */
60
+ export function pour(box: HTMLElement, mark: SVGPathElement | null, to: 0 | 1, side: number, cls: string, prev: Pour | null): Pour | null {
61
+ const live = prev && !prev.done ? (prev as Pour & { svg?: SVGSVGElement; halt?: () => void }) : null
62
+ const from = live ? live.u : 1 - to
63
+ live?.halt?.()
64
+ const ms = motionFor('slow') * Math.abs(to - from)
65
+ if (!ms) {
66
+ live?.stop()
67
+ return null
68
+ }
69
+ // A run caught half way may hand over to the other mark (tick or dash): the old one rests.
70
+ box.querySelectorAll<SVGElement>('[data-mark]').forEach((m) => m !== mark && m.style.removeProperty('stroke-dashoffset'))
71
+ const W = box.offsetWidth
72
+ const bw = box.clientLeft
73
+ const look = getComputedStyle(box)
74
+ const r = parseFloat(look.borderTopLeftRadius) || 0
75
+ const fill = box.querySelector<HTMLElement>('[data-pour-fill]')
76
+ const outer = boxPath({ cx: W / 2, cy: W / 2, hw: W / 2, hh: W / 2, r })
77
+ const inner = W - 2 * bw
78
+ const cup: Cup = { x0: bw, x1: W - bw, top: bw, bot: W - bw, tilt: inner / 3, men: inner / 9 }
79
+ let svg = live?.svg
80
+ let liquid: SVGPathElement
81
+ let clipUrl: string
82
+ if (svg) {
83
+ liquid = svg.querySelector('path[data-measure]')!
84
+ clipUrl = liquid.getAttribute('clip-path') ?? ''
85
+ } else {
86
+ const l = layer(box, cls, box.firstChild)
87
+ svg = l.svg
88
+ liquid = l.paths[0]
89
+ const clip = clipOf(svg)
90
+ clip.path.setAttribute('d', outer)
91
+ clipUrl = clip.url
92
+ svg.setAttribute('width', `${W}`)
93
+ svg.setAttribute('height', `${W}`)
94
+ svg.style.left = svg.style.top = `${-bw}px`
95
+ liquid.style.fill = fill ? getComputedStyle(fill).backgroundColor : 'currentColor'
96
+ liquid.setAttribute('data-measure', 'surface')
97
+ liquid.setAttribute('data-cup', cupAttr(cup))
98
+ }
99
+ box.dataset.pouring = ''
100
+ const e = morphEase()
101
+ const s = live ? live.side : side
102
+ const layerSvg = svg
103
+ const run = {
104
+ u: from,
105
+ side: s,
106
+ done: false,
107
+ svg: layerSvg,
108
+ halt: () => {},
109
+ stop: () => {
110
+ run.done = true
111
+ run.halt()
112
+ layerSvg.remove()
113
+ box.querySelectorAll<SVGElement>('[data-mark]').forEach((m) => m.style.removeProperty('stroke-dashoffset'))
114
+ delete box.dataset.pouring
115
+ },
116
+ }
117
+ const draw = (p: number) => {
118
+ run.u = lerp(from, to, e(p))
119
+ const f = seg(run.u, 0, 0.78)
120
+ const cp = seg(run.u, 0.7, 1)
121
+ mark?.style.setProperty('stroke-dashoffset', `${1.01 * (1 - cp)}`)
122
+ if (p >= 1) {
123
+ liquid.removeAttribute('clip-path')
124
+ liquid.setAttribute('d', to ? outer : '')
125
+ return
126
+ }
127
+ liquid.setAttribute('clip-path', clipUrl)
128
+ liquid.setAttribute('d', f > 0 ? cupPath(cupLevel(f, s, cup), -1, W + 1, W + 2) : '')
129
+ }
130
+ run.halt = frames(ms, draw, () => run.stop())
131
+ return run
132
+ }
133
+
134
+ // ---------- field edge ----------
135
+
136
+ type Ring = Array<[number, number, number, number]>
137
+
138
+ function ringLength(cl: Ring) {
139
+ let len = 0
140
+ for (let i = 0; i < cl.length; i++) {
141
+ const a = cl[i]
142
+ const b = cl[(i + 1) % cl.length]
143
+ len += Math.hypot(b[0] - a[0], b[1] - a[1])
144
+ }
145
+ return len
146
+ }
147
+
148
+ /**
149
+ * The edge at progress `e` (0 to 1): two heads run both ways round the centre line `cl` from `i0`, a
150
+ * little fuller than the edge, and meet on the far side; the joined bump then relaxes into the ring.
151
+ */
152
+ export function edgeLoops(cl: Ring, i0: number, e: number, band: number, head = 1.2, over = 10): Pt[][] {
153
+ const N = cl.length
154
+ const P = ringLength(cl)
155
+ const ds = P / N
156
+ const at = (i: number) => cl[((i % N) + N) % N]
157
+ const wAt = (d: number) => band + head * Math.exp(-(d * d) / 9)
158
+ const a = e * (P / 2 + over)
159
+ const g = P - 2 * a
160
+ if (g > wAt(0)) {
161
+ const k = Math.max(1, Math.round(a / ds))
162
+ const out: Pt[] = []
163
+ const inn: Pt[] = []
164
+ for (let j = -k; j <= k; j++) {
165
+ const p = at(i0 + j)
166
+ const w = wAt((k - Math.abs(j)) * ds) / 2
167
+ out.push([p[0] + p[2] * w, p[1] + p[3] * w])
168
+ inn.push([p[0] - p[2] * w, p[1] - p[3] * w])
169
+ }
170
+ // A round drop head on each end.
171
+ const cap = (p: Ring[number], dir: number, from: number): Pt[] => {
172
+ const r = wAt(0) / 2
173
+ const n = [p[2] * from, p[3] * from]
174
+ const t = [-p[3] * dir, p[2] * dir]
175
+ const c: Pt[] = []
176
+ for (let q = 1; q < 10; q++) {
177
+ const th = (q / 10) * Math.PI
178
+ c.push([p[0] + r * (n[0] * Math.cos(th) + t[0] * Math.sin(th)), p[1] + r * (n[1] * Math.cos(th) + t[1] * Math.sin(th))])
179
+ }
180
+ return c
181
+ }
182
+ return [out.concat(cap(at(i0 + k), 1, 1), inn.reverse(), cap(at(i0 - k), -1, -1))]
183
+ }
184
+ const iM = (i0 + Math.round(N / 2)) % N
185
+ const m = clamp01((g + 2 * over) / (wAt(0) + 2 * over))
186
+ const out: Pt[] = []
187
+ const inn: Pt[] = []
188
+ for (let i = 0; i < N; i++) {
189
+ let dj = Math.abs(i - iM) % N
190
+ dj = Math.min(dj, N - dj) * ds
191
+ const p = cl[i]
192
+ const w = (band + head * m * Math.exp(-(dj * dj) / 16)) / 2
193
+ out.push([p[0] + p[2] * w, p[1] + p[3] * w])
194
+ inn.push([p[0] - p[2] * w, p[1] - p[3] * w])
195
+ }
196
+ return [out, inn]
197
+ }
198
+
199
+ function nearestOn(cl: Ring, x: number, y: number) {
200
+ let best = 0
201
+ let m = Infinity
202
+ cl.forEach((p, i) => {
203
+ const d = (p[0] - x) ** 2 + (p[1] - y) ** 2
204
+ if (d < m) {
205
+ m = d
206
+ best = i
207
+ }
208
+ })
209
+ return best
210
+ }
211
+
212
+ /**
213
+ * Field focus: while `el` matches `on`, it carries data-edge, which its CSS draws as the dark edge
214
+ * (the field's focus indicator, --gooee-line-focus thick).
215
+ * When it starts to match, the edge first flows both ways round from where it was pressed (or from the
216
+ * start edge for a key) and meets on the far side, then data-edge lands; when it stops mid-flow, the
217
+ * drawing fades. The layer sits in `root` (the field itself, or a wrapper for a textarea). Returns a stop.
218
+ */
219
+ export function edgeFlow(el: HTMLElement, root: HTMLElement, on: string, cls: string) {
220
+ let shown = el.matches(on)
221
+ if (shown) el.dataset.edge = ''
222
+ let pressed: { x: number; y: number; t: number } | null = null
223
+ let run: { svg: SVGSVGElement; stop: () => void } | null = null
224
+ const end = () => {
225
+ run?.stop()
226
+ run?.svg.remove()
227
+ run = null
228
+ }
229
+ const settle = () => {
230
+ end()
231
+ if (shown) el.dataset.edge = ''
232
+ }
233
+ const start = () => {
234
+ end()
235
+ const ms = motionFor('base') + motionFor('instant')
236
+ if (!ms) return settle()
237
+ const look = getComputedStyle(el)
238
+ // The settled edge is a focus indicator: --gooee-line-focus thick, inside the border box.
239
+ const bw = parseFloat(look.getPropertyValue('--gooee-line-focus')) || 2
240
+ const r = parseFloat(look.borderTopLeftRadius) || 0
241
+ const rect = el.getBoundingClientRect()
242
+ let W = el.offsetWidth
243
+ let H = el.offsetHeight
244
+ const ringOf = () => boxRing({ cx: W / 2, cy: H / 2, hw: (W - bw) / 2, hh: (H - bw) / 2, r: Math.max(0, r - bw / 2) }, 0.5)
245
+ let cl = ringOf()
246
+ const fresh = pressed && performance.now() - pressed.t < 1000
247
+ const rtl = look.direction === 'rtl'
248
+ const i0 = fresh ? nearestOn(cl, pressed!.x - rect.left, pressed!.y - rect.top) : nearestOn(cl, rtl ? W : 0, H / 2)
249
+ let at = i0 / cl.length
250
+ pressed = null
251
+ const { svg, paths } = layer(root, cls, null)
252
+ const path = paths[0]
253
+ path.style.fill = look.getPropertyValue('--gooee-flow-edge').trim() || 'currentColor'
254
+ path.setAttribute('fill-rule', 'evenodd')
255
+ path.setAttribute('data-measure', 'shape')
256
+ const place = () => {
257
+ svg.setAttribute('width', `${W}`)
258
+ svg.setAttribute('height', `${H}`)
259
+ svg.style.left = `${el === root ? -el.clientLeft : el.offsetLeft}px`
260
+ svg.style.top = `${el === root ? -el.clientTop : el.offsetTop}px`
261
+ }
262
+ place()
263
+ const e = morphEase()
264
+ const draw = (u: number) => {
265
+ // A field that grows while it flows (a textarea) keeps the flow on its edge.
266
+ if (el.offsetWidth !== W || el.offsetHeight !== H) {
267
+ W = el.offsetWidth
268
+ H = el.offsetHeight
269
+ cl = ringOf()
270
+ place()
271
+ }
272
+ if (u >= 1) {
273
+ path.setAttribute('d', boxPath({ cx: W / 2, cy: H / 2, hw: W / 2, hh: H / 2, r }) + boxPath({ cx: W / 2, cy: H / 2, hw: W / 2 - bw, hh: H / 2 - bw, r: Math.max(0, r - bw) }))
274
+ return
275
+ }
276
+ path.setAttribute('d', edgeLoops(cl, Math.round(at * cl.length), e(u), bw).map((l) => polyPath(l)).join(''))
277
+ }
278
+ run = { svg, stop: frames(ms, draw, settle) }
279
+ }
280
+ const leave = () => {
281
+ if (!run) return
282
+ const r = run
283
+ r.stop()
284
+ const ms = motionFor('fast')
285
+ if (!ms || typeof r.svg.animate !== 'function') return end()
286
+ const fade = r.svg.animate({ opacity: [1, 0] }, { duration: ms, easing: 'linear', fill: 'forwards' })
287
+ r.stop = () => fade.cancel()
288
+ fade.finished.then(() => run === r && end(), () => {})
289
+ }
290
+ const check = () => {
291
+ const now = el.matches(on)
292
+ if (now === shown) return
293
+ shown = now
294
+ if (now) start()
295
+ else {
296
+ delete el.dataset.edge
297
+ leave()
298
+ }
299
+ }
300
+ const later = () => queueMicrotask(check)
301
+ const down = (ev: PointerEvent) => {
302
+ pressed = { x: ev.clientX, y: ev.clientY, t: performance.now() }
303
+ }
304
+ const watch = new MutationObserver(check)
305
+ watch.observe(el, { attributes: true, attributeFilter: ['data-open', 'data-invalid'] })
306
+ el.addEventListener('pointerdown', down, true)
307
+ el.addEventListener('focusin', later)
308
+ el.addEventListener('focusout', later)
309
+ return () => {
310
+ watch.disconnect()
311
+ el.removeEventListener('pointerdown', down, true)
312
+ el.removeEventListener('focusin', later)
313
+ el.removeEventListener('focusout', later)
314
+ end()
315
+ delete el.dataset.edge
316
+ }
317
+ }
318
+
319
+ // ---------- CopyButton ----------
320
+
321
+ const sdSeg = (x: number, y: number, a: Pt, b: Pt) => {
322
+ const bx = b[0] - a[0]
323
+ const by = b[1] - a[1]
324
+ const L = bx * bx + by * by
325
+ const h = L > 0 ? clamp01(((x - a[0]) * bx + (y - a[1]) * by) / L) : 0
326
+ return Math.hypot(x - a[0] - bx * h, y - a[1] - by * h)
327
+ }
328
+
329
+ /**
330
+ * Distance to a stroke of half width `w`: two arms from B (directions u1 and u2, lengths L1 and L2)
331
+ * joined by an arc of radius rc. Its outline is an exact offset of a smooth centre line, so it is as
332
+ * wide everywhere and has no point.
333
+ */
334
+ function strokeSdf(B: Pt, u1: Pt, u2: Pt, L1: number, L2: number, rc: number, w: number): Sdf {
335
+ const e1: Pt = [B[0] + u1[0] * L1, B[1] + u1[1] * L1]
336
+ const e2: Pt = [B[0] + u2[0] * L2, B[1] + u2[1] * L2]
337
+ const phi = Math.acos(Math.max(-1, Math.min(1, u1[0] * u2[0] + u1[1] * u2[1])))
338
+ const beta = Math.PI - phi
339
+ if (beta < 1e-4) return (x, y) => Math.min(sdSeg(x, y, B, e1), sdSeg(x, y, B, e2)) - w
340
+ const T = rc * Math.tan(beta / 2)
341
+ const p1: Pt = [B[0] + u1[0] * T, B[1] + u1[1] * T]
342
+ const p2: Pt = [B[0] + u2[0] * T, B[1] + u2[1] * T]
343
+ const bl = Math.hypot(u1[0] + u2[0], u1[1] + u2[1])
344
+ const oc = rc / Math.sin(phi / 2)
345
+ const O: Pt = [B[0] + ((u1[0] + u2[0]) / bl) * oc, B[1] + ((u1[1] + u2[1]) / bl) * oc]
346
+ const a: Pt = [p1[0] - O[0], p1[1] - O[1]]
347
+ const b: Pt = [p2[0] - O[0], p2[1] - O[1]]
348
+ const cr = (m: Pt, n: Pt) => m[0] * n[1] - m[1] * n[0]
349
+ const sg = Math.sign(cr(a, b))
350
+ return (x, y) => {
351
+ let d = Math.min(sdSeg(x, y, p1, e1), sdSeg(x, y, p2, e2))
352
+ const v: Pt = [x - O[0], y - O[1]]
353
+ if (cr(a, v) * sg >= 0 && cr(v, b) * sg >= 0) d = Math.min(d, Math.abs(Math.hypot(v[0], v[1]) - rc))
354
+ return d - w
355
+ }
356
+ }
357
+
358
+ /** The filled square (`sq`) and the check it becomes: its corner B, arm lengths and half width. */
359
+ export type CheckMorph = { sq: Box; B: Pt; L1: number; L2: number; w: number }
360
+
361
+ const ROUND = 0.04
362
+
363
+ /**
364
+ * The filled square at m = 0 becomes the check at m = 1 in one shape: it rounds into a drop (the first
365
+ * 4%), stretches into a bar, and bends into the check as it thins. Through the bend the join radius
366
+ * stays at least 1.9 times the half width, so its inside never pinches.
367
+ */
368
+ export function checkLoops(m: number, g: CheckMorph): Pt[][] {
369
+ const { sq } = g
370
+ if (m < ROUND) {
371
+ const q = m / ROUND
372
+ const r = lerp(sq.r, sq.hw, q * q * (3 - 2 * q))
373
+ return [boxRing({ ...sq, r }, 0.5).map((p) => [p[0], p[1]] as Pt)]
374
+ }
375
+ const t = (m - ROUND) / (1 - ROUND)
376
+ const w = lerp(sq.hw, g.w, t)
377
+ const rc = 1.9 * w + 0.2
378
+ const B: Pt = [lerp(sq.cx, g.B[0], t), lerp(sq.cy, g.B[1], t)]
379
+ const L1 = g.L1 * t
380
+ const L2 = g.L2 * t
381
+ const sm = t * t * (3 - 2 * t)
382
+ const beta = Math.min((Math.PI / 2) * sm, 2 * Math.atan((0.95 * Math.min(L1, L2)) / rc))
383
+ const phi = Math.PI - beta
384
+ const up = -Math.PI / 2
385
+ const u1: Pt = [Math.cos(up - phi / 2), Math.sin(up - phi / 2)]
386
+ const u2: Pt = [Math.cos(up + phi / 2), Math.sin(up + phi / 2)]
387
+ const T = rc * Math.tan(beta / 2)
388
+ return trace(strokeSdf(B, u1, u2, L1, L2, rc, w), [[B[0] + u1[0] * T, B[1] + u1[1] * T, 0, 1]])
389
+ }
390
+
391
+ /** Where a copy run is: front filled, back slid under, square morphed into the check, each 0 to 1. */
392
+ export type CopyState = { fill: number; slide: number; morph: number }
393
+
394
+ // The copy icon (internal/icons CopyIcon) in its 24-unit box, and the check's corner and arms.
395
+ const ICON = { front: 8.5, size: 11, r: 2.5, back: 4, stroke: 1.75, B: [9.5, 17] as Pt, L1: 4.5 * Math.SQRT2, L2: 9.5 * Math.SQRT2, check: 2.25 }
396
+ const BACK_D = 'M15.5 8.5V6.5a2 2 0 0 0-2-2h-7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h2'
397
+
398
+ /**
399
+ * CopyButton: a drop forms where it was pressed (`at`, from the icon's corner; null for a key), falls
400
+ * into the copy icon and fills its front square, the back square slides under and merges, and the
401
+ * filled square turns into the check. `to` 0 plays it back from wherever it is. The icon box carries
402
+ * data-pouring while it runs, so the CSS icons stand down.
403
+ */
404
+ export function copyRun(icons: HTMLElement, to: 0 | 1, at: Pt | null, cls: string, prev: CopyRun | null): CopyRun | null {
405
+ if (prev?.done) prev = null
406
+ const from: CopyState = prev ? { ...prev.state } : to ? { fill: 0, slide: 0, morph: 0 } : { fill: 1, slide: 1, morph: 1 }
407
+ prev?.halt()
408
+ const k = motionFor('morph') / 600
409
+ if (!k) {
410
+ prev?.stop()
411
+ return null
412
+ }
413
+ const size = icons.offsetWidth
414
+ const s = size / 24
415
+ const o = (ICON.front - ICON.stroke / 2) * s
416
+ const S = (ICON.size + ICON.stroke) * s
417
+ const sq: Box = { cx: o + S / 2, cy: o + S / 2, hw: S / 2, hh: S / 2, r: (ICON.r + ICON.stroke / 2) * s }
418
+ const ring = ICON.stroke * s
419
+ const hole: Box = { ...sq, hw: S / 2 - ring, hh: S / 2 - ring, r: Math.max(0, sq.r - ring) }
420
+ const frontD = boxPath(sq)
421
+ const g: CheckMorph = { sq, B: [ICON.B[0] * s, ICON.B[1] * s], L1: ICON.L1 * s, L2: ICON.L2 * s, w: (ICON.check / 2) * s }
422
+ const inner = hole.hw * 2
423
+ const cup: Cup = { x0: hole.cx - hole.hw, x1: hole.cx + hole.hw, top: hole.cy - hole.hh, bot: hole.cy + hole.hh, tilt: inner * 0.29, men: inner * 0.1 }
424
+ const entry: Pt = [sq.cx, cup.top + 1]
425
+ const drop = !prev && to === 1
426
+ const P: Pt = at ?? [size / 2, size / 2]
427
+ const side = Math.max(-1, Math.min(1, (P[0] - entry[0]) / 32)) * 0.6
428
+ let svg = prev?.svg
429
+ let p: { back: SVGPathElement; liquid: SVGPathElement; front: SVGPathElement; drop: SVGPathElement; clip: string }
430
+ if (svg && prev) p = prev.paths
431
+ else {
432
+ const l = layer(icons, cls, null, 4)
433
+ svg = l.svg
434
+ svg.setAttribute('width', `${size}`)
435
+ svg.setAttribute('height', `${size}`)
436
+ const [back, liquid, front, dropPath] = l.paths
437
+ const inside = clipOf(svg)
438
+ inside.path.setAttribute('d', frontD)
439
+ // The back square shows only outside the front one, so it slides under it.
440
+ const outside = clipOf(svg)
441
+ outside.path.setAttribute('d', `M-${size} -${size}H${2 * size}V${2 * size}H-${size}Z${frontD}`)
442
+ outside.path.setAttribute('clip-rule', 'evenodd')
443
+ back.setAttribute('d', BACK_D)
444
+ back.setAttribute('clip-path', outside.url)
445
+ back.style.cssText = `fill:none;stroke:currentColor;stroke-width:${ICON.stroke};stroke-linecap:round;stroke-linejoin:round`
446
+ front.setAttribute('fill-rule', 'evenodd')
447
+ for (const q of [liquid, front, dropPath]) q.style.fill = 'currentColor'
448
+ dropPath.setAttribute('data-measure', 'shape')
449
+ p = { back, liquid, front, drop: dropPath, clip: inside.url }
450
+ }
451
+ icons.dataset.pouring = ''
452
+ const e = morphEase()
453
+ const s2 = (rel: number, a: number, b: number) => clamp01((rel - a * k) / ((b - a) * k))
454
+ const toward = (v: number, t: number) => lerp(v, to, e(t))
455
+ const ms = (to ? (drop ? 600 : 440) : 560) * k
456
+ const layerSvg = svg
457
+ const run: CopyRun = {
458
+ state: { ...from },
459
+ done: false,
460
+ svg: layerSvg,
461
+ paths: p,
462
+ halt: () => {},
463
+ stop: () => {
464
+ run.done = true
465
+ run.halt()
466
+ layerSvg.remove()
467
+ delete icons.dataset.pouring
468
+ },
469
+ }
470
+ const frame = (rel: number) => {
471
+ const st = run.state
472
+ let dp: { x: number; y: number; r: number } | null = null
473
+ if (to) {
474
+ // From rest: the drop forms, flies and sinks in, then the front fills, the back slides under and
475
+ // the square becomes the check. From part way: the same order, without the drop.
476
+ const [f0, f1, s0, s1, m0, m1] = drop ? [160, 300, 200, 300, 300, 600] : [0, 140, 40, 140, 140, 440]
477
+ st.fill = toward(from.fill, s2(rel, f0, f1))
478
+ st.slide = toward(from.slide, s2(rel, s0, s1))
479
+ st.morph = toward(from.morph, s2(rel, m0, m1))
480
+ if (drop) {
481
+ const form = s2(rel, 0, 70)
482
+ const fly = s2(rel, 70, 190)
483
+ const sink = s2(rel, 190, 240)
484
+ const q = fly * fly * (3 - 2 * fly)
485
+ const r = size * 0.15 * e(form) * (1 - sink)
486
+ if (r > 0.05) dp = { x: lerp(P[0], entry[0], q), y: lerp(P[1], entry[1], q) - size * 2 * q * (1 - q) + size * 0.25 * sink, r }
487
+ }
488
+ } else {
489
+ st.morph = toward(from.morph, s2(rel, 0, 300))
490
+ st.slide = toward(from.slide, s2(rel, 300, 400))
491
+ st.fill = toward(from.fill, s2(rel, 380, 560))
492
+ }
493
+ const full = st.fill >= 1
494
+ const { liquid } = p
495
+ if (st.fill <= 0) {
496
+ liquid.removeAttribute('clip-path')
497
+ liquid.removeAttribute('data-measure')
498
+ liquid.setAttribute('d', '')
499
+ } else if (!full) {
500
+ liquid.setAttribute('clip-path', p.clip)
501
+ liquid.setAttribute('data-measure', 'surface')
502
+ liquid.setAttribute('data-cup', cupAttr(cup))
503
+ liquid.setAttribute('d', cupPath(cupLevel(st.fill, side, cup), sq.cx - sq.hw - 1, sq.cx + sq.hw + 1, sq.cy + sq.hh + 2))
504
+ } else {
505
+ liquid.removeAttribute('clip-path')
506
+ // The square itself is the icon's own shape; the morph is judged from the first step on.
507
+ if (st.morph > 0) liquid.setAttribute('data-measure', 'morph')
508
+ else liquid.removeAttribute('data-measure')
509
+ liquid.setAttribute('d', st.morph > 0 ? checkLoops(st.morph, g).map((l) => polyPath(l)).join('') : frontD)
510
+ }
511
+ // Once the front is full, its outline and the hidden back square are under the ink.
512
+ p.front.setAttribute('d', full ? '' : frontD + boxPath(hole))
513
+ p.back.setAttribute('d', full && st.slide >= 1 ? '' : BACK_D)
514
+ const off = ICON.back * s * st.slide
515
+ p.back.setAttribute('transform', `translate(${off} ${off}) scale(${s})`)
516
+ p.drop.setAttribute('d', dp ? `M${dp.x - dp.r} ${dp.y}a${dp.r} ${dp.r} 0 1 0 ${2 * dp.r} 0a${dp.r} ${dp.r} 0 1 0 ${-2 * dp.r} 0Z` : '')
517
+ }
518
+ run.halt = frames(ms, (u) => frame(u * ms), () => run.stop())
519
+ return run
520
+ }
521
+
522
+ export type CopyRun = {
523
+ state: CopyState
524
+ done: boolean
525
+ svg: SVGSVGElement
526
+ paths: { back: SVGPathElement; liquid: SVGPathElement; front: SVGPathElement; drop: SVGPathElement; clip: string }
527
+ halt: () => void
528
+ stop: () => void
529
+ }
530
+
531
+ // ---------- menu bead ----------
532
+
533
+ function smin(a: number, b: number, k: number) {
534
+ if (k <= 1e-6) return Math.min(a, b)
535
+ const h = Math.max(k - Math.abs(a - b), 0) / k
536
+ return Math.min(a, b) - (h * h * h * k) / 6
537
+ }
538
+
539
+ // Up to SLIDE px apart, front and tail are one stretched box. Past it the tail narrows and a neck
540
+ // forms, never longer than NECK px.
541
+ const SLIDE = 24
542
+ const NECK = 24
543
+
544
+ /** The bead with its front at F and its tail at T (centres on y), each with its half height. */
545
+ export function beadLoops(cx: number, hw: number, r: number, F: { y: number; hh: number }, T: { y: number; hh: number }): Pt[][] {
546
+ const d = Math.abs(F.y - T.y)
547
+ if (d <= SLIDE) {
548
+ const y0 = Math.min(F.y - F.hh, T.y - T.hh)
549
+ const y1 = Math.max(F.y + F.hh, T.y + T.hh)
550
+ return [boxRing({ cx, cy: (y0 + y1) / 2, hw, hh: (y1 - y0) / 2, r }, 0.5).map((p) => [p[0], p[1]] as Pt)]
551
+ }
552
+ const e = clamp01((d - SLIDE) / 30)
553
+ const kk = 18 * e
554
+ const hwT = hw * (1 - 0.1 * e * e)
555
+ const hhT = T.hh - 6 * e
556
+ const my = (F.y + T.y) / 2
557
+ // Wide until the gap between the two is tall enough for round fillets, so no slot opens between them.
558
+ const gq = clamp01((d - F.hh - hhT - 12) / 14)
559
+ const nw = lerp(hwT - 2, Math.min(30, hwT - 2), gq * gq * (3 - 2 * gq))
560
+ const sdf: Sdf = (x, y) =>
561
+ smin(smin(sdBox(x, y, { cx, cy: F.y, hw, hh: F.hh, r }), sdBox(x, y, { cx, cy: T.y, hw: hwT, hh: hhT, r }), kk), sdBox(x, y, { cx, cy: my, hw: nw, hh: d / 2, r: Math.min(nw, 8) }), kk)
562
+ return trace(sdf, [[cx, F.y, 1, 0]])
563
+ }
564
+
565
+ /**
566
+ * Menu items: the hover fill is a bead that follows focus (which follows the pointer) from item to
567
+ * item. A next item settles in about 100ms with a slight stretch; a jump of two or more stretches a
568
+ * short neck. While it moves `root` (the menu panel) carries data-bead, so the items' own fill stands down; at rest
569
+ * the focused item's CSS fill is back. Focus leaving the panel mid-move fades the bead where it is.
570
+ * Only this panel's own items count (submenus sit inside it). Returns a stop.
571
+ */
572
+ export function bead(root: HTMLElement, cls: string) {
573
+ const st = { F: 0, T: 0, hF: 0, hT: 0 }
574
+ let goal: HTMLElement | null = null
575
+ let run: { svg: SVGSVGElement; path: SVGPathElement; id: number; last: number } | null = null
576
+ const itemOf = (t: EventTarget | null) => {
577
+ const el = t instanceof Element ? t.closest<HTMLElement>('[role^="menuitem"]') : null
578
+ return el && el.closest('[role="menu"]') === root ? el : null
579
+ }
580
+ // Layout boxes, not screen ones: the panel and its items may be mid scale or slide as they arrive.
581
+ const boxOf = (el: HTMLElement) => {
582
+ let x = 0
583
+ let y = 0
584
+ for (let n: HTMLElement | null = el; n && n !== root; n = n.offsetParent as HTMLElement | null) {
585
+ x += n.offsetLeft
586
+ y += n.offsetTop
587
+ if (n.offsetParent && n.offsetParent !== root) {
588
+ x += (n.offsetParent as HTMLElement).clientLeft
589
+ y += (n.offsetParent as HTMLElement).clientTop
590
+ }
591
+ }
592
+ return { x, y, w: el.offsetWidth, h: el.offsetHeight }
593
+ }
594
+ const end = () => {
595
+ if (!run) return
596
+ cancelAnimationFrame(run.id)
597
+ run.svg.remove()
598
+ run = null
599
+ // The focused item's own fill comes back at once, not through its fade.
600
+ const el = goal
601
+ if (el) el.style.transition = 'none'
602
+ delete root.dataset.bead
603
+ if (el) {
604
+ void getComputedStyle(el).backgroundColor
605
+ el.style.removeProperty('transition')
606
+ }
607
+ }
608
+ const tick = (now: number) => {
609
+ if (!run || !goal) return
610
+ const dt = Math.min(64, Math.max(0, now - run.last))
611
+ run.last = now
612
+ const fast = motionFor('fast')
613
+ const b = boxOf(goal)
614
+ const gy = b.y + b.h / 2
615
+ const gh = b.h / 2
616
+ st.F += (gy - st.F) * (1 - Math.exp(-dt / (fast / 9)))
617
+ st.hF += (gh - st.hF) * (1 - Math.exp(-dt / (fast / 9)))
618
+ st.T += (st.F - st.T) * (1 - Math.exp(-dt / (fast / 7)))
619
+ st.hT += (st.hF - st.hT) * (1 - Math.exp(-dt / (fast / 7)))
620
+ const most = st.hF + st.hT - 6 + NECK
621
+ if (Math.abs(st.F - st.T) > most) st.T = st.F - Math.sign(st.F - st.T) * most
622
+ const r = parseFloat(getComputedStyle(goal).borderTopLeftRadius) || 0
623
+ if (Math.abs(gy - st.F) < 0.05 && Math.abs(st.F - st.T) < 0.05 && Math.abs(gh - st.hT) < 0.05) {
624
+ run.path.setAttribute('d', boxPath({ cx: b.x + b.w / 2, cy: gy, hw: b.w / 2, hh: gh, r }))
625
+ end()
626
+ return
627
+ }
628
+ const loops = beadLoops(b.x + b.w / 2, b.w / 2, r, { y: st.F, hh: st.hF }, { y: st.T, hh: st.hT })
629
+ run.path.setAttribute('d', loops.map((l) => polyPath(l, 2)).join(''))
630
+ run.id = requestAnimationFrame(tick)
631
+ }
632
+ const focusIn = (ev: FocusEvent) => {
633
+ const to = itemOf(ev.target)
634
+ if (!to) return
635
+ const from = itemOf(ev.relatedTarget)
636
+ goal = to
637
+ if (!motionFor('fast')) return end()
638
+ if (!run) {
639
+ // A first highlight just appears (its CSS fade); only a move between items flows.
640
+ if (!from || from === to) return
641
+ root.dataset.bead = ''
642
+ const b = boxOf(from)
643
+ st.F = st.T = b.y + b.h / 2
644
+ st.hF = st.hT = b.h / 2
645
+ const { svg, paths } = layer(root, cls, root.firstChild)
646
+ svg.setAttribute('width', `${root.scrollWidth}`)
647
+ svg.setAttribute('height', `${root.scrollHeight}`)
648
+ paths[0].setAttribute('data-measure', 'shape')
649
+ run = { svg, path: paths[0], id: 0, last: performance.now() }
650
+ run.id = requestAnimationFrame(tick)
651
+ tick(performance.now())
652
+ }
653
+ if (run) run.path.style.fill = getComputedStyle(to).getPropertyValue('--gooee-bead').trim()
654
+ }
655
+ const focusOut = (ev: FocusEvent) => {
656
+ if (!run || itemOf(ev.relatedTarget)) return
657
+ const r = run
658
+ cancelAnimationFrame(r.id)
659
+ run = null
660
+ goal = null
661
+ delete root.dataset.bead
662
+ const ms = motionFor('fast')
663
+ if (!ms || typeof r.svg.animate !== 'function') return r.svg.remove()
664
+ r.svg.animate({ opacity: [1, 0] }, { duration: ms, easing: 'linear', fill: 'forwards' }).finished.then(
665
+ () => r.svg.remove(),
666
+ () => r.svg.remove(),
667
+ )
668
+ }
669
+ root.addEventListener('focusin', focusIn)
670
+ root.addEventListener('focusout', focusOut)
671
+ return () => {
672
+ root.removeEventListener('focusin', focusIn)
673
+ root.removeEventListener('focusout', focusOut)
674
+ end()
675
+ }
676
+ }