Skip to content

⚠ 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

Design: layout and rich text

sophistry should make general motion graphics, not only mathematical ones. Everything stays inside the scene: layout, styling and text are drawn on the canvas like every other node, so they share tracks, seekable timelines, cameras, bindings and frame export. Nothing animates DOM elements.

Four pieces get there:

  1. One rich text system: arbitrary inline styling, wrapping and lists from a single Text node.
  2. Units: design pixels for layout, scene units for maths, and a way to opt into either.
  3. Box: CSS-like flex and grid layout with typed inline styles, backed by a standalone layout engine.
  4. @sophistry/layout: that engine, written so it could stand on its own.
  • Block, float and table layout. Box is flex by default.
  • Selectors and the cascade. Styles are typed props on each node; only text properties inherit.
  • Box shadows, blur and blend modes, for the first pass.
  • Forms, scrolling and text selection. Interaction stays what it is today (dragging, hit testing, keyboard access); entering data belongs in the page’s DOM, outside the scene.
  • Bidirectional text.

Scene units already handle resizing: units spans the full width, so a bigger or smaller stage shows the same picture at a different resolution. Screen pixels would not: a 300 px panel would take a different share of a resized stage while the maths beside it scaled.

So layout uses design pixels, a fixed fraction of a scene unit. A stage is 1920 design pixels wide, so at the default units of 16, one scene unit is 120 px. The ratio is fixed when the scene is created; a stage that animates units to zoom zooms its boxes with everything else.

Situation Result
The stage grows or shrinks Everything scales together; nothing lays out again, and text wraps the same.
Export at 4K The same layout, sharper. 1920 is not an output resolution.
The aspect ratio changes Fixed-size boxes stay put; a box that fills the frame lays out again to the new height.
A camera zooms Boxes zoom with the scene.

The theme’s default font size, 0.4 units, is exactly 48 px.

Numbers are scalars; a node’s lengthUnit says what scales them.

<Box lengthUnit="scene" style={{ padding: 0.5, gap: 0.25 }} />
<Group lengthUnit="px">
<Circle radius={100} strokeWidth={4} />
</Group>
  • lengthUnit is "scene" or "px". It only scales: it never flips the y axis, and box flow is always top to bottom.
  • It applies to a node’s size and contents. The node’s own x and y stay in its parent’s units, the way group already treats scale.
  • Box defaults to "px". Maths nodes default to "scene". Text follows its surroundings: px inside a px box, scene units elsewhere.
  • Box, Text and Group accept it. Other definitions do not: their default lengths (tick sizes, arrow tips, gaps, dot radii) are scene values, so a composite such as Axes would draw near-invisible details in px. Size maths in pixels by putting it in a sized box instead.
  • Inside a box, one value can still mix units: "2u" is scene units and "100px" is design pixels, whatever the box’s lengthUnit.

Theme defaults need one fix: bakeStrokeStyle and bakeTextStyle multiply a missing strokeWidth or fontSize by the same scale as an authored one, so a default would shrink to 0.045 px under a px group. Defaults scale only by non-unit scales.

Text is the one text node. A plain string is the simple case; spans give arbitrary inline styling.

<Text
width={6}
text={[
"The ",
{ text: "derivative", color: "tomato", fontWeight: 700 },
" measures ",
{ text: "change", underline: true },
".",
]}
/>

In the core it is the same text prop: text.create({ width: 6, text: [...] }).

  • Without width, only newlines break; with it, text wraps.
  • Inline styles: color, fontFamily, fontSize, fontWeight, italic, letterSpacing, opacity, underline, strikethrough and highlight (a background fill).
  • textAlign places each line within the wrap width; lineHeight is a multiple of the largest font on each line.
  • Spans are plain values; a span changes when the text prop is set again. Readable span props, a progress per span, and baseline shifts for superscript and subscript can follow.
  • Words split across spans (["b", { text: "old", fontWeight: 700 }]) never break in the middle.
  • A markup() helper that parses a string into spans can follow later.

Changes to the existing text API (renamed outright, no aliases):

Node In this design
label, paragraph text
bulletedList A preset on the same layout, with rich items.
title A preset: Text pinned to the frame, plus its rule.
decimalNumber, variable Unchanged; tabular digits are their own job.
mathTex Unchanged; usable inline later.

A wrapped paragraph should not be a stack of child nodes. TextSpec carries a list of positioned fragments (text, position, style), and the renderer paints them in order. A plain one-line string is one fragment and costs what a label costs today, which matters because axis ticks, legends and most composites draw text.

