diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 90c8740f83725..111940699775d 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -34,6 +34,7 @@ const clientSettings: ClientSettings = { confirmThreadArchive: true, confirmThreadDelete: false, confirmThreadUnpin: false, + diffAutoAdvanceOnViewed: true, diffFilesCollapsed: true, diffIgnoreWhitespace: true, diffLayout: "stacked", diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index ab9df2d7bb34d..fdefc2eb72cdc 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -46,9 +46,13 @@ const state = vi.hoisted(() => ({ checkpointDiff: null as { diff: string } | null, })); -vi.mock("~/state/server", () => ({ - serverEnvironment: { configValueAtom: () => state.config }, -})); +vi.mock("~/state/server", async () => { + const { Atom } = await import("effect/reactivity"); + return { + serverEnvironment: { configValueAtom: () => state.config }, + primaryServerKeybindingsAtom: Atom.make([]), + }; +}); vi.mock("~/state/review", () => ({ reviewEnvironment: { diffPreview: ({ input }: { input: { baseRef?: string } }) => diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 77200799d6a74..f19070b3dbb04 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -7,6 +7,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { CHECKPOINT_DIFF_TRUNCATED_MARKER, type ReviewBranchCommitsResult, @@ -28,7 +29,7 @@ import { ChevronsUpDownIcon, } from "lucide-react"; import * as Schema from "effect/Schema"; -import { type MouseEvent, useEffect, useRef, useState } from "react"; +import { type ComponentProps, type MouseEvent, useEffect, useRef, useState } from "react"; import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal"; import { useCodeViewScrollRestore } from "./diffs/useCodeViewScrollRestore"; import { useFilesystemReadAccess } from "~/state/filesystem"; @@ -47,6 +48,7 @@ import { useDiffPanelSessionStore, useDiffPanelStore, } from "../diffPanelStore"; +import { diffViewedEntry, diffViewedFingerprint, useDiffViewedStore } from "../diffViewedStore"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { useHideTestFiles } from "./diffs/useHideTestFiles"; @@ -73,7 +75,24 @@ import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampForma import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { DiffStatLabel } from "./chat/DiffStatLabel"; -import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView"; +import { + AnnotatableCodeView, + type AnnotatableCodeViewHandle, + type AnnotatableCodeViewReview, +} from "./diffs/AnnotatableCodeView"; +import { + DiffCursorOutline, + DiffSingleFileToggle, + DiffViewedCount, + DiffViewedToggle, +} from "./diffs/DiffReviewControls"; +import { + DiffReviewCursorContext, + type DiffReviewFile, + useDiffReviewCursorFilePath, + useDiffReviewKeyboard, + useDiffReviewSelectedLines, +} from "./diffs/useDiffReviewKeyboard"; import { DiffFileTree } from "./diffs/DiffFileTree"; import { FileExplorerPane } from "./files/FileExplorerPane"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; @@ -121,9 +140,33 @@ import { useOpenLink } from "../browser/useOpenLink"; type DiffThemeType = "light" | "dark"; const AUTOMATIC_BASE_REF = "__automatic_base_ref__"; const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen"; +const viewedFingerprintCache = new WeakMap(); + +function getViewedFingerprint(fileDiff: FileDiffMetadata) { + let fingerprint = viewedFingerprintCache.get(fileDiff); + if (fingerprint === undefined) { + fingerprint = diffViewedFingerprint(fileDiff); + viewedFingerprintCache.set(fileDiff, fingerprint); + } + return fingerprint; +} const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet = new Set(); +/** The code view with the review cursor's lines selected; a cursor move redraws only this. */ +function ReviewAnnotatableCodeView( + props: Omit, "selectedLines">, +) { + const selectedLines = useDiffReviewSelectedLines(); + return ; +} + +/** Highlights the review cursor's file, falling back to the file another view selected. */ +function ReviewFileTree(props: ComponentProps) { + const cursorPath = useDiffReviewCursorFilePath(); + return ; +} + function DiffFileCollapseToggle({ filePath, fileKey, @@ -139,45 +182,50 @@ function DiffFileCollapseToggle({ }) { const gt = useGT(); return ( - - { - if (!node || !load) return; - return observeIntersection( - node, - (entry) => { - if (entry.isIntersecting) load(); - }, - { rootMargin: "600px" }, - ); - }} - data-diff-file-key={fileKey} - onClick={(event) => { - event.stopPropagation(); - onToggle(fileKey); - }} - /> - } - > - {collapsed ? ( - - ) : ( - - )} - - {collapsed ? gt("Expand diff") : gt("Collapse diff")} - + <> + + + { + if (!node || !load) return; + return observeIntersection( + node, + (entry) => { + if (entry.isIntersecting) load(); + }, + { rootMargin: "600px" }, + ); + }} + data-diff-file-key={fileKey} + onClick={(event) => { + event.stopPropagation(); + onToggle(fileKey); + }} + /> + } + > + {collapsed ? ( + + ) : ( + + )} + + + {collapsed ? gt("Expand diff") : gt("Collapse diff")} + + + ); } @@ -225,6 +273,7 @@ export default function DiffPanel({ const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); const settings = useClientSettings((settings) => ({ + diffAutoAdvanceOnViewed: settings.diffAutoAdvanceOnViewed, diffFilesCollapsed: settings.diffFilesCollapsed, diffIgnoreWhitespace: settings.diffIgnoreWhitespace, diffLayout: settings.diffLayout, @@ -690,24 +739,51 @@ export default function DiffPanel({ .getState() .updateCollapsedFileKeys(collapseScopeKey, defaultCollapsedDiffFileKeys, update); }; - const renderLoadingBoundary = () => - remainingFileCount > 0 ? ( - - ) : null; - const codeViewFiles = shownFileEntries.map(({ fileDiff, fileKey, fileVersion }) => ({ - fileDiff, - filePath: resolveFileDiffPath(fileDiff), + const isFilePending = (fileDiff: FileDiffMetadata) => + fileDiff.cacheKey?.endsWith(":pending") === true; + const viewedThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; + const viewedEntries = useDiffViewedStore((state) => + viewedThreadKey ? state.viewedByThreadKey[viewedThreadKey] : undefined, + ); + const viewedEntrySet = new Set(viewedEntries); + const isFileViewed = (fileDiff: FileDiffMetadata) => + viewedEntrySet.has( + diffViewedEntry(resolveFileDiffPath(fileDiff), getViewedFingerprint(fileDiff)), + ); + const setFileViewed = (fileDiff: FileDiffMetadata, viewed: boolean) => { + if (!viewedThreadKey) return; + useDiffViewedStore + .getState() + .setFileViewed( + viewedThreadKey, + resolveFileDiffPath(fileDiff), + getViewedFingerprint(fileDiff), + viewed, + ); + }; + const pendingFileKeys = new Set( + renderableFileEntries + .filter(({ fileDiff }) => isFilePending(fileDiff)) + .map((file) => file.fileKey), + ); + const setDiffFileCollapsed = useStableCallback((fileKey: string, collapsed: boolean) => { + const file = renderableFileEntries.find((candidate) => candidate.fileKey === fileKey); + if (!collapsed && lazySource && file) requestFile(resolveFileDiffPath(file.fileDiff)); + updateCollapsedDiffFiles((current) => { + if (current.has(fileKey) === collapsed) return current; + const next = new Set(current); + if (collapsed) next.add(fileKey); + else next.delete(fileKey); + return next; + }); + }); + const reviewFiles: DiffReviewFile[] = shownFileEntries.map(({ fileDiff, fileKey }) => ({ fileKey, - fileVersion, - collapsed: - collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true, + filePath: resolveFileDiffPath(fileDiff), + fileDiff, + rendered: !isFilePending(fileDiff), })); - const pendingFiles = renderableFiles.filter( - (file) => file.cacheKey?.endsWith(":pending") && isFileShown(file), - ); - const allDiffFilesCollapsed = areAllDiffFilesCollapsed(shownFileKeys, collapsedDiffFileKeys); - const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles); - const fileTreeEntries = diffFileTreeEntries(renderableFiles.filter(isFileShown)); + const viewedFileCount = shownFileEntries.filter(({ fileDiff }) => isFileViewed(fileDiff)).length; const codeViewReveal = useCodeViewFileReveal(); // Lazy files that sat above the saved position load again only when asked for. const codeViewScroll = useCodeViewScrollRestore( @@ -715,28 +791,74 @@ export default function DiffPanel({ !isRefreshingDiff && remainingFileCount === 0, remainingFileCount > 0 ? loadNextFiles : null, ); - const attachCodeView = useStableCallback((handle: AnnotatableCodeViewHandle | null) => { + const viewerHandleRef = useRef(null); + const attachViewer = useStableCallback((handle: AnnotatableCodeViewHandle | null) => { + viewerHandleRef.current = handle; codeViewScroll.attach(handle); codeViewReveal.attach(handle); }); - const flushCodeView = useStableCallback(() => { + const revealFileAt = (index: number, align?: "start" | "nearest") => { + const file = renderableFileEntries[index]; + if (!file) return; + codeViewScroll.discard(); + if (lazySource) requestFile(resolveFileDiffPath(file.fileDiff)); + codeViewReveal.request(file.fileKey, undefined, align); + }; + const reviewRef = useRef(null); + const { rootRef: reviewRootRef, ...review } = useDiffReviewKeyboard({ + scopeKey: collapseScopeKey, + files: reviewFiles, + diffStyle: diffLayout === "split" ? "split" : "unified", + canLoadFullFiles: currentLoadDiffFiles !== undefined, + autoAdvanceOnViewed: settings.diffAutoAdvanceOnViewed, + getViewer: () => viewerHandleRef.current, + isCollapsed: (fileKey) => collapsedDiffFileKeys.has(fileKey) || pendingFileKeys.has(fileKey), + setCollapsed: setDiffFileCollapsed, + isViewed: (file) => isFileViewed(file.fileDiff), + setViewed: (file, viewed) => { + setFileViewed(file.fileDiff, viewed); + setDiffFileCollapsed(file.fileKey, viewed); + }, + revealFile: (file, align) => + revealFileAt( + renderableFileEntries.findIndex(({ fileKey }) => fileKey === file.fileKey), + align, + ), + beginComment: (fileKey, range) => reviewRef.current?.beginComment(fileKey, range), + }); + const onPostRender = useStableCallback(() => { codeViewScroll.flush(); codeViewReveal.flush(); + review.flushScroll(); }); + const renderLoadingBoundary = () => + review.singleFileKey === undefined && remainingFileCount > 0 ? ( + + ) : null; + const codeViewFiles = shownFileEntries + .filter(({ fileKey }) => review.singleFileKey === undefined || fileKey === review.singleFileKey) + .map(({ fileDiff, fileKey, fileVersion }) => ({ + fileDiff, + filePath: resolveFileDiffPath(fileDiff), + fileKey, + fileVersion, + collapsed: + isFilePending(fileDiff) || + (fileKey !== review.singleFileKey && collapsedDiffFileKeys.has(fileKey)), + })); + const pendingFiles = renderableFiles.filter((file) => isFilePending(file) && isFileShown(file)); + const allDiffFilesCollapsed = areAllDiffFilesCollapsed(shownFileKeys, collapsedDiffFileKeys); + const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles); + const fileTreeEntries = diffFileTreeEntries(renderableFiles.filter(isFileShown)); const revealDiffFile = (filePath: string) => { const index = renderableFileEntries.findIndex( (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, ); const file = renderableFileEntries[index]; if (!file) return false; - codeViewScroll.discard(); - updateCollapsedDiffFiles((current) => { - const next = new Set(current); - next.delete(file.fileKey); - return next; - }); - if (lazySource) requestFile(filePath); - codeViewReveal.request(file.fileKey); + setDiffFileCollapsed(file.fileKey, false); + review.selectFile(filePath); + revealFileAt(index); return true; }; @@ -781,32 +903,10 @@ export default function DiffPanel({ }, }); }; - const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => { - const file = renderableFileEntries.find((file) => file.fileKey === fileKey); - if (lazySource && file) requestFile(resolveFileDiffPath(file.fileDiff)); - const pending = file?.fileDiff.cacheKey?.endsWith(":pending") === true; - updateCollapsedDiffFiles((current) => { - const next = new Set(current); - if (pending || next.has(fileKey)) { - next.delete(fileKey); - } else { - next.add(fileKey); - } - return next; - }); - }); - const setDiffFileCollapsed = useStableCallback((fileKey: string, collapsed: boolean) => { - updateCollapsedDiffFiles((current) => { - if (current.has(fileKey) === collapsed) return current; - const next = new Set(current); - if (collapsed) next.add(fileKey); - else next.delete(fileKey); - return next; - }); - }); const toggleDiffFileCollapse = () => { codeViewScroll.discard(); + review.showAllFiles(); updateCollapsedDiffFiles((current) => toggleAllDiffFiles(shownFileKeys, current)); }; @@ -1192,6 +1292,11 @@ export default function DiffPanel({ headerCommitSha !== null && "gap-0", )} > + {shownFileEntries.length > 0 ? ( + + viewed + + ) : null} {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? ( + {diffFileKeys.length > 0 && ( + + )} - {!activeThread ? ( -
- Select a thread to inspect turn diffs. -
- ) : !isGitRepo && !toolCallSelection ? ( -
- Turn diffs are unavailable because this project is not a git repository. -
- ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? ( -
- No completed turns yet. -
- ) : isGitSelection && !canReadFiles ? ( - fileAccess.isPending ? ( - - ) : ( + + + {!activeThread ? (
- {fileAccess.error ?? gt("This connection cannot read local diffs.")} + Select a thread to inspect turn diffs.
- ) - ) : ( - <> -
- {preview?.incomplete && ( -

- {selectedPatchError - ? gt( - "Showing tracked changes. Untracked changes could not be loaded. Refresh to retry.", - ) - : gt("Showing tracked changes. Checking untracked files...")} -

- )} - {isSelectedPatchTruncated && !lazySource && ( -

- {isGitSelection && selectedGitSource?.files && !preview?.incomplete - ? gt( - "This preview exceeds the size limit. Changes shown are incomplete. Totals include all changes.", - ) - : gt("This preview exceeds the size limit. Changes shown are incomplete.")} -

- )} - {omittedToolCallFiles > 0 && ( -

- {gt( - "This tool call changed {recorded} files. The recorded patch omits {omitted} of them.", - { - recorded: recordedToolCallFileCount, - omitted: omittedToolCallFiles, - }, - )} -

- )} - {selectedPatchError && !renderablePatch && ( -
-

{selectedPatchError}

-
- )} - {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? ( -
-

- The provider recorded file content without a diff. + ) : !isGitRepo && !toolCallSelection ? ( +

+ Turn diffs are unavailable because this project is not a git repository. +
+ ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? ( +
+ No completed turns yet. +
+ ) : isGitSelection && !canReadFiles ? ( + fileAccess.isPending ? ( + + ) : ( +
+ {fileAccess.error ?? gt("This connection cannot read local diffs.")} +
+ ) + ) : ( + <> +
+ {preview?.incomplete && ( +

+ {selectedPatchError + ? gt( + "Showing tracked changes. Untracked changes could not be loaded. Refresh to retry.", + ) + : gt("Showing tracked changes. Checking untracked files...")}

- {toolCallPreview.content.map(({ label, text }) => ( -
-

{label}

-
-                      {text === "" ? gt("Empty content.") : text}
-                    
-
- ))} -
- ) : !renderablePatch && !lazySource ? ( - isLoadingSelectedPatch ? ( - - ) : ( -
-

- {hasNoNetChanges - ? gt("No net changes in this selection.") - : gt("No patch available for this selection.")} + )} + {isSelectedPatchTruncated && !lazySource && ( +

+ {isGitSelection && selectedGitSource?.files && !preview?.incomplete + ? gt( + "This preview exceeds the size limit. Changes shown are incomplete. Totals include all changes.", + ) + : gt("This preview exceeds the size limit. Changes shown are incomplete.")} +

+ )} + {omittedToolCallFiles > 0 && ( +

+ {gt( + "This tool call changed {recorded} files. The recorded patch omits {omitted} of them.", + { + recorded: recordedToolCallFileCount, + omitted: omittedToolCallFiles, + }, + )} +

+ )} + {selectedPatchError && !renderablePatch && ( +
+

{selectedPatchError}

+
+ )} + {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? ( +
+

+ The provider recorded file content without a diff.

+ {toolCallPreview.content.map(({ label, text }) => ( +
+

{label}

+
+                        {text === "" ? gt("Empty content.") : text}
+                      
+
+ ))}
- ) - ) : lazySource || renderablePatch?.kind === "files" ? ( -
-
{ - const action = getDiffHeaderClickAction(event.nativeEvent); - if (action?.type === "open") openDiffFile(action.filePath); - else if (action?.type === "toggle") toggleDiffFileCollapsed(action.fileKey); - }} - onContextMenuCapture={(event) => { - const composedPath = event.nativeEvent.composedPath?.() ?? []; - const title = composedPath.find( - (node): node is HTMLElement => - node instanceof HTMLElement && node.hasAttribute("data-title"), - ); - const filePath = title?.textContent?.trim(); - if (!filePath) return; - event.preventDefault(); - onFileContextMenu( - { - environmentId: activeThread?.environmentId ?? null, - filePath, - workspaceRoot: activeCwd, - repositoryRoot: diffPathRepositoryRoot, - }, - event, - ); - }} - > - { - const path = resolveFileDiffPath(fileDiff); - const state = fileStates.get(path); - return ( - + ) : !renderablePatch && !lazySource ? ( + isLoadingSelectedPatch ? ( + + ) : ( +
+

+ {hasNoNetChanges + ? gt("No net changes in this selection.") + : gt("No patch available for this selection.")} +

+
+ ) + ) : lazySource || renderablePatch?.kind === "files" ? ( +
+
{ + const action = getDiffHeaderClickAction(event.nativeEvent); + if (action?.type === "open") openDiffFile(action.filePath); + else if (action?.type === "toggle") + review.toggleFileCollapsed(action.fileKey); + }} + onContextMenuCapture={(event) => { + const composedPath = event.nativeEvent.composedPath?.() ?? []; + const title = composedPath.find( + (node): node is HTMLElement => + node instanceof HTMLElement && node.hasAttribute("data-title"), + ); + const filePath = title?.textContent?.trim(); + if (!filePath) return; + event.preventDefault(); + onFileContextMenu( + { + environmentId: activeThread?.environmentId ?? null, + filePath, + workspaceRoot: activeCwd, + repositoryRoot: diffPathRepositoryRoot, + }, + event, ); }} - {...(lazySource - ? { - unsafeCSSExtra: - "[data-additions-count], [data-deletions-count] { display: none; }", - renderHeaderMetadata: (fileDiff: FileDiffMetadata) => { - const stat = fileStats.get(resolveFileDiffPath(fileDiff)); - return stat ? ( + > + { + const path = resolveFileDiffPath(fileDiff); + const state = fileStates.get(path); + return ( + + ); + }} + {...(lazySource + ? { + unsafeCSSExtra: + "[data-additions-count], [data-deletions-count] { display: none; }", + } + : {})} + renderHeaderMetadata={(fileDiff, fileKey) => { + const path = resolveFileDiffPath(fileDiff); + const stat = lazySource ? fileStats.get(path) : undefined; + return ( + <> + {stat ? ( - ) : null; - }, - } - : {})} - onFileCollapsedChange={setDiffFileCollapsed} - renderHeaderPrefix={(fileDiff, fileKey, collapsed) => { - return ( + ) : null} + {isFilePending(fileDiff) ? null : ( + { + setFileViewed(fileDiff, viewed); + setDiffFileCollapsed(fileKey, viewed); + }} + /> + )} + + ); + }} + onFileCollapsedChange={setDiffFileCollapsed} + renderHeaderPrefix={(fileDiff, fileKey, collapsed) => ( requestFile(resolveFileDiffPath(fileDiff)), - } + onToggle={review.toggleFileCollapsed} + {...(isFilePending(fileDiff) && !collapsedDiffFileKeys.has(fileKey) + ? { load: () => requestFile(resolveFileDiffPath(fileDiff)) } : {})} /> - ); - }} - options={{ - diffStyle: diffLayout === "split" ? "split" : "unified", - lineDiffType: "none", - overflow: wordWrap ? "wrap" : "scroll", - theme: resolveDiffThemeName(resolvedTheme), - preferredHighlighter: PREFERRED_HIGHLIGHTER, - themeType: resolvedTheme as DiffThemeType, - stickyHeaders: true, - onPostRender: flushCodeView, - ...(currentLoadDiffFiles ? { loadDiffFiles } : {}), - }} - /> -
- {fileTreeOpen ? ( - - - - ) : null} -
- ) : ( -
-
-

- {renderablePatch?.kind === "raw" ? renderablePatch.reason : null} -

-
-                    {renderablePatch?.kind === "raw" ? renderablePatch.text : null}
-                  
+
+ {fileTreeOpen ? ( + + + + ) : null}
-
- )} -
- - )} + ) : ( +
+
+

+ {renderablePatch?.kind === "raw" ? renderablePatch.reason : null} +

+
+                      {renderablePatch?.kind === "raw" ? renderablePatch.text : null}
+                    
+
+
+ )} +
+ + )} + ); } diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index 456f70516b23b..82459c019bf98 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from "react"; +import type { ReactNode, Ref } from "react"; import { isElectron } from "~/env"; import { cn } from "~/lib/utils"; @@ -18,17 +18,25 @@ function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) { ); } -export function DiffPanelShell(props: { +export function DiffPanelShell({ + ref, + ...props +}: { mode: DiffPanelMode; header: ReactNode; children: ReactNode; + ref?: Ref; }) { const shouldUseDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded"; return ( + // Focusable so a click anywhere in the panel, header included, gives it the review keys.
{ + const composerKeys: string[] = []; + await using _screen = await render( + <> + +
+ , + options, + ); + + await userEvent.keyboard("a "); + + expect(composerKeys).toEqual([]); +}); + it("leaves a non-Latin launcher letter to the launcher by its physical key", async () => { const composerKeys: string[] = []; const received: string[] = []; diff --git a/apps/web/src/components/diffs/AnnotatableCodeView.browser.test.tsx b/apps/web/src/components/diffs/AnnotatableCodeView.browser.test.tsx index 3f8335150e6c2..569aa24866cb2 100644 --- a/apps/web/src/components/diffs/AnnotatableCodeView.browser.test.tsx +++ b/apps/web/src/components/diffs/AnnotatableCodeView.browser.test.tsx @@ -1,6 +1,11 @@ -import type { CodeViewDiffItem, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs"; +import type { + CodeViewDiffItem, + CodeViewLineSelection, + FileDiffMetadata, + SelectedLineRange, +} from "@pierre/diffs"; import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; -import { StrictMode, type ComponentProps } from "react"; +import { StrictMode, useState, type ComponentProps } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; @@ -75,24 +80,42 @@ function file( }; } +function SelectableCodeView(props: { + files: ReturnType[]; + codeViewKey: string; + pendingFiles: FileDiffMetadata[]; + onDraftClose?: () => void; +}) { + const [selectedLines, setSelectedLines] = useState(null); + return ( + null} + renderHeaderPrefix={() => null} + onFileCollapsedChange={() => {}} + /> + ); +} + function view( files: ReturnType[], codeViewKey = "initial", pendingFiles: FileDiffMetadata[] = [], + onDraftClose?: () => void, ) { return ( - null} - renderHeaderPrefix={() => null} - onFileCollapsedChange={() => {}} + {...(onDraftClose ? { onDraftClose } : {})} /> ); @@ -160,4 +183,23 @@ describe("diff comment drafts", () => { ]); expect(container.querySelector("p")?.textContent).toBe("Keep this draft"); }); + + it("hands focus back when a refresh drops a draft's file, unless focus moved on", async () => { + using _drafts = setup(); + const onDraftClose = vi.fn(); + const shown = file("shown.ts"); + await using screen = await render(view([shown], "initial", [], onDraftClose), { container }); + await click("Comment on shown.ts"); + editor().focus(); + await screen.rerender(view([], "dropped", [], onDraftClose)); + expect(onDraftClose).toHaveBeenCalledOnce(); + + await screen.rerender(view([shown], "back", [], onDraftClose)); + await click("Comment on shown.ts"); + const elsewhere = document.createElement("input"); + container.append(elsewhere); + elsewhere.focus(); + await screen.rerender(view([], "moved", [], onDraftClose)); + expect(onDraftClose).toHaveBeenCalledOnce(); + }); }); diff --git a/apps/web/src/components/diffs/AnnotatableCodeView.tsx b/apps/web/src/components/diffs/AnnotatableCodeView.tsx index 1fb8b99f7c4ca..e256f2bd239c1 100644 --- a/apps/web/src/components/diffs/AnnotatableCodeView.tsx +++ b/apps/web/src/components/diffs/AnnotatableCodeView.tsx @@ -2,15 +2,25 @@ import type { AnnotationSide, CodeViewDiffItem, CodeViewItem, + CodeViewLineSelection, DiffLineAnnotation, FileDiffMetadata, SelectedLineRange, } from "@pierre/diffs"; import type { CodeViewHandle, CodeViewProps } from "@pierre/diffs/react"; import type { EnvironmentId, ProjectId, ScopedThreadRef } from "@t3tools/contracts"; -import { useState, type ReactNode, type Ref } from "react"; +import { useGT } from "gt-react"; +import { + useEffect, + useEffectEvent, + useImperativeHandle, + useState, + type ReactNode, + type Ref, +} from "react"; import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; +import { useStableCallback } from "~/hooks/useStableCallback"; import { fnv1a32, resolveFileDiffPath, resolveFileDiffPreviousPath } from "~/lib/diffRendering"; import { buildDiffReviewComment, @@ -36,6 +46,10 @@ interface DiffCommentAnnotationGroup { type DiffCommentLineAnnotation = DiffLineAnnotation; export type AnnotatableCodeViewHandle = CodeViewHandle; +export interface AnnotatableCodeViewReview { + /** Opens a comment draft on the range; false while another draft is open. */ + beginComment(fileKey: string, range: SelectedLineRange): boolean; +} const EMPTY_REVIEW_COMMENTS: ReadonlyArray = []; function annotationSide(range: SelectedLineRange): AnnotationSide { @@ -88,11 +102,16 @@ interface AnnotatableCodeViewProps { composerDraftTarget: ScopedThreadRef | DraftId; options: StyledDiffCodeViewOptions; viewerRef?: Ref; + reviewRef?: Ref; + selectedLines: CodeViewLineSelection | null; + onSelectedLinesChange: (selection: CodeViewLineSelection | null) => void; + onDraftClose?: () => void; + commentShortcutLabel?: string | null; onScroll?: CodeViewProps["onScroll"]; className?: string; renderCodeViewFooter?: () => ReactNode; unsafeCSSExtra?: string; - renderHeaderMetadata?: (fileDiff: FileDiffMetadata) => ReactNode; + renderHeaderMetadata?: (fileDiff: FileDiffMetadata, fileKey: string) => ReactNode; renderHeaderFilenameSuffix: (fileDiff: FileDiffMetadata) => ReactNode; renderHeaderPrefix: ( fileDiff: FileDiffMetadata, @@ -102,10 +121,6 @@ interface AnnotatableCodeViewProps { onFileCollapsedChange: (fileKey: string, collapsed: boolean) => void; } -interface DiffSelectionContext { - item: CodeViewItem; -} - export function AnnotatableCodeView({ environmentId, projectId, @@ -117,6 +132,11 @@ export function AnnotatableCodeView({ composerDraftTarget, options, viewerRef, + reviewRef, + selectedLines, + onSelectedLinesChange, + onDraftClose, + commentShortcutLabel, onScroll, className, renderCodeViewFooter, @@ -126,15 +146,12 @@ export function AnnotatableCodeView({ renderHeaderPrefix, onFileCollapsedChange, }: AnnotatableCodeViewProps) { + const gt = useGT(); const addReviewComment = useComposerDraftStore((store) => store.addReviewComment); const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment); const reviewComments = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS, ); - const [selectedLines, setSelectedLines] = useState<{ - id: string; - range: SelectedLineRange; - } | null>(null); const [draft, setDraft] = useState<{ fileKey: string; filePath: string; @@ -142,6 +159,14 @@ export function AnnotatableCodeView({ annotation: DiffCommentLineAnnotation; } | null>(null); const [draftText, setDraftText] = useState(""); + const [droppedDraftCount, setDroppedDraftCount] = useState(0); + const draftDropped = useEffectEvent(() => { + if (document.activeElement === document.body) onDraftClose?.(); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a refresh that drops the draft's file unmounts its focused textarea, and focus must not fall to the page + useEffect(() => { + if (droppedDraftCount > 0) draftDropped(); + }, [droppedDraftCount]); const filesByKey = new Map(files.map((file) => [file.fileKey, file])); if ( @@ -156,7 +181,7 @@ export function AnnotatableCodeView({ ) { setDraft(null); setDraftText(""); - setSelectedLines(null); + setDroppedDraftCount((count) => count + 1); } const items: CodeViewDiffItem[] = files.map( ({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => { @@ -198,12 +223,17 @@ export function AnnotatableCodeView({ }, ); + const closeDraft = () => { + setDraft(null); + setDraftText(""); + onDraftClose?.(); + }; + const removeEntry = (entryId: string) => { - setSelectedLines(null); if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) { - setDraft(null); - setDraftText(""); + closeDraft(); } else { + onSelectedLinesChange(null); removeReviewComment(composerDraftTarget, entryId); } }; @@ -222,32 +252,28 @@ export function AnnotatableCodeView({ text, }); if (comment) addReviewComment(composerDraftTarget, comment); - setSelectedLines(null); - setDraft(null); - setDraftText(""); + closeDraft(); }; - const beginComment = (range: SelectedLineRange | null, context: DiffSelectionContext) => { - if (!range) return; - const item = context.item; - if (item.type !== "diff") return; + const beginComment = (fileKey: string, range: SelectedLineRange) => { + const file = filesByKey.get(fileKey); + if (draft !== null || !file) return false; const id = nextFileCommentId(); - const filePath = resolveFileDiffPath(item.fileDiff); const comment = buildDiffReviewComment({ id, sectionId, sectionTitle, - filePath, - fileDiff: item.fileDiff, + filePath: file.filePath, + fileDiff: file.fileDiff, range, text: "", }); - if (!comment) return; + if (!comment) return false; setDraftText(""); setDraft({ - fileKey: item.id, - filePath, - previousFilePath: resolveFileDiffPreviousPath(item.fileDiff), + fileKey, + filePath: file.filePath, + previousFilePath: resolveFileDiffPreviousPath(file.fileDiff), annotation: { side: annotationSide(range), lineNumber: range.end, @@ -256,11 +282,26 @@ export function AnnotatableCodeView({ }, }, }); + return true; }; + useImperativeHandle(reviewRef, () => ({ beginComment })); + const onGutterUtilityClick = useStableCallback( + ( + range: SelectedLineRange | null, + { item }: { item: CodeViewItem }, + ) => { + if (range) beginComment(item.id, range); + }, + ); return ( key={codeViewKey} + gutterUtilityLabel={ + commentShortcutLabel + ? gt("Add comment ({shortcut})", { shortcut: commentShortcutLabel }) + : gt("Add comment") + } {...(viewerRef ? { viewerRef } : {})} {...(onScroll ? { onScroll } : {})} {...(className ? { className } : {})} @@ -268,18 +309,18 @@ export function AnnotatableCodeView({ {...(renderHeaderMetadata ? { renderHeaderMetadata: (item: CodeViewItem) => - item.type === "diff" ? renderHeaderMetadata(item.fileDiff) : null, + item.type === "diff" ? renderHeaderMetadata(item.fileDiff, item.id) : null, } : {})} {...(renderCodeViewFooter ? { renderCodeViewFooter } : {})} items={items} selectedLines={selectedLines} - onSelectedLinesChange={setSelectedLines} + onSelectedLinesChange={onSelectedLinesChange} options={{ ...options, enableGutterUtility: draft === null, enableLineSelection: draft === null, - onGutterUtilityClick: beginComment, + onGutterUtilityClick, onItemCollapsedChange: (_item, nextItem) => onFileCollapsedChange(nextItem.id, nextItem.collapsed === true), }} diff --git a/apps/web/src/components/diffs/DiffReviewControls.tsx b/apps/web/src/components/diffs/DiffReviewControls.tsx new file mode 100644 index 0000000000000..b1a8921d858ba --- /dev/null +++ b/apps/web/src/components/diffs/DiffReviewControls.tsx @@ -0,0 +1,140 @@ +import { T, useGT, Var } from "gt-react"; +import { CheckIcon, FileIcon } from "lucide-react"; + +import { Checkbox } from "../ui/checkbox"; +import { Toggle } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { useIsDiffReviewCursorFile } from "./useDiffReviewKeyboard"; + +/** The viewed count; once every file is viewed it reads as a finished review. */ +export function DiffViewedCount({ viewed, total }: { viewed: number; total: number }) { + if (total === 0 || viewed < total) { + return ( + <> + {viewed} / {total} + + ); + } + return ( + + + + All {total} + + + ); +} + +/** Outlines the file header under the review cursor; render it in the header prefix. */ +export function DiffCursorOutline({ filePath }: { filePath: string }) { + if (!useIsDiffReviewCursorFile(filePath)) return null; + return ( + // The sticky header is the nearest positioned box, so this outlines the whole header. + + ); +} + +export function DiffViewedToggle({ + filePath, + viewed, + stale = false, + shortcutLabel, + onViewedChange, +}: { + filePath: string; + viewed: boolean; + /** The file changed after it was marked viewed. */ + stale?: boolean; + shortcutLabel: string | null; + onViewedChange: (viewed: boolean, extendRange: boolean) => void; +}) { + const gt = useGT(); + const action = viewed + ? shortcutLabel + ? gt("Mark as not viewed ({shortcut})", { shortcut: shortcutLabel }) + : gt("Mark as not viewed") + : shortcutLabel + ? gt("Mark as viewed ({shortcut})", { shortcut: shortcutLabel }) + : gt("Mark as viewed"); + return ( + + event.stopPropagation()} + /> + } + > + + onViewedChange( + next === true, + "shiftKey" in details.event && details.event.shiftKey === true, + ) + } + /> + {stale ? ( + + Changed + + ) : ( + + Viewed + + )} + + + {stale + ? `${gt("This file has been pushed to since you marked it viewed.")} ${action}` + : action} + + + ); +} + +export function DiffSingleFileToggle({ + singleFile, + shortcutLabel, + onToggle, +}: { + singleFile: boolean; + shortcutLabel: string | null; + onToggle: () => void; +}) { + const gt = useGT(); + const label = singleFile ? gt("Show all files") : gt("Show one file at a time"); + const tooltip = shortcutLabel + ? singleFile + ? gt("Show all files ({shortcut})", { shortcut: shortcutLabel }) + : gt("Show one file at a time ({shortcut})", { shortcut: shortcutLabel }) + : label; + return ( + + + } + > + + + {tooltip} + + ); +} diff --git a/apps/web/src/components/diffs/StyledDiffCodeView.tsx b/apps/web/src/components/diffs/StyledDiffCodeView.tsx index a64e8d887d1f4..cf7a1244cf485 100644 --- a/apps/web/src/components/diffs/StyledDiffCodeView.tsx +++ b/apps/web/src/components/diffs/StyledDiffCodeView.tsx @@ -7,10 +7,12 @@ import { type UncontrolledCodeViewProps, } from "@pierre/diffs/react"; /* oxlint-enable eslint/no-restricted-imports */ -import type { Ref } from "react"; +import { type Ref, useState } from "react"; import { DIFF_SURFACE_THEME_UNSAFE_CSS } from "~/lib/diffRendering"; import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { Tooltip, TooltipPopup } from "../ui/tooltip"; +import { keepShallowEqual, keepUnchangedItems, useKeepUnchanged } from "./keepUnchanged"; export const DIFF_VIEW_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS} /* A 1fr track's automatic minimum grows with the currently mounted lines. In split @@ -226,6 +228,8 @@ type StyledDiffCodeViewProps = ( readonly options?: StyledDiffCodeViewOptions; readonly viewerRef?: Ref>; readonly unsafeCSSExtra?: string; + /** Tooltip for the gutter's "+" button while it is enabled. */ + readonly gutterUtilityLabel?: string; }; export function StyledDiffCodeView({ @@ -233,37 +237,74 @@ export function StyledDiffCodeView({ viewerRef, className, unsafeCSSExtra, + gutterUtilityLabel, ...props }: StyledDiffCodeViewProps) { + const [hoveredUtilityButton, setHoveredUtilityButton] = useState(null); + // The viewer redraws for a new options object or item list, so keep them while nothing changed. + const keptOptions = useKeepUnchanged(options ?? {}, keepShallowEqual); + const keptItems = useKeepUnchanged(props.items, (previous, next) => + previous && next ? keepUnchangedItems(previous, next) : next, + ); + const viewProps = + props.items === undefined || keptItems === undefined ? props : { ...props, items: keptItems }; + const view = ( + + {...viewProps} + {...(viewerRef ? { ref: viewerRef } : {})} + className={ + className + ? `diff-render-surface [--code-background:var(--background)] outline-none ${className}` + : "diff-render-surface [--code-background:var(--background)] outline-none" + } + options={{ + ...keptOptions, + unsafeCSS: unsafeCSSExtra + ? `${DIFF_VIEW_UNSAFE_CSS}\n${unsafeCSSExtra}` + : DIFF_VIEW_UNSAFE_CSS, + itemMetrics: { + diffHeaderHeight: 32, + hunkSeparatorHeight: 24, + // Zero both spacing and paddingTop; Pierre's expanded-file fallback otherwise adds an 8px header + // gap. + spacing: 0, + paddingTop: 0, + // Include Pierre's 8px --diffs-gap-fallback in metrics or each expanded file loses a scrollable + // row. + paddingBottom: 8, + }, + layout: { paddingTop: 0, paddingBottom: 0, gap: 0 }, + }} + /> + ); return ( - - {...props} - {...(viewerRef ? { ref: viewerRef } : {})} - className={ - className - ? `diff-render-surface [--code-background:var(--background)] outline-none ${className}` - : "diff-render-surface [--code-background:var(--background)] outline-none" - } - options={{ - ...options, - unsafeCSS: unsafeCSSExtra - ? `${DIFF_VIEW_UNSAFE_CSS}\n${unsafeCSSExtra}` - : DIFF_VIEW_UNSAFE_CSS, - itemMetrics: { - diffHeaderHeight: 32, - hunkSeparatorHeight: 24, - // Zero both spacing and paddingTop; Pierre's expanded-file fallback otherwise adds an 8px header - // gap. - spacing: 0, - paddingTop: 0, - // Include Pierre's 8px --diffs-gap-fallback in metrics or each expanded file loses a scrollable - // row. - paddingBottom: 8, - }, - layout: { paddingTop: 0, paddingBottom: 0, gap: 0 }, - }} - /> + {gutterUtilityLabel ? ( + // The viewer draws its "+" button inside a shadow root, so the tooltip is anchored from here. +
+ setHoveredUtilityButton( + event.nativeEvent + .composedPath() + .find( + (node): node is HTMLElement => + node instanceof HTMLElement && node.hasAttribute("data-utility-button"), + ) ?? null, + ) + } + onPointerLeave={() => setHoveredUtilityButton(null)} + > + + + {gutterUtilityLabel} + + + {view} +
+ ) : ( + view + )}
); } diff --git a/apps/web/src/components/diffs/diffHeaderClick.ts b/apps/web/src/components/diffs/diffHeaderClick.ts index 0adaefb98f13f..5dae414bbdf37 100644 --- a/apps/web/src/components/diffs/diffHeaderClick.ts +++ b/apps/web/src/components/diffs/diffHeaderClick.ts @@ -2,7 +2,13 @@ export function getDiffHeaderClickAction(event: MouseEvent) { const path = event.composedPath(); // Controls own their actions; handling the chevron here too would toggle twice. for (const node of path) { - if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) return null; + if ( + node instanceof HTMLButtonElement || + node instanceof HTMLAnchorElement || + node instanceof HTMLLabelElement + ) { + return null; + } } const title = path.find( (node): node is HTMLElement => node instanceof HTMLElement && node.hasAttribute("data-title"), diff --git a/apps/web/src/components/diffs/diffReviewCursor.test.ts b/apps/web/src/components/diffs/diffReviewCursor.test.ts new file mode 100644 index 0000000000000..ad2a561f79366 --- /dev/null +++ b/apps/web/src/components/diffs/diffReviewCursor.test.ts @@ -0,0 +1,200 @@ +import { parseDiffFromFile } from "@pierre/diffs"; +import { describe, expect, it } from "vite-plus/test"; + +import { + adjacentFileKey, + adjacentUnviewedFileKey, + cursorFromSelectedRange, + cursorSelectedRange, + type DiffRow, + fileScrollAlign, + fileToStartFrom, + nearestGapExpansion, + stepRow, + topToBottomRange, + visibleDiffRows, +} from "./diffReviewCursor"; + +const lines = (count: number, edit: (line: number) => string) => + Array.from({ length: count }, (_, index) => `${edit(index + 1)}\n`).join(""); + +// Changes lines 8 and 22 of 30: hunks keep 4 context lines, leaving hidden gaps of 3 lines +// above, 5 between, and 4 after. +const fileDiff = parseDiffFromFile( + { name: "a.ts", contents: lines(30, (line) => `line ${line}`) }, + { + name: "a.ts", + contents: lines(30, (line) => (line === 8 || line === 22 ? `changed ${line}` : `line ${line}`)), + }, +); +const NO_EXPANSIONS = new Map(); +const unified = visibleDiffRows(fileDiff, "unified", NO_EXPANSIONS); +const split = visibleDiffRows(fileDiff, "split", NO_EXPANSIONS); +const rowAt = (rows: ReadonlyArray, lineNumber: number, side = "additions") => + rows.find((row) => row.lineNumber === lineNumber && row.side === side)!; + +describe("visibleDiffRows", () => { + it("lists deletions and additions as separate unified rows and paired split rows", () => { + expect(unified.map((row) => `${row.side[0]}${row.lineNumber}`)).toEqual( + ["a4", "a5", "a6", "a7", "d8", "a8", "a9", "a10", "a11", "a12"].concat([ + "a18", + "a19", + "a20", + "a21", + "d22", + "a22", + "a23", + "a24", + "a25", + "a26", + ]), + ); + expect(split.map((row) => `${row.side[0]}${row.lineNumber}`)).toEqual( + ["a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12"].concat([ + "a18", + "a19", + "a20", + "a21", + "a22", + "a23", + "a24", + "a25", + "a26", + ]), + ); + expect(split[4]).toMatchObject({ deletionLineNumber: 8, additionLineNumber: 8 }); + expect(unified[0]).toMatchObject({ hunkIndex: 0, hiddenBefore: 3 }); + expect(rowAt(unified, 18)).toMatchObject({ hunkIndex: 1, hiddenBefore: 5 }); + expect(unified.at(-1)).toMatchObject({ hiddenAfter: 4 }); + }); + + it("includes expanded context and shrinks the remaining gap", () => { + const rows = visibleDiffRows(fileDiff, "unified", new Map([[1, { fromStart: 2, fromEnd: 0 }]])); + expect(rowAt(rows, 13)).toMatchObject({ hunkIndex: 1, hiddenBefore: 0 }); + expect(rowAt(rows, 14)).toBeDefined(); + expect(rowAt(rows, 18)).toMatchObject({ hiddenBefore: 3 }); + expect(nearestGapExpansion(fileDiff, rows, rowAt(rows, 12), "below")).toEqual({ + hunkIndex: 1, + direction: "up", + }); + }); +}); + +describe("stepRow", () => { + it("stops at the first and last row", () => { + expect(stepRow(unified, unified[0]!, -1)).toBe(unified[0]); + expect(stepRow(unified, unified[0]!, 1)).toBe(unified[1]); + expect(stepRow(unified, unified.at(-1)!, 1)).toBe(unified.at(-1)); + }); + + it("finds a context row from either side", () => { + expect(stepRow(split, { lineNumber: 4, side: "deletions" }, 1)).toBe(split[1]); + }); +}); + +describe("nearestGapExpansion", () => { + it.each([ + [5, "above", { hunkIndex: 0, direction: "down" }], + [9, "above", { hunkIndex: 0, direction: "down" }], + [5, "below", { hunkIndex: 1, direction: "up" }], + [20, "above", { hunkIndex: 1, direction: "down" }], + [20, "below", { hunkIndex: 2, direction: "up" }], + [26, "below", { hunkIndex: 2, direction: "up" }], + ] as const)("from line %i %s reveals %o", (lineNumber, toward, expansion) => { + expect(nearestGapExpansion(fileDiff, unified, rowAt(unified, lineNumber), toward)).toEqual( + expansion, + ); + }); + + it("finds nothing once the file is fully shown", () => { + const expanded = new Map( + [0, 1, 2].map((hunkIndex) => [hunkIndex, { fromStart: 1_000_000, fromEnd: 0 }]), + ); + const rows = visibleDiffRows(fileDiff, "unified", expanded); + expect(rows).toHaveLength(32); + expect(nearestGapExpansion(fileDiff, rows, rowAt(rows, 1), "below")).toBeNull(); + expect(nearestGapExpansion(fileDiff, rows, rowAt(rows, 30), "above")).toBeNull(); + }); +}); + +describe("cursor selections", () => { + const file = { fileKey: "a", filePath: "a.ts" }; + + it("orders a selection made upward top to bottom across sides", () => { + const range = cursorSelectedRange({ + mode: "select", + ...file, + anchor: { lineNumber: 11, side: "additions" }, + head: { lineNumber: 8, side: "deletions" }, + }); + expect(range).toEqual({ start: 11, side: "additions", end: 8, endSide: "deletions" }); + expect(topToBottomRange(range!, unified)).toEqual({ + start: 8, + side: "deletions", + end: 11, + endSide: "additions", + }); + }); + + it("reads a single line as line mode and a range as a selection", () => { + expect(cursorFromSelectedRange(file, { start: 6, side: "additions", end: 6 })).toEqual({ + mode: "line", + ...file, + row: { lineNumber: 6, side: "additions" }, + }); + expect( + cursorFromSelectedRange(file, { start: 8, side: "deletions", end: 9, endSide: "additions" }), + ).toEqual({ + mode: "select", + ...file, + anchor: { lineNumber: 8, side: "deletions" }, + head: { lineNumber: 9, side: "additions" }, + }); + }); +}); + +describe("file navigation", () => { + const keys = ["a", "b", "c", "d"]; + + it("starts at the first file and stops at the ends", () => { + expect(adjacentFileKey(keys, null, -1)).toBe("a"); + expect(adjacentFileKey(keys, "a", -1)).toBe("a"); + expect(adjacentFileKey(keys, "c", 1)).toBe("d"); + expect(adjacentFileKey(keys, "d", 1)).toBe("d"); + }); + + it("wraps to the next unviewed file and skips viewed ones", () => { + const viewed = new Set(["a", "d"]); + const isViewed = (key: string) => viewed.has(key); + expect(adjacentUnviewedFileKey(keys, "c", 1, isViewed)).toBe("b"); + expect(adjacentUnviewedFileKey(keys, "b", -1, isViewed)).toBe("c"); + expect(adjacentUnviewedFileKey(keys, null, 1, isViewed)).toBe("b"); + expect(adjacentUnviewedFileKey(keys, null, -1, isViewed)).toBe("c"); + expect(adjacentUnviewedFileKey(keys, "a", 1, () => true)).toBeNull(); + }); + + it("starts from the file in view when the cursor's file is off screen", () => { + const placed = keys.map((fileKey, index) => ({ fileKey, top: 10 + index * 500 })); + const view = (top: number) => ({ top, bottom: top + 400, contentEnd: 2010 }); + expect(fileToStartFrom(placed, null, view(0))).toBe("a"); + expect(fileToStartFrom(placed, null, view(1200))).toBe("c"); + expect(fileToStartFrom(placed, "a", view(1200))).toBe("c"); + expect(fileToStartFrom(placed, "b", view(1200))).toBe("c"); + expect(fileToStartFrom(placed, "c", view(1200))).toBeNull(); + expect(fileToStartFrom(placed, "d", view(1200))).toBeNull(); + expect(fileToStartFrom(placed, "d", view(1610))).toBeNull(); + }); + + it("scrolls the least to a file that fits on screen and to the header of a taller one", () => { + const placed = [ + { fileKey: "a", top: 0 }, + { fileKey: "b", top: 32 }, + { fileKey: "c", top: 400 }, + ]; + const view = { height: 300, contentEnd: 432 }; + expect(fileScrollAlign(placed, "a", view)).toBe("nearest"); + expect(fileScrollAlign(placed, "b", view)).toBe("start"); + expect(fileScrollAlign(placed, "c", view)).toBe("nearest"); + expect(fileScrollAlign(placed, "missing", view)).toBe("start"); + }); +}); diff --git a/apps/web/src/components/diffs/diffReviewCursor.ts b/apps/web/src/components/diffs/diffReviewCursor.ts new file mode 100644 index 0000000000000..714baccc93b8f --- /dev/null +++ b/apps/web/src/components/diffs/diffReviewCursor.ts @@ -0,0 +1,221 @@ +import type { + ExpansionDirections, + FileDiffMetadata, + HunkExpansionRegion, + SelectedLineRange, + SelectionSide, +} from "@pierre/diffs"; +import { iterateOverDiff } from "@pierre/diffs/utils/iterateOverDiff"; + +export interface DiffRowRef { + readonly lineNumber: number; + readonly side: SelectionSide; +} + +interface DiffCursorFile { + readonly fileKey: string; + // Lazy placeholders change identity key once loaded; the path keeps the cursor on the file. + readonly filePath: string; +} + +export type DiffReviewCursor = + | ({ readonly mode: "file" } & DiffCursorFile) + | ({ readonly mode: "line"; readonly row: DiffRowRef } & DiffCursorFile) + | ({ + readonly mode: "select"; + readonly anchor: DiffRowRef; + readonly head: DiffRowRef; + } & DiffCursorFile); + +export interface DiffRow extends DiffRowRef { + readonly hunkIndex: number; + readonly hiddenBefore: number; + readonly hiddenAfter: number; + readonly deletionLineNumber: number | null; + readonly additionLineNumber: number | null; +} + +export interface DiffGapExpansion { + readonly hunkIndex: number; + readonly direction: ExpansionDirections; +} + +/** Each row the viewer draws for the file, top to bottom, with folded lines left out. */ +export function visibleDiffRows( + fileDiff: FileDiffMetadata, + diffStyle: "unified" | "split", + expandedHunks: ReadonlyMap, +): DiffRow[] { + const rows: DiffRow[] = []; + iterateOverDiff({ + diff: fileDiff, + diffStyle, + expandedHunks: new Map(expandedHunks), + callback: ({ hunkIndex, collapsedBefore, collapsedAfter, additionLine, deletionLine }) => { + const additionLineNumber = additionLine?.lineNumber ?? null; + const deletionLineNumber = deletionLine?.lineNumber ?? null; + rows.push({ + lineNumber: additionLineNumber ?? deletionLineNumber ?? 0, + side: additionLineNumber === null ? "deletions" : "additions", + hunkIndex, + hiddenBefore: collapsedBefore, + hiddenAfter: collapsedAfter, + deletionLineNumber, + additionLineNumber, + }); + }, + }); + return rows; +} + +function findRowIndex(rows: ReadonlyArray, ref: DiffRowRef): number { + return rows.findIndex((row) => + ref.side === "additions" + ? row.additionLineNumber === ref.lineNumber + : row.deletionLineNumber === ref.lineNumber, + ); +} + +/** Moves one visible row, stopping at the first and last. A row no longer shown restarts at the top. */ +export function stepRow( + rows: ReadonlyArray, + ref: DiffRowRef, + delta: 1 | -1, +): DiffRow | null { + const index = findRowIndex(rows, ref); + if (index < 0) return rows[0] ?? null; + return rows[Math.min(rows.length - 1, Math.max(0, index + delta))] ?? null; +} + +/** + * The nearest still-hidden block on one side of the row, as the expansion that reveals the lines + * touching the row. A gap keyed `i` sits above hunk `i`; key `hunks.length` trails the last hunk. + */ +export function nearestGapExpansion( + fileDiff: FileDiffMetadata, + rows: ReadonlyArray, + ref: DiffRowRef, + toward: "above" | "below", +): DiffGapExpansion | null { + const index = findRowIndex(rows, ref); + if (index < 0) return null; + if (toward === "above") { + for (let cursor = index; cursor >= 0; cursor -= 1) { + const row = rows[cursor]; + if (row && row.hiddenBefore > 0) return { hunkIndex: row.hunkIndex, direction: "down" }; + } + return null; + } + for (let cursor = index; cursor < rows.length; cursor += 1) { + const row = rows[cursor]; + if (!row) continue; + if (cursor > index && row.hiddenBefore > 0) + return { hunkIndex: row.hunkIndex, direction: "up" }; + if (row.hiddenAfter > 0) return { hunkIndex: fileDiff.hunks.length, direction: "up" }; + } + return null; +} + +/** The cursor as a viewer selection, from where it started to where it is now. */ +export function cursorSelectedRange(cursor: DiffReviewCursor): SelectedLineRange | null { + if (cursor.mode === "file") return null; + const [from, to] = + cursor.mode === "line" ? [cursor.row, cursor.row] : [cursor.anchor, cursor.head]; + return { start: from.lineNumber, side: from.side, end: to.lineNumber, endSide: to.side }; +} + +/** Puts the range's lower row last, where a comment on it is drawn. */ +export function topToBottomRange( + range: SelectedLineRange, + rows: ReadonlyArray, +): SelectedLineRange { + const start: DiffRowRef = { lineNumber: range.start, side: range.side ?? "additions" }; + const end: DiffRowRef = { lineNumber: range.end, side: range.endSide ?? start.side }; + if (findRowIndex(rows, end) >= findRowIndex(rows, start)) return range; + return { start: end.lineNumber, side: end.side, end: start.lineNumber, endSide: start.side }; +} + +export function cursorFromSelectedRange( + file: DiffCursorFile, + range: SelectedLineRange, +): DiffReviewCursor { + const anchor: DiffRowRef = { lineNumber: range.start, side: range.side ?? "additions" }; + const head: DiffRowRef = { lineNumber: range.end, side: range.endSide ?? anchor.side }; + if (anchor.lineNumber === head.lineNumber && anchor.side === head.side) { + return { mode: "line", ...file, row: anchor }; + } + return { mode: "select", ...file, anchor, head }; +} + +export interface PlacedFile { + readonly fileKey: string; + /** Where the file's header sits in the scrolled content. */ + readonly top: number; +} + +/** + * The file whose rows cross the top of the view, to start from when the cursor's file is off + * screen or there is no cursor. Null while the cursor's file is on screen. + */ +export function fileToStartFrom( + placed: ReadonlyArray, + cursorKey: string | null, + view: { readonly top: number; readonly bottom: number; readonly contentEnd: number }, +): string | null { + const cursorIndex = placed.findIndex((file) => file.fileKey === cursorKey); + const cursorFile = placed[cursorIndex]; + if (cursorFile) { + const end = placed[cursorIndex + 1]?.top ?? view.contentEnd; + if (cursorFile.top < view.bottom && end > view.top) return null; + } + let inView = placed[0]?.fileKey ?? null; + for (const file of placed) { + if (file.top > view.top) break; + inView = file.fileKey; + } + return inView; +} + +/** + * How moving to a file scrolls: no further than it must while the whole file fits on screen, + * else to its header, since lining up a taller file's end would hide that header. + */ +export function fileScrollAlign( + placed: ReadonlyArray, + fileKey: string, + view: { readonly height: number; readonly contentEnd: number }, +): "nearest" | "start" { + const index = placed.findIndex((file) => file.fileKey === fileKey); + const file = placed[index]; + if (!file) return "start"; + const end = placed[index + 1]?.top ?? view.contentEnd; + return end - file.top <= view.height ? "nearest" : "start"; +} + +/** The neighbouring file, stopping at the ends; with no current file, the first. */ +export function adjacentFileKey( + fileKeys: ReadonlyArray, + currentKey: string | null, + delta: 1 | -1, +): string | null { + const index = currentKey === null ? -1 : fileKeys.indexOf(currentKey); + if (index < 0) return fileKeys[0] ?? null; + return fileKeys[Math.min(fileKeys.length - 1, Math.max(0, index + delta))] ?? null; +} + +/** The next file not yet viewed in the given direction, wrapping around the list. */ +export function adjacentUnviewedFileKey( + fileKeys: ReadonlyArray, + currentKey: string | null, + delta: 1 | -1, + isViewed: (fileKey: string) => boolean, +): string | null { + const count = fileKeys.length; + const currentIndex = currentKey === null ? -1 : fileKeys.indexOf(currentKey); + const start = currentIndex >= 0 ? currentIndex : delta > 0 ? -1 : count; + for (let step = 1; step <= count; step += 1) { + const key = fileKeys[(((start + delta * step) % count) + count) % count]; + if (key !== undefined && !isViewed(key)) return key; + } + return null; +} diff --git a/apps/web/src/components/diffs/keepUnchanged.test.ts b/apps/web/src/components/diffs/keepUnchanged.test.ts new file mode 100644 index 0000000000000..81ebee7aaffca --- /dev/null +++ b/apps/web/src/components/diffs/keepUnchanged.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { keepShallowEqual, keepUnchangedItems } from "./keepUnchanged"; + +describe("keepUnchangedItems", () => { + const a = { id: "a", type: "diff", version: 1 }; + const b = { id: "b", type: "diff", version: 1 }; + + it("keeps the previous list while every id, type and version matches", () => { + const previous = [a, b]; + expect(keepUnchangedItems(previous, [{ ...a }, { ...b }])).toBe(previous); + }); + + it("takes an item whose version changed and keeps the others", () => { + const changed = { ...b, version: 2 }; + const kept = keepUnchangedItems([a, b], [{ ...a }, changed]); + expect(kept[0]).toBe(a); + expect(kept[1]).toBe(changed); + }); + + it("returns a new list when items move, arrive, or leave", () => { + expect(keepUnchangedItems([a, b], [{ ...b }, { ...a }])).toEqual([b, a]); + expect(keepUnchangedItems([a], [{ ...a }, b])).toEqual([a, b]); + const previous = [a, b]; + expect(keepUnchangedItems(previous, [{ ...a }])).not.toBe(previous); + }); +}); + +describe("keepShallowEqual", () => { + const onPostRender = () => {}; + + it("keeps the previous object until a value or key changes", () => { + const previous = { theme: "dark", onPostRender }; + expect(keepShallowEqual(previous, { theme: "dark", onPostRender })).toBe(previous); + const next = { theme: "light", onPostRender }; + expect(keepShallowEqual(previous, next)).toBe(next); + const added = { theme: "dark", onPostRender, stickyHeaders: true }; + expect(keepShallowEqual(previous, added)).toBe(added); + }); +}); diff --git a/apps/web/src/components/diffs/keepUnchanged.ts b/apps/web/src/components/diffs/keepUnchanged.ts new file mode 100644 index 0000000000000..dabf25266e338 --- /dev/null +++ b/apps/web/src/components/diffs/keepUnchanged.ts @@ -0,0 +1,51 @@ +import { useState } from "react"; + +interface VersionedItem { + readonly id: string; + readonly type: string; + readonly version?: number | undefined; +} + +/** + * Keeps each item the viewer would treat as unchanged, since it ignores an item whose id, type and + * version match, and the previous list when every item is kept. A new list makes it redraw. + */ +export function keepUnchangedItems( + previous: ReadonlyArray, + next: ReadonlyArray, +): ReadonlyArray { + if (previous === next) return previous; + const previousById = new Map(previous.map((item) => [item.id, item])); + let changed = previous.length !== next.length; + const kept = next.map((item, index) => { + const old = previousById.get(item.id); + const keep = old !== undefined && old.type === item.type && old.version === item.version; + const result = keep ? old : item; + if (result !== previous[index]) changed = true; + return result; + }); + return changed ? kept : previous; +} + +export function keepShallowEqual(previous: Value, next: Value): Value { + if (previous === next) return previous; + const previousKeys = Object.keys(previous); + if (previousKeys.length !== Object.keys(next).length) return next; + for (const key of previousKeys) { + if (!Object.hasOwn(next, key) || Reflect.get(previous, key) !== Reflect.get(next, key)) { + return next; + } + } + return previous; +} + +/** The value from the last render while `keep` finds nothing changed. */ +export function useKeepUnchanged( + next: Value, + keep: (previous: Value, next: Value) => Value, +) { + const [kept, setKept] = useState(next); + const value = keep(kept, next); + if (value !== kept) setKept(value); + return value; +} diff --git a/apps/web/src/components/diffs/useCodeViewFileReveal.ts b/apps/web/src/components/diffs/useCodeViewFileReveal.ts index 60b76290fbe2f..a6bfcfacd97d4 100644 --- a/apps/web/src/components/diffs/useCodeViewFileReveal.ts +++ b/apps/web/src/components/diffs/useCodeViewFileReveal.ts @@ -65,6 +65,7 @@ export function createCodeViewFileReveal() { let detachedInstance: object | undefined; let pending: { id: string; + align: "start" | "nearest"; range?: SelectedLineRange; positionedFile?: boolean; loadingFile?: boolean; @@ -73,7 +74,8 @@ export function createCodeViewFileReveal() { const flush = () => { if (pending === null || viewer === null) return; const item = viewer.getItem(pending.id); - if (!viewer.getInstance() || item === undefined || item.collapsed === true) return; + if (!viewer.getInstance() || item === undefined) return; + if (pending.range && item.collapsed === true) return; const renderedItems = viewer.getInstance()?.getRenderedItems?.(); if (pending.range && renderedItems) { const rendered = renderedItems.find((entry) => entry.id === pending?.id); @@ -142,7 +144,7 @@ export function createCodeViewFileReveal() { viewer.scrollTo( target.range ? { type: "range", id: target.id, range: target.range, align: "center" } - : { type: "item", id: target.id, align: "start" }, + : { type: "item", id: target.id, align: target.align }, ); }; return { @@ -163,8 +165,9 @@ export function createCodeViewFileReveal() { viewer = next; flush(); }, - request(fileKey: string, range?: SelectedLineRange) { - pending = { id: fileKey, ...(range ? { range } : {}) }; + /** `nearest` leaves a file already on screen in place. */ + request(fileKey: string, range?: SelectedLineRange, align: "start" | "nearest" = "start") { + pending = { id: fileKey, align, ...(range ? { range } : {}) }; flush(); }, /** The user scrolled; a reveal still being positioned must not pull them back. */ diff --git a/apps/web/src/components/diffs/useDiffReviewKeyboard.browser.test.tsx b/apps/web/src/components/diffs/useDiffReviewKeyboard.browser.test.tsx new file mode 100644 index 0000000000000..76a2cb87576a6 --- /dev/null +++ b/apps/web/src/components/diffs/useDiffReviewKeyboard.browser.test.tsx @@ -0,0 +1,192 @@ +import { parseDiffFromFile } from "@pierre/diffs"; +import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { + DiffReviewCursorContext, + useDiffReviewCursorFilePath, + useDiffReviewKeyboard, + useDiffReviewSelectedLines, +} from "./useDiffReviewKeyboard"; + +vi.mock("~/state/server", async () => { + const { Atom } = await import("effect/reactivity"); + const { DEFAULT_RESOLVED_KEYBINDINGS } = await import("@t3tools/shared/keybindings"); + return { primaryServerKeybindingsAtom: Atom.make(DEFAULT_RESOLVED_KEYBINDINGS) }; +}); + +const file = { + fileKey: "a", + filePath: "a.ts", + fileDiff: parseDiffFromFile({ name: "a.ts", contents: "a\n" }, { name: "a.ts", contents: "b\n" }), + rendered: true, +}; +const otherFile = { ...file, fileKey: "b", filePath: "b.ts" }; + +function CursorFile() { + const filePath = useDiffReviewCursorFilePath(); + const onLines = useDiffReviewSelectedLines() !== null; + return filePath === null ? null :

Cursor on {onLines ? `lines of ${filePath}` : filePath}

; +} + +function Panel(props: { + folds: string[]; + clicks: string[]; + reveals?: string[]; + renders?: string[]; + hidden?: boolean; + twoFiles?: boolean; + viewedUnsupported?: boolean; + autoAdvance?: boolean; +}) { + props.renders?.push("panel"); + const { rootRef, cursorStore, singleFile, toggleFileCollapsed } = useDiffReviewKeyboard({ + scopeKey: "scope", + files: props.twoFiles ? [file, otherFile] : [file], + diffStyle: "unified", + canLoadFullFiles: false, + autoAdvanceOnViewed: props.autoAdvance ?? false, + getViewer: () => null, + isCollapsed: () => false, + setCollapsed: (fileKey) => void props.folds.push(fileKey), + isViewed: () => false, + setViewed: props.viewedUnsupported ? null : () => {}, + revealFile: (revealed) => void props.reveals?.push(revealed.fileKey), + beginComment: () => {}, + }); + return ( +
+ + + {singleFile ?

One file at a time

: null} + + + +
+ ); +} + +// router: false because the panel stand-in never navigates. +const options = { router: false } as const; + +it("takes the keys from a clicked control and drops its focus ring", async () => { + const folds: string[] = []; + const clicks: string[] = []; + await using screen = await render(, options); + await userEvent.click(screen.getByRole("button", { name: "Changes" })); + + await userEvent.keyboard("j"); + expect(document.activeElement).toBe(screen.getByTestId("panel").element()); + await userEvent.click(screen.getByRole("button", { name: "Changes" })); + await userEvent.keyboard("{Enter}"); + + expect(folds).toEqual(["a"]); + expect(clicks).toEqual(["Changes", "Changes"]); +}); + +it("leaves v alone where files cannot be marked viewed", async () => { + const folds: string[] = []; + await using screen = await render( + , + options, + ); + screen.getByTestId("panel").element().focus(); + + await userEvent.keyboard("jv"); + + expect(folds).toEqual([]); + await expect.element(screen.getByText("Cursor on a.ts")).toBeInTheDocument(); +}); + +it("leaves Enter to a control reached with Tab", async () => { + const folds: string[] = []; + const clicks: string[] = []; + await using screen = await render(, options); + screen.getByTestId("panel").element().focus(); + await userEvent.keyboard("j"); + + await userEvent.keyboard("{Tab}{Enter}"); + + expect(folds).toEqual([]); + expect(clicks).toEqual(["Changes"]); + await userEvent.keyboard("j"); + expect(document.activeElement).toBe(screen.getByTestId("panel").element()); +}); + +it("takes the keys from anywhere in the panel showing the diff", async () => { + const reveals: string[] = []; + const hiddenReveals: string[] = []; + await using screen = await render( + <> +
+ + +
+ + , + options, + ); + + await userEvent.click(screen.getByRole("button", { name: "Code" })); + await userEvent.keyboard("j"); + expect(document.activeElement).toBe(screen.getByTestId("panel").first().element()); + await userEvent.click(screen.getByRole("button", { name: "Elsewhere" })); + await userEvent.keyboard("j"); + + expect(reveals).toEqual(["a"]); + expect(hiddenReveals).toEqual([]); +}); + +it("moves the cursor without redrawing the panel", async () => { + const renders: string[] = []; + await using screen = await render(, options); + screen.getByTestId("panel").element().focus(); + const rendersBefore = renders.length; + + await userEvent.keyboard("j"); + + await expect.element(screen.getByText("Cursor on a.ts")).toBeInTheDocument(); + expect(renders).toHaveLength(rendersBefore); +}); + +it("returns to the full list when the single shown file is closed", async () => { + const folds: string[] = []; + await using screen = await render(, options); + screen.getByTestId("panel").element().focus(); + await userEvent.keyboard("f"); + await expect.element(screen.getByText("One file at a time")).toBeInTheDocument(); + + await userEvent.click(screen.getByRole("button", { name: "Collapse a.ts" })); + + await expect.element(screen.getByText("One file at a time")).not.toBeInTheDocument(); + expect(folds).toEqual(["a"]); +}); + +it("leaves a file's lines past either end", async () => { + const folds: string[] = []; + await using screen = await render(, options); + screen.getByTestId("panel").element().focus(); + await userEvent.keyboard("ji"); + await expect.element(screen.getByText("Cursor on lines of a.ts")).toBeInTheDocument(); + + await userEvent.keyboard("k"); + await expect.element(screen.getByText("Cursor on a.ts")).toBeInTheDocument(); + + await userEvent.keyboard("ijj"); + const foldsBefore = [...folds]; + await userEvent.keyboard("j"); + await expect.element(screen.getByText("Cursor on b.ts")).toBeInTheDocument(); + expect(folds).toEqual(foldsBefore); +}); diff --git a/apps/web/src/components/diffs/useDiffReviewKeyboard.ts b/apps/web/src/components/diffs/useDiffReviewKeyboard.ts new file mode 100644 index 0000000000000..ce439b785dafb --- /dev/null +++ b/apps/web/src/components/diffs/useDiffReviewKeyboard.ts @@ -0,0 +1,560 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { + CodeViewLineScrollTarget, + CodeViewLineSelection, + FileDiffMetadata, + HunkExpansionRegion, + SelectedLineRange, +} from "@pierre/diffs"; +import type { CodeViewHandle } from "@pierre/diffs/react"; +import type { KeybindingCommand } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { createContext, use, useEffect, useRef, useState, useSyncExternalStore } from "react"; + +import { useLocalStorage } from "~/hooks/useLocalStorage"; +import { useStableCallback } from "~/hooks/useStableCallback"; +import { shortcutLabelForCommand } from "~/keybindings"; +import { diffPanelHasFocus } from "~/lib/diffFocus"; +import { type CommandHandlers, registerCommands } from "~/shortcuts/dispatcher"; +import { primaryServerKeybindingsAtom } from "~/state/server"; + +import { + adjacentFileKey, + adjacentUnviewedFileKey, + cursorFromSelectedRange, + cursorSelectedRange, + type DiffReviewCursor, + type DiffRowRef, + fileScrollAlign, + fileToStartFrom, + nearestGapExpansion, + stepRow, + topToBottomRange, + visibleDiffRows, +} from "./diffReviewCursor"; + +const DIFF_REVIEW_COMMANDS = [ + "diff.nextFile", + "diff.previousFile", + "diff.nextUnviewedFile", + "diff.previousUnviewedFile", + "diff.toggleFileCollapsed", + "diff.toggleFileViewed", + "diff.toggleSingleFile", + "diff.enterLineMode", + "diff.nextLine", + "diff.previousLine", + "diff.expandBelow", + "diff.expandAbove", + "diff.comment", + "diff.startSelection", + "diff.back", +] as const satisfies ReadonlyArray; +type DiffReviewCommand = (typeof DIFF_REVIEW_COMMANDS)[number]; + +// Holding these keeps moving; holding a toggle would flip it on every repeat. +const REPEATABLE_COMMANDS: ReadonlySet = new Set([ + "diff.nextFile", + "diff.previousFile", + "diff.nextUnviewedFile", + "diff.previousUnviewedFile", + "diff.nextLine", + "diff.previousLine", + "diff.expandBelow", + "diff.expandAbove", +]); + +const NO_EXPANSIONS: ReadonlyMap = new Map(); +const SINGLE_FILE_STORAGE_KEY = "t3code.diffSingleFile"; +// The viewer's 100 lines per step pushes the cursor far off screen; a small step stays readable. +const KEYBOARD_EXPANSION_LINES = 20; + +const CONTROL_SELECTOR = + 'button, a[href], input, select, [role="button"], [role="checkbox"], [role="switch"]'; + +function isControlFocused(): boolean { + return (document.activeElement?.closest(CONTROL_SELECTOR) ?? null) !== null; +} + +/** + * The review cursor, kept outside React state: a key press redraws only what shows the cursor, + * not the panel around it. One store belongs to one diff scope. + */ +export interface DiffReviewCursorStore { + readonly get: () => DiffReviewCursor | null; + readonly getSelectedLines: () => CodeViewLineSelection | null; + readonly subscribe: (listener: () => void) => () => void; +} + +interface WritableDiffReviewCursorStore extends DiffReviewCursorStore { + readonly set: (cursor: DiffReviewCursor | null) => void; +} + +function createDiffReviewCursorStore(): WritableDiffReviewCursorStore { + let cursor: DiffReviewCursor | null = null; + let selectedLines: CodeViewLineSelection | null = null; + const listeners = new Set<() => void>(); + return { + get: () => cursor, + getSelectedLines: () => selectedLines, + subscribe: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + set: (next) => { + cursor = next; + const range = next ? cursorSelectedRange(next) : null; + selectedLines = next && range ? { id: next.fileKey, range } : null; + for (const listener of listeners) listener(); + }, + }; +} + +const NO_CURSOR_STORE: DiffReviewCursorStore = { + get: () => null, + getSelectedLines: () => null, + subscribe: () => () => {}, +}; + +export const DiffReviewCursorContext = createContext(NO_CURSOR_STORE); + +/** Whether the review cursor is on the file; matched by path, which survives lazy loading. */ +export function useIsDiffReviewCursorFile(filePath: string): boolean { + const store = use(DiffReviewCursorContext); + return useSyncExternalStore(store.subscribe, () => store.get()?.filePath === filePath); +} + +export function useDiffReviewCursorFilePath(): string | null { + const store = use(DiffReviewCursorContext); + return useSyncExternalStore(store.subscribe, () => store.get()?.filePath ?? null); +} + +/** The cursor's lines as a viewer selection; changes only when the selection does. */ +export function useDiffReviewSelectedLines(): CodeViewLineSelection | null { + const store = use(DiffReviewCursorContext); + return useSyncExternalStore(store.subscribe, store.getSelectedLines); +} + +export interface DiffReviewFile { + readonly fileKey: string; + readonly filePath: string; + readonly fileDiff: FileDiffMetadata; + /** Loaded and drawn by the viewer; placeholders can be visited but not reviewed. */ + readonly rendered: boolean; +} + +interface DiffReviewKeyboardInput { + /** The thread and diff scope; a new one starts without a cursor. */ + readonly scopeKey: string | null; + readonly files: ReadonlyArray; + readonly diffStyle: "unified" | "split"; + /** Partial diffs only expand when the full files can be loaded. */ + readonly canLoadFullFiles: boolean; + readonly autoAdvanceOnViewed: boolean; + readonly getViewer: () => CodeViewHandle | null; + readonly isCollapsed: (fileKey: string) => boolean; + readonly setCollapsed: (fileKey: string, collapsed: boolean) => void; + readonly isViewed: (file: DiffReviewFile) => boolean; + /** Folds the file as its Viewed checkbox does. Null where files can't be marked viewed, which leaves the key to others. */ + readonly setViewed: ((file: DiffReviewFile, viewed: boolean) => void) | null; + /** Loads the file if needed and scrolls it into view. */ + readonly revealFile: (file: DiffReviewFile, align?: "start" | "nearest") => void; + readonly beginComment: (fileKey: string, range: SelectedLineRange) => void; +} + +/** + * Keyboard review of the Diff panel: a file cursor, a line cursor inside a file, and a line + * selection. Commands run through the shortcut dispatcher while focus is in the diff's panel. + */ +export function useDiffReviewKeyboard(input: DiffReviewKeyboardInput) { + const { scopeKey, files } = input; + const [scopedStore, setScopedStore] = useState(() => ({ + scopeKey, + store: createDiffReviewCursorStore(), + })); + if (scopedStore.scopeKey !== scopeKey) { + setScopedStore({ scopeKey, store: createDiffReviewCursorStore() }); + } + const cursorStore = scopedStore.store; + const rootRef = useRef(null); + // Shows only the cursor's file, forced open; one preference for every diff view. + const [singleFile, setSingleFile] = useLocalStorage( + SINGLE_FILE_STORAGE_KEY, + false, + Schema.Boolean, + ); + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const pendingScrollRef = useRef(null); + // Chrome marks a clicked control :focus-visible on the next key press, so record how focus came. + const tabbedToRef = useRef(null); + + // Only single-file mode redraws the panel as the cursor moves, since the shown file changes. + const singleFilePath = useSyncExternalStore(cursorStore.subscribe, () => + singleFile ? (cursorStore.get()?.filePath ?? null) : null, + ); + const singleFileKey = singleFile + ? (files.find((file) => file.filePath === singleFilePath) ?? files[0])?.fileKey + : undefined; + const isCollapsed = (fileKey: string) => fileKey !== singleFileKey && input.isCollapsed(fileKey); + // Read when a key runs, not in render: the panel does not redraw for a cursor move. + const readCursor = () => { + const stored = cursorStore.get(); + const cursorFile = stored + ? (files.find((file) => file.fileKey === stored.fileKey) ?? + files.find((file) => file.filePath === stored.filePath) ?? + null) + : null; + const cursor: DiffReviewCursor | null = + stored === null || cursorFile === null + ? null + : stored.mode !== "file" && (!cursorFile.rendered || isCollapsed(cursorFile.fileKey)) + ? { mode: "file", fileKey: cursorFile.fileKey, filePath: cursorFile.filePath } + : { ...stored, fileKey: cursorFile.fileKey }; + return { cursor, cursorFile }; + }; + + const setCursor = (next: DiffReviewCursor | null) => cursorStore.set(next); + const fileCursor = (file: { fileKey: string; filePath: string }): DiffReviewCursor => ({ + mode: "file", + fileKey: file.fileKey, + filePath: file.filePath, + }); + + const fileDiffInstance = (fileKey: string) => { + const item = input + .getViewer() + ?.getInstance() + ?.getRenderedItems() + .find((candidate) => candidate.id === fileKey); + return item?.type === "diff" ? item.instance : undefined; + }; + const rowsFor = (file: DiffReviewFile) => { + const item = input.getViewer()?.getItem(file.fileKey); + return visibleDiffRows( + item?.type === "diff" ? item.fileDiff : file.fileDiff, + input.diffStyle, + fileDiffInstance(file.fileKey)?.getExpandedHunks() ?? NO_EXPANSIONS, + ); + }; + const canExpand = (file: DiffReviewFile) => !file.fileDiff.isPartial || input.canLoadFullFiles; + + const flushScroll = useStableCallback(() => { + const target = pendingScrollRef.current; + const viewer = input.getViewer(); + if (target === null || !viewer?.getInstance()) return; + const item = viewer.getItem(target.id); + // A file unfolded by the same key press is drawn on a later render. + if (!item || item.collapsed === true) return; + pendingScrollRef.current = null; + viewer.scrollTo(target); + }); + const queueScrollToRow = ( + file: DiffReviewFile, + row: DiffRowRef, + align: "nearest" | "center" = "nearest", + ) => { + pendingScrollRef.current = { + type: "line", + id: file.fileKey, + lineNumber: row.lineNumber, + side: row.side, + align, + }; + }; + const scrollToRow = (file: DiffReviewFile, row: DiffRowRef) => { + queueScrollToRow(file, row); + flushScroll(); + }; + const placeFiles = () => { + const viewer = input.getViewer()?.getInstance(); + if (!viewer) return null; + const top = viewer.getScrollTop(); + const height = viewer.getHeight(); + return { + placed: files.flatMap(({ fileKey }) => { + const fileTop = viewer.getTopForItem(fileKey); + return fileTop === undefined ? [] : [{ fileKey, top: fileTop }]; + }), + view: { top, bottom: top + height, height, contentEnd: viewer.getScrollHeight() }, + }; + }; + const moveToFile = (fileKey: string | null) => { + const file = files.find((candidate) => candidate.fileKey === fileKey); + if (!file) return; + pendingScrollRef.current = null; + setCursor(fileCursor(file)); + // Lining every file up at the top jolts the list, and the pull request header with it. + const placement = placeFiles(); + input.revealFile( + file, + placement ? fileScrollAlign(placement.placed, file.fileKey, placement.view) : "start", + ); + }; + + // After the reader scrolls away from the cursor, the file keys start from what is on screen. + const fileKeyInView = (cursorKey: string | null) => { + const placement = placeFiles(); + return placement ? fileToStartFrom(placement.placed, cursorKey, placement.view) : null; + }; + + const toggleFileCollapsed = useStableCallback((fileKey: string) => { + // Single-file mode keeps its file open, so closing that file returns to the full list. + if (fileKey === singleFileKey) setSingleFile(false); + input.setCollapsed(fileKey, !isCollapsed(fileKey)); + }); + + const runCommand = (command: DiffReviewCommand): boolean => { + const { cursor, cursorFile } = readCursor(); + const range = cursor ? cursorSelectedRange(cursor) : null; + const fileKeys = files.map((file) => file.fileKey); + const currentKey = cursorFile?.fileKey ?? null; + const isKeyViewed = (fileKey: string) => { + const file = files.find((candidate) => candidate.fileKey === fileKey); + return file !== undefined && input.isViewed(file); + }; + switch (command) { + case "diff.nextFile": + case "diff.previousFile": { + if (files.length === 0) return false; + const delta = command === "diff.nextFile" ? 1 : -1; + moveToFile(fileKeyInView(currentKey) ?? adjacentFileKey(fileKeys, currentKey, delta)); + return true; + } + case "diff.nextUnviewedFile": + case "diff.previousUnviewedFile": { + if (files.length === 0) return false; + const delta = command === "diff.nextUnviewedFile" ? 1 : -1; + const inView = fileKeyInView(currentKey); + moveToFile( + inView !== null && !isKeyViewed(inView) + ? inView + : adjacentUnviewedFileKey(fileKeys, inView ?? currentKey, delta, isKeyViewed), + ); + return true; + } + case "diff.toggleFileCollapsed": { + if (!cursorFile) return false; + toggleFileCollapsed(cursorFile.fileKey); + return true; + } + case "diff.toggleFileViewed": { + if (!cursorFile || !input.setViewed) return false; + if (!cursorFile.rendered) return true; + const viewed = !input.isViewed(cursorFile); + input.setViewed(cursorFile, viewed); + const nextKey = + viewed && input.autoAdvanceOnViewed + ? adjacentUnviewedFileKey( + fileKeys, + cursorFile.fileKey, + 1, + (fileKey) => fileKey === cursorFile.fileKey || isKeyViewed(fileKey), + ) + : null; + moveToFile(nextKey ?? cursorFile.fileKey); + return true; + } + case "diff.toggleSingleFile": { + const file = cursorFile ?? files[0]; + if (!file) return false; + setCursor(fileCursor(file)); + setSingleFile(!singleFile); + input.revealFile(file); + return true; + } + case "diff.enterLineMode": { + const file = cursorFile ?? files[0]; + if (!file) return false; + if (!file.rendered) return true; + const firstRow = rowsFor(file)[0]; + if (!firstRow) return true; + input.setCollapsed(file.fileKey, false); + // Shift+J and Shift+K need the full file; loading it on the first one draws the new + // lines after the scroll that should follow them. A refresh mid-load rejects this + // warm-up, and expanding then loads the file itself. + if (canExpand(file)) { + fileDiffInstance(file.fileKey) + ?.prepareForEditing() + .catch(() => {}); + } + setCursor({ mode: "line", fileKey: file.fileKey, filePath: file.filePath, row: firstRow }); + scrollToRow(file, firstRow); + return true; + } + case "diff.nextLine": + case "diff.previousLine": { + if (!cursor || !cursorFile || cursor.mode === "file") return false; + const delta = command === "diff.nextLine" ? 1 : -1; + const rows = rowsFor(cursorFile); + const at = cursor.mode === "line" ? cursor.row : cursor.head; + const next = stepRow(rows, at, delta); + if (!next) return true; + if (cursor.mode === "line" && next.lineNumber === at.lineNumber && next.side === at.side) { + // Stepping past the first line returns to the file, past the last on to the next file. + const fileKey = + delta === -1 ? cursorFile.fileKey : adjacentFileKey(fileKeys, cursorFile.fileKey, 1); + if (delta === -1 || fileKey !== cursorFile.fileKey) moveToFile(fileKey); + return true; + } + const row: DiffRowRef = { lineNumber: next.lineNumber, side: next.side }; + setCursor(cursor.mode === "line" ? { ...cursor, row } : { ...cursor, head: row }); + scrollToRow(cursorFile, row); + return true; + } + case "diff.expandBelow": + case "diff.expandAbove": { + if (!cursor || !cursorFile || cursor.mode === "file") return false; + const instance = fileDiffInstance(cursorFile.fileKey); + if (!instance || !canExpand(cursorFile)) return true; + const row = cursor.mode === "line" ? cursor.row : cursor.head; + const gap = nearestGapExpansion( + cursorFile.fileDiff, + rowsFor(cursorFile), + row, + command === "diff.expandBelow" ? "below" : "above", + ); + if (!gap) return true; + instance.expandHunk(gap.hunkIndex, gap.direction, KEYBOARD_EXPANSION_LINES); + if (command === "diff.expandAbove") { + // Lines added above push the cursor down by heights the viewer only estimates until + // drawn, so centre it rather than aim for an edge it can miss. + queueScrollToRow(cursorFile, row, "center"); + } + return true; + } + case "diff.comment": { + if (!cursor || !cursorFile || !range) return false; + input.beginComment(cursorFile.fileKey, topToBottomRange(range, rowsFor(cursorFile))); + return true; + } + case "diff.startSelection": { + if (!cursor || cursor.mode === "file") return false; + const anchor = cursor.mode === "line" ? cursor.row : cursor.head; + setCursor({ + mode: "select", + fileKey: cursor.fileKey, + filePath: cursor.filePath, + anchor, + head: anchor, + }); + return true; + } + case "diff.back": { + if (!cursor || cursor.mode === "file") return false; + setCursor( + cursor.mode === "select" + ? { mode: "line", fileKey: cursor.fileKey, filePath: cursor.filePath, row: cursor.head } + : fileCursor(cursor), + ); + return true; + } + } + }; + + const handleCommand = useStableCallback((command: DiffReviewCommand, event: KeyboardEvent) => { + const handled = event.repeat && !REPEATABLE_COMMANDS.has(command) ? true : runCommand(command); + if (handled) { + event.preventDefault(); + // The viewer drops a scroll requested during a key press that reaches it. + event.stopPropagation(); + // The key now drives the diff, so a control keeping focus would show a stale focus ring. + const root = rootRef.current; + if (root && (isControlFocused() || !root.contains(document.activeElement))) { + root.focus({ preventScroll: true }); + } + } + return handled; + }); + const isLineMode = useStableCallback(() => { + const { cursor } = readCursor(); + return cursor !== null && cursor.mode !== "file"; + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the review keys with the app-wide shortcut dispatcher while the panel is mounted + useEffect(() => { + const handlers: CommandHandlers = {}; + for (const command of DIFF_REVIEW_COMMANDS) { + handlers[command] = (event) => handleCommand(command, event); + } + let lastInputWasKeyboard = false; + const onPointerDown = () => { + lastInputWasKeyboard = false; + }; + const onKeyDown = () => { + lastInputWasKeyboard = true; + }; + const onFocusIn = (event: FocusEvent) => { + tabbedToRef.current = lastInputWasKeyboard ? event.target : null; + }; + window.addEventListener("pointerdown", onPointerDown, true); + window.addEventListener("keydown", onKeyDown, true); + window.addEventListener("focusin", onFocusIn, true); + // Capture phase, so the keys reach the panel before type-to-focus sends them to the composer. + const unregister = registerCommands(handlers, { + capture: true, + when: (event) => { + if (!rootRef.current || !diffPanelHasFocus(rootRef.current)) return false; + // A control reached from the keyboard keeps Enter; a clicked one hands it over. + return !( + event.key === "Enter" && + isControlFocused() && + document.activeElement === tabbedToRef.current + ); + }, + context: () => ({ diffLineMode: isLineMode() }), + }); + return () => { + unregister(); + window.removeEventListener("pointerdown", onPointerDown, true); + window.removeEventListener("keydown", onKeyDown, true); + window.removeEventListener("focusin", onFocusIn, true); + }; + }, [handleCommand, isLineMode]); + + const labelFor = (command: DiffReviewCommand, diffLineMode = false) => + shortcutLabelForCommand(keybindings, command, { context: { diffFocus: true, diffLineMode } }); + + return { + cursorStore, + singleFile, + singleFileKey, + rootRef, + flushScroll, + shortcutLabels: { + viewed: labelFor("diff.toggleFileViewed"), + comment: labelFor("diff.comment", true), + singleFile: labelFor("diff.toggleSingleFile"), + }, + toggleSingleFile: () => runCommand("diff.toggleSingleFile"), + toggleFileCollapsed, + /** Leaves single-file mode, for actions that only make sense in the full list. */ + showAllFiles: () => setSingleFile(false), + /** Puts the file cursor on a file the user picked another way, such as the file tree. */ + selectFile: (filePath: string) => { + const file = files.find((candidate) => candidate.filePath === filePath); + if (file) setCursor(fileCursor(file)); + }, + onSelectedLinesChange: (selection: CodeViewLineSelection | null) => { + if (selection === null) { + const { cursor } = readCursor(); + if (cursor && cursor.mode !== "file") setCursor(fileCursor(cursor)); + return; + } + const file = files.find((candidate) => candidate.fileKey === selection.id); + if (file) setCursor(cursorFromSelectedRange(file, selection.range)); + }, + // The draft's textarea held focus; without this it falls to the page and the keys stop. + onDraftClose: () => { + const { cursor } = readCursor(); + if (cursor?.mode === "select") { + setCursor({ + mode: "line", + fileKey: cursor.fileKey, + filePath: cursor.filePath, + row: cursor.head, + }); + } + rootRef.current?.focus({ preventScroll: true }); + }, + }; +} diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 4d305c4da66ed..600a109dcac23 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -226,25 +226,25 @@ it("restores saved Viewed folds, follows cleared marks, and allows explicit expa const container = document.createElement("div"); container.className = "flex h-[700px] w-[900px]"; await using screen = await render(tab(0), { container }); - await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked(); + await expect.element(screen.getByRole("checkbox", { name: "Viewed a.ts" })).toBeChecked(); await expect .element(screen.getByRole("button", { name: "Expand diff", exact: true })) .toHaveAttribute("aria-expanded", "false"); await screen.getByRole("button", { name: "Expand diff", exact: true }).click(); await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); - screen.getByRole("checkbox", { name: "Viewed" }).element().focus(); + screen.getByRole("checkbox", { name: "Viewed a.ts" }).element().focus(); await userEvent.keyboard(" "); - await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked(); + await expect.element(screen.getByRole("checkbox", { name: "Viewed a.ts" })).not.toBeChecked(); await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); - screen.getByRole("checkbox", { name: "Viewed" }).element().focus(); + screen.getByRole("checkbox", { name: "Viewed a.ts" }).element().focus(); await userEvent.keyboard(" "); await expect .element(screen.getByRole("button", { name: "Expand diff", exact: true })) .toHaveAttribute("aria-expanded", "false"); deliverViewedPaths(new Set()); - await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).not.toBeChecked(); + await expect.element(screen.getByRole("checkbox", { name: "Viewed a.ts" })).not.toBeChecked(); await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); deliverViewedPaths(new Set(["a.ts"])); await expect @@ -276,7 +276,7 @@ it("keeps a revealed file open when its Viewed mark loads afterwards", async () await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); deliverViewedPaths(new Set(["a.ts"])); - await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked(); + await expect.element(screen.getByRole("checkbox", { name: "Viewed a.ts" })).toBeChecked(); await expect .element(screen.getByRole("button", { name: "Collapse diff" })) @@ -375,6 +375,37 @@ it("never requests the diff of a selected commit the pull request no longer has" expect(mocks.diffCommits).not.toContain("gone"); }); +it("keeps an open comment on its line when the comment key is pressed again", async () => { + setup({ paged: false }); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render( + {}} + environmentId={EnvironmentId.make("environment")} + reference={detail} + detail={detail} + selectedCommitOid={null} + onSelectedCommitChange={() => {}} + onRefresh={() => {}} + onAddToAgentSelection={() => {}} + />, + { container }, + ); + await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible(); + const panel = container.querySelector("[data-diff-panel]")!; + panel.focus(); + await userEvent.keyboard("ic"); + const draft = screen.getByRole("textbox"); + await expect.element(draft).toBeVisible(); + const line = draft.element().getAttribute("aria-label"); + + panel.focus(); + await userEvent.keyboard("jjjc"); + + await expect.element(screen.getByRole("textbox")).toHaveAccessibleName(line!); +}); + it("answers a commit's diff link only once that commit's diff is shown", async () => { setup({ paged: false }); const container = document.createElement("div"); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index f29d002c2bf81..32ae9dbae3b20 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -14,10 +14,11 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import type { CodeViewItem, DiffLineAnnotation, + FileDiffContentsLoader, FileDiffMetadata, SelectedLineRange, } from "@pierre/diffs"; -import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react"; +import type { CodeViewAnnotationArgs, CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react"; import type { EnvironmentId, PullRequestDetailView, @@ -57,6 +58,7 @@ import { useEffectEvent, useRef, useState, + type ComponentProps, type ReactNode, } from "react"; import { msg, T, useGT, useMessages, Var } from "gt-react"; @@ -65,6 +67,7 @@ import { m, type MessageResolver } from "~/i18n/messages"; import { observeIntersection } from "~/lib/observeIntersection"; import { useLocalStorage } from "~/hooks/useLocalStorage"; +import { useStableCallback } from "~/hooks/useStableCallback"; import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; import { useRenderedAppearance } from "~/hooks/useTheme"; import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse"; @@ -112,11 +115,21 @@ import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { DiffFileTree } from "../diffs/DiffFileTree"; import { FileExplorerPane } from "../files/FileExplorerPane"; import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal"; +import { + DiffCursorOutline, + DiffSingleFileToggle, + DiffViewedCount, + DiffViewedToggle, +} from "../diffs/DiffReviewControls"; +import { + DiffReviewCursorContext, + useDiffReviewKeyboard, + useDiffReviewSelectedLines, +} from "../diffs/useDiffReviewKeyboard"; import { useHideTestFiles } from "../diffs/useHideTestFiles"; import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic"; import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView"; import { Button } from "../ui/button"; -import { Checkbox } from "../ui/checkbox"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { DropdownMenu, @@ -305,6 +318,13 @@ interface FileViewedToggleState { readonly isViewed: (path: string) => boolean; readonly isStale: (path: string) => boolean; readonly setFileViewed: (fileKey: string, viewed: boolean, extendRange: boolean) => void; + readonly shortcutLabel: string | null; +} + +/** The viewer with the review cursor's lines selected; a cursor move redraws only this. */ +function ReviewCodeView(props: ComponentProps>) { + const selectedLines = useDiffReviewSelectedLines(); + return {...props} selectedLines={selectedLines} />; } // Context updates viewed toggles without invalidating memoized header portals. @@ -319,49 +339,20 @@ function FileViewedToggle({ readonly path: string; readonly stat: ReactNode; }) { - const gt = useGT(); const viewedFiles = use(FileViewedToggleContext); if (viewedFiles === null || !viewedFiles.enabled) return stat; - const viewed = viewedFiles.isViewed(path); - const stale = viewedFiles.isStale(path); return ( {stat} - + + viewedFiles.setFileViewed(fileKey, viewed, extendRange) + } + /> ); } @@ -447,6 +438,7 @@ function PullRequestCodeTab({ useDiffWorkerPool(); const settings = useClientSettings((settings) => ({ diffFilesCollapsed: settings.diffFilesCollapsed, + diffAutoAdvanceOnViewed: settings.diffAutoAdvanceOnViewed, diffIgnoreWhitespace: settings.diffIgnoreWhitespace, diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, @@ -466,10 +458,6 @@ function PullRequestCodeTab({ Schema.Boolean, ); const [hideTestFiles, setHideTestFiles] = useHideTestFiles(); - const [selectedLines, setSelectedLines] = useState<{ - id: string; - range: SelectedLineRange; - } | null>(null); const [draft, setDraft] = useState(null); const [threadPending, setThreadPending] = useState(false); const [orphansOpen, setOrphansOpen] = useState(false); @@ -495,7 +483,6 @@ function PullRequestCodeTab({ setStateScopeKey(scopeKey); setLastViewedFileKey(null); setDraft(null); - setSelectedLines(null); setFoldChoices(new Map()); setFoldOverride(null); setVisibleCommitCount(COMMIT_PAGE_SIZE); @@ -646,12 +633,15 @@ function PullRequestCodeTab({ const codeViewReveal = useCodeViewFileReveal(); const answeredRevealNonce = useRef(null); - const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, { + const currentLoadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, { environmentId, reference, commit, cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, }); + const loadDiffFiles: FileDiffContentsLoader = useStableCallback((fileDiff) => + currentLoadDiffFiles(fileDiff), + ); const completionScope = pullRequestCompletionScope(detail, environmentId, reference); const hostReview = detail.capabilities.review; const review = { @@ -946,14 +936,76 @@ function PullRequestCodeTab({ const foldsAsViewed = (path: string) => filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); - const items: CodeViewDiffItem[] = annotatedFiles.map( - ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { - const collapsed = isFileDiffCollapsed( - fileKey, - effectiveFoldOverride, - foldChoices, - foldsAsViewed(path), - ); + const pathByFileKey = new Map(annotatedFiles.map((file) => [file.fileKey, file.path])); + const isCollapsed = (fileKey: string) => { + const path = pathByFileKey.get(fileKey); + return isFileDiffCollapsed( + fileKey, + effectiveFoldOverride, + foldChoices, + path !== undefined && foldsAsViewed(path), + ); + }; + const setCollapsed = (fileKey: string, collapsed: boolean) => + setFoldChoices((current) => withFileDiffFold(current, fileKey, collapsed)); + const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { + const range = getFileViewedRange( + annotatedFiles, + fileKey, + extendRange ? lastViewedFileKey : null, + ); + setLastViewedFileKey(fileKey); + for (const file of range) { + // A commit's diff names that commit's version of the file, not the head's. + setViewed(file.path, viewed, commit === null ? file.fileDiff.newObjectId : undefined); + } + setFoldChoices((current) => + range.reduce( + (next, file) => + withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), + current, + ), + ); + }; + const viewerHandleRef = useRef | null>(null); + const attachViewer = useStableCallback( + (handle: CodeViewHandle | null) => { + viewerHandleRef.current = handle; + codeViewReveal.attach(handle); + }, + ); + const { rootRef: reviewRootRef, ...diffReview } = useDiffReviewKeyboard({ + scopeKey, + files: annotatedFiles.map(({ fileKey, path, fileDiff }) => ({ + fileKey, + filePath: path, + fileDiff, + rendered: true, + })), + diffStyle: diffLayout === "split" ? "split" : "unified", + canLoadFullFiles: true, + autoAdvanceOnViewed: settings.diffAutoAdvanceOnViewed, + getViewer: () => viewerHandleRef.current, + isCollapsed, + setCollapsed, + isViewed: (file) => filesViewedEnabled && isFileViewed(file.filePath), + setViewed: filesViewedEnabled + ? (file, viewed) => setFileViewed(file.fileKey, viewed, false) + : null, + revealFile: (file, align) => codeViewReveal.request(file.fileKey, undefined, align), + beginComment: (fileKey, range) => { + const item = items.find((candidate) => candidate.id === fileKey); + if (item) beginComment(range, { item }); + }, + }); + + const items: CodeViewDiffItem[] = annotatedFiles + .filter( + ({ fileKey }) => + diffReview.singleFileKey === undefined || fileKey === diffReview.singleFileKey, + ) + .map(({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { + const collapsed = fileKey !== diffReview.singleFileKey && isCollapsed(fileKey); const viewedMark = filesViewedEnabled ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` : ""; @@ -965,8 +1017,7 @@ function PullRequestCodeTab({ collapsed, version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), }; - }, - ); + }); const fileKeys = items.map((item) => item.id); const collapsedFileKeys = new Set( items.filter((item) => item.collapsed === true).map((item) => item.id), @@ -994,54 +1045,26 @@ function PullRequestCodeTab({ ); }; - const toggleFile = (fileKey: string) => { - const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path; - const viewed = path !== undefined && foldsAsViewed(path); - setFoldChoices((current) => - withFileDiffFold( - current, - fileKey, - !isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed), - ), - ); - }; - - const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { - const range = getFileViewedRange( - annotatedFiles, - fileKey, - extendRange ? lastViewedFileKey : null, - ); - setLastViewedFileKey(fileKey); - for (const file of range) { - // A commit's diff names that commit's version of the file, not the head's. - setViewed(file.path, viewed, commit === null ? file.fileDiff.newObjectId : undefined); - } - setFoldChoices((current) => - range.reduce( - (next, file) => - withFileDiffFold(next, file.fileKey, effectiveFoldOverride === null ? undefined : viewed), - current, - ), - ); - }; const fileViewedToggle = { enabled: filesViewedEnabled, isViewed: isFileViewed, isStale: isFileViewedStale, setFileViewed, + shortcutLabel: diffReview.shortcutLabels.viewed, }; const revealFile = (path: string, range?: SelectedLineRange) => { - const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); - if (item === undefined) return; + const file = annotatedFiles.find((candidate) => candidate.path === path); + if (file === undefined) return; + if (range) diffReview.onSelectedLinesChange({ id: file.fileKey, range }); + else diffReview.selectFile(path); // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. - setFoldChoices((current) => withFileDiffFold(current, item.id, false)); - if (range) setSelectedLines({ id: item.id, range }); - codeViewReveal.request(item.id, range); + setCollapsed(file.fileKey, false); + codeViewReveal.request(file.fileKey, range); }; const toggleAllFiles = () => { + diffReview.showAllFiles(); setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); setFoldChoices(new Map()); }; @@ -1051,33 +1074,37 @@ function PullRequestCodeTab({ (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate), ); - const beginComment = ( - range: SelectedLineRange | null, - context: { item: CodeViewItem }, - ) => { - if (!range || !canSelectLines || withheldRefetching) return; - const item = context.item; - if (item.type !== "diff") return; - const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id); - if (!file) return; - // On a host without ranged comments a range collapses to its last line: one that silently - // lost its first line there would be worse than one line. - const path = resolveFileDiffPath(file); - const previousPath = resolveFileDiffPreviousPath(file); - const sourceFile = parsedSlices - .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : [])) - .find((candidate) => resolveFileDiffPath(candidate) === path); - const anchor = - (sourceFile && resolveDiffReviewAnchor(sourceFile, range, rangeComments)) ?? - resolveDiffReviewAnchor(file, range, rangeComments); - if (anchor === null) return; - setDraft({ - fileKey: item.id, - path, - oldPath: previousPath === path ? null : previousPath, - ...anchor, - range, - }); + const beginComment = useStableCallback( + (range: SelectedLineRange | null, context: { item: CodeViewItem }) => { + if (!range || !canSelectLines || draft !== null || withheldRefetching) return; + const item = context.item; + if (item.type !== "diff") return; + const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id); + if (!file) return; + // On a host without ranged comments a range collapses to its last line: one that silently + // lost its first line there would be worse than one line. + const path = resolveFileDiffPath(file); + const previousPath = resolveFileDiffPreviousPath(file); + const sourceFile = parsedSlices + .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : [])) + .find((candidate) => resolveFileDiffPath(candidate) === path); + const anchor = + (sourceFile && resolveDiffReviewAnchor(sourceFile, range, rangeComments)) ?? + resolveDiffReviewAnchor(file, range, rangeComments); + if (anchor === null) return; + setDraft({ + fileKey: item.id, + path, + oldPath: previousPath === path ? null : previousPath, + ...anchor, + range, + }); + }, + ); + + const closeDraft = () => { + setDraft(null); + diffReview.onDraftClose(); }; const finishSelection = ( @@ -1099,8 +1126,7 @@ function PullRequestCodeTab({ range: anchor.range, text, }); - setDraft(null); - setSelectedLines(null); + closeDraft(); if (comment !== null) onFinish(comment); }; @@ -1129,23 +1155,28 @@ function PullRequestCodeTab({ const renderHeaderPrefix = (item: CodeViewItem) => { const collapsed = item.collapsed === true; return ( - + <> + {item.type === "diff" ? ( + + ) : null} + + ); }; @@ -1172,6 +1203,10 @@ function PullRequestCodeTab({ ); }; + const onPostRender = useStableCallback(() => { + codeViewReveal.flush(); + diffReview.flushScroll(); + }); const diffViewOptions = { diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const), lineDiffType: "none" as const, @@ -1192,7 +1227,7 @@ function PullRequestCodeTab({ onGutterUtilityClick: beginComment, onLineSelectionEnd: beginComment, onPostRender: (fileContainer: HTMLElement, instance: object) => { - codeViewReveal.flush(); + onPostRender(); // Containers are reused across files, so the flag is set or cleared on every render. fileContainer.toggleAttribute( "data-cut-lines", @@ -1203,10 +1238,7 @@ function PullRequestCodeTab({ onItemCollapsedChange: ( _item: CodeViewItem, nextItem: CodeViewItem, - ) => - setFoldChoices((current) => - withFileDiffFold(current, nextItem.id, nextItem.collapsed === true), - ), + ) => setCollapsed(nextItem.id, nextItem.collapsed === true), }; const runThreadCommand = async ( @@ -1346,10 +1378,7 @@ function PullRequestCodeTab({ }, } : {})} - onCancel={() => { - setDraft(null); - setSelectedLines(null); - }} + onCancel={closeDraft} onComment={(body) => { if (!canCommentOnLines) { if (onAddToAgentSelection) { @@ -1367,8 +1396,7 @@ function PullRequestCodeTab({ position: draft.position, body, }); - setDraft(null); - setSelectedLines(null); + closeDraft(); }} /> ) : null} @@ -1380,7 +1408,7 @@ function PullRequestCodeTab({ const changeIgnoreWhitespace = (next: boolean) => { setIgnoreWhitespace(next); setDraft(null); - setSelectedLines(null); + diffReview.onSelectedLinesChange(null); }; const toolbar = (
@@ -1455,7 +1483,10 @@ function PullRequestCodeTab({ {filesViewed.enabled && files.length > 0 ? ( - {filePaths.filter(isFileViewed).length} / {files.length} + {viewedFilesStore === "environment" @@ -1702,6 +1733,13 @@ function PullRequestCodeTab({ ) : null} + {annotatedFiles.length > 0 ? ( + + ) : null} {fileKeys.length > 0 ? ( { if (revealRequest === null || answeredRevealNonce.current === revealRequest.nonce) return; - if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) { + if (!annotatedFiles.some((file) => file.path === revealRequest.path)) { if (canLoadNextSlice) loadNextSlice(); return; } @@ -1755,10 +1793,7 @@ function PullRequestCodeTab({ } const key = `${scopeKey}:${revealUrl}`; if (answeredLink.current === key) return; - if ( - !pendingLinkPath || - !items.some((item) => resolveFileDiffPath(item.fileDiff) === pendingLinkPath) - ) { + if (!pendingLinkPath || !annotatedFiles.some((file) => file.path === pendingLinkPath)) { if (canLoadNextSlice) loadNextSlice(); // Every page is loaded and none has the file. else if (!pendingLinkPath && loadedSlices.length > 0 && nextCursor === null) { @@ -1852,7 +1887,13 @@ function PullRequestCodeTab({ } return ( -
+ // Focusable so a click anywhere in the tab, toolbar included, gives it the review keys. +
{toolbar} {orphanFiles.size > 0 ? (
@@ -1933,7 +1974,7 @@ function PullRequestCodeTab({ const item = items.find( (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, ); - if (item !== undefined) toggleFile(item.id); + if (item !== undefined) diffReview.toggleFileCollapsed(item.id); return; } } @@ -1941,20 +1982,28 @@ function PullRequestCodeTab({ > {/* The viewer must own its scroll element to position virtual rows within it. */} - - className="@container h-full overflow-auto [scrollbar-gutter:stable]" - containerRef={scrollerRef} - viewerRef={codeViewReveal.attach} - items={items} - selectedLines={selectedLines} - onSelectedLinesChange={setSelectedLines} - options={diffViewOptions} - renderCodeViewFooter={renderCodeViewFooter} - renderHeaderPrefix={renderHeaderPrefix} - renderHeaderMetadata={renderHeaderMetadata} - renderAnnotation={renderAnnotation} - unsafeCSSExtra={`${REPLACE_FILE_COUNTS_CSS}\n${CUT_LINES_CSS}`} - /> + + +
{fileTreeOpen ? ( diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index e90f58d7566be..a87e6a8d03598 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -236,7 +236,12 @@ const KEYBINDING_GROUPS = [ { id: "threads", title: msg("Threads"), prefixes: ["thread", "chat", "pullRequest"] }, { id: "composer", title: msg("Composer"), prefixes: ["composer", "modelPicker"] }, { id: "terminal", title: msg("Terminal"), prefixes: ["terminal"] }, - { id: "preview", title: msg("Preview & diff"), prefixes: ["preview", "diff"] }, + { + id: "preview", + title: msg("Preview", { $context: "the in-app browser preview" }), + prefixes: ["preview"], + }, + { id: "diff", title: msg("Diff", { $context: "noun, a code diff viewer" }), prefixes: ["diff"] }, { id: "appearance", title: msg("Appearance"), @@ -429,6 +434,21 @@ const COMMAND_LABELS: Partial> = { "rightPanel.close": msg("Right Panel: Close"), "pullRequest.copyNumber": msg("Pull Request: Copy Number"), "diff.toggle": msg("Diff: Toggle"), + "diff.nextFile": msg("Diff: Next File"), + "diff.previousFile": msg("Diff: Previous File"), + "diff.nextUnviewedFile": msg("Diff: Next Unviewed File"), + "diff.previousUnviewedFile": msg("Diff: Previous Unviewed File"), + "diff.toggleFileCollapsed": msg("Diff: Toggle File Collapsed"), + "diff.toggleFileViewed": msg("Diff: Toggle File Viewed"), + "diff.toggleSingleFile": msg("Diff: Toggle Single File"), + "diff.enterLineMode": msg("Diff: Enter Line Mode"), + "diff.nextLine": msg("Diff: Next Line"), + "diff.previousLine": msg("Diff: Previous Line"), + "diff.expandBelow": msg("Diff: Expand Below"), + "diff.expandAbove": msg("Diff: Expand Above"), + "diff.comment": msg("Diff: Comment"), + "diff.startSelection": msg("Diff: Start Selection"), + "diff.back": msg("Diff: Back"), "preview.toggle": msg("Preview: Toggle"), "preview.refresh": msg("Preview: Refresh"), "preview.zoomIn": msg("Preview: Zoom In"), diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index e0a12417848fa..d188e3d20815f 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -564,6 +564,9 @@ export function useSettingsRestore(onRestored?: () => void) { ? [gt("Diff whitespace changes")] : []), ...(settings.diffLayout !== DEFAULT_UNIFIED_SETTINGS.diffLayout ? [gt("Diff layout")] : []), + ...(settings.diffAutoAdvanceOnViewed !== DEFAULT_UNIFIED_SETTINGS.diffAutoAdvanceOnViewed + ? [gt("Auto-advance after marking viewed")] + : []), ...(settings.proactivePanelsEnabled !== DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled ? [gt("Open pull requests and changes panels proactively")] : []), @@ -705,6 +708,7 @@ export function useSettingsRestore(onRestored?: () => void) { diffFilesCollapsed: DEFAULT_UNIFIED_SETTINGS.diffFilesCollapsed, diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace, diffLayout: DEFAULT_UNIFIED_SETTINGS.diffLayout, + diffAutoAdvanceOnViewed: DEFAULT_UNIFIED_SETTINGS.diffAutoAdvanceOnViewed, proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled, showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu, composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled, @@ -1737,6 +1741,32 @@ export function DiffsSettingsPanel() { } /> + + updateSettings({ + diffAutoAdvanceOnViewed: DEFAULT_UNIFIED_SETTINGS.diffAutoAdvanceOnViewed, + }) + } + /> + ) : null + } + control={ + + updateSettings({ diffAutoAdvanceOnViewed: Boolean(checked) }) + } + aria-label={gt("Auto-advance after marking viewed")} + /> + } + /> diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index b02f8d2f0b0c8..62f37d30ed69c 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -767,6 +767,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/diffs", searchTerms: [msg("collapsed expanded collapse expand files pull request pr code tab")], }, + { + id: "diff-auto-advance-on-viewed", + title: msg("Auto-advance after marking viewed"), + to: "/settings/diffs", + searchTerms: [msg("viewed review next unviewed file jump keyboard")], + }, { id: "diff-layout", title: msg("Diff layout"), diff --git a/apps/web/src/diffViewedStore.test.ts b/apps/web/src/diffViewedStore.test.ts new file mode 100644 index 0000000000000..03fafcfb7755b --- /dev/null +++ b/apps/web/src/diffViewedStore.test.ts @@ -0,0 +1,73 @@ +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; +import { describe, expect, it } from "vite-plus/test"; + +import { diffViewedEntry, diffViewedFingerprint, useDiffViewedStore } from "./diffViewedStore"; + +function patchFile(index: string, hunk: string) { + return parsePatchFiles( + `diff --git a/a.ts b/a.ts\nindex ${index} 100644\n--- a/a.ts\n+++ b/a.ts\n${hunk}`, + { cacheKeyPrefix: "a.ts" }, + )[0]!.files[0]!; +} + +const WITH_WHITESPACE = "@@ -1,2 +1,2 @@\n-a = 1\n+a = 1\n-b\n+c\n"; +const WITHOUT_WHITESPACE = "@@ -2 +2 @@\n-b\n+c\n"; + +function setup() { + useDiffViewedStore.setState({ viewedByThreadKey: {} }); + return useDiffViewedStore.getState(); +} + +describe("diffViewedFingerprint", () => { + it("survives the whitespace toggle and changes with the file contents", () => { + const viewed = patchFile("1111111..2222222", WITH_WHITESPACE); + expect(diffViewedFingerprint(patchFile("1111111..2222222", WITHOUT_WHITESPACE))).toBe( + diffViewedFingerprint(viewed), + ); + expect(diffViewedFingerprint(patchFile("1111111..3333333", WITH_WHITESPACE))).not.toBe( + diffViewedFingerprint(viewed), + ); + }); + + it("falls back to the diff content without blob ids", () => { + const withoutIndex = (hunk: string) => + parsePatchFiles(`diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n${hunk}`, { + cacheKeyPrefix: "a.ts", + })[0]!.files[0]!; + expect(diffViewedFingerprint(withoutIndex(WITHOUT_WHITESPACE))).not.toBe( + diffViewedFingerprint(withoutIndex(WITH_WHITESPACE)), + ); + }); +}); + +describe("useDiffViewedStore", () => { + it("keeps one fingerprint per file, so a changed file reads as unviewed", () => { + const store = setup(); + store.setFileViewed("thread", "a.ts", "old", true); + store.setFileViewed("thread", "a.ts", "new", true); + expect(useDiffViewedStore.getState().viewedByThreadKey.thread).toEqual([ + diffViewedEntry("a.ts", "new"), + ]); + store.setFileViewed("thread", "a.ts", "new", false); + expect(useDiffViewedStore.getState().viewedByThreadKey).toEqual({}); + }); + + it("drops the oldest files and the least recently reviewed threads past the caps", () => { + const store = setup(); + for (let index = 0; index <= 2000; index += 1) { + store.setFileViewed("big", `file-${index}.ts`, "v", true); + } + const files = useDiffViewedStore.getState().viewedByThreadKey.big; + expect(files).toHaveLength(2000); + expect(files?.[0]).toBe(diffViewedEntry("file-1.ts", "v")); + + for (let index = 0; index < 100; index += 1) { + store.setFileViewed(`thread-${index}`, "a.ts", "v", true); + } + store.setFileViewed("thread-0", "b.ts", "v", true); + const threads = Object.keys(useDiffViewedStore.getState().viewedByThreadKey); + expect(threads).toHaveLength(100); + expect(threads).not.toContain("big"); + expect(threads.at(-1)).toBe("thread-0"); + }); +}); diff --git a/apps/web/src/diffViewedStore.ts b/apps/web/src/diffViewedStore.ts new file mode 100644 index 0000000000000..5c15060d742c8 --- /dev/null +++ b/apps/web/src/diffViewedStore.ts @@ -0,0 +1,64 @@ +import type { FileDiffMetadata } from "@pierre/diffs"; +import { create } from "zustand"; +import { createJSONStorage, persist } from "zustand/middleware"; + +import { buildFileDiffContentVersion } from "./lib/diffRendering"; +import { resolveStorage } from "./lib/storage"; + +// Nothing removes a thread's entries when it goes away, so both levels drop their oldest. +const MAX_VIEWED_FILES_PER_THREAD = 2000; +const MAX_VIEWED_THREADS = 100; + +/** + * Identifies the reviewed contents of a file. Blob ids survive the whitespace toggle, which + * changes the hunks but not the files; diffs without them fall back to the rendered content. + */ +export function diffViewedFingerprint(fileDiff: FileDiffMetadata): string { + return fileDiff.prevObjectId && fileDiff.newObjectId + ? `${fileDiff.prevObjectId}..${fileDiff.newObjectId}` + : `v${buildFileDiffContentVersion(fileDiff)}`; +} + +export function diffViewedEntry(filePath: string, fingerprint: string): string { + return `${filePath}\u0000${fingerprint}`; +} + +interface DiffViewedStoreState { + /** Per thread, viewed `path\0fingerprint` entries, newest last. Threads are oldest first. */ + viewedByThreadKey: Record>; + setFileViewed: ( + threadKey: string, + filePath: string, + fingerprint: string, + viewed: boolean, + ) => void; +} + +export const useDiffViewedStore = create()( + persist( + (set) => ({ + viewedByThreadKey: {}, + setFileViewed: (threadKey, filePath, fingerprint, viewed) => + set((state) => { + const pathPrefix = diffViewedEntry(filePath, ""); + const entries = (state.viewedByThreadKey[threadKey] ?? []).filter( + (entry) => !entry.startsWith(pathPrefix), + ); + if (viewed) entries.push(diffViewedEntry(filePath, fingerprint)); + const { [threadKey]: _previous, ...others } = state.viewedByThreadKey; + const threads = Object.entries(others); + if (entries.length > 0) + threads.push([threadKey, entries.slice(-MAX_VIEWED_FILES_PER_THREAD)]); + return { viewedByThreadKey: Object.fromEntries(threads.slice(-MAX_VIEWED_THREADS)) }; + }), + }), + { + name: "t3code:diff-viewed-files:v1", + version: 1, + storage: createJSONStorage(() => + resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), + ), + partialize: (state) => ({ viewedByThreadKey: state.viewedByThreadKey }), + }, + ), +); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..272b55785177d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5289,6 +5289,8 @@ "48d7d2bee4c40a5a": "Screenshot fehlgeschlagen. Versuche es erneut.", "d48deeb7c5f630c2": "Unerwartete Antwort auf den Android-Faltbefehl.", "f32c20d2aab69630": "Faltbefehl fehlgeschlagen ({status}).", + "1ed62d567b394717": "Kommentar hinzufügen ({shortcut})", + "0f4e08f6bb804947": "Kommentar hinzufügen", "c05ae9b20227f416": "Kommentar löschen", "e8c281b1a85ac547": "Kommentar hinzufügen…", "f2160b630793c7b4": "Zeilen {rangeLabel} kommentieren", @@ -5298,6 +5300,27 @@ "1601d7e39a52c48f": "Laden des Diffs wiederholen", "b7b137472adb6989": "Teilweise Diff-Vorschau", "f0d79aa56f06663f": "Diese Datei ist zu groß für die vollständige Anzeige. Die Zahlen umfassen alle Änderungen.", + "fc8c74e56f56d6aa": "Als nicht angesehen markieren ({shortcut})", + "6b16762624454603": "Als nicht angesehen markieren", + "c1ee14e8052af637": "Als angesehen markieren ({shortcut})", + "e1e45c361a6c893c": "Als angesehen markieren", + "7061d634f9053c0d": "Geändert {path}", + "e8897fabdb381131": "Angesehen {path}", + "9756a1dd860b0fff": "Auf diese Datei wurde gepusht, seit du sie als angesehen markiert hast.", + "849059a11e9baf7a": "Alle Dateien anzeigen", + "e2545556a6fd305d": "Eine Datei nach der anderen anzeigen", + "c5e67ae1effef813": "Alle Dateien anzeigen ({shortcut})", + "3161e88a920d29f8": "Eine Datei nach der anderen anzeigen ({shortcut})", + "b989b376adde129c": [ + "Alle ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "d4ccbc96f4d05950": "Geändert", + "6594b013f63d2a3a": "Angesehen", "07b9970b662ab70d": "Mermaid-Quelltext anzeigen", "5a422b7be35243f5": "Gerendertes Diagramm anzeigen", "c0628ad999cbbbf5": "Markdown-Quelltext anzeigen", @@ -6452,8 +6475,6 @@ "909a53aaeab5f1bf": "Antwort konnte nicht veröffentlicht werden", "fe77d063483acfab": "Der Kommentar konnte nicht gespeichert werden", "c3fde30a048e5c47": "Die Unterhaltung konnte nicht aktualisiert werden", - "6345153b5d556fa4": "Geändert", - "951472eed80ea27d": "Angesehen", "68fdae4308598c56": "In einem Thread beheben", "a65107f54ff65902": "Weitere Dateien werden geladen...", "e545fcdb83e2c36a": "Zum Review hinzufügen", @@ -6484,9 +6505,6 @@ "1239149344bb4b2b": "Der Diff ist zu groß zum Anzeigen.", "3ab928741d208f41": "Wird geladen...", "3e272ae9c5b76744": "Diff laden", - "d4ccbc96f4d05950": "Geändert", - "c12888742e7bd0ce": "Auf diese Datei wurde gepusht, seit du sie als angesehen markiert hast.", - "6594b013f63d2a3a": "Angesehen", "687f81dd084a5ab0": "Der Rest dieses Diffs konnte nicht geladen werden.", "cf44cf4e3479ea7a": "Alle Commits", "d27b1db7f856ec3a": "Dieser Host speichert nicht zentral, welche Dateien du gelesen hast, daher werden diese Häkchen von dieser Umgebung gespeichert. Sie folgen dir zwischen den damit verbundenen Apps, aber die eigene Weboberfläche des Hosts zeigt sie nicht an.", @@ -8446,7 +8464,8 @@ "84a605b241ce65b7": "Gruppe und ihre Bedingungen entfernen", "1d5b3500189fef41": "Verwende Variablen mit !, &&, || und Klammern.", "a7384e7d2952afad": "Eingabefeld", - "555805dcc65047bc": "Vorschau & Diff", + "e5381928638adda1": "Vorschau", + "dfb5bf2368e336a1": "Diff", "319ee1816b17bd21": "Sonstiges", "37f2a47d12cdfdf8": "Eingabefeld: Gegenteilige Aktion (Einreihen oder Umlenken)", "d9d54dde0ba27d96": "Eingabefeld: Im Hintergrund starten", @@ -8470,6 +8489,21 @@ "97c7de6aaab317a2": "Rechter Bereich: Schließen", "97b8f50a68ff3e02": "Pull Request: Nummer kopieren", "a608714c5062154d": "Diff: Umschalten", + "42bd56eaf24cd5c5": "Diff: Nächste Datei", + "209821876545c056": "Diff: Vorherige Datei", + "74ec1f25fe3198b7": "Diff: Nächste nicht angesehene Datei", + "790509b6a5dc2f28": "Diff: Vorherige nicht angesehene Datei", + "4bda8f6a3646df83": "Diff: Datei ein- oder ausklappen", + "55ada6d6542c8bbb": "Diff: Datei als angesehen markieren oder Markierung aufheben", + "d3a74a866bb98292": "Diff: Einzeldateiansicht umschalten", + "375e9fb4adfc8203": "Diff: Zeilenmodus starten", + "e40c4bb6a3d916a3": "Diff: Nächste Zeile", + "2a1239fed9e89426": "Diff: Vorherige Zeile", + "ea7b090c1913762c": "Diff: Nach unten erweitern", + "913bb88e66ae6825": "Diff: Nach oben erweitern", + "f908dede79dee496": "Diff: Kommentieren", + "8cd1716a4948da8a": "Diff: Auswahl beginnen", + "6b54f2e44e813a00": "Diff: Zurück", "c63b12ef6fc2d448": "Vorschau: Umschalten", "6ca1f18ba380f986": "Vorschau: Aktualisieren", "a5b6c1936995ec20": "Vorschau: Vergrößern", @@ -9732,6 +9766,7 @@ "8dc3e3036cfebeaa": "Kontext im Eingabefeld", "95be9d8739887c7f": "Standardzustand von Diff-Dateien", "04fb467bba7698e2": "Leerzeichenänderungen im Diff", + "87fc1f32edf5f7ea": "Nach dem Markieren als angesehen automatisch weiter", "71d047b3f6ea9497": "Pull-Request- und Änderungs-Panels proaktiv öffnen", "4b46043fd3700c17": "Skills im Slash-Menü anzeigen", "2407d5d61e7f7206": "Rich-Text-Eingabefeld", @@ -9815,6 +9850,8 @@ "aa2ead0db85b3fde": "Standardzustand von Diff-Dateien auf Standard zurücksetzen", "610ab21300968834": "Eingeklappt", "f300ec21e6391b6c": "Ausgeklappt", + "d0eb2f1d85767f3c": "Nachdem du eine Datei als angesehen markiert hast, geht es zur nächsten nicht angesehenen Datei.", + "c160336a3f88d439": "Automatisches Weitergehen nach dem Markieren als angesehen auf Standard zurücksetzen", "a0eb0e4f76608833": "Verknüpfte Pull Requests zuerst öffnen. Andernfalls „Änderungen“ bei Bearbeitungen an mindestens 3 Dateien oder 50 Zeilen öffnen.", "16bdc70b858c223f": "Proaktive Panels auf Standard zurücksetzen", "c5424f09d77138ff": "Wann ein inaktiver Claude-Thread über 200.000 Tokens komprimiert wird: nach deiner Rückkehr, kurz bevor sein Prompt-Cache abläuft, oder nie. Jeder Claude-Anbieter kann das überschreiben.", @@ -11501,6 +11538,7 @@ "23f7dd84f1f777f0": "ausgabe token absatz gepuffert warten turn runde legacy", "28595b22d495356e": "diff leerzeichen ignorieren bearbeitungen standard", "b46730711c2d6089": "eingeklappt ausgeklappt einklappen ausklappen dateien pull request pr code tab", + "6fdf1b1784286ea6": "angesehen review nächste nicht angesehene datei springen tastatur", "6a6b1c244a1a0476": "untereinander nebeneinander geteilt vereinheitlicht inline ansicht", "7d0ab4cf50686d31": "proaktiv automatisch öffnen diff pull request pr rechter bereich agent abschluss", "5256dd2ed3a24332": "befehlsmenü dollar $ slash /", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..175a022e40c1b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5290,6 +5290,8 @@ "48d7d2bee4c40a5a": "Screenshot capture failed. Try again.", "d48deeb7c5f630c2": "Unexpected Android fold response.", "f32c20d2aab69630": "Fold command failed ({status}).", + "1ed62d567b394717": "Add comment ({shortcut})", + "0f4e08f6bb804947": "Add comment", "c05ae9b20227f416": "Delete comment", "e8c281b1a85ac547": "Add a comment…", "f2160b630793c7b4": "Comment on lines {rangeLabel}", @@ -5299,6 +5301,27 @@ "1601d7e39a52c48f": "Retry loading diff", "b7b137472adb6989": "Partial diff preview", "f0d79aa56f06663f": "This file is too large to show in full. Counts include all changes.", + "fc8c74e56f56d6aa": "Mark as not viewed ({shortcut})", + "6b16762624454603": "Mark as not viewed", + "c1ee14e8052af637": "Mark as viewed ({shortcut})", + "e1e45c361a6c893c": "Mark as viewed", + "7061d634f9053c0d": "Changed {path}", + "e8897fabdb381131": "Viewed {path}", + "9756a1dd860b0fff": "This file has been pushed to since you marked it viewed.", + "849059a11e9baf7a": "Show all files", + "e2545556a6fd305d": "Show one file at a time", + "c5e67ae1effef813": "Show all files ({shortcut})", + "3161e88a920d29f8": "Show one file at a time ({shortcut})", + "b989b376adde129c": [ + "All ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "d4ccbc96f4d05950": "Changed", + "6594b013f63d2a3a": "Viewed", "07b9970b662ab70d": "Show Mermaid source", "5a422b7be35243f5": "Show rendered diagram", "c0628ad999cbbbf5": "Show markdown source", @@ -6459,8 +6482,6 @@ "909a53aaeab5f1bf": "Reply could not be posted", "fe77d063483acfab": "The comment could not be saved", "c3fde30a048e5c47": "The conversation could not be updated", - "6345153b5d556fa4": "Changed", - "951472eed80ea27d": "Viewed", "68fdae4308598c56": "Fix in a thread", "a65107f54ff65902": "Loading more files...", "e545fcdb83e2c36a": "Add to review", @@ -6491,9 +6512,6 @@ "1239149344bb4b2b": "Diff too large to display.", "3ab928741d208f41": "Loading...", "3e272ae9c5b76744": "Load diff", - "d4ccbc96f4d05950": "Changed", - "c12888742e7bd0ce": "This file has been pushed to since you marked it viewed.", - "6594b013f63d2a3a": "Viewed", "687f81dd084a5ab0": "The rest of this diff could not be loaded.", "cf44cf4e3479ea7a": "All commits", "d27b1db7f856ec3a": "This host keeps no shared record of which files you have read, so these ticks are kept by this environment. They follow you between the apps connected to it, but the host's own web UI will not show them.", @@ -8454,7 +8472,8 @@ "84a605b241ce65b7": "Remove group and its conditions", "1d5b3500189fef41": "Use variables with !, &&, ||, and parentheses.", "a7384e7d2952afad": "Composer", - "555805dcc65047bc": "Preview & diff", + "e5381928638adda1": "Preview", + "dfb5bf2368e336a1": "Diff", "319ee1816b17bd21": "Other", "37f2a47d12cdfdf8": "Composer: Opposite Queue or Steer Action", "d9d54dde0ba27d96": "Composer: Start in Background", @@ -8478,6 +8497,21 @@ "97c7de6aaab317a2": "Right Panel: Close", "97b8f50a68ff3e02": "Pull Request: Copy Number", "a608714c5062154d": "Diff: Toggle", + "42bd56eaf24cd5c5": "Diff: Next File", + "209821876545c056": "Diff: Previous File", + "74ec1f25fe3198b7": "Diff: Next Unviewed File", + "790509b6a5dc2f28": "Diff: Previous Unviewed File", + "4bda8f6a3646df83": "Diff: Toggle File Collapsed", + "55ada6d6542c8bbb": "Diff: Toggle File Viewed", + "d3a74a866bb98292": "Diff: Toggle Single File", + "375e9fb4adfc8203": "Diff: Enter Line Mode", + "e40c4bb6a3d916a3": "Diff: Next Line", + "2a1239fed9e89426": "Diff: Previous Line", + "ea7b090c1913762c": "Diff: Expand Below", + "913bb88e66ae6825": "Diff: Expand Above", + "f908dede79dee496": "Diff: Comment", + "8cd1716a4948da8a": "Diff: Start Selection", + "6b54f2e44e813a00": "Diff: Back", "c63b12ef6fc2d448": "Preview: Toggle", "6ca1f18ba380f986": "Preview: Refresh", "a5b6c1936995ec20": "Preview: Zoom In", @@ -9741,6 +9775,7 @@ "8dc3e3036cfebeaa": "Composer context", "95be9d8739887c7f": "Default diff file state", "04fb467bba7698e2": "Diff whitespace changes", + "87fc1f32edf5f7ea": "Auto-advance after marking viewed", "71d047b3f6ea9497": "Open pull requests and changes panels proactively", "4b46043fd3700c17": "Show skills in slash menu", "2407d5d61e7f7206": "Rich text composer", @@ -9824,6 +9859,8 @@ "aa2ead0db85b3fde": "Reset default diff file state to default", "610ab21300968834": "Collapsed", "f300ec21e6391b6c": "Expanded", + "d0eb2f1d85767f3c": "After you mark a file viewed, move to the next unviewed file.", + "c160336a3f88d439": "Reset auto-advance after marking viewed to default", "a0eb0e4f76608833": "Open linked pull requests first. Otherwise, open Changes for edits to at least 3 files or 50 lines.", "16bdc70b858c223f": "Reset proactive panels to default", "c5424f09d77138ff": "When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this.", @@ -11509,6 +11546,7 @@ "23f7dd84f1f777f0": "output token paragraph buffered wait turn legacy", "28595b22d495356e": "diff ignore spaces edits default", "b46730711c2d6089": "collapsed expanded collapse expand files pull request pr code tab", + "6fdf1b1784286ea6": "viewed review next unviewed file jump keyboard", "6a6b1c244a1a0476": "stacked split side by side unified inline view", "7d0ab4cf50686d31": "proactive automatically open diff pull request pr right panel agent completion", "5256dd2ed3a24332": "command menu dollar $ slash /", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..ea236b5b47f19 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5288,6 +5288,8 @@ "48d7d2bee4c40a5a": "Falló la captura de pantalla. Vuelve a intentarlo.", "d48deeb7c5f630c2": "Respuesta de plegado de Android inesperada.", "f32c20d2aab69630": "Falló el comando de plegado ({status}).", + "1ed62d567b394717": "Añadir comentario ({shortcut})", + "0f4e08f6bb804947": "Añadir comentario", "c05ae9b20227f416": "Eliminar comentario", "e8c281b1a85ac547": "Añade un comentario…", "f2160b630793c7b4": "Comentar las líneas {rangeLabel}", @@ -5297,6 +5299,28 @@ "1601d7e39a52c48f": "Reintentar la carga del diff", "b7b137472adb6989": "Vista previa parcial del diff", "f0d79aa56f06663f": "Este archivo es demasiado grande para mostrarlo completo. Los recuentos incluyen todos los cambios.", + "fc8c74e56f56d6aa": "Marcar como no visto ({shortcut})", + "6b16762624454603": "Marcar como no visto", + "c1ee14e8052af637": "Marcar como visto ({shortcut})", + "e1e45c361a6c893c": "Marcar como visto", + "7061d634f9053c0d": "Cambiado {path}", + "e8897fabdb381131": "Visto {path}", + "9756a1dd860b0fff": "Se ha hecho push a este archivo desde que lo marcaste como visto.", + "849059a11e9baf7a": "Mostrar todos los archivos", + "e2545556a6fd305d": "Mostrar un archivo a la vez", + "c5e67ae1effef813": "Mostrar todos los archivos ({shortcut})", + "3161e88a920d29f8": "Mostrar un archivo a la vez ({shortcut})", + "b989b376adde129c": [ + "Todos (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "d4ccbc96f4d05950": "Cambiado", + "6594b013f63d2a3a": "Visto", "07b9970b662ab70d": "Mostrar el código fuente de Mermaid", "5a422b7be35243f5": "Mostrar el diagrama renderizado", "c0628ad999cbbbf5": "Mostrar el código fuente markdown", @@ -6452,8 +6476,6 @@ "909a53aaeab5f1bf": "No se pudo publicar la respuesta", "fe77d063483acfab": "No se pudo guardar el comentario", "c3fde30a048e5c47": "No se pudo actualizar la conversación", - "6345153b5d556fa4": "Cambiado", - "951472eed80ea27d": "Visto", "68fdae4308598c56": "Corregir en un hilo", "a65107f54ff65902": "Cargando más archivos...", "e545fcdb83e2c36a": "Añadir a la revisión", @@ -6484,9 +6506,6 @@ "1239149344bb4b2b": "El diff es demasiado grande para mostrarlo.", "3ab928741d208f41": "Cargando...", "3e272ae9c5b76744": "Cargar diff", - "d4ccbc96f4d05950": "Cambiado", - "c12888742e7bd0ce": "Se ha hecho push a este archivo desde que lo marcaste como visto.", - "6594b013f63d2a3a": "Visto", "687f81dd084a5ab0": "No se pudo cargar el resto de este diff.", "cf44cf4e3479ea7a": "Todos los commits", "d27b1db7f856ec3a": "Este host no guarda un registro compartido de los archivos que has leído, así que estas marcas las guarda este entorno. Te siguen entre las apps conectadas a él, pero la interfaz web del propio host no las mostrará.", @@ -8444,7 +8463,8 @@ "84a605b241ce65b7": "Quitar grupo y sus condiciones", "1d5b3500189fef41": "Usa variables con !, &&, || y paréntesis.", "a7384e7d2952afad": "Cuadro de mensaje", - "555805dcc65047bc": "Vista previa y diff", + "e5381928638adda1": "Vista previa", + "dfb5bf2368e336a1": "Diff", "319ee1816b17bd21": "Otros", "37f2a47d12cdfdf8": "Cuadro de mensaje: acción contraria a poner en cola o redirigir", "d9d54dde0ba27d96": "Cuadro de mensaje: iniciar en segundo plano", @@ -8468,6 +8488,21 @@ "97c7de6aaab317a2": "Panel derecho: cerrar", "97b8f50a68ff3e02": "Pull request: copiar número", "a608714c5062154d": "Diff: alternar", + "42bd56eaf24cd5c5": "Diff: archivo siguiente", + "209821876545c056": "Diff: archivo anterior", + "74ec1f25fe3198b7": "Diff: siguiente archivo no visto", + "790509b6a5dc2f28": "Diff: anterior archivo no visto", + "4bda8f6a3646df83": "Diff: contraer o expandir archivo", + "55ada6d6542c8bbb": "Diff: marcar o desmarcar archivo como visto", + "d3a74a866bb98292": "Diff: alternar vista de un solo archivo", + "375e9fb4adfc8203": "Diff: entrar en modo línea", + "e40c4bb6a3d916a3": "Diff: línea siguiente", + "2a1239fed9e89426": "Diff: línea anterior", + "ea7b090c1913762c": "Diff: expandir hacia abajo", + "913bb88e66ae6825": "Diff: expandir hacia arriba", + "f908dede79dee496": "Diff: comentar", + "8cd1716a4948da8a": "Diff: iniciar selección", + "6b54f2e44e813a00": "Diff: atrás", "c63b12ef6fc2d448": "Vista previa: alternar", "6ca1f18ba380f986": "Vista previa: actualizar", "a5b6c1936995ec20": "Vista previa: acercar", @@ -9729,6 +9764,7 @@ "8dc3e3036cfebeaa": "Contexto del cuadro de mensaje", "95be9d8739887c7f": "Estado predeterminado de los archivos del diff", "04fb467bba7698e2": "Cambios de espacios en blanco en el diff", + "87fc1f32edf5f7ea": "Avanzar automáticamente al marcar como visto", "71d047b3f6ea9497": "Abrir los paneles de pull requests y cambios de forma proactiva", "4b46043fd3700c17": "Mostrar skills en el menú de barra", "2407d5d61e7f7206": "Cuadro de mensaje con texto enriquecido", @@ -9812,6 +9848,8 @@ "aa2ead0db85b3fde": "Restablecer el estado predeterminado de archivos del diff al valor predeterminado", "610ab21300968834": "Contraídos", "f300ec21e6391b6c": "Expandidos", + "d0eb2f1d85767f3c": "Después de marcar un archivo como visto, pasa al siguiente archivo no visto.", + "c160336a3f88d439": "Restablecer el avance automático al marcar como visto al valor predeterminado", "a0eb0e4f76608833": "Abre primero las pull requests vinculadas. Si no hay, abre Cambios cuando se editan al menos 3 archivos o 50 líneas.", "16bdc70b858c223f": "Restablecer los paneles proactivos al valor predeterminado", "c5424f09d77138ff": "Cuándo compactar un hilo inactivo de Claude con más de 200 000 tokens: al volver, justo antes de que caduque su caché de prompts o nunca. Cada proveedor de Claude puede anularlo.", @@ -11494,6 +11532,7 @@ "23f7dd84f1f777f0": "salida token párrafo en búfer esperar turno heredado", "28595b22d495356e": "diff ignorar espacios ediciones predeterminado", "b46730711c2d6089": "contraído expandido contraer expandir archivos pull request pr código pestaña", + "6fdf1b1784286ea6": "visto revisión siguiente no visto archivo saltar teclado", "6a6b1c244a1a0476": "apilado dividido en paralelo unificado en línea vista", "7d0ab4cf50686d31": "proactivo abrir automáticamente diff pull request pr panel derecho agente finalización", "5256dd2ed3a24332": "menú de comandos dólar $ barra /", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..3625ef3232443 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5289,6 +5289,8 @@ "48d7d2bee4c40a5a": "Échec de la capture d’écran. Réessayez.", "d48deeb7c5f630c2": "Réponse de pliage Android inattendue.", "f32c20d2aab69630": "Échec de la commande de pliage ({status}).", + "1ed62d567b394717": "Ajouter un commentaire ({shortcut})", + "0f4e08f6bb804947": "Ajouter un commentaire", "c05ae9b20227f416": "Supprimer le commentaire", "e8c281b1a85ac547": "Ajouter un commentaire…", "f2160b630793c7b4": "Commenter les lignes {rangeLabel}", @@ -5298,6 +5300,28 @@ "1601d7e39a52c48f": "Réessayer de charger le diff", "b7b137472adb6989": "Aperçu partiel du diff", "f0d79aa56f06663f": "Ce fichier est trop volumineux pour être affiché en entier. Les totaux incluent toutes les modifications.", + "fc8c74e56f56d6aa": "Marquer comme non vu ({shortcut})", + "6b16762624454603": "Marquer comme non vu", + "c1ee14e8052af637": "Marquer comme vu ({shortcut})", + "e1e45c361a6c893c": "Marquer comme vu", + "7061d634f9053c0d": "Modifié {path}", + "e8897fabdb381131": "Vu {path}", + "9756a1dd860b0fff": "Ce fichier a reçu un push depuis que vous l’avez marqué comme vu.", + "849059a11e9baf7a": "Afficher tous les fichiers", + "e2545556a6fd305d": "Afficher un fichier à la fois", + "c5e67ae1effef813": "Afficher tous les fichiers ({shortcut})", + "3161e88a920d29f8": "Afficher un fichier à la fois ({shortcut})", + "b989b376adde129c": [ + "Tous (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "d4ccbc96f4d05950": "Modifié", + "6594b013f63d2a3a": "Vu", "07b9970b662ab70d": "Afficher la source Mermaid", "5a422b7be35243f5": "Afficher le diagramme rendu", "c0628ad999cbbbf5": "Afficher la source Markdown", @@ -6453,8 +6477,6 @@ "909a53aaeab5f1bf": "Impossible de publier la réponse", "fe77d063483acfab": "Impossible d’enregistrer le commentaire", "c3fde30a048e5c47": "Impossible de mettre à jour la conversation", - "6345153b5d556fa4": "Modifié", - "951472eed80ea27d": "Vu", "68fdae4308598c56": "Corriger dans un fil", "a65107f54ff65902": "Chargement d’autres fichiers...", "e545fcdb83e2c36a": "Ajouter à la revue", @@ -6485,9 +6507,6 @@ "1239149344bb4b2b": "Diff trop volumineux pour être affiché.", "3ab928741d208f41": "Chargement...", "3e272ae9c5b76744": "Charger le diff", - "d4ccbc96f4d05950": "Modifié", - "c12888742e7bd0ce": "Ce fichier a reçu un push depuis que vous l’avez marqué comme vu.", - "6594b013f63d2a3a": "Vu", "687f81dd084a5ab0": "Impossible de charger le reste de ce diff.", "cf44cf4e3479ea7a": "Tous les commits", "d27b1db7f856ec3a": "Cet hôte ne garde aucune trace partagée des fichiers que vous avez lus ; ces coches sont donc conservées par cet environnement. Elles vous suivent entre les apps qui y sont connectées, mais l’interface web de l’hôte ne les affichera pas.", @@ -8445,7 +8464,8 @@ "84a605b241ce65b7": "Supprimer le groupe et ses conditions", "1d5b3500189fef41": "Utilisez des variables avec !, &&, || et des parenthèses.", "a7384e7d2952afad": "Zone de saisie", - "555805dcc65047bc": "Aperçu et diff", + "e5381928638adda1": "Aperçu", + "dfb5bf2368e336a1": "Diff", "319ee1816b17bd21": "Autre", "37f2a47d12cdfdf8": "Zone de saisie : action inverse (file d’attente ou réorientation)", "d9d54dde0ba27d96": "Zone de saisie : démarrer en arrière-plan", @@ -8469,6 +8489,21 @@ "97c7de6aaab317a2": "Panneau de droite : fermer", "97b8f50a68ff3e02": "Pull request : copier le numéro", "a608714c5062154d": "Diff : afficher/masquer", + "42bd56eaf24cd5c5": "Diff : fichier suivant", + "209821876545c056": "Diff : fichier précédent", + "74ec1f25fe3198b7": "Diff : fichier non vu suivant", + "790509b6a5dc2f28": "Diff : fichier non vu précédent", + "4bda8f6a3646df83": "Diff : réduire ou développer le fichier", + "55ada6d6542c8bbb": "Diff : marquer le fichier comme vu ou non vu", + "d3a74a866bb98292": "Diff : afficher un seul fichier ou tous", + "375e9fb4adfc8203": "Diff : passer en mode ligne", + "e40c4bb6a3d916a3": "Diff : ligne suivante", + "2a1239fed9e89426": "Diff : ligne précédente", + "ea7b090c1913762c": "Diff : développer vers le bas", + "913bb88e66ae6825": "Diff : développer vers le haut", + "f908dede79dee496": "Diff : commenter", + "8cd1716a4948da8a": "Diff : commencer une sélection", + "6b54f2e44e813a00": "Diff : retour", "c63b12ef6fc2d448": "Aperçu : afficher/masquer", "6ca1f18ba380f986": "Aperçu : actualiser", "a5b6c1936995ec20": "Aperçu : zoom avant", @@ -9731,6 +9766,7 @@ "8dc3e3036cfebeaa": "Contexte de la zone de saisie", "95be9d8739887c7f": "État par défaut des fichiers du diff", "04fb467bba7698e2": "Modifications d’espaces dans le diff", + "87fc1f32edf5f7ea": "Avancer automatiquement après avoir marqué comme vu", "71d047b3f6ea9497": "Ouvrir proactivement les panneaux des pull requests et des modifications", "4b46043fd3700c17": "Afficher les skills dans le menu slash", "2407d5d61e7f7206": "Zone de saisie en texte enrichi", @@ -9814,6 +9850,8 @@ "aa2ead0db85b3fde": "Réinitialiser l’état par défaut des fichiers du diff à la valeur par défaut", "610ab21300968834": "Réduits", "f300ec21e6391b6c": "Développés", + "d0eb2f1d85767f3c": "Après avoir marqué un fichier comme vu, passer au fichier non vu suivant.", + "c160336a3f88d439": "Réinitialiser l’avancement automatique après marquage comme vu à la valeur par défaut", "a0eb0e4f76608833": "Ouvre d’abord les pull requests associées. Sinon, ouvre Modifications pour des changements touchant au moins 3 fichiers ou 50 lignes.", "16bdc70b858c223f": "Réinitialiser les panneaux proactifs à la valeur par défaut", "c5424f09d77138ff": "Quand compacter un fil Claude inactif de plus de 200 000 tokens : à votre retour, juste avant l’expiration de son cache de prompt, ou jamais. Chaque fournisseur Claude peut remplacer ce paramètre.", @@ -11499,6 +11537,7 @@ "23f7dd84f1f777f0": "sortie jeton paragraphe mis en tampon attendre tour ancien", "28595b22d495356e": "diff ignorer espaces modifications par défaut", "b46730711c2d6089": "réduit développé réduire développer fichiers pull request pr onglet code", + "6fdf1b1784286ea6": "vu revue suivant non vu fichier sauter clavier", "6a6b1c244a1a0476": "empilé scindé côte à côte unifié vue en ligne", "7d0ab4cf50686d31": "proactif ouvrir automatiquement diff pull request pr panneau de droite agent fin", "5256dd2ed3a24332": "commande menu dollar $ slash /", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..2f1351d3a266f 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5272,6 +5272,8 @@ "48d7d2bee4c40a5a": "スクリーンショットの撮影に失敗しました。もう一度お試しください。", "d48deeb7c5f630c2": "予期しない Android の折りたたみの応答です。", "f32c20d2aab69630": "折りたたみコマンドに失敗しました ({status})。", + "1ed62d567b394717": "コメントを追加 ({shortcut})", + "0f4e08f6bb804947": "コメントを追加", "c05ae9b20227f416": "コメントを削除", "e8c281b1a85ac547": "コメントを追加…", "f2160b630793c7b4": "{rangeLabel} 行にコメント", @@ -5281,6 +5283,28 @@ "1601d7e39a52c48f": "差分の読み込みを再試行", "b7b137472adb6989": "差分の部分プレビュー", "f0d79aa56f06663f": "このファイルは大きすぎて全体を表示できません。件数にはすべての変更が含まれます。", + "fc8c74e56f56d6aa": "未確認にする ({shortcut})", + "6b16762624454603": "未確認にする", + "c1ee14e8052af637": "確認済みにする ({shortcut})", + "e1e45c361a6c893c": "確認済みにする", + "7061d634f9053c0d": "変更あり {path}", + "e8897fabdb381131": "確認済み {path}", + "9756a1dd860b0fff": "確認済みにした後で、このファイルに新しいプッシュがありました。", + "849059a11e9baf7a": "すべてのファイルを表示", + "e2545556a6fd305d": "1 ファイルずつ表示", + "c5e67ae1effef813": "すべてのファイルを表示 ({shortcut})", + "3161e88a920d29f8": "1 ファイルずつ表示 ({shortcut})", + "b989b376adde129c": [ + "全 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 件" + ], + "d4ccbc96f4d05950": "変更あり", + "6594b013f63d2a3a": "確認済み", "07b9970b662ab70d": "Mermaid のソースを表示", "5a422b7be35243f5": "レンダリングした図を表示", "c0628ad999cbbbf5": "Markdown のソースを表示", @@ -6422,8 +6446,6 @@ "909a53aaeab5f1bf": "返信を投稿できませんでした", "fe77d063483acfab": "コメントを保存できませんでした", "c3fde30a048e5c47": "会話を更新できませんでした", - "6345153b5d556fa4": "変更あり", - "951472eed80ea27d": "確認済み", "68fdae4308598c56": "スレッドで修正", "a65107f54ff65902": "さらにファイルを読み込んでいます...", "e545fcdb83e2c36a": "レビューに追加", @@ -6454,9 +6476,6 @@ "1239149344bb4b2b": "差分が大きすぎて表示できません。", "3ab928741d208f41": "読み込んでいます...", "3e272ae9c5b76744": "差分を読み込む", - "d4ccbc96f4d05950": "変更あり", - "c12888742e7bd0ce": "確認済みにした後で、このファイルに新しいプッシュがありました。", - "6594b013f63d2a3a": "確認済み", "687f81dd084a5ab0": "この差分の残りを読み込めませんでした。", "cf44cf4e3479ea7a": "すべてのコミット", "d27b1db7f856ec3a": "このホストには、どのファイルを読んだかを共有して記録する仕組みがないため、確認済みマークはこの環境に保存されます。この環境に接続したアプリ間では共有されますが、ホストの Web UI には表示されません。", @@ -8402,7 +8421,8 @@ "84a605b241ce65b7": "グループとその条件を削除", "1d5b3500189fef41": "変数と !、&&、||、括弧を使用できます。", "a7384e7d2952afad": "入力欄", - "555805dcc65047bc": "プレビューと差分", + "e5381928638adda1": "プレビュー", + "dfb5bf2368e336a1": "差分", "319ee1816b17bd21": "その他", "37f2a47d12cdfdf8": "入力欄: キュー/軌道修正の逆の操作", "d9d54dde0ba27d96": "入力欄: バックグラウンドで開始", @@ -8426,6 +8446,21 @@ "97c7de6aaab317a2": "右パネル: 閉じる", "97b8f50a68ff3e02": "プルリクエスト: 番号をコピー", "a608714c5062154d": "差分: 切り替え", + "42bd56eaf24cd5c5": "差分: 次のファイル", + "209821876545c056": "差分: 前のファイル", + "74ec1f25fe3198b7": "差分: 次の未確認ファイル", + "790509b6a5dc2f28": "差分: 前の未確認ファイル", + "4bda8f6a3646df83": "差分: ファイルの折りたたみを切り替え", + "55ada6d6542c8bbb": "差分: ファイルの確認済みを切り替え", + "d3a74a866bb98292": "差分: 1 ファイル表示を切り替え", + "375e9fb4adfc8203": "差分: 行モードに入る", + "e40c4bb6a3d916a3": "差分: 次の行", + "2a1239fed9e89426": "差分: 前の行", + "ea7b090c1913762c": "差分: 下に展開", + "913bb88e66ae6825": "差分: 上に展開", + "f908dede79dee496": "差分: コメント", + "8cd1716a4948da8a": "差分: 選択を開始", + "6b54f2e44e813a00": "差分: 戻る", "c63b12ef6fc2d448": "プレビュー: 切り替え", "6ca1f18ba380f986": "プレビュー: 再読み込み", "a5b6c1936995ec20": "プレビュー: 拡大", @@ -9683,6 +9718,7 @@ "8dc3e3036cfebeaa": "入力欄のコンテキスト", "95be9d8739887c7f": "差分ファイルのデフォルト表示", "04fb467bba7698e2": "差分の空白の変更", + "87fc1f32edf5f7ea": "確認済みにしたら次へ自動で進む", "71d047b3f6ea9497": "プルリクエストと変更のパネルを自動的に開く", "4b46043fd3700c17": "スラッシュメニューにスキルを表示", "2407d5d61e7f7206": "リッチテキスト入力欄", @@ -9766,6 +9802,8 @@ "aa2ead0db85b3fde": "差分ファイルのデフォルト表示をデフォルトにリセット", "610ab21300968834": "折りたたみ", "f300ec21e6391b6c": "展開", + "d0eb2f1d85767f3c": "ファイルを確認済みにすると、次の未確認ファイルに移動します。", + "c160336a3f88d439": "確認済み後の自動移動をデフォルトにリセット", "a0eb0e4f76608833": "リンクされたプルリクエストがあれば最初に開きます。ない場合は、3 ファイル以上または 50 行以上の編集で変更パネルを開きます。", "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "c5424f09d77138ff": "200,000 トークンを超えるアイドル状態の Claude スレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの有効期限の直前、またはしない、から選びます。Claude プロバイダーごとに上書きできます。", @@ -11449,6 +11487,7 @@ "23f7dd84f1f777f0": "出力 トークン 段落 バッファー 待機 ターン レガシー streaming", "28595b22d495356e": "差分 空白を無視 スペース 編集 デフォルト diff whitespace", "b46730711c2d6089": "折りたたみ 展開 ファイル プルリクエスト PR コード タブ collapsed expanded", + "6fdf1b1784286ea6": "確認済み レビュー 次 未確認 ファイル ジャンプ キーボード viewed review", "6a6b1c244a1a0476": "縦並び 分割 左右 統合 インライン 表示 stacked split unified", "7d0ab4cf50686d31": "自動 開く 差分 プルリクエスト PR 右パネル エージェント 完了 proactive", "5256dd2ed3a24332": "コマンドメニュー ドル $ スラッシュ / command menu", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..04973f950ef8d 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5269,6 +5269,8 @@ "48d7d2bee4c40a5a": "스크린샷을 캡처하지 못했습니다. 다시 시도하세요.", "d48deeb7c5f630c2": "예기치 않은 Android 접기 응답입니다.", "f32c20d2aab69630": "접기 명령에 실패했습니다({status}).", + "1ed62d567b394717": "댓글 추가({shortcut})", + "0f4e08f6bb804947": "댓글 추가", "c05ae9b20227f416": "댓글 삭제", "e8c281b1a85ac547": "댓글 추가…", "f2160b630793c7b4": "{rangeLabel}행에 댓글 달기", @@ -5278,6 +5280,28 @@ "1601d7e39a52c48f": "변경 사항 다시 불러오기", "b7b137472adb6989": "변경 사항 일부 미리 보기", "f0d79aa56f06663f": "이 파일은 너무 커서 전체를 표시할 수 없습니다. 개수에는 모든 변경 사항이 포함됩니다.", + "fc8c74e56f56d6aa": "확인 안 함으로 표시({shortcut})", + "6b16762624454603": "확인 안 함으로 표시", + "c1ee14e8052af637": "확인함으로 표시({shortcut})", + "e1e45c361a6c893c": "확인함으로 표시", + "7061d634f9053c0d": "변경됨 {path}", + "e8897fabdb381131": "확인함 {path}", + "9756a1dd860b0fff": "확인함으로 표시한 후 이 파일에 새로운 푸시가 있었습니다.", + "849059a11e9baf7a": "모든 파일 표시", + "e2545556a6fd305d": "한 번에 한 파일씩 표시", + "c5e67ae1effef813": "모든 파일 표시({shortcut})", + "3161e88a920d29f8": "한 번에 한 파일씩 표시({shortcut})", + "b989b376adde129c": [ + "전체 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "개" + ], + "d4ccbc96f4d05950": "변경됨", + "6594b013f63d2a3a": "확인함", "07b9970b662ab70d": "Mermaid 소스 표시", "5a422b7be35243f5": "렌더링된 다이어그램 표시", "c0628ad999cbbbf5": "Markdown 소스 표시", @@ -6424,8 +6448,6 @@ "909a53aaeab5f1bf": "답글을 게시할 수 없습니다", "fe77d063483acfab": "댓글을 저장할 수 없습니다", "c3fde30a048e5c47": "대화를 업데이트할 수 없습니다", - "6345153b5d556fa4": "변경됨", - "951472eed80ea27d": "확인함", "68fdae4308598c56": "스레드에서 수정", "a65107f54ff65902": "파일을 더 불러오는 중...", "e545fcdb83e2c36a": "검토에 추가", @@ -6456,9 +6478,6 @@ "1239149344bb4b2b": "변경 사항이 너무 커서 표시할 수 없습니다.", "3ab928741d208f41": "불러오는 중...", "3e272ae9c5b76744": "변경 사항 불러오기", - "d4ccbc96f4d05950": "변경됨", - "c12888742e7bd0ce": "확인함으로 표시한 후 이 파일에 새로운 푸시가 있었습니다.", - "6594b013f63d2a3a": "확인함", "687f81dd084a5ab0": "이 변경 사항의 나머지를 불러올 수 없습니다.", "cf44cf4e3479ea7a": "모든 커밋", "d27b1db7f856ec3a": "이 호스트는 어떤 파일을 읽었는지 공유 기록을 보관하지 않으므로 이 체크 표시는 이 환경에 보관됩니다. 이 환경에 연결된 앱 간에는 따라오지만 호스트의 웹 UI에는 표시되지 않습니다.", @@ -8405,7 +8424,8 @@ "84a605b241ce65b7": "그룹과 조건 제거", "1d5b3500189fef41": "변수와 !, &&, ||, 괄호를 사용하세요.", "a7384e7d2952afad": "입력창", - "555805dcc65047bc": "미리 보기 및 변경 사항", + "e5381928638adda1": "미리 보기", + "dfb5bf2368e336a1": "변경 사항", "319ee1816b17bd21": "기타", "37f2a47d12cdfdf8": "입력창: 대기열/방향 조정 반대 동작", "d9d54dde0ba27d96": "입력창: 백그라운드에서 시작", @@ -8429,6 +8449,21 @@ "97c7de6aaab317a2": "오른쪽 패널: 닫기", "97b8f50a68ff3e02": "풀 리퀘스트: 번호 복사", "a608714c5062154d": "변경 사항: 전환", + "42bd56eaf24cd5c5": "변경 사항: 다음 파일", + "209821876545c056": "변경 사항: 이전 파일", + "74ec1f25fe3198b7": "변경 사항: 다음 미확인 파일", + "790509b6a5dc2f28": "변경 사항: 이전 미확인 파일", + "4bda8f6a3646df83": "변경 사항: 파일 접기 전환", + "55ada6d6542c8bbb": "변경 사항: 파일 확인함 전환", + "d3a74a866bb98292": "변경 사항: 단일 파일 보기 전환", + "375e9fb4adfc8203": "변경 사항: 줄 모드 시작", + "e40c4bb6a3d916a3": "변경 사항: 다음 줄", + "2a1239fed9e89426": "변경 사항: 이전 줄", + "ea7b090c1913762c": "변경 사항: 아래로 펼치기", + "913bb88e66ae6825": "변경 사항: 위로 펼치기", + "f908dede79dee496": "변경 사항: 댓글", + "8cd1716a4948da8a": "변경 사항: 선택 시작", + "6b54f2e44e813a00": "변경 사항: 뒤로", "c63b12ef6fc2d448": "미리 보기: 전환", "6ca1f18ba380f986": "미리 보기: 새로 고침", "a5b6c1936995ec20": "미리 보기: 확대", @@ -9686,6 +9721,7 @@ "8dc3e3036cfebeaa": "입력창 컨텍스트", "95be9d8739887c7f": "기본 변경 파일 상태", "04fb467bba7698e2": "공백 변경 사항", + "87fc1f32edf5f7ea": "확인함으로 표시한 후 자동으로 다음 파일로 이동", "71d047b3f6ea9497": "풀 리퀘스트 및 변경 사항 패널 미리 열기", "4b46043fd3700c17": "슬래시 메뉴에 스킬 표시", "2407d5d61e7f7206": "서식 있는 텍스트 입력창", @@ -9769,6 +9805,8 @@ "aa2ead0db85b3fde": "기본 변경 사항 파일 상태 기본값으로 재설정", "610ab21300968834": "접힘", "f300ec21e6391b6c": "펼침", + "d0eb2f1d85767f3c": "파일을 확인함으로 표시하면 다음 미확인 파일로 이동합니다.", + "c160336a3f88d439": "확인함 표시 후 자동 이동 기본값으로 재설정", "a0eb0e4f76608833": "연결된 풀 리퀘스트를 먼저 엽니다. 없으면 3개 이상의 파일 또는 50줄 이상이 편집되었을 때 변경 사항을 엽니다.", "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "c5424f09d77138ff": "200,000 토큰이 넘는 유휴 Claude 스레드를 압축할 시점입니다. 돌아온 뒤, 프롬프트 캐시가 만료되기 직전, 또는 압축 안 함 중에서 선택합니다. 각 Claude 제공자에서 재정의할 수 있습니다.", @@ -11446,6 +11484,7 @@ "23f7dd84f1f777f0": "출력 토큰 문단 버퍼링 대기 턴 레거시", "28595b22d495356e": "변경 사항 공백 무시 편집 기본값", "b46730711c2d6089": "접힘 펼침 접기 펼치기 파일 풀 리퀘스트 PR 코드 탭", + "6fdf1b1784286ea6": "확인함 리뷰 다음 미확인 파일 이동 키보드 viewed review", "6a6b1c244a1a0476": "세로 분할 나란히 통합 인라인 보기", "7d0ab4cf50686d31": "자동 열기 변경 사항 풀 리퀘스트 PR 오른쪽 패널 에이전트 완료", "5256dd2ed3a24332": "명령 메뉴 달러 $ 슬래시 /", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..46423d2abb03f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5288,6 +5288,8 @@ "48d7d2bee4c40a5a": "Falha na captura de tela. Tente novamente.", "d48deeb7c5f630c2": "Resposta inesperada da dobra do Android.", "f32c20d2aab69630": "Falha no comando de dobrar ({status}).", + "1ed62d567b394717": "Adicionar comentário ({shortcut})", + "0f4e08f6bb804947": "Adicionar comentário", "c05ae9b20227f416": "Excluir comentário", "e8c281b1a85ac547": "Adicione um comentário…", "f2160b630793c7b4": "Comentar as linhas {rangeLabel}", @@ -5297,6 +5299,28 @@ "1601d7e39a52c48f": "Tentar carregar o diff novamente", "b7b137472adb6989": "Pré-visualização parcial do diff", "f0d79aa56f06663f": "Este arquivo é grande demais para ser mostrado por inteiro. As contagens incluem todas as alterações.", + "fc8c74e56f56d6aa": "Marcar como não visto ({shortcut})", + "6b16762624454603": "Marcar como não visto", + "c1ee14e8052af637": "Marcar como visto ({shortcut})", + "e1e45c361a6c893c": "Marcar como visto", + "7061d634f9053c0d": "Alterado {path}", + "e8897fabdb381131": "Visto {path}", + "9756a1dd860b0fff": "Houve push neste arquivo desde que você o marcou como visto.", + "849059a11e9baf7a": "Mostrar todos os arquivos", + "e2545556a6fd305d": "Mostrar um arquivo por vez", + "c5e67ae1effef813": "Mostrar todos os arquivos ({shortcut})", + "3161e88a920d29f8": "Mostrar um arquivo por vez ({shortcut})", + "b989b376adde129c": [ + "Todos (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "d4ccbc96f4d05950": "Alterado", + "6594b013f63d2a3a": "Visto", "07b9970b662ab70d": "Mostrar o código Mermaid", "5a422b7be35243f5": "Mostrar o diagrama renderizado", "c0628ad999cbbbf5": "Mostrar o código Markdown", @@ -6452,8 +6476,6 @@ "909a53aaeab5f1bf": "Não foi possível publicar a resposta", "fe77d063483acfab": "Não foi possível salvar o comentário", "c3fde30a048e5c47": "Não foi possível atualizar a discussão", - "6345153b5d556fa4": "Alterado", - "951472eed80ea27d": "Visto", "68fdae4308598c56": "Corrigir em uma thread", "a65107f54ff65902": "Carregando mais arquivos...", "e545fcdb83e2c36a": "Adicionar à revisão", @@ -6484,9 +6506,6 @@ "1239149344bb4b2b": "O diff é grande demais para exibir.", "3ab928741d208f41": "Carregando...", "3e272ae9c5b76744": "Carregar diff", - "d4ccbc96f4d05950": "Alterado", - "c12888742e7bd0ce": "Houve push neste arquivo desde que você o marcou como visto.", - "6594b013f63d2a3a": "Visto", "687f81dd084a5ab0": "Não foi possível carregar o restante deste diff.", "cf44cf4e3479ea7a": "Todos os commits", "d27b1db7f856ec3a": "Este host não mantém um registro compartilhado de quais arquivos você leu, então estas marcações são mantidas por este ambiente. Elas acompanham você entre os apps conectados a ele, mas a interface web do próprio host não as mostra.", @@ -8444,7 +8463,8 @@ "84a605b241ce65b7": "Remover grupo e as condições dele", "1d5b3500189fef41": "Use variáveis com !, &&, || e parênteses.", "a7384e7d2952afad": "Editor de mensagens", - "555805dcc65047bc": "Pré-visualização e diff", + "e5381928638adda1": "Pré-visualização", + "dfb5bf2368e336a1": "Diff", "319ee1816b17bd21": "Outros", "37f2a47d12cdfdf8": "Editor: ação oposta de enfileirar ou direcionar", "d9d54dde0ba27d96": "Editor: iniciar em segundo plano", @@ -8468,6 +8488,21 @@ "97c7de6aaab317a2": "Painel direito: fechar", "97b8f50a68ff3e02": "Pull request: copiar número", "a608714c5062154d": "Diff: alternar", + "42bd56eaf24cd5c5": "Diff: próximo arquivo", + "209821876545c056": "Diff: arquivo anterior", + "74ec1f25fe3198b7": "Diff: próximo arquivo não visto", + "790509b6a5dc2f28": "Diff: arquivo não visto anterior", + "4bda8f6a3646df83": "Diff: recolher ou expandir arquivo", + "55ada6d6542c8bbb": "Diff: marcar ou desmarcar arquivo como visto", + "d3a74a866bb98292": "Diff: alternar visualização de um só arquivo", + "375e9fb4adfc8203": "Diff: entrar no modo de linha", + "e40c4bb6a3d916a3": "Diff: próxima linha", + "2a1239fed9e89426": "Diff: linha anterior", + "ea7b090c1913762c": "Diff: expandir para baixo", + "913bb88e66ae6825": "Diff: expandir para cima", + "f908dede79dee496": "Diff: comentar", + "8cd1716a4948da8a": "Diff: iniciar seleção", + "6b54f2e44e813a00": "Diff: voltar", "c63b12ef6fc2d448": "Pré-visualização: alternar", "6ca1f18ba380f986": "Pré-visualização: atualizar", "a5b6c1936995ec20": "Pré-visualização: aumentar zoom", @@ -9730,6 +9765,7 @@ "8dc3e3036cfebeaa": "Contexto do editor de mensagens", "95be9d8739887c7f": "Estado padrão dos arquivos no diff", "04fb467bba7698e2": "Alterações de espaço em branco no diff", + "87fc1f32edf5f7ea": "Avançar automaticamente ao marcar como visto", "71d047b3f6ea9497": "Abrir os painéis de pull requests e alterações proativamente", "4b46043fd3700c17": "Mostrar skills no menu de barra", "2407d5d61e7f7206": "Editor de texto formatado", @@ -9813,6 +9849,8 @@ "aa2ead0db85b3fde": "Redefinir o estado padrão dos arquivos no diff para o padrão", "610ab21300968834": "Recolhido", "f300ec21e6391b6c": "Expandido", + "d0eb2f1d85767f3c": "Depois de marcar um arquivo como visto, vai para o próximo arquivo não visto.", + "c160336a3f88d439": "Redefinir o avanço automático ao marcar como visto para o padrão", "a0eb0e4f76608833": "Abre primeiro os pull requests vinculados. Caso contrário, abre Alterações para edições em pelo menos 3 arquivos ou 50 linhas.", "16bdc70b858c223f": "Redefinir os painéis proativos para o padrão", "c5424f09d77138ff": "Quando compactar uma thread do Claude ociosa com mais de 200.000 tokens: depois que você voltar, logo antes de o cache do prompt expirar ou nunca. Cada provedor Claude pode substituir isso.", @@ -11498,6 +11536,7 @@ "23f7dd84f1f777f0": "saída token parágrafo em buffer aguardar turno legado", "28595b22d495356e": "diff ignorar espaços edições padrão", "b46730711c2d6089": "recolhido expandido recolher expandir arquivos pull request pr aba código", + "6fdf1b1784286ea6": "visto revisão próximo não visto arquivo pular teclado", "6a6b1c244a1a0476": "empilhado dividido lado a lado unificado inline visualização", "7d0ab4cf50686d31": "proativo abrir automaticamente diff pull request pr painel direito agente conclusão", "5256dd2ed3a24332": "menu de comandos cifrão $ barra /", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..e206605a378c0 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5288,6 +5288,8 @@ "48d7d2bee4c40a5a": "Не удалось сделать скриншот. Повторите попытку.", "d48deeb7c5f630c2": "Неожиданный ответ складывания Android.", "f32c20d2aab69630": "Ошибка команды складывания ({status}).", + "1ed62d567b394717": "Добавить комментарий ({shortcut})", + "0f4e08f6bb804947": "Добавить комментарий", "c05ae9b20227f416": "Удалить комментарий", "e8c281b1a85ac547": "Добавьте комментарий…", "f2160b630793c7b4": "Комментарий к строкам {rangeLabel}", @@ -5297,6 +5299,28 @@ "1601d7e39a52c48f": "Повторить загрузку диффа", "b7b137472adb6989": "Частичный предпросмотр диффа", "f0d79aa56f06663f": "Файл слишком большой, чтобы показать его полностью. Счётчики учитывают все изменения.", + "fc8c74e56f56d6aa": "Отметить как непросмотренный ({shortcut})", + "6b16762624454603": "Отметить как непросмотренный", + "c1ee14e8052af637": "Отметить как просмотренный ({shortcut})", + "e1e45c361a6c893c": "Отметить как просмотренный", + "7061d634f9053c0d": "Изменён {path}", + "e8897fabdb381131": "Просмотрен {path}", + "9756a1dd860b0fff": "В этот файл пушили после того, как вы отметили его просмотренным.", + "849059a11e9baf7a": "Показать все файлы", + "e2545556a6fd305d": "Показывать по одному файлу", + "c5e67ae1effef813": "Показать все файлы ({shortcut})", + "3161e88a920d29f8": "Показывать по одному файлу ({shortcut})", + "b989b376adde129c": [ + "Все (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "d4ccbc96f4d05950": "Изменён", + "6594b013f63d2a3a": "Просмотрен", "07b9970b662ab70d": "Показать исходник Mermaid", "5a422b7be35243f5": "Показать диаграмму", "c0628ad999cbbbf5": "Показать исходник Markdown", @@ -6452,8 +6476,6 @@ "909a53aaeab5f1bf": "Не удалось опубликовать ответ", "fe77d063483acfab": "Не удалось сохранить комментарий", "c3fde30a048e5c47": "Не удалось обновить обсуждение", - "6345153b5d556fa4": "Изменён", - "951472eed80ea27d": "Просмотрен", "68fdae4308598c56": "Исправить в треде", "a65107f54ff65902": "Загрузка других файлов...", "e545fcdb83e2c36a": "Добавить в ревью", @@ -6484,9 +6506,6 @@ "1239149344bb4b2b": "Дифф слишком большой для отображения.", "3ab928741d208f41": "Загрузка...", "3e272ae9c5b76744": "Загрузить дифф", - "d4ccbc96f4d05950": "Изменён", - "c12888742e7bd0ce": "В этот файл пушили после того, как вы отметили его просмотренным.", - "6594b013f63d2a3a": "Просмотрен", "687f81dd084a5ab0": "Не удалось загрузить остальную часть диффа.", "cf44cf4e3479ea7a": "Все коммиты", "d27b1db7f856ec3a": "Этот хост не хранит общую запись о прочитанных файлах, поэтому отметки хранит это окружение. Они доступны во всех подключённых к нему приложениях, но веб-интерфейс хоста их не покажет.", @@ -8446,7 +8465,8 @@ "84a605b241ce65b7": "Удалить группу и её условия", "1d5b3500189fef41": "Используйте переменные с !, &&, || и скобками.", "a7384e7d2952afad": "Поле ввода", - "555805dcc65047bc": "Предпросмотр и дифф", + "e5381928638adda1": "Предпросмотр", + "dfb5bf2368e336a1": "Дифф", "319ee1816b17bd21": "Другое", "37f2a47d12cdfdf8": "Поле ввода: противоположное действие (очередь или корректировка)", "d9d54dde0ba27d96": "Поле ввода: запустить в фоне", @@ -8470,6 +8490,21 @@ "97c7de6aaab317a2": "Правая панель: закрыть", "97b8f50a68ff3e02": "Пул-реквест: скопировать номер", "a608714c5062154d": "Дифф: показать/скрыть", + "42bd56eaf24cd5c5": "Дифф: следующий файл", + "209821876545c056": "Дифф: предыдущий файл", + "74ec1f25fe3198b7": "Дифф: следующий непросмотренный файл", + "790509b6a5dc2f28": "Дифф: предыдущий непросмотренный файл", + "4bda8f6a3646df83": "Дифф: свернуть или развернуть файл", + "55ada6d6542c8bbb": "Дифф: отметить файл просмотренным или снять отметку", + "d3a74a866bb98292": "Дифф: показывать один файл или все", + "375e9fb4adfc8203": "Дифф: перейти в построчный режим", + "e40c4bb6a3d916a3": "Дифф: следующая строка", + "2a1239fed9e89426": "Дифф: предыдущая строка", + "ea7b090c1913762c": "Дифф: развернуть ниже", + "913bb88e66ae6825": "Дифф: развернуть выше", + "f908dede79dee496": "Дифф: комментировать", + "8cd1716a4948da8a": "Дифф: начать выделение", + "6b54f2e44e813a00": "Дифф: назад", "c63b12ef6fc2d448": "Предпросмотр: показать/скрыть", "6ca1f18ba380f986": "Предпросмотр: обновить", "a5b6c1936995ec20": "Предпросмотр: увеличить", @@ -9733,6 +9768,7 @@ "8dc3e3036cfebeaa": "Контекст поля ввода", "95be9d8739887c7f": "Состояние файлов диффа по умолчанию", "04fb467bba7698e2": "Изменения пробелов в диффе", + "87fc1f32edf5f7ea": "Переходить дальше после отметки просмотренным", "71d047b3f6ea9497": "Заранее открывать панели пул-реквестов и изменений", "4b46043fd3700c17": "Показывать навыки в меню /", "2407d5d61e7f7206": "Поле ввода с форматированием", @@ -9816,6 +9852,8 @@ "aa2ead0db85b3fde": "Сбросить состояние файлов диффа к значению по умолчанию", "610ab21300968834": "Свёрнуты", "f300ec21e6391b6c": "Развёрнуты", + "d0eb2f1d85767f3c": "После того как вы отметите файл просмотренным, открывается следующий непросмотренный файл.", + "c160336a3f88d439": "Сбросить переход после отметки просмотренным к значению по умолчанию", "a0eb0e4f76608833": "Сначала открывать привязанные пул-реквесты. Иначе открывать «Изменения» при правках не менее 3 файлов или 50 строк.", "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "c5424f09d77138ff": "Когда сжимать неактивный тред Claude больше 200 000 токенов: после вашего возвращения, перед самым истечением его кеша промптов или никогда. Каждый провайдер Claude может это переопределить.", @@ -11499,6 +11537,7 @@ "23f7dd84f1f777f0": "вывод токен абзац буферизация ждать ход устаревший", "28595b22d495356e": "дифф игнорировать пробелы правки по умолчанию", "b46730711c2d6089": "свёрнуто развёрнуто свернуть развернуть файлы пул-реквест pr код вкладка", + "6fdf1b1784286ea6": "просмотрен ревью следующий непросмотренный файл переход клавиатура", "6a6b1c244a1a0476": "стопкой раздельно рядом единый встроенный вид", "7d0ab4cf50686d31": "заблаговременно автоматически открывать дифф пул-реквест pr правая панель агент завершение", "5256dd2ed3a24332": "меню команд доллар $ слеш /", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..943fbc3c185d7 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5289,6 +5289,8 @@ "48d7d2bee4c40a5a": "Det gick inte att ta en skärmbild. Försök igen.", "d48deeb7c5f630c2": "Oväntat vikningssvar från Android.", "f32c20d2aab69630": "Vikkommandot misslyckades ({status}).", + "1ed62d567b394717": "Lägg till kommentar ({shortcut})", + "0f4e08f6bb804947": "Lägg till kommentar", "c05ae9b20227f416": "Ta bort kommentar", "e8c281b1a85ac547": "Lägg till en kommentar…", "f2160b630793c7b4": "Kommentera raderna {rangeLabel}", @@ -5298,6 +5300,27 @@ "1601d7e39a52c48f": "Försök läsa in diffen igen", "b7b137472adb6989": "Partiell diffförhandsvisning", "f0d79aa56f06663f": "Den här filen är för stor för att visas i sin helhet. Antalen inkluderar alla ändringar.", + "fc8c74e56f56d6aa": "Markera som inte visad ({shortcut})", + "6b16762624454603": "Markera som inte visad", + "c1ee14e8052af637": "Markera som visad ({shortcut})", + "e1e45c361a6c893c": "Markera som visad", + "7061d634f9053c0d": "Ändrad {path}", + "e8897fabdb381131": "Visad {path}", + "9756a1dd860b0fff": "Den här filen har fått nya pushar sedan du markerade den som visad.", + "849059a11e9baf7a": "Visa alla filer", + "e2545556a6fd305d": "Visa en fil i taget", + "c5e67ae1effef813": "Visa alla filer ({shortcut})", + "3161e88a920d29f8": "Visa en fil i taget ({shortcut})", + "b989b376adde129c": [ + "Alla ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "d4ccbc96f4d05950": "Ändrad", + "6594b013f63d2a3a": "Visad", "07b9970b662ab70d": "Visa Mermaid-källa", "5a422b7be35243f5": "Visa renderat diagram", "c0628ad999cbbbf5": "Visa Markdown-källa", @@ -6458,8 +6481,6 @@ "909a53aaeab5f1bf": "Svaret kunde inte publiceras", "fe77d063483acfab": "Kommentaren kunde inte sparas", "c3fde30a048e5c47": "Konversationen kunde inte uppdateras", - "6345153b5d556fa4": "Ändrad", - "951472eed80ea27d": "Visad", "68fdae4308598c56": "Åtgärda i en tråd", "a65107f54ff65902": "Läser in fler filer...", "e545fcdb83e2c36a": "Lägg till i granskning", @@ -6490,9 +6511,6 @@ "1239149344bb4b2b": "Diffen är för stor för att visas.", "3ab928741d208f41": "Läser in...", "3e272ae9c5b76744": "Läs in diff", - "d4ccbc96f4d05950": "Ändrad", - "c12888742e7bd0ce": "Den här filen har fått nya pushar sedan du markerade den som visad.", - "6594b013f63d2a3a": "Visad", "687f81dd084a5ab0": "Resten av den här diffen kunde inte läsas in.", "cf44cf4e3479ea7a": "Alla commits", "d27b1db7f856ec3a": "Den här värden sparar ingen delad uppgift om vilka filer du har läst, så de här bockarna sparas av den här miljön. De följer med dig mellan apparna som är anslutna till den, men värdens eget webbgränssnitt visar dem inte.", @@ -8452,7 +8470,8 @@ "84a605b241ce65b7": "Ta bort gruppen och dess villkor", "1d5b3500189fef41": "Använd variabler med !, &&, || och parenteser.", "a7384e7d2952afad": "Inmatningsfält", - "555805dcc65047bc": "Förhandsvisning och diff", + "e5381928638adda1": "Förhandsvisning", + "dfb5bf2368e336a1": "Diff", "319ee1816b17bd21": "Övrigt", "37f2a47d12cdfdf8": "Inmatningsfält: motsatt köa- eller styr om-åtgärd", "d9d54dde0ba27d96": "Inmatningsfält: starta i bakgrunden", @@ -8476,6 +8495,21 @@ "97c7de6aaab317a2": "Högerpanel: stäng", "97b8f50a68ff3e02": "Pull request: kopiera nummer", "a608714c5062154d": "Diff: växla", + "42bd56eaf24cd5c5": "Diff: nästa fil", + "209821876545c056": "Diff: föregående fil", + "74ec1f25fe3198b7": "Diff: nästa ej visade fil", + "790509b6a5dc2f28": "Diff: föregående ej visade fil", + "4bda8f6a3646df83": "Diff: fäll ihop eller ut fil", + "55ada6d6542c8bbb": "Diff: markera fil som visad eller inte visad", + "d3a74a866bb98292": "Diff: växla enfilsvy", + "375e9fb4adfc8203": "Diff: starta radläge", + "e40c4bb6a3d916a3": "Diff: nästa rad", + "2a1239fed9e89426": "Diff: föregående rad", + "ea7b090c1913762c": "Diff: expandera nedåt", + "913bb88e66ae6825": "Diff: expandera uppåt", + "f908dede79dee496": "Diff: kommentera", + "8cd1716a4948da8a": "Diff: starta markering", + "6b54f2e44e813a00": "Diff: tillbaka", "c63b12ef6fc2d448": "Förhandsvisning: växla", "6ca1f18ba380f986": "Förhandsvisning: uppdatera", "a5b6c1936995ec20": "Förhandsvisning: zooma in", @@ -9739,6 +9773,7 @@ "8dc3e3036cfebeaa": "Kontext i inmatningsfältet", "95be9d8739887c7f": "Standardläge för filer i diffar", "04fb467bba7698e2": "Blankstegsändringar i diffar", + "87fc1f32edf5f7ea": "Gå automatiskt vidare efter markering som visad", "71d047b3f6ea9497": "Öppna panelerna för pull requests och ändringar proaktivt", "4b46043fd3700c17": "Visa färdigheter i snedstrecksmenyn", "2407d5d61e7f7206": "Inmatningsfält med formaterad text", @@ -9822,6 +9857,8 @@ "aa2ead0db85b3fde": "Återställ standardläge för diff-filer till standard", "610ab21300968834": "Ihopfällda", "f300ec21e6391b6c": "Utfällda", + "d0eb2f1d85767f3c": "När du markerar en fil som visad går du vidare till nästa ej visade fil.", + "c160336a3f88d439": "Återställ automatisk förflyttning efter markering som visad till standard", "a0eb0e4f76608833": "Öppna länkade pull requests först. Annars öppnas Ändringar för redigeringar av minst 3 filer eller 50 rader.", "16bdc70b858c223f": "Återställ proaktiva paneler till standard", "c5424f09d77138ff": "När en inaktiv Claude-tråd på över 200 000 token ska komprimeras: när du kommer tillbaka, precis innan dess promptcache går ut, eller aldrig. Varje Claude-leverantör kan åsidosätta detta.", @@ -11507,6 +11544,7 @@ "23f7dd84f1f777f0": "utdata token stycke buffrad vänta omgång äldre", "28595b22d495356e": "diff ignorera blanksteg ändringar standard", "b46730711c2d6089": "ihopfälld expanderad fäll ihop expandera filer pull request pr kodflik", + "6fdf1b1784286ea6": "visad granskning nästa ej visad fil hoppa tangentbord", "6a6b1c244a1a0476": "staplad delad sida vid sida enhetlig inline vy", "7d0ab4cf50686d31": "proaktiv öppna automatiskt diff pull request pr högerpanel agent slutförd", "5256dd2ed3a24332": "kommandomeny dollar $ snedstreck /", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..e7cadd7a4bcde 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5295,6 +5295,8 @@ "48d7d2bee4c40a5a": "截屏失败,请重试。", "d48deeb7c5f630c2": "意外的 Android 折叠响应。", "f32c20d2aab69630": "折叠命令失败({status})。", + "1ed62d567b394717": "添加批注 ({shortcut})", + "0f4e08f6bb804947": "添加批注", "c05ae9b20227f416": "删除评论", "e8c281b1a85ac547": "添加评论…", "f2160b630793c7b4": "评论第 {rangeLabel} 行", @@ -5304,6 +5306,28 @@ "1601d7e39a52c48f": "重试加载差异", "b7b137472adb6989": "部分差异预览", "f0d79aa56f06663f": "此文件过大,无法完整显示。统计包含全部改动。", + "fc8c74e56f56d6aa": "标记为未查看 ({shortcut})", + "6b16762624454603": "标记为未查看", + "c1ee14e8052af637": "标记为已查看 ({shortcut})", + "e1e45c361a6c893c": "标记为已查看", + "7061d634f9053c0d": "有更新 {path}", + "e8897fabdb381131": "已查看 {path}", + "9756a1dd860b0fff": "你标记已查看后,此文件有新的推送。", + "849059a11e9baf7a": "显示全部文件", + "e2545556a6fd305d": "一次显示一个文件", + "c5e67ae1effef813": "显示全部文件 ({shortcut})", + "3161e88a920d29f8": "一次显示一个文件 ({shortcut})", + "b989b376adde129c": [ + "全部 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 个" + ], + "d4ccbc96f4d05950": "有更新", + "6594b013f63d2a3a": "已查看", "07b9970b662ab70d": "显示 Mermaid 源码", "5a422b7be35243f5": "显示渲染后的图表", "c0628ad999cbbbf5": "显示 Markdown 源码", @@ -6464,8 +6488,6 @@ "909a53aaeab5f1bf": "无法发表回复", "fe77d063483acfab": "无法保存评论", "c3fde30a048e5c47": "无法更新对话", - "6345153b5d556fa4": "有更新", - "951472eed80ea27d": "已查看", "68fdae4308598c56": "在会话中修复", "a65107f54ff65902": "正在加载更多文件…", "e545fcdb83e2c36a": "添加到审查", @@ -6496,9 +6518,6 @@ "1239149344bb4b2b": "差异过大,无法显示。", "3ab928741d208f41": "加载中…", "3e272ae9c5b76744": "加载差异", - "d4ccbc96f4d05950": "有更新", - "c12888742e7bd0ce": "你标记已查看后,此文件有新的推送。", - "6594b013f63d2a3a": "已查看", "687f81dd084a5ab0": "此差异的剩余部分无法加载。", "cf44cf4e3479ea7a": "全部提交", "d27b1db7f856ec3a": "此托管平台不保存你已阅读哪些文件的共享记录,因此这些勾选由当前环境保存。它们会在此环境关联的各应用之间同步,但托管平台自带的网页界面不会显示。", @@ -8462,7 +8481,8 @@ "84a605b241ce65b7": "移除条件组及其条件", "1d5b3500189fef41": "请使用变量、!、&&、|| 和括号编写表达式。", "a7384e7d2952afad": "输入框", - "555805dcc65047bc": "预览与差异", + "e5381928638adda1": "预览", + "dfb5bf2368e336a1": "差异", "319ee1816b17bd21": "其他", "37f2a47d12cdfdf8": "输入框:使用相反的排队或引导操作", "d9d54dde0ba27d96": "输入框:在后台启动", @@ -8486,6 +8506,21 @@ "97c7de6aaab317a2": "右侧面板:关闭", "97b8f50a68ff3e02": "PR:复制编号", "a608714c5062154d": "差异:切换显示", + "42bd56eaf24cd5c5": "差异:下一个文件", + "209821876545c056": "差异:上一个文件", + "74ec1f25fe3198b7": "差异:下一个未查看文件", + "790509b6a5dc2f28": "差异:上一个未查看文件", + "4bda8f6a3646df83": "差异:折叠或展开文件", + "55ada6d6542c8bbb": "差异:切换文件已查看状态", + "d3a74a866bb98292": "差异:切换单文件视图", + "375e9fb4adfc8203": "差异:进入行模式", + "e40c4bb6a3d916a3": "差异:下一行", + "2a1239fed9e89426": "差异:上一行", + "ea7b090c1913762c": "差异:向下展开", + "913bb88e66ae6825": "差异:向上展开", + "f908dede79dee496": "差异:批注", + "8cd1716a4948da8a": "差异:开始选择", + "6b54f2e44e813a00": "差异:返回", "c63b12ef6fc2d448": "预览:切换显示", "6ca1f18ba380f986": "预览:刷新", "a5b6c1936995ec20": "预览:放大", @@ -9746,6 +9781,7 @@ "8dc3e3036cfebeaa": "输入框上下文", "95be9d8739887c7f": "差异文件默认状态", "04fb467bba7698e2": "差异空白字符改动", + "87fc1f32edf5f7ea": "标记已查看后自动前进", "71d047b3f6ea9497": "自动打开 PR 与改动面板", "4b46043fd3700c17": "在斜杠菜单中显示技能", "2407d5d61e7f7206": "富文本输入框", @@ -9829,6 +9865,8 @@ "aa2ead0db85b3fde": "重置默认差异文件状态为默认值", "610ab21300968834": "折叠", "f300ec21e6391b6c": "展开", + "d0eb2f1d85767f3c": "将文件标记为已查看后,跳到下一个未查看文件。", + "c160336a3f88d439": "重置标记已查看后自动前进为默认值", "a0eb0e4f76608833": "优先打开关联的 pull request;否则在改动至少 3 个文件或 50 行时打开“改动”面板。", "16bdc70b858c223f": "重置主动面板为默认值", "c5424f09d77138ff": "空闲且超过 200,000 token 的 Claude 会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。每个 Claude 提供方都可以单独覆盖此设置。", @@ -11523,6 +11561,7 @@ "23f7dd84f1f777f0": "输出 token 段落 缓冲 等待 轮次 旧版", "28595b22d495356e": "差异 忽略 空格 编辑 默认", "b46730711c2d6089": "折叠 展开 收起 文件 PR pr 代码 标签页", + "6fdf1b1784286ea6": "已查看 审阅 下一个 未查看 文件 跳转 键盘 viewed review", "6a6b1c244a1a0476": "堆叠 拆分 并排 统一 内联 视图", "7d0ab4cf50686d31": "主动 自动打开 差异 PR pr 右侧面板 智能体 完成", "5256dd2ed3a24332": "命令 菜单 美元 $ 斜杠 /", diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 3b596f838fa0d..2c8e5b149e788 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -984,3 +984,35 @@ describe("Usage shortcuts", () => { ); }); }); + +describe("Diff review shortcuts", () => { + it.each([ + [event({ key: "j" }), { diffFocus: true }, "diff.nextFile"], + [event({ key: "j" }), { diffFocus: true, diffLineMode: true }, "diff.nextLine"], + [event({ key: "j" }), {}, null], + [ + event({ key: "J", shiftKey: true }), + { diffFocus: true, diffLineMode: true }, + "diff.expandBelow", + ], + [ + event({ key: "V", shiftKey: true }), + { diffFocus: true, diffLineMode: true }, + "diff.startSelection", + ], + [event({ key: "v" }), { diffFocus: true, diffLineMode: true }, "diff.toggleFileViewed"], + [event({ key: "c" }), { diffFocus: true, diffLineMode: true }, "diff.comment"], + [event({ key: " ", code: "Space" }), { diffFocus: true }, null], + [event({ key: "Enter" }), { diffFocus: true }, "diff.toggleFileCollapsed"], + [event({ key: "Escape" }), { diffFocus: true, diffLineMode: true }, "diff.back"], + [event({ key: "Escape" }), { diffFocus: true }, null], + ] as const)("resolves %o with %o to %s", (shortcut, context, command) => { + assert.strictEqual( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context, + }), + command, + ); + }); +}); diff --git a/apps/web/src/lib/diffFocus.ts b/apps/web/src/lib/diffFocus.ts new file mode 100644 index 0000000000000..fba3b9ce12ea8 --- /dev/null +++ b/apps/web/src/lib/diffFocus.ts @@ -0,0 +1,14 @@ +import { isEditableFocused } from "./editableFocus"; + +/** Focus anywhere in the panel showing the diff, its header and tabs included, outside text fields. */ +export function diffPanelHasFocus(panel: Element): boolean { + const activeElement = document.activeElement; + if (activeElement === null || isEditableFocused()) return false; + const area = panel.closest("[data-workspace-area]") ?? panel; + // Hidden tabs stay mounted, so a panel's area can hold diffs that are not on screen. + return area.contains(activeElement) && panel.checkVisibility({ visibilityProperty: true }); +} + +export function isDiffFocused(): boolean { + return Array.from(document.querySelectorAll("[data-diff-panel]")).some(diffPanelHasFocus); +} diff --git a/apps/web/src/shortcuts/dispatcher.ts b/apps/web/src/shortcuts/dispatcher.ts index 9e361e825db7f..9a37897f11183 100644 --- a/apps/web/src/shortcuts/dispatcher.ts +++ b/apps/web/src/shortcuts/dispatcher.ts @@ -1,6 +1,7 @@ import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { resolveShortcutCommand, type ShortcutMatchContext } from "../keybindings"; +import { isDiffFocused } from "../lib/diffFocus"; import { isEditableFocused } from "../lib/editableFocus"; import { isPreviewFocused } from "../lib/previewFocus"; import { isTerminalFocused } from "../lib/terminalFocus"; @@ -48,6 +49,7 @@ function readFocusContext(event: KeyboardEvent): Partial { return { terminalFocus: isTerminalFocused(), previewFocus: isPreviewFocused(), + diffFocus: isDiffFocused(), editableFocus: isEditableFocused(event.target), modelPickerOpen: isModelPickerOpen(), }; diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 308d7d934c1f8..1b56416afff8c 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -72,6 +72,44 @@ match in a folded file opens it. Escape closes the search. This shortcut is not configurable. A very large uncommitted diff loads its files as you scroll, and find only searches the files loaded so far. +## Review a diff from the keyboard + +Click into the Diff panel or a pull request's Code tab to review it without the +mouse. The keys also work while a button or tab elsewhere in that panel has focus, +but not while you type in a text field. Both start on files. Press `i` to move into a file's lines, and Escape to step back out. + +On files: + +- `j` and `k` move to the next or previous file. +- `n` and `Shift+n` jump to the next or previous file you have not viewed. +- After you scroll away from the current file, these keys start from the file on screen. +- `v` marks the file viewed, which also folds it. Press it again to unmark. +- Enter folds or unfolds the file. +- `f` shows only the current file. `j`, `k`, and `n` switch which file it shows. + Folding that file, or pressing `f` again, shows every file. + +On lines: + +- `j` and `k` move one line. `k` on the first line returns to the file, and `j` + on the last line moves on to the next file. +- `Shift+j` and `Shift+k` show more of the unchanged lines below or above. +- `c` comments on the line. In a pull request, that starts a review comment. + After you send or cancel the comment, you are back on the line. +- `Shift+v` starts a selection. `j` and `k` extend it, and `c` comments on + the selected lines. +- `v` marks the file viewed and returns to files. + +In the Diff panel, viewed marks belong to this device and thread, and a file that +changes after you view it shows as not viewed again. In a pull request, `v` sets +the same marks as the Viewed checkbox; see +[Mark files as viewed](./source-control.md#mark-files-as-viewed). To jump to the next unviewed file after each +mark, turn on **Settings → Diffs → Auto-advance after marking viewed**. Once every +file is viewed, the count above the diff reads, for example, **All 5 viewed**. + +Change any of these keys in **Settings → Keybindings** under the **Diff** +commands. Showing more unchanged lines needs the full files, so it is not +available for turn and tool call diffs. + ## iPad With a hardware keyboard, use `Cmd+1` through `Cmd+9` to open the first nine @@ -127,10 +165,12 @@ Join modifiers and a key with `+`, such as `mod+shift+d` or `ctrl+l`. ## When conditions Available context keys are `terminalFocus`, `terminalOpen`, `previewFocus`, -`previewOpen`, `rightPanelOpen`, `modelPickerOpen`, `usagePageOpen`, `composerFocus`, -`draftThreadRoute`, `turnRunning`, `editableFocus`, `isWeb`, and `isDesktop`. -In a thread, `rightPanelOpen` is true while its right panel is open; the default -`mod+t` uses it to open the panel's new-tab menu. +`previewOpen`, `rightPanelOpen`, `diffFocus`, `diffLineMode`, `modelPickerOpen`, +`usagePageOpen`, `composerFocus`, `draftThreadRoute`, `turnRunning`, `editableFocus`, +`isWeb`, and `isDesktop`. In a thread, `rightPanelOpen` is true while its right panel is open; +the default `mod+t` uses it to open the panel's new-tab menu. +`diffFocus` is true while the Diff panel has the keyboard and no text field in it does. +`diffLineMode` is true while you are on a diff's lines or a selection. `draftThreadRoute` is true on a draft thread, including a restored draft, until it is first sent. `editableFocus` is true while a text field, the composer, or another editor has the keyboard. `isWeb` is true in a browser tab. `isDesktop` is true in the diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..f7574f4099800 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -74,6 +74,21 @@ export const STATIC_KEYBINDING_COMMANDS = [ "view.reopenClosed", "pullRequest.copyNumber", "diff.toggle", + "diff.nextFile", + "diff.previousFile", + "diff.nextUnviewedFile", + "diff.previousUnviewedFile", + "diff.toggleFileCollapsed", + "diff.toggleFileViewed", + "diff.toggleSingleFile", + "diff.enterLineMode", + "diff.nextLine", + "diff.previousLine", + "diff.expandBelow", + "diff.expandAbove", + "diff.comment", + "diff.startSelection", + "diff.back", "preview.toggle", "preview.refresh", "preview.focusUrl", diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 678f58294c66a..7adb5681a5827 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -472,6 +472,7 @@ export const ClientSettingsSchema = Schema.Struct({ confirmTerminalClose: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + diffAutoAdvanceOnViewed: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), diffFilesCollapsed: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), diffLayout: DiffLayout.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_DIFF_LAYOUT))), @@ -2073,6 +2074,7 @@ export const ClientSettingsPatch = Schema.Struct({ confirmTerminalClose: Schema.optionalKey(Schema.Boolean), confirmThreadDelete: Schema.optionalKey(Schema.Boolean), confirmThreadUnpin: Schema.optionalKey(Schema.Boolean), + diffAutoAdvanceOnViewed: Schema.optionalKey(Schema.Boolean), diffFilesCollapsed: Schema.optionalKey(Schema.Boolean), diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean), diffLayout: Schema.optionalKey(DiffLayout), diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 9a67264d8bd1f..d37d2cc424510 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -75,6 +75,21 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+w", command: "rightPanel.close", when: "!terminalFocus" }, { key: "mod+shift+t", command: "view.reopenClosed" }, { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" }, + { key: "j", command: "diff.nextFile", when: "diffFocus && !diffLineMode" }, + { key: "k", command: "diff.previousFile", when: "diffFocus && !diffLineMode" }, + { key: "n", command: "diff.nextUnviewedFile", when: "diffFocus && !diffLineMode" }, + { key: "shift+n", command: "diff.previousUnviewedFile", when: "diffFocus && !diffLineMode" }, + { key: "enter", command: "diff.toggleFileCollapsed", when: "diffFocus && !diffLineMode" }, + { key: "v", command: "diff.toggleFileViewed", when: "diffFocus" }, + { key: "f", command: "diff.toggleSingleFile", when: "diffFocus && !diffLineMode" }, + { key: "i", command: "diff.enterLineMode", when: "diffFocus && !diffLineMode" }, + { key: "j", command: "diff.nextLine", when: "diffFocus && diffLineMode" }, + { key: "k", command: "diff.previousLine", when: "diffFocus && diffLineMode" }, + { key: "shift+j", command: "diff.expandBelow", when: "diffFocus && diffLineMode" }, + { key: "shift+k", command: "diff.expandAbove", when: "diffFocus && diffLineMode" }, + { key: "c", command: "diff.comment", when: "diffFocus && diffLineMode" }, + { key: "shift+v", command: "diff.startSelection", when: "diffFocus && diffLineMode" }, + { key: "escape", command: "diff.back", when: "diffFocus && diffLineMode" }, { key: "mod+shift+j", command: "preview.toggle" }, { key: "mod+r", command: "preview.refresh", when: "previewFocus" }, { key: "mod+l", command: "preview.focusUrl", when: "previewFocus" }, diff --git a/patches/@pierre__diffs@1.7.0-beta.4.patch b/patches/@pierre__diffs@1.7.0-beta.4.patch index de01e159e079c..a4b8ea97bcf19 100644 --- a/patches/@pierre__diffs@1.7.0-beta.4.patch +++ b/patches/@pierre__diffs@1.7.0-beta.4.patch @@ -1,3 +1,31 @@ +diff --git a/dist/components/VirtualizedFileDiff.d.ts b/dist/components/VirtualizedFileDiff.d.ts +index 17e73dafdbeb697929c389e9583f98a6f296fbd5..a0ee3365b4f9ec10283318c00a09cf04520b8bab 100644 +--- a/dist/components/VirtualizedFileDiff.d.ts ++++ b/dist/components/VirtualizedFileDiff.d.ts +@@ -68,6 +68,8 @@ declare class VirtualizedFileDiff ex + protected handleFilesLoaded(expectedDiff: FileDiffMetadata, files: LoadedPartialDiffContents): Promise; + protected loadFilesIfNecessary(): void; + isLineInCollapsedContext(lineNumber: number, side?: SelectionSide, expandedHunks?: ExpandedHunksMap): boolean; ++ /** T3 patch: the expansions the next render draws, so keyboard review can walk the same rows. */ ++ getExpandedHunks(): ExpandedHunksMap; + private invalidateEditSessionLayout; + protected escalateEditSessionRender(cause: 'change' | 'exit'): void; + protected shouldSelfHealEditSession(): boolean; +diff --git a/dist/components/VirtualizedFileDiff.js b/dist/components/VirtualizedFileDiff.js +index 2a22f35cec93a35f71d2187999cc3f18e4502c4e..8cb7340048ffda56ae0c06867d41061654e5fa19 100644 +--- a/dist/components/VirtualizedFileDiff.js ++++ b/dist/components/VirtualizedFileDiff.js +@@ -560,6 +560,10 @@ var VirtualizedFileDiff = class extends FileDiff { + isLineInCollapsedContext(lineNumber, side = "additions", expandedHunks = this.pendingExpandedHunks ?? this.hunksRenderer.getExpandedHunksMap()) { + return super.isLineInCollapsedContext(lineNumber, side, expandedHunks); + } ++ /** T3 patch: the expansions the next render draws, so keyboard review can walk the same rows. */ ++ getExpandedHunks() { ++ return this.pendingExpandedHunks ?? this.hunksRenderer.getExpandedHunksMap(); ++ } + invalidateEditSessionLayout() { + this.getSimpleVirtualizer()?.markDOMDirty(); + this.invalidateLayout({ diff --git a/dist/editor/editor.js b/dist/editor/editor.js index b4c280390b52434f63fbe7916d81b150d9006fb4..cb7fb89a22c8adac9ea951b8767b5fd446347746 100644 --- a/dist/editor/editor.js @@ -148,10 +176,10 @@ index 48568bd..f27123f 100644 return stripGitPrefix && (name.startsWith("a/") || name.startsWith("b/")) ? name.slice(2) : name; } diff --git a/package.json b/package.json -index d1fa4d5d79ba70b6cd990b0ac9df5206fe55b58d..8762624a075174f5d9f35224cf091596d951a1a7 100644 +index d1fa4d5d79ba70b6cd990b0ac9df5206fe55b58d..0835b01213ec34ab1a943fe4d6c18a505f8038d6 100644 --- a/package.json +++ b/package.json -@@ -60,6 +60,18 @@ +@@ -60,6 +60,22 @@ "./worker/worker-portable.js": { "types": "./dist/worker/worker-portable.d.ts", "import": "./dist/worker/worker-portable.js" @@ -167,6 +195,10 @@ index d1fa4d5d79ba70b6cd990b0ac9df5206fe55b58d..8762624a075174f5d9f35224cf091596 + "./utils/parsePatchFiles": { + "types": "./dist/utils/parsePatchFiles.d.ts", + "import": "./dist/utils/parsePatchFiles.js" ++ }, ++ "./utils/iterateOverDiff": { ++ "types": "./dist/utils/iterateOverDiff.d.ts", ++ "import": "./dist/utils/iterateOverDiff.js" } }, "publishConfig": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e003246a26e8c..b8ee99344e51b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -371,7 +371,7 @@ patchedDependencies: '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 - '@pierre/diffs@1.7.0-beta.4': b24b206d14c79de95be10322b96490b82e41cc13c8a02c7378aaf8e03623431b + '@pierre/diffs@1.7.0-beta.4': f6d54b9cfc1b5e9ce0e062f6632e3fdd5b65419ba21404e5db9fe2df3cb39fde '@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d '@react-navigation/native-stack@7.21.0': 990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42 @@ -581,7 +581,7 @@ importers: version: 0.3.0 '@pierre/diffs': specifier: 1.7.0-beta.4 - version: 1.7.0-beta.4(patch_hash=b24b206d14c79de95be10322b96490b82e41cc13c8a02c7378aaf8e03623431b)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + version: 1.7.0-beta.4(patch_hash=f6d54b9cfc1b5e9ce0e062f6632e3fdd5b65419ba21404e5db9fe2df3cb39fde)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@pierre/highlights': specifier: 'catalog:' version: 0.5.0 @@ -1105,7 +1105,7 @@ importers: version: 1.8.0 '@pierre/diffs': specifier: 1.7.0-beta.4 - version: 1.7.0-beta.4(patch_hash=b24b206d14c79de95be10322b96490b82e41cc13c8a02c7378aaf8e03623431b)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + version: 1.7.0-beta.4(patch_hash=f6d54b9cfc1b5e9ce0e062f6632e3fdd5b65419ba21404e5db9fe2df3cb39fde)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -1521,7 +1521,7 @@ importers: dependencies: '@pierre/diffs': specifier: 1.7.0-beta.4 - version: 1.7.0-beta.4(patch_hash=b24b206d14c79de95be10322b96490b82e41cc13c8a02c7378aaf8e03623431b)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + version: 1.7.0-beta.4(patch_hash=f6d54b9cfc1b5e9ce0e062f6632e3fdd5b65419ba21404e5db9fe2df3cb39fde)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -16497,7 +16497,7 @@ snapshots: tslib: 2.8.1 webcrypto-core: 1.9.2 - '@pierre/diffs@1.7.0-beta.4(patch_hash=b24b206d14c79de95be10322b96490b82e41cc13c8a02c7378aaf8e03623431b)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@pierre/diffs@1.7.0-beta.4(patch_hash=f6d54b9cfc1b5e9ce0e062f6632e3fdd5b65419ba21404e5db9fe2df3cb39fde)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@pierre/highlights': 0.5.1 '@pierre/patches': 0.0.1