gooee 0.48.0 → 0.51.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.
Files changed (185) hide show
  1. package/package.json +4 -2
  2. package/scripts/add.js +28 -6
  3. package/src/components/Accordion/Accordion.vue +62 -0
  4. package/src/components/Accordion/AccordionItem.vue +45 -0
  5. package/src/components/Accordion/accordionContext.ts +6 -0
  6. package/src/components/Alert/Alert.tsx +7 -27
  7. package/src/components/Alert/Alert.vue +59 -0
  8. package/src/components/AlertDialog/AlertDialog.vue +126 -0
  9. package/src/components/AnimatedNumber/AnimatedNumber.vue +36 -0
  10. package/src/components/AspectRatio/AspectRatio.vue +17 -0
  11. package/src/components/Avatar/Avatar.vue +56 -0
  12. package/src/components/AvatarGroup/AvatarGroup.vue +42 -0
  13. package/src/components/Badge/Badge.vue +32 -0
  14. package/src/components/Breadcrumb/Breadcrumb.vue +58 -0
  15. package/src/components/Button/Button.vue +130 -0
  16. package/src/components/ButtonGroup/ButtonGroup.tsx +4 -21
  17. package/src/components/ButtonGroup/ButtonGroup.vue +33 -0
  18. package/src/components/Card/Card.vue +34 -0
  19. package/src/components/Center/Center.vue +32 -0
  20. package/src/components/Checkbox/Checkbox.tsx +8 -25
  21. package/src/components/Checkbox/Checkbox.vue +108 -0
  22. package/src/components/CheckboxGroup/CheckboxGroup.vue +76 -0
  23. package/src/components/Cluster/Cluster.vue +34 -0
  24. package/src/components/CodeBlock/CodeBlock.vue +45 -0
  25. package/src/components/Collapsible/Collapsible.vue +59 -0
  26. package/src/components/Container/Container.vue +22 -0
  27. package/src/components/CopyButton/CopyButton.tsx +3 -49
  28. package/src/components/CopyButton/CopyButton.vue +116 -0
  29. package/src/components/Dial/Dial.tsx +12 -120
  30. package/src/components/Dial/Dial.vue +228 -0
  31. package/src/components/Dialog/Dialog.vue +139 -0
  32. package/src/components/Divider/Divider.vue +27 -0
  33. package/src/components/DropdownMenu/DropdownMenu.tsx +11 -46
  34. package/src/components/DropdownMenu/DropdownMenu.vue +185 -0
  35. package/src/components/EmptyState/EmptyState.vue +33 -0
  36. package/src/components/Fab/Fab.tsx +4 -14
  37. package/src/components/Fab/Fab.vue +115 -0
  38. package/src/components/Fieldset/Fieldset.vue +42 -0
  39. package/src/components/FormField/FormField.tsx +2 -17
  40. package/src/components/FormField/FormField.vue +64 -0
  41. package/src/components/Grid/Grid.vue +43 -0
  42. package/src/components/HoldToConfirm/HoldToConfirm.tsx +13 -142
  43. package/src/components/HoldToConfirm/HoldToConfirm.vue +281 -0
  44. package/src/components/IconButton/IconButton.vue +25 -0
  45. package/src/components/Input/Input.vue +112 -0
  46. package/src/components/InputGroup/InputGroup.vue +102 -0
  47. package/src/components/Kbd/Kbd.tsx +2 -12
  48. package/src/components/Kbd/Kbd.vue +21 -0
  49. package/src/components/Link/Link.vue +38 -0
  50. package/src/components/LivePill/LivePill.tsx +12 -40
  51. package/src/components/LivePill/LivePill.vue +152 -0
  52. package/src/components/Meter/Meter.vue +88 -0
  53. package/src/components/MorphButton/MorphButton.tsx +11 -67
  54. package/src/components/MorphButton/MorphButton.vue +120 -0
  55. package/src/components/NumberInput/NumberInput.tsx +11 -48
  56. package/src/components/NumberInput/NumberInput.vue +184 -0
  57. package/src/components/Pagination/Pagination.tsx +2 -15
  58. package/src/components/Pagination/Pagination.vue +87 -0
  59. package/src/components/Pagination/range.ts +15 -0
  60. package/src/components/PasswordInput/PasswordInput.vue +53 -0
  61. package/src/components/PickerWheel/DateWheel.vue +48 -0
  62. package/src/components/PickerWheel/PickerWheel.tsx +15 -129
  63. package/src/components/PickerWheel/PickerWheel.vue +77 -0
  64. package/src/components/PickerWheel/TimeWheel.vue +50 -0
  65. package/src/components/PickerWheel/WheelColumn.vue +70 -0
  66. package/src/components/Popover/Popover.vue +108 -0
  67. package/src/components/ProgressBar/ProgressBar.vue +48 -0
  68. package/src/components/Prose/Prose.vue +18 -0
  69. package/src/components/Radio/Radio.vue +49 -0
  70. package/src/components/Radio/RadioGroup.vue +69 -0
  71. package/src/components/Retime/Retime.tsx +7 -40
  72. package/src/components/Retime/Retime.vue +64 -0
  73. package/src/components/RulerScrubber/RulerScrubber.tsx +9 -38
  74. package/src/components/RulerScrubber/RulerScrubber.vue +166 -0
  75. package/src/components/ScrollArea/ScrollArea.tsx +17 -129
  76. package/src/components/ScrollArea/ScrollArea.vue +58 -0
  77. package/src/components/SearchInput/SearchInput.tsx +2 -15
  78. package/src/components/SearchInput/SearchInput.vue +70 -0
  79. package/src/components/SegmentedControl/SegmentedControl.tsx +7 -51
  80. package/src/components/SegmentedControl/SegmentedControl.vue +111 -0
  81. package/src/components/Select/Select.tsx +16 -47
  82. package/src/components/Select/Select.vue +236 -0
  83. package/src/components/Sheet/Sheet.tsx +52 -231
  84. package/src/components/Sheet/Sheet.vue +249 -0
  85. package/src/components/Skeleton/Skeleton.vue +38 -0
  86. package/src/components/Slider/Slider.tsx +25 -84
  87. package/src/components/Slider/Slider.vue +113 -0
  88. package/src/components/Spinner/Spinner.vue +30 -0
  89. package/src/components/Split/Split.vue +34 -0
  90. package/src/components/SplitFlap/SplitFlap.tsx +11 -175
  91. package/src/components/SplitFlap/SplitFlap.vue +52 -0
  92. package/src/components/Stack/Stack.vue +22 -0
  93. package/src/components/SwipeDeck/SwipeDeck.tsx +30 -194
  94. package/src/components/SwipeDeck/SwipeDeck.vue +168 -0
  95. package/src/components/Switch/Switch.tsx +6 -75
  96. package/src/components/Switch/Switch.vue +66 -0
  97. package/src/components/Table/Table.module.css +12 -3
  98. package/src/components/Table/Table.tsx +8 -59
  99. package/src/components/Table/Table.vue +274 -0
  100. package/src/components/TableOfContents/TableOfContents.vue +90 -0
  101. package/src/components/Tabs/Tab.vue +37 -0
  102. package/src/components/Tabs/TabList.vue +47 -0
  103. package/src/components/Tabs/TabPanel.vue +26 -0
  104. package/src/components/Tabs/Tabs.module.css +2 -2
  105. package/src/components/Tabs/Tabs.tsx +11 -84
  106. package/src/components/Tabs/Tabs.vue +33 -0
  107. package/src/components/Tabs/tabsContext.ts +15 -0
  108. package/src/components/Tag/Tag.tsx +6 -26
  109. package/src/components/Tag/Tag.vue +63 -0
  110. package/src/components/Textarea/Textarea.tsx +2 -22
  111. package/src/components/Textarea/Textarea.vue +120 -0
  112. package/src/components/ThemeToggle/ThemeToggle.tsx +10 -84
  113. package/src/components/ThemeToggle/ThemeToggle.vue +90 -0
  114. package/src/components/Toast/Toast.tsx +34 -264
  115. package/src/components/Toast/Toast.vue +138 -0
  116. package/src/components/Toast/ToastItem.vue +108 -0
  117. package/src/components/Toggle/Toggle.vue +52 -0
  118. package/src/components/Tooltip/Tooltip.tsx +17 -48
  119. package/src/components/Tooltip/Tooltip.vue +95 -0
  120. package/src/components/VisuallyHidden/VisuallyHidden.vue +17 -0
  121. package/src/internal/FieldMessage.vue +41 -0
  122. package/src/internal/Roll.vue +20 -0
  123. package/src/internal/fling.ts +29 -106
  124. package/src/internal/focus.ts +4 -79
  125. package/src/internal/icons.module.css +39 -27
  126. package/src/internal/layers.ts +7 -61
  127. package/src/internal/liquid.ts +26 -213
  128. package/src/internal/liquidMatter.ts +9 -181
  129. package/src/internal/liquidMore.ts +6 -669
  130. package/src/internal/motion/alert.ts +17 -0
  131. package/src/internal/motion/buttonGroup.ts +21 -0
  132. package/src/internal/motion/checkbox.ts +39 -0
  133. package/src/internal/motion/collapseOut.ts +26 -0
  134. package/src/internal/motion/copyButton.ts +48 -0
  135. package/src/internal/motion/dial.ts +137 -0
  136. package/src/internal/motion/fab.ts +14 -0
  137. package/src/internal/motion/fling.ts +147 -0
  138. package/src/internal/motion/floating.ts +58 -0
  139. package/src/internal/motion/focus.ts +88 -0
  140. package/src/internal/motion/formField.ts +19 -0
  141. package/src/internal/motion/holdToConfirm.ts +147 -0
  142. package/src/internal/motion/index.ts +20 -0
  143. package/src/internal/motion/keys.ts +42 -0
  144. package/src/internal/motion/layers.ts +78 -0
  145. package/src/internal/motion/liquid.ts +241 -0
  146. package/src/internal/motion/liquidMatter.ts +198 -0
  147. package/src/internal/motion/liquidMore.ts +676 -0
  148. package/src/internal/motion/listbox.ts +69 -0
  149. package/src/internal/motion/livePill.ts +71 -0
  150. package/src/internal/motion/menuKeys.ts +58 -0
  151. package/src/internal/motion/morphButton.ts +71 -0
  152. package/src/internal/motion/numberInput.ts +57 -0
  153. package/src/internal/motion/pickerWheel.ts +166 -0
  154. package/src/internal/motion/retime.ts +45 -0
  155. package/src/internal/motion/ruler.ts +57 -0
  156. package/src/internal/motion/scrollArea.ts +133 -0
  157. package/src/internal/motion/scrollFrame.ts +152 -0
  158. package/src/internal/motion/scrubLook.ts +15 -0
  159. package/src/internal/motion/scrubber.ts +154 -0
  160. package/src/internal/motion/segmented.ts +63 -0
  161. package/src/internal/motion/sheetDetents.ts +271 -0
  162. package/src/internal/motion/slider.ts +108 -0
  163. package/src/internal/motion/softPress.ts +334 -0
  164. package/src/internal/motion/splitFlap.ts +205 -0
  165. package/src/internal/motion/swipeDeck.ts +236 -0
  166. package/src/internal/motion/switchThumb.ts +83 -0
  167. package/src/internal/motion/table.ts +77 -0
  168. package/src/internal/motion/tabs.ts +105 -0
  169. package/src/internal/motion/textarea.ts +22 -0
  170. package/src/internal/motion/themeIcon.ts +91 -0
  171. package/src/internal/motion/themeReveal.ts +71 -0
  172. package/src/internal/motion/toast.ts +291 -0
  173. package/src/internal/motion/tooltip.ts +58 -0
  174. package/src/internal/scrollFrame.ts +4 -145
  175. package/src/internal/softPress.ts +27 -289
  176. package/src/internal/themeReveal.ts +3 -61
  177. package/src/internal/useFloating.ts +9 -49
  178. package/src/internal/useScrub.ts +15 -120
  179. package/src/internal/vue/trigger.ts +18 -0
  180. package/src/internal/vue/useFloating.ts +38 -0
  181. package/src/internal/vue/usePresence.ts +21 -0
  182. package/src/internal/vue/useScrub.ts +40 -0
  183. package/src/internal/vueIcons.ts +134 -0
  184. package/src/tokens.css +5 -0
  185. package/src/internal/relativeTime.ts +0 -26
