Back

VibeFox JS Diagram — Help

Overview

VibeFox JS Diagram is a library for interactive diagrams: flowcharts, BPMN processes, UML and ER diagrams, org charts, mind maps and network diagrams. Users draw nodes and connections, edit labels, resize and rotate shapes, and the library routes the edges around the nodes, lays the graph out automatically, and exports SVG, PNG, PDF and the common diagram file formats. It is plain JavaScript with no dependencies and works with or without a framework.

You create a diagram with one call, createDiagram(target, options), and control it through the same methods as every VibeFox JS library: setData, setOptions, on, getState, setState, setTheme, destroy.

Key features

  • SVG drawing with zoom and pan, a minimap, a background grid with snapping, smart alignment guides, selection, marquee, copy / paste, undo / redo.
  • Shapes: rectangles, rounded boxes, ellipses, diamonds, hexagons, cylinders, images, groups and swimlanes; shape sets for BPMN 2.0, UML, ER, org charts, mind maps and networks; your own shapes and HTML / SVG node templates with data binding.
  • Edges: straight, curved and orthogonal routing around the nodes, ports, many arrow heads (including ER crow's feet), labels, bend points, reconnecting by dragging.
  • Automatic layouts: layered (Sugiyama), tree, force, grid, circular, orthogonal, radial, mind map and incremental.
  • Editing tools: a shape palette, a property inspector, a node toolbar, context menus, tooltips, align / distribute / z-order, containers that grow around their children.
  • Import and export of Mermaid, BPMN 2.0 XML, GraphML and draw.io files; SVG, PNG, vector PDF on several pages and printing.
  • Large graphs of tens of thousands of nodes (virtual drawing and a canvas level of detail).
  • Real-time collaboration through your own transport, with cursors of the other participants.
  • Text to diagram ("Start -> Review -> Approve"), "explain this diagram", a linter, a visual diff of two versions, flow tracing and a process simulation with bottlenecks; an optional adapter for your own language model.
  • Five ready-made styles, every color and size as a CSS variable, themes, keyboard navigation, screen reader support and touch gestures.

Requirements

  • A current web browser.
  • No runtime dependencies. Nothing is loaded from the network: the library makes no requests of its own (images of image nodes are loaded from the URLs you give).
  • Node.js is not needed in the browser. The ES module can be imported in Node (no DOM is touched at import), so the model and file functions run on a server: GraphModel, layouts, routeOrthogonal, importDiagram, exportDiagram, textToDiagram, explainDiagram, FlowSimulation, CollabDoc.

Installation

Files of the library

VibeFox JS Diagram is a separate product with its own files. The whole JavaScript of the library is one file and the styles are one CSS file: a page needs exactly these two. The other files are optional.

FileWhat it is
vibefox-js-diagram.global.jsThe library for a classic <script> tag; defines one global variable, VibeFoxJSDiagram. Minified: vibefox-js-diagram.global.min.js.
vibefox-js-diagram.esm.jsThe same code as an ES module. Minified: vibefox-js-diagram.esm.min.js.
vibefox-js-diagram.cssAll styles of the library, inside @layer vfjs; includes the themes light, dark and high-contrast. Minified: vibefox-js-diagram.min.css.
vibefox-js-themes.cssOptional theme pack: 18 ready-made themes (see Theming and styling). Minified: vibefox-js-themes.min.css.
locales/vibefox-js-diagram.<lang>.jsOptional language files, one for each language except English (see Localization and RTL). The same language as an ES module: .esm.js; as plain strings: .json.
vibefox-js-diagram.d.tsTypeScript declarations (also vibefox-js-diagram.esm.d.ts).
*.js.mapSource maps.
vibefox-js-diagram-react.js, vibefox-js-diagram-vue.js, vibefox-js-diagram-svelte.js, vibefox-js-diagram-jquery.jsOptional framework wrappers (each with its .d.ts).
vibefox-js-diagram-angularOptional Angular package (Angular Package Format).
vibefox-js-diagram-wc.jsOptional Web Components wrapper (custom elements).

Script tag

Link the CSS file and the script. The global variable VibeFoxJSDiagram holds every export of the library. This also works from a file opened from disk (file://).

<link rel="stylesheet" href="vibefox-js-diagram.css">
<script src="vibefox-js-diagram.global.js"></script>
<script>
  const diagram = VibeFoxJSDiagram.createDiagram('#app', { data });
</script>

ES module

Import the ES module file and link the CSS file. Browsers load modules only over http(s), not from file://.

<link rel="stylesheet" href="vibefox-js-diagram.css">
<script type="module">
  import { createDiagram } from './vibefox-js-diagram.esm.js';
  const diagram = createDiagram('#app', { data });
</script>

npm

The library is also prepared as an npm package named @vibefox/js-diagram. Install it from the package folder (or its packed .tgz file) that you received, then import it by name. Bundlers take the CSS through the @vibefox/js-diagram/css export.

npm install ./vibefox-js-diagram
import { createDiagram } from '@vibefox/js-diagram';
import '@vibefox/js-diagram/css';

Exports of the package: @vibefox/js-diagram (ES module), @vibefox/js-diagram/min, @vibefox/js-diagram/global, @vibefox/js-diagram/global.min, @vibefox/js-diagram/css, @vibefox/js-diagram/min.css, @vibefox/js-diagram/themes, @vibefox/js-diagram/themes.min.css, @vibefox/js-diagram/locales/<lang>, @vibefox/js-diagram/locales/<lang>.json. TypeScript finds the declarations by itself.

Framework wrappers

The wrappers are small separate files; the library works without them. Each wrapper needs only VibeFox JS Diagram and its framework (a peer dependency). The wrappers do not load CSS: link vibefox-js-diagram.css yourself.

FrameworkFilenpm packageSupported versions
Reactvibefox-js-diagram-react.js@vibefox/js-diagram-reactReact 16.8 and newer
Vue 3vibefox-js-diagram-vue.js@vibefox/js-diagram-vueVue 3.3 and newer
Angularvibefox-js-diagram-angular@vibefox/js-diagram-angularAngular 17 and newer
Sveltevibefox-js-diagram-svelte.js@vibefox/js-diagram-svelteSvelte 3, 4 and 5
jQueryvibefox-js-diagram-jquery.js@vibefox/js-diagram-jqueryjQuery 1.12 to 4.x
Web Componentsvibefox-js-diagram-wc.js@vibefox/js-diagram-wcno framework

The ES module wrappers import the library as @vibefox/js-diagram. Without npm, map that name to vibefox-js-diagram.esm.js in your bundler settings or in an import map. The jQuery wrapper takes the library from the global VibeFoxJSDiagram.

Common rules of all wrappers: props / inputs are the options of the library (changed ones go to setData or one setOptions call); events are framework events with the same payload object as on(); the instance is available for every method; on the server (SSR) an empty container is rendered and the instance is created in the browser only. The option style (ready-made look) is the prop variant in React, Vue, Svelte and Angular, because style and className / class belong to the host element.

Web Components

Load vibefox-js-diagram-wc.js after the library file. It defines the element <vfjs-diagram> from the global VibeFoxJSDiagram. Attributes are options in kebab-case (JSON for objects and arrays), properties are options, the methods of the component are methods of the element, events are CustomEvents named vfjsdiagram:<event> with the payload in detail. The element uses the light DOM, so the CSS of the library and your page CSS apply as usual.

<link rel="stylesheet" href="vibefox-js-diagram.css">
<script src="vibefox-js-diagram.global.js"></script>
<script type="module" src="vibefox-js-diagram-wc.js"></script>
<vfjs-diagram id="g" style="height: 400px" variant="flowchart"></vfjs-diagram>
<script>
  const el = document.getElementById('g');
  el.data = { nodes: [{ id: 'a', label: 'Start', x: 40, y: 40 }, { id: 'b', label: 'End', x: 240, y: 40 }], edges: [{ source: 'a', target: 'b' }] };
  el.addEventListener('vfjsdiagram:nodeClick', (e) => console.log(e.detail.node));
</script>

With a bundler: import * as lib from '@vibefox/js-diagram'; import { define } from '@vibefox/js-diagram-wc'; define(lib);

Quick start

Plain HTML

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="vibefox-js-diagram.css">
  <script src="vibefox-js-diagram.global.js"></script>
</head>
<body>
  <div id="palette" style="width: 200px; float: left"></div>
  <div id="app" style="height: 480px; margin-left: 210px"></div>
  <script>
    const diagram = VibeFoxJSDiagram.createDiagram('#app', {
      style: 'flowchart',
      data: {
        nodes: [
          { id: 'start', label: 'Start', shape: 'ellipse', kind: 'start', x: 40, y: 140 },
          { id: 'check', label: 'Order valid?', shape: 'diamond', kind: 'decision', x: 220, y: 120 },
          { id: 'ship', label: 'Ship', kind: 'process', x: 440, y: 60 },
          { id: 'reject', label: 'Reject', kind: 'process', x: 440, y: 220 },
        ],
        edges: [
          { source: 'start', target: 'check' },
          { source: 'check', target: 'ship', label: 'yes', kind: 'yes' },
          { source: 'check', target: 'reject', label: 'no', kind: 'no' },
        ],
      },
      on: { nodeClick: (e) => console.log('clicked', e.node.label) },
    });
    diagram.mountPalette('#palette');
  </script>
</body>
</html>

The diagram fills its element: give the element a height (without one, the diagram is 400 px high: the variable --vfjs-diagram-min-height).

React

import { useRef } from 'react';
import { VibeFoxJSDiagramReact } from '@vibefox/js-diagram-react';
import '@vibefox/js-diagram/css';

const data = { nodes: [{ id: 'a', label: 'Start', x: 40, y: 40 }, { id: 'b', label: 'End', x: 240, y: 40 }], edges: [{ source: 'a', target: 'b' }] };

export function Flow() {
  const diagram = useRef(null); // the VibeFoxJSDiagram instance
  return (
    <div style={{ height: 400 }}>
      <button onClick={() => diagram.current.applyLayout('layered')}>Layout</button>
      <VibeFoxJSDiagramReact ref={diagram} data={data} variant="flowchart" onNodeClick={(e) => console.log(e.node)} />
    </div>
  );
}

Vue 3

<script setup>
import { ref } from 'vue';
import { VibeFoxJSDiagramVue } from '@vibefox/js-diagram-vue';
import '@vibefox/js-diagram/css';
const data = ref({ nodes: [{ id: 'a', label: 'Start', x: 40, y: 40 }], edges: [] });
</script>
<template>
  <VibeFoxJSDiagramVue :data="data" style="height: 400px" @node-click="(e) => console.log(e.node)" />
</template>

Angular

import { Component } from '@angular/core';
import { VibeFoxJSDiagramComponent } from '@vibefox/js-diagram-angular';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [VibeFoxJSDiagramComponent],
  template: `
    <vfjs-diagram-ng #diagram [data]="data" style="display: block; height: 400px"
      (nodeClick)="clicked($event)"></vfjs-diagram-ng>
    <button (click)="diagram.instance?.fitToContent()">Fit</button>`,
})
export class AppComponent {
  data = { nodes: [{ id: 'a', label: 'Start', x: 40, y: 40 }], edges: [] };
  clicked(e: unknown) { console.log(e); }
}

