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';

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

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>;

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.