Skip to content

Commit efcc7dc

Browse files
committed
feat: add back and forward navigation controls
1 parent d53873b commit efcc7dc

7 files changed

Lines changed: 264 additions & 9 deletions

File tree

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,13 @@ export const make = Effect.gen(function* () {
694694
});
695695

696696
if (environment.platform === "darwin") {
697+
// Some macOS mouse drivers send Back/Forward as page-swipe gestures,
698+
// rather than DOM mouse button events.
699+
window.on("swipe", (_event, direction) => {
700+
const history = window.webContents.navigationHistory;
701+
if (direction === "left" && history.canGoBack()) history.goBack();
702+
else if (direction === "right" && history.canGoForward()) history.goForward();
703+
});
697704
window.on("enter-full-screen", () => {
698705
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
699706
});

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

Lines changed: 5 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 { NavigationHistoryControls } from "./NavigationHistoryControls";
4142
import LegacyThreadSidebar from "./LegacySidebar";
4243
import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
4344
import ThreadSidebar from "./Sidebar";
@@ -204,6 +205,7 @@ function SidebarControl() {
204205
Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
205206
</TooltipPopup>
206207
</Tooltip>
208+
<NavigationHistoryControls onBackdrop={isSidebarVisible && stageBackdropVariant !== null} />
207209
</div>
208210
);
209211
}
@@ -372,6 +374,8 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
372374
const sidebarProviderStyle = {
373375
"--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
374376
"--panel-animation-duration": `${panelAnimationDurationMs}ms`,
377+
"--workspace-titlebar-content-left":
378+
"calc(var(--workspace-controls-left) + var(--workspace-titlebar-control-size) + var(--workspace-titlebar-control-gap) + var(--workspace-history-controls-width))",
375379
...windowControlsInsetStyle,
376380
} as CSSProperties;
377381

@@ -398,7 +402,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
398402
return (
399403
<PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
400404
<SidebarProvider
401-
className="h-dvh! min-h-0!"
405+
className="h-dvh! min-h-0! [--workspace-history-controls-width:0px] md:[--workspace-history-controls-width:3.5rem]"
402406
data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
403407
defaultOpen
404408
style={sidebarProviderStyle}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import { useRouter } from "@tanstack/react-router";
3+
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
4+
import { useState, useSyncExternalStore } from "react";
5+
6+
import { shortcutLabelForCommand } from "../keybindings";
7+
import { createNavigationHistoryStore } from "../navigationHistory";
8+
import { primaryServerKeybindingsAtom } from "../state/server";
9+
import { Button } from "./ui/button";
10+
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
11+
12+
export function NavigationHistoryControls({ onBackdrop }: { onBackdrop: boolean }) {
13+
const { history } = useRouter();
14+
const [store] = useState(() => {
15+
const navigation = window.navigation;
16+
const currentEntry = navigation?.currentEntry;
17+
const forwardEntries = currentEntry ? navigation.entries().length - currentEntry.index - 1 : 0;
18+
return createNavigationHistoryStore(history, forwardEntries);
19+
});
20+
const { canGoBack, canGoForward } = useSyncExternalStore(store.subscribe, store.getSnapshot);
21+
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
22+
const controls = [
23+
["Back", "navigation.back", ArrowLeftIcon, canGoBack, () => history.back()],
24+
["Forward", "navigation.forward", ArrowRightIcon, canGoForward, () => history.forward()],
25+
] as const;
26+
27+
return (
28+
<div
29+
className="pointer-events-auto hidden items-center [-webkit-app-region:no-drag] md:flex"
30+
role="group"
31+
aria-label="Navigation history"
32+
>
33+
{controls.map(([label, command, Icon, enabled, onClick]) => {
34+
const shortcut = shortcutLabelForCommand(keybindings, command);
35+
return (
36+
<Tooltip key={command}>
37+
<TooltipTrigger render={<span className="relative flex" />}>
38+
<Button
39+
aria-label={label}
40+
disabled={!enabled}
41+
onClick={onClick}
42+
size="icon-sm"
43+
variant={onBackdrop ? "media-navigation" : "ghost"}
44+
className={onBackdrop ? "relative top-auto translate-y-0" : undefined}
45+
>
46+
<Icon />
47+
</Button>
48+
</TooltipTrigger>
49+
<TooltipPopup side="bottom">
50+
{label}
51+
{shortcut ? ` (${shortcut})` : ""}
52+
</TooltipPopup>
53+
</Tooltip>
54+
);
55+
})}
56+
</div>
57+
);
58+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { act, render } from "../../../test/render";
4+
import { MainAppLocationTracker, useNavigateToMainApp } from "./mainAppLocation";
5+
6+
function LeaveUtilityPage() {
7+
const navigateToMainApp = useNavigateToMainApp();
8+
return (
9+
<>
10+
<MainAppLocationTracker />
11+
<button type="button" onClick={() => void navigateToMainApp()}>
12+
Back to threads
13+
</button>
14+
</>
15+
);
16+
}
17+
18+
describe("leaving a utility page", () => {
19+
it("keeps the remembered entry when traversing past it without overwriting it", async () => {
20+
await using screen = await render(<LeaveUtilityPage />, { router: "/settings" });
21+
const router = screen.router!;
22+
23+
await act(() => router.navigate({ href: "/env/thread-a" }));
24+
await act(() => router.navigate({ href: "/settings/general" }));
25+
await act(() => router.history.go(-2));
26+
await act(() => router.history.go(2));
27+
await screen.getByRole("button", { name: "Back to threads" }).click();
28+
29+
expect(router.state.location.pathname).toBe("/env/thread-a");
30+
await act(() => router.history.forward());
31+
expect(router.state.location.pathname).toBe("/settings/general");
32+
});
33+
34+
it("does not traverse to a utility page that replaced the remembered entry", async () => {
35+
await using screen = await render(<LeaveUtilityPage />, { router: "/env/thread-a" });
36+
const router = screen.router!;
37+
38+
await act(() => router.navigate({ href: "/settings/general", replace: true }));
39+
await act(() => router.navigate({ href: "/usage" }));
40+
await screen.getByRole("button", { name: "Back to threads" }).click();
41+
expect(router.state.location.pathname).toBe("/env/thread-a");
42+
});
43+
44+
it("closing Settings preserves earlier threads and forward history", async () => {
45+
await using screen = await render(<LeaveUtilityPage />, { router: "/env/thread-a" });
46+
const router = screen.router!;
47+
48+
await act(() => router.navigate({ href: "/env/thread-b" }));
49+
await act(() => router.navigate({ href: "/settings/general" }));
50+
await act(() => router.navigate({ href: "/settings/appearance" }));
51+
await act(() => router.navigate({ href: "/settings/open-source-licenses" }));
52+
await screen.getByRole("button", { name: "Back to threads" }).click();
53+
expect(router.state.location.pathname).toBe("/env/thread-b");
54+
55+
await act(() => router.history.back());
56+
expect(router.state.location.pathname).toBe("/env/thread-a");
57+
await act(() => router.history.forward());
58+
expect(router.state.location.pathname).toBe("/env/thread-b");
59+
await act(() => router.history.forward());
60+
expect(router.state.location.pathname).toBe("/settings/general");
61+
});
62+
63+
it("returns to the remembered thread after its history entry is replaced", async () => {
64+
await using screen = await render(<LeaveUtilityPage />, { router: "/settings" });
65+
const router = screen.router!;
66+
67+
await act(() => router.navigate({ href: "/env/thread-a" }));
68+
await act(() => router.history.back());
69+
await act(() => router.navigate({ href: "/usage" }));
70+
await act(() => router.navigate({ href: "/settings" }));
71+
await screen.getByRole("button", { name: "Back to threads" }).click();
72+
expect(router.state.location.pathname).toBe("/env/thread-a");
73+
});
74+
});
Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useLocation, useNavigate } from "@tanstack/react-router";
1+
import { useNavigate, useRouter } from "@tanstack/react-router";
22
import { useEffect } from "react";
33

44
export function isSidebarUtilityPage(pathname: string) {
@@ -11,19 +11,44 @@ export function isSidebarUtilityPage(pathname: string) {
1111
);
1212
}
1313

14-
let mainAppHref: string | null = null;
14+
let mainAppEntry: { href: string; historyIndex: number | null } | null = null;
1515

1616
export function MainAppLocationTracker() {
17-
const href = useLocation({
18-
select: (location) => (isSidebarUtilityPage(location.pathname) ? null : location.href),
19-
});
17+
const { history } = useRouter();
2018
useEffect(() => {
21-
if (href !== null) mainAppHref = href;
22-
}, [href]);
19+
const { location } = history;
20+
if (!isSidebarUtilityPage(location.pathname)) {
21+
mainAppEntry = { href: location.href, historyIndex: location.state.__TSR_index };
22+
}
23+
return history.subscribe(({ location, action }) => {
24+
const historyIndex = location.state.__TSR_index;
25+
if (!isSidebarUtilityPage(location.pathname)) {
26+
mainAppEntry = { href: location.href, historyIndex };
27+
} else if (
28+
mainAppEntry?.historyIndex != null &&
29+
((action.type === "PUSH" && historyIndex <= mainAppEntry.historyIndex) ||
30+
(action.type === "REPLACE" && historyIndex === mainAppEntry.historyIndex))
31+
) {
32+
mainAppEntry = { href: mainAppEntry.href, historyIndex: null };
33+
}
34+
});
35+
}, [history]);
2336
return null;
2437
}
2538

