fix(forge): address review on file menu reveal and comment quote summaries

- Reveal the selected file again when files arrive or reorder around it,
  so a navigation that selects a file before the diff loads still scrolls
  the wide pane; a changed filter shows its results from the top.
- Compare quote summaries in draft change detection, so restoring a draft
  that only adds or changes a summary updates the snapshot and storage.
- Read the full path and range instead of the short label to assistive
  technology; the Web snapshot now records src/<file>.
- Type the stored summary schema against QuoteSummary, test the stored
  round trip, and document why revealRow does not use scrollIntoView.
This commit is contained in:
Yichen Jiang committed 2026-11-06 13:10:37 +08:00
1 parent 7a22c11866
commit 3c839748bd
13 files changed
+107 -18

No files matched your search

@@ -1,6 +1,6 @@
- textbox "发消息或创建任务, / 调用指令, @ 文件或对话":
- paragraph:
- button "移除引用"
- text: extra.ts R1 请检查这项修改
- text: src/extra.ts R1 请检查这项修改
- button "移除引用"
- text: app.ts R1 请解释这行代码
- text: src/app.ts R1 请解释这行代码
@@ -1,6 +1,7 @@
/** Semantic draft snapshots shared by storage, programmatic input, and editor restoration. */
import { z } from 'zod'
import { formatQuoteText } from '@deepseek-ai/dsh-client-ui-primitives'
import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives'
import type { DraftInput, DraftQuote, DraftReference, DraftSnapshot, Occurrence } from './contract/draft-editor.ts'
const referenceSchema = z.object({
@@ -18,11 +19,16 @@ const commandSchema = z.object({
token: z.string(),
})
// Lists every QuoteSummary field: parsing strips unknown keys, so a field missing here is dropped from restored drafts.
const quoteSummarySchema: z.ZodType<QuoteSummary> = z.object({
label: z.string(), title: z.string(), detail: z.string().optional(), body: z.string(),
})
const quoteSchema = z.object({
offset: z.number().int().nonnegative(),
length: z.number().int().positive(),
text: z.string().refine(text => text.trim() !== ''),
summary: z.object({ label: z.string(), title: z.string(), detail: z.string().optional(), body: z.string() }).optional(),
summary: quoteSummarySchema.optional(),
})
const snapshotSchema = z.object({
@@ -101,12 +101,17 @@ function frozen(phase: InputState['phase']): boolean {
}
/** Whether two projections differ in content (selection and caret excluded). */
function sameSummary(left: QuoteSummary | undefined, right: QuoteSummary | undefined): boolean {
return left === right || (left !== undefined && right !== undefined && left.label === right.label
&& left.title === right.title && left.detail === right.detail && left.body === right.body)
}
function projectionContentChanged(prev: EditorProjection, next: EditorProjection): boolean {
if (prev.clipboardText !== next.clipboardText || prev.detectText !== next.detectText) return true
if (prev.command !== next.command) return true
if (prev.quotes.length !== next.quotes.length || prev.quotes.some((quote, i) => {
const old = next.quotes[i]
return old?.text !== quote.text || old.offset !== quote.offset
return old?.text !== quote.text || old.offset !== quote.offset || !sameSummary(old.summary, quote.summary)
})) return true
if (prev.occurrences.length !== next.occurrences.length) return true
return next.occurrences.some((occ, i) => {
@@ -102,7 +102,7 @@ describe('QuoteNode composer lifecycle', () => {
const persisted = mirrored.at(-1)
expect(persisted).toEqual({ text: '> selected source text ', references: [], quotes: [{ offset: 0, length: 22, text: quote, summary }] })
const view = render(<QuoteNodeView editor={shell.editor} nodeKey="quote-key" text={quote} summary={summary} labels={{ remove: 'Remove quote' }} />)
expect(view.container.querySelector('[data-quote-preview-text]')?.textContent).toBe('index.ts L78 rename this')
expect(view.container.querySelector('[data-quote-preview-text]')?.textContent).toBe('index.ts L78src/index.ts L78 rename this')
view.unmount()
const restored = bench().shell
@@ -121,6 +121,26 @@ describe('QuoteNode composer lifecycle', () => {
await vi.waitFor(() => { expect(shell.snapshot.draft).toBe('') })
})
it('treats a summary added or changed at the same text and offset as a draft change', () => {
const summary = { label: 'index.ts L78', title: 'src/index.ts', detail: 'L78', body: 'rename this' }
const { shell } = bench()
const mirrored: DraftSnapshot[] = []
shell.bindDraftPersistence((document) => { mirrored.push(document) })
shell.insertQuote(quote)
const plain = shell.draftSnapshot
const revision = shell.snapshot.draftRev
shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary }] })
expect(shell.snapshot.draftRev).toBeGreaterThan(revision)
expect(shell.draftSnapshot.quotes).toEqual([{ offset: 0, length: 22, text: quote, summary }])
expect(mirrored.at(-1)?.quotes).toEqual([{ offset: 0, length: 22, text: quote, summary }])
shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary: { ...summary, body: 'keep this' } }] })
expect(shell.draftSnapshot.quotes?.[0]?.summary?.body).toBe('keep this')
shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary: { ...summary, body: 'keep this' } }] })
expect(shell.draftSnapshot.quotes?.[0]?.summary?.body).toBe('keep this')
shell.setDraft(plain)
expect(shell.draftSnapshot.quotes).toEqual([{ offset: 0, length: 22, text: quote }])
})
it('treats insert, close removal, Backspace, undo, and redo as whole-node operations', async () => {
const direct = bench().shell
direct.insertQuote(quote)
@@ -15,6 +15,17 @@ describe('quote draft spans', () => {
expect(parseStoredDraft({ ...draft, quotes: [quote, quote] })).toBeUndefined()
})
it('restores a stored quote summary and leaves summary-less drafts without one', () => {
const summary = { label: 'a.ts R1', title: 'src/a.ts', detail: 'R1', body: 'why' }
const draft = { text: '> quote', references: [], quotes: [{ offset: 0, length: 7, text: 'quote', summary }] }
expect(parseStoredDraft(JSON.parse(JSON.stringify(draft)))).toEqual(draft)
const { detail: _detail, ...withoutDetail } = summary
const brief = { ...draft, quotes: [{ offset: 0, length: 7, text: 'quote', summary: withoutDetail }] }
expect(parseStoredDraft(JSON.parse(JSON.stringify(brief)))).toEqual(brief)
expect(parseStoredDraft({ text: '> quote', references: [], quotes: [{ offset: 0, length: 7, text: 'quote' }] })?.quotes?.[0]?.summary).toBeUndefined()
expect(parseStoredDraft({ ...draft, quotes: [{ offset: 0, length: 7, text: 'quote', summary: { label: 'a.ts' } }] })).toBeUndefined()
})
it('serializes reference owners outside quotes into ordinary Markdown text', async () => {
const serialize = vi.fn(() => Promise.resolve('@[Session](dsh-session:id)'))
const quote = '/review @literal'
@@ -45,8 +45,8 @@
en: 45f4cd1ef96bb6d2
zh: f264d25b780ad1dc
/deepseek-ai-dsh-client-ui-primitives/further-exploration:
en: 025625ef07799f7d
zh: 4210f4eed382a553
en: 19f1407f92cb8264
zh: 16205d2db9c91ad1
/deepseek-ai-dsh-client-ui-primitives/model-experience:
en: 3120df665299c634
zh: 1d9f365d091d0d2a
+1 -1
View File
@@ -209,7 +209,7 @@ These pages place the atoms in the client stack and the design system.
-----
`QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text unless the owner supplies a `QuoteSummary`: its label and body then replace the inline excerpt, and the popover shows its title, optional detail, and body on every hover. Editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation.
`QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text unless the owner supplies a `QuoteSummary`: its label and body then replace the inline excerpt, assistive technology reads the title and optional detail in place of the label, and the popover shows its title, optional detail, and body on every hover. Editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation.
`MarkdownDelegate.getTriggerProps` receives explicit file, URL, or original-image targets and returns gesture props. File paths and line numbers are carried by callbacks. File mentions can supply `contextMenuProps`; `ImageLightbox.contextMenuProps` delegates the original image gesture. An image menu owns Escape and Tab while it holds focus, returning to the preview before closing it.
+1 -1
View File
@@ -209,7 +209,7 @@ kind: "package-library"
-----
`QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文,除非所有者提供 `QuoteSummary`:此时行内摘录改为显示其 label 和 body,每次悬停时弹层显示其 title、可选的 detail 和 body。可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。
`QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文,除非所有者提供 `QuoteSummary`:此时行内摘录改为显示其 label 和 body,辅助技术以 title 和可选的 detail 代替 label 朗读,每次悬停时弹层显示其 title、可选的 detail 和 body。可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。
`MarkdownDelegate.getTriggerProps` 接收明确的文件、链接或原图目标并返回手势 props。文件路径与行号通过回调传递。文件引用可提供 `contextMenuProps`;`ImageLightbox.contextMenuProps` 转发原图手势。图片菜单持有焦点时负责 Escape 与 Tab,先返回预览再关闭预览。
@@ -22,6 +22,15 @@
white-space: pre-wrap;
}
.visuallyHidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
}
.inlineBody {
color: var(--dsw-alias-label-secondary);
}
@@ -27,9 +27,9 @@ export interface QuotePreviewRemoval {
/** Owner-supplied readable form of a quote whose exact text is long structured content. */
export interface QuoteSummary {
/** Short inline label shown before `body` in place of the exact text. */
/** Short inline label shown before `body` in place of the exact text; assistive technology reads `title` and `detail` instead. */
readonly label: string
/** First popover line, such as a file path. */
/** First popover line, such as a file path; also the label's accessible text. */
readonly title: string
/** Secondary popover line, such as a line range. */
readonly detail?: string | undefined
@@ -39,7 +39,7 @@ export interface QuoteSummary {
/** Presentation inputs for one compact quote excerpt. */
export interface QuotePreviewProps {
/** Exact selected text rendered inline and exposed in a popover while clipped. */
/** Exact selected text rendered inline and exposed in a popover while clipped, unless `summary` replaces it. */
readonly text: string
/** Readable replacement for `text`: its label renders inline and its popover opens on every hover. */
readonly summary?: QuoteSummary | undefined
@@ -101,7 +101,13 @@ export function QuotePreview({ text, summary, removal }: QuotePreviewProps): JSX
</button>
)}
<span ref={sourceRef} className={css.source} data-quote-preview-text="">
{summary === undefined ? text : <>{summary.label} <span className={css.inlineBody}>{summary.body}</span></>}
{summary === undefined ? text : (
<>
<span aria-hidden="true">{summary.label}</span>
<span className={css.visuallyHidden}>{summary.detail === undefined ? summary.title : `${summary.title} ${summary.detail}`}</span>
{' '}<span className={css.inlineBody}>{summary.body}</span>
</>
)}
</span>
</span>
)
@@ -116,7 +116,9 @@ describe('QuotePreview', () => {
const text = '## User Comment 1\nFile: src/index.ts\nComment:\nrename this'
const view = render(<QuotePreview text={text} summary={{ label: 'index.ts L78', title: 'src/index.ts', detail: 'L78', body: 'rename this' }} />)
const quote = view.container.querySelector<HTMLElement>('[data-quote-preview]')!
expect(quote.querySelector('[data-quote-preview-text]')?.textContent).toBe('index.ts L78 rename this')
const inline = quote.querySelector('[data-quote-preview-text]')!
expect([...inline.children].map(part => [part.textContent, part.getAttribute('aria-hidden')]))
.toEqual([['index.ts L78', 'true'], ['src/index.ts L78', null], ['rename this', null]])
expect(view.queryByText(text)).toBeNull()
fireEvent.pointerEnter(quote)
await waitFor(() => {
@@ -126,6 +128,7 @@ describe('QuotePreview', () => {
view.unmount()
render(<QuotePreview text={text} summary={{ label: 'index.ts', title: 'src/index.ts', body: 'rename this' }} />)
expect(document.querySelector('[data-quote-preview-text]')?.children[1]?.textContent).toBe('src/index.ts')
fireEvent.pointerEnter(document.querySelector<HTMLElement>('[data-quote-preview]')!)
await waitFor(() => {
expect([...document.querySelector('[data-quote-popover]')!.children].map(line => line.textContent)).toEqual(['src/index.ts', 'rename this'])
@@ -5,7 +5,7 @@ import { FileTypeIcon, IconChevronDownOutlineRegular, IconFolderCloseRegular, In
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { ForgeDiffFile } from '../types.ts'
import { Counts } from './DiffFile.tsx'
import { changedFileTree, filterFileTree, type ChangedFileNode } from './file-tree.ts'
import { changedFileTree, filesInTreeOrder, filterFileTree, type ChangedFileNode } from './file-tree.ts'
import type { NS } from './locales.ts'
import css from './ChangedFiles.module.css'
@@ -64,6 +64,8 @@ function Rows({ nodes, depth, props }: {
/**
* Scroll only the row container to show a row that is not wholly visible; a visible row stays where it is.
* `scrollIntoView` would also scroll every scrollable ancestor, moving the menu card or the page behind it, and
* its `container` option is not yet supported widely enough, so the offset is measured here.
* @param container - the scrolling rows.
* @param row - the row to show.
* @param align - `center` places the row mid-view with its neighbors; `nearest` scrolls by the least distance.
@@ -85,10 +87,23 @@ function revealRow(container: HTMLElement, row: HTMLElement, align: 'center' | '
export function ChangedFiles(props: ChangedFilesProps): ReactNode {
const tree = useMemo(() => changedFileTree(props.files), [props.files])
const nodes = useMemo(() => filterFileTree(tree, props.state.query), [tree, props.state.query])
const order = useMemo(() => filesInTreeOrder(tree), [tree])
const selectedIndex = order.findIndex(file => file.path === props.state.selected)
const rows = useRef<HTMLDivElement>(null)
const query = useRef(props.state.query)
// A changed filter shows its results from the top.
useLayoutEffect(() => {
if (query.current === props.state.query) return
query.current = props.state.query
const container = rows.current
/* v8 ignore next -- the ref is attached before layout effects run. */
if (container === null) return
container.scrollTop = 0
}, [props.state.query])
const mounted = useRef(false)
// The toolbar menu mounts these rows at the top on every opening, so mounting centers the selected file;
// later file steps in the diff move the selection by the least distance.
// The toolbar menu mounts these rows at the top on every opening, so mounting centers the selected file. Later, a
// file step in the diff, or files arriving or reordering around a selection, scrolls by the least distance; a
// refresh that keeps the selected file's position leaves the reader's scroll alone.
useLayoutEffect(() => {
const align = mounted.current ? 'nearest' : 'center'
mounted.current = true
@@ -96,7 +111,7 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode {
const row = container?.querySelector<HTMLElement>('[aria-current="true"]')
if (container == null || row == null) return
revealRow(container, row, align)
}, [props.state.selected])
}, [props.state.selected, selectedIndex])
return <div className={css.root} data-forge-file-tree="">
<div className={css.search}><Input className={clsx(css.searchInput)} aria-label={props.t('diff.filterFiles')} placeholder={props.t('diff.filterFiles')}
value={props.state.query} onChange={(event) => { props.filter(event.target.value) }}
@@ -112,6 +112,20 @@ it('centers the selected file on each menu opening and then follows selection st
expect(rows().scrollTop).toBe(0)
select('c.ts')
expect(rows().scrollTop).toBe(0)
select('h.ts')
expect(rows().scrollTop).toBe(150)
pane.rerender(<ChangedFiles {...props} state={{ query: 'ts', collapsed: {}, selected: 'h.ts' }} />)
expect(rows().scrollTop).toBe(0)
pane.unmount()
// A navigation selects its file before the diff arrives; the rows then reveal it once they exist.
const early = render(<ChangedFiles {...props} files={[]} state={{ query: '', collapsed: {}, selected: 'h.ts' }} />)
expect(rows().scrollTop).toBe(0)
early.rerender(<ChangedFiles {...props} state={{ query: '', collapsed: {}, selected: 'h.ts' }} />)
expect(rows().scrollTop).toBe(150)
rows().scrollTop = 0
early.rerender(<ChangedFiles {...props} files={[...files]} state={{ query: '', collapsed: {}, selected: 'h.ts' }} />)
expect(rows().scrollTop).toBe(0)
})
it('bounds pointer and keyboard resizing, retains hidden width, and stops cancelled drags', () => {