Skip to main content

Types

All types shown here are exported from vizcraft and can be imported as:

import type { VizScene, VizNode, VizEdge, ... } from 'vizcraft';

VizSpec

Declarative, JSON-serialisable scene description for use with fromSpec.

FieldTypeRequiredDescription
view{ width; height }Viewport dimensions in scene units
nodesNodeSpec[]Scene nodes. See NodeSpec
edgesEdgeSpec[]Edges. See EdgeSpec
overlaysStaticOverlaySpec[]Overlay annotations. See StaticOverlaySpec
autoSignalsAutoSignalSpec[]Self-animating signals (future). See AutoSignalSpec
stepsVizStepSpec[]Step-through walkthrough. See VizStepSpec and createStepControllerFromSpec

NodeSpec

Plain JSON node description consumed by fromSpec.

FieldTypeDefaultDescription
idstringUnique id
labelstring | string[]Display text. Array → multi-line
shapeNodeSpecShape'rect'Shape name. See NodeSpecShape
xnumberCentre X in scene coordinates
ynumberCentre Y in scene coordinates
widthnumberper-shapeWidth (circle: diameter, ellipse: full width)
heightnumberper-shapeHeight (ignored for circle / hexagon)
fillstringFill colour
strokestringStroke colour
strokeWidthnumberStroke width
opacitynumberOpacity 0–1
dashedbooleanDashed border
dottedbooleanDotted border
classstringCSS class on the node's SVG element
tooltipobject{ title, sections? } hover tooltip

NodeSpecShape

String union used in NodeSpec.shape. One of: 'rect' · 'circle' · 'diamond' · 'cylinder' · 'hexagon' · 'ellipse' · 'cloud' · 'document' · 'parallelogram' · 'triangle' · 'note'


EdgeSpec

Plain JSON edge description consumed by fromSpec.

FieldTypeDefaultDescription
fromstringSource node id
tostringTarget node id
idstringfrom-toExplicit id for overlay anchoring
labelstringEdge label
styleEdgeStyleSpec'straight''straight' · 'curved' · 'orthogonal'
arrowArrowModeSpec'end''end' · 'start' · 'both' · false
animate'flow' | false'flow' → marching-ants CSS animation
strokestringStroke colour
strokeWidthnumberStroke width
dashedbooleanDashed stroke
dottedbooleanDotted stroke
opacitynumberOpacity 0–1
classstringCSS class

StaticOverlaySpec

Discriminated union on type ('rect' · 'circle' · 'text'). Consumed by fromSpec.

Shared positioning fields:

FieldTypeDescription
typestringShape discriminant
keystringOptional stable key for runtime patching
nodeIdstringAnchor to node centre; x/y become offsets
xnumberAbsolute x, or x-offset when nodeId is set
ynumberAbsolute y, or y-offset when nodeId is set
opacitynumberOpacity 0–1

Type-specific fields for 'rect': width, height, rx, fill, stroke, strokeWidth.
Type-specific fields for 'circle': r, fill, stroke, strokeWidth.
Type-specific fields for 'text': text, fill, fontSize, fontWeight, textAnchor.


AutoSignalSpec

Declarative self-animating signal spec. Stored by VizBuilder.autoSignal() and accepted in VizSpec.autoSignals. The internal animator starts automatically when mount() is called — no consumer code needed.

FieldTypeDefaultDescription
idstringUnique stable id
chainstring[]Ordered node ids (min 2)
durationPerHopnumber800ms per hop
totalDurationnumberTotal ms across all hops (alternative to per-hop)
loopbooleanfalseRestart after reaching the final node
loopDelaynumber0Pause in ms before restarting when loop: true
keepFinalbooleanfalsePark the dot at the final node when not looping
colorstringDot fill colour
glowColorstringGlow / halo colour
magnitudenumber1Visual scale of the signal dot, 0–1

VizStepSpec

One step in a VizSpec.steps walkthrough. Used with createStepControllerFromSpec.