Link vibefox-js-diagram.css in angular.json (styles) or in index.html. For NgModule applications import VibeFoxJSDiagramModule.

Svelte

<script>
  import { vfjsDiagram } from '@vibefox/js-diagram-svelte';
  let data = { nodes: [{ id: 'a', label: 'Start', x: 40, y: 40 }], edges: [] };
</script>
<div style="height: 400px" use:vfjsDiagram={{ data }}
     on:vfjsdiagram:nodeClick={(e) => console.log(e.detail.node)}></div>

jQuery

<script src="jquery.min.js"></script>
<link rel="stylesheet" href="vibefox-js-diagram.css">
<script src="vibefox-js-diagram.global.js"></script>
<script src="vibefox-js-diagram-jquery.js"></script>
<script>
  $('#diagram').vfjsDiagram({ data: { nodes: [{ id: 'a', label: 'Start' }], edges: [] } })
    .on('vfjsdiagram:nodeClick', (e, payload) => console.log(payload.node));
  $('#diagram').vfjsDiagram('applyLayout', 'tree');
</script>

Core concepts

Data model

The data is { nodes, edges }. A node has an id, a shape (default 'rect'), a position x, y and a size width, height (top left corner, world coordinates in px), a label, optional parent (container), style, ports, angle, template, kind (a role for the styles: start, decision, …), tooltip, locked, resizable, rotatable, collapsed and your own data. An edge has a source and a target (a node id or { node, port }), a label, a router, waypoints, arrowStart, arrowEnd, style, kind, tooltip and data. Missing ids, sizes and positions are filled in.

Creating and destroying

const diagram = VibeFoxJSDiagram.createDiagram('#app', { data: { nodes: [], edges: [] } });
diagram.setData({ nodes: [{ id: 'a', label: 'A' }], edges: [] }); // replace the graph (history is cleared)
diagram.setOptions({ grid: { show: false }, minimap: false });
diagram.getData();               // { nodes, edges } with the user's edits
diagram.destroy();

new VibeFoxJSDiagram(target, options) is the same as createDiagram. toJSON() / loadJSON(json) serialize the graph; diagram.model is the GraphModel for read access.

Events

Every event handler receives one payload object. Subscribe in the options (on: { nodeClick: fn }) or later with on, once and off; on('*', (event, payload) => …) receives every event.

diagram.on('edgeCreate', (e) => console.log('connected', e.edge.source.node, '→', e.edge.target.node));
diagram.on('nodeMove', (e) => console.log(e.nodes.length, e.dx, e.dy));
diagram.on('selectionChange', (e) => console.log(e.ids));

Every VibeFox JS component emits ready, dataChange, optionsChange, themeChange and destroy. contextMenu and nodeToolbarClick can be cancelled with preventDefault(). The full list is in API reference.

State snapshots

getState() returns a JSON-safe snapshot of the view and the user's arrangement: zoom, pan, selection, collapsed containers, the geometry of every node ([x, y, width, height, angle]), the drawing order and the style. setState(state) restores it.

localStorage.setItem('flow-view', JSON.stringify(diagram.getState()));
diagram.setState(JSON.parse(localStorage.getItem('flow-view')));

Undo and redo

Every edit is an undo step (history.limit, default 100): Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z, or undo(), redo(), canUndo(), canRedo(); event historyChange.

Nodes and edges

Editing from code

const n = diagram.addNode({ label: 'Review', shape: 'rounded', x: 300, y: 100 });
diagram.updateNode(n.id, { label: 'Code review', style: { fill: '#fef3c7' } });
diagram.updateNodeData(n.id, { owner: 'Ann' });
diagram.resizeNode(n.id, { width: 180 });
diagram.rotateNode(n.id, 15);
const e = diagram.addEdge({ source: 'start', target: n.id, label: 'next', arrowEnd: 'arrow' });
diagram.reconnectEdge(e.id, 'target', { node: 'ship', port: 'left' });
diagram.removeNode(n.id);         // with its children and edges
diagram.getNode('start'); diagram.getNodes(); diagram.getEdges();

User interaction

Users drag nodes (with grid snapping and smart guides), draw edges from the ports of a node, double-click to edit a label, resize and rotate the selected node with its handles (Shift snaps the angle by nodes.rotateStep), drag the end handles of a selected edge to reconnect it, and drag bend points. Options: nodes (editable, resizable, rotatable, minWidth, minHeight, rotateStep), edges (router, editable, reconnect, avoidObstacles, obstacleMargin, separation, bendPenalty, kind), grid (show, size, snap), guides, allowSelfLoops, canConnect(payload) (return false to refuse a connection), readOnly.

Selection: select(ids, { additive }), toggleSelect(), selectAll(), clearSelection(), getSelection(), isSelected(), selectionIds(), removeSelection(). Clipboard: copySelection(), cutSelection(), paste(at), duplicateSelection(). editLabel(id) opens the label editor.

Arranging

diagram.alignNodes('left');                       // the selected nodes; also 'center', 'right', 'top', 'middle', 'bottom'
diagram.distributeNodes('horizontal', null, { by: 'gap' });
diagram.bringToFront(); diagram.sendToBack(); diagram.bringForward(); diagram.sendBackward();

Event: nodeArrange.

Edges, routers and arrows

Routers: 'straight', 'bezier' and 'ortho' (default; goes around the nodes, keeps a gap between parallel segments). Arrow heads (arrowStart, arrowEnd): 'none', 'arrow', 'open', 'diamond', 'diamond-open', 'circle', 'circle-open', 'bar', 'triangle-open', 'slash', 'cross', and the ER ends 'one', 'only-one', 'zero-or-one', 'many', 'one-or-many', 'zero-or-many'. Ports: { id, side: 'left' | 'right' | 'top' | 'bottom', offset }. The orthogonal router is also available without a diagram: routeOrthogonal(data, options), OrthoRouter.

Nodes with the label under the shape (network devices, BPMN events, 'image'): an orthogonal edge that ends at the bottom side leaves under the label when there is room for it, otherwise it runs straight through its own label, which has a halo in the background color so that it stays readable. Labels of other nodes are still kept free of edges.

Shapes, templates and shape sets

Built-in shapes and templates

Built-in shapes: 'rect', 'rounded', 'ellipse', 'diamond', 'hexagon', 'cylinder', 'image' (with image: a URL), 'group', 'swimlane' and 'none' (drawn by its template only). SHAPE_DEFAULTS lists their default sizes.

A template (option templates, node template) draws a node from its data: html (HTML in the node box) or svg content with {{path}} placeholders (escaped; {{{path}}} raw), bind (data → label, image or a style key), shape, width, height, style, ports, tooltip, label, className, resizable, rotatable, keepRatio, minWidth, minHeight.

VibeFoxJSDiagram.createDiagram('#app', {
  templates: {
    person: {
      shape: 'rounded', width: 180, height: 56,
      html: '<b>{{data.name}}</b><br>{{data.role}}',
      bind: { fill: 'data.color' },
      tooltip: '{{data.email}}',
    },
  },
  data: { nodes: [{ id: 'p1', template: 'person', data: { name: 'Ann Lee', role: 'CEO', color: '#dbeafe', email: '[email protected]' } }], edges: [] },
});

Your own shapes

registerShape(name, def) (every diagram of the page) or the option shapes (this diagram) adds a shape: path(width, height, node) returns the outline as an SVG path, or render draws it; width, height, ports, boundary, label, size, labelWidth, resizable, rotatable, keepRatio, minWidth, minHeight, container, fields.

VibeFoxJSDiagram.registerShape('tag', {
  path: (w, h) => `M0 0 H${w - 16} L${w} ${h / 2} L${w - 16} ${h} H0 Z`,
  width: 120, height: 40,
});

getShape(name), getShapeNames() and fillTemplate(template, node) are helpers.

Shape sets

Built-in sets (getShapeSetNames()): bpmn, uml, er, org, mindmap, network. Their shapes are named <set>:<shape> with modifiers (for example 'bpmn:task.user'), their edge kinds <set>:<kind> (for example kind: 'uml:inheritance' sets the arrows and the line). mountPalette(target, ['bpmn', 'uml']) shows the items of the sets; registerShapeSet(set) adds your own set (name, shapes, edges, connect, items, locales); getShapeSet(name) describes one.

Rows of the table shapes come from the node data: an ER entity ('er:entity') shows data.attributes — strings or { name, type, key, nullable } with key 'pk', 'fk', 'pk,fk' or 'uk'; a UML class ('uml:class') shows data.stereotype, data.attributes and data.operations (or data.methods) — strings or { visibility, name, type, params }; a UML object ('uml:object') shows data.attributes as { name, value }. The property inspector edits these rows as lines of text; a new node gets the height of its rows.

data: { nodes: [
  { id: 'customer', shape: 'er:entity', label: 'Customer', data: { attributes: [
    { name: 'id', type: 'int', key: 'pk' }, { name: 'email', type: 'text' }, { name: 'org_id', type: 'int', key: 'fk', nullable: true },
  ] } },
  { id: 'order', shape: 'uml:class', label: 'Order', x: 300, data: {
    attributes: [{ visibility: '+', name: 'id', type: 'int' }],
    methods: [{ visibility: '+', name: 'total', params: [], type: 'number' }],
  } },
], edges: [] }

Containers

Nodes with a parent are inside a container ('group', 'swimlane', BPMN pools and lanes, or a shape with container): they move with it and the container grows around them (containers: { autoSize, padding }). groupSelection({ label, shape }), ungroup(id), toggleCollapse(id), fitContainer(id); event groupChange.

Layouts

applyLayout(name, options) arranges the graph (animated, one undo step; layout.animate ms; event layoutApply).

await diagram.applyLayout('layered', { dir: 'LR', layerGap: 80, nodeGap: 30 });
await diagram.applyLayout('incremental', { nodes: ['new1', 'new2'] }); // place only new nodes
diagram.fitToContent();

Layouts: 'layered' (= 'sugiyama'), 'tree', 'force', 'grid', 'circular', 'orthogonal', 'radial', 'mindmap', 'incremental'. Options: dir ('TB', 'BT', 'LR', 'RL'; mind map 'H' / 'V'), layerGap, nodeGap, edgeGap, ordering, sweeps, keepOrder, root, startAngle, nodes, base, containers, container, inner, keepWaypoints, waypoints, edgeRouter, slice, iterations, spacing, cols, gap, animate. The layouts are also pure functions in layouts (Node too).

Viewport

Users zoom with the mouse wheel (zoom: { min, max, wheel }) and pan by dragging the background; minimap: true (default) shows an overview. autoFit: true fits the content after the first render.

diagram.setZoom(1.5); diagram.zoomIn(); diagram.zoomOut();
diagram.fitToContent(40);
diagram.centerOn('check');
diagram.setPan({ x: 0, y: 0 });
diagram.clientToWorld(event.clientX, event.clientY);

Also getZoom(), getPan(), centerAt(x, y), svgRect(), viewportWorldRect(); event viewportChange.

Editing tools

Palette

mountPalette(target, items) shows a searchable list of shapes; users drag items onto the diagram (event paletteDrop). Items are node templates ({ shape, label, group, width, height, … }) or shape set names; defaultPaletteItems() returns the built-in items.

Property inspector and node toolbar

