diff --git a/src/client/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index ca27af61..251c51a7 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -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 (``) at its edges. The host + * renderer emits one text node per raw-HTML token, so an author's + * `` 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 { + const props: Record = {} + 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 (`
`) 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 | null { const probe = DOMPurify.sanitize(`<${tag}${attrs}>`, { @@ -114,13 +140,37 @@ function sanitizeTagProps(tag: string, attrs: string): Record | holder.innerHTML = probe const element = holder.firstElementChild if (element === null || element.tagName.toLowerCase() !== tag) return null - const props: Record = {} - 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 `` 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 `
`, + * but every balanced leaf renders inside a block wrapper — so a README's + * `
` + `` 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; 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 `` 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 | null } | { kind: 'close' } + /** A `` hoisted out of a leaf so it can be a `
` direct child. */ + | { kind: 'summary'; props: Record; 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 `` 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() + } else if (part.kind === 'summary') { + // Emitted as a real element (not a block leaf) so it stays a direct + // child of the enclosing
— 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 { diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index d47c7463..f42e0789 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -2117,7 +2117,11 @@ body[data-dsh-sidebar-dragging] .bottomPanel { padding: 4px 0; } -.editorHtmlBlock summary { +/* A `` the renderer hoisted out of a leaf is a direct child of its + `
` (see MarkdownHtml.tsx), so it no longer sits inside + `.editorHtmlBlock` — match it against the preview container too. */ +.editorHtmlBlock summary, +.editorMd details > summary { cursor: pointer; } diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index 7e6d8fd3..6244a81b 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -116,6 +116,7 @@ async function seedSession(): Promise { ' ', '', '', + '', '## 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
', + ).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 + // `` 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('') await expect( details.locator('h3', { hasText: 'Inside' }), 'the heading between the details tags must nest inside the element', diff --git a/tests/markdown-html-render.spec.tsx b/tests/markdown-html-render.spec.tsx index ec9e1360..78da0c0d 100644 --- a/tests/markdown-html-render.spec.tsx +++ b/tests/markdown-html-render.spec.tsx @@ -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
').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
', async () => { + const { container, root } = await renderDocument([ + '
', + 'Implementation internals — click to expand', + '', + 'The bundle is a static patch document.', + '', + '
', + '', + '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([ + '
', + 'Folded details', + '', + 'body', + '', + '
', + ].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
frame open) must still take the plain leaf path. + const { container, root } = await renderDocument([ + '
', + 'not a disclosure widget here', + '
', + ].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([ + '
label', + '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 + // `` arrives as two siblings: the open tag (sanitized into a + // real element) and a lone `` that DOMPurify can only drop. That stray + // node used to fall through the "keep prose untouched" branch and print the + // source's `` into the preview. + it('drops a stray close tag instead of printing it, keeping the anchor id', async () => { + const { container, root } = await renderDocument([ + '', + '', + '## Heading', + ].join('\n')) + expect(container.textContent, 'the raw close tag must not reach the page').not.toContain('') + 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 (``) 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', + '', + '', + '', + 'between', + '', + '', + '', + 'after the run', + ].join('\n')) + expect(container.textContent).not.toContain('') + expect(container.textContent).not.toContain('') + 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', + '', + '', + '', + '

', + '', + 'after', + ].join('\n')) + expect(container.textContent).not.toContain('') + expect(container.textContent).not.toContain('

') + 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 { it('renders markdown-syntax local images through the /sidebar/file route', async () => { const { container, root } = await renderDocument([