Files
apes-sidebar/tests/text-editor-line-jump.spec.tsx
T
ymac 776e777da7 fix(editor): 落地到行时把光标亮出来,并让引用赢过预览的阅读位置(#826 收尾之四)
第一次真机手测反馈:跳转确实进了编辑视图,但**看不到光标**,所以不知道落在哪一行。
两个原因:

1. **没给编辑器焦点**。落地只 `dispatch({ selection })`,而 CodeMirror 只在
   **获焦**的编辑器里画光标,且零长度选择本身不画任何东西——未获焦的落地读起来
   就是「文件打开了,停在某处」。现在只在**行号引用**这条路上 `view.focus()`
   (普通打开不动读者的焦点,读者可能是从聊天输入框点的链接)。

2. **预览的阅读位置会覆盖它**。进入编辑态时那条「按预览滚动位置恢复」的副作用
   声明在落地之后,两个 effect 在同一次提交里,它会把选择与滚动重新写回读者
   刚才预览的地方——读者先在预览里滚动过,再点带行号的引用,跳转就被静默抹掉。
   落地前清掉 `previewSyncRef`:引用要的是源码里的那一行,不是预览里那个位置。

测试:text-editor-line-jump.spec.tsx 加 3 例(落地后 focus 被调用、普通打开不抢焦点、
markdown 翻转后仍获焦)+ 1 例判别性用例(预览滚到 90% 后再跳第 3 行,最后一次
dispatch 必须是第 3 行的 offset 8 而不是按比例算出的 14;去掉清空那行即红)。
2026-10-11 16:06:42 +08:00

193 lines
7.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Landing on the line a file reference named (#826 second half).
*
* `fileParamsOf` splits `path:131` off the address and the host hands its own
* `#L131` fragment down as `navigation.params.line`; before this, both landed
* on the record and then on nothing — the file opened and the reader stayed
* on line 1. The record's side is pinned in `tests/native-tab-line.spec.ts`;
* this file pins the last hop, into CodeMirror.
*
* The SCROLL write is deliberately not asserted: it rides two nested
* `requestAnimationFrame`s after a `lineBlockAt` measure, and jsdom lays
* nothing out (every block measures 0). What is asserted is the SELECTION the
* reveal dispatches — the same anchor the scroll positions, and unlike a
* scrollTop it is observable without layout.
*/
// @vitest-environment jsdom
import './browser-globals.ts'
import { act } from 'react-dom/test-utils'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { EditorView } from '@codemirror/view'
import type { TransactionSpec } from '@codemirror/state'
import type { Context } from '../src/context-types.ts'
import { TextEditor } from '../src/client/TextEditor.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import type { FileViewerProps } from '../src/client/service.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
const CTX = {} as Context
/** Four lines plus the empty one the trailing newline opens; the from-offset
* of line N is 4 × (N − 1), and the LAST line starts at 16. */
const CONTENT = 'aaa\nbbb\nccc\nddd\n'
const base = (overrides: Partial<FileViewerProps> = {}): FileViewerProps => ({
ctx: CTX,
store: createSidebarStore(),
scope: { sessionId: 's1', cwd: '/workspace' },
path: '/workspace/a.ts',
title: 'a.ts',
viewerId: 'code',
content: CONTENT,
toolbar: 'host',
...overrides,
})
describe('TextEditor lands on a referenced line', () => {
let root: Root | undefined
let container: HTMLDivElement | undefined
const anchors: number[] = []
const originalDispatch = EditorView.prototype.dispatch
const originalFocus = EditorView.prototype.focus
/** Whether the landing showed the caret (CodeMirror draws it only when the
* editor has focus, so an unfocused jump reads as "opened somewhere"). */
const focus = vi.fn()
beforeEach(() => {
anchors.length = 0
focus.mockClear()
vi.spyOn(EditorView.prototype, 'focus').mockImplementation(function (this: EditorView) {
focus()
return originalFocus.call(this)
})
// Record the selections the component dispatches, and let the real dispatch
// run: the reveal reads the document back out of the view right after
// writing to it.
vi.spyOn(EditorView.prototype, 'dispatch').mockImplementation(function (
this: EditorView,
transaction: TransactionSpec,
) {
const spec = transaction as { selection?: { anchor?: number } }
if (spec?.selection?.anchor !== undefined) anchors.push(spec.selection.anchor)
return originalDispatch.call(this, transaction)
})
})
const render = (overrides: Partial<FileViewerProps> = {}): HTMLDivElement => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
act(() => { root!.render(createElement(TextEditor, base(overrides))) })
return container
}
afterEach(() => {
act(() => { root?.unmount() })
container?.remove()
root = undefined
container = undefined
vi.restoreAllMocks()
})
it('selects the line the reference named', () => {
render({ line: 3 })
expect(anchors).toContain(8)
})
it('clamps a line past the end of the file to its last line', () => {
// A link can outlive the revision it was written against; it must land at
// the bottom rather than throw.
render({ line: 99 })
expect(anchors).toContain(16)
})
it('never jumps on an ordinary open', () => {
render()
expect(anchors).toEqual([])
})
it('flips a markdown file out of preview, where the line is reachable', () => {
// Preview renders no source lines to put a cursor on, and its own
// mount-time scroll restore would fight the jump — the reference asked for
// source, so the file opens in the editor.
const el = render({ viewerId: 'markdown', path: '/workspace/readme.md', line: 2 })
expect(anchors).toContain(4)
expect(el.querySelector('[class*="editorCmHidden"]')).toBeNull()
})
it('leaves a markdown file in preview when the reference named no line', () => {
const el = render({ viewerId: 'markdown', path: '/workspace/readme.md' })
expect(el.querySelector('[class*="editorCmHidden"]')).not.toBeNull()
})
it('lands once, not on every re-delivery of the same navigation', () => {
// The host keeps a visited tab body mounted and re-delivers its
// navigation on every store notification — a reader must not be yanked
// back to the same line each time.
const el = render({ line: 2 })
const after = anchors.length
act(() => { root!.render(createElement(TextEditor, base({ line: 2 }))) })
expect(anchors.length).toBe(after)
expect(el.querySelector('.cm-content')).not.toBeNull()
})
it('reports the navigation spent once, and only after the jump', () => {
// The host has to know when to stop handing the line out: it owns that
// memory, because a reload REMOUNTS this component (see
// tests/editor-line-nav-mode.spec.tsx). Reporting on the forced flip would
// spend it before the line ever landed.
const consumed = vi.fn()
render({ viewerId: 'markdown', path: '/workspace/readme.md', line: 2, onLineConsumed: consumed })
expect(consumed).toHaveBeenCalledTimes(1)
})
it('reports nothing on an ordinary open', () => {
const consumed = vi.fn()
render({ onLineConsumed: consumed })
expect(consumed).not.toHaveBeenCalled()
})
it('focuses the editor so the caret is visible where it landed', () => {
// Without focus CodeMirror paints no cursor at all and a zero-length
// selection paints nothing either, so the reader could not tell where the
// reference put them (reported from the first manual test).
render({ line: 3 })
expect(focus).toHaveBeenCalled()
expect(anchors).toContain(8)
})
it('does not steal focus on an ordinary open', () => {
render()
expect(focus).not.toHaveBeenCalled()
})
it('focuses after a markdown file is flipped out of preview (the editor is display:none until then)', () => {
render({ viewerId: 'markdown', path: '/workspace/readme.md', line: 2 })
expect(focus).toHaveBeenCalled()
})
it('a line reference beats the preview reading position it was scrolled to', () => {
// The flip's "enter edit where the reader was" effect is declared AFTER the
// landing and re-dispatches the preview-derived position, so a reader who
// had scrolled the preview first got their jump silently undone (the
// scroller was restored to where they came from).
const el = render({ viewerId: 'markdown', path: '/workspace/readme.md' })
const preview = el.querySelector('[data-dsh-md-surface]')!
Object.defineProperty(preview, 'scrollHeight', { configurable: true, value: 1000 })
Object.defineProperty(preview, 'clientHeight', { configurable: true, value: 100 })
Object.defineProperty(preview, 'scrollTop', { configurable: true, value: 810, writable: true })
// 90% down the preview: the proportional fallback alone would land on the
// LAST line (offset 14) — a different place from line 3 (offset 8).
act(() => { preview.dispatchEvent(new Event('scroll')) })
act(() => {
root!.render(createElement(TextEditor, base({ viewerId: 'markdown', path: '/workspace/readme.md', line: 3 })))
})
expect(anchors.at(-1)).toBe(8)
})
})