Skip to main content

Builder API

Complete reference for the fluent builder chain. All methods return this for chaining unless noted otherwise.

viz()

Creates a new VizBuilder instance.

import { viz } from 'vizcraft';
const builder = viz();

VizBuilder

The top-level scene builder.

.view(w, h)

Sets the SVG viewBox dimensions.

builder.view(800, 600);

.grid(cols, rows, opts?)

Defines a grid system for cell-based node positioning.

ParamTypeDescription
colsnumberNumber of columns
rowsnumberNumber of rows
opts.xnumberLeft padding
opts.ynumberTop padding

.node(id)NodeBuilder

Creates or re-opens a node definition. Returns a NodeBuilder for chaining node-specific methods.

.node(id, opts)VizBuilder

Creates a node declaratively via NodeOptions. Returns the VizBuilder (not NodeBuilder).

See NodeOptions for the full options shape.

.edge(from, to)EdgeBuilder

Creates or re-opens an edge. Returns an EdgeBuilder.

.edge(from, to, opts)VizBuilder

Creates an edge declaratively via EdgeOptions. Returns the VizBuilder.

See EdgeOptions for the full options shape.

.overlay(id, params, key?)

Adds a single overlay instance (shorthand form).

.overlay(callback)

Adds overlays via the OverlayBuilder callback form. See Overlay API.

.animate(callback)AnimationSpec

Defines a data-only timeline animation. See Animation API.

.layout(algorithm, options?)

Applies a synchronous auto-layout algorithm to compute node positions.

import { circularLayout } from 'vizcraft';
builder.layout(circularLayout, { cx: 250, cy: 150, radius: 80 });

Throws if the algorithm returns a Promise — use .layoutAsync() instead.

.layoutAsync(algorithm, options?)Promise<VizBuilder>

Applies an async layout algorithm (e.g. ELK via web workers). Works with both sync and async algorithms.

await builder.layoutAsync(elkLayout);
builder.mount(container);

.use(plugin, options?)

Applies a VizPlugin to the builder.

builder.use(watermarkPlugin, { text: 'Draft' });

.on(event, callback)

Subscribes to lifecycle events.

EventPayloadDescription
'build'{ scene }After .build() compiles the scene
'mount'{ container, controller }After .mount() renders to DOM

.build()VizScene

Compiles the builder state into a plain VizScene data object.

.mount(container, opts?)MountController

Renders the scene to a DOM element.

OptionTypeDefaultDescription
panZoombooleanfalseEnable interactive pan & zoom
minZoomnumber0.1Minimum zoom level
maxZoomnumber5Maximum zoom level
initialZoom'fit' | number'fit'Initial zoom
autoplaybooleanfalseAuto-play animations
cssstringInjected CSS string
overlayRegistryOverlayRegistrydefaultCustom overlay registry

.svg(opts?)string

Exports the scene as an SVG string.

OptionTypeDescription
includeRuntimebooleanInclude runtime state (animation frame)

.play(container?, specs?)PlaybackController

Starts animation playback.

.resizeNode(id, size)

Resizes a node at runtime.

builder.resizeNode('dynamic', { w: 180, h: 80 });

.patchRuntime(container)

Applies runtime changes (resize, property overrides) to the mounted SVG.

.addNode(nodeData) / .addEdge(edgeData)

Imperatively add nodes/edges for incremental mutations.

.updateNode(id, partial) / .removeNode(id)

Update or remove nodes at runtime.

.commit(container)

Syncs incremental mutations to the DOM.


NodeBuilder

Returned by builder.node(id). All methods return this for chaining.

Shape methods

Each method sets the node's geometry:

MethodParamsNotes
.circle(r)radius
.rect(w, h, rx?)width, height, corner radius
.diamond(w, h)width, height
.ellipse(rx, ry)horizontal, vertical radii
.hexagon(r, orientation?)radius, 'pointy' or 'flat'
.cylinder(w, h, arcHeight?)width, height, cap arc
.triangle(w, h, direction?)width, height, 'up'/'down'/'left'/'right'
.star(points, outerR, innerR?)tip count, outer radius, inner radius
.cloud(w, h)bounding width/height
.cross(size, barWidth?)overall size, bar thickness
.cube(w, h, depth?)width, height, isometric depth
.arc(r, startAngle, endAngle, closed?)radius, start°, end°, close path
.blockArrow(length, bodyW, headW, headL, dir?)dimensions + direction
.callout(w, h, opts?)width, height, pointer options
.document(w, h, waveHeight?)width, height, wave amplitude
.note(w, h, foldSize?)width, height, fold corner size
.parallelogram(w, h, skew?)width, height, skew offset
.trapezoid(topW, bottomW, h)top/bottom widths, height
.path(d, w, h)SVG path data, bounding boxCustom shape escape hatch

Positioning

MethodDescription
.at(x, y)Set absolute position
.cell(col, row, align?)Place in grid cell

