diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index dddec32e3b..93e140c104 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -18,8 +18,8 @@ en: 705f7f143fc7d6fb zh: e757a4bf6b0ebce1 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 8a32164b43695f96 - zh: c5659ca104118d3b + en: 6dd304b2ee1d1771 + zh: 9749536a0672dc8f /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 4cc0215ddd1aa565 - zh: 5a39cbdafc70fce9 + en: fbbb6498637ec87d + zh: e1616f743fa30869 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index f07279f905..ff7fadb14e 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -77,7 +77,7 @@ Each inspection also decides whether the worktree is missing: the Session's dire `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host. | Source | Responsibility | |---|---| @@ -152,6 +152,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. +- **Highlighting across collapsed lines** — rows after collapsed unchanged lines take the colors of the lines before them only once the file is read: local files when they draw, change request files after one of their gaps expands. A code block, comment, or string that opens more than 120 lines before a run still leaves the run colored as if it started there. - **Undrawn files** — until the reader scrolls near an expanded file, it holds 22 px per drawn line, which leaves out side-by-side pairing, wrapped lines, unchanged-line rows, and review cards, so the scroll range shifts a little as files draw; its saved review comments also appear only once it draws. - **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own. - **Viewed files on the code host** — GitHub keeps one viewed mark per file and user, not one per commit, so marks in a view of chosen commits stay in this browser, and another browser or device starts without them. A file beyond the provider's `maxViewedFiles` shows no mark from GitHub until it is marked in this view. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 634e04bd5a..c1d4d50019 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -77,7 +77,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。 | 源码 | 职责 | |---|---| @@ -152,6 +152,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 +- **跨折叠行的高亮**——折叠的未变更行之后的行,要等文件被读取后才按它之前的内容着色:本地文件在绘制时读取,变更请求的文件要等它的某处折叠行展开后。在一段行之前超过 120 行处开始的代码块、注释或字符串,这段行仍按从段首开始着色。 - **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。 - **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 - **代码托管平台上的已审阅状态**——GitHub 对每个文件和用户只保存一个已审阅标记,不按提交区分,因此所选提交视图中的标记只保存在本浏览器中,换浏览器或设备后没有这些标记。超出提供方 `maxViewedFiles` 的文件在本视图中标记之前不显示 GitHub 上的标记。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 1b5b0a2bcf..851b99cd2d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -805,6 +805,8 @@ export function ChangesTab({ const [expansion, setExpansion] = useState({ source: null, texts: {}, open: {} }) const current = expansion.source === expansionSource ? expansion : { source: expansionSource, texts: {}, open: {} } const latest = useRef(expansionSource) + // Files whose new side was read ahead for highlighting in this comparison, each read at most once. + const contextReads = useRef<{ readonly source: typeof expansionSource; readonly paths: Set }>({ source: null, paths: new Set() }) useLayoutEffect(() => { latest.current = expansionSource }, [expansionSource]) const [revealed, setRevealed] = useState>(new Set()) // The line budget counts the files not marked viewed when the diff loads, so later marks leave it unchanged. A file stays @@ -897,6 +899,23 @@ export function ChangesTab({ }) }) } + /** + * Read a local file's new side ahead of any expansion, once per comparison, so its rows can be highlighted with the + * lines before them. A change request's files are not read for this, since each read costs a request to the code host. + */ + const readContext = (owner: ChangesData, file: ForgeDiffFile): void => { + const path = file.path + if (owner.kind !== 'local') return + if (contextReads.current.source !== expansionSource) contextReads.current = { source: expansionSource, paths: new Set() } + if (contextReads.current.paths.has(path)) return + contextReads.current.paths.add(path) + void localText(owner.scope, path).then((result) => { + const lines = result.ok ? textLines(result.value) : undefined + // A read that fails or no longer matches leaves the file as it is, and an expansion reads it again and says why. + if (lines === undefined || !matchesHunks(lines, file.hunks)) return + update(value => value.texts[path] !== undefined ? value : { ...value, texts: { ...value.texts, [path]: lines } }) + }) + } const fileActions = (owner: ChangesData, file: ForgeDiffFile): DiffFileAction[] => { const list: DiffFileAction[] = [{ label: 'diff.copyPath', run: () => { copyPath(file.path) } }] if (file.status === 'deleted') return list @@ -1112,8 +1131,8 @@ export function ChangesTab({ // an effect would hand them the previous diff's links. A render React discards leaves values derived from the same // props and state, which the retried render assigns again. const callbacks = { - data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, lensTitle, - renderSlot, kept, t, + data, expandedByDefault, expand, readContext, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, + lensTitle, renderSlot, kept, t, } const live = useRef(callbacks) live.current = callbacks @@ -1128,6 +1147,11 @@ export function ChangesTab({ /* v8 ignore next -- sections render only while changes are loaded */ if (owner !== null) open(owner, file, index, expansion) }, + readContext: (file) => { + const { data: owner, readContext: read } = live.current + /* v8 ignore next -- sections render only while changes are loaded */ + if (owner !== null) read(owner, file) + }, view: (file, viewed) => { const { data: owner, markViewed: mark } = live.current /* v8 ignore next -- sections render only while changes are loaded */ diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index e0362e4f18..eb3facd043 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -33,6 +33,7 @@ import type { ForgePanelKey, NS } from './locales.ts' import type { ViewedState } from './viewed-files.ts' import type { SectionReach } from './section-reach.ts' import type { SourcedAnnotation } from './annotations.ts' +import { oldSideLines, runKey, sideRun, useContextHighlight, type FileSides, type SideRun } from './highlight-context.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -59,6 +60,8 @@ export interface DiffFileHandlers { readonly reveal: (path: string) => void /** Show more of one gap of a file. */ readonly expand: (file: ForgeDiffFile, index: number, expansion: GapExpansion) => void + /** Read a file's new side ahead of any expansion, for highlighting rows after its collapsed lines; a source may ignore it. */ + readonly readContext: (file: ForgeDiffFile) => 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. */ @@ -148,23 +151,33 @@ const SIGN: Record = { add: '+', del: '-', context: '' /** Highlighted tokens of one side's lines by line number, or undefined while the grammar is unavailable. */ type SideSpans = ReadonlyMap | undefined -/** A segment ready to draw: collapsed lines, or rows with the tokens of each side. */ +/** A segment ready to draw: collapsed lines, or rows with the tokens of each side and the lines each side numbers. */ type Prepared = | Extract - | { 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. */ -function sideSpans(rows: readonly DiffRow[], side: 'old' | 'new', highlighter: CodeHighlighter): SideSpans { - const numbered: { readonly no: number; readonly text: string }[] = [] - for (const row of rows) { - const no = row[side] - if (no !== null) numbered.push({ no, text: row.text }) + | { + readonly kind: 'rows' + readonly rows: readonly DiffRow[] + readonly old: SideSpans + readonly new: SideSpans + readonly oldRun: SideRun | undefined + readonly newRun: SideRun | undefined } - if (numbered.length === 0) return new Map() - const highlighted = highlighter(numbered.map(line => line.text).join('\n')) + +/** + * Highlight one side of a run of rows as one fragment, so tokens spanning lines keep their state. The tokens are kept by + * the run's lines in `kept`, which the caller replaces with the file or the highlighter. + */ +function sideSpans(run: SideRun | undefined, highlighter: CodeHighlighter, kept: Map): SideSpans { + if (run === undefined) return new Map() + const key = runKey(run) + const known = kept.get(key) + if (known !== undefined) return known + const highlighted = highlighter(run.texts.join('\n')) if (highlighted === undefined) return undefined // Shiki omits a final empty token row, so a final empty line gets no tokens. - return new Map(numbered.map((line, index) => [line.no, highlighted[index] ?? []])) + const spans = new Map(run.texts.map((_text, index) => [run.first + index, highlighted[index] ?? []])) + kept.set(key, spans) + return spans } function Code({ text, spans, old, next }: { @@ -350,10 +363,26 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme && inHunks(file, [index], thread.selection.comment.side, thread.selection.comment.endLine))) return new Set([...folded.hunks].filter(index => !holds(index))) }, [folded, editors, review, comments.threads, file]) - const prepared = useMemo(() => segmentsOf(file, lines, open, foldHunks).map((segment): Prepared => segment.kind !== 'rows' - ? segment - : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), - [file, lines, open, foldHunks, highlighter]) + // Runs whose lines stay the same keep their tokens when the file's text arrives or another gap expands. + const kept = useMemo(() => new Map(), [file, highlighter]) + const prepared = useMemo(() => segmentsOf(file, lines, open, foldHunks).map((segment): Prepared => { + if (segment.kind !== 'rows') return segment + const oldRun = sideRun(segment.rows, 'old') + const newRun = sideRun(segment.rows, 'new') + return { ...segment, old: sideSpans(oldRun, highlighter, kept), new: sideSpans(newRun, highlighter, kept), oldRun, newRun } + }), [file, lines, open, foldHunks, highlighter, kept]) + // Rows drawn after collapsed lines take the colors of the lines before them once the whole file is known, after they draw. + const runs = useMemo(() => prepared.flatMap(segment => segment.kind !== 'rows' ? [] + : [segment.oldRun, segment.newRun].filter((run): run is SideRun => run !== undefined)), [prepared]) + const sides = useMemo((): FileSides | undefined => lines === undefined ? undefined + : { new: lines, old: oldSideLines(lines, file.hunks) }, [lines, file.hunks]) + const corrected = useContextHighlight(runs, sides, highlighter, root, selecting) + const spansOf = (spans: SideSpans, run: SideRun | undefined): SideSpans => run === undefined ? spans : corrected.get(runKey(run)) ?? spans + const collapsed = prepared.some(segment => segment.kind === 'gap') + const grammar = languageForPath(file.path) !== undefined + useEffect(() => { + if (text === undefined && collapsed && grammar) handlers.readContext(file) + }, [text, collapsed, grammar, file, handlers]) // Returns whether the range was accepted; a range across hunks or outside them keeps the previous selection. const choose = (side: 'L' | 'R', line: number, extend: boolean): boolean => { /* v8 ignore next -- the line buttons and hover pluses that choose a range draw only with review actions */ @@ -530,6 +559,8 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme } for (const [at, segment] of prepared.entries()) { + const oldSpans = segment.kind === 'rows' ? spansOf(segment.old, segment.oldRun) : undefined + const newSpans = segment.kind === 'rows' ? spansOf(segment.new, segment.newRun) : undefined if (segment.kind === 'gap') { rows.push(gapRow(segment)) for (const item of unplaced) { @@ -565,7 +596,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme for (const [index, pair] of splitRows(segment.rows).entries()) { rows.push(
{ extendAdd(event.buttons, pair.left?.no ?? null, pair.right?.no ?? null) }}> - {cell(pair.left, segment.old, 'L')}{cell(pair.right, segment.new, 'R')} + {cell(pair.left, oldSpans, 'L')}{cell(pair.right, newSpans, 'R')}
) notes(`notes-${at}-${index}`, pair) } @@ -576,7 +607,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme rows.push(
{ extendAdd(event.buttons, row.old, row.new) }}> {singleSide !== 'R' && number('L', row.old, row.kind === 'del' && !labeled)}{singleSide !== 'L' && number('R', row.new, row.kind !== 'del' && !labeled)}{SIGN[row.kind]} - +
) rows.push(...commentsAt('L', row.old), ...commentsAt('R', row.new)) } diff --git a/packages/experimental/client-ui-forge/src/client/highlight-context.ts b/packages/experimental/client-ui-forge/src/client/highlight-context.ts new file mode 100644 index 0000000000..da4e3d5788 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/highlight-context.ts @@ -0,0 +1,204 @@ +/** + * Highlighting of drawn rows with the lines before them. A run of rows drawn after collapsed unchanged lines is + * highlighted again with up to {@link HIGHLIGHT_CONTEXT_LINES} lines of the file before it, so a code block, comment, + * or string that opens in the collapsed lines colors the run as it does in the whole file. Constructs that open further + * back keep the colors of the run alone. + */ + +import { useCallback, useEffect, useRef, useState, type RefObject } from 'react' +import type { CodeHighlighter, HighlightSpan } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ForgeDiffHunk } from '../types.ts' +import type { DiffRow } from './diff-rows.ts' + +/** Lines before a run that its highlighting reads; one call stays within an idle period for the slower grammars. */ +export const HIGHLIGHT_CONTEXT_LINES = 120 + +/** Tokens of one side's lines by line number. */ +export type LineSpans = ReadonlyMap + +/** One side of one run of rows: its first and last line numbers and their texts. */ +export interface SideRun { + readonly side: 'old' | 'new' + readonly first: number + readonly last: number + readonly texts: readonly string[] +} + +/** A line as drawn: without the carriage return of a CRLF line ending. */ +function drawn(text: string): string { + return text.endsWith('\r') ? text.slice(0, -1) : text +} + +/** + * Rebuild the old side of a file from its new side and the hunks of its diff. + * @param lines - the new side, which the hunks describe. + * @param hunks - the hunks, in file order. + * @returns the old side's lines. + */ +export function oldSideLines(lines: readonly string[], hunks: readonly ForgeDiffHunk[]): string[] { + const old: string[] = [] + let at = 1 + for (const hunk of hunks) { + old.push(...lines.slice(at - 1, hunk.newStart - 1)) + at = Math.max(at, hunk.newStart) + for (const line of hunk.lines) { + const sign = line.charAt(0) + if (sign === ' ' || sign === '-') old.push(line.slice(1)) + if (sign === ' ' || sign === '+') at++ + } + } + old.push(...lines.slice(at - 1)) + return old +} + +/** + * One side of a run of rows, which numbers its lines consecutively. + * @param rows - the run. + * @param side - the side. + * @returns the side's lines, or undefined when the run has none on that side. + */ +export function sideRun(rows: readonly DiffRow[], side: 'old' | 'new'): SideRun | undefined { + const numbers: number[] = [] + const texts: string[] = [] + for (const row of rows) { + const no = row[side] + if (no === null) continue + numbers.push(no) + texts.push(row.text) + } + const first = numbers[0] + const last = numbers.at(-1) + return first === undefined || last === undefined ? undefined : { side, first, last, texts } +} + +/** + * Highlight one side of a run after the lines of the file before it. + * @param run - the side of the run. + * @param file - the whole side the run belongs to. + * @param highlighter - the file's highlighter. + * @returns the run's tokens by line number, null when nothing precedes the run, or undefined while the grammar is + * unavailable. + */ +export function contextSpans(run: SideRun, file: readonly string[], highlighter: CodeHighlighter): LineSpans | null | undefined { + const start = Math.max(1, run.first - HIGHLIGHT_CONTEXT_LINES) + if (start === run.first) return null + const context = file.slice(start - 1, run.first - 1).map(drawn) + const highlighted = highlighter([...context, ...run.texts].join('\n')) + if (highlighted === undefined) return undefined + // Shiki omits a final empty token row, so a final empty line gets no tokens. + return new Map(run.texts.map((_text, index) => [run.first + index, highlighted[context.length + index] ?? []])) +} + +/** Whole sides of a file: the new side as read, and the old side rebuilt from it. */ +export interface FileSides { + readonly old: readonly string[] + readonly new: readonly string[] +} + +/** + * Key of one side of a run, which the corrected tokens are kept under. + * @param run - the side of the run. + * @returns the key. + */ +export function runKey(run: SideRun): string { + return `${run.side}:${String(run.first)}:${String(run.last)}` +} + +const NO_SPANS: ReadonlyMap = new Map() + +/** Schedule work for an idle period, or soon where the browser offers none. */ +function whenIdle(work: () => void): () => void { + if (typeof requestIdleCallback === 'function') { + const handle = requestIdleCallback(work, { timeout: 2000 }) + return () => { cancelIdleCallback(handle) } + } + const handle = setTimeout(work, 16) + return () => { clearTimeout(handle) } +} + +/** Whether the reader holds a text selection inside an element. */ +function selectsIn(element: HTMLElement | null): boolean { + const selection = window.getSelection() + return element !== null && selection !== null && !selection.isCollapsed && element.contains(selection.anchorNode) +} + +/** + * Highlight each side of each run again with the lines before it, one side of one run per idle period, once the whole + * file is known. The tokens apply in one update when every run is done and only while the reader selects nothing + * inside `root`, since redrawn tokens would drop the selection; a selection or drag defers them until it ends. A run + * keeps its tokens while its lines stay the same, and a changed file starts over. + * @param runs - the sides of the drawn runs. + * @param sides - the whole file, or undefined while it is unknown. + * @param highlighter - the file's highlighter; a grammar that loads later resumes the work. + * @param root - the element whose selection defers the update. + * @param selecting - whether the reader is dragging a selection. + * @returns the corrected tokens by {@link runKey}. + */ +export function useContextHighlight( + runs: readonly SideRun[], sides: FileSides | undefined, highlighter: CodeHighlighter, + root: RefObject, selecting: boolean, +): ReadonlyMap { + const [applied, setApplied] = useState(NO_SPANS) + const shown = useRef(applied) + shown.current = applied + const cache = useRef<{ sides: FileSides | undefined; spans: Map }>({ sides: undefined, spans: new Map() }) + const pending = useRef | null>(null) + const held = useRef(selecting) + held.current = selecting + // Applies the pending tokens unless the reader is selecting, else tries again at each selection change until they apply. + const attempt = (): void => { + if (pending.current === null) return + if (held.current || selectsIn(root.current)) { + document.addEventListener('selectionchange', retry) + return + } + document.removeEventListener('selectionchange', retry) + setApplied(pending.current) + pending.current = null + } + const latest = useRef(attempt) + latest.current = attempt + const retry = useCallback((): void => { latest.current() }, []) + useEffect(() => () => { document.removeEventListener('selectionchange', retry) }, [retry]) + useEffect(() => { if (!selecting) retry() }, [selecting, retry]) + useEffect(() => { + if (sides === undefined) return + if (cache.current.sides !== sides) { + cache.current = { sides, spans: new Map() } + pending.current = null + setApplied(NO_SPANS) + } + const spans = cache.current.spans + const waiting = runs.filter(run => !spans.has(runKey(run))) + let cancel = (): void => {} + const finish = (): void => { + const done = new Map() + for (const run of runs) { + const value = spans.get(runKey(run)) + if (value !== undefined && value !== null) done.set(runKey(run), value) + } + // Tokens the view already shows need no update, which would redraw every row of the file. + const current = shown.current + if (done.size === current.size && [...done].every(([key, value]) => current.get(key) === value)) return + pending.current = done + retry() + } + const next = (at: number): void => { + const run = waiting[at] + if (run === undefined) { + finish() + return + } + cancel = whenIdle(() => { + const value = contextSpans(run, sides[run.side], highlighter) + // A grammar still loading leaves the rest to the highlighter that arrives with it. + if (value === undefined) return + spans.set(runKey(run), value) + next(at + 1) + }) + } + next(0) + return () => { cancel() } + }, [runs, sides, highlighter, retry]) + return applied +} diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 6d99a4dc02..b8c30f1e42 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -712,7 +712,8 @@ describe('ChangesTab local reads', () => { }) it('retains expanded context and the file node when an unchanged tab becomes visible again', async () => { - const m = mount() + // The read ahead for highlighting fails, so the lines after the last hunk stay of unknown length. + const m = mount({ setup: (faces) => { faces.localText.mockResolvedValueOnce(REFUSED.gone) } }) await settle() const section = m.section('src/app.ts') fireEvent.click(within(section).getByRole('button', { name: '2 unchanged lines' })) @@ -1066,8 +1067,10 @@ describe('ChangesTab layout', () => { describe('ChangesTab unchanged lines', () => { it('expands collapsed lines from the new side of the scope, reading each file once', async () => { - const m = mount() + // The read ahead for highlighting fails quietly, so the first expansion reads the file. + const m = mount({ setup: (faces) => { faces.localText.mockResolvedValueOnce(REFUSED.gone) } }) await settle() + expect(m.faces.report).not.toHaveBeenCalled() const app = m.section('src/app.ts') const gaps = (): string[] => [...app.querySelectorAll('[data-forge-diff-gap]')].map(gap => gap.textContent ?? '') expect(gaps()).toEqual(['2 unchanged lines', '4 unchanged lines', en['diff.unchangedRest']]) @@ -1083,7 +1086,7 @@ describe('ChangesTab unchanged lines', () => { fireEvent.click(within(app).getByRole('button', { name: '2 unchanged lines' })) await settle() expect(gaps()).toEqual([]) - expect(m.faces.localText).toHaveBeenCalledOnce() + expect(m.faces.localText).toHaveBeenCalledTimes(2) expect(rowTexts(app).slice(-2)).toEqual(['const t13 = 13', 'const t13 = 13']) }) @@ -1105,7 +1108,6 @@ describe('ChangesTab 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' }) @@ -1131,7 +1133,8 @@ describe('ChangesTab unchanged lines', () => { const m = mount({ setup: (faces) => { faces.localDiff.mockResolvedValue(ok({ base: BASE, files: [long], omitted: 0 })) - faces.localText.mockResolvedValue(ok(`${lines.join('\n')}\n`)) + // The read ahead for highlighting fails, so the lines after the hunk stay of unknown length. + faces.localText.mockResolvedValueOnce(REFUSED.gone).mockResolvedValue(ok(`${lines.join('\n')}\n`)) }, }) await settle() @@ -1142,10 +1145,53 @@ describe('ChangesTab unchanged lines', () => { expect(within(section).getByRole('group', { name: '38 unchanged lines' })).toBeTruthy() }) + it('reads a local file ahead once per comparison, quietly, to highlight rows with the lines before them', async () => { + const m = mount({ setup: (faces) => { faces.localText.mockResolvedValueOnce(REFUSED.gone) } }) + await settle() + expect(m.faces.localText).toHaveBeenCalledOnce() + expect(m.faces.localText).toHaveBeenCalledWith({ kind: 'branch', base: null, commits: null }, 'src/app.ts') + expect(m.faces.report).not.toHaveBeenCalled() + const app = m.section('src/app.ts') + fireEvent.click(within(app).getByRole('button', { name: 'Collapse app.ts' })) + fireEvent.click(within(app).getByRole('button', { name: 'Expand app.ts' })) + await settle() + expect(m.faces.localText).toHaveBeenCalledOnce() + }) + + it('counts the lines after the last hunk once the read ahead answers', async () => { + const m = mount() + await settle() + const gaps = [...m.section('src/app.ts').querySelectorAll('[data-forge-diff-gap]')].map(gap => gap.textContent) + expect(gaps).toEqual(['2 unchanged lines', '4 unchanged lines', '2 unchanged lines']) + expect(m.faces.localText).toHaveBeenCalledOnce() + }) + + it('keeps the lines an expansion read when the read ahead of the same file answers later', async () => { + const ahead = deferred>() + const m = mount({ setup: (faces) => { faces.localText.mockReturnValueOnce(ahead.promise) } }) + await settle() + const app = m.section('src/app.ts') + fireEvent.click(within(app).getByRole('button', { name: '2 unchanged lines' })) + await settle() + expect(rowTexts(app).slice(0, 2)).toEqual(['const a1 = 1', 'const a1 = 1']) + ahead.settle(ok(APP_TEXT)) + await settle() + expect(rowTexts(app).slice(0, 2)).toEqual(['const a1 = 1', 'const a1 = 1']) + expect(m.faces.localText).toHaveBeenCalledTimes(2) + }) + + it('reads no file of a change request ahead of an expansion', async () => { + const m = mount({ source: { kind: 'change', url: URL7 } }) + await settle() + expect(m.section('src/app.ts')).toBeTruthy() + expect(m.faces.changeRequestText).not.toHaveBeenCalled() + }) + it('reports a read that failed or no longer matches and keeps the lines collapsed', async () => { const m = mount({ setup: (faces) => { - faces.localText.mockResolvedValueOnce(REFUSED.gone).mockResolvedValueOnce(ok('changed\n')) + // The read ahead for highlighting fails quietly before the two reads the expansions make. + faces.localText.mockResolvedValueOnce(REFUSED.gone).mockResolvedValueOnce(REFUSED.gone).mockResolvedValueOnce(ok('changed\n')) }, }) await settle() @@ -1160,19 +1206,21 @@ describe('ChangesTab unchanged lines', () => { await settle() expect(m.faces.report).toHaveBeenLastCalledWith('toast.expandStale') expect(within(app).getByRole('button', { name: '2 unchanged lines' })).toBeTruthy() - expect(m.faces.localText).toHaveBeenCalledTimes(2) + expect(m.faces.localText).toHaveBeenCalledTimes(3) }) it('drops lines read for changes that a newer read replaced', async () => { const text = deferred>() - const m = mount({ setup: (faces) => { faces.localText.mockReturnValueOnce(text.promise) } }) + const m = mount({ setup: (faces) => { faces.localText.mockResolvedValueOnce(REFUSED.gone).mockReturnValueOnce(text.promise) } }) await settle() fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: '2 unchanged lines' })) fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) await settle() text.settle(ok(APP_TEXT)) await settle() - expect(within(m.section('src/app.ts')).getByRole('button', { name: '2 unchanged lines' }).hasAttribute('disabled')).toBe(false) + // The newer comparison reads the file ahead again, which also counts the lines after the last hunk. + const [leading] = within(m.section('src/app.ts')).getAllByRole('button', { name: '2 unchanged lines' }) + expect(leading?.hasAttribute('disabled')).toBe(false) expect(m.faces.report).not.toHaveBeenCalled() }) }) diff --git a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx index 100edf7403..67d43336bb 100644 --- a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx @@ -27,7 +27,8 @@ function mount(overrides: Partial = {}) { const records = new ReviewQueue('diff-review') const review: ReviewActions = { source, addToInput, records, onQuoted: (item) => { records.recordAgent(item) } } const handlers = { - toggle: vi.fn(), reveal: vi.fn(), expand: vi.fn(), view: vi.fn(), actions: () => [], section: vi.fn(), nextThread: vi.fn(), + toggle: vi.fn(), reveal: vi.fn(), expand: vi.fn(), readContext: vi.fn(), view: vi.fn(), actions: () => [], section: vi.fn(), + nextThread: vi.fn(), 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, diff --git a/packages/experimental/client-ui-forge/tests/highlight-context.client.spec.tsx b/packages/experimental/client-ui-forge/tests/highlight-context.client.spec.tsx new file mode 100644 index 0000000000..0936226874 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/highlight-context.client.spec.tsx @@ -0,0 +1,176 @@ +// @vitest-environment jsdom +/** Highlighting of drawn rows with the lines before them: the old side rebuilt, runs, context tokens, and idle updates. */ +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { CodeHighlighter } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ForgeDiffHunk } from '../src/types.ts' +import { hunkRows } from '../src/client/diff-rows.ts' +import { + contextSpans, HIGHLIGHT_CONTEXT_LINES, oldSideLines, runKey, sideRun, useContextHighlight, type FileSides, type SideRun, +} from '../src/client/highlight-context.ts' + +/** New side of a file whose hunks change lines 3–5 and delete one line after line 10. */ +const NEW_SIDE = ['a1', 'a2', 'a3', 'y', 'z', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 't12', 't13'] +const HUNKS: readonly ForgeDiffHunk[] = [ + { oldStart: 3, oldLines: 3, newStart: 3, newLines: 4, lines: [' a3', '-x', '+y', '+z', ' a5'] }, + { oldStart: 10, oldLines: 2, newStart: 11, newLines: 1, lines: [' a10', '-w'] }, +] + +/** A highlighter that colors each line by its index in the fragment and records the fragments it reads. */ +function recorder(): CodeHighlighter & { readonly calls: string[] } { + const calls: string[] = [] + const highlight = (code: string) => { + calls.push(code) + return code.split('\n').map((text, index) => [{ text, style: { color: `c${String(index)}` } }]) + } + return Object.assign(highlight, { calls }) +} + +afterEach(() => { + cleanup() + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +describe('oldSideLines', () => { + it('rebuilds the old side from the new side and the hunks, deletions and trailing lines included', () => { + expect(oldSideLines(NEW_SIDE, HUNKS)).toEqual(['a1', 'a2', 'a3', 'x', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'w', 't12', 't13']) + const deletion: ForgeDiffHunk = { oldStart: 2, oldLines: 1, newStart: 2, newLines: 0, lines: ['-gone', '\\ No newline at end of file'] } + expect(oldSideLines(['a', 'b'], [deletion])).toEqual(['a', 'gone', 'b']) + expect(oldSideLines(['a', 'b', 'c'], [{ oldStart: 3, oldLines: 0, newStart: 3, newLines: 1, lines: ['+c'] }])).toEqual(['a', 'b']) + }) +}) + +describe('sideRun', () => { + it('numbers a side of a run consecutively and has none for a side without lines', () => { + expect(sideRun(hunkRows(HUNKS[0]!), 'old')).toEqual({ side: 'old', first: 3, last: 5, texts: ['a3', 'x', 'a5'] }) + expect(sideRun(hunkRows(HUNKS[0]!), 'new')).toEqual({ side: 'new', first: 3, last: 6, texts: ['a3', 'y', 'z', 'a5'] }) + expect(sideRun(hunkRows({ oldStart: 1, oldLines: 0, newStart: 1, newLines: 1, lines: ['+n'] }), 'old')).toBeUndefined() + expect(runKey({ side: 'new', first: 3, last: 6, texts: [] })).toBe('new:3:6') + }) +}) + +describe('contextSpans', () => { + const run: SideRun = { side: 'new', first: 11, last: 12, texts: ['a10', 't12'] } + + it('highlights a run after the lines before it, without their carriage returns, and keeps only the run\'s tokens', () => { + const highlighter = recorder() + const spans = contextSpans(run, NEW_SIDE.map(line => `${line}\r`), highlighter) + expect(highlighter.calls).toEqual([[...NEW_SIDE.slice(0, 10), 'a10', 't12'].join('\n')]) + expect(spans).toEqual(new Map([[11, [{ text: 'a10', style: { color: 'c10' } }]], [12, [{ text: 't12', style: { color: 'c11' } }]]])) + }) + + it(`reads at most ${String(HIGHLIGHT_CONTEXT_LINES)} lines before a run`, () => { + const file = Array.from({ length: 400 }, (_, at) => `l${String(at + 1)}`) + const highlighter = recorder() + contextSpans({ side: 'old', first: 300, last: 300, texts: ['l300'] }, file, highlighter) + expect(highlighter.calls[0]?.split('\n')).toEqual([...file.slice(300 - HIGHLIGHT_CONTEXT_LINES - 1, 299), 'l300']) + }) + + it('has nothing to do for a run on the first line, waits for a grammar, and gives a final empty line no tokens', () => { + expect(contextSpans({ ...run, first: 1, last: 2 }, NEW_SIDE, recorder())).toBeNull() + expect(contextSpans(run, NEW_SIDE, () => undefined)).toBeUndefined() + expect(contextSpans({ side: 'new', first: 2, last: 3, texts: ['a2', ''] }, NEW_SIDE, code => code.split('\n').slice(0, -1).map(text => [{ text, style: {} }]))) + .toEqual(new Map([[2, [{ text: 'a2', style: {} }]], [3, []]])) + }) +}) + +describe('useContextHighlight', () => { + const SIDES: FileSides = { new: NEW_SIDE, old: oldSideLines(NEW_SIDE, HUNKS) } + const RUNS: readonly SideRun[] = [ + { side: 'new', first: 1, last: 6, texts: NEW_SIDE.slice(0, 6) }, + { side: 'old', first: 10, last: 11, texts: ['a10', 'w'] }, + ] + let root: HTMLDivElement + + beforeEach(() => { + vi.useFakeTimers() + vi.stubGlobal('requestIdleCallback', undefined) + root = document.createElement('div') + root.textContent = 'code' + document.body.append(root) + }) + + afterEach(() => { + root.remove() + window.getSelection()?.removeAllRanges() + }) + + interface HookProps { + readonly runs: readonly SideRun[] + readonly sides: FileSides | undefined + readonly highlighter: CodeHighlighter + readonly selecting: boolean + } + + function hook(initial: Partial = {}) { + const initialProps: HookProps = { runs: RUNS, sides: SIDES, highlighter: recorder(), selecting: false, ...initial } + const use = (props: HookProps) => useContextHighlight(props.runs, props.sides, props.highlighter, { current: root }, props.selecting) + return renderHook(use, { initialProps }) + } + + it('applies the tokens of the runs after other lines once each has had an idle turn', () => { + const { result } = hook() + expect(result.current.size).toBe(0) + act(() => { vi.advanceTimersByTime(16) }) + expect(result.current.size).toBe(0) + act(() => { vi.advanceTimersByTime(16) }) + expect([...result.current.keys()]).toEqual(['old:10:11']) + expect(result.current.get('old:10:11')?.get(11)).toEqual([{ text: 'w', style: { color: 'c10' } }]) + }) + + it('waits for the whole file and for a grammar, and starts over for another file', () => { + const { result, rerender } = hook({ sides: undefined }) + act(() => { vi.runAllTimers() }) + expect(result.current.size).toBe(0) + rerender({ runs: RUNS, sides: SIDES, highlighter: () => undefined, selecting: false }) + act(() => { vi.runAllTimers() }) + expect(result.current.size).toBe(0) + const highlighter = recorder() + rerender({ runs: RUNS, sides: SIDES, highlighter, selecting: false }) + act(() => { vi.runAllTimers() }) + expect(result.current.size).toBe(1) + // The same runs keep their tokens across a new highlighter, without a second read or an update. + const before = result.current + rerender({ runs: [...RUNS], sides: SIDES, highlighter: recorder(), selecting: false }) + act(() => { vi.runAllTimers() }) + expect(result.current).toBe(before) + expect(highlighter.calls).toHaveLength(1) + rerender({ runs: RUNS, sides: { ...SIDES }, highlighter, selecting: false }) + expect(result.current.size).toBe(0) + act(() => { vi.runAllTimers() }) + expect(result.current.size).toBe(1) + }) + + it('defers the update while the reader drags or selects text inside the file', () => { + const { result, rerender } = hook({ selecting: true }) + act(() => { vi.runAllTimers() }) + expect(result.current.size).toBe(0) + const range = document.createRange() + range.selectNodeContents(root) + window.getSelection()?.addRange(range) + rerender({ runs: RUNS, sides: SIDES, highlighter: recorder(), selecting: false }) + expect(result.current.size).toBe(0) + act(() => { document.dispatchEvent(new Event('selectionchange')) }) + expect(result.current.size).toBe(0) + window.getSelection()?.removeAllRanges() + act(() => { document.dispatchEvent(new Event('selectionchange')) }) + expect(result.current.size).toBe(1) + }) + + it('uses idle callbacks where the browser has them and cancels pending work when unmounted', () => { + const cancel = vi.fn() + const queued: (() => void)[] = [] + vi.stubGlobal('requestIdleCallback', (work: () => void) => queued.push(work)) + vi.stubGlobal('cancelIdleCallback', cancel) + const { result, unmount } = hook() + expect(queued).toHaveLength(1) + act(() => { queued[0]!() }) + act(() => { queued[1]!() }) + expect(result.current.size).toBe(1) + const again = hook({ sides: { ...SIDES } }) + again.unmount() + unmount() + expect(cancel).toHaveBeenCalled() + }) +})