hlmnhkl-ui 0.32.2 → 0.33.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,174 @@
1
+ 'use client'
2
+
3
+ import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from 'react'
4
+ import { cx } from '../../internal/cx'
5
+ import { focusables } from '../../internal/focus'
6
+ import { XIcon } from '../../internal/icons'
7
+ import { useDismiss } from '../../internal/layers'
8
+ import { useControllable } from '../../internal/useControllable'
9
+ import styles from './MorphButton.module.css'
10
+
11
+ export type MorphButtonProps = {
12
+ /** The button's text. It stays on the same spot and becomes the panel's title and name. */
13
+ label: ReactNode
14
+ /** Icon before the label. */
15
+ icon?: ReactNode
16
+ /** What the panel holds, such as a short form or a list of choices. */
17
+ children: ReactNode
18
+ /** Whether the panel is open, when you control it. */
19
+ open?: boolean
20
+ /** Starting open state when you do not control it. */
21
+ defaultOpen?: boolean
22
+ /** Called with the new open state. */
23
+ onOpenChange?: (open: boolean) => void
24
+ /** How wide the panel grows. It never runs past the edge of the screen. */
25
+ width?: 'sm' | 'md'
26
+ /** Screen reader name for the close button. */
27
+ closeLabel?: string
28
+ /** Element to focus when it opens. Defaults to the first control in the panel. */
29
+ initialFocus?: RefObject<HTMLElement | null>
30
+ /** Extra class for the outer box, which keeps the button's place in the page. */
31
+ className?: string
32
+ }
33
+
34
+ type Corner = 'tl' | 'tr' | 'bl' | 'br'
35
+
36
+ // The space kept between the panel and the edge of the screen.
37
+ const EDGE = 16
38
+
39
+ export function MorphButton({
40
+ label,
41
+ icon,
42
+ children,
43
+ open: openProp,
44
+ defaultOpen = false,
45
+ onOpenChange,
46
+ width = 'sm',
47
+ closeLabel = 'Close',
48
+ initialFocus,
49
+ className,
50
+ }: MorphButtonProps) {
51
+ const id = useId()
52
+ const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)
53
+ const [corner, setCorner] = useState<Corner>('tl')
54
+ const [room, setRoom] = useState<number>()
55
+ const [box, setBox] = useState({ tw: 0, th: 0, pw: 0, ph: 0 })
56
+ const anchorRef = useRef<HTMLDivElement>(null)
57
+ const shellRef = useRef<HTMLDivElement>(null)
58
+ const triggerRef = useRef<HTMLButtonElement>(null)
59
+ const panelRef = useRef<HTMLDivElement>(null)
60
+
61
+ useLayoutEffect(() => {
62
+ const t = triggerRef.current
63
+ const s = shellRef.current
64
+ if (!t || !s) return
65
+ const measure = () => setBox({ tw: t.offsetWidth, th: t.offsetHeight, pw: s.offsetWidth, ph: s.offsetHeight })
66
+ measure()
67
+ const ro = new ResizeObserver(measure)
68
+ ro.observe(t)
69
+ ro.observe(s)
70
+ return () => ro.disconnect()
71
+ }, [])
72
+
73
+ // It grows toward the side with room, decided before the move starts and never during it.
74
+ const place = () => {
75
+ const a = anchorRef.current?.getBoundingClientRect()
76
+ const s = shellRef.current
77
+ if (!a || !s) return
78
+ const right = window.innerWidth - EDGE - a.left
79
+ const left = a.right - EDGE
80
+ const below = window.innerHeight - EDGE - a.top
81
+ const above = a.bottom - EDGE
82
+ const flipX = right < box.pw && left > right
83
+ const up = below < box.ph && above > below
84
+ setCorner(`${up ? 'b' : 't'}${flipX ? 'r' : 'l'}` as Corner)
85
+ setRoom(Math.max(box.tw, flipX ? left : right))
86
+ }
87
+
88
+ const show = (next: boolean) => {
89
+ if (next) place()
90
+ setOpen(next)
91
+ }
92
+ const backToButton = () => triggerRef.current?.focus({ preventScroll: true })
93
+
94
+ // A controlled open from outside picks its side too.
95
+ useLayoutEffect(() => {
96
+ if (open) place()
97
+ }, [open])
98
+
99
+ useEffect(() => {
100
+ if (!open || !panelRef.current) return
101
+ const first = initialFocus?.current ?? focusables(panelRef.current).find((el) => !el.hasAttribute('data-skip-initial-focus')) ?? panelRef.current
102
+ first.focus({ preventScroll: true })
103
+ }, [open])
104
+
105
+ // Esc, a press outside, or focus moving on closes it. A layer it opened, such as a Select's list, is
106
+ // above it, so picking there does not count. Focus goes back to the button unless the press landed on
107
+ // something that takes focus itself.
108
+ useDismiss(
109
+ open,
110
+ [shellRef],
111
+ (reason, e) => {
112
+ setOpen(false)
113
+ const target = e.target instanceof Element ? e.target : null
114
+ if (reason === 'escape') backToButton()
115
+ else if (e.type === 'pointerdown' && !target?.closest('a[href], button, input, select, textarea, label, [tabindex]:not([tabindex="-1"])')) window.setTimeout(backToButton)
116
+ },
117
+ { focusOut: true },
118
+ )
119
+
120
+ // Shut, the surface is cut back to the button's own box in the chosen corner.
121
+ const dx = Math.max(0, box.pw - box.tw)
122
+ const dy = Math.max(0, box.ph - box.th)
123
+ const shut = { tl: [0, dx, dy, 0], tr: [0, 0, dy, dx], bl: [dy, dx, 0, 0], br: [dy, 0, 0, dx] }[corner]
124
+ const [t, r, b, l] = open ? [0, 0, 0, 0] : shut
125
+ const vars = {
126
+ '--t': `${t}px`,
127
+ '--r': `${r}px`,
128
+ '--b': `${b}px`,
129
+ '--l': `${l}px`,
130
+ '--pill': `${box.th / 2}px`,
131
+ maxWidth: room,
132
+ } as CSSProperties
133
+
134
+ return (
135
+ <div ref={anchorRef} className={cx(styles.anchor, className)} style={{ width: box.tw || undefined, height: box.th || undefined }}>
136
+ <div ref={shellRef} className={styles.shell} data-open={open || undefined} data-corner={corner} data-width={width} style={vars}>
137
+ <div className={styles.surface} aria-hidden="true" />
138
+ <div className={styles.content}>
139
+ <button
140
+ ref={triggerRef}
141
+ type="button"
142
+ className={styles.trigger}
143
+ aria-expanded={open}
144
+ aria-haspopup="dialog"
145
+ aria-controls={`${id}-panel`}
146
+ onClick={() => show(!open)}
147
+ >
148
+ {icon && (
149
+ <span className={styles.icon} aria-hidden="true">
150
+ {icon}
151
+ </span>
152
+ )}
153
+ <span id={`${id}-label`}>{label}</span>
154
+ </button>
155
+ <div ref={panelRef} id={`${id}-panel`} role="dialog" aria-labelledby={`${id}-label`} tabIndex={-1} className={styles.panel} inert={!open} aria-hidden={!open || undefined}>
156
+ <button
157
+ type="button"
158
+ className={styles.close}
159
+ aria-label={closeLabel}
160
+ data-skip-initial-focus
161
+ onClick={() => {
162
+ setOpen(false)
163
+ backToButton()
164
+ }}
165
+ >
166
+ <XIcon />
167
+ </button>
168
+ {children}
169
+ </div>
170
+ </div>
171
+ </div>
172
+ </div>
173
+ )
174
+ }
@@ -0,0 +1 @@
1
+ export * from './MorphButton'
@@ -161,3 +161,68 @@
161
161
  @keyframes fadeOut { to { opacity: 0; } }
