mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-04 14:16:49 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f891fa2bc6 | ||
|
|
7db2863001 | ||
|
|
90adba1434 | ||
|
|
88855d1346 | ||
|
|
df8c49b290 | ||
|
|
aea0f0e7cb | ||
|
|
ea387e144b | ||
|
|
cc7ac5fc28 |
+3
-2
@@ -216,16 +216,17 @@ not change the shipped scroll view. Keep this behavior in the app's compiled nat
|
||||
|
||||
## F-Droid / source-only Android builds
|
||||
|
||||
F-Droid builds should set `PASEO_FDROID_BUILD=1` when running Expo prebuild:
|
||||
F-Droid builds should set `PASEO_FDROID_BUILD=1` for `npm ci` (or `npm install`), Expo prebuild, and Gradle:
|
||||
|
||||
```bash
|
||||
PASEO_FDROID_BUILD=1 npm ci
|
||||
cd packages/app
|
||||
PASEO_FDROID_BUILD=1 APP_VARIANT=production npx expo prebuild --platform android --clean --non-interactive
|
||||
cd android
|
||||
PASEO_FDROID_BUILD=1 ./gradlew assembleRelease --no-daemon --max-workers=1 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
The flag must be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications.
|
||||
Setting `PASEO_FDROID_BUILD=1` during install makes `packages/react-native-enriched-markdown/postinstall.mjs` skip downloading the prebuilt iOS RaTeX XCFramework into the source tree. The flag must also be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications. Setting `PASEO_FDROID_BUILD=1` also disables native RaTeX math in `react-native-enriched-markdown` and falls back to raw LaTeX text without requiring a Rust toolchain.
|
||||
|
||||
For a single-ABI APK, pass React Native's architecture property to Gradle:
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`, and downloads RaTeX into `ios/vendor` when `enableMath` is true (unless `PASEO_FDROID_BUILD=1`). The `enriched-markdown` block in `packages/app/package.json` chooses the languages and enables native math.
|
||||
|
||||
CI does not build native code or run the fork's Robolectric suites. Run `npm run test:android --workspace=@getpaseo/app` for Android changes. Native changes require a client rebuild; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
@@ -46,7 +46,17 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
Built-in LaTeX math is enabled by default, and video is disabled. Task lists and admonitions are enabled, and task checkboxes stay read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing, and details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
### LaTeX math
|
||||
|
||||
`components/markdown/math.ts` accepts `$...$`, `$$...$$`, `\(...\)`, `\[...\]`, and closed `math` fences (` ```math ` or `~~~math`). Inline `$...$` requires non-alphanumeric outer boundaries, no inner edge spaces, and no leading currency number or shell prose. Escaped `\[1, 2\]` citations, `$PATH`, regexes, and `latex` or `tex` code fences stay literal. Non-math messages skip scanning with a fast character check and do not trigger an `mdast` parse. Adapted expressions canonicalize to `$...$` or `$$...$$` for `md4c`, escape table pipes inside table rows, and flank adjacent CJK characters with hair spaces.
|
||||
|
||||
On web and Electron, `react-native-enriched-markdown` loads KaTeX (`htmlAndMathml` output with `.woff2` fonts) lazily when a document contains a math node. It caches rendered HTML in a 256-entry LRU and skips root-font overrides on `.katex` elements. Selection copy restores `[data-math-source]` to `$...$` or `$$\n...\n$$` without hidden `.katex-mathml` or `annotation` nodes. Chat Find ignores `.katex-mathml`, `annotation`, and `annotation-xml` nodes as well.
|
||||
|
||||
On iOS and Android, native views render with RaTeX (`enableMath: true` in `packages/app/package.json`). F-Droid builds (`PASEO_FDROID_BUILD=1`) disable native RaTeX in Gradle and `postinstall.mjs`, falling back to raw LaTeX. On 32-bit `x86` Android devices without `libratex_ffi.so`, the math views catch `Throwable` and render raw LaTeX text.
|
||||
|
||||
While streaming, `streaming.ts` keeps open `$$`, `\[`, and `math` fences in the unsealed tail so equations never split across blocks. Incomplete inline and display math stays withheld or literal until its closing delimiter arrives.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
|
||||
Generated
+1
@@ -37620,6 +37620,7 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"htmlparser2": "^12.0.0",
|
||||
"i18next": "^26.3.0",
|
||||
"katex": "^0.16.47",
|
||||
"lucide-react-native": "^1.50.0",
|
||||
"markdown-it": "^10.0.0",
|
||||
"mdast-util-from-markdown": "2.0.3",
|
||||
|
||||
Vendored
+4
@@ -1 +1,5 @@
|
||||
declare module "*.css";
|
||||
declare module "*.woff2" {
|
||||
const src: string;
|
||||
export default src;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ const customWebPlatform = (process.env.PASEO_WEB_PLATFORM ?? "")
|
||||
.toLowerCase();
|
||||
|
||||
const config = getDefaultConfig(projectRoot);
|
||||
if (!config.resolver.assetExts.includes("woff2")) {
|
||||
config.resolver.assetExts.push("woff2");
|
||||
}
|
||||
config.cacheVersion = isWatchdogBuild ? "watchdog" : "standard";
|
||||
const defaultResolveRequest = config.resolver.resolveRequest ?? resolve;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --tests '*MathRenderingFallbackTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
@@ -110,6 +110,7 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"htmlparser2": "^12.0.0",
|
||||
"i18next": "^26.3.0",
|
||||
"katex": "^0.16.47",
|
||||
"lucide-react-native": "^1.50.0",
|
||||
"markdown-it": "^10.0.0",
|
||||
"mdast-util-from-markdown": "2.0.3",
|
||||
@@ -178,7 +179,7 @@
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"enriched-markdown": {
|
||||
"enableMath": false,
|
||||
"enableMath": true,
|
||||
"enableCodeHighlight": true,
|
||||
"codeHighlightLanguages": [
|
||||
"json",
|
||||
|
||||
@@ -122,3 +122,26 @@ it("keeps text around nested plugin blocks in separate occurrences", () => {
|
||||
expect(findRenderedMatches(row, "details").map((range) => range.toString())).toEqual(["details"]);
|
||||
expect(findRenderedMatches(row, "beta").map((range) => range.toString())).toEqual(["beta"]);
|
||||
});
|
||||
|
||||
it("ignores KaTeX MathML and annotations while keeping block math as a boundary", () => {
|
||||
const row = content(
|
||||
[
|
||||
"<p>Before ",
|
||||
'<span role="math" aria-label="alpha" data-display="inline" data-math-source="$alpha$">',
|
||||
'<span class="katex">',
|
||||
'<span class="katex-mathml"><math><semantics><mrow><mi>alpha</mi></mrow><annotation encoding="application/x-tex">alpha</annotation><annotation-xml encoding="MathML-Content"><ci>alpha</ci></annotation-xml></semantics></math></span>',
|
||||
'<span class="katex-html" aria-hidden="true"><span>alpha</span></span>',
|
||||
"</span>",
|
||||
"</span>",
|
||||
" after</p>",
|
||||
'<span role="math" aria-label="x^2" data-display="block" data-math-source="$$\nx^2\n$$">block fallback</span>',
|
||||
"<p>next</p>",
|
||||
].join(""),
|
||||
);
|
||||
|
||||
expect(findRenderedMatches(row, "alpha")).toEqual([]);
|
||||
expect(findRenderedMatches(row, "Before").map((range) => range.toString())).toEqual(["Before"]);
|
||||
expect(findRenderedMatches(row, "after").map((range) => range.toString())).toEqual(["after"]);
|
||||
expect(findRenderedMatches(row, "fallbacknext")).toEqual([]);
|
||||
expect(findRenderedMatches(row, "after fallbacknext")).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
const BLOCKS = ["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"]
|
||||
.flatMap((tag) => [tag, `[data-paseo-markdown-tag="${tag}"]`])
|
||||
.join(",");
|
||||
const BLOCKS = [
|
||||
...["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"].flatMap((tag) => [
|
||||
tag,
|
||||
`[data-paseo-markdown-tag="${tag}"]`,
|
||||
]),
|
||||
'[role="math"][data-display="block"]',
|
||||
].join(",");
|
||||
const IGNORED =
|
||||
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], button, [role="button"], svg, script, style';
|
||||
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], .katex-mathml, annotation, annotation-xml, button, [role="button"], svg, script, style';
|
||||
|
||||
/** Rendered rows carrying a source message identity, in reading order. */
|
||||
export function findMessageRows(root: HTMLElement | null, messageId: string): HTMLElement[] {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { applyRootUiFont } from "./apply-root-font.web";
|
||||
|
||||
describe("applyRootUiFont", () => {
|
||||
afterEach(() => {
|
||||
document.getElementById("paseo-ui-font")?.remove();
|
||||
document.documentElement.style.removeProperty("--paseo-ui-font");
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it("applies the UI font to prose while excluding monospace, role=math, and KaTeX subtrees", () => {
|
||||
applyRootUiFont("'Custom UI Font', sans-serif");
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.id = "root";
|
||||
root.innerHTML = `
|
||||
<p id="prose">Prose</p>
|
||||
<code data-pmono="true" style="font-family: monospace"><span id="mono">code</span></code>
|
||||
<span id="math-host" role="math" style="font-family: KaTeX_Main"><span id="katex-root" class="katex"><span id="katex-glyph">x</span></span></span>
|
||||
`;
|
||||
document.body.append(root);
|
||||
|
||||
expect(getComputedStyle(document.getElementById("prose")!).fontFamily).toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("mono")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("math-host")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("katex-root")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("katex-glyph")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,9 +7,10 @@
|
||||
// beats both RN-web's base font and Unistyles' generated classes (0,1,0) — no reliance
|
||||
// on stylesheet order. Code/diff/terminal surfaces carry `data-pmono` (and have their
|
||||
// subtree excluded via `:not([data-pmono] *)`) so they keep their monospace font.
|
||||
// KaTeX math containers carry `role="math"` and `.katex` and keep KaTeX font faces.
|
||||
const STYLE_ID = "paseo-ui-font";
|
||||
const RULE =
|
||||
":is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *){font-family:var(--paseo-ui-font);}";
|
||||
':is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *):not([role="math"]):not([role="math"] *):not(.katex):not(.katex *){font-family:var(--paseo-ui-font);}';
|
||||
|
||||
export function applyRootUiFont(uiFontStack: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
|
||||
@@ -997,7 +997,11 @@ describe("quote copy", () => {
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
async function renderMarkdown(
|
||||
markdown: string,
|
||||
lastText: string,
|
||||
latexMath = false,
|
||||
): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
@@ -1017,7 +1021,7 @@ describe("quote copy", () => {
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
md4cFlags: { latexMath, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
@@ -1135,4 +1139,102 @@ describe("quote copy", () => {
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
|
||||
it("copies rendered inline and display math inside a quote as LaTeX", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Inline $E = mc^2$ and:\n>\n> $$\nx^2\n$$",
|
||||
"Inline",
|
||||
true,
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(rendered.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(2),
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Inline $E = mc^2$ and:\n\n$$\nx^2\n$$");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math selection copy", () => {
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement | undefined;
|
||||
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
afterEach(() => {
|
||||
const mounted = root;
|
||||
if (mounted) flushSync(() => mounted.unmount());
|
||||
root = undefined;
|
||||
host?.remove();
|
||||
host = undefined;
|
||||
});
|
||||
|
||||
async function renderMathMarkdown(markdown: string): Promise<HTMLElement> {
|
||||
host = document.createElement("div");
|
||||
host.setAttribute("data-testid", "assistant-message");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
flushSync(() =>
|
||||
root!.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: true, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.querySelector(".katex")).not.toBeNull());
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies inline math as $tex$ and display math as $$\\ntex\\n$$ without leaking MathML", async () => {
|
||||
const rendered = await renderMathMarkdown(
|
||||
"Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.",
|
||||
);
|
||||
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(rendered));
|
||||
expect(content?.plainText).toBe("Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
expect(content?.html).toContain("$a_i < b_j$");
|
||||
});
|
||||
|
||||
it("copies a standalone selected math formula as its LaTeX source", async () => {
|
||||
const rendered = await renderMathMarkdown("Equation $E = mc^2$ here.");
|
||||
const mathEl = fixtureElement(rendered, '[role="math"]');
|
||||
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(mathEl));
|
||||
expect(content?.plainText).toBe("$E = mc^2$");
|
||||
});
|
||||
|
||||
it("strips .katex-mathml, annotation, and annotation-xml on partial math selection", async () => {
|
||||
const rendered = await renderMathMarkdown("Formula $a + b + c$ end.");
|
||||
const mathmlAnnotation = fixtureElement(rendered, ".katex-mathml annotation");
|
||||
const katexHtml = fixtureElement(rendered, ".katex-html");
|
||||
const firstLeaf = tokenText(katexHtml, "a");
|
||||
const secondLeaf = tokenText(katexHtml, "b");
|
||||
|
||||
// Partial selection inside .katex-html
|
||||
const partial = copyBetween([firstLeaf, 0], [secondLeaf, 1]);
|
||||
expect(partial?.plainText).toBe("a+b");
|
||||
expect(partial?.plainText).not.toContain("a + b + c");
|
||||
|
||||
// Selection starting inside .katex-mathml annotation and ending inside .katex-html
|
||||
const crossing = copyBetween([textNode(mathmlAnnotation), 0], [secondLeaf, 1]);
|
||||
expect(crossing?.plainText).toBe("a+b");
|
||||
expect(crossing?.plainText).not.toContain("a + b + c");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
KATEX_MATHML_SELECTOR,
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
@@ -20,6 +21,8 @@ import {
|
||||
MARKDOWN_COPY_TAG_ATTRIBUTE,
|
||||
MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE,
|
||||
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
|
||||
MARKDOWN_MATH_DISPLAY_ATTRIBUTE,
|
||||
MARKDOWN_MATH_SOURCE_ATTRIBUTE,
|
||||
TRAILING_CODE_LINE_BREAKS,
|
||||
} from "./markup";
|
||||
|
||||
@@ -106,6 +109,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
// Rendered math copies back as `$tex$` (inline) or `$$\ntex\n$$` (block).
|
||||
turndown.addRule("mathSource", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE),
|
||||
replacement: (_content, node) => {
|
||||
const element = node as Element;
|
||||
const source = element.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE) ?? "";
|
||||
const isBlock = element.getAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE) === "block";
|
||||
const formatted = flavor === "markdown" ? turndown.escape(source) : source;
|
||||
return isBlock ? `\n\n${formatted}\n\n` : formatted;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -411,12 +425,19 @@ function nodeAtPath(root: Node, path: number[]): Node {
|
||||
}
|
||||
|
||||
function removeUnselectedSemantics(range: Range, source: Element, clone: Element): void {
|
||||
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
|
||||
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], [${MARKDOWN_MATH_SOURCE_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
|
||||
const originals = Array.from(source.querySelectorAll(selector));
|
||||
const copies = Array.from(clone.querySelectorAll(selector));
|
||||
|
||||
originals.forEach((original, index) => {
|
||||
const copy = copies[index];
|
||||
if (original.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
|
||||
if (copy && (!range.intersectsNode(original) || !hasSelectedAllContents(range, original))) {
|
||||
copy.removeAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
|
||||
copy.removeAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (copy) copySemanticAttributes(original, copy);
|
||||
if (!copy || shouldPreserveSemanticElement(range, original)) {
|
||||
if (copy) {
|
||||
@@ -440,6 +461,9 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean
|
||||
if (!range.intersectsNode(element)) {
|
||||
return false;
|
||||
}
|
||||
if (element.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
|
||||
return hasSelectedAllContents(range, element);
|
||||
}
|
||||
const tag = semanticTag(element);
|
||||
// An image has no part to select, so touching it selects all of it.
|
||||
if (tag === "p" || tag === "img" || isTableStructure(tag)) {
|
||||
@@ -590,7 +614,9 @@ function selectsNothingOutside(range: Range, element: Element): boolean {
|
||||
|
||||
function hasMarkdownContent(fragment: DocumentFragment, includeIgnored: boolean): boolean {
|
||||
if (!includeIgnored) {
|
||||
for (const ignored of fragment.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
|
||||
for (const ignored of fragment.querySelectorAll(
|
||||
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
|
||||
)) {
|
||||
ignored.remove();
|
||||
}
|
||||
}
|
||||
@@ -681,8 +707,19 @@ function selectedMessageParts(range: Range): SelectedMessagePart[] | null {
|
||||
});
|
||||
}
|
||||
|
||||
function restoreMathSources(container: HTMLElement): void {
|
||||
for (const math of container.querySelectorAll(`[${MARKDOWN_MATH_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = math.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
|
||||
if (source !== null) {
|
||||
math.textContent = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function restoreMarkdownElements(container: HTMLElement): void {
|
||||
for (const ignored of container.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
|
||||
for (const ignored of container.querySelectorAll(
|
||||
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
|
||||
)) {
|
||||
ignored.remove();
|
||||
}
|
||||
|
||||
@@ -732,7 +769,11 @@ function restoreMarkdownElements(container: HTMLElement): void {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
|
||||
const presentational = Array.from(container.querySelectorAll("div, span"));
|
||||
restoreMathSources(container);
|
||||
|
||||
const presentational = Array.from(
|
||||
container.querySelectorAll(`div, span:not([${MARKDOWN_MATH_SOURCE_ATTRIBUTE}])`),
|
||||
);
|
||||
for (const element of presentational.toReversed()) {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
|
||||
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
|
||||
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
|
||||
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
|
||||
/** Set by the Markdown library's web KaTeX renderer on rendered math elements. */
|
||||
export const MARKDOWN_MATH_SOURCE_ATTRIBUTE = "data-math-source";
|
||||
export const MARKDOWN_MATH_DISPLAY_ATTRIBUTE = "data-display";
|
||||
export const KATEX_MATHML_SELECTOR = ".katex-mathml, annotation, annotation-xml";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
export interface LineEnd {
|
||||
contentEnd: number;
|
||||
nextLineStart: number;
|
||||
}
|
||||
|
||||
export interface BlockquoteStrip {
|
||||
quoteDepth: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface IndentMeasure {
|
||||
spaces: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface ListMarkerMatch {
|
||||
markerEnd: number;
|
||||
contentIndent: number;
|
||||
markerChar: string;
|
||||
}
|
||||
|
||||
export interface FenceOpenerMatch {
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
fenceOffset: number;
|
||||
indent: number;
|
||||
info: string;
|
||||
}
|
||||
|
||||
export interface BlockScanState {
|
||||
listIndents: number[];
|
||||
listQuoteDepth: number;
|
||||
inParagraph: boolean;
|
||||
prevQuoteDepth: number;
|
||||
inIndentedCode: boolean;
|
||||
indentedCodeQuoteDepth: number;
|
||||
indentedCodeMinIndent: number;
|
||||
}
|
||||
|
||||
export type BlockLine =
|
||||
| { kind: "blank"; quoteDepth: number; afterQuotes: number }
|
||||
| { kind: "indented-code"; quoteDepth: number; afterQuotes: number }
|
||||
| {
|
||||
kind: "fence";
|
||||
quoteDepth: number;
|
||||
afterQuotes: number;
|
||||
fenceOffset: number;
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
info: string;
|
||||
maxCloseIndent: number;
|
||||
contentStripIndent: number;
|
||||
inList: boolean;
|
||||
listMinIndent: number;
|
||||
firstLinePrefix: string;
|
||||
continuationPrefix: string;
|
||||
}
|
||||
| { kind: "text"; quoteDepth: number; afterQuotes: number; containerIndent: number };
|
||||
|
||||
export function isWhitespaceChar(ch: string | undefined): boolean {
|
||||
return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
|
||||
}
|
||||
|
||||
export function isAsciiPunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (
|
||||
(code >= 0x21 && code <= 0x2f) ||
|
||||
(code >= 0x3a && code <= 0x40) ||
|
||||
(code >= 0x5b && code <= 0x60) ||
|
||||
(code >= 0x7b && code <= 0x7e)
|
||||
);
|
||||
}
|
||||
|
||||
export function isAsciiAlnum(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
}
|
||||
|
||||
export function findLineEnd(source: string, from: number): LineEnd {
|
||||
let i = from;
|
||||
while (i < source.length) {
|
||||
const code = source.charCodeAt(i);
|
||||
if (code === 10) return { contentEnd: i, nextLineStart: i + 1 };
|
||||
if (code === 13) {
|
||||
const next = i + 1 < source.length && source.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
|
||||
return { contentEnd: i, nextLineStart: next };
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return { contentEnd: source.length, nextLineStart: source.length };
|
||||
}
|
||||
|
||||
export function stripBlockquotesAt(source: string, from: number, limit: number): BlockquoteStrip {
|
||||
let offset = from;
|
||||
let quoteDepth = 0;
|
||||
while (offset < limit) {
|
||||
let spaces = 0;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === " " && spaces < 3) {
|
||||
cursor++;
|
||||
spaces++;
|
||||
}
|
||||
if (cursor >= limit || source[cursor] !== ">") break;
|
||||
quoteDepth++;
|
||||
cursor++;
|
||||
if (cursor < limit && (source[cursor] === " " || source[cursor] === "\t")) cursor++;
|
||||
offset = cursor;
|
||||
}
|
||||
return { quoteDepth, offset };
|
||||
}
|
||||
|
||||
export function measureIndentAt(source: string, from: number, limit: number): IndentMeasure {
|
||||
let spaces = 0;
|
||||
let offset = from;
|
||||
while (offset < limit) {
|
||||
const ch = source[offset];
|
||||
if (ch === " ") {
|
||||
spaces++;
|
||||
offset++;
|
||||
} else if (ch === "\t") {
|
||||
spaces += 4 - (spaces % 4);
|
||||
offset++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { spaces, offset };
|
||||
}
|
||||
|
||||
export function isBlankRange(source: string, from: number, limit: number): boolean {
|
||||
for (let i = from; i < limit; i++) {
|
||||
if (source[i] !== " " && source[i] !== "\t") return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isThematicBreakText(trimmed: string): boolean {
|
||||
return /^(?:([-*_])(?:[ \t]*\1){2,})[ \t]*$/.test(trimmed);
|
||||
}
|
||||
|
||||
function parseListMarkerPrefix(
|
||||
source: string,
|
||||
offset: number,
|
||||
limit: number,
|
||||
disallowOrderedNonOne: boolean,
|
||||
): { markerChars: number; after: number; markerChar: string } | null {
|
||||
const ch = source[offset];
|
||||
if (ch === "-" || ch === "*" || ch === "+") {
|
||||
if ((ch === "-" || ch === "*") && isThematicBreakText(source.slice(offset, limit))) {
|
||||
return null;
|
||||
}
|
||||
return { markerChars: 1, after: offset + 1, markerChar: ch };
|
||||
}
|
||||
if (ch < "0" || ch > "9") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] >= "0" && source[cursor] <= "9" && cursor - offset < 9) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor >= limit || (source[cursor] !== "." && source[cursor] !== ")")) return null;
|
||||
if (disallowOrderedNonOne && Number(source.slice(offset, cursor)) !== 1) return null;
|
||||
return { markerChars: cursor + 1 - offset, after: cursor + 1, markerChar: ch };
|
||||
}
|
||||
|
||||
function measureMarkerSeparator(
|
||||
source: string,
|
||||
after: number,
|
||||
limit: number,
|
||||
startColumn: number,
|
||||
): { extraSpaces: number; endPos: number } {
|
||||
let col = startColumn;
|
||||
let extraSpaces = 0;
|
||||
let pos = after;
|
||||
while (pos < limit) {
|
||||
const ws = source[pos];
|
||||
if (ws === " ") {
|
||||
extraSpaces += 1;
|
||||
col += 1;
|
||||
pos++;
|
||||
} else if (ws === "\t") {
|
||||
const tabWidth = 4 - (col % 4);
|
||||
extraSpaces += tabWidth;
|
||||
col += tabWidth;
|
||||
pos++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { extraSpaces, endPos: pos };
|
||||
}
|
||||
|
||||
export function matchListMarkerAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent = 3,
|
||||
options?: { allowEmpty?: boolean; disallowOrderedNonOne?: boolean },
|
||||
): ListMarkerMatch | null {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit) return null;
|
||||
|
||||
const prefix = parseListMarkerPrefix(
|
||||
source,
|
||||
offset,
|
||||
limit,
|
||||
options?.disallowOrderedNonOne ?? false,
|
||||
);
|
||||
if (!prefix) return null;
|
||||
|
||||
const { extraSpaces, endPos } = measureMarkerSeparator(
|
||||
source,
|
||||
prefix.after,
|
||||
limit,
|
||||
spaces + prefix.markerChars,
|
||||
);
|
||||
|
||||
if (extraSpaces === 0) {
|
||||
if (endPos === limit && options?.allowEmpty) {
|
||||
return {
|
||||
markerEnd: endPos,
|
||||
contentIndent: spaces + prefix.markerChars + 1,
|
||||
markerChar: prefix.markerChar,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// CommonMark §5.2: >=5 spaces after a marker keeps 4+ spaces as an indented code block.
|
||||
const consumed = extraSpaces >= 5 ? 1 : extraSpaces;
|
||||
const markerEnd = extraSpaces >= 5 ? prefix.after + 1 : endPos;
|
||||
return {
|
||||
markerEnd,
|
||||
contentIndent: spaces + prefix.markerChars + consumed,
|
||||
markerChar: prefix.markerChar,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseFenceOpenerAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent: number,
|
||||
): FenceOpenerMatch | null {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit) return null;
|
||||
const ch = source[offset];
|
||||
if (ch !== "`" && ch !== "~") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === ch) cursor++;
|
||||
const length = cursor - offset;
|
||||
if (length < 3) return null;
|
||||
const info = source.slice(cursor, limit);
|
||||
if (ch === "`" && info.includes("`")) return null;
|
||||
return { char: ch, length, fenceOffset: offset, indent: spaces, info };
|
||||
}
|
||||
|
||||
export function isClosingFenceAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent: number,
|
||||
char: "`" | "~",
|
||||
minLength: number,
|
||||
): boolean {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit || source[offset] !== char) return false;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === char) cursor++;
|
||||
if (cursor - offset < minLength) return false;
|
||||
while (cursor < limit) {
|
||||
if (source[cursor] !== " " && source[cursor] !== "\t") return false;
|
||||
cursor++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function checkFenceContainerExit(
|
||||
source: string,
|
||||
lineStart: number,
|
||||
contentEnd: number,
|
||||
openQuoteDepth: number,
|
||||
listMinIndent: number,
|
||||
): { exited: boolean; quoteDepth: number; afterQuotes: number } {
|
||||
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
|
||||
if (quoteDepth < openQuoteDepth) {
|
||||
return { exited: true, quoteDepth, afterQuotes };
|
||||
}
|
||||
if (
|
||||
listMinIndent > 0 &&
|
||||
quoteDepth === openQuoteDepth &&
|
||||
!isBlankRange(source, afterQuotes, contentEnd) &&
|
||||
measureIndentAt(source, afterQuotes, contentEnd).spaces < listMinIndent
|
||||
) {
|
||||
return { exited: true, quoteDepth, afterQuotes };
|
||||
}
|
||||
return { exited: false, quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
export function createBlockScanState(): BlockScanState {
|
||||
return {
|
||||
listIndents: [],
|
||||
listQuoteDepth: 0,
|
||||
inParagraph: false,
|
||||
prevQuoteDepth: 0,
|
||||
inIndentedCode: false,
|
||||
indentedCodeQuoteDepth: 0,
|
||||
indentedCodeMinIndent: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function syncListContainer(state: BlockScanState, quoteDepth: number, spaces: number): number {
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listIndents.length = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (quoteDepth !== state.listQuoteDepth) return 0;
|
||||
while (state.listIndents.length > 0 && spaces < state.listIndents[state.listIndents.length - 1]) {
|
||||
state.listIndents.pop();
|
||||
}
|
||||
return state.listIndents.length > 0 ? state.listIndents[state.listIndents.length - 1] : 0;
|
||||
}
|
||||
|
||||
function peelLineListMarkers(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
afterQuotes: number,
|
||||
contentEnd: number,
|
||||
quoteDepth: number,
|
||||
initialIndent: number,
|
||||
): { cursor: number; containerIndent: number; peeledList: boolean } {
|
||||
let cursor = afterQuotes;
|
||||
let containerIndent = initialIndent;
|
||||
let peeledList = false;
|
||||
let marker = matchListMarkerAt(source, cursor, contentEnd, containerIndent + 3, {
|
||||
allowEmpty: !state.inParagraph,
|
||||
disallowOrderedNonOne: state.inParagraph,
|
||||
});
|
||||
while (marker) {
|
||||
const markerBase = cursor === afterQuotes ? 0 : containerIndent;
|
||||
const totalIndent = markerBase + marker.contentIndent;
|
||||
state.listIndents.push(totalIndent);
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
containerIndent = totalIndent;
|
||||
cursor = marker.markerEnd;
|
||||
peeledList = true;
|
||||
marker = matchListMarkerAt(source, cursor, contentEnd, 3, { allowEmpty: true });
|
||||
}
|
||||
return { cursor, containerIndent, peeledList };
|
||||
}
|
||||
|
||||
function startIndentedCode(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
containerIndent: number,
|
||||
): BlockLine {
|
||||
state.inIndentedCode = true;
|
||||
state.indentedCodeQuoteDepth = quoteDepth;
|
||||
state.indentedCodeMinIndent = containerIndent + 4;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "indented-code", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
function isContinuationIndentedCode(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
spaces: number,
|
||||
): boolean {
|
||||
if (!state.inIndentedCode) return false;
|
||||
if (quoteDepth === state.indentedCodeQuoteDepth && spaces >= state.indentedCodeMinIndent) {
|
||||
return true;
|
||||
}
|
||||
state.inIndentedCode = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
function classifyBlankBlockLine(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
): BlockLine {
|
||||
state.inParagraph = false;
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listIndents.length = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (state.inIndentedCode && quoteDepth < state.indentedCodeQuoteDepth) {
|
||||
state.inIndentedCode = false;
|
||||
}
|
||||
return { kind: "blank", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
function classifyTextBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
cursor: number,
|
||||
contentEnd: number,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
containerIndent: number,
|
||||
peeledList: boolean,
|
||||
): BlockLine {
|
||||
const { spaces: trimmedSpaces, offset: trimmedOffset } = measureIndentAt(
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
);
|
||||
const relSpaces = peeledList ? trimmedSpaces : trimmedSpaces - containerIndent;
|
||||
const trimmed = source.slice(trimmedOffset, contentEnd);
|
||||
const endsParagraph =
|
||||
relSpaces <= 3 &&
|
||||
(/^#{1,6}(?:[ \t]|$)/.test(trimmed) ||
|
||||
isThematicBreakText(trimmed) ||
|
||||
(state.inParagraph && !peeledList && /^(?:-+|=+)[ \t]*$/.test(trimmed)));
|
||||
state.inParagraph = !endsParagraph;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "text", quoteDepth, afterQuotes, containerIndent };
|
||||
}
|
||||
|
||||
function buildFenceBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
lineStart: number,
|
||||
afterQuotes: number,
|
||||
quoteDepth: number,
|
||||
containerIndent: number,
|
||||
peeledList: boolean,
|
||||
opener: FenceOpenerMatch,
|
||||
): BlockLine {
|
||||
state.inParagraph = false;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
const quotePrefix = source.slice(lineStart, afterQuotes);
|
||||
const contentStripIndent = peeledList ? containerIndent + opener.indent : opener.indent;
|
||||
const inList = quoteDepth === state.listQuoteDepth && state.listIndents.length > 0;
|
||||
return {
|
||||
kind: "fence",
|
||||
quoteDepth,
|
||||
afterQuotes,
|
||||
fenceOffset: opener.fenceOffset,
|
||||
char: opener.char,
|
||||
length: opener.length,
|
||||
info: opener.info,
|
||||
maxCloseIndent: containerIndent + 3,
|
||||
contentStripIndent,
|
||||
inList,
|
||||
listMinIndent: inList ? containerIndent : 0,
|
||||
firstLinePrefix: source.slice(lineStart, opener.fenceOffset),
|
||||
continuationPrefix: `${quotePrefix}${" ".repeat(contentStripIndent)}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify one line in CommonMark block order (quotes -> blank -> indented code ->
|
||||
* list markers -> fenced code -> ATX/Setext/thematic-break -> paragraph text) so math
|
||||
* scanners skip nested-list code fences and indented code blocks identically to md4c.
|
||||
*/
|
||||
export function classifyBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
lineStart: number,
|
||||
contentEnd: number,
|
||||
): BlockLine {
|
||||
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
|
||||
|
||||
if (isBlankRange(source, afterQuotes, contentEnd)) {
|
||||
return classifyBlankBlockLine(state, quoteDepth, afterQuotes);
|
||||
}
|
||||
|
||||
if (quoteDepth > state.prevQuoteDepth) {
|
||||
state.inParagraph = false;
|
||||
state.inIndentedCode = false;
|
||||
}
|
||||
|
||||
const { spaces } = measureIndentAt(source, afterQuotes, contentEnd);
|
||||
if (isContinuationIndentedCode(state, quoteDepth, spaces)) {
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "indented-code", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
const baseIndent = syncListContainer(state, quoteDepth, spaces);
|
||||
if (!state.inParagraph && spaces >= baseIndent + 4) {
|
||||
return startIndentedCode(state, quoteDepth, afterQuotes, baseIndent);
|
||||
}
|
||||
|
||||
const { cursor, containerIndent, peeledList } = peelLineListMarkers(
|
||||
state,
|
||||
source,
|
||||
afterQuotes,
|
||||
contentEnd,
|
||||
quoteDepth,
|
||||
baseIndent,
|
||||
);
|
||||
if (peeledList) {
|
||||
state.inParagraph = false;
|
||||
const afterMarker = measureIndentAt(source, cursor, contentEnd);
|
||||
if (afterMarker.offset < contentEnd && afterMarker.spaces >= 4) {
|
||||
return startIndentedCode(state, quoteDepth, afterQuotes, containerIndent);
|
||||
}
|
||||
if (isBlankRange(source, cursor, contentEnd)) {
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "text", quoteDepth, afterQuotes: cursor, containerIndent };
|
||||
}
|
||||
}
|
||||
|
||||
const opener = parseFenceOpenerAt(
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
peeledList ? 3 : containerIndent + 3,
|
||||
);
|
||||
if (opener) {
|
||||
return buildFenceBlockLine(
|
||||
state,
|
||||
source,
|
||||
lineStart,
|
||||
afterQuotes,
|
||||
quoteDepth,
|
||||
containerIndent,
|
||||
peeledList,
|
||||
opener,
|
||||
);
|
||||
}
|
||||
|
||||
return classifyTextBlockLine(
|
||||
state,
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
quoteDepth,
|
||||
afterQuotes,
|
||||
containerIndent,
|
||||
peeledList,
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
import { isOffsetInRanges, scanMarkdownMath, type MathRange } from "./math";
|
||||
|
||||
const ATTRIBUTE = String.raw`\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\x60]+|'[^']*'|"[^"]*"))?`;
|
||||
const TAG = String.raw`<(?:[A-Za-z][A-Za-z0-9-]*(?:${ATTRIBUTE})*\s*\/?|\/[A-Za-z][A-Za-z0-9-]*\s*)>`;
|
||||
@@ -55,12 +56,14 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
const mathRanges = scanMarkdownMath(source);
|
||||
const protectedRanges = mergeRanges(codeRanges, mathRanges);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, protectedRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
if (codeRanges.some(({ start, end }) => offset >= start && offset < end)) return raw;
|
||||
if (isOffsetInRanges(offset, protectedRanges)) return raw;
|
||||
if (raw.startsWith("<!--")) return "";
|
||||
const summary = /^<summary\b[^>]*>([\s\S]*?)<\/summary\s*>$/i.exec(raw);
|
||||
if (summary) {
|
||||
@@ -261,3 +264,19 @@ function collectTableRanges(
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
function mergeRanges(a: readonly MathRange[], b: readonly MathRange[]): MathRange[] {
|
||||
if (a.length === 0 && b.length === 0) return [];
|
||||
const sorted = [...a, ...b].sort((left, right) => left.start - right.start);
|
||||
const merged: MathRange[] = [{ ...sorted[0] }];
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
const current = sorted[i];
|
||||
const last = merged[merged.length - 1];
|
||||
if (current.start <= last.end) {
|
||||
if (current.end > last.end) last.end = current.end;
|
||||
} else {
|
||||
merged.push({ ...current });
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,277 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import {
|
||||
EnrichedMarkdownText,
|
||||
getLoadedKaTeX,
|
||||
preloadMarkdownParser,
|
||||
registerKaTeXStyleLoader,
|
||||
} from "react-native-enriched-markdown";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { applyRootUiFont } from "@/appearance/apply-root-font.web";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { darkTheme, lightTheme } from "@/styles/theme";
|
||||
import { ensureKaTeXStyles } from "./katex-styles.web";
|
||||
import { MarkdownRenderer } from "./renderer";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { WEB_RENDERERS } from "./renderers.web";
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
const toast = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
const MATH_FLAGS = { latexMath: true, admonitions: true };
|
||||
|
||||
function wrapProviders(node: React.ReactNode) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>{node}</ToastApiProvider>
|
||||
</I18nextProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
await preloadMarkdownParser();
|
||||
container = document.createElement("div");
|
||||
container.id = "root";
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
document.getElementById("paseo-ui-font")?.remove();
|
||||
document.documentElement.style.removeProperty("--paseo-ui-font");
|
||||
});
|
||||
|
||||
describe("web KaTeX math rendering", () => {
|
||||
it("does not load KaTeX when rendering prose without math", async () => {
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<MarkdownRenderer text="Costs $5 and $10, or $100/mo, with $PATH and \[1, 2\]." />,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
expect(container.querySelector('[role="math"]')).toBeNull();
|
||||
expect(container.textContent).toContain("Costs $5 and $10, or $100/mo");
|
||||
expect(container.textContent).toContain("$PATH");
|
||||
});
|
||||
|
||||
it("falls back to raw LaTeX when stylesheet loading fails and recovers on retry", async () => {
|
||||
let shouldFail = true;
|
||||
registerKaTeXStyleLoader(async () => {
|
||||
if (shouldFail) throw new Error("Simulated KaTeX CSS chunk failure");
|
||||
ensureKaTeXStyles();
|
||||
});
|
||||
|
||||
try {
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text="Inline $x^2 + 1$ and $$y^2$$" />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const mathNodes = container.querySelectorAll('[role="math"]');
|
||||
expect(mathNodes.length).toBe(2);
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
expect(container.querySelector('[role="math"] .katex')).toBeNull();
|
||||
expect(container.textContent).toContain("$x^2 + 1$");
|
||||
expect(container.textContent).toContain("$$y^2$$");
|
||||
|
||||
shouldFail = false;
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text="Recovered $x^2 + 1$ and $$y^2$$" />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(2);
|
||||
});
|
||||
expect(getLoadedKaTeX()).not.toBeNull();
|
||||
expect(document.getElementById("paseo-katex-css")).not.toBeNull();
|
||||
} finally {
|
||||
registerKaTeXStyleLoader(() => {
|
||||
ensureKaTeXStyles();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("lazily loads KaTeX and .woff2-only CSS for math, renders all 5 syntaxes, and renders synchronously on second mount", async () => {
|
||||
applyRootUiFont("'Custom UI Font', sans-serif");
|
||||
|
||||
const markdown = [
|
||||
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\).",
|
||||
"",
|
||||
"$$x^2 + y^2 = z^2$$",
|
||||
"",
|
||||
"\\[\\int_0^1 x^2\\,dx\\]",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{i=1}^n i",
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text={markdown} />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(5);
|
||||
});
|
||||
|
||||
expect(getLoadedKaTeX()).not.toBeNull();
|
||||
|
||||
const styleEl = document.getElementById("paseo-katex-css");
|
||||
expect(styleEl).not.toBeNull();
|
||||
const css = styleEl?.textContent ?? "";
|
||||
expect(css).toContain(".woff2");
|
||||
expect(css).not.toContain('.woff")');
|
||||
expect(css).not.toContain('.ttf")');
|
||||
|
||||
const mathNodes = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(mathNodes.map((el) => el.dataset.display)).toEqual([
|
||||
"inline",
|
||||
"inline",
|
||||
"block",
|
||||
"block",
|
||||
"block",
|
||||
]);
|
||||
expect(mathNodes[0]?.dataset.mathSource).toBe("$E = mc^2$");
|
||||
expect(mathNodes[2]?.dataset.mathSource).toBe("$$\nx^2 + y^2 = z^2\n$$");
|
||||
expect(mathNodes[0]?.querySelector(".katex-mathml")).not.toBeNull();
|
||||
expect(mathNodes[0]?.querySelector(".katex-html")).not.toBeNull();
|
||||
|
||||
// KaTeX font is preserved even when applyRootUiFont is active on #root.
|
||||
const mathInner = mathNodes[0]!.querySelector<HTMLElement>(".katex")!;
|
||||
expect(getComputedStyle(mathInner).fontFamily).toContain("KaTeX_Main");
|
||||
|
||||
// Second mount renders synchronously from module cache without raw-TeX flash.
|
||||
const secondHost = document.createElement("div");
|
||||
document.body.append(secondHost);
|
||||
const secondRoot = createRoot(secondHost);
|
||||
try {
|
||||
flushSync(() => {
|
||||
secondRoot.render(
|
||||
wrapProviders(
|
||||
<EnrichedMarkdownText
|
||||
markdown="Instant $x + 1$"
|
||||
flavor="github"
|
||||
md4cFlags={MATH_FLAGS}
|
||||
renderers={WEB_RENDERERS}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
});
|
||||
// Immediately available after synchronous flushSync without waiting for timers.
|
||||
expect(secondHost.querySelector('[role="math"] .katex')).not.toBeNull();
|
||||
} finally {
|
||||
flushSync(() => secondRoot.unmount());
|
||||
secondHost.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["light", lightTheme],
|
||||
["dark", darkTheme],
|
||||
] as const)(
|
||||
"renders display and inline math cleanly in %s theme with horizontal scroll",
|
||||
async (_name, theme) => {
|
||||
const { markdownStyle } = createMarkdownStyles(theme, { blockGap: 16 });
|
||||
const wideEquation = `$$${Array.from({ length: 12 }, (_, i) => `x_{${i}}`).join(" + ")}$$`;
|
||||
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<EnrichedMarkdownText
|
||||
markdown={`Inline $x$ and:\n\n${wideEquation}`}
|
||||
markdownStyle={markdownStyle}
|
||||
flavor="github"
|
||||
md4cFlags={MATH_FLAGS}
|
||||
renderers={WEB_RENDERERS}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(2);
|
||||
});
|
||||
|
||||
const blockMath = container.querySelector<HTMLElement>(
|
||||
'[role="math"][data-display="block"]',
|
||||
)!;
|
||||
expect(blockMath.style.backgroundColor).toBe("transparent");
|
||||
expect(blockMath.style.overflowX).toBe("auto");
|
||||
expect(blockMath.style.textAlign).toBe("center");
|
||||
},
|
||||
);
|
||||
|
||||
it("renders accurate formula output across inline/display mode and repeated renders past cache turnover", async () => {
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<MarkdownRenderer text={"Inline $x_0$ vs display:\n\n$$x_0$$\n\nRepeated $x_0$."} />,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(3);
|
||||
});
|
||||
|
||||
const htmlText = (el: HTMLElement | undefined) =>
|
||||
el?.querySelector(".katex-html")?.textContent?.replace(/\u200B/g, "");
|
||||
const annotationText = (el: HTMLElement | undefined) =>
|
||||
el?.querySelector(".katex-mathml annotation")?.textContent;
|
||||
|
||||
const initialMath = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(initialMath.map((el) => el.dataset.display)).toEqual(["inline", "block", "inline"]);
|
||||
expect(initialMath[0]?.querySelector(".katex-display")).toBeNull();
|
||||
expect(initialMath[1]?.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(htmlText(initialMath[0])).toBe("x0");
|
||||
expect(htmlText(initialMath[1])).toBe("x0");
|
||||
expect(htmlText(initialMath[2])).toBe("x0");
|
||||
expect(annotationText(initialMath[0])).toBe("x_0");
|
||||
expect(annotationText(initialMath[1])).toBe("x_0");
|
||||
|
||||
// Exceed the 256-entry render cache and re-render earlier formulas to verify evicted entries stay accurate.
|
||||
const manyFormulas = Array.from({ length: 265 }, (_, i) => `$a_{${i}}$`).join(" ");
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(<MarkdownRenderer text={`${manyFormulas} $x_0$ $$x_0$$ $a_{0}$`} />),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(268);
|
||||
});
|
||||
|
||||
const rendered = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(htmlText(rendered[0])).toBe("a0");
|
||||
expect(annotationText(rendered[0])).toBe("a_{0}");
|
||||
expect(htmlText(rendered[264])).toBe("a264");
|
||||
expect(annotationText(rendered[264])).toBe("a_{264}");
|
||||
expect(rendered[265]?.dataset.display).toBe("inline");
|
||||
expect(htmlText(rendered[265])).toBe("x0");
|
||||
expect(rendered[266]?.dataset.display).toBe("block");
|
||||
expect(htmlText(rendered[266])).toBe("x0");
|
||||
expect(rendered[267]?.dataset.mathSource).toBe("$a_{0}$");
|
||||
expect(htmlText(rendered[267])).toBe("a0");
|
||||
expect(annotationText(rendered[267])).toBe("a_{0}");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,437 @@
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
import { adaptMarkdownMath, findBlockMathSpans, scanMarkdownMath } from "./math";
|
||||
import { prepareMarkdownSource } from "./source";
|
||||
|
||||
const MATH_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
|
||||
const NO_MATH_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
|
||||
function collectNodes(node: ASTNode, result: ASTNode[] = []): ASTNode[] {
|
||||
result.push(node);
|
||||
node.children?.forEach((child) => collectNodes(child, result));
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectMathNodes(ast: ASTNode): { type: string; content: string }[] {
|
||||
return collectNodes(ast)
|
||||
.filter((node) => node.type === "LatexMathInline" || node.type === "LatexMathDisplay")
|
||||
.map((node) => ({
|
||||
type: node.type,
|
||||
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
|
||||
}));
|
||||
}
|
||||
|
||||
function collectText(node: ASTNode): string {
|
||||
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") return "";
|
||||
if (node.type === "Text") return node.content ?? "";
|
||||
return (node.children ?? []).map(collectText).join("");
|
||||
}
|
||||
|
||||
describe("math source adaptation — currency, shell, regex, and literal prose", () => {
|
||||
it.each([
|
||||
["Costs $5 and $10.", "Costs $5 and $10."],
|
||||
["Costs $5 and 10$", "Costs $5 and 10$"],
|
||||
["From $100/mo to $200/mo", "From $100/mo to $200/mo"],
|
||||
["Costs $100/mo (or 200$)", "Costs $100/mo (or 200$)"],
|
||||
["Total: $5 ($)", "Total: $5 ($)"],
|
||||
["Costs $5. Run $ ls", "Costs $5. Run $ ls"],
|
||||
["Pay $10 and get $ back", "Pay $10 and get $ back"],
|
||||
["I have $ 5 and $ 10", "I have $ 5 and $ 10"],
|
||||
["Price is US$5 or CA$10", "Price is US$5 or CA$10"],
|
||||
["Set $PATH and $HOME", "Set $PATH and $HOME"],
|
||||
["Use $PATH with /^foo$/", "Use $PATH with /^foo$/"],
|
||||
["Save $5 with sed s/foo$/bar/", "Save $5 with sed s/foo$/bar/"],
|
||||
["Check $HOME then foo$", "Check $HOME then foo$"],
|
||||
["$3$4", "$3$4"],
|
||||
["Costs $50k or $10M or $2B today", "Costs $50k or $10M or $2B today"],
|
||||
["Costs $5! Or $10)?", "Costs $5! Or $10)?"],
|
||||
["Escaped \\$x\\$", "Escaped $x$"],
|
||||
["See citation \\[1, 2\\]", "See citation [1, 2]"],
|
||||
])(
|
||||
"keeps %s literal when parsed with latexMath: true and latexMath: false",
|
||||
async (source, expectedText) => {
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
for (const flags of [MATH_FLAGS, NO_MATH_FLAGS]) {
|
||||
const ast = await parseMarkdown(rendered, flags);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
expect(collectText(ast)).toBe(expectedText);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves inline code and latex/tex code fences literal", async () => {
|
||||
const inlineCode = "Use `$x$` and ``$$y$$`` and `\\(z\\)`";
|
||||
const preparedInline = prepareMarkdownSource(inlineCode).render();
|
||||
expect(preparedInline).toBe(inlineCode);
|
||||
const inlineAst = await parseMarkdown(preparedInline, MATH_FLAGS);
|
||||
expect(collectMathNodes(inlineAst)).toEqual([]);
|
||||
|
||||
for (const lang of ["latex", "tex"]) {
|
||||
const fence = `\`\`\`${lang}\n\\documentclass{article}\n$x = 1$\n\`\`\``;
|
||||
const preparedFence = prepareMarkdownSource(fence).render();
|
||||
expect(preparedFence).toBe(fence);
|
||||
const fenceAst = await parseMarkdown(preparedFence, MATH_FLAGS);
|
||||
expect(collectMathNodes(fenceAst)).toEqual([]);
|
||||
expect(collectNodes(fenceAst).some((node) => node.type === "CodeBlock")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves list-nested fenced code blocks containing blank lines, $, \\(, and $$ verbatim", async () => {
|
||||
const nested = [
|
||||
"1. Install:",
|
||||
" - Run this:",
|
||||
"",
|
||||
" ```bash",
|
||||
' export PATH="$HOME/bin:$PATH"',
|
||||
"",
|
||||
" grep -E '\\(foo\\)' log.txt",
|
||||
" ```",
|
||||
].join("\n");
|
||||
const renderedNested = prepareMarkdownSource(nested).render();
|
||||
expect(renderedNested).toBe(nested);
|
||||
const nestedAst = await parseMarkdown(renderedNested, MATH_FLAGS);
|
||||
expect(collectMathNodes(nestedAst)).toEqual([]);
|
||||
const nestedCodeBlock = collectNodes(nestedAst).find((node) => node.type === "CodeBlock");
|
||||
expect(nestedCodeBlock).toBeDefined();
|
||||
expect(collectText(nestedCodeBlock!)).toBe(
|
||||
"export PATH=\"$HOME/bin:$PATH\"\n\ngrep -E '\\(foo\\)' log.txt\n",
|
||||
);
|
||||
|
||||
const deepNested = [
|
||||
"1. Outer:",
|
||||
" 1. Inner:",
|
||||
" - Leaf:",
|
||||
"",
|
||||
" ```sh",
|
||||
" echo $HOME",
|
||||
"",
|
||||
" printf '%s\\n' '\\(a+b\\)' '$$x^2$$'",
|
||||
" ```",
|
||||
].join("\n");
|
||||
const renderedDeep = prepareMarkdownSource(deepNested).render();
|
||||
expect(renderedDeep).toBe(deepNested);
|
||||
const deepAst = await parseMarkdown(renderedDeep, MATH_FLAGS);
|
||||
expect(collectMathNodes(deepAst)).toEqual([]);
|
||||
const deepCodeBlock = collectNodes(deepAst).find((node) => node.type === "CodeBlock");
|
||||
expect(deepCodeBlock).toBeDefined();
|
||||
expect(collectText(deepCodeBlock!)).toBe(
|
||||
"echo $HOME\n\nprintf '%s\\n' '\\(a+b\\)' '$$x^2$$'\n",
|
||||
);
|
||||
expect(scanMarkdownMath(deepNested)).toEqual([]);
|
||||
expect(findBlockMathSpans(deepNested)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves CommonMark 4-space and tab indented code blocks verbatim", async () => {
|
||||
const atStart = [
|
||||
' export PATH="$HOME/bin:$PATH"',
|
||||
" grep -E '\\(foo\\)' log.txt",
|
||||
" echo $$x^2$$",
|
||||
].join("\n");
|
||||
const renderedStart = prepareMarkdownSource(atStart).render();
|
||||
expect(renderedStart).toBe(atStart);
|
||||
const startAst = await parseMarkdown(renderedStart, MATH_FLAGS);
|
||||
expect(collectMathNodes(startAst)).toEqual([]);
|
||||
const startCode = collectNodes(startAst).find((node) => node.type === "CodeBlock");
|
||||
expect(startCode).toBeDefined();
|
||||
expect(collectText(startCode!)).toBe(
|
||||
"export PATH=\"$HOME/bin:$PATH\"\ngrep -E '\\(foo\\)' log.txt\necho $$x^2$$\n",
|
||||
);
|
||||
|
||||
const afterBlank = [
|
||||
"Run this:",
|
||||
"",
|
||||
" echo $HOME",
|
||||
" echo \\(foo\\)",
|
||||
" echo $$x^2$$",
|
||||
"",
|
||||
"\techo $USER",
|
||||
].join("\n");
|
||||
const renderedAfterBlank = prepareMarkdownSource(afterBlank).render();
|
||||
expect(renderedAfterBlank).toBe(afterBlank);
|
||||
const afterBlankAst = await parseMarkdown(renderedAfterBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(afterBlankAst)).toEqual([]);
|
||||
const afterBlankCodes = collectNodes(afterBlankAst).filter((node) => node.type === "CodeBlock");
|
||||
expect(afterBlankCodes).toHaveLength(1);
|
||||
expect(collectText(afterBlankCodes[0]!)).toBe(
|
||||
"echo $HOME\necho \\(foo\\)\necho $$x^2$$\n\necho $USER\n",
|
||||
);
|
||||
expect(scanMarkdownMath(afterBlank)).toEqual([]);
|
||||
expect(findBlockMathSpans(afterBlank)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves later non-math fences after prose", async () => {
|
||||
const source = "Intro.\n\n~~~sh\necho $PATH\n~~~";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toBe(source);
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
const codeBlock = collectNodes(ast).find((node) => node.type === "CodeBlock");
|
||||
expect(collectText(codeBlock!)).toBe("echo $PATH\n");
|
||||
});
|
||||
|
||||
it("exits an unclosed list-nested fence when the enclosing list ends and adapts later math", async () => {
|
||||
const withBlank = "- ~~~sh\n echo ok\n\nOutside \\(x+1\\).";
|
||||
const renderedWithBlank = prepareMarkdownSource(withBlank).render();
|
||||
expect(renderedWithBlank).toBe("- ~~~sh\n echo ok\n\nOutside $x+1$.");
|
||||
const astWithBlank = await parseMarkdown(renderedWithBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(astWithBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
|
||||
|
||||
const noBlank = "- ~~~sh\n echo ok\nOutside \\(x+1\\).";
|
||||
const astRaw = await parseMarkdown(noBlank, MATH_FLAGS);
|
||||
// Verify md4c closes the list fence immediately on unindented non-blank lines too.
|
||||
expect(collectNodes(astRaw).some((node) => node.type === "CodeBlock")).toBe(true);
|
||||
const renderedNoBlank = prepareMarkdownSource(noBlank).render();
|
||||
const astNoBlank = await parseMarkdown(renderedNoBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(astNoBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
|
||||
});
|
||||
|
||||
it("ignores escaped \\\\( and \\\\[ and HTML comments", async () => {
|
||||
const source = "Literal \\\\(x\\\\) and \\\\[y\\\\] and <!-- $hidden$ -->";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
expect(collectText(ast)).toContain("\\(x\\)");
|
||||
expect(collectText(ast)).toContain("\\[y\\]");
|
||||
});
|
||||
|
||||
it("protects <autolinks> containing dollar signs", async () => {
|
||||
const source = "Visit <https://example.com/$5> and pay $10";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toContain("<https://example.com/$5>");
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
const link = collectNodes(ast).find((node) => node.type === "Link");
|
||||
expect(link?.attributes?.url).toBe("https://example.com/$5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math source adaptation — valid inline and display math", () => {
|
||||
it.each([
|
||||
["$x$", "x"],
|
||||
["$a_i$", "a_i"],
|
||||
["$E = mc^2$", "E = mc^2"],
|
||||
["$2^k$", "2^k"],
|
||||
["$3x + 1$", "3x + 1"],
|
||||
["$0.5\\theta$", "0.5\\theta"],
|
||||
["$1/2$", "1/2"],
|
||||
["$5+2$", "5+2"],
|
||||
["$10 \\times 20$", "10 \\times 20"],
|
||||
["$\\theta \\in [0.5, 1.0]$", "\\theta \\in [0.5, 1.0]"],
|
||||
["$k$-means", "k"],
|
||||
["公式$x=1$的值", "x=1"],
|
||||
["\\(a^2 + b^2 = c^2\\)", "a^2 + b^2 = c^2"],
|
||||
["$x < y$ and $a > b$", "x < y"],
|
||||
["$a < b > c$", "a < b > c"],
|
||||
["Paragraph line\n with 4-space indented continuation $x$", "x"],
|
||||
])("parses inline math %s through md4c", async (source, firstContent) => {
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const mathNodes = collectMathNodes(ast);
|
||||
expect(mathNodes.length).toBeGreaterThanOrEqual(1);
|
||||
expect(mathNodes[0]).toMatchObject({
|
||||
type: "LatexMathInline",
|
||||
content: firstContent,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses both $x < y$ and $a > b$ without HTML mangling", async () => {
|
||||
const source = "$x < y$ and $a > b$";
|
||||
const ast = await parseMarkdown(prepareMarkdownSource(source).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([
|
||||
{ type: "LatexMathInline", content: "x < y" },
|
||||
{ type: "LatexMathInline", content: "a > b" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("inserts hair space around CJK-flanked math and preserves surrounding CJK text", async () => {
|
||||
const source = "公式$x=1$的值";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toBe("公式\u200A$x=1$\u200A的值");
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([{ type: "LatexMathInline", content: "x=1" }]);
|
||||
expect(collectText(ast)).toBe("公式\u200A\u200A的值");
|
||||
});
|
||||
|
||||
it("escapes GFM table pipes inside math without splitting columns", async () => {
|
||||
const source = [
|
||||
"| Metric | Formula | Norm |",
|
||||
"| --- | --- | --- |",
|
||||
"| Cond | $P(A|B)$ | $\\|x\\|$ |",
|
||||
].join("\n");
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const table = collectNodes(ast).find((node) => node.type === "Table");
|
||||
const bodyRow = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(bodyRow?.children).toHaveLength(3);
|
||||
expect(collectMathNodes(bodyRow!)).toEqual([
|
||||
{ type: "LatexMathInline", content: "P(A\\vert B)" },
|
||||
{ type: "LatexMathInline", content: "\\Vert x\\Vert " },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps matrix & and || intact inside math when mdast runs", async () => {
|
||||
const source = [
|
||||
"Before & ||spoiler||",
|
||||
"",
|
||||
"$$",
|
||||
"\\begin{pmatrix}",
|
||||
"a & b \\\\",
|
||||
"c & d",
|
||||
"\\end{pmatrix}",
|
||||
"$$",
|
||||
"",
|
||||
"Norm $\\|x\\| + ||y||$ and <end>.",
|
||||
].join("\n");
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const mathNodes = collectMathNodes(ast);
|
||||
expect(mathNodes).toHaveLength(2);
|
||||
expect(mathNodes[0].type).toBe("LatexMathDisplay");
|
||||
expect(mathNodes[0].content).toContain("a & b \\\\");
|
||||
expect(mathNodes[1]).toEqual({
|
||||
type: "LatexMathInline",
|
||||
content: "\\|x\\| + ||y||",
|
||||
});
|
||||
const text = collectText(ast);
|
||||
expect(text).toContain("Before & ||spoiler||");
|
||||
expect(text).toContain("<end>.");
|
||||
});
|
||||
|
||||
it("parses display math syntaxes: $$, multiline $$ with blank lines/comments, \\[...\\], and ```math", async () => {
|
||||
const single = await parseMarkdown(prepareMarkdownSource("$$E = mc^2$$").render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(single)).toEqual([{ type: "LatexMathDisplay", content: "E = mc^2" }]);
|
||||
|
||||
const multilineBlank = [
|
||||
"$$",
|
||||
"x = 1 % first variable",
|
||||
"% whole line comment",
|
||||
"",
|
||||
"y = 50\\% + 2 % trailing comment",
|
||||
"$$",
|
||||
].join("\n");
|
||||
const multiAst = await parseMarkdown(
|
||||
prepareMarkdownSource(multilineBlank).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
const multiMath = collectMathNodes(multiAst);
|
||||
expect(multiMath).toHaveLength(1);
|
||||
expect(multiMath[0].type).toBe("LatexMathDisplay");
|
||||
expect(multiMath[0].content).toContain("x = 1");
|
||||
expect(multiMath[0].content).toContain("y = 50\\% + 2");
|
||||
expect(multiMath[0].content).not.toContain("first variable");
|
||||
expect(multiMath[0].content).not.toContain("whole line comment");
|
||||
expect(multiMath[0].content).not.toContain("trailing comment");
|
||||
|
||||
const bracketSource = "\\[ \\int_0^1 x^2\\,dx \\]";
|
||||
const bracketAst = await parseMarkdown(
|
||||
prepareMarkdownSource(bracketSource).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(bracketAst)).toEqual([
|
||||
{ type: "LatexMathDisplay", content: " \\int_0^1 x^2\\,dx " },
|
||||
]);
|
||||
|
||||
const fencedMath = "```math\n\\sum_{i=1}^n i\n```";
|
||||
const fencedAst = await parseMarkdown(prepareMarkdownSource(fencedMath).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(fencedAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(fencedAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(fencedAst)[0].content?.trim()).toBe("\\sum_{i=1}^n i");
|
||||
|
||||
const tildeMath = "~~~math\na^2 + b^2 = c^2\n~~~";
|
||||
const tildeAst = await parseMarkdown(prepareMarkdownSource(tildeMath).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(tildeAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(tildeAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(tildeAst)[0].content?.trim()).toBe("a^2 + b^2 = c^2");
|
||||
|
||||
const proseThenMath = "Intro.\n\n~~~math\nx=1\n~~~";
|
||||
const proseThenMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(proseThenMath).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(proseThenMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(proseThenMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(proseThenMathAst)[0].content?.trim()).toBe("x=1");
|
||||
|
||||
const listMathFence = "1. Compute:\n\n ```math\n x = 1\n ```";
|
||||
const listMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(listMathFence).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(listMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(listMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(listMathAst)[0].content?.trim()).toBe("x = 1");
|
||||
expect(collectNodes(listMathAst).some((node) => node.type === "OrderedList")).toBe(true);
|
||||
|
||||
const nestedListMathFence = "1. Outer:\n - Inner:\n\n ```math\n y = 2\n ```";
|
||||
const nestedListMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(nestedListMathFence).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(nestedListMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(nestedListMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(nestedListMathAst)[0].content?.trim()).toBe("y = 2");
|
||||
expect(collectNodes(nestedListMathAst).some((node) => node.type === "UnorderedList")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("escapes internal unescaped $ inside \\(...\\), \\[...\\], and ```math", async () => {
|
||||
const paren = prepareMarkdownSource("\\(\\text{cost } $5\\)").render();
|
||||
expect(paren).toBe("$\\text{cost } \\$5$");
|
||||
const parenAst = await parseMarkdown(paren, MATH_FLAGS);
|
||||
expect(collectMathNodes(parenAst)).toEqual([
|
||||
{ type: "LatexMathInline", content: "\\text{cost } \\$5" },
|
||||
]);
|
||||
|
||||
const bracket = prepareMarkdownSource("\\[\\text{cost } $5\\]").render();
|
||||
const bracketAst = await parseMarkdown(bracket, MATH_FLAGS);
|
||||
expect(collectMathNodes(bracketAst)).toEqual([
|
||||
{ type: "LatexMathDisplay", content: "\\text{cost } \\$5" },
|
||||
]);
|
||||
|
||||
const fenced = prepareMarkdownSource("```math\n\\text{cost } $5\n```").render();
|
||||
const fencedAst = await parseMarkdown(fenced, MATH_FLAGS);
|
||||
expect(collectMathNodes(fencedAst)[0].content?.trim()).toBe("\\text{cost } \\$5");
|
||||
});
|
||||
|
||||
it("keeps unclosed ```math, $$, \\[, \\(, and $ literal", () => {
|
||||
expect(adaptMarkdownMath("```math\n\\frac{a}{").source).toBe("```math\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("$$\n\\frac{a}{").source).toBe("\\$\\$\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("\\[\n\\frac{a}{").source).toBe("\\[\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("$\\alpha +").source).toBe("\\$\\alpha +");
|
||||
expect(adaptMarkdownMath("\\(\\alpha +").source).toBe("\\(\\alpha +");
|
||||
});
|
||||
|
||||
it("protects math ranges in normalizeMarkdownHtml", () => {
|
||||
expect(normalizeMarkdownHtml("$a < b > c$ and <b>bold</b>")).toBe("$a < b > c$ and **bold**");
|
||||
expect(normalizeMarkdownHtml("$$\n<div>x</div>\n$$")).toBe("$$\n<div>x</div>\n$$");
|
||||
expect(
|
||||
normalizeMarkdownHtml("<details><summary>Proof</summary>\n\n$a < b > c$\n</details>"),
|
||||
).toBe("**Proof**\n\n\n\n$a < b > c$\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math fast path invariants", () => {
|
||||
it("bails out immediately on plain prose without math triggers", () => {
|
||||
const prose = "Plain markdown with **bold**, `code`, and [link](https://example.com).";
|
||||
expect(scanMarkdownMath(prose)).toEqual([]);
|
||||
const adapted = adaptMarkdownMath(prose);
|
||||
expect(adapted.source).toBe(prose);
|
||||
expect(adapted.mathRanges).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves plain prose and canonicalizes math-only prose synchronously through prepareMarkdownSource", () => {
|
||||
const plain = "Plain prose without special triggers.";
|
||||
expect(prepareMarkdownSource(plain).render()).toBe(plain);
|
||||
|
||||
const mathSource =
|
||||
"Inline $E = mc^2$, paren \\(a+b\\), display $$x^2 + y^2$$.\n\n```math\nz = 1\n```";
|
||||
const rendered = prepareMarkdownSource(mathSource).render();
|
||||
expect(rendered).toContain("$E = mc^2$");
|
||||
expect(rendered).toContain("$a+b$");
|
||||
expect(rendered).toContain("$$\nz = 1\n$$");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -806,9 +806,37 @@ it.each([
|
||||
color: theme.colors.accentBright,
|
||||
});
|
||||
expect(style.thematicBreak?.color).toBe(theme.colors.border);
|
||||
expect(style.math).toMatchObject({
|
||||
color: theme.colors.foreground,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
marginTop: 0,
|
||||
marginBottom: 16,
|
||||
textAlign: "center",
|
||||
});
|
||||
expect(style.inlineMath).toMatchObject({
|
||||
color: theme.colors.foreground,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("uses muted text colour for math when compact and muted", () => {
|
||||
const { markdownStyle: style } = createMarkdownStyles(darkTheme, {
|
||||
compact: true,
|
||||
muted: true,
|
||||
blockGap: 12,
|
||||
});
|
||||
expect(style.math).toMatchObject({
|
||||
color: darkTheme.colors.foregroundMuted,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
marginTop: 0,
|
||||
marginBottom: 12,
|
||||
textAlign: "center",
|
||||
});
|
||||
expect(style.inlineMath).toEqual({ color: darkTheme.colors.foregroundMuted });
|
||||
});
|
||||
|
||||
it.each([darkTheme, lightTheme])("supplies the theme selection colour to the renderer", (theme) => {
|
||||
expect(createMarkdownStyles(theme, { blockGap: 16 })).toHaveProperty(
|
||||
"selectionColor",
|
||||
@@ -1442,3 +1470,69 @@ describe("web Markdown parser preload", () => {
|
||||
expect(ast?.children?.map((node) => node.type)).toEqual(["Heading", "Paragraph"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("math preparation compatibility with latexMath false and true", () => {
|
||||
it("renders currency literally with latexMath: false while enabling math with latexMath: true", async () => {
|
||||
const source =
|
||||
"Costs $5 and $10; inline $E = mc^2$, \\(a+b\\), \\[c+d\\], and:\n\n```math\nx^2\n```";
|
||||
const prepared = prepareMarkdownSource(source).render();
|
||||
|
||||
const noMathAst = await parseMarkdown(prepared, {
|
||||
latexMath: false,
|
||||
hardSoftBreaks: true,
|
||||
admonitions: true,
|
||||
});
|
||||
const noMathText = JSON.stringify(noMathAst);
|
||||
expect(noMathText).toContain("Costs $5 and $10");
|
||||
expect(noMathText).not.toContain("LatexMath");
|
||||
|
||||
const mathAst = await parseMarkdown(prepared, {
|
||||
latexMath: true,
|
||||
hardSoftBreaks: true,
|
||||
admonitions: true,
|
||||
});
|
||||
const mathNodes: { type: string; content: string }[] = [];
|
||||
const walk = (node: ASTNode) => {
|
||||
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") {
|
||||
mathNodes.push({
|
||||
type: node.type,
|
||||
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
|
||||
});
|
||||
}
|
||||
node.children?.forEach(walk);
|
||||
};
|
||||
walk(mathAst);
|
||||
expect(mathNodes.map((n) => [n.type, n.content.trim()])).toEqual([
|
||||
["LatexMathInline", "E = mc^2"],
|
||||
["LatexMathInline", "a+b"],
|
||||
["LatexMathDisplay", "c+d"],
|
||||
["LatexMathDisplay", "x^2"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web KaTeX .woff2-only stylesheet sync", () => {
|
||||
it("includes all 20 .woff2 fonts from katex and drops .woff/.ttf fallbacks", async () => {
|
||||
const fs = await import("node:fs");
|
||||
const path = await import("node:path");
|
||||
const katexCssPath = require.resolve("katex/dist/katex.min.css");
|
||||
const katexFontsDir = path.join(path.dirname(katexCssPath), "fonts");
|
||||
const woff2Files = fs
|
||||
.readdirSync(katexFontsDir)
|
||||
.filter((name) => name.endsWith(".woff2"))
|
||||
.sort();
|
||||
expect(woff2Files).toHaveLength(20);
|
||||
|
||||
const katexStylesSource = fs.readFileSync(
|
||||
path.resolve(__dirname, "katex-styles.web.ts"),
|
||||
"utf8",
|
||||
);
|
||||
for (const fontFile of woff2Files) {
|
||||
expect(katexStylesSource).toContain(`katex/dist/fonts/${fontFile}`);
|
||||
}
|
||||
expect(katexStylesSource).not.toContain('.woff")');
|
||||
expect(katexStylesSource).not.toContain('.ttf")');
|
||||
expect(katexStylesSource).toContain(".katex{");
|
||||
expect(katexStylesSource).toContain(".enrm-text .katex-display{margin:0}");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,7 +35,7 @@ export type { MarkdownDestinations };
|
||||
export type MarkdownSoftBreaks = "break" | "join";
|
||||
|
||||
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
|
||||
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
const MD4C_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
|
||||
const JOINED_SOFT_BREAKS_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
|
||||
|
||||
// Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it.
|
||||
|
||||
@@ -8,10 +8,11 @@ import {
|
||||
type ComponentProps,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import type {
|
||||
CodeBlockRendererProps,
|
||||
LinkRendererProps,
|
||||
MarkdownRenderers,
|
||||
import {
|
||||
registerKaTeXStyleLoader,
|
||||
type CodeBlockRendererProps,
|
||||
type LinkRendererProps,
|
||||
type MarkdownRenderers,
|
||||
} from "react-native-enriched-markdown";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useFileLink } from "@/assistant-file-links";
|
||||
@@ -151,6 +152,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
registerKaTeXStyleLoader(async () => {
|
||||
const mod = await import("./katex-styles.web");
|
||||
mod.ensureKaTeXStyles();
|
||||
});
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview";
|
||||
import { classifyAssistantFileLink } from "@/assistant-file-links";
|
||||
import { ASSISTANT_FILE_EXTENSIONS } from "@/assistant-file-links/extensions";
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
import { adaptMarkdownMath, isOffsetInRanges } from "./math";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { AssistantFileLinkSource } from "@/assistant-file-links";
|
||||
@@ -231,6 +232,8 @@ export function prepareMarkdownSource(
|
||||
} = {},
|
||||
) {
|
||||
source = normalizeMarkdownHtml(source);
|
||||
const { source: adaptedSource, mathRanges } = adaptMarkdownMath(source);
|
||||
source = adaptedSource;
|
||||
const images: MarkdownImage[] = [];
|
||||
let tree: Root | undefined;
|
||||
const getTree = () =>
|
||||
@@ -351,53 +354,59 @@ export function prepareMarkdownSource(
|
||||
edits.push({ start, end: labelStart, text: "" });
|
||||
edits.push({ start: labelEnd, end, text: "" });
|
||||
}
|
||||
function adaptTableHeaderGap(start: number, previous?: Nodes, line?: number) {
|
||||
if (previous?.type !== "paragraph" || previous.position?.end.line !== (line ?? -1) - 1) return;
|
||||
// MD4C only recognizes a table header on the first line of a paragraph.
|
||||
const lineStart =
|
||||
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
|
||||
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
|
||||
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
function adaptTableRow(start: number, end: number) {
|
||||
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
|
||||
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
|
||||
const row = source.slice(start, end);
|
||||
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
|
||||
if (isOffsetInRanges(start + match.index, mathRanges)) continue;
|
||||
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
|
||||
}
|
||||
}
|
||||
function adaptTextNode(start: number, end: number) {
|
||||
const slice = source.slice(start, end);
|
||||
const text = slice.replace(
|
||||
/(?<!\\)(?:(&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);)|(\|\|))/g,
|
||||
(match, entity: string | undefined, _bars: string | undefined, offset: number) => {
|
||||
if (isOffsetInRanges(start + offset, mathRanges)) return match;
|
||||
if (entity) return decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&");
|
||||
return "\\|\\|";
|
||||
},
|
||||
);
|
||||
if (text !== slice) edits.push({ start, end, text });
|
||||
}
|
||||
function visit(node: Nodes, previous?: Nodes) {
|
||||
const position = node.position;
|
||||
if (position?.start.offset !== undefined && position.end.offset !== undefined) {
|
||||
const start = position.start.offset;
|
||||
const end = position.end.offset;
|
||||
if (node.type === "paragraph") splitStandaloneImages(node, start, end);
|
||||
if (
|
||||
node.type === "table" &&
|
||||
previous?.type === "paragraph" &&
|
||||
previous.position?.end.line === position.start.line - 1
|
||||
) {
|
||||
// MD4C only recognizes a table header on the first line of a paragraph.
|
||||
const lineStart =
|
||||
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
|
||||
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
|
||||
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
}
|
||||
if (node.type === "tableRow") {
|
||||
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
|
||||
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
|
||||
const row = source.slice(start, end);
|
||||
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
|
||||
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
|
||||
if (node.type === "table") adaptTableHeaderGap(start, previous, position.start.line);
|
||||
if (!isOffsetInRanges(start, mathRanges)) {
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
}
|
||||
}
|
||||
if (node.type === "tableRow") adaptTableRow(start, end);
|
||||
if (node.type === "image" || node.type === "imageReference") {
|
||||
collectImage(node, start, end);
|
||||
if (!isOffsetInRanges(start, mathRanges)) collectImage(node, start, end);
|
||||
return;
|
||||
}
|
||||
if (node.type === "text") {
|
||||
const text = source
|
||||
.slice(start, end)
|
||||
.replace(/(?<!\\)&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);/g, (entity) =>
|
||||
decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&"),
|
||||
)
|
||||
.replace(/(?<!\\)\|\|/g, "\\|\\|");
|
||||
if (text !== source.slice(start, end)) edits.push({ start, end, text });
|
||||
}
|
||||
if (node.type === "text") adaptTextNode(start, end);
|
||||
}
|
||||
if ("children" in node)
|
||||
node.children.forEach((child, index) => visit(child, node.children[index - 1]));
|
||||
|
||||
@@ -1,3 +1,22 @@
|
||||
import {
|
||||
checkFenceContainerExit,
|
||||
isAsciiAlnum,
|
||||
isAsciiPunctuation,
|
||||
isBlankRange,
|
||||
isClosingFenceAt,
|
||||
matchListMarkerAt,
|
||||
measureIndentAt,
|
||||
parseFenceOpenerAt,
|
||||
stripBlockquotesAt,
|
||||
} from "./block-scan";
|
||||
import {
|
||||
isUnclosedInlineMathCandidate,
|
||||
matchClosedBracketMath,
|
||||
matchClosedDollarDisplayMath,
|
||||
matchClosedInlineMath,
|
||||
matchClosedParenMath,
|
||||
} from "./math";
|
||||
|
||||
/**
|
||||
* Sentinel destination for incomplete links while streaming. Web renders it as a
|
||||
* non-interactive link-styled span; native styles it as a link and ignores taps.
|
||||
@@ -15,8 +34,17 @@ interface OpenFence {
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
lineStart: number;
|
||||
lastLineStart: number;
|
||||
quoteDepth: number;
|
||||
maxCloseIndent: number;
|
||||
listMinIndent: number;
|
||||
hasContent: boolean;
|
||||
}
|
||||
|
||||
interface OpenDisplayMath {
|
||||
kind: "$$" | "\\[";
|
||||
withholdFrom: number;
|
||||
quoteDepth: number;
|
||||
hasContent: boolean;
|
||||
}
|
||||
|
||||
@@ -24,7 +52,9 @@ interface FenceScanCheckpoint {
|
||||
/** Exact prefix of completed lines already scanned (ends at `\n` or `\r`, or is `""`). */
|
||||
scannedPrefix: string;
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
listContentIndent: number;
|
||||
listQuoteDepth: number;
|
||||
/** Start offset of the most recent closing fence line, or -1 if none. */
|
||||
lastClosedFenceLineStart: number;
|
||||
}
|
||||
@@ -110,76 +140,20 @@ function lastCompletedLineEnd(source: string): number {
|
||||
return lastBreak === -1 ? 0 : lastBreak + 1;
|
||||
}
|
||||
|
||||
/** Strip leading CommonMark blockquote markers (`> `) and return quote depth + content offset. */
|
||||
function stripBlockquotes(text: string): { quoteDepth: number; offset: number } {
|
||||
let offset = 0;
|
||||
let quoteDepth = 0;
|
||||
while (offset < text.length) {
|
||||
let spaces = 0;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === " " && spaces < 3) {
|
||||
cursor++;
|
||||
spaces++;
|
||||
}
|
||||
if (text[cursor] !== ">") break;
|
||||
quoteDepth++;
|
||||
cursor++;
|
||||
if (text[cursor] === " " || text[cursor] === "\t") cursor++;
|
||||
offset = cursor;
|
||||
}
|
||||
return { quoteDepth, offset };
|
||||
return stripBlockquotesAt(text, 0, text.length);
|
||||
}
|
||||
|
||||
function measureIndent(text: string, from: number): { spaces: number; offset: number } {
|
||||
let spaces = 0;
|
||||
let offset = from;
|
||||
while (offset < text.length) {
|
||||
const ch = text[offset];
|
||||
if (ch === " ") {
|
||||
spaces++;
|
||||
offset++;
|
||||
} else if (ch === "\t") {
|
||||
spaces += 4 - (spaces % 4);
|
||||
offset++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { spaces, offset };
|
||||
return measureIndentAt(text, from, text.length);
|
||||
}
|
||||
|
||||
function matchListMarker(
|
||||
text: string,
|
||||
from: number,
|
||||
maxIndent = Number.POSITIVE_INFINITY,
|
||||
): { markerEnd: number; contentIndent: number } | null {
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (offset >= text.length) return null;
|
||||
const ch = text[offset];
|
||||
if (ch === "-" || ch === "*" || ch === "+") {
|
||||
const after = offset + 1;
|
||||
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
|
||||
return { markerEnd: after + 1, contentIndent: spaces + 2 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (ch >= "0" && ch <= "9") {
|
||||
let cursor = offset;
|
||||
while (
|
||||
cursor < text.length &&
|
||||
text[cursor] >= "0" &&
|
||||
text[cursor] <= "9" &&
|
||||
cursor - offset < 9
|
||||
) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor < text.length && (text[cursor] === "." || text[cursor] === ")")) {
|
||||
const after = cursor + 1;
|
||||
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
|
||||
return { markerEnd: after + 1, contentIndent: spaces + (after - offset) + 1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return matchListMarkerAt(text, from, text.length, maxIndent);
|
||||
}
|
||||
|
||||
function parseFenceOpener(
|
||||
@@ -187,17 +161,7 @@ function parseFenceOpener(
|
||||
from: number,
|
||||
maxIndent: number,
|
||||
): { char: "`" | "~"; length: number; info: string } | null {
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (spaces > maxIndent || offset >= text.length) return null;
|
||||
const ch = text[offset];
|
||||
if (ch !== "`" && ch !== "~") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === ch) cursor++;
|
||||
const length = cursor - offset;
|
||||
if (length < 3) return null;
|
||||
const info = text.slice(cursor);
|
||||
if (ch === "`" && info.includes("`")) return null;
|
||||
return { char: ch, length, info };
|
||||
return parseFenceOpenerAt(text, from, text.length, maxIndent);
|
||||
}
|
||||
|
||||
function isClosingFence(
|
||||
@@ -207,16 +171,7 @@ function isClosingFence(
|
||||
char: "`" | "~",
|
||||
minLength: number,
|
||||
): boolean {
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (spaces > maxIndent || offset >= text.length || text[offset] !== char) return false;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === char) cursor++;
|
||||
if (cursor - offset < minLength) return false;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor] !== " " && text[cursor] !== "\t") return false;
|
||||
cursor++;
|
||||
}
|
||||
return true;
|
||||
return isClosingFenceAt(text, from, text.length, maxIndent, char, minLength);
|
||||
}
|
||||
|
||||
function isPartialClosingFence(
|
||||
@@ -237,18 +192,191 @@ function isPartialClosingFence(
|
||||
}
|
||||
|
||||
function isBlankRest(text: string, from: number): boolean {
|
||||
for (let i = from; i < text.length; i++) {
|
||||
if (text[i] !== " " && text[i] !== "\t") return false;
|
||||
}
|
||||
return true;
|
||||
return isBlankRange(text, from, text.length);
|
||||
}
|
||||
|
||||
interface FenceStepState {
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
listContentIndent: number;
|
||||
listQuoteDepth: number;
|
||||
lastClosedFenceLineStart: number;
|
||||
}
|
||||
|
||||
function hasTrailingOddBackslash(text: string): boolean {
|
||||
let backslashes = 0;
|
||||
for (let i = text.length - 1; i >= 0 && text[i] === "\\"; i--) backslashes++;
|
||||
return backslashes % 2 === 1;
|
||||
}
|
||||
|
||||
function hasTrailingPartialDoubleDollarCloser(text: string): boolean {
|
||||
if (!text.endsWith("$")) return false;
|
||||
if (text.length >= 2 && text[text.length - 2] === "$") return false;
|
||||
return !hasTrailingOddBackslash(text.slice(0, -1));
|
||||
}
|
||||
|
||||
function findSameLineBracketClose(text: string, from: number): number {
|
||||
let j = from;
|
||||
while (j < text.length) {
|
||||
if (text[j] === "\\" && text[j + 1] === "]") return j + 2;
|
||||
if (text[j] === "\\" && j + 1 < text.length) {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function findSameLineDoubleDollarClose(text: string, from: number): number {
|
||||
let j = from;
|
||||
while (j < text.length) {
|
||||
if (text[j] === "\\" && j + 1 < text.length) {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
if (text[j] === "$" && text[j + 1] === "$") {
|
||||
let closeEnd = j;
|
||||
while (closeEnd < text.length && text[closeEnd] === "$") closeEnd++;
|
||||
if (closeEnd - j === 2) return closeEnd;
|
||||
j = closeEnd;
|
||||
continue;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function openDisplayMathFromLine(
|
||||
kind: "$$" | "\\[",
|
||||
text: string,
|
||||
from: number,
|
||||
openIndex: number,
|
||||
restStart: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
): OpenDisplayMath {
|
||||
const withholdFrom = isBlankRest(text.slice(from, openIndex), 0)
|
||||
? lineStart
|
||||
: lineStart + openIndex;
|
||||
const rest = text.slice(restStart);
|
||||
const effectiveRest =
|
||||
kind === "\\[" && isTrailingPartialLine && hasTrailingOddBackslash(rest)
|
||||
? rest.slice(0, -1)
|
||||
: rest;
|
||||
return {
|
||||
kind,
|
||||
withholdFrom,
|
||||
quoteDepth,
|
||||
hasContent: !isBlankRest(effectiveRest, 0),
|
||||
};
|
||||
}
|
||||
|
||||
function scanLineForDisplayMath(
|
||||
text: string,
|
||||
from: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
state: FenceStepState,
|
||||
): void {
|
||||
let k = from;
|
||||
while (k < text.length) {
|
||||
const ch = text[k];
|
||||
if (ch === "\\") {
|
||||
if (text[k + 1] === "[") {
|
||||
const closeEnd = findSameLineBracketClose(text, k + 2);
|
||||
if (closeEnd !== -1) {
|
||||
k = closeEnd;
|
||||
continue;
|
||||
}
|
||||
state.openDisplayMath = openDisplayMathFromLine(
|
||||
"\\[",
|
||||
text,
|
||||
from,
|
||||
k,
|
||||
k + 2,
|
||||
lineStart,
|
||||
quoteDepth,
|
||||
isTrailingPartialLine,
|
||||
);
|
||||
return;
|
||||
}
|
||||
k += k + 1 < text.length && isAsciiPunctuation(text[k + 1]) ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
let runEnd = k;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd++;
|
||||
const closePos = findMatchingBacktickRun(text, runEnd, runEnd - k);
|
||||
k = closePos !== -1 ? closePos + (runEnd - k) : runEnd;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$") {
|
||||
let runEnd = k;
|
||||
while (runEnd < text.length && text[runEnd] === "$") runEnd++;
|
||||
if (runEnd - k === 2) {
|
||||
const closeEnd = findSameLineDoubleDollarClose(text, runEnd);
|
||||
if (closeEnd !== -1) {
|
||||
k = closeEnd;
|
||||
continue;
|
||||
}
|
||||
state.openDisplayMath = openDisplayMathFromLine(
|
||||
"$$",
|
||||
text,
|
||||
from,
|
||||
k,
|
||||
runEnd,
|
||||
lineStart,
|
||||
quoteDepth,
|
||||
isTrailingPartialLine,
|
||||
);
|
||||
return;
|
||||
}
|
||||
k = runEnd;
|
||||
continue;
|
||||
}
|
||||
k++;
|
||||
}
|
||||
}
|
||||
|
||||
function stepOpenDisplayMathLine(
|
||||
text: string,
|
||||
offset: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
state: FenceStepState,
|
||||
): boolean {
|
||||
const open = state.openDisplayMath!;
|
||||
if (quoteDepth < open.quoteDepth) {
|
||||
state.openDisplayMath = null;
|
||||
return false;
|
||||
}
|
||||
const closeEnd =
|
||||
open.kind === "$$"
|
||||
? findSameLineDoubleDollarClose(text, offset)
|
||||
: findSameLineBracketClose(text, offset);
|
||||
if (closeEnd !== -1) {
|
||||
state.openDisplayMath = null;
|
||||
state.lastClosedFenceLineStart = lineStart;
|
||||
scanLineForDisplayMath(text, closeEnd, lineStart, quoteDepth, isTrailingPartialLine, state);
|
||||
return true;
|
||||
}
|
||||
const rest = text.slice(offset);
|
||||
let effectiveRest = rest;
|
||||
if (isTrailingPartialLine) {
|
||||
if (open.kind === "$$" && hasTrailingPartialDoubleDollarCloser(rest)) {
|
||||
effectiveRest = rest.slice(0, -1);
|
||||
} else if (open.kind === "\\[" && hasTrailingOddBackslash(rest)) {
|
||||
effectiveRest = rest.slice(0, -1);
|
||||
}
|
||||
}
|
||||
if (!isBlankRest(effectiveRest, 0)) open.hasContent = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
function stepFenceLine(
|
||||
text: string,
|
||||
lineStart: number,
|
||||
@@ -258,8 +386,17 @@ function stepFenceLine(
|
||||
const { quoteDepth, offset } = stripBlockquotes(text);
|
||||
|
||||
if (state.openFence !== null) {
|
||||
if (quoteDepth < state.openFence.quoteDepth) {
|
||||
// Leaving the blockquote closes any fence opened inside it.
|
||||
if (
|
||||
checkFenceContainerExit(
|
||||
text,
|
||||
0,
|
||||
text.length,
|
||||
state.openFence.quoteDepth,
|
||||
state.openFence.listMinIndent,
|
||||
).exited
|
||||
) {
|
||||
// Leaving the blockquote or enclosing list closes any fence opened inside it.
|
||||
state.lastClosedFenceLineStart = state.openFence.lastLineStart;
|
||||
state.openFence = null;
|
||||
} else if (
|
||||
isClosingFence(
|
||||
@@ -274,6 +411,7 @@ function stepFenceLine(
|
||||
state.openFence = null;
|
||||
return;
|
||||
} else {
|
||||
state.openFence.lastLineStart = lineStart;
|
||||
const partialCloser =
|
||||
isTrailingPartialLine &&
|
||||
quoteDepth === state.openFence.quoteDepth &&
|
||||
@@ -289,34 +427,62 @@ function stepFenceLine(
|
||||
}
|
||||
}
|
||||
|
||||
if (isBlankRest(text, offset)) return;
|
||||
if (
|
||||
state.openDisplayMath !== null &&
|
||||
stepOpenDisplayMathLine(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBlankRest(text, offset)) {
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listContentIndent = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listContentIndent = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
|
||||
let cursor = offset;
|
||||
let lineIndentBase = state.listContentIndent;
|
||||
let lineIndentBase = quoteDepth === state.listQuoteDepth ? state.listContentIndent : 0;
|
||||
const { spaces: firstSpaces } = measureIndent(text, cursor);
|
||||
if (firstSpaces < state.listContentIndent) {
|
||||
if (quoteDepth === state.listQuoteDepth && firstSpaces < state.listContentIndent) {
|
||||
state.listContentIndent = 0;
|
||||
lineIndentBase = 0;
|
||||
}
|
||||
let marker = matchListMarker(text, cursor);
|
||||
let peeledList = false;
|
||||
let marker = matchListMarker(text, cursor, lineIndentBase + 3);
|
||||
while (marker) {
|
||||
state.listContentIndent = marker.contentIndent;
|
||||
lineIndentBase = marker.contentIndent;
|
||||
const markerBase = cursor === offset ? 0 : lineIndentBase;
|
||||
const totalIndent = markerBase + marker.contentIndent;
|
||||
state.listContentIndent = totalIndent;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
lineIndentBase = totalIndent;
|
||||
cursor = marker.markerEnd;
|
||||
marker = matchListMarker(text, cursor);
|
||||
peeledList = true;
|
||||
marker = matchListMarker(text, cursor, 3);
|
||||
}
|
||||
|
||||
const opener = parseFenceOpener(text, cursor, lineIndentBase + 3);
|
||||
const opener = parseFenceOpener(text, cursor, peeledList ? 3 : lineIndentBase + 3);
|
||||
if (opener) {
|
||||
state.openFence = {
|
||||
char: opener.char,
|
||||
length: opener.length,
|
||||
lineStart,
|
||||
lastLineStart: lineStart,
|
||||
quoteDepth,
|
||||
maxCloseIndent: lineIndentBase + 3,
|
||||
listMinIndent: lineIndentBase,
|
||||
hasContent: false,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
scanLineForDisplayMath(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state);
|
||||
}
|
||||
|
||||
function advanceFenceRange(source: string, from: number, to: number, state: FenceStepState): void {
|
||||
@@ -339,18 +505,28 @@ function cloneOpenFence(fence: OpenFence | null): OpenFence | null {
|
||||
return fence ? { ...fence } : null;
|
||||
}
|
||||
|
||||
function cloneOpenDisplayMath(math: OpenDisplayMath | null): OpenDisplayMath | null {
|
||||
return math ? { ...math } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Incrementally advance fence tracking across completed lines so steady-state
|
||||
* Incrementally advance fence and display-math tracking across completed lines so steady-state
|
||||
* streaming frames within a line scan 0 prior lines, and each newline scans 1 line.
|
||||
*/
|
||||
function resolveFenceState(
|
||||
source: string,
|
||||
checkpoint: FenceScanCheckpoint | null,
|
||||
): { openFence: OpenFence | null; lastClosedFenceLineStart: number } {
|
||||
): {
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
lastClosedFenceLineStart: number;
|
||||
} {
|
||||
const completedEnd = lastCompletedLineEnd(source);
|
||||
const state: FenceStepState = {
|
||||
openFence: null,
|
||||
openDisplayMath: null,
|
||||
listContentIndent: 0,
|
||||
listQuoteDepth: 0,
|
||||
lastClosedFenceLineStart: -1,
|
||||
};
|
||||
|
||||
@@ -361,7 +537,9 @@ function resolveFenceState(
|
||||
source.startsWith(checkpoint.scannedPrefix);
|
||||
if (matchedPrefix && checkpoint) {
|
||||
state.openFence = cloneOpenFence(checkpoint.openFence);
|
||||
state.openDisplayMath = cloneOpenDisplayMath(checkpoint.openDisplayMath);
|
||||
state.listContentIndent = checkpoint.listContentIndent;
|
||||
state.listQuoteDepth = checkpoint.listQuoteDepth;
|
||||
state.lastClosedFenceLineStart = checkpoint.lastClosedFenceLineStart;
|
||||
scanFrom = checkpoint.scannedPrefix.length;
|
||||
}
|
||||
@@ -373,7 +551,9 @@ function resolveFenceState(
|
||||
if (checkpoint && (!matchedPrefix || completedEnd !== checkpoint.scannedPrefix.length)) {
|
||||
checkpoint.scannedPrefix = source.slice(0, completedEnd);
|
||||
checkpoint.openFence = cloneOpenFence(state.openFence);
|
||||
checkpoint.openDisplayMath = cloneOpenDisplayMath(state.openDisplayMath);
|
||||
checkpoint.listContentIndent = state.listContentIndent;
|
||||
checkpoint.listQuoteDepth = state.listQuoteDepth;
|
||||
checkpoint.lastClosedFenceLineStart = state.lastClosedFenceLineStart;
|
||||
}
|
||||
|
||||
@@ -383,6 +563,7 @@ function resolveFenceState(
|
||||
|
||||
return {
|
||||
openFence: state.openFence,
|
||||
openDisplayMath: state.openDisplayMath,
|
||||
lastClosedFenceLineStart: state.lastClosedFenceLineStart,
|
||||
};
|
||||
}
|
||||
@@ -663,17 +844,6 @@ function isWhitespaceChar(ch: string | undefined): boolean {
|
||||
return ch === undefined || ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
|
||||
}
|
||||
|
||||
function isAsciiPunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (
|
||||
(code >= 0x21 && code <= 0x2f) ||
|
||||
(code >= 0x3a && code <= 0x40) ||
|
||||
(code >= 0x5b && code <= 0x60) ||
|
||||
(code >= 0x7b && code <= 0x7e)
|
||||
);
|
||||
}
|
||||
|
||||
function isUnicodePunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
if (isAsciiPunctuation(ch)) return true;
|
||||
@@ -861,6 +1031,7 @@ interface InlineScanState {
|
||||
stack: InlineStackEntry[];
|
||||
openCode: { pos: number; length: number; contentStart: number } | null;
|
||||
openHtmlPos: number | null;
|
||||
openInlineMathPos: number | null;
|
||||
trailingBackslash: boolean;
|
||||
}
|
||||
|
||||
@@ -1153,7 +1324,7 @@ function stripPartialEmphCloser(output: string, entry: EmphEntry): string {
|
||||
|
||||
function unwindInlineState(source: string, state: InlineScanState): string {
|
||||
let output = source;
|
||||
const { openCode, openHtmlPos, trailingBackslash, stack } = state;
|
||||
const { openCode, openHtmlPos, openInlineMathPos, trailingBackslash, stack } = state;
|
||||
|
||||
if (openCode) {
|
||||
let codeContent = output.slice(openCode.contentStart);
|
||||
@@ -1167,6 +1338,8 @@ function unwindInlineState(source: string, state: InlineScanState): string {
|
||||
: output.slice(0, openCode.contentStart) + codeContent + "`".repeat(openCode.length);
|
||||
} else if (openHtmlPos !== null) {
|
||||
output = output.slice(0, openHtmlPos);
|
||||
} else if (openInlineMathPos !== null) {
|
||||
output = output.slice(0, openInlineMathPos);
|
||||
} else if (trailingBackslash) {
|
||||
output = output.slice(0, -1);
|
||||
}
|
||||
@@ -1210,6 +1383,56 @@ function scanBacktickToken(source: string, i: number, state: InlineScanState): n
|
||||
return null;
|
||||
}
|
||||
|
||||
function isOnTrailingLine(source: string, from: number): boolean {
|
||||
return source.indexOf("\n", from) === -1 && source.indexOf("\r", from) === -1;
|
||||
}
|
||||
|
||||
function scanInlineBackslashToken(
|
||||
source: string,
|
||||
i: number,
|
||||
state: InlineScanState,
|
||||
): number | null {
|
||||
if (source[i + 1] === "(") {
|
||||
const closedParen = matchClosedParenMath(source, i);
|
||||
if (closedParen !== -1) return closedParen;
|
||||
if (isOnTrailingLine(source, i + 2)) {
|
||||
if (i + 2 === source.length) state.openInlineMathPos = i;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (source[i + 1] === "[") {
|
||||
const closedBracket = matchClosedBracketMath(source, i);
|
||||
if (closedBracket !== -1) return closedBracket;
|
||||
}
|
||||
if (i + 1 === source.length) {
|
||||
state.trailingBackslash = true;
|
||||
return null;
|
||||
}
|
||||
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
|
||||
}
|
||||
|
||||
function scanInlineDollarToken(source: string, i: number, state: InlineScanState): number | null {
|
||||
if (source[i + 1] === "$") {
|
||||
const closedDisplay = matchClosedDollarDisplayMath(source, i);
|
||||
if (closedDisplay !== -1) return closedDisplay;
|
||||
let runEnd = i;
|
||||
while (runEnd < source.length && source[runEnd] === "$") runEnd++;
|
||||
return runEnd;
|
||||
}
|
||||
const closedInline = matchClosedInlineMath(source, i);
|
||||
if (closedInline !== -1) return closedInline;
|
||||
if (isOnTrailingLine(source, i + 1)) {
|
||||
const charBefore = i > 0 ? source[i - 1] : undefined;
|
||||
const validOpenerFlank = charBefore !== "\\" && charBefore !== "$" && !isAsciiAlnum(charBefore);
|
||||
if (i + 1 === source.length && validOpenerFlank) {
|
||||
state.openInlineMathPos = i;
|
||||
return null;
|
||||
}
|
||||
if (isUnclosedInlineMathCandidate(source, i)) return null;
|
||||
}
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
function stepInlineScanner(
|
||||
source: string,
|
||||
i: number,
|
||||
@@ -1219,13 +1442,8 @@ function stepInlineScanner(
|
||||
): number | null {
|
||||
const ch = source[i];
|
||||
if (ch === "\n") return lineContentStarts.get(i + 1) ?? i + 1;
|
||||
if (ch === "\\") {
|
||||
if (i + 1 === source.length) {
|
||||
state.trailingBackslash = true;
|
||||
return null;
|
||||
}
|
||||
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
|
||||
}
|
||||
if (ch === "\\") return scanInlineBackslashToken(source, i, state);
|
||||
if (ch === "$") return scanInlineDollarToken(source, i, state);
|
||||
if (ch === "`") return scanBacktickToken(source, i, state);
|
||||
if (ch === "<") return scanHtmlToken(source, i, state);
|
||||
if (ch === "[" || (ch === "!" && source[i + 1] === "[")) {
|
||||
@@ -1248,6 +1466,7 @@ function stabilizeInlineBlock(
|
||||
stack: [],
|
||||
openCode: null,
|
||||
openHtmlPos: null,
|
||||
openInlineMathPos: null,
|
||||
trailingBackslash: false,
|
||||
};
|
||||
|
||||
@@ -1259,42 +1478,74 @@ function stabilizeInlineBlock(
|
||||
const hasOpenState =
|
||||
state.openCode !== null ||
|
||||
state.openHtmlPos !== null ||
|
||||
state.openInlineMathPos !== null ||
|
||||
state.stack.length > 0 ||
|
||||
state.trailingBackslash;
|
||||
return hasOpenState ? unwindInlineState(source, state) : source;
|
||||
}
|
||||
|
||||
function stabilizeOpenFence(
|
||||
source: string,
|
||||
openFence: OpenFence,
|
||||
endsWithNewline: boolean,
|
||||
): string {
|
||||
if (!openFence.hasContent) {
|
||||
return source.slice(0, openFence.lineStart);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
const last = prevLineSlice(source, source.length);
|
||||
if (last) {
|
||||
const lastText = lineText(source, last);
|
||||
const lastQ = stripBlockquotes(lastText);
|
||||
if (
|
||||
lastQ.quoteDepth === openFence.quoteDepth &&
|
||||
(isPartialClosingFence(
|
||||
lastText,
|
||||
lastQ.offset,
|
||||
openFence.maxCloseIndent,
|
||||
openFence.char,
|
||||
openFence.length,
|
||||
) ||
|
||||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
|
||||
) {
|
||||
return source.slice(0, last.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function stabilizeOpenDisplayMath(
|
||||
source: string,
|
||||
openDisplayMath: OpenDisplayMath,
|
||||
endsWithNewline: boolean,
|
||||
): string {
|
||||
if (!openDisplayMath.hasContent) {
|
||||
return source.slice(0, openDisplayMath.withholdFrom);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
if (openDisplayMath.kind === "$$" && hasTrailingPartialDoubleDollarCloser(source)) {
|
||||
return source.slice(0, -1);
|
||||
}
|
||||
if (openDisplayMath.kind === "\\[" && hasTrailingOddBackslash(source)) {
|
||||
return source.slice(0, -1);
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function stabilizeWithCheckpoint(source: string, checkpoint: FenceScanCheckpoint | null): string {
|
||||
if (source.length === 0) return source;
|
||||
const endsWithNewline = sourceEndsWithNewline(source);
|
||||
|
||||
// 1. Fenced code blocks (top-level, quoted, or inside lists) — O(new lines) when incremental.
|
||||
const { openFence, lastClosedFenceLineStart } = resolveFenceState(source, checkpoint);
|
||||
if (openFence !== null) {
|
||||
if (!openFence.hasContent) {
|
||||
return source.slice(0, openFence.lineStart);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
const last = prevLineSlice(source, source.length);
|
||||
if (last) {
|
||||
const lastText = lineText(source, last);
|
||||
const lastQ = stripBlockquotes(lastText);
|
||||
if (
|
||||
lastQ.quoteDepth === openFence.quoteDepth &&
|
||||
(isPartialClosingFence(
|
||||
lastText,
|
||||
lastQ.offset,
|
||||
openFence.maxCloseIndent,
|
||||
openFence.char,
|
||||
openFence.length,
|
||||
) ||
|
||||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
|
||||
) {
|
||||
return source.slice(0, last.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return source;
|
||||
// 1. Fenced code blocks & display math blocks — O(new lines) when incremental.
|
||||
const { openFence, openDisplayMath, lastClosedFenceLineStart } = resolveFenceState(
|
||||
source,
|
||||
checkpoint,
|
||||
);
|
||||
if (openFence !== null) return stabilizeOpenFence(source, openFence, endsWithNewline);
|
||||
if (openDisplayMath !== null) {
|
||||
return stabilizeOpenDisplayMath(source, openDisplayMath, endsWithNewline);
|
||||
}
|
||||
|
||||
// 2. Trailing GFM table — O(table rows) backwards from EOF.
|
||||
@@ -1330,7 +1581,9 @@ export function createStreamingMarkdownStabilizer(): StreamingMarkdownStabilizer
|
||||
const checkpoint: FenceScanCheckpoint = {
|
||||
scannedPrefix: "",
|
||||
openFence: null,
|
||||
openDisplayMath: null,
|
||||
listContentIndent: 0,
|
||||
listQuoteDepth: 0,
|
||||
lastClosedFenceLineStart: -1,
|
||||
};
|
||||
return {
|
||||
|
||||
@@ -544,3 +544,119 @@ describe("stabilizeStreamingMarkdown — fences, tables, HTML, and full prefix s
|
||||
expect(incremental.stabilize("Plain\nCheck `inline")).toBe("Plain\nCheck `inline`");
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
describe("streaming Markdown math safety", () => {
|
||||
it("keeps open multiline $$, \\[, and ```math blocks in the tail without splitting mid-equation", () => {
|
||||
const blocks = ["$$\na = 1\n\nb = 2\n", "\\[\na = 1\n\nb = 2\n", "```math\na = 1\n\nb = 2\n"];
|
||||
for (const openMath of blocks) {
|
||||
const source = `Intro.\n\n${openMath}`;
|
||||
const split = splitOnce(source);
|
||||
expect(split.head).toBe("Intro.\n\n");
|
||||
expect(split.tail).toBe(openMath);
|
||||
}
|
||||
|
||||
// Even after a blank-line $$ or \[ block closes, it stays together until a following block arrives.
|
||||
const closedDollar = "Intro.\n\n$$\na = 1\n\nb = 2\n$$\n";
|
||||
expect(splitOnce(closedDollar)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail: "$$\na = 1\n\nb = 2\n$$\n",
|
||||
});
|
||||
expect(splitOnce(`${closedDollar}\nAfter.\n`)).toEqual({
|
||||
head: closedDollar + "\n",
|
||||
tail: "After.\n",
|
||||
});
|
||||
|
||||
const closedBracket = "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n";
|
||||
expect(splitOnce(closedBracket)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail: "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n".slice("Intro.\n\n".length),
|
||||
});
|
||||
expect(splitOnce(`${closedBracket}\nAfter.\n`)).toEqual({
|
||||
head: closedBracket + "\n",
|
||||
tail: "After.\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("withholds dangling math openers and partial closers without auto-closing partial TeX", () => {
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n$$")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n$$\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n\\[")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n\\[\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```math")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```math\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Formula: $")).toBe("Formula: ");
|
||||
expect(stabilizeStreamingMarkdown("Formula: \\(")).toBe("Formula: ");
|
||||
// Currency/escaped trailing dollars are not math openers.
|
||||
expect(stabilizeStreamingMarkdown("Price is US$")).toBe("Price is US$");
|
||||
expect(stabilizeStreamingMarkdown("Escaped \\$")).toBe("Escaped \\$");
|
||||
|
||||
// Partial TeX content stays literal and is never auto-closed or mangled by inline emphasis/links.
|
||||
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{")).toBe("$$\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{")).toBe("\\[\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("```math\n\\frac{a}{")).toBe("```math\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("Compute $\\alpha + *x")).toBe("Compute $\\alpha + *x");
|
||||
expect(stabilizeStreamingMarkdown("Compute \\(\\alpha + [a")).toBe("Compute \\(\\alpha + [a");
|
||||
|
||||
// Partial closing markers inside open display math are withheld until completed.
|
||||
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{b}\n$")).toBe("$$\n\\frac{a}{b}\n");
|
||||
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{b}\n\\")).toBe("\\[\n\\frac{a}{b}\n");
|
||||
|
||||
// Currency dollars do not suppress emphasis stabilization later on the line.
|
||||
expect(stabilizeStreamingMarkdown("Costs $5 and **bold")).toBe("Costs $5 and **bold**");
|
||||
// Closed inline math protects internal * / _ from emphasis stabilization.
|
||||
expect(stabilizeStreamingMarkdown("Compute $a * b$ and **bold")).toBe(
|
||||
"Compute $a * b$ and **bold**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Compute \\(a * b\\) and **bold")).toBe(
|
||||
"Compute \\(a * b\\) and **bold**",
|
||||
);
|
||||
|
||||
// An unclosed list-nested fence ends once a non-blank line exits the list container.
|
||||
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside\n$$")).toBe(
|
||||
"- ~~~sh\n echo ok\nOutside\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside **bo")).toBe(
|
||||
"- ~~~sh\n echo ok\nOutside **bo**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- ```sh\n echo ok\nOutside **bo")).toBe(
|
||||
"- ```sh\n echo ok\nOutside **bo**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- item\n - ```\n code\n back **bo")).toBe(
|
||||
"- item\n - ```\n code\n back **bo**",
|
||||
);
|
||||
// Exiting a deeper quote clears stale list indent so outer quoted code stays open.
|
||||
expect(stabilizeStreamingMarkdown("> > - item\n>\n> ~~~sh\n> echo **bo")).toBe(
|
||||
"> > - item\n>\n> ~~~sh\n> echo **bo",
|
||||
);
|
||||
});
|
||||
|
||||
it("maintains incremental stabilizer parity and idempotence across math streaming prefixes", () => {
|
||||
const sample = [
|
||||
"Inline $a * b$ and \\(c_1 + d_2\\).",
|
||||
"",
|
||||
"$$",
|
||||
"x = 1",
|
||||
"",
|
||||
"y = 2",
|
||||
"$$",
|
||||
"",
|
||||
"\\[",
|
||||
"\\int_0^1 x^2\\,dx",
|
||||
"\\]",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{i=1}^n i",
|
||||
"```",
|
||||
"",
|
||||
"Done.",
|
||||
].join("\n");
|
||||
|
||||
const incremental = createStreamingMarkdownStabilizer();
|
||||
for (let end = 0; end <= sample.length; end++) {
|
||||
const prefix = sample.slice(0, end);
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
expect(incremental.stabilize(prefix), `incremental parity at ${end}`).toBe(stabilized);
|
||||
expect(stabilizeStreamingMarkdown(stabilized), `idempotent at ${end}`).toBe(stabilized);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { Nodes, Root } from "mdast";
|
||||
import { findBlockMathSpans } from "./math";
|
||||
|
||||
export {
|
||||
createStreamingMarkdownStabilizer,
|
||||
@@ -80,12 +81,24 @@ export function createStreamingMarkdownSplitter(
|
||||
partStarts = [0];
|
||||
return;
|
||||
}
|
||||
const mathSpans = findBlockMathSpans(open);
|
||||
let settled = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
const splitAt = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
let crossesMath = false;
|
||||
let insideUnclosedMath = false;
|
||||
for (const span of mathSpans) {
|
||||
if (splitAt > span.start && splitAt < span.end) {
|
||||
crossesMath = true;
|
||||
if (span.end === Number.POSITIVE_INFINITY) insideUnclosedMath = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (insideUnclosedMath) break;
|
||||
if (!crossesMath) settled = splitAt;
|
||||
}
|
||||
if (settled === 0) return;
|
||||
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
|
||||
|
||||
@@ -103,6 +103,17 @@ export function createMarkdownStyles(
|
||||
inlineImage: { size: paragraph.lineHeight },
|
||||
image: { ...block, height: 320, resizeMode: "contain", borderRadius: 8 },
|
||||
thematicBreak: { ...block, color: theme.colors.border, height: 1 },
|
||||
math: {
|
||||
fontSize,
|
||||
color: paragraph.color,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
...block,
|
||||
textAlign: "center",
|
||||
},
|
||||
inlineMath: {
|
||||
color: paragraph.color,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -227,6 +227,9 @@ export default defineConfig({
|
||||
// Loaded by the reanimated-web-style-helpers plugin, which the dependency scan does not see.
|
||||
"react-native-web/dist/exports/StyleSheet/compiler/createReactDOMStyle",
|
||||
"react-native-web/dist/exports/StyleSheet/preprocess",
|
||||
// Dynamically imported by the excluded react-native-enriched-markdown package;
|
||||
// pre-optimizing avoids mid-suite Vite re-optimization invalidating browser imports.
|
||||
"katex",
|
||||
],
|
||||
exclude: [
|
||||
"react-native-enriched-markdown",
|
||||
|
||||
@@ -94,6 +94,12 @@ if (consumerConfig.containsKey("enableMath")) {
|
||||
} else {
|
||||
enableMath = true
|
||||
}
|
||||
if (System.getenv("PASEO_FDROID_BUILD") == "1") {
|
||||
if (enableMath) {
|
||||
logger.lifecycle("[ReactNativeEnrichedMarkdown] F-Droid build (PASEO_FDROID_BUILD=1); disabling native RaTeX math.")
|
||||
}
|
||||
enableMath = false
|
||||
}
|
||||
|
||||
// Default grammar set derived from the single source of truth,
|
||||
// vendor/grammar-versions.json (every grammar with default:true), so the compiled
|
||||
|
||||
+1
-1
@@ -931,7 +931,7 @@ object MeasurementStore {
|
||||
val method = mathMeasureHelperClass.getMethod("measure", Context::class.java, List::class.java)
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
method.invoke(null, context, requests) as List<MathMetrics>
|
||||
} catch (_: Exception) {
|
||||
} catch (_: Throwable) {
|
||||
requests.map { estimateMathFallback(it) }
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -152,7 +152,7 @@ class RendererFactory(
|
||||
// genuinely mid-line display math (e.g. `a $$x$$ b`); render it inline
|
||||
// rather than dropping it via the TextRenderer fallback.
|
||||
put(MarkdownASTNode.NodeType.LatexMathDisplay, mathInlineRenderer)
|
||||
} catch (_: Exception) {
|
||||
} catch (_: Throwable) {
|
||||
// math not available
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -154,7 +154,7 @@ object SegmentViewCreators {
|
||||
private val cachedMathContainerClass: Class<*>? by lazy {
|
||||
try {
|
||||
Class.forName("com.swmansion.enriched.markdown.segments.MathContainerView")
|
||||
} catch (_: Exception) {
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,7 @@ object SegmentViewCreators {
|
||||
}
|
||||
resolvedClass.getMethod("applyLatex", String::class.java).invoke(view, segment.latex)
|
||||
view
|
||||
} catch (e: Exception) {
|
||||
} catch (e: Throwable) {
|
||||
Log.e(TAG, "Failed to create math view", e)
|
||||
View(config.context)
|
||||
}
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ fun Spannable.replaceMathSpansWithPlaceholders(context: Context) {
|
||||
}
|
||||
} catch (_: ClassNotFoundException) {
|
||||
// Expected if the module isn't linked; silent return
|
||||
} catch (e: Exception) {
|
||||
} catch (e: Throwable) {
|
||||
Log.e("MathSpan", "Failed to replace math spans", e)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-2
@@ -2,6 +2,7 @@ package com.swmansion.enriched.markdown.renderer
|
||||
|
||||
import android.content.Context
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.util.Log
|
||||
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
|
||||
import com.swmansion.enriched.markdown.spans.MathInlineSpan
|
||||
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
|
||||
@@ -14,11 +15,15 @@ class MathInlineRenderer(
|
||||
override fun render(
|
||||
node: MarkdownASTNode,
|
||||
builder: SpannableStringBuilder,
|
||||
onLinkPress: ((String) -> Unit)?,
|
||||
onLinkPress: ((String, String) -> Unit)?,
|
||||
onLinkLongPress: ((String) -> Unit)?,
|
||||
factory: RendererFactory,
|
||||
) {
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
try {
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to load RaTeX fonts; math will fall back to raw LaTeX", e)
|
||||
}
|
||||
|
||||
val latex = extractLatex(node)
|
||||
if (latex.isEmpty()) return
|
||||
@@ -52,4 +57,8 @@ class MathInlineRenderer(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "MathInlineRenderer"
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -59,7 +59,11 @@ class MathContainerView(
|
||||
|
||||
val paddingPx = mathStyle.padding.toInt()
|
||||
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
try {
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to load RaTeX fonts; math will fall back to raw LaTeX", e)
|
||||
}
|
||||
|
||||
val mathLayoutParams =
|
||||
FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply {
|
||||
@@ -97,7 +101,7 @@ class MathContainerView(
|
||||
val displayList = RaTeXEngine.parseBlocking(latex, displayMode = true, color = mathStyle.color)
|
||||
mathView.renderer = RaTeXRenderer(displayList, mathStyle.fontSize) { RaTeXFontLoader.getTypeface(it) }
|
||||
mathView.fallbackText = null
|
||||
} catch (e: Exception) {
|
||||
} catch (e: Throwable) {
|
||||
Log.e(TAG, "Failed to render LaTeX", e)
|
||||
mathView.renderer = null
|
||||
mathView.fallbackText = "\$\$" + latex + "\$\$"
|
||||
|
||||
+2
-1
@@ -31,6 +31,7 @@ class MathInlineSpan(
|
||||
if (renderFailed) return
|
||||
|
||||
try {
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
val displayList = RaTeXEngine.parseBlocking(latex, displayMode = false, color = textColor)
|
||||
val renderer = RaTeXRenderer(displayList, fontSize) { RaTeXFontLoader.getTypeface(it) }
|
||||
|
||||
@@ -47,7 +48,7 @@ class MathInlineSpan(
|
||||
|
||||
renderer.draw(Canvas(bitmap))
|
||||
cachedBitmap = bitmap
|
||||
} catch (e: Exception) {
|
||||
} catch (e: Throwable) {
|
||||
renderFailed = true
|
||||
fallbackText = "\$" + latex + "\$"
|
||||
onLatexError?.report(latex, e.message, false)
|
||||
|
||||
+8
-1
@@ -14,7 +14,12 @@ object MathMeasureHelper {
|
||||
): List<MathMetrics> {
|
||||
if (requests.isEmpty()) return emptyList()
|
||||
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
try {
|
||||
RaTeXFontLoader.ensureLoaded(context)
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to load RaTeX fonts; using fallback metrics", e)
|
||||
return requests.map { estimateFallback(it) }
|
||||
}
|
||||
|
||||
return requests.map { request ->
|
||||
runCatching { measureSingle(context, request) }.getOrElse { estimateFallback(request) }
|
||||
@@ -54,4 +59,6 @@ object MathMeasureHelper {
|
||||
descent = h * 0.3f,
|
||||
)
|
||||
}
|
||||
|
||||
private const val TAG = "MathMeasureHelper"
|
||||
}
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.TextPaint
|
||||
import android.view.View
|
||||
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
|
||||
import com.swmansion.enriched.markdown.segments.MathContainerView
|
||||
import com.swmansion.enriched.markdown.spans.MathInlinePlaceholderSpan
|
||||
import com.swmansion.enriched.markdown.spans.MathInlineSpan
|
||||
import com.swmansion.enriched.markdown.spans.MathMeasureHelper
|
||||
import com.swmansion.enriched.markdown.spans.MathMeasureRequest
|
||||
import com.swmansion.enriched.markdown.spans.MathRenderMode
|
||||
import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.render
|
||||
import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.styleConfig
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.latexMathDisplay
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.latexMathInline
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph
|
||||
import com.swmansion.enriched.markdown.utils.text.extensions.replaceMathSpansWithPlaceholders
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(manifest = Config.NONE, sdk = [34])
|
||||
class MathRenderingFallbackTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Test fun inlineMathDegradesToRawLatexWhenNativeRatexIsUnavailable() {
|
||||
val style = styleConfig()
|
||||
val spannable = render(style, paragraph(latexMathInline("E = mc^2")))
|
||||
val spans = spannable.getSpans(0, spannable.length, MathInlineSpan::class.java)
|
||||
assertEquals(1, spans.size)
|
||||
|
||||
val span = spans.single()
|
||||
val paint = TextPaint().apply { textSize = 16f }
|
||||
val fm = Paint.FontMetricsInt()
|
||||
val width = span.getSize(paint, spannable, 0, spannable.length, fm)
|
||||
assertTrue("Fallback inline math width should be positive", width > 0)
|
||||
assertTrue("Fallback inline math font metrics should span vertically", fm.descent - fm.ascent > 0)
|
||||
|
||||
val bitmap = Bitmap.createBitmap(width.coerceAtLeast(1), 64, Bitmap.Config.ARGB_8888)
|
||||
span.draw(Canvas(bitmap), spannable, 0, spannable.length, 0f, 0, 32, 64, paint)
|
||||
}
|
||||
|
||||
@Test fun displayMathContainerDegradesToRawLatexWhenNativeRatexIsUnavailable() {
|
||||
val style = styleConfig()
|
||||
val view = MathContainerView(context, style)
|
||||
view.applyLatex("\\frac{a}{b}")
|
||||
|
||||
val widthSpec = View.MeasureSpec.makeMeasureSpec(300, View.MeasureSpec.AT_MOST)
|
||||
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
view.measure(widthSpec, heightSpec)
|
||||
assertTrue("Fallback display math width should be positive", view.measuredWidth > 0)
|
||||
assertTrue("Fallback display math height should be positive", view.measuredHeight > 0)
|
||||
|
||||
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
|
||||
val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
}
|
||||
|
||||
@Test fun mathMeasureHelperAndPlaceholdersDegradeCleanlyWhenNativeRatexIsUnavailable() {
|
||||
val request = MathMeasureRequest(fontSize = 16f, latex = "\\sum_{i=1}^n i", mode = MathRenderMode.Display)
|
||||
val metrics = MathMeasureHelper.measure(context, listOf(request))
|
||||
assertEquals(1, metrics.size)
|
||||
assertTrue(metrics[0].width > 0)
|
||||
assertTrue(metrics[0].ascent > 0f)
|
||||
assertTrue(metrics[0].descent > 0f)
|
||||
|
||||
val style = styleConfig()
|
||||
val height = MathContainerView.measureMathHeight("\\sum_{i=1}^n i", style.mathStyle, context)
|
||||
assertTrue(height > 0f)
|
||||
|
||||
val rendered = render(style, paragraph(latexMathInline("x^2"), latexMathDisplay("y^2")))
|
||||
val builder = SpannableStringBuilder(rendered)
|
||||
builder.replaceMathSpansWithPlaceholders(context)
|
||||
val placeholders = builder.getSpans(0, builder.length, MathInlinePlaceholderSpan::class.java)
|
||||
assertEquals(2, placeholders.size)
|
||||
}
|
||||
}
|
||||
+20
@@ -37,6 +37,26 @@ object MarkdownRenderTestSupport {
|
||||
val style = JavaOnlyMap()
|
||||
listOf("paragraph", "strong", "em", "strikethrough", "code", "superscript", "subscript", "highlight")
|
||||
.forEach { style.putMap(it, textElement()) }
|
||||
style.putMap(
|
||||
"math",
|
||||
JavaOnlyMap.of(
|
||||
"fontSize",
|
||||
16.0,
|
||||
"color",
|
||||
Color.BLACK,
|
||||
"backgroundColor",
|
||||
Color.TRANSPARENT,
|
||||
"padding",
|
||||
8.0,
|
||||
"marginTop",
|
||||
0.0,
|
||||
"marginBottom",
|
||||
0.0,
|
||||
"textAlign",
|
||||
"center",
|
||||
),
|
||||
)
|
||||
style.putMap("inlineMath", JavaOnlyMap.of("color", Color.BLACK))
|
||||
style.putMap("link", textElement().apply { putString("fontFamily", "serif") })
|
||||
style.putArray(
|
||||
"linkVariants",
|
||||
|
||||
+4
@@ -8,6 +8,10 @@ object TestAstFactory {
|
||||
|
||||
fun text(content: String): MarkdownASTNode = MarkdownASTNode(NodeType.Text, content = content)
|
||||
|
||||
fun latexMathInline(latex: String): MarkdownASTNode = MarkdownASTNode(NodeType.LatexMathInline, content = latex)
|
||||
|
||||
fun latexMathDisplay(latex: String): MarkdownASTNode = MarkdownASTNode(NodeType.LatexMathDisplay, content = latex)
|
||||
|
||||
/** An ordered list; [start] is the first number, as md4c reports it. */
|
||||
fun orderedList(
|
||||
vararg items: MarkdownASTNode,
|
||||
|
||||
@@ -7,6 +7,10 @@ export function isMarkdownParserReady() {
|
||||
export function preloadMarkdownParser() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
export function getLoadedKaTeX() {
|
||||
return null;
|
||||
}
|
||||
export function registerKaTeXStyleLoader(_loader) {}
|
||||
export { DEFAULT_ACCESSIBILITY_LABELS, resolveAccessibilityLabels } from "./accessibilityLabelDefaults.js";
|
||||
export { EnrichedMarkdownTextInput } from "./EnrichedMarkdownTextInput.js";
|
||||
//# sourceMappingURL=index.js.map
|
||||
@@ -2,4 +2,5 @@
|
||||
|
||||
export { EnrichedMarkdownText, default } from "./web/EnrichedMarkdownText.js";
|
||||
export { isMarkdownParserReady, preloadMarkdownParser } from "./web/parseMarkdown.js";
|
||||
export { getLoadedKaTeX, registerKaTeXStyleLoader } from "./web/katex.js";
|
||||
//# sourceMappingURL=index.web.js.map
|
||||
+36
-19
@@ -6,8 +6,8 @@ import { zeroTrailingMargins, parseErrorFallbackStyle, buildStyles } from "./sty
|
||||
import { parseMarkdown, parseMarkdownSync } from "./parseMarkdown.js";
|
||||
import { recognizeTextLinks } from "./recognizeTextLinks.js";
|
||||
import { RenderNode } from "./renderers/index.js";
|
||||
import { indexTaskItems, markInlineImages } from "./utils.js";
|
||||
import { loadKaTeX } from "./katex.js";
|
||||
import { hasMathNode, indexTaskItems, markInlineImages } from "./utils.js";
|
||||
import { getLoadedKaTeX, loadKaTeX } from "./katex.js";
|
||||
import { ENRM_TEXT_CLASS, ENRM_SELECTION_BG_VAR } from "./globalStyles.js";
|
||||
import { filterNativeOnlyProps } from "./nativeProps.js";
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
@@ -33,7 +33,7 @@ export const EnrichedMarkdownText = ({
|
||||
}) => {
|
||||
const normalizedStyle = useMemo(() => normalizeMarkdownStyle(markdownStyle), [markdownStyle]);
|
||||
const [parsed, setParsed] = useState(null);
|
||||
const [katex, setKatex] = useState(null);
|
||||
const [katex, setKatex] = useState(() => (md4cFlags.latexMath ?? true) ? getLoadedKaTeX() : null);
|
||||
const [parseError, setParseError] = useState(false);
|
||||
const {
|
||||
underline = false,
|
||||
@@ -45,6 +45,7 @@ export const EnrichedMarkdownText = ({
|
||||
preserveBlankLines = false,
|
||||
admonitions = true
|
||||
} = md4cFlags;
|
||||
const activeKatex = latexMath ? katex ?? getLoadedKaTeX() : null;
|
||||
|
||||
// A regex literal in JSX is a new object every render; re-parse only when its text changes.
|
||||
const linkRecognitionRef = useRef(linkRecognition);
|
||||
@@ -83,10 +84,22 @@ export const EnrichedMarkdownText = ({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, parsed]);
|
||||
useEffect(() => {
|
||||
if (immediate && (!latexMath || katex)) return;
|
||||
if (immediate) {
|
||||
if (!latexMath || activeKatex || !immediate.ast || !hasMathNode(immediate.ast)) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
loadKaTeX().then(katexInstance => {
|
||||
if (!cancelled && katexInstance) {
|
||||
setKatex(katexInstance);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
let cancelled = false;
|
||||
const katexPromise = latexMath ? loadKaTeX() : Promise.resolve(null);
|
||||
Promise.all([parseMarkdown(markdown, {
|
||||
parseMarkdown(markdown, {
|
||||
underline,
|
||||
latexMath,
|
||||
superscript,
|
||||
@@ -95,17 +108,21 @@ export const EnrichedMarkdownText = ({
|
||||
hardSoftBreaks,
|
||||
preserveBlankLines,
|
||||
admonitions
|
||||
}), katexPromise]).then(([result, katexInstance]) => {
|
||||
if (!cancelled) {
|
||||
indexTaskItems(result);
|
||||
markInlineImages(result);
|
||||
setParseError(false);
|
||||
}).then(async result => {
|
||||
if (cancelled) return;
|
||||
indexTaskItems(result);
|
||||
markInlineImages(result);
|
||||
const needsKatex = latexMath && hasMathNode(result);
|
||||
const katexInstance = needsKatex ? getLoadedKaTeX() ?? (await loadKaTeX()) : getLoadedKaTeX();
|
||||
if (cancelled) return;
|
||||
setParseError(false);
|
||||
if (katexInstance) {
|
||||
setKatex(katexInstance);
|
||||
setParsed({
|
||||
markdown,
|
||||
ast: recognizeTextLinks(result, linkRecognitionRef.current?.text, linkRecognitionRef.current?.inlineCode)
|
||||
});
|
||||
}
|
||||
setParsed({
|
||||
markdown,
|
||||
ast: recognizeTextLinks(result, linkRecognitionRef.current?.text, linkRecognitionRef.current?.inlineCode)
|
||||
});
|
||||
}).catch(error => {
|
||||
if (!cancelled) {
|
||||
if (__DEV__) {
|
||||
@@ -119,7 +136,7 @@ export const EnrichedMarkdownText = ({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, immediate, katex]);
|
||||
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, immediate, activeKatex]);
|
||||
const callbacks = useMemo(() => ({
|
||||
onLinkPress,
|
||||
onLinkLongPress,
|
||||
@@ -128,10 +145,10 @@ export const EnrichedMarkdownText = ({
|
||||
onCodeBlockPress
|
||||
}), [onLinkPress, onLinkLongPress, onImagePress, onTaskListItemPress, onCodeBlockPress]);
|
||||
const capabilities = useMemo(() => ({
|
||||
katex,
|
||||
katex: activeKatex,
|
||||
enableTaskListItemToggle,
|
||||
renderers
|
||||
}), [katex, enableTaskListItemToggle, renderers]);
|
||||
}), [activeKatex, enableTaskListItemToggle, renderers]);
|
||||
const lastChildStyle = useMemo(() => allowTrailingMargin ? normalizedStyle : zeroTrailingMargins(normalizedStyle), [normalizedStyle, allowTrailingMargin]);
|
||||
const styles = useMemo(() => buildStyles(normalizedStyle), [normalizedStyle]);
|
||||
const lastChildStyles = useMemo(() => buildStyles(lastChildStyle), [lastChildStyle]);
|
||||
@@ -180,4 +197,4 @@ export const EnrichedMarkdownText = ({
|
||||
});
|
||||
};
|
||||
export default EnrichedMarkdownText;
|
||||
//# sourceMappingURL=EnrichedMarkdownText.js.map
|
||||
//# sourceMappingURL=EnrichedMarkdownText.js.map
|
||||
|
||||
+60
-13
@@ -1,22 +1,69 @@
|
||||
"use strict";
|
||||
|
||||
let loadedKatex = null;
|
||||
let katexLoadPromise = null;
|
||||
let styleLoader = null;
|
||||
let styleLoadPromise = null;
|
||||
let stylesReady = true;
|
||||
|
||||
/** Lazily loads KaTeX. Resolves to null if not installed. */
|
||||
function ensureKaTeXStyles() {
|
||||
if (!styleLoader) {
|
||||
stylesReady = true;
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!styleLoadPromise) {
|
||||
styleLoadPromise = Promise.resolve()
|
||||
.then(() => styleLoader())
|
||||
.then(() => {
|
||||
stylesReady = true;
|
||||
})
|
||||
.catch((error) => {
|
||||
styleLoadPromise = null;
|
||||
stylesReady = false;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return styleLoadPromise;
|
||||
}
|
||||
|
||||
/** Synchronously returns the cached KaTeX instance once loaded and styled, or null. */
|
||||
export function getLoadedKaTeX() {
|
||||
return loadedKatex && stylesReady ? loadedKatex : null;
|
||||
}
|
||||
|
||||
/** Registers a lazy stylesheet loader invoked alongside KaTeX loading. */
|
||||
export function registerKaTeXStyleLoader(loader) {
|
||||
styleLoader = loader;
|
||||
styleLoadPromise = null;
|
||||
katexLoadPromise = null;
|
||||
stylesReady = false;
|
||||
}
|
||||
|
||||
/** Lazily loads KaTeX and any registered stylesheet. Resolves to null if unavailable. */
|
||||
export function loadKaTeX() {
|
||||
if (loadedKatex && stylesReady) {
|
||||
return Promise.resolve(loadedKatex);
|
||||
}
|
||||
if (!katexLoadPromise) {
|
||||
let instance = null;
|
||||
try {
|
||||
const mod = require('katex');
|
||||
const candidate = mod?.default ?? mod;
|
||||
if (typeof candidate?.renderToString === 'function') {
|
||||
instance = candidate;
|
||||
}
|
||||
} catch {
|
||||
// katex not installed — math rendering will be skipped
|
||||
}
|
||||
katexLoadPromise = Promise.resolve(instance);
|
||||
katexLoadPromise = Promise.all([
|
||||
loadedKatex ? Promise.resolve({ default: loadedKatex }) : import('katex'),
|
||||
ensureKaTeXStyles(),
|
||||
])
|
||||
.then(([mod]) => {
|
||||
const candidate = mod?.default ?? mod;
|
||||
if (typeof candidate?.renderToString === 'function') {
|
||||
loadedKatex = candidate;
|
||||
return candidate;
|
||||
}
|
||||
katexLoadPromise = null;
|
||||
return null;
|
||||
})
|
||||
.catch(() => {
|
||||
// katex or its stylesheet failed to load — fall back to raw LaTeX and allow retry
|
||||
katexLoadPromise = null;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return katexLoadPromise;
|
||||
}
|
||||
//# sourceMappingURL=katex.js.map
|
||||
//# sourceMappingURL=katex.js.map
|
||||
|
||||
+51
-8
@@ -2,6 +2,43 @@
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
const KATEX_RENDER_CACHE_LIMIT = 256;
|
||||
const renderCacheByInstance = new WeakMap();
|
||||
function renderKaTeXHtml(katex, content, displayMode) {
|
||||
let cache = renderCacheByInstance.get(katex);
|
||||
if (!cache) {
|
||||
cache = new Map();
|
||||
renderCacheByInstance.set(katex, cache);
|
||||
}
|
||||
const key = `${displayMode ? 1 : 0}:${content}`;
|
||||
const cached = cache.get(key);
|
||||
if (cached !== undefined) {
|
||||
cache.delete(key);
|
||||
cache.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
try {
|
||||
const html = katex.renderToString(content, {
|
||||
output: 'htmlAndMathml',
|
||||
displayMode,
|
||||
throwOnError: false,
|
||||
trust: false,
|
||||
maxSize: 20,
|
||||
maxExpand: 1000,
|
||||
strict: 'ignore'
|
||||
});
|
||||
if (cache.size >= KATEX_RENDER_CACHE_LIMIT) {
|
||||
const oldestKey = cache.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
cache.set(key, html);
|
||||
return html;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export function KaTeXRenderer({
|
||||
content,
|
||||
katex,
|
||||
@@ -9,24 +46,28 @@ export function KaTeXRenderer({
|
||||
style
|
||||
}) {
|
||||
const delimiter = displayMode ? '$$' : '$';
|
||||
const mathSource = displayMode ? `$$\n${content.trim()}\n$$` : `$${content}$`;
|
||||
const html = useMemo(() => {
|
||||
if (!katex) return null;
|
||||
return katex.renderToString(content, {
|
||||
output: 'mathml',
|
||||
displayMode,
|
||||
throwOnError: false,
|
||||
trust: false
|
||||
});
|
||||
return renderKaTeXHtml(katex, content, displayMode);
|
||||
}, [katex, content, displayMode]);
|
||||
const displayStyle = displayMode ? {
|
||||
...style,
|
||||
display: 'block',
|
||||
whiteSpace: 'pre-wrap'
|
||||
maxWidth: '100%',
|
||||
overflowX: 'auto',
|
||||
overflowY: 'hidden',
|
||||
boxSizing: 'border-box',
|
||||
...(html ? null : {
|
||||
whiteSpace: 'pre-wrap'
|
||||
})
|
||||
} : style;
|
||||
if (!html) {
|
||||
return /*#__PURE__*/_jsx("span", {
|
||||
role: "math",
|
||||
"aria-label": content,
|
||||
"data-display": displayMode ? 'block' : 'inline',
|
||||
"data-math-source": mathSource,
|
||||
style: displayStyle,
|
||||
children: `${delimiter}${content}${delimiter}`
|
||||
});
|
||||
@@ -34,10 +75,12 @@ export function KaTeXRenderer({
|
||||
return /*#__PURE__*/_jsx("span", {
|
||||
role: "math",
|
||||
"aria-label": content,
|
||||
"data-display": displayMode ? 'block' : 'inline',
|
||||
"data-math-source": mathSource,
|
||||
style: displayStyle,
|
||||
dangerouslySetInnerHTML: {
|
||||
__html: html
|
||||
}
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=KaTeXRenderer.js.map
|
||||
//# sourceMappingURL=KaTeXRenderer.js.map
|
||||
|
||||
@@ -60,4 +60,12 @@ function stampInlineImages(node) {
|
||||
}
|
||||
node.children?.forEach(stampInlineImages);
|
||||
}
|
||||
|
||||
/** Returns true when the parsed AST contains at least one LaTeX math node. */
|
||||
export function hasMathNode(node) {
|
||||
if (node.type === 'LatexMathInline' || node.type === 'LatexMathDisplay') {
|
||||
return true;
|
||||
}
|
||||
return node.children?.some(hasMathNode) ?? false;
|
||||
}
|
||||
//# sourceMappingURL=utils.js.map
|
||||
@@ -5,6 +5,8 @@ export type { LinkContextMenuItem, LinkRecognition, } from './types/MarkdownText
|
||||
export { default as EnrichedMarkdownText } from './native/EnrichedMarkdownText';
|
||||
export declare function isMarkdownParserReady(): boolean;
|
||||
export declare function preloadMarkdownParser(): Promise<void>;
|
||||
export declare function getLoadedKaTeX(): null;
|
||||
export declare function registerKaTeXStyleLoader(_loader: () => Promise<void> | void): void;
|
||||
export type { EnrichedMarkdownTextProps, StreamingConfig, MarkdownStyle, Md4cFlags, ContextMenuItem as TextContextMenuItem, SelectionMenuConfig as TextSelectionMenuConfig, SelectionMenuPluralLabels as TextSelectionMenuPluralLabels, } from './native/EnrichedMarkdownText';
|
||||
export type { LinkPressEvent, LinkLongPressEvent, ImagePressEvent, TaskListItemPressEvent, CopyPressEvent, LatexErrorEvent, CodeBlockPressEvent, } from './types/events';
|
||||
export type { AccessibilityLabels, ResolvedAccessibilityLabels, } from './types/AccessibilityLabels';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export type { MarkdownRenderers, CodeBlockRendererProps, BlockquoteRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
|
||||
export { EnrichedMarkdownText, default } from './web/EnrichedMarkdownText';
|
||||
export { isMarkdownParserReady, preloadMarkdownParser } from './web/parseMarkdown';
|
||||
export { getLoadedKaTeX, registerKaTeXStyleLoader, type KaTeXInstance, type KaTeXRenderOptions } from './web/katex';
|
||||
export type { EnrichedMarkdownTextProps } from './types/MarkdownTextProps.web';
|
||||
export type { MarkdownStyle, Md4cFlags } from './types/MarkdownStyle';
|
||||
export type { LinkPressEvent, LinkLongPressEvent, ImagePressEvent, TaskListItemPressEvent, CopyPressEvent, LatexErrorEvent, CodeBlockPressEvent, } from './types/events';
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
export interface KaTeXInstance {
|
||||
renderToString(expression: string, options?: {
|
||||
displayMode?: boolean;
|
||||
throwOnError?: boolean;
|
||||
trust?: boolean;
|
||||
output?: 'html' | 'mathml' | 'htmlAndMathml';
|
||||
}): string;
|
||||
export interface KaTeXRenderOptions {
|
||||
displayMode?: boolean;
|
||||
throwOnError?: boolean;
|
||||
trust?: boolean;
|
||||
maxSize?: number;
|
||||
maxExpand?: number;
|
||||
strict?: boolean | 'ignore' | 'warn' | 'error';
|
||||
output?: 'html' | 'mathml' | 'htmlAndMathml';
|
||||
}
|
||||
/** Lazily loads KaTeX. Resolves to null if not installed. */
|
||||
export interface KaTeXInstance {
|
||||
renderToString(expression: string, options?: KaTeXRenderOptions): string;
|
||||
}
|
||||
/** Synchronously returns the cached KaTeX instance once loaded, or null. */
|
||||
export declare function getLoadedKaTeX(): KaTeXInstance | null;
|
||||
/** Registers a lazy stylesheet loader invoked alongside KaTeX loading. */
|
||||
export declare function registerKaTeXStyleLoader(loader: () => Promise<void> | void): void;
|
||||
/** Lazily loads KaTeX and any registered stylesheet. Resolves to null if unavailable. */
|
||||
export declare function loadKaTeX(): Promise<KaTeXInstance | null>;
|
||||
//# sourceMappingURL=katex.d.ts.map
|
||||
//# sourceMappingURL=katex.d.ts.map
|
||||
|
||||
@@ -18,4 +18,6 @@ export declare function indexTaskItems(node: ASTNode, counter?: {
|
||||
* Mutates the AST in-place (safe: called once on the freshly-parsed result).
|
||||
*/
|
||||
export declare function markInlineImages(node: ASTNode): void;
|
||||
/** Returns true when the parsed AST contains at least one LaTeX math node. */
|
||||
export declare function hasMathNode(node: ASTNode): boolean;
|
||||
//# sourceMappingURL=utils.d.ts.map
|
||||
@@ -245,7 +245,7 @@ if (enableMath === undefined && process.env.ENRICHED_MARKDOWN_ENABLE_MATH) {
|
||||
}
|
||||
|
||||
enableCodeHighlight = enableCodeHighlight !== false;
|
||||
enableMath = enableMath !== false;
|
||||
enableMath = enableMath !== false && process.env.PASEO_FDROID_BUILD !== '1';
|
||||
|
||||
if (!enableCodeHighlight && !enableMath) {
|
||||
console.log(`${LOG} both code highlighting and math are disabled via package.json ("enriched-markdown"); skipping postinstall.`);
|
||||
@@ -279,7 +279,9 @@ if (enableCodeHighlight) {
|
||||
}
|
||||
|
||||
// RaTeX XCFramework + Swift sources + fonts (iOS math)
|
||||
if (!enableMath) {
|
||||
if (process.env.PASEO_FDROID_BUILD === '1') {
|
||||
console.log(`${LOG} F-Droid build (PASEO_FDROID_BUILD=1); skipping RaTeX iOS assets.`);
|
||||
} else if (!enableMath) {
|
||||
console.log(`${LOG} math disabled via package.json ("enriched-markdown".enableMath = false); skipping RaTeX.`);
|
||||
} else if (fs.existsSync(ratexManifest) && fs.existsSync(vendorRatex)) {
|
||||
const r2 = spawnSync(process.execPath, [
|
||||
|
||||
@@ -17,6 +17,12 @@ export function isMarkdownParserReady(): boolean {
|
||||
export function preloadMarkdownParser(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
export function getLoadedKaTeX(): null {
|
||||
return null;
|
||||
}
|
||||
export function registerKaTeXStyleLoader(
|
||||
_loader: () => Promise<void> | void
|
||||
): void {}
|
||||
export type {
|
||||
EnrichedMarkdownTextProps,
|
||||
StreamingConfig,
|
||||
|
||||
@@ -9,6 +9,12 @@ export {
|
||||
isMarkdownParserReady,
|
||||
preloadMarkdownParser,
|
||||
} from './web/parseMarkdown';
|
||||
export {
|
||||
getLoadedKaTeX,
|
||||
registerKaTeXStyleLoader,
|
||||
type KaTeXInstance,
|
||||
type KaTeXRenderOptions,
|
||||
} from './web/katex';
|
||||
export type { EnrichedMarkdownTextProps } from './types/MarkdownTextProps.web';
|
||||
export type { MarkdownStyle, Md4cFlags } from './types/MarkdownStyle';
|
||||
export type {
|
||||
|
||||
@@ -16,8 +16,8 @@ import { parseMarkdown, parseMarkdownSync } from './parseMarkdown';
|
||||
import { recognizeTextLinks } from './recognizeTextLinks';
|
||||
import { RenderNode } from './renderers';
|
||||
import type { ASTNode, RendererCallbacks, RenderCapabilities } from './types';
|
||||
import { indexTaskItems, markInlineImages } from './utils';
|
||||
import { loadKaTeX } from './katex';
|
||||
import { hasMathNode, indexTaskItems, markInlineImages } from './utils';
|
||||
import { getLoadedKaTeX, loadKaTeX } from './katex';
|
||||
import type { KaTeXInstance } from './katex';
|
||||
import { ENRM_TEXT_CLASS, ENRM_SELECTION_BG_VAR } from './globalStyles';
|
||||
import { filterNativeOnlyProps } from './nativeProps';
|
||||
@@ -51,7 +51,9 @@ export const EnrichedMarkdownText = ({
|
||||
ast: ASTNode;
|
||||
markdown: string;
|
||||
} | null>(null);
|
||||
const [katex, setKatex] = useState<KaTeXInstance | null>(null);
|
||||
const [katex, setKatex] = useState<KaTeXInstance | null>(() =>
|
||||
(md4cFlags.latexMath ?? true) ? getLoadedKaTeX() : null
|
||||
);
|
||||
const [parseError, setParseError] = useState<boolean>(false);
|
||||
|
||||
const {
|
||||
@@ -65,6 +67,8 @@ export const EnrichedMarkdownText = ({
|
||||
admonitions = true,
|
||||
} = md4cFlags;
|
||||
|
||||
const activeKatex = latexMath ? (katex ?? getLoadedKaTeX()) : null;
|
||||
|
||||
// A regex literal in JSX is a new object every render; re-parse only when its text changes.
|
||||
const linkRecognitionRef = useRef(linkRecognition);
|
||||
linkRecognitionRef.current = linkRecognition;
|
||||
@@ -117,40 +121,60 @@ export const EnrichedMarkdownText = ({
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (immediate && (!latexMath || katex)) return;
|
||||
if (immediate) {
|
||||
if (
|
||||
!latexMath ||
|
||||
activeKatex ||
|
||||
!immediate.ast ||
|
||||
!hasMathNode(immediate.ast)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
loadKaTeX().then((katexInstance) => {
|
||||
if (!cancelled && katexInstance) {
|
||||
setKatex(katexInstance);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const katexPromise = latexMath ? loadKaTeX() : Promise.resolve(null);
|
||||
parseMarkdown(markdown, {
|
||||
underline,
|
||||
latexMath,
|
||||
superscript,
|
||||
subscript,
|
||||
highlight,
|
||||
hardSoftBreaks,
|
||||
preserveBlankLines,
|
||||
admonitions,
|
||||
})
|
||||
.then(async (result) => {
|
||||
if (cancelled) return;
|
||||
indexTaskItems(result);
|
||||
markInlineImages(result);
|
||||
const needsKatex = latexMath && hasMathNode(result);
|
||||
const katexInstance = needsKatex
|
||||
? (getLoadedKaTeX() ?? (await loadKaTeX()))
|
||||
: getLoadedKaTeX();
|
||||
if (cancelled) return;
|
||||
|
||||
Promise.all([
|
||||
parseMarkdown(markdown, {
|
||||
underline,
|
||||
latexMath,
|
||||
superscript,
|
||||
subscript,
|
||||
highlight,
|
||||
hardSoftBreaks,
|
||||
preserveBlankLines,
|
||||
admonitions,
|
||||
}),
|
||||
katexPromise,
|
||||
])
|
||||
.then(([result, katexInstance]) => {
|
||||
if (!cancelled) {
|
||||
indexTaskItems(result);
|
||||
markInlineImages(result);
|
||||
|
||||
setParseError(false);
|
||||
setParseError(false);
|
||||
if (katexInstance) {
|
||||
setKatex(katexInstance);
|
||||
setParsed({
|
||||
markdown,
|
||||
ast: recognizeTextLinks(
|
||||
result,
|
||||
linkRecognitionRef.current?.text,
|
||||
linkRecognitionRef.current?.inlineCode
|
||||
),
|
||||
});
|
||||
}
|
||||
setParsed({
|
||||
markdown,
|
||||
ast: recognizeTextLinks(
|
||||
result,
|
||||
linkRecognitionRef.current?.text,
|
||||
linkRecognitionRef.current?.inlineCode
|
||||
),
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) {
|
||||
@@ -180,7 +204,7 @@ export const EnrichedMarkdownText = ({
|
||||
textLinkKey,
|
||||
inlineCodeLinkKey,
|
||||
immediate,
|
||||
katex,
|
||||
activeKatex,
|
||||
]);
|
||||
|
||||
const callbacks = useMemo<RendererCallbacks>(
|
||||
@@ -201,8 +225,8 @@ export const EnrichedMarkdownText = ({
|
||||
);
|
||||
|
||||
const capabilities = useMemo<RenderCapabilities>(
|
||||
() => ({ katex, enableTaskListItemToggle, renderers }),
|
||||
[katex, enableTaskListItemToggle, renderers]
|
||||
() => ({ katex: activeKatex, enableTaskListItemToggle, renderers }),
|
||||
[activeKatex, enableTaskListItemToggle, renderers]
|
||||
);
|
||||
|
||||
const lastChildStyle = useMemo(
|
||||
|
||||
@@ -1,31 +1,82 @@
|
||||
export interface KaTeXInstance {
|
||||
renderToString(
|
||||
expression: string,
|
||||
options?: {
|
||||
displayMode?: boolean;
|
||||
throwOnError?: boolean;
|
||||
trust?: boolean;
|
||||
output?: 'html' | 'mathml' | 'htmlAndMathml';
|
||||
}
|
||||
): string;
|
||||
export interface KaTeXRenderOptions {
|
||||
displayMode?: boolean;
|
||||
throwOnError?: boolean;
|
||||
trust?: boolean;
|
||||
maxSize?: number;
|
||||
maxExpand?: number;
|
||||
strict?: boolean | 'ignore' | 'warn' | 'error';
|
||||
output?: 'html' | 'mathml' | 'htmlAndMathml';
|
||||
}
|
||||
|
||||
let katexLoadPromise: Promise<KaTeXInstance | null> | null = null;
|
||||
export interface KaTeXInstance {
|
||||
renderToString(expression: string, options?: KaTeXRenderOptions): string;
|
||||
}
|
||||
|
||||
/** Lazily loads KaTeX. Resolves to null if not installed. */
|
||||
let loadedKatex: KaTeXInstance | null = null;
|
||||
let katexLoadPromise: Promise<KaTeXInstance | null> | null = null;
|
||||
let styleLoader: (() => Promise<void> | void) | null = null;
|
||||
let styleLoadPromise: Promise<void> | null = null;
|
||||
let stylesReady = true;
|
||||
|
||||
function ensureKaTeXStyles(): Promise<void> {
|
||||
if (!styleLoader) {
|
||||
stylesReady = true;
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!styleLoadPromise) {
|
||||
styleLoadPromise = Promise.resolve()
|
||||
.then(() => styleLoader!())
|
||||
.then(() => {
|
||||
stylesReady = true;
|
||||
})
|
||||
.catch((error) => {
|
||||
styleLoadPromise = null;
|
||||
stylesReady = false;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return styleLoadPromise;
|
||||
}
|
||||
|
||||
/** Synchronously returns the cached KaTeX instance once loaded and styled, or null. */
|
||||
export function getLoadedKaTeX(): KaTeXInstance | null {
|
||||
return loadedKatex && stylesReady ? loadedKatex : null;
|
||||
}
|
||||
|
||||
/** Registers a lazy stylesheet loader invoked alongside KaTeX loading. */
|
||||
export function registerKaTeXStyleLoader(
|
||||
loader: () => Promise<void> | void
|
||||
): void {
|
||||
styleLoader = loader;
|
||||
styleLoadPromise = null;
|
||||
katexLoadPromise = null;
|
||||
stylesReady = false;
|
||||
}
|
||||
|
||||
/** Lazily loads KaTeX and any registered stylesheet. Resolves to null if unavailable. */
|
||||
export function loadKaTeX(): Promise<KaTeXInstance | null> {
|
||||
if (loadedKatex && stylesReady) {
|
||||
return Promise.resolve(loadedKatex);
|
||||
}
|
||||
if (!katexLoadPromise) {
|
||||
let instance: KaTeXInstance | null = null;
|
||||
try {
|
||||
const mod = require('katex');
|
||||
const candidate = (mod?.default ?? mod) as KaTeXInstance | null;
|
||||
if (typeof candidate?.renderToString === 'function') {
|
||||
instance = candidate;
|
||||
}
|
||||
} catch {
|
||||
// katex not installed — math rendering will be skipped
|
||||
}
|
||||
katexLoadPromise = Promise.resolve(instance);
|
||||
katexLoadPromise = Promise.all([
|
||||
loadedKatex ? Promise.resolve({ default: loadedKatex }) : import('katex'),
|
||||
ensureKaTeXStyles(),
|
||||
])
|
||||
.then(([mod]) => {
|
||||
const candidate = (mod?.default ?? mod) as KaTeXInstance | null;
|
||||
if (typeof candidate?.renderToString === 'function') {
|
||||
loadedKatex = candidate;
|
||||
return candidate;
|
||||
}
|
||||
katexLoadPromise = null;
|
||||
return null;
|
||||
})
|
||||
.catch(() => {
|
||||
// katex or its stylesheet failed to load — fall back to raw LaTeX and allow retry
|
||||
katexLoadPromise = null;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return katexLoadPromise;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,51 @@ interface KaTeXRendererProps {
|
||||
style: CSSProperties;
|
||||
}
|
||||
|
||||
const KATEX_RENDER_CACHE_LIMIT = 256;
|
||||
const renderCacheByInstance = new WeakMap<KaTeXInstance, Map<string, string>>();
|
||||
|
||||
function renderKaTeXHtml(
|
||||
katex: KaTeXInstance,
|
||||
content: string,
|
||||
displayMode: boolean
|
||||
): string | null {
|
||||
let cache = renderCacheByInstance.get(katex);
|
||||
if (!cache) {
|
||||
cache = new Map<string, string>();
|
||||
renderCacheByInstance.set(katex, cache);
|
||||
}
|
||||
|
||||
const key = `${displayMode ? 1 : 0}:${content}`;
|
||||
const cached = cache.get(key);
|
||||
if (cached !== undefined) {
|
||||
cache.delete(key);
|
||||
cache.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
const html = katex.renderToString(content, {
|
||||
output: 'htmlAndMathml',
|
||||
displayMode,
|
||||
throwOnError: false,
|
||||
trust: false,
|
||||
maxSize: 20,
|
||||
maxExpand: 1000,
|
||||
strict: 'ignore',
|
||||
});
|
||||
if (cache.size >= KATEX_RENDER_CACHE_LIMIT) {
|
||||
const oldestKey = cache.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
cache.set(key, html);
|
||||
return html;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function KaTeXRenderer({
|
||||
content,
|
||||
katex,
|
||||
@@ -15,24 +60,36 @@ export function KaTeXRenderer({
|
||||
style,
|
||||
}: KaTeXRendererProps) {
|
||||
const delimiter = displayMode ? '$$' : '$';
|
||||
const mathSource = displayMode
|
||||
? `$$\n${content.trim()}\n$$`
|
||||
: `$${content}$`;
|
||||
|
||||
const html = useMemo(() => {
|
||||
if (!katex) return null;
|
||||
return katex.renderToString(content, {
|
||||
output: 'mathml',
|
||||
displayMode,
|
||||
throwOnError: false,
|
||||
trust: false,
|
||||
});
|
||||
return renderKaTeXHtml(katex, content, displayMode);
|
||||
}, [katex, content, displayMode]);
|
||||
|
||||
const displayStyle = displayMode
|
||||
? { ...style, display: 'block' as const, whiteSpace: 'pre-wrap' as const }
|
||||
const displayStyle: CSSProperties = displayMode
|
||||
? {
|
||||
...style,
|
||||
display: 'block',
|
||||
maxWidth: '100%',
|
||||
overflowX: 'auto',
|
||||
overflowY: 'hidden',
|
||||
boxSizing: 'border-box',
|
||||
...(html ? null : { whiteSpace: 'pre-wrap' }),
|
||||
}
|
||||
: style;
|
||||
|
||||
if (!html) {
|
||||
return (
|
||||
<span role="math" aria-label={content} style={displayStyle}>
|
||||
<span
|
||||
role="math"
|
||||
aria-label={content}
|
||||
data-display={displayMode ? 'block' : 'inline'}
|
||||
data-math-source={mathSource}
|
||||
style={displayStyle}
|
||||
>
|
||||
{`${delimiter}${content}${delimiter}`}
|
||||
</span>
|
||||
);
|
||||
@@ -42,6 +99,8 @@ export function KaTeXRenderer({
|
||||
<span
|
||||
role="math"
|
||||
aria-label={content}
|
||||
data-display={displayMode ? 'block' : 'inline'}
|
||||
data-math-source={mathSource}
|
||||
style={displayStyle}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
|
||||
@@ -63,3 +63,11 @@ function stampInlineImages(node: ASTNode): void {
|
||||
}
|
||||
node.children?.forEach(stampInlineImages);
|
||||
}
|
||||
|
||||
/** Returns true when the parsed AST contains at least one LaTeX math node. */
|
||||
export function hasMathNode(node: ASTNode): boolean {
|
||||
if (node.type === 'LatexMathInline' || node.type === 'LatexMathDisplay') {
|
||||
return true;
|
||||
}
|
||||
return node.children?.some(hasMathNode) ?? false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user