mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 04:59:37 +08:00
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>
This commit is contained in:
@@ -65,23 +65,43 @@ export function parseNoteMarkdown(
|
||||
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' && Array.isArray(block.content)) {
|
||||
block.content = block.content.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 (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 (cursor < item.text.length) out.push({ ...item, text: item.text.slice(cursor) })
|
||||
return out
|
||||
})
|
||||
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)
|
||||
})
|
||||
|
||||
@@ -41,6 +41,7 @@ const MATH_WORDS = new Set([
|
||||
"sec",
|
||||
"csc",
|
||||
"log",
|
||||
"ln",
|
||||
"exp",
|
||||
"lim",
|
||||
"max",
|
||||
@@ -53,7 +54,53 @@ const MATH_WORDS = new Set([
|
||||
"lcm",
|
||||
"mod",
|
||||
"arg",
|
||||
"argmax",
|
||||
"argmin",
|
||||
]);
|
||||
// Statistics and linear-algebra names. `Var(X)` and `Cov(X, Y)` are ordinary
|
||||
// prose to the Latin-word heuristic unless these are known, which used to make
|
||||
// `escapeStrayDollars` turn `$Var(N)$` back into literal source. Most are also
|
||||
// English words or keywords ("$52k mean, $48k median", `var x = 1`), so they
|
||||
// only count when written as a call.
|
||||
const FUNCTION_NAMES = new Set([
|
||||
"var",
|
||||
"cov",
|
||||
"corr",
|
||||
"std",
|
||||
"sd",
|
||||
"mean",
|
||||
"median",
|
||||
"mode",
|
||||
"prob",
|
||||
"pdf",
|
||||
"cdf",
|
||||
"pmf",
|
||||
"mgf",
|
||||
"rank",
|
||||
"tr",
|
||||
"trace",
|
||||
"span",
|
||||
"ker",
|
||||
"deg",
|
||||
]);
|
||||
|
||||
/** Is every Latin word of at least `minLength` letters in `value` maths? */
|
||||
function wordsAreMath(
|
||||
value: string,
|
||||
minLength: number,
|
||||
allow: (word: string) => boolean = () => false,
|
||||
): boolean {
|
||||
for (const match of value.matchAll(/[A-Za-z]+/g)) {
|
||||
const word = match[0];
|
||||
if (word.length < minLength) continue;
|
||||
const name = word.toLowerCase();
|
||||
if (MATH_WORDS.has(name) || allow(word)) continue;
|
||||
const called = /^\s*\(/.test(value.slice(match.index + word.length));
|
||||
if (FUNCTION_NAMES.has(name) && called) continue;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// masking
|
||||
@@ -208,8 +255,7 @@ function plausibleMathBody(body: string, tight: boolean): boolean {
|
||||
|
||||
// Latin prose gives itself away with words. `x + y`, `f(x)` and `E = mc` are
|
||||
// all formulas; "5 and the value of " is not.
|
||||
const words = value.match(/[A-Za-z]{3,}/g) ?? [];
|
||||
return words.every((word) => MATH_WORDS.has(word.toLowerCase()));
|
||||
return wordsAreMath(value, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,11 +280,10 @@ function looksLikePlainMathExpression(value: string): boolean {
|
||||
|
||||
// Multi-letter runs are variables juxtaposed for multiplication (`AB`, `BCD`)
|
||||
// or named functions — never lowercase words like `npm run dev`.
|
||||
const words = value.match(/[A-Za-z]{2,}/g) ?? [];
|
||||
return words.every(
|
||||
(word) =>
|
||||
MATH_WORDS.has(word.toLowerCase()) ||
|
||||
(word.length <= 4 && word === word.toUpperCase()),
|
||||
return wordsAreMath(
|
||||
value,
|
||||
2,
|
||||
(word) => word.length <= 4 && word === word.toUpperCase(),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -126,6 +126,13 @@ test("a code span holding code stays code", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a statistics name only reads as maths when it is called", () => {
|
||||
// `var` is a keyword in a page that also has real maths, not Var(X).
|
||||
const code = "设 $x$ 为变量,代码写成 `var x = 1`。";
|
||||
assert.equal(normalizeMathMarkup(code), code);
|
||||
assert.equal(normalizeMathMarkup("方差 $Var (N)$ 与 $Cov(X, Y)$。"), "方差 $Var (N)$ 与 $Cov(X, Y)$。");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// backslashes that are not maths
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -215,6 +222,11 @@ test("currency is escaped so remark-math cannot swallow it", () => {
|
||||
normalizeMathMarkup("It costs $5 and the value of $x$ is 2."),
|
||||
"It costs \\$5 and the value of $x$ is 2.",
|
||||
);
|
||||
// Statistics names are English words too: between two prices they are prose.
|
||||
assert.equal(
|
||||
normalizeMathMarkup("Salaries: $52k mean, $48k median."),
|
||||
"Salaries: \\$52k mean, $48k median.",
|
||||
);
|
||||
});
|
||||
|
||||
test("real formulas survive the same pass", () => {
|
||||
@@ -223,6 +235,9 @@ test("real formulas survive the same pass", () => {
|
||||
"设 $x$ 为变量,$y$ 为常量。",
|
||||
"$\\text{速度} = \\frac{s}{t}$",
|
||||
"已知 $速度 = 路程/时间$ 求解。",
|
||||
"求 $N$ 的方差 $Var(N)$。",
|
||||
"> 方差 $Var(N)$ 已知。",
|
||||
"统计量 $Cov(X,Y)$ 与 $Corr(X,Y)$。",
|
||||
"$$\n\\overline{A+B}=\\bar{A}\\bar{B}\n$$",
|
||||
]) {
|
||||
assert.equal(normalizeMathMarkup(input), input);
|
||||
@@ -261,6 +276,9 @@ test("routing agrees with what normalisation produces", () => {
|
||||
assert.equal(hasMarkdownMath(input), true, input);
|
||||
assert.notEqual(normalizeMathMarkup(input), input, input);
|
||||
}
|
||||
// Already-delimited statistics notation must route to KaTeX and survive
|
||||
// normalisation byte-for-byte.
|
||||
assert.equal(hasMarkdownMath("求 $N$ 的方差 $Var(N)$。"), true);
|
||||
|
||||
const shouldNot = [
|
||||
"价格是 $5 和 $10。",
|
||||
|
||||
@@ -24,6 +24,38 @@ describe('notebook migration and generated content', () => {
|
||||
it('keeps unfinished math input as ordinary text', () => {
|
||||
expect(parseNoteMarkdown('$$\nunclosed', parse)[0].type).toBe('paragraph')
|
||||
})
|
||||
it('converts inline math inside table cells', () => {
|
||||
const tableParse = (): NoteBlock[] => [
|
||||
{
|
||||
id: 'table',
|
||||
type: 'table',
|
||||
props: {},
|
||||
content: {
|
||||
type: 'tableContent',
|
||||
rows: [
|
||||
{
|
||||
cells: [
|
||||
{
|
||||
type: 'tableCell',
|
||||
content: [
|
||||
{ type: 'text', text: '$P(A\\mid B)=\\dfrac{P(AB)}{P(B)}$', styles: {} },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
const blocks = parseNoteMarkdown('table', tableParse)
|
||||
const table = blocks[0].content as {
|
||||
rows: Array<{ cells: Array<{ content: Array<{ type: string; props?: { formula?: string } }> }> }>
|
||||
}
|
||||
const cell = table.rows[0].cells[0].content
|
||||
expect(cell).toHaveLength(1)
|
||||
expect(cell[0].type).toBe('inlineMath')
|
||||
expect(cell[0].props?.formula).toBe('P(A\\mid B)=\\dfrac{P(AB)}{P(B)}')
|
||||
})
|
||||
it('persists question payloads without the chat quiz provider', () => {
|
||||
const result = resultLearningBlock({
|
||||
summary: { results: [{ qa_pair: { question: 'Frequency?', correct_answer: 'Hz' } }] },
|
||||
|
||||
Reference in New Issue
Block a user