fix(markdown): render anchors without a stray close tag and keep <details> summaries as direct children
Two raw-HTML preview defects (client rendering only, no DSH source touched):
- A stray `</a>` from an author's `<a id="x"></a>` was printed as literal text.
The host renderer emits one text node per raw-HTML token, so the open tag and
its close tag arrive as siblings; DOMPurify drops a lone close tag (no element
children), which fell into the inline pass's "no elements means prose, keep
the text" branch. The pass now deletes a node that is nothing but a close tag,
keeping the anchor id and leaving comparison prose (`a < b`, `x </ y`) intact.
- A `<details>` fold showed the UA's own "Details" label while the authored
summary text dropped into the body: `<summary>…</summary>` is a balanced span,
so analyzeHtmlSegment reduced it to an `html` leaf wrapped in a block div,
which is not a direct child of `<details>` and therefore not honored as the
disclosure widget. The renderer now hoists a leaf-leading summary into a real
`<summary>` element inside its details frame (attributes via the shared props
extraction, media/anchors still hardened), with no hardcoded label.
Also scope `.editorMd details > summary { cursor: pointer }` so a hoisted
summary keeps its pointer cursor (the old `.editorHtmlBlock summary` rule no
longer matches once it leaves the leaf wrapper).
Tests: 8 new/tightened cases in tests/markdown-html-render.spec.tsx (13 -> 21),
plus a seeded anchor and direct-child summary assertions in the real mount
smoke (tests/e2e/mount.e2e.ts). Verified pnpm test (113 files / 1140 passed),
typecheck, lint, and pnpm test:mount (7/7).
Fixes #778
This commit is contained in:
1 parent
ad6b0b1486
commit
f5ffd10474
4 files changed
+272
-18
No files matched your search
+102
-16
@@ -46,6 +46,16 @@ export interface MarkdownHtmlMedia {
|
||||
/** Tag-like text in a rendered text node — the inline pass gate. */
|
||||
const TAGLIKE_TEXT_RE = /<\/?[a-zA-Z][a-zA-Z0-9-]*[\s/>]/
|
||||
|
||||
/**
|
||||
* A text node that is nothing but one close tag (`</a>`) at its edges. The host
|
||||
* renderer emits one text node per raw-HTML token, so an author's
|
||||
* `<a id="x"></a>` arrives as two sibling nodes: the open tag (which this pass
|
||||
* swaps for a sanitized element) and this stray close tag. DOMPurify drops a
|
||||
* lone close tag, so it can never be swapped — and unlike prose it carries no
|
||||
* text a reader should see, so the pass deletes it instead of printing it.
|
||||
*/
|
||||
const ORPHAN_CLOSE_TAG_RE = /^<\/[a-zA-Z][a-zA-Z0-9-]*\s*>$/
|
||||
|
||||
/** Explicit denylist on top of DOMPurify's defaults: no active content, no
|
||||
* form chrome, no document-level elements inside a preview. */
|
||||
const PURIFY_FORBID_TAGS = [
|
||||
@@ -86,6 +96,8 @@ function sanitizeHtmlBlock(source: string, media: MarkdownHtmlMedia): string {
|
||||
* Sanitize literal tag text from a rendered markdown text node. Returns null
|
||||
* when nothing real survived (pure prose like `a < b` — the DOMPurify output
|
||||
* has no element children), so the caller leaves the text node untouched.
|
||||
* A node that is nothing but a close tag never reaches here — the caller drops
|
||||
* it (see {@link ORPHAN_CLOSE_TAG_RE}).
|
||||
*/
|
||||
function sanitizeInlineHtml(text: string, media: MarkdownHtmlMedia): string | null {
|
||||
const holder = document.createElement('span')
|
||||
@@ -98,12 +110,26 @@ function sanitizeInlineHtml(text: string, media: MarkdownHtmlMedia): string | nu
|
||||
return holder.innerHTML
|
||||
}
|
||||
|
||||
/**
|
||||
* React props for a sanitized element: `class`/`for` map to their React names,
|
||||
* `style` is dropped (React needs an object; wrappers with inline styles are
|
||||
* vanishingly rare and not worth a CSS parser), and event handlers / invalid
|
||||
* attribute names never survive DOMPurify's defaults but are filtered anyway.
|
||||
*/
|
||||
function propsFromElement(element: Element): Record<string, string> {
|
||||
const props: Record<string, string> = {}
|
||||
for (const attr of element.attributes) {
|
||||
if (/^on/i.test(attr.name) || !/^[a-zA-Z][a-zA-Z0-9:._-]*$/.test(attr.name)) continue
|
||||
if (attr.name === 'style') continue
|
||||
props[attr.name === 'class' ? 'className' : attr.name === 'for' ? 'htmlFor' : attr.name] = attr.value
|
||||
}
|
||||
return props
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a wrapper open tag (`<details open>`) into React props. Returns
|
||||
* null when DOMPurify dropped the whole tag (denied element) — the renderer
|
||||
* then treats the wrapper as transparent. `class`/`for` map to their React
|
||||
* names; `style` is dropped (React needs an object; wrappers with inline
|
||||
* styles are vanishingly rare and not worth a CSS parser).
|
||||
* then treats the wrapper as transparent.
|
||||
*/
|
||||
function sanitizeTagProps(tag: string, attrs: string): Record<string, string> | null {
|
||||
const probe = DOMPurify.sanitize(`<${tag}${attrs}></${tag}>`, {
|
||||
@@ -114,13 +140,37 @@ function sanitizeTagProps(tag: string, attrs: string): Record<string, string> |
|
||||
holder.innerHTML = probe
|
||||
const element = holder.firstElementChild
|
||||
if (element === null || element.tagName.toLowerCase() !== tag) return null
|
||||
const props: Record<string, string> = {}
|
||||
for (const attr of element.attributes) {
|
||||
if (/^on/i.test(attr.name) || !/^[a-zA-Z][a-zA-Z0-9:._-]*$/.test(attr.name)) continue
|
||||
if (attr.name === 'style') continue
|
||||
props[attr.name === 'class' ? 'className' : attr.name === 'for' ? 'htmlFor' : attr.name] = attr.value
|
||||
return propsFromElement(element)
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a sanitized HTML leaf whose first element is a `<summary>` into that
|
||||
* summary's props/inner markup plus the remainder. HTML's content model makes
|
||||
* the summary a disclosure widget **only** as a direct child of `<details>`,
|
||||
* but every balanced leaf renders inside a block wrapper — so a README's
|
||||
* `<details>` + `<summary>` would otherwise show the browser's own default
|
||||
* label ("Details") and demote the authored text to body content. Returns
|
||||
* null when the leaf's first element is anything else (or non-whitespace text
|
||||
* precedes it), leaving the plain leaf path untouched. Media and anchors
|
||||
* inside the hoisted summary go through the same hardening as any leaf.
|
||||
*/
|
||||
function splitLeadingSummary(
|
||||
html: string,
|
||||
media: MarkdownHtmlMedia,
|
||||
): { props: Record<string, string>; inner: string; rest: string } | null {
|
||||
const holder = document.createElement('div')
|
||||
holder.innerHTML = html
|
||||
const first = holder.firstElementChild
|
||||
if (first === null || first.tagName.toLowerCase() !== 'summary') return null
|
||||
for (const node of holder.childNodes) {
|
||||
if (node === first) break
|
||||
if ((node.textContent ?? '').trim() !== '') return null
|
||||
}
|
||||
return props
|
||||
postProcessSanitized(first, media)
|
||||
const props = propsFromElement(first)
|
||||
const inner = first.innerHTML
|
||||
first.remove()
|
||||
return { props, inner, rest: holder.innerHTML }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,6 +197,13 @@ function runInlineHtmlPass(container: HTMLElement, media: MarkdownHtmlMedia): vo
|
||||
const targets: Text[] = []
|
||||
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) targets.push(node as Text)
|
||||
for (const node of targets) {
|
||||
// A lone close tag is not prose and cannot be sanitized into an element:
|
||||
// drop it so `</a>` never renders as text (the matching open tag already
|
||||
// became its element, so anchors keep their id and stay invisible).
|
||||
if (ORPHAN_CLOSE_TAG_RE.test(node.data.trim())) {
|
||||
node.remove()
|
||||
continue
|
||||
}
|
||||
const html = sanitizeInlineHtml(node.data, media)
|
||||
if (html === null) continue
|
||||
const span = document.createElement('span')
|
||||
@@ -210,6 +267,8 @@ type PreparedHtmlPart =
|
||||
| { kind: 'html'; html: string }
|
||||
| { kind: 'open'; tag: string; props: Record<string, string> | null }
|
||||
| { kind: 'close' }
|
||||
/** A `<summary>` hoisted out of a leaf so it can be a `<details>` direct child. */
|
||||
| { kind: 'summary'; props: Record<string, string>; inner: string }
|
||||
|
||||
type PreparedSegment =
|
||||
| { kind: 'markdown'; text: string; hasMermaid: boolean }
|
||||
@@ -246,14 +305,36 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr
|
||||
hasMermaid: splitMermaidBlocks(text).some((block) => block.kind === 'mermaid'),
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: 'html',
|
||||
parts: analyzeHtmlSegment(segment.text).parts.map((part): PreparedHtmlPart => {
|
||||
if (part.kind === 'html') return { kind: 'html', html: sanitizeHtmlBlock(part.html, media) }
|
||||
if (part.kind === 'open') return { kind: 'open', tag: part.tag, props: sanitizeTagProps(part.tag, part.attrs) }
|
||||
return { kind: 'close' }
|
||||
}),
|
||||
const parts: PreparedHtmlPart[] = []
|
||||
/** Tag of the wrapper the previous part opened — the only place a
|
||||
* following leaf can hoist a `<summary>` out of its block wrapper. */
|
||||
let openTag: string | null = null
|
||||
for (const part of analyzeHtmlSegment(segment.text).parts) {
|
||||
if (part.kind === 'html') {
|
||||
const html = sanitizeHtmlBlock(part.html, media)
|
||||
const summary = openTag === 'details' ? splitLeadingSummary(html, media) : null
|
||||
if (summary === null) {
|
||||
parts.push({ kind: 'html', html })
|
||||
} else {
|
||||
parts.push({ kind: 'summary', props: summary.props, inner: summary.inner })
|
||||
// Anything after the summary keeps the plain block-leaf treatment.
|
||||
if (summary.rest.trim() !== '') parts.push({ kind: 'html', html: summary.rest })
|
||||
}
|
||||
openTag = null
|
||||
continue
|
||||
}
|
||||
if (part.kind === 'open') {
|
||||
const props = sanitizeTagProps(part.tag, part.attrs)
|
||||
parts.push({ kind: 'open', tag: part.tag, props })
|
||||
// A denied wrapper renders transparent, so its children have no element
|
||||
// to be a direct child of — never hoist a summary into that case.
|
||||
openTag = props === null ? null : part.tag
|
||||
continue
|
||||
}
|
||||
parts.push({ kind: 'close' })
|
||||
openTag = null
|
||||
}
|
||||
return { kind: 'html', parts }
|
||||
// `media` is a memoized object in the host (TextEditor); identity tracks
|
||||
// scope/path/origin changes so sanitization re-runs exactly when needed.
|
||||
}), [info, media])
|
||||
@@ -275,6 +356,11 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr
|
||||
if (part.kind === 'html') {
|
||||
if (part.html.trim() === '') continue
|
||||
emit(<HtmlLeaf key={`html-${key += 1}`} html={part.html} />)
|
||||
} else if (part.kind === 'summary') {
|
||||
// Emitted as a real element (not a block leaf) so it stays a direct
|
||||
// child of the enclosing <details> — the content-model requirement for
|
||||
// it to act as the disclosure widget, with the authored label.
|
||||
emit(createElement('summary', { ...part.props, key: `summary-${key += 1}`, dangerouslySetInnerHTML: { __html: part.inner } }))
|
||||
} else if (part.kind === 'open') {
|
||||
frames.push({ tag: part.tag, props: part.props, children: [] })
|
||||
} else {
|
||||
|
||||
@@ -2117,7 +2117,11 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.editorHtmlBlock summary {
|
||||
/* A `<summary>` the renderer hoisted out of a leaf is a direct child of its
|
||||
`<details>` (see MarkdownHtml.tsx), so it no longer sits inside
|
||||
`.editorHtmlBlock` — match it against the preview container too. */
|
||||
.editorHtmlBlock summary,
|
||||
.editorMd details > summary {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@ async function seedSession(): Promise<void> {
|
||||
' <script>alert(1)</script>',
|
||||
'</div>',
|
||||
'',
|
||||
'<a id="readme-anchor"></a>',
|
||||
'## Setup',
|
||||
'',
|
||||
'[docs link][def]',
|
||||
@@ -545,6 +546,26 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
|
||||
const details = pane.locator('details')
|
||||
await expect(details, 'the details run must render as a real element').toHaveCount(1, { timeout: 30_000 })
|
||||
await expect(details.locator('summary'), 'the details summary must render').toHaveCount(1)
|
||||
// Direct child, not merely a descendant: HTML only honors a summary there,
|
||||
// so a block-leaf wrapper in between silently swaps in the UA's own label.
|
||||
await expect(
|
||||
details.locator(':scope > summary'),
|
||||
'the summary must be a direct child of <details>',
|
||||
).toHaveCount(1)
|
||||
await expect(
|
||||
details.locator(':scope > summary'),
|
||||
'the authored summary text must be the disclosure label',
|
||||
).toHaveText('Steps')
|
||||
// The bare anchor line: the id must survive as a real anchor, and the stray
|
||||
// `</a>` half of the pair must never be printed as source text.
|
||||
await expect(
|
||||
pane.locator('a#readme-anchor'),
|
||||
'an author anchor must keep its id for deep links',
|
||||
).toHaveCount(1)
|
||||
await expect(
|
||||
pane.locator('p:has(a#readme-anchor)'),
|
||||
'the stray close tag must not be printed next to its anchor',
|
||||
).not.toContainText('</a>')
|
||||
await expect(
|
||||
details.locator('h3', { hasText: 'Inside' }),
|
||||
'the heading between the details tags must nest inside the element',
|
||||
|
||||
@@ -107,7 +107,13 @@ describe('MarkdownDocument (nesting + markdown runs)', () => {
|
||||
].join('\n'))
|
||||
const details = container.querySelector('details')
|
||||
expect(details, 'the open part must lower following runs into a details element').not.toBeNull()
|
||||
expect(details?.querySelector('summary')).not.toBeNull()
|
||||
// Direct child, not just a descendant: HTML only treats a summary as the
|
||||
// disclosure widget in that position (a nested one gets the UA's own
|
||||
// "Details" label and the authored text drops into the body).
|
||||
const summary = details?.querySelector(':scope > summary')
|
||||
expect(summary, 'the summary must be a direct child of <details>').not.toBeNull()
|
||||
expect(summary?.textContent).toBe('更新')
|
||||
expect(summary?.querySelector('b'), 'inline markup inside the summary must survive').not.toBeNull()
|
||||
expect(details?.textContent).toContain('dsh plugin --profile web add x')
|
||||
// The close part pops the frame: the trailing markdown is a sibling.
|
||||
expect(details?.textContent).not.toContain('after the fold')
|
||||
@@ -115,6 +121,70 @@ describe('MarkdownDocument (nesting + markdown runs)', () => {
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('keeps the authored summary label and the markdown run inside <details>', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<details>',
|
||||
'<summary>Implementation internals — click to expand</summary>',
|
||||
'',
|
||||
'The bundle is a static patch document.',
|
||||
'',
|
||||
'</details>',
|
||||
'',
|
||||
'outside the fold',
|
||||
].join('\n'))
|
||||
const details = container.querySelector('details')
|
||||
const summary = details?.querySelector(':scope > summary')
|
||||
expect(summary?.textContent).toBe('Implementation internals — click to expand')
|
||||
// The leaf wrapper must not sit between the details and its summary.
|
||||
expect(details?.firstElementChild?.tagName).toBe('SUMMARY')
|
||||
expect(details?.querySelector('[data-dsh-html-segment]'), 'no leaf wrapper around the summary').toBeNull()
|
||||
const paragraph = [...(details?.querySelectorAll('p') ?? [])]
|
||||
.find((node) => node.textContent?.includes('The bundle is a static patch document.'))
|
||||
expect(paragraph, 'the following markdown run must stay inside the details').not.toBeUndefined()
|
||||
expect(details?.textContent).not.toContain('outside the fold')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('never injects a hardcoded disclosure label', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<details>',
|
||||
'<summary>Folded details</summary>',
|
||||
'',
|
||||
'body',
|
||||
'',
|
||||
'</details>',
|
||||
].join('\n'))
|
||||
expect(container.textContent).not.toContain('Details')
|
||||
expect(container.textContent).not.toContain('详情')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('keeps a summary leaf inside a non-details wrapper', async () => {
|
||||
// The hoist is details-specific: a balanced run that merely starts with a
|
||||
// summary (no <details> frame open) must still take the plain leaf path.
|
||||
const { container, root } = await renderDocument([
|
||||
'<div>',
|
||||
'<summary>not a disclosure widget here</summary>',
|
||||
'</div>',
|
||||
].join('\n'))
|
||||
const leaf = container.querySelector('[data-dsh-html-segment]')
|
||||
expect(leaf, 'the run must stay a sanitized leaf').not.toBeNull()
|
||||
expect(leaf?.querySelector('summary')).not.toBeNull()
|
||||
expect(container.querySelector('details')).toBeNull()
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('keeps trailing leaf content after a hoisted summary', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<details><summary>label</summary>',
|
||||
'trailing html line',
|
||||
].join('\n'))
|
||||
const details = container.querySelector('details')
|
||||
expect(details?.querySelector(':scope > summary')?.textContent).toBe('label')
|
||||
expect(details?.textContent).toContain('trailing html line')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('keeps reference definitions resolving across lifted HTML runs', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'see [the docs][shared]',
|
||||
@@ -178,6 +248,79 @@ describe('MarkdownDocument (inline pass)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('MarkdownDocument (isolated close tags)', () => {
|
||||
// The host renderer emits one text node per raw-HTML token, so a README's
|
||||
// `<a id="x"></a>` arrives as two siblings: the open tag (sanitized into a
|
||||
// real element) and a lone `</a>` that DOMPurify can only drop. That stray
|
||||
// node used to fall through the "keep prose untouched" branch and print the
|
||||
// source's `</a>` into the preview.
|
||||
it('drops a stray close tag instead of printing it, keeping the anchor id', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<a id="understand-the-implementation"></a>',
|
||||
'',
|
||||
'## Heading',
|
||||
].join('\n'))
|
||||
expect(container.textContent, 'the raw close tag must not reach the page').not.toContain('</a>')
|
||||
const anchor = container.querySelector('a#understand-the-implementation')
|
||||
expect(anchor, 'the anchor id must survive (deep links target it)').not.toBeNull()
|
||||
expect(anchor?.textContent).toBe('')
|
||||
expect(container.textContent).toContain('Heading')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('drops isolated inline-only close tags that stay in the markdown run', async () => {
|
||||
// Block-level close lines (`</div>`) are lifted into their own HTML run and
|
||||
// never reach this pass; the tags below are inline-only, stay in the
|
||||
// markdown run, and are the ones the pass has to drop.
|
||||
const { container, root } = await renderDocument([
|
||||
'before the run',
|
||||
'',
|
||||
'</a>',
|
||||
'',
|
||||
'between',
|
||||
'',
|
||||
'</sub>',
|
||||
'',
|
||||
'after the run',
|
||||
].join('\n'))
|
||||
expect(container.textContent).not.toContain('</a>')
|
||||
expect(container.textContent).not.toContain('</sub>')
|
||||
expect(container.textContent).toContain('before the run')
|
||||
expect(container.textContent).toContain('between')
|
||||
expect(container.textContent).toContain('after the run')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('never prints a stray block-level close line either', async () => {
|
||||
// The block-run path (frame stack) already drops top-level stray closes —
|
||||
// pinned here so the "no source close tag on screen" acceptance holds for
|
||||
// block tags too, not just for the inline pass.
|
||||
const { container, root } = await renderDocument([
|
||||
'before',
|
||||
'',
|
||||
'</div>',
|
||||
'',
|
||||
'</p>',
|
||||
'',
|
||||
'after',
|
||||
].join('\n'))
|
||||
expect(container.textContent).not.toContain('</div>')
|
||||
expect(container.textContent).not.toContain('</p>')
|
||||
expect(container.textContent).toContain('before')
|
||||
expect(container.textContent).toContain('after')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('leaves comparison prose untouched', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'a < b and x </ y and 1 < 2 all stay text',
|
||||
].join('\n'))
|
||||
expect(container.textContent).toContain('a < b and x </ y and 1 < 2 all stay text')
|
||||
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
|
||||
await unmount(root)
|
||||
})
|
||||
})
|
||||
|
||||
describe('MarkdownDocument (local markdown images)', () => {
|
||||
it('renders markdown-syntax local images through the /sidebar/file route', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
|
||||
Reference in new issue
Block a user