⚠ 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
LaTeX in sophistry is geometry, not an image: MathTex turns a formula into outlines you can draw, write or recolor, and MathTransform morphs one formula into another by matching shared symbols. The components come from @sophistry/solidjs/text and the definitions from @sophistry/text, a separate package, so KaTeX and opentype.js are bundled only when you use it.
Start with EulerIdentity and QuadraticFormula for typesetting, then FormulaMorph. The remaining examples combine formulas with graphs, planes and linear maps.
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> );}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> );}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> );}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> );}Linear transformation
A shear matrix warps the plane and a unit square, while the basis vectors show where each column of the matrix lands.
11 collapsed lines
import { hold, track, valueTo } from "@sophistry/core";import { linearMap } from "@sophistry/core/geometry";import { BasisVectors, LinearTransform, NumberPlane, Polygon, Stage, usePlayer,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
const SHEAR = linearMap([ [1, 1], [0, 1],]);const SQUARE = [ { x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 },];
export default function LinearTransformation() { const { play, signal } = usePlayer(); const t = track(0);
onSettled(() => { void (async () => { while (!signal.aborted) { await play(hold(0.8)); await play(valueTo(t, 1, { duration: 2.5 })); await play(hold(1)); await play(valueTo(t, 0, { duration: 2.5 })); } })(); });
return ( <Stage units={14}> <NumberPlane xRange={[-4, 4]} yRange={[-3, 3]} width={8} height={6} gridOpacity={0.15} /> <LinearTransform matrix={SHEAR} progress={t}> <NumberPlane xRange={[-4, 4]} yRange={[-3, 3]} width={8} height={6} /> <Polygon points={SQUARE} fill="#58c4dd" fillOpacity={0.4} /> </LinearTransform> <BasisVectors matrix={SHEAR} progress={t} labels /> </Stage> );}Complex multiplication
Multiplying z by 1 + i turns it by 45 degrees and stretches it by the square root of 2, which is the argument and modulus of 1 + i.
10 collapsed lines
import { derive, hold, track, valueTo } from "@sophistry/core";import { ComplexPlane, LabeledDot, Stage, Text, usePlayer, Vector,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
// z = 1 + 0.5i is multiplied by w = 1 + i, whose modulus is sqrt(2) and// argument is 45 degrees. t = 0..1 applies that rotation and scaling gradually.const Z = { x: 1, y: 0.5 };const ARG_W = Math.PI / 4;
export default function ComplexMultiplication() { const { play, signal } = usePlayer(); const t = track(0); const zw = derive(t, (t) => { const scale = Math.SQRT2 ** t; const [cos, sin] = [Math.cos(t * ARG_W), Math.sin(t * ARG_W)]; return { x: scale * (Z.x * cos - Z.y * sin), y: scale * (Z.x * sin + Z.y * cos), }; }); const moved = derive(t, (t) => t > 0.02);
onSettled(() => { void (async () => { while (!signal.aborted) { await play(hold(1)); await play(valueTo(t, 1, { duration: 2.5 })); await play(hold(1.5)); await play(valueTo(t, 0, { duration: 1.5 })); } })(); });
return ( <Stage units={12}> <ComplexPlane xRange={[-3, 3]} yRange={[-3, 3]} width={6} height={6} /> <Vector to={zw} visible={moved} /> <LabeledDot center={zw} text="z·w" visible={moved} /> <Vector to={Z} /> <LabeledDot center={Z} text="z" /> <Text text="w = 1 + i" x={-4.3} y={2} /> </Stage> );}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> );}Squaring the complex plane
A grid of lines is sent through z ↦ z²: straight lines bend into parabolas, and right angles stay right angles.
10 collapsed lines
import { applyComplexFunction, derive, hold, sequence, track,} from "@sophistry/core";import type { Polyline } from "@sophistry/core/geometry";import { Line, Path, Stage, usePlayer, useScene } from "@sophistry/solidjs";import { onSettled } from "solid-js";
/** Horizontal and vertical lines over 0.3 ≤ x ≤ 1.5, −0.6 ≤ y ≤ 0.6. */function grid(): Polyline[] { const lines: Polyline[] = []; for (let i = 0; i <= 6; i++) { const y = -0.6 + i * 0.2; lines.push([ { x: 0.3, y }, { x: 1.5, y }, ]); const x = 0.3 + i * 0.2; lines.push([ { x, y: -0.6 }, { x, y: 0.6 }, ]); } return lines;}
const square = ({ re, im }: { re: number; im: number }) => ({ re: re * re - im * im, im: 2 * re * im,});
function Squaring() { const accent = derive(useScene().theme, (theme) => theme.palette.accent); const { play, signal } = usePlayer(); const lines = track(grid());
onSettled(() => { void (async () => { while (!signal.aborted) { lines.set(grid()); await play( sequence( hold(0.6), applyComplexFunction(lines, square, { duration: 2.5 }), hold(1.2), ), ); } })(); });
return ( <> <Line from={{ x: -1, y: 0 }} to={{ x: 3, y: 0 }} opacity={0.35} /> <Line from={{ x: 0, y: -2 }} to={{ x: 0, y: 2 }} opacity={0.35} /> <Path points={lines} stroke={accent} strokeWidth={0.015} /> </> );}
export default function ComplexSquaring() { return ( <Stage units={7.6} center={{ x: 1, y: 0 }}> <Squaring /> </Stage> );}A pendulum's phase flow
A disc of starting states flows along a pendulum's phase portrait: near the bottom it circles round, and it stretches into a thin arc as the swings drift out of step.
10 collapsed lines
import { derive, hold, phaseFlow, sequence, track } from "@sophistry/core";import { circlePolyline } from "@sophistry/core/geometry";import { Path, Stage, StreamLines, usePlayer, useScene,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
/** Angle along x, angular velocity along y. */const pendulum = ({ x, y }: { x: number; y: number }) => ({ x: y, y: -Math.sin(x),});const start = () => circlePolyline(-1.6, 0, 0.45);
function Flow() { const theme = useScene().theme; const { play, signal } = usePlayer(); const disc = track(start());
onSettled(() => { void (async () => { while (!signal.aborted) { disc.set(start()); await play( sequence( hold(0.5), phaseFlow(disc, pendulum, { virtualTime: 6, duration: 4 }), hold(1), ), ); } })(); });
return ( <> <StreamLines function={pendulum} xRange={[-5, 5]} yRange={[-2.8, 2.8]} opacity={0.35} /> <Path points={disc} closed fill={derive(theme, (t) => t.palette.accent)} fillOpacity={0.6} stroke={derive(theme, (t) => t.palette.foreground)} strokeWidth={0.02} /> </> );}
export default function PendulumPhaseFlow() { return ( <Stage units={10}> <Flow /> </Stage> );}A tracker and a dot on a graph
Manim's ValueTracker plus always_redraw, as a track() and derive(): a dot rides y = sin x while its x readout updates.
22 collapsed lines
import type { SceneNode } from "@sophistry/core";import { coordsOf, derive, draw, hold, ORIGIN, sequence, track, valueTo,} from "@sophistry/core";import { Axes, Dot, FunctionGraph, Line, Stage, Text, usePlayer, useScene,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
function Tracker() { const { play, signal } = usePlayer(); const theme = useScene().theme; const drawn = track(0); const x = track(0); // The node is the handle; coordsOf reads the system it publishes. let axes!: SceneNode; const toScene = (x: number, y: number) => coordsOf(axes)?.coordsToPoint(x, y) ?? ORIGIN;
onSettled(() => { void (async () => { await play(draw(drawn, { duration: 1.5 })); while (!signal.aborted) { await play( sequence( valueTo(x, 2 * Math.PI, { duration: 4, easing: "smooth" }), hold(0.6), valueTo(x, 0, { duration: 1.5, easing: "smooth" }), hold(0.6), ), ); } })(); });
return ( <> <Axes ref={(node) => (axes = node)} xRange={[0, 7, 1]} yRange={[-1.5, 1.5, 0.5]} width={11} height={4.5} > <FunctionGraph function={Math.sin} stroke={derive(theme, (t) => t.palette.series[0])} progress={drawn} /> </Axes> <Line from={derive(x, (x) => toScene(x, 0))} to={derive(x, (x) => toScene(x, Math.sin(x)))} stroke={derive(theme, (t) => t.palette.muted)} dash={[0.1, 0.1]} /> <Dot center={derive(x, (x) => toScene(x, Math.sin(x)))} radius={0.14} color={derive(theme, (t) => t.palette.series[1])} /> <Text text={derive(x, (x) => `x = ${x.toFixed(2)}`)} y={3.4} /> </> );}
export default function ValueTrackerDot() { return ( <Stage units={14}> <Tracker /> </Stage> );}