From 47a37afc204c459f2bf39edf8ee44bbbe7b69656 Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:16:43 -0500 Subject: [PATCH 01/12] fix(web): reserve the accent color for selection and focus The browser review page used the theme accent for pressed toggles, checked segments, the active panel tab, every note card, and the minimap viewport as well as for the selected hunk and file. An "on" control now uses a neutral raised fill, so the accent marks only where the reviewer is and what has keyboard focus. Co-Authored-By: Claude Fable 5.2 --- .changeset/web-accent-means-selection.md | 5 ++++ packages/hunk/src/web/styles.css | 34 +++++++++++++----------- test/web/review-shell.e2e.ts | 32 ++++++++++++++++++++++ 3 files changed, 55 insertions(+), 16 deletions(-) create mode 100644 .changeset/web-accent-means-selection.md diff --git a/.changeset/web-accent-means-selection.md b/.changeset/web-accent-means-selection.md new file mode 100644 index 000000000..b615e84b1 --- /dev/null +++ b/.changeset/web-accent-means-selection.md @@ -0,0 +1,5 @@ +--- +"hunkdiff": patch +--- + +The browser review page now reserves its accent color for your position and focus, so pressed toggles, checked segments, resting note cards, and the minimap viewport use a neutral "on" style instead. diff --git a/packages/hunk/src/web/styles.css b/packages/hunk/src/web/styles.css index d2da1b3ea..dc52b882d 100644 --- a/packages/hunk/src/web/styles.css +++ b/packages/hunk/src/web/styles.css @@ -211,10 +211,14 @@ body { text-align: center; } -/* A pressed toggle reads like a checked segment: tinted, with the accent border. */ +/* A pressed toggle is a neutral "on" state, not a selection: the accent stays reserved for + position and focus. The filled panel, the full-strength label, and the dot glyph (on text + toggles) tell on from off without relying on color alone. */ .tool-button[aria-pressed="true"] { - background: var(--hunk-accent-muted); - border-color: var(--hunk-accent); + background: var(--hunk-panel-alt); + border-color: var(--hunk-border); + color: var(--hunk-text); + box-shadow: inset 0 -2px 0 var(--hunk-muted); } .toggle-button[aria-pressed]::before { @@ -226,7 +230,7 @@ body { } .toggle-button[aria-pressed="true"]::before { - color: var(--hunk-accent); + color: var(--hunk-text); content: "●" / ""; } @@ -328,8 +332,10 @@ body { } .segmented button[aria-checked="true"] { - background: var(--hunk-accent-muted); - border-color: var(--hunk-accent); + background: var(--hunk-panel-alt); + border-color: var(--hunk-border); + color: var(--hunk-text); + box-shadow: inset 0 -2px 0 var(--hunk-muted); position: relative; } @@ -648,15 +654,11 @@ body { max-width: 920px; padding: 6px 10px 8px; background: var(--hunk-panel); - border: 1px solid var(--hunk-note-border, var(--hunk-accent)); + border: 1px solid var(--hunk-border); border-left-width: 3px; border-radius: 6px; } -.note-card[data-source="user"] { - border-color: var(--hunk-accent); -} - .note-card[data-stale] { border-style: dashed; opacity: 0.8; @@ -671,7 +673,7 @@ body { } .note-author { - color: var(--hunk-accent); + color: var(--hunk-text); font-weight: 600; } @@ -1219,7 +1221,7 @@ body { .side-panel-tabs [role="tab"][aria-selected="true"] { color: var(--hunk-text); - border-bottom-color: var(--hunk-accent); + border-bottom-color: var(--hunk-text); } .side-panel-close { @@ -1641,7 +1643,7 @@ body { } .notes-author { - color: var(--hunk-accent); + color: var(--hunk-text); font-weight: 600; } @@ -1707,8 +1709,8 @@ body { left: 0; right: 0; box-sizing: border-box; - background: color-mix(in srgb, var(--hunk-accent) 14%, transparent); - border: 1px solid color-mix(in srgb, var(--hunk-accent) 70%, transparent); + background: color-mix(in srgb, var(--hunk-muted) 14%, transparent); + border: 1px solid color-mix(in srgb, var(--hunk-muted) 60%, transparent); pointer-events: none; } diff --git a/test/web/review-shell.e2e.ts b/test/web/review-shell.e2e.ts index 0ad446c0f..12ca1aee2 100644 --- a/test/web/review-shell.e2e.ts +++ b/test/web/review-shell.e2e.ts @@ -88,6 +88,38 @@ async function selectedHunk(page: Page) { .getAttribute("data-hunk-index")}`; } +// Intent: the accent marks position and focus; an "on" toggle or a checked segment is neutral. +test("pressed toggles and checked segments stay off the accent color", async ({ page }) => { + await openTestReview(page, "--rich"); + + const colors = await page.evaluate(() => { + const resolve = (value: string) => { + const probe = document.createElement("i"); + probe.style.backgroundColor = value; + document.body.append(probe); + const resolved = getComputedStyle(probe).backgroundColor; + probe.remove(); + return resolved; + }; + const paint = (element: Element | null) => { + const style = getComputedStyle(element!); + return { background: style.backgroundColor, border: style.borderTopColor }; + }; + + return { + accent: resolve("var(--hunk-accent)"), + accentMuted: resolve("var(--hunk-accent-muted)"), + toggle: paint(document.querySelector('[data-testid="toggle-line-numbers"]')), + segment: paint(document.querySelector('.segmented button[aria-checked="true"]')), + }; + }); + + for (const painted of [colors.toggle, colors.segment]) { + expect([painted.background, painted.border]).not.toContain(colors.accent); + expect([painted.background, painted.border]).not.toContain(colors.accentMuted); + } +}); + // Intent: Space is a checkbox's only native key; the page must not turn it into a page-down. test("Space on a focused Viewed checkbox toggles it instead of paging", async ({ page }) => { await openTestReview(page, "--rich"); From dfda397277110747a9e8fd4c171948d6b4ea6ebf Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:59:30 -0500 Subject: [PATCH 02/12] feat(web): one-row toolbar with icon controls and a View menu The browser review page's toolbar was two rows of text buttons and wrapped to three at 800px. It is now one 44px row: layout, refresh, copy link, and the pane toggles are icon buttons, viewed progress is a ring, and the line and review toggles plus the theme picker live in a View menu that shows each shortcut. Adds the inline SVG icon module the rest of the page builds on. Co-Authored-By: Claude Fable 5.2 --- .changeset/web-toolbar-one-row.md | 5 + packages/hunk/src/web/app/ReviewApp.tsx | 96 ++-- packages/hunk/src/web/app/ReviewControls.tsx | 168 ++++--- packages/hunk/src/web/app/ThemeMenu.tsx | 130 +++--- packages/hunk/src/web/app/Toolbar.tsx | 158 +++---- packages/hunk/src/web/app/ViewMenu.tsx | 290 ++++++++++++ packages/hunk/src/web/app/ViewedControls.tsx | 35 -- packages/hunk/src/web/app/ViewedProgress.tsx | 48 ++ packages/hunk/src/web/app/useReviewTools.tsx | 2 + packages/hunk/src/web/icons/Icon.tsx | 40 ++ packages/hunk/src/web/icons/iconPaths.tsx | 86 ++++ packages/hunk/src/web/styles.css | 438 +++++++++++++++++-- test/web/review-accessibility.e2e.ts | 9 +- test/web/review-keyboard.e2e.ts | 17 +- test/web/review-notes.e2e.ts | 9 +- test/web/review-screenshots.e2e.ts | 24 +- test/web/review-shell.e2e.ts | 84 +++- test/web/review-tools-screenshots.e2e.ts | 18 +- test/web/review-viewed.e2e.ts | 28 +- test/web/webTestHarness.ts | 20 +- 20 files changed, 1344 insertions(+), 361 deletions(-) create mode 100644 .changeset/web-toolbar-one-row.md create mode 100644 packages/hunk/src/web/app/ViewMenu.tsx delete mode 100644 packages/hunk/src/web/app/ViewedControls.tsx create mode 100644 packages/hunk/src/web/app/ViewedProgress.tsx create mode 100644 packages/hunk/src/web/icons/Icon.tsx create mode 100644 packages/hunk/src/web/icons/iconPaths.tsx diff --git a/.changeset/web-toolbar-one-row.md b/.changeset/web-toolbar-one-row.md new file mode 100644 index 000000000..bd8abac09 --- /dev/null +++ b/.changeset/web-toolbar-one-row.md @@ -0,0 +1,5 @@ +--- +"hunkdiff": patch +--- + +The browser review page's toolbar is now one compact row of icon controls that stays on one line in narrow windows, with wrapping, line numbers, agent notes, hidden viewed files, and the theme moved into a new View menu and a Commands button that opens the command palette. diff --git a/packages/hunk/src/web/app/ReviewApp.tsx b/packages/hunk/src/web/app/ReviewApp.tsx index bf878b011..dfa94cbb0 100644 --- a/packages/hunk/src/web/app/ReviewApp.tsx +++ b/packages/hunk/src/web/app/ReviewApp.tsx @@ -97,7 +97,7 @@ import { NotesTab } from "../notesPanel/NotesTab"; import { OverviewTab } from "../overview/OverviewTab"; import { selectWebReviewOverview } from "../panel/overviewInput"; import { webLocalKeyCommands, withWebLocalChords } from "../panel/panelCommands"; -import type { WebLocalCommandId } from "../commands/webLocalCommands"; +import { webModChordLabel, type WebLocalCommandId } from "../commands/webLocalCommands"; import { readSidePanelPreferences, resolveSidePanelOpen, @@ -108,13 +108,14 @@ import { SidePanel, type SidePanelTool } from "../panel/SidePanel"; import type { ThemeMenuOption } from "./ThemeMenu"; import { ToastRegion } from "../actions/toasts"; import { reviewLinkWithCapability, watchReviewCapability } from "../session/capability"; -import { ReviewControls } from "./ReviewControls"; +import { FilterField, ReviewActions } from "./ReviewControls"; import { Toolbar } from "./Toolbar"; import { useReviewInteraction } from "./useReviewInteraction"; import { useReviewTools } from "./useReviewTools"; import { useViewedFiles, type ViewedFiles } from "../viewed/useViewedFiles"; import type { ReviewViewedControls } from "../stream/FileSection"; -import { ViewedControls } from "./ViewedControls"; +import { ViewedProgress } from "./ViewedProgress"; +import { ViewMenu } from "./ViewMenu"; /** Width of one monospace column on this page, measured once the fonts are in place. */ function useColumnWidth() { @@ -791,9 +792,16 @@ export function ReviewApp({ session }: { session: ReviewSession }) { }); const toolsRef = useRef(undefined); toolsRef.current = tools; - const panelHint = webCommandChords(pageKeymap, "hunk.web.toggleSidePanel") - .map(formatKeyChord) - .join(" / "); + const pageHint = (commandId: WebLocalCommandId) => + webCommandChords(pageKeymap, commandId).map(formatKeyChord).join(" / ") || undefined; + const panelHint = pageHint("hunk.web.toggleSidePanel"); + const viewMenuHints = { + wrap: keyHint("hunk.view.toggleLineWrap"), + lineNumbers: keyHint("hunk.view.toggleLineNumbers"), + agentNotes: keyHint("hunk.view.toggleAgentNotes"), + hideViewed: pageHint("hunk.web.toggleHideViewed"), + theme: keyHint("hunk.view.openThemeSelector"), + }; const panelTools: SidePanelTool[] = overview ? [ { @@ -902,42 +910,56 @@ export function ReviewApp({ session }: { session: ReviewSession }) { ? `Loading ${mirror.loadedFiles} of ${mirror.totalFiles}` : undefined } - preferences={preferences} + layout={preferences.layout} + onLayout={(next) => updatePreferences({ layout: next })} sidebarOpen={sidebarOpen} resolvedLayout={layout} - themes={themeOptions} - themeId={selectedId} - {...(theme ? { themeLabel: theme.label } : {})} - themeMenuOpen={themeMenuOpen} - onThemeMenuOpen={setThemeMenuOpen} keyHint={keyHint} - onPreferences={updatePreferences} onToggleSidebar={() => updatePreferences({ sidebarOpen: !sidebarOpen })} - onTheme={choose} - controls={ - <> - void interactive.refresh()} - {...(keyHint("hunk.app.refresh") - ? { refreshKeyHint: keyHint("hunk.app.refresh") } - : {})} - onCopyLink={copyLink} - sessionEnded={sessionEnded} - /> - - + filterField={ + + } + viewedProgress={} + viewMenu={ + void interactive.toggleAgentNotes()} + hideViewed={viewed.hideViewed} + onToggleHideViewed={viewed.toggleHideViewed} + sessionEnded={sessionEnded} + themes={themeOptions} + themeId={selectedId} + {...(theme ? { themeLabel: theme.label } : {})} + themeMenuOpen={themeMenuOpen} + onThemeMenuOpen={setThemeMenuOpen} + onTheme={choose} + hints={viewMenuHints} + /> + } + reviewActions={ + void interactive.refresh()} + {...(keyHint("hunk.app.refresh") + ? { refreshKeyHint: keyHint("hunk.app.refresh") } + : {})} + onCopyLink={copyLink} + sessionEnded={sessionEnded} + /> } + onOpenCommands={tools.openPalette} + commandsHint={webModChordLabel("k")} panelOpen={panelOpen} {...(panelHint ? { panelHint } : {})} onTogglePanel={() => updatePanel({ open: !panelOpen })} diff --git a/packages/hunk/src/web/app/ReviewControls.tsx b/packages/hunk/src/web/app/ReviewControls.tsx index 4a95a0d91..785562afd 100644 --- a/packages/hunk/src/web/app/ReviewControls.tsx +++ b/packages/hunk/src/web/app/ReviewControls.tsx @@ -2,84 +2,118 @@ /** * The toolbar's review controls: the shared file filter, refresh, and "Copy review link". * - * The filter and agent-note visibility are shared with every surface of the review, the - * terminal included, so the filter says so beside itself. Refresh reopens the session's input - * (`POST /refresh`), paced by the session. Copying the review link is the one deliberate way the - * capability leaves the page. + * The filter is shared with every surface of the review, the terminal included, so the field + * says so beside itself and in its tooltip. Refresh reopens the session's input + * (`POST /refresh`), paced by the session. Copying the review link is the one deliberate way + * the capability leaves the page. Refresh and copy are icon buttons whose accessible names + * carry their state ("Refreshing…", "Copied", "Copy failed"), and the copy result also shows + * as a brief visible label. */ import { forwardRef, useState } from "react"; +import { Icon } from "../icons/Icon"; -export interface ReviewControlsProps { +export interface FilterFieldProps { filterText: string; onFilterChange: (text: string) => void; - /** The shortcut that focuses the filter, for its tooltip. */ + /** The shortcut that focuses the filter, shown in the field and its tooltip. */ filterKeyHint?: string; - refreshing: boolean; - onRefresh: () => void; - refreshKeyHint?: string; - onCopyLink: () => Promise; - /** The session has ended: the filter and refresh need it, so both are disabled. */ + /** The session has ended: the filter needs it, so it is disabled. */ sessionEnded?: boolean; } -/** The filter field, refresh button, and copy-link button. */ -export const ReviewControls = forwardRef( - function ReviewControls(props, filterRef) { - const [copied, setCopied] = useState<"idle" | "copied" | "failed">("idle"); +/** The shared file filter field. */ +export const FilterField = forwardRef( + function FilterField(props, filterRef) { return ( -
- - - -
+ /> + + {props.filterKeyHint ? ( + + ) : null} + ); }, ); + +export interface ReviewActionsProps { + refreshing: boolean; + onRefresh: () => void; + refreshKeyHint?: string; + onCopyLink: () => Promise; + /** The session has ended: refresh needs it, so it is disabled. */ + sessionEnded?: boolean; +} + +/** The refresh and copy-link icon buttons. */ +export function ReviewActions(props: ReviewActionsProps) { + const [copied, setCopied] = useState<"idle" | "copied" | "failed">("idle"); + const copyLabel = + copied === "copied" ? "Copied" : copied === "failed" ? "Copy failed" : "Copy link"; + + return ( + <> + + + + ); +} diff --git a/packages/hunk/src/web/app/ThemeMenu.tsx b/packages/hunk/src/web/app/ThemeMenu.tsx index 5ef8820aa..a1bf9432f 100644 --- a/packages/hunk/src/web/app/ThemeMenu.tsx +++ b/packages/hunk/src/web/app/ThemeMenu.tsx @@ -1,16 +1,16 @@ /** @jsxImportSource react */ /** - * The theme picker: a toolbar button that opens a listbox of the built-in themes. + * The theme picker's list: a listbox of the built-in themes, opened from the View menu's + * Theme row or with `t` (the terminal's `hunk.view.openThemeSelector`). * - * A real button and a real listbox rather than a native ``, so it can wear the theme's own colors. + * Keyboard behaves like a select: the arrow keys, Home, and End move the active option, typing + * a letter jumps to the next theme starting with it, Enter or Space chooses, and Escape or Tab + * closes. Opening starts at the current theme; closing hands focus back through `onClose`, + * which the View menu points at its own button. When the session resolved a theme, the first + * option follows it ("Use session theme") and choosing it clears this browser's override. */ -import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react"; +import { useEffect, useId, useRef, useState, type KeyboardEvent, type RefObject } from "react"; import type { WebTheme } from "../theme/themeIndex"; /** One choice in the menu. */ @@ -20,35 +20,32 @@ export interface ThemeMenuProps { themes: readonly ThemeMenuOption[]; /** The option shown as chosen. */ themeId: string | undefined; - /** The theme in effect, named on the button. */ - currentLabel?: string; open: boolean; onOpenChange: (open: boolean) => void; onTheme: (themeId: string) => void; - /** The shortcut that opens the menu, for its tooltip. */ - keyHint?: string; + /** The region a click inside does not count as "outside" (the menu's anchor). */ + anchorRef: RefObject; + /** Returns focus to the control that owns the list once it closes from the keyboard. */ + onClose: () => void; } -/** The toolbar's theme picker. */ +/** The theme picker's listbox, shown while `open`. */ export function ThemeMenu({ themes, themeId, open, onOpenChange, onTheme, - keyHint, - currentLabel, + anchorRef, + onClose, }: ThemeMenuProps) { const listId = useId(); - const buttonRef = useRef(null); const listRef = useRef(null); - const rootRef = useRef(null); const currentIndex = Math.max( 0, themes.findIndex((theme) => theme.id === themeId), ); const [active, setActive] = useState(currentIndex); - const label = currentLabel ?? themes.find((theme) => theme.id === themeId)?.label; // Opening starts at the current theme and moves focus into the list. useEffect(() => { @@ -66,20 +63,21 @@ export function ThemeMenu({ ?.scrollIntoView({ block: "nearest" }); }, [active, open]); - // A click anywhere else closes the menu without choosing. + // A click anywhere else closes the list without choosing. useEffect(() => { if (!open) return; const onPointerDown = (event: PointerEvent) => { - if (!rootRef.current?.contains(event.target as Node)) onOpenChange(false); + if (!anchorRef.current?.contains(event.target as Node)) onOpenChange(false); }; window.addEventListener("pointerdown", onPointerDown); return () => window.removeEventListener("pointerdown", onPointerDown); - }, [open, onOpenChange]); + }, [open, onOpenChange, anchorRef]); const close = () => { onOpenChange(false); - buttonRef.current?.focus(); + onClose(); }; + const choose = (index: number) => { const theme = themes[index]; if (theme) onTheme(theme.id); @@ -123,61 +121,39 @@ export function ThemeMenu({ } }; + if (!open) return null; + return ( -
- - {open ? ( -
    + {themes.map((theme, index) => ( +
  • setActive(index)} + onClick={() => choose(index)} > - {themes.map((theme, index) => ( -
  • setActive(index)} - onClick={() => choose(index)} - > - - {theme.appearance === "light" ? "☀" : "☾"} - - {theme.label} -
  • - ))} -
- ) : null} -
+ + {theme.appearance === "light" ? "☀" : "☾"} + + {theme.label} + + ))} + ); } diff --git a/packages/hunk/src/web/app/Toolbar.tsx b/packages/hunk/src/web/app/Toolbar.tsx index 253c2dada..9dccb3998 100644 --- a/packages/hunk/src/web/app/Toolbar.tsx +++ b/packages/hunk/src/web/app/Toolbar.tsx @@ -1,20 +1,21 @@ /** @jsxImportSource react */ /** - * The page's toolbar: what the terminal's menu bar title says, plus web-native view controls. + * Lays out the page's toolbar as one row: what the terminal's menu bar title says on the left, + * web-native view controls on the right. * * The left side mirrors the terminal's `topTitle` — review title, file count, and total - * `+A -D` — with connection and load state beside it. The right side holds the per-browser - * view controls: sidebar, layout (auto, split, unified), wrapping, line numbers, and theme. - * They are real buttons, styled from the theme's tokens, and each names the shortcut that - * does the same thing (from the page's keymap, so a remap shows up here too). None of them - * reaches the session. + * `+A -D` — with connection and load state beside it (a quiet dot while connected, words while + * loading, reconnecting, or failed). The right side holds the shared filter, viewed progress, + * layout (auto, split, unified), the View menu, refresh, copy link, the command palette, and + * the side panel. Controls are icon buttons where the icon says enough; each names its action + * and the shortcut that does the same thing (from the page's keymap, so a remap shows up here + * too) in its tooltip. Narrow windows drop labels before controls (`styles.css`) so the row + * never wraps. None of the view controls reaches the session. */ import type { KeyboardEvent, ReactNode } from "react"; import type { LayoutMode } from "../../core/run/commandInputs"; import type { WebImplementedCommandId } from "../commands/webCommandTable"; - -import type { WebViewPreferences } from "../view/viewPreferences"; -import { ThemeMenu, type ThemeMenuOption } from "./ThemeMenu"; +import { Icon, type IconName } from "../icons/Icon"; export interface ToolbarProps { title: string; @@ -23,27 +24,28 @@ export interface ToolbarProps { deletions: number; status: { label: string; state: "connected" | "loading" | "reconnecting" | "failed" }; progress?: string; - preferences: WebViewPreferences; + layout: LayoutMode; + onLayout: (layout: LayoutMode) => void; sidebarOpen: boolean; resolvedLayout: "split" | "unified"; - themes: readonly ThemeMenuOption[]; - /** The theme option shown as chosen. */ - themeId: string | undefined; - /** The theme in effect. */ - themeLabel?: string; /** The session's source, shown beside the title. */ sourceLabel?: string; /** The shared file filter, when the session has one. */ filter?: string; /** Sidecar notes the session left out of the shared state; the terminal still shows them. */ omittedNotes?: number; - themeMenuOpen: boolean; - onThemeMenuOpen: (open: boolean) => void; - onPreferences: (next: Partial) => void; onToggleSidebar: () => void; - onTheme: (themeId: string) => void; - /** Review controls shown before the view controls (filter, refresh, copy link). */ - controls?: ReactNode; + /** The filter field. */ + filterField?: ReactNode; + /** Viewed progress. */ + viewedProgress?: ReactNode; + /** The View menu. */ + viewMenu?: ReactNode; + /** Refresh and copy link. */ + reviewActions?: ReactNode; + /** Opens the command palette, and the chord that does the same. */ + onOpenCommands?: () => void; + commandsHint?: string; /** The shortcut label for one command, when it has one on this page. */ keyHint: (commandId: WebImplementedCommandId) => string | undefined; /** Whether the side panel of review tools is open, and how to toggle it. */ @@ -52,10 +54,10 @@ export interface ToolbarProps { onTogglePanel?: () => void; } -const LAYOUTS: readonly { mode: LayoutMode; command: WebImplementedCommandId }[] = [ - { mode: "auto", command: "hunk.view.layoutAuto" }, - { mode: "split", command: "hunk.view.layoutSplit" }, - { mode: "unified", command: "hunk.view.layoutUnified" }, +const LAYOUTS: readonly { mode: LayoutMode; command: WebImplementedCommandId; icon: IconName }[] = [ + { mode: "auto", command: "hunk.view.layoutAuto", icon: "layout-auto" }, + { mode: "split", command: "hunk.view.layoutSplit", icon: "layout-split" }, + { mode: "unified", command: "hunk.view.layoutUnified", icon: "layout-unified" }, ]; /** A tooltip naming one action and, when bound, its shortcut. */ @@ -65,16 +67,17 @@ function hinted(label: string, hint: string | undefined) { /** The page toolbar. */ export function Toolbar(props: ToolbarProps) { - const { preferences, keyHint } = props; + const { keyHint } = props; + const connected = props.status.state === "connected"; // Arrow keys move the choice within the layout group, as in any radio group. const onLayoutKeyDown = (event: KeyboardEvent) => { const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]; if (step === undefined) return; event.preventDefault(); - const index = LAYOUTS.findIndex((layout) => layout.mode === preferences.layout); + const index = LAYOUTS.findIndex((layout) => layout.mode === props.layout); const next = LAYOUTS[(index + step + LAYOUTS.length) % LAYOUTS.length]!; - props.onPreferences({ layout: next.mode }); + props.onLayout(next.mode); event.currentTarget.querySelector(`[data-testid="layout-${next.mode}"]`)?.focus(); }; @@ -92,17 +95,33 @@ export function Toolbar(props: ToolbarProps) { onClick={props.onToggleSidebar} data-testid="toggle-sidebar" > - +
- + {/* The tooltip carries the whole title, which a narrow toolbar truncates. */} + {props.title} - - {props.fileCount === 1 ? "1 file" : `${props.fileCount} files`} + + + {props.fileCount === 1 ? "1 file" : `${props.fileCount} files`} + + {`+${props.additions}`} + {`-${props.deletions}`} + + {/* Connected is the quiet default: a dot whose words stay available to assistive + technology. Every other state keeps its words on screen. */} + + {props.status.label} - {`+${props.additions}`} - {`-${props.deletions}`} {props.filter ? ( {`filter: ${props.filter}`} @@ -117,9 +136,6 @@ export function Toolbar(props: ToolbarProps) { {`${props.omittedNotes} agent ${props.omittedNotes === 1 ? "note" : "notes"} not shown`} ) : null} - - {props.status.label} - {props.progress ? ( {props.progress} @@ -127,22 +143,25 @@ export function Toolbar(props: ToolbarProps) { ) : null}
- {props.controls} + {props.filterField} + {props.viewedProgress} +
diff --git a/packages/hunk/src/web/app/ViewMenu.tsx b/packages/hunk/src/web/app/ViewMenu.tsx new file mode 100644 index 000000000..8e3029abb --- /dev/null +++ b/packages/hunk/src/web/app/ViewMenu.tsx @@ -0,0 +1,290 @@ +/** @jsxImportSource react */ +/** + * Shows the toolbar's View menu: the display toggles that do not earn a toolbar button of + * their own, plus the theme picker. + * + * Rows: Wrap long lines, Line numbers (this browser's view preferences), Agent notes (shared + * with every surface through the `hunk.view.toggleAgentNotes` command path, and labelled as + * shared), Hide viewed files (this browser only), and Theme, which opens the theme listbox + * (`ThemeMenu`) in place of the menu. Each row names its shortcut from the page's keymap, so a + * remap shows up here too; the shortcuts work with the menu closed. + * + * Menu semantics follow `ThemeMenu`: opening moves focus to the first row, the arrow keys, + * Home, and End move between rows, Escape closes and returns focus to the View button, Tab + * and a click elsewhere close it. Toggling a row keeps the menu open so several can change at + * once. The menu stays mounted while closed (`hidden`), so the rows' state stays queryable. + */ +import { + useCallback, + useEffect, + useId, + useRef, + useState, + type KeyboardEvent, + type ReactNode, +} from "react"; +import { Icon } from "../icons/Icon"; +import { ThemeMenu, type ThemeMenuOption } from "./ThemeMenu"; + +export interface ViewMenuProps { + wrapLines: boolean; + showLineNumbers: boolean; + onPreferences: (next: { wrapLines?: boolean; showLineNumbers?: boolean }) => void; + agentNotesVisible: boolean; + onToggleAgentNotes: () => void; + hideViewed: boolean; + onToggleHideViewed: () => void; + /** The session has ended: shared toggles need it, so they are disabled. */ + sessionEnded?: boolean; + themes: readonly ThemeMenuOption[]; + /** The theme option shown as chosen. */ + themeId: string | undefined; + /** The theme in effect, named on the Theme row. */ + themeLabel?: string; + themeMenuOpen: boolean; + onThemeMenuOpen: (open: boolean) => void; + onTheme: (themeId: string) => void; + /** Shortcut labels for the rows that have one on this page. */ + hints: { + wrap: string | undefined; + lineNumbers: string | undefined; + agentNotes: string | undefined; + hideViewed: string | undefined; + theme: string | undefined; + }; +} + +/** The selector for every row the arrow keys move between. */ +const ROW_SELECTOR = '[role="menuitemcheckbox"]:not(:disabled), [role="menuitem"]:not(:disabled)'; + +interface ToggleRowProps { + label: string; + /** Extra words for assistive technology only, appended to the visible label. */ + spokenSuffix?: string; + /** A short visible note beside the label ("shared"). */ + note?: string; + checked: boolean; + hint?: string; + title: string; + disabled?: boolean; + testId?: string; + onToggle: () => void; +} + +/** One checkable menu row with its shortcut and an on/off switch. */ +function ToggleRow(props: ToggleRowProps) { + return ( + + ); +} + +/** A labelled group of rows. */ +function RowGroup({ label, children }: { label: string; children: ReactNode }) { + const id = useId(); + return ( +
+ + {children} +
+ ); +} + +/** The toolbar's View button and menu. */ +export function ViewMenu(props: ViewMenuProps) { + const { themeMenuOpen, onThemeMenuOpen } = props; + const [open, setOpen] = useState(false); + const menuId = useId(); + const rootRef = useRef(null); + const buttonRef = useRef(null); + const menuRef = useRef(null); + const themeLabel = + props.themeLabel ?? props.themes.find((theme) => theme.id === props.themeId)?.label; + + const rows = (): HTMLElement[] => + menuRef.current ? Array.from(menuRef.current.querySelectorAll(ROW_SELECTOR)) : []; + + // Opening moves focus to the first row. + useEffect(() => { + if (open) rows()[0]?.focus(); + }, [open]); + + // The theme list replaces the menu, whichever way it opened (`t` or the Theme row). + useEffect(() => { + if (themeMenuOpen) setOpen(false); + }, [themeMenuOpen]); + + // A click anywhere else closes the menu. + useEffect(() => { + if (!open) return; + const onPointerDown = (event: PointerEvent) => { + if (!rootRef.current?.contains(event.target as Node)) setOpen(false); + }; + window.addEventListener("pointerdown", onPointerDown); + return () => window.removeEventListener("pointerdown", onPointerDown); + }, [open]); + + const focusButton = useCallback(() => buttonRef.current?.focus(), []); + + const onMenuKeyDown = (event: KeyboardEvent) => { + const items = rows(); + const index = items.indexOf(document.activeElement as HTMLElement); + const last = items.length - 1; + const moves: Record number> = { + ArrowDown: () => (index >= last ? 0 : index + 1), + ArrowUp: () => (index <= 0 ? last : index - 1), + Home: () => 0, + End: () => last, + }; + const move = moves[event.key]; + if (move) { + event.preventDefault(); + items[move()]?.focus(); + return; + } + if (event.key === "Escape") { + event.preventDefault(); + setOpen(false); + focusButton(); + return; + } + if (event.key === "Tab") setOpen(false); + }; + + return ( +
+ + ))} diff --git a/packages/hunk/src/web/app/Toolbar.tsx b/packages/hunk/src/web/app/Toolbar.tsx index 9dccb3998..d42a5ecc9 100644 --- a/packages/hunk/src/web/app/Toolbar.tsx +++ b/packages/hunk/src/web/app/Toolbar.tsx @@ -15,6 +15,7 @@ import type { KeyboardEvent, ReactNode } from "react"; import type { LayoutMode } from "../../core/run/commandInputs"; import type { WebImplementedCommandId } from "../commands/webCommandTable"; +import { formatAddedCount, formatFileCount, formatRemovedCount } from "../format/lineCounts"; import { Icon, type IconName } from "../icons/Icon"; export interface ToolbarProps { @@ -107,10 +108,10 @@ export function Toolbar(props: ToolbarProps) { - {props.fileCount === 1 ? "1 file" : `${props.fileCount} files`} + {formatFileCount(props.fileCount)} - {`+${props.additions}`} - {`-${props.deletions}`} + {formatAddedCount(props.additions)} + {formatRemovedCount(props.deletions)} {/* Connected is the quiet default: a dot whose words stay available to assistive technology. Every other state keeps its words on screen. */} diff --git a/packages/hunk/src/web/app/useReviewTools.tsx b/packages/hunk/src/web/app/useReviewTools.tsx index e6036e676..304abd66a 100644 --- a/packages/hunk/src/web/app/useReviewTools.tsx +++ b/packages/hunk/src/web/app/useReviewTools.tsx @@ -21,7 +21,8 @@ */ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { formatReviewAddress, type ReviewAddress } from "../../core/review/address"; -import { formatReviewSidebarStat, reviewFileChangeGlyph } from "../../core/review/fileLabels"; +import { reviewFileChangeGlyph } from "../../core/review/fileLabels"; +import { formatAddedBadge, formatRemovedBadge } from "../format/lineCounts"; import type { WebKeymap } from "../commands/keyboard"; import type { WebCommand } from "../commands/webCommandTable"; import { matchWebLocalChord, type WebLocalCommandId } from "../commands/webLocalCommands"; @@ -404,6 +405,12 @@ export function useReviewTools(options: ReviewToolsOptions) { (items: readonly PaletteEntry[], query: string) => rankPaletteEntries(items, query, recents), [recents], ); + // Recently run commands lead the empty palette under their own heading; the rest sit under + // their category. + const paletteSectionOf = useCallback( + (entry: PaletteEntry) => (recents.includes(entry.id) ? "Recent" : entry.category), + [recents], + ); const runEntry = useCallback( (entry: PaletteEntry) => { const next = rememberRecentCommand(recents, entry.id); @@ -451,11 +458,20 @@ export function useReviewTools(options: ReviewToolsOptions) { rank={rankCommands} itemKey={(entry) => entry.id} empty="No matching commands." - renderItem={(entry) => ( + sectionOf={paletteSectionOf} + renderItem={(entry, { sectioned }) => ( <> {entry.title} - {entry.category} - {entry.keys ? {entry.keys} : null} + {sectioned ? null : {entry.category}} + {entry.keys ? ( + + {entry.keys.split(" / ").map((chord) => ( + + {chord} + + ))} + + ) : null} )} onPick={runEntry} @@ -483,11 +499,9 @@ export function useReviewTools(options: ReviewToolsOptions) { {entry.path} - {formatReviewSidebarStat("+", entry.stats.additions, entry.stats.truncated)} + {formatAddedBadge(entry.stats.additions, entry.stats.truncated)} {" "} - - {formatReviewSidebarStat("-", entry.stats.deletions)} - + {formatRemovedBadge(entry.stats.deletions)} ); diff --git a/packages/hunk/src/web/format/lineCounts.test.ts b/packages/hunk/src/web/format/lineCounts.test.ts new file mode 100644 index 000000000..70fcd5af7 --- /dev/null +++ b/packages/hunk/src/web/format/lineCounts.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from "bun:test"; +import { + formatAddedBadge, + formatAddedCount, + formatCount, + formatFileCount, + formatRemovedBadge, + formatRemovedCount, +} from "./lineCounts"; + +describe("line count formatting", () => { + test("groups digits with the en-US separator", () => { + expect(formatCount(999)).toBe("999"); + expect(formatCount(25048)).toBe("25,048"); + expect(formatCount(1234567)).toBe("1,234,567"); + }); + + test("signs additions with + and removals with a true minus", () => { + expect(formatAddedCount(25048)).toBe("+25,048"); + expect(formatAddedCount(10, true)).toBe("+10+"); + expect(formatRemovedCount(47)).toBe("−47"); + }); + + test("names file counts", () => { + expect(formatFileCount(1)).toBe("1 file"); + expect(formatFileCount(0)).toBe("0 files"); + expect(formatFileCount(2000)).toBe("2,000 files"); + }); + + test("hides zero badges", () => { + expect(formatAddedBadge(0)).toBeNull(); + expect(formatRemovedBadge(0)).toBeNull(); + expect(formatAddedBadge(1200)).toBe("+1,200"); + expect(formatRemovedBadge(1200)).toBe("−1,200"); + }); +}); diff --git a/packages/hunk/src/web/format/lineCounts.ts b/packages/hunk/src/web/format/lineCounts.ts new file mode 100644 index 000000000..71013b61b --- /dev/null +++ b/packages/hunk/src/web/format/lineCounts.ts @@ -0,0 +1,38 @@ +/** + * Formats the line and file counts the browser page prints. + * + * Counts group their digits with the `en-US` separator (`25,048`) so the text does not depend on + * the viewer's locale, and removals use a true minus sign (`−47`) so they align with `+`. + * Terminal output keeps its own plain formatting in `core/`. + */ +const GROUPED = new Intl.NumberFormat("en-US"); + +/** A whole number with grouped digits. */ +export function formatCount(value: number): string { + return GROUPED.format(value); +} + +/** `+25,048`, with a trailing `+` when the producer truncated the count. */ +export function formatAddedCount(value: number, truncated = false): string { + return `+${formatCount(value)}${truncated ? "+" : ""}`; +} + +/** `−47`, with a true minus sign. */ +export function formatRemovedCount(value: number): string { + return `−${formatCount(value)}`; +} + +/** `1 file` or `2,000 files`. */ +export function formatFileCount(value: number): string { + return value === 1 ? "1 file" : `${formatCount(value)} files`; +} + +/** An added-lines badge that hides a zero, for the sidebar and pickers. */ +export function formatAddedBadge(value: number, truncated = false): string | null { + return value > 0 ? formatAddedCount(value, truncated) : null; +} + +/** A removed-lines badge that hides a zero, for the sidebar and pickers. */ +export function formatRemovedBadge(value: number): string | null { + return value > 0 ? formatRemovedCount(value) : null; +} diff --git a/packages/hunk/src/web/icons/Icon.tsx b/packages/hunk/src/web/icons/Icon.tsx index 0a68207b3..82da1bc6b 100644 --- a/packages/hunk/src/web/icons/Icon.tsx +++ b/packages/hunk/src/web/icons/Icon.tsx @@ -6,6 +6,7 @@ * one names itself (`aria-label` or visible text). They inherit the text color and size to * 16px unless a smaller `size` is asked for. */ +import { isValidElement, type ReactNode } from "react"; import { ICON_PATHS, type IconName } from "./iconPaths"; export type { IconName } from "./iconPaths"; @@ -38,3 +39,46 @@ export function Icon({ name, size = 16, className }: IconProps) { ); } + +const SVG_NS = "http://www.w3.org/2000/svg"; + +/** Appends the SVG nodes one icon entry describes, walking its fragments and shapes. */ +function appendShapes(parent: Element, node: ReactNode) { + if (!isValidElement(node)) return; + const { children, ...attributes } = node.props as Record & { + children?: ReactNode; + }; + if (typeof node.type !== "string") { + // A fragment: its children belong to the parent. + for (const child of Array.isArray(children) ? children : [children]) { + appendShapes(parent, child as ReactNode); + } + return; + } + const shape = document.createElementNS(SVG_NS, node.type); + for (const [name, value] of Object.entries(attributes)) shape.setAttribute(name, String(value)); + parent.append(shape); +} + +/** + * Builds one icon as a DOM node, for the controls the page draws inside Pierre's diff, which + * React does not render. It matches `Icon` exactly: same grid, stroke, and hidden-from-AT + * treatment. + */ +export function createIconElement(name: IconName, size = 16): SVGSVGElement { + const svg = document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("class", "icon"); + svg.setAttribute("width", String(size)); + svg.setAttribute("height", String(size)); + svg.setAttribute("viewBox", "0 0 16 16"); + svg.setAttribute("fill", "none"); + svg.setAttribute("stroke", "currentColor"); + svg.setAttribute("stroke-width", "1.5"); + svg.setAttribute("stroke-linecap", "round"); + svg.setAttribute("stroke-linejoin", "round"); + svg.setAttribute("aria-hidden", "true"); + svg.setAttribute("focusable", "false"); + svg.dataset.icon = name; + appendShapes(svg, ICON_PATHS[name]); + return svg; +} diff --git a/packages/hunk/src/web/icons/iconPaths.tsx b/packages/hunk/src/web/icons/iconPaths.tsx index 9d5f84090..b9cd26b02 100644 --- a/packages/hunk/src/web/icons/iconPaths.tsx +++ b/packages/hunk/src/web/icons/iconPaths.tsx @@ -76,6 +76,8 @@ export const ICON_PATHS = { "chevron-down": , /** A chevron pointing right. */ "chevron-right": , + /** A chevron pointing up. */ + "chevron-up": , /** A check mark. */ check: , /** A cross. */ diff --git a/packages/hunk/src/web/notesPanel/NotesTab.tsx b/packages/hunk/src/web/notesPanel/NotesTab.tsx index e0780c403..42d5bf38f 100644 --- a/packages/hunk/src/web/notesPanel/NotesTab.tsx +++ b/packages/hunk/src/web/notesPanel/NotesTab.tsx @@ -9,6 +9,7 @@ * the stream scrolls to its card; nothing reaches the session. Read-only: notes are written * and edited in the stream. */ +import { Icon } from "../icons/Icon"; import { useMemo, useState } from "react"; import { reviewNoteRangeLabel, reviewNoteThreadTitle } from "../../core/review/noteLabels"; import type { @@ -172,7 +173,8 @@ export function NotesTab({ files, activeNoteId, agentNotesHidden, onSelectNote } aria-expanded={open} onClick={() => toggleThread(id)} > - {`${open ? "▾" : "▸"} ${replies} ${replies === 1 ? "reply" : "replies"}`} + + {`${replies} ${replies === 1 ? "reply" : "replies"}`} ) : null} {open ? ( diff --git a/packages/hunk/src/web/overview/OverviewTab.tsx b/packages/hunk/src/web/overview/OverviewTab.tsx index d1916d3f4..b2954caf4 100644 --- a/packages/hunk/src/web/overview/OverviewTab.tsx +++ b/packages/hunk/src/web/overview/OverviewTab.tsx @@ -8,7 +8,9 @@ * numbers as text, with `+` and `−` signs, so nothing depends on color. Every row naming a * file or a directory jumps to it in the stream (a directory to its first file). */ +import { Icon } from "../icons/Icon"; import { useState, type ReactNode } from "react"; +import { formatCount, formatFileCount } from "../format/lineCounts"; import { REVIEW_FILE_ROLES, type ReviewFileRole } from "../../core/review/fileRoles"; import type { ReviewOverview, @@ -52,7 +54,7 @@ const CHANGE_KIND_LABELS: readonly [keyof ReviewOverview["changeKinds"], string] /** A count with a lower-bound mark when the producer truncated it. */ function count(value: number, truncated: boolean) { - return truncated ? `≥${value}` : String(value); + return truncated ? `≥${formatCount(value)}` : formatCount(value); } /** `+A −D`, with lower-bound marks, as two separately colored spans. */ @@ -96,7 +98,7 @@ function Section({ title, children }: { title: string; children: ReactNode }) { /** Files, in words. */ function files(value: number) { - return value === 1 ? "1 file" : `${value} files`; + return formatFileCount(value); } /** One directory row and, when expanded, its subdirectories. */ @@ -124,7 +126,9 @@ function DirectoryRows({ style={hasChildren ? undefined : { visibility: "hidden" }} onClick={() => setExpanded((current) => !current)} > - + {hasChildren ? ( + + ) : null} - {directory.files} + {formatCount(directory.files)}
@@ -208,7 +212,7 @@ export function OverviewTab({ overview, onSelectFile }: OverviewTabProps) { ) : null} {overview.viewed ? (

- {`${overview.viewed.files} of ${files(overview.viewed.total)} viewed`} + {`${formatCount(overview.viewed.files)} of ${files(overview.viewed.total)} viewed`}

) : null} @@ -236,7 +240,7 @@ export function OverviewTab({ overview, onSelectFile }: OverviewTabProps) { return ( {ROLE_LABELS[role]} - {row.files} + {formatCount(row.files)} @@ -255,7 +259,7 @@ export function OverviewTab({ overview, onSelectFile }: OverviewTabProps) { {CHANGE_KIND_LABELS.map(([kind, label]) => (
{label}
-
{overview.changeKinds[kind]}
+
{formatCount(overview.changeKinds[kind])}
))} diff --git a/packages/hunk/src/web/palette/PickerDialog.tsx b/packages/hunk/src/web/palette/PickerDialog.tsx index 2c3102a35..dcc02f852 100644 --- a/packages/hunk/src/web/palette/PickerDialog.tsx +++ b/packages/hunk/src/web/palette/PickerDialog.tsx @@ -7,6 +7,12 @@ * Enter or a click picks the active row; Escape or a click outside closes the dialog, and the * caller restores focus. Ranking belongs to the caller (`rank`), so both pickers share this * component and differ only in their rows. + * + * A caller may name each row's section (`sectionOf`). While the query is empty the rows are + * gathered under section headings, in order of first appearance, and each row drops its own + * category label; once the user types, the list is one flat list in the caller's ranking. + * Headings sit in `role="group"` wrappers labelled by the heading, so the listbox stays valid + * and arrow keys only ever visit options. */ import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import { ModalDialog } from "./ModalDialog"; @@ -17,7 +23,10 @@ export interface PickerDialogProps { items: readonly T[]; rank: (items: readonly T[], query: string) => T[]; itemKey: (item: T) => string; - renderItem: (item: T) => ReactNode; + /** Draws one row; `sectioned` is true while a heading already names the row's category. */ + renderItem: (item: T, context: { sectioned: boolean }) => ReactNode; + /** The section heading a row belongs under while the query is empty. */ + sectionOf?: (item: T) => string; onPick: (item: T) => void; onClose: () => void; /** Shown when nothing matches. */ @@ -33,10 +42,23 @@ export function PickerDialog(props: PickerDialogProps) { const [query, setQuery] = useState(""); const [active, setActive] = useState(0); const inputRef = useRef(null); - const listRef = useRef(null); + const listRef = useRef(null); const listId = useId(); const { items, rank } = props; - const ranked = useMemo(() => rank(items, query).slice(0, MAX_ROWS), [items, rank, query]); + const { sectionOf } = props; + const sectioned = sectionOf !== undefined && query.trim() === ""; + const { ranked, groups } = useMemo(() => { + const ordered = rank(items, query).slice(0, MAX_ROWS); + if (!sectioned || !sectionOf) return { ranked: ordered, groups: null }; + // Group by section in order of first appearance; each group keeps the caller's ranking. + const byTitle = new Map(); + for (const item of ordered) { + const title = sectionOf(item); + byTitle.set(title, [...(byTitle.get(title) ?? []), item]); + } + const grouped = [...byTitle].map(([title, rows]) => ({ title, rows })); + return { ranked: grouped.flatMap((group) => group.rows), groups: grouped }; + }, [items, rank, query, sectioned, sectionOf]); const activeIndex = Math.min(active, Math.max(0, ranked.length - 1)); const optionId = (index: number) => `${listId}-option-${index}`; @@ -52,6 +74,25 @@ export function PickerDialog(props: PickerDialogProps) { if (item !== undefined) props.onPick(item); }; + const renderOption = (item: T, inSection: boolean) => { + const index = ranked.indexOf(item); + return ( +
index !== activeIndex && setActive(index)} + onMouseDown={(event) => event.preventDefault()} + onClick={() => pick(index)} + > + {props.renderItem(item, { sectioned: inSection })} +
+ ); + }; + return ( (props: PickerDialogProps) { } }} /> -
    - {ranked.map((item, index) => ( -
  • index !== activeIndex && setActive(index)} - onMouseDown={(event) => event.preventDefault()} - onClick={() => pick(index)} - > - {props.renderItem(item)} -
  • - ))} -
+
+ {groups + ? groups.map((group, groupIndex) => ( +
+
+ {group.title} +
+ {group.rows.map((item) => renderOption(item, true))} +
+ )) + : ranked.map((item) => renderOption(item, false))} +
{ranked.length === 0 ?

{props.empty}

: null}
); diff --git a/packages/hunk/src/web/panel/SidePanel.tsx b/packages/hunk/src/web/panel/SidePanel.tsx index 8241f7f3d..3b617de27 100644 --- a/packages/hunk/src/web/panel/SidePanel.tsx +++ b/packages/hunk/src/web/panel/SidePanel.tsx @@ -10,6 +10,7 @@ * pattern: focusable, with its width bounds, moved by the arrow keys, Home, and End as well as * by dragging; a drag the browser cancels ends like one released. */ +import { Icon } from "../icons/Icon"; import type { KeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from "react"; import { clampSidePanelWidth, @@ -151,7 +152,7 @@ export function SidePanel(props: SidePanelProps) { title={props.closeHint ? `Close side panel (${props.closeHint})` : "Close side panel"} onClick={props.onClose} > - +
) : null} - {`+${index.stats.additions}${index.stats.truncated ? "+" : ""}`}{" "} - {`-${index.stats.deletions}`} + + {formatAddedCount(index.stats.additions, index.stats.truncated)} + {" "} + {formatRemovedCount(index.stats.deletions)} {viewed ? (
); } +/** + * A binary file's byte sizes as the page's resource catalog already states them + * (`135 B → 127 B`, or one size for an added or deleted file); nothing is read to learn them. + */ +export function useBinaryFileSizes(fileKey: string, binary: boolean): string | undefined { + const context = useContext(PreviewContext); + if (!binary || !context) return undefined; + const sizes = (["old", "new"] as const).flatMap((side) => { + const bytes = context + .resources(fileKey) + .find((resource) => resource.kind === "bytes" && resource.side === side); + return bytes?.byteLength !== undefined ? [formatPreviewBytes(bytes.byteLength)] : []; + }); + return sizes.length > 0 ? sizes.join(" → ") : undefined; +} + +/** + * Whether a file that renders no rows still has a body to show: an image preview may stand in + * for a binary image, and a too-large file says why it is not drawn. Every other such file is + * a header-only row whose state chip explains it. + */ +export function emptyFileHasBody(file: ReviewFile, emptyReason: string) { + if (emptyReason === "too-large") return true; + return emptyReason === "binary" && file.flags.binary && isPreviewImagePath(file.path); +} + /** The body: an image preview, rendered Markdown, or the stream's own body. */ export function FilePreviewBody({ fileKey, diff --git a/packages/hunk/src/web/stream/FileSection.tsx b/packages/hunk/src/web/stream/FileSection.tsx index 2aca92908..be2941159 100644 --- a/packages/hunk/src/web/stream/FileSection.tsx +++ b/packages/hunk/src/web/stream/FileSection.tsx @@ -3,28 +3,50 @@ * Draws one file of the review stream: its sticky header and its body. * * The header shows what the terminal's file header shows — change-kind letter, the path with - * `old -> new` for a rename and a state suffix, and right-aligned `+A -D` — from the shared - * labels in `core/review/fileLabels.ts`. The body is Pierre once the file is near the - * viewport, a placeholder for a file with nothing to render (its reason from the shared - * model, its wording this page's own), or space reserved from the file's row count while the - * file is still loading or far away. + * the old name of a rename, and right-aligned `+A −D` that hides zeros — from the shared labels + * in `core/review/fileLabels.ts`. The path dims its directory and a rename's old name so the + * basename reads first, and stays one selectable string. A quiet chip after it says what kind + * of change the file is ("new", "renamed, no content changes", "binary", "too large") from the + * shared model, so a file with nothing to render needs no body sentence: it is a header-only + * row, except a too-large file, whose body says why it is not drawn. The body is otherwise + * Pierre once the file is near the viewport, or space reserved from the file's row count while + * the file is still loading or far away. * - * The header also carries the reviewer's "Viewed" checkbox, and says when a file changed since - * it was marked. A viewed file's body is collapsed to one row that expands it on click; the - * page decides which files are viewed and collapsed (`../viewed/useViewedFiles.ts`). + * The header carries the file's actions: a chevron that collapses and expands the body, a + * copy-path button shown on hover and focus, the reviewer's "Viewed" checkbox, and a marker + * when a file changed since it was marked. A viewed file is collapsed by default and any file + * can be folded; the page decides which files are viewed and collapsed + * (`../viewed/useViewedFiles.ts`). */ -import { memo, useCallback, useContext, useMemo, useRef, type CSSProperties } from "react"; +import { + memo, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + type CSSProperties, +} from "react"; import type { ReviewEmptyDiffReason } from "../../core/review/document"; +import { reviewEmptyDiffReason } from "../../core/review/document"; import type { ReviewStoredNote } from "../../core/review/state"; import type { ReviewAgentHighlight, ReviewSharedNote } from "../../session/reviewSharedState"; import type { NoteComposer } from "../notes/composerStore"; import { planReviewFileNotes } from "../notes/noteProjection"; import type { ReviewNoteInteraction } from "../notes/noteInteraction"; -import { reviewFileChangeGlyph, reviewFileLabelParts } from "../../core/review/fileLabels"; -import { formatAddedCount, formatRemovedCount } from "../format/lineCounts"; +import { reviewFileChangeGlyph } from "../../core/review/fileLabels"; +import { webFileHeaderPath, webFileStateChip } from "../format/fileHeader"; +import { formatAddedBadge, formatRemovedBadge } from "../format/lineCounts"; +import { Icon } from "../icons/Icon"; import type { ReviewFileIndexEntry } from "../mirror/fileIndex"; import type { ReviewFileRenderPlan } from "./fileProjection"; -import { FilePreviewBody, FilePreviewHeaderAction } from "../previews/FilePreviews"; +import { + emptyFileHasBody, + FilePreviewBody, + FilePreviewHeaderAction, + useBinaryFileSizes, +} from "../previews/FilePreviews"; import type { ReviewFileGeometry } from "./hunkGeometry"; import { PierreFileView } from "./PierreFileView"; import { SessionEndedContext } from "../session/sessionEnded"; @@ -34,25 +56,18 @@ import type { ReviewViewedStatus } from "../viewed/viewedFiles"; export const STREAM_ROW_HEIGHT_PX = 20; export const STREAM_HEADER_HEIGHT_PX = 34; -/** Height of a collapsed viewed file's body, in CSS pixels. */ -export const VIEWED_COLLAPSED_HEIGHT_PX = 32; +/** Height of a collapsed file's body, in CSS pixels: the header stands alone. */ +export const COLLAPSED_BODY_HEIGHT_PX = 0; -/** What the viewed controls in a file header do; stable for the page's lifetime. */ +/** What the viewed and collapse controls in a file header do; stable for the page's lifetime. */ export interface ReviewViewedControls { toggle: (fileKey: string) => void; expand: (fileKey: string) => void; collapse: (fileKey: string) => void; } -/** What a file with nothing to render says, per shared reason. */ -export const EMPTY_DIFF_MESSAGES: Record = { - "rename-only": "No textual hunks. This change only renames the file.", - binary: "Binary file skipped", - "too-large": "File too large to render automatically.", - "new-file": "No textual hunks. The file is marked as new.", - "deleted-file": "No textual hunks. The file is marked as deleted.", - "no-hunks": "No textual hunks to render for this file.", -}; +/** What a too-large file's body says; the other empty reasons are told by the header chip. */ +export const TOO_LARGE_MESSAGE = "File too large to render automatically."; export interface FileSectionProps { fileKey: string; @@ -89,9 +104,11 @@ export interface FileSectionProps { interaction: ReviewNoteInteraction; /** This file's viewed mark as the page shows it. */ viewedStatus?: ReviewViewedStatus; - /** Whether the body is collapsed because the file is viewed. */ + /** Whether the body is collapsed: the file is viewed, or the reader folded it. */ collapsed?: boolean; viewed?: ReviewViewedControls; + /** The keymap's chord for the viewed toggle, given only to the selected file's header. */ + viewedKeyHint?: string; /** * Called with the body element each time one is created or removed (with the one it * replaces), so the stream measures every body this file ever has. @@ -101,48 +118,158 @@ export interface FileSectionProps { const NO_HIGHLIGHTS: readonly ReviewAgentHighlight[] = []; +/** How long a copy result shows before the button returns to its icon, in milliseconds. */ +const COPY_FEEDBACK_MS = 2_000; + +/** + * Why a file renders no rows, from the plan once it loads, or from the index entry when that + * already knows the file has no hunks. + */ +function headerEmptyReason( + index: ReviewFileIndexEntry, + plan: ReviewFileRenderPlan | undefined, +): ReviewEmptyDiffReason | undefined { + if (plan) return plan.emptyReason; + if (index.hunkCount !== 0) return undefined; + return reviewEmptyDiffReason({ + changeKind: index.changeKind, + binary: index.flags.binary, + tooLarge: index.flags.tooLarge, + }); +} + +/** Whether a file has a body to collapse: rows to draw, or a preview or message in their place. */ +export function fileHasBody(plan: ReviewFileRenderPlan | undefined) { + return !plan?.emptyReason || emptyFileHasBody(plan.file, plan.emptyReason); +} + +/** The copy-path button, which shows the copy's result briefly the way the toolbar's does. */ +function CopyPathButton({ path }: { path: string }) { + const [copied, setCopied] = useState<"idle" | "copied" | "failed">("idle"); + const timer = useRef | undefined>(undefined); + useEffect(() => () => clearTimeout(timer.current), []); + const label = copied === "copied" ? "Copied" : copied === "failed" ? "Copy failed" : "Copy path"; + + return ( + + ); +} + /** The header row for one file. */ function FileHeader({ index, + plan, fileKey, expandedGaps, onCollapseGaps, viewedStatus, collapsed, viewed, + viewedKeyHint, }: { index?: ReviewFileIndexEntry; + plan?: ReviewFileRenderPlan; fileKey: string; expandedGaps: number; onCollapseGaps: () => void; viewedStatus?: ReviewViewedStatus; collapsed?: boolean; viewed?: ReviewViewedControls; + viewedKeyHint?: string; }) { const sessionEnded = useContext(SessionEndedContext); + const sizes = useBinaryFileSizes(fileKey, index?.flags.binary ?? false); if (!index) { return (
+
); } const glyph = reviewFileChangeGlyph(index.changeKind, index.flags.untracked); - const { filename, stateLabel } = reviewFileLabelParts({ + const path = webFileHeaderPath({ path: index.path, ...(index.previousPath !== undefined ? { previousPath: index.previousPath } : {}), changeKind: index.changeKind, untracked: index.flags.untracked, }); + const emptyReason = headerEmptyReason(index, plan); + const chip = webFileStateChip({ + changeKind: index.changeKind, + untracked: index.flags.untracked, + ...(emptyReason ? { emptyReason } : {}), + ...(sizes ? { sizes } : {}), + }); + const added = formatAddedBadge(index.stats.additions, index.stats.truncated); + const removed = formatRemovedBadge(index.stats.deletions); + // A file with rows to draw can fold; a header-only row has nothing under it to hide. + const hasBody = plan ? fileHasBody(plan) : emptyReason === undefined; + return (
+ {viewed && hasBody ? ( + + ) : ( +
@@ -187,6 +319,7 @@ export function reservedBodyHeight( index: ReviewFileIndexEntry | undefined, layout: "split" | "unified", ) { + if (!fileHasBody(plan)) return 0; const rows = plan ? plan.reservedRows[layout] : index @@ -221,8 +354,8 @@ export const FileSection = memo(function FileSection(props: FileSectionProps) { cards: group.cards.map((card) => ({ ...card, actionsDisabled: true })), })); }, [fileKey, plan, liveNotes, userNotes, showAgentNotes, sidecarNotes, sessionEnded]); - // Collapsing a viewed file removes its body and expanding creates a new one; each is handed - // to the stream's observer for its whole life. + // Collapsing a file removes its body and expanding creates a new one; each is handed to the + // stream's observer for its whole life. const { observeBody } = props; const body = useRef(null); const bodyRef = useCallback( @@ -243,29 +376,21 @@ export const FileSection = memo(function FileSection(props: FileSectionProps) { className="file-section" data-file-key={fileKey} data-selected={props.selected ? "" : undefined} + data-collapsed={props.collapsed && props.viewed ? "" : undefined} aria-label={index?.path ?? "Loading file"} > props.onCollapseGaps(fileKey)} {...(props.viewedStatus ? { viewedStatus: props.viewedStatus } : {})} {...(props.collapsed ? { collapsed: true } : {})} {...(props.viewed ? { viewed: props.viewed } : {})} + {...(props.viewedKeyHint ? { viewedKeyHint: props.viewedKeyHint } : {})} /> - {props.collapsed && props.viewed ? ( - // Not a `.file-body`: the stream measures bodies, and a collapsed one must not stand in - // for the file's real height once it is expanded or unmounted. - - ) : ( + {props.collapsed && props.viewed ? null : (
{!plan ? (

Loading…

- ) : plan.emptyReason ? ( -

- {EMPTY_DIFF_MESSAGES[plan.emptyReason]} -

- ) : mounted ? ( + ) : plan.emptyReason === "too-large" ? ( +

{TOO_LARGE_MESSAGE}

+ ) : plan.emptyReason ? null : mounted ? ( ; - /** Viewed files whose bodies are collapsed. */ + /** Files whose bodies are collapsed: viewed files, and files the reader folded. */ collapsedFiles?: ReadonlySet; - /** What the viewed controls do; stable for the page's lifetime. */ + /** What the viewed and collapse controls do; stable for the page's lifetime. */ viewed?: ReviewViewedControls; + /** The keymap's chord for toggling the selected file's viewed mark, shown on its header. */ + viewedKeyHint?: string; /** What an empty stream says, when the page knows better than "no files". */ emptyMessage?: ReactNode; } @@ -521,7 +523,7 @@ export function ReviewStream(props: ReviewStreamProps) { result.set( slot.key, current.collapsedFiles?.has(slot.key) - ? VIEWED_COLLAPSED_HEIGHT_PX + ? COLLAPSED_BODY_HEIGHT_PX : (heights.get(slot.key) ?? reservedBodyHeight(file ? plan(file) : undefined, slot.index, current.layout)), ); @@ -673,7 +675,7 @@ export function ReviewStream(props: ReviewStreamProps) { }; }, []); - // A viewed file that collapses unmounts its diff view while staying in the mounted window, + // A file that collapses unmounts its diff view while staying in the mounted window, // so its hunk geometry would outlive the drawing it describes. useEffect(() => { for (const fileKey of props.collapsedFiles ?? NO_COLLAPSED) { @@ -681,7 +683,7 @@ export function ReviewStream(props: ReviewStreamProps) { } }, [props.collapsedFiles]); - // Collapsing or opening a viewed file, wrapping, or a layout switch moves every file below + // Collapsing or opening a file, wrapping, or a layout switch moves every file below // it without a scroll; overviews hear about it here as well as from measured bodies. useEffect(() => { for (const listener of Array.from(layoutListeners.current)) listener(); @@ -711,6 +713,7 @@ export function ReviewStream(props: ReviewStreamProps) { measuredHeight={heights.get(slot.key)} selected={selected} {...(selected ? { selectedHunk } : {})} + {...(selected && props.viewedKeyHint ? { viewedKeyHint: props.viewedKeyHint } : {})} {...(slot.key === activeNoteFileKey ? { activeNoteId } : {})} layout={props.layout} wrapLines={props.wrapLines} diff --git a/packages/hunk/src/web/styles.css b/packages/hunk/src/web/styles.css index bab0ffc9a..b8054f8cf 100644 --- a/packages/hunk/src/web/styles.css +++ b/packages/hunk/src/web/styles.css @@ -661,7 +661,7 @@ body { gap: 8px; height: 34px; box-sizing: border-box; - padding: 0 12px; + padding: 0 10px 0 6px; background: var(--hunk-panel); border-bottom: 1px solid var(--hunk-border); font-family: var(--code-font); @@ -701,15 +701,125 @@ body { } .file-name { - flex: 1; + flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-size: 13px; +} + +/* The directory and a rename's old name step back so the basename reads first. */ +.file-path-dir, +.file-path-from { + color: var(--hunk-muted); +} + +.file-path-from { + opacity: 0.8; +} + +.file-path-base { + color: var(--hunk-text); + font-weight: 600; +} + +.file-path-arrow { + display: inline-flex; + vertical-align: -1px; + margin: 0 4px; + color: var(--hunk-muted); +} + +/* Zero-size text: selection and copy still read `old -> new`, the icon draws the arrow. */ +.file-path-arrow-text { + font-size: 0; +} + +.file-section[data-collapsed] .file-path-base { + color: var(--hunk-muted); + font-weight: 400; } -.file-state { +.file-chip { + flex: none; + padding: 0 6px; + font-family: var(--ui-font); + font-size: 11px; + line-height: 18px; + white-space: nowrap; color: var(--hunk-muted); + border: 1px solid var(--hunk-border); + border-radius: 4px; +} + +.file-header-spacer { + flex: 1; + min-width: 0; +} + +/* The header's icon buttons: the collapse chevron and copy path. */ +.file-header-button { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + gap: 4px; + min-width: 24px; + height: 24px; + padding: 0; + font: inherit; + font-family: var(--ui-font); + font-size: 11px; + color: var(--hunk-muted); + background: transparent; + border: 0; + border-radius: 5px; + cursor: pointer; +} + +.file-header-button:hover { + color: var(--hunk-text); + background: var(--hunk-panel-alt); +} + +.file-collapse-spacer { + flex: none; + width: 24px; +} + +.file-header .file-collapse { + margin-right: -6px; +} + +/* Copy path shows on header hover and keyboard focus, and while it reports a result. */ +.file-copy-path { + opacity: 0; +} + +.file-header:hover .file-copy-path, +.file-copy-path:focus-visible, +.file-copy-path[data-state="copied"], +.file-copy-path[data-state="failed"] { + opacity: 1; +} + +.file-copy-path[data-state="copied"], +.file-copy-path[data-state="failed"] { + padding: 0 6px; +} + +.file-copy-path[data-state="copied"] { + color: var(--hunk-badge-added, #1a7f37); +} + +.file-copy-path[data-state="failed"] { + color: var(--hunk-removed-sign-color, #d1242f); +} + +.file-header .segmented.icon-segmented button { + width: 26px; + height: 20px; } .file-stats { @@ -2395,23 +2505,56 @@ body { border-top: 1px solid var(--hunk-border); } -/* Viewed files: header checkbox, "changed since viewed", collapsed body, sidebar and toolbar. */ +/* Viewed files: header checkbox, "changed since viewed", sidebar and toolbar. */ + +/* A real checkbox in a bordered, button-like label; checked, it takes the "added" family. */ .viewed-toggle { display: inline-flex; flex: none; align-items: center; - gap: 4px; + gap: 5px; + height: 24px; + box-sizing: border-box; + padding: 0 7px 0 6px; font-family: var(--ui-font); - font-size: 11px; + font-size: 12px; color: var(--hunk-muted); + border: 1px solid var(--hunk-border); + border-radius: 6px; cursor: pointer; } -.viewed-toggle[data-status="viewed"] { +.viewed-toggle:hover { color: var(--hunk-text); } -.viewed-toggle input, +.viewed-toggle:focus-within:has(:focus-visible) { + outline: 2px solid var(--hunk-accent); + outline-offset: 1px; +} + +.viewed-toggle input:focus-visible { + outline: none; +} + +.viewed-toggle[data-status="viewed"] { + color: var(--hunk-badge-added, #1a7f37); + border-color: color-mix(in srgb, var(--hunk-badge-added, #1a7f37) 45%, transparent); + background: color-mix(in srgb, var(--hunk-badge-added, #1a7f37) 10%, transparent); +} + +.viewed-toggle input { + margin: 0; + accent-color: var(--hunk-badge-added, #1a7f37); + cursor: pointer; +} + +.viewed-toggle .key-hint { + padding: 0 3px; + font-size: 10px; + line-height: 14px; +} + .flat-viewed { margin: 0; accent-color: var(--hunk-accent); @@ -2428,26 +2571,6 @@ body { color: var(--hunk-accent); } -.file-collapsed { - display: flex; - align-items: center; - width: 100%; - padding: 0 16px; - font: inherit; - font-family: var(--ui-font); - font-size: 12px; - color: var(--hunk-muted); - background: var(--hunk-panel-alt); - border: 0; - text-align: left; - cursor: pointer; -} - -.file-collapsed:hover, -.file-collapsed:focus-visible { - color: var(--hunk-text); -} - .flat-row { display: flex; align-items: center; diff --git a/packages/hunk/src/web/viewed/useViewedFiles.ts b/packages/hunk/src/web/viewed/useViewedFiles.ts index d13ecde25..2e6c8a1df 100644 --- a/packages/hunk/src/web/viewed/useViewedFiles.ts +++ b/packages/hunk/src/web/viewed/useViewedFiles.ts @@ -1,7 +1,7 @@ /** * Runs the page's viewed-files workflow: the "Viewed" checkboxes in file headers and sidebar * rows, the `V` chord and palette commands, the toolbar's progress and "Hide viewed" toggle, - * and collapsing viewed files in the stream. + * and collapsing files in the stream. * * Marking a file viewed is shared review state: it is sent as `files/set-viewed` through the * page's one action sender and comes back in the shared-state snapshot, which lists only marks @@ -11,9 +11,11 @@ * file whose content changed since it was marked says so; * - "hide viewed", per browser, which removes viewed files from the stream and the sidebar and * makes navigation walk past them (through the store's `hiddenFileKeys` fact); - * - which viewed files the reader expanded. A viewed file's body is collapsed by default; a - * click expands it, and a hunk reveal into it (`]`, a note jump, an agent's navigation) - * expands it before the stream scrolls there; + * - which files' bodies are collapsed. A viewed file's body is collapsed by default and the + * reader may expand it; any other file is collapsed only while the reader folded it from its + * header's chevron. Either way a hunk reveal into it (`]`, a note jump, an agent's + * navigation) opens it before the stream scrolls there. Folding is per tab and presentation + * only: nothing about it leaves the page; * - the one hidden file an explicit jump revealed. Relative navigation never lands on a hidden * file, so any reveal request that does (a deep link, go to file, an Overview row, a Notes * tab row, an agent's navigation) is one the reader or the agent asked for by name: that file @@ -66,6 +68,14 @@ function writeStored(key: string, value: string) { } } +/** The set without one key, or the same set when it does not hold it. */ +function withoutKey(set: ReadonlySet, key: string): ReadonlySet { + if (!set.has(key)) return set; + const next = new Set(set); + next.delete(key); + return next; +} + /** Remembered sessions kept besides the current one; older ones are pruned on load. */ const REMEMBERED_SESSIONS_KEPT = 8; @@ -125,6 +135,13 @@ export function useViewedFiles(options: UseViewedFilesOptions) { const [memory, setMemory] = useState(() => readMemory(sessionId)); const [hideViewed, setHideViewed] = useState(() => readStored(HIDE_VIEWED_KEY) === "on"); const [expanded, setExpanded] = useState>(() => new Set()); + const [folded, setFolded] = useState>(() => new Set()); + + /** Open one collapsed file, whether it is collapsed as viewed or folded by the reader. */ + const open = useCallback((fileKey: string) => { + setExpanded((current) => (current.has(fileKey) ? current : new Set(current).add(fileKey))); + setFolded((current) => withoutKey(current, fileKey)); + }, []); // Every mark the session lists is remembered at its content, for "changed since viewed"; // a mark it stopped listing while the content stayed the same was cleared, and is forgotten. @@ -175,27 +192,27 @@ export function useViewedFiles(options: UseViewedFilesOptions) { const landing = hunkToken !== absorbed.hunkToken || fileTopToken !== absorbed.fileTopToken ? selectedKey : null; const landingViewed = landing !== null && statuses.get(landing) === "viewed"; - // A hunk reveal opens a collapsed viewed file; any reveal onto a hidden one reveals it. - const opening = landingViewed && hunkToken !== absorbed.hunkToken ? landing : null; + const landingCollapsed = landingViewed || (landing !== null && folded.has(landing)); + // A hunk reveal opens a collapsed file; any reveal onto a hidden one reveals it. + const opening = landingCollapsed && hunkToken !== absorbed.hunkToken ? landing : null; const shownDespiteHide = landingViewed && hideViewed ? landing : landing ? null : revealed; useEffect(() => { if (hunkToken === absorbed.hunkToken && fileTopToken === absorbed.fileTopToken) return; - if (opening) { - setExpanded((current) => (current.has(opening) ? current : new Set(current).add(opening))); - } + if (opening) open(opening); setRevealed(shownDespiteHide); setAbsorbed({ hunkToken, fileTopToken }); - }, [hunkToken, fileTopToken, absorbed, opening, shownDespiteHide]); + }, [hunkToken, fileTopToken, absorbed, opening, shownDespiteHide, open]); const { hidden, collapsed } = useMemo( () => reviewViewedVisibility(statuses, { hideViewed, expanded, + folded, opening, revealed: shownDespiteHide, }), - [statuses, hideViewed, expanded, opening, shownDespiteHide], + [statuses, hideViewed, expanded, folded, opening, shownDespiteHide], ); useEffect(() => { store.setHiddenFiles(hidden); @@ -230,14 +247,10 @@ export function useViewedFiles(options: UseViewedFilesOptions) { stateRevision: outcome.applied.stateRevision, }); // Marking collapses the file again, and hides it again if a jump had revealed it; - // clearing forgets the content it was marked at. + // clearing forgets the content it was marked at and leaves the file open. if (viewed) setRevealed((current) => (current === fileKey ? null : current)); - setExpanded((current) => { - if (!current.has(fileKey)) return current; - const next = new Set(current); - next.delete(fileKey); - return next; - }); + setExpanded((current) => withoutKey(current, fileKey)); + setFolded((current) => withoutKey(current, fileKey)); if (!viewed) setMemory((current) => forgetViewedMark(current, fileKey)); }, [actions, showError], @@ -271,17 +284,20 @@ export function useViewedFiles(options: UseViewedFilesOptions) { [setViewed, statuses], ); - const expand = useCallback((fileKey: string) => { - setExpanded((current) => new Set(current).add(fileKey)); - }, []); + /** Expand one file from its header's chevron. */ + const expand = open; - const collapse = useCallback((fileKey: string) => { - setExpanded((current) => { - const next = new Set(current); - next.delete(fileKey); - return next; - }); - }, []); + /** Collapse one file: a viewed file returns to its default, any other is folded. */ + const collapse = useCallback( + (fileKey: string) => { + if (statuses.get(fileKey) === "viewed") { + setExpanded((current) => withoutKey(current, fileKey)); + return; + } + setFolded((current) => (current.has(fileKey) ? current : new Set(current).add(fileKey))); + }, + [statuses], + ); // Toggling either way ends a jump's reveal: the setting then means what it says. const toggleHideViewed = useCallback(() => { @@ -293,7 +309,7 @@ export function useViewedFiles(options: UseViewedFilesOptions) { }, []); /** - * Open a collapsed viewed file that hunk navigation (`]`, `[`, annotated hunks) just entered. + * Open a collapsed file that hunk navigation (`]`, `[`, annotated hunks) just entered. * * Crossing into the next file reveals its top rather than the hunk, which carries no hunk * reveal for the workflow above to see, so the page's hunk commands call this instead. File @@ -301,10 +317,10 @@ export function useViewedFiles(options: UseViewedFilesOptions) { */ const openForHunk = useCallback( (fileKey: string) => { - if (statuses.get(fileKey) !== "viewed") return; - setExpanded((current) => (current.has(fileKey) ? current : new Set(current).add(fileKey))); + if (statuses.get(fileKey) !== "viewed" && !folded.has(fileKey)) return; + open(fileKey); }, - [statuses], + [statuses, folded, open], ); return { diff --git a/packages/hunk/src/web/viewed/viewedFiles.test.ts b/packages/hunk/src/web/viewed/viewedFiles.test.ts index 28c696744..5b8d366d3 100644 --- a/packages/hunk/src/web/viewed/viewedFiles.test.ts +++ b/packages/hunk/src/web/viewed/viewedFiles.test.ts @@ -96,6 +96,26 @@ describe("viewed files", () => { ).toEqual(["a", "b", "c"]); }); + // Intent: a file the reader folded collapses whatever its mark, is never hidden by "Hide + // viewed", and a navigation opening it unfolds it as it does a viewed file. + test("collapses files the reader folded, unless a navigation opens them", () => { + const statuses = new Map([ + ["a", "unviewed"], + ["b", "changed"], + ["c", "unviewed"], + ] as const); + const visibility = reviewViewedVisibility(statuses, { + hideViewed: true, + expanded: new Set(), + folded: new Set(["a", "b", "c"]), + opening: "c", + revealed: null, + }); + + expect([...visibility.hidden]).toEqual([]); + expect([...visibility.collapsed].sort()).toEqual(["a", "b"]); + }); + test("labels progress as the toolbar shows it", () => { expect(formatReviewViewedProgress({ viewed: 12, total: 47 })).toBe("12 of 47 viewed"); }); diff --git a/packages/hunk/src/web/viewed/viewedFiles.ts b/packages/hunk/src/web/viewed/viewedFiles.ts index 46bb1eac7..1a7d4eace 100644 --- a/packages/hunk/src/web/viewed/viewedFiles.ts +++ b/packages/hunk/src/web/viewed/viewedFiles.ts @@ -84,26 +84,29 @@ export function forgetClearedViewedMarks( return next ?? memory; } -/** What the page shows of its viewed files: which are left out and which are folded to a row. */ +/** What the page shows of its files' bodies: which viewed files are left out, which are folded. */ export interface ReviewViewedVisibility { /** Viewed files "Hide viewed" removes from the stream, the sidebar, and navigation. */ hidden: ReadonlySet; - /** Viewed files drawn as one collapsed row. */ + /** Files drawn as a header alone: viewed files by default, and any file the reader folded. */ collapsed: ReadonlySet; } /** - * Decide which viewed files the page hides and which it collapses. + * Decide which viewed files the page hides and which files it collapses. * * A viewed file is collapsed unless the reader expanded it or a navigation is opening it - * (`opening`), and hidden while "Hide viewed" is on. The one file an explicit jump revealed - * (`revealed`) is the exception to both: it is shown, expanded, despite "Hide viewed". + * (`opening`), and hidden while "Hide viewed" is on. Any other file is collapsed only while the + * reader folded it (`folded`), and a navigation opening it unfolds it the same way. The one + * file an explicit jump revealed (`revealed`) is the exception to all of these: it is shown, + * expanded, despite "Hide viewed". */ export function reviewViewedVisibility( statuses: ReadonlyMap, options: { hideViewed: boolean; expanded: ReadonlySet; + folded?: ReadonlySet; opening: string | null; revealed: string | null; }, @@ -115,6 +118,12 @@ export function reviewViewedVisibility( if (options.hideViewed) hidden.add(key); if (!options.expanded.has(key) && key !== options.opening) collapsed.add(key); } + for (const key of options.folded ?? []) { + if (statuses.get(key) === "viewed" || key === options.revealed || key === options.opening) { + continue; + } + collapsed.add(key); + } return { hidden, collapsed }; } diff --git a/test/web/review-accessibility.e2e.ts b/test/web/review-accessibility.e2e.ts index b144de78f..2e61bd1d0 100644 --- a/test/web/review-accessibility.e2e.ts +++ b/test/web/review-accessibility.e2e.ts @@ -161,7 +161,7 @@ test("passes axe with a viewed file collapsed and with viewed files hidden", asy // The mark shows once the session echoes it back, so click rather than `check()`. await firstSection.locator(".viewed-toggle input").click(); await expect(firstSection.locator(".viewed-toggle input")).toBeChecked(); - await expect(firstSection.locator(".file-collapsed")).toBeVisible(); + await expect(firstSection.locator('.file-collapse[aria-expanded="false"]')).toBeVisible(); expect(await seriousPageViolations(page)).toEqual([]); // With the View menu open, then closed again. diff --git a/test/web/review-interactive.e2e.ts b/test/web/review-interactive.e2e.ts index dfcbdf511..e5c7dad99 100644 --- a/test/web/review-interactive.e2e.ts +++ b/test/web/review-interactive.e2e.ts @@ -284,6 +284,8 @@ test("shares the filter and note visibility with a second page", async ({ page, await page.locator(".review-stream").click({ position: { x: 5, y: 5 } }); await page.keyboard.press("a"); await expect(noteCard(other, "An agent note.")).toHaveCount(0); + // The next press flips this page's own copy of the setting, so wait until it has it too. + await expect(noteCard(page, "An agent note.")).toHaveCount(0); await page.keyboard.press("a"); await expect(noteCard(other, "An agent note.")).toBeVisible(); expect(otherProblems).toEqual([]); diff --git a/test/web/review-palette.e2e.ts b/test/web/review-palette.e2e.ts index c2d02ff99..23de39098 100644 --- a/test/web/review-palette.e2e.ts +++ b/test/web/review-palette.e2e.ts @@ -323,7 +323,7 @@ test("names why a linked file is hidden and opens a collapsed viewed one", async }, ); const main = page.locator("section[data-file-key]").first(); - await expect(main.locator(".file-collapsed")).toHaveCount(0); + await expect(main.locator('.file-collapse[aria-expanded="false"]')).toHaveCount(0); await expect(main.locator("diffs-container")).toHaveCount(1); const keys = await fileKeys(); diff --git a/test/web/review-previews.e2e.ts b/test/web/review-previews.e2e.ts index d442834c9..47b8645b4 100644 --- a/test/web/review-previews.e2e.ts +++ b/test/web/review-previews.e2e.ts @@ -3,8 +3,8 @@ * * Images: a changed PNG compares side by side, by swipe, and by onion skin with sizes and * dimensions; an added and a deleted image show their one side; bytes named like an image - * that are not one keep the stream's "Binary file skipped"; a PNG declaring 30000 × 30000 is - * refused before decoding; an SVG, text or binary, never becomes a blob or an ``, and + * that are not one keep a header-only row whose chip says "binary"; a PNG declaring + * 30000 × 30000 is refused before decoding; an SVG, text or binary, never becomes a blob or an ``, and * every blob the page mints has a raster type. Markdown: the header toggle swaps * a file's diff for its rendered text, a deleted file renders its old text, and nothing in the * document runs. No CSP violation or console error, and axe stays green. @@ -89,9 +89,11 @@ test("shows added and deleted images single-sided, and keeps the placeholder for /^Deleted · 16 × 16/, ); await section(page, "images/fake.png").scrollIntoViewIfNeeded(); + // Not an image: a header-only row whose chip says binary. await expect(section(page, "images/fake.png").locator('[data-empty-reason="binary"]')).toHaveText( - "Binary file skipped", + /^binary/, ); + await expect(section(page, "images/fake.png").locator(".file-placeholder")).toHaveCount(0); await expect(section(page, "images/fake.png").locator("img")).toHaveCount(0); }); @@ -129,7 +131,7 @@ test("never turns an SVG into a blob or an image, text or binary", async ({ page // A binary SVG keeps the stream's placeholder. const packed = section(page, "images/packed.svg"); await packed.scrollIntoViewIfNeeded(); - await expect(packed.locator('[data-empty-reason="binary"]')).toHaveText("Binary file skipped"); + await expect(packed.locator('[data-empty-reason="binary"]')).toHaveText(/binary/); await expect(packed.locator("img")).toHaveCount(0); const types = await page.evaluate(() => (window as { __blobTypes?: string[] }).__blobTypes); @@ -179,10 +181,11 @@ test("toggles a Markdown file between its diff and its rendered text, inertly", }) => { const guide = section(page, "docs/guide.md"); await guide.scrollIntoViewIfNeeded(); - // Two segments name both views; the checked one is the view showing. + // Two icon segments name both views; the checked one is the view showing. const diffMode = guide.getByTestId("markdown-mode-diff"); const renderedMode = guide.getByTestId("markdown-mode-rendered"); - await expect(guide.getByTestId("markdown-mode")).toHaveText("DiffRendered"); + await expect(diffMode).toHaveAccessibleName("Diff"); + await expect(renderedMode).toHaveAccessibleName("Rendered"); await expect(diffMode).toHaveAttribute("aria-checked", "true"); await expect(renderedMode).toHaveAttribute("aria-checked", "false"); await renderedMode.click(); diff --git a/test/web/review-shell.e2e.ts b/test/web/review-shell.e2e.ts index 586e2e0fe..db108a2ca 100644 --- a/test/web/review-shell.e2e.ts +++ b/test/web/review-shell.e2e.ts @@ -283,7 +283,7 @@ test("c expands a collapsed viewed file and opens its composer", async ({ page } .first() .click(); await page.keyboard.press("Shift+V"); - await expect(main.locator(".file-collapsed")).toBeVisible(); + await expect(main.locator('.file-collapse[aria-expanded="false"]')).toBeVisible(); await page.locator(".review-stream").focus(); await page.keyboard.press("c"); diff --git a/test/web/review-stream.e2e.ts b/test/web/review-stream.e2e.ts index 5d0dbf6fb..a0fe04a52 100644 --- a/test/web/review-stream.e2e.ts +++ b/test/web/review-stream.e2e.ts @@ -76,19 +76,96 @@ test("loads progressively and shows every file shape", async ({ page }) => { expect( await page.evaluate(() => (window as unknown as { __sawProgress?: boolean }).__sawProgress), ).toBe(true); + // A file with nothing to render says why in its header chip. await expect(page.locator('[data-empty-reason="rename-only"]')).toHaveText( - "No textual hunks. This change only renames the file.", - ); - await expect(page.locator('[data-empty-reason="binary"]')).toHaveText("Binary file skipped"); - await expect(page.locator('[data-empty-reason="too-large"]')).toHaveText( - "File too large to render automatically.", + "renamed, no content changes", ); + await expect(page.locator('[data-empty-reason="binary"]')).toHaveText(/^binary/); + await expect(page.locator('[data-empty-reason="too-large"]')).toHaveText("too large"); await expect(page.locator(".file-path", { hasText: "docs/日本語 ノート.md" })).toBeVisible(); await expect( page.locator(".file-path", { hasText: "src/app/renamed-old.ts -> renamed-new.ts" }), ).toBeVisible(); }); +// Intent: a header says what kind of change a file is in a chip instead of a body sentence; +// rename-only and binary files are header-only rows, a too-large file keeps one row saying why, +// and a file without line changes prints no `+0 −0`. +test("states each file's kind in its header", async ({ page }) => { + await openTestReview(page); + const section = (path: string) => page.locator(`section.file-section[aria-label="${path}"]`); + + await expect(section("docs/日本語 ノート.md").locator(".file-chip")).toHaveText("new"); + await expect(section("old/legacy.txt").locator(".file-chip")).toHaveText("deleted"); + await expect(section("src/app/main.ts").locator(".file-chip")).toHaveCount(0); + await expect(section("old/legacy.txt").locator(".file-stats")).toHaveText("−2"); + + const logo = section("assets/logo.svg"); + await logo.scrollIntoViewIfNeeded(); + await expect(logo.locator(".file-path")).toHaveText("assets/logo-old.svg -> logo.svg"); + await expect(logo.locator(".file-stats")).toHaveCount(0); + await expect(logo.locator(".file-placeholder")).toHaveCount(0); + await expect(logo.locator(".file-collapse")).toHaveCount(0); + expect( + await logo.locator(".file-body").evaluate((body) => (body as HTMLElement).offsetHeight), + ).toBe(0); + + const image = section("assets/image.png"); + await expect(image.locator(".file-chip")).toHaveText(/^binary/); + await expect(image.locator(".file-placeholder")).toHaveCount(0); + + const huge = section("data/huge.json"); + await huge.scrollIntoViewIfNeeded(); + await expect(huge.locator(".file-chip")).toHaveText("too large"); + await expect(huge.locator(".file-placeholder")).toHaveText( + "File too large to render automatically.", + ); +}); + +// Intent: the chevron folds any file's body, viewed or not, without marking it; hunk +// navigation into a folded file opens it. +test("folds and unfolds a file from its header chevron", async ({ page }) => { + await openTestReview(page); + const main = page.locator('section.file-section[aria-label="src/app/main.ts"]'); + const chevron = main.locator(".file-collapse"); + + await expect(chevron).toHaveAttribute("aria-expanded", "true"); + await chevron.click(); + await expect(chevron).toHaveAttribute("aria-expanded", "false"); + await expect(main.locator(".file-body")).toHaveCount(0); + await expect(main.locator(".viewed-toggle input")).not.toBeChecked(); + await chevron.press("Enter"); + await expect(chevron).toHaveAttribute("aria-expanded", "true"); + await expect(main.locator(".file-body")).toBeVisible(); + + await chevron.click(); + await page.locator(".review-stream").focus(); + await page.keyboard.press("]"); + await page.keyboard.press("["); + await expect(page.locator("section[data-selected]")).toHaveAttribute( + "aria-label", + "src/app/main.ts", + ); + await expect(main.locator(".file-body")).toBeVisible(); +}); + +// Intent: the header's copy button puts the file's path on the clipboard (the new path of a +// rename) and says so, the way the toolbar's copy link does. +test("copies a file's path from its header", async ({ page }) => { + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + await openTestReview(page); + const renamed = page.locator('section.file-section[aria-label="src/app/renamed-new.ts"]'); + const copy = renamed.locator(".file-copy-path"); + + await expect(copy).toHaveCSS("opacity", "0"); + await renamed.locator(".file-header").hover(); + await expect(copy).toHaveCSS("opacity", "1"); + await copy.click(); + await expect(copy).toHaveAttribute("data-state", "copied"); + await expect(copy).toHaveText("Copied"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("src/app/renamed-new.ts"); +}); + test("jumps from the sidebar to the stream and follows the stream back", async ({ page }) => { await openTestReview(page); await page.getByRole("radio", { name: "Flat" }).click(); diff --git a/test/web/review-tools.e2e.ts b/test/web/review-tools.e2e.ts index 9f452660e..a7717e960 100644 --- a/test/web/review-tools.e2e.ts +++ b/test/web/review-tools.e2e.ts @@ -338,7 +338,7 @@ test("the minimap repaints when a file collapses without a scroll", async ({ pag const drift = await minimapHeightDrift(page); await page.locator("section[data-file-key]").first().locator(".viewed-toggle input").click(); - await expect(page.locator(".file-collapsed").first()).toBeVisible(); + await expect(page.locator('.file-collapse[aria-expanded="false"]').first()).toBeVisible(); // The stream settles over a frame or two after the collapse and the minimap repaints one // frame behind it, so the two are compared once they agree rather than at one instant. @@ -385,7 +385,7 @@ test("the minimap dims a file's block once it is marked viewed", async ({ page } const open = await minimapAlphaAt(page, 8, 0); await page.locator("section[data-file-key]").first().locator(".viewed-toggle input").click(); - await expect(page.locator(".file-collapsed").first()).toBeVisible(); + await expect(page.locator('.file-collapse[aria-expanded="false"]').first()).toBeVisible(); await expect.poll(() => minimapAlphaAt(page, 8, 0)).toBeLessThan(open * 0.6); expect(await minimapAlphaAt(page, 8, 0)).toBeGreaterThan(0); @@ -415,7 +415,7 @@ test("keeps measuring a file body re-created by expanding a viewed file", async await page.waitForTimeout(500); await last.locator(".viewed-toggle input").click(); - await last.locator(".file-collapsed").click(); + await last.locator('.file-collapse[aria-expanded="false"]').click(); await expect.poll(mounted).toBe(true); await page.waitForTimeout(500); const drift = await minimapHeightDrift(page); diff --git a/test/web/review-viewed.e2e.ts b/test/web/review-viewed.e2e.ts index 72f14c3e5..eaaf4db38 100644 --- a/test/web/review-viewed.e2e.ts +++ b/test/web/review-viewed.e2e.ts @@ -100,12 +100,12 @@ test("marks a file viewed from its header, collapses it, and counts it everywher await expect(page.getByTestId("overview-viewed")).toContainText("1 of"); // Collapsed to one row; a click expands it and the header can collapse it again. - await expect(main.locator(".file-collapsed")).toBeVisible(); + await expect(main.locator('.file-collapse[aria-expanded="false"]')).toBeVisible(); await expect(main.locator(".file-body")).toHaveCount(0); - await main.locator(".file-collapsed").click(); + await main.locator('.file-collapse[aria-expanded="false"]').click(); await expect(main.locator(".file-body")).toBeVisible(); - await main.getByRole("button", { name: "Collapse" }).click(); - await expect(main.locator(".file-collapsed")).toBeVisible(); + await main.getByRole("button", { name: "Collapse file" }).click(); + await expect(main.locator('.file-collapse[aria-expanded="false"]')).toBeVisible(); // Navigating into a collapsed viewed file by hunk opens it where the reveal lands. await page.locator(".review-stream").focus(); @@ -116,7 +116,7 @@ test("marks a file viewed from its header, collapses it, and counts it everywher "src/app/main.ts", ); await expect(main.locator(".file-body")).toBeVisible(); - await main.getByRole("button", { name: "Collapse" }).click(); + await main.getByRole("button", { name: "Collapse file" }).click(); // Clearing the mark from the keyboard-free mouse path in the flat sidebar. await page.getByRole("radio", { name: "Flat" }).click(); @@ -128,6 +128,27 @@ test("marks a file viewed from its header, collapses it, and counts it everywher await expect(headerCheckbox(page, "src/app/main.ts")).not.toBeChecked(); }); +// Intent: only the selected file's Viewed control shows the toggle's chord, and it is the +// chord the page's keymap binds (the palette lists the same one), never a fixed letter. +test("shows the viewed chord on the selected file's header only", async ({ page }) => { + await openTestReview(page); + await page.keyboard.press("Control+k"); + const palette = page.getByTestId("command-palette"); + await page.keyboard.type("Mark the selected file viewed"); + const chord = await palette.getByRole("option").first().locator("kbd.key-hint").textContent(); + await page.keyboard.press("Escape"); + + await expect(page.locator(".viewed-toggle .key-hint")).toHaveCount(1); + await expect(page.locator("section[data-selected] .viewed-toggle .key-hint")).toHaveText(chord!); + const checkbox = headerCheckbox(page, "src/app/main.ts"); + await checkbox.click(); + await expect(checkbox).toBeChecked(); + await expect(section(page, "src/app/main.ts").locator(".viewed-toggle")).toHaveCSS( + "border-top-style", + "solid", + ); +}); + test("toggles the selected file with V and shares the mark with a second page", async ({ page, context, @@ -143,7 +164,9 @@ test("toggles the selected file with V and shares the mark with a second page", timeout: 30_000, }); await expect(headerCheckbox(second, "src/app/main.ts")).toBeChecked(); - await expect(section(second, "src/app/main.ts").locator(".file-collapsed")).toBeVisible(); + await expect( + section(second, "src/app/main.ts").locator('.file-collapse[aria-expanded="false"]'), + ).toBeVisible(); await page.keyboard.press("V"); await expect(headerCheckbox(page, "src/app/main.ts")).not.toBeChecked(); @@ -291,7 +314,7 @@ test("opens a collapsed viewed file that hunk navigation enters", async ({ page await openTestReview(page); await headerCheckbox(page, "src/app/renamed-new.ts").click(); const renamed = section(page, "src/app/renamed-new.ts"); - await expect(renamed.locator(".file-collapsed")).toBeVisible(); + await expect(renamed.locator('.file-collapse[aria-expanded="false"]')).toBeVisible(); await page.locator(".review-stream").click({ position: { x: 5, y: 5 } }); await expect.poll(() => selectedPath(page)).toBe("src/app/main.ts"); @@ -299,15 +322,15 @@ test("opens a collapsed viewed file that hunk navigation enters", async ({ page await page.keyboard.press("]"); await expect.poll(() => selectedPath(page)).toBe("src/app/renamed-new.ts"); await expect(renamed.locator(".file-body")).toBeVisible(); - await expect(renamed.locator(".file-collapsed")).toHaveCount(0); + await expect(renamed.locator('.file-collapse[aria-expanded="false"]')).toHaveCount(0); // File navigation lands on the collapsed row and leaves it collapsed. - await renamed.getByRole("button", { name: "Collapse" }).click(); + await renamed.getByRole("button", { name: "Collapse file" }).click(); await page.locator(".review-stream").focus(); await page.keyboard.press(","); await page.keyboard.press("."); await expect.poll(() => selectedPath(page)).toBe("src/app/renamed-new.ts"); - await expect(renamed.locator(".file-collapsed")).toBeVisible(); + await expect(renamed.locator('.file-collapse[aria-expanded="false"]')).toBeVisible(); }); // Intent: a mark cleared in another browser leaves the shared state while the content still @@ -342,7 +365,9 @@ test("has no serious accessibility violations with viewed files", async ({ page await openTestReview(page); await headerCheckbox(page, "src/app/main.ts").click(); await page.getByRole("radio", { name: "Flat" }).click(); - await expect(section(page, "src/app/main.ts").locator(".file-collapsed")).toBeVisible(); + await expect( + section(page, "src/app/main.ts").locator('.file-collapse[aria-expanded="false"]'), + ).toBeVisible(); const results = await new AxeBuilder({ page }) .exclude("diffs-container") .exclude("file-tree-container") From a03d8ab109ea987c775fdf5a9270c43ddab13ffc Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:24:27 -0500 Subject: [PATCH 08/12] fix(web): rename the header's old-path class so the seam gate reads it right MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The source-boundary gate scans for `from "…"` to find module specifiers, and a class name ending in `from` followed by a quote matched it. The old-path span is now `file-path-previous`, and the helper's field is `previous` to match. Co-Authored-By: Claude Fable 5.2 --- packages/hunk/src/web/format/fileHeader.test.ts | 6 +++--- packages/hunk/src/web/format/fileHeader.ts | 8 ++++---- packages/hunk/src/web/stream/FileSection.tsx | 4 ++-- packages/hunk/src/web/styles.css | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/hunk/src/web/format/fileHeader.test.ts b/packages/hunk/src/web/format/fileHeader.test.ts index f0649fe41..8daebe639 100644 --- a/packages/hunk/src/web/format/fileHeader.test.ts +++ b/packages/hunk/src/web/format/fileHeader.test.ts @@ -20,7 +20,7 @@ describe("webFileHeaderPath", () => { }); expect(sameDirectory).toEqual({ text: "src/app/renamed-old.ts -> renamed-new.ts", - from: "src/app/renamed-old.ts", + previous: "src/app/renamed-old.ts", directory: "", basename: "renamed-new.ts", }); @@ -33,11 +33,11 @@ describe("webFileHeaderPath", () => { }); expect(moved).toEqual({ text: "a/old.ts -> b/new.ts", - from: "a/old.ts", + previous: "a/old.ts", directory: "b/", basename: "new.ts", }); - expect(`${moved.from} -> ${moved.directory}${moved.basename}`).toBe(moved.text); + expect(`${moved.previous} -> ${moved.directory}${moved.basename}`).toBe(moved.text); }); }); diff --git a/packages/hunk/src/web/format/fileHeader.ts b/packages/hunk/src/web/format/fileHeader.ts index 919b64644..f2731e9f3 100644 --- a/packages/hunk/src/web/format/fileHeader.ts +++ b/packages/hunk/src/web/format/fileHeader.ts @@ -16,7 +16,7 @@ export interface WebFileHeaderPath { /** The whole label, as the header's text content and tooltip read it. */ text: string; /** The old path of a rename, drawn dimmed before the arrow. */ - from?: string; + previous?: string; /** The shown path's directory with its trailing slash, or empty. */ directory: string; basename: string; @@ -31,12 +31,12 @@ export function webFileHeaderPath(file: { }): WebFileHeaderPath { const { filename } = reviewFileLabelParts(file); const renamed = file.previousPath !== undefined && file.previousPath !== file.path; - const from = renamed ? file.previousPath : undefined; - const shown = from !== undefined ? filename.slice(from.length + " -> ".length) : filename; + const previous = renamed ? file.previousPath : undefined; + const shown = previous !== undefined ? filename.slice(previous.length + " -> ".length) : filename; const slash = shown.lastIndexOf("/"); return { text: filename, - ...(from !== undefined ? { from } : {}), + ...(previous !== undefined ? { previous } : {}), directory: shown.slice(0, slash + 1), basename: shown.slice(slash + 1), }; diff --git a/packages/hunk/src/web/stream/FileSection.tsx b/packages/hunk/src/web/stream/FileSection.tsx index be2941159..6cacf9666 100644 --- a/packages/hunk/src/web/stream/FileSection.tsx +++ b/packages/hunk/src/web/stream/FileSection.tsx @@ -249,9 +249,9 @@ function FileHeader({ - {path.from !== undefined ? ( + {path.previous !== undefined ? ( <> - {path.from} + {path.previous} {/* The arrow's text, so a copied or read path still says `old -> new`. */} diff --git a/packages/hunk/src/web/styles.css b/packages/hunk/src/web/styles.css index b8054f8cf..6ad2ecd46 100644 --- a/packages/hunk/src/web/styles.css +++ b/packages/hunk/src/web/styles.css @@ -711,11 +711,11 @@ body { /* The directory and a rename's old name step back so the basename reads first. */ .file-path-dir, -.file-path-from { +.file-path-previous { color: var(--hunk-muted); } -.file-path-from { +.file-path-previous { opacity: 0.8; } From 32ab15b066de15884103961dc1f3fa7dda539ea7 Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:40:43 -0500 Subject: [PATCH 09/12] feat(web): show review state in the files sidebar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The browser review page's sidebar encoded review state in terse glyphs: `*2` for notes, `✓` for viewed, `Δ` for changed since viewed. A note count is now a comment mark with the number, a viewed file dims and gets a green check, a file changed since viewed gets a refresh mark, and a folder shows how much of it is viewed (`1/40`). The header shows the file count, and Tree / Flat is an icon radiogroup. Co-Authored-By: Claude Fable 5.2 --- .changeset/web-sidebar-review-state.md | 5 + packages/hunk/src/web/app/ReviewApp.tsx | 77 +++++++-- packages/hunk/src/web/icons/iconPaths.tsx | 8 + packages/hunk/src/web/sidebar/FileSidebar.tsx | 67 ++++++-- packages/hunk/src/web/sidebar/TreeSidebar.tsx | 154 +++++++++++++++--- .../hunk/src/web/sidebar/viewedRollup.test.ts | 89 ++++++++++ packages/hunk/src/web/sidebar/viewedRollup.ts | 88 ++++++++++ packages/hunk/src/web/styles.css | 71 ++++++-- test/web/review-notes.e2e.ts | 6 +- test/web/review-tools-screenshots.e2e.ts | 5 + test/web/review-viewed.e2e.ts | 79 +++++++++ 11 files changed, 588 insertions(+), 61 deletions(-) create mode 100644 .changeset/web-sidebar-review-state.md create mode 100644 packages/hunk/src/web/sidebar/viewedRollup.test.ts create mode 100644 packages/hunk/src/web/sidebar/viewedRollup.ts diff --git a/.changeset/web-sidebar-review-state.md b/.changeset/web-sidebar-review-state.md new file mode 100644 index 000000000..df819c5bf --- /dev/null +++ b/.changeset/web-sidebar-review-state.md @@ -0,0 +1,5 @@ +--- +"hunkdiff": patch +--- + +The browser review page's files sidebar now shows review state at a glance: note counts as a comment icon, viewed files dimmed with a check, a refresh mark on files changed since they were viewed, viewed counts on folders, and the file count and an icon Tree / Flat switch in its header. diff --git a/packages/hunk/src/web/app/ReviewApp.tsx b/packages/hunk/src/web/app/ReviewApp.tsx index 65215d43c..c2256eaae 100644 --- a/packages/hunk/src/web/app/ReviewApp.tsx +++ b/packages/hunk/src/web/app/ReviewApp.tsx @@ -34,6 +34,7 @@ import { useState, useSyncExternalStore, type CSSProperties, + type KeyboardEvent, type PointerEvent as ReactPointerEvent, } from "react"; import { selectActiveRevealNoteId } from "../../core/review/selectors"; @@ -56,6 +57,8 @@ import { reviewFailureMessage, type ReviewSession } from "../session/reviewSessi import { REVIEW_SESSION_ENDED_MESSAGE } from "../session/failureMessages"; import { SessionEndedContext } from "../session/sessionEnded"; import { FileSidebar } from "../sidebar/FileSidebar"; +import { formatCount } from "../format/lineCounts"; +import { Icon, type IconName } from "../icons/Icon"; import { isLocalReviewIntent } from "../store/clientReviewStore"; import { ReviewStream, @@ -212,6 +215,30 @@ function useWebTheme(sessionTheme: ReviewThemeDefaults | undefined) { const NO_HIGHLIGHTS = {}; +/** The files sidebar's two modes as icon radios, each named by its old text label. */ +const SIDEBAR_MODES: readonly { + mode: "tree" | "flat"; + label: string; + title: string; + icon: IconName; + command: WebLocalCommandId; +}[] = [ + { + mode: "tree", + label: "Tree", + title: "Show files as a tree", + icon: "tree", + command: "hunk.web.filesAsTree", + }, + { + mode: "flat", + label: "Flat", + title: "Show files as a flat list", + icon: "list", + command: "hunk.web.filesAsList", + }, +]; + /** Below this viewport or stream width the minimap hides, leaving the room to the diff. */ const MINIMAP_MIN_VIEWPORT = 1000; const MINIMAP_MIN_STREAM_WIDTH = 560; @@ -805,6 +832,17 @@ export function ReviewApp({ session }: { session: ReviewSession }) { const pageHint = (commandId: WebLocalCommandId) => webCommandChords(pageKeymap, commandId).map(formatKeyChord).join(" / ") || undefined; const panelHint = pageHint("hunk.web.toggleSidePanel"); + + // Arrow keys move the choice within the sidebar mode group, as in any radio group. + const onSidebarModeKeyDown = (event: KeyboardEvent) => { + const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]; + if (step === undefined) return; + event.preventDefault(); + const index = SIDEBAR_MODES.findIndex(({ mode }) => mode === preferences.sidebarMode); + const next = SIDEBAR_MODES[(index + step + SIDEBAR_MODES.length) % SIDEBAR_MODES.length]!; + updatePreferences({ sidebarMode: next.mode }); + event.currentTarget.querySelector(`[data-mode="${next.mode}"]`)?.focus(); + }; // The palette's chord is a page-only Ctrl/Cmd chord, so it is read from the page's command // table rather than the keymap; the Commands button never names a key of its own. const paletteCommand = WEB_LOCAL_COMMANDS.find( @@ -998,19 +1036,32 @@ export function ReviewApp({ session }: { session: ReviewSession }) { <>