Skip to content

Commit 476590d

Browse files
feat(desktop): back/forward buttons and trackpad swipe navigation (#27430)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 97e35bc commit 476590d

9 files changed

Lines changed: 307 additions & 5 deletions

File tree

‎apps/desktop/src/ipc/channels.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event";
1414
export const WEB_LINK_OPEN_CHANNEL = "desktop:web-link-open";
1515
export const WEB_LINK_READY_CHANNEL = "desktop:web-link-ready";
1616
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
17+
export const TRACKPAD_SCROLL_BEGIN_CHANNEL = "desktop:trackpad-scroll-begin";
1718
export const TRACKPAD_SCROLL_END_CHANNEL = "desktop:trackpad-scroll-end";
1819
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
1920
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";

‎apps/desktop/src/preload.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
9191
ipcRenderer.on(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler);
9292
return () => ipcRenderer.removeListener(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler);
9393
},
94+
onTrackpadScrollBegin: (listener) => {
95+
const handler = () => listener();
96+
ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_BEGIN_CHANNEL, handler);
97+
return () => ipcRenderer.removeListener(IpcChannels.TRACKPAD_SCROLL_BEGIN_CHANNEL, handler);
98+
},
9499
onTrackpadScrollEnd: (listener) => {
95100
const handler = () => listener();
96101
ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler);

‎apps/desktop/src/window/DesktopWindow.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
MENU_ACTION_CHANNEL,
2424
QUIT_SHORTCUT_CHANNEL,
2525
SNAP_SHOT_EVENT_CHANNEL,
26+
TRACKPAD_SCROLL_BEGIN_CHANNEL,
2627
TRACKPAD_SCROLL_END_CHANNEL,
2728
WINDOW_FULLSCREEN_STATE_CHANNEL,
2829
} from "../ipc/channels.ts";
@@ -652,7 +653,11 @@ export const make = Effect.gen(function* () {
652653
}
653654
});
654655
window.webContents.on("input-event", (_event, input) => {
655-
if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
656+
if (input.type === "gestureScrollBegin") {
657+
window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL);
658+
} else if (input.type === "gestureScrollEnd") {
659+
window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
660+
}
656661
});
657662
// Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event.
658663
window.webContents.on("zoom-changed", (_event, direction) => {

‎apps/web/src/components/AppSidebarLayout.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
usePanelNavigationSuppression,
3939
} from "../panelAnimations";
4040
import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
41+
import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
4142
import ThreadSidebar from "./Sidebar";
4243
import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";
4344
import { isAppModalPage } from "./sidebar/mainAppLocation";
@@ -449,7 +450,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
449450
defaultOpen
450451
style={sidebarProviderStyle}
451452
>
452-
<SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
453+
<SidebarBrandWidthProbe isElectron={isElectron} onWidthChange={setBrandWidth} />
453454
<Sidebar
454455
side="left"
455456
collapsible="offcanvas"
@@ -474,6 +475,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
474475
{children}
475476
<BackgroundThreadAnnouncer />
476477
<SidebarControl />
478+
{isElectron ? <HistorySwipeNavigation /> : null}
477479
</SidebarProvider>
478480
</PanelAnimationSuppressionProvider>
479481
);
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { isMomentumTail } from "./HistorySwipeNavigation";
4+
5+
describe("isMomentumTail", () => {
6+
it.each([
7+
["steady momentum decay", [40, 37, 34, 31.3, 28.8], true],
8+
["fingers still moving", [12, 18, 9, 15, 11], false],
9+
["fingers slowing unevenly", [30, 22, 20, 12, 11], false],
10+
["reversing", [10, 8, 6, 4, -2], false],
11+
["too few samples", [40, 37, 34], false],
12+
])("%s", (_name, deltas, expected) => {
13+
expect(isMomentumTail(deltas)).toBe(expected);
14+
});
15+
});
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
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+
}

