Layout and Render Passes in GoFish Graphics
This document explains the order and mechanics of layout and render passes in the GoFish graphics system, with specific examples and code references.
Overview
The GoFish rendering pipeline transforms a declarative chart specification into a rendered SVG visualization through a series of well-defined passes. The process can be divided into two main phases:
- Layout Phase: Computes positions, sizes, and spatial relationships
- Render Phase: Lowers the laid-out tree into a flat display-list IR, then paints that IR with a backend (SVG today)
Entry Point: The gofish() Function
The rendering process begins with the gofish() function in src/ast/gofish.tsx. This function orchestrates the entire pipeline:
const runGofish = async (): Promise<LayoutData> => {
const session: RenderSession = {
scopeContext: new Map(),
scaleContext: { unit: { color: new Map() } },
keyContext: {},
};
try {
const contexts = {
session,
};
const layoutResult = await layout(
{ w, h, x, y, transform, debug, defs, axes },
child,
contexts
);
return {
...layoutResult,
scaleContext: session.scaleContext,
keyContext: session.keyContext,
};
} finally {
// session is per-run and naturally discarded here
}
};The chart builders do one thing between resolving a chart and handing it to gofish(): they install the build-in (installBuildIn in src/animation/install.ts, called from resolveForRender and from a mark's or a combinator's render terminal alike, on the first render only). It reads the transitions off the resolved tree, checks each one's phases against the clock that plays it, solves the enter timing, and puts every animated mark on one clock for the chart. The timing depends on the tree's structure and data, not on layout, so it is read before the chrome passes below add axes and legends, which therefore appear at once. The builders' render options playing and at hold that clock, as the options of the same names hold a time.sequence's.
Layout Phase
The layout phase is handled by the layout() function, which performs multiple passes over the chart tree.
Pass 1: Context Initialization
Location: src/ast/gofish.tsx:272-275
Three per-run session contexts are initialized:
scopeContext: Manages variable scoping and data bindings (type:Map)scaleContext: Stores computed color scales and scale mappings (type:{ unit: { color: Map<any, string> } })keyContext: Maps string keys to nodes for axis labeling (type:{ [key: string]: GoFishNode })
These are attached to the render session and propagated to the node tree, rather than stored as module-global mutable state. This establishes clean state for the rendering process and ensures no interference between multiple chart renders.
Calendar math (a time axis's cells) runs synchronously during elaboration, on the Temporal API that applySchema (schema.ts) loads when the chart's data has a time column (loadTemporal() in calendar.ts): the native API where the runtime has one, else temporal-polyfill, imported only then. A time axis needs a time column, so layout itself loads nothing, and a chart without one never loads the polyfill.
Pass 2: Color Scale Resolution
Location: src/ast/gofish.tsx:172
child.resolveColorScale();Implementation: src/ast/_node.ts:175-192
This pass traverses the tree and:
- Identifies color encodings (e.g.,
fill: "category"in bar charts) - Assigns colors from the
color6palette - Stores mappings in
scaleContext.unit.color
Example: In a bar chart with fill: "category", each unique category value gets assigned a color from the palette.
Pass 3: Reference Resolution
Location: src/ast/gofish.tsx (after resolveAliases, Pass 5.5)
resolveReferences(child);Implementation: src/ast/_ref.tsx (resolveReferences)
The one resolver for every reference in the tree. It registers token names in their scopes, resolves each ref to its target, resolves each layer's constraint operands and paint-order operands to nodes (writing each operand's key, the node's uid, which the placement solve reads), and checks each layer's .relate() clauses for a cycle. It runs after resolveAliases, because that pass installs the operators' constraints, and again after every pass that rewrites the tree (reresolve). See Name Resolution & Scoping.
Pass 4: Key Resolution
Location: src/ast/gofish.tsx:174
child.resolveKeys();Implementation: src/ast/_node.ts:203-210
Assigns unique keys to nodes. These keys are critical for:
- Axis labeling: Ordinal axes use keys to position category labels
(Legends do not use keys — they are elaborated from the resolved color map; see Legends.)
Example: In a bar chart using spread("category", { dir: "x" }), each bar gets a key like "category-value", which is later used to position the x-axis labels.
Pass 5: Size Domain Inference
Location: src/ast/gofish.tsx:175
const sizeDomains = child.inferSizeDomains();Implementation: src/ast/_node.ts:225-232
Determines the intrinsic size requirements for each dimension. For rect shapes, this is implemented in:
Location: src/ast/shapes/rect.tsx:171-176
inferSizeDomains: (shared, children) => {
return {
w: computeIntrinsicSize(dims[0].size),
h: computeIntrinsicSize(dims[1].size),
};
};The computeIntrinsicSize() function returns a size claim: a Pwl.Value, a piecewise linear function of the scale factor σ (src/ast/solver/pwl.ts), that gives the pixel size for a scale. Layout reads it later to decide how much room each element needs.
Pass 5.5: Axis-Name Resolution
Location: src/ast/gofish.tsx (child.resolveAliases()), src/ast/_node.ts (resolveAliases)
x/y/w/h mean axis 0 and axis 1 in every coordinate space. A coordinate transform may also declare names for its two axes in its aliases field: Coord.polar()/Coord.clock() declare { x: "theta", y: "r" } and Coord.geo() declares { x: "lon", y: "lat" }. That declaration is the only source of the names. They are used in two places, and in both the meaning of a name depends on where the node sits, which a factory does not know when it runs:
- a box-dims mark's
dimsoption, keyed by axis name (rect({ dims: { theta: { size: 0.4 } } })), and a treemap'sdimsfor its own box. Channel inference has already run on it at build time: a mark gives each slot a kind by its structure (sizeis a size channel; a bare value,min,center,maxare positions), and an operator gives each slot the channel of its top-level counterpart. Neither depends on the axis, somapAxisDimsapplies it before the axis is known. - an operator's
dir(spread, stack) and a scatter'sdims. Everything in these operators that needs the axis (the align/distribute or position constraints andaxisDir) waits for the axis, and so do the constraints.relate()installs. Spread's per-entrysizewrapper uses adimsoption keyed bydir, so it resolves in the same pass.
Both kinds of work are deferred the same way: the factory sets one hook on the node, _elaborateInAxisScope(outer, inner). outer is the scope the node's own box lives in (its parent's scope, even on a coord) and inner is the scope of its children. A mark's hook (deferAxisDims in dims.ts) writes its dims bag onto its per-axis dims array against outer with applyAxisDims. An operator's hook resolves its names against inner and calls .relate(), which is async. A spread given its own dims runs the layer's dims hook first, then its own.
resolveAliases is a top-down pass (run before underlying space, which reads the dims and the constraints) that carries the axis scope, whose names map each name to an axis, starting at { x: 0, y: 1 }. Every coord replaces the scope for its subtree with x, y, and the names its transform declares. Most transforms (linear, wavy) declare none, so inside them only x/y are visible: a name has a meaning only inside the space that declares it, and the innermost coord wins. A coord declares its space on its node (_space: the transform's aliases and type). The scope also carries warpedBy, the type of the nearest enclosing space that is not linear, for work that is only correct in a linear one (scatter's overlap). The walk is synchronous: it queues each node's hook with its two scopes, in pre-order. The pass then runs the queue one hook at a time, in that order. It does not run them concurrently, so a hook never interleaves with a descendant's. An operator installs its constraints through the core of .relate() (INTERNAL_relate), which builds no environment, since the operator refers to its children by slot. The walk sees the tree before any hook runs; that is enough, because spread's and scatter's constraints add no nodes. A name the scope does not declare throws, listing the names it does; so does setting one (axis, anchor) slot twice, across the top-level keys and dims or within dims. Scatter merges its top-level x/xMin/xMax (and y ones) with its dims through the same mergeAxisDims as the marks, with its own rules: a bare value is the point (center), and size is not a key. A span is checked on the merged axis, so xMin with dims.x.max is a span, and one end without the other throws, from either spelling. Like the later embedding pass it mutates the per-axis dims array by reassigning its elements, so the captured layout/space closures observe the result.
A hook is cleared once it has run to completion, so the pass is idempotent. A hook that throws stays, and so do the hooks queued after it, so a rerun reports the same error instead of skipping work. That lets gofish.tsx rerun it after axis, title, and legend elaboration, whose chrome is built from Spread nodes that install their constraints in this pass. See Authoring Coordinate Transforms.
Pass 6: Underlying Space Resolution
Location: src/ast/gofish.tsx:176
const [underlyingSpaceX, underlyingSpaceY] = child.resolveUnderlyingSpace();Implementation: src/ast/_node.ts:212-223
This is one of the most important passes. It determines the underlying space type for each dimension, which affects how scales are computed and how axes are rendered. A second walk over the same tree, resolveExtent(), then computes each continuous dimension's size claim (an Extent: ascent, descent, and width, each a Pwl.Value, piecewise linear in σ) from the children's claims and the already-resolved types. Types never read claims; layout reads both.
Underlying Space Kinds (defined in src/ast/underlyingSpace.ts). Since the #586 collapse there are only three kinds — continuous, ordinal, undefined — and the old POSITION / DIFFERENCE / SIZE trichotomy is now three origin states of the single continuous kind (read via the originOf(space) read):
CONTINUOUS: one data-driven extent, a signeddataIntervalin data units about its local origin plus anoriginstate:origin: "pinned"— POSITION: the interval is the absolute data domain (e.g.x: value(5)); builds a position scale (niced per σ-scope at the scope's solve, when an axis views the scope — issue #659), absolute axis.origin: "free"— SIZE: a baseline magnitude, sized but unplaced (e.g.h: "value"with no min),[−descent, ascent]about its baseline; no position scale.origin: "none"— DIFFERENCE: unanchorable, only differences are meaningful (stacked/centered); a length scale, so no axis, and a length entry in the legend.
ORDINAL: Discrete categorical scale (e.g.,spread("category"))UNDEFINED: No data-driven encoding
See Underlying Space for the full treatment of this intermediate representation.
Constraints participate too. resolveUnderlyingSpace passes a node's positioning constraints to its resolver (a fourth constraints argument). A layer folds the datum coordinates of its Constraint.position constraints into a POSITION domain on that axis (collectPositionDomains), unioned with the children's spaces — so a position constraint contributes a fragment of this pass, which is what lets the layer build a data→pixel scale to resolve those constraints at layout time. See Operators vs Constraints.
Example for Bar Chart Rectangles:
Location: src/ast/shapes/rect.tsx:92-169
For a vertical bar chart where:
- X-axis:
spread("category")→ORDINALspace - Y-axis:
h: "value"→SIZEspace (if no min) orPOSITIONspace (if min is specified). TheSIZEspace isCONTINUOUS(interval(0, value), "free"): the value's positive part is its ascent and its negative part its descent, so a negative bar extends below its baseline. A rect writes no claim hook, so its claim is the one its type implies:value·σon the matching side.
The logic in resolveUnderlyingSpace checks:
if (!isValue(dims[0].min) && !isValue(dims[0].size)) {
underlyingSpaceX = ORDINAL([]);
} else if (isAesthetic(dims[0].min) && isValue(dims[0].size)) {
underlyingSpaceX = CONTINUOUS(interval(0, getValue(dims[0].size)!), "none");
} else if (!isValue(dims[0].min) && isValue(dims[0].size)) {
underlyingSpaceX = CONTINUOUS(interval(0, getValue(dims[0].size)!), "free");
} else {
const min = isValue(dims[0].min) ? getValue(dims[0].min) : 0;
const size = isValue(dims[0].size) ? getValue(dims[0].size) : 0;
const domain = interval(min, min + size);
underlyingSpaceX = CONTINUOUS(domain, "pinned");
}Pass 7: Chrome Elaboration
Location: src/ast/gofish.tsx (layout()), src/ast/axes/elaborate.tsx
resolveAxes walks the tree top-down flagging which node owns an axis on each dimension, and draws it where the nearest chart's axes option turns that dimension on (the render's axes at the root, each chart's own below it). Ownership records a signature per claimed dim: a continuous axis claims it opaquely (single-owner — the root-most one wins, descendants defer to the chart-level scale), and only at a chart() boundary or the render root (Axes). An axis whose chart turns it off is still owned, so it is hidden rather than drawn lower down. Ordinal axes nest — a node claims its own ordinal axis even under an ancestor ordinal axis, as long as it is a different grouping (a finer level). So a grouped or faceted chart renders one ordinal axis per grouping level (per facet) — e.g. a spread(lake)+stack(species) bar gets an outer lake axis and a per-lake species axis. Wherever it sets an owning flag, resolveAxes also leaves a persistent axisDemand stamp — the axis's ticks (AxisTicks: a count; a time axis adds its rows when it is elaborated, since they depend on the levels below it), which later gate and shape per-scope domain nicing at the σ-scope solves (issue #659), since resolveNiceDomains's old per-node tree walk is gone; nicing is now demand- driven at each scope's own solve (below). Then elaborateChrome rewrites the tree. Each node that owns chrome (axes, axis titles, a legend) is wrapped in rings of Layers containing ordinary rect/text/spread shapes wired with align/distribute/position constraints. Chrome is not a privileged node type, and there is no chrome-specific code later in the pipeline. After this pass it is just nodes. Because the rewrite inserts new nodes and moves keys onto wrappers, the name, alias, and underlying space passes rerun on the new tree. The color scale does not: it was final before the pass, and chrome adds no data colors. Label elaboration follows and reruns the same passes. Domain nicing is not a tree pass at all: each sized node nices its keyed domain at its solve, if some node draws an axis over that domain (KeyedDomains, built once after the first type walk, before chrome, so chrome only reads the domains; the nodes a rewrite adds read the seat of the content they wrap).
See Axes for the full elaboration story (the two-tier structure, origin pins, negative-space gutters, and the continuous/difference/ordinal kinds).
The chart's options describe the chrome of the chart root. layout() passes elaborateChrome two answers that apply only to the root:
- Axis titles. The root titles each axis it owns that the
axesoption turns on. The title text is the option'stitle, or else the axis's title (spaceTitle: a continuous axis names itself by its quantity names, joined with", ", never by its unit; an ordinal axis by its grouping field). A space with no measure has no title. The title is read off the root's space before elaboration re-resolves it, so it names the OUTERMOST grouping (lake, not the innerspecies). - The legend. Axes are for scales that have positions; legends are for scales that do not. The color scale is resolved once, from the root, and each length scale the root maps (a space with no origin) is read off the keyed domains (
KeyedDomains.lengthScales), so the root carries one legend with an entry for each that thelegendoption leaves on.
Each title is a ring seated past the root's axes and centered on the axis line it describes. The legend is the ring outside that, so it is seated past the titles. Each ring is marked GoFishNode._chromeRing, and nothing records the boxes inside it: layout() reads the root's axis direction off the content, which GoFishNode.dressedBox finds by walking the rings' first children. The chrome takes room: every chrome shape claims its size, and each ring claims it where it places it (see Chrome around a chart under Pass 9). See Axes and Legends.
Pass 8: Position Scale Computation
Location: src/ast/gofish.tsx (layout()), src/ast/solver/scopes.ts
const scope =
keyed !== undefined
? scopes.scopeAt(meta, space, claim, keyed)
: scopes.fit(
meta,
given[axis] === undefined ? undefined : root,
space,
claim,
allocated
);For every continuous root axis, the one scope fit (ScopeRegistry.fit) solves σ from the axis's size claim against the canvas (claim.width(σ) = canvas), so pixel overhead such as spacing, and the chrome, keeps its pixels, and, when the axis has an origin, the pixel of data 0 (originPx). The canvas is the render's w/h: the render size is the whole graphic (#493). A claim with no σ in it maps no domain and is not solved. When no σ ≥ 0 fits, the rest of the one rule for a claim in its slot (Pwl.fill, which ScopeRegistry.solveFixed also uses to lay a plot out in a node's own size) picks σ: 0 where the claim's fixed parts fill the canvas up to rounding (Pwl.overflows), else, where they are larger than the canvas, the σ solved from the part of the claim that grows with σ (Pwl.rising), so the data fills the canvas as if the fixed parts took no room, the fixed parts overflow, and the fit warns (see Layout warnings). The same fit, with the same rule, serves a layer with a size of its own and a coord boundary. Next to σ, the fit returns the box it laid the claim out in (Fitted.box): the slot, or the claim at its σ where that is longer, and a claim that is only pixels is its own box. Only a slot that is a limit (the render's size, a layer's own size) warns; the default canvas grows to hold the claim, and a coord's budget does not warn. The root's size is that box, so a root whose claim overflows the render's size is its claim, seated at the canvas's top-left: a y-up root overflows past the bottom, not the top. A layer with a size of its own is that size whatever its content claims, so it reads its size, not the box. A root whose nodes with a literal size map its keyed domain maps it at the σ they solved (ScopeRegistry.keyedSigma), on an axis the render does not size, and on one it does where the root's content claims no data of its own there (its plot has a size of its own, and only chrome such as a legend's length entry maps the domain): the render's slot sets no second σ. Any other unsized root is fitted to the default canvas, which is not a limit: it grows to hold what does not fit, so the fit does not warn there (#1179). A pinned axis hands its content the map px(d) = σ·d + originPx; a free root is placed at originPx. A one-value domain (a one-point chart) has no width for σ to scale, so its value maps to the middle of the canvas, as in d3 and Vega-Lite: σ is 0 and the claim is centered.
Pass 8.5: Embedding Resolution
Location: src/ast/gofish.tsx (child.resolveEmbedding()), src/ast/_node.ts (resolveEmbedding)
resolveEmbedding is the sole author of each dim's embedded flag — the flag the shape renders switch on for point (0 embedded axes) / line (1) / area (2). It runs top-down after underlying space resolves and before layout, and mutates the shared args.dims element in place (like resolveAliases) so the captured render closure observes it. Explicit emX/emY (and connect's embed()) lock the flag to true and are never recomputed.
A dim embeds iff its size is a data value or unsized (baseEmbedded, data.ts) AND, only inside a coordinate space, it is no glyph size (GoFishNode.isGlyph, #972): a size placed at a datum in another unit, by its parent's position or by the mark's own min/center/max, stays ink, a flat point at the mapped center (a scatter bubble), not a swept wedge. Units are read through the render's union-find, which resolveEmbedding installs as the type walk does. Embedding and sizing ask this one question, so a glyph is never warped and a length of the space always is (see Glyph sizes and lengths of the space). The revocation is coord-scoped, so Cartesian behavior matches the former construction-time inference. (Route A, relational, measure-free embedding, is not yet implemented; tracked under #618.)
Pass 9: Layout Calculation
Location: src/ast/gofish.tsx:208
child.layout([w, h], [undefined, undefined], posScales);Implementation: src/ast/_node.ts:234-252
This is where the actual positioning and sizing happens. Each node's layout function is called with:
- Available space:
[w, h] - Scale factors:
[undefined, undefined](computed internally) - Position scales:
posScales(forPOSITIONspaces)
It applies layout algorithms (stacking, positioning, etc.), calculates intrinsic dimensions for each node, and handles nested layouts and complex arrangements.
Axis direction
Layout stores every node's geometry (its local box, its translate, its bbox ledger) in y-down pixels, the canvas's own frame. Nothing is mirrored later. What makes a continuous y grow upward is the node's axis direction (yDirection(node) in src/ast/axisDirection.ts), the one resolution site for which way a node's axis order runs on the screen. Only y has one to resolve; x always runs with the pixels:
+1: the order runs with the pixels. Every x axis, and a discrete y (an ordinal space, or a spread along y, whose space is UNDEFINED when its children carry no keys): the first item is at the top.-1: the order runs against the pixels. A continuous y (a value axis, a magnitude, a datum-positioned mark) grows upward from its origin, sostart, the baseline and the first part of a stack sit at the bottom.- A node with no y axis (an UNDEFINED y: a fixed-size shape, a text label, a layer of those) has no direction of its own and takes its parent's: it reads in the frame it sits in. On the canvas that is top-down; inside a bar chart a fixed-size shape's box sits above its origin like the bars around it.
A text is a box, placed exactly as a rect of the same size would be: its origin is its box's start edge in its own axis order (the top in a frame that reads top-down, the bottom in one that grows upward), so y, a parent's seating and every operator treat it as they treat a rect. The glyphs' own anchor (the point on the baseline that textAnchor and rotate refer to) sits inside that box; the text lowers it from the origin by glyphDy, the box's top in pixels less the glyphs' top.
It is read off the node's own resolved underlying space, so it is local: an ordinal spread inside a bar chart reads top-down inside, and a bar chart inside an ordinal spread grows upward inside its row. A coord and everything inside it is -1, because a coordinate transform is math-handed; the coord reflects y where its interior meets the canvas (see Flattening the Scenegraph). A ref takes its target's direction.
Each node resolves its direction once, top-down, into GoFishNode.yFrame (the direction plus whether the node is in a coordinate space), from its resolved spaces and its parent's frame. The frame is cleared with the spaces (clearUnderlyingSpace), which every rewrite of the tree re-resolves; reading it before the node's spaces are resolved is an error.
Operators never consult it directly. A node's _layout reasons in its own axis order (order = direction · pixel), and GoFishNode.layout converts at the node boundary, so spread, stack, align, distribute, the σ maps and baseline seating all run unchanged:
- the box and translate a
_layoutreturns are stored in pixels (orientDims,orientTransform); - the y map a node receives is reflected when it and its parent run opposite ways (
orientScales; σ, a magnitude, never changes); - the node is handed back to its parent as a view in the PARENT's axis order (
orientView), which reflects every y read (box, anchors, translate, shape) and every y write (placements, extents) about the parent's local origin. Anchors swapmin↔max(orientSide);centerandbaselinestay. The view is built once per child, and its reflected shape is rebuilt only when the child's own is.
A ref stores a pixel copy of its target, so it is read through its parent's view like any child. An elaboration wrapper (axes, labels, titles, a legend) builds its constraints before its own space is resolved, so it reads its direction off wrapperDirection(node): the direction of a layer that reports the wrapped node's spaces and takes its parent. A side named on the screen (the top, the bottom) is turned into the side in a frame's axis order by orientSide("start" | "end", direction). Geometry a node keeps for its own lower (a connector's paths, an arrow, a polygon's vertices, a tween's run) is in its axis order too; lower receives one node-local map, local (p ↦ translate + (x, direction·y)), the one place that geometry is reflected. A node that runs a pixel-native algorithm (the treemap's d3 tiling, pack's packSiblings) places its children in its own axis order like any operator, with no reflection of its own. A treemap or pack with no data-driven size has no y axis, so it takes its frame's direction: in free space d3's first tile lands at the top left, as in d3; in a chart whose y grows upward it lands at the bottom left.
Seating a child at its baseline is the one place a boundary between two directions needs more than the reflection: a child whose y grows upward inside a layer that reads top-down, and that no scope of the layer seats, is seated at the bottom of the band the layer allocated it (or of its own box when unsized), its own start end, by the rule the root sits in the canvas by (seatInBand, which placeRoot and the layer's seatOf both call). A scope's seat is already in the layer's axis order. So a bar chart in a cell of a layer that reads top-down sits with its baseline at the bottom of its cell. Every other child is seated by its origin at the seat. That is not one rule "each child at its own start end of its band": a child that reads top-down inside a layer whose y grows upward is still seated at the seat, the band's bottom, not at the band's top. Such children are placed by what they hold (a value label's spread around a ref to its bar); seating them at the band's top lifts them off their bars.
A chain of baselines (a spread with spacing: Spacing.pitch(d, { at: "baseline" })) starts at its first member's origin rather than its start edge (its sequence origin in solveAxisProblem), so two such chains over the same rows solve to the same lines whatever their rows hold: a ridgeline's upward-growing silhouettes and its rules.
Inferring an omitted w/h. The chart-level w and h are optional. An omitted dimension is resolved per axis from the root's size claim on it:
- An axis with a claim (a scatter axis, bar heights
= value, or bar widths= valuelaid side by side, whose spread is ordinal but whose room is σ-dependent) has data to scale into pixels, so it falls back to a concrete canvas (DEFAULT_CANVAS_SIZE = 400). The exception is a keyed domain that nodes with a literal size below the root already solve, all at one σ (ScopeRegistry.keyedSigma): the root is not a sized node on an axis the render does not size, so it maps the domain at that σ, and its size there is its claim at that σ (rootSizesingofish.tsx; see sized nodes). A claim that is only pixels lays out unsized, like an axis with no claim. - An axis with no claim (a bar chart's category axis, or a bare fixed-size shape) has nothing to scale, so it lays out unsized: marks keep their default sizes (a mark treats a non-finite size as "use my default" via its
Number.isFiniteguards) and the operator shrinks to fit.
layout() therefore computes the root's scope and size once per axis (rootSizes: its σ, and its claim at that σ), which the root scale factors, the equal-measure step and the root's frame in Pass 10 all read, and distinguishes it from the layoutW/layoutH it hands to child.layout (where a shrink-to-fit axis is left unsized). Shared-measure equal scale (#582) adds one reconciliation step here, after the per-axis scales are built and before child.layout: when the two axes are in one measure, each axis's pixels-per-data-unit — a POSITION domain's canvas / range or a baseline-magnitude σ — is equated to the binding min(...) so one data unit measures the same on both axes (circles stay circular, maps stay undistorted). Two axes are in one measure in either of two cases. They share a DECLARED unit (spaceUnit(x).unit and spaceUnit(y).unit are equal; two unknowns that unified through overlays do not count). Or they are in one TIED unit: an aspect-locked mark whose size is data (circle({ r }), circle({ h }), an ellipse with aspectRatio) draws one value of its unit as a length on both axes, so it ties the unit (tieUnit in the type walk, #1087), and the axes equalize when each maps that unit and no other (KeyedDomains.tiedUnitOf). An axis that also maps another unit (a marginal histogram's count beside the scatter's) is not one measure with the other axis, so a tied unit the two merely both contain does not equalize them. The binding axis fills, and on the other the box keeps its size and the content sits at its top-left, the leftover empty after it in screen terms (its claim takes the leftover at its far end, or at its start for a y that grows upward). Stage 6c makes this a named equalizeMeasure operation on the scope registry rather than an inline rewrite, so it is the one post-solve σ adjustment on the registry's books and GOFISH_DUMP_SCOPES records the final σ. A chart with a size of its own on both axes makes the same adjustment to its own scopes through it (equalizeFixed). Where the leftover goes is provisional, to be revisited once real use suggests a preference. (After the scope dump, GOFISH_DUMP_SHARING prints each layer's sharing sets, see Underlying Space. It only reads the tree.) It is type equality, not a knob, and a single-coordinate-space coupling — it does not reach sizes solved in separate nested operator scopes. A chart with a literal w and h (chart(data, { w, h })) is a sized node that solves its own scopes in the claim walk, so it applies the same equality there (ScopeRegistry.equalizeFixed): both axes take the smaller σ, and the chart still claims its size, its content at that σ at the box's top-left. (Its layout box is still the hull of its content, so a chart rendered alone draws only the content's width.) After layout it reads the chart's final extent back off the root via child.dims[i].size, so an unsized axis still yields a concrete SVG size (e.g. a no-width bar chart gets default-width bars and a width of n·barWidth + spacing). A user-supplied dimension is always authoritative. This computed extent — not the raw option — is what the render pass uses to size the SVG. The chrome (axes, titles, the legend) is part of the laid-out tree (Pass 7), so it is included in this computed extent when w/h are omitted. When a dimension is given, the SVG is exactly that size: the root, its chrome included, was fitted to it, and anything that does not fit (a fixed size larger than the canvas) is clipped. See Legends.
Literal pixel sizes are invisible to the underlying-space tree (a fixed-size shape resolves to
UNDEFINED, notSIZE), which is why the unsized path relies on the marks' default-size guards and the bbox readback rather than reading an intrinsic size from the space. Tracking constant sizes in the space system is a separate change.
Example: Rect Layout Function
Location: src/ast/shapes/rect.tsx:138-269
For a bar chart rectangle, the layout function:
Computes position (x, y):
typescriptconst x = computeAesthetic(dims[0].min, posScales?.[0]!, undefined); const y = computeAesthetic(dims[1].min, posScales?.[1]!, undefined);Computes size (width, height):
typescript// If both min and size are data-driven, compute from position scale if (isValue(dims[0].min) && isValue(dims[0].size)) { const min = x; const max = computeAesthetic( value(getValue(dims[0].min)! + getValue(dims[0].size)!), posScales[0], undefined ); w = max - min; } else if (isValue(dims[0].size) && posScales?.[0]) { // Size-only: compute from position scale with baseline at 0 const minPos = posScales[0](0); const maxPos = posScales[0](getValue(dims[0].size)!); w = maxPos - minPos; } else { // Use size scale factor w = computeSize(dims[0].size, scaleFactors?.[0]!, size[0]); }Returns intrinsic dimensions and transform:
typescriptreturn { intrinsicDims: { 0: { min: Math.min(0, w), size: Math.abs(w), embedded: dims[0].embedded, }, 1: { min: Math.min(0, h), size: Math.abs(h), embedded: dims[1].embedded, }, }, transform: { translate: [x, y] }, };
The intrinsicDims represent the element's box in its local coordinate system (with min typically at 0, or at the negative endpoint of a negative bar), while transform.translate positions it in the parent's coordinate system. The node's dims compose the two exactly once (combineDims: min = local min + translate), so a layout must never fold its translate into intrinsicDims.min as well; doing so counts the offset twice (#755).
The cell a parent gives a child
A partition gives each child its cell in data, as a position constraint with a region (PositionRegion, src/ast/constraints/position.ts), and the cell reaches the child the way any data position does: through the partition's scale.
- The layer proposes the cell's pixel length as the child's size on each axis the cell spans (
buildChildSpans), and the cell places the child's middle at the cell's middle: the claim walk reads the cell as an interval (constraintsOn) and seats a child with a size of its own in the middle of it (placeByClaims), and the placement solve, handed a cell directly, pins the middle (lowerPositionPlacement). So a node with no size of its own there (arectwith now) fills the cell, and any other node keeps its size and sits in the middle. - A child placed by its data in the layer's frame is not pinned. A
regionmark is one: it reads its cell (enclosingCell), its type there is the cell's interval, pinned, and it maps the cell's edges, and the outline of a cell of the plane, through the map the partition hands it (childPosScalesFor). A layer of marks in a cell is one too, so the marks in it share the partition's frame. A text beside aregionin such a layer is placed by analignthat names the two, as any mark in a layer is. Theregion's own data places it there, as a rect's dataxandx2do (placedByOwnData), so the align moves the text to the region and never the region to the text. A layer around the region is placed by its data the same way. - Either way, the child's room is its whole cell. What a child draws may end before its cell does: a band through the rows over a cell of time ends at the last row, a day before the last month's cell ends. The claim walk takes the cell as the room of a child placed by its data (
roomsinplaceByClaims), as it does for a child centered in it, and the layer's box covers every cell its regions give (cellSpans), so the claim and the box agree, and the canvas holds the last cell whole. - A partition inside another partition's cell divides that cell: on each axis its key does not place, it gives each child the cell it is in, so the child is placed there as a child of the outer partition is. That cell makes no cells of the inner partition (
PositionRegion.placed).
See Underlying Space. A cell of a binned struct (struct({ x, y }).bin(Bin.hex(...))) also has an outline, the cell's polygon; every other cell is a box.
The shape a parent gives a child
Beside a size, a parent may hand a child a shape: layout(size, scales, shape), where shape is a convex ring (Ring, src/ast/geometry/ring.ts) in the child's own frame, inside the box [0, w] × [0, h]. No shape means the box itself. GoFishNode.layout flips the ring with the scales when the child's y runs the other way, so every Layout reads it in its own axis order. Three parents make one, and two nodes read it:
- A
partition's layer maps each cell's outline to pixels through the child's scales, in the walk that gives the child its span (buildChildSpans,src/ast/constraints/proposalPlan.ts), and hands it to the child in that cell. The cell's span and placement still go through the data position above; only the outline goes through the shape. - A
treemaphands each child its tile: a box for a rectangular tiling (boxRing), a convex polygon forTile.voronoi(src/ast/geometry/voronoiTiling.ts: a power diagram of the region, clipped half-plane by half-plane withclipToHalfPlane. Each round moves every site to its cell's centroid, then fits the weights with a damped Newton step, until each cell's area is within 2% of its share and the sites have settled). EveryTilestrategy is one function, aTilingintreemap.tsx, from the region and the weights to one ring per child, so the treemap has one placement loop. The child's size is the ring's box, and the ring is shifted into it (inItsBox). On an axis where the child fills its room (fillsRoom) it is centered on that box; on an axis where it does not (a text, a circle) it is centered on the ring's centroid, which is inside a convex cell, where a polygon's box center may not be. A ring with no area (hasArea: a tile rounded to no width, a cell itsspacingate, or a Voronoi region with no area, whose cells are all empty) gets a child laid out at size zero with no shape, at the cell's center.Tile.voronoichecks that its region is convex whatever the padding, and does notroundits cells. The treemap's own box is always the region it was given,[0, w] × [0, h], so itspaddingstays inside it. - An
enclosearound a member with no size of its own (fillingLayout, see Enclose) hands down its outline.
The shape travels with the room a layer proposes a child (childLayoutSizeProposal): the layer's own shape with the layer's box, so a layer([region, text]) in a cell still finds the cell; a cell's outline with the cell's span; and no shape with any other room (a grid cell, a share of a scope, a span with no outline, a size a nest derives, or what a ring's chrome leaves). A treemap with no size of its own reads its shape as the region it tiles (a rectangular tiling there is an error unless the shape is the whole box), and a region draws it. Every other node ignores it.
Chrome around a chart
Chrome sits outside its chart (#1032). A chart's own w/h is its plot, and the slot a parent gives it (a share of a chain, a grid cell, or the canvas at the root) is its whole graphic, its chrome included. Each ring of chrome is an ordinary layer of what it dresses and its chrome shapes (#1257): it seats its content at its data 0, claims the hull of its children where its constraints place them, and hands its content what its chrome leaves of its room. There is no separate channel for how far the chrome reaches: it is in the ring's claim, so one layout fits a chart and its chrome to its slot (#493: fixed-size nodes report their size).
- Fixed-size nodes claim their size. A text is measured when the claims are resolved, and a rect or ellipse of literal size claims that size (
boxExtentinextent.ts). A tick label, a tick, a legend swatch and a title all have a claim with no σ in it. - A layer claims the hull of its children where its constraints place them (
placeByClaimsinconstraints/claimPlacement.ts). The children its own union leaves out (a literal pin, a datum pin, a seat beside a sibling) are placed by the same placement solver layout runs, on boxes that are their claims, with data mapped through σ from data 0. The solve runs once in formulas (Tape), so each box's edges are piecewise-linear in σ, and the hull is their envelope (buildPlaninsolver/plan.ts). A ring is such a layer, so its claim holds its axis, titles or legend around what it wraps, and so does a scatter's around its marks. - Frames read across layers. A
positionwithin: refplaces a datum in the frame of the noderefnames (#1257). The claim walk reads that frame's data 0 and one data unit up the plans from the node to the layer (frameIninsolver/plan.ts), crossing each scope at the σ it solved (leaving), and layout measures them (in0:,in1:). Where a scope between cannot be read out of, or where the child of the layer that holds the node is placed by the solve (its frame would move with it, which needs a relation, not a pin), what the datum places is ink. - Placement claims. A
refstand-in, or an operand nested in a child, stands where its node lands in the layer's frame. The claim walk knows that (planPlacementinsolver/plan.ts): it takes the node's box and moves it by each ancestor's place in the next, where each layer places its children by its plan (GoFishNode.claimWalk.plan). The step into the node the two share reads only where that node seats its child (its origin, or a literal pin), since its own claim may be the one being computed. A layer with a literal size solved its σ in the claim walk, so a node inside it lands where the plans compose at that σ, which is a number wherever the layer is placed: the tick labels of an axis drawn outside a sized chart take room the same way. The other way is not composed: a stand-in inside a sized layer for a node outside it waits on the layer's σ, which is solved after the plan that asks, so it is ink. So a.label()text beside its bar, or a text in a spread beside aref, takes room where it draws, and σ is solved with it, while the mark it describes stays where its own layout puts it. A layer that places such a stand-in claims the hull of its solve, not the fold that starts its children at its origin. A region (apartitioncell) places a child that fills across its datum span, as an interval does, and a child with a size of its own in the middle of it, as layout does; either way the cell is the room it takes (ClaimPlacement.rooms). A child with no claim (a filler) takes no room: the solve places it as a point, so what a relation ties to it stays placed, and the hull holds that point only where a position puts it, at a datum or a pixel (a ring seats what it dresses at its origin, so its chrome's reach past a plot that fills is measured from there). A ring's chrome along a chain is a legend that reads no room, so it takes only its need and the slack goes to the plot that fills it (the room rule below, which names no chrome). A child its own data places (placedByOwnData,ClaimChild.dataPositioned) is placed before the solve, where its frame seats it, so no constraint but aposition(which gives it a frame of its own) moves it, as layout does not move it. Anenclosearound placed members (.relate()operands,ref(...)children, or aselectAllin the chart form) is placed from its refs the same way (GoFishNode.placedFromRefs): its box is its members' boxes, each whereplanPlacementlands it in the layer that holds the outline, grown by the padding. So the outline takes room where it draws and never moves its members. The box is exact forShape.box(), and a blob lies inside it; an oval can reach past it, and that reach is ink. - Bands are shares, and a share is a claim (#493 piece 3, #1176 step 5). A share is a σ weight in its nearest scope (
GoFishNode.scopeOf), a node whose room is fixed from outside its content. That is the render root in the canvas, a node with a size of its own, a coordinate space (in its own coordinates), a node whose room its parent gives it (a region's cell or a treemap tile,GoFishNode.givenRoom, which the plan lists inSharingPlan.rooms) when σ sizes its content and its data does not place it in its parent's frame (placedByOwnData: a layer of marks in a cell, or a partition inside another's cell, reads the parent's frame), and a node of pinned data in a slot (a facet panel). On an axis where nothing in a scope is sized or placed by data (GoFishNode.carriesData, which does not look inside a nested scope), σ has no data unit to be the pixels of, so it is the room a node with no size of its own takes (GoFishNode.sharesRoom): a node that fills (a leaf with no size of its own, or a node with no size of its own that is a scope or whose children all fill) and has no claim of its own claims one σ there when it is in a slot or inside a node in a slot, with no room given between. A scope that fills solves its content in its own room and claims one σ in the scope above, and what dresses its content reaches past that σ (aroundShareinsolver/plotForms.ts): its whole past its plot, read as a function of the share through the content's plot (throughinsolver/pwl.ts). So facet panels are shares of the chain that holds them, and their axes take room in its claim. A node in no slot (a rule laid over a bar chart) claims nothing, and fills the room of what holds it. A spread ofnbands with spacinggclaimsn·σ + (n − 1)·g, so the claim walk knows where each band lands, and a value label beside a band, or the half of a category label past the last band, takes room. Solving the scope against its slot narrows the bands to make it. On an axis the render gives no size there is no slot to share, and the bands keep their default size. A node that fills (GoFishNode.fillsRoom: a leaf with no size of its own, or a node with no size of its own whose children all fill) and that anestderives takes the inner's size plus the padding, not a share. A node that fills in a slot of a scope that carries data is a share too: it is one σ, one data unit, and the layout warns that its chain mixes data-driven and flexible sizes (mixed-sizes, below). - Room versus box (#1257, #1292). A layer lays each child out in a room, and the child's box is the hull of what it draws, which may be smaller. In an overlay a child's room is the layer's room. Along a chain (a
distributeon the axis), a member with no size of its own (GoFishNode.sizedOn: no literal, data or percent size, and no claim of its own as a leaf; a ring of chrome is sized where the box it dresses is, so a chart'sw/hhold for its outermost ring) gets its need, its claim at the σ the layer hands its children, plus its share of the slack: what the layer's room leaves past the hull of the needs, split among the members of its own chain that read their room byGoFishNode.flexWeight(kforfr(k), else 1). A member reads its room (GoFishNode.readsRoom) where the room reaches something that fills it: a filler, a share of a scope, or a node with no scope of its own that holds one. Any other member (a legend of fixed swatches and text, which a ring's chrome usually is) takes only its need, because a larger room would change nothing it draws; and where no member of a chain reads its room, the slack is left over and each member's room is its need. Nothing in this rule names chrome. Each chain splits the slack on its own (chainsOfinlayer), so two chains of one width side by side each fill the room; a chain narrower than the hull gets only the hull's slack. This is CSS'sflex: 1 1 auto. σ is solved from the needs alone, so where a scope fits its needs to its room the slack is 0 and the members get their needs, the σ the scope solved. A filler (a rect with no height) is its room, so a backdrop behind a bar fills the band, and a stack's filler takes what the stack's other parts leave. The children that are part of the layer's plot are proposed the layer's room less how far the rest (dressing, a ring's chrome) reaches past what they draw (LayerPlan.plotWhole), so a ring's content gets what its chrome leaves. A percent is laid out at the length its claim reads (GoFishNode.ownLength), so the claim walk and layout agree (#1300): a part of the nearest room with a size (roomFor), in pixels, orρσfor a percent of a band, at the σ its parent hands it. So[percent(100), 40]in a stack overflows by 40 px, and a percent inside a chain member with no size of its own is of the chain's room, not the member's. - Category labels overdraw their neighbors (#1115). A category label is centered on its slot's ref, and only its overhang past the ends of its axis takes room: the claim of a ring is the hull of its labels, so labels between neighbors overlap rather than push the bands apart. A label in a ring a spread along that axis holds (the labels of one group of a grouped bar chart) is ink there, since its overhang would widen the gap between groups. Across the axis it is seated past the content and takes room.
- Ink. Where the claim walk does not know where a node lands, whatever a constraint ties to it is ink on that axis: it takes no room in the claim or in its layer's box. That is a node in a coordinate space or under a node with a size of its own, one under a node that reads y the other way, a node that reads its place from refs (
GoFishNode.inkOn: the span a label over a run of several slots is centered on, or anenclosewith a member the claim walk cannot place). - Nicing holds the domain. A claim is the hull of what the content draws, so widening it to a keyed or niced domain (
widenTo, whichGoFishNode.widenToDomainapplies for every reader) takes the farther of the claim and the domain's end on each side. A tick label past the last tick, or a mark past its datum, takes room only where the domain does not already reach past it, so widening twice is widening once. The plot an axis is seated beside covers its whole niced domain (_axesBeside): its plan (domainPlaninlayer) and its layout box (GoFishNode.domainSpan) both reach the domain's ends, so its axes frame the domain's corner, and the room handed to it counts the domain as plot, not as dressing. - The layout. A ring lays its content out in the room its chrome leaves (
plotRoomsinlayer), and seats it at its origin on both axes, as any layer seats a child it pins at a literal pixel. A chart is placed whole, its chrome with it: on an axis with no data 0 (a spread of bands) it has no baseline to share, so a baseline alignment seats it by its start in reading order (GoFishNode.baselineIsStart: the chart's box reports its start as its baseline throughlocalAnchor, and the claim walk's stand-in throughClaimChild.startBaseline, #1241), and a caption above a bar chart starts where the chart's tick labels do. On an axis with a data 0 it keeps that baseline. Every other box keeps its own origin (a layer of literal positions, a rotated label's pivot). Which origin a pinned content's own constants are about (a noise offset, a label slot) is still open (#1239): the claim walk and layout both read it from the content's data 0. - A node with a size of its own. Its own
w/his its plot, for a chart and a plain layer alike. Its forms are its content's claim and plot, widened to its keyed domain (plotFormsinsolver/plotForms.ts), and the size is solved as the plot: σ fits the plot to the size, and the node claims its size and the reach of what dresses it at that σ (ScopeRegistry.solveFixed,reachPast), its data 0 past the start reach, whether the content fits or overflows the size. Content that maps no domain is fitted by the same fit, which solves no scope there, and claims the size and the reach of what dresses it where its plot fills the size. Layout lays the node out at the box its claim solved (ScopeRegistry.fixedBox), and its box covers that size from the start of what it holds, as its claim does, whether or not its content fills it (#1320): a scatter that maps x only is stillhtall, and its x axis sits below that. A chart's chrome goes around the chart's frame (frameChart, #1257), so it is no part of those forms: the ticks read their datums in the frame (position'sin), and the size is the plot alone. What dresses the content inside the frame still is: a label hanging off the first bar is dressing, so it adds around the plot. Labels beside a plain layer's content (and the outlines of its shapes) add around it the same way. - The plot leaves out dressing. A layer's space is a collection of its children's spaces (see Underlying Space): the type pass gives each child the space it is in in the layer (
ClaimWalk.parts), and the layer's axes attach to the children whose space there is continuous or ordinal. Dressing is any other child of a layer that has such a part: its geometry is read off other nodes' pixels, not placed by data on that axis. That is a value label beside its bar'sref, a tier of texts seated beside the bars of another tier, anenclosedrawn around placed members, and a chart of outlines or a line layered over a scatter (.layer(chart(selectAll(…)))), whose type isundefinedon both axes. A layer with no such part has no dressing: all of it is plot. A ring's chrome is chrome, not dressing (ClaimChild.chrome). Each node has a plot claim next to its claim (GoFishNode.resolvePlotExtent): a layer composes its children's plot claims the way it composes their claims, its hull of what its constraints place leaves out the dressing (buildPlan's plot envelope). A child may also handplaceByClaimsa plot apart from its box (ClaimChild.plot), which a chain lays it by as layout does (localSpan("plot", …)), say that it places itself at a literal pixel and stays there (placesItself), or that it is a ring's chrome (chrome), which a chain lays past its whole box; the plan insolver/plan.tssets them (#1176 step 3). A node that wears chrome has its content's plot as its plot: its rings are never plot, so a grouped bar chart's inner row of category labels adds around the outer chart's plot, as its own axes do. A chart's outer box is the exception (_chartRing, which chrome elaboration sets on the ring it wraps achart()in): the outermost ring around achart()with no size of its own is its parent's plot whole, axes included, since a parent lays a chart out by its outer box. So a chart in a spread beside a caption or another chart keeps its axes clear of them. Each child also has a third claim, its box without its dressing (ChildForms.barein the plan,GoFishNode.resolveBareExtentin the claim,localSpan("bare", …)in layout, inputsbare0/bare1beside the plot'splot0/plot1, each undefined where it is the box; onespanHullcomputes both local spans): the hull of its children that are no dressing and no ink, a ring's chrome included. It is what chrome is laid beside. - Dressing never moves the parts it dresses. Labels are a layer applied after the spread: they take room in the chart, but do not change how the spread lays out its parts. A chain of parts of the plot lays them by their plots, in its claim (the plan lays each dressed part by its plot, and the whole part only reaches) and in its layout (a chain edge reads each part's anchors off
GoFishNode.localSpan("plot", …), the hull of a layer's children that are no dressing and no chrome, in the node's own pixels; a chain that reads y the other way reads it reflected, as it reads the part's box). So the spacing is between plots, and σ and the parts' sizes ignore the dressing. A label between two rows sits in the gap, and overlaps where it does not fit (#1171); a label past the first or last row reaches past the chain, into the chart's margin. A part that is a share and a scope of its own (a facet panel) has its share as its plot, and its chrome adds around it (aroundShareinsolver/plotForms.ts). A chain edge between two parts of the plot lays them by their plots. An edge to a part that is no part of the plot (dressing, ink, a ring's chrome) lays that part by its whole box and the other end by its box without its dressing. So an axis line sits past its own box, beside what it dresses less the outlines and labels that dress it: the ovals around a scatter's groups, which are dressing, draw over the axes rather than push them out. Inner chrome is no dressing, so a ring still seats its title past its tick labels. The plot of a chain with a stand-in reaches only as far as its stand-ins. A child that reads y the other way has its plot read reflected with its box, at the one place a child's claim meets its parent (formsOfinsolver/plan.ts), which anest's padding reads too (plotIn). A stack places every part by its data offset from the stack's 0 (stackPlaces). A part whose offset is a constant is placed by the solve at that offset times σ, so its claim is its own claim moved there, its stroke included, and the stack adds no overhang between parts or to its data extent. A band in a stacked area is moved by an offset that changes along u, so the box its own claim describes is not where it draws. Its parent claims it at the box it draws there, the interval it covers about the stack's 0 over every u times σ, all of it plot, and its outline past it (ClaimChild.stackPlace,placedForms). In layout the parent hands the band its offset as theshearof itsAxisScale, and the band adds it to both edges; only a part whose offset changes gets one. This claim is exact only while the band's cross-section is all data; a pixel term in it (a ribbon'sinset) is a TODO. A chart with a size of its own maps the plot of its content into its size, and its labels, like its chrome, add around it (#1032). A node with a size of its own, and a chart's outer box, are a part of their parent's plot, chrome and labels included (GoFishNode.plotIsBox), in the claim and in the layout alike: a chain lays such a part by its whole box, and an align that places it by its plot aligns that box. The axes around a node with a size of its own still sit beside its box without its dressing, its content's at the σ it solved (thelayerclaim hook sets_bareExtent), so outlines that reach past its size draw over them. So a row of charts aligned at their tops lines up the tops of their outer boxes, and a chart whose labels reach above its plot sits lower than one whose labels do not. Thespacingbetween charts is measured between their whole boxes, labels included: this is a declared choice, and spacing or aligning by a plot's edge is deferred (see #1210). - An outline takes room as dressing does. A shape's box is its geometry, which data places and sizes and a chain lays out. Its stroke is centered on that geometry, so it is drawn half its width past the box on every side (
GoFishNode.strokeOverhang,outlineOverhangin_node.ts; 0 where no stroke is drawn). The shape's claim is its box widened by that, and its plot is its box (resolveExtent), so a chain still lays shapes by their boxes and an outline never moves a shape or changes its size: it reaches past the chain, or overlaps its neighbor in the gap. A node that draws from refs (anenclosearound placed members) widens its placement the same way, and a node anestsizes from its inner claims its own outline past the padded inner's plot (applyNestExtentPlan). Inside a coordinate space claims are in the space's units, so they are not widened: the space fits its content inside its box and widens the box it measures by the largest outline inside it (outlineincoord.tsx), so its box holds its outlines. A space that frames its own window (geo) clips them, as it clips the rest of what its window leaves out. A painted region composite (intersectand the rest, with a stroke) strokes its own outline, so it widens its claim the same way. A shape that fills a cell has no claim of its own: the plan reads its claim as the cell widened by its outline (buildPlan), so the outlines of the outer cells stay on the canvas. A shape that fills the canvas has no claim to widen, and its outline is centered on the canvas edge.
At the root, layout() measures what the root draws past its box after its one layout (drawnOverflow): its ink and its outlines. A node's box holds what it draws, except a layer's ink children, which its box leaves out, and a shape's outline, drawn past its box: the drawing is the hull of the root's box, of every ink child's box, and of every node's box grown by its outline. A coordinate space's box stands for its interior, and a node that clips its content to its box (an intersect, subtract or atop composite: GoFishNode.clipsToBox) draws nothing past it. The claim walk records the layers that found ink children on the render session, and layout records whether a shape draws an outline, so a render with neither skips the walk. A literal start or pixel offset (spread({ y: 50 }), .translate()) moves a box, and its claim moves with it, so it is no ink. On an axis the render gives no size, the SVG is the root's box plus what it draws past it, and the box sits past what it draws before it. Content larger than the canvas whatever it is handed (fixed spacing wider than the canvas, a literal position past it, an inner size equal to the render size) still overflows and is clipped.
On an axis the render gives a size, the outlines of the nodes that take room are in the root's claim, which was fitted to the canvas, so a root that no data seats has its box placed past the outlines before it, as far as the outlines after it still fit (a shape that fills the canvas keeps its box there, its outline centered on the canvas edge). The ink is not fitted inside the canvas, and it overflows it.
Layout warnings
Layout never draws nothing and never grows the canvas past the render's w/h. Where it cannot fit, it draws anyway and records a LayoutWarning on the render session (warnLayout and the builders in layoutWarnings.ts). layout() returns them, gofish() puts the latest on view.warnings and prints each one once per chart (a re-render does not print it again), and the export terminals print them too, each as one console.warn prefixed [gofish:layout]. The story capture scripts forward those lines, so pnpm capture-one prints them under the story.
- Fixed parts larger than their slot (
fixed-overflow). A claim's fixed pixels are its width at σ = 0: literal spacing, literal sizes and positions, text, chrome, and what hangs off bands. Where they exceed the slot no σ ≥ 0 fits. The one scope fit (ScopeRegistry.fit) checks it wherever a claim is fitted to a slot: the root on each axis the render sizes, and a layer with a size of its own (its content's claim against its size), whether or not the content solves a domain on that axis (panels and gaps with fixed sizes, apercent(30)and apercent(70)part with a 12 px gap), since a length has no content minimum. The node still claims its size. A coord boundary fits through it too but does not warn, since its budget is in coordinate units, not pixels (an open question). The warning names the node that holds the fixed parts: down from where the check failed through each node whose fixed pixels are mostly one child's (rings, label wrappers), taking off what each adds, to the first spread, sized node or leaf. It lists the spacing of each spread below it and the size of each node with a size of its own, the parts of one description summed (with their count when they are one size,×2 = 720 px, and each size when they differ,216 px + 504 px = 720 px), and the rest of the fixed pixels. The scope then maps its data at the σ where the parts that grow with σ fill the slot, as if the fixed parts took no room. - Data-driven and flexible sizes in one chain (
mixed-sizes). A part with no size of its own beside parts sized by data has a flexible size, which is a data type with no name: no one scale fits it and the data. The claim walk gives it one σ, one data unit (GoFishNode.isShare). Anfr(k)part or anfrspacing in such a chain is flexible too, and so is a table's track that no cell sizes (shareTracks). The chain checks its parts and gaps once per axis (warnFlexibleSizes), and warns once, naming the chain, the axis, each flexible part and gap, and the data-driven parts. - A flexible gap with no room (
no-room). Anfrspacing in a chain whose scope is the unsized root on that axis has nothing to divide, so its gaps are 0 (as in CSS and Typst), and the warning asks for aworh(warnFlexibleSizes). The root lays that axis out unsized, at a σ of 0, so the gapkσis 0 there. One predicate says where shares have no room (GoFishNode.sharesHaveNoRoom), and both the root's layout and this check read it: the default canvas gives a data σ room but gives shares none. - A drawing past the canvas (
ink-overflow). After placement, on each axis the render sizes and no fixed-overflow was found, the hull of the root's box and its ink is checked against the canvas, naming the ink node that reaches farthest. Where the root's own box reaches past the canvas, no ink node is to blame, and the warning says only that: layout drew the box larger than its claim, or away from it.
Shape geometry after layout
Once a node is laid out, node.geometry() describes its shape in the same local frame as intrinsicDims, with no translate applied (src/ast/geometry/). The result always has a box, which is intrinsicDims as a plain box. It may also answer optional queries, one file per query in src/ast/geometry/, joined into Geometry with extends. There are three. A consumer calls each query's helper, which falls back to the box when the node does not answer.
crossSection(crossSection(g, axis)): for each position u on the other axis, the interval the shape covers alongaxisthere, as a function value (Fun<Interval>,ast/fun.ts). The fallback is the box: the box's interval onaxisat every u across the box (boxCrossSection). The shape form ofribbonandline(Band,src/ast/shapes/band.tsx) answers it exactly along its value axis: the interval between its two edges at each point of its parameter, in pixels. Its form before layout, in data units, is the space'sprofile(see Underlying Space).enclosingCircle(enclosingCircle(g)): a circle around the shape. The fallback is the circle through the box corners.outline(g.outline(tolerance)): the shape's outline as polylines that stray at mosttolerancepixels from it. Each states three facts.closedis its topology: the path loops back, or it is open, with a start, an end and a direction of travel.filledis its paint: the inside of a closed loop is drawn. An open outline is never filled, and a mark is filled unless its fill is"none"or"transparent"(outlinePaint).widthis its stroke: the width of the band drawn along it, on an open or a closed outline, and absent when no stroke is drawn. The ink is the inside when filled, plus the band. An outline may also nameparts, arc-length ranges for the mark's own pieces. A region with holes (several loops under a fill rule) is not an outline yet (#1201). An outline markedboundsstands in for the ink without tracing it: the box fallback and a rotated text's glyph box. Arect's outline is what it draws: its box drawn in by itsinset(insetBox, whichregionuses too), with its rounded corners sampled (roundedBoxOutline). A path boolean (a paintedintersect) reads only outlines that are notbounds, and clips them withgeometry/clip.ts(Sutherland-Hodgman, exact when one ring is convex; the general case is #1201). Every node answers it:GoFishNode.geometry()gives a node whose definition has no outline the box as a closed, filled rect (boxOutline) whose parts are its edges,x-min,x-max,y-minandy-max, named in the node's own axis order (so on a continuous y,y-maxis the top edge), and keeps each tolerance's samples for the layout. Every outline, a node's own and the box alike, is in the frame of the geometry it was read from: pixels, y down, for a node's own geometry, and the parent's axis order for a parent's view of a child (orientViewreflects the outlines with the box; the parts keep their names). Beside its samples, an outline may give its shape exactly: anellipse(cx,cy,rx,ry) or aboxon a closed outline. Moving or reflecting an outline moves its exact forms with it.placedOutlines(p, tolerance)reads a placed node's outlines in its parent's frame, moved so the geometry's box sits wherep.dimsputs it. Labels andencloseread members this way, andoutlineSegmentswalks an outline's straight pieces for both.A node definition may pass a
geometryfunction next tolower.ellipseanswers with the circle of its larger radius and its sampled outline, which gives the ellipse exactly, andpolygonwith the smallest circle through its ring and the ring itself. Arectanswers with its box as the fallback reads it, painted as it is drawn. Alineconnector's outline is the open path it draws, one per run, aribbon's is its closed band, and anarrow's is its body run on to the tip of its head, so its end is where its ink ends. A rotatedtextanswers with its turned glyph box, read as filled, and aregionwith its cell's outline when it has one. Each mark readsfilledandwidthfrom its ownfill,strokeandstrokeWidthonce, when it is made; a node with no paint of its own (a layer, ablank) is read as filling its box. Rings and paths that a node keeps in its axis order are turned into pixel outlines byringOutlineandpathOutline(throughorderToPixel).enclosereads its members throughoutline(enclose/members.ts), taking the exact forms where an outline gives them: an ellipse is a disc, a box a box, an open outline or an unfilled closed one its pieces as wide as its stroke, and any other filled closed outline its bounding box for now (#1207; see Enclose).A node with children and no
geometryfunction answersenclosingCirclelazily. It takes the smallest circle around its children's circles, each moved by the child's translate into the node's frame.GoFishNodecomputesgeometry()on the first call and keeps the result.layout(), and any later write to the local box (placerecording a localmin,setExtent,setSizeOnly), clears it. Callinggeometry()before layout throws.A
refand a nested constraint operand return their target's geometry, because they share its local frame.
The pack operator (graphicalOperators/pack.tsx) is the first consumer. It lays out each child, reads enclosingCircle(child.geometry()), runs d3's packSiblings, and places each child so its circle lands where d3 put it. spacing grows each circle by half of it before packing, so it is the gap in pixels between siblings. The pack's own circle is the smallest around the children themselves, not their grown circles, so a pack carries no margin past its outermost children, and nested packs with the same spacing keep the same gap between groups. A pack answers the queries itself: its outline is its children's outlines, each moved to where the pack placed it, and its enclosing circle is the smallest circle around theirs. So an enclose around a pack hugs the circles, not the pack's box, and a pack of packs packs the inner packs' circles. A group with children answers only enclosingCircle in general, and its outline is still its box (#1233): labels and enclose members read outlines, so the general rule would move existing renders, and only pack answers its outline so far. Geometry exists only after layout, so a parent cannot yet read it while sizing. That is why pack keeps its children at their pixel size and does not fit itself to the space it is given (#967). The design note is internals/design/shape-geometry.md on the geometry-representations branch.
The second consumer is scatter's overlap option, Overlap.separate() (#969) or Overlap.noise() (#970, #1014). Overlap.sina() and Overlap.jitter() are Overlap.noise() with other defaults filled in, so they reach layout as the same {kind: "noise"} object. scatter elaborates to a layer with a position constraint per child on each axis a field places, and an align on every other ("free") axis. With an overlap strategy, the free axis gets an overlap constraint (constraints/overlap.ts) in place of the align. It is not a difference constraint, so the placement solver never sees it: applyConstraints runs it after the solve, when each child's position on the data axis is known. It reads each child's enclosingCircle, asks the strategy (graphicalOperators/overlap.ts) for each circle center's offset from the alignment line, and pins each child there. A strategy returns one free-axis number per child, so it cannot move the data axis. applyConstraints also passes the data axis's pixels per data unit (the layer's position-scale sigma), which noise needs to turn a smoothing bandwidth in data units into pixels. smoothing: 0 (the default), smoothing: Infinity and smoothing: "silverman" need no scale. 0 and Infinity are the same in any unit. Silverman's rule reads the dots' own pixel positions, and on a linear axis the rule in pixels is the rule in data units times the scale. The strategies share one broad phase, NeighborGrid, a uniform grid of square cells kept as lists in insertion order: separate buckets placed dots on the data axis, and noise's "blue" on both axes. separate merges each dot's blocked intervals into disjoint runs in one sorted sweep and takes the nearest free candidate. noise's outline (noiseOutline) is a Gaussian density estimate in two steps. First each dot is blurred by a bell of the smoothing bandwidth s, which estimates where the data is. Then each dot is blurred by its own footprint, a bell of σ_dot = pitch/√(2π) whose peak is one dot spread over one dot width. Gaussians compose by adding variances, so each dot adds one bell with σ = √(σ_dot² + s²), and the outline follows the sum. The bells are summed on a grid, not pair by pair: each dot's weight is split between its two nearest grid points, the grid is convolved with the bell cut off at four bandwidths, and each dot reads the sum back by linear interpolation, the way R's density() bins. At the ends of the data range the sum is divided by the part of the smoothing bell (bandwidth s, not σ) at that point that lies inside the range, so a cut off bell does not thin the ends; this keeps the outline's total size about the same for every bandwidth. The footprint step is not corrected, since it is the dot's size, not missing data. With s = 0 (the default, and what Silverman's rule gives for fewer than two dots or equal values) the bell is the footprint alone and nothing is corrected, so a lone dot sits on the line even at the end of the range. The footprint is the smallest blur, since a smaller bell would let dots with nearly equal values draw on top of each other. A scatter with an overlap strategy reports no size on its free axis in the space pass (a fixed-pixel dot's space is UNDEFINED there), and its real extent comes from where the children land, in the layer's box fold, the way a text label's extent is measured at layout. So a beeswarm takes the room its dots need and does not shrink to fit. It throws inside a non-linear coordinate space, where the layout frame is not the screen (#1002); the axis scope the scatter elaborates in carries the nearest non-linear space (AxisScope.warpedBy), so the scatter can tell.
The third consumer is .label() with a Place strategy (see Labels). Its label layer gets a labelPlace constraint (labels/placeStep.ts), another step the solver never sees: applyConstraints runs it last, after overlap, when the labeled marks and the labels a position string placed are where they land. It reads each labeled mark's outline through its ref(), picks each label's first free candidate spot, and writes the label's box with setExtent. A node definition may also pass labelPosition, where a .label() with no position goes on it: a strategy by convention, or "outline", read from its outline when the label is placed. After the root's layout, gofish.tsx prints one note for the labels the step hid (reportHiddenLabels).
Pass 10: Placement
Location: src/ast/gofish.tsx
// The root's axis order starts at a frame's start edge: the top, or the
// bottom for a continuous y (`direction` −1).
const fromFrameStart = (p, size, direction) => (direction === 1 ? p : size - p);
// A scope solved against the render's slot with a data 0 seats the root's
// baseline in its own frame (its size, `rootSizes`). Anywhere else the
// root's box is placed, its start edge at the frame's start.
// A seat read in `direction` inside a band (`seatInBand`, the rule a layer
// seats its children by too).
const seatInBand = (seat, band, direction) => ({
px: fromFrameStart(seat.px, band, direction),
anchor: seat.anchor,
});
given && scope?.originPx !== undefined
? root.place(
axis,
pad +
seatInBand(
{ px: offset + seatPx, anchor: "baseline" },
rootSizes[axis].px,
direction
).px,
"baseline"
)
: root.pinAnchor(
axis,
pad + fromFrameStart(offset, root.dims[axis].size, direction),
orientSide("min", direction)
);Implementation: src/ast/_node.ts
Pins the whole chart into the container by landing one anchor of the root's bbox at a target coordinate. The canvas is a frame [pad, size − pad] on each axis, and the root's axis order starts at the frame's start edge (the bottom for a continuous y). Which anchor depends on whether data places the root:
A scope solved against the render's slot that has a data 0 (a given dimension that maps a domain with an origin) → pin the baseline (local
0) at the scope's seat from the start edge of the root's own frame. The root fills the slot, so its frame is the slot, and the scope'soriginPxalready counts how far the root's claim reaches before its data 0 (the chrome before its plot), so the root's box, chrome included, starts at the frame's start.Anywhere else (a shrink-to-fit dimension, a given dimension whose scope has no data 0, such as a spread of magnitudes whose rows reach past its origin on either side, or a given dimension the root maps no domain into: a category axis, a chart with a size of its own) → pin the root's box start edge to the frame's start, at the top-left for either y direction (#1032). The box is the whole graphic, chrome included, so a shrink-to-fit canvas is exactly the box, and a root smaller than its slot sits at the slot's top-left.
Pinning the box rather than the baseline is what keeps a box with a negative
min(content below/left of its baseline, a chrome gutter) or a positive one (a self-placed diagram seated at, say,(20, 20)) inside the canvas, with no phantom band (#574).The box pin uses
pinAnchor, not the write-onceplace(): a chart whose root carries its own transform (a hand-built diagram like the pulley) has already self-placed that axis, andplace()short-circuits on a placed axis.pinAnchoris the authoritative override — it rebuilds the axis ledger so the pin lands regardless — and for an unplaced root it matches whatplace(…, "min")would have done.
Constraint placement works in anchor coordinates, not just node origins. The Placeable protocol in _node.ts exposes localAnchor(axis, anchor) so the placement solver can turn start/middle/end/baseline relations into equations over a node's absolute min. GoFishNode.localAnchor() reads the node's intrinsic dimensions in its own local frame, which keeps baseline and asymmetric-box alignment independent from whatever display transform is later projected for rendering.
Pass 11: Ordinal Scale Building
Location: src/ast/gofish.tsx:216-223
const ordinalScales: [OrdinalScale | undefined, OrdinalScale | undefined] = [
isORDINAL(underlyingSpaceX) && keyContext
? buildOrdinalScaleX(keyContext, child)
: undefined,
isORDINAL(underlyingSpaceY) && keyContext
? buildOrdinalScaleY(keyContext, child)
: undefined,
];Implementation: src/ast/gofish.tsx:65-119
For ORDINAL spaces, this builds scales that map category keys to pixel positions. The function:
- Iterates through
keyContextto find all nodes with keys - Computes their final positions (accounting for transforms)
- Returns a function
(key: string) => number | undefined
Example: In a bar chart with spread("category", { dir: "x" }), each bar has a key like "category-A", "category-B", etc. The ordinal scale maps these keys to their x-positions for axis labeling.
Render Phase
After layout completes, the render phase turns the laid-out tree into pixels in two passes: lower (walk the baked scenegraph, emit a flat display-list IR of positioned primitives in absolute pixels) and paint (a single backend turns that IR into output — SVG today). There is no per-shape SVG emission in between: each shape/operator owns a lower() method that describes itself as display-list items, and one backend paints the whole list. The full as-built model is Rendering; this section covers how render() drives it.
Entry Point: The render() Function
Location: src/ast/gofish.tsx (render())
The render function is called from gofish() after layout data is available:
return render(
{ width: data.width, height: data.height, defs, interaction },
data.child
);render() takes no axes/axisFields or scale/space context — all the chrome is in the laid-out tree by now — and no margins: layout() placed the graphic on the canvas, chrome included, so render only needs the SVG's size. It lowers the baked tree and paints each item into an <svg>. toDisplayList uses the same size as its viewport.
Render Pass 1: No Chrome, No Reserves
render() draws no chart chrome of its own — no axis lines, tick marks, tick labels, ordinal category labels, or titles, and no legend swatches. All of it was elaborated into ordinary nodes during layout (see Pass 7: Chrome Elaboration) and renders as part of the node tree like any other shape.
It reserves no room either. The render's w/h is the whole graphic (#493): the root's chrome takes room inside it (see Chrome around a chart), so there is nothing left to reserve around it. The former per-side overhang measurements and the PADDING/EDGE_GAP reserves of svgFrame are deleted, and so is the render's padding option.
Render Pass 2: SVG Container Creation
Location: src/ast/gofish.tsx (render())
<svg width={width} height={height} xmlns="http://www.w3.org/2000/svg">The SVG is the render's w/h exactly, or, on a dimension the render does not give, the root's laid-out box plus its ink. There is no inner flip <g>: layout is already in y-down pixels, so the display-list items paint directly under the <svg>.
Render Pass 3: The Coordinate Fold (toPixel)
Location: src/ast/displayList/lower.ts (lowerToDisplayList)
SVG is y-down (top-left origin), and so is layout: a continuous y grows upward because layout placed it that way (see Axis direction), and the root is placed on the canvas by layout (Pass 10). So the map on the render session is the identity:
export const lowerToDisplayList = (root, toPixel: ToPixel = (p) => p) => …The lower pass produces items already in final absolute pixels: no flip group, no per-shape transform. See Rendering.
Render Pass 4: Lowering the Baked Tree
Location: src/ast/gofish.tsx (render()), src/ast/displayList/lower.ts
const paintBaked = () => lowerToDisplayList(child).map(paintSVG);lowerToDisplayList(child) bakes the resolved tree into a globally z-ordered list of { node, transform } entries (see Flattening the Scenegraph) and lets each entry lower itself via INTERNAL_lower(coordTransform?, transformOverride?):
export const lowerToDisplayList = (root) =>
bake(root).flatMap((d) => d.node.INTERNAL_lower(undefined, d.transform));The display list is the concatenation of every node's DisplayItem[] fragment. Unlike the old INTERNAL_render, INTERNAL_lower does not pre-recurse children: a node reaching it is either a leaf or a bake boundary (coord, box, connect, arrow, enclose, the compositors) that re-walks its own subtree with its absolute transform composed in. A node with no lower() throws. Each lowering also records, as paintedStyle, the style of the first item the node painted itself (not a child's) that puts down paint (a fill or a stroke), before any paint-time animation. Every layout() clears it. A label lowers after its mark and reads it to pick its color (see Labels).
Nodes that draw nothing. A node can take part in layout without contributing any pixels: it keeps its dims, its datum and its role as a selectAll anchor, and emits an empty fragment. There are two ways. A hidden node (isHidden() on _node.ts: .hidden() set _hidden, or it never paints) draws nothing unless a compositor reads its shape: the root bake and bakeSubtree stop at it, so it makes no draw entry at all, and under a compositor it lowers as its shape only (see Rendering). blank() is one: Blank in src/ast/shapes/rect.tsx builds a rect node, renames its type to blank and builds it as one that never paints (_neverPaints), so .hidden() has no effect on it. INTERNAL_emitNothing() (_node.ts) is the other: it replaces the node's lowering with one that returns [], so the node gives no shape either. A mark with no value is built this way, and GoFishRef (a placement stand-in) has always lowered the same way. Because every draw path — the SVG paint pass, the toDisplayList export, and a bake boundary's re-walk of its subtree — goes through the bake and INTERNAL_lower, each rule holds everywhere. blank() takes no paint-only options (stroke, corner radius): its fill survives only because it seeds the color scale. This matters at scale: the blank-fusion rewrite synthesizes one anchor blank per row, so a 26,000-row line chart used to emit 26,000 zero-size <rect> elements (and 26,000 entries in the interaction hit-test map) that nobody could see or click.
Its sibling is INTERNAL_visibleWhile(owner, visible), and the pair is worth reading together because the difference is which tier decides. .hidden() and INTERNAL_emitNothing are for a node that must never draw, and they answer at resolve. INTERNAL_visibleWhile is for a node whose drawing comes and goes with a signal — a time.sequence's keyframe groups, where the clock picks which band is showing — and it answers at paint: the items are lowered either way and their opacity is patched through the live-slot side table, each rule read once per tick as one decision the items under it share, so only the items whose rule changed its answer are patched (see Reactivity). A resolve-time answer there would make the clock a pipeline dependency and put the whole chart through layout on every tick, for a change that alters nothing above the marks themselves. Emitting nothing wins over being visible: a node with no items has nothing to patch, so the two compose with no coordination.
A visibility rule is set under an owner (a sequence, for its keyframes) and covers the node's whole subtree. INTERNAL_lower paints a node only while every owner's rule holds, each owner's being the one set nearest the node, so a sequence sets the rule once on each keyframe group, and marks that a later elaboration pass adds under the group hide with it. Setting a rule again from the same owner replaces it, so a second layout does not pile rules up. The label pass is the case that needs this: it wraps a keyframe group in a new layer that holds the group beside its label Texts, after the sequence has set its rule. wrapPreservingIdentity (src/ast/elaborationUtils.ts) moves the rule onto the wrapper along with the group's name and key, so the labels are inside the rule's subtree, show only with the year they label, and belong to that year's keyframe (keyframeOf in src/timeWindow.ts reads the key of the node under the sequence's Frame).
A time.history({ last }) inside a keyframe gets a rule of its own from the sequence, set under the same owner, so for the marks under it it stands in for the keyframe group's rule: they show while the group's band overlaps [T − last, T] (lifetimeRule in src/timeWindow.ts). A transition hides the marks it moves, labels included, with INTERNAL_emitNothing: the moving mark is their drawing, and a trail behind it is a time.history of another mark in the same keyframe. Each leaf it moves also lends the transition its drawing, INTERNAL_lendDrawing: the transition draws a text where the playhead has taken it, and paints a box as the mark it moves is painted. A node keeps the lowering it was built with, so it lends its real drawing even after it has been silenced. The lent drawing lowers through the same body as INTERNAL_lower, so its items keep their ids and live channels, but it skips the visibility rule: the transition decides when the moving copy shows.
A build-in (src/animation/) uses a third hook, INTERNAL_animate(rule), which also answers at paint. The node lowers at rest. The rule then rewrites the items to the build clock's current state and registers a live slot for each field that changes: the geometry for a grow or a wipe, the opacity for a fade. The node keeps its layout box, the room it takes at rest, so nothing above it sees the effect play, and the chart is laid out once. A mark's labels paint under the same rule as riders that follow its timing. They find it through _attachedTo, which the label pass sets with INTERNAL_attach (the inverse of _attachments), so the order in which a mark and its label lower does not matter. A taken-over drawing skips the rule, as it skips visibility.
Render Pass 5: Per-Shape Lowering and Painting
Each shape/operator owns a lower(ctx) → DisplayItem[] — the extension point that replaced _render. It receives { intrinsicDims, transform, renderData, coordinateTransform, toPixel } and returns this node's fragment of the display list: an axis-aligned rect lowers to a rect item; a bar in a non-linear (e.g. polar) coordinate space lowers to a warped path item (its points mapped through both the coordinate transform and toPixel); text lowers to a text item; and so on. The "draw-rect vs draw-path" decision a rect used to make at render time is decided once, during lowering. Shared helpers live in src/ast/displayList/lowerHelpers.ts (pathToPixelSVG, rectItemFromBox, lowerStyle). A rect's inset is applied here too: on an axis where the rect fills the space it was given (no size or span of its own), the drawn box moves in by inset pixels at each end. Layout never sees it, so the rect's box, which refs and constraints read, stays the space it was given. Its corner radii follow SVG's rule (cornerRadii): one of rx and ry given is both, neither is 0, and an explicit 0 stays 0.
A single backend then paints each item. paintSVG (src/ast/displayList/paintSVG.tsx) emits SolidJS JSX for the live path; its pure-string sibling displayListToSVG (in gofish-ir) emits markup with no DOM. Both consume the same list and a cross-check test keeps them in lockstep. Because items are in final absolute pixels, painting is verbatim — a rect item becomes <rect x y width height …/>. See Rendering for the IR's item kinds (rect/ellipse/path/text/image/group/composite) and the toDisplayList({ w, h }) terminal that stops at the IR for non-SVG consumers.
Render Pass 5.5: Interaction hooks (when reactive)
The reactive layer adds a few hooks to this phase that are inert on the static path. The render terminal (chartBuilder.ts) always hands the resolve its chart's registrar (its interaction runtime, carried on the root LayerContext), so a live() channel or a library input read inside derive() can register during resolve; if nothing registers, rendering proceeds untouched. When something does, INTERNAL_lower (_node.ts) stamps each emitted item's id (the node's uid, for data-gf-id hit-testing) and — for a live() channel carried on the node as __gfLive — bakes a datum-bound thunk into a per-item side table (liveSlots.ts) that paintSVG re-evaluates reactively. render() (gofish.tsx) then publishes the lowered frame (items + recorded posScales/toPixel) to the runtime before paint and attaches delegated event listeners to the <svg>. See Rendering for the paint side.
Render Pass 6: Axis Rendering (removed)
The bespoke axis-rendering pass that used to live here (hand-written SVG for continuous/ordinal axes, ~400 lines of gofish.tsx) was deleted. Axes are now elaborated into ordinary GoFish nodes during layout (see Pass 7: Axis Elaboration and Axes), so they render through the normal node-tree pass above with no special casing. Axis titles were the last artifact still drawn here; they too are now elaborated during layout (see Render Pass 1), so nothing axis-related is drawn directly at render time.
Render Pass 7: Legend Rendering (removed)
The bespoke legend-rendering pass that used to live here (a <For> over scaleContext.unit.color hand-placing swatches behind a fixed LEGEND_MARGIN) was deleted. Color legends are now elaborated into ordinary GoFish nodes during layout (see Pass 7: Chrome Elaboration, and Legends), so they render through the normal node-tree pass above with no special casing.
Complete Example: Bar Chart Rendering
Let's trace through a complete bar chart example:
barChart(data, {
x: "category",
y: "value",
orientation: "y",
});Step 1: Chart Construction
Location: src/charts/bar.ts:88-97
const builder = chart(data)
.flow(spread("category", { dir: "x" }))
.mark(rect({ h: "value" }));This creates:
- A
chartnode with the data - A
spreadoperator that groups by "category" and spreads along x - A
rectmark with height driven by "value"
Step 2: Layout Passes
- Color Resolution: No colors specified, so this is a no-op
- Key Resolution: Each bar gets a key like
"category-A","category-B", etc. - Size Domain Inference: For each rect,
inferSizeDomainsreturns a monotonic function for height - Underlying Space Resolution:
- X-axis:
ORDINAL(fromspread) - Y-axis:
SIZE(height is data-driven, no position)
- X-axis:
- Chrome Elaboration (axes when
axesis enabled): the chart is wrapped in layers carrying the y tick marks/labels (constraint-pinned at their data values) and the per-category x labels (ref-bound to the bars) - Layout Calculation:
- X-positions computed by
spreadoperator (ordinal spacing) - Y-positions set to 0 (bars start at baseline)
- Heights computed from data values using size scale factors
- X-positions computed by
- Ordinal Scale Building: Maps category keys to x-positions
Step 3: Render Pass
Lower: each bar's
lower()emits a singlerectdisplay-list item — a linear-space, one-dimension-data-driven bar lowers to an axis-aligned rectangle in absolute pixels (its pixel box mapped throughtoPixel):typescript// X is aesthetic (positioned by spread), Y is data-driven const gxMin = displayDims[0].min ?? 0; const width = displayDims[0].size ?? 0; // Inferred by spread const height = displayDims[1].size ?? 0; // From data // rectItemFromBox maps the box through toPixel → { kind: "rect", x, y, w, h } return [ rectItemFromBox(gxMin, gxMin + width, 0, height, toPixel, { style }), ];Axes: already part of the node tree (elaborated during layout), so the category labels, the y tick marks, and the axis titles lower alongside the bars — nothing axis-related is drawn separately.
Paint:
paintSVGturns eachrectitem into<rect x y width height …/>; the whole list paints directly under the<svg>with no flip group.
Debug Support
The system includes debugging capabilities. When the debug option is set:
if (debug) {
debugNodeTree(child);
console.log("scopeContext", scopeContext);
}- Node Tree Debugging: Visualizes the complete chart tree structure
- Context Logging: Outputs all context information for inspection
- Development Aid: Helps identify layout issues and optimization opportunities
Performance Considerations
- Single Traversal: Each pass traverses the tree only once when possible.
- Per-run sessions: Contexts are scoped to a single render session and discarded afterward, so there is no leakage between renders.
Measuring the passes
The passes above are instrumented for benchmarking via src/ast/perf.ts. Each labeled phase is bracketed in runLayout() / layout() (and the paint path in render()) with perfNow() / perfAdd(label, …), accumulating per-pass durations under the labels resolve (Passes 2–6: color/name/label/alias/space resolution = domain inference), axes (Pass 7 + title/legend elaboration), embed (the resolveEmbedding pass), claims (the root's claim walk, root.resolveExtent(), and the root's scope solve against the render's slot), solve (Pass 9 constraint solve), lower (display-list lowering) and paint (display-item → SVG), plus fonts (the webfont-readiness await).
Alongside the per-pass timings (current.labels), the same run records scene-graph size counters (current.counts) via perfSetCount(name, value): nodes (the count of nodes in the fully elaborated tree the solver sees, walked just before solve) and displayItems (the number of items lower emits). Unlike timings these are absolute sizes, not accumulated. The bench driver reads the global directly, so the shape window.__GOFISH_PERF__.current = { labels, counts } — with counts.nodes and counts.displayItems — is the contract; perfSnapshot() returns a { labels, counts } copy of the same.
Collection is off by default and zero-cost when off: the helpers short-circuit on globalThis.__GOFISH_PERF__?.enabled, and the node-count walk is additionally guarded by perfEnabled() so the off path never traverses the tree. The published library build replaces the compile-time constant __GOFISH_PERF_INSTRUMENTATION__ with false (via vite.config.ts's define), so the minifier dead-code-eliminates the whole subsystem — the npm package ships none of it. The bench harness (tests/scripts/bench.ts) flips the runtime flag on to read per-pass numbers for the ecological example suites and the synthetic asymptotics sweeps.
For production-codegen numbers (rather than the Vite dev transform + SolidJS dev mode no user runs), the build:bench script (vite build --mode bench) emits an instrumented, minified bundle to dist-bench/ — identical to the published dist/ build but with __GOFISH_PERF_INSTRUMENTATION__ defined true so the subsystem survives. dist-bench/ is gitignored and excluded from the published package; the bench driver aliases gofish-graphics to it.
Key Takeaways
- Layout is separate from rendering: All spatial calculations happen in the layout phase
- Underlying space determines scale types: The underlying space resolution pass is critical for determining how to scale and render
- Keys enable axis labeling: The key resolution pass enables ordinal axes to find and position category labels
- Rendering adapts to coordinate spaces: each shape's
lower()adapts what display-list item it emits (an axis-alignedrectvs a warpedpath) based on which dimensions are data-driven and what coordinate transform is active - Contexts flow through passes: The three session contexts (scope, scale, key) are populated during layout and used during rendering
Code References Summary
- Main entry point:
src/ast/gofish.tsx - Node implementation:
src/ast/_node.ts - Rect shape:
src/ast/shapes/rect.tsx - Bar chart helper:
src/charts/bar.ts - Underlying space types:
src/ast/underlyingSpace.ts
