fix(webui): preserve TeX formula boundaries in streaming Markdown
This commit is contained in:
1 parent
d0d0a44e57
commit
810802e016
9 files changed
+329
-46
No files matched your search
@@ -0,0 +1,56 @@
|
||||
import type { Nodes } from "mdast";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import remarkMath from "remark-math";
|
||||
import remarkParse from "remark-parse";
|
||||
import { parseMarkdownIntoBlocks } from "streamdown";
|
||||
import { unified } from "unified";
|
||||
|
||||
import { remarkTexMath } from "@/lib/remark-tex-math";
|
||||
|
||||
const boundaryParser = unified()
|
||||
.use(remarkParse)
|
||||
.use(remarkGfm)
|
||||
.use(remarkMath, { singleDollarTextMath: false })
|
||||
.use(remarkTexMath, { allowUnclosedFlow: true })
|
||||
.freeze();
|
||||
|
||||
function containsMath(node: Nodes): boolean {
|
||||
return node.type === "math" || node.type === "inlineMath"
|
||||
|| ("children" in node && node.children.some(containsMath));
|
||||
}
|
||||
|
||||
/** Keep formula boundaries intact without replacing Streamdown's ordinary block grouping. */
|
||||
export function parseMathAwareMarkdownBlocks(source: string): string[] {
|
||||
const blocks = parseMarkdownIntoBlocks(source);
|
||||
if (blocks.length < 2 || !/\$\$|\\\[/.test(source)) return blocks;
|
||||
|
||||
// Marked normalizes line endings. Do not compare its offsets against different source bytes.
|
||||
if (blocks.join("") !== source) return [source];
|
||||
|
||||
const ranges: Array<{ start: number; end: number }> = [];
|
||||
for (const node of boundaryParser.parse(source).children) {
|
||||
if (!containsMath(node)) continue;
|
||||
const start = node.position?.start.offset;
|
||||
const end = node.position?.end.offset;
|
||||
if (start === undefined || end === undefined) return [source];
|
||||
// Protect the enclosing list/quote too: isolated continuation lines lose their container.
|
||||
ranges.push({ start, end });
|
||||
}
|
||||
if (ranges.length === 0) return blocks;
|
||||
|
||||
const merged: string[] = [];
|
||||
let pending = "";
|
||||
let offset = 0;
|
||||
let rangeIndex = 0;
|
||||
for (const block of blocks) {
|
||||
pending += block;
|
||||
offset += block.length;
|
||||
while (rangeIndex < ranges.length && offset >= ranges[rangeIndex].end) rangeIndex++;
|
||||
const range = ranges[rangeIndex];
|
||||
if (range && range.start < offset && offset < range.end) continue;
|
||||
merged.push(pending);
|
||||
pending = "";
|
||||
}
|
||||
if (pending) merged.push(pending);
|
||||
return merged;
|
||||
}
|
||||
@@ -25,37 +25,50 @@ type ProcessorData = {
|
||||
micromarkExtensions?: Extension[];
|
||||
};
|
||||
|
||||
const texMathSyntax: Extension = {
|
||||
flow: {
|
||||
[BACKSLASH]: {
|
||||
tokenize: tokenizeTexMathFlow,
|
||||
concrete: true,
|
||||
name: "texMathFlow",
|
||||
function texMathSyntax(allowUnclosedFlow: boolean): Extension {
|
||||
return {
|
||||
flow: {
|
||||
[BACKSLASH]: {
|
||||
tokenize(effects, ok, nok) {
|
||||
return tokenizeTexMathFlow(effects, ok, nok, allowUnclosedFlow);
|
||||
},
|
||||
concrete: true,
|
||||
name: "texMathFlow",
|
||||
},
|
||||
[DOLLAR]: {
|
||||
tokenize(effects, ok, nok) {
|
||||
return tokenizeDollarMathFlow(effects, ok, nok, allowUnclosedFlow);
|
||||
},
|
||||
concrete: true,
|
||||
name: "dollarMathFlow",
|
||||
},
|
||||
},
|
||||
[DOLLAR]: {
|
||||
tokenize: tokenizeDollarMathFlow,
|
||||
concrete: true,
|
||||
name: "dollarMathFlow",
|
||||
text: {
|
||||
[BACKSLASH]: {
|
||||
tokenize: tokenizeTexMathText,
|
||||
name: "texMathText",
|
||||
},
|
||||
[DOLLAR]: {
|
||||
tokenize: tokenizeGuardedDollarMathText,
|
||||
name: "guardedDollarMathText",
|
||||
},
|
||||
},
|
||||
},
|
||||
text: {
|
||||
[BACKSLASH]: {
|
||||
tokenize: tokenizeTexMathText,
|
||||
name: "texMathText",
|
||||
},
|
||||
[DOLLAR]: {
|
||||
tokenize: tokenizeGuardedDollarMathText,
|
||||
name: "guardedDollarMathText",
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export const remarkTexMath: Plugin<[], Root> = function remarkTexMath() {
|
||||
interface TexMathOptions {
|
||||
/** Keep an unfinished display formula together when locating streaming block boundaries. */
|
||||
allowUnclosedFlow?: boolean;
|
||||
}
|
||||
|
||||
export const remarkTexMath: Plugin<[TexMathOptions?], Root> = function remarkTexMath(
|
||||
{ allowUnclosedFlow = false } = {},
|
||||
) {
|
||||
const data = this.data() as ProcessorData;
|
||||
const micromarkExtensions =
|
||||
data.micromarkExtensions || (data.micromarkExtensions = []);
|
||||
|
||||
micromarkExtensions.push(texMathSyntax);
|
||||
micromarkExtensions.push(texMathSyntax(allowUnclosedFlow));
|
||||
};
|
||||
|
||||
function isLineEnding(code: Code): boolean {
|
||||
@@ -93,6 +106,19 @@ const dollarMathFlowClose: Construct = {
|
||||
partial: true,
|
||||
};
|
||||
|
||||
const nonLazyContinuation: Construct = {
|
||||
partial: true,
|
||||
tokenize(effects, ok, nok) {
|
||||
const lineStart: State = (code) => this.parser.lazy[this.now().line] ? nok(code) : ok(code);
|
||||
return (code) => {
|
||||
effects.enter("lineEnding");
|
||||
effects.consume(code);
|
||||
effects.exit("lineEnding");
|
||||
return lineStart;
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
// Model output commonly uses `$...$`; numeric-only spans are usually prices, not formulas.
|
||||
function tokenizeGuardedDollarMathText(effects: Effects, ok: State, nok: State): State {
|
||||
let hasMathSignal = false;
|
||||
@@ -212,18 +238,26 @@ function tokenizeTexMathText(effects: Effects, ok: State, nok: State): State {
|
||||
}
|
||||
}
|
||||
|
||||
function tokenizeTexMathFlow(effects: Effects, ok: State, nok: State): State {
|
||||
return tokenizeMathFlow(effects, ok, nok, LEFT_BRACKET, BACKSLASH, texMathFlowClose);
|
||||
function tokenizeTexMathFlow(
|
||||
effects: Effects, ok: State, nok: State, allowUnclosedFlow: boolean,
|
||||
): State {
|
||||
return tokenizeMathFlow(
|
||||
effects, ok, nok, LEFT_BRACKET, BACKSLASH, texMathFlowClose, allowUnclosedFlow,
|
||||
);
|
||||
}
|
||||
|
||||
// Treat text after an opening $$ as formula content, not Markdown fence metadata.
|
||||
function tokenizeDollarMathFlow(effects: Effects, ok: State, nok: State): State {
|
||||
return tokenizeMathFlow(effects, ok, nok, DOLLAR, DOLLAR, dollarMathFlowClose);
|
||||
function tokenizeDollarMathFlow(
|
||||
effects: Effects, ok: State, nok: State, allowUnclosedFlow: boolean,
|
||||
): State {
|
||||
return tokenizeMathFlow(
|
||||
effects, ok, nok, DOLLAR, DOLLAR, dollarMathFlowClose, allowUnclosedFlow,
|
||||
);
|
||||
}
|
||||
|
||||
function tokenizeMathFlow(
|
||||
effects: Effects, ok: State, nok: State,
|
||||
openingTail: number, closingStart: number, closing: Construct,
|
||||
openingTail: number, closingStart: number, closing: Construct, allowUnclosedFlow = false,
|
||||
): State {
|
||||
return start;
|
||||
|
||||
@@ -251,14 +285,9 @@ function tokenizeMathFlow(
|
||||
}
|
||||
|
||||
function contentStart(code: Code): State | undefined {
|
||||
if (code === null) return nok(code);
|
||||
if (code === null) return allowUnclosedFlow ? done(code) : nok(code);
|
||||
|
||||
if (isLineEnding(code)) {
|
||||
effects.enter("lineEnding");
|
||||
effects.consume(code);
|
||||
effects.exit("lineEnding");
|
||||
return contentStart;
|
||||
}
|
||||
if (isLineEnding(code)) return beforeLineEnding(code);
|
||||
|
||||
if (code === closingStart) {
|
||||
return effects.attempt(closing, done, contentStartAfterDelimiter)(code);
|
||||
@@ -271,15 +300,12 @@ function tokenizeMathFlow(
|
||||
function content(code: Code): State | undefined {
|
||||
if (code === null) {
|
||||
effects.exit("mathFlowValue");
|
||||
return nok(code);
|
||||
return allowUnclosedFlow ? done(code) : nok(code);
|
||||
}
|
||||
|
||||
if (isLineEnding(code)) {
|
||||
effects.exit("mathFlowValue");
|
||||
effects.enter("lineEnding");
|
||||
effects.consume(code);
|
||||
effects.exit("lineEnding");
|
||||
return contentStart;
|
||||
return beforeLineEnding(code);
|
||||
}
|
||||
|
||||
if (code === closingStart) {
|
||||
@@ -291,6 +317,20 @@ function tokenizeMathFlow(
|
||||
return openingTail === DOLLAR && code === BACKSLASH ? escaped : content;
|
||||
}
|
||||
|
||||
function beforeLineEnding(code: Code): State | undefined {
|
||||
// A pending formula must end with its list/quote, not absorb following root blocks.
|
||||
return allowUnclosedFlow
|
||||
? effects.check(nonLazyContinuation, consumeLineEnding, done)(code)
|
||||
: consumeLineEnding(code);
|
||||
}
|
||||
|
||||
function consumeLineEnding(code: Code): State | undefined {
|
||||
effects.enter("lineEnding");
|
||||
effects.consume(code);
|
||||
effects.exit("lineEnding");
|
||||
return contentStart;
|
||||
}
|
||||
|
||||
function escaped(code: Code): State | undefined {
|
||||
if (code === null || isLineEnding(code)) return content(code);
|
||||
effects.consume(code);
|
||||
@@ -305,12 +345,12 @@ function tokenizeMathFlow(
|
||||
|
||||
function done(code: Code): State | undefined {
|
||||
effects.exit("mathFlow");
|
||||
if (openingTail === DOLLAR) return factorySpace(effects, afterClose, "whitespace")(code);
|
||||
return ok(code);
|
||||
// Flow constructs must finish at EOL/EOF, including Remend's synthetic link suffixes.
|
||||
return factorySpace(effects, afterClose, "whitespace")(code);
|
||||
}
|
||||
|
||||
function afterClose(code: Code): State | undefined {
|
||||
// Inline formulas followed by prose belong to remark-math's text tokenizer.
|
||||
// Reject suffixes that would leave the flow tokenizer in the middle of a line.
|
||||
return code === null || isLineEnding(code) ? ok(code) : nok(code);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user