2639
export function useNavigateToMainApp() {
2740
const navigate = useNavigate();
28-
return () => navigate({ href: mainAppHref ?? "/" });
41+
const router = useRouter();
42+
return () => {
43+
// Pushing the thread URL again would leave Settings in the way of earlier threads.
44+
const stepsBack =
45+
mainAppEntry?.historyIndex != null
46+
? router.history.location.state.__TSR_index - mainAppEntry.historyIndex
47+
: 0;
48+
if (stepsBack > 0) {
49+
router.history.go(-stepsBack);
50+
return;
51+
}
52+
void navigate({ href: mainAppEntry?.href ?? "/" });
53+
};
2954
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { createMemoryHistory } from "@tanstack/react-router";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { createNavigationHistoryStore } from "./navigationHistory";
5+
6+
describe("navigation history controls", () => {
7+
it("picks up navigation before the controls subscribe", () => {
8+
const history = createMemoryHistory({ initialEntries: ["/"] });
9+
const store = createNavigationHistoryStore(history);
10+
11+
history.push("/threads/one");
12+
expect(store.getSnapshot()).toEqual({ canGoBack: true, canGoForward: false });
13+
history.push("/settings");
14+
const unsubscribe = store.subscribe(() => {});
15+
try {
16+
history.back();
17+
expect(store.getSnapshot()).toEqual({ canGoBack: true, canGoForward: true });
18+
} finally {
19+
unsubscribe();
20+
}
21+
});
22+
23+
it("restores forward availability when mounting inside existing history", () => {
24+
const history = createMemoryHistory({
25+
initialEntries: ["/", "/threads/one", "/settings"],
26+
initialIndex: 1,
27+
});
28+
const store = createNavigationHistoryStore(history, 1);
29+
expect(store.getSnapshot()).toEqual({ canGoBack: true, canGoForward: true });
30+
});
31+
32+
it("keeps Forward across a replace and clears it on a new push", () => {
33+
const history = createMemoryHistory({ initialEntries: ["/"] });
34+
const store = createNavigationHistoryStore(history);
35+
const unsubscribe = store.subscribe(() => {});
36+
try {
37+
expect(store.getSnapshot()).toEqual({ canGoBack: false, canGoForward: false });
38+
history.push("/threads/one");
39+
history.push("/settings");
40+
expect(store.getSnapshot()).toEqual({ canGoBack: true, canGoForward: false });
41+
history.back();
42+
expect(store.getSnapshot()).toEqual({ canGoBack: true, canGoForward: true });
43+
history.replace("/threads/two");
44+
expect(store.getSnapshot().canGoForward).toBe(true);
45+
history.forward();
46+
expect(store.getSnapshot().canGoForward).toBe(false);
47+
history.go(-2);
48+
expect(store.getSnapshot()).toEqual({ canGoBack: false, canGoForward: true });
49+
history.push("/usage");
50+
expect(store.getSnapshot()).toEqual({ canGoBack: true, canGoForward: false });
51+
} finally {
52+
unsubscribe();
53+
}
54+
});
55+
});

‎apps/web/src/navigationHistory.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import type { RouterHistory } from "@tanstack/react-router";
2+
3+
export function createNavigationHistoryStore(history: RouterHistory, forwardEntries = 0) {
4+
// Browser history.length includes pages outside T3, so only offer Forward
5+
// for entries known to belong to this app.
6+
let lastIndex = history.location.state.__TSR_index + forwardEntries;
7+
const readSnapshot = () => ({
8+
canGoBack: history.canGoBack(),
9+
canGoForward: history.location.state.__TSR_index < lastIndex,
10+
});
11+
let snapshot = readSnapshot();
12+
const getSnapshot = () => {
13+
lastIndex = Math.max(lastIndex, history.location.state.__TSR_index);
14+
const next = readSnapshot();
15+
if (next.canGoBack !== snapshot.canGoBack || next.canGoForward !== snapshot.canGoForward) {
16+
snapshot = next;
17+
}
18+
return snapshot;
19+
};
20+
21+
return {
22+
getSnapshot,
23+
subscribe: (onChange: () => void) => {
24+
getSnapshot();
25+
return history.subscribe(({ location, action }) => {
26+
if (action.type === "PUSH") lastIndex = location.state.__TSR_index;
27+
const previous = snapshot;
28+
if (getSnapshot() !== previous) onChange();
29+
});
30+
},
31+
};
32+
}

0 commit comments

Comments
 (0)