You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "jackwener (via GitHub)" <gi...@apache.org> on 2026/08/29 19:42:51 UTC
Re: [PR] perf(ui): incrementally prepare streamed Markdown math [maka]
jackwener commented on code in PR #4207:
URL: https://github.com/apache/maka/pull/4207#discussion_r3887493480
##########
patches/@astryxdesign+core+0.5.0.patch:
##########
@@ -188,26 +193,59 @@ index 0fd8329..7e4ec57 100644
import { Fragment } from 'react';
import * as stylex from '@stylexjs/stylex';
import "../theme/tokens.stylex.js";
-@@ -1048,6 +1048,7 @@ export function Markdown({
+@@ -1048,6 +1048,8 @@ export function Markdown({
density = 'default',
headingLevelStart = 1,
isStreaming = false,
+ settledText,
++ transformSource,
onLinkClick,
sources,
citationStyle = 'label',
-@@ -1072,7 +1073,9 @@ export function Markdown({
+@@ -1072,26 +1074,22 @@ export function Markdown({
// Smooth bursty streamed chunks into a steady character-by-character reveal.
// When not streaming, the hook returns children unchanged (no-op).
- const smoothedText = useStreamingText(children, isStreaming);
+ const smoothedText = useStreamingText(children, isStreaming, {
+ settledText
+ });
++ const parsedText = transformSource ? transformSource(smoothedText) : smoothedText;
const incrementalStateRef = useRef(createIncrementalState());
- // Reset incremental cache when the autolink option toggles — cached
- // settled blocks were parsed with the previous setting.
-@@ -1139,17 +1142,25 @@ export function Markdown({
+- // Reset incremental cache when the autolink option toggles — cached
Review Comment:
**P3 — this silently drops a documented invariant guard.**
The patch now removes Astryx's autolink-toggle cache reset. That reset existed for a stated reason: settled blocks already in the incremental cache were parsed under the previous `autolink` setting, so toggling it without invalidating them leaves stale parses on screen.
It is safe today only because of a single fact outside this file — `markdown-body.tsx:161` passes `autolink="gfm"` as a hardcoded literal, and there is no other call site, so the flag cannot change at runtime and the reset was dead code here.
What I would ask for is a line in the PR body or the patch saying that, because the removal is currently unexplained. As it stands, the comment explaining *why* the guard existed is deleted along with the guard, so whoever later makes `autolink` dynamic gets a stale-cache bug with nothing left to warn them.
##########
packages/ui/src/markdown-math.tsx:
##########
@@ -20,177 +20,280 @@
import katex from 'katex';
import type { MarkdownInlinePlugin } from '@astryxdesign/core/Markdown';
-export interface PreparedMarkdownMath {
+const TOKEN_START = '\uE000MAKA_MATH:';
+const TOKEN_END = '\uE001';
+const TOKEN_PATTERN = /\uE000MAKA_MATH:([012]):([0-9a-f]+)\uE001/g;
+const LITERAL_TOKEN_PATTERN = /^\uE000MAKA_MATH:[012]:[0-9a-f]+\uE001/;
+
+/**
+ * Discardable derived state owned by one MarkdownBody mount. Capacity is two
+ * strings no larger than that component's currently displayed source and its
+ * transport form; a rewrite resets both and unmounting drops the cache.
+ */
+export interface MarkdownMathCache {
+ source: string;
text: string;
- settledText?: string;
- plugin: MarkdownInlinePlugin;
+ safeSourceEnd: number;
+ safeTextEnd: number;
}
-interface MathTokenValue {
- formula: string;
- displayMode: boolean;
+export function createMarkdownMathCache(): MarkdownMathCache {
+ return { source: '', text: '', safeSourceEnd: 0, safeTextEnd: 0 };
}
export function prepareMarkdownMath(
source: string,
- settledSource?: string,
-): PreparedMarkdownMath {
- const registry = createMathTokenRegistry([source, settledSource]);
- return {
- text: protectMathOutsideCode(source, registry.register),
- ...(settledSource === undefined
- ? {}
- : { settledText: protectMathOutsideCode(settledSource, registry.register) }),
- plugin: {
- pattern: registry.pattern,
- render: (match, key) => {
- const value = registry.values.get(match[0]);
- if (!value) return match[0];
- const html = katex.renderToString(value.formula, {
- displayMode: value.displayMode,
- output: 'htmlAndMathml',
- strict: 'warn',
- throwOnError: false,
- trust: false,
- });
- return (
- <span
- key={key}
- className={
- value.displayMode ? 'maka-math maka-math-display' : 'maka-math maka-math-inline'
- }
- dangerouslySetInnerHTML={{ __html: html }}
- />
- );
- },
- },
- };
-}
+ cache: MarkdownMathCache,
+): string {
+ // The caller currently supplies a full string rather than an append token,
+ // so proving that a rewrite did not occur requires this prefix check. It
+ // keeps the JavaScript lexer on the changing tail; it does not make the
+ // full-string identity check itself incremental.
+ const extendsPrevious = source.startsWith(cache.source);
+ const sourceStart = extendsPrevious ? cache.safeSourceEnd : 0;
+ const textStart = extendsPrevious ? cache.safeTextEnd : 0;
+ const protectedTail = protectMarkdownMath(
+ source.slice(sourceStart),
+ sourceStart === 0 || source[sourceStart - 1] === '\n',
+ );
+ const text = `${extendsPrevious ? cache.text.slice(0, textStart) : ''}${protectedTail.text}`;
-function createMathTokenRegistry(sources: Array<string | undefined>): {
- pattern: RegExp;
- register: (formula: string, displayMode: boolean) => string;
- values: Map<string, MathTokenValue>;
-} {
- let namespaceIndex = 0;
- let namespace = '';
- do {
- namespace = `\uE000MAKAMATH:${namespaceIndex}:`;
- namespaceIndex += 1;
- } while (sources.some((source) => source?.includes(namespace)));
-
- const tokenEnd = ':\uE001';
- const values = new Map<string, MathTokenValue>();
- const tokensByValue = new Map<string, string>();
- let nextTokenId = 0;
- return {
- pattern: new RegExp(`${escapeRegExp(namespace)}\\d+${escapeRegExp(tokenEnd)}`, 'g'),
- register: (formula, displayMode) => {
- const valueKey = JSON.stringify([displayMode, formula]);
- const existingToken = tokensByValue.get(valueKey);
- if (existingToken) return existingToken;
-
- const token = `${namespace}${nextTokenId}${tokenEnd}`;
- nextTokenId += 1;
- values.set(token, { formula, displayMode });
- tokensByValue.set(valueKey, token);
- return token;
- },
- values,
- };
+ cache.source = source;
+ cache.text = text;
+ cache.safeSourceEnd = sourceStart + protectedTail.safeSourceEnd;
+ cache.safeTextEnd = textStart + protectedTail.safeTextEnd;
+ return text;
}
-function protectMathOutsideCode(
- source: string,
- register: (formula: string, displayMode: boolean) => string,
-): string {
- const lines = source.split('\n');
- let fence: { character: string; length: number } | undefined;
- let proseLines: string[] = [];
- const protectedParts: string[] = [];
-
- const flushProse = () => {
- if (proseLines.length === 0) return;
- protectedParts.push(protectMathInProse(proseLines.join('\n'), register));
- proseLines = [];
+export const MARKDOWN_MATH_PLUGINS = [{
+ pattern: TOKEN_PATTERN,
+ render: (match, key) => {
+ const formula = decodeFormula(match[2] ?? '');
+ if (match[1] === '2') return formula;
+ const displayMode = match[1] === '1';
+ const html = katex.renderToString(formula, {
+ displayMode,
+ output: 'htmlAndMathml',
+ strict: 'warn',
+ throwOnError: false,
+ trust: false,
+ });
+ return (
+ <span
+ key={key}
+ className={
+ displayMode ? 'maka-math maka-math-display' : 'maka-math maka-math-inline'
+ }
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ );
+ },
+}] satisfies MarkdownInlinePlugin[];
+
+function protectMarkdownMath(source: string, startsAtLineStart = true): {
+ text: string;
+ safeSourceEnd: number;
+ safeTextEnd: number;
+} {
+ let text = '';
+ let index = 0;
+ let safeSourceEnd = 0;
+ let safeTextEnd = 0;
+ let atLineStart = startsAtLineStart;
+ let canMarkSafe = true;
+ const markSafe = () => {
+ if (!canMarkSafe) return;
+ safeSourceEnd = index;
+ safeTextEnd = text.length;
};
- for (const line of lines) {
- const opening = /^( {0,3})(`{3,}|~{3,})/.exec(line);
- if (opening) {
- flushProse();
- const marker = opening[2] ?? '';
- const character = marker[0] ?? '';
- if (!fence) {
- fence = { character, length: marker.length };
- } else if (character === fence.character && marker.length >= fence.length) {
- fence = undefined;
- }
- protectedParts.push(line);
- } else if (fence) {
- protectedParts.push(line);
- } else {
- proseLines.push(line);
+ while (index < source.length) {
+ const fence = atLineStart ? readFence(source, index) : undefined;
+ if (fence) {
+ text += source.slice(index, fence.end);
+ index = fence.end;
+ atLineStart = source[index - 1] === '\n';
+ if (fence.closed) markSafe();
+ else break;
+ continue;
}
- }
- flushProse();
-
- return protectedParts.join('\n');
-}
-function protectMathInProse(
- source: string,
- register: (formula: string, displayMode: boolean) => string,
-): string {
- let output = '';
- let index = 0;
+ const literalToken = readLiteralToken(source, index);
+ if (literalToken?.kind === 'pending') {
+ text += source.slice(index);
+ break;
+ }
+ if (literalToken?.kind === 'match') {
+ text += transportToken(literalToken.source, '2');
+ index = literalToken.end;
+ atLineStart = false;
+ markSafe();
+ continue;
+ }
- while (index < source.length) {
if (source[index] === '`') {
- const run = /^`+/.exec(source.slice(index))?.[0] ?? '`';
- const close = source.indexOf(run, index + run.length);
- if (close >= 0) {
- output += source.slice(index, close + run.length);
- index = close + run.length;
+ let runEnd = index + 1;
+ while (source[runEnd] === '`') runEnd++;
+ const run = source.slice(index, runEnd);
+ const close = source.indexOf(run, runEnd);
+ if (close < 0) {
+ text += run;
+ index = runEnd;
+ atLineStart = false;
+ canMarkSafe = false;
Review Comment:
**P3 — the one coverage combination that is missing.**
Each half of this is tested: the unterminated cases (unclosed fence, unmatched backtick, pending delimiter) have behavioural tests, and the append path is exercised by the growing-tail streaming test.
What no test covers is the *interaction* — an append that closes a construct which was unterminated in the previous render. That is exactly the case this latch exists for: the boundary must have stayed behind the opener so the closer is re-scanned in context.
A cheap direct test would prepare `a \`b` (unclosed backtick), then prepare `a \`b\` c`, and assert the result equals a single one-shot preparation of the full string. The same shape for `\(` and for a fence would pin the invariant at the unit level instead of relying on it holding through the rendered output.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org