Styling

MethodDescription
.fill(color)Fill color
.stroke(color, width?)Stroke color and optional width
.opacity(value)Opacity (0–1)
.dash(pattern)Dash pattern: 'dashed', 'dotted', 'dash-dot', 'solid', or SVG dasharray
.shadow(opts?)Drop shadow ({ dx, dy, blur, color })
.sketch(enabled?, seed?)Hand-drawn rendering mode
.class(className)CSS class
.zIndex(n)Z-ordering depth

Labels

MethodDescription
.label(text, opts?)Simple text label
.multiLineLabel(lines, opts?)Multi-line label (array of strings)
.richLabel(callback)Rich text builder: (l) => l.bold('Hi').text(' world')

Media

MethodDescription
.image(href, w, h, opts?)Embed an image
.icon(id, size, opts?)Embed an icon from the registry
.svgContent(content, w, h, opts?)Embed inline SVG

Ports

MethodDescription
.port(id, offset, direction?)Add a named connection port

Containers

MethodDescription
.container(config?)Mark as a container node
.parent(parentId)Set parent container

Compartments

MethodDescription
.compartment(id, cb?)Add a compartment section. Optional callback receives a CompartmentBuilder
.collapsed(state?)Render only the first compartment (header). Pass false to expand. Default: true
.collapseIndicator(opts)Customise or hide the collapse chevron. Pass false to hide, or an object with color, visible, render. See CollapseIndicatorOptions
.collapseAnchor(anchor)Set the anchor for collapse animation: 'top', 'center' (default), or 'bottom'. See CollapseAnchor

CompartmentBuilder

Returned inside the .compartment(id, cb) callback. All methods return this for chaining.

MethodDescription
.label(text, opts?)Set the compartment label (defaults textAnchor: 'start'). Mutually exclusive with .entry().
.entry(id, text, opts?)Add an interactive entry line. See EntryOptions. Mutually exclusive with .label().
.height(px)Set explicit height (auto-sized from label/entries when omitted)
.onClick(handler)Register a click handler. Receives CompartmentClickContext with nodeId, compartmentId, collapsed, and toggle() helper
tip

.label() and .entry() are mutually exclusive within a single compartment. Calling one after the other replaces the previous content and logs a console warning.

Interaction

MethodDescription
.onClick(handler)Attach click handler (id, node) => void
.tooltip(content)Hover tooltip — string or { title?, sections: {label,value}[] }
.badge(text, opts?)Text badge pinned to a corner — see VizNodeBadge

Animation

MethodDescription
.animate(callback)Per-node animation via AnimationBuilder
.animateTo(props, opts)Quick transition shorthand

Chaining control

MethodReturnsDescription
.done()VizBuilderReturn to the parent builder

EdgeBuilder

Returned by builder.edge(from, to). All methods return this for chaining.

Routing & path

MethodDescription
.routing(mode)'straight', 'curved', 'orthogonal'
.waypoint(x, y)Add an intermediate waypoint

Markers

MethodDescription
.arrow()Add arrow marker at target end
.arrowBoth()Arrows at both ends
.arrowStart()Arrow at source end
.marker(end?, start?)Set explicit marker types

Port connection

MethodDescription
.fromPort(portId)Connect from a specific source port
.toPort(portId)Connect to a specific target port
.fromAngle(degrees)Fixed perimeter angle at source
.toAngle(degrees)Fixed perimeter angle at target

Straight-line perimeter anchors

MethodDescription
.straightLine()Auto-compute fromAngle + toAngle for a straight line
.straightLineFrom()Auto-compute fromAngle only (source aimed at target)
.straightLineTo()Auto-compute toAngle only (target aimed at source)

Explicit fromAngle/toAngle overrides the auto-computed value when both are set.

Self-loops

MethodDescription
.loopSide(side)Loop direction: 'top', 'right', 'bottom', 'left'
.loopSize(px)Loop extension distance

Styling

MethodDescription
.stroke(color, width?)Stroke color and width
.fill(color)Fill color
.opacity(value)Opacity
.dash(pattern)Dash pattern
.sketch(enabled?)Hand-drawn mode
.class(className)CSS class
.hitArea(width)Invisible hit-area width

Labels

MethodDescription
.label(text, opts?)Add a label (chainable for multiple)

Animation

MethodDescription
.animate(name, opts?)CSS/registry animation (e.g. 'flow')

Data

MethodDescription
.meta(data)Attach metadata
.data(payload)Attach custom data
.onClick(handler)Attach click handler
.tooltip(content)Hover tooltip — string or { title?, sections: {label,value}[] }

Chaining control

MethodReturnsDescription
.done()VizBuilderReturn to the parent builder

NodeOptions

Full declarative options object for builder.node(id, opts). See the Types reference for all fields.

EdgeOptions

Full declarative options object for builder.edge(from, to, opts). See the Types reference for all fields.


Found a problem? Open an issue on GitHub.