Hit testing, bounds, progress reveals and halos work across all fragments of one spec.

Line breaking uses Pretext, through its rich-inline API: one run per span with its own font and letter spacing, breaks across run boundaries, Unicode word segmentation, and fixed-width atomic boxes. It returns line fragments with their widths, which map directly onto TextSpec fragments.

A pure function in spec/ does the work:

layoutText(runs, { width, lineHeight, align, pixelsPerUnit }): TextLayout

It is what Text calls, and what a box asks when it needs a text’s height at a given width.

Pretext needs a 2D canvas for measureText. Where there is none (server rendering, tests without a canvas) a greedy wrapper breaking at spaces takes over, measuring with the metrics estimate, so layout still works.

Text is measured at its size in design pixels. System fonts have optical sizes, so the same text is not quite proportionally wide at every size; when a fragment is drawn at another size (a zoomed camera, a high-density screen) the renderer fits it to its laid-out width.

Known limits: no bidirectional reordering, and no kerning across span boundaries.

Maths inside a sentence (“let x be real”) is common in maths explainers. A run is text or { inline: node, baseline? }. Layout asks only for the node’s width, and how far it reaches above and below the baseline: a Pretext atomic box, so lines break around it as around a word, and its line grows to hold it.

  • Text is a container: its inline nodes are its children, placed in scene units scaled with the text’s group, and disposed when dropped from the text.
  • Nodes are measured by their own box (ownBounds). A node that says where its baseline is (textBaseline()) sits on it; mathTex reports its first baseline from the typesetter, so the core never imports @sophistry/text. Other nodes are centred a little above the baseline unless the run gives baseline.
  • A node that changes size lays the text out again, through the same geometry watching a box uses.
  • progress writes the text’s glyphs only; inline nodes animate themselves.
<Box x={0} y={0} style={{ width: 1600, height: 900, padding: 48, gap: 32, flexDirection: "column" }}>
<Text text="Fourier series" fontSize={72} />
<Box style={{ flex: 1 }}>
<Axes xRange={[0, 6]} />
</Box>
</Box>
  • The root is an ordinary node. Its x and y are in the parent’s units and it is centred on them, like every other node. A Readable binds, so a box can follow a point on a graph.
  • Inside, numbers are px and y runs downward. Each box gives each child a space of its own (a container’s childSpaceFor), scaled from pixels to scene units, so a child moves without being wrapped in anything.
  • One layout per tree. Only the root computes layout. It builds one layout tree from the boxes nested directly inside it (and inside those) and lays it out in one pass, with the frame as the available size. A box behind another node (a group, say) is a root of its own.
  • Not a composite. Layout depends on the enclosing space, the reason TextLayoutNode is not built with defineComposite. Box follows that precedent.

Any node can be a box child.

  • Maths keeps y-up and scene units: a counter-scaled group cancels the px scale, so Axes means the same inside a box as outside.
  • The box measures text with measure(width), and any other node by its own outline, without the space the box gives it.
  • A box watches the scene nodes inside it (through groups too): when one’s geometry or transform runs again and its box changed, the tree lays out again.
  • Re-providing frameContext as each box’s content box, so toEdge, toCorner and nodes that fill the frame treat the box as their screen, can follow.
  • Boxes report ordinary bounds, so nextTo(box) and arrows from a box to a graph work.

Styles are typed inline props, one object per node. There are no selectors and no cascade. Text properties inherit from the nearest ancestor box that sets them; nothing else inherits.

Lengths: a number (in the node’s lengthUnit), "50%", "2u", "100px", or "auto".

Group Properties
Display display ("flex" by default, "grid", "none"), position ("relative", "absolute"), top, right, bottom, left
Size width, height, minWidth, maxWidth, minHeight, maxHeight, aspectRatio. Sizes always include padding and border.
Spacing margin, padding (a length, [vertical, horizontal] or [top, right, bottom, left]), and per-side forms such as paddingTop
Flex flexDirection, flexWrap, flex, flexGrow, flexShrink, flexBasis, justifyContent, alignItems, alignSelf, alignContent, gap, rowGap, columnGap
Paint background (colour or gradient), borderWidth, borderColor, borderRadius (per corner), opacity, overflow ("visible", "hidden")
Text (inherited) color, fontFamily, fontSize, fontWeight, italic, letterSpacing, lineHeight, textAlign, underline, strikethrough

