Files
DeepTutor/web/features/notes/model/markdown.ts
lytanjie 305eb7bf75 fix: parse inline math in note tables and statistics notation (#2737)
* fix: parse inline math in note tables and statistics notation

BlockNote only renders `inlineMath` nodes, and two common shapes never
became one:

- `parseNoteMarkdown` converted inline `$...$` in a block's top-level
  content, but table cells live under `tableContent.rows`, which the walk
  never reached.
- The normaliser treated `$Var(N)$` and `$Cov(X, Y)$` as prose because the
  Latin-word heuristic did not recognise statistics function names, so it
  escaped the delimiters as stray dollars.

Recurse into `tableContent` cells and add the common statistics function
names to the math-word allowlist, with regression tests for both.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(web): count statistics names as maths only when they are called

"mean", "median", "rank", "span" and "var" are English words and a
keyword too, so with them in the word list "$52k mean, $48k median" became a
formula and a backticked `var x = 1` on a page with maths turned into KaTeX.
Keep them out of MATH_WORDS and accept them only before "(", which is how
Var(X) and Cov(X, Y) are written.

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: zszz3 <91608029+zszz3@users.noreply.github.com>
2026-11-29 15:11:07 +08:00

111 lines
3.8 KiB
TypeScript

import type { NoteBlock } from '@/lib/notes-api'
/** Keep editor.md math and diagram fences intact while migrating ordinary Markdown. */
export function parseNoteMarkdown(
markdown: string,
parse: (text: string) => NoteBlock[]
): NoteBlock[] {
const result: NoteBlock[] = []
const lines = markdown.split('\n')
let prose: string[] = []
const flush = () => {
if (prose.join('\n').trim()) result.push(...parse(prose.join('\n')))
prose = []
}
for (let index = 0; index < lines.length; index++) {
const line = lines[index]
const formula = /^\s*\$\$(.*?)\$\$\s*$/.exec(line)
if (formula) {
flush()
result.push({
id: crypto.randomUUID(),
type: 'math',
props: { formula: formula[1] },
children: [],
})
continue
}
if (/^\s*\$\$\s*$/.test(line)) {
const end = lines.findIndex((next, n) => n > index && /^\s*\$\$\s*$/.test(next))
if (end > index) {
flush()
result.push({
id: crypto.randomUUID(),
type: 'math',
props: { formula: lines.slice(index + 1, end).join('\n') },
children: [],
})
index = end
continue
}
}
const fence = /^\s*(`{3,}|~{3,})(\S*)\s*$/.exec(line)
if (fence) {
let end = index + 1
const close = new RegExp(`^\\s*${fence[1][0]}{${fence[1].length},}\\s*$`)
while (end < lines.length && !close.test(lines[end])) end++
if (end < lines.length && ['mermaid', 'flow', 'seq'].includes(fence[2])) {
flush()
result.push({
id: crypto.randomUUID(),
type: 'learning',
props: {
kind: fence[2] === 'mermaid' ? 'mermaid' : 'legacy_diagram',
markdown: lines.slice(index, end + 1).join('\n'),
prompt: '',
data: '{}',
sourceUrl: '',
},
children: [],
})
} else prose.push(...lines.slice(index, end + 1))
index = end
continue
}
prose.push(line)
}
flush()
const splitInlineMath = (items: unknown[]): unknown[] =>
items.flatMap(raw => {
const item = raw as { type: string; text?: string; styles?: Record<string, unknown> }
if (item.type !== 'text' || item.styles?.code || !item.text) return [raw]
const out: unknown[] = []
let cursor = 0
for (const match of item.text.matchAll(/(?<![\\$])\$([^$\n]+)\$(?!\$)/g)) {
if (match.index! > cursor)
out.push({ ...item, text: item.text.slice(cursor, match.index) })
out.push({ type: 'inlineMath', props: { formula: match[1] } })
cursor = match.index! + match[0].length
}
if (cursor < item.text.length) out.push({ ...item, text: item.text.slice(cursor) })
return out
})
const inlineMath = (blocks: NoteBlock[]) =>
blocks.forEach(block => {
if (block.type !== 'codeBlock') {
if (Array.isArray(block.content)) {
block.content = splitInlineMath(block.content)
} else if (block.content && typeof block.content === 'object') {
// BlockNote table cells carry their own inline-content arrays. The
// top-level walk never reached them, so formulas inside a table
// stayed literal `$...$` text and rendered as raw LaTeX.
const table = block.content as {
type?: string
rows?: Array<{ cells?: Array<{ content?: unknown }> }>
}
if (table.type === 'tableContent' && Array.isArray(table.rows)) {
for (const row of table.rows) {
for (const cell of row.cells ?? []) {
if (Array.isArray(cell.content)) cell.content = splitInlineMath(cell.content)
}
}
}
}
}
if (block.children) inlineMath(block.children)
})
inlineMath(result)
return result
}