Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

test: catch copied KaTeX stylesheet drift during upgrades (#11232)

Shahmir Varqhae353e2744d31
diff --git a/frontend/package.json b/frontend/package.json
index 9fe7ab8ab5..33e1cb1745 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -182,7 +182,8 @@
"build:islands": "cross-env VITE_MARIMO_ISLANDS=true vite --config islands/vite.config.mts build",
"preview:islands": "cross-env VITE_MARIMO_VERSION='0.4.6' VITE_MARIMO_ISLANDS=true vite --config islands/vite.config.mts build",
"storybook": "storybook dev -p 6006",
- "build-storybook": "storybook build"
+ "build-storybook": "storybook build",
+ "sync-katex-css": "node --experimental-strip-types scripts/sync-katex-css.ts"
},
"peerDependencies": {
"react": "^17 || ^18 || ^19",
diff --git a/frontend/scripts/katex-css.ts b/frontend/scripts/katex-css.ts
new file mode 100644
index 0000000000..a4114eca04
--- /dev/null
+++ b/frontend/scripts/katex-css.ts
@@ -0,0 +1,196 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { format } from "oxfmt";
+import postcss, { type Rule } from "postcss";
+import stylelint from "stylelint";
+
+const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
+export const stylesheetPath = path.resolve(
+ scriptDirectory,
+ "../src/css/katex.min.css",
+);
+const require = createRequire(import.meta.url);
+
+export function readUpstreamCss(): Promise<string> {
+ return readFile(require.resolve("katex/dist/katex.min.css"), "utf8");
+}
+
+const header = `/*
+ * Generated from the installed katex/dist/katex.min.css.
+ * Run \`pnpm sync-katex-css\` from the repository root or frontend to regenerate.
+ * Do not edit this file directly; update scripts/katex-css.ts for local overrides.
+ *
+ * Documented marimo overrides:
+ * - Remove @font-face: font declarations live in katex-fonts.css.
+ * - Preserve em units so scripts, rules, and spacing scale with surrounding math.
+ * - Replace .katex's font shorthand with its font-family, font-size: 110%,
+ * font-style: normal, and line-height: inherit to follow surrounding text size
+ * and keep math upright in blockquotes.
+ * - Right-align display equation tags.
+ * - Reset equation counters on each display block as well as body.
+ * - Preserve duplicate SVG rules in their upstream order and scope, with a
+ * targeted stylelint exemption so their cascade remains intact.
+ * Formatting and syntax normalization use oxfmt and stylelint; adjacent exact
+ * duplicate declarations left by vendor-prefix normalization are removed.
+ */
+
+/* stylelint-disable unit-allowed-list -- KaTeX sizes are relative to the math. */
+
+`;
+
+async function formatCss(css: string): Promise<string> {
+ const result = await format("katex.min.css", css);
+ if (result.errors.length > 0) {
+ throw new Error(
+ `Cannot format KaTeX CSS: ${JSON.stringify(result.errors)}`,
+ );
+ }
+ return result.code;
+}
+
+export async function generateKatexCss(upstream: string): Promise<string> {
+ const root = postcss.parse(await formatCss(upstream));
+ root.walkAtRules("font-face", (rule) => {
+ rule.remove();
+ });
+
+ function findRule(selector: string): Rule {
+ const rules: Rule[] = [];
+ root.walkRules(selector, (rule) => {
+ rules.push(rule);
+ });
+ if (rules.length !== 1) {
+ throw new Error(
+ `Expected one upstream ${selector} rule; review KaTeX overrides in frontend/scripts/katex-css.ts.`,
+ );
+ }
+ return rules[0];
+ }
+
+ const math = findRule(".katex");
+ const font = math.nodes.find(
+ (node) => node.type === "decl" && node.prop === "font",
+ );
+ if (
+ !font ||
+ font.type !== "decl" ||
+ font.value.replace(/\s+/g, " ").trim() !==
+ "normal 1.21em KaTeX_Main, Times New Roman, serif"
+ ) {
+ throw new Error(
+ "Upstream KaTeX font shorthand changed; review the font override in frontend/scripts/katex-css.ts.",
+ );
+ }
+ font.replaceWith(
+ postcss.decl({
+ prop: "font-family",
+ value: '"KaTeX_Main", "Times New Roman", serif',
+ }),
+ postcss.decl({ prop: "font-size", value: "110%" }),
+ postcss.decl({ prop: "font-style", value: "normal" }),
+ );
+
+ function replaceValue(
+ rule: Rule,
+ property: string,
+ expected: string,
+ value: string,
+ ) {
+ const declarations = rule.nodes.filter(
+ (node) => node.type === "decl" && node.prop === property,
+ );
+ const declaration = declarations[0];
+ if (
+ declarations.length !== 1 ||
+ declaration.type !== "decl" ||
+ declaration.value !== expected
+ ) {
+ throw new Error(
+ `Upstream ${rule.selector} ${property} changed; review overrides in frontend/scripts/katex-css.ts.`,
+ );
+ }
+ declaration.value = value;
+ }
+ replaceValue(math, "line-height", "1.2", "inherit");
+ const tag = findRule(".katex-display > .katex > .katex-html > .katex-tag");
+ if (
+ tag.nodes.some((node) => node.type === "decl" && node.prop === "text-align")
+ ) {
+ throw new Error(
+ "Upstream equation tag alignment changed; review the marimo override.",
+ );
+ }
+ tag.append(postcss.decl({ prop: "text-align", value: "right" }));
+ const counters = findRule("body");
+ replaceValue(
+ counters,
+ "counter-reset",
+ "katexEqnNo mmlEqnNo",
+ "katexEqnNo mmlEqnNo",
+ );
+ counters.selector = "body, .katex-display";
+
+ const svgScopes = new Set<NonNullable<Rule["parent"]>>();
+ root.walkRules(".katex svg", (rule) => {
+ const parent = rule.parent;
+ if (!parent) {
+ return;
+ }
+ if (svgScopes.has(parent)) {
+ // Moving declarations across intervening rules or scopes can change the
+ // cascade. Exempt only this duplicate rule instead of merging it.
+ rule.before(
+ postcss.comment({
+ text: "stylelint-disable no-duplicate-selectors -- Preserve the upstream SVG cascade.",
+ }),
+ );
+ rule.after(
+ postcss.comment({ text: "stylelint-enable no-duplicate-selectors" }),
+ );
+ }
+ svgScopes.add(parent);
+ });
+
+ const formatted = await formatCss(header + root.toString());
+ const linted = await stylelint.lint({
+ code: formatted,
+ codeFilename: stylesheetPath,
+ configFile: path.resolve(scriptDirectory, "../.stylelintrc.cjs"),
+ fix: true,
+ });
+ if (linted.errored) {
+ throw new Error(
+ `Generated KaTeX CSS failed stylelint: ${JSON.stringify(linted.results)}`,
+ );
+ }
+ // Vendor prefixes can normalize to identical declarations during stylelint's
+ // fixes. Remove only adjacent exact duplicates; retain fallback ordering.
+ const normalized = postcss.parse(linted.code ?? formatted);
+ normalized.walkDecls((decl) => {
+ const previous = decl.prev();
+ if (
+ previous?.type === "decl" &&
+ previous.prop === decl.prop &&
+ previous.value === decl.value &&
+ previous.important === decl.important
+ ) {
+ decl.remove();
+ }
+ });
+ return formatCss(normalized.toString());
+}
+
+export async function checkKatexCss(
+ upstream: string,
+ local: string,
+): Promise<void> {
+ if (local !== (await generateKatexCss(upstream))) {
+ throw new Error(
+ "KaTeX stylesheet drift detected. Run `pnpm sync-katex-css` from the repository root, review the CSS diff, then run `pnpm --dir frontend test src/css/katex-css.test.ts`. Change documented overrides in frontend/scripts/katex-css.ts if needed; do not hand-edit katex.min.css.",
+ );
+ }
+}
diff --git a/frontend/scripts/sync-katex-css.ts b/frontend/scripts/sync-katex-css.ts
new file mode 100644
index 0000000000..940f59c8bb
--- /dev/null
+++ b/frontend/scripts/sync-katex-css.ts
@@ -0,0 +1,16 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { writeFile } from "node:fs/promises";
+import {
+ generateKatexCss,
+ readUpstreamCss,
+ stylesheetPath,
+} from "./katex-css.ts";
+
+await writeFile(
+ stylesheetPath,
+ await generateKatexCss(await readUpstreamCss()),
+);
+process.stdout.write(
+ "Regenerated frontend/src/css/katex.min.css. Review the diff and run pnpm --dir frontend test src/css/katex-css.test.ts.\n",
+);
diff --git a/frontend/src/css/katex-css.test.ts b/frontend/src/css/katex-css.test.ts
new file mode 100644
index 0000000000..0db9f753ad
--- /dev/null
+++ b/frontend/src/css/katex-css.test.ts
@@ -0,0 +1,166 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { readFile } from "node:fs/promises";
+import postcss from "postcss";
+import { beforeAll, describe, expect, it } from "vitest";
+import {
+ checkKatexCss,
+ generateKatexCss,
+ readUpstreamCss,
+ stylesheetPath,
+} from "../../scripts/katex-css";
+
+let upstream: string;
+let generated: string;
+
+beforeAll(async () => {
+ upstream = await readUpstreamCss();
+ generated = await generateKatexCss(upstream);
+});
+
+describe("copied KaTeX stylesheet", () => {
+ it("matches the installed package with only documented marimo overrides", async () => {
+ await expect(
+ checkKatexCss(upstream, await readFile(stylesheetPath, "utf8")),
+ ).resolves.toBeUndefined();
+ });
+
+ it.each(["added", "removed", "changed"])(
+ "detects %s upstream rule without a version change",
+ async (change) => {
+ const root = postcss.parse(upstream);
+ if (change === "added") {
+ root.append(
+ postcss.parse(
+ ".katex .reflectbox { display: inline-block; transform: scaleX(-1); }",
+ ),
+ );
+ } else {
+ root.walkRules(".katex .mspace", (rule) => {
+ if (change === "removed") {
+ rule.remove();
+ } else {
+ rule.append(postcss.decl({ prop: "color", value: "red" }));
+ }
+ });
+ }
+ await expect(checkKatexCss(root.toString(), generated)).rejects.toThrow(
+ "pnpm sync-katex-css",
+ );
+ const regenerated = await generateKatexCss(root.toString());
+ await checkKatexCss(root.toString(), regenerated);
+ },
+ );
+
+ it.each(["added", "removed", "changed"])(
+ "detects %s local rule",
+ async (change) => {
+ const root = postcss.parse(generated);
+ if (change === "added") {
+ root.append(postcss.parse(".katex .unexpected { display: none; }"));
+ } else {
+ root.walkRules(".katex .mspace", (rule) => {
+ if (change === "removed") {
+ rule.remove();
+ } else {
+ rule.append(postcss.decl({ prop: "color", value: "red" }));
+ }
+ });
+ }
+ await expect(checkKatexCss(upstream, root.toString())).rejects.toThrow(
+ "pnpm sync-katex-css",
+ );
+ },
+ );
+
+ it("preserves math sizing, tag alignment, and equation counters without bundling font faces", () => {
+ const root = postcss.parse(generated);
+ const declarations = (selector: string) => {
+ const values: Record<string, string> = {};
+ root.walkRules(selector, (rule) => {
+ rule.walkDecls((decl) => {
+ values[decl.prop] = decl.value;
+ });
+ });
+ return values;
+ };
+ expect(declarations(".katex")).toEqual({
+ "font-family": '"KaTeX_Main", "Times New Roman", serif',
+ "font-size": "110%",
+ "font-style": "normal",
+ "line-height": "inherit",
+ position: "relative",
+ "text-indent": "0",
+ "text-rendering": "auto",
+ });
+ expect(
+ declarations(".katex-display > .katex > .katex-html > .katex-tag"),
+ ).toEqual({ position: "absolute", right: "0", "text-align": "right" });
+ expect(declarations("body,\n.katex-display")).toEqual({
+ "counter-reset": "katexEqnNo mmlEqnNo",
+ });
+ expect(declarations(".katex .angl")["border-right"]).toBe("0.049em solid");
+ const fontFaces: postcss.AtRule[] = [];
+ root.walkAtRules("font-face", (rule) => {
+ fontFaces.push(rule);
+ });
+ expect(fontFaces).toEqual([]);
+ });
+
+ it.each(["root", "media"])(
+ "preserves SVG rule order and %s scope when upstream adds a competing rule",
+ async (scope) => {
+ const root = postcss.parse(upstream);
+ const svgRules: postcss.Rule[] = [];
+ root.walkRules(".katex svg", (rule) => {
+ svgRules.push(rule);
+ });
+ const secondSvg = svgRules[1];
+ secondSvg.before(postcss.parse(".katex :is(svg) { stroke-width: 3; }"));
+ if (scope === "media") {
+ const media = postcss.atRule({ name: "media", params: "print" });
+ secondSvg.before(media);
+ media.append(secondSvg);
+ }
+
+ const svgCascade = (css: string) => {
+ const rules: {
+ selector: string;
+ scope: string;
+ strokeWidth: string | undefined;
+ }[] = [];
+ postcss.parse(css).walkRules((rule) => {
+ if (
+ rule.selector !== ".katex svg" &&
+ rule.selector !== ".katex :is(svg)"
+ ) {
+ return;
+ }
+ let strokeWidth: string | undefined;
+ rule.walkDecls("stroke-width", (decl) => {
+ strokeWidth = decl.value;
+ });
+ const parent = rule.parent;
+ rules.push({
+ selector: rule.selector,
+ scope:
+ parent?.type === "atrule"
+ ? `${parent.name} ${parent.params}`
+ : "root",
+ strokeWidth,
+ });
+ });
+ return rules;
+ };
+ const regenerated = await generateKatexCss(root.toString());
+ expect(svgCascade(regenerated)).toEqual(svgCascade(root.toString()));
+ await checkKatexCss(root.toString(), regenerated);
+ },
+ );
+
+ it("requires review when an overridden upstream declaration changes", async () => {
+ await expect(
+ generateKatexCss(upstream.replace("line-height:1.2", "line-height:1.3")),
+ ).rejects.toThrow("review overrides");
+ });
+});
diff --git a/frontend/src/css/katex.min.css b/frontend/src/css/katex.min.css
index 4dd541e103..50c9341519 100644
--- a/frontend/src/css/katex.min.css
+++ b/frontend/src/css/katex.min.css
@@ -1,23 +1,20 @@
/*
- * Adapted from https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css
+ * Generated from the installed katex/dist/katex.min.css.
+ * Run `pnpm sync-katex-css` from the repository root or frontend to regenerate.
+ * Do not edit this file directly; update scripts/katex-css.ts for local overrides.
*
- * KaTeX's class names change between versions (0.18 prefixed most of its
- * internal classes with `katex-`), so this file must be regenerated whenever
- * the `katex` package is bumped. Steps:
- *
- * 1. Copy the upstream katex.min.css for the installed version.
- * 2. Delete every `@font-face` block. The fonts are declared in katex-fonts.css.
- * 3. Keep the upstream `em` values. KaTeX sizes scripts, rules, and spacing
- * relative to the surrounding math, which can differ from the root size.
- * 4. Run oxfmt to expand the file, then stylelint with --fix. Merge the two
- * `.katex svg` rules stylelint flags as duplicates.
- * 5. Re-apply the marimo edits below:
- * - `.katex`: `font-size: 110%`, `line-height: inherit` and
- * `font-style: normal` in place of the upstream `font` shorthand, so math
- * follows the surrounding text size and stays upright in blockquotes.
- * - `.katex-tag` inside `.katex-display`: `text-align: right`.
- * - `counter-reset` on `.katex-display` as well as `body`, so equation
- * numbers restart for each display block.
+ * Documented marimo overrides:
+ * - Remove @font-face: font declarations live in katex-fonts.css.
+ * - Preserve em units so scripts, rules, and spacing scale with surrounding math.
+ * - Replace .katex's font shorthand with its font-family, font-size: 110%,
+ * font-style: normal, and line-height: inherit to follow surrounding text size
+ * and keep math upright in blockquotes.
+ * - Right-align display equation tags.
+ * - Reset equation counters on each display block as well as body.
+ * - Preserve duplicate SVG rules in their upstream order and scope, with a
+ * targeted stylelint exemption so their cascade remains intact.
+ * Formatting and syntax normalization use oxfmt and stylelint; adjacent exact
+ * duplicate declarations left by vendor-prefix normalization are removed.
*/
/* stylelint-disable unit-allowed-list -- KaTeX sizes are relative to the math. */
@@ -1002,6 +999,17 @@
.katex svg {
fill: currentcolor;
stroke: currentcolor;
+ display: block;
+ height: inherit;
+ position: absolute;
+ width: 100%;
+}
+
+.katex svg path {
+ stroke: none;
+}
+/* stylelint-disable no-duplicate-selectors -- Preserve the upstream SVG cascade. */
+.katex svg {
fill-rule: nonzero;
fill-opacity: 1;
stroke-width: 1;
@@ -1011,16 +1019,8 @@
stroke-dasharray: none;
stroke-dashoffset: 0;
stroke-opacity: 1;
- display: block;
- height: inherit;
- position: absolute;
- width: 100%;
}
-
-.katex svg path {
- stroke: none;
-}
-
+/* stylelint-enable no-duplicate-selectors */
.katex img {
border-style: none;
max-height: none;
diff --git a/package.json b/package.json
index 131ac83805..fe1b13f155 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,8 @@
"build": "turbo build",
"codegen": "turbo run codegen",
"lint": "pnpm run -r lint",
- "dev": "pnpm run --filter @marimo-team/frontend dev"
+ "dev": "pnpm run --filter @marimo-team/frontend dev",
+ "sync-katex-css": "pnpm --dir frontend sync-katex-css"
},
"devDependencies": {
"@testing-library/jest-dom": "^7.0.1",