Grid: display: "grid", gridTemplateColumns and gridTemplateRows (lengths, fr, "auto", "min-content", "max-content", minmax, fitContent, repeat with a count, "auto-fill" or "auto-fit"), gridAutoColumns, gridAutoRows, gridAutoFlow, gridColumn, gridRow, justifyItems and justifySelf. Templates are typed values, not CSS strings:

gridTemplateColumns: [{ fr: 1 }, 240, { minmax: [120, { fr: 2 }] }]

Moving, rotating and scaling a box are node props (x, y, rotation, scale), as on every other node. They never affect layout.

Style props map onto the existing stages, so an edit costs what the equivalent CSS change costs in a browser:

Change Cost
A size, spacing, flex, grid or text property The root lays out its tree again.
background, border*, opacity, color That node’s style stage only.
x, y, rotation, scale That node’s transform only.

Layout transitions animate boxes between two layouts: layoutTo(box, { style, children }, timing) is a seekable leaf. When it starts it records every node’s place in the tree (from the outermost box’s top left), applies the change and lays out once; as it runs, the outermost box shows each box’s size and each node’s position blended from its old place to its new one. Nodes are matched by identity, so reordering and moving between boxes in the tree glide. Styles switch at the start, and rewinding to the start puts the old ones back.

@sophistry/layout is a TypeScript flexbox and grid engine. It is built so it could become its own project without refactoring:

  • No sophistry imports and no runtime dependencies. A source-level test fails the build if that changes, as geometry/layering.test.ts does for the core.
  • Plain data in, plain data out. A tree of style objects and a measure callback go in; boxes come out. Numbers are unitless and y runs downward. No tracks, points or scene types.
  • Consumed only through its public entry. No /internal subpath; the core’s box uses the same API anyone else would.
  • Its tests live with it, along with their generator and the README that documents it on its own.
computeLayout(root: LayoutNode, available: Size, measure: MeasureFunction): LayoutResult

The measure callback answers “how big is this leaf at this width?”. Text height depends on width, so box forwards it to layoutText.

Behaviour matches Chrome for every supported property, so CSS intuitions carry over. Taffy is the reference implementation for the hard parts (flex line breaking, grid track sizing, intrinsic sizes). The code is written fresh, in TypeScript’s own idiom.

Tests are generated, not written by hand: each fixture is a small HTML layout, a script renders it in Chrome through Playwright and records every box, and the generated tests compare the engine’s output with those boxes. Running the tests needs no browser; only regenerating them does. Fixtures for unsupported features (block, floats, display: contents) are not generated.

The core gains what a box needs, and every shape benefits:

  • Rounded corners as true arcs, with a radius per corner. rect’s rounded corners are a faceted polyline today.
  • Per-side borders.
  • Images from files: an image definition on top of defineImage, with objectFit. ImageSpec carries raw pixels today.

Gradients, clipping, opacity and dashes already exist.

Package Contents
@sophistry/core Text, layoutText and the Pretext dependency; lengthUnit on Group; the scene’s design width; paint additions; Box (style parsing, the root and nested boxes, scene children) and layoutTo. Depends on the layout engine.
@sophistry/layout (new) The layout engine. Depends on nothing.
@sophistry/solidjs, @sophistry/react Box is generated with the core’s other components.

A box is a node like any other, so it lives in the core; the engine is a package of its own because it is useful, and testable, without a scene. @sophistry/layout is versioned with the other packages and joins the root build script, before the core.

  1. @sophistry/layout: flexbox and generated tests.
  2. Paint additions.
  3. Rich text: Text, spans, fragments, Pretext, presets.
  4. Units: the design width, lengthUnit, theme defaults.
  5. Box in the core, and the bindings.
  6. Grid.
  7. Layout transitions; inline nodes.
  • Pretext’s licence and measuring context. Confirm the licence, and how it is given a measuring context in headless scenes and tests.
  • Pinned to the screen. Cameras move everything, and nothing stays fixed to the screen during a camera move. A title that holds still needs a small layer of its own, useful without Box as well.
  • Responsive pixels. A panel whose text stays at 16 CSS pixels on a phone needs a mode where px follow the canvas’s CSS size and lay out again on resize. Only the scale factor changes, so design pixels do not block it; it is not part of the first pass.
  • Architecture: the layers, stages and invariants this design builds on.
  • Roadmap: where this sits among other work.