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