⚠ Early release: v0.3.2.sophistry is not ready for production use. Until 1.0, any minor release may break the API; expect missing features and bugs too.Stability and versioning
Math and LaTeX
@sophistry/text typesets LaTeX with KaTeX and extracts the glyph outlines as scene geometry. Its definitions are mathTex and mathTransform, and the components <MathTex> and <MathTransform> come from @sophistry/solidjs/text (or @sophistry/react/text). A formula is therefore shapes, not a text run: it writes itself on stroke by stroke, takes gradients and the theme’s colors, and morphs into another formula with every symbol the two share gliding to its new place.
Install it with KaTeX, and import KaTeX’s stylesheet once in your app; the layout comes from it (see Installation):
pnpm add @sophistry/text kateximport "katex/dist/katex.css";MathTex
Section titled “MathTex”<MathTex> renders a TeX string, centred on its position. fontSize is in scene units per em and is the only thing that sets size, so every dimension inside the formula scales with it. The component returns the node, and the node is the handle: ref receives a MathTexNode with ready(), pending(), status, placed(), parts() and partBounds(index) on top of every node method.
5 collapsed lines
import { draw, track } from "@sophistry/core";import { Stage, usePlayer } from "@sophistry/solidjs";import { MathTex } from "@sophistry/solidjs/text";import type { MathTexNode } from "@sophistry/text";import { onSettled } from "solid-js";
export function Euler() { const drawn = track(0); const player = usePlayer(); let formula: MathTexNode | undefined;
onSettled(() => { // Typesetting is async: wait for the formula before writing it out. void formula ?.ready() .then(() => player.play(draw(drawn, { duration: 2 }))) .catch(() => {}); });
return ( <Stage units={10}> <MathTex tex="e^{i\pi} + 1 = 0" fontSize={0.9} progress={drawn} ref={(node) => { formula = node; }} /> </Stage> );}Without a framework it is the same definition: scene.add(mathTex.create({ tex, fontSize: 0.9, progress: drawn })), then await node.ready() before scene.play(draw(drawn)).
tex is KaTeX source. In a JSX string attribute (tex="\frac{a}{b}") write backslashes as-is; inside a JS expression (tex={"\\frac{a}{b}"}) double them, or use String.raw. Other props:
fill,stroke,opacity,x,y,rotation,scaleand the rest of the shape props.filldefaults to the theme foreground, so a formula follows light and dark mode.strokeWidthdefaults to 0; the outline a formula is written with is drawn instrokeif you give one, and otherwise in the fill.displayMode(defaulttrue: display-size operators and centered fractions) andmacros(extra KaTeX macros such as{ "\\R": "\\mathbb{R}" }).partFillcolours parts individually (Manim’stex_to_color_map): a record from source character to paint ({ x: "gold" }) or a function of the part and its index. See below.onTypesetis called with the placed parts whenever the placed formula changes: a new outline landing, andfontSizere-placing the current one. The loading model is described below.onErroris called when typesetting fails and also contains the failure (the formula renders nothing); without it the error is rethrown from the scene’s next commit. KaTeX parse errors are not failures: KaTeX renders the bad source in its error color, so a half-typed formula still draws.
progress writes a formula out the way Manim’s Write does: glyph after glyph in reading order, each starting a little after the last (lag_ratio = min(4 / glyphs, 0.2)), each tracing its outline over the first half of its window and filling in over the second as the outline fades. So draw(progress) is Write, and a finished formula is fill alone, with no stroke. write takes an array of tracks to stagger several formulas:
Quadratic formula
An equation and its solution are written out one after the other with write().
5 collapsed lines
import { track, write } from "@sophistry/core";import { Stage, usePlayer } from "@sophistry/solidjs";import { MathTex } from "@sophistry/solidjs/text";import type { MathTexNode } from "@sophistry/text";import { onSettled } from "solid-js";
export default function QuadraticFormula() { const { play } = usePlayer(); const equation = track(0); const solution = track(0);
// Wait for both formulas to be typeset before writing them out. const formulas: MathTexNode[] = []; onSettled(() => { // `ready()` rejects (AbortError) if the scene goes away first. void Promise.all(formulas.map((f) => f.ready())) .then(() => play(write([equation, solution], { duration: 2.5, lag: 0.8 })), ) .catch(() => {}); });
return ( <Stage units={10}> <MathTex tex="ax^2 + bx + c = 0" fontSize={0.65} progress={equation} ref={(f) => formulas.push(f)} y={1.6} /> <MathTex tex="x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}" fontSize={0.75} progress={solution} ref={(f) => formulas.push(f)} y={-0.6} /> </Stage> );}Euler's identity
LaTeX is geometry: two formulas are written out stroke by stroke.
5 collapsed lines
import { draw, track } from "@sophistry/core";import { Stage, usePlayer } from "@sophistry/solidjs";import { MathTex } from "@sophistry/solidjs/text";import type { MathTexNode } from "@sophistry/text";import { onSettled } from "solid-js";
export default function EulerIdentity() { const { play } = usePlayer(); const progress = track(0);
// Typesetting is async: write only once both formulas exist, or the // reveal could run to its end before anything is on screen. const formulas: MathTexNode[] = []; onSettled(() => { // `ready()` rejects (AbortError) if the scene goes away first. void Promise.all(formulas.map((f) => f.ready())) .then(() => play(draw(progress, { duration: 2 }))) .catch(() => {}); });
return ( <Stage units={10}> <MathTex tex="e^{i\pi} + 1 = 0" fontSize={0.9} progress={progress} ref={(f) => formulas.push(f)} y={1.2} /> <MathTex tex="\int_0^\infty e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2}" fontSize={0.7} progress={progress} ref={(f) => formulas.push(f)} y={-1.2} /> </Stage> );}Use <Text> (label) for prose. It draws with fillText, which is one call instead of a few thousand points. Reach for MathTex when the text is maths, or when the writing itself is the point.
Loading, pending and waiting
Section titled “Loading, pending and waiting”Typesetting is asynchronous: a couple of frames the first time a formula is seen, a cache hit afterwards. There are no loading boundaries to set up; each formula node manages its own state.
- First load. Typesetting starts at the node’s first commit. Until the formula lands the node draws nothing, and the rest of the scene paints as usual.
- A changed formula (
tex,displayModeormacros) stays on screen until the new one is ready, then swaps in one step.fontSizechanges never wait: they re-place the outline without typesetting. A formula already typeset elsewhere on the page (the outline cache shares one request per formula) is taken in the same commit, so going back to a formula never blanks a frame. pending()on the node is true while typesetting, andstatusis the same state as aReadable("pending","ready"or"failed") to bind a prop to.ready()resolves once the formula is typeset, and rejects with the error, or with anAbortErrorif the node is disposed first. Await it beforedrawor a morph, or the animation runs while nothing is on screen. AmathTransformnode’sready()covers both formulas.- Errors go to
onError, which also contains them; without it they are rethrown from the scene’s next commit. Either wayready()rejects anderror()returns the failure, and the formula recovers whentexchanges to something valid.
4 collapsed lines
import { derive } from "@sophistry/core";import { Stage } from "@sophistry/solidjs";import { MathTex } from "@sophistry/solidjs/text";import { createSignal } from "solid-js";
export function Swap() { const [tex, setTex] = createSignal("a^2 + b^2");
return ( <> <Stage units={8}> <MathTex tex={tex()} // Dim the old formula while the next one loads: bound in core. ref={(formula) => formula.set("opacity", derive(formula.status, (status) => (status === "pending" ? 0.4 : 1))) } /> </Stage> <button type="button" onClick={() => setTex("c^2")}> next </button> </> );}ready() is safe to call from onSettled. A rejected ready() with an AbortError only means the formula unmounted first, so most scripts ignore that one.
Per-glyph control with createLatex
Section titled “Per-glyph control with createLatex”For colouring parts, partFill on <MathTex> is usually enough: the formula becomes one shape per part, and progress still writes it as a whole.
<MathTex tex="3x^2 + 2x - x = 4x^2 - 5" partFill={{ x: "gold" }} fontSize={0.9} />createLatex(tex, options) stops one step short of a node: it returns the placed formula as a Readable (null until the first typeset lands), with the same pending(), status, ready() and error() as the nodes, plus dispose(). tex and options may themselves be Readables. The value has parts (one per glyph, rule or stretchy piece, in reading order, already in scene units, y up and centred on the origin), plus width and height. Render each part as its own <Path> and give it its own colour, track or interaction:
4 collapsed lines
import { derive } from "@sophistry/core";import { Path, Stage, useScene, useTrackValue } from "@sophistry/solidjs";import { createLatex } from "@sophistry/text";import { For, onCleanup } from "solid-js";
function Parts() { const palette = derive(useScene().theme, (theme) => theme.palette); const formula = createLatex("3x^2 + 2x - x = 4x^2 - 5", { fontSize: 0.9 }); onCleanup(() => formula.dispose()); // The parts change only when a new formula lands: fine to follow in Solid. const placed = useTrackValue(formula);
return ( <For each={placed()?.parts ?? []}> {(part) => ( <Path points={part.polylines} closed fill={derive(palette, (palette) => (part.char === "x" ? palette.highlight : palette.foreground))} stroke="none" /> )} </For> );}
export const Highlighted = () => ( <Stage units={12}> <Parts /> </Stage>);Each part has kind ("glyph", "rule" for fraction bars and overlines, or "svg" for stretchy pieces such as radical tails and big delimiters), char (glyph only: the source character), polylines and box. Matching on char is the simple way to colour all the xs; for a specific symbol, find its index in reading order. Give each part stroke="none": a glyph is fill alone, as in MathTex, and a <Path> otherwise strokes in the theme’s diagram width and colour, which rings every letter.
To write the parts out the way MathTex does, give each one its place in the write with writePhase(progress, index, count) (from @sophistry/core). It returns how much of the glyph’s outline is traced (border, its progress) and how far its fill is up (fill, its fillOpacity); the outline is fontSize * OUTLINE_RATIO wide (OUTLINE_RATIO is exported by @sophistry/text) and thins away as the fill comes up:
Coloring parts of a formula
createLatex hands back every glyph as its own part, so each one can get its own color. Here the unknown x is picked out from the rest of the equation.
10 collapsed lines
import { derive, draw, track, writePhase } from "@sophistry/core";import { Path, Stage, usePlayer, useScene, useTrackValue,} from "@sophistry/solidjs";import { createLatex, OUTLINE_RATIO } from "@sophistry/text";import { For, onCleanup, onSettled } from "solid-js";
const fontSize = 0.9;
function Formula() { const { play } = usePlayer(); const theme = useScene().theme; const progress = track(0); const latex = createLatex("3x^2 + 2x - x = 4x^2 - 5", { fontSize }); onCleanup(() => latex.dispose()); // Which glyphs exist is Solid logic: one <Path> per part, once typeset. const placed = useTrackValue(latex); const count = () => latex.peek()?.parts.length ?? 1;
onSettled(() => { // `ready()` rejects (AbortError) if the formula goes away first. void latex .ready() .then(() => play(draw(progress, { duration: 2 }))) .catch(() => {}); });
return ( <For each={placed()?.parts ?? []}> {(part, i) => { const ink = derive(theme, (t) => part.char === "x" ? t.palette.highlight : t.palette.foreground, ); // Where this glyph stands in the write, as MathTex would write it: // outline first, then the fill comes up as the outline fades. const phase = derive(progress, (p) => writePhase(p, i(), count())); return ( <Path points={part.polylines} closed fill={ink} fillOpacity={derive(phase, (p) => p.fill)} stroke={ink} strokeWidth={derive( phase, (p) => fontSize * OUTLINE_RATIO * (1 - p.fill), )} progress={derive(phase, (p) => p.border)} /> ); }} </For> );}
export default function ColoredFormula() { return ( <Stage units={12}> <Formula /> </Stage> );}Transforming formulas
Section titled “Transforming formulas”<MathTransform from to blend /> morphs one formula into another. blend runs 0 to 1 (0 is exactly from, 1 exactly to); it is a morph, not a reveal, hence not progress. Bind it to a track and drive that with valueTo or a spring:
5 collapsed lines
import { track, valueTo } from "@sophistry/core";import { Stage, usePlayer } from "@sophistry/solidjs";import { MathTransform } from "@sophistry/solidjs/text";import type { MathTransformNode } from "@sophistry/text";import { onSettled } from "solid-js";
export function Square() { const blend = track(0); const player = usePlayer(); let formula: MathTransformNode | undefined;
onSettled(() => { // `ready()` covers both formulas: the morph never starts from half a pair. void formula ?.ready() .then(() => player.play(valueTo(blend, 1, { duration: 1.6 }))) .catch(() => {}); });
return ( <Stage units={8}> <MathTransform from="x^2 + 2x + 1" to="(x + 1)^2" blend={blend} fontSize={1.1} ref={(node) => { formula = node; }} /> </Stage> );}MathTransform is Manim’s TransformMatchingTex: parts pair by character, each going to the nearest part of the same character and size (an exponent 2 goes to the exponent 2, not a full-size 2 next door). Matched parts move; the rest cross-fade, drifting toward where the new parts arrive.
Formula morph
Symbols shared by two equations glide to their new places while the rest fade, so completing the square reads as algebra.
5 collapsed lines
import { hold, track, valueTo } from "@sophistry/core";import { Stage, Text, usePlayer } from "@sophistry/solidjs";import { MathTransform } from "@sophistry/solidjs/text";import type { MathTransformNode } from "@sophistry/text";import { onSettled } from "solid-js";
export default function FormulaMorph() { const { play, signal } = usePlayer(); const blend = track(0);
let formula: MathTransformNode | undefined; onSettled(() => { void (async () => { // Both outlines must exist before the first blend means anything. // `ready()` rejects (AbortError) if the scene goes away first. if ( await formula?.ready().then( () => false, () => true, ) ) return; while (!signal.aborted) { await play(hold(0.8)); await play(valueTo(blend, 1, { duration: 2 })); await play(hold(1)); await play(valueTo(blend, 0, { duration: 2 })); } })(); });
return ( <Stage units={10}> <Text text="completing the square" y={2} /> <MathTransform from="x^2 + 2x + 1" to="(x + 1)^2" blend={blend} ref={(f) => (formula = f)} fontSize={1.1} /> </Stage> );}Two options steer the matching:
keyMap={{ "2": "\\pi" }}forces a correspondence the characters do not imply, so that pair moves instead of cross-fading.mismatch="morph"reshapes leftover parts (a2that must become a\pi) into their nearest partner instead of fading them: more spectacle, less legibility. The default"fade"is Manim’s behavior. Outlines become outlines and holes become holes, so a counter never fills in on the way, and a piece with no partner grows or shrinks.
To color parts by what the transform did to them, use partFill: it receives each MorphedPart (with a role of "moved", "morphed", "out" or "in") and returns a paint, or undefined for the default:
<MathTransform from="2x + 6 = 10" to="2x = 10 - 6" blend={blend} partFill={(part) => (part.role === "in" ? "tomato" : undefined)}/>Nothing is drawn until both formulas are typeset, and when from or to changes the previous morph stays up until the new pair has landed. MathTransform does not support strokeAlong or pointer interaction props; its ref receives a MathTransformNode, with the same loading methods as a MathTexNode.
Matching arbitrary shapes
Section titled “Matching arbitrary shapes”For shapes that are not TeX (an imported outline, a different font), the same idea works from raw geometry. The transformMatchingShapes definition (<TransformMatchingShapes> in the bindings; see Animation) draws this morph for you; underneath it is the morphShapes(from, to, options) function (from @sophistry/core/geometry, re-exported by @sophistry/text), which takes two lists of { id?, polylines } and returns a function from t to the in-between parts, each with polylines, opacity and a role. matchShapesByPointCloud returns just the correspondence.
import { morphShapes, regularPolygon, type ShapePart } from "@sophistry/core/geometry";
const sourceShapes: ShapePart[] = [{ id: "tri", polylines: [regularPolygon(0, 0, 1, 3)] }];const targetShapes: ShapePart[] = [{ id: "sq", polylines: [regularPolygon(0, 0, 1, 4)] }];
const at = morphShapes(sourceShapes, targetShapes, { maxCost: 5 });const parts = at(0.5); // [{ id, polylines, opacity, role }, ...]Pairing is greedy, cheapest first, on a similarity descriptor with no rotation invariance, so coincidental matches are possible: a round blob will happily match another round blob. maxCost leaves poor pairs unmatched (they fade) instead of forcing them together. There is no "morphed" role here: an unmatched shape has nothing plausible to become.
Numbers that animate
Section titled “Numbers that animate”Not everything needs LaTeX. DecimalNumber, Integer and Variable (definitions decimalNumber, integer and variable in @sophistry/core) draw a number one character per node, with tabular digits so the width does not shimmer as it counts. Bind value to a track and drive it with valueTo:
3 collapsed lines
import { track, valueTo } from "@sophistry/core";import { DecimalNumber, Stage, usePlayer, Variable } from "@sophistry/solidjs";import { onSettled } from "solid-js";
export function Counter() { const price = track(0); const player = usePlayer(); onSettled(() => { void player.play(valueTo(price, 9.5, { duration: 1.5 })); });
return ( <Stage units={8}> <Variable label="price" value={price} y={1} /> <DecimalNumber value={price} decimalPlaces={2} unit=" USD" y={-1} /> </Stage> );}minIntegerDigits and reserveSign hold columns open so a centered counter stays still when it grows from 9 to 10; digitStyle styles individual characters; Integer is DecimalNumber with no decimals; Variable draws label = value (left-aligned by default).
Animated numbers
An Integer, a DecimalNumber and a Variable count up and back down with valueTo; digits keep fixed-width columns so nothing jitters.
10 collapsed lines
import { hold, parallel, sequence, track, valueTo } from "@sophistry/core";import { DecimalNumber, Integer, Stage, Text, usePlayer, Variable,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
export default function AnimatedNumbers() { const { play, signal } = usePlayer(); const count = track(0); const speed = track(0); const price = track(0);
onSettled(() => { void (async () => { while (!signal.aborted) { await play( sequence( parallel( valueTo(count, 12345, { duration: 2 }), valueTo(speed, 98.6, { duration: 2 }), valueTo(price, 9.5, { duration: 2 }), ), hold(1), parallel( valueTo(count, 0, { duration: 1.5 }), valueTo(speed, 0, { duration: 1.5 }), valueTo(price, 0, { duration: 1.5 }), ), hold(0.6), ), ); } })(); });
return ( <Stage units={10}> <Text text="Integer" x={-4.5} y={1.6} align="left" fontSize={0.4} /> <Integer value={count} x={4.5} y={1.6} align="right" fontSize={0.8} groupDigits minIntegerDigits={6} /> <Text text="DecimalNumber" x={-4.5} y={0} align="left" fontSize={0.4} /> <DecimalNumber value={speed} x={4.5} y={0} align="right" fontSize={0.8} decimalPlaces={1} unit=" m/s" minIntegerDigits={2} /> <Text text="Variable" x={-4.5} y={-1.6} align="left" fontSize={0.4} /> <Variable label="price" value={price} x={-0.5} y={-1.6} fontSize={0.8} /> </Stage> );}Fonts, loading and cost
Section titled “Fonts, loading and cost”KaTeX typesets the formula into a hidden DOM node, the layout is read back out, and opentype.js supplies glyph outlines from KaTeX’s own fonts, so the canvas draws exactly what the DOM would.
- Each distinct formula costs a few milliseconds once, then is cached. The first time, nothing is drawn for a couple of frames while fonts load.
- Fonts load lazily: only the faces a formula uses are fetched, and opentype.js itself is loaded on the first face it parses.
ensureWebFonts(),loadFace(name)andresolveFace(...)preload them. - On the server nothing typesets (a request never settles there); the formula typesets in the browser after mount, with no mismatch.
- Bundle size: KaTeX and opentype.js are large. Only
@sophistry/textuses them, so apps that never import it (or the bindings’/textsubpaths) pay nothing; see Installation.
Lazy-loading the text entry point
Section titled “Lazy-loading the text entry point”If maths is a minor feature of your page, keep it out of the main bundle. Put the scene that uses /text in its own module and load it with Solid’s lazy (or React’s):
2 collapsed lines
import { Stage } from "@sophistry/solidjs";import { MathTex } from "@sophistry/solidjs/text";
export default function FormulaScene() { return ( <Stage units={10}> <MathTex tex="\int_0^1 x^2\,dx = \tfrac{1}{3}" fontSize={0.9} /> </Stage> );}import { lazy, Loading } from "solid-js";
const FormulaScene = lazy(() => import("./FormulaScene"));
export function App() { return ( <Loading fallback={<p>Loading formula…</p>}> <FormulaScene /> </Loading> );}The bundler splits FormulaScene (with KaTeX and opentype.js) into a chunk fetched on first render. You can also trigger the load yourself, for example on hover or scroll, with FormulaScene.preload(), or with a plain dynamic import("@sophistry/text") inside an event handler.
More recipes
Section titled “More recipes”Formulas compose with the rest of the toolkit. The Taylor series example draws successive polynomial approximations of sin x next to their formulas, and the Fourier example adds harmonics one at a time until a sine wave becomes a square wave:
Taylor series
Polynomial approximations of sin x of degree 1, 3, 5 and 7 are drawn in turn, each hugging the curve for longer.
4 collapsed lines
import { BLUE, GREEN, ORANGE, RED, track, write } from "@sophistry/core";import { Axes, FunctionGraph, Stage, usePlayer } from "@sophistry/solidjs";import { MathTex } from "@sophistry/solidjs/text";import { onSettled } from "solid-js";
/** The Taylor polynomial of sin x with terms up to x^degree. */const taylor = (degree: number) => (x: number) => { let sum = 0; let term = x; for (let n = 1; n <= degree; n += 2) { sum += term; term *= (-x * x) / ((n + 1) * (n + 2)); } return sum;};
const DEGREES = [1, 3, 5, 7];const COLORS = [RED, ORANGE, GREEN, BLUE];
export default function TaylorSeries() { const { play } = usePlayer(); const drawn = DEGREES.map(() => track(0));
onSettled(() => { void play(write(drawn, { duration: 1.5, lag: 1.2 })); });
return ( <Stage units={14}> <MathTex tex="\sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \cdots" fontSize={0.5} y={3.1} /> <Axes xRange={[-7, 7, 2]} yRange={[-3, 3, 1]} width={11} height={5} center={{ x: 0, y: -0.6 }} > <FunctionGraph function={Math.sin} strokeWidth={0.07} /> {DEGREES.map((degree, i) => ( <FunctionGraph function={taylor(degree)} stroke={COLORS[i]} progress={drawn[i]} /> ))} </Axes> </Stage> );}Fourier square wave
Adding odd sine harmonics one at a time turns a plain sine wave into a square wave.
9 collapsed lines
import { derive, track, valueTo } from "@sophistry/core";import { Axes, FunctionGraph, Stage, Text, usePlayer,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
/** Partial Fourier sum of a square wave: (4/pi) * sum of sin((2k-1)x) / (2k-1). */const squareWave = (harmonics: number) => (x: number) => { let sum = 0; for (let k = 1; k <= harmonics; k++) { sum += Math.sin((2 * k - 1) * x) / (2 * k - 1); } return (4 / Math.PI) * sum;};
export default function FourierSquareWave() { const { play } = usePlayer(); const harmonics = track(1); const count = derive(harmonics, Math.round);
onSettled(() => { void play(valueTo(harmonics, 25, { duration: 8, easing: "linear" })); });
return ( <Stage units={14}> <Axes xRange={[-7, 7, 2]} yRange={[-2, 2, 1]} width={11} height={5} center={{ x: 0, y: -0.4 }} > <FunctionGraph function={derive(count, squareWave)} samples={600} /> </Axes> <Text text={derive( count, (n) => `${n} ${n === 1 ? "harmonic" : "harmonics"}`, )} y={3.2} /> </Stage> );}For plotting what a formula describes, see Coordinate systems and graphs; for sequencing a formula’s reveal with the rest of a scene, see Timelines.
Next steps
Section titled “Next steps”- Animation: drive
blendandprogresswith presets. - Timelines: scrub a formula’s reveal.
- Maths gallery: live, copyable examples.