feat(editor): Markdown 预览内嵌 HTML 安全渲染 + 目录大纲(TOC)
宿主 MarkdownText 出于聊天安全把 raw HTML 按字面文本渲染,预览 GitHub 风格 README(徽章墙 div、details 折叠块内嵌 markdown、表格单元格内联 标签、video/picture)时全是源码文本。本次在不动渲染器的前提下: - markdown-html.ts(纯函数):fence 感知切分器把文档切成 markdown/html 段(CommonMark type-6 块级标签名单 + 注释段 + 空行终止);段内标签 tokenizer 归约 open/close/html parts;全文档引用定义收集(每段追加 保持 [text][id] 跨段语义) - MarkdownHtml.tsx:DOMPurify 白名单消毒(显式禁 script/iframe/form 等;a 强制 _blank+noopener;本地媒体 src 经 /sidebar/file 重写); MarkdownDocument 帧栈状态机让 <details> 跨段嵌套内部 markdown; MarkdownSegment 内联替换(MutationObserver 幂等 pass,把表格单元格 等处标签文本消毒还原为元素,纯散文不误伤) - md-toc.tsx:零高度 sticky 浮动目录按钮(≥3 标题)+ 弹出大纲,跳转 平滑滚动 + 自动展开折叠 details + 高亮闪现。关键修复:子组件读父 ref 在 React layout 阶段恒为 null(子先于父),改为经自身 bar ref 的 parentElement 定位容器(jsdom 单测传预填 ref 掩盖了该 bug,仅 真实挂载 e2e 抓到) - 纯 markdown 文档走原单次解析路径零变化(现有 mermaid e2e 守卫一字 不动);新增 readme-style.md 种子 + 探针(消毒渲染/嵌套/内联/TOC 全链路);19 语言词典新增 toc 键;dompurify 提升为直接依赖(与 mermaid 传递依赖去重单版本) 设计文档 docs/plans/2026-08-24-markdown-html-toc-design.md
This commit is contained in:
@@ -48,6 +48,11 @@ const SEEDED_FILE = 'hello.txt'
|
||||
* and render a sanitized SVG diagram. */
|
||||
const SEEDED_MD_FILE = 'diagram.md'
|
||||
|
||||
/** A GitHub-style README markdown (badge div, <details> nesting markdown,
|
||||
* inline tags in table cells), opened through the Files window's tree to
|
||||
* prove raw-HTML runs render as sanitized DOM and the TOC outline works. */
|
||||
const SEEDED_README_FILE = 'readme-style.md'
|
||||
|
||||
/**
|
||||
* The plugin's crash markers. The client mounts inside an error boundary that
|
||||
* renders a strip whose text starts with these prefixes instead of crashing
|
||||
@@ -87,6 +92,41 @@ async function seedSession(): Promise<void> {
|
||||
'tail text',
|
||||
'',
|
||||
].join('\n'))
|
||||
// The README-style probe file: raw-HTML runs (badge wall div with an
|
||||
// embedded script, a <details> nesting a fence + heading) plus inline tags
|
||||
// inside a table cell. The script must be sanitized away in the preview.
|
||||
writeFileSync(join(WORKSPACE_PATH, SEEDED_README_FILE), [
|
||||
'# Readme Style',
|
||||
'',
|
||||
'<div align="center">',
|
||||
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
|
||||
' <script>alert(1)</script>',
|
||||
'</div>',
|
||||
'',
|
||||
'## Setup',
|
||||
'',
|
||||
'[docs link][def]',
|
||||
'',
|
||||
'<details>',
|
||||
'<summary><b>Steps</b></summary>',
|
||||
'',
|
||||
'### Inside',
|
||||
'',
|
||||
'```sh',
|
||||
'dsh plugin --profile web add x',
|
||||
'```',
|
||||
'',
|
||||
'</details>',
|
||||
'',
|
||||
'## Table',
|
||||
'',
|
||||
'| col | note |',
|
||||
'| --- | --- |',
|
||||
'| alpha | line one<br/>line two |',
|
||||
'',
|
||||
'[def]: https://example.com/def',
|
||||
'',
|
||||
].join('\n'))
|
||||
const workspace = await api.post(`${BASE_URL}/api/workspace.create`, {
|
||||
data: { type: 'client-request', rpcId: 'e2e-workspace', method: 'workspace.create', payload: { path: WORKSPACE_PATH } },
|
||||
})
|
||||
@@ -433,6 +473,75 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
|
||||
).toBeHidden()
|
||||
await assertNoCrash()
|
||||
|
||||
// README-style markdown (raw-HTML runs + TOC): open the seeded file and
|
||||
// require the full round-trip — sanitized HTML leaves (badge image as a
|
||||
// real element, active content stripped), markdown nested inside the
|
||||
// unclosed <details> run, the inline pass turning the table cell's <br/>
|
||||
// into an element, the reference link resolving across the HTML run, and
|
||||
// the TOC outline jumping into the collapsed details (auto-expanding it).
|
||||
await sidebar.locator('[title="Files"][draggable="true"]').first().click()
|
||||
const readmeRow = sidebar.locator(`[role="button"][title$="${SEEDED_README_FILE}"]:visible`)
|
||||
await expect(
|
||||
readmeRow,
|
||||
`the seeded "${SEEDED_README_FILE}" file must appear in the files window's tree`,
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
await readmeRow.click({ position: { x: 8, y: 8 } })
|
||||
await expect(
|
||||
sidebar.locator(`[title="${SEEDED_README_FILE}"][draggable="true"]`),
|
||||
'separate mode opens a new tab for the README-style markdown file',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
// The hero div renders as a sanitized leaf with the badge image as a real
|
||||
// element (the remote src may not load in the sandboxed lane; the ELEMENT
|
||||
// is the proof of rendering, not the bytes).
|
||||
await expect(
|
||||
sidebar.locator('[data-dsh-html-segment] img[src*="img.shields.io"]'),
|
||||
'the badge-wall div must render its image as a real element',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
// Active content never survives sanitization.
|
||||
await expect(
|
||||
sidebar.locator('script'),
|
||||
'the embedded <script> must be sanitized away',
|
||||
).toHaveCount(0)
|
||||
// The unclosed <details> run lowers the following markdown inside itself.
|
||||
const details = sidebar.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)
|
||||
await expect(
|
||||
details.locator('h3', { hasText: 'Inside' }),
|
||||
'the heading between the details tags must nest inside the element',
|
||||
).toHaveCount(1)
|
||||
// The inline pass: the table cell's literal <br/> became a real element.
|
||||
await expect(
|
||||
sidebar.locator('[data-html-inline] br'),
|
||||
'the table cell <br/> must render as a real element',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
// The reference link resolves although its definition sits after an HTML run.
|
||||
await expect(
|
||||
sidebar.locator('a[href="https://example.com/def"]'),
|
||||
'reference links must resolve across lifted HTML runs',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
// TOC: the outline button appears (4 headings), opens the panel, and
|
||||
// jumping into the collapsed details expands it.
|
||||
const tocButton = sidebar.locator('[data-dsh-md-toc]')
|
||||
await expect(
|
||||
tocButton,
|
||||
'the TOC button must appear once the document has enough headings',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
await tocButton.click()
|
||||
const tocPanel = sidebar.locator('[data-dsh-md-toc-panel]')
|
||||
await expect(tocPanel, 'the TOC panel must open').toHaveCount(1)
|
||||
const insideItem = tocPanel.locator('button', { hasText: 'Inside' })
|
||||
await expect(insideItem, 'the nested heading must appear in the outline').toHaveCount(1)
|
||||
await insideItem.click()
|
||||
await expect(
|
||||
details,
|
||||
'jumping into a collapsed details must expand it',
|
||||
).toHaveAttribute('open', '')
|
||||
await assertNoCrash()
|
||||
|
||||
// The plugin's own console prefix must never appear in errors, and no
|
||||
// unhandled rejection may escape the sweep.
|
||||
const pluginErrors = consoleErrors.filter((text) => /dsh-better-sidebar|Unhandled/.test(text))
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* MarkdownDocument spec: the split-document renderer — sanitized HTML leaves
|
||||
* (denylist + anchor hardening + local media rewrite), `<details>` nesting of
|
||||
* in-between markdown, cross-segment reference definitions, and the inline
|
||||
* pass that turns tag text inside rendered markdown back into elements.
|
||||
* Renders with the real shared MarkdownText in jsdom (same pattern as
|
||||
* tests/mermaid-markdown.spec.tsx).
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { describe, expect, it, beforeEach } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { MarkdownDocument, type MarkdownHtmlMedia } from '../src/client/MarkdownHtml.tsx'
|
||||
import { analyzeMarkdownHtml } from '../src/client/markdown-html.ts'
|
||||
|
||||
// The act() environment flag (React 18.2 reads it before flushing effects).
|
||||
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const media: MarkdownHtmlMedia = {
|
||||
scope: { sessionId: 's1', cwd: '/ws' },
|
||||
path: '/ws/docs/README.md',
|
||||
origin: 'http://gui.origin',
|
||||
}
|
||||
const codeLabels = { copyLabel: 'Copy', copiedLabel: 'Copied' }
|
||||
|
||||
async function renderDocument(text: string): Promise<{ container: HTMLElement; root: Root }> {
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
await act(async () => {
|
||||
root.render(createElement(MarkdownDocument, {
|
||||
info: analyzeMarkdownHtml(text),
|
||||
media,
|
||||
codeLabels,
|
||||
}))
|
||||
// Let the MutationObserver's queued inline pass settle inside the act scope.
|
||||
await new Promise((resolve) => { setTimeout(resolve, 0) })
|
||||
})
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
async function unmount(root: Root): Promise<void> {
|
||||
await act(async () => { root.unmount() })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
describe('MarkdownDocument (HTML leaves)', () => {
|
||||
it('renders a balanced HTML block as sanitized DOM, not literal text', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'# Title',
|
||||
'',
|
||||
'<div align="center">',
|
||||
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
|
||||
'</div>',
|
||||
].join('\n'))
|
||||
const leaf = container.querySelector('[data-dsh-html-segment]')
|
||||
expect(leaf, 'the html run must render as a sanitized leaf').not.toBeNull()
|
||||
expect(leaf?.querySelector('img[src*="img.shields.io"]')).not.toBeNull()
|
||||
expect(leaf?.firstElementChild?.getAttribute('align')).toBe('center')
|
||||
expect(container.textContent).not.toContain('<div')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('strips denied tags and hardens anchors', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<div>',
|
||||
' <script>alert(1)</script>',
|
||||
' <a href="https://example.com">link</a>',
|
||||
'</div>',
|
||||
].join('\n'))
|
||||
expect(container.querySelector('script')).toBeNull()
|
||||
const anchor = container.querySelector('a[href="https://example.com"]')
|
||||
expect(anchor).not.toBeNull()
|
||||
expect(anchor?.getAttribute('target')).toBe('_blank')
|
||||
expect(anchor?.getAttribute('rel')).toBe('noopener noreferrer')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('rewrites local media sources through the /sidebar/file route', async () => {
|
||||
const { container, root } = await renderDocument('<picture><img src="./shot.png" alt="shot"/></picture>')
|
||||
const img = container.querySelector('img')
|
||||
expect(img?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
|
||||
await unmount(root)
|
||||
})
|
||||
})
|
||||
|
||||
describe('MarkdownDocument (nesting + markdown runs)', () => {
|
||||
it('nests markdown runs inside an unclosed <details> element', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<details>',
|
||||
'<summary><b>更新</b></summary>',
|
||||
'',
|
||||
'```sh',
|
||||
'dsh plugin --profile web add x',
|
||||
'```',
|
||||
'',
|
||||
'</details>',
|
||||
'',
|
||||
'after the fold',
|
||||
].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()
|
||||
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')
|
||||
expect(container.querySelector('details')?.nextElementSibling?.textContent).toContain('after the fold')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('keeps reference definitions resolving across lifted HTML runs', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'see [the docs][shared]',
|
||||
'',
|
||||
'<div align="center">badges</div>',
|
||||
'',
|
||||
'[shared]: https://example.com/docs',
|
||||
].join('\n'))
|
||||
const anchor = container.querySelector('a[href="https://example.com/docs"]')
|
||||
expect(anchor, 'a definition after an HTML run must still resolve').not.toBeNull()
|
||||
expect(anchor?.textContent).toContain('the docs')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('renders a forbidden wrapper as transparent (children survive)', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'<form action="/x">',
|
||||
'',
|
||||
'inner text',
|
||||
'',
|
||||
'</form>',
|
||||
].join('\n'))
|
||||
expect(container.querySelector('form')).toBeNull()
|
||||
expect(container.textContent).toContain('inner text')
|
||||
await unmount(root)
|
||||
})
|
||||
})
|
||||
|
||||
describe('MarkdownDocument (inline pass)', () => {
|
||||
it('turns tag text in table cells back into elements', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'| feature | notes |',
|
||||
'|---|---|',
|
||||
'| alpha | line one<br/>line two |',
|
||||
].join('\n'))
|
||||
const cell = [...container.querySelectorAll('td')].find((td) => td.textContent?.includes('line one'))
|
||||
expect(cell?.querySelector('[data-html-inline] br'), 'the <br/> must render as a real element').not.toBeNull()
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('leaves rendered code and comparison prose untouched', async () => {
|
||||
const { container, root } = await renderDocument([
|
||||
'a < b comparison stays text',
|
||||
'',
|
||||
'```html',
|
||||
'<div>demo</div>',
|
||||
'```',
|
||||
].join('\n'))
|
||||
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
|
||||
expect(container.textContent).toContain('a < b comparison stays text')
|
||||
const code = container.querySelector('code')
|
||||
expect(code?.textContent).toContain('<div>demo</div>')
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('rewrites local image src inside inline-swapped tags', async () => {
|
||||
const { container, root } = await renderDocument('text <img src="./icon.png" alt="i"/> tail')
|
||||
const img = container.querySelector('[data-html-inline] img')
|
||||
expect(img?.getAttribute('src')).toContain('/sidebar/file?')
|
||||
await unmount(root)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* markdown-html splitter spec: the pure lifting of raw-HTML runs out of the
|
||||
* markdown stream (fence-aware), the tag-balance part analysis (unclosed
|
||||
* `<details>` → wrapper opens, stray closes → pops), the doc-wide reference
|
||||
* definition collection, and the inline-html gate.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
analyzeHtmlSegment,
|
||||
analyzeMarkdownHtml,
|
||||
collectReferenceDefinitions,
|
||||
splitHtmlBlocks,
|
||||
type HtmlPart,
|
||||
} from '../src/client/markdown-html.ts'
|
||||
|
||||
/** Structural view of parts: html parts as [html <text>], opens/closes by kind. */
|
||||
function shape(parts: readonly HtmlPart[]): string[] {
|
||||
return parts.map((part) => part.kind === 'html'
|
||||
? `html(${part.html})`
|
||||
: part.kind === 'open'
|
||||
? `open(${part.tag}${part.attrs.trim() !== '' ? ` ${part.attrs.trim()}` : ''})`
|
||||
: `close(${part.tag})`)
|
||||
}
|
||||
|
||||
describe('splitHtmlBlocks', () => {
|
||||
it('returns one markdown segment for plain markdown (no HTML)', () => {
|
||||
const text = '# Title\n\nsome **markdown**\n\n- a\n- b\n'
|
||||
expect(splitHtmlBlocks(text)).toEqual([{ kind: 'markdown', text: text.replace(/\n$/, '') }])
|
||||
})
|
||||
|
||||
it('lifts a balanced block-tag run out of the markdown stream', () => {
|
||||
const segments = splitHtmlBlocks([
|
||||
'# Title',
|
||||
'',
|
||||
'<div align="center">',
|
||||
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
|
||||
'</div>',
|
||||
'',
|
||||
'tail text',
|
||||
].join('\n'))
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'markdown', text: '# Title' },
|
||||
{ kind: 'html', text: '<div align="center">\n <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />\n</div>' },
|
||||
{ kind: 'markdown', text: 'tail text' },
|
||||
])
|
||||
})
|
||||
|
||||
it('ends an HTML run at a blank line', () => {
|
||||
const segments = splitHtmlBlocks('<p>a</p>\n\nafter')
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'html', text: '<p>a</p>' },
|
||||
{ kind: 'markdown', text: 'after' },
|
||||
])
|
||||
})
|
||||
|
||||
it('does not lift tag-like lines inside fenced code blocks', () => {
|
||||
const segments = splitHtmlBlocks([
|
||||
'```html',
|
||||
'<div class="demo">',
|
||||
' <p>example</p>',
|
||||
'</div>',
|
||||
'```',
|
||||
'',
|
||||
'<div align="center">real</div>',
|
||||
].join('\n'))
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'markdown', text: '```html\n<div class="demo">\n <p>example</p>\n</div>\n```' },
|
||||
{ kind: 'html', text: '<div align="center">real</div>' },
|
||||
])
|
||||
})
|
||||
|
||||
it('does not lift inline-only tags or prose starting with a comparison', () => {
|
||||
const segments = splitHtmlBlocks([
|
||||
'a < b and <code>x</code> inline',
|
||||
'<br/> alone on its line',
|
||||
].join('\n'))
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'markdown', text: 'a < b and <code>x</code> inline\n<br/> alone on its line' },
|
||||
])
|
||||
})
|
||||
|
||||
it('treats a close-tag-only line as an HTML run', () => {
|
||||
const segments = splitHtmlBlocks('text\n\n</details>\n\nmore')
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'markdown', text: 'text' },
|
||||
{ kind: 'html', text: '</details>' },
|
||||
{ kind: 'markdown', text: 'more' },
|
||||
])
|
||||
})
|
||||
|
||||
it('accumulates a comment run until the closing marker line', () => {
|
||||
const segments = splitHtmlBlocks('<!-- section\n banner\n-->\n\nbody')
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'html', text: '<!-- section\n banner\n-->' },
|
||||
{ kind: 'markdown', text: 'body' },
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps an unterminated fence as markdown (CommonMark recovery)', () => {
|
||||
const segments = splitHtmlBlocks('```\n<div>x</div>')
|
||||
expect(segments).toEqual([{ kind: 'markdown', text: '```\n<div>x</div>' }])
|
||||
})
|
||||
|
||||
it('keeps the README details shape as three segments', () => {
|
||||
const segments = splitHtmlBlocks([
|
||||
'<details>',
|
||||
'<summary><b>更新</b></summary>',
|
||||
'',
|
||||
'```sh',
|
||||
'dsh plugin --profile web add x',
|
||||
'```',
|
||||
'',
|
||||
'</details>',
|
||||
].join('\n'))
|
||||
expect(segments.map((segment) => segment.kind)).toEqual(['html', 'markdown', 'html'])
|
||||
expect(segments[0]).toEqual({ kind: 'html', text: '<details>\n<summary><b>更新</b></summary>' })
|
||||
expect(segments[2]).toEqual({ kind: 'html', text: '</details>' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('analyzeHtmlSegment', () => {
|
||||
it('reduces a balanced run to a single html part', () => {
|
||||
expect(shape(analyzeHtmlSegment('<div align="center"><img src="https://x/y.png"/></div>').parts))
|
||||
.toEqual(['html(<div align="center"><img src="https://x/y.png"/></div>)'])
|
||||
})
|
||||
|
||||
it('surfaces an unclosed open tag as a wrapper with its inner html', () => {
|
||||
expect(shape(analyzeHtmlSegment('<details>\n<summary><b>更新</b></summary>').parts))
|
||||
.toEqual(['open(details)', 'html(\n<summary><b>更新</b></summary>)'])
|
||||
})
|
||||
|
||||
it('surfaces an unmatched close as a pop', () => {
|
||||
expect(shape(analyzeHtmlSegment('</details>').parts)).toEqual(['close(details)'])
|
||||
})
|
||||
|
||||
it('orders mixed leading closes before following html and closes', () => {
|
||||
expect(shape(analyzeHtmlSegment('</div> mid </details>').parts))
|
||||
.toEqual(['close(div)', 'html( mid )', 'close(details)'])
|
||||
})
|
||||
|
||||
it('nests multiple unclosed opens outermost-first', () => {
|
||||
expect(shape(analyzeHtmlSegment('<div align="center"><details>').parts))
|
||||
.toEqual(['open(div align="center")', 'open(details)'])
|
||||
})
|
||||
|
||||
it('keeps attrs of the open token for the wrapper', () => {
|
||||
const parts = analyzeHtmlSegment('<details open class="x">body').parts
|
||||
expect(parts[0]).toEqual({ kind: 'open', tag: 'details', attrs: ' open class="x"' })
|
||||
})
|
||||
|
||||
it('ignores void and self-closing tags for balance', () => {
|
||||
expect(shape(analyzeHtmlSegment('<img src="x"><br/><span/>after').parts))
|
||||
.toEqual(['html(<img src="x"><br/><span/>after)'])
|
||||
})
|
||||
|
||||
it('ignores tags inside comments', () => {
|
||||
expect(shape(analyzeHtmlSegment('<!-- <div> commented out -->').parts))
|
||||
.toEqual(['html(<!-- <div> commented out -->)'])
|
||||
})
|
||||
|
||||
it('pops implicitly through a mismatched close', () => {
|
||||
// <p> is implicitly closed by </div>: nothing structural remains.
|
||||
expect(shape(analyzeHtmlSegment('<div><p>text</div>').parts))
|
||||
.toEqual(['html(<div><p>text</div>)'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('collectReferenceDefinitions + analyzeMarkdownHtml', () => {
|
||||
it('collects definitions from markdown runs only, in document order', () => {
|
||||
const info = analyzeMarkdownHtml([
|
||||
'intro [link][shared]',
|
||||
'',
|
||||
'<div align="center">badges</div>',
|
||||
'',
|
||||
'[shared]: https://example.com',
|
||||
'[img]: ./local.png',
|
||||
].join('\n'))
|
||||
expect(info.referenceDefinitions).toBe('[shared]: https://example.com\n[img]: ./local.png')
|
||||
expect(collectReferenceDefinitions(info.segments)).toBe(info.referenceDefinitions)
|
||||
})
|
||||
|
||||
it('reports hasBlockHtml only when a run was lifted', () => {
|
||||
expect(analyzeMarkdownHtml('# plain\ntext').hasBlockHtml).toBe(false)
|
||||
expect(analyzeMarkdownHtml('<div>x</div>').hasBlockHtml).toBe(true)
|
||||
// Inline-only tags: no block html, but the inline gate is on.
|
||||
const inline = analyzeMarkdownHtml('| a | b |\n|---|---|\n| x<br/>y | z |')
|
||||
expect(inline.hasBlockHtml).toBe(false)
|
||||
expect(inline.hasInlineHtml).toBe(true)
|
||||
})
|
||||
|
||||
it('gates inline html on tag-like source text', () => {
|
||||
expect(analyzeMarkdownHtml('a < b').hasInlineHtml).toBe(false)
|
||||
expect(analyzeMarkdownHtml('a <b>bold</b>').hasInlineHtml).toBe(true)
|
||||
expect(analyzeMarkdownHtml('plain markdown').hasInlineHtml).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* MdToc spec: the markdown preview's outline button + popover. Covers the
|
||||
* minimum-headings gate, collection from the rendered DOM (including headings
|
||||
* inside HTML `<details>` runs, which appear late through the observer),
|
||||
* jump behavior (smooth scroll + flash + auto-expanding collapsed ancestors)
|
||||
* and Esc-to-close.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { describe, expect, it, beforeEach, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { MdToc, TOC_MIN_HEADINGS } from '../src/client/md-toc.tsx'
|
||||
|
||||
// The act() environment flag (React 18.2 reads it before flushing effects).
|
||||
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const scrollIntoView = vi.fn()
|
||||
Element.prototype.scrollIntoView = scrollIntoView
|
||||
|
||||
/** The preview-harness shape MdToc mounts in: the bar is a direct child of
|
||||
* the scroll container, headings are siblings (inside or outside details). */
|
||||
interface HeadingSpec {
|
||||
tag: string
|
||||
text: string
|
||||
insideClosedDetails?: boolean
|
||||
}
|
||||
|
||||
function Harness({ specs }: { specs: readonly HeadingSpec[] }): React.ReactElement {
|
||||
return createElement(
|
||||
'div',
|
||||
null,
|
||||
createElement(MdToc),
|
||||
...specs.map((spec) => spec.insideClosedDetails === true
|
||||
? createElement('details', null, createElement(spec.tag, null, spec.text))
|
||||
: createElement(spec.tag, null, spec.text)),
|
||||
)
|
||||
}
|
||||
|
||||
/** Render the harness; returns the scroll container (the bar's parent). */
|
||||
async function mountToc(specs: readonly HeadingSpec[]): Promise<{ container: HTMLDivElement; root: Root }> {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
await act(async () => {
|
||||
root.render(createElement(Harness, { specs }))
|
||||
await new Promise((resolve) => { setTimeout(resolve, 0) })
|
||||
})
|
||||
const container = host.firstElementChild as HTMLDivElement
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
async function unmount(root: Root): Promise<void> {
|
||||
await act(async () => { root.unmount() })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
scrollIntoView.mockClear()
|
||||
})
|
||||
|
||||
describe('MdToc', () => {
|
||||
it('exposes the minimum-headings threshold', () => {
|
||||
expect(TOC_MIN_HEADINGS).toBe(3)
|
||||
})
|
||||
|
||||
it('stays hidden below the heading threshold', async () => {
|
||||
const { container, root } = await mountToc([
|
||||
{ tag: 'h1', text: 'One' },
|
||||
{ tag: 'h2', text: 'Two' },
|
||||
])
|
||||
expect(container.querySelector('[data-dsh-md-toc]')).toBeNull()
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('shows the button and lists collected headings', async () => {
|
||||
const { container, root } = await mountToc([
|
||||
{ tag: 'h1', text: 'Title' },
|
||||
{ tag: 'h2', text: 'Install' },
|
||||
{ tag: 'h2', text: 'Usage' },
|
||||
{ tag: 'h3', text: 'Deep' },
|
||||
])
|
||||
const button = container.querySelector<HTMLButtonElement>('[data-dsh-md-toc]')
|
||||
expect(button).not.toBeNull()
|
||||
await act(async () => { button!.click() })
|
||||
const panel = container.querySelector('[data-dsh-md-toc-panel]')
|
||||
expect(panel).not.toBeNull()
|
||||
const items = [...panel!.querySelectorAll('button')]
|
||||
expect(items.map((item) => item.textContent)).toEqual(['1Title', '2Install', '2Usage', '3Deep'])
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('jumps: expands collapsed details ancestors, smooth-scrolls, flashes, closes', async () => {
|
||||
// Mount with real timers (the settle await needs them), then fake only the
|
||||
// flash-removal timeout window.
|
||||
const { container, root } = await mountToc([
|
||||
{ tag: 'h1', text: 'Title' },
|
||||
{ tag: 'h2', text: 'Outside' },
|
||||
{ tag: 'h3', text: 'Hidden', insideClosedDetails: true },
|
||||
])
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const button = container.querySelector<HTMLButtonElement>('[data-dsh-md-toc]')!
|
||||
await act(async () => { button.click() })
|
||||
const target = [...container.querySelectorAll('h3')].find((h) => h.textContent === 'Hidden')!
|
||||
const item = [...container.querySelectorAll<HTMLButtonElement>('[data-dsh-md-toc-panel] button')]
|
||||
.find((candidate) => candidate.textContent?.includes('Hidden'))!
|
||||
await act(async () => { item.click() })
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' })
|
||||
expect(target.closest('details')?.hasAttribute('open'), 'the collapsed ancestor must open').toBe(true)
|
||||
expect(target.className, 'the jumped-to heading must flash').not.toBe('')
|
||||
expect(container.querySelector('[data-dsh-md-toc-panel]'), 'the panel must close on jump').toBeNull()
|
||||
vi.advanceTimersByTime(1300)
|
||||
expect(target.className, 'the flash class must clear after the timeout').toBe('')
|
||||
await unmount(root)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('collects headings that appear after mount (observer path)', async () => {
|
||||
const { container, root } = await mountToc([
|
||||
{ tag: 'h1', text: 'Title' },
|
||||
{ tag: 'h2', text: 'Only two so far' },
|
||||
])
|
||||
expect(container.querySelector('[data-dsh-md-toc]')).toBeNull()
|
||||
const late = document.createElement('h2')
|
||||
late.textContent = 'Late'
|
||||
await act(async () => {
|
||||
container.appendChild(late)
|
||||
await new Promise((resolve) => { setTimeout(resolve, 0) })
|
||||
})
|
||||
expect(container.querySelector('[data-dsh-md-toc]'), 'late headings must surface the button').not.toBeNull()
|
||||
await unmount(root)
|
||||
})
|
||||
|
||||
it('closes the popover on Escape', async () => {
|
||||
const { container, root } = await mountToc([
|
||||
{ tag: 'h1', text: 'Title' },
|
||||
{ tag: 'h2', text: 'A' },
|
||||
{ tag: 'h2', text: 'B' },
|
||||
])
|
||||
const button = container.querySelector<HTMLButtonElement>('[data-dsh-md-toc]')!
|
||||
await act(async () => { button.click() })
|
||||
expect(container.querySelector('[data-dsh-md-toc-panel]')).not.toBeNull()
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
|
||||
})
|
||||
expect(container.querySelector('[data-dsh-md-toc-panel]')).toBeNull()
|
||||
await unmount(root)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user