162
162
  @keyframes sheetIn { from { transform: translateY(100%); } }
163
163
  @keyframes sheetOut { to { transform: translateY(100%); } }
164
+
165
+ /* With detents. The sheet is as tall as its highest height and slides to show more or less of itself.
166
+ The dim follows the height, and only the highest height takes the page behind. */
167
+ .overlay[data-detents] {
168
+ opacity: 0;
169
+ pointer-events: none;
170
+ }
171
+
172
+ .overlay[data-detents][data-top] { pointer-events: auto; }
173
+
174
+ .sheet[data-detents] {
175
+ max-height: none;
176
+ transition: none;
177
+ touch-action: none;
178
+ }
179
+
180
+ .sheet[data-detents][data-dragging] { user-select: none; }
181
+ .sheet[data-detents]:not([data-top]) .body { overflow: hidden; }
182
+ .sheet[data-detents][data-top] .body { touch-action: pan-y; }
183
+
184
+ /* The grabber is the control for the height. Its width shows it: short when low, long when full. */
185
+ .grabber {
186
+ display: grid;
187
+ flex: none;
188
+ place-items: center;
189
+ align-self: center;
190
+ width: calc(var(--hl-hit-min) * 2);
191
+ height: var(--hl-hit-min);
192
+ border-radius: var(--hl-radius-full);
193
+ cursor: grab;
194
+ outline: none;
195
+ }
196
+
197
+ .sheet[data-dragging] .grabber { cursor: grabbing; }
198
+ .grabber:focus-visible { box-shadow: var(--hl-focus-ring); }
199
+
200
+ .pill {
201
+ display: block;
202
+ width: var(--hl-handle-w);
203
+ height: var(--hl-handle-h);
204
+ border-radius: var(--hl-radius-full);
205
+ background: var(--hl-color-border-strong);
206
+ transition:
207
+ width var(--hl-motion-base) var(--hl-ease-liquid),
208
+ background-color var(--hl-motion-fast) var(--hl-ease-out);
209
+ }
210
+
211
+ .grabber[data-detent="peek"] .pill { width: var(--hl-handle-w-short); }
212
+ .grabber[data-detent="full"] .pill { width: var(--hl-handle-w-active); }
213
+ .grabber:focus-visible .pill { background: var(--hl-color-accent); }
214
+
215
+ @media (hover: hover) {
216
+ .grabber:hover .pill { background: var(--hl-color-fg-muted); }
217
+ }
218
+
219
+ .sheet[data-detents] .header { padding-top: 0; }
220
+
221
+ .srOnly {
222
+ position: absolute;
223
+ width: 1px;
224
+ height: 1px;
225
+ overflow: hidden;
226
+ clip-path: inset(50%);
227
+ white-space: nowrap;
228
+ }
@@ -1,15 +1,19 @@
1
1
  'use client'
