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.

6.4 KB
Raw Blame
/* 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.",
    );
  }
}