Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

bottom-sheet.tsx

215 lines7.2 KB

1import { useEffect, useRef } from "react";
2import type {
3 MouseEvent as ReactMouseEvent,
4 PointerEvent as ReactPointerEvent,
5 ReactNode,
6 RefObject,
7} from "react";
8​
9import { useFocusTrap } from "@/hooks/use-focus-trap";
10import { cn } from "@/lib/utils";
11​
12import { DRAG_START_THRESHOLD, sheetOffset, shouldCloseOnRelease } from "./sheet-gesture";
13​
14interface BottomSheetProps {
15 open: boolean;
16 onClose: () => void;
17 /** Accessible name of the dialog. */
18 label: string;
19 /** The sheet's top bar. Together with the grab handle it's the area you can swipe down. */
20 header: ReactNode;
21 children: ReactNode;
23​
24/**
25 * A near-full-screen sheet that slides up over the page, iOS style. Closes
26 * with Escape, a tap on the dimmed page behind it, or a swipe down on its
27 * header.
28 *
29 * Unlike a dialog, the content stays mounted while the sheet is closed (just
30 * hidden and inert), so whatever is inside keeps its state between openings.
31 * That's also why focus is kept in with `useFocusTrap` rather than a focus
32 * scope that relies on mounting and unmounting.
33 * The open/close motion lives in `styles.css` (`.bottom-sheet`).
34 */
35export function BottomSheet({ open, onClose, label, header, children }: BottomSheetProps) {
36 const sheetRef = useRef<HTMLDivElement>(null);
37 const backdropRef = useRef<HTMLDivElement>(null);
38 const drag = useSheetDrag({ sheetRef, backdropRef, onClose });
39​
40 // Focus moves in on open, stays in (Tab wraps), and goes back to the trigger on close.
41 useFocusTrap(sheetRef, open);
42​
43 // Escape closes, wherever focus is.
44 const onCloseRef = useRef(onClose);
45 onCloseRef.current = onClose;
46 useEffect(() => {
47 if (!open) return;
48 const onKeyDown = (event: KeyboardEvent) => {
49 if (event.key === "Escape" && !event.defaultPrevented) onCloseRef.current();
50 };
51 document.addEventListener("keydown", onKeyDown);
52 return () => document.removeEventListener("keydown", onKeyDown);
53 }, [open]);
54​
55 const state = open ? "open" : "closed";
56​
57 return (
58 <>
59 <div
60 ref={backdropRef}
61 data-state={state}
62 aria-hidden
63 onClick={onClose}
64 className="bottom-sheet-backdrop fixed inset-0 z-40 touch-none bg-black/30 dark:bg-black/60"
65 />
66 <div
67 ref={sheetRef}
68 role="dialog"
69 aria-modal
70 aria-label={label}
71 tabIndex={-1}
72 inert={!open}
73 data-state={state}
74 className={cn(
75 "bottom-sheet fixed inset-x-0 z-50 mx-auto flex max-w-2xl flex-col overflow-hidden outline-none",
76 // Reaches 3rem below the screen (padded back up), so the slight overshoot
77 // of the opening spring never shows a gap under the sheet.
78 "top-[calc(env(safe-area-inset-top)+2rem)] -bottom-12 pb-12",
79 "rounded-t-[22px] border-t border-black/5 bg-browser-toolbar shadow-[0_-8px_40px_rgb(0_0_0/0.18)] dark:border-white/10",
80 )}
81 >
82 <div
83 className="shrink-0 cursor-grab touch-none select-none active:cursor-grabbing"
84 {...drag.handlers}
85 >
86 <div className="flex justify-center pt-2 pb-1" aria-hidden>
87 <span className="h-[5px] w-9 rounded-full bg-foreground/25" />
88 </div>
89 {header}
90 </div>
91 <div className="relative min-h-0 flex-1">{children}</div>
92 </div>
93 </>
94 );
96​
97interface DragState {
98 pointerId: number;
99 startY: number;
100 lastY: number;
101 lastTime: number;
102 velocity: number;
103 /** Became a drag (moved past the threshold), as opposed to a tap. */
104 dragging: boolean;
106​
107/**
108 * Swipe down on the header to close. The sheet follows the pointer by writing
109 * its transform directly (no re-render per frame); on release it either
110 * closes or springs back, and the CSS transition animates from wherever the
111 * finger left it.
112 *
113 * The press starts on the header, but the pointer leaves it almost at once,
114 * so moves and the release are tracked on the window.
115 */
116function useSheetDrag({
117 sheetRef,
118 backdropRef,
119 onClose,
120}: {
121 sheetRef: RefObject<HTMLDivElement | null>;
122 backdropRef: RefObject<HTMLDivElement | null>;
123 onClose: () => void;
124}) {
125 const stopTrackingRef = useRef<(() => void) | null>(null);
126 const suppressClickRef = useRef(false);
127​
128 useEffect(() => () => stopTrackingRef.current?.(), []);
129​
130 function setOffset(offset: number | null) {
131 const sheet = sheetRef.current;
132 const backdrop = backdropRef.current;
133 if (!sheet || !backdrop) return;
134 if (offset === null) {
135 sheet.style.removeProperty("transform");
136 sheet.style.removeProperty("transition");
137 backdrop.style.removeProperty("opacity");
138 backdrop.style.removeProperty("transition");
139 return;
140 }
141 sheet.style.transition = "none";
142 sheet.style.transform = `translate3d(0, ${offset}px, 0)`;
143 backdrop.style.transition = "none";
144 backdrop.style.opacity = String(Math.max(0, 1 - offset / sheet.offsetHeight));
145 }
146​
147 function onPointerDown(event: ReactPointerEvent) {
148 if (event.button !== 0 || stopTrackingRef.current) return;
149 const drag: DragState = {
150 pointerId: event.pointerId,
151 startY: event.clientY,
152 lastY: event.clientY,
153 lastTime: event.timeStamp,
154 velocity: 0,
155 dragging: false,
156 };
157​
158 const onMove = (event: PointerEvent) => {
159 if (event.pointerId !== drag.pointerId) return;
160 const distance = event.clientY - drag.startY;
161 if (!drag.dragging && Math.abs(distance) < DRAG_START_THRESHOLD) return;
162 drag.dragging = true;
163 const elapsed = event.timeStamp - drag.lastTime;
164 if (elapsed > 0) drag.velocity = (event.clientY - drag.lastY) / elapsed;
165 drag.lastY = event.clientY;
166 drag.lastTime = event.timeStamp;
167 setOffset(sheetOffset(distance));
168 };
169​
170 const onEnd = (event: PointerEvent) => {
171 if (event.pointerId !== drag.pointerId) return;
172 stopTracking();
173 if (!drag.dragging) return;
174​
175 // The press was a drag, so it shouldn't also click a header button. That
176 // click (if any) comes right after the release; don't swallow later ones.
177 suppressClickRef.current = true;
178 window.setTimeout(() => {
179 suppressClickRef.current = false;
180 });
181 const sheetHeight = sheetRef.current?.offsetHeight ?? 0;
182 const offset = sheetOffset(drag.lastY - drag.startY);
183 // A pause before letting go cancels the flick.
184 const velocity = event.timeStamp - drag.lastTime > 100 ? 0 : drag.velocity;
185 const close =
186 event.type === "pointerup" && shouldCloseOnRelease({ offset, velocity, sheetHeight });
187 setOffset(null);
188 if (close) onClose();
189 };
190​
191 const stopTracking = () => {
192 window.removeEventListener("pointermove", onMove);
193 window.removeEventListener("pointerup", onEnd);
194 window.removeEventListener("pointercancel", onEnd);
195 stopTrackingRef.current = null;
196 };
197​
198 window.addEventListener("pointermove", onMove);
199 window.addEventListener("pointerup", onEnd);
200 window.addEventListener("pointercancel", onEnd);
201 stopTrackingRef.current = stopTracking;
202 }
203​
204 return {
205 handlers: {
206 onPointerDown,
207 onClickCapture: (event: ReactMouseEvent) => {
208 if (!suppressClickRef.current) return;
209 suppressClickRef.current = false;
210 event.preventDefault();
211 event.stopPropagation();
212 },
213 },
214 };