diff --git a/CHANGELOG.md b/CHANGELOG.md index 0885ecd3..38ac3689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ ### Unreleased +- 🔁 **引用行号的四处收尾([#826](https://github.com/omdsh-dev/DSH-better-sidebar/issues/826) 后续)**:上一批把行号接进了编辑器,真机手测与代码审计在这条路上又抓到四类问题,一并收掉。 + - **跳转后回不到预览**:`line` 的「已消费」记忆原本在 **viewer 组件实例**里,而 `EditorHost` 每次 reload 都用 loading 行把 viewer 整个重建——重建出的实例 `mode` 回到 `preview`、记忆为空,于是同一条行号再次强制切编辑;**而「预览」按钮本身就会 reload**(#167 part B 的编辑→预览重载),所以读者点下去必然被切回去,页头刷新 / #855 自动刷新 / 预览态保存后的刷新同理。记忆改由**宿主**持有(它比 viewer 活得久):viewer 落地后回调 `onLineConsumed()`,`EditorHost` 记住已消费的 `${path}#${line}` 并停止再下发(换文件清空、换行号自然重置)。公开面纯增量:`FileViewerProps.onLineConsumed?: () => void`。 + - **插件自绘的预览里点 `#L131` 根本不跳行**:`MarkdownDelegate.openFile(path, { line })` 收到的行号只被当成「这是行号不是标题锚点」的判据,随后在 `use-markdown-surface` → `openSidebarFile` → `openTab` 三跳里被丢掉(种子没有 `line` 字段、原生分支的 `surface.openResource` 也没传,而末跳 `src/client/native/surface.ts` 本来就支持)。现在补齐三跳,并新增 `lineOfHostFragment` 兜住只有 destination 的调用方(区间取起始行);四处插件自绘 markdown(编辑器预览 / 侧边对话转录 / 文件变动阅读窗 / 任务窗口)从此与聊天正文行为一致:**跳到那一行 + 离开预览**。 + - **换文件会继承上一个文件的行号**:`updateTab` 的补丁只有 title/path/meta,合并模式在页头换文件、以及文件树里重命名打开的文件,都把上一个文件的行号留在记录里——新文件跳到旧行号,markdown 还被拉进编辑态(与 reload 那条同症状,触发点不同)。规则统一成「**改 path 就是一次新的打开**」,两个记录层(`patchTab` 与原生 `records.update`)都清掉瞬态行号;只改 title / meta 的补丁不动它。 + - **落地没有光标,还会被预览的阅读位置覆盖**:落地只 `dispatch({ selection })`,而 CodeMirror **只在获焦的编辑器里画光标**、零长度选择本身什么都不画——文件短时一页装得下又没有光标,读者无从判断落在哪。且「进入编辑态按预览滚动位置恢复」那条副作用**声明在落地之后**,同一次提交里会把选择与滚动重新写回读者刚才预览的位置:先在预览里滚动、再点带行号的引用,跳转被静默抹掉。现在行号引用这条路上 `view.focus()`(普通打开不动读者焦点,他可能正从聊天输入框点链接),并在落地前清空 `previewSyncRef`。 + - 🧪 测试:新增 `tests/editor-line-nav-mode.spec.tsx`(4 例,**真 `TextEditor` 过真 `EditorHost`**:落地后能切回预览 / 页头刷新不回弹 / 同文件新行号仍落地 / 换文件不继承行号),`tests/text-editor-line-jump.spec.tsx` +6(落地获焦 / 普通打开不抢焦点 / markdown 翻转后仍获焦 / 消费契约两例 / 预览位置覆盖),`tests/markdown-surface.spec.tsx` +2(真实宿主 `MarkdownText` 下点 `#L42` 与 `#L20-L25` 进记录、标题锚点仍只走 parked 片段),`tests/native-tab-line.spec.ts` +2(换 path 清行号 / 只改 title 保留),`tests/markdown-navigation.spec.ts` +1(`lineOfHostFragment`),`tests/file-open-claim.spec.ts` +1(种子透传与「不传就不带这个键」)。判别性:去掉 `previewSyncRef` 清空 → 预览覆盖用例红(期望第 3 行的 offset 8、实得按比例算出的 14);去掉两个记录层的清行号 → 对应两条红。(回归报告 [#914](https://github.com/omdsh-dev/DSH-better-sidebar/issues/914);贡献者 PR [#916](https://github.com/omdsh-dev/DSH-better-sidebar/pull/916) @yanzhaohui1999) + - 📜 **超大文件的预览改成 VS Code 那种追加式滚动**:第一版做的是「上一页/下一页」的显式翻页(新页替换当前页),现在改为**滚到底自动取下一页并拼接**——读者读过的内容不会被抽走,行号跨页连续,「加载全部」就是一路追加到 EOF(必须串行:每一页的 `offset` 就是上一页响应的 `nextOffset`)。超限提示条最右侧新增「加载全部」按钮,加载中显示已读字节进度,到 EOF 后自动置灰。 配套的**行数上限**(`MAX_PREVIEW_ROWS = 50_000`)是这里唯一 VS Code 不需要、而本插件必须有的东西:它的 `TextModel` 与视图都做了虚拟化,所以模型里塞进一个 GB、DOM 仍然很小;本插件渲染的是真实元素。到顶后停止追加并明确提示改用下载——看得见的天花板胜过卡死的标签页,且这个数远高于任何人在侧栏里真会读的日志(6 MB 参考日志约 3.5 万条记录)。上限由读取 hook 持有而不是视图按**已渲染**行数判断:`loadAll` 在 `await` 循环里推进时 React 尚未重渲染,读渲染态的数字会滞后好几页把上限冲过去(新 spec 直接抓到:worker 十秒内 OOM)。 @@ -95,7 +102,7 @@ - 🧷 **修掉「展开底部面板」按钮在会话头与备用入口之间叠成两个**:blank 会话里宿主不渲染会话头,插件的会话头入口随之不可达,于是空白会话专用入口以 `position: fixed` 贴到宿主「Open right sidebar」按钮左侧(#698 / #623)。但**相位判定不足以互斥**——相位是每 1s 轮询来的,而会话头入口由宿主自行决定何时渲染,两者之间必然存在窗口(相位读取失败时还会按「非 blank」降级,一个从未成功读到的会话可能一直停在 blank);而两套入口在版面上**就是同一个位置**,同时在场即精确重叠成一团。现在除相位外再加一条与相位无关的兜底:**会话头那套入口只要真的在 DOM 里,备用入口就让位**,判别性用例见 `tests/dock-fallback.spec.tsx`(造出「相位说 blank + 会话头入口在场」的不一致状态,还原守卫即红)。最多 500ms 的让位延迟(与位置对齐同一节拍)。 -- 🎯 **文件引用终于落到那一行([#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` 时行号会被**清掉**(更新路径比的是当前值而不是「有没有传」),否则每次通知都会把读者弹回去;同一引用重复投递不重复跳,同一文件的新行号照跳。 +- 🎯 **文件引用终于落到那一行([#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;文本编辑器在**到达时定位一次**并给编辑器焦点(CodeMirror 只在获焦时画光标),越界行号钳到最后一行,区间(`:起-止`)只取起始行、列号丢弃(编辑器只有一处光标)。定位直接写 `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:`(另一个 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 页面同源不变)。 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index a8752ac2..63df400f 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -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 上 `:` 本就不是合法文件名字符)。行号随后顺着记录一路走到 viewer:两种写法落到**同一行**(`#L131` 由宿主解析成 `navigation.params.line`,`path:131` 由插件切出来,两者合流到 `SidebarTab.line`),文本编辑器在**到达时定位一次**并高亮该行,越界行号钳到最后一行。区间只取起始行、列号丢弃——编辑器只有一处光标。`line` 是**瞬态**:`sanitizePersistedTab` 的白名单不含它,刷新后不会把读者拽回几天前的那一行。markdown / html 收到行号时会**强制切到编辑态**再定位(预览里没有源码行号可放,而它自己的挂载滚动恢复也会和跳转打架)——引用要的是源码 | +| 地址里的行号(#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 收到行号时会**强制切到编辑态**再定位(预览里没有源码行号可放,而它自己的挂载滚动恢复也会和跳转打架)——引用要的是源码。这条强制是**一次性导航、不是文件的模式**:viewer 定位完成后回调 `onLineConsumed?.()`,宿主(`EditorHost`,它比 viewer 活得久——一次 reload 会把 viewer 整个重建)就停止再下发同一个 `line`;不这样做的话,读者点「预览」触发的 reload 会让重建出来的 viewer 重新强制切回编辑态,永远回不去。不消费 `line` 的 viewer(如按扩展名认领、只渲染图片的)与本行为无关。**两条入口现在一致**:聊天正文由宿主解析出 `navigation.params.line`;插件自绘的 markdown 预览(编辑器预览 / 侧边对话转录 / 变更阅读窗 / 任务窗口)在 `MarkdownDelegate.openFile(path, { line })` 里收到同一个数字,转成 seed 的 `line` 再走同一条链路——所以预览里点 `#L42` 与聊天里点 `#L42` 行为相同(跳到第 42 行 + 切到编辑态)| | 链接接管(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 兜底) | @@ -520,6 +520,9 @@ interface FileViewerProps { mtimeMs?: number // fetchStrategy='fsRead' 时:本次读取的磁盘 mtime(保存冲突基线) mediaUrl?: string // fetchStrategy='mediaUrl' 时 customData?: unknown // fetchStrategy='custom' 时(load() 的返回值) + // 引用带行号时才有(#826,见 §0「地址里的行号」):一次性导航,不是文件的属性 + line?: number // 1 基行号(如 `a.c#L131` / `a.c:131`);定位用得上的 viewer 消费它 + onLineConsumed?: () => void // 已消费该 line 的回报;不调用则每次加载都会重新下发(默认不消费) // 以下为内置文本编辑器与 EditorHost 内部协作字段,外部 viewer 忽略: toolbar?: 'self' | 'host' visible?: boolean // 本 tab 是否在屏(原生 tab 停驻时仍挂载) @@ -792,7 +795,10 @@ interface BetterSidebarService { * (含 React 自己的渲染订阅),也不会把整条侧栏换成错误条——所以 * listener 里读宿主 state 的字段仍请自己判空,别指望异常能当哨兵。 */ subscribeState(listener: () => void): () => void - /** 更新一个已打开 tab 的显示字段(title/path/meta);tab 不存在时 no-op */ + /** 更新一个已打开 tab 的显示字段(title/path/meta);tab 不存在时 no-op。 + * **改 path 等于一次新的打开**:引用带的行号(#826)是那次导航的瞬态状态, + * 会随之清掉——原地切换文件 / 重命名若留着它,下一个文件会跳到上一个文件 + * 的行号(markdown 还会被拉进编辑态)。 */ updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }): void /** 激活一个已打开的 tab(tab 栏点击路径;触发 descriptor.onActivate; * 未知 id 严格 no-op);scope(v0.12.0+)随回调传递,同 closeTab */ @@ -823,6 +829,10 @@ interface OpenTabSeed { /** 文件路径:editor = 打开文件资源;其余类型 = 组件种子(落在 tab.path,v0.19.2+) */ path?: string diff?: SidebarTab['diff'] + /** 文件引用带的行号(`a.c#L131` / `a.c:131`,1 基,#826)。只对 `editor` + * 有意义:它是一次性导航——编辑器到达时定位一次(markdown/html 因此 + * 离开预览),随后记录就忘了它。不传 = 普通打开。 */ + line?: SidebarTab['line'] id?: string url?: string /** JSON 可序列化的自定义状态,随 tab 持久化(刷新后原样恢复); diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index aa99da34..00f2b6cb 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -140,6 +140,25 @@ export function EditorHost(props: { // with the same path/scope — the only reload entry besides open/close. const [reloadSeq, setReloadSeq] = useState(0) + // The reference's landing line, SPENT once per open (#826). + // + // `tab.line` is one navigation, but the record keeps it for as long as the + // tab is open (the host re-delivers its navigation on every notification). + // The viewer cannot own that memory: a reload REMOUNTS it — this host swaps + // in the loading row — and a fresh instance starts at preview mode with an + // empty journal, so it would apply the same line again. For markdown/html + // that means re-forcing the file into the editor, and since the preview + // button reloads by design (#167 part B), the reader could never get back to + // preview. This host survives every reload, so the spent line is remembered + // here; the key carries the line, so a NEW reference re-arms it, and a file + // switch drops it (coming back to a file is a fresh open). + const [spentLine, setSpentLine] = useState(null) + const lineKey = tab.line === undefined ? null : `${path}#${tab.line}` + const onLineConsumed = useCallback(() => { + if (lineKey !== null) setSpentLine(lineKey) + }, [lineKey]) + useEffect(() => { setSpentLine(null) }, [path]) + // Manual refresh (issue #167 + PR #228): a dirty draft is dropped by the // reload (the editor instance remounts), so confirm before discarding it. const refreshFile = (): void => { @@ -610,10 +629,11 @@ 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, + // The reference's landing line, if the address carried one (#826) + // AND this open has not spent it yet. Only the text viewer acts on + // it; a markdown/html/image viewer gets the field and ignores it. + line: lineKey !== null && lineKey !== spentLine ? tab.line : undefined, + onLineConsumed, content: load.content, size: load.size, largeFile: load.largeFile, diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index 9476f246..facc434b 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -418,6 +418,11 @@ export function TextEditor(props: FileViewerProps) { return } landedAtRef.current = key + // The reference asked for a LINE, so it wins over the preview's remembered + // reading position: the flip's own "enter edit where the reader was" effect + // is declared AFTER this one and would otherwise re-dispatch (and re-scroll + // to) the preview position in the same commit, silently undoing the jump. + previewSyncRef.current = { text: null, ratio: 0 } // 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 @@ -430,6 +435,13 @@ export function TextEditor(props: FileViewerProps) { // on the editor scroller can never touch anything outside the editor. view.requestMeasure() view.dispatch({ selection: { anchor: target } }) + // Show the caret. A selection alone is invisible here: CodeMirror draws the + // cursor only in a FOCUSED editor, and a zero-length selection paints + // nothing — so an unfocused landing read as "the file just opened + // somewhere" (reported from the first manual test of this feature). Only a + // line reference focuses; an ordinary open leaves the reader's focus where + // it was (e.g. in the chat composer they clicked the link from). + view.focus() requestAnimationFrame(() => { requestAnimationFrame(() => { const block = view.lineBlockAt(target) @@ -440,10 +452,15 @@ export function TextEditor(props: FileViewerProps) { view.requestMeasure() }) }) + // The navigation is SPENT now: tell the host, which owns that memory (a + // reload remounts this component, and a fresh instance handed the same line + // again would re-force a markdown/html file into the editor — the reader + // could never click their way back to preview). + props.onLineConsumed?.() // 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]) + }, [content, path, line, mode, props.onLineConsumed]) // Scheme flip: re-theme in place (the compartment holds only the // scheme-dependent extensions; everything else is untouched). diff --git a/src/client/markdown-navigation.ts b/src/client/markdown-navigation.ts index e5fac80e..b2d2ab2b 100644 --- a/src/client/markdown-navigation.ts +++ b/src/client/markdown-navigation.ts @@ -43,8 +43,10 @@ * below, so {@link rewriteLocalMarkdownLinks} never claims it. It keeps * rendering as plain text — exactly what it did before this feature existed, * i.e. no regression, but also no jump. - * - A `#L24` line destination is left to the host (it rides `options.line`), so - * nothing scrolls the opened file to line 24. + * - A `#L24` line destination belongs to the host's own grammar: the renderer + * leaves the destination alone and hands the number over as `options.line`, + * so the surface forwards it as the open's landing line (see + * {@link lineOfHostFragment}) — it is NOT a heading anchor and never parks. */ import { maskCodeRegions } from './markdown-code.ts' import { normalizeLocalPath } from './markdown-images.ts' @@ -95,6 +97,21 @@ export function isHostLineFragment(fragment: string): boolean { return HOST_LINE_FRAGMENT_RE.test(fragment) } +/** + * The FIRST line a host line fragment names (`L24` → 24, `L24-L30` → 24), or + * undefined when the fragment is a heading anchor. + * + * The host hands the same number over as `MarkdownDelegate.openFile`'s + * `options.line`, so this is the fallback for a caller that only has the + * destination (and the single place that knows the grammar — the editor has + * one caret, so a range contributes its start). + */ +export function lineOfHostFragment(fragment: string): number | undefined { + if (!isHostLineFragment(fragment)) return undefined + const line = Number.parseInt(fragment.slice(1).split('-', 1)[0] ?? '', 10) + return Number.isSafeInteger(line) && line > 0 ? line : undefined +} + /** Percent-decode one URL piece, tolerating a malformed escape (a literal `%`). */ function decodePercent(value: string): string { try { diff --git a/src/client/native/tab-adapter.tsx b/src/client/native/tab-adapter.tsx index 65383cc6..5619ec84 100644 --- a/src/client/native/tab-adapter.tsx +++ b/src/client/native/tab-adapter.tsx @@ -320,7 +320,14 @@ export function createNativeTabRecords(): NativeTabRecords { const key = viewKey(sessionId, id) const entry = views.get(key) if (entry === undefined) return - put(key, { ...entry, tab: { ...entry.tab, ...patch } }) + const next: SidebarTab = { ...entry.tab, ...patch } + // A path change is a NEW open: the landing line (#826) rides the + // navigation that delivered the file, so it must not survive into the + // next one — `updateTab` is exactly how an in-place switch and a rename + // retarget a record. Keeping it sent the next file to the previous + // file's line (and forced a markdown file into the editor). + if (patch.path !== undefined && patch.path !== entry.tab.path) next.line = undefined + put(key, { ...entry, tab: next }) }, drop(sessionId, id) { const key = viewKey(sessionId, id) diff --git a/src/client/service.ts b/src/client/service.ts index adc9bfbf..1477a357 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -313,6 +313,14 @@ export interface FileViewerProps { * positions the reader there once, on arrival; every other viewer ignores * it. Absent on an ordinary open. */ line?: number + /** The viewer reports that it has APPLIED the `line` it was handed (or that + * the line does not apply to it), and the host stops handing it out: the + * line is one navigation, not a mode of the file. The host has to own that + * memory — a reload remounts the viewer, so a viewer that only remembers + * the line inside itself would receive it again after every refresh (for + * markdown/html that means re-forcing the editor open, and the reader could + * never return to preview). Optional: absent means "keep handing it out". */ + onLineConsumed?: () => void /** fsRead text content (fetchStrategy='fsRead'). Absent when the file is * above the editable threshold — see {@link largeFile}. */ content?: string @@ -473,6 +481,17 @@ export interface OpenTabSeed { path?: string /** A diff reference (the diff tab's content seed). */ diff?: SidebarTab['diff'] + /** + * The 1-based line a file reference named, for the `editor` kind (`#826`). + * Transient like the record's own `line`: it rides the open as a navigation + * the editor applies once (leaving preview, which renders no source lines) + * and the record forgets it right after. + * + * It is applied on a CREATE and on a native re-navigation; a store-branch + * FOCUS of an already-open tab (a host with no native surface) keeps the tab + * as it is — the same limitation the `diff` seed has. + */ + line?: SidebarTab['line'] /** Explicit tab id (defaults to the type). */ id?: string /** A URL the tab navigates to on mount (the browser tab's seed). */ @@ -684,6 +703,13 @@ export interface BetterSidebarService { * so a component that knows its scope should pass it; omitted, a native id * resolves against the mounted seat. */ + /** + * Update the display fields of one open tab (title / path / meta) without + * re-opening it. A **path change is a new open**: the transient landing line + * a reference carried (#826) is dropped with it, because that line belongs to + * the navigation that delivered the file — an in-place switch or a rename + * that kept it would send the next file to the previous file's line. + */ updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }, sessionId?: string): void /** * Activate an open tab (the tab-bar activation path; fires @@ -1085,6 +1111,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe title, ...(componentPath === undefined ? {} : { path: componentPath }), ...(seed.diff === undefined ? {} : { diff: seed.diff }), + ...(seed.line === undefined ? {} : { line: seed.line }), ...(seed.meta === undefined && minted?.tab.meta === undefined ? {} : { meta: seed.meta ?? minted?.tab.meta }), } if (seed.type === 'editor') { @@ -1100,6 +1127,9 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe sessionId: targetSessionId, address: surface.fileAddress(targetSessionId, scope?.cwd, seed.path), revealIfOpened: reveal, + // The reference's landing line, when the open came from one + // (`a.c#L131` — #826). Transient: the record spends it on arrival. + ...(seed.line === undefined ? {} : { line: seed.line }), ...(side ? { preferNewPane: true } : {}), }) } else { @@ -1161,6 +1191,9 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe title: seed.title ?? (typeof descriptor.title === 'function' ? descriptor.title() : descriptor.title), ...(seed.path !== undefined ? { path: seed.path } : {}), ...(seed.diff !== undefined ? { diff: seed.diff } : {}), + // The landing line, when this open came from a file reference + // (`a.c#L131` — #826); the editor spends it on arrival. + ...(seed.line !== undefined ? { line: seed.line } : {}), ...(seed.meta !== undefined ? { meta: seed.meta } : {}), } next = applyDedupe(state, tab, descriptor, land) diff --git a/src/client/sidebar-file.ts b/src/client/sidebar-file.ts index 1b6130c5..7c82fcd5 100644 --- a/src/client/sidebar-file.ts +++ b/src/client/sidebar-file.ts @@ -122,9 +122,13 @@ export function openClaimedNativeFile(ctx: Context, sessionId: string, cwd: stri * @param ctx - client context carrying `betterSidebar`. * @param sessionId - the session whose cwd resolves a relative path. * @param path - absolute or session-relative file path. + * @param line - the 1-based line a file reference named (`a.c#L131`, #826). + * Omitted on an ordinary open. It rides the open as a transient navigation: + * the editor lands on it once (leaving preview, which renders no source + * lines) and the record forgets it afterwards. * @returns nothing. */ -export function openSidebarFile(ctx: Context, sessionId: string, path: string): void { +export function openSidebarFile(ctx: Context, sessionId: string, path: string, line?: number): void { const summary = ctx.sessions.list.getSnapshot().byId[sessionId] const absolute = resolveSidebarPath(summary?.cwd, path) // A type that explicitly claims this file owns it: hand the address to the @@ -133,5 +137,11 @@ export function openSidebarFile(ctx: Context, sessionId: string, path: string): if (openClaimedNativeFile(ctx, sessionId, summary?.cwd, absolute)) return const at = Math.max(absolute.lastIndexOf('/'), absolute.lastIndexOf('\\')) const title = at === -1 ? absolute : absolute.slice(at + 1) - ctx.get('betterSidebar')?.openTab({ type: 'editor', title, path: absolute, id: `editor:${absolute}` }) + ctx.get('betterSidebar')?.openTab({ + type: 'editor', + title, + path: absolute, + id: `editor:${absolute}`, + ...(line === undefined ? {} : { line }), + }) } diff --git a/src/client/state.ts b/src/client/state.ts index 4c6ec327..43b83af6 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -384,7 +384,13 @@ export function isUnread(state: SidebarState | undefined, type: TabType): boolea * re-opening it. The browser tab persists its current URL and hostname * title through this reducer so a reload restores the visited page. A * missing tab id is a no-op. The tab may live in either tree or a free - * window. */ + * window. + * + * A PATH CHANGE is a new open: the transient landing line (#826) is dropped + * with it. `line` belongs to the navigation that delivered the file, not to + * the tab — an in-place switch or a rename that kept it would send the next + * file to the previous file's line (and force a markdown file into the + * editor, which is how the reader gets stuck). */ export function patchTab( state: SidebarState, tabId: string, @@ -398,6 +404,12 @@ export function patchTab( ...(patch.title !== undefined ? { title: patch.title } : {}), ...(patch.path !== undefined ? { path: patch.path } : {}), ...(patch.meta !== undefined ? { meta: patch.meta } : {}), + // Cleared (not merely left alone) so the reader's next file does not + // inherit this one's line. Compared against the current value to keep + // the object identity when nothing moved. + ...(patch.path !== undefined && patch.path !== tab.path && tab.line !== undefined + ? { line: undefined } + : {}), } } const walk = (node: SplitNode): SplitNode => { diff --git a/src/client/use-markdown-surface.ts b/src/client/use-markdown-surface.ts index 75d2c350..2af281f7 100644 --- a/src/client/use-markdown-surface.ts +++ b/src/client/use-markdown-surface.ts @@ -28,6 +28,7 @@ import { useCallback, useRef } from 'react' import type { Context } from '../context-types.ts' import { jumpToFragment, + lineOfHostFragment, markdownAnchorTarget, prepareMarkdownAnchors, rememberMarkdownAnchor, @@ -102,13 +103,18 @@ export function useMarkdownSurface(opts: MarkdownSurfaceOptions): MarkdownSurfac if (container !== null) jumpToFragment(container, target.fragment) return } - // `#L24` arrives as the host's own line option (never as an anchor); a - // heading fragment parks a jump for the document about to open. - if (options?.line === undefined && target.fragment !== '') { + // `#L24` is a LINE, not an anchor: the host hands the number over as + // `options.line` (and leaves the destination untouched), the fragment is + // the same grammar for a caller that only has the destination. Either way + // the line has to travel WITH the open — a line reference asks for source, + // so the editor lands on it (and leaves preview, which renders no lines). + // Only a heading fragment parks a jump for the document about to open. + const line = options?.line ?? lineOfHostFragment(target.fragment) + if (line === undefined && target.fragment !== '') { rememberMarkdownAnchor(sessionId, resolveCwd(), target.path, target.fragment) } try { - openSidebarFile(ctx, sessionId, target.path) + openSidebarFile(ctx, sessionId, target.path, line) } catch (error) { // A failed open leaves the reader where they are (the link was claimed); // the parked fragment expires on its own. diff --git a/tests/editor-line-nav-mode.spec.tsx b/tests/editor-line-nav-mode.spec.tsx new file mode 100644 index 00000000..80a89518 --- /dev/null +++ b/tests/editor-line-nav-mode.spec.tsx @@ -0,0 +1,236 @@ +/** + * A markdown reference that names a line must not own the file's mode forever + * (#826, second half — the forced edit-mode flip). + * + * The text editor flips a markdown/html file OUT of preview when a reference + * named a line (preview renders no source lines). That flip is part of the + * navigation, not a property of the file: the reader must be able to go back to + * preview afterwards. It cannot be tracked inside the viewer, because a reload + * REMOUNTS the viewer (EditorHost renders the loading row in its place) and the + * fresh instance — mode `preview`, no memory — would re-force the flip on every + * refresh, including the one the preview button itself triggers. + * + * `tests/text-editor-line-jump.spec.tsx` renders the viewer alone, so it cannot + * see any of this: the host is what decides when a navigation is spent. + */ +// @vitest-environment jsdom +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' +import type { Context } from '../src/context-types.ts' +import { EditorHost } from '../src/client/EditorHost.tsx' +import { TextEditor } from '../src/client/TextEditor.tsx' +import { createBetterSidebarService } from '../src/client/service.ts' +import { allLeaves, createSidebarStore, type SidebarStore, type SidebarTab } from '../src/client/state.ts' + +setupReactAct() + +const fsRead = vi.fn() +vi.mock('../src/client/api.ts', () => ({ + api: { + fsRead: (...args: unknown[]) => fsRead(...args), + mediaUrl: () => '', + }, +})) + +const SESSION = 'line-nav-session' +const BODY = '# title\n\nfirst\n\nsecond\n' + +/** fsRead call count: the "did a reload remount the viewer" evidence. */ +function reads(): number { + return fsRead.mock.calls.length +} + +/** Let the initial load (and any reload it triggers) settle. */ +async function settle(): Promise { + for (let index = 0; index < 4; index += 1) { + await act(async () => { await Promise.resolve() }) + } +} + +interface Harness { + ctx: Context + store: SidebarStore + /** The editor tab for `path`, carrying `line` when the reference named one. */ + tabOf: (path: string, line?: number) => SidebarTab +} + +/** One sidebar service + store with the REAL text editor behind `markdown`. */ +function harness(): Harness { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null }) + service.registerFileViewer({ + id: 'markdown', + exts: ['md'], + priority: 0, + fetchStrategy: 'fsRead', + component: TextEditor, + }) + store.setSession(SESSION) + const ctx = { + betterSidebar: service, + sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { [SESSION]: { cwd: '/tmp' } } }) } }, + get: (name: string) => name === 'betterSidebar' ? service : undefined, + } as unknown as Context + return { + ctx, + store, + tabOf: (path, line): SidebarTab => { + ctx.betterSidebar.openTab({ type: 'editor', title: path.split('/').pop()!, path, id: `editor:${path}` }) + const tab = allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) + .find(item => item.path === path)! + return line === undefined ? tab : { ...tab, line } + }, + } +} + +function mount(ctx: Context, tab: SidebarTab, store: SidebarStore): ReturnType { + return renderRoot(createElement(EditorHost, { + ctx, + store, + scope: { sessionId: SESSION, cwd: '/tmp' }, + tab, + visible: true, + expanded: [], + revealed: [], + onToggleDir: () => {}, + onReferenceFile: () => {}, + })) +} + +/** The editor is on screen (edit mode) — in preview the CodeMirror host is hidden. */ +function editing(container: HTMLElement): boolean { + return container.querySelector('[class*="editorCmHidden"]') === null +} + +function modeButton(container: HTMLElement, label: string): HTMLButtonElement { + return Array.from(container.querySelectorAll('button')) + .find(button => button.textContent === label)! +} + +function click(button: HTMLButtonElement): void { + act(() => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) +} + +beforeEach(() => { + fsRead.mockReset() + fsRead.mockResolvedValue({ kind: 'text', content: BODY, truncated: false }) +}) + +describe('a referenced line does not own the file mode (#826)', () => { + it('a markdown reference opens in the editor, and the reader can go back to preview', async () => { + const { ctx, store, tabOf } = harness() + const view = mount(ctx, tabOf('/tmp/readme.md', 3), store) + try { + await settle() + expect(reads()).toBe(1) + // The reference asked for source, so the file lands in the editor. + expect(editing(view.container)).toBe(true) + + // Back to preview — this reloads (#167 part B), which REMOUNTS the viewer. + click(modeButton(view.container, 'Preview')) + await settle() + expect(reads()).toBe(2) + + // ...and the remount must not flip the file back into the editor. + expect(editing(view.container)).toBe(false) + } finally { + view.unmount() + } + }) + + it('the header refresh does not flip a previewed file back into the editor either', async () => { + const { ctx, store, tabOf } = harness() + const view = mount(ctx, tabOf('/tmp/readme.md', 3), store) + try { + await settle() + expect(editing(view.container)).toBe(true) + click(modeButton(view.container, 'Preview')) + await settle() + + const refresh = view.container.querySelector( + 'button[aria-label="Refresh"], button[aria-label="刷新"]', + )! + click(refresh) + await settle() + expect(reads()).toBe(3) + + expect(editing(view.container)).toBe(false) + } finally { + view.unmount() + } + }) + + it('a NEW line on the same open file still lands (and re-opens the editor)', async () => { + const { ctx, store, tabOf } = harness() + const view = mount(ctx, tabOf('/tmp/readme.md', 3), store) + try { + await settle() + expect(editing(view.container)).toBe(true) + click(modeButton(view.container, 'Preview')) + await settle() + expect(editing(view.container)).toBe(false) + + // The same tab navigated to another line of the same file. + view.rerender(createElement(EditorHost, { + ctx, + store, + scope: { sessionId: SESSION, cwd: '/tmp' }, + tab: { ...tabOf('/tmp/readme.md', 5), line: 5 }, + visible: true, + expanded: [], + revealed: [], + onToggleDir: () => {}, + onReferenceFile: () => {}, + })) + await settle() + + expect(editing(view.container)).toBe(true) + } finally { + view.unmount() + } + }) +}) +describe('a spent line must not ride along to the next file', () => { + it('an in-place path switch drops it (updateTab retargets the record)', async () => { + // The reader types another path into the same window (merged mode): the + // record keeps its identity and takes the new path, but the landing line + // belonged to the navigation that delivered the PREVIOUS file. Keeping it + // sent the new file to line 3 — and, being markdown, forced it into the + // editor, which is the same "stuck in edit mode" the reload bug produced. + const { ctx, store, tabOf } = harness() + const tab = tabOf('/tmp/a.md', 3) + const view = mount(ctx, tab, store) + const host = (next: SidebarTab): ReturnType => createElement(EditorHost, { + ctx, + store, + scope: { sessionId: SESSION, cwd: '/tmp' }, + tab: next, + visible: true, + expanded: [], + revealed: [], + onToggleDir: () => {}, + onReferenceFile: () => {}, + }) + try { + await settle() + expect(editing(view.container)).toBe(true) + + // The real retarget path (`EditorHost.openFile` merged mode / a rename), + // then the tab the store actually holds after it. + ctx.betterSidebar.updateTab(tab.id, { path: '/tmp/b.md', title: 'b.md' }, SESSION) + const retargeted = allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) + .find(item => item.id === tab.id)! + expect(retargeted.line).toBeUndefined() + + view.rerender(host(retargeted)) + await settle() + + expect(editing(view.container)).toBe(false) + } finally { + view.unmount() + } + }) +}) diff --git a/tests/file-open-claim.spec.ts b/tests/file-open-claim.spec.ts index 762ae061..1281bbec 100644 --- a/tests/file-open-claim.spec.ts +++ b/tests/file-open-claim.spec.ts @@ -114,6 +114,20 @@ describe('openSidebarFile', () => { expect(harness.opened).toEqual([]) }) + it('carries a reference\'s landing line into the open, and omits it otherwise (#826)', () => { + // The line is a transient navigation seed, not part of the file identity: + // present only when the open came from `#L42` / `a.c:42`. + const harness = makeCtx({ candidates: () => [{ kind: 'editor' }] }) + + openSidebarFile(harness.ctx, 'session-1', 'out/notes.md', 42) + + expect(harness.opened).toEqual([ + { type: 'editor', title: 'notes.md', path: '/ws/out/notes.md', id: 'editor:/ws/out/notes.md', line: 42 }, + ]) + openSidebarFile(harness.ctx, 'session-1', 'out/other.md') + expect('line' in harness.opened[1]!).toBe(false) + }) + it('ranks by the registry order: the editor keeps files no other type claims', () => { // `editor` first is the normal case (our type registers // `dsh-resource://file/**` in the extension band, so it beats the diff --git a/tests/markdown-navigation.spec.ts b/tests/markdown-navigation.spec.ts index 8e3673f2..3f0b54ff 100644 --- a/tests/markdown-navigation.spec.ts +++ b/tests/markdown-navigation.spec.ts @@ -10,13 +10,13 @@ * same note): a destination with an ESCAPED parenthesis (`[x](./a\(1\).md)`) or * a single-quoted title (`[x](./a.md 'title')`) does not match the link grammar * and is therefore never claimed — it keeps rendering as plain text, exactly as - * it did before this feature. A `#L24` line destination belongs to the host and - * is not turned into a line jump. + * it did before this feature. */ import { afterEach, describe, expect, it, vi } from 'vitest' import { githubHeadingSlug, isHostLineFragment, + lineOfHostFragment, markdownAnchorTarget, rememberMarkdownAnchor, rewriteLocalMarkdownLinks, @@ -67,6 +67,20 @@ describe('isHostLineFragment', () => { }) }) +describe('lineOfHostFragment', () => { + it('reads the first line of the host line grammar, and nothing else', () => { + expect(lineOfHostFragment('L24')).toBe(24) + expect(lineOfHostFragment('L24-L30')).toBe(24) + // A heading anchor is not a line — it rides the parked-fragment table. + expect(lineOfHostFragment('小节')).toBeUndefined() + expect(lineOfHostFragment('')).toBeUndefined() + // The grammar already rejected these, but the parser must not invent a + // number from them either. + expect(lineOfHostFragment('L0')).toBeUndefined() + expect(lineOfHostFragment('l24')).toBeUndefined() + }) +}) + describe('markdownAnchorTarget', () => { it('claims a relative .md link against the DOCUMENT directory, not the cwd', () => { // The whole point of the base rule: the link lives in /ws/docs, so its diff --git a/tests/markdown-surface.spec.tsx b/tests/markdown-surface.spec.tsx index 91f32621..5ce595bf 100644 --- a/tests/markdown-surface.spec.tsx +++ b/tests/markdown-surface.spec.tsx @@ -63,7 +63,7 @@ function nextSession(): string { interface Mounted { container: HTMLDivElement /** Every editor tab the sidebar currently holds (path-typed ones last). */ - tabs: () => { type: string; path?: string }[] + tabs: () => { type: string; path?: string; line?: number }[] unmount: () => void } @@ -72,7 +72,7 @@ interface Mounted { function sidebarCtx(sessionId: string): { ctx: Context store: ReturnType - tabs: () => { type: string; path?: string }[] + tabs: () => { type: string; path?: string; line?: number }[] } { const store = createSidebarStore() const service = createBetterSidebarService(store) @@ -84,7 +84,11 @@ function sidebarCtx(sessionId: string): { get: (name: string) => name === 'betterSidebar' ? service : undefined, sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { [sessionId]: { cwd: '/p' } } }) } }, } as unknown as Context - return { ctx, store, tabs: () => allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) } + return { + ctx, + store, + tabs: () => allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs), + } } /** @@ -260,6 +264,37 @@ describe('the markdown preview surface', () => { mounted.unmount() }) + it('carries a `#L42` destination through the open as the landing line (#826)', () => { + // The host hands the line over as its delegate's `options.line` and leaves + // the destination alone, so the surface has to forward it: without it the + // file opened at line 1 (and a markdown file stayed in preview, which + // renders no source lines to put a cursor on). + const mounted = mountEditor( + '[42](./target.md#L42) and [range](./range.md#L20-L25) and [anchor](./anchored.md#小节)\n', + '/p/docs/README.md', + ) + // The host strips the line fragment from the button's title (it is the + // host's own `parseFileLink` that consumed it), so the link is found by + // its bare destination. + const surface = surfaceOf(mounted.container) + click(fileLink(surface, './target.md')!) + expect(mounted.tabs().map(tab => ({ path: tab.path, line: tab.line }))) + .toEqual([{ path: '/p/docs/target.md', line: 42 }]) + // A range contributes its start: the editor has exactly one caret. + click(fileLink(surface, './range.md')!) + expect(mounted.tabs()[1]?.line).toBe(20) + mounted.unmount() + }) + + it('parks a heading fragment instead of forwarding a line (it has none)', () => { + const mounted = mountEditor('[go](./anchored.md#小节)\n', '/p/docs/README.md') + click(fileLink(surfaceOf(mounted.container), './anchored.md#小节')!) + // A heading fragment rides the parked-anchor table (the target document does + // not exist yet), so the open itself carries no line. + expect(mounted.tabs()[0]?.line).toBeUndefined() + mounted.unmount() + }) + it('keeps remote links as links and non-markdown local links as inert text', () => { const mounted = mountEditor([ '[site](https://example.com/a.md)', diff --git a/tests/native-tab-line.spec.ts b/tests/native-tab-line.spec.ts index 589480c3..390dad80 100644 --- a/tests/native-tab-line.spec.ts +++ b/tests/native-tab-line.spec.ts @@ -74,6 +74,25 @@ describe('the landing line on a native tab record (#826)', () => { expect(bare.tab.line).toBeUndefined() }) + it('DROPS the line when an updateTab retarget moves the record to another file', () => { + // The plugin's own writers (`updateTab`: an in-place path switch, a rename) + // are not host navigations, so they never passed through the clearing rule + // above. A path change is a new open all the same: the reader asked for + // that other file, not for line 131 of it. + const seeded = ensure({ path: 'a.ts', line: 131 }, 1) + records.update('seat-1', 'tab-1', { path: 'b.ts', title: 'b.ts' }) + const retargeted = records.get('seat-1', 'tab-1')!.tab + expect(retargeted.path).toBe('b.ts') + expect(retargeted.line).toBeUndefined() + expect(seeded.line).toBe(131) + }) + + it('keeps the line when updateTab patches only the title (same file)', () => { + ensure({ path: 'a.ts', line: 7 }, 1) + records.update('seat-1', 'tab-1', { title: 'renamed.ts' }) + expect(records.get('seat-1', 'tab-1')!.tab.line).toBe(7) + }) + 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 diff --git a/tests/text-editor-line-jump.spec.tsx b/tests/text-editor-line-jump.spec.tsx index bff929b8..5b1ce50a 100644 --- a/tests/text-editor-line-jump.spec.tsx +++ b/tests/text-editor-line-jump.spec.tsx @@ -53,9 +53,18 @@ 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. @@ -126,4 +135,59 @@ const render = (overrides: Partial = {}): HTMLDivElement => { 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) + }) }) \ No newline at end of file