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.
- package/package.json +1 -1
- package/src/components/HoldToConfirm/HoldToConfirm.tsx +2 -1
- package/src/components/LivePill/LivePill.tsx +1 -1
- package/src/internal/fling.ts +29 -106
- package/src/internal/focus.ts +2 -34
- package/src/internal/liquid.ts +26 -213
- package/src/internal/liquidMatter.ts +9 -181
- package/src/internal/liquidMore.ts +6 -669
- package/src/internal/motion/fling.ts +147 -0
- package/src/internal/motion/focus.ts +35 -0
- package/src/internal/motion/index.ts +20 -0
- package/src/internal/motion/liquid.ts +241 -0
- package/src/internal/motion/liquidMatter.ts +198 -0
- package/src/internal/motion/liquidMore.ts +676 -0
- package/src/internal/motion/scrollFrame.ts +152 -0
- package/src/internal/motion/scrubber.ts +154 -0
- package/src/internal/motion/softPress.ts +334 -0
- package/src/internal/scrollFrame.ts +4 -145
- package/src/internal/softPress.ts +27 -289
- package/src/internal/useScrub.ts +14 -107
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { morphTo, rubber, speedTracker } from '../feel'
|
|
2
|
+
import { morphCurve, readMotionMs } from '../motion'
|
|
3
|
+
|
|
4
|
+
/** An element, or a function that returns it, for frameworks that hand it over later (a React ref). */
|
|
5
|
+
export type Target = HTMLElement | (() => HTMLElement | null)
|
|
6
|
+
const resolve = (t: Target) => (typeof t === 'function' ? t() : t)
|
|
7
|
+
|
|
8
|
+
/** What a drag needs from a pointer event: native and React events both have these. */
|
|
9
|
+
export type PointerLike = Pick<PointerEvent, 'clientY' | 'pointerId' | 'pointerType' | 'button' | 'type'> & { target: EventTarget | null; currentTarget: EventTarget | null }
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A let-go: runs from `from` to `to` on the morph curve, starting at `velocity` (units per second), so
|
|
13
|
+
* it carries on at the hand's speed. From rest it takes --gooee-motion-morph-out: Retime slows it,
|
|
14
|
+
* reduced motion (0ms) jumps. Returns a stop function.
|
|
15
|
+
*/
|
|
16
|
+
export function release(from: number, to: number, velocity: number, onFrame: (value: number) => void, onDone?: () => void) {
|
|
17
|
+
return morphTo({ from, to, velocity, duration: readMotionMs('morph-out'), curve: morphCurve(), onFrame, onDone })
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A panel that the hand drags along one axis and lets go of. `fling` glides it to a place at the hand's
|
|
22
|
+
* speed. While it runs, data-fluid on the panel turns its CSS motion off; once it closes on the way out,
|
|
23
|
+
* the CSS close keyframes stay off too, so they do not start over. Call `opened` and `closed` as the
|
|
24
|
+
* panel opens and closes.
|
|
25
|
+
*/
|
|
26
|
+
export function createFling(target: Target, axis: 'x' | 'y') {
|
|
27
|
+
let at = 0
|
|
28
|
+
let to = 0
|
|
29
|
+
let stop = () => {}
|
|
30
|
+
|
|
31
|
+
const paint = (v: number) => {
|
|
32
|
+
at = v
|
|
33
|
+
const el = resolve(target)
|
|
34
|
+
if (el) el.style.transform = v ? `translate${axis === 'x' ? 'X' : 'Y'}(${v}px)` : ''
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
get at() {
|
|
39
|
+
return at
|
|
40
|
+
},
|
|
41
|
+
paint,
|
|
42
|
+
fling(place: number, speed: number) {
|
|
43
|
+
const el = resolve(target)
|
|
44
|
+
if (!el) return
|
|
45
|
+
stop()
|
|
46
|
+
to = place
|
|
47
|
+
el.setAttribute('data-fluid', '')
|
|
48
|
+
stop = release(at, place, speed, paint, () => {
|
|
49
|
+
if (place === 0) el.removeAttribute('data-fluid')
|
|
50
|
+
})
|
|
51
|
+
},
|
|
52
|
+
stop: () => stop(),
|
|
53
|
+
// Opened again, even mid-close on the same panel: it starts at rest, not where the old glide was going.
|
|
54
|
+
opened() {
|
|
55
|
+
stop()
|
|
56
|
+
to = 0
|
|
57
|
+
paint(0)
|
|
58
|
+
resolve(target)?.removeAttribute('data-fluid')
|
|
59
|
+
},
|
|
60
|
+
// Closed by Esc or a tap while gliding back: the CSS close takes over from where it is.
|
|
61
|
+
closed() {
|
|
62
|
+
if (to !== 0) return
|
|
63
|
+
stop()
|
|
64
|
+
resolve(target)?.removeAttribute('data-fluid')
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type Fling = ReturnType<typeof createFling>
|
|
70
|
+
|
|
71
|
+
// Past this share of its height, or flicked down this fast (px per second), a let-go closes the sheet.
|
|
72
|
+
const CLOSE_RATIO = 0.3
|
|
73
|
+
const CLOSE_SPEED = 500
|
|
74
|
+
|
|
75
|
+
export type DragCloseOptions = {
|
|
76
|
+
/** Asked to close. If the panel is still open a frame later, it glides back. */
|
|
77
|
+
onClose: () => void
|
|
78
|
+
isOpen: () => boolean
|
|
79
|
+
/** Asked at each press, so a part can take hold only in its phone layout, or only by its header. */
|
|
80
|
+
can?: (e: PointerLike) => boolean
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A bottom sheet the hand drags down to close. Feed it the pointer events of the part it is held by, or
|
|
85
|
+
* call `listen` on that part. A let-go past a third of its height, or a flick down, closes it; any other
|
|
86
|
+
* let-go glides it back.
|
|
87
|
+
*/
|
|
88
|
+
export function createDragClose(target: Target, { onClose, isOpen, can = () => true }: DragCloseOptions) {
|
|
89
|
+
const fling = createFling(target, 'y')
|
|
90
|
+
let drag: { y: number; dy: number; pointer: number; speed: ReturnType<typeof speedTracker> } | null = null
|
|
91
|
+
|
|
92
|
+
const down = (e: PointerLike) => {
|
|
93
|
+
if ((e.target as HTMLElement).closest('button') || !can(e)) return
|
|
94
|
+
if (e.pointerType === 'mouse' && e.button !== 0) return
|
|
95
|
+
fling.stop()
|
|
96
|
+
// Caught mid-glide, it carries on from where it is.
|
|
97
|
+
drag = { y: e.clientY - fling.at, dy: fling.at, pointer: e.pointerId, speed: speedTracker() }
|
|
98
|
+
drag.speed.add(fling.at)
|
|
99
|
+
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
|
|
100
|
+
resolve(target)?.setAttribute('data-dragging', '')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const move = (e: PointerLike) => {
|
|
104
|
+
const panel = resolve(target)
|
|
105
|
+
if (!drag || !panel || drag.pointer !== e.pointerId) return
|
|
106
|
+
const raw = e.clientY - drag.y
|
|
107
|
+
drag.dy = raw >= 0 ? raw : rubber(raw, panel.offsetHeight)
|
|
108
|
+
drag.speed.add(drag.dy)
|
|
109
|
+
fling.paint(drag.dy)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const up = (e: PointerLike) => {
|
|
113
|
+
const d = drag
|
|
114
|
+
const panel = resolve(target)
|
|
115
|
+
drag = null
|
|
116
|
+
if (!d || !panel) return
|
|
117
|
+
;(e.currentTarget as HTMLElement).releasePointerCapture(d.pointer)
|
|
118
|
+
panel.removeAttribute('data-dragging')
|
|
119
|
+
const cancelled = e.type === 'pointercancel'
|
|
120
|
+
const speed = cancelled ? 0 : d.speed.speed()
|
|
121
|
+
const h = panel.offsetHeight
|
|
122
|
+
if (!cancelled && (d.dy > h * CLOSE_RATIO || (speed > CLOSE_SPEED && d.dy > 24))) {
|
|
123
|
+
fling.fling(h, speed)
|
|
124
|
+
onClose()
|
|
125
|
+
requestAnimationFrame(() => {
|
|
126
|
+
if (isOpen()) fling.fling(0, 0)
|
|
127
|
+
})
|
|
128
|
+
} else fling.fling(0, speed)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
fling,
|
|
133
|
+
down,
|
|
134
|
+
move,
|
|
135
|
+
up,
|
|
136
|
+
/** Listens on the part it is held by. Returns a function that stops listening. */
|
|
137
|
+
listen(handle: HTMLElement) {
|
|
138
|
+
const ac = new AbortController()
|
|
139
|
+
const opts = { signal: ac.signal }
|
|
140
|
+
handle.addEventListener('pointerdown', down, opts)
|
|
141
|
+
handle.addEventListener('pointermove', move, opts)
|
|
142
|
+
handle.addEventListener('pointerup', up, opts)
|
|
143
|
+
handle.addEventListener('pointercancel', up, opts)
|
|
144
|
+
return () => ac.abort()
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { watchKeyboard } from '../keyboard'
|
|
2
|
+
|
|
3
|
+
const FOCUSABLE =
|
|
4
|
+
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]), [contenteditable="true"]'
|
|
5
|
+
|
|
6
|
+
export function focusables(root: HTMLElement): HTMLElement[] {
|
|
7
|
+
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
|
|
8
|
+
(el) => !el.hasAttribute('inert') && el.getClientRects().length > 0,
|
|
9
|
+
)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Safari, on iPhone and on Mac, does not focus a button when it is tapped or clicked. So the control
|
|
13
|
+
// that opened a layer is often not the focused element; remember the last one pressed instead.
|
|
14
|
+
// Watched from the moment this file loads, since a layer only mounts after the press that opens it.
|
|
15
|
+
let lastPressed: HTMLElement | null = null
|
|
16
|
+
if (typeof document !== 'undefined') {
|
|
17
|
+
document.addEventListener(
|
|
18
|
+
'pointerdown',
|
|
19
|
+
(e) => {
|
|
20
|
+
lastPressed = (e.target instanceof Element ? e.target.closest<HTMLElement>(FOCUSABLE) : null) ?? null
|
|
21
|
+
},
|
|
22
|
+
true,
|
|
23
|
+
)
|
|
24
|
+
// Focus moved from code stays above a phone keyboard.
|
|
25
|
+
watchKeyboard()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Where focus should go back to: the focused element, unless it is the page or a box around the
|
|
29
|
+
// control that was just pressed. Then that control.
|
|
30
|
+
export function returnTarget(): HTMLElement | null {
|
|
31
|
+
const active = document.activeElement as HTMLElement | null
|
|
32
|
+
const pressed = lastPressed && lastPressed.isConnected ? lastPressed : null
|
|
33
|
+
if (pressed && (!active || active === document.body || (active !== pressed && active.contains(pressed)))) return pressed
|
|
34
|
+
return active
|
|
35
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// gooee-motion: the motion of Gooee UI's parts, with no framework. Timing comes from the --gooee-*
|
|
2
|
+
// tokens (gooee-tokens), so load those too; reduced motion sets them to 0 and every move jumps.
|
|
3
|
+
|
|
4
|
+
// Panels that grow out of what opened them, and highlights that stretch to a new choice.
|
|
5
|
+
export { createLiquid, createDialogMorph, createStretch, stretch, startShape, type LiquidOrigin, type StretchBox } from './liquid'
|
|
6
|
+
// A highlight that flows to a new choice on a neck that thins and breaks.
|
|
7
|
+
export { createFlow, type FlowOptions, type Place } from './liquidMatter'
|
|
8
|
+
// A field's focus edge that flows round from the press, and a menu's hover bead.
|
|
9
|
+
export { edgeFlow, bead } from './liquidMore'
|
|
10
|
+
// A button whose edge dents under the finger.
|
|
11
|
+
export { createSoftPress, type SoftLook, type SoftPressOptions } from './softPress'
|
|
12
|
+
// Panels the hand drags and lets go of, and a sheet dragged down to close.
|
|
13
|
+
export { createFling, createDragClose, release, type Fling, type DragCloseOptions, type Target } from './fling'
|
|
14
|
+
// A value turned by drag, keys and wheel that coasts and lands on a mark.
|
|
15
|
+
export { createScrubber, type ScrubberOptions } from './scrubber'
|
|
16
|
+
// One frame loop for everything that follows the page's scroll.
|
|
17
|
+
export { onScrollFrame, bandProgress, easeToward, type ScrollFrame, type ScrollReader } from './scrollFrame'
|
|
18
|
+
// The motion maths underneath: the morph curve, glides and follows.
|
|
19
|
+
export { MORPH, bezier, morphTo, glide, follow, rubber, speedTracker, type Curve, type MorphOptions, type GlideOptions } from '../feel'
|
|
20
|
+
export { motionMs, readMotionMs, easing, morphCurve, prefersReducedMotion, type MotionToken } from '../motion'
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { returnTarget } from './focus'
|
|
2
|
+
import { bezier } from '../feel'
|
|
3
|
+
import { easing, morphCurve, motionMs, prefersReducedMotion } from '../motion'
|
|
4
|
+
|
|
5
|
+
// Liquid: a panel grows out of what opened it. It starts as the opener's own shape (its width and its
|
|
6
|
+
// corners) at the panel's edge nearest the opener, then fills out to the whole panel; on close it
|
|
7
|
+
// folds back. Only a clip changes, so nothing inside the panel is stretched and text stays sharp.
|
|
8
|
+
// Both ways play the morph curve forward, so a close moves from its first frame, and a move caught
|
|
9
|
+
// half way starts from the shape on screen.
|
|
10
|
+
// Where the browser cannot clip or animate this way, or with reduced motion, the part's own CSS fade
|
|
11
|
+
// runs instead.
|
|
12
|
+
|
|
13
|
+
/** What the panel grows from: the opener element, or one found at open time, or a rectangle (such as the point of a right click). */
|
|
14
|
+
export type LiquidOrigin = HTMLElement | DOMRect | (() => HTMLElement | DOMRect | null)
|
|
15
|
+
|
|
16
|
+
type El = HTMLElement | (() => HTMLElement | null)
|
|
17
|
+
const get = (t: El) => (typeof t === 'function' ? t() : t)
|
|
18
|
+
|
|
19
|
+
const able = () =>
|
|
20
|
+
typeof CSS !== 'undefined' &&
|
|
21
|
+
CSS.supports('clip-path', 'inset(0px round 1px)') &&
|
|
22
|
+
typeof Element !== 'undefined' &&
|
|
23
|
+
typeof Element.prototype.animate === 'function'
|
|
24
|
+
|
|
25
|
+
const clamp = (v: number, max: number) => Math.max(0, Math.min(max, v))
|
|
26
|
+
|
|
27
|
+
// How far the panel's shadow reaches past its box, so the clip can end there and the shadow grows in
|
|
28
|
+
// with the panel instead of appearing all at once when the clip is removed.
|
|
29
|
+
function shadowReach(el: HTMLElement) {
|
|
30
|
+
let reach = 0
|
|
31
|
+
for (const shadow of getComputedStyle(el).boxShadow.split(/,(?![^(]*\))/)) {
|
|
32
|
+
if (shadow.includes('inset')) continue
|
|
33
|
+
const [x = 0, y = 0, blur = 0, spread = 0] = (shadow.replace(/rgba?\([^)]*\)|#[\da-f]+/gi, '').match(/-?[\d.]+px/g) ?? []).map(parseFloat)
|
|
34
|
+
reach = Math.max(reach, Math.abs(x) + blur + spread, Math.abs(y) + blur + spread)
|
|
35
|
+
}
|
|
36
|
+
return Math.ceil(reach)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The opener's footprint on the panel, as an inset from each edge. An opener above or below the panel
|
|
40
|
+
// lands as a strip on the nearest edge; one beside it, on the nearest side; one inside it (a click
|
|
41
|
+
// point), where it is.
|
|
42
|
+
export function startShape(panel: DOMRect, from: DOMRect, radius: string) {
|
|
43
|
+
const w = panel.width
|
|
44
|
+
const h = panel.height
|
|
45
|
+
let top = clamp(from.top - panel.top, h)
|
|
46
|
+
let bottom = clamp(panel.bottom - from.bottom, h)
|
|
47
|
+
let left = clamp(from.left - panel.left, w)
|
|
48
|
+
let right = clamp(panel.right - from.right, w)
|
|
49
|
+
const fh = Math.min(from.height, h)
|
|
50
|
+
const fw = Math.min(from.width, w)
|
|
51
|
+
if (from.bottom <= panel.top + 1) [top, bottom] = [0, h - fh]
|
|
52
|
+
else if (from.top >= panel.bottom - 1) [top, bottom] = [h - fh, 0]
|
|
53
|
+
else if (from.right <= panel.left + 1) [left, right] = [0, w - fw]
|
|
54
|
+
else if (from.left >= panel.right - 1) [left, right] = [w - fw, 0]
|
|
55
|
+
// Never less than a sliver, so the shape always has somewhere to grow from.
|
|
56
|
+
if (w - left - right < 2) right = Math.max(0, w - left - 2)
|
|
57
|
+
if (h - top - bottom < 2) bottom = Math.max(0, h - top - 2)
|
|
58
|
+
return `inset(${top}px ${right}px ${bottom}px ${left}px round ${radius})`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The phone layout of Dialog and AlertDialog, as their CSS sets it.
|
|
62
|
+
const SHEET = '(max-width: 520px)'
|
|
63
|
+
|
|
64
|
+
const live = (run: Animation | null) => run?.playState === 'running' || run?.playState === 'paused'
|
|
65
|
+
|
|
66
|
+
// Grows the panel out of `found` (or folds it back) from wherever the last run left it.
|
|
67
|
+
function clipMorph(p: HTMLElement, found: HTMLElement | DOMRect, state: 'open' | 'closed', last: Animation | null) {
|
|
68
|
+
const opener = found instanceof HTMLElement ? found : null
|
|
69
|
+
const from = found instanceof HTMLElement ? found.getBoundingClientRect() : found
|
|
70
|
+
const now = live(last) ? getComputedStyle(p).clipPath : null
|
|
71
|
+
last?.cancel()
|
|
72
|
+
// Set before measuring, so the part's CSS enter animation is not caught mid-scale.
|
|
73
|
+
p.dataset.liquid = ''
|
|
74
|
+
// Never rounder than half the opener's height: a pill's 999px corner would keep a tall panel a
|
|
75
|
+
// capsule for most of the growth.
|
|
76
|
+
const cap = Math.min(from.width, from.height) / 2
|
|
77
|
+
const radius = `${Math.min(cap, opener ? parseFloat(getComputedStyle(opener).borderRadius) || 0 : cap)}px`
|
|
78
|
+
const start = startShape(p.getBoundingClientRect(), from, radius)
|
|
79
|
+
const room = shadowReach(p)
|
|
80
|
+
const corner = getComputedStyle(p).borderRadius || '0px'
|
|
81
|
+
const end = `inset(${-room}px round calc(${corner} + ${room}px))`
|
|
82
|
+
// data-liquid stays set while the panel is open: taking it off would restart the part's CSS enter animation.
|
|
83
|
+
if (state === 'open') return p.animate({ clipPath: [now ?? start, end] }, { duration: motionMs('morph'), easing: easing('morph') })
|
|
84
|
+
// A close starts at the panel's own edge, not out past its shadow, so the edge moves on the first frame.
|
|
85
|
+
// It also fades by 65% of the fold: when the opener sits outside the panel, the shrinking clip would
|
|
86
|
+
// otherwise leave a strip of the panel on its near edge until the very end.
|
|
87
|
+
return p.animate(
|
|
88
|
+
[
|
|
89
|
+
{ clipPath: now ?? `inset(0px round ${corner})`, opacity: 1 },
|
|
90
|
+
{ opacity: 1, offset: 0.2 },
|
|
91
|
+
{ opacity: 0, offset: 0.65 },
|
|
92
|
+
{ clipPath: start, opacity: 0 },
|
|
93
|
+
],
|
|
94
|
+
{ duration: motionMs('morph-out'), easing: easing('morph'), fill: 'forwards' },
|
|
95
|
+
)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Plays the growth when `play('open')` is called (once the panel is in its place) and the fold on
|
|
100
|
+
* `play('closed')`. Marks the panel with data-liquid while it runs, so the part's CSS can stand its own
|
|
101
|
+
* enter and exit animation down. Keep the panel in the page for --gooee-motion-morph-out after a close,
|
|
102
|
+
* so the fold lands as it goes. The origin is read fresh each time.
|
|
103
|
+
*/
|
|
104
|
+
export function createLiquid(panel: El, origin: LiquidOrigin) {
|
|
105
|
+
let run: Animation | null = null
|
|
106
|
+
return {
|
|
107
|
+
play(state: 'open' | 'closed') {
|
|
108
|
+
const p = get(panel)
|
|
109
|
+
if (!p || prefersReducedMotion() || !able()) return
|
|
110
|
+
const found = typeof origin === 'function' ? origin() : origin
|
|
111
|
+
if (!found) return
|
|
112
|
+
run = clipMorph(p, found, state, run)
|
|
113
|
+
},
|
|
114
|
+
destroy: () => run?.cancel(),
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A centred dialog grows out of the control that opened it (the one focus goes back to) and folds back
|
|
120
|
+
* into it. Opened from code with no such control, it grows from the middle of the screen. On a phone
|
|
121
|
+
* the dialog is a bottom sheet: it grows out of a control it covers, as one in the thumb zone is, and
|
|
122
|
+
* otherwise rises from the bottom edge. A sheet the hand drags away (data-fluid) is carried by the drag.
|
|
123
|
+
* Call `opening` as it starts to open, before focus moves into it; then `play` once it is in the page.
|
|
124
|
+
*/
|
|
125
|
+
export function createDialogMorph(panel: El) {
|
|
126
|
+
let opener: HTMLElement | null = null
|
|
127
|
+
let run: Animation | null = null
|
|
128
|
+
let rise = false
|
|
129
|
+
return {
|
|
130
|
+
opening() {
|
|
131
|
+
opener = returnTarget()
|
|
132
|
+
},
|
|
133
|
+
play(state: 'open' | 'closed') {
|
|
134
|
+
const p = get(panel)
|
|
135
|
+
if (!p || prefersReducedMotion() || !able()) return
|
|
136
|
+
const el = opener
|
|
137
|
+
const box = el && el !== document.body && el.isConnected ? el.getBoundingClientRect() : null
|
|
138
|
+
const found = el && box && box.width > 0 && box.height > 0 ? el : null
|
|
139
|
+
if (state === 'open' && !live(run)) {
|
|
140
|
+
const r = p.getBoundingClientRect()
|
|
141
|
+
rise = window.matchMedia(SHEET).matches && !(found && box && box.top >= r.top && box.bottom <= r.bottom + 1)
|
|
142
|
+
}
|
|
143
|
+
if (state === 'closed' && 'fluid' in p.dataset) return
|
|
144
|
+
if (!rise) {
|
|
145
|
+
run = clipMorph(p, found ?? new DOMRect(window.innerWidth / 2 - 1, window.innerHeight / 2 - 1, 2, 2), state, run)
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
const now = live(run) ? getComputedStyle(p).transform : null
|
|
149
|
+
run?.cancel()
|
|
150
|
+
p.dataset.liquid = ''
|
|
151
|
+
const down = 'translateY(100%)'
|
|
152
|
+
run =
|
|
153
|
+
state === 'open'
|
|
154
|
+
? p.animate({ transform: [now ?? down, 'none'] }, { duration: motionMs('morph'), easing: easing('morph') })
|
|
155
|
+
: p.animate({ transform: [now ?? 'none', down] }, { duration: motionMs('morph-out'), easing: easing('morph'), fill: 'forwards' })
|
|
156
|
+
},
|
|
157
|
+
destroy: () => run?.cancel(),
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A highlight's place in its row: its start edge (left, or top on the y axis), its length, and (for rows that wrap) its top. */
|
|
162
|
+
export type StretchBox = { x: number; w: number; y?: number }
|
|
163
|
+
|
|
164
|
+
// The leading edge moves over this share of the time; the trailing edge starts the rest of the way in.
|
|
165
|
+
const LEAD = 0.75
|
|
166
|
+
const runs = new WeakMap<HTMLElement, Animation>()
|
|
167
|
+
|
|
168
|
+
// Where a stretch caught half way has the highlight now.
|
|
169
|
+
function placeNow(node: HTMLElement, axis: 'x' | 'y'): StretchBox {
|
|
170
|
+
const s = getComputedStyle(node)
|
|
171
|
+
const m = new DOMMatrixReadOnly(s.transform === 'none' ? undefined : s.transform)
|
|
172
|
+
return axis === 'x' ? { x: m.m41, w: parseFloat(s.width), y: m.m42 } : { x: m.m42, w: parseFloat(s.height) }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Moves a highlight with two edges: the one nearest the new place leaves first and the far one
|
|
177
|
+
* catches up, both on the morph curve, so it stretches toward the choice and settles there. A move
|
|
178
|
+
* caught half way turns from where it is. `place` turns a box into the highlight's transform.
|
|
179
|
+
*/
|
|
180
|
+
export function stretch(node: HTMLElement, from: StretchBox, to: StretchBox, place: (b: StretchBox) => string, axis: 'x' | 'y' = 'x') {
|
|
181
|
+
const last = runs.get(node) ?? null
|
|
182
|
+
const start = live(last) ? placeNow(node, axis) : from
|
|
183
|
+
last?.cancel()
|
|
184
|
+
const ms = motionMs('base')
|
|
185
|
+
if (!ms || prefersReducedMotion() || !able()) return
|
|
186
|
+
const size = axis === 'x' ? 'width' : 'height'
|
|
187
|
+
const ease = bezier(morphCurve())
|
|
188
|
+
const ahead = to.x + to.w / 2 >= start.x + start.w / 2
|
|
189
|
+
const frames: Keyframe[] = []
|
|
190
|
+
for (let i = 0; i <= 12; i++) {
|
|
191
|
+
const t = i / 12
|
|
192
|
+
const lead = ease(Math.min(1, t / LEAD))
|
|
193
|
+
const trail = ease(Math.max(0, (t - 1 + LEAD) / LEAD))
|
|
194
|
+
const a = start.x + (to.x - start.x) * (ahead ? trail : lead)
|
|
195
|
+
const b = start.x + start.w + (to.x + to.w - start.x - start.w) * (ahead ? lead : trail)
|
|
196
|
+
frames.push({ transform: place({ x: a, w: b - a, y: to.y }), [size]: `${b - a}px` })
|
|
197
|
+
}
|
|
198
|
+
node.dataset.liquid = ''
|
|
199
|
+
const run = node.animate(frames, { duration: ms })
|
|
200
|
+
runs.set(node, run)
|
|
201
|
+
// Only the latest stretch takes the mark off: a cancelled one settles later, mid-way through the next.
|
|
202
|
+
const done = () => {
|
|
203
|
+
if (runs.get(node) === run) delete node.dataset.liquid
|
|
204
|
+
}
|
|
205
|
+
run.finished.then(done, done)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Liquid highlight: when the choice changes, the highlight stretches toward it (see stretch). Call
|
|
210
|
+
* `update` with the highlight's box and the choice behind it whenever either may have changed; it runs
|
|
211
|
+
* only on a change of choice, and a resize simply follows. Along one row, or one column with axis 'y'.
|
|
212
|
+
*/
|
|
213
|
+
export function createStretch(el: El, place: (b: StretchBox) => string, axis: 'x' | 'y' = 'x') {
|
|
214
|
+
let last: { box: StretchBox; choice: unknown } | null = null
|
|
215
|
+
let moved: HTMLElement | null = null
|
|
216
|
+
return {
|
|
217
|
+
update(box: StretchBox | null, choice: unknown, ready: boolean) {
|
|
218
|
+
const node = get(el)
|
|
219
|
+
const prev = last
|
|
220
|
+
// A part often renders the new choice before it has measured its new place, so only a moved box
|
|
221
|
+
// counts; it then stretches if the choice behind it changed, and simply follows a resize.
|
|
222
|
+
// No highlight (nothing chosen): forget the old place, so the next one appears rather than stretching from it.
|
|
223
|
+
if (!box) {
|
|
224
|
+
last = null
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
if (prev && prev.box.x === box.x && prev.box.w === box.w && prev.box.y === box.y) return
|
|
228
|
+
last = { box, choice }
|
|
229
|
+
if (!node || !prev || !ready) return
|
|
230
|
+
if (prev.choice === choice || (prev.box.y ?? 0) !== (box.y ?? 0)) {
|
|
231
|
+
runs.get(node)?.cancel()
|
|
232
|
+
return
|
|
233
|
+
}
|
|
234
|
+
moved = node
|
|
235
|
+
stretch(node, prev.box, box, place, axis)
|
|
236
|
+
},
|
|
237
|
+
destroy() {
|
|
238
|
+
if (moved) runs.get(moved)?.cancel()
|
|
239
|
+
},
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { bezier } from '../feel'
|
|
2
|
+
import { body, BEND, boxPath, flowScene, loopsPath, pincher, trace, type Box } from '../liquidPath'
|
|
3
|
+
import { morphCurve, motionMs, prefersReducedMotion, type MotionToken } from '../motion'
|
|
4
|
+
|
|
5
|
+
// The page side of liquid matter (the maths is in liquidPath.ts): an SVG layer that exists only while a
|
|
6
|
+
// part moves, a frame loop, and the flowing highlight Tabs and SegmentedControl share.
|
|
7
|
+
|
|
8
|
+
const NS = 'http://www.w3.org/2000/svg'
|
|
9
|
+
|
|
10
|
+
export const morphEase = () => bezier(morphCurve())
|
|
11
|
+
|
|
12
|
+
/** A duration token in ms, or 0 when motion is reduced. */
|
|
13
|
+
export const motionFor = (token: MotionToken) => (prefersReducedMotion() ? 0 : motionMs(token))
|
|
14
|
+
|
|
15
|
+
type Shadow = { x: number; y: number; blur: number; colour: string }
|
|
16
|
+
|
|
17
|
+
/** An element's outer box shadows. A shadow that is only a spread (a 1px ring) comes back as `ring`, to draw as a stroke. */
|
|
18
|
+
export function shadowOf(el: Element) {
|
|
19
|
+
const shadows: Shadow[] = []
|
|
20
|
+
let ring: { colour: string; width: number } | null = null
|
|
21
|
+
for (const part of getComputedStyle(el).boxShadow.split(/,(?![^(]*\))/)) {
|
|
22
|
+
if (part.trim() === 'none' || part.includes('inset')) continue
|
|
23
|
+
const colour = part.match(/rgba?\([^)]*\)|#[\da-f]+/i)?.[0] ?? 'currentColor'
|
|
24
|
+
const [x = 0, y = 0, blur = 0, spread = 0] = (part.replace(colour, '').match(/-?[\d.]+px/g) ?? []).map(parseFloat)
|
|
25
|
+
if (spread > 0 && !x && !y && !blur) ring = { colour, width: spread }
|
|
26
|
+
else shadows.push({ x, y, blur, colour })
|
|
27
|
+
}
|
|
28
|
+
return { shadows, ring }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let filterId = 0
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Casts `shadows` from the layer's paths the way box-shadow does: each one blurred from the shape on its
|
|
35
|
+
* own, then merged. A chain of CSS drop-shadows would shadow the shadows too, so the drawing would come out
|
|
36
|
+
* darker than the part it stands in for and jump at the hand-over.
|
|
37
|
+
*/
|
|
38
|
+
export function castShadow(svg: SVGSVGElement, shadows: Shadow[]) {
|
|
39
|
+
if (!shadows.length) return
|
|
40
|
+
const el = (tag: string, attrs: Record<string, string | number>, parent: Element) => {
|
|
41
|
+
const node = parent.appendChild(document.createElementNS(NS, tag))
|
|
42
|
+
for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, String(v))
|
|
43
|
+
return node
|
|
44
|
+
}
|
|
45
|
+
const { width, height } = svg.getBoundingClientRect()
|
|
46
|
+
const m = Math.max(...shadows.map((s) => Math.max(Math.abs(s.x), Math.abs(s.y)) + s.blur * 1.5)) + 2
|
|
47
|
+
const id = `gooee-shadow-${++filterId}`
|
|
48
|
+
const filter = el('filter', { id, filterUnits: 'userSpaceOnUse', x: -m, y: -m, width: width + m * 2, height: height + m * 2, 'color-interpolation-filters': 'sRGB' }, el('defs', {}, svg))
|
|
49
|
+
shadows.forEach((s, i) => {
|
|
50
|
+
el('feGaussianBlur', { in: 'SourceAlpha', stdDeviation: s.blur / 2 }, filter)
|
|
51
|
+
el('feOffset', { dx: s.x, dy: s.y, result: `b${i}` }, filter)
|
|
52
|
+
el('feFlood', { 'flood-color': s.colour }, filter)
|
|
53
|
+
el('feComposite', { in2: `b${i}`, operator: 'in', result: `s${i}` }, filter)
|
|
54
|
+
})
|
|
55
|
+
// box-shadow paints its first shadow on top, so they merge last to first, under the shape.
|
|
56
|
+
const merge = el('feMerge', {}, filter)
|
|
57
|
+
for (let i = shadows.length - 1; i >= 0; i--) el('feMergeNode', { in: `s${i}` }, merge)
|
|
58
|
+
el('feMergeNode', { in: 'SourceGraphic' }, merge)
|
|
59
|
+
const g = el('g', { filter: `url(#${id})` }, svg)
|
|
60
|
+
for (const path of Array.from(svg.querySelectorAll(':scope > path'))) g.appendChild(path)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** An SVG in `host`, before `before`, with `count` paths. It is marked data-gooee-liquid. */
|
|
64
|
+
export function layer(host: Element, className: string, before: Node | null, count = 1) {
|
|
65
|
+
const svg = document.createElementNS(NS, 'svg')
|
|
66
|
+
svg.setAttribute('class', className)
|
|
67
|
+
svg.setAttribute('aria-hidden', 'true')
|
|
68
|
+
svg.setAttribute('data-gooee-liquid', '')
|
|
69
|
+
const paths = Array.from({ length: count }, () => svg.appendChild(document.createElementNS(NS, 'path')))
|
|
70
|
+
host.insertBefore(svg, before)
|
|
71
|
+
return { svg, paths }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Draws frame 0 now (so the part's new CSS state never shows first), then one per frame over `ms`
|
|
76
|
+
* with progress 0 to 1, then calls `done`. Returns a stop.
|
|
77
|
+
*/
|
|
78
|
+
export function frames(ms: number, draw: (u: number, now: number) => void, done: () => void) {
|
|
79
|
+
const t0 = performance.now()
|
|
80
|
+
draw(0, t0)
|
|
81
|
+
let id = 0
|
|
82
|
+
const tick = (now: number) => {
|
|
83
|
+
const u = Math.min(1, Math.max(0, (now - t0) / ms))
|
|
84
|
+
draw(u, now)
|
|
85
|
+
if (u >= 1) done()
|
|
86
|
+
else id = requestAnimationFrame(tick)
|
|
87
|
+
}
|
|
88
|
+
id = requestAnimationFrame(tick)
|
|
89
|
+
return () => cancelAnimationFrame(id)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** A highlight's place in its row: its start edge and its width. */
|
|
93
|
+
export type Place = { x: number; w: number }
|
|
94
|
+
|
|
95
|
+
type Flow = { front: Box; rest: Box; stop: () => void; svg: SVGSVGElement; pin: ReturnType<typeof pincher> }
|
|
96
|
+
|
|
97
|
+
export type FlowOptions = {
|
|
98
|
+
/** The liquid layer's class. */
|
|
99
|
+
cls: string
|
|
100
|
+
/** A thin underline, which only splits and joins. */
|
|
101
|
+
line?: boolean
|
|
102
|
+
/** Gets the drawn outline each frame (null at the end), for text that changes colour under the liquid. */
|
|
103
|
+
ink?: (outline: string | null) => void
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type El = HTMLElement | (() => HTMLElement | null)
|
|
107
|
+
const get = (t: El) => (typeof t === 'function' ? t() : t)
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Flow: when the choice changes, the highlight `mark` runs to the new place on a neck that thins and
|
|
111
|
+
* breaks, and what is left drains after it and joins by 60% of the move (liquidPath flowScene). While
|
|
112
|
+
* it moves the mark is hidden and an SVG in `host` draws it; at rest the mark is back, exact. A flow
|
|
113
|
+
* caught half way starts from the shape on screen. Call `update` whenever the choice or its place
|
|
114
|
+
* changes, and `destroy` when the part goes.
|
|
115
|
+
*/
|
|
116
|
+
export function createFlow(host: El, mark: El, { cls, line = false, ink }: FlowOptions) {
|
|
117
|
+
let last: { place: Place; choice: unknown } | null = null
|
|
118
|
+
let run: Flow | null = null
|
|
119
|
+
const end = () => {
|
|
120
|
+
const f = run
|
|
121
|
+
if (!f) return
|
|
122
|
+
f.stop()
|
|
123
|
+
f.svg.remove()
|
|
124
|
+
run = null
|
|
125
|
+
const m = get(mark), h = get(host)
|
|
126
|
+
if (m) delete m.dataset.flowing
|
|
127
|
+
if (h) delete h.dataset.flowing
|
|
128
|
+
ink?.(null)
|
|
129
|
+
}
|
|
130
|
+
const update = (place: Place | null, choice: unknown, ready: boolean) => {
|
|
131
|
+
const root = get(host)
|
|
132
|
+
const m = get(mark)
|
|
133
|
+
const prev = last
|
|
134
|
+
// A new choice arrives before its place is measured: wait for the place.
|
|
135
|
+
if (!place || (prev && prev.place.x === place.x && prev.place.w === place.w)) return
|
|
136
|
+
last = { place, choice }
|
|
137
|
+
if (!root || !m || !prev || !ready || prev.choice === choice) {
|
|
138
|
+
end()
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
const ms = motionFor('morph-out')
|
|
142
|
+
if (!ms) {
|
|
143
|
+
end()
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
const hh = m.offsetHeight / 2
|
|
147
|
+
const cy = m.offsetTop + hh
|
|
148
|
+
const r = Math.min(hh, parseFloat(getComputedStyle(m).borderTopLeftRadius) || 0)
|
|
149
|
+
const boxOf = (p: Place): Box => ({ cx: p.x + p.w / 2, cy, hw: p.w / 2, hh, r })
|
|
150
|
+
const to = boxOf(place)
|
|
151
|
+
const from = run ?? { front: boxOf(prev.place), rest: boxOf(prev.place) }
|
|
152
|
+
const e = morphEase()
|
|
153
|
+
let f = run
|
|
154
|
+
if (f) f.stop()
|
|
155
|
+
else {
|
|
156
|
+
const { svg, paths } = layer(root, cls, m.nextSibling)
|
|
157
|
+
const look = getComputedStyle(m)
|
|
158
|
+
const { shadows, ring } = shadowOf(m)
|
|
159
|
+
paths[0].style.fill = look.backgroundColor
|
|
160
|
+
if (ring && !line) {
|
|
161
|
+
paths[0].style.stroke = ring.colour
|
|
162
|
+
paths[0].style.strokeWidth = `${ring.width * 2}px`
|
|
163
|
+
paths[0].style.paintOrder = 'stroke'
|
|
164
|
+
}
|
|
165
|
+
castShadow(svg, shadows)
|
|
166
|
+
f = { front: from.front, rest: from.rest, stop: () => {}, svg, pin: pincher(e, motionFor('fast')) }
|
|
167
|
+
run = f
|
|
168
|
+
m.dataset.flowing = ''
|
|
169
|
+
root.dataset.flowing = ''
|
|
170
|
+
}
|
|
171
|
+
const flow = f
|
|
172
|
+
const path = flow.svg.querySelector('path') as SVGPathElement
|
|
173
|
+
const lift = Math.max(BEND + 0.5, hh / 2)
|
|
174
|
+
const settle = Math.max(BEND + 0.5, hh / 3)
|
|
175
|
+
const start = { front: from.front, rest: from.rest }
|
|
176
|
+
const draw = (u: number, now: number) => {
|
|
177
|
+
const s = line ? flowScene(e, u, start.front, start.rest, to, 0, [BEND, hh], [hh, hh]) : flowScene(e, u, start.front, start.rest, to, hh / 6, [lift, lift], [settle, settle])
|
|
178
|
+
flow.front = s.front
|
|
179
|
+
flow.rest = s.rest
|
|
180
|
+
let d: string
|
|
181
|
+
if (line) {
|
|
182
|
+
const a = s.front
|
|
183
|
+
const b = s.rest
|
|
184
|
+
// Two lines of one thickness on one row: one where they overlap, two apart.
|
|
185
|
+
const lo = Math.min(a.cx - a.hw, b.cx - b.hw)
|
|
186
|
+
const hi = Math.max(a.cx + a.hw, b.cx + b.hw)
|
|
187
|
+
d = Math.abs(a.cx - b.cx) <= a.hw + b.hw ? boxPath({ cx: (lo + hi) / 2, cy, hw: (hi - lo) / 2, hh, r: hh }) : boxPath(a) + boxPath(b)
|
|
188
|
+
} else {
|
|
189
|
+
const p = flow.pin(body(s.front), body(s.rest), now)
|
|
190
|
+
d = loopsPath(trace(p.sdf, [[s.front.cx, cy, 0, -1], [s.rest.cx, cy, 0, -1]]))
|
|
191
|
+
}
|
|
192
|
+
path.setAttribute('d', d)
|
|
193
|
+
ink?.(d)
|
|
194
|
+
}
|
|
195
|
+
flow.stop = frames(ms, draw, end)
|
|
196
|
+
}
|
|
197
|
+
return { update, destroy: end }
|
|
198
|
+
}
|