Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(preview): apply Markdown typography to knowledge doc preview (#4439)

linus-liu-web48788693b6ef
diff --git a/frontend/src/components/css/markdown.less b/frontend/src/components/css/markdown.less
index 195886acc..110293562 100644
--- a/frontend/src/components/css/markdown.less
+++ b/frontend/src/components/css/markdown.less
@@ -1,5 +1,16 @@
// Legacy Markdown styles for non-chat document/editor surfaces that render
// `.md-content`. Chat answer Markdown must use `chat-markdown.less` only.
+//
+// 正文容器是 `.md-content`(合并视图额外带 `.doc-merged-content` 以限制行宽)。
+// `.doc_content` 只是文档抽屉的外壳,里面还有「元数据 / 文件内容」等 UI 标题,
+// 不要为了「让样式命中」把 Markdown 排版挂到 `.doc_content` 上——那会连抽屉
+// 自身的 h4 小标题一起改掉。
+:deep(.doc-merged-content) {
+ // 合并全文视图独占抽屉宽度:限制行宽(钉钉式窄栏)并居中。
+ max-width: 680px;
+ margin-inline: auto;
+}
+
:deep(.md-content) {
box-sizing: border-box !important;
@@ -29,12 +40,56 @@
h4,
h5,
h6 {
- margin-top: 5px;
- font-weight: bold;
+ margin: 20px 0 10px;
+ font-weight: 700;
+ line-height: 1.35;
color: var(--td-text-color-primary);
font-family: var(--app-font-family);
transition: all var(--app-motion-base) ease-out;
+ }
+
+ // 标题层级必须一眼可辨:旧规则把 h1~h6 都设成 --app-text-3xl(20px),
+ // 而后面的 h2/h3 又把字号调小,导致 h4(20px) 反而比 h3(16px) 还大。
+ h1 {
+ font-size: var(--app-text-4xl);
+ margin-top: 24px;
+ }
+
+ h2 {
font-size: var(--app-text-3xl);
+ margin-top: 22px;
+ }
+
+ h3 {
+ font-size: var(--app-text-2xl);
+ font-weight: 600;
+ margin-top: 18px;
+ margin-bottom: 8px;
+ }
+
+ h4 {
+ font-size: var(--app-text-xl);
+ font-weight: 600;
+ margin-top: 16px;
+ margin-bottom: 8px;
+ }
+
+ h5 {
+ font-size: var(--app-text-lg);
+ font-weight: 600;
+ margin-top: 14px;
+ margin-bottom: 6px;
+ }
+
+ h6 {
+ font-size: var(--app-text-base);
+ font-weight: 600;
+ margin-top: 12px;
+ margin-bottom: 6px;
+ }
+
+ > :first-child {
+ margin-top: 0;
}
.hljs-title,
@@ -96,25 +151,11 @@
font-family: var(--app-font-family);
}
- h2 {
- font-size: var(--app-text-2xl);
- }
-
- h3 {
- font-size: var(--app-text-xl);
- font-weight: 500;
- }
-
summary {
font-size: var(--app-text-base);
cursor: pointer;
}
- li>ol,
- li>ul {
- margin: 0 0;
- }
-
hr {
padding: 0;
margin: 24px 0;
@@ -159,12 +200,43 @@
}
p {
- margin: 0;
+ margin: 0 0 var(--app-space-3);
+ line-height: 1.75;
+ }
+
+ p:last-child {
+ margin-bottom: 0;
}
code {
white-space: pre-wrap;
word-break: break-all;
+ padding: 1px 5px;
+ background: var(--td-bg-color-secondarycontainer);
+ border-radius: var(--app-radius-xs);
+ font-family: var(--app-font-family-mono);
+ font-size: 0.92em;
+ }
+
+ pre {
+ margin: 14px 0;
+ padding: 12px 14px;
+ background: var(--td-bg-color-secondarycontainer);
+ border-radius: var(--app-radius-md);
+ overflow-x: auto;
+ font-size: var(--app-text-md);
+ line-height: 1.6;
+ white-space: pre;
+ word-break: normal;
+
+ code {
+ padding: 0;
+ background: none;
+ border-radius: 0;
+ font-size: inherit;
+ white-space: pre;
+ word-break: normal;
+ }
}
h1 p,
@@ -183,6 +255,22 @@
ul,
ol {
padding-left: 30px;
+ margin: 10px 0;
+ }
+
+ li {
+ margin: 2px 0;
+ line-height: 1.75;
+ }
+
+ li>ul,
+ li>ol {
+ margin: 4px 0;
+ padding-left: 26px;
+ }
+
+ li>p {
+ margin: 4px 0;
}
ul:first-child,
@@ -196,13 +284,22 @@
}
blockquote {
- padding: 0.8em 1.4rem;
- margin: 1em 0;
+ padding: 10px 16px;
+ margin: 14px 0;
font-weight: 400;
+ line-height: 1.75;
+ color: var(--td-text-color-secondary);
border-left: 4px solid var(--td-brand-color);
- background-color: var(--td-brand-color)21;
- border-radius: 0px 8px 8px 0px;
- box-shadow: rgb(149 149 149 / 13%) 0px 5px 10px;
+ background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
+ border-radius: 0 var(--app-radius-md) var(--app-radius-md) 0;
+
+ > :first-child {
+ margin-top: 0;
+ }
+
+ > :last-child {
+ margin-bottom: 0;
+ }
}
table {
diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue
index c243ea896..5c5a72821 100644
--- a/frontend/src/components/doc-content.vue
+++ b/frontend/src/components/doc-content.vue
@@ -17,6 +17,7 @@ import {
import { MessagePlugin } from "tdesign-vue-next";
import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages, isValidURL } from '@/utils/security';
import { normalizeSpuriousTablePrefixes } from '@/utils/markdownTableNormalize';
+import { stripDuplicateLeadingH1 } from '@/utils/markdownTitleDedupe';
import { ensureLiteralSingleTildeOnGlobalMarked } from '@/utils/markedLiteralTilde';
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
import { diffWikiLines, type WikiDiffLine } from '@/utils/wikiLineDiff';
@@ -924,6 +925,9 @@ const processMarkdown = (markdownText) => {
.replace(/>/g, '>')
.replace(/&/g, '&');
+ // 抽屉标题已经显示条目名,正文第一行的同名 H1 会重复;仅在同名时剥掉。
+ processedText = stripDuplicateLeadingH1(processedText, [props.details?.title]);
+
// 处理被 <p> 包裹的表格行,转换为正常的表格行,并在前后补空行
processedText = processedText.replace(/<p>\s*(\|[\s\S]*?\|)\s*<\/p>/gi, '\n$1\n');
@@ -1870,7 +1874,7 @@ const handleChunkPageChange = (pageInfo: { current: number }) => {
</div>
<template v-else>
<div v-if="!mergedContent" class="no_content">{{ $t('common.noData') }}</div>
- <div v-else class="md-content" v-html="processMarkdown(mergedContent)"></div>
+ <div v-else class="md-content doc-merged-content" v-html="processMarkdown(mergedContent)"></div>
</template>
</div>
diff --git a/frontend/src/components/document-preview.vue b/frontend/src/components/document-preview.vue
index 5ee3369c4..afd521856 100644
--- a/frontend/src/components/document-preview.vue
+++ b/frontend/src/components/document-preview.vue
@@ -344,7 +344,10 @@ async function renderMarkdown(blob: Blob) {
return;
}
- markdownHtml.value = renderDocumentPreviewMarkdown(text);
+ markdownHtml.value = renderDocumentPreviewMarkdown(text, undefined, {
+ // 预览工具栏已经显示文件名;正文第一行的同名 H1 属于重复标题。
+ titles: [props.fileName],
+ });
}
function onImageLoad(e: Event) {
@@ -1481,9 +1484,12 @@ onUnmounted(() => {
:deep(.markdown-body) {
font-size: var(--app-text-base);
- line-height: 1.7;
+ line-height: 1.75;
color: @text-primary;
word-break: break-word;
+ // 正文窄栏:全屏 / 宽抽屉下限制行宽,避免中文长行难以阅读。
+ max-width: 680px;
+ margin-inline: auto;
h1, h2, h3, h4, h5, h6 {
margin-top: 20px;
@@ -1491,20 +1497,36 @@ onUnmounted(() => {
font-weight: 600;
line-height: 1.4;
}
+ h1:first-child,
+ h2:first-child,
+ h3:first-child,
+ h4:first-child,
+ h5:first-child,
+ h6:first-child { margin-top: 0; }
+ // 标题层级:旧规则里 h4~h6 没有字号,会退回正文字号(14px),和 h3 的
+ // 17px 几乎看不出差别;这里补齐 24 / 20 / 18 / 16 / 15 / 14 的完整层级。
h1 { font-size: var(--app-text-4xl); border-bottom: 1px solid @border-color; padding-bottom: 8px; }
h2 { font-size: var(--app-text-3xl); border-bottom: 1px solid @border-color; padding-bottom: 6px; }
- h3 { font-size: 17px; }
+ h3 { font-size: var(--app-text-2xl); }
+ h4 { font-size: var(--app-text-xl); margin-top: 16px; margin-bottom: 8px; }
+ h5 { font-size: var(--app-text-lg); margin-top: 14px; margin-bottom: 6px; }
+ h6 { font-size: var(--app-text-base); margin-top: 12px; margin-bottom: 6px; }
- p { margin: 8px 0; }
+ p { margin: 10px 0; }
+ p:last-child { margin-bottom: 0; }
blockquote {
- margin: 12px 0;
- padding: 8px 16px;
+ margin: 14px 0;
+ padding: 10px 16px;
border-left: 4px solid @border-color;
background: @bg-subtle;
color: var(--td-text-color-secondary);
}
- ul, ol { padding-left: 24px; margin: 8px 0; }
- li { margin: 4px 0; }
+ blockquote > :first-child { margin-top: 0; }
+ blockquote > :last-child { margin-bottom: 0; }
+ ul, ol { padding-left: 28px; margin: 10px 0; }
+ li { margin: 4px 0; line-height: 1.75; }
+ li > ul, li > ol { margin: 4px 0; padding-left: 24px; }
+ li > p { margin: 4px 0; }
ul li:has(> .task-checkbox) { list-style: none; }
.task-checkbox {
display: inline-block;
@@ -1549,9 +1571,9 @@ onUnmounted(() => {
}
code {
background: var(--td-bg-color-secondarycontainer);
- padding: 2px 6px;
- border-radius: 3px;
- font-size: 0.9em;
+ padding: 1px 5px;
+ border-radius: var(--app-radius-xs);
+ font-size: 0.92em;
}
img { max-width: 100%; border-radius: var(--app-radius-xs); }
hr { border: none; border-top: 1px solid @border-color; margin: 20px 0; }
diff --git a/frontend/src/components/previewMarkdownTypography.test.ts b/frontend/src/components/previewMarkdownTypography.test.ts
new file mode 100644
index 000000000..aa90525df
--- /dev/null
+++ b/frontend/src/components/previewMarkdownTypography.test.ts
@@ -0,0 +1,263 @@
+/**
+ * 知识库文档预览 Markdown 排版回归测试。
+ *
+ * 为什么这样断言:仓库里的测试在 `tsx --test`(Node,无 DOM)下运行,依赖里
+ * 没有 jsdom/Playwright,也不适合为一个排版断言引入浏览器。这里:
+ * 1. 用 `@vue/compiler-sfc` 的 `parse` + `compileStyle({ scoped, preprocessLang: 'less' })`
+ * 编译组件的真实 `<style scoped lang="less">`(与 Vite 构建同一套实现,
+ * 包括 `@import` 进来的 markdown.less 和 `:deep()` 的 scoped 展开);
+ * 2. 用真实的 marked 渲染管线生成正文 HTML,套进组件模板里真实的容器
+ * (`.doc-markdown-root > .md-content` / `.document-preview > .markdown-body`);
+ * 3. 用 `@vue/compiler-dom` 解析出 DOM 树,按 CSS 级联算出 `font-size` /
+ * `padding-left` / `margin-bottom` 等属性的生效值,断言关键属性。
+ *
+ * 这样断言的是「编译后的样式 + 真实渲染出的标签结构」,能同时抓住选择器
+ * 不命中(类名/作用域写错)和样式本身太弱(标题同级、列表无缩进)两类问题。
+ */
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+
+import { parse as parseSfc, compileStyle } from '@vue/compiler-sfc'
+
+import {
+ buildDomTree,
+ parseCssRules,
+ winningDeclaration,
+ type DomNode,
+} from '../test-utils/cssRuleMatcher.ts'
+import { renderDocumentPreviewMarkdown } from '../utils/documentPreviewMarkdown.ts'
+
+const SCOPE_ID = 'data-v-previewtest'
+const FRONTEND_ROOT = new URL('../../', import.meta.url)
+const DOC_CONTENT_SFC = new URL('src/components/doc-content.vue', FRONTEND_ROOT)
+const DOCUMENT_PREVIEW_SFC = new URL('src/components/document-preview.vue', FRONTEND_ROOT)
+const THEME_CSS = new URL('src/assets/theme/theme.css', FRONTEND_ROOT)
+
+type StyleLang = 'less' | 'sass' | 'scss' | 'styl' | 'stylus'
+
+const SAMPLE = `# 一线标题
+
+正文段落用于确认段落间距。
+
+## 二级标题
+
+- 项目协同(团队版中)
+- 项目分享(团队版中)
+
+### 三级标题
+
+> 引用块
+
+#### 四级标题
+
+| 能力 | 说明 |
+| --- | --- |
+| 列表 | 支持 |
+
+行内 \`code\` 与代码块:
+
+\`\`\`ts
+const a = 1
+\`\`\`
+`
+
+/** 编译 SFC 里所有 scoped style 块(包含 less `@import` 与 `:deep()`)。 */
+function compileScopedStyle(file: URL): string {
+ const filename = fileURLToPath(file)
+ const { descriptor, errors } = parseSfc(readFileSync(filename, 'utf8'), { filename })
+ assert.equal(errors.length, 0, `SFC parse errors in ${filename}`)
+ const scoped = descriptor.styles.filter(style => style.scoped)
+ assert.ok(scoped.length > 0, `expected a scoped style block in ${filename}`)
+ return scoped
+ .map(style =>
+ compileStyle({
+ source: style.content,
+ filename,
+ id: SCOPE_ID,
+ scoped: true,
+ preprocessLang: style.lang as StyleLang | undefined,
+ }),
+ )
+ .map(result => {
+ assert.equal(result.errors.length, 0, `style compile errors in ${filename}`)
+ return result.code
+ })
+ .join('\n')
+}
+
+/** 读取 theme.css 里的 `--app-text-*` / `--app-space-*` 令牌。 */
+function readThemeTokens(): Map<string, string> {
+ const css = readFileSync(fileURLToPath(THEME_CSS), 'utf8')
+ const tokens = new Map<string, string>()
+ for (const match of css.matchAll(/--(app-(?:text|space)-[\w-]+)\s*:\s*([\d.]+px)/g)) {
+ tokens.set(`--${match[1]}`, match[2])
+ }
+ return tokens
+}
+
+const TOKENS = readThemeTokens()
+
+function resolvePx(value: string | undefined | null): number | null {
+ if (!value) return null
+ const trimmed = value.trim()
+ const varMatch = trimmed.match(/^var\(\s*(--[\w-]+)\s*\)$/)
+ if (varMatch) {
+ const token = TOKENS.get(varMatch[1])
+ return token ? Number.parseFloat(token) : null
+ }
+ const pxMatch = trimmed.match(/^(-?[\d.]+)px$/)
+ return pxMatch ? Number.parseFloat(pxMatch[1]) : null
+}
+
+function findByTag(root: DomNode, tag: string): DomNode | null {
+ for (const child of root.children) {
+ if (child.tag === tag) return child
+ const nested = findByTag(child, tag)
+ if (nested) return nested
+ }
+ return null
+}
+
+function findByClass(root: DomNode, className: string): DomNode | null {
+ for (const child of root.children) {
+ if (child.classes.includes(className)) return child
+ const nested = findByClass(child, className)
+ if (nested) return nested
+ }
+ return null
+}
+
+function requiredDeclared(rules: ReturnType<typeof parseCssRules>, node: DomNode, property: string): string {
+ const declaration = winningDeclaration(rules, node, property)
+ assert.ok(
+ declaration,
+ `no rule declares ${property} for <${node.tag}> under .${node.classes.join('.')}`,
+ )
+ return declaration.value
+}
+
+function numberFor(rules: ReturnType<typeof parseCssRules>, node: DomNode, property: string): number {
+ const value = requiredDeclared(rules, node, property)
+ const px = resolvePx(value)
+ assert.ok(px !== null, `cannot resolve ${property}: ${value}`)
+ return px
+}
+
+function markdownBody(): string {
+ // 两个界面用的是同一套 marked + marked-katex 结构;这里用预览管线生成
+ // 真实标签(h1/h2/ul/li/p/table/blockquote/pre/code),再分别套上各自的
+ // 容器与编译后的 scoped CSS。
+ return renderDocumentPreviewMarkdown(SAMPLE, value => value)
+}
+
+function mergedPreviewTree(): DomNode {
+ // 与 doc-content.vue 模板一致:.doc_content 下的正文根节点带 scoped 属性,
+ // v-html 容器是 .md-content。
+ const html = `<div class="doc_content" ${SCOPE_ID}><div class="doc-markdown-root doc-drawer-body" ${SCOPE_ID}><div class="md-content doc-merged-content" ${SCOPE_ID}>${markdownBody()}</div></div></div>`
+ return buildDomTree(html)
+}
+
+function documentPreviewTree(): DomNode {
+ // 与 document-preview.vue 模板一致:根 .document-preview 带 scoped 属性,
+ // Markdown 渲染进 .markdown-body。
+ const html = `<div class="document-preview" ${SCOPE_ID}><div class="preview-markdown"><div class="markdown-body" ${SCOPE_ID}>${markdownBody()}</div></div></div>`
+ return buildDomTree(html)
+}
+
+function assertTypography(surface: string, tree: DomNode, rules: ReturnType<typeof parseCssRules>) {
+ const headings = ['h1', 'h2', 'h3', 'h4'].map(tag => {
+ const node = findByTag(tree, tag)
+ assert.ok(node, `${surface}: rendered markup is missing <${tag}>`)
+ return numberFor(rules, node, 'font-size')
+ })
+
+ for (let index = 1; index < headings.length; index += 1) {
+ assert.ok(
+ headings[index] < headings[index - 1],
+ `${surface}: heading scale is flat (h${index}=${headings[index - 1]}px, h${index + 1}=${headings[index]}px)`,
+ )
+ }
+ assert.notEqual(headings[0], headings[1], `${surface}: h1 and h2 must not share a font-size`)
+
+ const ul = findByTag(tree, 'ul')
+ assert.ok(ul, `${surface}: rendered markup is missing <ul>`)
+ const ulIndent = numberFor(rules, ul, 'padding-left')
+ assert.ok(ulIndent >= 16, `${surface}: list indent too small (${ulIndent}px)`)
+
+ const li = findByTag(ul, 'li')
+ assert.ok(li, `${surface}: rendered markup is missing <li>`)
+ const liLineHeight = Number.parseFloat(requiredDeclared(rules, li, 'line-height'))
+ assert.ok(liLineHeight >= 1.5, `${surface}: list line-height too tight (${liLineHeight})`)
+
+ const paragraph = findByTag(tree, 'p')
+ assert.ok(paragraph, `${surface}: rendered markup is missing <p>`)
+ const paragraphGap = numberFor(rules, paragraph, 'margin-bottom')
+ assert.ok(paragraphGap > 0, `${surface}: paragraphs have no bottom spacing`)
+
+ const blockquote = findByTag(tree, 'blockquote')
+ assert.ok(blockquote, `${surface}: rendered markup is missing <blockquote>`)
+ const quoteBorder = numberFor(rules, blockquote, 'border-left-width')
+ assert.ok(quoteBorder > 0, `${surface}: blockquote has no left border`)
+
+ const table = findByTag(tree, 'table')
+ assert.ok(table, `${surface}: rendered markup is missing <table>`)
+ assert.equal(
+ requiredDeclared(rules, table, 'border-collapse').trim(),
+ 'collapse',
+ `${surface}: table borders must collapse`,
+ )
+
+ const pre = findByTag(tree, 'pre')
+ assert.ok(pre, `${surface}: rendered markup is missing <pre>`)
+ const preBackground = winningDeclaration(rules, pre, 'background')
+ assert.ok(preBackground, `${surface}: code block has no background`)
+
+ const inlineCode = findByTag(paragraph, 'code') ?? findByTag(tree, 'code')
+ assert.ok(inlineCode, `${surface}: rendered markup is missing <code>`)
+ assert.ok(
+ winningDeclaration(rules, inlineCode, 'padding') ?? winningDeclaration(rules, inlineCode, 'padding-left'),
+ `${surface}: inline code has no padding`,
+ )
+
+ // 正文窄栏:容器有可读的行宽上限(不是无限拉满整屏)。
+ const contentRoot = findByClass(tree, 'md-content') ?? findByClass(tree, 'markdown-body')
+ assert.ok(contentRoot, `${surface}: rendered markup is missing the content root`)
+ const maxWidth = numberFor(rules, contentRoot, 'max-width')
+ assert.ok(maxWidth >= 480 && maxWidth <= 800, `${surface}: reading column is ${maxWidth}px wide`)
+}
+
+test('merged/chunk view (.md-content) gets real Markdown typography', () => {
+ const rules = parseCssRules(compileScopedStyle(DOC_CONTENT_SFC))
+ assertTypography('.md-content', mergedPreviewTree(), rules)
+})
+
+test('preview view (.markdown-body) gets real Markdown typography', () => {
+ const rules = parseCssRules(compileScopedStyle(DOCUMENT_PREVIEW_SFC))
+ assertTypography('.markdown-body', documentPreviewTree(), rules)
+})
+
+test('scoped Markdown rules need the real container class in the DOM', () => {
+ const rules = parseCssRules(compileScopedStyle(DOC_CONTENT_SFC))
+ const treeWithoutClass = buildDomTree(
+ `<div class="doc_content" ${SCOPE_ID}><div class="doc-markdown-root" ${SCOPE_ID}><div class="doc_content-body">${markdownBody()}</div></div></div>`,
+ )
+ const h1 = findByTag(treeWithoutClass, 'h1')
+ assert.ok(h1)
+ // 没有 .md-content 容器时,这些排版规则不应命中(正是本次要修的「选择器
+ // 不命中」故障形态)。若这里开始能命中,说明规则被写成了全局标签选择器。
+ assert.equal(winningDeclaration(rules, h1, 'font-size'), null)
+})
+
+test('Markdown rules no longer depend on .doc_content being the render container', () => {
+ const rules = parseCssRules(compileScopedStyle(DOC_CONTENT_SFC))
+ const tree = mergedPreviewTree()
+ const h1 = findByTag(tree, 'h1')
+ assert.ok(h1)
+ const winner = winningDeclaration(rules, h1, 'font-size')
+ assert.ok(winner)
+ // 命中的选择器必须落在真实容器 .md-content 上,而不是抽屉外壳 .doc_content。
+ assert.match(winner.selector, /\.md-content/)
+ assert.doesNotMatch(winner.selector, /\.doc_content(?![\w-])/)
+})
diff --git a/frontend/src/test-utils/cssRuleMatcher.ts b/frontend/src/test-utils/cssRuleMatcher.ts
new file mode 100644
index 000000000..81e3b0092
--- /dev/null
+++ b/frontend/src/test-utils/cssRuleMatcher.ts
@@ -0,0 +1,322 @@
+/**
+ * 极简 CSS 规则匹配器,只服务于「排版样式是否命中」这类回归测试。
+ *
+ * 为什么不用 jsdom / Playwright:本仓库的测试跑在 `tsx --test`(纯 Node)里,
+ * 依赖里没有 DOM 实现,也不适合为了一个排版断言引入浏览器。这里用
+ * `@vue/compiler-dom` 解析真实渲染出的 HTML,再用 `@vue/compiler-sfc` 的
+ * `compileStyle`(与 Vite 构建同一条管线)得到编译后的 scoped CSS,最后按
+ * CSS 级联规则算出目标属性的生效值。
+ *
+ * 只支持测试里用到的选择器子集:标签、`.class`、`[attr]`、`[attr=value]`、
+ * 后代(空格)与子代(`>`)。带伪类/伪元素/兄弟选择器的规则一律视为不命中,
+ * 因此不要在断言里依赖它们。
+ */
+
+import { parse as parseDom } from '@vue/compiler-dom';
+
+export interface CssDeclaration {
+ prop: string;
+ value: string;
+ important: boolean;
+}
+
+export interface CssRule {
+ selector: string;
+ declarations: CssDeclaration[];
+}
+
+export interface DomNode {
+ tag: string;
+ classes: string[];
+ attributes: Record<string, string>;
+ parent: DomNode | null;
+ children: DomNode[];
+}
+
+/** 拆分选择器列表(不处理 `:has()` 等含逗号的伪类;此类规则本来就不支持)。 */
+function splitSelectorList(selector: string): string[] {
+ return selector
+ .split(',')
+ .map(part => part.trim())
+ .filter(Boolean);
+}
+
+function findBlockEnd(css: string, openBrace: number): number {
+ let depth = 0;
+ let quote: string | null = null;
+ for (let i = openBrace; i < css.length; i += 1) {
+ const char = css[i];
+ if (quote) {
+ if (char === '\\') i += 1;
+ else if (char === quote) quote = null;
+ continue;
+ }
+ if (char === '"' || char === "'") quote = char;
+ else if (char === '{') depth += 1;
+ else if (char === '}') {
+ depth -= 1;
+ if (depth === 0) return i;
+ }
+ }
+ return css.length - 1;
+}
+
+function splitDeclarations(body: string): string[] {
+ const parts: string[] = [];
+ let current = '';
+ let quote: string | null = null;
+ let parens = 0;
+ for (const char of body) {
+ if (quote) {
+ current += char;
+ if (char === quote) quote = null;
+ continue;
+ }
+ if (char === '"' || char === "'") quote = char;
+ else if (char === '(') parens += 1;
+ else if (char === ')') parens = Math.max(0, parens - 1);
+ if (char === ';' && parens === 0) {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ if (current.trim()) parts.push(current);
+ return parts;
+}
+
+/** 解析编译后的 CSS 文本(跳过 `@media` 等 at-rule,测试不依赖它们)。 */
+export function parseCssRules(css: string): CssRule[] {
+ const source = css.replace(/\/\*[\s\S]*?\*\//g, '');
+ const rules: CssRule[] = [];
+ let index = 0;
+ while (index < source.length) {
+ const openBrace = source.indexOf('{', index);
+ if (openBrace < 0) break;
+ const selector = source.slice(index, openBrace).trim();
+ const end = findBlockEnd(source, openBrace);
+ const body = source.slice(openBrace + 1, end);
+ if (!selector.startsWith('@')) {
+ rules.push({ selector, declarations: parseDeclarations(body) });
+ }
+ index = end + 1;
+ }
+ return rules;
+}
+
+function parseDeclarations(body: string): CssDeclaration[] {
+ const declarations: CssDeclaration[] = [];
+ for (const chunk of splitDeclarations(body)) {
+ const colon = chunk.indexOf(':');
+ if (colon < 0) continue;
+ const prop = chunk.slice(0, colon).trim().toLowerCase();
+ let value = chunk.slice(colon + 1).trim();
+ let important = false;
+ if (/!important\s*$/i.test(value)) {
+ important = true;
+ value = value.replace(/\s*!important\s*$/i, '').trim();
+ }
+ if (prop && value) declarations.push({ prop, value, important });
+ }
+ return declarations;
+}
+
+function elementProps(node: unknown): Array<Record<string, unknown>> {
+ const props = (node as { props?: unknown }).props;
+ return Array.isArray(props) ? (props as Array<Record<string, unknown>>) : [];
+}
+
+/** 把 `@vue/compiler-dom` 的模板 AST 转成便于匹配的简化树。 */
+export function buildDomTree(html: string): DomNode {
+ const root: DomNode = { tag: '#root', classes: [], attributes: {}, parent: null, children: [] };
+ const ast = parseDom(html);
+
+ const visit = (nodes: Array<Record<string, unknown>>, parent: DomNode) => {
+ for (const node of nodes) {
+ const type = node.type as number;
+ if (type !== 1) continue; // 只关心元素节点
+ const classes: string[] = [];
+ const attributes: Record<string, string> = {};
+ for (const prop of elementProps(node)) {
+ if (prop.type !== 6) continue;
+ const name = String(prop.name ?? '');
+ const valueNode = prop.value as { content?: string } | undefined;
+ const value = valueNode?.content ?? '';
+ if (name === 'class') {
+ classes.push(...value.split(/\s+/).filter(Boolean));
+ } else if (name) {
+ attributes[name] = value;
+ }
+ }
+ const element: DomNode = {
+ tag: String(node.tag ?? '').toLowerCase(),
+ classes,
+ attributes,
+ parent,
+ children: [],
+ };
+ parent.children.push(element);
+ visit((node.children as Array<Record<string, unknown>>) ?? [], element);
+ }
+ };
+
+ visit(
+ ((ast as unknown as { children?: Array<Record<string, unknown>> }).children) ?? [],
+ root,
+ );
+ return root;
+}
+
+function matchCompound(node: DomNode, compound: string): boolean {
+ // 不支持的语法(伪类、id、通配、兄弟选择器)直接判不命中
+ if (!compound || /[:#*+~]/.test(compound)) return false;
+ const parsed = compound.match(/^([a-zA-Z][\w-]*)?((?:\.[\w-]+|\[[^\]]+\])*)$/);
+ if (!parsed) return false;
+ const [, tag, rest] = parsed;
+ if (tag && node.tag !== tag.toLowerCase()) return false;
+
+ const tokenRe = /\.([\w-]+)|\[([^\]=]+)(?:=("([^"]*)"|'([^']*)'|([^\]]+)))?\]/g;
+ let match: RegExpExecArray | null;
+ while ((match = tokenRe.exec(rest ?? ''))) {
+ if (match[1]) {
+ if (!node.classes.includes(match[1])) return false;
+ continue;
+ }
+ const attrName = (match[2] ?? '').trim();
+ const expected = match[4] ?? match[5] ?? match[6];
+ if (!(attrName in node.attributes)) return false;
+ if (expected !== undefined && node.attributes[attrName] !== expected) return false;
+ }
+ return true;
+}
+
+/** 判断元素是否命中单个选择器(支持后代与 `>` 子代组合)。 */
+export function elementMatches(node: DomNode, selector: string): boolean {
+ if (!selector || /[+~]/.test(selector)) return false;
+ const parts = selector
+ .replace(/\s*>\s*/g, ' > ')
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (!parts.length) return false;
+ if (!matchCompound(node, parts[parts.length - 1])) return false;
+
+ let current = node;
+ let index = parts.length - 2;
+ while (index >= 0) {
+ const token = parts[index];
+ if (token === '>') {
+ const parent = current.parent;
+ if (!parent || !matchCompound(parent, parts[index - 1])) return false;
+ current = parent;
+ index -= 2;
+ continue;
+ }
+ let ancestor = current.parent;
+ while (ancestor && !matchCompound(ancestor, token)) ancestor = ancestor.parent;
+ if (!ancestor) return false;
+ current = ancestor;
+ index -= 1;
+ }
+ return true;
+}
+
+function specificity(selector: string): [number, number, number] {
+ const classAndAttr = (selector.match(/\.[\w-]+|\[[^\]]+\]/g) ?? []).length;
+ const tags = (selector.replace(/\[[^\]]+\]/g, ' ').match(/(^|\s|>)[a-zA-Z][\w-]*/g) ?? []).length;
+ const ids = (selector.match(/#[\w-]+/g) ?? []).length;
+ return [ids, classAndAttr, tags];
+}
+
+function compareSpecificity(a: [number, number, number], b: [number, number, number]): number {
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
+}
+
+function expand(value: string): string[] {
+ return value.trim().split(/\s+/).filter(Boolean);
+}
+
+function expandLonghands(declaration: CssDeclaration): CssDeclaration[] {
+ const { prop, value, important } = declaration;
+ const box = (prefix: 'margin' | 'padding') => {
+ const parts = expand(value);
+ const [top, right = top, bottom = top, left = right] = parts;
+ return [
+ { prop: `${prefix}-top`, value: top, important },
+ { prop: `${prefix}-right`, value: right, important },
+ { prop: `${prefix}-bottom`, value: bottom, important },
+ { prop: `${prefix}-left`, value: left, important },
+ ];
+ };
+ if (prop === 'margin') return box('margin');
+ if (prop === 'padding') return box('padding');
+ if (prop === 'border-left' || prop === 'border-right' || prop === 'border-top' || prop === 'border-bottom') {
+ const side = prop.slice('border-'.length);
+ const parts = expand(value);
+ const width = parts.find(part => /^(?:\d|\.)/.test(part) || part === 'thin' || part === 'medium' || part === 'thick') ?? '0';
+ const style = parts.find(part => /^(?:none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test(part)) ?? 'none';
+ return [{ prop: `border-${side}-width`, value: width, important }, { prop: `border-${side}-style`, value: style, important }];
+ }
+ if (prop === 'border') {
+ const parts = expand(value);
+ const width = parts.find(part => /^(?:\d|\.)/.test(part) || /^(?:thin|medium|thick)$/.test(part)) ?? '0';
+ const style = parts.find(part => /^(?:none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test(part)) ?? 'none';
+ return ['top', 'right', 'bottom', 'left'].flatMap(side => [
+ { prop: `border-${side}-width`, value: width, important },
+ { prop: `border-${side}-style`, value: style, important },
+ ]);
+ }
+ if (prop === 'background') {
+ return [
+ { prop: 'background', value, important },
+ { prop: 'background-color', value, important },
+ ];
+ }
+ return [{ prop, value, important }];
+}
+
+/**
+ * 计算某个元素上某个属性最终生效的声明(含简单级联:`!important` > 特异性 >
+ * 源码顺序)。返回 `null` 表示没有任何规则命中。
+ */
+export function winningDeclaration(
+ rules: CssRule[],
+ node: DomNode,
+ property: string,
+): { value: string; selector: string } | null {
+ let best: { value: string; selector: string; important: boolean; spec: [number, number, number] } | null = null;
+ for (const rule of rules) {
+ for (const selector of splitSelectorList(rule.selector)) {
+ if (!elementMatches(node, selector)) continue;
+ for (const declaration of rule.declarations) {
+ for (const longhand of expandLonghands(declaration)) {
+ if (longhand.prop !== property) continue;
+ const spec = specificity(selector);
+ if (
+ !best ||
+ (longhand.important && !best.important) ||
+ (longhand.important === best.important && compareSpecificity(spec, best.spec) >= 0)
+ ) {
+ best = { value: longhand.value, selector, important: longhand.important, spec };
+ }
+ }
+ }
+ }
+ }
+ return best ? { value: best.value, selector: best.selector } : null;
+}
+
+/** 从 CSS 中找出所有命中 `node` 且声明了 `property` 的规则选择器。 */
+export function matchingSelectors(rules: CssRule[], node: DomNode, property: string): string[] {
+ const selectors: string[] = [];
+ for (const rule of rules) {
+ for (const selector of splitSelectorList(rule.selector)) {
+ if (!elementMatches(node, selector)) continue;
+ if (rule.declarations.some(declaration => expandLonghands(declaration).some(longhand => longhand.prop === property))) {
+ selectors.push(selector);
+ }
+ }
+ }
+ return selectors;
+}
diff --git a/frontend/src/utils/documentPreviewMarkdown.ts b/frontend/src/utils/documentPreviewMarkdown.ts
index 79eee9d33..9ace48bb7 100644
--- a/frontend/src/utils/documentPreviewMarkdown.ts
+++ b/frontend/src/utils/documentPreviewMarkdown.ts
@@ -4,6 +4,7 @@ import markedKatex from 'marked-katex-extension'
import { domPurifyAllowedUriRegexp } from './markdownDomPurify.ts'
import { literalSingleTildeExtension } from './markedLiteralTilde.ts'
+import { stripDuplicateLeadingH1 } from './markdownTitleDedupe.ts'
import { escapeHTML, safeMarkdownToHTML, sanitizeDocumentPreviewHTML } from './security.ts'
const PREVIEW_IMAGE_ATTRIBUTES = 'loading="lazy" decoding="async" fetchpriority="low"'
@@ -64,10 +65,25 @@ function preprocessMathDelimiters(rawText: string): string {
.replace(/\\\(([\s\S]*?)\\\)/g, '$$$1$$')
}
+export interface DocumentPreviewMarkdownOptions {
+ /**
+ * Names already shown by the surrounding UI (drawer header, preview
+ * toolbar). A leading level-1 heading that normalizes to one of them is
+ * dropped so the document title is not rendered twice.
+ */
+ titles?: Array<string | null | undefined>
+}
+
export function renderDocumentPreviewMarkdown(
markdown: string,
sanitize: (html: string) => string = sanitizeDocumentPreviewHTML,
+ options: DocumentPreviewMarkdownOptions = {},
): string {
- const mathSafe = preprocessMathDelimiters(markdown)
+ // Strip the duplicated heading before delimiter preprocessing so the
+ // comparison sees the original text (math delimiters stay untouched).
+ const deduped = options.titles?.length
+ ? stripDuplicateLeadingH1(markdown, options.titles)
+ : markdown
+ const mathSafe = preprocessMathDelimiters(deduped)
return sanitize(previewMarked.parse(safeMarkdownToHTML(mathSafe)) as string)
}
diff --git a/frontend/src/utils/markdownTitleDedupe.test.ts b/frontend/src/utils/markdownTitleDedupe.test.ts
new file mode 100644
index 000000000..4521ab86d
--- /dev/null
+++ b/frontend/src/utils/markdownTitleDedupe.test.ts
@@ -0,0 +1,143 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ normalizeHeadingText,
+ stripDuplicateLeadingH1,
+} from './markdownTitleDedupe.ts'
+import { renderDocumentPreviewMarkdown } from './documentPreviewMarkdown.ts'
+
+const TITLE = '线上天诛2024新版本使用培训及使用细节事项注意点'
+
+test('strips the leading H1 when it repeats the document title', () => {
+ const source = `# ${TITLE}
+
+## 项目任务管理
+
+- 项目协同(团队版中)
+`
+ const result = stripDuplicateLeadingH1(source, [TITLE])
+
+ assert.equal(result, `## 项目任务管理
+
+- 项目协同(团队版中)
+`)
+})
+
+test('keeps the leading H1 when it differs from the document title', () => {
+ const source = `# 完全不同的标题
+
+正文段落。
+`
+ assert.equal(stripDuplicateLeadingH1(source, [TITLE]), source)
+})
+
+test('leaves Markdown without an H1 untouched', () => {
+ const source = `## 项目任务管理
+
+- 项目协同(团队版中)
+`
+ assert.equal(stripDuplicateLeadingH1(source, [TITLE]), source)
+})
+
+test('only strips the first heading, never a later H1', () => {
+ const source = `## 项目任务管理
+
+# ${TITLE}
+
+- 项目协同(团队版中)
+`
+ assert.equal(stripDuplicateLeadingH1(source, [TITLE]), source)
+})
+
+test('does not strip an H2 that happens to equal the title', () => {
+ const source = `## ${TITLE}
+
+正文。
+`
+ assert.equal(stripDuplicateLeadingH1(source, [TITLE]), source)
+})
+
+test('matches file names with an extension and decorative title prefixes', () => {
+ assert.equal(
+ stripDuplicateLeadingH1(`# ${TITLE}\n\n正文。\n`, [`${TITLE}.md`]),
+ '正文。\n',
+ )
+ assert.equal(
+ stripDuplicateLeadingH1(`# ${TITLE}\n\n正文。\n`, [`【使用必看】${TITLE}`]),
+ '正文。\n',
+ )
+ // 全角数字 / 多余空白也算同一个标题
+ assert.equal(
+ stripDuplicateLeadingH1('# 线上天诛2024新版本使用培训及使用细节事项注意点\n\n正文。\n', [TITLE]),
+ '正文。\n',
+ )
+})
+
+test('keeps YAML front matter while dropping the duplicated heading', () => {
+ const source = `---
+title: ${TITLE}
+tags: [kb]
+---
+
+# ${TITLE}
+
+正文。
+`
+ assert.equal(
+ stripDuplicateLeadingH1(source, [TITLE]),
+ `---
+title: ${TITLE}
+tags: [kb]
+---
+正文。
+`,
+ )
+})
+
+test('is a no-op when no usable title is supplied', () => {
+ const source = `# ${TITLE}\n\n正文。\n`
+ assert.equal(stripDuplicateLeadingH1(source, []), source)
+ assert.equal(stripDuplicateLeadingH1(source, [null, undefined, ' ']), source)
+})
+
+test('normalization collapses display-only differences but not real text', () => {
+ assert.equal(normalizeHeadingText(' 【使用必看】 **天诛** 2024 '), '天诛 2024')
+ assert.equal(normalizeHeadingText('`Code` [链接](https://x.test) 标题'), 'code 链接 标题')
+ assert.notEqual(normalizeHeadingText('天诛 2024'), normalizeHeadingText('天诛 2025'))
+})
+
+test('document preview renders the body without the duplicated H1 but keeps rich blocks', () => {
+ const source = `# ${TITLE}
+
+| 能力 | 说明 |
+| --- | --- |
+| 列表 | 支持 |
+
+\`\`\`ts
+const a = 1
+\`\`\`
+
+行内公式 $E = mc^2$
+
+- 项目协同
+`
+ const html = renderDocumentPreviewMarkdown(source, value => value, {
+ titles: [`${TITLE}.md`],
+ })
+
+ assert.doesNotMatch(html, /<h1>/)
+ assert.match(html, /<table>/)
+ assert.match(html, /<pre><code class="hljs">/)
+ assert.match(html, /class="katex"/)
+ assert.match(html, /<ul>/)
+ assert.match(html, /<li>项目协同<\/li>/)
+})
+
+test('document preview keeps an unrelated H1 intact', () => {
+ const html = renderDocumentPreviewMarkdown('# 另一个标题\n\n正文。\n', value => value, {
+ titles: [TITLE],
+ })
+
+ assert.match(html, /<h1>另一个标题<\/h1>/)
+})
diff --git a/frontend/src/utils/markdownTitleDedupe.ts b/frontend/src/utils/markdownTitleDedupe.ts
new file mode 100644
index 000000000..c9f0465c4
--- /dev/null
+++ b/frontend/src/utils/markdownTitleDedupe.ts
@@ -0,0 +1,97 @@
+/**
+ * 去掉正文开头与文档标题重复的一级标题。
+ *
+ * 文档抽屉 / 预览工具栏本身已经展示了条目名,而不少导入来源(飞书、钉钉、
+ * MarkItDown 等)会在正文第一行再写一次 `# 标题`,视觉上就是同一个标题连
+ * 出现两次。这里只在「正文第一个非空行是 ATX 一级标题,且规范化后等于当前
+ * 条目名」时删掉这一行;标题不同、没有一级标题、或一级标题出现在正文中间
+ * 时都原样返回,避免误删真正的章节结构。
+ *
+ * 本模块不依赖 DOM / marked,纯字符串处理,便于单测覆盖。
+ */
+
+/** YAML Front matter(允许在去掉标题时原样保留)。 */
+const FRONT_MATTER = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*\r?\n/;
+
+/** 仅用于把「文件名」和「标题」对齐的常见文档扩展名。 */
+const FILE_EXTENSION = /\.(?:md|markdown|mdown|mkd|mdx|txt|text|html?|pdf|docx?|pptx?)$/i;
+
+const ZERO_WIDTH = /[\u200b-\u200d\u2060\ufeff]/g;
+
+/**
+ * 标题规范化:只抹平「展示层」差异,不做模糊匹配。
+ *
+ * - NFKC:全角字母/数字与半角等价(`2024` == `2024`);
+ * - 去掉零宽字符、折叠空白;
+ * - 去掉标题/条目名开头常见的装饰标签(`【使用必看】`、`[Draft]`、`(1)`);
+ * - 去掉行内 Markdown 标记(`**`、`` ` ``、`[文字](链接)` 只留文字);
+ * - 去掉 ATX 标题两端的 `#`;
+ * - ASCII 大小写不敏感。
+ *
+ * 规范化后仍不相等就不删,这是「宁可不删,不可误删」的边界。
+ */
+export function normalizeHeadingText(value: string): string {
+ return value
+ .normalize('NFKC')
+ .replace(ZERO_WIDTH, '')
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/[*_`~]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .replace(/^(?:【[^】]*】|\[[^\]]*\]|\([^)]*\))\s*/, '')
+ .replace(/^#+\s*/, '')
+ .replace(/\s*#+$/, '')
+ .trim()
+ .toLowerCase();
+}
+
+function titleCandidates(titles: Array<string | null | undefined>): Set<string> {
+ const candidates = new Set<string>();
+ for (const title of titles) {
+ if (typeof title !== 'string') continue;
+ const trimmed = title.trim();
+ if (!trimmed) continue;
+ const withoutExtension = trimmed.replace(FILE_EXTENSION, '');
+ for (const variant of [trimmed, withoutExtension]) {
+ const normalized = normalizeHeadingText(variant);
+ if (normalized) candidates.add(normalized);
+ }
+ }
+ return candidates;
+}
+
+/**
+ * 删除正文开头与 `titles` 之一重复的一级标题。
+ *
+ * @param markdown 原始 Markdown 文本(可带 Front matter)。
+ * @param titles 当前界面上已经展示过的标题 / 文件名;空值会被忽略。
+ * @returns 去掉重复标题后的 Markdown;未命中时返回与输入完全相同的字符串。
+ */
+export function stripDuplicateLeadingH1(
+ markdown: string,
+ titles: Array<string | null | undefined>,
+): string {
+ if (!markdown || typeof markdown !== 'string') return markdown;
+ const candidates = titleCandidates(titles);
+ if (candidates.size === 0) return markdown;
+
+ const frontMatter = markdown.match(FRONT_MATTER)?.[0] ?? '';
+ const body = markdown.slice(frontMatter.length);
+ const eol = body.includes('\r\n') ? '\r\n' : '\n';
+ const lines = body.split(/\r?\n/);
+
+ let firstContent = 0;
+ while (firstContent < lines.length && lines[firstContent].trim() === '') firstContent += 1;
+ if (firstContent >= lines.length) return markdown;
+
+ // 只认 ATX 一级标题(`#` + 空格),`##` 及以下保持不动。
+ const heading = lines[firstContent].match(/^[ \t]{0,3}#(?:[ \t]+(.*))?$/);
+ if (!heading) return markdown;
+ if (!candidates.has(normalizeHeadingText(heading[1] ?? ''))) return markdown;
+
+ // 连同标题行后面紧跟的空行一起删掉,避免正文顶部多出空行。
+ let removeEnd = firstContent + 1;
+ while (removeEnd < lines.length && lines[removeEnd].trim() === '') removeEnd += 1;
+
+ return frontMatter + lines.slice(removeEnd).join(eol);
+}