merge fix/826-file-link-line-jump into dev(#826 第二半:行号不再被解析完就扔掉。两种写法合流到同一个字段——#L131 由宿主解析成 navigation.params.line、path:131 由插件在 path-line.ts 切出,都落到 SidebarTab.line,再经 FileViewerProps.line 交给 viewer;TextEditor 到达时定位一次并高亮,越界钳到最后一行,区间只取起始行。line 是瞬态(sanitizePersistedTab 白名单不含它,刷新不把读者拽回旧行);markdown/html 收到行号先强制切到编辑态再定位,避开预览自己的挂载滚动恢复。公开面是纯增量:FileViewerProps.line?: number)
# Conflicts: # docs/external-plugin-guide.md
This commit is contained in:
commit
45285014d9
11 files changed
+317
-5
No files matched your search
@@ -4,6 +4,9 @@
|
||||
|
||||
### Unreleased
|
||||
|
||||
- 🎯 **文件引用终于落到那一行([#826](https://github.com/omdsh-dev/DSH-better-sidebar/issues/826) 第二半)**:第一半把 `path:131` 的行号从地址上切了下来、文件能打开了,但行号**被解析出来就扔掉**——点开停在第 1 行。现在两种写法合流到同一个字段:`#L131` 由宿主解析成 `navigation.params.line`,`path:131` 由插件在 `src/client/path-line.ts` 切出,都落到 `SidebarTab.line`,再经 `FileViewerProps.line` 交给 viewer;文本编辑器在**到达时定位一次**并高亮该行,越界行号钳到最后一行,区间(`:起-止`)只取起始行、列号丢弃(编辑器只有一处光标)。定位直接写 `view.scrollDOM.scrollTop` 而不是 `scrollIntoView`——后者会走遍每一层可滚动祖先,浏览器缩放时连 window 都算上、把整个侧栏拖上去。**`line` 是瞬态**:`sanitizePersistedTab` 的白名单不含它(与 `revealed` 同处理),链接可能是几天前写的,刷新后不该把读者拽回那一行。**markdown / html 收到行号会先强制切到编辑态再定位**——预览里没有源码行号可放,而它自己挂载时的滚动恢复(`useLayoutEffect`)会和跳转抢同一个 `scrollTop`;引用要的是源码,所以让源码先可见。**公开面纯增量**:`FileViewerProps.line?: number`(§5 已同步),第三方 viewer 忽略它即可。原地把 `a.ts:131` 切到 `a.ts` 时行号会被**清掉**(更新路径比的是当前值而不是「有没有传」),否则每次通知都会把读者弹回去;同一引用重复投递不重复跳,同一文件的新行号照跳。
|
||||
- 🧪 测试:`tests/native-tab-line.spec.ts`(6 例:记录铸造 / 宿主 `#L` 片段 / 普通打开不种子 / 新导航改行 / **裸路径清行** / 重复投递保住记录身份)、`tests/text-editor-line-jump.spec.tsx`(6 例:落到指定行 / 越界钳位 / 普通打开不跳 / **markdown 强制切出预览** / 无行号留在预览 / 只落一次),`tests/native-surface.spec.ts` 的 `fileParamsOf` 断言补上 `line` 并加区间与 `行:列` 两例。scroll 那一步刻意不断言(骑在两层嵌套 rAF 之后、且 jsdom 不排版),断言的是同一次 dispatch 的 selection anchor。(贡献者 PR [#865](https://github.com/omdsh-dev/DSH-better-sidebar/pull/865) @yanzhaohui1999)
|
||||
|
||||
- 🖥️ **桌面壳里插件路由不再满屏「Failed to fetch」**:HTTP 与 WebSocket 需要**不同**基址,而壳正是把两者拉开的地方——页面在 `dsh-app://app/`,注入的 `__DSH_TRANSPORT__.streamBaseUrl` 却是宿主的 `http://127.0.0.1:<port>`(另一个 origin)。壳的 `protocol.handle` 会把非静态的 `dsh-app://app/*` 路径**同源转发**给宿主,所以 HTTP 必须骑**页面基址**(`hostHttpBase()` → `document.baseURI`,反代目录前缀也带在里面,一套规则覆盖两种部署);发到注入 origin 就是跨源,而插件自己的 `/sidebar/*` 路由不带 `Access-Control-Allow-*`,浏览器直接拒(文件树 / git / 编辑器全部请求失败)。WebSocket 反过来,必须用注入 origin:自定义 scheme 承载不了 `ws:`,而 `dsh-app://app` 的 host 是字面量 `app`,DNS 永远不解析。`tests/base-path.spec.ts` 钉住三种场景(壳内页面基址 + 注入 origin 的 socket、无页面基址时回退注入基址、普通 http 页面同源不变)。
|
||||
- 👁️ **被 park 过的编辑器不再是一片空白**:原生页签在宿主里靠 `keepMounted` 存活,宿主把不活跃的 body **移动**进隐藏 seat、需要时再移回来——而移动一个节点**不改变它的 border box**,所以只看尺寸变化的 `ResizeObserver` 一次都不触发,一个在隐藏宿主里被打开的编辑器会把视口量成 0 并把这个空的虚拟视口一直留着(症状很有辨识度:**行号槽照常画,正文空白**)。现在每次「显现」都重新测量:`IntersectionObserver` 报显现本身(补上移动这条 ResizeObserver 看不见的路径),`requestAnimationFrame` 兜住「显现与挂载同帧」的那一次(此时 CodeMirror 的首次测量仍可能读到 0),另接 `visibilitychange` 与 `window` resize;四种观察器都可缺省、逐个 dispose,旧浏览器/测试环境不受影响。
|
||||
- 🛡️ **会话切换不再把上一个项目的写操作带进新项目([#848](https://github.com/omdsh-dev/DSH-better-sidebar/issues/848))**:右侧栏的每个 page 都按「会话 + 页签 id」**复用同一个组件实例**,而页签 id 每会话重新计数——换会话(或换 cwd)时组件是**原地重渲染**而不是重挂,于是上一个项目里选中的行、打开的行菜单、内联重命名/新建编辑器、以及**已经弹出来的删除确认框**都会活到下一个项目里。最危险的是选中集:「删除选中」会把**新会话的 scope 配上一个会话的绝对路径**发给宿主,而 v0.23.0 起包含性检查是刻意移除的,宿主对绝对路径照单执行——**它会删掉另一个项目的文件**。现在这些状态随会话与 cwd 一起失效(选中集、锚点、行菜单、内联编辑器、确认框、拖拽落点、busy 标志、错误条),批量删除与打包构建按 generation 捕获自己的 scope、并把**结算**(pruneTree / 选中集 / busy / 任务条)在换代后退役(它们结算的是「在屏项目」的状态,已经不一定是自己开始的那个项目了)。
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
| 内置类型接管 | 插件的 `editor` 类型以 `extension` 优先级认领 `dsh-resource://file/**`(压过内置 `ui-sidebar-documentpreview` 的 `text` 预览——即 `fallback` 带),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件的文件树);插件卸载/禁用时内置实现自动复位。**但认领是有选择的**:宿主自己的文档预览已经覆盖的格式(表格 / PDF / 图片 / Office,清单见 §5.4)由 `editor.canOpen` 主动**拒绝**,地址交回内置 `text` 档 |
|
||||
| 文件树实时刷新(v0.21.1+) | 插件接管了内置 `files` 页,所以宿主自己的按目录 watch 覆盖不到这棵树——插件自带一条 `/sidebar/ws/fs-watch` socket:客户端上报**已展开**的目录集,宿主侧按目录 `fs.watch`(150ms 去抖、每连接上限 64 个句柄),变动后只让那一层缓存失效并重列;目录折叠即退订。路径仍走 `fs.tree` 同一套词法解析 |
|
||||
| 编辑器预览自动刷新(#855) | 模型在会话里改完文件后,**正在看的那个预览**自己刷新,不必再手点刷新或重开文件。信号是插件自有的会话事件增量流 `changes.ops`(宿主 `src/index.ts` 路由),**每会话一个共享轮询器**(N 个编辑器 tab 每 tick 仍只有 1 个请求,全部隐藏即停;**叠加口径**:文件变动页的会话透镜有它自己的轮询器,两者同开时该会话每 tick 是 **2 个** `changes.ops` 请求,「1 个」只算编辑器这一份),**不新增 fs.watch / fsRead 指纹轮询**。只有 `write` / `edit` **结算成功**且路径命中本页文件的那些调用会触发重载(走既有的 `fsRead`/`load` 路径),未命中的文件零重读;**dirty 草稿与编辑态一律跳过**(脏态优先)。第三方 viewer 要保住自己的草稿就必须如实上报 `onToolbarState.dirty` / `mode`,见 §5.2 |
|
||||
| 地址里的行号(#826) | 宿主的 markdown 链接语法只认 GitHub 的 `#L131` 片段,`path:131` 形式(编译器诊断 / `grep` 的写法,模型输出很常见)会被当成**文件名的一部分**送进地址。插件的 `editor` 类型在把地址转成合成记录时把尾部行号规格(`:行` / `:起-止` / `:行:列`)切掉,tab 标题同样按切完的文件名给——否则点开就是一个报「文件不存在」的 `x.c:131`。切分只在这一步发生(`src/client/path-line.ts`),文件树 / 搜索 / 插件自有流程的路径不经过它;代价是**从聊天链接**打开一个真名以 `:数字` 结尾的文件会丢掉后缀(Windows 上 `:` 本就不是合法文件名字符) |
|
||||
| 地址里的行号(#826) | 宿主的 markdown 链接语法只认 GitHub 的 `#L131` 片段,`path:131` 形式(编译器诊断 / `grep` 的写法,模型输出很常见)会被当成**文件名的一部分**送进地址。插件的 `editor` 类型在把地址转成合成记录时把尾部行号规格(`:行` / `:起-止` / `:行:列`)切掉,tab 标题同样按切完的文件名给——否则点开就是一个报「文件不存在」的 `x.c:131`。切分只在这一步发生(`src/client/path-line.ts`),文件树 / 搜索 / 插件自有流程的路径不经过它;代价是**从聊天链接**打开一个真名以 `:数字` 结尾的文件会丢掉后缀(Windows 上 `:` 本就不是合法文件名字符)。行号随后顺着记录一路走到 viewer:两种写法落到**同一行**(`#L131` 由宿主解析成 `navigation.params.line`,`path:131` 由插件切出来,两者合流到 `SidebarTab.line`),文本编辑器在**到达时定位一次**并高亮该行,越界行号钳到最后一行。区间只取起始行、列号丢弃——编辑器只有一处光标。`line` 是**瞬态**:`sanitizePersistedTab` 的白名单不含它,刷新后不会把读者拽回几天前的那一行。markdown / html 收到行号时会**强制切到编辑态**再定位(预览里没有源码行号可放,而它自己的挂载滚动恢复也会和跳转打架)——引用要的是源码 |
|
||||
| 链接接管(v0.21.1+) | DOM 层只接管**有类型通过 `urlTarget` 声明认领**的外链(Ctrl/Cmd/Shift/Alt 点击一律放行);一个都没认领到时**不阻止默认行为**,交回宿主。见 §4.1 的 `urlTarget` |
|
||||
| path 种子的去向(v0.19.2+) | `path` seed 的含义**跟随类型**:只有 `editor`(唯一认领 `dsh-resource://file/**` 的类型)把 path 转成资源地址打开(文件落在编辑器);**其余类型保留页面型打开**,path 随导航 params 落到合成记录的 `tab.path` 供组件消费——组件型 tab 的 path seed 不会被改道到文件编辑器(v0.19.0/0.19.1 上一切 path seed 都被改道,组件从未挂载,#632) |
|
||||
| 文件打开的认领判定 | 插件自己的一切文件入口(文件树点击 / 路径输入 / 文件变动页 / 「新标签页打开」,合并与分屏两种模式)都先问宿主原生 tab 注册表:`ctx.sidebarRightTabs.candidates(address)` 的头名若不是本插件的 `editor`,地址改走 `ctx.sidebarRight.openResource`,由**认领类型**渲染自己的 tab——第三方直接在宿主注册表按更具体 glob 注册的原生类型(如 `.drawio` 画板)从此在文件树里点得开(#695);无人认领、宿主无注册表或探测失败时行为逐字保持原样(落到 `editor` / code 兜底) |
|
||||
|
||||
@@ -613,6 +613,10 @@ export function EditorHost(props: {
|
||||
{!showEmpty && load.status === 'ready' && createElement(load.viewer.component, {
|
||||
ctx, store, scope, path, title,
|
||||
viewerId: load.viewer.id,
|
||||
// The reference's landing line, if the address carried one (#826).
|
||||
// Only the text viewer acts on it; a markdown/html/image viewer
|
||||
// gets the field and ignores it.
|
||||
line: tab.line,
|
||||
content: load.content,
|
||||
truncated: load.truncated,
|
||||
mtimeMs: load.mtimeMs,
|
||||
|
||||
@@ -72,7 +72,7 @@ function sameDocument(a: string, b: string): boolean {
|
||||
}
|
||||
|
||||
export function TextEditor(props: FileViewerProps) {
|
||||
const { ctx, scope, path, viewerId, content, truncated } = props
|
||||
const { ctx, scope, path, viewerId, content, truncated, line } = props
|
||||
const [mode, setMode] = useState<ViewMode>('preview')
|
||||
/** The editor's current text (null while clean); preview renders this. */
|
||||
const [draft, setDraft] = useState<string | null>(null)
|
||||
@@ -389,6 +389,60 @@ export function TextEditor(props: FileViewerProps) {
|
||||
}
|
||||
}, [content, path])
|
||||
|
||||
/** The landing line already honoured, as `${path}#${line}`. The host keeps a
|
||||
* visited tab body mounted (`keepMounted`) and re-delivers its navigation on
|
||||
* every store notification, so without this a reader would be yanked back to
|
||||
* the same line each time — while a NEW line on the SAME file must land. */
|
||||
const landedAtRef = useRef<string | null>(null)
|
||||
|
||||
// Land on the line a file reference named (`a/b.c#L131`, `a/b.c:131` — #826).
|
||||
// One-shot per (file, line): an ordinary open carries no line and never
|
||||
// fires, and a fresh reference re-fires it.
|
||||
useEffect(() => {
|
||||
if (line === undefined) {
|
||||
landedAtRef.current = null
|
||||
return
|
||||
}
|
||||
if (content === undefined) return
|
||||
const view = viewRef.current
|
||||
if (view === null) return
|
||||
const key = `${path}#${line}`
|
||||
if (landedAtRef.current === key) return
|
||||
// A markdown/html file opens in preview, which has no source lines to put
|
||||
// a cursor on. The reference asked for source, so land in the editor; the
|
||||
// key is NOT recorded yet, so the re-run after the flip does the jump.
|
||||
if ((markdown || html) && mode === 'preview') {
|
||||
setMode('edit')
|
||||
return
|
||||
}
|
||||
landedAtRef.current = key
|
||||
// Out-of-range references clamp to the last line rather than throwing —
|
||||
// the file can have changed since the link was written.
|
||||
const doc = view.state.doc
|
||||
const target = doc.line(Math.min(Math.max(line, 1), doc.lines)).from
|
||||
// Position by writing the editor's OWN scroller (after a fresh measure)
|
||||
// instead of CodeMirror's scrollIntoView: that path walks every scrollable
|
||||
// ancestor — and even the window when the browser is zoomed
|
||||
// (visualViewport < innerHeight) — which dragged the whole sidebar up when
|
||||
// the reader was at the very end of the document. A plain scrollTop write
|
||||
// on the editor scroller can never touch anything outside the editor.
|
||||
view.requestMeasure()
|
||||
view.dispatch({ selection: { anchor: target } })
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
const block = view.lineBlockAt(target)
|
||||
view.scrollDOM.scrollTop = Math.max(0, block.top - 8)
|
||||
// CodeMirror's scroll-observer is async and can lag a direct write, so
|
||||
// force a re-measure at the NEW scroll position or the virtualized
|
||||
// viewport keeps rendering the old one.
|
||||
view.requestMeasure()
|
||||
})
|
||||
})
|
||||
// The reveal reads the live view ref; `markdown`/`html` are derived from
|
||||
// `viewerId`, which the view-creation effect already keys on.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [content, path, line, mode])
|
||||
|
||||
// Scheme flip: re-theme in place (the compartment holds only the
|
||||
// scheme-dependent extensions; everything else is untouched).
|
||||
useEffect(() => {
|
||||
|
||||
@@ -171,6 +171,13 @@ interface Registration {
|
||||
* file called `b.c:131` and the editor reports it missing (#826). The tab
|
||||
* TITLE is seeded from the same spec, because the host derives it from the same
|
||||
* string and would otherwise label the tab `b.c:131`.
|
||||
*
|
||||
* The LINE rides along in the same seed. DSH's own `#L131` form already
|
||||
* arrives as `navigation.params.line` (the host parses it and sends it down),
|
||||
* so seeding it here is what makes both spellings land on the same row — see
|
||||
* {@link NativeTabParams.line}. The range end and the column are deliberately
|
||||
* dropped: {@link splitTrailingLineSpec} parses them, and a start line is all
|
||||
* the editor has anywhere to put a cursor.
|
||||
* @param info - the native tab record the body is drawing.
|
||||
* @returns the seed, or `undefined` when the tab is not a file address.
|
||||
*/
|
||||
@@ -179,7 +186,7 @@ export function fileParamsOf(info: NativeTabInfo): NativeTabParams | undefined {
|
||||
if (address === undefined) return undefined
|
||||
const spec = splitTrailingLineSpec(address.path)
|
||||
if (spec === undefined) return { path: address.path }
|
||||
return { path: spec.path, title: baseName(spec.path) }
|
||||
return { path: spec.path, title: baseName(spec.path), line: spec.line }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -262,6 +262,7 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
type: kind as TabType,
|
||||
title: params?.title ?? seeded?.title ?? title,
|
||||
...(path === undefined ? {} : { path }),
|
||||
...(params?.line === undefined ? {} : { line: params.line }),
|
||||
...(params?.diff === undefined ? {} : { diff: params.diff }),
|
||||
...(meta === undefined ? {} : { meta }),
|
||||
},
|
||||
@@ -286,6 +287,12 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
const patch: Partial<SidebarTab> = {}
|
||||
const nextPath = params?.path ?? params?.url
|
||||
if (nextPath !== undefined && nextPath !== existing.tab.path) patch.path = nextPath
|
||||
// The landing line clears as well as sets: an in-place switch from
|
||||
// `a.c:131` to a bare `a.c` must not leave the old line behind and jump
|
||||
// the reader back there. Compared against the current value so the
|
||||
// common case (both absent) adds nothing to the patch and the record
|
||||
// keeps its identity.
|
||||
if (params?.line !== existing.tab.line) patch.line = params?.line
|
||||
if (params?.diff !== undefined) patch.diff = params.diff
|
||||
if (revision !== undefined && navigationRevisions.get(key) !== revision) {
|
||||
navigationRevisions.set(key, revision)
|
||||
|
||||
@@ -308,6 +308,11 @@ export interface FileViewerProps {
|
||||
title: string
|
||||
/** The matching descriptor's id (`'code'`, `'my-plugin:csv'`). */
|
||||
viewerId: string
|
||||
/** The 1-based line the tab's file reference named, when it carried one
|
||||
* (`a/b.c#L131`, `a/b.c:131` — see #826). A viewer that renders text
|
||||
* positions the reader there once, on arrival; every other viewer ignores
|
||||
* it. Absent on an ordinary open. */
|
||||
line?: number
|
||||
/** fsRead text content (fetchStrategy='fsRead'). */
|
||||
content?: string
|
||||
truncated?: boolean
|
||||
|
||||
@@ -32,6 +32,13 @@ export interface SidebarTab {
|
||||
type: TabType
|
||||
title: string
|
||||
path?: string
|
||||
/** The 1-based line a file reference named (`a/b.c#L131`, `a/b.c:131`).
|
||||
* Transient by design: `sanitizePersistedTab` copies a whitelist of known
|
||||
* fields, and this one is deliberately left out — a link's landing line is
|
||||
* a one-shot navigation target, and a reload that yanked the reader back
|
||||
* to a line they scrolled away from days ago would be worse than starting
|
||||
* at the top. Same spirit as `revealed`. */
|
||||
line?: number
|
||||
diff?: SidebarDiffRef
|
||||
/** Plugin-owned state (v0.12.0+): MUST be JSON-serializable — it is
|
||||
* persisted with the layout and restored verbatim on reload. */
|
||||
|
||||
@@ -209,16 +209,27 @@ describe('fileParamsOf (the file-address seed, #826)', () => {
|
||||
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/main.ts'))).toEqual({ path: 'src/main.ts' })
|
||||
})
|
||||
|
||||
it('splits a `path:line` spec off the address and titles the tab after the file', () => {
|
||||
it('splits a `path:line` spec off the address, titles the tab after the file and keeps the line', () => {
|
||||
// This is the #826 case: DSH reads a `#`-less markdown destination as the
|
||||
// file name verbatim, so the address arrives naming `CMakeLists.txt:131`
|
||||
// and the editor would read a file that does not exist.
|
||||
// and the editor would read a file that does not exist. The line rides
|
||||
// along in the same seed so the editor can land on it (#826 second half).
|
||||
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/omlx/csrc/CMakeLists.txt:131'))).toEqual({
|
||||
path: 'omlx/csrc/CMakeLists.txt',
|
||||
title: 'CMakeLists.txt',
|
||||
line: 131,
|
||||
})
|
||||
})
|
||||
|
||||
it('seeds only the FIRST line of a range or a line:column spec', () => {
|
||||
// The editor has nowhere to put a second cursor; the start line is the
|
||||
// one a reader can act on.
|
||||
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/main.ts:40-60')))
|
||||
.toMatchObject({ path: 'src/main.ts', line: 40 })
|
||||
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/main.ts:40:7')))
|
||||
.toMatchObject({ path: 'src/main.ts', line: 40 })
|
||||
})
|
||||
|
||||
it('keeps a colon-carrying name that is not a line spec', () => {
|
||||
expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/data:2024.csv'))).toEqual({ path: 'data:2024.csv' })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The landing line a file reference carries (`a/b.c#L131`, `a/b.c:131`).
|
||||
*
|
||||
* `fileParamsOf` already split the `path:line` form off the address (#826
|
||||
* first half, `src/client/path-line.ts`); what is left — the second half — is
|
||||
* that nothing CONSUMED the line it parsed. `NativeTabParams.line` was
|
||||
* declared, the host's own `#L131` fragment already arrives as
|
||||
* `navigation.params.line`, and the record simply dropped both on the floor,
|
||||
* so `[path](path:131)` opened the file and left the reader on line 1.
|
||||
*
|
||||
* These assertions are on the RECORD's event surface, not on the editor's
|
||||
* pixels: the record is what carries the line from the address to the viewer,
|
||||
* and it is where a stale line would survive (the host keeps a visited tab
|
||||
* body mounted and re-delivers its navigation, so "just put it in the record"
|
||||
* is only half of it — the record must also let it go again).
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx'
|
||||
|
||||
describe('the landing line on a native tab record (#826)', () => {
|
||||
const records = createNativeTabRecords()
|
||||
const scope = { sessionId: 's1', cwd: '/work' }
|
||||
|
||||
const ensure = (params: { path?: string; title?: string; line?: number } | undefined, revision?: number) =>
|
||||
records.ensure({
|
||||
sessionId: 'seat-1',
|
||||
id: 'tab-1',
|
||||
kind: 'editor',
|
||||
title: 'CMakeLists.txt',
|
||||
params,
|
||||
scope,
|
||||
revision,
|
||||
}).tab
|
||||
|
||||
it('seeds the line a `path:line` address named', () => {
|
||||
const tab = ensure({ path: 'omlx/CMakeLists.txt', title: 'CMakeLists.txt', line: 131 })
|
||||
expect(tab.path).toBe('omlx/CMakeLists.txt')
|
||||
expect(tab.line).toBe(131)
|
||||
})
|
||||
|
||||
it('carries the host’s own `#L131` fragment the same way', () => {
|
||||
// The host parses `path#L131` and hands it down as a navigation param;
|
||||
// both spellings must land on the same row, so both take this one field.
|
||||
expect(ensure({ path: 'omlx/CMakeLists.txt', line: 131 }).line).toBe(131)
|
||||
})
|
||||
|
||||
it('seeds no line on an ordinary open', () => {
|
||||
expect(ensure({ path: 'src/main.ts' }).line).toBeUndefined()
|
||||
})
|
||||
|
||||
it('re-seeds the line when a new navigation moves it', () => {
|
||||
records.ensure({
|
||||
sessionId: 'seat-1', id: 'tab-2', kind: 'editor', title: 'a.ts',
|
||||
params: { path: 'a.ts', line: 10 }, scope, revision: 1,
|
||||
})
|
||||
const moved = records.ensure({
|
||||
sessionId: 'seat-1', id: 'tab-2', kind: 'editor', title: 'a.ts',
|
||||
params: { path: 'a.ts', line: 90 }, scope, revision: 2,
|
||||
})
|
||||
expect(moved.tab.line).toBe(90)
|
||||
})
|
||||
|
||||
it('CLEARS the line when the same tab is navigated to a bare path', () => {
|
||||
// An in-place switch from `a.ts:131` to `a.ts` must not leave 131 behind:
|
||||
// the reader asked for the file, not for that line of it.
|
||||
records.ensure({
|
||||
sessionId: 'seat-1', id: 'tab-3', kind: 'editor', title: 'a.ts',
|
||||
params: { path: 'a.ts', line: 131 }, scope, revision: 1,
|
||||
})
|
||||
const bare = records.ensure({
|
||||
sessionId: 'seat-1', id: 'tab-3', kind: 'editor', title: 'a.ts',
|
||||
params: { path: 'a.ts' }, scope, revision: 2,
|
||||
})
|
||||
expect(bare.tab.line).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the record identity when the navigation repeats unchanged', () => {
|
||||
// The host re-delivers the last navigation on every store notification;
|
||||
// an unchanged line must not mint a new record (a new object identity is
|
||||
// what re-renders every kept-mounted body).
|
||||
const first = ensure({ path: 'a.ts', line: 5 }, 1)
|
||||
const again = ensure({ path: 'a.ts', line: 5 }, 1)
|
||||
expect(again).toBe(first)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 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
|
||||
|
||||
beforeEach(() => {
|
||||
anchors.length = 0
|
||||
// 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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user