Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 78 additions & 5 deletions apps/web/src/components/AppSidebarLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ import {
type CSSProperties,
type ReactNode,
} from "react";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
useCanGoBack,
useLocation,
useNavigate,
useParams,
useRouter,
} from "@tanstack/react-router";
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";

import { isElectron } from "../env";
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
Expand All @@ -24,6 +31,7 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { resolveThreadRouteRef } from "../threadRoutes";
import { cn, isMacPlatform } from "../lib/utils";
import { useCanGoForward } from "../navigationHistory";
import { primaryServerKeybindingsAtom } from "../state/server";
import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
import {
Expand Down Expand Up @@ -55,6 +63,7 @@ import {
useSidebar,
useSidebarVisibility,
} from "./ui/sidebar";
import { Button } from "./ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";

const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
Expand Down Expand Up @@ -92,6 +101,9 @@ function SidebarControl() {
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
context: { usagePageOpen },
});
// Over the stage artwork the controls sit on imagery, like the media viewer's
// arrows; that variant positions itself, so the layout is reset here.
const onStageBackdrop = isSidebarVisible && stageBackdropVariant !== null;

useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
Expand Down Expand Up @@ -139,12 +151,10 @@ function SidebarControl() {
<TooltipTrigger
render={
<SidebarTrigger
// Over the stage artwork the trigger is a control on imagery, like the media
// viewer's arrows; that variant positions itself, so the layout is reset here.
variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
variant={onStageBackdrop ? "media-navigation" : "ghost"}
className={cn(
"pointer-events-auto",
isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
onStageBackdrop && "relative top-auto translate-y-0",
)}
aria-label="Toggle main sidebar"
/>
Expand All @@ -154,6 +164,62 @@ function SidebarControl() {
Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
</TooltipPopup>
</Tooltip>
{/* Browsers bring their own Back and Forward buttons; the desktop window has none. */}
{isElectron ? <NavigationHistoryControls onStageBackdrop={onStageBackdrop} /> : null}
</div>
);
}

// Titlebar Back and Forward buttons, the clickable form of navigation.back/forward.
function NavigationHistoryControls({ onStageBackdrop }: { onStageBackdrop: boolean }) {
const { history } = useRouter();
const canGoBack = useCanGoBack();
const canGoForward = useCanGoForward();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const controls = [
{
label: "Back",
command: "navigation.back",
icon: <ArrowLeftIcon />,
enabled: canGoBack,
go: () => history.back(),
},
{
label: "Forward",
command: "navigation.forward",
icon: <ArrowRightIcon />,
enabled: canGoForward,
go: () => history.forward(),
},
] as const;

return (
<div className="pointer-events-auto ml-0.5 flex items-center gap-0.5 [-webkit-app-region:no-drag]">
{controls.map(({ label, command, icon, enabled, go }) => {
const shortcutLabel = shortcutLabelForCommand(keybindings, command);
return (
<Tooltip key={command}>
<TooltipTrigger
render={
<Button
aria-label={label}
className={onStageBackdrop ? "relative top-auto translate-y-0" : undefined}
disabled={!enabled}
onClick={go}
size="icon-sm"
variant={onStageBackdrop ? "media-navigation" : "ghost"}
>
{icon}
</Button>
}
/>
<TooltipPopup side="bottom">
{label}
{shortcutLabel ? ` (${shortcutLabel})` : ""}
</TooltipPopup>
</Tooltip>
);
})}
</div>
);
}
Expand Down Expand Up @@ -258,6 +324,13 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
...(isMacosDesktop && !isWindowFullscreen
? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
: {}),
// Titlebar content clears the sidebar toggle plus the Back and Forward controls.
...(isElectron
? {
"--workspace-titlebar-content-left":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tailwind in the owning component: This static titlebar inset belongs in a conditional Tailwind arbitrary-property class on the sidebar provider, rather than in sidebarProviderStyle.

Posted via Macroscope — UI Consistency

"calc(var(--workspace-controls-left) + 3 * var(--workspace-titlebar-control-size) + 2 * 0.125rem + var(--workspace-titlebar-control-gap))",
}
: {}),
} as CSSProperties;

useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/sidebar/SidebarChrome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
<Link
aria-label="Go to threads"
className={cn(
"relative z-10 ml-[var(--workspace-titlebar-content-left)] hidden h-7 w-fit min-w-0 shrink-0 items-center overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2 md:flex",
"relative z-10 ml-[var(--workspace-titlebar-content-left)] hidden h-7 w-fit min-w-0 shrink items-center overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2 md:flex",
onBackdrop ? "text-white" : "text-foreground",
)}
to="/"
Expand Down
86 changes: 86 additions & 0 deletions apps/web/src/navigationHistory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { createMemoryHistory } from "@tanstack/react-router";
import { describe, expect, it } from "vite-plus/test";

import { canGoForward, trackNavigationHistory } from "./navigationHistory";

