English
Graph integration
Walkthroughs for building on NetworkGraph: large graphs and touch, deleting, context menus and tooltips, snapping and the clipboard, collapsible groups and edge styles, swimlanes, BPMN processes, quantity flows, ELK.js layouts, Mermaid, GraphML and draw.io files, layouts in a Worker and a small diagram editor. The props and events they use are listed on NetworkGraph.
Large graphs, touch and search
For graphs with thousands of nodes, set cullOffscreen so only the visible region is in the DOM. Keep showMinimap on to orient users, because the minimap still draws every node. A search box can pass the IDs found by your own code as matchIds and call focusNode(id) on the component ref to bring a result into view.
vue
<NetworkGraph ref="graph" :nodes="nodes" :edges="edges" cull-offscreen show-minimap :match-ids="matches" />ts
graph.value?.focusNode(matches.value.values().next().value, { scale: 1 })The graph needs no setup for touch: pinch to zoom and drag with two fingers to pan. Nested groups take an optional parentId on each group; see the API reference. Culled nodes are absent from the DOM and keyboard order, so offer a search or list for keyboard users who need to reach a distant node.
Deleting, context menus and tooltips
Deletion, like every graph edit, is a proposal. Enable deletable (and edgesSelectable so edges can be selected), then apply the delete event with removeGraphElements from the core entry. Committing the result as one useEditHistory entry lets Undo restore the nodes and edges together. Prune selections, saved positions and groups that mention removed IDs.
vue
<NetworkGraph :nodes="nodes" :edges="edges" edges-selectable deletable context-menu
v-model:selected-ids="selection" v-model:selected-edge-ids="edgeSelection"
@delete="applyDeletion" @context-menu="openMenu">
<template #tooltip="{ target }">
{{ target.kind === 'node' ? target.node.detail : target.edge.label }}
</template>
</NetworkGraph>ts
function applyDeletion(deletion: GraphDeletion) {
const next = removeGraphElements(nodes.value, edges.value, deletion)
history.commit({ ...history.state.value, ...next })
}The context-menu event only reports the request with its target, chart point and viewport coordinates. Render your own menu, for example with position: fixed at clientX and clientY; give it role="menu" and role="menuitem" entries, focus the first entry, close it with Escape and return focus to the graph element. The tooltip slot renders HTML in an overlay that the component positions; keep it short and non-interactive, because a tooltip cannot be focused.
Snapping, palettes and the clipboard
Turn on snapGrid (with background="dots" to show the grid), alignmentGuides and autoPan for a diagram editor feel. Node moves still arrive as node-move and nodes-move proposals, already snapped.
A palette can add nodes in two ways. Drag and drop: make the palette items draggable, put an identifier in dataTransfer, set droppable on the graph and read it back in the node-drop event. Keyboard: let the same item be a button that adds the node at getViewportCenter(), because HTML drag and drop needs a pointer.
GraphPalette packages both ways (drag payload, readPaletteDrop and an insert event for Enter and Space), and PropertyInspector edits the selected node; see Diagram editor parts.
vue
<button type="button" draggable="true" @dragstart="$event.dataTransfer?.setData('application/x-node', 'task')"
@click="addTask(graph!.getViewportCenter())">Add task</button>
<NetworkGraph ref="graph" :nodes="nodes" :edges="edges" :positions="positions" draggable droppable clipboard
:snap-grid="20" background="dots" alignment-guides auto-pan
@node-drop="drop => drop.dataTransfer?.getData('application/x-node') === 'task' && addTask(drop.point)"
@copy-selection="copied = $event" @paste-request="paste" @duplicate-selection="duplicate" />drop.point is the drop position in chart coordinates, rounded to the grid. To centre a new node on the pointer instead of placing its corner there, convert drop.clientX and drop.clientY with toGraphPoint and round the corner once with snapGraphPoint. Saved positions must stay nonnegative.
The copy-selection, paste-request and duplicate-selection events only report keys and selections; the application keeps the copied data. cloneGraphElements from the core entry copies nodes and the edges between them with new IDs, moved positions and moved edge waypoints:
ts
function duplicate(selection: GraphClipboardSelection) {
const copies = cloneGraphElements(nodes.value, edges.value, selection.nodeIds, {
createId: (id, kind) => id + '-copy-' + nextNumber(kind),
positions: selection.positions,
offset: { x: 40, y: 40 },
})
history.commit({
nodes: [...nodes.value, ...copies.nodes], edges: [...edges.value, ...copies.edges],
positions: new Map([...positions.value, ...copies.positions]),
})
}For paste-request, store the copied nodes, edges and positions from the copy-selection event, then clone them with an offset that moves their top-left corner to event.point. Committing each operation as one useEditHistory entry makes Undo remove the copies together.
Collapsing groups, edge styles, waypoints and resizing
Keep the collapsed group IDs, node sizes and edge waypoints in your application state next to positions, and commit each accepted proposal as one history entry:
vue
<NetworkGraph :nodes="nodes" :edges="edges" :groups="groups" :positions="positions" :sizes="sizes" draggable
collapsible-groups :collapsed-group-ids="collapsed" @update:collapsed-group-ids="ids => commit({ collapsed: ids })"
edge-style="orthogonal" editable-edges edges-selectable resizable :lod-threshold="0.5"
@edge-reshape="reshape" @node-resize="resize" @node-move="move" @nodes-move="moveAll" />ts
function reshape({ id, after }: GraphEdgeReshape) {
commit({ edges: edges.value.map(edge => edge.id === id ? { ...edge, points: after.length ? after : undefined } : edge) })
}
function resize({ id, before, after }: GraphNodeResize) {
const nextPositions = after.x !== before.x || after.y !== before.y ? new Map(positions.value).set(id, { x: after.x, y: after.y }) : positions.value
commit({ sizes: new Map(sizes.value).set(id, { width: after.width, height: after.height }), positions: nextPositions })
}A collapsed group is drawn as a proxy node with the group's ID. Moves of the proxy arrive as moves of its members and deletions as deletions of its members, but selection and connection proposals carry the proxy ID, so reject or map them in validateConnection. collapseGraphGroups from the core entry computes the same view, for example to map the proxy back to its members in a context menu. Custom node slots can use the scale slot prop for their own level of detail. The handles use the classes vw-group-toggle, vw-waypoint-handle, vw-waypoint-add and vw-resize-handle and take their colours from --vw-accent and --vw-surface; no further theme variables are needed.
Swimlanes for process flows
To draw a process with one lane per department or work centre, lay it out with layoutSwimlaneGraph and pass its lanes to the lanes prop. Hand-overs between departments then read as edges that cross a lane boundary.
ts
const swimlanes = computed(() => layoutSwimlaneGraph(steps.value, links.value, {
lanes: departments.value.map(item => ({ id: item.id, label: item.name })), // the order you list is the order drawn
laneOf: step => step.data.department,
direction: direction.value,
}))
const layout: GraphLayoutFunction = () => swimlanes.valuevue
<NetworkGraph :nodes="steps" :edges="links" :layout="layout" :lanes="swimlanes.lanes" :options="{ direction }"
edge-style="orthogonal" avoid-nodes draggable @node-move="moveStep" />- Keep the lane list in application state. Lanes without steps still get a band, so the order stays stable as steps are added; to hide a lane, remove it from the list. Every step needs a lane that is in the list (otherwise the layout throws); keep an explicit "Unassigned" lane if your data can lack one.
- The component never reassigns a lane. On
node-move, callgraphSwimlaneAt(swimlanes.value.lanes, { ...change.after, width, height })and apply your domain rule: change the step's department and lay out again, or refuse the move.undefinedmeans the box would be outside every lane. The demo's Process lanes example (examples/SwimlaneDemo.vue) does this. - Use
edgeStyle: 'orthogonal'withavoidNodeswhen edges skip ranks, so they go around the steps in between. Lane headers are not obstacles foravoidNodes; they sit before the first rank, so routes and edge labels between steps stay out of them. exportSvg,exportPngandrenderGraphSvg({ lanes })draw the bands and titles. Long titles are clipped to the header; the full title is the lane's accessible name and, in exports, its<title>.
BPMN processes and flowcharts
The default renderer can draw a BPMN process or a classic flowchart without slots. Node fields choose the shape (circle, stadium, parallelogram, document, cylinder, data-object, plus the earlier diamond, ellipse and hexagon), a BPMN event border (event: 'start' | 'intermediate' | 'end'), a decorative symbol (marker: gateway, event or task type) and where the label goes (labelPosition: 'below' for small events and gateways). Edges add dashed and the hollow-arrow marker for message flows. Pools (BPMN participants) come from the pools option of layoutSwimlaneGraph and the pools prop.
ts
const event = (id: string, label: string, kind: NetworkNodeEvent, lane: string): NetworkNode<{ lane: string }> =>
({ id, label, shape: 'circle', event: kind, labelPosition: 'below', data: { lane } })
const nodes = [
event('received', 'Order received', 'start', 'sales'),
{ id: 'check', label: 'Check order', shape: 'rounded', marker: 'user', data: { lane: 'sales' } },
{ id: 'accept', label: 'Accept?', shape: 'diamond', marker: 'exclusive', labelPosition: 'below', data: { lane: 'sales' } },
{ id: 'orders', label: 'Orders', shape: 'cylinder', data: { lane: 'sales' } },
event('closed', 'Order closed', 'end', 'customer'),
]
// Sequence flows keep the default arrow; message flows cross pools.
const messageFlow = (id: string, from: string, to: string): GraphEdge =>
({ id, from, to, dashed: true, markerStart: 'circle', markerEnd: 'hollow-arrow' })
const swimlanes = computed(() => layoutSwimlaneGraph(nodes, edges, {
lanes: ['customer', 'sales', 'warehouse'],
pools: [{ id: 'buyer', label: 'Customer', lanes: ['customer'] }, { id: 'supplier', label: 'Supplier', lanes: ['sales', 'warehouse'] }],
laneOf: node => node.data?.lane,
}))vue
<NetworkGraph :nodes="nodes" :edges="edges" :layout="layout" :lanes="swimlanes.lanes" :pools="swimlanes.pools"
edge-style="orthogonal" connectable @connect="addFlow" />- Layouts give every node the same box. Circles and diamonds look right in square boxes, so a custom
layoutfunction can shrink the boxes of events and gateways around their centres and keep the rest oflayoutSwimlaneGraph's result. Useedge-style="orthogonal"or"straight"then: those styles route every edge from the boxes and end it on the shape's outline, while the layout's own curve paths still end on the old box sides. The demo's BPMN process example (examples/BpmnDemo.vue) does this. - Labels below a shape are not part of its box. Leave room with
rowGapandlanePadding; long labels can overlap neighbours or edges, and the halo keeps them readable. - Markers, event borders and shapes are decorative: the accessible name is the label (plus
detail). If assistive technology users need the BPMN type, put it intodetailor a tooltip. - Connecting, selecting, dragging and deleting work as for every node; whether a new connection is a sequence flow or a message flow (for example, by comparing the pools of its ends) is the application's decision in
validateConnectionand@connect. - Ports and connection handles stay on the node box, as for the other shapes.
exportSvg,exportPngandrenderGraphSvg({ lanes, pools })draw the same shapes, markers, labels, dashed edges and pools.
The pools add three variables, the other new parts reuse the node and edge colours. Event borders, the cylinder rim and the data object fold (vw-node-shape-detail) use the node's --vw-<tone>-line (--vw-<tone>-ink when hovered, focused, selected or related), markers (vw-node-marker) the node ink (--vw-on-solid when selected), labels below (vw-node-label-below) --vw-text on a --vw-surface-muted halo, and dashed edges (vw-network-edge vw-is-dashed) the edge colour. In forced-colors mode markers and lines are CanvasText (HighlightText on a selected node), labels below CanvasText on a Canvas halo, and pools Canvas outlined in CanvasText with CanvasText titles.
| Variable | Default | Used for |
|---|---|---|
--vw-pool-fill | --vw-surface (#ffffff) | Fill of a pool frame (vw-swimlane-pool-band) |
--vw-pool-header-fill | --vw-surface-hover (#e4ecf2) | Fill of a pool title band (vw-swimlane-pool-header) |
--vw-pool-border | --vw-muted (#4c6371) | Outline of pool frames and title bands; titles use --vw-lane-title |
Quantity flows (Sankey diagrams)
To show how much flows along each edge, such as a lot that splits and merges again or a cost allocated across departments, project the quantities with layoutFlowGraph and draw its bands with the edgeBands prop. Every band is as thick as its quantity on one scale for the whole picture, and keeps the original edge ID.
ts
const flow = computed(() => layoutFlowGraph(steps.value, transfers.value, {
quantity: transfer => transfer.data.amount,
unit: transfer => transfer.data.unit, // every edge states its unit
displayUnit: unit.value, // only this unit is drawn and summed
direction: direction.value,
scale: { fitExtent: 320 }, // or { pixelsPerUnit: 2 } for a fixed scale across pictures
}))
const layout: GraphLayoutFunction = () => flow.value
const shown = computed(() => transfers.value.filter(transfer => flow.value.paths.has(transfer.id)))
const bands = computed(() => graphFlowBands(flow.value))vue
<NetworkGraph :nodes="steps" :edges="shown" :layout="layout" :edge-bands="bands" :options="{ direction }"
edges-selectable @update:selected-edge-ids="showTransfer" />- Units are never added. Edges in another unit are left out of the picture and listed in
flow.excludedwith their ID, unit and quantity; show that list next to the graph, as the demo does, so nothing disappears silently. Convert units in your own data before the projection if a conversion is meaningful. - Differences are yours to explain.
flow.nodesreportsinflow,outflowanddifferenceper node as given; the layout never balances them. Name the difference in your domain (scrap, stock, yield, rounding) or add the missing edges. - Loops are references. An edge that closes a cycle, such as a rework loop, and a self-loop come back as
reference: truebands, drawn dashed below the picture and counted inreferenceInflowandreferenceOutflow, not in the totals. To show rework as forward flow over time, give each period its own node copies before the projection. - Zero quantities keep a 1-unit hairline band (
minBandWidth) that can still be selected. - Band names come from
label, for example "Cut → Inspect: 60 pcs"; passnodeLabelandformatQuantityto localize them. Thin node boxes leave little room for text: draw labels next to the boxes in anodeslot, as the demo does, and remember that exports use the default node drawing. exportSvg,exportPngandrenderGraphSvg(flow, nodes, shown, { edgeBands: bands })draw the same bands, each with its label as<title>. The demo's Quantity flow example (examples/QuantityFlowDemo.vue) shows a split, a merge, a yield loss, a rework loop and a unit switch.
Use ELK.js for layout
The built-in layouts (layoutLayeredGraph, layoutTreeGraph, layoutRadialGraph, layoutCircularGraph, layoutGridGraph, layoutConcentricGraph and layoutForceGraph) are synchronous, have no dependencies and cover flows, trees and organic graphs of up to a few thousand nodes. Prefer them unless you need what a full layout engine adds: node sizes that vary a lot, many ports with ordering constraints, labels placed together with the routes (the opt-in edgeLabelPlacement prop only moves labels along their fixed routes), compound graphs or orthogonal routes that avoid nodes and each other (the opt-in avoidNodes prop routes orthogonal edges around node boxes, but each edge on its own). Then an application can install ELK.js (npm install elkjs) itself and turn its output into a GraphLayout. @eightkk/vue-weave does not depend on ELK; the code below lives in your application.
ELK lays out asynchronously, and NetworkGraph's layout prop is synchronous. Compute the layout in the application (in a worker, with ELK's workerUrl, for large graphs), then pass the nodes, the edges and a layout function that returns the cached result together, so that the chart never sees data without matching geometry.
ts
import ELK from 'elkjs/lib/elk.bundled.js'
import type { ElkExtendedEdge, ElkNode, ElkPoint } from 'elkjs/lib/elk-api'
import { shallowRef, watch, type Ref } from 'vue'
import { graphPortAnchor, type GraphBox, type GraphEdge, type GraphLayout, type GraphLayoutFunction, type NetworkNode } from '@eightkk/vue-weave'
const elk = new ELK()
const nodeWidth = 144, nodeHeight = 58
const elkSide = { left: 'WEST', right: 'EAST', top: 'NORTH', bottom: 'SOUTH' } as const
const elkPortId = (nodeId: string, portId: string) => nodeId + '\u0000' + portId
function toElkGraph(nodes: readonly NetworkNode[], edges: readonly GraphEdge[]): ElkNode {
return {
id: 'root',
layoutOptions: {
'org.eclipse.elk.algorithm': 'layered',
'org.eclipse.elk.direction': 'RIGHT',
'org.eclipse.elk.edgeRouting': 'ORTHOGONAL',
'org.eclipse.elk.spacing.nodeNode': '24',
'org.eclipse.elk.layered.spacing.nodeNodeBetweenLayers': '50',
'org.eclipse.elk.padding': '[top=20,left=20,bottom=20,right=20]',
},
children: nodes.map(node => ({
id: node.id,
width: nodeWidth,
height: nodeHeight,
// Fixed ports at the anchors NetworkGraph draws (side and offset), so ELK places the nodes for them.
layoutOptions: node.ports?.length ? { 'org.eclipse.elk.portConstraints': 'FIXED_POS' } : undefined,
ports: node.ports?.map(port => {
const anchor = graphPortAnchor({ x: 0, y: 0, width: nodeWidth, height: nodeHeight, rank: 0 }, port)
return {
id: elkPortId(node.id, port.id), x: anchor.x, y: anchor.y, width: 0, height: 0,
layoutOptions: { 'org.eclipse.elk.port.side': elkSide[port.side] },
}
}),
})),
edges: edges.map(edge => ({
id: edge.id,
sources: [edge.fromPort === undefined ? edge.from : elkPortId(edge.from, edge.fromPort)],
targets: [edge.toPort === undefined ? edge.to : elkPortId(edge.to, edge.toPort)],
labels: edge.label ? [{ text: edge.label, width: edge.label.length * 7, height: 14 }] : undefined,
})),
}
}
/** An SVG path through the start, bend and end points of each orthogonal edge section. */
function sectionPath(edge: ElkExtendedEdge) {
return (edge.sections ?? []).map(section => [section.startPoint, ...(section.bendPoints ?? []), section.endPoint]
.map((point: ElkPoint, index) => `${index ? 'L' : 'M'} ${point.x} ${point.y}`).join(' ')).join(' ')
}
function fromElkGraph(graph: ElkNode): GraphLayout {
const children = graph.children ?? []
// ELK reports no layer index; number the distinct x positions of the left-to-right layers instead.
const layers = [...new Set(children.map(child => child.x ?? 0))].sort((a, b) => a - b)
const boxes = new Map<string, GraphBox>(children.map(child => [child.id, {
x: child.x ?? 0, y: child.y ?? 0, width: child.width ?? nodeWidth, height: child.height ?? nodeHeight,
rank: layers.indexOf(child.x ?? 0),
}]))
const paths = new Map<string, string>()
const edgeLabels = new Map<string, { x: number; y: number }>()
for (const edge of graph.edges ?? []) {
paths.set(edge.id, sectionPath(edge))
const label = edge.labels?.[0]
if (label?.x !== undefined && label.y !== undefined) {
edgeLabels.set(edge.id, { x: label.x + (label.width ?? 0) / 2, y: label.y + (label.height ?? 0) / 2 })
}
}
return { boxes, paths, edgeLabels, width: Math.max(1, graph.width ?? 1), height: Math.max(1, graph.height ?? 1) }
}
/** Nodes, edges and a synchronous layout that always belong together; undefined until the first layout finishes. */
export function useElkLayout(nodes: Ref<readonly NetworkNode[]>, edges: Ref<readonly GraphEdge[]>) {
const view = shallowRef<{ nodes: readonly NetworkNode[]; edges: readonly GraphEdge[]; layout: GraphLayoutFunction }>()
watch([nodes, edges], async ([currentNodes, currentEdges], _previous, onCleanup) => {
let stale = false
onCleanup(() => { stale = true })
const result = fromElkGraph(await elk.layout(toElkGraph(currentNodes, currentEdges)))
// A newer change may have started another layout while this one ran.
if (!stale) view.value = { nodes: currentNodes, edges: currentEdges, layout: () => result }
}, { immediate: true })
return view
}vue
<NetworkGraph v-if="view" :nodes="view.nodes" :edges="view.edges" :layout="view.layout" />Notes:
- The edge coordinates above are those of the root graph, which holds every node and edge of a flat graph. For compound graphs (
childreninside children), ELK reports positions relative to each parent; add the parent offsets, or setorg.eclipse.elk.json.edgeCoordstoROOTandorg.eclipse.elk.json.shapeCoordstoROOT. - NetworkGraph checks the result: every node needs a box with a positive size and every edge a path, and
widthandheightmust be positive. Give ELK the sizes you render, for example from thesizesprop. - With the default
routingPolicy('builtin'), keep the defaultedgeStyle(curve) to draw ELK's routes:orthogonalandstraightreroute every edge with the built-in router, and edges with afromPortortoPortare redrawn from their port anchors (routeGraphPorts), so ELK's sections are used for edges without named ports, while the ports still shape where ELK places the nodes. Setrouting-policy="preserve"to keep ELK's sections for every edge, port edges and the orthogonal and straight styles included, while they still end at their ports and boxes; returnroutesmetadata to have the ends checked against the ports and sides (see Preserving external routes). With either policy, savedpositionsandsizesmove or resize nodes after the layout and reroute only the edges of those nodes. - With
collapsedGroupIds, NetworkGraph callslayoutwith the collapsed view (proxy nodes and merged edges) and with the expanded graph; a cached result covers only the graph it was computed for. Lay out both, or use the built-in layouts for collapsible groups. org.eclipse.elk.directionDOWN,LEFTorUPcorrespond toTB,RLandBT; number the layers byyfor vertical directions.
Incremental layouts with an external engine
When the graph grows (a new node, a page of a graph expansion), an engine that supports incremental layout can keep the nodes the user was looking at. Pass the information through useAsyncGraphLayout: positions (the boxes on display), fixedIds (nodes that must not move) and addedIds (nodes new since the last layout) are optional fields of the input, copied to every request, and part of the input key. Requests without them carry none of these fields, so adapters that ignore them work unchanged.
ts
import { computed, shallowRef } from 'vue'
import { useAsyncGraphLayout, type GraphLayoutRequest } from '@eightkk/vue-weave'
const shownBoxes = shallowRef(new Map()) // the boxes on display, updated when a frame is shown
const input = computed(() => {
const addedIds = new Set(nodes.value.filter(node => !shownBoxes.value.has(node.id)).map(node => node.id))
return { nodes: nodes.value, edges: edges.value, positions: shownBoxes.value, fixedIds: pinned.value, addedIds }
})
const graph = useAsyncGraphLayout({ input, adapter: request => layoutWithElk(request) })
// Forward the incremental fields to ELK. The layered algorithm's interactive strategies read the input coordinates of
// the nodes to keep their layers and order; check the option names against the ELK reference of the version you use.
async function layoutWithElk(request: GraphLayoutRequest) {
const graphInput = toElkGraph(request.nodes, request.edges)
if (request.positions?.size) {
graphInput.layoutOptions = {
...graphInput.layoutOptions,
'org.eclipse.elk.layered.layering.strategy': 'INTERACTIVE',
'org.eclipse.elk.layered.cycleBreaking.strategy': 'INTERACTIVE',
'org.eclipse.elk.layered.crossingMinimization.semiInteractive': 'true',
}
for (const child of graphInput.children ?? []) {
const position = request.positions.get(child.id)
if (position) Object.assign(child, { x: position.x, y: position.y })
}
}
const layout = fromElkGraph(await elk.layout(graphInput))
// ELK treats these coordinates as hints and does not pin nodes; put the fixed ones back, or fail the request.
for (const id of request.fixedIds ?? []) {
const box = layout.boxes.get(id), position = request.positions?.get(id)
if (box && position && (box.x !== position.x || box.y !== position.y)) throw new Error('The engine moved a pinned node: ' + id)
}
return layout
}- Which options an engine offers differs: yFiles and similar engines take incremental hints for the added nodes and exact fixed positions, ELK layered uses the coordinates as ordering hints. An engine that cannot honour
fixedIdsshould fail the request (as above) rather than silently move pinned nodes. - In the
shownrequest of a collapsed view,fixedIdsandaddedIdsare passed as given; IDs of members hidden in a collapsed group are not nodes of that request and are ignored. - Without an engine,
layoutGraphIncrementallyfrom@eightkk/vue-weave/coredoes the same synchronously: it keeps every positioned node exactly and places only the new ones (see Incremental placement). Use it as the adapter, or as a fallback when the engine fails.
Diagram files: Mermaid, GraphML and draw.io
To open a diagram drawn elsewhere, read the file as text and pass it to fromMermaid, fromGraphMl or fromDrawioAsync (which also reads the compressed pages draw.io saves by default). The result holds the NetworkGraph props, so commit nodes, edges, groups, positions and sizes as one history entry and show warnings to the user: they say what the file contained that NetworkGraph cannot draw (styling, other shapes, ports) and what was left out.
ts
import { fromDrawioAsync, fromGraphMl, fromMermaid, toDrawio } from '@eightkk/vue-weave/core'
async function openDiagram(file: File) {
const text = await file.text()
const diagram = file.name.endsWith('.graphml') ? fromGraphMl(text)
: file.name.endsWith('.drawio') ? await fromDrawioAsync(text)
: fromMermaid(text)
history.commit({ nodes: diagram.nodes, edges: diagram.edges, groups: diagram.groups, positions: diagram.positions, sizes: diagram.sizes })
return diagram.warnings
}
// Save the current state for draw.io; nodes the user never moved are placed with the layered layout.
const xml = toDrawio({ nodes, edges, groups, positions, sizes }, { pageName: 'Process', direction: 'LR' })A Mermaid file has no coordinates, so NetworkGraph lays it out; use the returned direction in options. GraphML and draw.io keep the positions and sizes of every node. Keep accepted node-move, nodes-move and node-resize proposals in positions and sizes so the next export carries them. The readers walk groups and chains with loops, bound their work with maxItems, and never expand XML entities; bound the size of uploaded files yourself as well. See Graph interchange for the mapping of shapes, markers and IDs.
Asynchronous layouts and preserved routes
NetworkGraph's layout prop stays synchronous. To compute layouts in a Worker or another asynchronous engine, use useAsyncGraphLayout and bind the frame it displays. The composable keeps the desired frame (the latest input, being computed) apart from the display frame (the last input whose layouts are all ready). Bind every field of display together, so new nodes are never drawn with old geometry, and pass the returned layout function, whose identity never changes, so a new result does not re-fit the camera:
vue
<script setup lang="ts">
import { computed, onBeforeUnmount } from 'vue'
import { NetworkGraph, graphLayoutWorkerAdapter, layoutLayeredGraph, useAsyncGraphLayout } from '@eightkk/vue-weave'
const worker = typeof Worker === 'undefined' ? undefined : new Worker(new URL('./graphLayout.worker.ts', import.meta.url), { type: 'module' })
const graph = useAsyncGraphLayout({
input: () => ({ nodes: nodes.value, edges: edges.value, groups, collapsedGroupIds: collapsed.value }),
adapter: worker ? graphLayoutWorkerAdapter(worker) : () => Promise.reject(new Error('Workers are not available')),
initialLayout: (shownNodes, shownEdges) => layoutLayeredGraph(shownNodes, shownEdges),
})
onBeforeUnmount(() => worker?.terminate())
// `initialLayout` makes the first frame synchronous, so `display` is always set here.
const frame = computed(() => graph.display.value!)
</script>
<template>
<NetworkGraph :nodes="frame.nodes" :edges="frame.edges" :groups="frame.groups"
:collapsed-group-ids="frame.collapsedGroupIds" :layout="graph.layout" v-bind="graph.gestureListeners" />
</template>- Requests start when the component mounts, so nothing runs during server rendering. With
initialLayoutthe server and the first client render show the same synchronous layout; without itdisplayis undefined until the first result, so render a loading state in both. - Use the controlled
collapsedGroupIdsprop with the frame's value. With collapsed groups NetworkGraph lays out two inputs (the full graph, to place proxies, and the collapsed view); a frame is shown only when both layouts are ready. UncontrolledcollapsibleGroupswould ask for a layout that has not been computed. - Every request carries a
requestIdand aninputKey. Only results for the current input are shown, whatever order they arrive in; results of cancelled or disposed requests are discarded.cacheSize(default 32) only sets how many computed layouts are kept for reuse by later inputs, such as expanding a group again; the current input's own results are held until it is shown, so any size, 0 included, completes a frame. The key covers edges, ports, sizes and labels, not just node IDs; bumprevisionwhen nodedataor engine settings outsidesettingschange the layout. - A finished frame waits while a gesture is in flight, so an ongoing drag is not cancelled; it is shown when the gesture ends. NetworkGraph reports every gesture a new layout would cancel through
gesture-startandgesture-end(node drags, resize and waypoint drags, connections from arming to completion, box selection, pan and pinch), one end for every start and after the proposal, so the graph has emitted itsnode-movebefore the waiting frame is shown.v-bind="graph.gestureListeners"connects those events to the composable;graph.gesturingtells whether frames are being held. Your own@gesture-startand@gesture-endlisteners can sit next to it. For gestures the application tracks itself (a drag in another component that edits the same data, for example), pass a boolean ref or getter as thegestureoption; frames wait while either is active. - A failure keeps the last display and sets
errorwith the revision and input key that failed. The failed request is not repeated, and the frame is not shown even if its other scope succeeds, until the input changes (assign a new input object to retry). With the defaultprovisional: truethat display can be the provisional frame of the failed input (display.source === 'provisional'): consistent, with the previous boxes and temporary routes for the new edges. Show that the routes are temporary, or setprovisional: falseto keep the last frame the engine produced. - When only edges change (for example after a
connectis accepted), the frame is shown at once with the previous boxes and temporary routes fromcompleteGraphLayout(source: 'provisional',temporaryEdgeIds) until the engine answers.
A Worker receives { type: 'request', request } and answers { type: 'success', requestId, inputKey, scope, layout } or { type: 'failure', requestId, inputKey, scope, message }; { type: 'cancel', requestId, inputKey } asks it to stop. graphLayoutWorkerAdapter rejects a response whose scope differs from the request's, and removes its listeners however the request ends, also when posting to the Worker throws. Check incoming messages with parseGraphLayoutMessage (structured clone keeps the Maps), or, when messages travel as JSON text, convert with graphLayoutMessageToJson and read with graphLayoutMessageFromJson, which turn each Map into an array of entries and back. Pass positions and sizes (and the incremental fixedIds and addedIds, see Incremental layouts with an external engine) in the input only when the engine honours them; they are then part of the input key. An engine that cannot place fixed nodes should fail the request with a message saying so rather than ignore them.
Preserving external routes
routeGraphPorts and routeGraphEdges take policy: 'preserve'. With it, a path the layout drew is kept, in every edge style and also for edges with named ports, while both ends still fit: at the port anchor for a named port, otherwise on the box border. A layout can return route metadata in layout.routes (start and end points, ports, the sides a route leaves and enters, bend points); it is then checked as well, and it is carried through applyGraphPositions, applyGraphSizes, routeGraphPorts and routeGraphEdges. Only these edges fall back to built-in routing: edges with points (explicit waypoints win), edges of a node that positions or sizes moved or resized, edges whose port or metadata no longer fits, and temporary routes. Note that with preserve, edges with named ports are not always rerouted; the default 'builtin' policy always reroutes them.
NetworkGraph applies the policy with its routingPolicy prop:
vue
<NetworkGraph :nodes="frame.nodes" :edges="frame.edges" :layout="graph.layout" routing-policy="preserve" edge-style="orthogonal" />A node drag keeps updating only the dragged nodes' edges and draws the same routes the committed move produces. A connection accepted before the engine answers is drawn with a temporary route (completeGraphLayout) instead of failing with Missing layout path, and is routed again when the new layout arrives. A new layout object with the same geometry for the same inputs does not cancel a drag in flight; a layout whose geometry changed still does, so bind gestureListeners from useAsyncGraphLayout to hold results until the gesture ends.
Direct core users get the routed layout that NetworkGraph draws, and that renderGraphSvg should receive, by running the same steps:
ts
import { applyGraphPositions, applyGraphSizes, renderGraphSvg, routeGraphEdges, routeGraphPorts } from '@eightkk/vue-weave/core'
const nodesById = new Map(nodes.map(node => [node.id, node]))
const placed = applyGraphSizes(applyGraphPositions(layout, edges, positions, direction), edges, sizes, direction)
const ported = routeGraphPorts(placed, nodesById, edges, direction, { policy: 'preserve' })
const routed = routeGraphEdges(ported, edges, nodesById, { style: 'orthogonal', direction, policy: 'preserve' })
const svg = renderGraphSvg(routed, nodes, edges, { theme })renderGraphSvg draws the paths it is given, so the export matches the screen without any routing option of its own.
Running core calculations in a Worker
useAsyncGraphLayout with graphLayoutWorkerAdapter is the way to lay out NetworkGraph's graphs in a Worker: it keys, cancels and orders the requests and holds results during gestures. Its Worker only has to answer the messages described above, for example with the built-in layered layout:
ts
// graphLayout.worker.ts: answers graphLayoutWorkerAdapter with the built-in layered layout.
import { layoutLayeredGraph, parseGraphLayoutMessage } from '@eightkk/vue-weave/core'
self.onmessage = (event: MessageEvent) => {
const message = parseGraphLayoutMessage(event.data)
// A synchronous engine cannot stop a layout it is computing; the adapter discards the result of a cancelled request.
if (message.type !== 'request') return
const { requestId, inputKey, scope, nodes, edges, direction } = message.request
try {
self.postMessage({ type: 'success', requestId, inputKey, scope, layout: layoutLayeredGraph(nodes, edges, { direction }) })
} catch (error) {
self.postMessage({ type: 'failure', requestId, inputKey, scope, message: error instanceof Error ? error.message : String(error) })
}
}Other heavy core calculations, such as routing a large graph for a custom renderer or an export, scheduleTasks and levelResources, run in a plain module Worker the same way. Everything they take and return is structured-cloneable: plain objects and arrays, and the Maps of a GraphLayout. Three things are not. Functions (a NetworkGraph layout callback, formatTime, or a function in node data) cannot be posted; leave them out of the message. Vue's reactive proxies cannot be cloned either; post toRaw(nodes.value) or a plain copy. A GraphRouteCache stays in the Worker that created it. Results lose no data in the clone, but a layout routed on one side and routed again on the other with policy: 'preserve' no longer knows which of its paths the built-in router drew, so run that whole chain (applyGraphPositions, routeGraphPorts, routeGraphEdges) in one place.
ts
// heavy.worker.ts: a module Worker for the core's heavy calculations.
import {
createGraphRouteCache, layoutLayeredGraph, levelResources, routeGraphEdges, routeGraphPorts, scheduleTasks,
type GraphEdge, type GraphEdgeRouteOptions, type GraphLayoutDirection, type LevelResourcesInput, type NetworkNode,
type ScheduleInput,
} from '@eightkk/vue-weave/core'
export type Job =
| { kind: 'graph'; input: { nodes: NetworkNode[]; edges: GraphEdge[]; direction?: GraphLayoutDirection; routing?: GraphEdgeRouteOptions } }
| { kind: 'schedule'; input: ScheduleInput }
| { kind: 'level'; input: LevelResourcesInput }
// Route caches cannot be cloned, so the worker keeps its own: each graph job reuses the routes the previous one drew
// where nothing that affects them changed.
const routes = createGraphRouteCache()
function compute(job: Job) {
switch (job.kind) {
case 'graph': {
const { nodes, edges, direction = 'LR', routing } = job.input
const nodesById = new Map(nodes.map(node => [node.id, node]))
const layout = layoutLayeredGraph(nodes, edges, { direction })
const ported = routeGraphPorts(layout, nodesById, edges, direction)
return routeGraphEdges(ported, edges, nodesById, { ...routing, direction, cache: routes })
}
case 'schedule': return scheduleTasks(job.input)
case 'level': return levelResources(job.input)
}
}
// The newest job of each kind. Jobs run after the messages already queued have arrived, so a burst of edits computes
// only its last input; the jobs it replaced are answered as stale.
const waiting = new Map<Job['kind'], { id: number; job: Job }>()
self.onmessage = (event: MessageEvent<{ id: number; job: Job }>) => {
const { id, job } = event.data
const replaced = waiting.get(job.kind)
if (replaced) self.postMessage({ id: replaced.id, stale: true })
waiting.set(job.kind, { id, job })
setTimeout(runWaiting)
}
function runWaiting() {
for (const [kind, { id, job }] of waiting) {
waiting.delete(kind)
try {
self.postMessage({ id, result: compute(job) })
} catch (error) {
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) })
}
}
}A Worker answers one message at a time and cannot stop a calculation once it has started. The Worker above therefore keeps only the newest job of each kind while messages are still queued, and the main thread ignores any answer that a newer job of the same kind has replaced, so a slow result never overwrites a newer one:
ts
// heavyWork.ts: the main-thread side. `run` resolves to the result, or to undefined when a newer job of the same kind
// was sent before the result arrived, so a late answer never overwrites a newer one.
import type { Job } from './heavy.worker'
type Reply = { id: number; result?: unknown; stale?: true; error?: string }
export function heavyWork(worker: Pick<Worker, 'postMessage' | 'addEventListener'>) {
let lastId = 0
const newest = new Map<Job['kind'], number>()
const pending = new Map<number, { kind: Job['kind']; resolve: (value: unknown) => void; reject: (error: Error) => void }>()
worker.addEventListener('message', (event: MessageEvent<Reply>) => {
const reply = event.data, request = pending.get(reply.id)
if (!request) return
pending.delete(reply.id)
if (reply.error !== undefined) request.reject(new Error(reply.error))
else request.resolve(reply.stale || newest.get(request.kind) !== reply.id ? undefined : reply.result)
})
return function run(job: Job): Promise<unknown> {
const id = ++lastId
newest.set(job.kind, id)
const answer = new Promise<unknown>((resolve, reject) => pending.set(id, { kind: job.kind, resolve, reject }))
worker.postMessage({ id, job })
return answer
}
}ts
const worker = new Worker(new URL('./heavy.worker.ts', import.meta.url), { type: 'module' })
const run = heavyWork(worker)
const result = await run({ kind: 'schedule', input: toRaw(plan.value) })
if (result) schedule.value = result as ScheduleResultTo abandon a long job, terminate the Worker and start a new one (its route cache starts empty again). A routed layout from the Worker is ready for renderGraphSvg or a custom renderer; for NetworkGraph, pass node boxes through useAsyncGraphLayout instead, since the component routes edges itself.
Diagram editor parts
GraphPalette and PropertyInspector (see Diagram editor parts) turn a droppable NetworkGraph into a small diagram editor. Both are controlled: the palette reports a drop or an insert, and the inspector a change (or a list-change for its assignments and dependencies tables, see Inspector list fields), and the application commits each as one history entry. The "Diagram editor" example of the documentation site puts them together.
vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
GraphPalette, NetworkGraph, PropertyInspector, readPaletteDrop, useEditHistory,
type GraphDrop, type GraphPaletteItem, type GraphPoint, type InspectorChange, type InspectorField, type NetworkNode,
} from '@eightkk/vue-weave'
const templates: GraphPaletteItem[] = [
{ id: 'step', label: 'Step', shape: 'box', section: 'Flow' },
{ id: 'decision', label: 'Decision', shape: 'diamond', tone: 'violet', section: 'Flow' },
]
const history = useEditHistory({ nodes: [] as NetworkNode[], positions: new Map<string, GraphPoint>() })
const graph = ref<InstanceType<typeof NetworkGraph>>()
const selectedId = ref<string>()
const selected = computed(() => history.state.value.nodes.find(node => node.id === selectedId.value) ?? null)
function add(template: GraphPaletteItem, center: GraphPoint) {
const { nodes, positions } = history.state.value
const id = template.id + '-' + (nodes.length + 1)
history.commit({
nodes: [...nodes, { id, label: template.label, shape: template.shape, tone: template.tone }],
positions: new Map(positions).set(id, { x: Math.max(0, center.x - 72), y: Math.max(0, center.y - 29) }),
})
selectedId.value = id
}
function drop(event: GraphDrop) {
const template = templates.find(item => item.id === readPaletteDrop(event)?.id)
if (template) add(template, graph.value!.toGraphPoint(event.clientX, event.clientY))
}
const fields: InspectorField<NetworkNode>[] = [
{ id: 'label', kind: 'text', label: 'Label', get: node => node.label, required: true },
]
function apply(change: InspectorChange) {
const state = history.state.value
history.commit({ ...state, nodes: state.nodes.map(node => node.id === change.id ? { ...node, label: String(change.after) } : node) })
}
</script>
<template>
<GraphPalette :items="templates" searchable @insert="item => add(item, graph!.getViewportCenter())" />
<NetworkGraph ref="graph" v-model:selected-id="selectedId" :nodes="history.state.value.nodes" :edges="[]"
:positions="history.state.value.positions" droppable @node-drop="drop" />
<PropertyInspector :item="selected" :fields="fields" @change="apply" />
</template>Inspector fields are typed fields, so a field definition written for a GanttChart column (TimelineColumn.field) needs only a label and a getter for the inspected item. Put validation that depends on other items, such as unique labels, in validateChange; its reason is shown under the field. When the selection changes, or an undo changes a value that is being edited, the inspector drops the draft instead of proposing a stale change.
Both components use the shared variables (--vw-surface, --vw-surface-muted, --vw-surface-hover, --vw-text, --vw-muted, --vw-border and --vw-accent, and the tone families for the palette previews), so vw-theme-dark and vw-theme-auto apply to them. They add two variables:
| Variable | Default | Used for |
|---|---|---|
--vw-palette-preview-width | 48px | Width of the shape preview of a palette item (vw-palette-preview); the height follows the 48 by 30 aspect ratio |
--vw-inspector-error | #b3261e (#ff8a80 in the dark themes) | Messages under inspector fields (vw-inspector-error) and the border of an invalid control |
Classes: vw-palette, vw-palette-search, vw-palette-list, vw-palette-section, vw-palette-heading, vw-palette-item (with vw-is-active and vw-is-disabled), vw-palette-preview, vw-palette-label, vw-palette-detail, vw-palette-empty; vw-inspector, vw-inspector-field (with vw-is-<kind>, vw-is-readonly and vw-is-invalid), vw-inspector-label, vw-inspector-input, vw-inspector-check, vw-inspector-color, vw-inspector-swatch, vw-inspector-description, vw-inspector-error and vw-inspector-empty. Layout uses logical properties, so dir="rtl" (or an inherited right-to-left direction with dir="auto") mirrors both. In forced-colors mode palette previews are drawn in CanvasText on Canvas and messages are underlined; the filter box is not printed.