mountInspector(target, { fields, sections, title }) shows the properties of the selection (label, look, size, data; edges: router and arrows); every change is one undo step (event propertyChange). Own fields: { key: 'data.owner', type: 'text', label: 'Owner' } with the types text, textarea, number, color, select, checkbox, lines. The node toolbar (nodeToolbar) shows quick actions beside one selected node — connect (a connected copy, addConnectedNode()), duplicate, shape, delete — plus your own items; event nodeToolbarClick.

diagram.mountInspector('#inspector', { fields: { node: [{ key: 'data.owner', type: 'text', label: 'Owner', section: 'data' }] } });

Context menu and tooltips

contextMenu (enabled, defaults, items, node, edge, canvas) adds your items to the menus of nodes, edges and the background; an item has id, label, labelKey, icon, shortcut, disabled, hidden, checked, radio, danger, children, divider, action(ctx). tooltips (enabled, delay, hideDelay, nodes, edges, template) shows the tooltip of nodes and edges. Methods: showContextMenu(), hideContextMenu(), getContextMenu(), showTooltip(), hideTooltip(). Events: contextMenu, contextMenuClose, menuItemClick, tooltipShow, tooltipHide.

contextMenu: { node: [{ id: 'mail', label: 'Mail the owner', action: (ctx) => console.log(ctx.node.data) }] }

Analysis tools

diagram.traceFlow('start', 'down');               // highlight everything reachable
diagram.clearTrace();
const issues = diagram.lint({ highlight: true });  // [{ rule, severity, nodeId, edgeId, message }]
diagram.clearLint();
const diff = diagram.showDiff(previousVersion);    // added / changed highlighted, removed as ghosts (also raw data)
diagram.clearDiff();

Lint rules: danglingEdge, duplicateEdge, orphanNode, overlap, unlabeledNode, cycle. diff(other) returns the differences without drawing. The other version may be raw data like that of setData() (nodes without sizes, edge ends as strings): it is normalized the same way before the comparison, so missing defaults do not count as changes. Nodes and edges are matched by id, so give your edges ids when you compare versions. diagram.model.normalize(data) (a GraphModel method) returns such a normalized copy of any data without changing the model. Events: traceChange, lintComplete, diffChange. Without a diagram: lintModel, diffJSON, traceFrom.

Process simulation

simulate(options) sends tokens through the flow (tasks, gateways, queues) and shows where they wait; bottlenecks() lists the slowest steps. The simulation object has play(), pause(), step(), setSpeed(), reset(), getStats(), bottlenecks(), destroy(); events simulationStep, simulationState, simulationEnd. FlowSimulation runs the same engine without a view (Node too).

const sim = diagram.simulate({ tokens: 20, interval: 2, taskTime: 5, seed: 1 });
sim.play();
diagram.on('simulationEnd', (e) => console.log(e.bottlenecks));

Options: seed, tokens, interval, arrival, taskTime, edgeTime, jitter, capacity, until, maxEvents, durations, duration, conditions, decide; view: motion, speed, bottleneck, stepInterval, autoplay, announce.

Import and export

Diagram files

const info = await diagram.importDiagram(fileOrText, { mode: 'replace' }); // Mermaid, BPMN 2.0 XML, GraphML, draw.io, JSON
console.log(info.format, info.warnings);
const mermaid = await diagram.exportDiagram('mermaid');
await diagram.exportDiagram('bpmn', { filename: 'process.bpmn' });

The format is detected (detectFormat()) or given (format). Import options: mode ('replace' or 'merge'), layout (files without positions are laid out), layoutOptions, fit, page (draw.io), meta, nodeDefaults (a function (node) => ({ shape, width, height }) for the size of a node that has none; the diagram method passes the sizes of its templates and own shapes). Export options: meta (a block that makes the round trip lossless), compressed (draw.io), type and dir (Mermaid), title, yed (GraphML). Without a diagram: importDiagram(), exportDiagram(), toMermaid, toBPMN, toGraphML, toDrawio, parseMermaid, parseBPMN, parseGraphML, parseDrawio. Events: import, export.

Images, PDF and printing

diagram.exportSVG({ filename: 'flow.svg' });
await diagram.exportPNG({ filename: 'flow.png', scale: 2 });
diagram.exportJSON({ filename: 'flow.json' });
await diagram.exportPDF({ filename: 'flow.pdf', pageSize: 'A4', fit: 'page', header: 'Order flow' });
await diagram.print({ fit: 'width' });

PDF options (DiagramPdfOptions): pageSize, orientation, margin, scale, fit ('page', 'width', { across, down } or null), area, padding, header, title, footer, pageNumbers, pageOrder, pages, background, grid, selection, author, subject, embedFonts. getPDF() returns the bytes and getPrintLayout() the pages. Text outside the standard PDF fonts stays selectable; to show it in your font, pass your font files with embedFonts (.ttf, .otf or .woff). With a font that has the letters, Arabic, Hebrew and Hindi text is written as on the screen: right to left where needed, Arabic letters joined, Devanagari syllables built. The library ships no fonts.

PDF export works on its own. If VibeFox JS PDF is also on the page (its file loaded), toPdfDocument() returns a VibeFox JS PDF document, drawPDF(page, box) draws the diagram on a page of your VibeFox JS PDF document, and previewPDF(target) uses the VibeFox JS PDF viewer instead of the browser viewer.

Large graphs

From performance.threshold (2 000) nodes and edges on, only the visible part is drawn; at low zoom or with many nodes in view a canvas level of detail draws simplified shapes. Options (performance): virtualize ('auto', true, false), threshold, overscan, lod, lodZoom, lodNodes, budget (ms of routing per frame). For very large graphs prefer edges.router: 'straight' or edges.avoidObstacles: false.

Collaboration

collaborate(options) shares the diagram with other participants in real time: every edit is sent as operations, concurrent edits are merged, and the cursors and selections of the others are shown. The default transport connects the tabs of one browser (createBroadcastTransport()); for other users give your own transport (WebSocket, WebRTC) with send(msg) and onMessage(fn).

const ws = new WebSocket('wss://example.com/rooms/flow-42');
const session = diagram.collaborate({
  room: 'flow-42',
  user: { name: 'Ann' },
  transport: {
    send: (msg) => ws.send(JSON.stringify(msg)),
    onMessage: (fn) => ws.addEventListener('message', (e) => fn(JSON.parse(e.data))),
  },
});
session.getPeers();

Options: transport, room, clientId, user, initial ('shared', 'local', 'remote'), connect, presence, closeTransport. The session has getPeers(), setUser(), connect(), disconnect(), sync(), receive(msg), destroy() and document (a CollabDoc, which a server can also keep). applyOperations(ops) applies operations as one undo step. Events: collabSend, remoteChange, collabSync, collabStatus, peersChange.

Text to diagram and explanations

fromText(text) builds or changes the diagram from text: an arrows notation (Start -> Review -> Approve, one chain per line) or simple English and Russian sentences; the result is laid out and is one undo step (event textApply). explain() describes the structure in words.

await diagram.fromText('Start -> Review -> Approve\nReview -> Reject');
console.log(diagram.explain());   // "The diagram has 4 steps and 3 connections. It starts at «Start». ..."

Your own language model: the option ai.resolve (or fromText(text, { resolve })) receives the text and a context with the JSON Schemas DIAGRAM_SCHEMA and DIAGRAM_OPS_SCHEMA, the current model and the result of the rules, and returns a model, operations or text; the answer is checked (validateDiagram, validateOperations) and the rules are the fallback. The library never calls a model itself. Without a diagram: textToDiagram(), parseText(), explainDiagram().

Touch

