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

HistorySwipeNavigation.tsx

188 lines7.2 KB

1import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
2import { useEffect, useState } from "react";
3​
4import { cn } 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/** Two-finger horizontal trackpad swipes go back and forward, like a browser. */
92export function HistorySwipeNavigation() {
93 const [swipe, setSwipe] = useState<SwipeIndicatorState | null>(null);
94​
95 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window wheel and desktop gesture listeners track trackpad swipes
96 useEffect(() => {
97 let gesture: SwipeGesture | null = null;
98 const hideIndicator = () =>
99 setSwipe((current) => (current === null ? null : { ...current, tracking: false }));
100 // The fingers lifted: navigate if the swipe went far enough, then ignore its momentum.
101 const release = () => {
102 if (gesture?.kind === "tracking" && gesture.distance >= SWIPE_TRIGGER_DISTANCE) {
103 navigateHistory(gesture.direction);
104 }
105 gesture = { kind: "ignored" };
106 hideIndicator();
107 };
108 // Chromium brackets each trackpad scroll, momentum included, with these.
109 const unsubscribeScrollBegin = window.desktopBridge?.onTrackpadScrollBegin(() => {
110 if (gesture?.kind === "ignored") gesture = null;
111 });
112 const unsubscribeScrollEnd = window.desktopBridge?.onTrackpadScrollEnd(() => {
113 if (gesture?.kind === "tracking") release();
114 gesture = null;
115 });
116 const onWheel = (event: WheelEvent) => {
117 if (gesture === null) {
118 gesture =
119 event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL
120 ? { kind: "ignored" }
121 : { kind: "pending", path: event.composedPath(), y: event.clientY, sumX: 0, sumY: 0 };
122 }
123 if (gesture.kind === "ignored") return;
124 if (gesture.kind === "pending") {
125 gesture.sumX += event.deltaX;
126 gesture.sumY += event.deltaY;
127 if (Math.abs(gesture.sumX) + Math.abs(gesture.sumY) < SWIPE_AXIS_LOCK_DISTANCE) return;
128 gesture = lockSwipeAxis({ ...gesture, path: [...gesture.path, ...event.composedPath()] });
129 if (gesture.kind === "ignored") return;
130 } else {
131 const delta = gesture.direction === "back" ? -event.deltaX : event.deltaX;
132 if (event.deltaX === 0 && event.deltaY === 0) return release();
133 gesture.deltas = [...gesture.deltas.slice(1 - MOMENTUM_SAMPLE_SIZE), delta];
134 if (isMomentumTail(gesture.deltas)) return release();
135 gesture.distance = Math.max(0, gesture.distance + delta);
136 }
137 setSwipe({
138 direction: gesture.direction,
139 progress: Math.min(1, gesture.distance / SWIPE_TRIGGER_DISTANCE),
140 y: gesture.y,
141 bounds: gesture.bounds,
142 tracking: true,
143 });
144 };
145 window.addEventListener("wheel", onWheel, { capture: true, passive: true });
146 return () => {
147 unsubscribeScrollBegin?.();
148 unsubscribeScrollEnd?.();
149 window.removeEventListener("wheel", onWheel, { capture: true });
150 };
151 }, []);
152​
153 return swipe === null ? null : <SwipeIndicator {...swipe} />;
155​
156// A circle pinned to the edge of the main content that peeks in up to half its width.
157function SwipeIndicator({ direction, progress, y, bounds, tracking }: SwipeIndicatorState) {
158 const armed = progress >= 1;
159 const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon;
160 const hidden = 100 - progress * 50;
161 return (
162 <div
163 aria-hidden="true"
164 className="pointer-events-none fixed z-100 overflow-hidden"
165 style={bounds}
166 >
167 <div
168 className={cn(
169 "absolute flex size-14 items-center rounded-full bg-muted text-foreground dark:bg-black dark:text-white",
170 direction === "back" ? "left-0 justify-end pr-2" : "right-0 justify-start pl-2",
171 !tracking && "transition-[opacity,transform] duration-200 ease-out",
172 )}
173 style={{
174 top: `clamp(0px, calc(${y - bounds.top}px - 1.75rem), calc(100% - 3.5rem))`,
175 opacity: tracking ? 1 : 0,
176 transform: `translateX(${direction === "back" ? -hidden : hidden}%)`,
177 }}
178 >
179 <Icon
180 className={cn(
181 "size-4 transition-opacity duration-100",
182 armed ? "opacity-100" : "opacity-40",
183 )}
184 />
185 </div>
186 </div>
187 );