feat(mobile): sheets that drag, fling and rise like native ones

The docked sheet could only be pulled by an invisible 20px strip, re-rendered
React on every finger move, and a flick sprang back to the top before fading
out. A finger on the content now carries the sheet once the content is at its
top, the panel moves through direct style writes, and a dismissing release
throws it off screen from where it was let go, faster the harder the flick.
With unsaved changes it springs back and asks instead. Pulling up only
stretches a little.

The docked sheet now rises from below the screen edge and sinks back there,
and the floating card pops in place the way a native alert does.
This commit is contained in:
Maurice
2026-11-06 12:14:20 +01:00
parent 25351c3628
commit 7293ee1174
5 changed files with 402 additions and 60 deletions
@@ -22,15 +22,21 @@ export function useDiscardGuard(guard: unknown, onClose: () => void) {
if (guardRef.current !== undefined && baseline.current === null) baseline.current = snapshot(guardRef.current)
}, [])
/** Whether a way out right now would stop to ask rather than close. */
const wouldAsk = useCallback(
() => guardRef.current !== undefined && baseline.current !== null && snapshot(guardRef.current) !== baseline.current,
[],
)
const requestClose = useCallback(() => {
if (guardRef.current !== undefined && baseline.current !== null && snapshot(guardRef.current) !== baseline.current) setAsking(true)
if (wouldAsk()) setAsking(true)
else onClose()
}, [onClose])
}, [onClose, wouldAsk])
const keepEditing = useCallback(() => setAsking(false), [])
const discard = useCallback(() => { setAsking(false); onClose() }, [onClose])
/** Forget the starting point, for a surface that stays mounted between openings. */
const reset = useCallback(() => { baseline.current = null; setAsking(false) }, [])
return { asking, markStart, requestClose, keepEditing, discard, reset }
return { asking, markStart, requestClose, wouldAsk, keepEditing, discard, reset }
}
+41 -49
View File
@@ -4,6 +4,7 @@ import { lockBodyScroll } from '../../utils/bodyScrollLock'
import { useTranslation } from '../../i18n'
import { useDiscardGuard } from '../../components/shared/useDiscardGuard'
import { keepTabInside, useModalFocus } from './modalFocus'
import { useSheetDrag } from './useSheetDrag'
export type MSheetVariant = 'card' | 'bottom' | 'drawer'
export type MSheetMaterial = 'glass' | 'bar-glass' | 'opaque'
@@ -31,7 +32,7 @@ interface MSheetProps {
discardGuard?: unknown
}
const EXIT_MS = 280
const EXIT_MS = 300
const DISCARD_BUTTON = 'rounded-full bg-danger px-4 py-2 text-body font-semibold text-white' // theme-lint-disable: white on the danger fill, as ConfirmDialog draws it
@@ -59,14 +60,20 @@ const MATERIAL: Record<MSheetMaterial, string> = {
opaque: 'bg-[color:var(--m-sheetop)] border border-[color:var(--m-shbr)]',
}
// The docked sheet rises from below the screen edge like a native sheet; the
// card pops in place like an alert; the drawer slides from the side.
const ENTER: Record<MSheetVariant, string> = { card: 'm-sheet-in', bottom: 'm-sheet-up', drawer: 'm-drawer-in' }
const EXIT: Record<MSheetVariant, string> = { card: 'm-sheet-out', bottom: 'm-sheet-down', drawer: 'm-drawer-out' }
function sheetRoot(): HTMLElement {
return document.getElementById('m-sheet-root') ?? document.body
}
/**
* The one sheet primitive of the mobile design system. Handles portal,
* scrim, ESC/backdrop dismissal, body scroll lock, focus trapping, 280ms
* enter/exit and — for the bottom variant — drag-to-dismiss on the top edge.
* scrim, ESC/backdrop dismissal, body scroll lock, focus trapping, native
* enter/exit motion and — for the bottom variant — drag-to-dismiss from the top
* edge or from content scrolled to its top (useSheetDrag).
*/
export default function MSheet({
open,
@@ -80,23 +87,42 @@ export default function MSheet({
discardGuard,
}: MSheetProps) {
const { t } = useTranslation()
const { asking, markStart, requestClose, keepEditing, discard, reset } = useDiscardGuard(discardGuard, onClose)
const { asking, markStart, requestClose, wouldAsk, keepEditing, discard, reset } = useDiscardGuard(discardGuard, onClose)
const [rendered, setRendered] = useState(open)
// Once the enter animation has played it is removed again: its forwards
// fill would otherwise override the inline drag transform for good.
const [entered, setEntered] = useState(false)
const [dragY, setDragY] = useState<number | null>(null)
// Thrown off screen by a drag: it leaves from where the finger let go, so the
// exit animation (which starts from the rest position) must not play.
const [flung, setFlung] = useState(false)
const panelRef = useRef<HTMLDivElement>(null)
const dragRef = useRef<{ startY: number; lastY: number; lastT: number; velocity: number } | null>(null)
const sheetDrag = useSheetDrag({
enabled: variant === 'bottom' && open && rendered,
panelRef,
onDismiss: () => {
if (wouldAsk()) {
requestClose()
return false
}
setFlung(true)
onClose()
return true
},
})
// Keep the sheet mounted through the exit animation.
useEffect(() => {
if (open) {
setRendered(true)
setFlung(false)
const panel = panelRef.current
if (panel) {
panel.style.transform = ''
panel.style.transition = ''
}
return
}
setEntered(false)
setDragY(null)
// The sheet stays mounted between openings; the next one starts afresh.
reset()
const t = setTimeout(() => setRendered(false), EXIT_MS)
@@ -130,46 +156,15 @@ export default function MSheet({
if (!rendered) return null
const handlePointerDown = (e: React.PointerEvent) => {
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
dragRef.current = { startY: e.clientY, lastY: e.clientY, lastT: e.timeStamp, velocity: 0 }
setDragY(0)
}
const handlePointerMove = (e: React.PointerEvent) => {
const d = dragRef.current
if (!d) return
d.velocity = (e.clientY - d.lastY) / Math.max(1, e.timeStamp - d.lastT)
d.lastY = e.clientY
d.lastT = e.timeStamp
setDragY(Math.max(0, e.clientY - d.startY))
}
const handlePointerEnd = () => {
const d = dragRef.current
if (!d) return
dragRef.current = null
const height = panelRef.current?.offsetHeight ?? 0
const dy = Math.max(0, d.lastY - d.startY)
setDragY(null)
// Past 30% of the panel or a decisive flick → dismiss.
if ((height > 0 && dy > height * 0.3) || d.velocity > 0.6) requestClose()
}
// Keep Tab inside the dialog while it is open.
const handleKeyDown = (e: React.KeyboardEvent) => keepTabInside(e, panelRef.current)
const enterClass = variant === 'drawer' ? 'm-drawer-in' : 'm-sheet-in'
const exitClass = variant === 'drawer' ? 'm-drawer-out' : 'm-sheet-out'
const animation = open ? (entered ? '' : enterClass) : exitClass
const enterClass = ENTER[variant]
const exitClass = EXIT[variant]
const animation = open ? (entered ? '' : enterClass) : flung ? '' : exitClass
const resolvedMaterial = material ?? (variant === 'bottom' ? 'bar-glass' : 'glass')
const dragStyle: React.CSSProperties =
dragY !== null
? { transform: `translateY(${dragY}px)`, transition: 'none' }
: { transition: 'transform 280ms var(--ease-drawer)' }
return createPortal(
// m-root on the overlay so the --m-* tokens resolve even when the portal
// has to fall back to document.body (sheet mounted in the same commit as
@@ -193,7 +188,6 @@ export default function MSheet({
data-m-sheet={open ? 'open' : 'closing'}
tabIndex={-1}
className={`relative flex flex-col overflow-hidden outline-none text-m-ink ${SHAPE[variant]} ${MATERIAL[resolvedMaterial]} ${animation} ${className}`}
style={variant === 'bottom' ? dragStyle : undefined}
onClick={(e) => e.stopPropagation()}
onKeyDown={handleKeyDown}
onKeyDownCapture={markStart}
@@ -203,14 +197,12 @@ export default function MSheet({
}}
>
{variant === 'bottom' && (
// Invisible drag strip along the top edge — the design shows no
// handle, the panel starts directly with its content.
// Invisible grab strip along the top edge — the design shows no
// handle, the panel starts directly with its content. The content
// pulls the sheet too, once it is scrolled to its top.
<div
className="absolute inset-x-0 top-0 z-[1] h-5 cursor-grab touch-none active:cursor-grabbing"
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerEnd}
onPointerCancel={handlePointerEnd}
className="absolute inset-x-0 top-0 z-[1] h-6 cursor-grab touch-none active:cursor-grabbing"
{...sheetDrag.strip}
/>
)}
{children}
@@ -0,0 +1,233 @@
import type { PointerEvent as ReactPointerEvent, RefObject } from 'react';
import { useCallback, useEffect, useRef } from 'react';
/**
* Drag-to-dismiss for the docked bottom sheet, the way a native sheet takes it.
*
* Two ways in. The grab strip along the top edge answers pointers, so a mouse
* or a pen on a narrow window can pull it too. And the sheet's content answers
* a finger pulling down once whatever it scrolls is at its top: the gesture
* that would otherwise only rubber-band the list carries the whole sheet, as
* on iOS. A content drag is claimed on the first move or not at all, so the
* list's own scroll and any horizontal scroller inside keep their gestures.
*
* The finger moves the panel through direct style writes, batched per frame,
* never through React state. On release the speed over the last few events
* decides: a flick or a pull past a third of the sheet throws it off screen
* from where the finger let go, anything else springs back. Pulling up past
* the rest position only stretches a little.
*/
/** Movement before a content touch is read as a drag or let go. */
const CLASSIFY_PX = 6;
/** Down must beat sideways by this much, so a horizontal scroller keeps its pan. */
const AXIS_BIAS = 1.2;
/** Pulled past this share of the sheet's height, the release dismisses. */
const DISMISS_SHARE = 0.3;
/** px/ms downward at release that dismisses on its own. */
const FLICK_V = 0.5;
/** Speed is read over this trailing window. */
const SAMPLE_MS = 80;
/** Upward pull: a fraction of the travel, capped, as a stretch rather than a move. */
const STRETCH = 0.2;
const STRETCH_MAX = 20;
export const SPRING_BACK = 'transform 280ms var(--ease-drawer)';
/** Controls that own a downward finger themselves. */
const OWNS_GESTURE = 'input[type="range"], textarea, select, [data-sheet-nodrag]';
interface Drag {
y0: number;
x0: number;
samples: { y: number; t: number }[];
claimed: boolean;
scroller: HTMLElement | null;
}
function nearestScroller(from: EventTarget | null, stop: HTMLElement): HTMLElement | null {
let el = from instanceof HTMLElement ? from : null;
while (el && el !== stop) {
const overflow = getComputedStyle(el).overflowY;
if ((overflow === 'auto' || overflow === 'scroll') && el.scrollHeight > el.clientHeight) return el;
el = el.parentElement;
}
return null;
}
function offsetFor(dy: number): number {
return dy >= 0 ? dy : -Math.min(STRETCH_MAX, -dy * STRETCH);
}
function sample(d: Drag, y: number, t: number): void {
d.samples.push({ y, t });
while (d.samples.length > 2 && t - d.samples[0].t > SAMPLE_MS) d.samples.shift();
}
export interface SheetDragOptions {
enabled: boolean;
panelRef: RefObject<HTMLElement | null>;
/** Called on a dismissing release. Returns true when the sheet will close, so
* it can be thrown off screen; false (an unsaved-changes question) springs it back. */
onDismiss: () => boolean;
}
export function useSheetDrag({ enabled, panelRef, onDismiss }: SheetDragOptions) {
const drag = useRef<Drag | null>(null);
const frame = useRef(0);
const latest = useRef(onDismiss);
latest.current = onDismiss;
const write = useCallback(
(y: number, transition: string) => {
const el = panelRef.current;
if (!el) return;
el.style.transition = transition;
el.style.transform = `translateY(${y}px)`;
},
[panelRef]
);
const follow = useCallback(
(dy: number) => {
cancelAnimationFrame(frame.current);
// Written at once as well as on the next frame: the first write starts the
// move without a frame's lag, the frame keeps a burst of events to one paint.
write(offsetFor(dy), 'none');
frame.current = requestAnimationFrame(() => write(offsetFor(dy), 'none'));
},
[write]
);
const release = useCallback(
(d: Drag, lastY: number) => {
cancelAnimationFrame(frame.current);
const el = panelRef.current;
if (!el) return;
const dy = lastY - d.y0;
const first = d.samples[0];
const last = d.samples[d.samples.length - 1];
const v = first && last ? (last.y - first.y) / Math.max(1, last.t - first.t) : 0;
const height = el.offsetHeight;
const dismiss = dy > 0 && ((height > 0 && dy > height * DISMISS_SHARE) || v > FLICK_V);
if (dismiss && latest.current()) {
// Off screen from where the finger let go, faster the harder the flick.
const distance = Math.max(height, window.innerHeight - el.getBoundingClientRect().top + dy) + 24;
const ms = Math.round(Math.min(320, Math.max(160, (distance - dy) / Math.max(v, 1.2))));
write(distance, `transform ${ms}ms cubic-bezier(0.2, 0.8, 0.2, 1)`);
return;
}
write(0, SPRING_BACK);
},
[panelRef, write]
);
// ── The grab strip: pointer events, any pointer type ──────────────────────
const onStripPointerDown = useCallback(
(e: ReactPointerEvent) => {
(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
drag.current = {
y0: e.clientY,
x0: e.clientX,
samples: [{ y: e.clientY, t: e.timeStamp }],
claimed: true,
scroller: null,
};
write(0, 'none');
},
[write]
);
const onStripPointerMove = useCallback(
(e: ReactPointerEvent) => {
const d = drag.current;
if (!d?.claimed) return;
sample(d, e.clientY, e.timeStamp);
follow(e.clientY - d.y0);
},
[follow]
);
const onStripPointerEnd = useCallback(
(e: ReactPointerEvent) => {
const d = drag.current;
drag.current = null;
if (!d?.claimed) return;
const last = d.samples[d.samples.length - 1];
release(d, Number.isFinite(e.clientY) && e.clientY !== 0 ? e.clientY : last.y);
},
[release]
);
// ── The content: touch events, claimed on the first move ──────────────────
useEffect(() => {
const panel = panelRef.current;
if (!enabled || !panel) return;
const onStart = (e: TouchEvent) => {
if (e.touches.length !== 1) {
drag.current = null;
return;
}
const target = e.target as Element | null;
if (target?.closest?.('[data-sheet-grab]') || target?.closest?.(OWNS_GESTURE)) return;
const t = e.touches[0];
drag.current = {
y0: t.clientY,
x0: t.clientX,
samples: [{ y: t.clientY, t: e.timeStamp }],
claimed: false,
scroller: nearestScroller(e.target, panel),
};
};
const onMove = (e: TouchEvent) => {
const d = drag.current;
if (!d || e.touches.length !== 1) return;
const t = e.touches[0];
const dy = t.clientY - d.y0;
const dx = t.clientX - d.x0;
if (!d.claimed) {
if (Math.abs(dy) <= CLASSIFY_PX && Math.abs(dx) <= CLASSIFY_PX) return;
const atTop = !d.scroller || d.scroller.scrollTop <= 0;
if (dy > 0 && Math.abs(dy) > Math.abs(dx) * AXIS_BIAS && atTop) {
d.claimed = true;
// Measured from here, so the sheet does not jump by the classify slop.
d.y0 = t.clientY;
d.samples = [{ y: t.clientY, t: e.timeStamp }];
} else {
drag.current = null;
return;
}
}
if (e.cancelable) e.preventDefault();
sample(d, t.clientY, e.timeStamp);
follow(t.clientY - d.y0);
};
const onEnd = (e: TouchEvent) => {
const d = drag.current;
drag.current = null;
if (!d?.claimed) return;
const last = d.samples[d.samples.length - 1];
release(d, e.changedTouches[0]?.clientY ?? last.y);
};
panel.addEventListener('touchstart', onStart, { passive: true });
panel.addEventListener('touchmove', onMove, { passive: false });
panel.addEventListener('touchend', onEnd, { passive: true });
panel.addEventListener('touchcancel', onEnd, { passive: true });
return () => {
cancelAnimationFrame(frame.current);
panel.removeEventListener('touchstart', onStart);
panel.removeEventListener('touchmove', onMove);
panel.removeEventListener('touchend', onEnd);
panel.removeEventListener('touchcancel', onEnd);
};
}, [enabled, panelRef, follow, release]);
return {
strip: {
'data-sheet-grab': '',
onPointerDown: onStripPointerDown,
onPointerMove: onStripPointerMove,
onPointerUp: onStripPointerEnd,
onPointerCancel: onStripPointerEnd,
},
};
}
+21 -8
View File
@@ -95,13 +95,24 @@
/* ── Keyframes ──────────────────────────────────────────────────────────── */
/* The floating card pops in place, the way a native alert does. */
@keyframes m-sheet-in {
from { opacity: 0; transform: translateY(24px); }
to { opacity: 1; transform: translateY(0); }
from { opacity: 0; transform: translateY(10px) scale(.96); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes m-sheet-out {
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(24px); }
from { opacity: 1; transform: translateY(0) scale(1); }
to { opacity: 0; transform: translateY(6px) scale(.97); }
}
/* The docked sheet rises from below the screen edge and sinks back there: it
sits above the nav, so it travels its own height plus that gap. */
@keyframes m-sheet-up {
from { transform: translateY(calc(100% + var(--bottom-nav-h, 84px) + 24px)); }
to { transform: translateY(0); }
}
@keyframes m-sheet-down {
from { transform: translateY(0); }
to { transform: translateY(calc(100% + var(--bottom-nav-h, 84px) + 24px)); }
}
@keyframes m-drawer-in {
from { transform: translateX(-100%); }
@@ -132,8 +143,10 @@
to { opacity: 0; transform: translateY(6px); }
}
.m-sheet-in { animation: m-sheet-in 280ms var(--ease-drawer) both; }
.m-sheet-out { animation: m-sheet-out 280ms var(--ease-drawer) both; }
.m-sheet-in { animation: m-sheet-in 260ms var(--ease-out-quint) both; }
.m-sheet-out { animation: m-sheet-out 220ms var(--ease-drawer) both; }
.m-sheet-up { animation: m-sheet-up 420ms var(--ease-drawer) both; }
.m-sheet-down { animation: m-sheet-down 300ms var(--ease-drawer) both; }
.m-drawer-in { animation: m-drawer-in 280ms var(--ease-drawer) both; }
.m-drawer-out { animation: m-drawer-out 280ms var(--ease-drawer) both; }
.m-fade-in { animation: m-fade-in 280ms var(--ease-drawer) both; }
@@ -144,10 +157,10 @@
/* Reduced motion: gentler, not zero (same rule the desktop keyframes follow). */
@media (prefers-reduced-motion: reduce) {
.m-sheet-in, .m-drawer-in, .m-pop-in, .m-toast-in {
.m-sheet-in, .m-sheet-up, .m-drawer-in, .m-pop-in, .m-toast-in {
animation: m-fade-in 120ms ease-out both;
}
.m-sheet-out, .m-drawer-out, .m-toast-out {
.m-sheet-out, .m-sheet-down, .m-drawer-out, .m-toast-out {
animation: m-fade-out 120ms ease-out both;
}
}
+98
View File
@@ -293,6 +293,104 @@ describe('MSheet', () => {
expect(baseCalls).toEqual([]);
});
describe('dragging the docked sheet', () => {
const touch = (y: number, x = 100) => ({ touches: [{ clientX: x, clientY: y }], changedTouches: [{ clientX: x, clientY: y }] });
function renderBottom(onClose = vi.fn(), content: React.ReactNode = <div>Sheet content</div>) {
HTMLElement.prototype.setPointerCapture = vi.fn();
render(
<MSheet open onClose={onClose} variant="bottom" ariaLabel="Bottom">
{content}
</MSheet>,
);
const dialog = screen.getByRole('dialog');
Object.defineProperty(dialog, 'offsetHeight', { configurable: true, value: 400 });
return { dialog, onClose };
}
it('FE-MOB-SHEET-022: a pull down on the content carries the sheet and throws it off past a third', () => {
const { dialog, onClose } = renderBottom();
const content = screen.getByText('Sheet content');
fireEvent.touchStart(content, touch(100));
fireEvent.touchMove(content, touch(140));
fireEvent.touchMove(content, touch(300));
expect(dialog.style.transform).toBe('translateY(160px)');
fireEvent.touchEnd(content, touch(300));
expect(onClose).toHaveBeenCalledTimes(1);
// Thrown from where the finger let go, not replayed from the rest position.
expect(dialog.style.transform).toMatch(/translateY\(\d+px\)/);
expect(dialog.className).not.toContain('m-sheet-down');
});
it('FE-MOB-SHEET-023: content scrolled down keeps its own scroll, and a sideways pan is let go', () => {
const { dialog, onClose } = renderBottom(vi.fn(), (
<div data-testid="list" style={{ overflowY: 'auto' }}>
<span>row</span>
</div>
));
const list = screen.getByTestId('list');
Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 900 });
Object.defineProperty(list, 'clientHeight', { configurable: true, value: 300 });
Object.defineProperty(list, 'scrollTop', { configurable: true, writable: true, value: 120 });
fireEvent.touchStart(screen.getByText('row'), touch(100));
fireEvent.touchMove(screen.getByText('row'), touch(200));
fireEvent.touchEnd(screen.getByText('row'), touch(200));
list.scrollTop = 0;
fireEvent.touchStart(list, touch(100, 100));
fireEvent.touchMove(list, touch(110, 160));
fireEvent.touchEnd(list, touch(110, 160));
expect(dialog.style.transform).toBe('');
expect(onClose).not.toHaveBeenCalled();
});
it('FE-MOB-SHEET-024: pulling up past the rest position only stretches a little', () => {
const { dialog } = renderBottom();
const strip = dialog.querySelector('.cursor-grab') as HTMLElement;
fireEvent.pointerDown(strip, { pointerId: 1, clientY: 300 });
fireEvent.pointerMove(strip, { pointerId: 1, clientY: 0 });
expect(dialog.style.transform).toBe('translateY(-20px)');
});
it('FE-MOB-SHEET-025: with unsaved changes a flick springs back and asks', () => {
HTMLElement.prototype.setPointerCapture = vi.fn();
const onClose = vi.fn();
function Form() {
const [name, setName] = React.useState('');
return (
<MSheet open onClose={onClose} variant="bottom" ariaLabel="Form" discardGuard={{ name }}>
<input aria-label="Name" value={name} onChange={e => setName(e.target.value)} />
</MSheet>
);
}
render(<Form />);
const input = screen.getByRole('textbox', { name: 'Name' });
fireEvent.pointerDown(input);
fireEvent.change(input, { target: { value: 'Porto' } });
const dialog = screen.getByRole('dialog', { name: 'Form' });
const strip = dialog.querySelector('.cursor-grab') as HTMLElement;
fireEvent.pointerDown(strip, { pointerId: 1, clientY: 100 });
fireEvent.pointerMove(strip, { pointerId: 1, clientY: 160 });
fireEvent.pointerUp(strip, { pointerId: 1, clientY: 160 });
expect(onClose).not.toHaveBeenCalled();
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
expect(dialog.style.transform).toBe('translateY(0px)');
});
it('FE-MOB-SHEET-026: the docked sheet rises from below, the card pops in place', () => {
const { dialog } = renderBottom();
expect(dialog.className).toContain('m-sheet-up');
});
});
describe('the unsaved-changes question', () => {
function Form({ open, onClose }: { open: boolean; onClose: () => void }) {
const [name, setName] = React.useState('');