Two fingers pinch-zoom and pan; one finger pans the background (or draws a marquee with touch.panFingers: 2), drags nodes, and draws an edge from a port of the selected node; a long press opens the context menu. Options (touch): panFingers, longPress, tolerance, portSlop.

Theming and styling

Themes

Every VibeFox JS component has the themes light (default), dark and high-contrast built into its CSS file. The optional vibefox-js-themes.css adds the theme pack: high-contrast-light, paper, paper-dark, glass, glass-dark, classic, classic-dark, ocean, ocean-dark, forest, forest-dark, sunset, sunset-dark, graphite, graphite-dark. The same file works for every VibeFox JS library.

VibeFoxJSDiagram.setTheme('dark');                 // the whole page
VibeFoxJSDiagram.setTheme('ocean', '#sidebar');    // every component inside a container
diagram.setTheme('glass');                    // one component (also: the theme option)
diagram.setTheme(null);                       // follow the page / container again

A component without its own theme follows the nearest container with a theme, then the page. After setTheme(name, container) the theme variables are set on the container itself too, so your CSS of the container can use them (#sidebar { background: var(--vfjs-bg); }). Your own theme: registerTheme(name, vars) with the theme variables (bg, fg, border, accent, accent-fg, muted, surface, radius, font, shadow, palette-0 … palette-9 and any other token); it applies at once to every component that uses it. getTheme() returns the page theme, themes lists the registered ones; the event themeChange reports a switch.

VibeFoxJSDiagram.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
diagram.setTheme('brand');

CSS variables

Every color, size, spacing, font, radius, shadow and duration of VibeFox JS Diagram is a CSS variable, so any setting is changed in one place. There are three levels:

  • theme variables shared by all VibeFox JS components: --vfjs-bg, --vfjs-fg, --vfjs-border, --vfjs-accent, --vfjs-accent-fg, --vfjs-muted, --vfjs-surface, --vfjs-radius, --vfjs-font, --vfjs-shadow, --vfjs-palette-0 … --vfjs-palette-9;
  • design tokens: spacing --vfjs-space-1 … --vfjs-space-8, font sizes --vfjs-font-size, --vfjs-font-size-sm and others, radii --vfjs-radius-sm …, status colors --vfjs-danger, --vfjs-success, --vfjs-warning, --vfjs-info, the scale --vfjs-size-unit, durations --vfjs-motion-duration, the focus ring --vfjs-focus-ring-color and --vfjs-focus-ring-width;
  • variables of the library, --vfjs-diagram-*, which default to the tokens above.
/* all VibeFox JS components of the page */
.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }
/* only this diagram */
#flow {
  --vfjs-diagram-node-fill: #f0f9ff;
  --vfjs-diagram-edge-stroke-width: 2px;
  --vfjs-diagram-grid-dot: transparent;
}

Main groups of the diagram variables: canvas and grid (--vfjs-diagram-bg, --vfjs-diagram-grid-dot, --vfjs-diagram-grid-line), nodes (--vfjs-diagram-node-fill, --vfjs-diagram-node-stroke, --vfjs-diagram-node-stroke-width, --vfjs-diagram-node-radius, --vfjs-diagram-node-shadow), labels (--vfjs-diagram-label-fg, --vfjs-diagram-label-font-size), containers (--vfjs-diagram-group-*), ports (--vfjs-diagram-port-radius, --vfjs-diagram-port-fill), edges (--vfjs-diagram-edge-stroke, --vfjs-diagram-edge-stroke-width, --vfjs-diagram-edge-dash, --vfjs-diagram-edge-corner-radius, --vfjs-diagram-edge-label-fg), arrows (--vfjs-diagram-arrow-size), selection (--vfjs-diagram-selection, --vfjs-diagram-halo, --vfjs-diagram-guide), minimap (--vfjs-diagram-minimap-width, --vfjs-diagram-minimap-height), the halo of labels under a shape (--vfjs-diagram-label-halo, default the canvas color, --vfjs-diagram-label-halo-width).

From JavaScript: a node or an edge has its own style (fill, stroke, strokeWidth, dash, color, fontSize, fontWeight), and kind gives it a role that the styles color (data-kind on its element).

Where to set them: on :root, on any container of your page (#checkout { --vfjs-accent: #0f766e; }), on the element of the component, or in a theme (registerTheme). The closest value wins; a component with its own theme (the option theme or component.setTheme(name)) keeps the theme variables of that theme even inside a container that sets them. A container inside another component (a form inside a dialog or a card) passes the variables of the library to the components in it as well. Only the shared design tokens (--vfjs-space, --vfjs-danger, --vfjs-selected-bg …) do not pass there: set them on a container outside the outer component or on the nested components themselves (#form .vfjs { … }). Popups, menus and dialogs placed in <body> take the values set on the page (:root), not those of the container of their component.

Default values: the theme variables are registered with @property (their initial value is the light theme), so they have a value on every element of the page. The variables of the library (--vfjs-diagram-*) keep their defaults inside the stylesheet, at the place where they are used, so a variable that you did not set has no value on your elements:

  • in your own CSS that uses a variable of the library, give it a fallback as the library does: var(--vfjs-diagram-bg, var(--vfjs-bg)), or use a theme variable directly;
  • from JavaScript, read the current value with cssVar(element, '--vfjs-diagram-node-radius') (exported by the library; it also returns the default value the component computes); getComputedStyle(element).getPropertyValue() can return an empty string for a variable of the library that nobody set.
/* your own element in the colors of the component */
.my-summary { background: var(--vfjs-diagram-bg, var(--vfjs-bg)); color: var(--vfjs-fg); }
const el = document.querySelector('#orders');
console.log(VibeFoxJSDiagram.cssVar(el, '--vfjs-diagram-node-radius'));                    // the value in use (also a default)
console.log(getComputedStyle(el).getPropertyValue('--vfjs-diagram-node-radius'));  // can be '' unless you set it

If the CSS file of the library comes from another origin without CORS (a <link> without the crossorigin attribute), the browser does not let scripts read the stylesheet, and cssVar() returns an empty string for a variable without a value on the root of the component. From your own origin, or with that attribute, it works.

--vfjs-diagram-tint has no value of its own: the library sets it on a shape with a data tint, from --vfjs-palette-0 … --vfjs-palette-9; change those. The variables of a ready-made style (--vfjs-diagram-blueprint-* and others) have a value only with that style.

The stylesheets are written with native CSS nesting; nothing changes for including them, and your own CSS can be written in any form.

Ready-made styles

The option style (the prop variant in the framework wrappers) picks a ready-made look; every style works with every theme. DIAGRAM_STYLES lists the names; setStyle() and getStyle() switch and read it (event styleChange).

StyleLook and node / edge kinds it colors
'flowchart'Flowchart colors; nodes start, end, terminal, process, decision, data, io, preparation; edges yes, no.
'bpmn'BPMN look; nodes start, end, intermediate, gateway, data; edges message, association.
'org'Org chart cards; nodes head, manager, assistant, vacant; edges dotted.
'blueprint'White lines on blue with a grid.
'sketch'Hand-drawn look.

The style is the class vfjs-diagram-style-<name> on the diagram element or any container; any other name uses your own CSS for that class.

Density and size

Set data-vfjs-density="compact", "normal" or "comfortable" on the page or on any container: heights and paddings of every VibeFox JS component inside follow. --vfjs-size-unit (default 1px) scales all sizes of a component at once, for example #orders { --vfjs-size-unit: 1.25px; }. Sizes you give as numbers in options are pixels and are not scaled.

Default height: when the element of the component has no height of its own, it gets the class vfjs-auto-height and a default height from the variable --vfjs-diagram-min-height (400 px × --vfjs-size-unit). An element with a height of its own (height, only a min-height, a flex item or a CSS Grid item, height: 100% of a parent with a height, absolute insets) gets the class vfjs-fit and is filled exactly, also when it is smaller; the content never makes it taller. With the variable at 0 (class vfjs-content-height) the height follows the width: --vfjs-diagram-aspect-ratio (default: the token --vfjs-aspect-ratio, 2 / 1).

Your own CSS

All library rules are inside the cascade layer @layer vfjs, so your own CSS always wins without !important. The class names of VibeFox JS Diagram start with vfjs-diagram- (state classes too, for example vfjs-diagram-is-keyboard), so other CSS frameworks on the page do not restyle it.

.vfjs-diagram [data-kind="risk"] .vfjs-diagram-shape { fill: #fee2e2; }
.vfjs-diagram-label { font-weight: 600; }

The library ships no font files. It uses the system font stacks of the tokens --vfjs-font, --vfjs-font-mono and --vfjs-font-serif; set them to your own fonts if you want. Animations follow prefers-reduced-motion, and colors follow forced-colors mode (Windows high contrast).

Localization and RTL

Languages

VibeFox JS Diagram comes with 14 interface languages. English (en) is built into the library file; each of the others is a language file of its own (dist/locales/vibefox-js-diagram.<lang>.js in the package), and a page loads only the ones it uses: Russian (ru), Spanish (es), German (de), French (fr), Italian (it), Portuguese (Brazilian) (pt), Ukrainian (uk), Turkish (tr), Chinese (Simplified) (zh), Japanese (ja), Korean (ko), Hindi (hi) and Arabic (ar). The locale option sets the language of one component; setLocale(lang) sets the default language of the page, which every component without its own locale follows (it re-renders on a change).

VibeFoxJSDiagram.setLocale('ru');                                  // page default
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data, locale: 'en' }); // this diagram only
diagram.setOptions({ locale: 'de' });

