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\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:
1 parent
5b768c86f3
commit
fab329d469
9 files changed
+698
-50
No files matched your search
@@ -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)] ?? ''),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user