gooee 0.48.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,152 @@
1
+ // One frame loop for every scroll part on the page. It runs only while the page moves, and stops
2
+ // after a moment of stillness; a scroll, a resize or a change in the page's size wakes it again.
3
+
4
+ /** Where the page is (px), how fast it moves (px/s, signed), and the time since the last frame (ms, 0 on mount). */
5
+ export type ScrollFrame = { y: number; v: number; dt: number }
6
+
7
+ /** Reads layout and returns the writes, so every part reads before any part writes. */
8
+ export type ScrollReader = (frame: ScrollFrame) => void | (() => void)
9
+
10
+ export type ScrollTokens = { ease: number; start: number; end: number; turn: number; turnNarrow: number }
11
+
12
+ const readers = new Set<{ current: ScrollReader }>()
13
+ let frame: ScrollFrame = { y: 0, v: 0, dt: 0 }
14
+ let last = { y: 0, t: -1 }
15
+ let raf = 0
16
+ let still = 0
17
+ let observer: ResizeObserver | null = null
18
+ let reduce: MediaQueryList | null = null
19
+ let tokens: ScrollTokens | null = null
20
+
21
+ export function readScrollTokens(): ScrollTokens {
22
+ const s = getComputedStyle(document.documentElement)
23
+ const n = (name: string) => parseFloat(s.getPropertyValue(name))
24
+ return { ease: n('--gooee-scroll-ease'), start: n('--gooee-draft-start'), end: n('--gooee-draft-end'), turn: n('--gooee-story-turn'), turnNarrow: n('--gooee-story-turn-narrow') }
25
+ }
26
+
27
+ /** The tokens, read once each time the loop starts or the window changes size. */
28
+ export const scrollTokens = () => (tokens ??= readScrollTokens())
29
+
30
+ /** Progress from 0 to 1 as an element's top moves from `start` to `end` (shares of the screen height). */
31
+ export function bandProgress(top: number, start: number, end: number) {
32
+ const p = (start - top / window.innerHeight) / (start - end)
33
+ return Math.max(0, Math.min(1, p))
34
+ }
35
+
36
+ // Set by a part that is still easing, so the loop keeps going after the page stops.
37
+ let settling = false
38
+
39
+ /** Moves `from` toward `to` by the scroll ease, the same weight at any frame rate. On mount it lands at once. */
40
+ export function easeToward(from: number, to: number, dt: number) {
41
+ if (dt <= 0) return to
42
+ const k = 1 - Math.pow(1 - scrollTokens().ease, Math.min(4, dt / (1000 / 60)))
43
+ const next = from + (to - from) * k
44
+ if (Math.abs(to - next) < 0.0005) return to
45
+ settling = true
46
+ return next
47
+ }
48
+
49
+ // One part that throws must not stop the loop for every other part, so each runs on its own and the
50
+ // error is reported after the frame.
51
+ function guard<T>(fn: () => T): T | undefined {
52
+ try {
53
+ return fn()
54
+ } catch (error) {
55
+ queueMicrotask(() => {
56
+ throw error
57
+ })
58
+ }
59
+ }
60
+
61
+ function runAll(list: Iterable<{ current: ScrollReader }>, f: ScrollFrame) {
62
+ const writes: Array<() => void> = []
63
+ for (const r of list) {
64
+ const w = guard(() => r.current(f))
65
+ if (w) writes.push(w)
66
+ }
67
+ writes.forEach((w) => guard(w))
68
+ }
69
+
70
+ function run(f: ScrollFrame) {
71
+ runAll(readers, f)
72
+ }
73
+
74
+ function tick(t: number) {
75
+ const y = window.scrollY
76
+ // The first frame after a wake only takes its bearings: its time can be earlier than the wake's.
77
+ let v = frame.v
78
+ if (last.t >= 0) {
79
+ v += (((y - last.y) / Math.max(1, t - last.t)) * 1000 - v) * 0.2
80
+ if (Math.abs(v) < 1) v = 0
81
+ }
82
+ const moved = y !== last.y
83
+ const dt = last.t >= 0 ? t - last.t : 0
84
+ last = { y, t }
85
+ frame = { y, v, dt }
86
+ settling = false
87
+ run(frame)
88
+ still = !moved && v === 0 && !settling ? still + 1 : 0
89
+ raf = still > 30 ? 0 : requestAnimationFrame(tick)
90
+ }
91
+
92
+ function wake() {
93
+ still = 0
94
+ if (raf) return
95
+ tokens = null
96
+ last = { y: window.scrollY, t: -1 }
97
+ raf = requestAnimationFrame(tick)
98
+ }
99
+
100
+ function onResize() {
101
+ tokens = null
102
+ wake()
103
+ }
104
+
105
+ function start() {
106
+ window.addEventListener('scroll', wake, { passive: true })
107
+ window.addEventListener('resize', onResize)
108
+ // Fonts, pictures or an opened panel can move things without a scroll.
109
+ observer = new ResizeObserver(wake)
110
+ observer.observe(document.body)
111
+ reduce = window.matchMedia('(prefers-reduced-motion: reduce)')
112
+ reduce.addEventListener('change', wake)
113
+ }
114
+
115
+ function stop() {
116
+ window.removeEventListener('scroll', wake)
117
+ window.removeEventListener('resize', onResize)
118
+ observer?.disconnect()
119
+ observer = null
120
+ reduce?.removeEventListener('change', wake)
121
+ reduce = null
122
+ cancelAnimationFrame(raf)
123
+ raf = 0
124
+ frame = { y: 0, v: 0, dt: 0 }
125
+ }
126
+
127
+ /**
128
+ * Calls `read` once (with the other parts that start in the same task, before the first paint) and then
129
+ * every frame while the page moves. Returns a function that stops it.
130
+ */
131
+ export function onScrollFrame(read: ScrollReader) {
132
+ const ref = { current: read }
133
+ if (!readers.size) start()
134
+ readers.add(ref)
135
+ mounting.add(ref)
136
+ if (mounting.size === 1) queueMicrotask(runMounts)
137
+ wake()
138
+ return () => {
139
+ readers.delete(ref)
140
+ mounting.delete(ref)
141
+ if (!readers.size) stop()
142
+ }
143
+ }
144
+
145
+ // Parts that mount together read once, together, before the first paint, so the page lays out once.
146
+ const mounting = new Set<{ current: ScrollReader }>()
147
+
148
+ function runMounts() {
149
+ const list = [...mounting]
150
+ mounting.clear()
151
+ runAll(list, { y: window.scrollY, v: frame.v, dt: 0 })
152
+ }
@@ -0,0 +1,154 @@
1
+ import { createScrub, type ScrubOptions } from '../feel'
2
+ import { morphCurve, readMotionMs } from '../motion'
3
+
4
+ // Pointer, keys and wheel in, the drawn position out, for Dial, RulerScrubber and PickerWheel. The
5
+ // motion itself lives in feel.ts (createScrub).
6
+
7
+ type Last = { x: number; y: number }
8
+
9
+ /** What the scrubber reads from a pointer event: native and React events both have these. */
10
+ export type PointerLike = Pick<PointerEvent, 'button' | 'clientX' | 'clientY' | 'pointerId' | 'pointerType' | 'timeStamp' | 'type'> & { currentTarget: EventTarget | null }
11
+ type KeyLike = Pick<KeyboardEvent, 'key' | 'altKey' | 'ctrlKey' | 'metaKey' | 'preventDefault'>
12
+
13
+ export type ScrubberOptions<P extends PointerLike = PointerEvent> = Pick<ScrubOptions, 'min' | 'max' | 'edge' | 'land' | 'coast' | 'maxSpeed'> & {
14
+ /** The value it starts at, and later the value from outside: `sync` glides there. */
15
+ value: number
16
+ onSettle: (value: number) => void
17
+ /** A new resting value came under the hand while it moves. */
18
+ onMark?: (value: number) => void
19
+ /** How far a pointer move turns the value, in its units. */
20
+ move: (e: P, last: Last, el: HTMLElement) => number
21
+ /** The value a key goes to, or null to leave the key alone. */
22
+ key: (key: string, target: number) => number | null
23
+ /** The value a plain tap goes to, or null to land where it is. */
24
+ tap?: (e: P, at: number) => number | null
25
+ /** The value a wheel turn goes to, or null to let the page scroll. */
26
+ wheel?: (e: WheelEvent, target: number, focused: boolean) => number | null
27
+ /** A short buzz on each new value under the hand, where the phone can (Android). */
28
+ haptics?: boolean
29
+ /** Where it is drawn now, each frame. */
30
+ onFrame?: (at: number) => void
31
+ /** True while it moves, false once it rests. */
32
+ onMoving?: (moving: boolean) => void
33
+ }
34
+
35
+ type Press = { id: number; sx: number; sy: number; x: number; y: number; moved: boolean }
36
+
37
+ // A press is not a drag until it moves this far, so a tap stays a tap.
38
+ const SLOP = 4
39
+
40
+ /** A scrubbed value: feed it the control's events, or call `listen` on the control. `update` takes new options. */
41
+ export function createScrubber<P extends PointerLike = PointerEvent>(options: ScrubberOptions<P>) {
42
+ let o = options
43
+ let press: Press | null = null
44
+ const s = createScrub({
45
+ value: o.value,
46
+ land: (p) => o.land(p),
47
+ duration: () => readMotionMs('morph-out'),
48
+ curve: morphCurve,
49
+ onFrame: (v) => o.onFrame?.(v),
50
+ onMoving: (m) => o.onMoving?.(m),
51
+ onMark: (v) => {
52
+ o.onMark?.(v)
53
+ if (o.haptics) navigator.vibrate?.(5)
54
+ },
55
+ // Only a new value is news: a tap, Home at the start, or a drag back to where it was says nothing.
56
+ onSettle: (v) => v !== o.value && o.onSettle(v),
57
+ })
58
+ const update = (next: ScrubberOptions<P>) => {
59
+ o = next
60
+ s.update({ min: o.min, max: o.max, edge: o.edge, coast: o.coast, maxSpeed: o.maxSpeed })
61
+ }
62
+ update(o)
63
+
64
+ const down = (e: P) => {
65
+ if (e.pointerType === 'mouse' && e.button !== 0) return
66
+ try {
67
+ ;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
68
+ } catch {
69
+ // A pointer the browser no longer knows (a synthetic one) cannot be captured, and needs no capture.
70
+ }
71
+ s.grab(e.timeStamp)
72
+ press = { id: e.pointerId, sx: e.clientX, sy: e.clientY, x: e.clientX, y: e.clientY, moved: false }
73
+ }
74
+ const move = (e: P) => {
75
+ const p = press
76
+ if (!p || p.id !== e.pointerId) return
77
+ if (!p.moved) {
78
+ if (Math.hypot(e.clientX - p.sx, e.clientY - p.sy) < SLOP) return
79
+ p.moved = true
80
+ }
81
+ const delta = o.move(e, p, e.currentTarget as HTMLElement)
82
+ p.x = e.clientX
83
+ p.y = e.clientY
84
+ s.drag(delta, e.timeStamp)
85
+ }
86
+ const up = (e: P) => {
87
+ const p = press
88
+ if (!p || p.id !== e.pointerId) return
89
+ press = null
90
+ if (e.type === 'pointercancel') return s.cancel()
91
+ if (p.moved) return s.release(e.timeStamp)
92
+ const t = o.tap?.(e, s.at)
93
+ if (t === null || t === undefined) s.release(e.timeStamp)
94
+ else s.go(t)
95
+ }
96
+ const keyDown = (e: KeyLike) => {
97
+ if (e.altKey || e.ctrlKey || e.metaKey) return
98
+ const t = o.key(e.key, s.target)
99
+ if (t === null) return
100
+ e.preventDefault()
101
+ s.go(t)
102
+ }
103
+
104
+ /** Lets the wheel turn it, when `wheel` is set. Returns a function that stops. */
105
+ const wheelOn = (el: HTMLElement) => {
106
+ const onWheel = (e: WheelEvent) => {
107
+ const t = o.wheel?.(e, s.target, document.activeElement === el) ?? null
108
+ if (t === null) return
109
+ e.preventDefault()
110
+ if (t !== s.target) s.go(t)
111
+ }
112
+ el.addEventListener('wheel', onWheel, { passive: false })
113
+ return () => el.removeEventListener('wheel', onWheel)
114
+ }
115
+
116
+ return {
117
+ down,
118
+ move,
119
+ up,
120
+ keyDown,
121
+ wheelOn,
122
+ /** A value set from outside (a controlled prop, a reset) glides there, unless the hand holds it. */
123
+ sync(value: number) {
124
+ if (press || s.moving || value === s.target) return
125
+ s.go(value)
126
+ },
127
+ update,
128
+ get at() {
129
+ return s.at
130
+ },
131
+ get moving() {
132
+ return s.moving
133
+ },
134
+ target: () => s.target,
135
+ go: (to: number) => s.go(to),
136
+ place: (to: number) => s.place(to),
137
+ destroy: () => s.stop(),
138
+ /** Listens on the control (pointer, keys, and the wheel when `wheel` is set). Returns a function that stops. */
139
+ listen(el: HTMLElement) {
140
+ const ac = new AbortController()
141
+ const opts = { signal: ac.signal }
142
+ el.addEventListener('pointerdown', (e) => down(e as unknown as P), opts)
143
+ el.addEventListener('pointermove', (e) => move(e as unknown as P), opts)
144
+ el.addEventListener('pointerup', (e) => up(e as unknown as P), opts)
145
+ el.addEventListener('pointercancel', (e) => up(e as unknown as P), opts)
146
+ el.addEventListener('keydown', keyDown, opts)
147
+ const stopWheel = o.wheel ? wheelOn(el) : () => {}
148
+ return () => {
149
+ ac.abort()
150
+ stopWheel()
151
+ }
152
+ },
153
+ }
154
+ }
@@ -0,0 +1,334 @@
1
+ import { boxRing, clamp01, lerp, nearest, polyPath, seg, softRing, type Pt } from '../liquidPath'
2
+ import { morphEase, motionFor } from './liquidMatter'
3
+ import { motionMs, prefersReducedMotion } from '../motion'
4
+
5
+ // Soft press (Button): while someone presses, hovers or lets go, an SVG draws the button's own shape
6
+ // with a soft edge. The edge dents where the finger is (the middle, for a key) and follows it, a mouse
7
+ // near the edge pulls it out a little, and a let-go sends one small wave round the edge. A wet spot
8
+ // spreads under the press and fades after. The label never moves. At rest the SVG is gone and the
9
+ // button's CSS shape is back, exact.
10
+
11
+ const NS = 'http://www.w3.org/2000/svg'
12
+ let ids = 0
13
+
14
+ export type SoftLook = { layer: string; fill: string; ring: string; wet: string }
15
+
16
+ type Ring = Array<[number, number, number, number]>
17
+
18
+ type Live = {
19
+ el: HTMLElement
20
+ svg: SVGSVGElement
21
+ fill: SVGPathElement
22
+ ring: SVGPathElement
23
+ clip: SVGPathElement
24
+ wet: SVGCircleElement
25
+ outer: Ring
26
+ inner: Ring
27
+ w: number
28
+ h: number
29
+ top: number
30
+ bottom: number
31
+ meet: number
32
+ }
33
+
34
+ const fine = () => window.matchMedia('(hover: hover) and (pointer: fine)').matches
35
+
36
+ export type SoftPressOptions = {
37
+ /** Class names for the layer and its parts. */
38
+ look: SoftLook
39
+ /** Keys that press it, such as Enter and Space. */
40
+ keys: string[]
41
+ /** True while it must not respond, such as when disabled or loading. */
42
+ inert?: boolean
43
+ }
44
+
45
+ type PointerLike = Pick<PointerEvent, 'button' | 'clientX' | 'clientY' | 'pointerId' | 'pointerType'> & { currentTarget: EventTarget | null }
46
+ type KeyLike = Pick<KeyboardEvent, 'key' | 'repeat'> & { currentTarget: EventTarget | null }
47
+
48
+ /**
49
+ * Soft press for one button. Options are read at each event, so they can change. Feed it the button's
50
+ * events, or call `listen` on the button. Call `destroy` when the button goes, and `stop` when it turns inert.
51
+ */
52
+ export function createSoftPress(o: SoftPressOptions) {
53
+ const s = ({
54
+ live: null as Live | null,
55
+ dent: 0,
56
+ press: null as null | { into: boolean; from: number; t0: number; ms: number; wave: boolean },
57
+ held: false,
58
+ byKey: false,
59
+ at: [0, 0] as Pt,
60
+ aim: [0, 0] as Pt,
61
+ pull: 0,
62
+ pullAim: 0,
63
+ to: [0, 0] as Pt,
64
+ toAim: [0, 0] as Pt,
65
+ wave: null as null | { t0: number; ms: number; from: number[] },
66
+ wet: null as null | { t0: number; ms: number; fade: { t0: number; ms: number } | null },
67
+ last: 0,
68
+ raf: 0,
69
+ off: () => {},
70
+ })
71
+
72
+ // The shape for the button's size now. Runs again when the size changes while the layer is up, such
73
+ // as a label that changes on click.
74
+ const fit = (L: Pick<Live, 'el' | 'svg'>) => {
75
+ const { el, svg } = L
76
+ const w = el.offsetWidth
77
+ const h = el.offsetHeight
78
+ const css = getComputedStyle(el)
79
+ const line = parseFloat(css.borderTopWidth) || 0
80
+ const r = Math.min(h / 2, parseFloat(css.borderTopLeftRadius) || 0)
81
+ const outer = boxRing({ cx: w / 2, cy: h / 2, hw: w / 2, hh: h / 2, r }, 1)
82
+ const inner = boxRing({ cx: w / 2, cy: h / 2, hw: w / 2 - line, hh: h / 2 - line, r: Math.max(0, r - line) }, 1)
83
+ svg.setAttribute('width', String(w))
84
+ svg.setAttribute('height', String(h))
85
+ let len = 0
86
+ outer.forEach((p, i) => (len += Math.hypot(outer[(i + 1) % outer.length][0] - p[0], outer[(i + 1) % outer.length][1] - p[1])))
87
+ return { outer, inner, w, h, top: nearest(outer, w / 2, 0), bottom: nearest(outer, w / 2, h), meet: len / 2 }
88
+ }
89
+
90
+ const build = (el: HTMLElement): Live => {
91
+ const svg = document.createElementNS(NS, 'svg')
92
+ svg.setAttribute('class', o.look.layer)
93
+ svg.setAttribute('aria-hidden', 'true')
94
+ svg.setAttribute('data-gooee-liquid', '')
95
+ const id = `gooee-soft-${++ids}`
96
+ const defs = svg.appendChild(document.createElementNS(NS, 'defs'))
97
+ const grad = defs.appendChild(document.createElementNS(NS, 'radialGradient'))
98
+ grad.id = `${id}-wet`
99
+ for (const [at, o] of [['0', '0.9'], ['0.5', '0.6'], ['1', '0']]) {
100
+ const stop = grad.appendChild(document.createElementNS(NS, 'stop'))
101
+ stop.setAttribute('offset', at)
102
+ stop.setAttribute('stop-opacity', o)
103
+ }
104
+ const clipEl = defs.appendChild(document.createElementNS(NS, 'clipPath'))
105
+ clipEl.id = `${id}-clip`
106
+ const clip = clipEl.appendChild(document.createElementNS(NS, 'path'))
107
+ const fill = svg.appendChild(document.createElementNS(NS, 'path'))
108
+ fill.setAttribute('class', o.look.fill)
109
+ const ring = svg.appendChild(document.createElementNS(NS, 'path'))
110
+ ring.setAttribute('class', o.look.ring)
111
+ ring.setAttribute('fill-rule', 'evenodd')
112
+ const wet = svg.appendChild(document.createElementNS(NS, 'circle'))
113
+ wet.setAttribute('class', o.look.wet)
114
+ wet.setAttribute('fill', `url(#${id}-wet)`)
115
+ wet.setAttribute('clip-path', `url(#${id}-clip)`)
116
+ wet.setAttribute('r', '0')
117
+ el.prepend(svg)
118
+ el.dataset.soft = ''
119
+ return { el, svg, fill, ring, clip, wet, ...fit({ el, svg }) }
120
+ }
121
+
122
+ const teardown = () => {
123
+ cancelAnimationFrame(s.raf)
124
+ s.raf = 0
125
+ s.off()
126
+ s.off = () => {}
127
+ if (s.live) {
128
+ const el = s.live.el
129
+ s.live.svg.remove()
130
+ // The button's own paint comes back at once, with no fade, so the hand-over does not show.
131
+ const own = el.style.transition
132
+ el.style.transition = 'none'
133
+ delete el.dataset.soft
134
+ delete el.dataset.held
135
+ void getComputedStyle(el).backgroundColor
136
+ el.style.transition = own
137
+ }
138
+ s.live = null
139
+ s.dent = 0
140
+ s.press = null
141
+ s.held = false
142
+ s.pull = 0
143
+ s.pullAim = 0
144
+ s.wave = null
145
+ s.wet = null
146
+ }
147
+
148
+ const frame = (now: number) => {
149
+ s.raf = 0
150
+ const L = s.live
151
+ if (!L) return
152
+ if (L.el.offsetWidth !== L.w || L.el.offsetHeight !== L.h) Object.assign(L, fit(L))
153
+ const dt = Math.max(0, now - s.last)
154
+ s.last = now
155
+ const e = morphEase()
156
+ const still = prefersReducedMotion()
157
+ const fast = motionMs('fast') || 1
158
+ const follow = still ? 1 : 1 - Math.exp(-dt / (fast / 3.5))
159
+ s.at = [s.at[0] + (s.aim[0] - s.at[0]) * follow, s.at[1] + (s.aim[1] - s.at[1]) * follow]
160
+ const pullTo = s.held || s.press || s.wave ? 0 : s.pullAim
161
+ s.pull = still ? 0 : s.pull + (pullTo - s.pull) * (1 - Math.exp(-dt / (fast / 1.5)))
162
+ if (pullTo === 0 && s.pull < 0.01) s.pull = 0
163
+ const ease = still ? 1 : 1 - Math.exp(-dt / (fast / 2.3))
164
+ s.to = [s.to[0] + (s.toAim[0] - s.to[0]) * ease, s.to[1] + (s.toAim[1] - s.to[1]) * ease]
165
+ const depth = parseFloat(getComputedStyle(L.el).getPropertyValue('--gooee-press-depth')) || 0
166
+ const p = s.press
167
+ if (p) {
168
+ const k = p.ms ? clamp01((now - p.t0) / p.ms) : 1
169
+ if (p.into) s.dent = lerp(p.from, depth, e(k))
170
+ else s.dent = p.wave ? p.from * (1 - e(seg(k, 0, 0.45))) : 0
171
+ if (!p.into && k >= 1) {
172
+ s.press = null
173
+ s.dent = 0
174
+ }
175
+ }
176
+ let wave = 0
177
+ let run = 0
178
+ if (s.wave) {
179
+ const k = s.wave.ms ? clamp01((now - s.wave.t0) / s.wave.ms) : 1
180
+ if (k >= 1) s.wave = null
181
+ else {
182
+ // It slows near the far side and fades out on the morph curve in its second half.
183
+ wave = Math.sin((Math.PI / 2) * clamp01(k / 0.12)) * (1 - e(seg(k, 0.55, 1)))
184
+ run = (1 - (1 - k) ** 2) * (L.meet / s.wave.from.length)
185
+ }
186
+ }
187
+ let wetOn = false
188
+ if (s.wet) {
189
+ const r = lerp(L.h * 0.21, L.h, s.wet.ms ? e(clamp01((now - s.wet.t0) / s.wet.ms)) : 1)
190
+ const f = s.wet.fade
191
+ const o = f ? (f.ms ? 1 - e(clamp01((now - f.t0) / f.ms)) : 0) : 1
192
+ if (o <= 0.002) s.wet = null
193
+ else {
194
+ wetOn = true
195
+ L.wet.setAttribute('cx', s.at[0].toFixed(2))
196
+ L.wet.setAttribute('cy', s.at[1].toFixed(2))
197
+ L.wet.setAttribute('r', r.toFixed(2))
198
+ L.wet.setAttribute('opacity', o.toFixed(3))
199
+ }
200
+ }
201
+ L.wet.style.display = wetOn ? '' : 'none'
202
+ const shape = { dent: s.dent, at: s.at, pull: s.pull, to: s.to, wave, run, from: s.wave?.from ?? [] }
203
+ if (!s.dent && !s.pull && !wave && !wetOn && !s.held && !s.press && !s.pullAim) {
204
+ teardown()
205
+ return
206
+ }
207
+ const outer = polyPath(softRing(L.outer, L.h, shape))
208
+ L.fill.setAttribute('d', outer)
209
+ L.clip.setAttribute('d', outer)
210
+ L.ring.setAttribute('d', outer + polyPath(softRing(L.inner, L.h, shape)))
211
+ s.raf = requestAnimationFrame(frame)
212
+ }
213
+
214
+ const wake = (el: HTMLElement) => {
215
+ if (!s.live) {
216
+ s.live = build(el)
217
+ s.at = [...s.aim]
218
+ s.to = [...s.toAim]
219
+ s.last = performance.now()
220
+ }
221
+ if (!s.raf) s.raf = requestAnimationFrame(frame)
222
+ }
223
+
224
+ const local = (el: HTMLElement, x: number, y: number): Pt => {
225
+ const r = el.getBoundingClientRect()
226
+ return [x - r.left, y - r.top]
227
+ }
228
+
229
+ const press = (el: HTMLElement, at: Pt, byKey: boolean) => {
230
+ s.aim = at
231
+ if (!s.held) s.at = [...at]
232
+ s.held = true
233
+ s.byKey = byKey
234
+ s.wave = null
235
+ el.dataset.held = ''
236
+ wake(el)
237
+ const L = s.live!
238
+ s.at = [...at]
239
+ s.press = { into: true, from: s.dent, t0: performance.now(), ms: motionFor('fast'), wave: false }
240
+ s.wet = { t0: performance.now(), ms: motionFor('slower'), fade: null }
241
+ // The wet spot darkens a light fill and lightens a dark one.
242
+ const rgb = getComputedStyle(L.fill).fill.match(/[\d.]+/g)?.map(Number) ?? [255, 255, 255, 0]
243
+ const light = (rgb[3] ?? 1) < 0.1 || 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2] > 140
244
+ L.svg.dataset.wet = light ? 'dark' : 'light'
245
+ }
246
+
247
+ const release = () => {
248
+ if (!s.held || !s.live) return
249
+ s.held = false
250
+ delete s.live.el.dataset.held
251
+ s.off()
252
+ s.off = () => {}
253
+ const ms = motionFor('slow')
254
+ s.press = { into: false, from: s.dent, t0: performance.now(), ms, wave: ms > 0 }
255
+ if (ms) s.wave = { t0: performance.now(), ms, from: s.byKey ? [s.live.top, s.live.bottom] : [nearest(s.live.outer, s.at[0], s.at[1])] }
256
+ if (s.wet) s.wet.fade = { t0: performance.now(), ms: motionFor('slow') }
257
+ wake(s.live.el)
258
+ }
259
+
260
+ const down = (e: PointerLike) => {
261
+ if (o.inert || e.button !== 0) return
262
+ const el = e.currentTarget as HTMLElement
263
+ press(el, local(el, e.clientX, e.clientY), false)
264
+ const move = (m: PointerEvent) => {
265
+ if (m.pointerId === e.pointerId) s.aim = local(el, m.clientX, m.clientY)
266
+ }
267
+ const up = (m: PointerEvent) => {
268
+ if (m.pointerId === e.pointerId) release()
269
+ }
270
+ window.addEventListener('pointermove', move)
271
+ window.addEventListener('pointerup', up)
272
+ window.addEventListener('pointercancel', up)
273
+ s.off = () => {
274
+ window.removeEventListener('pointermove', move)
275
+ window.removeEventListener('pointerup', up)
276
+ window.removeEventListener('pointercancel', up)
277
+ }
278
+ }
279
+ const hover = (e: PointerLike) => {
280
+ if (o.inert || e.pointerType !== 'mouse' || !fine() || prefersReducedMotion() || s.held) return
281
+ const el = e.currentTarget as HTMLElement
282
+ const [x, y] = local(el, e.clientX, e.clientY)
283
+ const w = el.offsetWidth
284
+ const h = el.offsetHeight
285
+ // Strongest at the edge, less toward the middle.
286
+ const edge = Math.min(x, w - x, y, h - y)
287
+ s.pullAim = Math.exp(-(edge * edge) / (2 * (h * 0.58) ** 2))
288
+ const ring = s.live?.outer ?? boxRing({ cx: w / 2, cy: h / 2, hw: w / 2, hh: h / 2, r: h / 2 }, 1)
289
+ const p = ring[nearest(ring, x, y)]
290
+ s.toAim = [p[0], p[1]]
291
+ wake(el)
292
+ }
293
+ const leave = () => {
294
+ s.pullAim = 0
295
+ }
296
+ const keyDown = (e: KeyLike) => {
297
+ if (o.inert || e.repeat || !o.keys.includes(e.key)) return
298
+ const el = e.currentTarget as HTMLElement
299
+ press(el, [el.offsetWidth / 2, el.offsetHeight / 2], true)
300
+ }
301
+ const keyUp = (e: KeyLike) => {
302
+ if (o.keys.includes(e.key) && s.byKey) release()
303
+ }
304
+ const blur = () => {
305
+ if (s.byKey) release()
306
+ }
307
+
308
+ return {
309
+ down,
310
+ hover,
311
+ leave,
312
+ keyDown,
313
+ keyUp,
314
+ blur,
315
+ /** Ends any press at once and removes the drawing. */
316
+ stop: teardown,
317
+ destroy: teardown,
318
+ /** Listens on the button. Returns a function that stops listening and removes the drawing. */
319
+ listen(button: HTMLElement) {
320
+ const ac = new AbortController()
321
+ const opts = { signal: ac.signal }
322
+ button.addEventListener('pointerdown', down, opts)
323
+ button.addEventListener('pointermove', hover, opts)
324
+ button.addEventListener('pointerleave', leave, opts)
325
+ button.addEventListener('keydown', keyDown, opts)
326
+ button.addEventListener('keyup', keyUp, opts)
327
+ button.addEventListener('blur', blur, opts)
328
+ return () => {
329
+ ac.abort()
330
+ teardown()
331
+ }
332
+ },
333
+ }
334
+ }