2
2
 
3
- import { useId, useRef, type PointerEvent, type ReactNode, type RefObject } from 'react'
3
+ import { useEffect, useId, useLayoutEffect, useRef, useState, type FocusEvent, type KeyboardEvent, type PointerEvent, type ReactNode, type RefObject } from 'react'
4
4
  import { cx } from '../../internal/cx'
5
- import { rubber, speedTracker, useFling } from '../../internal/spring'
6
- import { useFocusTrap } from '../../internal/focus'
5
+ import { readMotionMs } from '../../internal/motion'
6
+ import { rubber, speedTracker, spring, useFling } from '../../internal/spring'
7
+ import { returnTarget, useFocusTrap } from '../../internal/focus'
7
8
  import { XIcon } from '../../internal/icons'
8
9
  import { useDismiss, useScrollLock } from '../../internal/layers'
9
10
  import { Portal } from '../../internal/Portal'
10
11
  import { usePresence } from '../../internal/usePresence'
11
12
  import styles from './Sheet.module.css'
12
13
 
14
+ /** A height a sheet can rest at: low with only its title showing, half the screen, or nearly all of it. */
15
+ export type SheetDetent = 'peek' | 'half' | 'full'
16
+
13
17
  export type SheetProps = {
14
18
  /** Whether the sheet is open. You always control it. */
15
19
  open: boolean
@@ -29,13 +33,47 @@ export type SheetProps = {
29
33
  initialFocus?: RefObject<HTMLElement | null>
30
34
  /** Extra class for the panel. */
31
35
  className?: string
36
+ /** Heights the sheet rests at, such as ['peek', 'half', 'full']. Below the highest one it is not modal: the page behind stays usable. */
37
+ detents?: SheetDetent[]
38
+ /** The height it rests at, when you control it. */
39
+ detent?: SheetDetent
40
+ /** The height it opens at when you do not control it. Defaults to the lowest. */
41
+ defaultDetent?: SheetDetent
42
+ /** Called with the new height after a drag, a tap or a key on the grabber, or Esc. */
43
+ onDetentChange?: (detent: SheetDetent) => void
44
+ /** Screen reader name for the grabber, which sets the height. */
45
+ heightLabel?: string
46
+ }
47
+
48
+ type BaseProps = Omit<SheetProps, 'detents' | 'detent' | 'defaultDetent' | 'onDetentChange' | 'heightLabel' | 'closeLabel'> & { closeLabel: string }
49
+
50
+ /** With detents, the grabber becomes a control for the height, and the sheet is modal only at its highest. */
51
+ export function Sheet({
52
+ open,
53
+ onOpenChange,
54
+ title,
55
+ description,
56
+ children,
57
+ footer,
58
+ closeLabel = 'Close',
59
+ initialFocus,
60
+ className,
61
+ detents,
62
+ detent,
63
+ defaultDetent,
64
+ onDetentChange,
65
+ heightLabel = 'Sheet height',
66
+ }: SheetProps) {
67
+ const base = { open, onOpenChange, title, description, children, footer, closeLabel, initialFocus, className }
68
+ if (!detents?.length) return <PlainSheet {...base} />
69
+ return <DetentSheet {...base} detents={detents} detent={detent} defaultDetent={defaultDetent} onDetentChange={onDetentChange} heightLabel={heightLabel} />
32
70
  }
33
71
 
34
72
  const CLOSE_RATIO = 0.3
35
73
  // px per second: a flick down this fast closes the sheet from anywhere.
36
74
  const CLOSE_SPEED = 500
37
75
 
38
- export function Sheet({ open, onOpenChange, title, description, children, footer, closeLabel = 'Close', initialFocus, className }: SheetProps) {
76
+ function PlainSheet({ open, onOpenChange, title, description, children, footer, closeLabel, initialFocus, className }: BaseProps) {
39
77
  const id = useId()
40
78
  const panelRef = useRef<HTMLDivElement>(null)
41
79
  const drag = useRef<{ y: number; dy: number; pointer: number; speed: ReturnType<typeof speedTracker> } | null>(null)
@@ -130,3 +168,337 @@ export function Sheet({ open, onOpenChange, title, description, children, footer
130
168
  </Portal>
131
169
  )
132
170
  }
171
+
172
+ // Shares of the screen, from the heights Apple Maps on the web and Vaul rest at.
173
+ const SHARE: Record<SheetDetent, number> = { peek: 0.19, half: 0.5, full: 0.96 }
174
+ const ORDER: SheetDetent[] = ['peek', 'half', 'full']
175
+ const NAME: Record<SheetDetent, string> = { peek: 'Low', half: 'Half', full: 'Full' }
176
+ // px per second: faster than this, a let-go is a flick and moves one height its way.
177
+ const FLICK = 400
178
+ // How far ahead, in seconds, a slow let-go is carried before the nearest height is picked.
179
+ const PROJECT = 0.2
180
+ // A press is not a drag until it moves this far, so taps on the content still work.
181
+ const SLOP = 6
182
+
183
+ const nearest = (v: number, hs: number[]) => hs.reduce((best, h, i) => (Math.abs(h - v) < Math.abs(hs[best] - v) ? i : best), 0)
184
+
185
+ // A flick moves one height from where the drag began, never two, even when the hand has already
186
+ // passed the next one. Real sheets measured all do this.
187
+ function pick(pos: number, v: number, start: number, hs: number[]) {
188
+ if (Math.abs(v) <= FLICK) return nearest(pos + v * PROJECT, hs)
189
+ return Math.max(0, Math.min(hs.length - 1, start + Math.sign(v)))
190
+ }
191
+
192
+ type DetentProps = BaseProps & Required<Pick<SheetProps, 'detents' | 'heightLabel'>> & Pick<SheetProps, 'detent' | 'defaultDetent' | 'onDetentChange'>
193
+
194
+ function DetentSheet({ open, onOpenChange, title, description, children, footer, closeLabel, initialFocus, className, detents, detent, defaultDetent, onDetentChange, heightLabel }: DetentProps) {
195
+ const id = useId()
196
+ const order = ORDER.filter((d) => detents.includes(d))
197
+ const top = order.length - 1
198
+ const [inner, setInner] = useState<SheetDetent>(defaultDetent ?? order[0])
199
+ const index = Math.max(0, order.indexOf(detent ?? inner))
200
+ const atTop = index === top
201
+ const { mounted, state } = usePresence(open, 'slow')
202
+ const [vh, setVh] = useState(() => (typeof window === 'undefined' ? 0 : window.innerHeight))
203
+ const heights = order.map((d) => Math.round(vh * SHARE[d]))
204
+ const [dragging, setDragging] = useState(false)
205
+ const [target, setTarget] = useState(index)
206
+ const [said, setSaid] = useState('')
207
+
208
+ const panelRef = useRef<HTMLDivElement>(null)
209
+ const overlayRef = useRef<HTMLDivElement>(null)
210
+ const grabRef = useRef<HTMLDivElement>(null)
211
+ const bodyRef = useRef<HTMLDivElement>(null)
212
+ const at = useRef(0)
213
+ const aimed = useRef(-1)
214
+ const stopSpring = useRef(() => {})
215
+ const unlisten = useRef(() => {})
216
+ const opener = useRef<HTMLElement | null>(null)
217
+ const trapStart = useRef<HTMLElement | null>(null)
218
+ const drag = useRef<{ y0: number; at0: number; start: number; pointer: number; live: boolean; speed: ReturnType<typeof speedTracker> } | null>(null)
219
+ const live = useRef({ heights, index, open })
220
+ live.current = { heights, index, open }
221
+
222
+ const change = (i: number) => {
223
+ if (detent === undefined) setInner(order[i])
224
+ onDetentChange?.(order[i])
225
+ }
226
+
227
+ const paint = (v: number) => {
228
+ at.current = v
229
+ const hs = live.current.heights
230
+ const panel = panelRef.current
231
+ if (!panel) return
232
+ panel.style.transform = `translateY(${hs[hs.length - 1] - v}px)`
233
+ // The dim follows the height between the two highest, so it never jumps.
234
+ const lo = hs.length > 1 ? hs[hs.length - 2] : 0
235
+ const dim = Math.max(0, Math.min(1, (v - lo) / (hs[hs.length - 1] - lo || 1)))
236
+ overlayRef.current?.style.setProperty('opacity', String(dim))
237
+ }
238
+
239
+ // No bounce at a height: critically damped, and never thrown at it faster than it can stop.
240
+ const settle = (to: number, v: number, done?: () => void) => {
241
+ stopSpring.current()
242
+ const period = readMotionMs('fling') / 1000
243
+ const d = at.current - to
244
+ const toward = Math.sign(v) === -Math.sign(d)
245
+ const w = period ? (2 * Math.PI) / period : 0
246
+ const speed = toward ? Math.sign(v) * Math.min(Math.abs(v), w * Math.abs(d)) : v
247
+ stopSpring.current = spring(at.current, to, speed, paint, done, 1)
248
+ }
249
+
250
+ const shownHidden = () => {
251
+ const active = document.activeElement as HTMLElement | null
252
+ return !!active && !!bodyRef.current?.contains(active) && active.getBoundingClientRect().top > window.innerHeight - 8
253
+ }
254
+
255
+ const go = (i: number, v = 0, spoken = true) => {
256
+ const hs = live.current.heights
257
+ if (i < 0) {
258
+ // A spring carries it off at the hand's speed, so the CSS close stays out of the way.
259
+ panelRef.current?.setAttribute('data-fluid', '')
260
+ settle(0, v)
261
+ onOpenChange(false)
262
+ requestAnimationFrame(() => {
263
+ if (live.current.open) {
264
+ panelRef.current?.removeAttribute('data-fluid')
265
+ settle(hs[live.current.index], 0)
266
+ }
267
+ })
268
+ return
269
+ }
270
+ aimed.current = i
271
+ setTarget(i)
272
+ if (i !== live.current.index) {
273
+ change(i)
274
+ if (spoken) setSaid(`${NAME[order[i]]} height`)
275
+ }
276
+ // Shrunk below a focused control: focus goes to the grabber, so it never sits on something hidden.
277
+ settle(hs[i], v, () => shownHidden() && grabRef.current?.focus({ preventScroll: true }))
278
+ }
279
+
280
+ const stepDown = () => (live.current.index > 0 ? go(live.current.index - 1) : onOpenChange(false))
281
+
282
+ useEffect(() => {
283
+ const onResize = () => setVh(window.innerHeight)
284
+ window.addEventListener('resize', onResize)
285
+ return () => window.removeEventListener('resize', onResize)
286
+ }, [])
287
+
288
+ useLayoutEffect(() => {
289
+ if (!open) return
290
+ opener.current = returnTarget()
291
+ aimed.current = -1
292
+ }, [open])
293
+
294
+ useLayoutEffect(() => {
295
+ if (!open || !mounted) return
296
+ if (aimed.current === -1) {
297
+ aimed.current = index
298
+ setTarget(index)
299
+ paint(heights[index])
300
+ if (!atTop) (initialFocus?.current ?? grabRef.current)?.focus({ preventScroll: true })
301
+ return
302
+ }
303
+ if (drag.current?.live) return
304
+ if (aimed.current !== index) {
305
+ aimed.current = index
306
+ setTarget(index)
307
+ settle(heights[index], 0)
308
+ } else paint(heights[index])
309
+ }, [open, mounted, index, vh])
310
+
311
+ // Closed, it gives focus back to its opener, and opens next time at the default height.
312
+ useEffect(() => {
313
+ if (open) return
314
+ setInner(defaultDetent ?? order[0])
315
+ const panel = panelRef.current
316
+ const active = document.activeElement
317
+ if (panel && opener.current?.isConnected && (!active || active === document.body || panel.contains(active))) opener.current.focus({ preventScroll: true })
318
+ }, [open])
319
+
320
+ useEffect(() => () => stopSpring.current(), [])
321
+
322
+ // Before the trap's own effect: at the top, focus stays where it is in the sheet.
323
+ useLayoutEffect(() => {
324
+ if (!atTop || !open) return
325
+ const active = document.activeElement as HTMLElement | null
326
+ trapStart.current = active && panelRef.current?.contains(active) ? active : (initialFocus?.current ?? null)
327
+ }, [atTop, open])
328
+ useScrollLock(open && atTop)
329
+ useFocusTrap(panelRef, open && mounted && atTop, { initialFocus: trapStart, restore: false })
330
+ useDismiss(open, [panelRef], stepDown, { outside: atTop })
331
+
332
+ const onPointerMove = (e: globalThis.PointerEvent) => {
333
+ const d = drag.current
334
+ const hs = live.current.heights
335
+ if (!d || d.pointer !== e.pointerId) return
336
+ const dy = d.y0 - e.clientY
337
+ if (!d.live) {
338
+ if (Math.abs(dy) < SLOP) return
339
+ if (bodyRef.current?.contains(e.target as Node) && live.current.index === top && dy > 0) return endDrag()
340
+ // A tap must not stop a settle half way, so the spring is caught only once it is a drag.
341
+ stopSpring.current()
342
+ d.live = true
343
+ d.at0 = at.current
344
+ d.start = nearest(at.current, hs)
345
+ d.speed.add(at.current)
346
+ d.y0 = e.clientY + (dy > 0 ? SLOP : -SLOP)
347
+ // Only now, so a tap on a button inside still clicks it.
348
+ if (e.target instanceof Element && panelRef.current?.contains(e.target)) panelRef.current.setPointerCapture?.(e.pointerId)
349
+ window.addEventListener('selectstart', block)
350
+ setDragging(true)
351
+ }
352
+ // A drag moves the sheet, never selects the page's text: a selection left over from one drag
353
+ // would turn the next press on it into the browser's own drag, which cancels the pointer. Safari
354
+ // keeps growing the selection it began on the press, so it is cleared on every move.
355
+ const selection = window.getSelection()
356
+ if (selection && !selection.isCollapsed) selection.removeAllRanges()
357
+ let raw = d.at0 + (d.y0 - e.clientY)
358
+ const full = hs[hs.length - 1]
359
+ if (raw > full) raw = full + rubber(raw - full, window.innerHeight - full)
360
+ if (raw < 0) raw = 0
361
+ d.speed.add(raw)
362
+ paint(raw)
363
+ const next = pick(raw, d.speed.speed(), d.start, hs)
364
+ setTarget((t) => (t === next ? t : next))
365
+ }
366
+
367
+ const onPointerUp = (e: globalThis.PointerEvent) => {
368
+ const d = drag.current
369
+ if (!d || d.pointer !== e.pointerId) return
370
+ endDrag()
371
+ if (!d.live) return
372
+ setDragging(false)
373
+ const hs = live.current.heights
374
+ const cancelled = e.type === 'pointercancel'
375
+ const v = cancelled ? 0 : d.speed.speed()
376
+ const pos = at.current
377
+ if (!cancelled && d.start === 0 && (v < -FLICK || pos < hs[0] * 0.5)) return go(-1, v)
378
+ go(pick(pos, v, d.start, hs), v)
379
+ }
380
+
381
+ // The hand often leaves the sheet before the drag counts as one, so the moves are followed on the window.
382
+ const block = (e: Event) => e.preventDefault()
383
+
384
+ const endDrag = () => {
385
+ drag.current = null
386
+ unlisten.current()
387
+ }
388
+
389
+ const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
390
+ if ((e.pointerType === 'mouse' && e.button !== 0) || drag.current) return
391
+ const el = e.target as Element
392
+ if (el.closest('input, textarea, select, [contenteditable="true"]')) return
393
+ const hs = live.current.heights
394
+ // At the top the content scrolls; a drag on it moves the sheet only from the top of the content.
395
+ if (bodyRef.current?.contains(el) && live.current.index === top && (bodyRef.current?.scrollTop ?? 0) > 0) return
396
+ drag.current = { y0: e.clientY, at0: at.current, start: nearest(at.current, hs), pointer: e.pointerId, live: false, speed: speedTracker() }
397
+ const move = onPointerMove
398
+ const up = onPointerUp
399
+ window.addEventListener('pointermove', move)
400
+ window.addEventListener('pointerup', up)
401
+ window.addEventListener('pointercancel', up)
402
+ window.addEventListener('dragstart', block)
403
+ unlisten.current = () => {
404
+ window.removeEventListener('pointermove', move)
405
+ window.removeEventListener('pointerup', up)
406
+ window.removeEventListener('pointercancel', up)
407
+ window.removeEventListener('dragstart', block)
408
+ window.removeEventListener('selectstart', block)
409
+ }
410
+ }
411
+
412
+ useEffect(() => () => unlisten.current(), [])
413
+
414
+ // A touch at the top of the content, moving down, belongs to the sheet: the browser would scroll it.
415
+ useEffect(() => {
416
+ const body = bodyRef.current
417
+ if (!body) return
418
+ let y = 0
419
+ const start = (e: TouchEvent) => (y = e.touches[0].clientY)
420
+ const move = (e: TouchEvent) => {
421
+ if (drag.current?.live || (live.current.index === live.current.heights.length - 1 && body.scrollTop <= 0 && e.touches[0].clientY > y)) e.preventDefault()
422
+ }
423
+ body.addEventListener('touchstart', start, { passive: true })
424
+ body.addEventListener('touchmove', move, { passive: false })
425
+ return () => {
426
+ body.removeEventListener('touchstart', start)
427
+ body.removeEventListener('touchmove', move)
428
+ }
429
+ }, [mounted])
430
+
431
+ const onGrabKey = (e: KeyboardEvent<HTMLDivElement>) => {
432
+ const i = live.current.index
433
+ if (e.key === 'Enter' || e.key === ' ') {
434
+ e.preventDefault()
435
+ return go(i === top ? 0 : i + 1, 0, false)
436
+ }
437
+ const keys: Record<string, number> = { ArrowUp: i + 1, ArrowRight: i + 1, ArrowDown: i - 1, ArrowLeft: i - 1, Home: 0, End: top, PageUp: top, PageDown: 0 }
438
+ if (!(e.key in keys)) return
439
+ e.preventDefault()
440
+ go(Math.max(0, Math.min(top, keys[e.key])), 0, false)
441
+ }
442
+
443
+ // Tabbing onto a control hidden below the screen's edge grows the sheet to the top, so it shows.
444
+ const onFocus = (e: FocusEvent<HTMLDivElement>) => {
445
+ if (!bodyRef.current?.contains(e.target) || live.current.index === top) return
446
+ if (e.target.getBoundingClientRect().bottom > window.innerHeight - 4) go(top)
447
+ }
448
+
449
+ if (!mounted) return null
450
+ const shown = order[dragging ? target : index]
451
+ return (
452
+ <Portal>
453
+ <div ref={overlayRef} className={styles.overlay} data-state={state} data-detents data-top={atTop || undefined} aria-hidden="true" />
454
+ <div
455
+ ref={panelRef}
456
+ role="dialog"
457
+ aria-modal={atTop || undefined}
458
+ aria-labelledby={`${id}-title`}
459
+ aria-describedby={description ? `${id}-desc` : undefined}
460
+ tabIndex={-1}
461
+ id={`${id}-sheet`}
462
+ className={cx(styles.sheet, className)}
463
+ data-state={state}
464
+ data-detents
465
+ data-top={atTop || undefined}
466
+ data-dragging={dragging || undefined}
467
+ style={{ height: heights[top] }}
468
+ onPointerDown={onPointerDown}
469
+ onFocus={onFocus}
470
+ >
471
+ <div
472
+ ref={grabRef}
473
+ className={styles.grabber}
474
+ role="slider"
475
+ tabIndex={0}
476
+ aria-label={heightLabel}
477
+ aria-orientation="vertical"
478
+ aria-valuemin={0}
479
+ aria-valuemax={top}
480
+ aria-valuenow={index}
481
+ aria-valuetext={NAME[order[index]]}
482
+ aria-controls={`${id}-sheet`}
483
+ data-detent={shown}
484
+ onKeyDown={onGrabKey}
485
+ onClick={() => go(index === top ? 0 : index + 1)}
486
+ >
487
+ <span className={styles.pill} />
488
+ </div>
489
+ <header className={styles.header}>
490
+ <div className={styles.titles}>
491
+ <h2 id={`${id}-title`} className={styles.title}>{title}</h2>
492
+ {description && <p id={`${id}-desc`} className={styles.description}>{description}</p>}
493
+ </div>
494
+ <button type="button" className={styles.close} aria-label={closeLabel} data-skip-initial-focus onClick={() => onOpenChange(false)}>
495
+ <XIcon />
496
+ </button>
497
+ </header>
498
+ {children && <div ref={bodyRef} className={styles.body}>{children}</div>}
499
+ {footer && <footer className={styles.footer}>{footer}</footer>}
500
+ <p className={styles.srOnly} aria-live="polite">{said}</p>
501
+ </div>
502
+ </Portal>
503
+ )
504
+ }
@@ -25,7 +25,7 @@ if (typeof document !== 'undefined') {
25
25
 
26
26
  // Where focus should go back to: the focused element, unless it is the page or a box around the
27
27
  // control that was just pressed. Then that control.
28
- function returnTarget(): HTMLElement | null {
28
+ export function returnTarget(): HTMLElement | null {
29
29
  const active = document.activeElement as HTMLElement | null
30
30
  const pressed = lastPressed && lastPressed.isConnected ? lastPressed : null
31
31
  if (pressed && (!active || active === document.body || (active !== pressed && active.contains(pressed)))) return pressed