Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Make documentation interactions resilient and theme-aware

Sina Atalayc2eac618b0eb
diff --git a/docs/content/javascripts/manimgx.js b/docs/content/javascripts/manimgx.js
index 4ee991c7..d886c9ab 100644
--- a/docs/content/javascripts/manimgx.js
+++ b/docs/content/javascripts/manimgx.js
@@ -14,6 +14,71 @@
}
}, { threshold: 0.5 })
+ // The README's pictures follow the site's selected palette. Zensical resolves system
+ // preference into this same body attribute. Keep the original media in the DOM so a
+ // cached page restored by instant navigation still knows which source is light or dark.
+ let palette
+ function pictures() {
+ const scheme = document.body.getAttribute("data-md-color-scheme")
+ for (const source of document.querySelectorAll("picture > source[media]")) {
+ const original = source.getAttribute("data-mx-color-media") ?? source.media
+ const match = /^\(prefers-color-scheme:\s*(light|dark)\)$/.exec(original)
+ if (!match) continue
+ source.setAttribute("data-mx-color-media", original)
+ const selected = scheme === "slate" ? "dark" : scheme === "default" ? "light" : null
+ const media = selected === null ? original : selected === match[1] ? "all" : "not all"
+ if (source.media !== media) source.media = media
+ }
+ }
+
+ // Most pages need no math renderer. Load it once on the first page with math, with its
+ // stylesheet beside the scripts in the persistent body: instant navigation replaces
+ // the head and page container, but keeps these assets. A failed download can be retried
+ // on the next navigation, while successfully loaded dependencies remain available.
+ const KATEX = "https://cdn.jsdelivr.net/npm/[email protected]/dist/"
+ const mathAssets = new Map()
+ function mathAsset(path) {
+ if (!mathAssets.has(path)) {
+ const style = path.endsWith(".css")
+ const asset = document.createElement(style ? "link" : "script")
+ if (style) {
+ asset.rel = "stylesheet"
+ asset.href = KATEX + path
+ } else asset.src = KATEX + path
+ mathAssets.set(path, new Promise((resolve, reject) => {
+ asset.onload = resolve
+ asset.onerror = () => {
+ asset.remove()
+ mathAssets.delete(path)
+ reject(new Error(`Could not load ${path}`))
+ }
+ document.body.appendChild(asset)
+ }))
+ }
+ return mathAssets.get(path)
+ }
+
+ function mathematics() {
+ const roots = document.querySelectorAll(".arithmatex")
+ if (!roots.length) return
+ Promise.all([
+ mathAsset("katex.min.css"),
+ mathAsset("katex.min.js").then(() => mathAsset("contrib/auto-render.min.js")),
+ ]).then(() => {
+ for (const math of roots) {
+ if (!math.isConnected) continue // the reader navigated away while assets loaded
+ renderMathInElement(math, {
+ delimiters: [
+ { left: "\\(", right: "\\)", display: false },
+ { left: "\\[", right: "\\]", display: true },
+ ],
+ })
+ }
+ }).catch(() => {
+ // Keep the readable source if the CDN is unavailable; a later page can retry.
+ })
+ }
+
// A rate function explorer, <div class="mx-rates" data-rates="smooth linear …">: a button for
// each function named, its curve with a dot that rides it as time passes, and under it a
// square that the function moves, beside a faint one that keeps one speed. It plays while it
@@ -179,9 +244,9 @@
}
// The footer's newsletter field (overrides/partials/academa.html). Its address goes to
- // academa.ai's door as JSON, the one way that door takes an address from another site; then
- // the field says what the door answered: the signup, or why not. Every page has a footer of
- // its own, so the field's form is found when it is submitted
+ // academa.ai's door as JSON. A signup is shown immediately; a refusal or network failure
+ // restores the same field, with its address intact. Every page has a footer of its own,
+ // so the field's form is found when it is submitted
document.addEventListener("submit", async event => {
const form = event.target
if (!(form instanceof HTMLFormElement) || !form.matches(".mx-footer__subscribe")) return
@@ -189,7 +254,11 @@
const answer = form.parentElement.querySelector(".mx-footer__answer")
const button = form.querySelector("button")
button.disabled = true
+ form.remove()
+ answer.classList.add("mx-footer__answer--joined")
+ answer.textContent = "You are on the list."
let reply = null
+ let accepted = false
try {
const response = await fetch(form.action, {
method: "POST",
@@ -198,18 +267,16 @@
body: JSON.stringify({ email: form.elements.email.value }),
})
reply = await response.json()
+ accepted = response.ok && reply?.success === true
} catch {
// the door unreachable, or an answer this page may not read
- } finally {
- button.disabled = false
}
- if (reply?.success === true) {
- form.remove()
- answer.classList.add("mx-footer__answer--joined")
- answer.textContent = "You are on the list."
- } else {
+ if (!accepted) {
+ answer.classList.remove("mx-footer__answer--joined")
answer.textContent =
typeof reply?.error === "string" ? reply.error : "Something went wrong. Please try again."
+ button.disabled = false
+ answer.before(form)
}
})
// a refusal is about what was typed: typing again clears it
@@ -221,24 +288,31 @@
})
// Every page, including those reached by instant navigation: its films, its math and its
- // rate function explorers
+ // rate function explorers and theme-aware pictures
document$.subscribe(() => {
+ palette ??= new MutationObserver(pictures)
+ palette.disconnect()
+ palette.observe(document.body, { attributes: true, attributeFilter: ["data-md-color-scheme"] })
+ pictures()
films.disconnect()
for (const film of document.querySelectorAll("video.mx-film")) films.observe(film)
- for (const math of document.querySelectorAll(".arithmatex")) {
- renderMathInElement(math, {
- delimiters: [
- { left: "\\(", right: "\\)", display: false },
- { left: "\\[", right: "\\]", display: true },
- ],
- })
- }
+ mathematics()
explorers.disconnect()
const roots = document.querySelectorAll(".mx-rates")
if (!roots.length) return
- curves ??= fetch(RATES).then(response => response.json())
+ curves ??= fetch(RATES).then(response => {
+ if (!response.ok) throw new Error(`Could not load rate functions: ${response.status}`)
+ return response.json()
+ }).catch(error => {
+ curves = undefined // a later page can retry a failed download
+ throw error
+ })
curves.then(data => {
- for (const root of roots) root.mxSeen ? explorers.observe(root) : explore(root, data)
+ for (const root of roots) {
+ if (root.isConnected) root.mxSeen ? explorers.observe(root) : explore(root, data)
+ }
+ }).catch(() => {
+ // The rate functions' reference remains readable if its interactive data is unavailable.
})
})
})()
diff --git a/docs/content/stylesheets/manimgx.css b/docs/content/stylesheets/manimgx.css
index 16736975..247aeeab 100644
--- a/docs/content/stylesheets/manimgx.css
+++ b/docs/content/stylesheets/manimgx.css
@@ -71,34 +71,34 @@ html {
.md-header__title .md-header__topic:first-child {
visibility: hidden;
}
+
+ .mx-lockup {
+ margin-inline: 0.6rem;
+ }
}
-/* The header's lockup (partials/header.html): the logo, and "by Academa" below it. Each is a
- header button of its own, a link that fades alone when hovered; stacked, they drop the
- padding between them. The byline is drawn in the logo's units, the logo's height being 60:
- its viewBox, 0 51.3 132 30.2, says where it starts under the logo's top and how tall it
- is (tests/docs/test_overrides.py checks these numbers against it). It lies over the logo's
- foot, where only GX's tail reaches, and is above it: the later of two header buttons */
+/* The header's two links share an SVG canvas height and text baseline (showcase/logo.py).
+ Their artwork sets the alignment; CSS only sizes and spaces the single row */
.mx-lockup {
- --mx-unit: calc(var(--mx-logo) / 60);
- display: grid;
- justify-items: start;
+ --mx-logo: 1.818rem;
+ display: flex;
+ align-items: center;
+ gap: 4px;
}
.mx-lockup > .md-logo {
- padding-block: 0;
-}
-
-.mx-lockup > [data-md-component="logo"] {
- margin-bottom: 0;
+ margin: 0;
+ padding: 0;
}
-.mx-lockup > .mx-byline {
- margin-top: calc((51.3 - 60) * var(--mx-unit));
+/* The tabs sit directly under the single-line header, with equal space above and below */
+.md-tabs__item {
+ height: auto;
}
-.mx-byline img.mx-logo {
- height: calc(30.2 * var(--mx-unit));
+.md-tabs__link {
+ margin-top: 0;
+ padding-block: 0.4rem;
}
/* The footer's band (partials/academa.html): academa.ai's footer, its ground and its
diff --git a/docs/overrides/partials/header.html b/docs/overrides/partials/header.html
index a9609be1..91a88f80 100644
--- a/docs/overrides/partials/header.html
+++ b/docs/overrides/partials/header.html
@@ -4,7 +4,7 @@
SPDX-License-Identifier: MIT
The header: Zensical's (zensical/templates/partials/header.html), but for its logo, which is
- ManimGX's lockup: the logo, its link Zensical's, and "by Academa" below it, a link to
+ ManimGX's lockup: the logo, its link Zensical's, and "by Academa" beside it, a link to
academa.ai. manimgx.css sets them; tests/docs/test_overrides.py checks that the rest is
Zensical's.
-#}
diff --git a/tests/docs/math.test.js b/tests/docs/math.test.js
new file mode 100644
index 00000000..7a2134d7
--- /dev/null
+++ b/tests/docs/math.test.js
@@ -0,0 +1,132 @@
+import { expect, test } from "bun:test"
+import { readFileSync } from "node:fs"
+import { runInNewContext } from "node:vm"
+
+const script = readFileSync(new URL("../../docs/content/javascripts/manimgx.js", import.meta.url), "utf8")
+const config = readFileSync(new URL("../../docs/zensical.toml", import.meta.url), "utf8")
+const CDN = "https://cdn.jsdelivr.net/npm/[email protected]/dist/"
+const flush = () => new Promise(resolve => setImmediate(resolve))
+const math = () => ({ isConnected: true })
+
+// Run the shipped script with controlled asset downloads and Zensical navigation. The
+// body persists, but each navigation discards the old page's nodes and head additions.
+function page(initial = []) {
+ let roots = initial, boot
+ const assets = [], rendered = [], head = []
+ const body = {
+ getAttribute: () => "default",
+ appendChild(asset) { asset.parent = body; assets.push(asset) },
+ }
+ const context = {
+ window: {}, URL,
+ location: { origin: "https://manimgx.academa.ai" },
+ matchMedia: () => ({ matches: false }),
+ IntersectionObserver: class { disconnect() {} observe() {} },
+ MutationObserver: class { disconnect() {} observe() {} },
+ document: {
+ body,
+ head: { appendChild: asset => head.push(asset) },
+ addEventListener() {},
+ querySelectorAll: selector => selector === ".arithmatex" ? roots : [],
+ createElement: tag => ({ tag, remove() { this.removed = true } }),
+ },
+ document$: { subscribe(callback) { boot = callback; callback() } },
+ }
+ runInNewContext(script, context)
+ return {
+ assets, rendered, head, body,
+ navigate(next) {
+ for (const root of roots) root.isConnected = false
+ for (const root of next) root.isConnected = true
+ roots = next
+ head.length = 0
+ boot()
+ },
+ async load(path) {
+ const asset = assets.findLast(asset => (asset.src ?? asset.href) === CDN + path)
+ expect(asset).toBeDefined()
+ if (path === "contrib/auto-render.min.js") {
+ context.renderMathInElement = (root, options) => rendered.push({ root, options })
+ }
+ asset.onload()
+ await flush()
+ },
+ async fail(path) {
+ const asset = assets.findLast(asset => (asset.src ?? asset.href) === CDN + path)
+ asset.onerror()
+ await flush()
+ return asset
+ },
+ reloadScript() { runInNewContext(script, context) },
+ }
+}
+
+test("pages without math request no KaTeX, including through global site configuration", () => {
+ const doc = page()
+ doc.navigate([])
+ doc.reloadScript()
+ expect(doc.assets).toHaveLength(0)
+ expect(doc.rendered).toHaveLength(0)
+ expect(config).not.toMatch(/https:\/\/[^"\s]*katex/)
+})
+
+test("a first math page waits for the stylesheet and loads the renderer after KaTeX", async () => {
+ const root = math(), doc = page([root])
+ expect(doc.assets.map(asset => asset.href ?? asset.src)).toEqual([
+ CDN + "katex.min.css", CDN + "katex.min.js",
+ ])
+ expect(doc.assets[0].rel).toBe("stylesheet")
+ expect(doc.rendered).toHaveLength(0)
+ await doc.load("katex.min.js")
+ expect(doc.assets[2].src).toBe(CDN + "contrib/auto-render.min.js")
+ await doc.load("contrib/auto-render.min.js")
+ expect(doc.rendered).toHaveLength(0)
+ await doc.load("katex.min.css")
+ expect(doc.rendered).toEqual([{
+ root,
+ options: { delimiters: [
+ { left: "\\(", right: "\\)", display: false },
+ { left: "\\[", right: "\\]", display: true },
+ ] },
+ }])
+})
+
+test("instant navigation shares downloads, skips departed math, and styles later pages", async () => {
+ const departed = math(), current = math(), later = math(), doc = page()
+ doc.navigate([departed])
+ doc.navigate([current])
+ expect(doc.assets).toHaveLength(2)
+ await doc.load("katex.min.css")
+ await doc.load("katex.min.js")
+ await doc.load("contrib/auto-render.min.js")
+ expect(doc.rendered.map(call => call.root)).toEqual([current])
+ doc.navigate([])
+ doc.navigate([later])
+ doc.reloadScript()
+ await flush()
+ expect(doc.rendered.map(call => call.root)).toEqual([current, later])
+ expect(doc.assets).toHaveLength(3)
+ expect(doc.assets.every(asset => asset.parent === doc.body && !asset.removed)).toBe(true)
+ expect(doc.head).toHaveLength(0)
+})
+
+test.each(["katex.min.css", "katex.min.js", "contrib/auto-render.min.js"])(
+ "a failed %s download leaves source readable and retries on the next math page",
+ async path => {
+ const first = math(), next = math(), doc = page([first])
+ if (path !== "katex.min.css") await doc.load("katex.min.css")
+ if (path !== "katex.min.js") {
+ await doc.load("katex.min.js")
+ if (path !== "contrib/auto-render.min.js") await doc.load("contrib/auto-render.min.js")
+ }
+ const failed = await doc.fail(path)
+ expect(failed.removed).toBe(true)
+ expect(doc.rendered).toHaveLength(0)
+ doc.navigate([next])
+ await flush()
+ await doc.load(path)
+ if (path === "katex.min.js") await doc.load("contrib/auto-render.min.js")
+ expect(doc.rendered.map(call => call.root)).toEqual([next])
+ expect(doc.assets).toHaveLength(4)
+ },
+)
diff --git a/tests/docs/newsletter.test.js b/tests/docs/newsletter.test.js
new file mode 100644
index 00000000..3cb4a6ae
--- /dev/null
+++ b/tests/docs/newsletter.test.js
@@ -0,0 +1,84 @@
+import { expect, test } from "bun:test"
+import { readFileSync } from "node:fs"
+import { runInNewContext } from "node:vm"
+
+const script = readFileSync(new URL("../../docs/content/javascripts/manimgx.js", import.meta.url), "utf8")
+
+// Run the shipped script with a deferred HTTP request. No address leaves the test.
+function signup() {
+ const listeners = new Map(), requests = [], classes = new Set()
+ const answer = {
+ textContent: "",
+ classList: { add: name => classes.add(name), remove: name => classes.delete(name) },
+ before: form => { form.attached = true },
+ }
+ class Form {
+ action = "https://academa.ai/api/newsletter"
+ elements = { email: { value: "[email protected]" } }
+ button = { disabled: false }
+ attached = true
+ parentElement = { querySelector: () => answer }
+ matches() { return true }
+ querySelector() { return this.button }
+ remove() { this.attached = false }
+ }
+ runInNewContext(script, {
+ window: {}, URL,
+ location: { origin: "https://manimgx.academa.ai" },
+ matchMedia: () => ({ matches: false }),
+ IntersectionObserver: class {},
+ HTMLFormElement: Form,
+ HTMLInputElement: class {},
+ document: { addEventListener: (name, listener) => listeners.set(name, listener) },
+ document$: { subscribe() {} },
+ fetch: (url, options) => new Promise((resolve, reject) => {
+ requests.push({ url, options, resolve, reject })
+ }),
+ })
+ const form = new Form()
+ const pending = listeners.get("submit")({ target: form, preventDefault() {} })
+ return { form, answer, classes, requests, pending }
+}
+
+test("signup appears before the server responds and survives acceptance", async () => {
+ const { form, answer, classes, requests, pending } = signup()
+ expect(form.attached).toBe(false)
+ expect(answer.textContent).toBe("You are on the list.")
+ expect(classes.has("mx-footer__answer--joined")).toBe(true)
+ expect(requests).toHaveLength(1)
+ const request = requests[0]
+ expect(request.url).toBe("https://academa.ai/api/newsletter")
+ expect(request.options.method).toBe("POST")
+ expect(request.options.credentials).toBe("omit")
+ expect(JSON.parse(request.options.body)).toEqual({ email: "[email protected]" })
+ request.resolve({ ok: true, json: async () => ({ success: true }) })
+ await pending
+ expect(form.attached).toBe(false)
+ expect(answer.textContent).toBe("You are on the list.")
+})
+
+test.each(["refused", "http-error", "network-error", "invalid-json"])(
+ "%s restores the entered address and lets the reader retry",
+ async failure => {
+ const { form, answer, classes, requests, pending } = signup()
+ const request = requests[0]
+ if (failure === "network-error") request.reject(new TypeError("Network error"))
+ else request.resolve({
+ ok: failure !== "http-error",
+ json: async () => {
+ if (failure === "invalid-json") throw new SyntaxError("Invalid JSON")
+ return failure === "refused"
+ ? { success: false, error: "Please use another email address." }
+ : { success: true }
+ },
+ })
+ await pending
+ expect(form.attached).toBe(true)
+ expect(form.elements.email.value).toBe("[email protected]")
+ expect(form.button.disabled).toBe(false)
+ expect(classes.has("mx-footer__answer--joined")).toBe(false)
+ expect(answer.textContent).toBe(failure === "refused"
+ ? "Please use another email address."
+ : "Something went wrong. Please try again.")
+ },
+)
diff --git a/tests/docs/rates.test.js b/tests/docs/rates.test.js
new file mode 100644
index 00000000..bcc05005
--- /dev/null
+++ b/tests/docs/rates.test.js
@@ -0,0 +1,84 @@
+import { expect, test } from "bun:test"
+import { readFileSync } from "node:fs"
+import { runInNewContext } from "node:vm"
+
+const script = readFileSync(new URL("../../docs/content/javascripts/manimgx.js", import.meta.url), "utf8")
+const flush = () => new Promise(resolve => setImmediate(resolve))
+const explorer = () => ({ isConnected: true, mxSeen() {} })
+
+// Cached pages retain their initialized explorers. Exercise the shipped script's download
+// and navigation boundary without replacing fetch with an already-resolved promise.
+function page(initial = []) {
+ let roots = initial, boot
+ const requests = [], observed = []
+ const context = {
+ window: {}, URL,
+ location: { origin: "https://manimgx.academa.ai" },
+ matchMedia: () => ({ matches: false }),
+ IntersectionObserver: class {
+ disconnect() { observed.length = 0 }
+ observe(root) { observed.push(root) }
+ },
+ MutationObserver: class { disconnect() {} observe() {} },
+ fetch(url) {
+ return new Promise((resolve, reject) => requests.push({ url: String(url), resolve, reject }))
+ },
+ document: {
+ body: { getAttribute: () => "default" },
+ addEventListener() {},
+ querySelectorAll: selector => selector === ".mx-rates" ? roots : [],
+ },
+ document$: { subscribe(callback) { boot = callback; callback() } },
+ }
+ runInNewContext(script, context)
+ return {
+ requests, observed,
+ navigate(next) {
+ for (const root of roots) root.isConnected = false
+ for (const root of next) root.isConnected = true
+ roots = next
+ boot()
+ },
+ async load() {
+ requests.at(-1).resolve({ ok: true, json: async () => ({ linear: [0, 1] }) })
+ await flush()
+ },
+ }
+}
+
+test("rate data is lazy, shared across pages, and never attaches departed explorers", async () => {
+ const first = explorer(), current = explorer(), later = explorer(), doc = page()
+ expect(doc.requests).toHaveLength(0)
+ doc.navigate([first])
+ doc.navigate([current])
+ expect(doc.requests).toHaveLength(1)
+ expect(doc.requests[0].url).toBe("https://manimgx.academa.ai/javascripts/rate-functions.json")
+ await doc.load()
+ expect(doc.observed).toEqual([current])
+ doc.navigate([later])
+ await flush()
+ expect(doc.observed).toEqual([later])
+ expect(doc.requests).toHaveLength(1)
+})
+
+test.each(["network", "http", "json"])(
+ "a %s failure is contained and the next explorer page retries",
+ async failure => {
+ const first = explorer(), next = explorer(), doc = page([first])
+ const request = doc.requests[0]
+ if (failure === "network") request.reject(new Error("offline"))
+ else request.resolve({
+ ok: failure !== "http", status: 503,
+ json: async () => {
+ if (failure === "json") throw new SyntaxError("invalid JSON")
+ return {}
+ },
+ })
+ await flush()
+ expect(doc.observed).toHaveLength(0)
+ doc.navigate([next])
+ expect(doc.requests).toHaveLength(2)
+ await doc.load()
+ expect(doc.observed).toEqual([next])
+ },
+)
diff --git a/tests/docs/test_overrides.py b/tests/docs/test_overrides.py
index be0d12f7..2e11bc5f 100644
--- a/tests/docs/test_overrides.py
+++ b/tests/docs/test_overrides.py
@@ -1,8 +1,8 @@
"""The theme's overrides, copied from Zensical, and what they add: the header's lockup (the logo
-and "by Academa" below it, each its own link) and the footer's band, Academa's. Each copy is
-checked against what it copies: Zensical's templates, and the numbers of the byline's SVG
-(`scripts/showcase/logo.py`) that the stylesheet repeats. And the band offers the newsletter
-only with the door its field posts to."""
+and "by Academa" beside it, each its own link) and the footer's band, Academa's. Each copy is
+checked against Zensical's templates. The logo and byline share a vertical canvas, so CSS
+needs no alignment offsets. And the band offers the newsletter only with the door its field
+posts to."""
import re
import tomllib
@@ -57,15 +57,15 @@ def test_the_footer_is_zensicals_but_for_the_band() -> None:
]
-def test_the_stylesheet_places_the_byline_where_its_svg_says() -> None:
- _, _, _, logo = view("logo-light.svg")
- x, y, _, height = view("byline-light.svg")
- assert view("byline-dark.svg") == view("byline-light.svg")
- assert x == 0 # from the logo's left edge
+def test_the_header_images_share_a_vertical_canvas_without_css_offsets() -> None:
+ for ground in ("light", "dark"):
+ x, y, _, height = view(f"byline-{ground}.svg")
+ _, top, _, logo_height = view(f"logo-{ground}.svg")
+ assert x == 0
+ assert (y, height) == (top, logo_height)
css = STYLESHEET.read_text(encoding="utf-8")
- assert f"calc(var(--mx-logo) / {logo:g})" in css
- assert f"calc(({y:g} - {logo:g}) * var(--mx-unit))" in css
- assert f"calc({height:g} * var(--mx-unit))" in css
+ lockup = re.findall(r"\.mx-(?:lockup|byline)[^{}]*\{([^{}]*)\}", css)
+ assert not any("transform:" in rule or "margin-top:" in rule for rule in lockup)
def band(extra: dict[str, object]) -> str: