⚠ 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
Advanced projects
Bigger scenes built from the pieces in the other categories: epicycles and gradient descent from tracks and paths, a sorting algorithm recorded as a scrubbable timeline, a graph traversal, a custom shape written with defineShape and used like a built-in component, and exporting the canvas as a PNG.
Read the recipes alongside these: each is a walkthrough of a pattern you can see running here.
Sine curve from the unit circle
A point circles a unit circle while its height is traced out as a sine wave to the right.
3 collapsed lines
import { derive, GOLD, hold, track, valueTo } from "@sophistry/core";import { Circle, Dot, Line, Plot, Stage, usePlayer } from "@sophistry/solidjs";import { onSettled } from "solid-js";
const R = 1.5;const CENTER = { x: -3.6, y: 0 };const WAVE_X = -1.8;
export default function SineCurveUnitCircle() { const { play, signal } = usePlayer(); const theta = track(0); const dot = derive(theta, (theta) => ({ x: CENTER.x + R * Math.cos(theta), y: R * Math.sin(theta), })); const tip = derive([theta, dot], (theta, dot) => ({ x: WAVE_X + 0.9 * theta, y: dot.y, }));
onSettled(() => { void (async () => { while (!signal.aborted) { theta.set(0); await play( valueTo(theta, 2 * Math.PI, { duration: 6, easing: "linear" }), ); await play(hold(1.5)); } })(); });
return ( <Stage units={12}> <Line from={{ x: -5.6, y: 0 }} to={{ x: 5.2, y: 0 }} opacity={0.4} /> <Circle center={CENTER} radius={R} /> <Line from={CENTER} to={dot} /> <Line from={dot} to={tip} dash={[0.1, 0.1]} opacity={0.6} /> <Plot function={(t) => ({ x: WAVE_X + 0.9 * t, y: R * Math.sin(t) })} from={0} to={theta} stroke={GOLD} /> <Dot center={dot} /> <Dot center={tip} color={GOLD} /> </Stage> );}Fourier epicycles
Four circles chained end to end, each spinning at its own rate; the tip of the last arm traces a rounded square.
3 collapsed lines
import { derive, GOLD, hold, track, valueTo } from "@sophistry/core";import { Circle, Dot, Path, Plot, Stage, usePlayer } from "@sophistry/solidjs";import { For, onSettled } from "solid-js";
// Frequency n spins n times per revolution; radius 2.3 / n^2 shrinks fast.const TERMS = [1, -3, 5, -7].map((n) => ({ n, r: 2.3 / (n * n) }));
/** Joint positions of the chained arms at angle t, from the origin to the tip. */function arms(t: number) { const joints = [{ x: 0, y: 0 }]; for (const { n, r } of TERMS) { const last = joints[joints.length - 1]; joints.push({ x: last.x + r * Math.cos(n * t), y: last.y + r * Math.sin(n * t), }); } return joints;}
export default function FourierEpicycles() { const { play, signal } = usePlayer(); const t = track(0); const joints = derive(t, arms); const tip = derive(joints, (joints) => joints[TERMS.length]);
onSettled(() => { void (async () => { while (!signal.aborted) { t.set(0); await play(valueTo(t, 2 * Math.PI, { duration: 10, easing: "linear" })); await play(hold(2)); } })(); });
return ( <Stage units={12}> <For each={TERMS}> {(term, i) => ( <Circle center={derive(joints, (joints) => joints[i()])} radius={Math.abs(term.r)} opacity={0.5} /> )} </For> <Path points={joints} /> <Plot function={(s) => arms(s)[TERMS.length]} from={0} to={t} samples={300} stroke={GOLD} /> <Dot center={tip} color={GOLD} /> </Stage> );}Gradient descent
A point rolls down the contours of f(x, y) = (x^2 + 6y^2) / 2, zig-zagging across the narrow valley and leaving a trail.
19 collapsed lines
import type { CoordinateSystem, Point, SceneNode } from "@sophistry/core";import { coordsReadable, derive, GOLD, hold, moveTo, track, trackPoint,} from "@sophistry/core";import { AnnotationDot, Axes, Path, Stage, usePlayer,} from "@sophistry/solidjs";import { Contour } from "@sophistry/solidjs/charts";import { onSettled } from "solid-js";
const START = { x: -2.6, y: 1.2 };const RATE = 0.28;const X = Array.from({ length: 61 }, (_, i) => -3 + i * 0.1);const Y = Array.from({ length: 41 }, (_, i) => -2 + i * 0.1);const Z = Y.map((y) => X.map((x) => (x * x + 6 * y * y) / 2));
/** Data coordinates to scene units, through the axes' coordinate system. */const toScene = (coords: CoordinateSystem | null, p: Point) => coords?.coordsToPoint(p.x, p.y) ?? { x: 0, y: 0 };
export default function GradientDescent() { const { play, signal } = usePlayer(); const pos = trackPoint(START.x, START.y); const trail = track<Point[]>([START]); let axes!: SceneNode;
onSettled(() => { void (async () => { while (!signal.aborted) { pos.set(START); trail.set([START]); await play(hold(0.8)); for (let step = 0; step < 14; step++) { const { x, y } = pos.peek(); // The gradient of f is (x, 6y). const next = { x: x - RATE * x, y: y - RATE * 6 * y }; await play(moveTo(pos, next, { duration: 0.45 })); trail.set([...trail.peek(), next]); } await play(hold(1.5)); } })(); });
return ( <Stage units={12}> <Axes ref={(node) => { axes = node; }} xRange={[-3, 3, 1]} yRange={[-2, 2, 1]} width={7.5} height={5} > <Contour xs={X} ys={Y} values={Z} levels={8} /> </Axes> {/* The axes are made first, so `axes` is set by the time these props are. */} <Path points={derive( [coordsReadable(axes), trail, pos], (coords, trail, pos) => [...trail, pos].map((p) => toScene(coords, p)), )} stroke={GOLD} /> <AnnotationDot center={derive([coordsReadable(axes), pos], toScene)} /> </Stage> );}Sorting visualizer
Bars bubble-sort themselves: a slots model keeps each bar's identity, each swap is one plan.swapAt() played with an await, and the compared pair is highlighted.
17 collapsed lines
import { arcMotion, createSlots, derive, GOLD, hold, rowSlots, track,} from "@sophistry/core";import { Rect, Stage, Text, usePlayer, useTrackValue,} from "@sophistry/solidjs";import { For, onSettled } from "solid-js";
const VALUES = [5, 2, 7, 3, 8, 1, 6, 4];
export default function SortingVisualizer() { const { play, signal } = usePlayer(); // Keys are the bar values; the model owns which bar is in which slot. const slots = createSlots(VALUES, { layout: rowSlots({ spacing: 1.2 }), motion: arcMotion({ bend: 0.3 }), duration: 0.35, }); const items = useTrackValue(slots.items); const active = track<number[]>([]);
onSettled(() => { void (async () => { while (!signal.aborted) { // Each `plan()` starts from the order the last play left. for (let end = VALUES.length - 1; end > 0; end--) { for (let i = 0; i < end; i++) { const order = slots.order.peek(); const [a, b] = [order[i], order[i + 1]] as [number, number]; active.set([a, b]); await play(hold(0.2)); if (a > b) await play(slots.plan().swapAt(i, i + 1)); } } active.set([]); await play(hold(1.5)); await play(slots.plan().permute(VALUES, { lag: 0.05 })); await play(hold(0.5)); } })(); });
return ( <Stage units={12}> <For each={items()}> {(item) => { const lit = derive(active, (active) => active.includes(item.key)); return ( <Rect center={derive(item.position, (position) => ({ x: position.x, // The arc's lift, so swapping bars pass round each other. y: position.y - 2.5 + item.key / 4, }))} width={1} height={item.key / 2} opacity={derive(lit, (lit) => (lit ? 1 : 0.55))} fill={derive(lit, (lit) => (lit ? GOLD : undefined))} /> ); }} </For> <Text text="bubble sort" y={2.8} /> </Stage> );}Scrubbable bubble sort
A sort recorded as one timeline: bars keep their identity in a slots model, every compare and swap is an animation, so you can play, pause, step and scrub the whole run in either direction.
18 collapsed lines
import { type Animation, arcMotion, colorTo, createClock, createSlots, derive, indicate, parallel, resolveTheme, rowSlots, type SlotItem, sequence, timeline, track,} from "@sophistry/core";import { Rect, Stage, Text, useTrackValue } from "@sophistry/solidjs";import { For, onSettled } from "solid-js";
const VALUES = [5, 2, 7, 3, 8, 1, 6, 4];
export default function ScrubbableSort() { // The recorded run bakes in the colours of the page's theme at mount. const colors = resolveTheme().palette; const clock = createClock();
// Identity and slots live in the model; each bar's value is its key. Items // keep their own tracks (position, scale), so bars never re-mount. const slots = createSlots(VALUES, { layout: rowSlots({ spacing: 1.25 }), motion: arcMotion({ bend: 0.3 }), duration: 0.4, }); const items = useTrackValue(slots.items); const fills = new Map(VALUES.map((v) => [v, track(colors.series[0])])); const scaleOf = (key: number) => (slots.item(key) as SlotItem<number>).scale;
// Record the whole run up front; the plan tracks the order as we go. const plan = slots.plan(); const steps: Animation[] = []; for (let end = VALUES.length - 1; end > 0; end--) { for (let i = 0; i < end; i++) { const a = plan.order[i] as number; const b = plan.order[i + 1] as number; const parts: Animation[] = [ parallel( indicate(scaleOf(a), { color: fills.get(a), duration: 0.4 }), indicate(scaleOf(b), { color: fills.get(b), duration: 0.4 }), ), ]; if (a > b) parts.push(plan.swapAt(i, i + 1)); steps.push(sequence(...parts)); } // The largest remaining bar has bubbled into place. const done = fills.get(plan.order[end] as number); if (done) steps.push(colorTo(done, colors.positive, { duration: 0.25 })); } const first = fills.get(plan.order[0] as number); if (first) steps.push(colorTo(first, colors.positive, { duration: 0.25 }));
// Where each step ends, for the "step" buttons. const ends: number[] = []; let t = 0; for (const step of steps) { t += step.duration; ends.push(t); }
const tl = timeline(sequence(...steps), { clock }); const time = useTrackValue(tl.time); const playing = useTrackValue(tl.playing); const stepIndex = derive( tl.time, (time) => ends.filter((end) => end <= time + 1e-6).length, ); const jump = (direction: 1 | -1) => { tl.pause(); const now = tl.time.peek(); const target = direction === 1 ? (ends.find((end) => end > now + 1e-6) ?? tl.duration) : ([0, ...ends].filter((end) => end < now - 1e-6).pop() ?? 0); tl.seek(target); };
onSettled(() => { void tl.play(); return () => tl.abort(); });
return ( <div> <Stage units={12} clock={clock}> <For each={items()}> {(item) => ( <Rect center={derive(item.position, (position) => ({ x: position.x, // The arc's lift, so swapping bars pass round each other. y: position.y - 1.5 + item.key / 4, }))} width={1} height={item.key / 2} scale={item.scale} fill={fills.get(item.key)} /> )} </For> <Text text={derive(stepIndex, (index) => `step ${index} / ${steps.length}`)} y={2.8} fontSize={0.4} /> </Stage> <div style={{ display: "flex", gap: "0.5rem", "align-items": "center", "margin-top": "0.5rem", }} > <button type="button" onClick={() => jump(-1)}> Step back </button> <button type="button" style={{ "min-width": "5rem" }} onClick={() => (tl.playing.peek() ? tl.pause() : void tl.play())} > {playing() ? "Pause" : "Play"} </button> <button type="button" onClick={() => jump(1)}> Step </button> <input type="range" aria-label="Timeline position" min={0} max={tl.duration} step="any" value={time()} style={{ flex: "1" }} onInput={(e) => { tl.pause(); tl.seek(Number(e.currentTarget.value)); }} /> </div> </div> );}Breadth-first traversal
A BFS over a small graph. The visit order is computed once; a single step counter drives which vertices and edges are lit.
10 collapsed lines
import { derive, hold, sequence, track, valueTo } from "@sophistry/core";import { edgeKey } from "@sophistry/core/geometry";import { NetworkGraph, Stage, Text, usePlayer, useScene,} from "@sophistry/solidjs";import { onSettled } from "solid-js";
const vertices = ["a", "b", "c", "d", "e", "f", "g"];const edges: [string, string][] = [ ["a", "b"], ["a", "c"], ["b", "d"], ["b", "e"], ["c", "f"], ["c", "g"], ["e", "f"],];
/** Visit order plus the edge each vertex was discovered through. */function bfs(start: string) { const order = [start]; const via = new Map<string, [string, string]>(); for (let head = 0; head < order.length; head++) { const u = order[head]; for (const [s, t] of edges) { const v = s === u ? t : t === u ? s : undefined; if (v && !order.includes(v)) { order.push(v); via.set(v, [u, v]); } } } return { order, via };}
function Traversal() { const theme = useScene().theme; const { play, signal } = usePlayer(); const { order, via } = bfs("a"); // How many vertices have been visited so far; the only moving part. const step = track(0); const visited = derive(step, (step) => order.slice(0, Math.round(step)));
const vertexConfigs = derive([visited, theme], (visited, theme) => Object.fromEntries( visited.map((v) => [v, { color: theme.palette.highlight }]), ), ); const edgeConfigs = derive([visited, theme], (visited, theme) => Object.fromEntries( visited.flatMap((v) => { const edge = via.get(v); return edge ? [ [ edgeKey(...edge), { stroke: theme.palette.highlight, strokeWidth: 0.07 }, ], ] : []; }), ), );
onSettled(() => { void (async () => { while (!signal.aborted) { await play( sequence( hold(0.6), valueTo(step, order.length, { duration: 4, easing: "linear" }), hold(1.2), valueTo(step, 0, { duration: 0.6 }), ), ); } })(); });
return ( <> <NetworkGraph vertices={vertices} edges={edges} layout="tree" layoutOptions={{ root: "a" }} layoutScale={{ width: 8, height: 4 }} labels vertexConfigs={vertexConfigs} edgeConfigs={edgeConfigs} /> <Text text={derive( visited, (visited) => `visited: ${visited.join(" ") || "-"}`, )} y={-3.4} fontSize={0.4} /> </> );}
export default function GraphTraversal() { return ( <Stage units={12} aspect={1.5}> <Traversal /> </Stage> );}A custom shape: Spiral
A new primitive in a dozen lines. defineShape takes the props and a geometry function, so it gets styling, transforms, gradients, draw() and paint order like any built-in; wrap() makes it a component.
11 collapsed lines
import type { Point, ShapeProps } from "@sophistry/core";import { defineShape, derive, draw, Invalidate, shapeProps, track,} from "@sophistry/core";import { Stage, usePlayer, useScene, wrap } from "@sophistry/solidjs";import { onSettled } from "solid-js";
interface SpiralProps extends ShapeProps { center?: Point; /** Radius after `turns` full turns, in scene units. */ radius: number; turns?: number;}
/** * An Archimedean spiral: radius grows linearly with the angle. Each prop says * which stage of the shape's pipeline it invalidates (core's `Invalidate` bits). */const spiral = defineShape<SpiralProps>({ name: "Spiral", props: { ...shapeProps, center: { invalidates: Invalidate.GEOMETRY }, radius: { default: 1, invalidates: Invalidate.GEOMETRY }, turns: { default: 3, invalidates: Invalidate.GEOMETRY }, }, geometry: (props) => { const turns = props.turns ?? 3; const steps = Math.ceil(turns * 48); const points = Array.from({ length: steps + 1 }, (_, i) => { const u = i / steps; const angle = u * turns * Math.PI * 2; return { x: (props.center?.x ?? 0) + props.radius * u * Math.cos(angle), y: (props.center?.y ?? 0) + props.radius * u * Math.sin(angle), }; }); return { polylines: [points], closed: false }; },});const Spiral = wrap(spiral);
function Spirals() { const theme = useScene().theme; const { play } = usePlayer(); const drawn = track(0);
onSettled(() => { void play(draw(drawn, { duration: 3 })); });
return ( <> <Spiral center={{ x: -2.6, y: 0 }} radius={2.2} turns={3} progress={drawn} stroke={derive(theme, (t) => t.palette.series[0])} strokeWidth={0.07} /> <Spiral center={{ x: 2.6, y: 0 }} radius={2.2} turns={5} progress={drawn} rotation={derive(drawn, (drawn) => drawn * Math.PI)} stroke={derive(theme, (t) => t.palette.series[1])} strokeWidth={0.05} dash={[0.2, 0.12]} /> </> );}
export default function CustomSpiralShape() { return ( <Stage units={10}> <Spirals /> </Stage> );}Export a PNG
The stage's ref hands you the scene. captureFrame encodes scene.canvas as last painted; download the blob.
4 collapsed lines
import type { Scene } from "@sophistry/core";import { captureFrame, derive, rotateBy, track } from "@sophistry/core";import { Circle, Stage, Text, usePlayer, useScene } from "@sophistry/solidjs";import { onSettled } from "solid-js";
function Orbit() { const palette = derive(useScene().theme, (theme) => theme.palette); const { play } = usePlayer(); const angle = track(0);
onSettled(() => { void play(rotateBy(angle, 2 * Math.PI, { duration: 8, easing: "linear" })); });
return ( <> <Circle center={{ x: 0, y: 0 }} radius={2.5} stroke={derive(palette, (palette) => palette.grid)} /> <Circle center={derive(angle, (angle) => ({ x: 2.5 * Math.cos(angle), y: 2.5 * Math.sin(angle), }))} radius={0.4} fill={derive(palette, (palette) => palette.series[0])} /> <Text text="a moving frame, saved on click" y={-3.4} color={derive(palette, (palette) => palette.muted)} /> </> );}
export default function ExportStill() { let scene: Scene | undefined;
const exportPng = async () => { const canvas = scene?.canvas; if (!canvas) return; const blob = await captureFrame(canvas, { type: "image/png" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = "sophistry-still.png"; link.click(); URL.revokeObjectURL(url); };
return ( <div> <Stage units={10} aspect={4 / 3} ref={(created) => { scene = created; }} > <Orbit /> </Stage> <button type="button" onClick={() => void exportPng()} style={{ "margin-top": "0.5rem" }} > Export PNG </button> </div> );}Export an image sequence
exportFrames seeks a timeline to exact instants, paints each one synchronously and encodes the canvas. The thumbnails are real exported frames.
4 collapsed lines
import type { Readable, Scene } from "@sophistry/core";import { derive, exportFrames, rotateTo, track } from "@sophistry/core";import { Circle, Stage, Text, usePlayer, useScene } from "@sophistry/solidjs";import { createSignal, For, onCleanup } from "solid-js";
interface Thumb { url: string; time: number;}
/** A dot on a ring at `angle`, in the scene's theme colours. */function Orbit(props: { angle: Readable<number> }) { const palette = derive(useScene().theme, (theme) => theme.palette);
return ( <> <Circle center={{ x: 0, y: 0 }} radius={2.5} stroke={derive(palette, (palette) => palette.grid)} /> <Circle center={derive(props.angle, (angle) => ({ x: 2.5 * Math.cos(angle), y: 2.5 * Math.sin(angle), }))} radius={0.4} fill={derive(palette, (palette) => palette.series[0])} /> <Text text="rendered frame by frame" y={-3.4} color={derive(palette, (palette) => palette.muted)} /> </> );}
export default function ExportFrames() { const { timeline } = usePlayer(); const angle = track(0); const spin = timeline( rotateTo(angle, 2 * Math.PI, { duration: 2, easing: "linear" }), ); let scene: Scene | undefined; const [thumbs, setThumbs] = createSignal<Thumb[]>([]); const [busy, setBusy] = createSignal(false);
const release = () => { for (const thumb of thumbs()) URL.revokeObjectURL(thumb.url); }; onCleanup(release);
const run = async () => { const canvas = scene?.canvas; if (!canvas || busy()) return; setBusy(true); release(); setThumbs([]); try { // 2 s at 6 fps, the last frame excluded so the sequence would loop. const frames = await exportFrames({ timeline: spin, canvas, fps: 6, to: 2 - 1 / 6, type: "image/webp", quality: 0.8, }); setThumbs( frames.map((frame) => ({ url: URL.createObjectURL(frame.blob), time: frame.time, })), ); } finally { setBusy(false); } };
return ( <div> <Stage units={10} aspect={4 / 3} ref={(created) => { scene = created; }} > <Orbit angle={angle} /> </Stage> <button type="button" onClick={() => void run()} disabled={busy()} style={{ "margin-top": "0.5rem" }} > {busy() ? "Exporting..." : "Export 12 frames"} </button> <div style={{ display: "flex", "flex-wrap": "wrap", gap: "0.25rem", "margin-top": "0.5rem", }} > <For each={thumbs()}> {(thumb) => ( <img src={thumb.url} alt={`Frame at ${thumb.time.toFixed(2)} seconds`} title={`t = ${thumb.time.toFixed(2)} s`} style={{ width: "96px", "border-radius": "4px" }} /> )} </For> </div> </div> );}