Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HistorySwipeNavigation.tsx

192 lines7.4 KB

1import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
2import { useEffect, useState } from "react";
3​
4import { cn, isMacPlatform } from "../lib/utils";
5import { canNavigateHistory, navigateHistory, type HistoryDirection } from "../navigationHistory";
6​
7const SWIPE_TRIGGER_DISTANCE = 120;
8// Movement needed before the gesture picks an axis; first events are often diagonal.
9const SWIPE_AXIS_LOCK_DISTANCE = 8;
10const MOMENTUM_SAMPLE_SIZE = 5;
11​
12type SwipeBounds = { left: number; top: number; width: number; height: number };
13type SwipeGesture =
14 | { kind: "pending"; path: EventTarget[]; y: number; sumX: number; sumY: number }
15 | {
16 kind: "tracking";
17 direction: HistoryDirection;
18 distance: number;
19 deltas: number[];
20 y: number;
21 bounds: SwipeBounds;
22 }
23 // Not a swipe, or one already decided: the rest of its events are ignored.
24 | { kind: "ignored" };
25type SwipeIndicatorState = {
26 direction: HistoryDirection;
27 progress: number;
28 y: number;
29 bounds: SwipeBounds;
30 tracking: boolean;
31};
32​
33function readMainContentBounds(): SwipeBounds {
34 const main = document.querySelector('[data-slot="sidebar-inset"]');
35 if (!main) return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };
36 const { left, top, width, height } = main.getBoundingClientRect();
37 return { left, top, width, height };
39​
40// `event.target` stops at a shadow host; the composed path also reaches scrollers inside it.
41function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): boolean {
42 for (const element of path) {
43 if (!(element instanceof Element) || element.scrollWidth <= element.clientWidth) continue;
44 const { overflowX } = getComputedStyle(element);
45 if (overflowX !== "auto" && overflowX !== "scroll") continue;
46 const canScroll =
47 deltaX < 0
48 ? element.scrollLeft > 0
49 : element.scrollLeft + element.clientWidth < element.scrollWidth - 1;
50 if (canScroll) return true;
51 }
52 return false;
54​
55function lockSwipeAxis(
56 pending: Extract<SwipeGesture, { kind: "pending" }>,
57): Exclude<SwipeGesture, { kind: "pending" }> {
58 const { path, sumX, sumY } = pending;
59 if (Math.abs(sumX) <= Math.abs(sumY)) return { kind: "ignored" };
60 if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) {
61 return { kind: "ignored" };
62 }
63 if (canScrollHorizontally(path, sumX)) return { kind: "ignored" };
64 const direction = sumX < 0 ? "back" : "forward";
65 if (!canNavigateHistory(direction)) return { kind: "ignored" };
66 return {
67 kind: "tracking",
68 direction,
69 distance: Math.abs(sumX),
70 deltas: [],
71 y: pending.y,
72 bounds: readMainContentBounds(),
73 };
75​
76/**
77 * macOS momentum after the fingers lift decays by a near-constant ratio per
78 * event; finger movement is noisier. Deltas are signed along the swipe.
79 */
80export function isMomentumTail(deltas: readonly number[]): boolean {
81 if (deltas.length < MOMENTUM_SAMPLE_SIZE) return false;
82 const recent = deltas.slice(-MOMENTUM_SAMPLE_SIZE);
83 if (recent.some((delta) => delta <= 0)) return false;
84 const ratios = recent.slice(1).map((delta, index) => delta / recent[index]!);
85 return (
86 ratios.every((ratio) => ratio >= 0.7 && ratio < 1) &&
87 Math.max(...ratios) - Math.min(...ratios) < 0.1
88 );
90​
91/**
92 * Two-finger horizontal trackpad swipes go back and forward, like a browser.
93 * macOS only: on Windows and Linux a mouse tilt wheel is indistinguishable from a trackpad swipe.
94 */
95export function HistorySwipeNavigation() {
96 const [swipe, setSwipe] = useState<SwipeIndicatorState | null>(null);
97​
98 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window wheel and desktop gesture listeners track trackpad swipes
99 useEffect(() => {
100 if (!isMacPlatform(navigator.platform)) return;
101 let gesture: SwipeGesture | null = null;
102 const hideIndicator = () =>
103 setSwipe((current) => (current === null ? null : { ...current, tracking: false }));
104 // The fingers lifted: navigate if the swipe went far enough, then ignore its momentum.
105 const release = () => {
106 if (gesture?.kind === "tracking" && gesture.distance >= SWIPE_TRIGGER_DISTANCE) {
107 navigateHistory(gesture.direction);
108 }
109 gesture = { kind: "ignored" };
110 hideIndicator();
111 };
112 // Chromium brackets each trackpad scroll, momentum included, with these.
113 const unsubscribeScrollBegin = window.desktopBridge?.onTrackpadScrollBegin(() => {
114 if (gesture?.kind === "ignored") gesture = null;
115 });
116 const unsubscribeScrollEnd = window.desktopBridge?.onTrackpadScrollEnd(() => {
117 if (gesture?.kind === "tracking") release();
118 gesture = null;
119 });
120 const onWheel = (event: WheelEvent) => {
121 if (gesture === null) {
122 gesture =
123 event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL
124 ? { kind: "ignored" }
125 : { kind: "pending", path: event.composedPath(), y: event.clientY, sumX: 0, sumY: 0 };
126 }
127 if (gesture.kind === "ignored") return;
128 if (gesture.kind === "pending") {
129 gesture.sumX += event.deltaX;
130 gesture.sumY += event.deltaY;
131 if (Math.abs(gesture.sumX) + Math.abs(gesture.sumY) < SWIPE_AXIS_LOCK_DISTANCE) return;
132 gesture = lockSwipeAxis({ ...gesture, path: [...gesture.path, ...event.composedPath()] });
133 if (gesture.kind === "ignored") return;
134 } else {
135 const delta = gesture.direction === "back" ? -event.deltaX : event.deltaX;
136 if (event.deltaX === 0 && event.deltaY === 0) return release();
137 gesture.deltas = [...gesture.deltas.slice(1 - MOMENTUM_SAMPLE_SIZE), delta];
138 if (isMomentumTail(gesture.deltas)) return release();
139 gesture.distance = Math.max(0, gesture.distance + delta);
140 }
141 setSwipe({
142 direction: gesture.direction,
143 progress: Math.min(1, gesture.distance / SWIPE_TRIGGER_DISTANCE),
144 y: gesture.y,
145 bounds: gesture.bounds,
146 tracking: true,
147 });
148 };
149 window.addEventListener("wheel", onWheel, { capture: true, passive: true });
150 return () => {
151 unsubscribeScrollBegin?.();
152 unsubscribeScrollEnd?.();
153 window.removeEventListener("wheel", onWheel, { capture: true });
154 };
155 }, []);
156​
157 return swipe === null ? null : <SwipeIndicator {...swipe} />;
159​
160// A circle pinned to the edge of the main content that peeks in up to half its width.
161function SwipeIndicator({ direction, progress, y, bounds, tracking }: SwipeIndicatorState) {
162 const armed = progress >= 1;
163 const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon;
164 const hidden = 100 - progress * 50;
165 return (
166 <div
167 aria-hidden="true"
168 className="pointer-events-none fixed z-100 overflow-hidden"
169 style={bounds}
170 >
171 <div
172 className={cn(
173 "absolute flex size-14 items-center rounded-full bg-muted text-foreground dark:bg-black dark:text-white",
174 direction === "back" ? "left-0 justify-end pr-2" : "right-0 justify-start pl-2",
175 !tracking && "transition-[opacity,transform] duration-200 ease-out",
176 )}
177 style={{
178 top: `clamp(0px, calc(${y - bounds.top}px - 1.75rem), calc(100% - 3.5rem))`,
179 opacity: tracking ? 1 : 0,
180 transform: `translateX(${direction === "back" ? -hidden : hidden}%)`,
181 }}
182 >
183 <Icon
184 className={cn(
185 "size-4 transition-opacity duration-100",
186 armed ? "opacity-100" : "opacity-40",
187 )}
188 />
189 </div>
190 </div>
191 );