‎apps/web/src/components/sidebar/SidebarChrome.tsx‎

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
1-
import { ArrowLeftIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react";
1+
import { ArrowLeftIcon, ArrowRightIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react";
22
import type { ReactNode } from "react";
33
import { memo } from "react";
44
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
55

6+
import { useAtomValue } from "@effect/atom-react";
67
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
8+
import { shortcutLabelForCommand } from "../../keybindings";
9+
import {
10+
navigateHistory,
11+
useCanNavigateHistory,
12+
type HistoryDirection,
13+
} from "../../navigationHistory";
14+
import { primaryServerKeybindingsAtom } from "../../state/server";
715
import { cn } from "../../lib/utils";
816
import { usePullRequestsSupported } from "../../state/environments";
917
import { T3Wordmark } from "../T3Wordmark";
@@ -14,6 +22,7 @@ import {
1422
useEnvironmentStageLabel,
1523
} from "../SidebarStageBackdrop";
1624
import { Badge } from "../ui/badge";
25+
import { Button } from "../ui/button";
1726
import {
1827
SidebarFooter,
1928
SidebarMenu,
@@ -63,7 +72,15 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
6372
/>
6473
</div>
6574
<div className="relative z-10 flex h-8 min-w-0 flex-1 flex-wrap content-start items-center gap-x-2 overflow-hidden py-0.5">
66-
<SidebarBrand onBackdrop={backdropVariant !== null} />
75+
<div className="flex shrink-0 items-center gap-1">
76+
<SidebarBrand onBackdrop={backdropVariant !== null} />
77+
{isElectron ? (
78+
<div className="hidden items-center md:flex">
79+
<HistoryNavigationButton direction="back" onBackdrop={backdropVariant !== null} />
80+
<HistoryNavigationButton direction="forward" onBackdrop={backdropVariant !== null} />
81+
</div>
82+
) : null}
83+
</div>
6784
{pillLabel ? (
6885
<div className="ml-1 flex h-7 items-center">
6986
<Badge data-environment-identification="pill" size="sm" variant="secondary">
@@ -77,8 +94,10 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
7794
});
7895

7996
export function SidebarBrandWidthProbe({
97+
isElectron,
8098
onWidthChange,
8199
}: {
100+
isElectron: boolean;
82101
onWidthChange: (width: number) => void;
83102
}) {
84103
const observeWidth = (probe: HTMLDivElement) => {
@@ -93,13 +112,56 @@ export function SidebarBrandWidthProbe({
93112
className="pointer-events-none invisible fixed top-0 left-0 flex w-max border-r border-transparent pr-3"
94113
ref={observeWidth}
95114
>
96-
<div className="ml-[var(--workspace-titlebar-content-left)] flex">
115+
<div className="ml-[var(--workspace-titlebar-content-left)] flex gap-1">
97116
<SidebarBrandMark onBackdrop={false} />
117+
{isElectron ? <div className="w-[calc(2*var(--workspace-titlebar-control-size))]" /> : null}
98118
</div>
99119
</div>
100120
);
101121
}
102122

123+
function HistoryNavigationButton({
124+
direction,
125+
onBackdrop,
126+
}: {
127+
direction: HistoryDirection;
128+
onBackdrop: boolean;
129+
}) {
130+
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
131+
const enabled = useCanNavigateHistory(direction);
132+
const label = direction === "back" ? "Go back" : "Go forward";
133+
const shortcutLabel = shortcutLabelForCommand(
134+
keybindings,
135+
direction === "back" ? "navigation.back" : "navigation.forward",
136+
);
137+
const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon;
138+
return (
139+
<Tooltip>
140+
<TooltipTrigger
141+
render={
142+
<Button
143+
aria-label={label}
144+
className={cn(
145+
"[-webkit-app-region:no-drag]",
146+
onBackdrop && "relative top-auto translate-y-0",
147+
)}
148+
disabled={!enabled}
149+
onClick={() => navigateHistory(direction)}
150+
size="icon-sm"
151+
variant={onBackdrop ? "media-navigation" : "ghost"}
152+
/>
153+
}
154+
>
155+
<Icon className="size-3.5" />
156+
</TooltipTrigger>
157+
<TooltipPopup side="bottom">
158+
{label}
159+
{shortcutLabel ? ` (${shortcutLabel})` : ""}
160+
</TooltipPopup>
161+
</Tooltip>
162+
);
163+
}
164+
103165
function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
104166
return (
105167
<Link

0 commit comments

Comments
 (0)