FieldTypeDescription
labelstringDescriptive label for the step
highlightstring[]Node ids to keep at full opacity; others are dimmed to 30%
overlaysStaticOverlaySpec[]Step-specific overlays added on top of the base scene; removed on step exit
signalsAutoSignalSpec[]Signals to animate. Always treated as loop: false
autoAdvancebooleanWhen true, calls next() automatically after all non-looping signals complete

StepDef

One step in a programmatic walkthrough. Used with createStepController.

FieldTypeDescription
labelstringText shown in the step bar / onStepChange callback
builderVizBuilder | (() => VizBuilder)Scene for this step. Factories are called once and cached
autoSignals?AutoSignalSpec[]Signals to run while this step is active
autoAdvance?booleanAuto-advance after non-looping signals complete. Default: false

StepController

Returned by createStepController and createStepControllerFromSpec.

MemberTypeDescription
next()() => voidAdvance to the next step. No-op at the last step
prev()() => voidGo back. No-op at the first step
goTo(index)(number) => voidJump to a step by index. Throws RangeError if out of range
reset()() => voidReturn to step 0
currentIndexnumber (readonly)0-based index of the active step
totalStepsnumber (readonly)Total number of steps
isReadyboolean (readonly)true once all non-looping animations have completed
pause()() => voidPause signal animations on the current step
resume()() => voidResume paused animations
destroy()() => voidStop animations, clear SVG, remove step bar. Idempotent

VizScene

Complete, serializable description of what to render.

FieldTypeDescription
viewBox{ w: number; h: number }SVG coordinate space
nodesVizNode[]Nodes to render
edgesVizEdge[]Edges to render
overlays?VizOverlaySpec[]Optional overlay layer
animationSpecs?AnimationSpec[]Data-only timelines
sketch?{ enabled?: boolean; seed?: number }Global hand-drawn mode

SignalOverlayHop

One hop inside a declarative signal chain.

FieldTypeDescription
fromstringHop source node id
tostringHop target node id
followEdge?booleanFollow the only matching from -> to edge path for this hop
edgeId?stringExplicit edge id to follow for this hop; takes precedence

SignalOverlayParams

Built-in params for the signal overlay.

Use either single-hop from / to fields or a declarative chain of SignalOverlayHop entries. Before arrival, the signal uses the normal center-to-center or edge-following motion rules. Single-hop signals park when resting or parkAt are set and progress >= 1. Chain signals park automatically once progress >= chain.length.

FieldTypeDescription
fromstringSingle-hop source node id. Mutually exclusive with chain
tostringSingle-hop target node id and the default parked node. Mutually exclusive with chain
chain?SignalOverlayHop[]Declarative multi-hop path. floor(progress) selects the active hop
progressnumberSingle-hop position 0..1, or hop index plus local progress for chain
magnitude?numberVisual intensity used to scale the marker radius
color?stringCSS color for the ball fill; defaults to the class fill (#3b82f6)
glowColor?stringSeparate glow / halo color; defaults to color when omitted
followEdge?booleanSingle-hop edge-follow hint; chain hops carry their own followEdge
edgeId?stringSingle-hop explicit edge id; chain hops carry their own edgeId
resting?booleanSingle-hop only: keep the signal visible at to once it arrives
parkAt?stringOverride the node used for parked placement after arrival
parkOffsetX?numberHorizontal parked offset from the parked node center
parkOffsetY?numberVertical parked offset from the parked node center

RectOverlayParams

Built-in params for the rect overlay.

Use either absolute x / y coordinates or nodeId with optional offsetX / offsetY. Absolute x / y keep the existing top-left rectangle semantics. When nodeId is used, VizCraft resolves the node center first and then centers the rectangle on that anchor.

FieldTypeDescription
xnumberAbsolute top-left x. Mutually exclusive with nodeId
ynumberAbsolute top-left y. Mutually exclusive with nodeId
nodeIdstringAnchor the rectangle to a node center
offsetX?numberHorizontal offset from the anchored node center
offsetY?numberVertical offset from the anchored node center
wnumberRectangle width
hnumberRectangle height
rx?numberCorner radius on x
ry?numberCorner radius on y
opacity?numberOptional opacity
fill?stringFill color
stroke?stringStroke color
strokeWidth?numberStroke width

CircleOverlayParams

Built-in params for the circle overlay.

Use either absolute x / y coordinates or nodeId with optional offsetX / offsetY. When nodeId is used, the circle center becomes node.centre + { offsetX, offsetY }.

FieldTypeDescription
xnumberAbsolute center x. Mutually exclusive with nodeId
ynumberAbsolute center y. Mutually exclusive with nodeId
nodeIdstringAnchor the circle to a node center
offsetX?numberHorizontal offset from the anchored node center
offsetY?numberVertical offset from the anchored node center
rnumberCircle radius
opacity?numberOptional opacity
fill?stringFill color
stroke?stringStroke color
strokeWidth?numberStroke width

TextOverlayParams

Built-in params for the text overlay.

Use either absolute x / y coordinates or nodeId with optional offsetX / offsetY. When nodeId is used, the text anchor point becomes node.centre + { offsetX, offsetY }.

FieldTypeDescription
xnumberAbsolute text anchor x. Mutually exclusive with nodeId
ynumberAbsolute text anchor y. Mutually exclusive with nodeId
nodeIdstringAnchor the text to a node center
offsetX?numberHorizontal offset from the anchored node center
offsetY?numberVertical offset from the anchored node center
textstringText content
opacity?numberOptional opacity
fill?stringFill color
fontSize?numberFont size
fontWeight?string | numberFont weight
textAnchor?'start' | 'middle' | 'end'SVG text-anchor
dominantBaseline?stringSVG dominant-baseline

GroupOverlayParams

Built-in params for the group overlay.

Use one of three positioning modes:

  • Absolute x / y translation in scene coordinates.
  • nodeId with optional offsetX / offsetY to anchor the group origin to a node center.
  • from / to with progress to interpolate between node centers.

When nodeId or from / to are used, x and y remain additional offsets applied after the resolved anchor.

FieldTypeDescription
x?numberAbsolute translation or additional offset
y?numberAbsolute translation or additional offset
nodeIdstringAnchor the group origin to a node center
offsetX?numberHorizontal offset from the anchored node center
offsetY?numberVertical offset from the anchored node center
fromstringSource node id for interpolated motion
tostringTarget node id for interpolated motion
progress?numberInterpolation amount used with from / to
magnitude?numberOptional pulse amount used to scale the group
scale?numberBase scale
rotation?numberRotation in degrees
opacity?numberGroup opacity
childrenVizOverlaySpec[]Child overlays in group-local coordinates

VizNode

A node in the scene graph.

| Field | Type | Description | | -------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------- | ---------------------- | ------------------------------------------------------------------------------ | | id | string | Unique identifier | | pos | { x: number; y: number } | Base position | | shape | NodeShape | Geometry (see NodeShape) | | label? | NodeLabel | Text label | | style? | object | fill, stroke, strokeWidth, opacity, strokeDasharray, shadow, sketch, sketchSeed | | className? | string | CSS class | | runtime? | VizRuntimeNodeProps | Runtime-only overrides (animation system) | | animations? | VizAnimSpec[] | Registry/CSS animation requests | | data? | unknown | Custom payload | | parentId? | string | Parent container node id | | container? | ContainerConfig | Container configuration | | ports? | NodePort[] | Explicit connection ports | | compartments? | VizNodeCompartment[] | Horizontal sections (UML-style). See VizNodeCompartment | | collapsed? | boolean | When true, only the first compartment is rendered (compact mode) | | collapseIndicator? | CollapseIndicatorOptions | false | Customise or hide the collapse chevron. Pass false to hide entirely | | collapseAnchor? | CollapseAnchor | Anchor point for collapse animation: 'top', 'center' (default), or 'bottom' | | tooltip? | TooltipContent | Tooltip shown on hover/focus. See TooltipContent | | badges? | VizNodeBadge[] | Text badges pinned to corners. See VizNodeBadge |


VizEdge

An edge connecting two nodes (or a dangling edge with free endpoints).

FieldTypeDescription
idstringUnique id (commonly "a->b")
from?stringSource node id
to?stringTarget node id
fromAt?Vec2Free-endpoint for source (dangling)
toAt?Vec2Free-endpoint for target (dangling)
fromPort?stringSource port id
toPort?stringTarget port id
fromAngle?numberFixed perimeter angle at source (degrees)
toAngle?numberFixed perimeter angle at target (degrees)
straightLine?boolean | 'from' | 'to'Auto-compute perimeter angles for a straight line between nodes
routing?EdgeRoutingPath algorithm
waypoints?Vec2[]Intermediate points
markerEnd?EdgeMarkerTypeTarget marker
markerStart?EdgeMarkerTypeSource marker
anchor?'center' | 'boundary'Connection behavior
labels?EdgeLabel[]Labels at various positions
style?objectstroke, strokeWidth, fill, opacity, strokeDasharray, sketch
runtime?VizRuntimeEdgePropsRuntime-only overrides
animations?VizAnimSpec[]Registry/CSS animation requests
meta?Record<string, unknown>User metadata
data?unknownCustom payload
tooltip?TooltipContentTooltip shown on hover/focus. See TooltipContent

EdgeRouting

ModeDescription
'straight'Direct line (default). Polyline with waypoints.
'curved'Smooth bezier. Catmull-Rom spline through waypoints.
'orthogonal'Right-angle (elbow) connectors.

EdgeMarkerType

TypeDescriptionUse case
'none'No markerPlain line
'arrow'Filled triangleDependency
'arrowOpen'Open triangleInheritance (UML)
'diamond'Filled diamondComposition (UML)
'diamondOpen'Open diamondAggregation (UML)
'circle'Filled circleNavigable association
'circleOpen'Open circleAssociation endpoint
'square'Filled squareCustom endpoint
'bar'Perpendicular T-lineER cardinality
'halfArrow'Single-sided arrowDirectional hint

EdgeLabel

PropertyTypeDescription
textstringLabel text
rich?RichTextRich formatted label
position'start' | 'mid' | 'end'Position on path
className?stringCSS class
dx?numberHorizontal offset
dy?numberVertical offset (default -10)
fill?stringText color
fontSize?number | stringFont size
fontWeight?number | stringFont weight
fontFamily?stringFont family

NodeShape

Supported geometries. Each variant is a discriminated union on kind:

KindKey paramsDescription
circlerCircle
rectw, h, rx?Rectangle
diamondw, hRhombus
ellipserx, ryEllipse
hexagonr, orientation?Regular hexagon
cylinderw, h, arcHeight?Database symbol
trianglew, h, direction?Triangle
starpoints, outerR, innerR?Multi-pointed star
cloudw, hBumpy outline
crosssize, barWidth?Plus sign
cubew, h, depth?3D isometric box
arcr, startAngle, endAngle, closed?Arc/pie slice
blockArrowlength, bodyWidth, headWidth, headLength, direction?Thick arrow
calloutw, h, pointer optionsSpeech bubble
documentw, h, waveHeight?Wavy bottom
notew, h, foldSize?Folded corner
parallelogramw, h, skew?Skewed rect
trapezoidtopW, bottomW, hTrapezoid
pathd, w, hCustom SVG path

NodeLabel

PropertyTypeDescription
textstringLabel text
rich?RichTextRich/mixed-format label
className?stringCSS class
dx?numberHorizontal offset
dy?numberVertical offset
fill?stringText color
fontSize?number | stringFont size
fontWeight?number | stringFont weight
fontFamily?stringFont family

RichText

Token model for mixed-format labels.

type RichText = { kind: 'rich'; tokens: RichTextToken[] };

type RichTextToken =
| {
kind: 'span';
text: string;
bold?: boolean;
italic?: boolean;
underline?: boolean;
code?: boolean;
href?: string;
fill?: string;
fontSize?: number | string;
fontWeight?: number | string;
fontFamily?: string;
baselineShift?: 'sub' | 'super';
className?: string;
}
| { kind: 'newline' };

NodePort

FieldTypeDescription
idstringPort identifier (e.g. 'top', 'right')
offsetVec2Position relative to node center
direction?numberOutgoing angle in degrees

Default ports

ShapeDefault portsIDs
rect, circle, diamond, ellipse, cylinder4top, right, bottom, left
hexagon (pointy)6top, top-right, bottom-right, bottom, bottom-left, top-left
hexagon (flat)6right, top-right, top-left, left, bottom-left, bottom-right
triangle3–4varies by direction
Fallback4top, right, bottom, left

Port utility functions

FunctionSignatureDescription
getDefaultPorts(shape) => NodePort[]Default ports for a shape
getNodePorts(node) => NodePort[]Effective ports (explicit or default)
findPort(node, portId) => NodePort?Lookup by id
findPortNearest(node, x, y) => NodePort?Closest port to a point
resolvePortPosition(node, portId) => Vec2?Absolute port position
getEquidistantPorts(shape, count?) => EquidistantPort[]N equidistant perimeter points
toNodePorts(ports) => NodePort[]Convert EquidistantPort to NodePort
registerPerimeterStrategy(strategy) => voidRegister custom perimeter strategy

EquidistantPort

FieldTypeDescription
idstringLocation-based identifier
anglenumberAngle from center (degrees)
tnumberParametric proportion [0, 1)
xnumberX offset from center
ynumberY offset from center

ContainerConfig

FieldTypeDefaultDescription
layout?'free' | 'vertical' | 'horizontal''free'Child layout
padding?{ top, right, bottom, left }Interior padding
autoSize?booleanAuto-resize to fit children
headerHeight?numberHeader band height

VizNodeCompartment

A horizontal section inside a compartmented node (e.g. UML class box name/attributes/methods).

FieldTypeDescription
idstringUnique id within the node (e.g. 'name', 'methods')
ynumberY offset from the node's top edge (computed at build)
heightnumberHeight in pixels
label?NodeLabelOptional label rendered inside the compartment
entries?CompartmentEntry[]Per-line interactive entries (mutually exclusive with label)
onClick?(ctx: CompartmentClickContext) => voidClick handler receiving context with toggle() helper. See CompartmentClickContext

Compartments are auto-sized when no explicit height is given — the builder estimates height from the label's line count and font size, or from the number of entries.

CompartmentClickContext

Context passed to a compartment's onClick handler, providing collapse control.

FieldTypeDescription
nodeIdstringThe node's id
compartmentIdstringThe compartment's id
collapsedbooleanCurrent collapsed state (before toggling)
collapseAnchorCollapseAnchorCurrent collapse anchor of the node ('center' when unset)
toggle(opts?: { animate?: number; anchor?: CollapseAnchor }) => voidToggle collapse; optional animate duration in ms, optional anchor override

CollapseIndicatorOptions

Options for customising the collapse indicator (chevron) on compartmented nodes.

FieldTypeDescription
color?stringFill colour of the default triangle. Defaults to the node's stroke colour
visible?booleanSet to false to hide the indicator. Defaults to true when a compartment has an onClick handler
render?(collapsed: boolean) => stringReturn a custom SVG string to replace the default triangle. Receives the current collapsed state

Pass false instead of an options object to hide the indicator entirely:

.collapseIndicator(false)

CollapseAnchor

The anchor point from which a node collapses/expands:

ValueDescription
'top'Top edge stays fixed; the node shrinks/grows downward
'center'The node shrinks/grows symmetrically (default)
'bottom'Bottom edge stays fixed; the node shrinks/grows upward
type CollapseAnchor = 'top' | 'center' | 'bottom';

CompartmentEntry

A single interactive line inside a compartment. Each entry has its own hit region, optional click handler, tooltip, and styling.

FieldTypeDescription
idstringUnique id within the compartment
ynumberY offset within the compartment (computed)
heightnumberHeight in pixels (computed, includes padding)
textstringDisplay text
label?NodeLabelResolved label with styles
onClick?() => voidClick handler for this entry
tooltip?TooltipContentTooltip shown on hover
className?stringCustom CSS class applied to the entry element
paddingTop?numberTop padding in pixels (default 0)
paddingBottom?numberBottom padding in pixels (default 0)

EntryStyle

Per-entry text styling options.

FieldTypeDescription
fill?stringText color
fontSize?number | stringFont size
fontWeight?number | stringFont weight
fontStyle?stringFont style (e.g. 'italic')
fontFamily?stringFont family

EntryOptions

Options passed to .entry(id, text, opts?) on the CompartmentBuilder.

FieldTypeDescription
onClick?() => voidClick handler
style?EntryStylePer-entry text styling
tooltip?TooltipContentTooltip shown on hover
maxWidth?numberMax text width in pixels
overflow?'clip' | 'ellipsis'Text overflow behavior
padding?number | { top?: number; bottom?: number }Vertical padding around entry text. A single number applies equally to top and bottom.
className?stringCustom CSS class applied to the entry element

TooltipContent

Tooltip content attached to a node or edge. Shown on hover or keyboard focus.

Can be a plain string or a structured object with optional title and labelled sections.

type TooltipContent = string | { title?: string; sections: TooltipSection[] };

TooltipSection

FieldTypeDescription
labelstringKey / label text
valuestringValue / info text

VizNodeBadge

A small text indicator pinned to a corner of a node shape.

FieldTypeDescription
textstring1–2 character badge text
positionBadgePositionCorner: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
fill?stringText color
background?stringOptional pill background color
fontSize?numberFont size in px (default 10)

BadgePosition

type BadgePosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';

VizPlugin

type VizPlugin<Options = any> = (
builder: VizBuilder,
options?: Options
) => void;

NodeOptions

Declarative options for builder.node(id, opts). See Builder API.

EdgeOptions

Declarative options for builder.edge(from, to, opts). See Builder API.


Animation types

AnimationSpec

{ version: 'viz-anim/1'; tweens: TweenSpec[] }

TweenSpec

{ kind: 'tween'; target: AnimationTarget; property: AnimProperty; to: number; duration: number; delay?: number; easing?: Ease; from?: number }

AnimationTarget

  • node:<id> — targets a node
  • edge:<id> — targets an edge
  • overlay:<key> — targets an overlay

AnimProperty / CoreAnimProperty

Core: x, y, opacity, scale, rotation (nodes); opacity, strokeDashoffset (edges). Custom properties via extendAdapter.

AnimatableProps

Property bag for aBuilder.to(props, opts). Typed for core properties, accepts arbitrary numeric keys.

TweenOptions

{ duration: number; easing?: Ease; from?: Record<string, number> }

Ease

'linear' | 'easeIn' | 'easeOut' | 'easeInOut'

PlaybackController

{ play(): void; pause(): void; stop(): void; seek(ms: number): void }

ExtendAdapter

(adapter: AnimationHostAdapter & Partial<RegistrableAdapter>) => void

VizRuntimeNodeProps

FieldType
x?number
y?number
opacity?number
scale?number
rotation?number

VizRuntimeEdgeProps

FieldType
strokeDashoffset?number
opacity?number

EdgePathResult

Low-level path computation result returned by computeEdgePath and computeSelfLoop.

FieldTypeDescription
dstringSVG path d attribute
midVec2Approximate midpoint along the path
startVec2Position near the source (~15% along the path)
endVec2Position near the target (~85% along the path)

ResolvedEdgeGeometry

Returned by resolveEdgeGeometry. Extends EdgePathResult with convenience fields.

FieldTypeDescription
dstringSVG path d attribute
midVec2Approximate midpoint along the path
startVec2Position near the source (~15% along the path) — same as startLabel
endVec2Position near the target (~85% along the path) — same as endLabel
startAnchorVec2True boundary/port position where the edge exits the source node
endAnchorVec2True boundary/port position where the edge enters the target node
startLabelVec2Label position ~15% along the path (alias of start)
endLabelVec2Label position ~85% along the path (alias of end)
waypointsVec2[]Waypoints used for the path (empty array when none)
isSelfLoopbooleanWhether this edge is a self-loop

Layout Types

LayoutGraph

Input graph structure passed to layout algorithms.

FieldTypeDescription
nodesVizNode[]All nodes
edgesVizEdge[]All edges

LayoutResult

Result returned by a layout algorithm.

FieldTypeDescription
nodesRecord<string, { x: number; y: number }>Computed node positions
edges?Record<string, { waypoints?: Vec2[] }>Optional edge routing waypoints

LayoutAlgorithm

A function that computes node positions. May return synchronously or as a Promise for async engines.

// Sync-only variant (for .layout())
type SyncLayoutAlgorithm<Options = any> = (
graph: LayoutGraph,
options?: Options
) => LayoutResult;

// Sync or async variant (for .layoutAsync())
type LayoutAlgorithm<Options = any> = (
graph: LayoutGraph,
options?: Options
) => LayoutResult | Promise<LayoutResult>;

Pan & Zoom Types

MountController

Always returned by .mount(). Exposes signal patching, the internal animator controls, and — when { panZoom: true } is passed — a panZoom sub-object.

MemberType / ReturnsDescription
patchSignals(signals)voidRender or update one or more in-flight signals by key
clearSignals()voidRemove all patched signal elements from the DOM
pause()voidPause the internal animator (auto-signals)
resume()voidResume a paused animator
stop()voidStop the animator and clear all signal dots
restart()voidClear and restart all auto-signals from progress 0
setSpeed(factor)voidMultiply animation speed (2 = twice as fast)
onSignalComplete(id, cb)() => voidSubscribe to a signal's completion; returns an unsubscribe function
panZoomPanZoomController | undefinedAvailable when { panZoom: true } was passed to mount()
destroy()voidTear down the scene — equivalent to builder.destroy()

PatchSignalSpec

A single signal to render or update via MountController.patchSignals().

FieldTypeDefaultDescription
keystringStable identifier; used to upsert the DOM element
from?stringSource node id (single-hop form)
to?stringTarget node id (single-hop form)
chain?Array<{ from: string; to: string }>Multi-hop form (alternative to from/to)
progressnumberPosition along the chain (0 → first node, 1 → second node, …)
resting?booleanKeep the dot visible at the final node after progress >= 1
parkAt?stringNode id to park at when signal completes
parkOffsetX?numberPixel offset from the parked node center (x)
parkOffsetY?numberPixel offset from the parked node center (y)
color?stringFill color for the signal dot
glowColor?stringGlow / drop-shadow color
magnitude?number1Dot size scale 0–1

PanZoomOptions

Options passed to .mount(container, opts) to configure interactive viewport controls.

FieldTypeDefaultDescription
panZoombooleanfalseEnable pan & zoom
minZoomnumber0.1Minimum zoom level
maxZoomnumber5Maximum zoom level
initialZoom'fit' | number'fit'Initial zoom level. 'fit' calculates zoom to fit content
initialPanVec2Initial pan offset. Only used when initialZoom is a number
zoomOnWheelbooleantrueWhether scroll wheel zooms
panOnDragbooleantrueWhether drag on empty space pans

PanZoomController

Returned by .mount() when panZoom is true.

MemberType / ReturnsDescription
zoomnumberCurrent zoom level (read-only)
panVec2Current pan offset (read-only copy)
setZoom(level, center?)voidSet zoom level, optionally keeping center fixed
setPan(offset)voidSet absolute pan offset
fitToContent(padding?)voidZoom & pan to fit all content
zoomToNode(nodeId, padding?)voidCenter on a specific node
reset()voidRestore initial zoom & pan
getState(){ zoom: number; pan: Vec2 }Snapshot current viewport state
onChange(cb)() => voidSubscribe to viewport changes; returns unsubscribe function
destroy()voidClean up event listeners

Utilities

getNodeBoundingBox(shape)

Computes the tight axis-aligned bounding-box size for a given NodeShape.

import { getNodeBoundingBox } from 'vizcraft';

const { width, height } = getNodeBoundingBox({ kind: 'circle', r: 25 });
// → { width: 50, height: 50 }

Supports every NodeShape variant (circle, rect, diamond, ellipse, hexagon, star, trapezoid, callout, blockArrow, etc.) and accounts for orientation, direction, pointer height, and other shape-specific parameters.


Found a problem? Open an issue on GitHub.