feat(desktop): add forward history menu

Co-authored-by: Jitter <d14dfe033ef0f809866f9f984de04821b0d900d7652fd85a54776ee40ca3a68f@buzz.block.builderlab.xyz>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
This commit is contained in:
Matt Toohey
2026-08-26 16:11:48 +10:00
parent 428d98c6d6
commit c8ac48ba55
6 changed files with 243 additions and 67 deletions

View File

@@ -157,8 +157,16 @@ export function AppShell() {
closeSettings,
openSearchHit,
} = useAppNavigation();
const { backHistory, canGoBack, canGoForward, goBack, goBackTo, goForward } =
useBackForwardControls(describeHistoryLocation(location, channels));
const {
backHistory,
canGoBack,
canGoForward,
forwardHistory,
goBack,
goBackTo,
goForward,
goForwardTo,
} = useBackForwardControls(describeHistoryLocation(location, channels));
const { selectedChannelId, selectedView } = React.useMemo(
() => deriveShellRoute(location.pathname),
[location.pathname],
@@ -778,10 +786,12 @@ export function AppShell() {
backHistory={backHistory}
canGoBack={canGoBack}
canGoForward={canGoForward}
forwardHistory={forwardHistory}
hasCommunityRail={hasCommunityRail}
onGoBack={goBack}
onGoBackTo={goBackTo}
onGoForward={goForward}
onGoForwardTo={goForwardTo}
/>
) : null}
{settingsOpen ? (

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import type { BackHistoryEntry } from "@/app/navigation/navigationHistory";
import type { NavigationHistoryEntry } from "@/app/navigation/navigationHistory";
import { isMacPlatform } from "@/shared/lib/platform";
import { useIsFullscreen } from "@/shared/lib/useIsFullscreen";
import { Button } from "@/shared/ui/button";
@@ -17,12 +17,14 @@ import { topChromeBackdrop } from "@/shared/layout/chromeLayout";
import { useOptionalSidebar } from "@/shared/ui/sidebar";
type AppTopChromeProps = {
backHistory: BackHistoryEntry[];
backHistory: NavigationHistoryEntry[];
canGoBack: boolean;
canGoForward: boolean;
forwardHistory: NavigationHistoryEntry[];
onGoBack: () => void;
onGoBackTo: (index: number) => void;
onGoForward: () => void;
onGoForwardTo: (index: number) => void;
hasCommunityRail?: boolean;
};
@@ -34,7 +36,7 @@ const TOP_CHROME_ICON_BUTTON_CLASS =
"h-[28px] w-[28px] rounded-[4px] text-sidebar-foreground/65 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground";
const HISTORY_ICON_BUTTON_CLASS =
"h-[28px] w-[24px] rounded-[4px] text-sidebar-foreground/65 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground [&_svg]:size-[16px]";
const BACK_HISTORY_LONG_PRESS_MS = 500;
const HISTORY_LONG_PRESS_MS = 500;
function preventTopChromeWheel(event: WheelEvent) {
event.preventDefault();
@@ -62,18 +64,28 @@ function TopChromeSidebarTrigger() {
);
}
function BackHistoryButton({
backHistory,
canGoBack,
onGoBack,
onGoBackTo,
}: Pick<
AppTopChromeProps,
"backHistory" | "canGoBack" | "onGoBack" | "onGoBackTo"
>) {
type HistoryButtonProps = {
canGo: boolean;
direction: "back" | "forward";
entries: NavigationHistoryEntry[];
onGo: () => void;
onGoTo: (index: number) => void;
};
function HistoryButton({
canGo,
direction,
entries,
onGo,
onGoTo,
}: HistoryButtonProps) {
const buttonRef = React.useRef<HTMLButtonElement>(null);
const longPressTimerRef = React.useRef<number | null>(null);
const longPressTriggeredRef = React.useRef(false);
const isBack = direction === "back";
const actionLabel = isBack ? "Go back" : "Go forward";
const testIdPrefix = isBack ? "global-back" : "global-forward";
const Icon = isBack ? ChevronLeft : ChevronRight;
const cancelLongPress = React.useCallback(() => {
if (longPressTimerRef.current !== null) {
@@ -86,7 +98,7 @@ function BackHistoryButton({
const handlePointerDown = React.useCallback(
(event: React.PointerEvent<HTMLButtonElement>) => {
if (event.button !== 0 || backHistory.length === 0) {
if (event.button !== 0 || entries.length === 0) {
return;
}
@@ -106,9 +118,9 @@ function BackHistoryButton({
view: window,
}),
);
}, BACK_HISTORY_LONG_PRESS_MS);
}, HISTORY_LONG_PRESS_MS);
},
[backHistory.length, cancelLongPress],
[cancelLongPress, entries.length],
);
return (
@@ -122,11 +134,11 @@ function BackHistoryButton({
<ContextMenuTrigger asChild>
<Button
ref={buttonRef}
aria-label="Go back"
aria-label={actionLabel}
className={HISTORY_ICON_BUTTON_CLASS}
data-history-count={backHistory.length}
data-testid="global-back"
disabled={!canGoBack}
data-history-count={entries.length}
data-testid={testIdPrefix}
disabled={!canGo}
onClick={(event) => {
if (longPressTriggeredRef.current) {
longPressTriggeredRef.current = false;
@@ -134,7 +146,7 @@ function BackHistoryButton({
return;
}
onGoBack();
onGo();
}}
onPointerCancel={cancelLongPress}
onPointerDown={handlePointerDown}
@@ -143,20 +155,20 @@ function BackHistoryButton({
size="icon"
variant="ghost"
>
<ChevronLeft />
<Icon />
</Button>
</ContextMenuTrigger>
{backHistory.length > 0 ? (
{entries.length > 0 ? (
<ContextMenuContent
className="w-64"
data-testid="global-back-history-menu"
data-testid={`${testIdPrefix}-history-menu`}
>
{backHistory.map((entry) => (
{entries.map((entry) => (
<ContextMenuItem
aria-label={`Go back to ${entry.label}`}
data-testid="global-back-history-item"
aria-label={`${actionLabel} to ${entry.label}`}
data-testid={`${testIdPrefix}-history-item`}
key={entry.key}
onSelect={() => onGoBackTo(entry.index)}
onSelect={() => onGoTo(entry.index)}
>
<span className="min-w-0 truncate">{entry.label}</span>
</ContextMenuItem>
@@ -171,9 +183,11 @@ export function AppTopChrome({
backHistory,
canGoBack,
canGoForward,
forwardHistory,
onGoBack,
onGoBackTo,
onGoForward,
onGoForwardTo,
hasCommunityRail = false,
}: AppTopChromeProps) {
const topChromeRef = React.useRef<HTMLDivElement>(null);
@@ -249,23 +263,20 @@ export function AppTopChrome({
>
<div className={cn("flex items-center gap-0.5", navRowAlignmentClass)}>
<TopChromeSidebarTrigger />
<BackHistoryButton
backHistory={backHistory}
canGoBack={canGoBack}
onGoBack={onGoBack}
onGoBackTo={onGoBackTo}
<HistoryButton
canGo={canGoBack}
direction="back"
entries={backHistory}
onGo={onGoBack}
onGoTo={onGoBackTo}
/>
<HistoryButton
canGo={canGoForward}
direction="forward"
entries={forwardHistory}
onGo={onGoForward}
onGoTo={onGoForwardTo}
/>
<Button
aria-label="Go forward"
className={HISTORY_ICON_BUTTON_CLASS}
data-testid="global-forward"
disabled={!canGoForward}
onClick={onGoForward}
size="icon"
variant="ghost"
>
<ChevronRight />
</Button>
</div>
<div
className={cn("flex min-w-0 flex-1 items-center", navRowAlignmentClass)}

View File

@@ -4,6 +4,7 @@ import test from "node:test";
import {
describeHistoryLocation,
getBackHistoryEntries,
getForwardHistoryEntries,
} from "./navigationHistory.ts";
function entry(index) {
@@ -21,6 +22,17 @@ test("back history returns the nearest ten entries in reverse order", () => {
);
});
test("forward history returns the nearest ten entries in navigation order", () => {
const entriesByIndex = new Map(
Array.from({ length: 14 }, (_, index) => [index, entry(index)]),
);
assert.deepEqual(
getForwardHistoryEntries(entriesByIndex, 0, 13).map(({ index }) => index),
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
);
});
test("history labels identify channel and thread destinations", () => {
const channels = [
{

View File

@@ -1,22 +1,22 @@
import type { Channel } from "@/shared/api/types";
export type BackHistoryEntry = {
export type NavigationHistoryEntry = {
index: number;
key: string;
label: string;
};
const MAX_BACK_HISTORY_ENTRIES = 10;
const MAX_HISTORY_MENU_ENTRIES = 10;
export function getBackHistoryEntries(
entriesByIndex: ReadonlyMap<number, BackHistoryEntry>,
entriesByIndex: ReadonlyMap<number, NavigationHistoryEntry>,
currentIndex: number,
): BackHistoryEntry[] {
const entries: BackHistoryEntry[] = [];
): NavigationHistoryEntry[] {
const entries: NavigationHistoryEntry[] = [];
for (
let index = currentIndex - 1;
index >= 0 && entries.length < MAX_BACK_HISTORY_ENTRIES;
index >= 0 && entries.length < MAX_HISTORY_MENU_ENTRIES;
index -= 1
) {
const entry = entriesByIndex.get(index);
@@ -28,6 +28,27 @@ export function getBackHistoryEntries(
return entries;
}
export function getForwardHistoryEntries(
entriesByIndex: ReadonlyMap<number, NavigationHistoryEntry>,
currentIndex: number,
maxIndex: number,
): NavigationHistoryEntry[] {
const entries: NavigationHistoryEntry[] = [];
for (
let index = currentIndex + 1;
index <= maxIndex && entries.length < MAX_HISTORY_MENU_ENTRIES;
index += 1
) {
const entry = entriesByIndex.get(index);
if (entry) {
entries.push(entry);
}
}
return entries;
}
type HistoryLocation = {
pathname: string;
search: unknown;

View File

@@ -9,8 +9,9 @@ import { listen } from "@tauri-apps/api/event";
import { matchBackForwardChord } from "@/app/navigation/backForwardChords";
import {
type BackHistoryEntry,
type NavigationHistoryEntry,
getBackHistoryEntries,
getForwardHistoryEntries,
} from "@/app/navigation/navigationHistory";
import {
traverseHistory,
@@ -37,7 +38,7 @@ export function useBackForwardControls(currentLabel: string) {
const locationKey =
locationState.__TSR_key ?? locationState.key ?? String(locationIndex);
const [historyState, setHistoryState] = React.useState(() => ({
entriesByIndex: new Map<number, BackHistoryEntry>([
entriesByIndex: new Map<number, NavigationHistoryEntry>([
[
locationIndex,
{ index: locationIndex, key: locationKey, label: currentLabel },
@@ -82,6 +83,15 @@ export function useBackForwardControls(currentLabel: string) {
() => getBackHistoryEntries(historyState.entriesByIndex, locationIndex),
[historyState.entriesByIndex, locationIndex],
);
const forwardHistory = React.useMemo(
() =>
getForwardHistoryEntries(
historyState.entriesByIndex,
locationIndex,
historyState.maxIndex,
),
[historyState.entriesByIndex, historyState.maxIndex, locationIndex],
);
const goBack = React.useCallback(() => {
if (!canGoBack) {
@@ -111,6 +121,18 @@ export function useBackForwardControls(currentLabel: string) {
[historyState.entriesByIndex, locationIndex, router.history],
);
const goForwardTo = React.useCallback(
(index: number) => {
const delta = index - locationIndex;
if (delta <= 0 || !historyState.entriesByIndex.has(index)) {
return;
}
traverseHistoryBy(router.history, delta);
},
[historyState.entriesByIndex, locationIndex, router.history],
);
const handleKeyDown = React.useEffectEvent((event: KeyboardEvent) => {
// Note: the chords deliberately fire even when focus is inside an
// editable element. The composer autofocuses on every channel switch
@@ -172,8 +194,10 @@ export function useBackForwardControls(currentLabel: string) {
backHistory,
canGoBack,
canGoForward,
forwardHistory,
goBack,
goBackTo,
goForward,
goForwardTo,
};
}

View File

@@ -1,5 +1,6 @@
import { expect, test } from "@playwright/test";
import { waitForAnimations } from "../helpers/animations";
import { installMockBridge } from "../helpers/bridge";
import { openSettings } from "../helpers/settings";
@@ -40,6 +41,69 @@ async function navigateToWorkflows(page: import("@playwright/test").Page) {
await expect(page.getByTestId("workflows-view")).toBeVisible();
}
async function openHistoryMenuWithLongPress(
page: import("@playwright/test").Page,
button: import("@playwright/test").Locator,
menu: import("@playwright/test").Locator,
) {
const bounds = await button.boundingBox();
expect(bounds).not.toBeNull();
await page.mouse.move(
(bounds?.x ?? 0) + (bounds?.width ?? 0) / 2,
(bounds?.y ?? 0) + (bounds?.height ?? 0) / 2,
);
await page.mouse.down();
await expect(menu).toBeVisible();
await page.mouse.up();
await expect(menu).toBeVisible();
}
async function captureHistoryControlAppearance(
page: import("@playwright/test").Page,
button: import("@playwright/test").Locator,
menu: import("@playwright/test").Locator,
) {
await waitForAnimations(page);
const [buttonBounds, menuBounds] = await Promise.all([
button.boundingBox(),
menu.boundingBox(),
]);
if (!buttonBounds || !menuBounds) {
throw new Error("History control is not visible");
}
const padding = 4;
const x = Math.max(
0,
Math.floor(Math.min(buttonBounds.x, menuBounds.x)) - padding,
);
const y = Math.max(
0,
Math.floor(Math.min(buttonBounds.y, menuBounds.y)) - padding,
);
const right = Math.ceil(
Math.max(
buttonBounds.x + buttonBounds.width,
menuBounds.x + menuBounds.width,
),
);
const bottom = Math.ceil(
Math.max(
buttonBounds.y + buttonBounds.height,
menuBounds.y + menuBounds.height,
),
);
return page.screenshot({
clip: {
height: bottom - y + padding,
width: right - x + padding,
x,
y,
},
});
}
async function createWorkflow(
page: import("@playwright/test").Page,
name: string,
@@ -93,7 +157,7 @@ test("global back and forward move across channel routes", async ({ page }) => {
await expect(page.getByTestId("chat-title")).toHaveText("random");
});
test("back history menu opens on right click and long press", async ({
test("back and forward history menus match across right click and long press", async ({
page,
}) => {
await page.goto("/");
@@ -116,26 +180,60 @@ test("back history menu opens on right click and long press", async ({
"#general",
"Inbox",
]);
const rightClickAppearance = await captureHistoryControlAppearance(
page,
backButton,
historyMenu,
);
await page.keyboard.press("Escape");
await expect(historyMenu).not.toBeVisible();
await openHistoryMenuWithLongPress(page, backButton, historyMenu);
await expect(historyMenu.getByTestId("global-back-history-item")).toHaveText([
"#random",
"#general",
"Inbox",
]);
expect(
await captureHistoryControlAppearance(page, backButton, historyMenu),
).toEqual(rightClickAppearance);
await historyMenu
.getByRole("menuitem", { name: "Go back to #general" })
.click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
await page.getByTestId("channel-deep-history").click();
await expect(page.getByTestId("chat-title")).toHaveText("deep-history");
const forwardButton = page.getByTestId("global-forward");
const forwardHistoryMenu = page.getByTestId("global-forward-history-menu");
const bounds = await backButton.boundingBox();
expect(bounds).not.toBeNull();
await page.mouse.move(
(bounds?.x ?? 0) + (bounds?.width ?? 0) / 2,
(bounds?.y ?? 0) + (bounds?.height ?? 0) / 2,
await expect(forwardButton).toHaveAttribute("data-history-count", "2");
await forwardButton.click({ button: "right" });
await expect(forwardHistoryMenu).toBeVisible();
await expect(
forwardHistoryMenu.getByTestId("global-forward-history-item"),
).toHaveText(["#random", "#engineering"]);
const forwardRightClickAppearance = await captureHistoryControlAppearance(
page,
forwardButton,
forwardHistoryMenu,
);
await page.mouse.down();
await expect(historyMenu).toBeVisible();
await page.mouse.up();
await expect(historyMenu).toBeVisible();
await historyMenu.getByRole("menuitem", { name: "Go back to Inbox" }).click();
await expect(page.getByTestId("home-inbox")).toBeVisible();
await page.keyboard.press("Escape");
await expect(forwardHistoryMenu).not.toBeVisible();
await openHistoryMenuWithLongPress(page, forwardButton, forwardHistoryMenu);
await expect(
forwardHistoryMenu.getByTestId("global-forward-history-item"),
).toHaveText(["#random", "#engineering"]);
expect(
await captureHistoryControlAppearance(
page,
forwardButton,
forwardHistoryMenu,
),
).toEqual(forwardRightClickAppearance);
await forwardHistoryMenu
.getByRole("menuitem", { name: "Go forward to #engineering" })
.click();
await expect(page.getByTestId("chat-title")).toHaveText("engineering");
});
test("back/forward keyboard chords work while the composer has focus", async ({