The example above needs the files of the languages it uses. With script tags, load a language file after the library. The order matters: loaded first, the file adds no language and writes a warning to the console.

<link rel="stylesheet" href="vibefox-js-diagram.css">
<script src="vibefox-js-diagram.global.min.js"></script>
<script src="locales/vibefox-js-diagram.ru.js"></script>

With npm or a bundler, import the language after the library. Without npm, an ES module page imports ./locales/vibefox-js-diagram.ru.esm.js, which registers the language in vibefox-js-diagram.esm.js.

import { createDiagram } from '@vibefox/js-diagram';
import '@vibefox/js-diagram/locales/ru';

The .esm.js language file does not fit the minified build @vibefox/js-diagram/min (it would load a second copy of the library). There, use the .json file:

import { createDiagram, addLocale } from '@vibefox/js-diagram/min';
import ru from '@vibefox/js-diagram/locales/ru.json';
addLocale('ru', ru);

Without its file, locale: 'ru' shows English and writes one warning to the console.

Language codes: uk, ko, zh and pt are the real codes; ua and kr also work, as aliases of uk and ko. For each string the library tries the exact code, then the alias, the base language (pt-BR → pt, zh-CN → zh), English, and finally the key itself. normalizeLocale(code) returns the real code of an alias.

A language does not set the direction: with locale: 'ar', also set rtl: true or dir="rtl" on the container.

Adding a language

addLocale(lang, dictionary) adds strings to a language (and creates it): a language of your own, or your own wording over a language file. A missing key follows the chain above, so a partial dictionary works; addLocale('ua', …) fills uk. Add the dictionary before the components that use it are created, or switch the locale afterwards.

VibeFoxJSDiagram.addLocale('de', {
  diagramSearchShapes: 'Formen suchen…',
  diagramShapeRect: 'Rechteck',
});

The keys of VibeFox JS Diagram are camel-case names with the prefix diagram (for example diagramShapeRect), about 290 keys: menus, the palette, the inspector, the node toolbar, screen reader texts, the words of explain(); shape set items use diagramSet-<set>-<shape>. The language files list every key (locales/vibefox-js-diagram.ru.json); the English texts are in the readable file vibefox-js-diagram.esm.js. Placeholders in braces are filled in by the library. t(key, params) translates a key in the page locale, diagram.t(key) in the diagram's locale; getLocale() returns the page locale, onLocaleChange(fn) reports changes. Labels of nodes and edges are your data and are not translated; palette items with labelKey are.

Plural forms: a text with a number has the keys <key>.zero, .one, .two, .few, .many and .other (the categories of Intl.PluralRules); .other is the fallback, so your dictionary can give only that form. {count} and {n} are filled in. tPlural(key, count, params, lang) picks the form; the method diagram.tPlural(key, count, params) does it in the locale of the component.

VibeFoxJSDiagram.addLocale('de', {
  'diagramExplainNodes.one': '{n} Schritt',
  'diagramExplainNodes.other': '{n} Schritte',
});
VibeFoxJSDiagram.tPlural('diagramExplainNodes', 5, {}, 'de');  // '5 Schritte'

The text rules of fromText() understand English and Russian (ai.lang) whatever language files are loaded; explain() writes in the language of its strings (lang).

Right-to-left

The option rtl: true lays the component out right-to-left (dir="rtl" on its element); rtl: false forces left-to-right; without it the component follows the page or its container (<html dir="rtl">). The arrow keys follow the reading order. isRtl(element) tells the direction of an element.

In VibeFox JS Diagram the drawing itself is not mirrored; the UI around it is: the minimap moves to the start side, menus and submenus open to the left, keyboard tab order of the nodes follows the reading order (right to left). Every text line of the drawing (labels of nodes, edges and groups, rows of UML and ER shapes, tooltips, the label editor and the fields of the property inspector) takes the direction of its own text, set by its first strong letter: a Latin label stays as written with rtl: true, and an Arabic or Hebrew label reads right to left on a left-to-right page.

Accessibility

The diagram is one tab stop with keyboard navigation over the nodes and edges; screen readers hear the focused node with its position and connections, moves, deletions and new connections. Focus is visible (the focus ring is the CSS variables --vfjs-focus-ring-color, --vfjs-focus-ring-width, --vfjs-focus-ring-offset, --vfjs-focus-ring-style); dialogs keep the focus inside and give it back when they close. The high-contrast and high-contrast-light themes, forced-colors mode and prefers-reduced-motion are supported.

Keyboard

KeysAction
Tab, Shift+TabNext / previous node in reading order (containers before their children).
Alt+arrowsThe nearest node in that direction.
Alt+Shift+arrowsThe connected node in that direction.
PageDown, PageUpThe edges of the node.
ArrowsMove the selected nodes (Shift: by 1 px); with nothing selected: the node in the middle of the view.
Enter, F2Edit the label.
Delete, BackspaceDelete.
CConnect: Tab / arrows choose the target, Enter creates the edge, Esc cancels.
Ctrl+Z, Ctrl+YUndo / redo.
Ctrl+C, Ctrl+X, Ctrl+VCopy, cut, paste.
EscDrop the focus / cancel.

Screen readers

The diagram element has the role application with a hidden key help; nodes and edges are images with names and role descriptions ("node", "connection"); the focused one is aria-activedescendant. Options (a11y): label, help, announce, tabOrder ('reading', 'data' or a compare function), nodeLabel(node), edgeLabel(edge, source, target); keyboard: false turns the keys off.

Methods: setKeyboardFocus(id, { announce }), getKeyboardFocus(), getAccessibleName(id). The library also exports the helpers it uses itself: announce(message), trapFocus, rovingFocus, setAria, prefersReducedMotion() and others (see API reference).

