diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54407f00..67edd93f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,14 @@
### Unreleased
+- 🔗 **Markdown 里的本地 `.md` 链接改在侧栏打开,标题锚点可跳转**([#363](https://github.com/omdsh-dev/DSH-better-sidebar/issues/363)):插件自绘的四处 markdown(编辑器预览 / 侧边对话转录 / 文件变动阅读视图 / 任务笔记)原先把 `[x](./other.md)` 渲染成**不可点的纯文本**——宿主渲染器只有在 `MarkdownDelegateProvider` 提供 `openFile` 时才把本地目标变成可点元素,且它自己的 `parseFileLink` **只认行号 fragment**(`#L24`),带标题 fragment 会让整个目标判为非法,于是「点了没反应」。现在链接被判为「同文档 fragment」或「要打开的文件」:同文档的就地滚动预览**自己的滚动容器**(不用 `window.scrollTo`,也不用 `scrollIntoView`——后者会连整条侧栏一起滚),跨文件的把 fragment 以 `%23` 编码带过宿主解析器、按「会话 + 绝对路径」暂存,目标文件渲染出来后落到对应标题。
+ - **标题 id 现在与 GitHub 逐字一致**:`githubHeadingSlug` 改成 GitHub `github-slugger` 的真实规则——**不 trim、不折叠连续空白**(每个空格各转一个 `-`)、删 emoji 与 `\uFE0F` 等 variation selector、删标点与符号、保留任意文字系统的字母/数字/组合标记、重复标题 `-1`/`-2`,文档里已存在的显式 id 先占用。**这是本批最有用户价值的一处**:仓库自己的两份 README 目录锚点因此从 **0/15 全部失效**(点击被认领成按钮但 `scrollTop` 纹丝不动,静默 no-op)变为 **15/15 全部可用**(真实 `TextEditor` + 真实宿主 `MarkdownText` 渲染后逐个锚点点击实测)。旧实现错在两处:先 `trim` 再把空白折叠成一个 `-`(GitHub 两者都不做,`## 🛠️ Development & Build` 的真实 id 是 `-development--build`),以及保留 `\p{M}` 而把 VS16 留在 id 里(`🖼️ 特性巡礼` 曾得到含不可见字符的 `"\uFE0F-特性巡礼"`)。
+ - 🧹 `` 这类空显式锚点(GitHub README 常用)被标为 `hidden`——不再占版面,id 仍在,`#x` 深链照旧。
+ - **范围决定**:非 markdown 的本地链接(`./notes.txt`、`./pic.png`、`./docs`)**维持纯文本不变**——本批只认领 `.md` / `.markdown`,目的是不把用户交到插件不打算服务的动作上。`#L24` 行号目标仍交给宿主自己的语法,**本批不做「打开后跳到第 24 行」**。
+ - 🧪 测试:`tests/markdown-navigation.spec.ts`(认领判定 / `%23` 载体 / 幂等 / 跨文件 fragment 表)、`tests/markdown-slug.spec.ts`(**以真实 `github-slugger` 正则做对照**的 slug 判定 + 两份 README 的锚点解析率断言)、`tests/markdown-surface.spec.tsx`(真实渲染下的 host delegate 点击路径、祖先滚动容器、跨文件落点)。
+- 🐞 **修掉 `~~~` 代码围栏内的链接与图片被改写**:两份源码改写器(`markdown-images.ts` / `markdown-navigation.ts`)各自内联的围栏 mask 只认三个反引号,于是 `~~~` 围栏里当作**示例**展示的 `[y](./b.md#u)` 会被写成 `[y](./b.md%23u)`、`` 会被写成 `/sidebar/file` URL(与 58d7f71 基线逐字对比,这是本批唯一的渲染差异)。现在抽出一个共享 mask(`src/client/markdown-code.ts`,CommonMark 规则:**3 个及以上反引号或 3 个及以上波浪号**开栏、闭合不短于开栏、未闭合则延伸到文末),两个 pass 共用。**图片那条盲区是既有缺陷而非本批引入**(58d7f71 上 `rewriteLocalImageUrls('~~~\n\n~~~')` 已经会改写),一并修掉。
+- 📝 如实记录的窄边(不修、无损坏):目的地含**转义括号**(`[x](./a\(1\).md)`)或**单引号 title**(`[x](./a.md 'title')`)的链接不会被认领,回退成纯文本——与本批之前的渲染逐字一致。
+
- 🧹 **移除「位置兼容模式 / 标题栏条带」整套机制与设置**([#430](https://github.com/omdsh-dev/DSH-better-sidebar/issues/430),细节与消费者普查见 [移除记录](docs/plans/2026-10-05-remove-titlebar-compat-strip.md)):这套设置想让人手动声明「我的桌面壳在顶部占了 N 像素」、好让插件把内容下移,但**插件内部早已没有消费者**——唯一的三条读 `--dsh-title-bar-strip` 的 CSS 规则随「顶部自绘 chrome 交还宿主」在 v0.19.0(`223b254`)删除,而用户期望被移动的「侧边栏按钮」是**宿主原生控件**(插件没有它的位置 API),宿主也不读这条契约(DSH 源码树对该契约与 `desktopWindow` 全 0 命中)。于是改设置只会写一个没人读的变量、**什么都不动**。本版把整套机制删除:`titlebar-strip.ts` / `wco.ts` / `shell-presets.ts` 三个模块与各自 spec、`titleBarScheme` / `titleBarPresetId` / `titleBarCompat` / `titleBarStripPx` 四个偏好键与设置界面、12 个词典 key × 21 份词典、挂载 lane 里两条 WCO / preset 场景。**保留**:`desktop-env.ts` 的 `hostTransportBase()`(反向代理前缀与 `dsh-app://` 解析基准,另有 3 个消费者)与「**自定义 CSS**」逃生口(改为独立分组、**非空即生效**)。旧偏好数据**安全忽略**(宿主 schema 为 OPEN 不报错、客户端 `parsePrefs` 只按声明字段构造、一次性 `settings.yaml` 回迁丢弃未声明键),三层各有测试与变异证伪。
- 🧪 测试:新增「旧数据被安全忽略」三层断言(`tests/prefs.spec.ts` / `tests/plugin-shape.spec.ts` / `tests/smoke.spec.ts`),挂载 lane 改为**负向断言**(戳记 URL 下 `body[data-dsh-title-bar-compat]` 必须缺席、`--dsh-title-bar-strip` 必须为空)并保留「自定义 CSS 实时注入」用例;删除 5 个只服务该机制的 spec。
- 🗂️ **资源管理器补「新建文件」**([#132](https://github.com/omdsh-dev/DSH-better-sidebar/issues/132),移植贡献者 PR [#832](https://github.com/omdsh-dev/DSH-better-sidebar/pull/832) 的交互语义):目录行右键「新建文件夹」旁新增「**新建文件**」,在该层顶部插入同款行内输入(Enter 提交 / Escape 取消 / 失焦提交 / IME 保护,图标跟随输入的文件名),与「新建文件夹」**互斥**(开一个即关另一个)。与 PR 的差别是**写路径落在服务端**:新增路由 `fs.createFile` → `fs-operations.ts` 的 `createWorkspaceFile`,复用既有 rename/mkdir 的单段名与「已存在即拒」规则(`fs-error` 409,同一句 `"x" already exists`),并额外拒绝 Windows 非法字符(`< > : " | ? *` 与控制字符)与保留设备名(CON / PRN / AUX / NUL / COM1-9 / LPT1-9,带不带扩展名都拒);落盘用 `wx`,**同名文件绝不被截断**;客户端在已加载的那一层先做一次大小写不敏感的占用检查(`newFileExists`),服务端仍是最终裁决。词条 `newFile` / `newFilePlaceholder` / `newFileInvalid` / `newFileExists` 同批进入 `locales.ts` 的 zh/en 与 19 份第三语言词典。
diff --git a/src/client/markdown-code.ts b/src/client/markdown-code.ts
new file mode 100644
index 00000000..706481f2
--- /dev/null
+++ b/src/client/markdown-code.ts
@@ -0,0 +1,132 @@
+/**
+ * The ONE code-region mask the two markdown source rewriters share
+ * (`markdown-images.ts` for image destinations, `markdown-navigation.ts` for
+ * link destinations).
+ *
+ * Both rewrites are regex passes over raw markdown, so anything that LOOKS like
+ * a link or an image inside a code region must be left verbatim: a README that
+ * documents `[x](./a.md#标题)` or `` means to show that syntax, not
+ * to have it rewritten. Masking preserves the region byte for byte — the
+ * sentinel is a NUL, which cannot appear in markdown source, and the original
+ * text goes back in after the pass.
+ *
+ * What counts as a code region is CommonMark's own rule: an INLINE code span
+ * (a backtick run closed by a run of the same length), and a FENCED block — an
+ * opening fence of three or more backticks OR three or more tildes, closed by a
+ * fence of the same character at least as long as the opener. The fence line
+ * itself is masked too (its leading run is what a backtick-span scan would
+ * otherwise mistake for a code span), and an unclosed fence runs to the end of
+ * the text, exactly as a renderer treats it.
+ *
+ * Both fence characters matter: `~~~` is a legal fence in CommonMark and in
+ * every renderer this plugin draws through, so an image or a link demonstrated
+ * inside one is as much an example as one inside ``` ``` ```.
+ */
+
+/** A backtick or tilde fence: three or more, at up to three spaces of indent. */
+const FENCE_RE = /^ {0,3}(`{3,}|~{3,})([^\n]*)$/gm
+/** An inline code span: a backtick run, then the next run of the SAME length. */
+const CODE_SPAN_RE = /(`+)[\s\S]*?\1/g
+
+/** A masked region's placeholder: NUL + index + NUL. */
+// eslint-disable-next-line no-control-regex -- NUL is the deliberate mask sentinel (cannot appear in source markdown)
+const MASK_RE = /\u0000(\d+)\u0000/g
+
+/** A half-open `[start, end)` range of the source. */
+type Region = [number, number]
+
+/**
+ * The length of the fence run at the start of `line` — its leading `\`` or `~`
+ * characters. Zero when the line is not a fence (or not one of ours).
+ */
+function fenceRun(line: string): { marker: string; length: number } | null {
+ const marker = line.charAt(0)
+ if (marker !== '`' && marker !== '~') return null
+ let length = 0
+ while (line.charAt(length) === marker) length += 1
+ return length >= 3 ? { marker, length } : null
+}
+
+/** Whether a line closes a fence opened by `marker` × `length` (CommonMark). */
+function closesFence(line: string, marker: string, length: number): boolean {
+ if (line.charAt(0) !== marker) return false
+ let run = 0
+ while (line.charAt(run) === marker) run += 1
+ return run >= length && /^[ \t]*$/.test(line.slice(run))
+}
+
+/**
+ * Every fenced block in `text`, as half-open ranges that INCLUDE the fence
+ * lines.
+ *
+ * The scan is a single forward walk that cannot be fooled by a fence-looking
+ * line inside a block or before the opener: a closing fence has to be the same
+ * character at least as long as its opener, and a fence nested inside a longer
+ * one is content, not a delimiter. An unclosed fence runs to the end of the
+ * text — the extent a renderer gives it.
+ */
+function fenceRegions(text: string): Region[] {
+ const regions: Region[] = []
+ let searchFrom = 0
+ for (;;) {
+ FENCE_RE.lastIndex = searchFrom
+ const opener = FENCE_RE.exec(text)
+ if (opener === null) break
+ const start = opener.index
+ const run = fenceRun(opener.at(1) ?? '')
+ const bodyStart = start + opener[0].length
+ let end = text.length
+ if (run !== null) {
+ // Walk the body line by line until a closing fence (or the end of text).
+ let at = bodyStart
+ while (at < text.length) {
+ if (text.charAt(at) === '\n') { at += 1; continue }
+ const lineEnd = text.indexOf('\n', at)
+ const stop = lineEnd === -1 ? text.length : lineEnd
+ if (closesFence(text.slice(at, stop), run.marker, run.length)) {
+ end = stop
+ break
+ }
+ at = stop + 1
+ }
+ }
+ regions.push([start, end])
+ searchFrom = end
+ }
+ return regions
+}
+
+/** The masked text, plus the way back to the original. */
+export interface MaskedCodeRegions {
+ /** `text` with every code region replaced by a placeholder. */
+ masked: string
+ /** Put every masked region back, in place. */
+ restore: (text: string) => string
+}
+
+/**
+ * Mask the fenced blocks and inline code spans of one markdown text.
+ * @param text - the markdown source.
+ * @returns the masked text and its restore function.
+ */
+export function maskCodeRegions(text: string): MaskedCodeRegions {
+ const masks: string[] = []
+ const mask = (region: string): string => {
+ masks.push(region)
+ return `\u0000${masks.length - 1}\u0000`
+ }
+
+ // Fences first (they are the outer region), and from the END backwards so
+ // each splice leaves the offsets of the not-yet-masked regions valid.
+ let fenced = text
+ for (const [start, end] of fenceRegions(text).reverse()) {
+ fenced = fenced.slice(0, start) + mask(text.slice(start, end)) + fenced.slice(end)
+ }
+ // Then the inline spans the fence pass did not swallow.
+ const masked = fenced.replace(CODE_SPAN_RE, (span: string) => mask(span))
+
+ return {
+ masked,
+ restore: (value: string): string => value.replace(MASK_RE, (_m, index: string) => masks[Number(index)] ?? ''),
+ }
+}
diff --git a/src/client/markdown-images.ts b/src/client/markdown-images.ts
index 003c277b..bad10e80 100644
--- a/src/client/markdown-images.ts
+++ b/src/client/markdown-images.ts
@@ -12,6 +12,7 @@
import type { SessionScope } from './api.ts'
import { hostRouteUrl } from './host-route-url.ts'
+import { maskCodeRegions } from './markdown-code.ts'
import { isAbsolutePath } from './paths.ts'
/**
@@ -54,7 +55,8 @@ export function normalizeLocalPath(path: string): string {
* destinations are left untouched for `MarkdownText`. Reference-style images
* (`![x][id]` + `[id]: url`) are covered by rewriting their definition lines.
*
- * Code spans (`` `...` ``) and fenced code blocks (``` ```...``` ```) are
+ * Code regions — inline spans AND fenced blocks, the latter opened by ``` ``` ```
+ * OR `~~~` (see `markdown-code.ts`, the mask both source rewriters share) — are
* masked before rewriting so documentation that demonstrates ``
* is not mutated into a `/sidebar/file` URL. Reference definitions are only
* rewritten when their label is actually referenced by an image (collapsed
@@ -105,14 +107,10 @@ export function rewriteLocalImageUrls(
): string {
const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, baseUrl)
- // Mask fenced code blocks and inline code spans so image-looking text
- // inside documentation examples is never rewritten. The sentinel uses a
- // character unlikely to appear in prose; the original spans are restored
- // after the image rewrite.
- const masks: string[] = []
- const masked = text
- .replace(/```[\s\S]*?```/g, (block) => { masks.push(block); return `\u0000${masks.length - 1}\u0000` })
- .replace(/`[^`\n]*`/g, (span) => { masks.push(span); return `\u0000${masks.length - 1}\u0000` })
+ // Fenced blocks (``` ``` ``` AND `~~~`) and inline code spans are masked so
+ // image-looking text inside documentation examples is never rewritten; the
+ // original text goes back in after the rewrite.
+ const { masked, restore } = maskCodeRegions(text)
const inline = masked.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, alt, dest) => {
return `})`
@@ -137,6 +135,5 @@ export function rewriteLocalImageUrls(
return `${head}${resolve(dest.replace(/^<|>$/g, ''))}`
})
- // eslint-disable-next-line no-control-regex -- NUL is the deliberate mask sentinel (cannot appear in source markdown)
- return refsRewritten.replace(/\u0000(\d+)\u0000/g, (_m, index: string) => masks[Number(index)] ?? '')
+ return restore(refsRewritten)
}
diff --git a/src/client/markdown-navigation.ts b/src/client/markdown-navigation.ts
index 3f426750..e5fac80e 100644
--- a/src/client/markdown-navigation.ts
+++ b/src/client/markdown-navigation.ts
@@ -35,7 +35,18 @@
* document, which does not exist yet — so the fragment is parked by session +
* absolute path and taken by the target's own surface once it mounts. The
* host's routing is untouched.
+ *
+ * KNOWN NARROW EDGES (deliberate, recorded rather than fixed — neither one
+ * corrupts anything):
+ * - A destination containing an ESCAPED parenthesis (`[x](./a\(1\).md)`) or a
+ * single-quoted title (`[x](./a.md 'title')`) does not match the link grammar
+ * 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.
*/
+import { maskCodeRegions } from './markdown-code.ts'
import { normalizeLocalPath } from './markdown-images.ts'
import { isAbsolutePath } from './paths.ts'
@@ -126,21 +137,42 @@ function separatorOf(destination: string): FragmentSeparator | null {
}
/**
- * The GitHub heading slug of one heading's text: trimmed, lower-cased,
- * punctuation and symbols dropped (`-` and `_` survive — GitHub's own slugger
- * keeps both), whitespace runs collapsed to a single dash, and every letter,
- * digit and combining mark of ANY script kept — so a Chinese heading keeps its
- * own text as its id, exactly like GitHub does.
+ * The characters GitHub's heading slug DROPS beyond punctuation and symbols:
+ * pictographs (every emoji), the variation selectors that follow a good many of
+ * them (`🖼️` is U+1F5BC + U+FE0F — GitHub's own pipeline renders an emoji as an
+ * `
`, so neither character reaches the slug text), regional-indicator pairs
+ * (flag emoji, which are `\p{So}` but outside `Extended_Pictographic`), and the
+ * control/format/unassigned characters. Combining marks are deliberately NOT
+ * here — `\p{M}` survives, as it does on GitHub.
+ */
+// eslint-disable-next-line no-misleading-character-class -- the ranges are deliberate, not a mis-ordered surrogate pair
+const DROPPED_EXTRA_RE = /[\p{Extended_Pictographic}\u{1F000}-\u{1FAFF}\u{FE00}-\u{FE0F}\u{1F1E6}-\u{1F1FF}\p{C}]/gu
+
+/**
+ * The GitHub heading slug of one heading's text — the id GitHub itself would
+ * give that heading, so the anchors a README's table of contents carries
+ * resolve. GitHub's slugger (`github-slugger`) lower-cases ASCII, drops
+ * punctuation and symbols, and turns EACH space into its own `-`; it does not
+ * trim and does not collapse runs, which is why `## 🛠️ Development & Build`
+ * has the id `-development--build` (the leading dash is the space the emoji
+ * left behind, the double dash is the removed `&`). Letters, digits and
+ * combining marks of ANY script survive, so a Chinese heading keeps its own
+ * text as its id.
+ *
+ * The one deliberate difference from `github-slugger` is where the emoji are
+ * removed: GitHub strips them while rendering the heading (to `
`), before
+ * the slugger ever sees the text, so a slugger run on plain text would keep
+ * `🚀` and produce `🚀-安装` instead of GitHub's real `-安装`. This function
+ * drops them here, in the same pass, which yields GitHub's actual ids.
* @param text - the heading's rendered text.
* @returns the slug (`''` for a heading with no letters or digits at all).
*/
export function githubHeadingSlug(text: string): string {
return text
- .trim()
.toLowerCase()
- .replace(/[^\p{L}\p{N}\p{M}\s_-]/gu, '')
- .trim()
- .replace(/\s+/g, '-')
+ .replace(DROPPED_EXTRA_RE, '')
+ .replace(/[^\p{L}\p{N}\p{M} _-]/gu, '')
+ .replace(/ /g, '-')
}
/**
@@ -284,7 +316,8 @@ function rewriteDestination(destination: string, docPath: string | undefined, cw
* a claimed `.md`/`.markdown` destination gets its heading fragment carried as
* `%23`, and every other local destination gets the `?` that keeps it inert.
*
- * Code spans and fenced blocks are masked first, so documentation that
+ * Code regions are masked first (see `maskCodeRegions` — fenced blocks opened
+ * by ``` ``` ``` OR `~~~`, and inline code spans), so documentation that
* demonstrates `[x](./a.md#标题)` is not mutated. Image destinations are left
* to `rewriteLocalImageUrls` (which must run FIRST: it rewrites the definitions
* an image uses into absolute media URLs, which this pass then ignores).
@@ -298,10 +331,7 @@ export function rewriteLocalMarkdownLinks(
docPath: string | undefined,
cwd: string | undefined,
): string {
- const masks: string[] = []
- const masked = text
- .replace(/```[\s\S]*?```/g, (block) => { masks.push(block); return `\u0000${masks.length - 1}\u0000` })
- .replace(/`[^`\n]*`/g, (span) => { masks.push(span); return `\u0000${masks.length - 1}\u0000` })
+ const { masked, restore } = maskCodeRegions(text)
const links = masked
// Inline links. The negative lookbehind keeps IMAGE destinations out, and
@@ -329,8 +359,7 @@ export function rewriteLocalMarkdownLinks(
},
)
- // eslint-disable-next-line no-control-regex -- NUL is the deliberate mask sentinel (cannot appear in source markdown)
- return links.replace(/\u0000(\d+)\u0000/g, (_m, index: string) => masks[Number(index)] ?? '')
+ return restore(links)
}
/**
diff --git a/tests/helpers/github-slug-reference.ts b/tests/helpers/github-slug-reference.ts
new file mode 100644
index 00000000..23c9cfa4
--- /dev/null
+++ b/tests/helpers/github-slug-reference.ts
@@ -0,0 +1,94 @@
+/**
+ * An independent GitHub heading-slug oracle for the specs, plus the README
+ * scanning they share.
+ *
+ * WHY A COPY LIVES HERE: `githubHeadingSlug` (`src/client/markdown-navigation.ts`)
+ * must produce the ids GitHub itself gives a heading, because the anchors a
+ * README's table of contents carries are written for GitHub. The oracle is
+ * therefore not this repo's own code reworded — it is `github-slugger@2.0.0`'s
+ * SLUGGER REGEX, copied verbatim from the published `regex.js`
+ * (, MIT, by Dan Flettre and Titus
+ * Wormer), with its two-line `slug()` around it. A future edit that changes
+ * `githubHeadingSlug` into "roughly GitHub-like" therefore fails a test instead
+ * of silently breaking every README anchor again — which is exactly what
+ * happened before: the old implementation trimmed and collapsed whitespace
+ * runs, so the repos' own two READMEs resolved **0 of 16** anchors.
+ *
+ * The oracle is only as good as its input: GitHub removes emoji while RENDERING
+ * a heading (each becomes an `
`) and hands the slugger the remaining text,
+ * so run these fixtures on emoji-free text (the spec keeps the emoji cases as
+ * explicit expectations instead — the README cases below are the end-to-end
+ * proof that the emoji handling is right).
+ */
+
+/* eslint-disable no-control-regex, no-misleading-character-class, no-useless-escape -- verbatim upstream pattern */
+/**
+ * `github-slugger@2.0.0` `regex.js`, verbatim. `slug()` deletes every match and
+ * then turns each space into a dash.
+ */
+const SLUGGER_REGEX = /[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09D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0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\u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\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g
+/* eslint-enable no-control-regex, no-misleading-character-class, no-useless-escape */
+
+/** GitHub's slug for ONE heading text (no repeat tracking). */
+export function referenceSlug(text: string): string {
+ return text.toLowerCase().replace(SLUGGER_REGEX, '').replace(/ /g, '-')
+}
+
+/**
+ * GitHub's ids for a whole document — the repeat counter included, `-1`/`-2`
+ * on every later heading whose slug was already taken, which is what the
+ * plugin's `assignHeadingIds` does too.
+ * @param headings - the heading texts, in document order.
+ */
+export function referenceHeadingIds(headings: string[]): string[] {
+ const taken = new Set()
+ return headings.map((heading) => {
+ const base = referenceSlug(heading)
+ if (base === '') return ''
+ let id = base
+ for (let suffix = 1; taken.has(id); suffix += 1) id = `${base}-${suffix}`
+ taken.add(id)
+ return id
+ })
+}
+
+/** One markdown document's headings and its in-document anchors. */
+export interface DocumentAnchors {
+ /** The heading texts, in document order (`#`…`######` ATX headings). */
+ headings: string[]
+ /** Every in-document link destination, `#` included (`'#top'`, `'#'`). */
+ anchors: string[]
+}
+
+/**
+ * Scan one markdown document for the two things a table of contents couples:
+ * its ATX headings and its same-document link destinations. Fenced code is
+ * skipped (a `#` inside a fence is a comment, not a heading) and so is the
+ * trailing `#`-run of a closed ATX heading.
+ * @param text - the markdown source.
+ */
+export function scanDocumentAnchors(text: string): DocumentAnchors {
+ const headings: string[] = []
+ const anchors: string[] = []
+ let fence: string | null = null
+ for (const line of text.split('\n')) {
+ const fenceLine = /^ {0,3}(`{3,}|~{3,})/.exec(line)
+ const fenceMarker = fenceLine?.at(1)?.charAt(0)
+ if (fenceMarker !== undefined) {
+ if (fence === null) fence = fenceMarker
+ else if (fence === fenceMarker) fence = null
+ continue
+ }
+ if (fence !== null) continue
+ const heading = /^#{1,6} (.*?)(?: #+)?$/.exec(line)?.at(1)
+ if (heading !== undefined) {
+ headings.push(heading)
+ continue
+ }
+ for (const anchor of line.matchAll(/\]\((#[^)\s]*)\)/g)) {
+ const destination = anchor.at(1)
+ if (destination !== undefined) anchors.push(destination)
+ }
+ }
+ return { headings, anchors }
+}
diff --git a/tests/markdown-images.spec.ts b/tests/markdown-images.spec.ts
index 51fccf9e..660af2d6 100644
--- a/tests/markdown-images.spec.ts
+++ b/tests/markdown-images.spec.ts
@@ -86,6 +86,35 @@ describe('rewriteLocalImageUrls', () => {
expect(out).toContain('/sidebar/file?')
})
+ it('leaves every code-region form alone, tilde fences included', () => {
+ // The image pass had the SAME `~~~` blind spot as the link pass, and it
+ // predates this feature: on the 58d7f71 baseline
+ // `rewriteLocalImageUrls('~~~\n\n~~~')` already produced a
+ // `/sidebar/file` URL. Both passes now share one fence mask
+ // (`markdown-code.ts`).
+ const forms = [
+ '```\n\n```',
+ '````\n```\n\n```\n````',
+ '~~~\n\n~~~',
+ '~~~\nuse `` here\n~~~',
+ ]
+ for (const form of forms) {
+ const out = rewriteLocalImageUrls(form, scope, '/repo/readme.md', ORIGIN)
+ expect(out, form).toBe(form)
+ expect(out, form).not.toContain('/sidebar/file')
+ }
+ // A longer closing fence closes, and a real image after it is rewritten.
+ const after = rewriteLocalImageUrls('~~~\n\n~~~~\n\n', scope, '/repo/readme.md', ORIGIN)
+ expect(after).toContain('~~~\n\n~~~~')
+ expect(after).toMatch(/\[real\]\(.*\/sidebar\/file/)
+ // An unclosed fence runs to the end of the document.
+ expect(rewriteLocalImageUrls('~~~\n', scope, '/repo/readme.md', ORIGIN))
+ .toBe('~~~\n')
+ // A reference definition inside the fence is not harvested either.
+ const ref = rewriteLocalImageUrls('~~~\n![i][r]\n\n[r]: ./p.png\n~~~', scope, '/repo/readme.md', ORIGIN)
+ expect(ref).toBe('~~~\n![i][r]\n\n[r]: ./p.png\n~~~')
+ })
+
it('does not rewrite a reference definition used only by a plain link', () => {
// The `[manual][docs]` link references `[docs]: ./docs.md`, but that
// definition must NOT be redirected to /sidebar/file because it is not
diff --git a/tests/markdown-navigation.spec.ts b/tests/markdown-navigation.spec.ts
index 337416f5..8e3673f2 100644
--- a/tests/markdown-navigation.spec.ts
+++ b/tests/markdown-navigation.spec.ts
@@ -5,6 +5,13 @@
* table. The DOM half — ids on real rendered markdown, the host delegate's
* click path, in-preview scrolling — lives in tests/markdown-surface.spec.tsx,
* which renders the REAL TextEditor (and therefore the real host `MarkdownText`).
+ *
+ * Known narrow edges, recorded rather than fixed (module header carries the
+ * 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.
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
@@ -34,31 +41,15 @@ function fileTarget(
}
describe('githubHeadingSlug', () => {
- it('lower-cases, drops punctuation and collapses whitespace runs to one dash', () => {
+ // The full behavior table (no trim, no whitespace collapsing, emoji + VS16
+ // removal, parity with the real github-slugger regex, and the repos' own
+ // README anchors) lives in tests/markdown-slug.spec.ts. This is the smoke
+ // layer the rest of this file's cases lean on.
+ it('slugs like GitHub: each space its own dash, emoji and punctuation gone', () => {
expect(githubHeadingSlug('Hello, World!')).toBe('hello-world')
- expect(githubHeadingSlug(' Mixed CASE ')).toBe('mixed-case')
- expect(githubHeadingSlug('API 参考 (v2)')).toBe('api-参考-v2')
- expect(githubHeadingSlug('`code` & "quotes"')).toBe('code-quotes')
- expect(githubHeadingSlug('Trailing punctuation:')).toBe('trailing-punctuation')
- })
-
- it('keeps Chinese text as its own id, like GitHub does', () => {
- expect(githubHeadingSlug('中文标题')).toBe('中文标题')
- expect(githubHeadingSlug('已核实的事实')).toBe('已核实的事实')
- // The full-width colon is punctuation: it goes, the text stays.
- expect(githubHeadingSlug('认领文件链接:在侧栏打开')).toBe('认领文件链接在侧栏打开')
- })
-
- it('keeps the dash and underscore GitHub keeps, and drops symbols', () => {
- expect(githubHeadingSlug('Foo-Bar_Baz')).toBe('foo-bar_baz')
- expect(githubHeadingSlug('C++ / C#')).toBe('c-c')
- expect(githubHeadingSlug('🎉 Party')).toBe('party')
- })
-
- it('yields an empty slug for text with nothing to keep', () => {
+ expect(githubHeadingSlug('🎉 Party')).toBe('-party')
+ expect(githubHeadingSlug('🖼️ 特性巡礼')).toBe('-特性巡礼')
expect(githubHeadingSlug('!!!')).toBe('')
- expect(githubHeadingSlug(' ')).toBe('')
- expect(githubHeadingSlug('')).toBe('')
})
})
@@ -197,6 +188,33 @@ describe('rewriteLocalMarkdownLinks', () => {
.toBe('[](./other.md%23x)')
})
+ it('leaves every code-region form alone, tilde fences included', () => {
+ // CommonMark's two fence characters and both span widths. The `~~~` form is
+ // the one the first batch of this feature missed: its content was rewritten
+ // into `[y](./b.md%23u)` (a rendered-diff regression against 58d7f71).
+ const forms = [
+ // triple backticks
+ '```\n[y](./b.md#u)\n```',
+ // four backticks (a fence long enough to CONTAIN a triple one)
+ '````\n```\n[y](./b.md#u)\n```\n````',
+ // triple tildes — the missed one
+ '~~~\n[y](./b.md#u)\n~~~',
+ // an inline code span inside a tilde fence stays inside the fence
+ '~~~\nuse `[y](./b.md#u)` here\n~~~',
+ ]
+ for (const form of forms) {
+ expect(rewriteLocalMarkdownLinks(form, DOC, CWD), form).toBe(form)
+ }
+ // A longer closing fence closes, and prose after it is still rewritten.
+ expect(rewriteLocalMarkdownLinks('~~~\n[x](./b.md#u)\n~~~~\n\n[y](./b.md#v)', DOC, CWD))
+ .toBe('~~~\n[x](./b.md#u)\n~~~~\n\n[y](./b.md%23v)')
+ // An unclosed fence runs to the end of the document, like a renderer.
+ expect(rewriteLocalMarkdownLinks('~~~\n[x](./b.md#u)', DOC, CWD)).toBe('~~~\n[x](./b.md#u)')
+ // Tildes are only a fence at the START of a line: a `~~~` mid-line is prose,
+ // and a link after it is still claimed.
+ expect(rewriteLocalMarkdownLinks('[x](./b.md#u) ~~~ tail', DOC, CWD)).toBe('[x](./b.md%23u) ~~~ tail')
+ })
+
it('rewrites reference definitions, brackets included', () => {
expect(rewriteLocalMarkdownLinks('[id]: ./other.md#标题', DOC, CWD)).toBe('[id]: ./other.md%23标题')
expect(rewriteLocalMarkdownLinks('[id]: <./a b.md#标题>', DOC, CWD)).toBe('[id]: <./a b.md%23标题>')
diff --git a/tests/markdown-slug.spec.ts b/tests/markdown-slug.spec.ts
new file mode 100644
index 00000000..ba8e7731
--- /dev/null
+++ b/tests/markdown-slug.spec.ts
@@ -0,0 +1,204 @@
+/**
+ * `githubHeadingSlug` must produce the id GITHUB gives a heading — that is the
+ * whole contract, because the anchors the repo's own READMEs carry were written
+ * for GitHub. Two independent checks:
+ *
+ * 1. PARITY against the real `github-slugger@2.0.0` slugger regex (vendored in
+ * `tests/helpers/github-slug-reference.ts`), character class by character
+ * class — a "roughly GitHub-like" implementation fails here.
+ * 2. THE REPOS' OWN READMEs, end to end: every in-document anchor must resolve
+ * against the ids their headings get. Before this batch the answer was
+ * **0 of 16 in each file** (the old slugger trimmed and collapsed whitespace
+ * runs, so a heading `🚀 安装` got the id `安装` while its table of contents
+ * pointed at `#-安装`).
+ *
+ * The id ASSIGNMENT (`assignHeadingIds`) is checked here too, on a real DOM
+ * tree, because repeat suffixes are part of GitHub's rule and the renderer
+ * ships bare `h1..h6`. tests/markdown-surface.spec.tsx covers the same pass
+ * through the real renderer.
+ */
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { assignHeadingIds, githubHeadingSlug } from '../src/client/markdown-navigation.ts'
+import { referenceHeadingIds, referenceSlug, scanDocumentAnchors } from './helpers/github-slug-reference.ts'
+
+const REPO_ROOT = process.cwd()
+
+/** The repo's own READMEs: the two documents whose anchors this batch must fix. */
+const README_FILES = ['README.md', 'README_EN.md']
+
+function readme(name: string): string {
+ return readFileSync(join(REPO_ROOT, name), 'utf8')
+}
+
+/**
+ * Drop the variation selectors from a heading text. GitHub renders an emoji
+ * heading into `🚀 安装`, and the slug text it hands
+ * `github-slugger` is the element's `alt` value — `🚀` WITHOUT the U+FE0F that
+ * followed it in the source. The vendored oracle has no such pipeline, so it is
+ * fed the same shape (the emoji itself it drops by range, the selector it does
+ * not — the deliberate divergence the parity case below pins).
+ */
+function vs16Free(text: string): string {
+ return text.replace(/[\uFE00-\uFE0F]/gu, '')
+}
+
+describe('githubHeadingSlug', () => {
+ it('lower-cases ASCII, drops punctuation and symbols, keeps - and _', () => {
+ expect(githubHeadingSlug('Hello, World!')).toBe('hello-world')
+ expect(githubHeadingSlug('Foo-Bar_Baz')).toBe('foo-bar_baz')
+ // `/` is dropped WITHOUT collapsing the two spaces it sat between: GitHub
+ // yields `c--c`, the old trimmed-and-collapsed slugger yielded `c-c`.
+ expect(githubHeadingSlug('C++ / C#')).toBe('c--c')
+ expect(referenceSlug('C++ / C#')).toBe('c--c')
+ expect(githubHeadingSlug('`code` & "quotes"')).toBe('code--quotes')
+ expect(referenceSlug('`code` & "quotes"')).toBe('code--quotes')
+ expect(githubHeadingSlug('Trailing punctuation:')).toBe('trailing-punctuation')
+ })
+
+ it('does NOT trim and does NOT collapse whitespace runs — each space is its own dash', () => {
+ // GitHub's slugger is `text.toLowerCase().replace(RE, '').replace(/ /g, '-')`:
+ // no trim, no run collapsing. This is what makes the READMEs' `#-安装`
+ // anchors work at all after the emoji is removed.
+ expect(githubHeadingSlug(' Mixed CASE ')).toBe('--mixed---case--')
+ expect(githubHeadingSlug('Installation')).toBe('installation')
+ // The repo's own evidence, verbatim: `🛠️ Development & Build` is linked as
+ // `#-development--build` — a leading dash from the space the emoji left,
+ // and a double dash from the removed `&`.
+ expect(githubHeadingSlug('🛠️ Development & Build')).toBe('-development--build')
+ // A tab is not a space, so it is dropped rather than turned into a dash.
+ expect(githubHeadingSlug('a\tb')).toBe('ab')
+ })
+
+ it('drops emoji and the variation selectors that follow them', () => {
+ // `🎉 Party` → the space before `Party` survives as a dash.
+ expect(githubHeadingSlug('🎉 Party')).toBe('-party')
+ // `🖼️` is U+1F5BC + U+FE0F: both go, and the id carries no invisible mark.
+ expect(githubHeadingSlug('🖼️ 特性巡礼')).toBe('-特性巡礼')
+ expect(githubHeadingSlug('🖼️ 特性巡礼')).not.toContain('\uFE0F')
+ expect(githubHeadingSlug('🚀 安装')).toBe('-安装')
+ expect(githubHeadingSlug('⌨️ 快捷键')).toBe('-快捷键')
+ // A flag emoji is a regional-indicator pair (`\p{So}`, outside
+ // Extended_Pictographic) — dropped all the same.
+ expect(githubHeadingSlug('🇨🇳 中国')).toBe('-中国')
+ // ZWJ sequences: the joiner is format-category, the pictographs go too.
+ expect(githubHeadingSlug('👨👩👧 Family')).toBe('-family')
+ // Nothing left at all: the slug is empty and no id is assigned.
+ expect(githubHeadingSlug('🚀')).toBe('')
+ })
+
+ it('keeps letters, digits and combining marks of every script', () => {
+ expect(githubHeadingSlug('中文标题')).toBe('中文标题')
+ expect(githubHeadingSlug('已核实的事实')).toBe('已核实的事实')
+ expect(githubHeadingSlug('API 参考 (v2)')).toBe('api-参考-v2')
+ // The full-width colon is punctuation: it goes, the text stays.
+ expect(githubHeadingSlug('认领文件链接:在侧栏打开')).toBe('认领文件链接在侧栏打开')
+ // A combining mark is NOT punctuation: `é` written as `e` + U+0301 keeps
+ // both halves (github-slugger keeps `\p{M}` too).
+ expect(githubHeadingSlug('Cafe\u0301')).toBe('cafe\u0301')
+ // Non-ASCII digits and letters survive as themselves.
+ expect(githubHeadingSlug('Γειά σου Κόσμε')).toBe('γειά-σου-κόσμε')
+ })
+
+ it('yields an empty slug for text with nothing to keep', () => {
+ expect(githubHeadingSlug('!!!')).toBe('')
+ expect(githubHeadingSlug('')).toBe('')
+ // Whitespace is not "nothing" to GitHub — each space is a dash, so a
+ // space-only heading has a non-empty id (and `assignHeadingIds` keeps it).
+ expect(githubHeadingSlug(' ')).toBe('---')
+ })
+
+ it('matches the real github-slugger regex on emoji-free text', () => {
+ // Everything the reference slugger keeps or drops that is NOT an emoji: the
+ // Unicode ranges, the punctuation/symbol classes, case folding. (Emoji and
+ // variation selectors are excluded on purpose — see `vs16Free` below.)
+ const samples = [
+ ...README_FILES.flatMap(name => scanDocumentAnchors(readme(name)).headings.map(vs16Free)),
+ 'Hello, World!',
+ ' Mixed CASE ',
+ 'API 参考 (v2)',
+ '认领文件链接:在侧栏打开',
+ 'Cafe\u0301 au lait',
+ 'Foo-Bar_Baz',
+ 'a\tb',
+ 'Trailing punctuation:',
+ 'C++ / C#',
+ '100% 覆盖 · 12/12',
+ 'ΑΒΓ αβγ',
+ 'Привет, мир',
+ '한국어 제목',
+ 'emoji-free ~~~ tilde fence',
+ '1. 有序标题',
+ '– dash –',
+ '已核实的事实',
+ ]
+
+ // Every README heading and every sample above must slug identically.
+ for (const sample of samples) {
+ expect(githubHeadingSlug(sample), sample).toBe(referenceSlug(sample))
+ }
+ // Guard the guard: the list really did carry the interesting scripts, and
+ // the README headings really were in it.
+ expect(samples).toContain('认领文件链接:在侧栏打开')
+ expect(samples).toContain('Cafe\u0301 au lait')
+ // The README headings were in the list too, emoji stripped (the emoji case
+ // is pinned separately below).
+ const stripped = vs16Free('🖼️ 特性巡礼')
+ expect(stripped).toBe('🖼 特性巡礼')
+ expect(samples).toContain(stripped)
+ expect(githubHeadingSlug(stripped)).toBe(referenceSlug(stripped))
+ // The one deliberate divergence: github-slugger KEEPS U+FE0F (the emoji is
+ // rendered to an `
` before the slugger ever runs, so upstream never has
+ // to drop it). Against the raw text `🖼️` would slug to `️` — an invisible
+ // id — which is exactly what we fix.
+ expect(referenceSlug('🖼️ 特性巡礼')).toBe('\uFE0F-特性巡礼')
+ expect(githubHeadingSlug('🖼️ 特性巡礼')).toBe('-特性巡礼')
+ })
+
+ it('assigns document-order ids with GitHub repeat suffixes, skipping empty slugs', () => {
+ const root = document.createElement('div')
+ root.innerHTML = [
+ 'Hello, World!
',
+ 'Hello, World!
',
+ 'Hello, World!
',
+ '🚀
',
+ 'Authored
',
+ 'Authored
',
+ '🚀 安装
',
+ ].join('')
+ assignHeadingIds(root)
+ expect([...root.querySelectorAll('h1, h2, h3, h4, h5, h6')].map(heading => heading.id))
+ .toEqual(['hello-world', 'hello-world-1', 'hello-world-2', '', 'authored', 'authored-1', '-安装'])
+ // The generated ids are the ones the reference slugger would produce.
+ expect(referenceHeadingIds(['Hello, World!', 'Hello, World!', 'Hello, World!', '', 'Authored', 'Authored']))
+ .toEqual(['hello-world', 'hello-world-1', 'hello-world-2', '', 'authored', 'authored-1'])
+ })
+})
+
+describe('the repos\u2019 own READMEs', () => {
+ for (const name of README_FILES) {
+ it(`${name}: every in-document anchor resolves against a real heading id`, () => {
+ const { headings, anchors } = scanDocumentAnchors(readme(name))
+ // The ids the PREVIEW actually puts on the headings — the plugin's own
+ // slugger, run over the parser's own heading list, exactly as
+ // `assignHeadingIds` does it in the DOM.
+ const ids = new Set(headings.map(heading => githubHeadingSlug(heading)).filter(id => id !== ''))
+ const unresolved = anchors.filter(anchor => !ids.has(decodeURIComponent(anchor.slice(1))))
+ // The regression this guards: `0/16 resolved` before this batch (the old
+ // slugger trimmed and collapsed whitespace, so `🚀 安装` got the id `安装`
+ // while its table of contents pointed at `#-安装`).
+ expect(anchors.length).toBeGreaterThanOrEqual(15)
+ expect(unresolved).toEqual([])
+ // Guard the other direction: resolution is not vacuous — the ids really
+ // are the emoji-stripped GitHub spellings, and an anchor no heading
+ // produces would still fail.
+ const expectsChinese = name === 'README.md'
+ expect(ids.has('-特性巡礼')).toBe(expectsChinese)
+ expect(ids.has('\uFE0F-特性巡礼')).toBe(false)
+ expect(ids.has('-preview-plugins-file-previewers')).toBe(false)
+ expect([...ids].filter(id => id.includes('\uFE0F'))).toEqual([])
+ })
+ }
+})
diff --git a/tests/markdown-surface.spec.tsx b/tests/markdown-surface.spec.tsx
index 6d534203..299fa4a9 100644
--- a/tests/markdown-surface.spec.tsx
+++ b/tests/markdown-surface.spec.tsx
@@ -17,6 +17,8 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
import { act } from 'react-dom/test-utils'
import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
import { renderRoot, setupReactAct } from './test-utils.ts'
@@ -331,6 +333,103 @@ describe('the markdown preview surface', () => {
mounted.unmount()
})
+ it('scrolls the nearest SCROLLABLE ANCESTOR, not the container itself', () => {
+ // jsdom applies no stylesheet and derives no overflow from layout, so the
+ // one way to reach the "found an ancestor scroller" branch is to inject the
+ // computed style the browser would report. Without this case the branch was
+ // unreachable from the shipped suite: making `scrollHostFor` return the
+ // container unconditionally left all 33 cases green.
+ const scroller = document.createElement('div')
+ const container = document.createElement('div')
+ scroller.append(container)
+ document.body.append(scroller)
+ const containerScrollTop = watchScrollTop(container)
+ Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 })
+ Object.defineProperty(scroller, 'clientHeight', { configurable: true, value: 100 })
+ scroller.scrollTop = 20
+ const computed = window.getComputedStyle.bind(window)
+ const style = vi.spyOn(window, 'getComputedStyle').mockImplementation(
+ (element: Element): CSSStyleDeclaration => {
+ const real = computed(element as HTMLElement)
+ if (element === scroller) {
+ return { ...real, overflowY: 'auto', overflow: 'auto' } as unknown as CSSStyleDeclaration
+ }
+ return { ...real, overflowY: 'visible', overflow: 'visible' } as unknown as CSSStyleDeclaration
+ },
+ )
+ try {
+ const target = document.createElement('h2')
+ container.append(target)
+ // The scroll offset is measured against the SCROLLER's own box and its
+ // live scrollTop: 480 - 100 + 20 - 8 = 392.
+ stubRectTop(scroller, 100)
+ stubRectTop(container, 100)
+ stubRectTop(target, 480)
+ expect(jumpToFragment(container, 'anything')).toBe(false) // no such id yet
+ target.id = 'found'
+ expect(jumpToFragment(container, 'found')).toBe(true)
+ expect(scroller.scrollTop).toBe(392)
+ // The container is NOT the scroller: it must not be written to at all.
+ expect(containerScrollTop()).toBe(0)
+ expect(scrollTo).not.toHaveBeenCalled()
+ expect(scrollIntoView).not.toHaveBeenCalled()
+ } finally {
+ style.mockRestore()
+ }
+ })
+
+ it('scrolls the container itself when no ancestor scrolls', () => {
+ // The fallback half of the same branch: with every ancestor reporting
+ // `visible`, the container is the scroller (no `window.scrollTo`, no
+ // `scrollIntoView` — either would drag the whole sidebar).
+ const mounted = mountEditor('[jump](#目标标题)\n\n## 目标标题\n', '/p/docs/README.md')
+ const surface = surfaceOf(mounted.container)
+ const scrollTop = watchScrollTop(surface)
+ stubRectTop(surface, 60)
+ stubRectTop(surface.querySelector('h2')!, 260)
+ click(fileLink(surface, '#目标标题')!)
+ expect(scrollTop()).toBe(192)
+ expect(scrollTo).not.toHaveBeenCalled()
+ expect(scrollIntoView).not.toHaveBeenCalled()
+ mounted.unmount()
+ })
+
+ it('drives the ancestor scroller through the real surface too', () => {
+ // The same branch, end to end: the real TextEditor's own delegate, a click
+ // on a real rendered link, and the write landing on the surrounding pane.
+ const mounted = mountEditor('[jump](#目标标题)\n\n## 目标标题\n', '/p/docs/README.md')
+ const scroller = document.createElement('div')
+ document.body.append(scroller)
+ scroller.append(mounted.container)
+ const surface = surfaceOf(mounted.container)
+ const heading = surface.querySelector('h2#目标标题')!
+ const containerScrollTop = watchScrollTop(surface)
+ Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 })
+ Object.defineProperty(scroller, 'clientHeight', { configurable: true, value: 100 })
+ const computed = window.getComputedStyle.bind(window)
+ const style = vi.spyOn(window, 'getComputedStyle').mockImplementation(
+ (element: Element): CSSStyleDeclaration => {
+ const real = computed(element as HTMLElement)
+ const overflowY = element === scroller ? 'auto' : 'visible'
+ return { ...real, overflowY, overflow: overflowY } as unknown as CSSStyleDeclaration
+ },
+ )
+ try {
+ stubRectTop(scroller, 0)
+ stubRectTop(surface, 0)
+ stubRectTop(heading, 300)
+ scroller.scrollTop = 0
+ click(fileLink(surface, '#目标标题')!)
+ expect(scroller.scrollTop).toBe(292)
+ expect(containerScrollTop()).toBe(0)
+ expect(scrollTo).not.toHaveBeenCalled()
+ expect(scrollIntoView).not.toHaveBeenCalled()
+ } finally {
+ style.mockRestore()
+ }
+ mounted.unmount()
+ })
+
it('opens a line destination without treating its line as an anchor', async () => {
// `#L24` is the host's own grammar (the parser hands it over as
// `options.line`), so the rewriter must leave it alone and the open must
@@ -396,6 +495,44 @@ describe('the markdown preview surface', () => {
expect(againScrollTop()).toBe(0)
again.unmount()
})
+
+ it('resolves and scrolls for EVERY table-of-contents anchor of the repo\u2019s own READMEs', () => {
+ // The acceptance case for the slug fix, through the real renderer: the
+ // READMEs are the documents whose anchors were 0/15 before it (the heading
+ // `🚀 安装` got the id `安装` while its contents entry pointed at `#-安装`,
+ // so the click was claimed and then did nothing). The probe takes each
+ // TOC bullet's link, finds the heading with that very id, and requires the
+ // click to move the surface's own scroller.
+ for (const name of ['README.md', 'README_EN.md']) {
+ const mounted = mountEditor(readFileSync(join(process.cwd(), name), 'utf8'), `/p/${name}`)
+ const surface = surfaceOf(mounted.container)
+ const headings = [...surface.querySelectorAll('h1, h2, h3, h4, h5, h6')]
+ const tocLines = readFileSync(join(process.cwd(), name), 'utf8').split('\n').slice(34, 44)
+ const tocAnchors = tocLines.flatMap(line => [...line.matchAll(/\]\((#[^)\s]*)\)/g)])
+ .map(match => match[1] ?? '')
+ .filter(anchor => anchor !== '')
+ expect(tocAnchors.length, name).toBeGreaterThanOrEqual(15)
+
+ stubRectTop(surface, 0)
+ const readScrollTop = watchScrollTop(surface)
+ const unresolved: string[] = []
+ for (const anchor of tocAnchors) {
+ const fragment = decodeURIComponent(anchor.slice(1))
+ const heading = headings.find(candidate => candidate.id === fragment)
+ const link = [...surface.querySelectorAll('button')].find(button => button.title === anchor)
+ if (heading === undefined || link === undefined) {
+ unresolved.push(`${anchor} (id=${heading === undefined ? 'missing' : 'ok'}, link=${link === undefined ? 'missing' : 'ok'})`)
+ continue
+ }
+ stubRectTop(heading, 300)
+ surface.scrollTop = 0
+ click(link)
+ if (readScrollTop() === 0) unresolved.push(`${anchor} (click did not scroll)`)
+ }
+ expect(unresolved, name).toEqual([])
+ mounted.unmount()
+ }
+ })
})
describe('the document pass', () => {