diff --git a/.changeset/web-file-headers.md b/.changeset/web-file-headers.md new file mode 100644 index 000000000..652634948 --- /dev/null +++ b/.changeset/web-file-headers.md @@ -0,0 +1,5 @@ +--- +"hunkdiff": patch +--- + +The browser review page's file headers dim the directory so the file name reads first, say what kind of change a file is in a quiet chip ("new", "renamed, no content changes", "binary", "too large") instead of a body sentence, hide `+0 −0`, fold any file from a chevron (viewed files start folded, with no extra row), copy the file's path from a button shown on hover, and draw the Viewed checkbox as a bordered control that turns green when checked. diff --git a/packages/hunk/src/web/app/ReviewApp.tsx b/packages/hunk/src/web/app/ReviewApp.tsx index 6b6ae497a..65215d43c 100644 --- a/packages/hunk/src/web/app/ReviewApp.tsx +++ b/packages/hunk/src/web/app/ReviewApp.tsx @@ -1055,6 +1055,9 @@ export function ReviewApp({ session }: { session: ReviewSession }) { viewedStatuses={viewed.statuses} collapsedFiles={viewed.collapsed} viewed={viewedControls} + {...(pageHint("hunk.web.toggleViewed") + ? { viewedKeyHint: pageHint("hunk.web.toggleViewed") } + : {})} {...(streamSlots.length === 0 && visibleSlots.length > 0 ? { emptyMessage: ( diff --git a/packages/hunk/src/web/format/fileHeader.test.ts b/packages/hunk/src/web/format/fileHeader.test.ts new file mode 100644 index 000000000..8daebe639 --- /dev/null +++ b/packages/hunk/src/web/format/fileHeader.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, test } from "bun:test"; +import { webFileHeaderPath, webFileStateChip } from "./fileHeader"; + +describe("webFileHeaderPath", () => { + test("splits a path into its directory and basename", () => { + expect( + webFileHeaderPath({ path: "src/app/main.ts", changeKind: "change", untracked: false }), + ).toEqual({ text: "src/app/main.ts", directory: "src/app/", basename: "main.ts" }); + expect( + webFileHeaderPath({ path: "README.md", changeKind: "change", untracked: false }), + ).toEqual({ text: "README.md", directory: "", basename: "README.md" }); + }); + + test("keeps a rename's old name apart and its text as the shared label", () => { + const sameDirectory = webFileHeaderPath({ + path: "src/app/renamed-new.ts", + previousPath: "src/app/renamed-old.ts", + changeKind: "rename-changed", + untracked: false, + }); + expect(sameDirectory).toEqual({ + text: "src/app/renamed-old.ts -> renamed-new.ts", + previous: "src/app/renamed-old.ts", + directory: "", + basename: "renamed-new.ts", + }); + + const moved = webFileHeaderPath({ + path: "b/new.ts", + previousPath: "a/old.ts", + changeKind: "rename-pure", + untracked: false, + }); + expect(moved).toEqual({ + text: "a/old.ts -> b/new.ts", + previous: "a/old.ts", + directory: "b/", + basename: "new.ts", + }); + expect(`${moved.previous} -> ${moved.directory}${moved.basename}`).toBe(moved.text); + }); +}); + +describe("webFileStateChip", () => { + test("names the change kind and says nothing for a plain modification", () => { + expect(webFileStateChip({ changeKind: "change", untracked: false })).toBeNull(); + expect(webFileStateChip({ changeKind: "new", untracked: false })).toBe("new"); + expect(webFileStateChip({ changeKind: "new", untracked: true })).toBe("untracked"); + expect(webFileStateChip({ changeKind: "deleted", untracked: false })).toBe("deleted"); + }); + + test("says why a file renders no rows", () => { + expect( + webFileStateChip({ changeKind: "rename-pure", untracked: false, emptyReason: "rename-only" }), + ).toBe("renamed, no content changes"); + expect( + webFileStateChip({ changeKind: "change", untracked: false, emptyReason: "binary" }), + ).toBe("binary"); + expect( + webFileStateChip({ changeKind: "change", untracked: false, emptyReason: "too-large" }), + ).toBe("too large"); + expect(webFileStateChip({ changeKind: "new", untracked: false, emptyReason: "new-file" })).toBe( + "new · empty", + ); + }); + + test("adds a binary file's sizes when given", () => { + expect( + webFileStateChip({ + changeKind: "change", + untracked: false, + emptyReason: "binary", + sizes: "135 B → 127 B", + }), + ).toBe("binary · 135 B → 127 B"); + }); +}); diff --git a/packages/hunk/src/web/format/fileHeader.ts b/packages/hunk/src/web/format/fileHeader.ts new file mode 100644 index 000000000..f2731e9f3 --- /dev/null +++ b/packages/hunk/src/web/format/fileHeader.ts @@ -0,0 +1,79 @@ +/** + * Words and path pieces the stream's file headers print. + * + * The header path is the shared label from `core/review/fileLabels.ts` (`old -> new` for a + * rename), split so the page can dim the directory and the old name while the text stays one + * copyable string. The state chip names what kind of change a file is from facts the review + * document already carries — its change kind, untracked flag, and the shared reason a file + * renders no rows — so the page never re-derives a file's kind on its own. + */ +import type { ReviewEmptyDiffReason } from "../../core/review/document"; +import { reviewFileLabelParts } from "../../core/review/fileLabels"; +import type { ReviewFileChangeKind } from "../../core/review/types"; + +/** The header path for one file, in the pieces the header styles differently. */ +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. */ + previous?: string; + /** The shown path's directory with its trailing slash, or empty. */ + directory: string; + basename: string; +} + +/** Split one file's header label into its old name, directory, and basename. */ +export function webFileHeaderPath(file: { + path: string; + previousPath?: string; + changeKind: ReviewFileChangeKind; + untracked: boolean; +}): WebFileHeaderPath { + const { filename } = reviewFileLabelParts(file); + const renamed = file.previousPath !== undefined && file.previousPath !== file.path; + const previous = renamed ? file.previousPath : undefined; + const shown = previous !== undefined ? filename.slice(previous.length + " -> ".length) : filename; + const slash = shown.lastIndexOf("/"); + return { + text: filename, + ...(previous !== undefined ? { previous } : {}), + directory: shown.slice(0, slash + 1), + basename: shown.slice(slash + 1), + }; +} + +/** What a file's state chip says about a file with nothing to render, per shared reason. */ +const EMPTY_REASON_WORDS: Record = { + "rename-only": null, + binary: "binary", + "too-large": "too large", + "new-file": "empty", + "deleted-file": "empty", + "no-hunks": "no textual changes", +}; + +/** + * The quiet chip after a file's path: "new", "deleted", "untracked", "renamed, no content + * changes", and for a file that renders no rows the shared reason ("binary", "too large"), + * joined with ` · `. Returns null for an ordinary modified file. + * + * `sizes` is extra detail a binary file may carry when the page already holds it. + */ +export function webFileStateChip(file: { + changeKind: ReviewFileChangeKind; + untracked: boolean; + emptyReason?: ReviewEmptyDiffReason; + sizes?: string; +}): string | null { + const words: string[] = []; + if (file.untracked) words.push("untracked"); + else if (file.changeKind === "new") words.push("new"); + else if (file.changeKind === "deleted") words.push("deleted"); + if (file.changeKind === "rename-pure" || file.emptyReason === "rename-only") { + words.push("renamed, no content changes"); + } + const reason = file.emptyReason ? EMPTY_REASON_WORDS[file.emptyReason] : null; + if (reason) words.push(reason); + if (file.emptyReason === "binary" && file.sizes) words.push(file.sizes); + return words.length > 0 ? words.join(" · ") : null; +} diff --git a/packages/hunk/src/web/icons/iconPaths.tsx b/packages/hunk/src/web/icons/iconPaths.tsx index ed3174dce..3759f7092 100644 --- a/packages/hunk/src/web/icons/iconPaths.tsx +++ b/packages/hunk/src/web/icons/iconPaths.tsx @@ -78,6 +78,24 @@ export const ICON_PATHS = { "chevron-right": , /** A chevron pointing up. */ "chevron-up": , + /** An arrow pointing right. */ + "arrow-right": , + /** Two overlapping sheets. */ + copy: ( + <> + + + + ), + /** Angle brackets around code. */ + code: , + /** An open eye. */ + eye: ( + <> + + + + ), /** A check mark. */ check: , /** A cross. */ diff --git a/packages/hunk/src/web/previews/FilePreviews.tsx b/packages/hunk/src/web/previews/FilePreviews.tsx index 5e5177a7e..47c5830da 100644 --- a/packages/hunk/src/web/previews/FilePreviews.tsx +++ b/packages/hunk/src/web/previews/FilePreviews.tsx @@ -1,15 +1,17 @@ /** @jsxImportSource react */ /** - * The stream's preview slots: a header toggle for Markdown files, and a body that shows an - * image preview or rendered Markdown in place of the default body when either applies. + * The stream's preview slots: a header toggle for Markdown files, a binary file's byte sizes + * for its header chip, and a body that shows an image preview or rendered Markdown in place of + * the default body when either applies. * * The stream renders these slots and knows nothing else about previews; everything they read * comes from `PreviewContext`, which the page provides. */ import { useContext, useSyncExternalStore, type ReactNode } from "react"; import type { ReviewFile } from "../../core/review/types"; +import { Icon, type IconName } from "../icons/Icon"; import { isPreviewImagePath } from "./imageSniff"; -import { ImagePreview } from "./ImagePreview"; +import { formatPreviewBytes, ImagePreview } from "./ImagePreview"; import { MarkdownPreview } from "./MarkdownPreview"; import { isMarkdownPath, markdownPreviewSide, PreviewContext } from "./previewContext"; @@ -53,13 +55,25 @@ export function FilePreviewHeaderAction({ }) { const { context, available, rendered } = useMarkdownSource(fileKey, path, changeKind); if (!available || !context) return null; - const modes = [ - { id: "diff", label: "Diff", title: "Show the diff", checked: !rendered }, - { id: "rendered", label: "Rendered", title: "Show the rendered document", checked: rendered }, - ] as const; + const modes: readonly { + id: "diff" | "rendered"; + label: string; + icon: IconName; + title: string; + checked: boolean; + }[] = [ + { id: "diff", label: "Diff", icon: "code", title: "Show the diff", checked: !rendered }, + { + id: "rendered", + label: "Rendered", + icon: "eye", + title: "Show the rendered document", + checked: rendered, + }, + ]; return (
{ if (!mode.checked) context.markdownModes.toggle(fileKey); }} > - {mode.label} + ))}
); } +/** + * 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..6cacf9666 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..6ad2ecd46 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-previous { + color: var(--hunk-muted); +} + +.file-path-previous { + 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")