Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | 5x 5x 5x 5x 5x 5x 5x 5x 37x 14x 11x 11x 11x 11x 5x 24x 16x 14x 8x 16x 8x 5x 4x 2x 3x 5x 53x 6x 6x 5x 13x 13x 21x 16x 8x 5x 3x 3x 3x 3x 3x 5x 8x 5x 17x 17x 5x 2x 1x 1x 2x 2x 5x 153x 153x 153x 5x 302x 302x 302x 302x 302x 112x 302x 15x 15x 15x 302x 47x 47x 47x 45x 45x 45x 21x 1x 1x 20x 2x 2x 18x 11x 11x 21x 11x 35x 35x 47x 47x 47x 4x 35x 35x 302x 16x 16x 16x 16x 15x 15x 11x 11x 16x 16x 5x 5x 6x 6x 11x 302x 111x 111x 111x 111x 105x 55x 55x 111x 111x 79x 41x 41x 111x 22x 12x 12x 111x 4x 2x 2x 111x 124x 124x 124x 111x 124x 124x 124x 111x 139x 139x 111x 14x 14x 14x 13x 13x 13x 13x 13x 111x 111x 111x 111x 111x 111x 302x 302x 3x 3x 2x 9x 9x 6x 6x 6x 6x 3x 302x | // SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type PointerEvent as ReactPointerEvent,
} from "react";
import { useLatestRef } from "@/hooks/useLatestRef";
/** Height cap of a sheet when it opens, and after a drag up expands it. */
const SHEET_HEIGHT = "85vh";
const SHEET_FULL_HEIGHT = "calc(100vh - env(safe-area-inset-top) - 0.5rem)";
/** Movement in px before a touch counts as a drag rather than a tap. */
const DRAG_SLOP = 6;
/** Only moves in the last this many ms count towards the release speed. */
const VELOCITY_WINDOW_MS = 100;
/** Release speed in px/ms that counts as a flick. */
export const FLICK_VELOCITY = 0.5;
/** A slow drag down closes the sheet past this many px, or a quarter of its height if less. */
export const CLOSE_DISTANCE = 120;
/** A slow drag up expands the sheet past this many px. */
export const EXPAND_DISTANCE = 60;
export type SheetRelease = "close" | "expand" | "settle";
export interface DragSample {
y: number;
t: number;
}
/**
* Speed in px/ms (positive is down) over the moves in the last
* VELOCITY_WINDOW_MS before `now`. 0 when the finger had stopped.
*/
export const releaseVelocity = (samples: DragSample[], now: number): number => {
const recent = samples.filter((s) => now - s.t <= VELOCITY_WINDOW_MS);
if (recent.length < 2) return 0;
const first = recent[0];
const last = recent[recent.length - 1];
const dt = last.t - first.t;
return dt > 0 ? (last.y - first.y) / dt : 0;
};
/**
* What a sheet does when the finger lifts. `offset` is how far it was dragged
* in px and `velocity` the release speed in px/ms, both positive downwards.
* `height` is the sheet's height in px.
*/
export const sheetReleaseAction = ({
offset,
velocity,
height,
expanded,
}: {
offset: number;
velocity: number;
height: number;
expanded: boolean;
}): SheetRelease => {
if (offset > 0) {
if (velocity <= -FLICK_VELOCITY) return "settle";
if (velocity >= FLICK_VELOCITY) return "close";
const closeAt = height > 0 ? Math.min(CLOSE_DISTANCE, height / 4) : CLOSE_DISTANCE;
return offset >= closeAt ? "close" : "settle";
}
if (offset < 0 && !expanded) {
if (velocity >= FLICK_VELOCITY) return "settle";
if (velocity <= -FLICK_VELOCITY) return "expand";
return -offset >= EXPAND_DISTANCE ? "expand" : "settle";
}
return "settle";
};
interface Gesture {
startX: number;
startY: number;
// "pending" until the move is big enough to tell a drag from a tap or a scroll.
mode: "pending" | "drag" | "ignore";
// The scrollable element the touch started in, if any.
scroller: Element | null;
// Whether a drag up can grow the sheet, decided when the drag starts.
canExpand: boolean;
// Lets the scroller scroll again after a drag that locked it.
unlockScroller: () => void;
height: number;
offset: number;
samples: DragSample[];
// Set for a mouse, which goes through pointer events. Touch uses touch events.
pointerId: number | null;
}
const scrollsY = (el: Element): boolean => {
if (el.scrollHeight <= el.clientHeight) return false;
const { overflowY } = getComputedStyle(el);
return overflowY === "auto" || overflowY === "scroll";
};
const findScroller = (target: EventTarget | null, sheet: Element): Element | null => {
let el = target instanceof Element ? target : null;
while (el && el !== sheet) {
if (scrollsY(el)) return el;
el = el.parentElement;
}
return null;
};
// Stops an element scrolling until the returned function runs.
const lockScroll = (el: Element): (() => void) => {
Iif (!(el instanceof HTMLElement)) return () => {};
const previous = el.style.overflowY;
el.style.overflowY = "hidden";
return () => {
el.style.overflowY = previous;
};
};
// True when the sheet cuts off some of its content, either by clipping it or
// in a scrolling list, so growing it shows more.
const hidesContent = (sheet: Element): boolean =>
sheet.scrollHeight > sheet.clientHeight ||
Array.from(sheet.querySelectorAll("*")).some(scrollsY);
// A dialog opened from inside the sheet, such as a download's confirm, isn't
// part of it for dragging.
const inDialog = (target: EventTarget | null, container: Element): boolean => {
const dialog = target instanceof Element ? target.closest('[role="dialog"]') : null;
return dialog !== null && container.contains(dialog);
};
// After a mouse drag the browser still clicks whatever the drag started on,
// such as the close button. This drops that click.
const dropNextClick = () => {
const drop = (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
};
window.addEventListener("click", drop, { capture: true, once: true });
// The click comes in the same task as the pointerup, if at all.
setTimeout(() => window.removeEventListener("click", drop, { capture: true }), 0);
};
// Down slides the sheet, up grows it towards full height. Written straight to
// the element so a drag doesn't re-render the pane on every move. It sets
// `translate`, the property Tailwind's translate-y classes set, so it replaces
// the sheet's slide while dragging and doesn't add to it.
const paint = (sheet: HTMLElement, offset: number, expanded: boolean) => {
const pull = expanded ? 0 : Math.max(0, -offset);
sheet.style.translate = offset > 0 ? `0 ${offset}px` : "";
sheet.style.maxHeight = expanded
? SHEET_FULL_HEIGHT
: pull > 0
? `min(calc(${SHEET_HEIGHT} + ${pull}px), ${SHEET_FULL_HEIGHT})`
: SHEET_HEIGHT;
};
/**
* Lets a bottom sheet be dragged like an iOS sheet. A drag down follows the
* finger and closes the sheet when released far enough or with a flick, and
* a drag up expands it to full height. In scrollable content only a pull down
* from the top moves the sheet, and the content stays still until the finger
* lifts. Anything else scrolls.
*
* Put `sheetRef` on the sheet, which gets its max height from here, and
* spread `handleProps` on the handle and header so a mouse can drag them too.
* The sheet's CSS transition on `translate` and `max-height` animates the
* release. Give scrolling content in the sheet `overscroll-y-none`, so a pull
* down from its top can't also bounce the content.
*/
export const useSheetDrag = ({
onClose,
enabled = true,
}: {
onClose: () => void;
enabled?: boolean;
}) => {
const sheetRef = useRef<HTMLDivElement>(null);
const gestureRef = useRef<Gesture | null>(null);
const [expanded, setExpanded] = useState(false);
const latestRef = useLatestRef({ onClose, enabled, expanded });
useLayoutEffect(() => {
Eif (sheetRef.current) paint(sheetRef.current, 0, expanded);
}, [expanded]);
const begin = useCallback(
(x: number, y: number, scroller: Element | null, pointerId: number | null) => {
const sheet = sheetRef.current;
Iif (!sheet || !latestRef.current.enabled) return;
gestureRef.current = {
startX: x,
startY: y,
mode: "pending",
scroller,
canExpand: false,
unlockScroller: () => {},
height: sheet.offsetHeight,
offset: 0,
samples: [],
pointerId,
};
},
[latestRef]
);
// True while the move belongs to the sheet, so the page shouldn't scroll.
const move = useCallback(
(x: number, y: number): boolean => {
const g = gestureRef.current;
const sheet = sheetRef.current;
if (!g || !sheet || g.mode === "ignore") return false;
const dx = x - g.startX;
const dy = y - g.startY;
if (g.mode === "pending") {
if (Math.abs(dx) > Math.abs(dy)) {
Eif (Math.abs(dx) >= DRAG_SLOP) g.mode = "ignore";
return false;
}
if (g.scroller && (dy < 0 || g.scroller.scrollTop > 0)) {
g.mode = "ignore";
return false;
}
// Not clearly a drag yet, so the move stays with the browser. WebKit lets
// the first touchmove decide whether anything under the finger can scroll
// for the rest of the touch, so claiming a small wobble would stop a list
// or a row that scrolls sideways from scrolling after it.
if (Math.abs(dy) < DRAG_SLOP) return false;
g.mode = "drag";
g.canExpand = !g.scroller && !latestRef.current.expanded && hidesContent(sheet);
// The browser may already own this touch for scrolling, and then
// preventDefault can't stop the list. Locking it keeps the list still
// if the finger goes back up while the sheet follows.
if (g.scroller) g.unlockScroller = lockScroll(g.scroller);
sheet.style.transition = "none";
}
const { expanded } = latestRef.current;
g.offset = g.canExpand ? dy : Math.max(0, dy);
const now = performance.now();
g.samples.push({ y, t: now });
while (g.samples.length > 2 && now - g.samples[0].t > VELOCITY_WINDOW_MS) {
g.samples.shift();
}
paint(sheet, g.offset, expanded);
return true;
},
[latestRef]
);
// True when the gesture was a drag, so the tap under the finger should be dropped.
const end = useCallback(
(cancelled: boolean): boolean => {
const g = gestureRef.current;
const sheet = sheetRef.current;
gestureRef.current = null;
if (!g || !sheet) return false;
g.unlockScroller();
if (g.mode !== "drag") return false;
const { expanded, onClose } = latestRef.current;
const action = cancelled
? "settle"
: sheetReleaseAction({
offset: g.offset,
velocity: releaseVelocity(g.samples, performance.now()),
height: g.height,
expanded,
});
sheet.style.transition = "";
if (action === "close") {
sheet.style.translate = "0 100%";
onClose();
} else {
paint(sheet, 0, expanded || action === "expand");
if (action === "expand") setExpanded(true);
}
return true;
},
[latestRef]
);
// Touch listeners go on the element because React's touchmove is passive,
// and only a non-passive listener can stop the content scrolling.
useEffect(() => {
const sheet = sheetRef.current;
Iif (!sheet) return;
// A touch's events keep going to the element it started on, even after
// a re-render removes that element, and then they no longer reach the
// sheet. So the touched element gets the listeners too, and an event
// that reaches both is handled once.
const handled = new WeakSet<Event>();
const firstTime = (e: Event) => {
if (handled.has(e)) return false;
handled.add(e);
return true;
};
let touched: EventTarget | null = null;
const onTouchMove = (e: TouchEvent) => {
if (!firstTime(e)) return;
const t = e.touches[0];
if (t && move(t.clientX, t.clientY) && e.cancelable) e.preventDefault();
};
const onTouchEnd = (e: TouchEvent) => {
if (!firstTime(e)) return;
release();
if (end(false) && e.cancelable) e.preventDefault();
};
const onTouchCancel = (e: TouchEvent) => {
if (!firstTime(e)) return;
release();
end(true);
};
const listen = (target: EventTarget) => {
target.addEventListener("touchmove", onTouchMove as EventListener, { passive: false });
target.addEventListener("touchend", onTouchEnd as EventListener, { passive: false });
target.addEventListener("touchcancel", onTouchCancel as EventListener);
};
const unlisten = (target: EventTarget) => {
target.removeEventListener("touchmove", onTouchMove as EventListener);
target.removeEventListener("touchend", onTouchEnd as EventListener);
target.removeEventListener("touchcancel", onTouchCancel as EventListener);
};
const release = () => {
if (touched && touched !== sheet) unlisten(touched);
touched = null;
};
const onTouchStart = (e: TouchEvent) => {
release();
Iif (e.touches.length !== 1) {
end(true);
return;
}
if (inDialog(e.target, sheet)) return;
const t = e.touches[0];
begin(t.clientX, t.clientY, findScroller(e.target, sheet), null);
Eif (gestureRef.current && e.target && e.target !== sheet) {
touched = e.target;
listen(touched);
}
};
sheet.addEventListener("touchstart", onTouchStart, { passive: true });
listen(sheet);
return () => {
release();
sheet.removeEventListener("touchstart", onTouchStart);
unlisten(sheet);
};
}, [begin, move, end]);
const ownsPointer = (e: ReactPointerEvent) => gestureRef.current?.pointerId === e.pointerId;
const handleProps = {
onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {
Iif (e.pointerType !== "mouse" || e.button !== 0) return;
if (inDialog(e.target, e.currentTarget)) return;
begin(e.clientX, e.clientY, null, e.pointerId);
},
onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {
const g = gestureRef.current;
if (!g || !ownsPointer(e)) return;
// The button came up somewhere we didn't hear about.
Iif ((e.buttons & 1) === 0) {
end(true);
return;
}
const wasPending = g.mode === "pending";
move(e.clientX, e.clientY);
if (wasPending && g.mode === "drag") e.currentTarget.setPointerCapture(e.pointerId);
},
onPointerUp: (e: ReactPointerEvent<HTMLElement>) => {
if (ownsPointer(e) && end(false)) dropNextClick();
},
onPointerCancel: (e: ReactPointerEvent<HTMLElement>) => {
if (ownsPointer(e)) end(true);
},
};
return { sheetRef, handleProps };
};
|