Skip to content
TypeScript

feat(desktop): back/forward buttons and trackpad swipe navigation (#27430)

Julius Marminge476590d0aded
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index bba4f6449b8..538dd06b0b4 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -14,6 +14,7 @@ export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event";
export const WEB_LINK_OPEN_CHANNEL = "desktop:web-link-open";
export const WEB_LINK_READY_CHANNEL = "desktop:web-link-ready";
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
+export const TRACKPAD_SCROLL_BEGIN_CHANNEL = "desktop:trackpad-scroll-begin";
export const TRACKPAD_SCROLL_END_CHANNEL = "desktop:trackpad-scroll-end";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 965b7db5d6d..950ed972c64 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -91,6 +91,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.on(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler);
return () => ipcRenderer.removeListener(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler);
},
+ onTrackpadScrollBegin: (listener) => {
+ const handler = () => listener();
+ ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_BEGIN_CHANNEL, handler);
+ return () => ipcRenderer.removeListener(IpcChannels.TRACKPAD_SCROLL_BEGIN_CHANNEL, handler);
+ },
onTrackpadScrollEnd: (listener) => {
const handler = () => listener();
ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler);
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index ab5fc8be26a..c1c0cf5446c 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -23,6 +23,7 @@ import {
MENU_ACTION_CHANNEL,
QUIT_SHORTCUT_CHANNEL,
SNAP_SHOT_EVENT_CHANNEL,
+ TRACKPAD_SCROLL_BEGIN_CHANNEL,
TRACKPAD_SCROLL_END_CHANNEL,
WINDOW_FULLSCREEN_STATE_CHANNEL,
} from "../ipc/channels.ts";
@@ -652,7 +653,11 @@ export const make = Effect.gen(function* () {
}
});
window.webContents.on("input-event", (_event, input) => {
- if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
+ if (input.type === "gestureScrollBegin") {
+ window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL);
+ } else if (input.type === "gestureScrollEnd") {
+ window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL);
+ }
});
// Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event.
window.webContents.on("zoom-changed", (_event, direction) => {
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx
index 6c8837e63f4..91df5616f7f 100644
--- a/apps/web/src/components/AppSidebarLayout.tsx
+++ b/apps/web/src/components/AppSidebarLayout.tsx
@@ -38,6 +38,7 @@ import {
usePanelNavigationSuppression,
} from "../panelAnimations";
import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
+import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
import ThreadSidebar from "./Sidebar";
import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";
import { isAppModalPage } from "./sidebar/mainAppLocation";
@@ -449,7 +450,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
defaultOpen
style={sidebarProviderStyle}
>
- <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
+ <SidebarBrandWidthProbe isElectron={isElectron} onWidthChange={setBrandWidth} />
<Sidebar
side="left"
collapsible="offcanvas"
@@ -474,6 +475,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
{children}
<BackgroundThreadAnnouncer />
<SidebarControl />
+ {isElectron ? <HistorySwipeNavigation /> : null}
</SidebarProvider>
</PanelAnimationSuppressionProvider>
);
diff --git a/apps/web/src/components/HistorySwipeNavigation.test.ts b/apps/web/src/components/HistorySwipeNavigation.test.ts
new file mode 100644
index 00000000000..9eef35f0dc6
--- /dev/null
+++ b/apps/web/src/components/HistorySwipeNavigation.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { isMomentumTail } from "./HistorySwipeNavigation";
+
+describe("isMomentumTail", () => {
+ it.each([
+ ["steady momentum decay", [40, 37, 34, 31.3, 28.8], true],
+ ["fingers still moving", [12, 18, 9, 15, 11], false],
+ ["fingers slowing unevenly", [30, 22, 20, 12, 11], false],
+ ["reversing", [10, 8, 6, 4, -2], false],
+ ["too few samples", [40, 37, 34], false],
+ ])("%s", (_name, deltas, expected) => {
+ expect(isMomentumTail(deltas)).toBe(expected);
+ });
+});
diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx
new file mode 100644
index 00000000000..c020878b253
--- /dev/null
+++ b/apps/web/src/components/HistorySwipeNavigation.tsx
@@ -0,0 +1,189 @@
+import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+
+import { cn } from "../lib/utils";
+import { canNavigateHistory, navigateHistory, type HistoryDirection } from "../navigationHistory";
+
+const SWIPE_TRIGGER_DISTANCE = 120;
+// Movement needed before the gesture picks an axis; first events are often diagonal.
+const SWIPE_AXIS_LOCK_DISTANCE = 8;
+const MOMENTUM_SAMPLE_SIZE = 5;
+
+type SwipeBounds = { left: number; top: number; width: number; height: number };
+type SwipeGesture =
+ | { kind: "pending"; target: EventTarget | null; y: number; sumX: number; sumY: number }
+ | {
+ kind: "tracking";
+ direction: HistoryDirection;
+ distance: number;
+ deltas: number[];
+ y: number;
+ bounds: SwipeBounds;
+ }
+ // Not a swipe, or one already decided: the rest of its events are ignored.
+ | { kind: "ignored" };
+type SwipeIndicatorState = {
+ direction: HistoryDirection;
+ progress: number;
+ y: number;
+ bounds: SwipeBounds;
+ tracking: boolean;
+};
+
+function readMainContentBounds(): SwipeBounds {
+ const main = document.querySelector('[data-slot="sidebar-inset"]');
+ if (!main) return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };
+ const { left, top, width, height } = main.getBoundingClientRect();
+ return { left, top, width, height };
+}
+
+function canScrollHorizontally(target: EventTarget | null, deltaX: number): boolean {
+ for (
+ let element = target instanceof Element ? target : null;
+ element;
+ element = element.parentElement
+ ) {
+ if (element.scrollWidth <= element.clientWidth) continue;
+ const { overflowX } = getComputedStyle(element);
+ if (overflowX !== "auto" && overflowX !== "scroll") continue;
+ const canScroll =
+ deltaX < 0
+ ? element.scrollLeft > 0
+ : element.scrollLeft + element.clientWidth < element.scrollWidth - 1;
+ if (canScroll) return true;
+ }
+ return false;
+}
+
+function lockSwipeAxis(
+ pending: Extract<SwipeGesture, { kind: "pending" }>,
+): Exclude<SwipeGesture, { kind: "pending" }> {
+ const { target, sumX, sumY } = pending;
+ if (Math.abs(sumX) <= Math.abs(sumY)) return { kind: "ignored" };
+ if (target instanceof Element && target.closest('[role="dialog"]')) return { kind: "ignored" };
+ if (canScrollHorizontally(target, sumX)) return { kind: "ignored" };
+ const direction = sumX < 0 ? "back" : "forward";
+ if (!canNavigateHistory(direction)) return { kind: "ignored" };
+ return {
+ kind: "tracking",
+ direction,
+ distance: Math.abs(sumX),
+ deltas: [],
+ y: pending.y,
+ bounds: readMainContentBounds(),
+ };
+}
+
+/**
+ * macOS momentum after the fingers lift decays by a near-constant ratio per
+ * event; finger movement is noisier. Deltas are signed along the swipe.
+ */
+export function isMomentumTail(deltas: readonly number[]): boolean {
+ if (deltas.length < MOMENTUM_SAMPLE_SIZE) return false;
+ const recent = deltas.slice(-MOMENTUM_SAMPLE_SIZE);
+ if (recent.some((delta) => delta <= 0)) return false;
+ const ratios = recent.slice(1).map((delta, index) => delta / recent[index]!);
+ return (
+ ratios.every((ratio) => ratio >= 0.7 && ratio < 1) &&
+ Math.max(...ratios) - Math.min(...ratios) < 0.1
+ );
+}
+
+/** Two-finger horizontal trackpad swipes go back and forward, like a browser. */
+export function HistorySwipeNavigation() {
+ const [swipe, setSwipe] = useState<SwipeIndicatorState | null>(null);
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window wheel and desktop gesture listeners track trackpad swipes
+ useEffect(() => {
+ let gesture: SwipeGesture | null = null;
+ const hideIndicator = () =>
+ setSwipe((current) => (current === null ? null : { ...current, tracking: false }));
+ // The fingers lifted: navigate if the swipe went far enough, then ignore its momentum.
+ const release = () => {
+ if (gesture?.kind === "tracking" && gesture.distance >= SWIPE_TRIGGER_DISTANCE) {
+ navigateHistory(gesture.direction);
+ }
+ gesture = { kind: "ignored" };
+ hideIndicator();
+ };
+ // Chromium brackets each trackpad scroll, momentum included, with these.
+ const unsubscribeScrollBegin = window.desktopBridge?.onTrackpadScrollBegin(() => {
+ if (gesture?.kind === "ignored") gesture = null;
+ });
+ const unsubscribeScrollEnd = window.desktopBridge?.onTrackpadScrollEnd(() => {
+ if (gesture?.kind === "tracking") release();
+ gesture = null;
+ });
+ const onWheel = (event: WheelEvent) => {
+ if (gesture === null) {
+ gesture =
+ event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL
+ ? { kind: "ignored" }
+ : { kind: "pending", target: event.target, y: event.clientY, sumX: 0, sumY: 0 };
+ }
+ if (gesture.kind === "ignored") return;
+ if (gesture.kind === "pending") {
+ gesture.sumX += event.deltaX;
+ gesture.sumY += event.deltaY;
+ if (Math.abs(gesture.sumX) + Math.abs(gesture.sumY) < SWIPE_AXIS_LOCK_DISTANCE) return;
+ gesture = lockSwipeAxis(gesture);
+ if (gesture.kind === "ignored") return;
+ } else {
+ const delta = gesture.direction === "back" ? -event.deltaX : event.deltaX;
+ if (event.deltaX === 0 && event.deltaY === 0) return release();
+ gesture.deltas = [...gesture.deltas.slice(1 - MOMENTUM_SAMPLE_SIZE), delta];
+ if (isMomentumTail(gesture.deltas)) return release();
+ gesture.distance = Math.max(0, gesture.distance + delta);
+ }
+ setSwipe({
+ direction: gesture.direction,
+ progress: Math.min(1, gesture.distance / SWIPE_TRIGGER_DISTANCE),
+ y: gesture.y,
+ bounds: gesture.bounds,
+ tracking: true,
+ });
+ };
+ window.addEventListener("wheel", onWheel, { capture: true, passive: true });
+ return () => {
+ unsubscribeScrollBegin?.();
+ unsubscribeScrollEnd?.();
+ window.removeEventListener("wheel", onWheel, { capture: true });
+ };
+ }, []);
+
+ return swipe === null ? null : <SwipeIndicator {...swipe} />;
+}
+
+// A circle pinned to the edge of the main content that peeks in up to half its width.
+function SwipeIndicator({ direction, progress, y, bounds, tracking }: SwipeIndicatorState) {
+ const armed = progress >= 1;
+ const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon;
+ const hidden = 100 - progress * 50;
+ return (
+ <div
+ aria-hidden="true"
+ className="pointer-events-none fixed z-100 overflow-hidden"
+ style={bounds}
+ >
+ <div
+ className={cn(
+ "absolute flex size-14 items-center rounded-full bg-muted text-foreground dark:bg-black dark:text-white",
+ direction === "back" ? "left-0 justify-end pr-2" : "right-0 justify-start pl-2",
+ !tracking && "transition-[opacity,transform] duration-200 ease-out",
+ )}
+ style={{
+ top: `clamp(0px, calc(${y - bounds.top}px - 1.75rem), calc(100% - 3.5rem))`,
+ opacity: tracking ? 1 : 0,
+ transform: `translateX(${direction === "back" ? -hidden : hidden}%)`,
+ }}
+ >
+ <Icon
+ className={cn(
+ "size-4 transition-opacity duration-100",
+ armed ? "opacity-100" : "opacity-40",
+ )}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx
index b136d47fd9c..dd41ddd2a02 100644
--- a/apps/web/src/components/sidebar/SidebarChrome.tsx
+++ b/apps/web/src/components/sidebar/SidebarChrome.tsx
@@ -1,9 +1,17 @@
-import { ArrowLeftIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react";
+import { ArrowLeftIcon, ArrowRightIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react";
import type { ReactNode } from "react";
import { memo } from "react";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
+import { useAtomValue } from "@effect/atom-react";
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
+import { shortcutLabelForCommand } from "../../keybindings";
+import {
+ navigateHistory,
+ useCanNavigateHistory,
+ type HistoryDirection,
+} from "../../navigationHistory";
+import { primaryServerKeybindingsAtom } from "../../state/server";
import { cn } from "../../lib/utils";
import { usePullRequestsSupported } from "../../state/environments";
import { T3Wordmark } from "../T3Wordmark";
@@ -14,6 +22,7 @@ import {
useEnvironmentStageLabel,
} from "../SidebarStageBackdrop";
import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
import {
SidebarFooter,
SidebarMenu,
@@ -63,7 +72,15 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
/>
</div>
<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">
- <SidebarBrand onBackdrop={backdropVariant !== null} />
+ <div className="flex shrink-0 items-center gap-1">
+ <SidebarBrand onBackdrop={backdropVariant !== null} />
+ {isElectron ? (
+ <div className="hidden items-center md:flex">
+ <HistoryNavigationButton direction="back" onBackdrop={backdropVariant !== null} />
+ <HistoryNavigationButton direction="forward" onBackdrop={backdropVariant !== null} />
+ </div>
+ ) : null}
+ </div>
{pillLabel ? (
<div className="ml-1 flex h-7 items-center">
<Badge data-environment-identification="pill" size="sm" variant="secondary">
@@ -77,8 +94,10 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
});
export function SidebarBrandWidthProbe({
+ isElectron,
onWidthChange,
}: {
+ isElectron: boolean;
onWidthChange: (width: number) => void;
}) {
const observeWidth = (probe: HTMLDivElement) => {
@@ -93,13 +112,56 @@ export function SidebarBrandWidthProbe({
className="pointer-events-none invisible fixed top-0 left-0 flex w-max border-r border-transparent pr-3"
ref={observeWidth}
>
- <div className="ml-[var(--workspace-titlebar-content-left)] flex">
+ <div className="ml-[var(--workspace-titlebar-content-left)] flex gap-1">
<SidebarBrandMark onBackdrop={false} />
+ {isElectron ? <div className="w-[calc(2*var(--workspace-titlebar-control-size))]" /> : null}
</div>
</div>
);
}
+function HistoryNavigationButton({
+ direction,
+ onBackdrop,
+}: {
+ direction: HistoryDirection;
+ onBackdrop: boolean;
+}) {
+ const keybindings = useAtomValue(primaryServerKeybindingsAtom);
+ const enabled = useCanNavigateHistory(direction);
+ const label = direction === "back" ? "Go back" : "Go forward";
+ const shortcutLabel = shortcutLabelForCommand(
+ keybindings,
+ direction === "back" ? "navigation.back" : "navigation.forward",
+ );
+ const Icon = direction === "back" ? ArrowLeftIcon : ArrowRightIcon;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-label={label}
+ className={cn(
+ "[-webkit-app-region:no-drag]",
+ onBackdrop && "relative top-auto translate-y-0",
+ )}
+ disabled={!enabled}
+ onClick={() => navigateHistory(direction)}
+ size="icon-sm"
+ variant={onBackdrop ? "media-navigation" : "ghost"}
+ />
+ }
+ >
+ <Icon className="size-3.5" />
+ </TooltipTrigger>
+ <TooltipPopup side="bottom">
+ {label}
+ {shortcutLabel ? ` (${shortcutLabel})` : ""}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
return (
<Link
diff --git a/apps/web/src/navigationHistory.ts b/apps/web/src/navigationHistory.ts
new file mode 100644
index 00000000000..e062bb8fd76
--- /dev/null
+++ b/apps/web/src/navigationHistory.ts
@@ -0,0 +1,22 @@
+import { useSyncExternalStore } from "react";
+
+export type HistoryDirection = "back" | "forward";
+
+function subscribeToNavigationHistory(onChange: () => void): () => void {
+ window.navigation.addEventListener("currententrychange", onChange);
+ return () => window.navigation.removeEventListener("currententrychange", onChange);
+}
+
+export function canNavigateHistory(direction: HistoryDirection): boolean {
+ return direction === "back" ? window.navigation.canGoBack : window.navigation.canGoForward;
+}
+
+export function navigateHistory(direction: HistoryDirection) {
+ if (direction === "back") window.history.back();
+ else window.history.forward();
+}
+
+/** Only for Electron: the Navigation API is Chromium-only. */
+export function useCanNavigateHistory(direction: HistoryDirection): boolean {
+ return useSyncExternalStore(subscribeToNavigationHistory, () => canNavigateHistory(direction));
+}
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index f460619f113..f14452fec5a 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -1018,6 +1018,7 @@ export interface DesktopBridge {
getClientPlatform: () => string;
setNotificationBadge: (badge: { count: number; image: string | null }) => Promise<void>;
onNotificationBadgeClear: (listener: () => void) => () => void;
+ onTrackpadScrollBegin: (listener: () => void) => () => void;
onTrackpadScrollEnd: (listener: () => void) => () => void;
/**
* Renderer `window.focus()` cannot raise an Electron window, and on Wayland