Labels & Phases
A vertex has two separate text fields. The phase (data.phase on the graph slice) is the
compute input for the spider/box types; the visual label (view slice label +
labelLocation) is display decoration for every vertex type. This page documents how a phase
string becomes HTML on the canvas, how the same string becomes a numeric phase, and how the
two paths stay in sync.
Three modules own this, all client-side:
| Module | Role |
|---|---|
src/lib/label/renderLabel.ts |
Label string → HTML (KaTeX or escaped plain text). Display only. |
src/lib/label/katex-loader.ts |
Lazy-loads KaTeX as a separate bundle chunk; re-render signal. |
src/lib/phase/parser.ts |
Phase expression → numeric radians. Consumed by the property panel and the compute layer. |
The Rust crate ports the parser (crates/zxw/src/phase.rs) so a phase parses identically on both sides
of the WASM boundary.
Which phases are parsed?
Section titled “Which phases are parsed?”isSpiderType(type) in src/lib/graph/vertex-registry.ts is the single source of truth:
- Phase-bearing —
z,x,zbox,xbox. Thedata.phasecarries the phase expression. - Decoration only —
empty,black_dot,w,h,and,input,output. The phase renders but never affects computation.black_dotis a phaseless Z spider: at compute time its phase is forced to 0 regardless of what was typed. For boundaries (input/output) the phase is purely cosmetic.
An empty phase on a spider means phase 0 (the identity). The renderer still shows nothing for an empty phase (the type’s default glyph is displayed instead).
The renderer: renderLabel
Section titled “The renderer: renderLabel”renderLabel(label) in src/lib/label/renderLabel.ts turns a label into safe-to-inject HTML,
returning { html, isLatex }. It routes on a single rule: a label whose trimmed form is exactly
$...$ (inline) or $$...$$ (display) is LaTeX; everything else is escaped plain text.
type RenderedLabel = { html: string; isLatex: boolean };
export function renderLabel(label: string): RenderedLabel;Key properties:
- Embedded math is intentionally not supported.
when $a = 0$ thenis not LaTeX here — it is escaped and shown verbatim. One math expression per label is the contract (a vertex body is small).isLatexLabel(label)exposes this predicate (no production callers today; tested). - Plain-text path is XSS-safe — it HTML-escapes
& < > " 'via a tiny inline escaper (no dependency). - KaTeX path is hardened —
throwOnError: true(a parse error falls back to escaped text, never a redkatex-errorspan),trust: false(blocks\href,\url,\includegraphics, so user-typed LaTeX can’t smuggle links onto the canvas), andoutput: "html"for compact output in the ~32 px vertex body. - Output is injected via
dangerouslySetInnerHTML— safe because both paths produce controlled HTML: escaped text upstream, and KaTeX output (which itself escapes) for math.
The two call sites are VertexLabelEditor (the label inside each vertex) and LabelPreview in
VertexPropertyPanel (the live “Renders” preview as you type); both consume .html synchronously.
Lazy-loading KaTeX
Section titled “Lazy-loading KaTeX”KaTeX is ~280 KB minified, and most labels are plain text — so it is lazy-loaded as a separate bundle chunk rather than imported statically. This keeps it off the route’s critical-path import graph, speeding up first compile and first paint.
src/lib/label/katex-loader.ts owns the load:
module load ──▶ import("katex") kicked off once (memoized) │ ▼ (async chunk fetch) chunk resolves ──▶ cache module, flip katexReady = true │ ▼ notify useSyncExternalStore subscribersThe tension this resolves: renderLabel is called synchronously from React render (its result
goes straight into dangerouslySetInnerHTML), but the KaTeX chunk loads asynchronously — a
synchronous function cannot await an async chunk load. The resolution:
- On module load,
import("katex")is kicked off once and memoized. renderLabelreads the cached module synchronously viagetKatex(). Three cases:- Plain text → rendered instantly; KaTeX is never touched.
- LaTeX + chunk loaded → rendered synchronously.
- LaTeX + chunk not yet loaded → falls back to escaped plain text for that one paint.
useKatexReady()(src/lib/hooks/useKatexReady.ts) is a one-lineuseSyncExternalStorewrapper. The two label-rendering components call it so they re-render exactly once when the chunk resolves, upgrading any fallback paint to rendered math.
In practice the fallback is rare: the chunk is fetched at module boot in parallel with the rest of
the app, so it has almost always landed by the time a user edits a LaTeX label. KaTeX’s CSS is
still loaded eagerly in src/app/layout.tsx, so styling is present before the JS chunk resolves —
a rendered label looks correct the moment its HTML is produced.
The chunk split is verifiable in the production build: KaTeX lands in its own file under
.next/static/chunks/, separate from the main route bundle.
The parser: parsePhase
Section titled “The parser: parsePhase”parsePhase(input) in src/lib/phase/parser.ts turns a phase expression into numeric radians,
returning a discriminated result rather than throwing, so callers can surface a readable
message:
type PhaseResult = | { ok: true; value: number } // value in radians | { ok: false; error: string };
export function parsePhase(input: string): PhaseResult;Grammar (v1, numeric only):
phase := term (('+' | '-') term)*term := factor (('*' | '/') factor)*factor := number | '\pi' | 'π' | 'pi' | 'PI' | '(' phase ')' | unaryunary := '-' factor | '+' factornumber := [0-9]+ ('.' [0-9]+)?Notable points:
- Empty / whitespace-only input returns
Ok(0)— the identity phase — so a blank spider phase means “no rotation”, matching the renderer’s “blank = show glyph” convention. - Math delimiters are stripped before parsing. A leading/trailing
$...$or$$...$$pair is removed, so the same string can be both rendered with KaTeX and parsed here — the linchpin that keeps the two paths in sync (see below). - Unicode operators are accepted as synonyms —
−(U+2212) for-,×(U+00D7) for*,÷(U+00F7) for/— so pasting from a typeset source works without retyping. - Free variables (
\alpha,\beta, …) are errors in v1 (symbolic arithmetic is planned Phase 6 work). A spider whose phase fails to parse is not a hard error at compute time — see Compute Layer.
The parser is consumed by the property panel’s live phase preview and (transitively, via the persisted
graph slice) by the Rust compute layer.
How the renderer and parser interact
Section titled “How the renderer and parser interact”The two paths are independent but share one invariant: the raw label string is the single source of truth, and math delimiters are stripped identically on both sides.
vertex label string (e.g. "$\\frac{\\pi}{4}$") │ ┌─────────────┴─────────────┐ ▼ ▼ renderLabel parsePhase (display path) (semantics path) │ │ detects $...$/$$...$$ strips $...$/$$...$$ │ │ ▼ ▼ KaTeX → HTML evaluate → radians (or escaped text (or { ok:false, error }) if not math) │ │ ▼ ▼ dangerouslySetInnerHTML property panel preview on the canvas + compute layer (via Rust)The contract that holds them together:
- Same detection rule. Both
renderLabelandparsePhasetreat a label as math iff its trimmed form is exactly$...$/$$...$$. The renderer’sextractMathBlockand the parser’sstripMathDelimitersagree on this. (If you change one, change the other.) - Plain text is never a phase error source. A non-math label on a spider still goes through
parsePhase; if it isn’t a valid numeric expression (e.g.hello), it returns{ ok: false, error }. At compute time this is downgraded to phase 0 + a warning, not a hard failure. - The renderer never parses; the parser never renders.
renderLabelproduces display HTML and has no notion of numeric value;parsePhaseproduces a number and has no notion of HTML. They share only the delimiter convention.
This is why a label like $\frac{\pi}{4}$ renders as a typeset fraction and computes as π/4
without any coordination between the modules — the string is unambiguous under the shared rule.
The Rust mirror
Section titled “The Rust mirror”crates/zxw/src/phase.rs ports parsePhase: the same grammar, delimiter stripping, and
Unicode-operator synonyms. So a phase parses the same way in the property panel (JS) and in the
tensor engine (Rust) — the values agree. The shared fixture
crates/zxw/tests/fixtures/phase_grammar.json pins the grammar on both sides (phase_grammar.rs
loads it in Rust; src/lib/phase/parser.test.ts in JS — add a case there and both sides pick it
up).
At compute time, a spider/box label that fails to parse is not a structural error — the
contraction downgrades it to phase 0 and pushes a human-readable string onto result.warnings.
Non-spider labels are decoration only and never warn. See Compute Layer
for the full error and warning model.
Where this fits
Section titled “Where this fits”- Graph Model — the
phasefield’s place inVertexData(graph slice) vs the visuallabel/labelLocation(view slice), and theisSpiderTypepredicate that decides whether a phase is parsed. - Compute Layer — how parsed phases feed the per-vertex tensor builders, and the warning-only treatment of parse failures.
- State Management — how phase edits flow through the store and the undo/redo policy that applies to them.