Using with other VibeFox JS libraries

VibeFox JS Diagram works on its own. Every VibeFox JS library is a separate file with its own copy of the shared core, and several libraries on one page work together without conflicts: one global variable per library (VibeFoxJSDiagram, VibeFoxJSCharts, …), class names with the library prefix, one page theme, the same events.

Connecting components with link()

link(source, event, target, method, transform) calls a method of one component whenever another emits an event; it returns a function that removes the link. connect(source, event, handler) subscribes and returns an unsubscribe function. bus is a page-wide event channel shared by all VibeFox JS libraries on the page.

// the selected node fills a table of VibeFox JS Grid (both files loaded on the page)
const unlink = VibeFoxJSDiagram.link(diagram, 'selectionChange', grid, 'setData', (e) => e.nodes.map((n) => ({ id: n.id, label: n.label })));
VibeFoxJSDiagram.bus.emit('flow:saved', { at: Date.now() });   // any library can listen: VibeFoxJSGrid.bus.on('flow:saved', fn)

What uses another library when it is on the page

  • PDF export and printing: work on their own; if VibeFox JS PDF is also on the page, toPdfDocument(), drawPDF() and the VibeFox JS PDF viewer in previewPDF() are available.
  • Export to SVG, PNG, JSON, Mermaid, BPMN, GraphML and draw.io works on its own.

AI tools

The library describes its main actions as tools for function calling with a language model. It never calls a model or a service itself: you send the descriptions to your model and run the calls it asks for.

ToolWhat it does
diagram_get_modelThe nodes and edges (toJSON()).
diagram_explainThe text of explain().
diagram_apply_operationsApplies operations (DIAGRAM_OPS_SCHEMA) as one undo step; new nodes are placed by the incremental layout.
const { describeTools, callTool, createToolKit } = VibeFoxJSDiagram;
const tools = describeTools(diagram, { format: 'openai' });   // 'plain' / 'anthropic', 'openai', 'webmcp'
const result = await callTool(diagram, 'diagram_explain', {}); // { ok: true, result } or { ok: false, error }
const kit = createToolKit({ flow: diagram });               // tool names get the prefix 'flow_'
const answer = await kit.ask('Add a step Testing after Review', {
  format: 'anthropic',
  model: async (request) => (await fetch('/api/llm', { method: 'POST', body: JSON.stringify(request.body) })).json(),
});

callTool checks the arguments against the tool schema before it runs and never throws for bad input. createToolKit(components, { webmcp, readOnly }) joins the tools of several components (also of other VibeFox JS libraries) under unique names; kit.ask(prompt, { model, format, system, maxSteps, signal, onToolCall }) runs the loop "model → tool calls → results" with your model function; kit.registerWebMCP() registers the tools in the browser's navigator.modelContext where available. registerTools(target, provider) adds your own tools; validateSchema(value, schema) is the schema check.

API reference

Exports

Library: createDiagram, VibeFoxJSDiagram, GraphModel, SHAPE_DEFAULTS, DIAGRAM_STYLES, layouts, OrthoRouter, routeOrthogonal, registerShape, getShape, getShapeNames, registerShapeSet, getShapeSet, getShapeSetNames, fillTemplate, defaultPaletteItems, parseText, diffJSON, lintModel, traceFrom, importDiagram, exportDiagram, detectFormat, toMermaid, toBPMN, toGraphML, toDrawio, parseMermaid, parseBPMN, parseGraphML, parseDrawio, CollabDoc, createBroadcastTransport, textToDiagram, explainDiagram, DIAGRAM_SCHEMA, DIAGRAM_OPS_SCHEMA, validateDiagram, validateOperations, FlowSimulation.

Shared core (the same in every VibeFox JS library): setTheme, getTheme, registerTheme, themes, tokens, componentTokens, densities, cssVar, cssColor, cssLength, observeTokens, setLocale, getLocale, addLocale, normalizeLocale, t, tPlural, withLocale, onLocaleChange, link, connect, bus, Emitter, VibeFoxJSComponent, factory, toCSV, downloadFile, downloadCanvasPNG, createVectorContext, VectorContext, vectorToSVG, vectorToPDF, printSVG, createVectorImage, loadVectorImage, SVG_MIME, PDF_MIME, PDF_PAGE_SIZES, describeTools, callTool, createToolKit, registerTools, validateSchema, announce, trapFocus, rovingFocus, getFocusable, focusFirst, saveFocus, setAria, ensureId, addAriaRef, removeAriaRef, isRtl, mirrorArrow, prefersReducedMotion, prefersHighContrast, motionDuration, onPreferenceChange, injectStyles, ensureBaseStyles, formatNumber, formatDate, escapeHtml, createEl, deepMerge, isPlainObject, getPath, setPath, uid, clamp, debounce, throttle, VERSION.

Options

Also every VibeFox JS component accepts theme, locale, rtl and on (see Core concepts).

OptionTypeDefaultDescription
data{ nodes, edges }emptyThe graph.
stylestring or nullnullReady-made style.
gridobject{ show: true, size: 20, snap: true }Background grid and snapping.
guidesbooleantrueSmart guides while dragging.
minimapbooleantrueMinimap.
autoFitbooleanfalseFit the content after the first render.
readOnlybooleanfalseNo editing.
keyboardbooleantrueKeyboard.
allowSelfLoopsbooleanfalseEdges from a node to itself.
canConnectfunction or nullnullValidation of new edges.
zoomobject{ min: 0.1, max: 4, wheel: true }Zoom limits.
nodesobject{ editable: true, resizable: true, rotatable: true, minWidth: 20, minHeight: 20, rotateStep: 15 }Node editing.
edgesobject{ router: 'ortho', editable: true, reconnect: true, avoidObstacles: true, obstacleMargin: 12, separation: 8, bendPenalty: 40, kind: null }Edges and routing.
contextMenuobject or false{ enabled: true, defaults: true }Context menus.
tooltipsobject or false{ enabled: true, delay: 500, hideDelay: 100, nodes: true, edges: true }Tooltips.
templatesobject{}Node templates.
shapesobject{}Own shapes of this diagram.
nodeToolbarobject or false{ enabled: true, defaults: true }Node toolbar.
containersobject{ autoSize: true, padding: 16 }Containers.
layout{ animate }{ animate: 400 }Layout animation, ms.
history{ limit }{ limit: 100 }Undo depth.
performanceobject or false{ virtualize: 'auto', threshold: 2000 }Large graphs.
a11yobject{ help: true, announce: true, tabOrder: 'reading' }Keyboard and screen readers.
touchobject{ panFingers: 1, longPress: 500, tolerance: 10, portSlop: 18 }Touch gestures.
ai{ resolve, lang }—Text to diagram: your model and the rule language.

Events

