Skip to content

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.

isSpiderType(type) in src/lib/graph/vertex-registry.ts is the single source of truth:

  • Phase-bearing — z, x, zbox, xbox. The data.phase carries the phase expression.
  • Decoration only — empty, black_dot, w, h, and, input, output. The phase renders but never affects computation. black_dot is 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).

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$ then is 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 red katex-error span), trust: false (blocks \href, \url, \includegraphics, so user-typed LaTeX can’t smuggle links onto the canvas), and output: "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.

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 subscribers

The 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:

  1. On module load, import("katex") is kicked off once and memoized.
  2. renderLabel reads the cached module synchronously via getKatex(). 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.
  3. useKatexReady() (src/lib/hooks/useKatexReady.ts) is a one-line useSyncExternalStore wrapper. 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.

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 ')' | unary
unary := '-' factor | '+' factor
number := [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.

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:

  1. Same detection rule. Both renderLabel and parsePhase treat a label as math iff its trimmed form is exactly $...$ / $$...$$. The renderer’s extractMathBlock and the parser’s stripMathDelimiters agree on this. (If you change one, change the other.)
  2. 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.
  3. The renderer never parses; the parser never renders. renderLabel produces display HTML and has no notion of numeric value; parsePhase produces 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.

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.

  • Graph Model — the phase field’s place in VertexData (graph slice) vs the visual label/labelLocation (view slice), and the isSpiderType predicate 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.