fix(forge): expand long unchanged-line gaps 20 lines at a time

A gap over 20 lines now offers a step down from the hunk above it and a
step up from the hunk below it, as GitHub's diff does, instead of drawing
every hidden line on one click. Gaps of at most 20 lines still expand at
once, and the first click on the unknown lines after the last hunk reads
the file and shows their first 20.
This commit is contained in:
LegGasai committed 2026-11-13 17:50:18 +08:00
1 parent f465541b32
commit 7ef8bed5f5
11 files changed
+323 -56

No files matched your search

@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
en: 240a0267069304b5
zh: 1e28533a1706a37d
en: 705f7f143fc7d6fb
zh: e757a4bf6b0ebce1
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
en: 8a32164b43695f96
zh: c5659ca104118d3b
@@ -38,7 +38,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
- **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll.
- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. When sign-in is missing, a banner shows the sign-in command the provider names, such as `gh auth login --hostname github.com`, with a button that copies it.
- **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent.
- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per hLine truncated
- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh iLine truncated
- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits.
- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none.
@@ -38,7 +38,7 @@ kind: "package-reference"
- **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。
- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`),并提供复制按钮。
- **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。
- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果Line truncated
- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxLine truncated
- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。
- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。
@@ -734,8 +734,9 @@
/* Collapsed unchanged lines; the row expands them. */
/* Collapsed unchanged lines, a collapsed large file, and a file whose lines cannot be drawn share one strip;
only the first two open on a click. */
only the first two open on a click. Unchanged lines over one expansion step name their count beside step buttons. */
.gap,
.gapSteps,
.fileNote {
display: flex;
align-items: center;
@@ -769,6 +770,41 @@
cursor: progress;
}
.gapSteps {
gap: 2px;
padding-inline-start: 7px;
}
.gapSteps > span {
margin-inline-start: 4px;
}
.gapStep {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 22px;
height: 20px;
padding: 0;
border: 0;
border-radius: var(--dsw-radius-sm);
background: transparent;
color: var(--dsw-alias-label-secondary);
cursor: pointer;
}
@media (hover: hover) {
.gapStep:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-primary);
}
}
.gapStep:disabled {
cursor: progress;
}
/* The local changes card of the panel: its toggle and refs, the view link and create action, then its files. */
.local {
min-width: 0;
@@ -902,7 +938,8 @@
.fileToggle:focus-visible,
.localFile:focus-visible,
.select:focus-visible,
.gap:focus-visible {
.gap:focus-visible,
.gapStep:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: -2px;
}
@@ -53,7 +53,7 @@ import { SectionReach } from './section-reach.ts'
import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx'
import { changedFileTree, filesInTreeOrder } from './file-tree.ts'
import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx'
import { drawnLines, matchesHunks, textLines } from './diff-rows.ts'
import { drawnLines, matchesHunks, revealGap, textLines, type GapExpansion, type GapReveal } from './diff-rows.ts'
import { ChangeRequestGlyph } from './glyphs.tsx'
import type { ForgePanelKey, NS } from './locales.ts'
import { useForgeCopy } from './forge-copy.ts'
@@ -200,7 +200,7 @@ interface WriteRefusal {
interface Expansion {
readonly source: string | Extract<ChangesData, { kind: 'local' }> | null
readonly texts: Readonly<Record<string, readonly string[] | 'loading'>>
readonly open: Readonly<Record<string, ReadonlySet<number>>>
readonly open: Readonly<Record<string, ReadonlyMap<number, GapReveal>>>
}
/** Files whose hunks draw more lines show the large-file notice until revealed. */
@@ -209,7 +209,7 @@ const LARGE_FILE_LINES = 1000
/** Lines the files above may change before a file starts collapsed. */
const OPEN_LINES = 5000
const NO_GAPS: ReadonlySet<number> = new Set()
const NO_GAPS: ReadonlyMap<number, GapReveal> = new Map()
const NO_FOLDS: ReadonlyMap<string, { readonly hunks: ReadonlySet<number>; readonly lens: string }> = new Map()
@@ -876,9 +876,9 @@ export function ChangesTab({
return change(previous.source === expansionSource ? previous : { source: expansionSource, texts: {}, open: {} })
})
}
const expand = (owner: ChangesData, file: ForgeDiffFile, index: number): void => {
const expand = (owner: ChangesData, file: ForgeDiffFile, index: number, expansion: GapExpansion): void => {
const path = file.path
update(value => ({ ...value, open: { ...value.open, [path]: new Set([...value.open[path] ?? [], index]) } }))
update(value => ({ ...value, open: { ...value.open, [path]: revealGap(value.open[path], index, expansion) } }))
if (current.texts[path] !== undefined) return
update(value => ({ ...value, texts: { ...value.texts, [path]: 'loading' } }))
const reading = owner.kind === 'local' ? localText(owner.scope, path) : changeRequestText(owner.url, owner.headSha, path)
@@ -1123,10 +1123,10 @@ export function ChangesTab({
setChosen(value => ({ ...value, [file.path]: !(value[file.path] ?? byDefault) }))
},
reveal: (path) => { setRevealed(value => new Set([...value, path])) },
expand: (file, index) => {
expand: (file, index, expansion) => {
const { data: owner, expand: open } = live.current
/* v8 ignore next -- sections render only while changes are loaded */
if (owner !== null) open(owner, file, index)
if (owner !== null) open(owner, file, index, expansion)
},
view: (file, viewed) => {
const { data: owner, markViewed: mark } = live.current
@@ -10,18 +10,21 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProper
import clsx from 'clsx'
import { flushSync } from 'react-dom'
import {
FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular,
FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconChevronUpOutlineRegular, IconEllipsisOutlineRegular,
IconPlusOutlineRegular,
Tag, Tooltip,
languageForPath, Menu, MenuItemButton, useCodeHighlighter, type CodeHighlighter, type HighlightSpan,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { ForgeDiffFile } from '../types.ts'
import { drawnLines, segmentsOf, splitRows, type DiffRow, type SplitCell, type SplitRow } from './diff-rows.ts'
import {
drawnLines, EXPAND_STEP, hidesLine, segmentsOf, splitRows,
type DiffRow, type DiffSegment, type GapExpansion, type GapReveal, type SplitCell, type SplitRow,
} from './diff-rows.ts'
import { codeSideAt, readCodeSelection } from './code-selection.ts'
import { reviewMatches, selectReviewLines, type ReviewSelection } from './review.ts'
import { ReviewThread, useFileReview } from './ReviewThread.tsx'
import { OutdatedThreads, ThreadCard, type FileThreads, type LineThread, type ThreadActions } from './ReviewThreads.tsx'
import { gapOf } from './review-threads.ts'
import type { FileReviewState } from './review-queue.ts'
import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx'
import reviewCss from './ReviewComposer.module.css'
@@ -54,8 +57,8 @@ export interface DiffFileHandlers {
readonly toggle: (file: ForgeDiffFile) => void
/** Show a large file anyway. */
readonly reveal: (path: string) => void
/** Expand one gap of a file. */
readonly expand: (file: ForgeDiffFile, index: number) => void
/** Show more of one gap of a file. */
readonly expand: (file: ForgeDiffFile, index: number, expansion: GapExpansion) => void
/** Mark a file viewed, which also collapses it, or clear the mark. */
readonly view: (file: ForgeDiffFile, viewed: boolean) => void
/** Rows of a file's menu, read whenever the menu draws. */
@@ -90,8 +93,8 @@ export interface DiffFileProps {
readonly revealed: boolean
/** The file's new side, which supplies collapsed unchanged lines. */
readonly text: DiffFileText
/** Indexes of the expanded gaps. */
readonly open: ReadonlySet<number>
/** The lines each expanded gap shows, by gap index. */
readonly open: ReadonlyMap<number, GapReveal>
/** Whether deletions and additions show in two columns; a file with only additions or only deletions keeps one. */
readonly split: boolean
/** Whether long lines wrap. */
@@ -147,8 +150,7 @@ type SideSpans = ReadonlyMap<number, readonly HighlightSpan[]> | undefined
/** A segment ready to draw: collapsed lines, or rows with the tokens of each side. */
type Prepared =
| { readonly kind: 'gap'; readonly index: number; readonly count: number | null }
| { readonly kind: 'folded'; readonly hunks: readonly number[] }
| Extract<DiffSegment, { kind: 'gap' | 'folded' }>
| { readonly kind: 'rows'; readonly rows: readonly DiffRow[]; readonly old: SideSpans; readonly new: SideSpans }
/** Highlight one side of a run of rows as one fragment, so tokens spanning lines keep their state. */
@@ -500,21 +502,44 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
)
rows.push(<div key={key} className={css.notes} data-forge-notes="">{side(pair.left, left)}{side(pair.right, right)}</div>)
}
// A gap of at most one step shows wholly on one click; a longer one shows a step down from the hunk above it or up
// from the hunk below it. The unknown lines after the last hunk show their first step once read.
const gapRow = (segment: Extract<DiffSegment, { kind: 'gap' }>): ReactNode => {
const loading = text === 'loading'
const label = segment.count === null ? t('diff.unchangedRest') : t('diff.unchanged', { count: segment.count.toLocaleString('en-US') })
if (segment.count === null || segment.count <= EXPAND_STEP) {
return <button key={`gap-${segment.index}`} type="button" className={css.gap} disabled={loading}
data-forge-diff-gap={segment.index} onClick={() => { handlers.expand(file, segment.index, segment.count === null ? 'down' : 'all') }}>
<IconChevronsUpDownOutlineRegular size={12} />
{label}
</button>
}
const step = (expansion: 'down' | 'up'): ReactNode => {
const name = t(expansion === 'down' ? 'diff.expandDown' : 'diff.expandUp', { count: String(EXPAND_STEP) })
return <Tooltip key={expansion} label={name} side="bottom">
<button type="button" className={css.gapStep} aria-label={name} disabled={loading} data-forge-gap-step={expansion}
onClick={() => { handlers.expand(file, segment.index, expansion) }}>
{expansion === 'down' ? <IconChevronDownOutlineRegular size={12} /> : <IconChevronUpOutlineRegular size={12} />}
</button>
</Tooltip>
}
return <div key={`gap-${segment.index}`} className={css.gapSteps} role="group" aria-label={label} data-forge-diff-gap={segment.index}>
{segment.edge !== 'leading' && step('down')}
{segment.edge !== 'trailing' && step('up')}
<span>{label}</span>
</div>
}
for (const [at, segment] of prepared.entries()) {
if (segment.kind === 'gap') {
rows.push(<button key={`gap-${segment.index}`} type="button" className={css.gap} disabled={text === 'loading'}
data-forge-diff-gap={segment.index} onClick={() => { handlers.expand(file, segment.index) }}>
<IconChevronsUpDownOutlineRegular size={12} />
{segment.count === null ? t('diff.unchangedRest') : t('diff.unchanged', { count: segment.count.toLocaleString('en-US') })}
</button>)
rows.push(gapRow(segment))
for (const item of unplaced) {
if (gapOf(file, item.place.side, item.place.endLine) !== segment.index) continue
if (!hidesLine(segment, item.place.side, item.place.endLine)) continue
rows.push(threadCard(item))
unplaced.delete(item)
}
for (const item of unplacedNotes) {
const at = lastLine(item)
if (gapOf(file, at.side, at.line) !== segment.index) continue
if (!hidesLine(segment, at.side, at.line)) continue
rows.push(annotationOf(item))
unplacedNotes.delete(item)
}
@@ -25,14 +25,38 @@ export interface SplitRow {
readonly right: SplitCell | null
}
/** Unchanged lines one step of a gap shows, and the most a gap shows on one click: the step of GitHub's and GitLab's diffs. */
export const EXPAND_STEP = 20
/** The lines a gap shows: `top` continue the hunk above it, `bottom` lead into the hunk below it. */
export interface GapReveal {
readonly top: number
readonly bottom: number
}
/** How a click expands a gap: one step down from the hunk above it, one step up from the hunk below it, or wholly. */
export type GapExpansion = 'down' | 'up' | 'all'
/** Where a gap sits: before the first hunk, between two hunks, or after the last hunk. */
export type GapEdge = 'leading' | 'middle' | 'trailing'
/** A run of drawn rows, or unchanged lines drawn as one row that expands them. */
export type DiffSegment =
| { readonly kind: 'rows'; readonly rows: readonly DiffRow[] }
/**
* `index` is the hunk the lines precede, or the hunk count for the lines after the last hunk;
* `count` is null while the length of the file is unknown.
* `index` is the hunk the lines precede, or the hunk count for the lines after the last hunk; `count` is null while
* the length of the file is unknown. The hidden lines are new-side lines `from` to `to`, null while unknown, whose old
* numbers are `offset` higher.
*/
| { readonly kind: 'gap'; readonly index: number; readonly count: number | null }
| {
readonly kind: 'gap'
readonly index: number
readonly count: number | null
readonly edge: GapEdge
readonly from: number
readonly to: number | null
readonly offset: number
}
/** Consecutive hunks a filter lens folds, drawn as one row that shows them, with the unchanged lines between them. */
| { readonly kind: 'folded'; readonly hunks: readonly number[] }
@@ -144,18 +168,19 @@ function endsNewSide(hunk: ForgeDiffHunk): boolean {
/**
* Lay out one file as runs of rows separated by collapsed unchanged lines.
* Unchanged lines before a hunk, between hunks, and after the last hunk
* collapse into one gap each; an open gap draws its lines from `lines` once
* they are known. The lines after the last hunk are unknown until `lines`
* collapse into one gap each; once `lines` is known, a gap draws the lines its
* reveal shows at its top and bottom, and a gap whose reveal covers it joins
* the rows around it. The lines after the last hunk are unknown until `lines`
* arrives, unless the file is new, deleted, or its last hunk reaches its end. Consecutive folded hunks draw as one
* folded segment that takes the unchanged lines between them too.
* @param file - one file of a diff.
* @param lines - the file's new side, which {@link matchesHunks} accepted, or undefined while it has not been read.
* @param open - indexes of the gaps the user expanded.
* @param open - the lines each expanded gap shows, by gap index.
* @param folded - indexes of the hunks a filter lens folds.
* @returns the segments in file order.
*/
export function segmentsOf(
file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlySet<number>, folded: ReadonlySet<number> = NO_FOLDS,
file: ForgeDiffFile, lines: readonly string[] | undefined, open: ReadonlyMap<number, GapReveal>, folded: ReadonlySet<number> = NO_FOLDS,
): DiffSegment[] {
const segments: DiffSegment[] = []
let rows: DiffRow[] = []
@@ -163,16 +188,30 @@ export function segmentsOf(
if (rows.length > 0) segments.push({ kind: 'rows', rows })
rows = []
}
/** Draw unchanged new-side lines `first` to `last` of the known file, whose old numbers are `offset` higher. */
const context = (known: readonly string[], first: number, last: number, offset: number): void => {
for (const [at, text] of known.slice(first - 1, last).entries()) {
rows.push({ kind: 'context', old: first + at + offset, new: first + at, text: drawn(text) })
}
}
/** Unchanged new-side lines `from` to `to`, null while unknown, whose old numbers are `offset` higher. */
const gap = (index: number, from: number, to: number | null, offset: number): void => {
if (lines !== undefined && to !== null && open.has(index)) {
for (const [at, text] of lines.slice(from - 1, to).entries()) {
rows.push({ kind: 'context', old: from + at + offset, new: from + at, text: drawn(text) })
}
const edge: GapEdge = index === 0 ? 'leading' : index === file.hunks.length ? 'trailing' : 'middle'
const reveal = open.get(index)
if (lines === undefined || to === null || reveal === undefined) {
flush()
segments.push({ kind: 'gap', index, count: to === null ? null : to - from + 1, edge, from, to, offset })
return
}
flush()
segments.push({ kind: 'gap', index, count: to === null ? null : to - from + 1 })
const total = to - from + 1
const top = Math.min(reveal.top, total)
const bottom = Math.min(reveal.bottom, total - top)
context(lines, from, from + top - 1, offset)
if (top + bottom < total) {
flush()
segments.push({ kind: 'gap', index, count: total - top - bottom, edge, from: from + top, to: to - bottom, offset })
}
context(lines, to - bottom + 1, to, offset)
}
let newEnd = 0
let oldEnd = 0
@@ -200,6 +239,34 @@ export function segmentsOf(
return segments
}
/**
* Show more of one gap: a step down from the hunk above it, a step up from the hunk below it, or all of it.
* @param open - the lines each expanded gap of a file shows, by gap index.
* @param index - the gap.
* @param expansion - which way the gap expands.
* @returns the reveals with that gap's widened.
*/
export function revealGap(
open: ReadonlyMap<number, GapReveal> | undefined, index: number, expansion: GapExpansion,
): ReadonlyMap<number, GapReveal> {
const previous = open?.get(index) ?? { top: 0, bottom: 0 }
const next = expansion === 'all' ? { top: Number.POSITIVE_INFINITY, bottom: 0 }
: expansion === 'down' ? { ...previous, top: previous.top + EXPAND_STEP } : { ...previous, bottom: previous.bottom + EXPAND_STEP }
return new Map([...open ?? [], [index, next]])
}
/**
* Whether a gap still hides a line.
* @param gap - the gap segment.
* @param side - the side that numbers the line.
* @param line - the line.
* @returns whether the line is among the gap's hidden lines.
*/
export function hidesLine(gap: Extract<DiffSegment, { kind: 'gap' }>, side: 'L' | 'R', line: number): boolean {
const at = side === 'L' ? line - gap.offset : line
return at >= gap.from && (gap.to === null || at <= gap.to)
}
/**
* Count the rows a file's hunks draw.
* @param file - one file of a diff.
@@ -292,6 +292,8 @@ export const zh = {
'diff.moreOptions': '更多视图选项',
'diff.unchanged': '{count} 行未变更',
'diff.unchangedRest': '其余未变更的行',
'diff.expandDown': '向下展开 {count} 行',
'diff.expandUp': '向上展开 {count} 行',
'diff.newFile': '新文件',
'diff.deletedFile': '已删除',
'diff.renamed': '由 {from} 重命名',
@@ -741,6 +743,8 @@ export const en: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'More view options',
'diff.unchanged': '{count} unchanged lines',
'diff.unchangedRest': 'Remaining unchanged lines',
'diff.expandDown': 'Expand {count} lines down',
'diff.expandUp': 'Expand {count} lines up',
'diff.newFile': 'New file',
'diff.deletedFile': 'Deleted',
'diff.renamed': 'Renamed from {from}',
@@ -1194,6 +1198,8 @@ export const ja: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'その他の表示オプション',
'diff.unchanged': '未変更 {count} 行',
'diff.unchangedRest': '残りの未変更行',
'diff.expandDown': '下へ {count} 行展開',
'diff.expandUp': '上へ {count} 行展開',
'diff.newFile': '新規ファイル',
'diff.deletedFile': '削除済み',
'diff.renamed': '{from} から名前変更',
@@ -1640,6 +1646,8 @@ export const es: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'Más opciones de vista',
'diff.unchanged': '{count} líneas sin cambios',
'diff.unchangedRest': 'Líneas restantes sin cambios',
'diff.expandDown': 'Expandir {count} líneas hacia abajo',
'diff.expandUp': 'Expandir {count} líneas hacia arriba',
'diff.newFile': 'Archivo nuevo',
'diff.deletedFile': 'Eliminado',
'diff.renamed': 'Renombrado desde {from}',
@@ -2086,6 +2094,8 @@ export const fr: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'Plus d’options d’affichage',
'diff.unchanged': '{count} lignes inchangées',
'diff.unchangedRest': 'Lignes inchangées restantes',
'diff.expandDown': 'Afficher {count} lignes vers le bas',
'diff.expandUp': 'Afficher {count} lignes vers le haut',
'diff.newFile': 'Nouveau fichier',
'diff.deletedFile': 'Supprimé',
'diff.renamed': 'Renommé depuis {from}',
@@ -2532,6 +2542,8 @@ export const de: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'Weitere Ansichtsoptionen',
'diff.unchanged': '{count} unveränderte Zeilen',
'diff.unchangedRest': 'Übrige unveränderte Zeilen',
'diff.expandDown': '{count} Zeilen nach unten einblenden',
'diff.expandUp': '{count} Zeilen nach oben einblenden',
'diff.newFile': 'Neue Datei',
'diff.deletedFile': 'Gelöscht',
'diff.renamed': 'Umbenannt von {from}',
@@ -2978,6 +2990,8 @@ export const ru: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'Другие параметры просмотра',
'diff.unchanged': 'Неизменённых строк: {count}',
'diff.unchangedRest': 'Остальные неизменённые строки',
'diff.expandDown': 'Показать {count} строк ниже',
'diff.expandUp': 'Показать {count} строк выше',
'diff.newFile': 'Новый файл',
'diff.deletedFile': 'Удалено',
'diff.renamed': 'Переименован из {from}',
@@ -3424,6 +3438,8 @@ export const pt: Record<ForgePanelKey, string> = {
'diff.moreOptions': 'Mais opções de exibição',
'diff.unchanged': '{count} linhas sem alterações',
'diff.unchangedRest': 'Demais linhas sem alterações',
'diff.expandDown': 'Expandir {count} linhas para baixo',
'diff.expandUp': 'Expandir {count} linhas para cima',
'diff.newFile': 'Novo arquivo',
'diff.deletedFile': 'Excluído',
'diff.renamed': 'Renomeado de {from}',
@@ -1087,6 +1087,61 @@ describe('ChangesTab unchanged lines', () => {
expect(rowTexts(app).slice(-2)).toEqual(['const t13 = 13', 'const t13 = 13'])
})
it('shows a gap over one step a step at a time from the hunk on either side, and a gap of one step at once', async () => {
const lines = Array.from({ length: 100 }, (_, at) => `line ${String(at + 1)}`)
const long = file('src/long.ts', {
additions: 1, deletions: 1,
hunks: [{ oldStart: 49, oldLines: 3, newStart: 49, newLines: 3, lines: [' line 49', '-old 50', '+line 50', ' line 51'] }],
})
const m = mount({
setup: (faces) => {
faces.localDiff.mockResolvedValue(ok({ base: BASE, files: [long], omitted: 0 }))
faces.localText.mockResolvedValue(ok(`${lines.join('\n')}\n`))
},
})
await settle()
const section = m.section('src/long.ts')
const leading = within(section).getByRole('group', { name: '48 unchanged lines' })
expect(within(leading).queryByRole('button', { name: 'Expand 20 lines down' })).toBeNull()
fireEvent.click(within(leading).getByRole('button', { name: 'Expand 20 lines up' }))
expect(within(leading).getByRole('button', { name: 'Expand 20 lines up' }).hasAttribute('disabled')).toBe(true)
await settle()
expect(rowTexts(section).slice(0, 2)).toEqual(['line 29', 'line 29'])
const trailing = within(section).getByRole('group', { name: '49 unchanged lines' })
expect(within(trailing).queryByRole('button', { name: 'Expand 20 lines up' })).toBeNull()
fireEvent.click(within(trailing).getByRole('button', { name: 'Expand 20 lines down' }))
expect(rowTexts(section).slice(-2)).toEqual(['line 71', 'line 71'])
expect(within(section).getByRole('group', { name: '29 unchanged lines' })).toBeTruthy()
fireEvent.click(within(section).getByRole('button', { name: 'Expand 20 lines up' }))
fireEvent.click(within(section).getByRole('button', { name: '8 unchanged lines' }))
expect(rowTexts(section).slice(0, 2)).toEqual(['line 1', 'line 1'])
expect([...section.querySelectorAll('[data-forge-diff-gap]')].map(gap => gap.textContent)).toEqual(['29 unchanged lines'])
expect(m.faces.localText).toHaveBeenCalledOnce()
})
it('shows the first step of the unknown lines after the last hunk once they are read', async () => {
const lines = Array.from({ length: 60 }, (_, at) => `line ${String(at + 1)}`)
const long = file('src/long.ts', {
additions: 1, deletions: 1,
hunks: [{ oldStart: 1, oldLines: 2, newStart: 1, newLines: 2, lines: [' line 1', '-old 2', '+line 2'] }],
})
const m = mount({
setup: (faces) => {
faces.localDiff.mockResolvedValue(ok({ base: BASE, files: [long], omitted: 0 }))
faces.localText.mockResolvedValue(ok(`${lines.join('\n')}\n`))
},
})
await settle()
const section = m.section('src/long.ts')
fireEvent.click(within(section).getByRole('button', { name: en['diff.unchangedRest'] }))
await settle()
expect(rowTexts(section).slice(-2)).toEqual(['line 22', 'line 22'])
expect(within(section).getByRole('group', { name: '38 unchanged lines' })).toBeTruthy()
})
it('reports a read that failed or no longer matches and keeps the lines collapsed', async () => {
const m = mount({
setup: (faces) => {
@@ -31,7 +31,7 @@ function mount(overrides: Partial<DiffFileProps> = {}) {
reach: new SectionReach(), annotation: vi.fn(() => null), fileMenu: vi.fn(() => null), unfold: vi.fn(),
}
const props: DiffFileProps = { file, visible: true, expanded: true, large: false, revealed: false,
text: undefined, open: new Set(), split: true, wrap: true, badge: '', tooltip: 'a.txt',
text: undefined, open: new Map(), split: true, wrap: true, badge: '', tooltip: 'a.txt',
viewed: 'unviewed', viewedNote: '', viewedDisabled: false, handlers, review, t, ...overrides }
const view = render(<DiffFile {...props} />)
const line = (name: string) => view.getByRole('button', { name: `Select line ${name}` })
@@ -1,7 +1,9 @@
/** Rows of a file diff: numbering, side-by-side pairing, and unchanged lines between hunks. */
import { describe, expect, it } from 'vitest'
import type { ForgeDiffFile, ForgeDiffHunk } from '../src/types.ts'
import { drawnLines, hunkRows, matchesHunks, segmentsOf, splitRows, textLines } from '../src/client/diff-rows.ts'
import {
drawnLines, EXPAND_STEP, hidesLine, hunkRows, matchesHunks, revealGap, segmentsOf, splitRows, textLines, type DiffSegment, type GapReveal,
} from '../src/client/diff-rows.ts'
/** Modified file whose hunks change lines 3–6 and 11 of its 13 new lines. */
const NEW_SIDE = ['a1', 'a2', 'a3', 'y', 'z', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 't12', 't13']
@@ -10,6 +12,18 @@ const HUNKS: readonly ForgeDiffHunk[] = [
{ oldStart: 10, oldLines: 2, newStart: 11, newLines: 1, lines: [' a10', '-w'] },
]
const NONE: ReadonlyMap<number, GapReveal> = new Map()
/** Gaps shown wholly. */
function opened(...indexes: number[]): ReadonlyMap<number, GapReveal> {
return new Map(indexes.map(index => [index, { top: Number.POSITIVE_INFINITY, bottom: 0 }]))
}
/** A segment as its row count, its gap's index and count, or itself. */
function brief(segment: DiffSegment): unknown {
return segment.kind === 'rows' ? segment.rows.length : segment.kind === 'gap' ? { kind: 'gap', index: segment.index, count: segment.count } : segment
}
function file(overrides: Partial<ForgeDiffFile> = {}): ForgeDiffFile {
return {
path: 'src/a.ts', previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, layer: 'implementation', digest: 'digest',
@@ -82,7 +96,7 @@ describe('matchesHunks', () => {
describe('segmentsOf', () => {
it('collapses the lines before, between, and after the hunks, the last of unknown length', () => {
expect(segmentsOf(file(), undefined, new Set([0, 1])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([
expect(segmentsOf(file(), undefined, opened(0, 1)).map(brief)).toEqual([
{ kind: 'gap', index: 0, count: 2 },
5,
{ kind: 'gap', index: 1, count: 4 },
@@ -92,7 +106,7 @@ describe('segmentsOf', () => {
})
it('draws the expanded gaps from the new side with the old numbers they had', () => {
const [rows, ...rest] = segmentsOf(file(), NEW_SIDE, new Set([0, 1, 2]))
const [rows, ...rest] = segmentsOf(file(), NEW_SIDE, opened(0, 1, 2))
expect(rest).toEqual([])
if (rows?.kind !== 'rows') throw new Error('expected one run of rows')
expect(rows.rows.map(row => [row.old, row.new, row.text])).toEqual([
@@ -105,17 +119,17 @@ describe('segmentsOf', () => {
})
it('keeps unexpanded gaps collapsed once the new side is known, and counts the lines after the last hunk', () => {
expect(segmentsOf(file(), NEW_SIDE, new Set([1])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([
expect(segmentsOf(file(), NEW_SIDE, opened(1)).map(brief)).toEqual([
{ kind: 'gap', index: 0, count: 2 },
11,
{ kind: 'gap', index: 2, count: 2 },
])
expect(segmentsOf(file(), NEW_SIDE.slice(0, 11), new Set()).at(-1)).toMatchObject({ kind: 'rows' })
expect(segmentsOf(file(), NEW_SIDE.slice(0, 11), NONE).at(-1)).toMatchObject({ kind: 'rows' })
})
it('maps lines around a hunk that only deletes to the old lines after the deletion', () => {
const deletion = file({ hunks: [{ oldStart: 5, oldLines: 2, newStart: 5, newLines: 0, lines: ['-d5', '-d6'] }] })
const [rows] = segmentsOf(deletion, ['b1', 'b2', 'b3', 'b4', 'b7'], new Set([0, 1]))
const [rows] = segmentsOf(deletion, ['b1', 'b2', 'b3', 'b4', 'b7'], opened(0, 1))
if (rows?.kind !== 'rows') throw new Error('expected one run of rows')
expect(rows.rows.map(row => [row.old, row.new, row.text])).toEqual([
[1, 1, 'b1'], [2, 2, 'b2'], [3, 3, 'b3'], [4, 4, 'b4'], [5, null, 'd5'], [6, null, 'd6'], [7, 5, 'b7'],
@@ -124,25 +138,25 @@ describe('segmentsOf', () => {
it('has nothing after the last hunk of a new or deleted file or of a hunk that reaches the end of the new side', () => {
const added = file({ status: 'added', hunks: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: 2, lines: ['+x', '+y'] }] })
expect(segmentsOf(added, undefined, new Set()).map(segment => segment.kind)).toEqual(['rows'])
expect(segmentsOf(added, undefined, NONE).map(segment => segment.kind)).toEqual(['rows'])
const deleted = file({ status: 'deleted', hunks: [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 0, lines: ['-x'] }] })
expect(segmentsOf(deleted, undefined, new Set()).map(segment => segment.kind)).toEqual(['rows'])
expect(segmentsOf(deleted, undefined, NONE).map(segment => segment.kind)).toEqual(['rows'])
const ending = file({ hunks: [{ oldStart: 4, oldLines: 1, newStart: 4, newLines: 1, lines: ['-a', '+b', '\\ No newline at end of file'] }] })
expect(segmentsOf(ending, undefined, new Set()).map(segment => segment.kind)).toEqual(['gap', 'rows'])
expect(segmentsOf(ending, undefined, NONE).map(segment => segment.kind)).toEqual(['gap', 'rows'])
const oldEnding = file({ hunks: [{ oldStart: 4, oldLines: 1, newStart: 4, newLines: 1, lines: ['-a', '\\ No newline at end of file', '+b'] }] })
expect(segmentsOf(oldEnding, undefined, new Set()).map(segment => segment.kind)).toEqual(['gap', 'rows', 'gap'])
expect(segmentsOf(oldEnding, undefined, NONE).map(segment => segment.kind)).toEqual(['gap', 'rows', 'gap'])
})
it('draws consecutive folded hunks as one row that takes the lines between them, and the gap before a folded run', () => {
const three = file({ hunks: [...HUNKS, { oldStart: 13, oldLines: 1, newStart: 13, newLines: 1, lines: ['-u', '+t13'] }] })
expect(segmentsOf(three, undefined, new Set(), new Set([1, 2])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([
expect(segmentsOf(three, undefined, NONE, new Set([1, 2])).map(brief)).toEqual([
{ kind: 'gap', index: 0, count: 2 },
5,
{ kind: 'gap', index: 1, count: 4 },
{ kind: 'folded', hunks: [1, 2] },
{ kind: 'gap', index: 3, count: null },
])
expect(segmentsOf(three, undefined, new Set(), new Set([0, 2])).map(segment => segment.kind === 'rows' ? segment.rows.length : segment)).toEqual([
expect(segmentsOf(three, undefined, NONE, new Set([0, 2])).map(brief)).toEqual([
{ kind: 'gap', index: 0, count: 2 },
{ kind: 'folded', hunks: [0] },
{ kind: 'gap', index: 1, count: 4 },
@@ -153,8 +167,37 @@ describe('segmentsOf', () => {
])
})
it('names where each gap sits and the new-side lines it hides, whose old numbers are its offset higher', () => {
expect(segmentsOf(file(), NEW_SIDE, NONE).filter(segment => segment.kind === 'gap')).toEqual([
{ kind: 'gap', index: 0, count: 2, edge: 'leading', from: 1, to: 2, offset: 0 },
{ kind: 'gap', index: 1, count: 4, edge: 'middle', from: 7, to: 10, offset: -1 },
{ kind: 'gap', index: 2, count: 2, edge: 'trailing', from: 12, to: 13, offset: 0 },
])
expect(segmentsOf(file(), undefined, NONE).at(-1)).toEqual({ kind: 'gap', index: 2, count: null, edge: 'trailing', from: 12, to: null, offset: 0 })
})
it('draws the lines a reveal shows at the top and bottom of a gap and keeps the rest collapsed', () => {
const segments = segmentsOf(file(), NEW_SIDE, new Map([[1, { top: 1, bottom: 2 }]]))
expect(segments.map(brief)).toEqual([{ kind: 'gap', index: 0, count: 2 }, 6, { kind: 'gap', index: 1, count: 1 }, 4, { kind: 'gap', index: 2, count: 2 }])
const [, above, gap, below] = segments
if (above?.kind !== 'rows' || below?.kind !== 'rows') throw new Error('expected rows around the gap')
expect(above.rows.at(-1)).toEqual({ kind: 'context', old: 6, new: 7, text: 'a6' })
expect(gap).toMatchObject({ kind: 'gap', index: 1, from: 8, to: 8 })
expect(below.rows.slice(0, 2)).toEqual([{ kind: 'context', old: 8, new: 9, text: 'a8' }, { kind: 'context', old: 9, new: 10, text: 'a9' }])
})
it('joins the rows around a gap that its reveal covers, however the steps add up', () => {
expect(segmentsOf(file(), NEW_SIDE, new Map([[1, { top: 3, bottom: 1 }]])).map(brief)).toEqual([{ kind: 'gap', index: 0, count: 2 }, 11, { kind: 'gap', index: 2, count: 2 }])
expect(segmentsOf(file(), NEW_SIDE, new Map([[1, { top: 40, bottom: 40 }]])).map(brief)).toEqual([{ kind: 'gap', index: 0, count: 2 }, 11, { kind: 'gap', index: 2, count: 2 }])
})
it('keeps a revealed gap collapsed until the new side is read', () => {
expect(segmentsOf(file(), undefined, new Map([[2, { top: EXPAND_STEP, bottom: 0 }]])).at(-1)).toMatchObject({ kind: 'gap', index: 2, count: null })
expect(segmentsOf(file(), NEW_SIDE, new Map([[2, { top: EXPAND_STEP, bottom: 0 }]])).map(brief)).toEqual([{ kind: 'gap', index: 0, count: 2 }, 5, { kind: 'gap', index: 1, count: 4 }, 4])
})
it('draws nothing for a file without hunks', () => {
expect(segmentsOf(file({ status: 'renamed', previousPath: 'old.ts', hunks: [] }), undefined, new Set())).toEqual([])
expect(segmentsOf(file({ status: 'renamed', previousPath: 'old.ts', hunks: [] }), undefined, NONE)).toEqual([])
})
})
@@ -164,3 +207,27 @@ describe('drawnLines', () => {
expect(drawnLines(file({ hunks: [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 1, lines: ['-a', '\\ No newline at end of file', '+b'] }] }))).toBe(2)
})
})
describe('revealGap', () => {
it('shows one step more down from the hunk above or up from the hunk below, or the whole gap', () => {
const down = revealGap(undefined, 1, 'down')
expect(down.get(1)).toEqual({ top: EXPAND_STEP, bottom: 0 })
const both = revealGap(down, 1, 'up')
expect(both.get(1)).toEqual({ top: EXPAND_STEP, bottom: EXPAND_STEP })
expect(revealGap(both, 1, 'down').get(1)).toEqual({ top: 2 * EXPAND_STEP, bottom: EXPAND_STEP })
expect(revealGap(both, 0, 'all')).toEqual(new Map([[1, { top: EXPAND_STEP, bottom: EXPAND_STEP }], [0, { top: Number.POSITIVE_INFINITY, bottom: 0 }]]))
expect(down.get(1)).toEqual({ top: EXPAND_STEP, bottom: 0 })
})
})
describe('hidesLine', () => {
it('finds the lines a gap still hides on either side', () => {
const middle = segmentsOf(file(), NEW_SIDE, new Map([[1, { top: 1, bottom: 2 }]]))[2]
if (middle?.kind !== 'gap') throw new Error('expected the middle gap')
expect([hidesLine(middle, 'R', 7), hidesLine(middle, 'R', 8), hidesLine(middle, 'R', 9)]).toEqual([false, true, false])
expect([hidesLine(middle, 'L', 6), hidesLine(middle, 'L', 7), hidesLine(middle, 'L', 8)]).toEqual([false, true, false])
const rest = segmentsOf(file(), undefined, NONE).at(-1)
if (rest?.kind !== 'gap') throw new Error('expected the gap after the last hunk')
expect([hidesLine(rest, 'R', 11), hidesLine(rest, 'R', 400), hidesLine(rest, 'L', 12)]).toEqual([false, true, true])
})
})