fix(markdown): match GitHub's heading slug and mask ~~~ fences (#363)

Two defects the independent verification rejected, plus the test gaps they
left behind.

1. `githubHeadingSlug` was not GitHub's slugger. It trimmed and collapsed
   whitespace runs (GitHub does neither: every space becomes its own dash) and
   kept `\p{M}`, which left the variation selector of `🖼️` inside the id. The
   consequence was the issue's main scenario: the repo's OWN READMEs resolved
   **0 of 15** table-of-contents anchors, and the click was claimed yet did
   nothing (`scrollTop` stayed 0). The slug is now `toLowerCase()`, drop
   pictographs / `\uFE00-\uFE0F` / regional indicators / `\p{C}`, drop
   everything that is not a letter, digit, combining mark, space, `-` or `_`,
   then each space → `-`. Emoji are removed here because GitHub removes them
   while RENDERING the heading (to `<img>`) before its slugger runs; that is
   the one deliberate difference from `github-slugger`, and it is what turns
   `🚀 安装` into GitHub's real `-安装`.

2. Both source rewriters inlined a fence mask that only recognised ```, so a
   link or image demonstrated inside a `~~~` fence was rewritten
   (`[y](./b.md#u)` → `[y](./b.md%23u)`; the image half predates this feature:
   `rewriteLocalImageUrls('~~~\n![i](./p.png)\n~~~')` already produced a
   `/sidebar/file` URL on 58d7f71). One shared mask now lives in
   `src/client/markdown-code.ts` (CommonMark: 3+ backticks OR 3+ tildes, a
   closing fence no shorter than its opener, an unclosed fence running to the
   end of the text) and both passes use it.

Evidence (all on the merged tree, HEAD after `git merge origin/dev`):
- Real `TextEditor` + real host `MarkdownText`, every TOC anchor clicked:
  README.md `0/15 → 15/15`, README_EN.md `0/15 → 15/15` (shipped as a case in
  tests/markdown-surface.spec.tsx; the id-level counts are 0/16 → 16/16).
- Parity against the actual `github-slugger@2.0.0` regex (vendored in
  tests/helpers/github-slug-reference.ts), plus explicit emoji/VS16 cases.
- Mutation: restoring the old trim+collapse+`\p{M}` slug reddens 9 cases
  (both README cases included); dropping the tilde fence reddens the new
  fence case in BOTH the link and the image spec; forcing `scrollHostFor` to
  return the container reddens the two new ancestor-scroller cases.
- `scrollHostFor`'s ancestor branch was unreachable from the shipped suite
  (the mutation above used to leave 33/33 green): tests/markdown-surface.spec.tsx
  now injects the computed style (`overflowY: auto` + `scrollHeight`/
  `clientHeight`) and asserts the write lands on the ancestor, that neither
  `window.scrollTo` nor `scrollIntoView` is called, and that the container's
  own `scrollTop` is never written.

Also: the untrue "exactly like GitHub does" comment, four-form fence cases per
pass (``` / ```` / ~~~ / an inline span inside ~~~), a CHANGELOG entry, and the
recorded narrow edges (a destination with an escaped parenthesis or a
single-quoted title is not claimed — plain text, unchanged; `#L24` does not
jump to a line).

Gates: typecheck / lint clean, `vitest run --maxWorkers=3` 182 files, 2120
passed | 13 skipped; `pnpm build` complete; mount lane
(`DSH_CMD='npx -y --package @deepseek-ai/dsh@0.2.0-rc.1 dsh' pnpm test:mount`)
9 passed (2.0m), exit 0. The bare `pnpm test:mount` now dies in preflight
because the installed CLI is 0.2.0-rc.2 while the baseline pins 0.2.0-rc.1;
the lane count is 9 rather than the verifier's 11 because merging origin/dev
removed the two WCO/preset cases with the titleBar mechanism.
This commit is contained in:
Menghuan1918 committed 2026-10-06 00:19:11 +08:00
1 parent 5b768c86f3
commit fab329d469
9 files changed
+698 -50

No files matched your search

+8
View File
@@ -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-特性巡礼"`)。
- 🧹 `<a id="x"></a>` 这类空显式锚点(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)`、`![i](./p.png)` 会被写成 `/sidebar/file` URL(与 58d7f71 基线逐字对比,这是本批唯一的渲染差异)。现在抽出一个共享 mask(`src/client/markdown-code.ts`,CommonMark 规则:**3 个及以上反引号或 3 个及以上波浪号**开栏、闭合不短于开栏、未闭合则延伸到文末),两个 pass 共用。**图片那条盲区是既有缺陷而非本批引入**(58d7f71 上 `rewriteLocalImageUrls('~~~\n![i](./p.png)\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 份第三语言词典。
+132
View File
@@ -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 `![i](./p.png)` 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)] ?? ''),
}
}
+8 -11
View File
@@ -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 `![alt](./img.png)`
* 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 `![${alt}](${resolve(dest)})`
@@ -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)
}
+45 -16
View File
@@ -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
* `<img>`, 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 `<img>`), 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)
}
/**
+94
View File
@@ -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`
* (<https://github.com/Flet/github-slugger>, 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 `<img>`) 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-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\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\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uLine truncated
/* 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<string>()
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 }
}
+29
View File
@@ -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![i](./p.png)\n~~~')` already produced a
// `/sidebar/file` URL. Both passes now share one fence mask
// (`markdown-code.ts`).
const forms = [
'```\n![i](./p.png)\n```',
'````\n```\n![i](./p.png)\n```\n````',
'~~~\n![i](./p.png)\n~~~',
'~~~\nuse `![i](./p.png)` 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![i](./p.png)\n~~~~\n\n![real](./real.png)', scope, '/repo/readme.md', ORIGIN)
expect(after).toContain('~~~\n![i](./p.png)\n~~~~')
expect(after).toMatch(/\[real\]\(.*\/sidebar\/file/)
// An unclosed fence runs to the end of the document.
expect(rewriteLocalImageUrls('~~~\n![i](./p.png)', scope, '/repo/readme.md', ORIGIN))
.toBe('~~~\n![i](./p.png)')
// 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
+41 -23
View File
@@ -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('[![alt](./pic.png)](./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标题>')
+204
View File
@@ -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 `<g-emoji>🚀</g-emoji> 安装`, 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 `<img>` 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 = [
'<h2>Hello, World!</h2>',
'<h2>Hello, World!</h2>',
'<h2>Hello, World!</h2>',
'<h2>🚀</h2>',
'<h2 id="authored">Authored</h2>',
'<h2>Authored</h2>',
'<h3>🚀 安装</h3>',
].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([])
})
}
})
+137
View File
@@ -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<HTMLElement>('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<HTMLElement>('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<HTMLButtonElement>('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', () => {