@@ -0,0 +1,147 @@
1
+ import { bezier } from '../feel'
2
+ import { body, boxPath, lerp, loopsPath, pincher, seg, trace, type Box } from '../liquidPath'
3
+ import { morphCurve, readMotionMs } from '../motion'
4
+ import { frames, layer, morphEase, motionFor } from './liquidMatter'
5
+
6
+ // The hold to confirm button's motion: the burning line on its edge and the cancel drop that buds out of it.
7
+
8
+ // A press shorter than this is a tap: it opens the confirm step, like one key press does.
9
+ export const TAP = 250
10
+ // Held this long, the hint changes to "Keep holding".
11
+ export const HINT_AFTER = 300
12
+ // A finger that slides this far off the button lets go.
13
+ export const LEAVE = 16
14
+ // How long the done state shows before the button can be used again.
15
+ export const DONE_FOR = 2400
16
+ // A click this soon after the step opens is the rest of a double-click, not a choice.
17
+ export const GUARD = 500
18
+
19
+ /**
20
+ * The cancel drop buds out of the button's right edge, its neck stretches and breaks, and it grows into
21
+ * the round cancel button (`in`), or flows back into the button (`out`). The button keeps its own look:
22
+ * the drawing is cut out where it is. `cls` is the drawing's class. Returns a stop, or null when motion is reduced.
23
+ */
24
+ export function bud(row: HTMLElement, shell: HTMLElement, x: HTMLElement, way: 'in' | 'out', cls: string) {
25
+ // 400ms both ways: the drop is small, and at the morph's 600ms the cancel button felt late to arrive.
26
+ const ms = motionFor('reveal')
27
+ if (!ms) return null
28
+ const box = (el: HTMLElement): Box => {
29
+ const r = el.getBoundingClientRect(),
30
+ o = row.getBoundingClientRect()
31
+ return { cx: r.left - o.left + r.width / 2, cy: r.top - o.top + r.height / 2, hw: r.width / 2, hh: r.height / 2, r: r.height / 2 }
32
+ }
33
+ const O = box(shell)
34
+ const look = getComputedStyle(x)
35
+ const line = parseFloat(look.getPropertyValue('--gooee-line-thick')) || 1.5
36
+ const T = box(x)
37
+ const T2: Box = { ...T, hw: T.hw - line / 2, hh: T.hh - line / 2, r: T.r - line / 2 }
38
+ const { svg, paths } = layer(row, cls, null)
39
+ const path = paths[0]
40
+ path.style.fill = look.backgroundColor
41
+ path.style.stroke = look.getPropertyValue('--gooee-color-border-strong')
42
+ path.style.strokeWidth = `${line}px`
43
+ const clip = svg.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'clipPath'))
44
+ clip.id = `gooee-hold-${Math.random().toString(36).slice(2)}`
45
+ const hole = clip.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'path'))
46
+ hole.setAttribute('clip-rule', 'evenodd')
47
+ hole.setAttribute('d', `M-4000 -4000H4000V4000H-4000Z${boxPath({ ...O, hw: O.hw + 0.5, hh: O.hh + 0.5, r: O.r + 0.5 })}`)
48
+ path.setAttribute('clip-path', `url(#${clip.id})`)
49
+ const e = morphEase()
50
+ const pin = pincher(e, motionFor('fast'))
51
+ const edge = O.cx + O.hw - O.hh
52
+ const r0 = O.hh * 0.45
53
+ x.style.opacity = '0'
54
+ const stop = frames(
55
+ ms,
56
+ (k, now) => {
57
+ const u = way === 'in' ? k : 1 - k
58
+ const f = e(u)
59
+ const r = lerp(r0, T2.hh, e(seg(u, 0.25, 1)))
60
+ const D: Box = { cx: lerp(O.cx + O.hw - r0, T2.cx, f), cy: O.cy, hw: r, hh: r, r }
61
+ const p = pin(body(O, [edge, O.cy]), body(D), now)
62
+ path.setAttribute(
63
+ 'd',
64
+ loopsPath(
65
+ trace(p.sdf, [
66
+ [edge, O.cy, 0, 1],
67
+ [D.cx, D.cy, 0, 1],
68
+ ]),
69
+ ),
70
+ )
71
+ },
72
+ () => {
73
+ svg.remove()
74
+ x.style.opacity = ''
75
+ },
76
+ )
77
+ return () => {
78
+ stop()
79
+ svg.remove()
80
+ x.style.opacity = ''
81
+ }
82
+ }
83
+
84
+ // The pill's outline as one closed path that starts on the bottom edge at x and runs left first. The
85
+ // line is drawn at both ends of the path at once, so it burns out both ways from x and meets opposite.
86
+ export function outline(w: number, h: number, inset: number, x: number) {
87
+ const r = h / 2 - inset
88
+ const t = inset
89
+ const b = h - inset
90
+ const l = h / 2
91
+ const rr = w - h / 2
92
+ const px = Math.max(l, Math.min(rr, x))
93
+ return `M${px},${b} H${l} A${r},${r} 0 0 1 ${l},${t} H${rr} A${r},${r} 0 0 1 ${rr},${b} Z`
94
+ }
95
+
96
+ export const cssMs = (el: Element | null, name: string, fallback: number) => {
97
+ const raw = el ? getComputedStyle(el).getPropertyValue(name).trim() : ''
98
+ const v = parseFloat(raw)
99
+ if (!Number.isFinite(v)) return fallback
100
+ return raw.endsWith('ms') ? v : raw.endsWith('s') ? v * 1000 : v
101
+ }
102
+
103
+ /**
104
+ * The burning line on the button's edge, drawn on `run` (a path with pathLength 1). `forward` burns at an
105
+ * even speed, since it is a clock, and calls `tick` each frame and `done` at the end. `rewind` runs back
106
+ * fast on the morph curve: a rubber band, not a clock.
107
+ */
108
+ export function createFuse(run: () => SVGPathElement | null) {
109
+ let p = 0
110
+ let raf = 0
111
+ const paint = (v: number) => {
112
+ p = v
113
+ const el = run()
114
+ if (!el) return
115
+ el.style.strokeDasharray = `${v / 2} ${1 - v} ${v / 2} 0`
116
+ el.style.opacity = v > 0 ? '1' : '0'
117
+ }
118
+ const stop = () => cancelAnimationFrame(raf)
119
+ const forward = (total: number, tick: (now: number) => void, done: () => void) => {
120
+ stop()
121
+ let last = performance.now()
122
+ const step = (now: number) => {
123
+ const next = Math.min(1, p + (now - last) / total)
124
+ last = now
125
+ paint(next)
126
+ tick(now)
127
+ if (next >= 1) return done()
128
+ raf = requestAnimationFrame(step)
129
+ }
130
+ raf = requestAnimationFrame(step)
131
+ }
132
+ const rewind = () => {
133
+ stop()
134
+ const from = p
135
+ const length = readMotionMs('fast')
136
+ if (!length || !from) return paint(0)
137
+ const ease = bezier(morphCurve())
138
+ const t0 = performance.now()
139
+ const step = (now: number) => {
140
+ const t = Math.min(1, (now - t0) / length)
141
+ paint(from * (1 - ease(t)))
142
+ if (t < 1) raf = requestAnimationFrame(step)
143
+ }
144
+ raf = requestAnimationFrame(step)
145
+ }
146
+ return { paint, forward, rewind, stop }
147
+ }
@@ -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,42 @@
1
+ // Page-wide key watchers shared by the React and Vue parts. Each returns a function that stops it.
2
+
3
+ // Calls down(true) while the key is held and down(false) when it is let go or the window loses focus.
4
+ export function holdKey(key: string, down: (held: boolean) => void) {
5
+ const match = (e: KeyboardEvent) => e.key.toLowerCase() === key.toLowerCase()
6
+ const onDown = (e: KeyboardEvent) => match(e) && down(true)
7
+ const onUp = (e: KeyboardEvent) => match(e) && down(false)
8
+ const reset = () => down(false)
9
+ window.addEventListener('keydown', onDown)
10
+ window.addEventListener('keyup', onUp)
11
+ window.addEventListener('blur', reset)
12
+ return () => {
13
+ window.removeEventListener('keydown', onDown)
14
+ window.removeEventListener('keyup', onUp)
15
+ window.removeEventListener('blur', reset)
16
+ }
17
+ }
18
+
19
+ const isTyping = (el: Element | null) =>
20
+ !!el && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement || (el as HTMLElement).isContentEditable)
21
+
22
+ // Pressing the key anywhere focuses and selects the field. Ignored while another field has focus, so it
23
+ // never steals typed text, and while a modal the field is not in is open, so focus never leaves the modal.
24
+ export function shortcutFocus(key: string, field: () => HTMLInputElement | null) {
25
+ const onKey = (e: KeyboardEvent) => {
26
+ if (e.key !== key || e.metaKey || e.ctrlKey || e.altKey || isTyping(document.activeElement)) return
27
+ const modals = document.querySelectorAll('[aria-modal="true"]')
28
+ if (modals.length && !modals[modals.length - 1].contains(field())) return
29
+ e.preventDefault()
30
+ field()?.focus()
31
+ field()?.select()
32
+ }
33
+ window.addEventListener('keydown', onKey)
34
+ return () => window.removeEventListener('keydown', onKey)
35
+ }
36
+
37
+ // A textarea grows with its text.
38
+ export function fitHeight(el: HTMLTextAreaElement | null) {
39
+ if (!el) return
40
+ el.style.height = 'auto'
41
+ el.style.height = `${el.scrollHeight}px`
42
+ }
@@ -0,0 +1,78 @@
1
+ // A stack of open layers, so Esc and outside clicks only close the top one.
2
+ const stack: Array<{ id: symbol; hint: boolean }> = []
3
+
4
+ export type DismissOptions = {
5
+ /** A press outside counts. On by default. */
6
+ outside?: boolean
7
+ /** A tooltip-like layer: it takes Esc first, but clicks pass to the layer below it. */
8
+ hint?: boolean
9
+ /** Focus moving outside it, while no layer is open above it, counts as outside too. */
10
+ focusOut?: boolean
11
+ }
12
+
13
+ /**
14
+ * Joins the layer stack until the returned function is called. Esc, and a press outside the elements
15
+ * `inside` returns (or focus leaving them, with focusOut), call `onDismiss` while this is the top layer.
16
+ */
17
+ export function dismissable(inside: () => Array<HTMLElement | null>, onDismiss: (reason: 'escape' | 'outside', event: Event) => void, { outside = true, hint = false, focusOut = false }: DismissOptions = {}) {
18
+ const id = Symbol('layer')
19
+ stack.push({ id, hint })
20
+ const isTop = () => stack[stack.length - 1]?.id === id
21
+ const isTopForPointer = () => stack.filter((l) => !l.hint).pop()?.id === id
22
+ const within = (target: Node) => inside().some((el) => el?.contains(target))
23
+
24
+ const onKey = (e: KeyboardEvent) => {
25
+ if (e.key === 'Escape' && isTop()) {
26
+ e.stopPropagation()
27
+ onDismiss('escape', e)
28
+ }
29
+ }
30
+ const onPointer = (e: PointerEvent) => {
31
+ if (!outside || !isTopForPointer()) return
32
+ const target = e.target as Node
33
+ if (within(target)) return
34
+ // Things like the toast stack sit above every layer and never count as outside.
35
+ if (target instanceof Element && target.closest('[data-gooee-layer-ignore]')) return
36
+ onDismiss('outside', e)
37
+ }
38
+ const onFocus = (e: FocusEvent) => {
39
+ if (!focusOut || !isTopForPointer()) return
40
+ if (within(e.target as Node)) return
41
+ onDismiss('outside', e)
42
+ }
43
+ document.addEventListener('keydown', onKey)
44
+ document.addEventListener('pointerdown', onPointer)
45
+ document.addEventListener('focusin', onFocus)
46
+ return () => {
47
+ document.removeEventListener('keydown', onKey)
48
+ document.removeEventListener('pointerdown', onPointer)
49
+ document.removeEventListener('focusin', onFocus)
50
+ const i = stack.findIndex((l) => l.id === id)
51
+ if (i >= 0) stack.splice(i, 1)
52
+ }
53
+ }
54
+
55
+ let lockCount = 0
56
+ let saved = ''
57
+ let savedPadding = ''
58
+
59
+ /** Stops the page from scrolling until the returned function is called. Locks can nest. */
60
+ export function lockScroll() {
61
+ if (lockCount === 0) {
62
+ const body = document.body
63
+ // Fills the space the scrollbar leaves, so the page does not shift sideways.
64
+ const bar = window.innerWidth - document.documentElement.clientWidth
65
+ saved = body.style.overflow
66
+ savedPadding = body.style.paddingRight
67
+ if (bar > 0) body.style.paddingRight = `calc(${getComputedStyle(body).paddingRight} + ${bar}px)`
68
+ body.style.overflow = 'hidden'
69
+ }
70
+ lockCount++
71
+ return () => {
72
+ lockCount--
73
+ if (lockCount === 0) {
74
+ document.body.style.overflow = saved
75
+ document.body.style.paddingRight = savedPadding
76
+ }
77
+ }
78
+ }
@@ -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
+ }