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

HistorySwipeNavigation.tsx

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