EventPayloadDescription
ready, dataChange, optionsChange, themeChange, destroysee Core conceptsCommon events.
nodeClick, nodeDblClick{ node, event }Node clicked.
nodeAdd{ node }Node added.
nodeChange{ node, patch }Node changed.
nodeMove{ nodes, dx, dy }Nodes moved.
nodeRemove{ nodes, edges }Nodes removed.
nodeResize{ node, from, to }Node resized.
nodeRotate{ node, from, to }Node rotated.
nodeArrange{ action, mode, nodes }Align / distribute / z-order.
edgeClick, edgeDblClick{ edge, event }Edge clicked.
edgeCreate{ edge }Edge created.
edgeChange{ edge, patch }Edge changed.
edgeRemove{ edges }Edges removed.
edgeReconnect{ edge, end, from, to }Edge end moved.
selectionChange{ nodes, edges, ids }Selection changed.
viewportChange{ zoom, pan }Zoom / pan.
labelChange{ type, id, label }Label edited.
groupChange{ action, group }Containers changed.
layoutApply{ name, options }Layout applied.
historyChange{ canUndo, canRedo }Undo history changed.
canvasClick{ x, y, event }Background clicked.
paletteDrop{ node, item }Palette item dropped.
traceChange{ source, direction, nodes, edges }Flow trace on / off.
lintComplete{ issues }Linter finished.
diffChange{ diff }Visual diff shown.
contextMenu{ target, node, edge, x, y, items, preventDefault }Menu opens (cancelable).
contextMenuClose{ reason }Menu closed.
menuItemClick{ item, id, target, node, edge }Menu item chosen.
tooltipShow, tooltipHide{ target, node, edge }Tooltip shown / hidden.
styleChange{ style, previous }Style switched.
propertyChange{ target, ids, key, value, previous }Inspector change.
nodeToolbarClick{ item, id, node, event, preventDefault }Node toolbar button (cancelable).
export{ format, filename, pages }PDF, print or file export.
import{ format, warnings, nodes, edges, laidOut, mode }File imported.
collabSend, remoteChange, collabSync, collabStatus, peersChangesee CollaborationCollaboration.
textApply{ source, kind, warnings, lang }fromText() applied.
simulationStep, simulationState, simulationEndsee Analysis toolsSimulation.

Methods

MethodReturnsDescription
setData, getData, setOptions, setOption, getOption, getState, setState, setTheme, on, once, off, use, t, destroy—Common methods (see Core concepts).
setStyle, getStylethis / nameReady-made style.
getZoom, setZoom, getPan, setPan, zoomIn, zoomOut, fitToContent, centerAt, centerOn, svgRect, clientToWorld, viewportWorldRectvalue / thisViewport.
select, toggleSelect, selectAll, clearSelection, getSelection, isSelected, selectionIdsthis / valueSelection.
addNode, updateNode, removeNode, addEdge, updateEdge, removeEdge, removeSelection, updateNodeData, resizeNode, rotateNode, reconnectEdgenode / edge / thisEditing (undoable).
getNode, getEdge, getNodes, getEdgesnode(s) / edge(s)Read.
copySelection, cutSelection, paste, duplicateSelection, editLabelthisClipboard, labels.
showContextMenu, hideContextMenu, getContextMenu, showTooltip, hideTooltipboolean / thisMenus and tooltips.
alignNodes, distributeNodes, bringToFront, sendToBack, bringForward, sendBackwardnodes / thisArranging.
groupSelection, ungroup, toggleCollapse, fitContainernode / thisContainers.
undo, redo, canUndo, canRedobooleanHistory.
applyLayout(name, options)PromiseAutomatic layout.
toJSON, loadJSON, exportJSON, exportSVG, exportPNGvalue / this / PromiseSerialization and images.
getPrintLayout, getPDF, exportPDF, print, drawPDF, toPdfDocument, previewPDFlayout / PromisePDF and printing.
importDiagram, exportDiagramPromiseDiagram files.
traceFlow, clearTrace, lint, clearLint, diff, showDiff, clearDiffvalue / thisAnalysis.
fromText, explain, applyOperationsPromise / string / resultText and operations.
collaborate, getCollaborationsessionCollaboration.
simulate, getSimulationsimulationSimulation.
mountPalette, mountInspector, getNodeToolbar, addConnectedNodepanel / nodeEditing tools.
setKeyboardFocus, getKeyboardFocus, getAccessibleNamevalueKeyboard focus.

The TypeScript declarations (vibefox-js-diagram.d.ts) describe every option, payload and return type in detail: DiagramOptions, DiagramNodeInput, DiagramEdgeInput, DiagramEvents, DiagramState, DiagramTemplate, DiagramShapeDef, DiagramLayoutOptions, DiagramPdfOptions and others.

Troubleshooting

No styles

Link vibefox-js-diagram.css next to the script. Without it the component works but is unstyled, and the console shows one warning "VibeFox JS stylesheet is not loaded". In a bundler, import @vibefox/js-diagram/css. The framework wrappers do not add the CSS for you.

My CSS does not apply, or a page CSS framework changes the component

Your rules win over the library rules without !important because the library CSS is in @layer vfjs. If they still do not apply, check the class names: state classes have the library prefix (vfjs-diagram-is-selected, not is-selected). The library never uses generic class names, so page CSS frameworks do not change it.

ES modules do not load from disk

Browsers load <script type="module"> only over http(s). Use a local web server, or use vibefox-js-diagram.global.js, which also works from file://.

Content Security Policy

The library does not use eval or inline scripts and loads nothing from the network. It sets inline styles on its elements (sizes and positions), so a policy with style-src must allow them ('unsafe-inline' for style attributes). Images of image nodes load from their URLs (img-src); the default collaboration transport uses BroadcastChannel.

Text in the PDF is not in my font

The library ships no fonts. The PDF uses the standard PDF fonts; text outside them stays selectable but is drawn with a fallback. Pass your own font files with embedFonts (.ttf, .otf or .woff), or embedFonts: true to take the @font-face fonts of the page.

The diagram is too small

The diagram fills its element. Give the element a height (CSS or an inline style); the diagram takes it exactly, also a small one. Without one it is 400 px high (--vfjs-diagram-min-height). The target element must exist when createDiagram runs (a selector that finds nothing throws an error). fitToContent() brings the whole graph into view.

Edges cross nodes

Edges with your own waypoints keep them; remove the waypoints or use applyLayout(name, { keepWaypoints: false }). The orthogonal router needs edges.avoidObstacles: true (default).

Layout or routing is slow on a large graph

Use edges.router: 'straight' or edges.avoidObstacles: false for thousands of edges, keep performance.virtualize on, and lay out with slice: true (default) so the page stays responsive.

HTML templates are blank in the PNG

The PNG export draws HTML templates through the browser; Safari may leave them blank. Use the SVG or PDF export, or SVG templates.

Limitations

  • Resize handles only for a single selected node; containers can be resized but not rotated, and their children are not scaled with them; marquee, guides and dropping into containers use the unrotated box.
  • Interactive elements (inputs, buttons) inside HTML templates are not special-cased: pointer events go to the node.
  • Routing: edges with waypoints keep the manual route; edge labels are not obstacles; the router can take seconds on very dense graphs with many long cross links (use straight edges there).
  • Per-node overrides of geometry variables (radii, port and arrow sizes) do not work; only colors, widths, dashes, fonts and shadows can be set per node with CSS.
  • PDF: the sketch style wobble is not drawn; HTML templates of rotated nodes print their texts only approximately.
  • Large graphs: the canvas level of detail draws no labels, arrows, ports, images, HTML templates or custom drawings (only boxes).
  • File formats: BPMN choreographies, conversations and vertical pools, several BPMN diagram planes, Mermaid click handlers and icons, GraphML hyperedges and special yEd shapes are not modelled (they are reported as warnings).
  • Collaboration: a concurrent edit of the same label keeps one whole text; positions are sent on drop, not while dragging; unsent offline edits are kept in memory only.
  • Text rules: a small grammar for English and Russian, not a language model; simulation: inclusive and complex gateways run as exclusive ones, timers and messages are plain steps.
  • Framework wrappers: functions in options are compared by reference; removing a prop does not reset the option to its default; Vue watches object props shallowly.

Bug Report

Thank you for helping us improve. We carefully review every report, but we do not reply to them individually. If your report leads to a change, it will be listed in the product changelog together with the report number. To discuss something in detail, please open a support ticket.

Slide to fit the puzzle