function memoryStorage(): Storage {
const values = new Map<string, string>();
return {
get length() {
return values.size;
},
clear: () => values.clear(),
getItem: (key) => values.get(key) ?? null,
key: (index) => [...values.keys()][index] ?? null,
removeItem: (key) => void values.delete(key),
setItem: (key, value) => void values.set(key, value),
};
}

function trackedHistory(storage = memoryStorage()) {
const history = createMemoryHistory({ initialEntries: ["/"] });
trackNavigationHistory(history, () => storage);
return history;
}

describe("canGoForward", () => {
it("allows Forward only after going back", () => {
const history = trackedHistory();
history.push("/a");
history.push("/b");
expect(canGoForward(history)).toBe(false);

history.back();
history.back();
expect(canGoForward(history)).toBe(true);

history.forward();
expect(canGoForward(history)).toBe(true);
history.forward();
expect(canGoForward(history)).toBe(false);
});

it("drops Forward entries when a new page is pushed", () => {
const history = trackedHistory();
history.push("/a");
history.push("/b");
history.back();
history.push("/c");
expect(canGoForward(history)).toBe(false);
});

it("keeps Forward entries across a replace", () => {
const history = trackedHistory();
history.push("/a");
history.back();
history.replace("/home");
expect(canGoForward(history)).toBe(true);
});

it("does not offer Forward for an untracked history", () => {
const history = createMemoryHistory({ initialEntries: ["/"] });
history.push("/a");
history.back();
expect(canGoForward(history)).toBe(false);
});

it("restores Forward after a reload of the same entry", () => {
const storage = memoryStorage();
const history = createMemoryHistory({ initialEntries: ["/"] });
storage.setItem(
"t3code:navigation-furthest-index",
JSON.stringify({ key: history.location.state.__TSR_key, furthest: 2 }),
);
trackNavigationHistory(history, () => storage);
expect(canGoForward(history)).toBe(true);
});

it("ignores a stored position from a different entry", () => {
const storage = memoryStorage();
storage.setItem(
"t3code:navigation-furthest-index",
JSON.stringify({ key: "another-entry", furthest: 2 }),
);
expect(canGoForward(trackedHistory(storage))).toBe(false);
});
});
69 changes: 69 additions & 0 deletions apps/web/src/navigationHistory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { useRouter, type RouterHistory } from "@tanstack/react-router";
import { useSyncExternalStore } from "react";

// Browsers expose how far back history goes (TanStack's `__TSR_index`) but not
// how far forward it goes. Each history remembers the furthest entry reached
// since its latest push, so the Forward control knows whether it has anywhere
// to go. Start tracking before the first navigation with `trackNavigationHistory`.
// The position lives in sessionStorage because a reload keeps the window's
// forward entries.
const FURTHEST_INDEX_KEY = "t3code:navigation-furthest-index";

const furthestIndexByHistory = new WeakMap<RouterHistory, { furthest: number }>();

function currentIndex(history: RouterHistory): number | null {
const index = history.location.state.__TSR_index;
return Number.isInteger(index) ? index : null;
}

// Stored with the current entry's key, so only a reload of that same entry reuses it.
function readStoredIndex(history: RouterHistory, getStorage: () => Storage): number | null {
try {
const stored = JSON.parse(getStorage().getItem(FURTHEST_INDEX_KEY) ?? "{}") as {
key?: unknown;
furthest?: unknown;
};
const { key, furthest } = stored;
return key === history.location.state.__TSR_key && Number.isInteger(furthest)
? Number(furthest)
: null;
} catch {
return null;
}
}

function storeIndex(history: RouterHistory, getStorage: () => Storage, furthest: number) {
try {
const key = history.location.state.__TSR_key;
getStorage().setItem(FURTHEST_INDEX_KEY, JSON.stringify({ key, furthest }));
} catch {
// Without storage, Forward still works until the next reload.
}
}

export function trackNavigationHistory(
history: RouterHistory,
getStorage: () => Storage = () => window.sessionStorage,
) {
if (furthestIndexByHistory.has(history)) return;
const index = currentIndex(history) ?? 0;
const tracked = { furthest: Math.max(index, readStoredIndex(history, getStorage) ?? index) };
furthestIndexByHistory.set(history, tracked);
history.subscribe(({ action }) => {
const index = currentIndex(history);
if (index === null) return;
tracked.furthest = action.type === "PUSH" ? index : Math.max(tracked.furthest, index);
storeIndex(history, getStorage, tracked.furthest);
});
}

export function canGoForward(history: RouterHistory): boolean {
const tracked = furthestIndexByHistory.get(history);
const index = currentIndex(history);
return tracked !== undefined && index !== null && index < tracked.furthest;
}

export function useCanGoForward(): boolean {
const { history } = useRouter();
return useSyncExternalStore(history.subscribe, () => canGoForward(history));
}
2 changes: 2 additions & 0 deletions apps/web/src/router.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { createRouter, RouterHistory } from "@tanstack/react-router";

import { trackNavigationHistory } from "./navigationHistory";
import { routeTree } from "./routeTree.gen";

export function getRouter(history: RouterHistory) {
trackNavigationHistory(history);
return createRouter({
routeTree,
history,
Expand Down
Loading