VibeFox JS Diagram — Demo
Início rápido
HTML puro
O fluxograma do início rápido com a paleta de formas à esquerda. Arraste uma forma da paleta para o diagrama, arraste um nó, desenhe um conector a partir de uma porta de um nó e dê duplo clique em um nó para editar o seu rótulo.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 180px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(panel, canvas);
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram(canvas, {
style: 'flowchart',
data,
on: { nodeClick: (e) => console.log('clicked', e.node.label) },
});
diagram.mountPalette(panel);Conceitos principais
Eventos
Cada manipulador de evento recebe um único objeto payload; a lista abaixo do diagrama mostra os eventos mais recentes. Clique, mova e conecte nós, edite um rótulo ou dê zoom com a roda do mouse.
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
const log = document.createElement('div');
log.style.cssText = 'height: 110px; overflow: auto; margin-top: 6px; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace';
document.getElementById('app').after(log);
const write = (text) => log.prepend(Object.assign(document.createElement('div'), { textContent: text }));
diagram.on('nodeClick', (e) => write('nodeClick ' + e.node.label));
diagram.on('nodeMove', (e) => write('nodeMove ' + e.nodes.map((n) => n.label).join(', ') + ' by ' + Math.round(e.dx) + ', ' + Math.round(e.dy)));
diagram.on('edgeCreate', (e) => write('edgeCreate ' + e.edge.source.node + ' → ' + e.edge.target.node));
diagram.on('selectionChange', (e) => write('selectionChange [' + e.ids.join(', ') + ']'));
diagram.on('labelChange', (e) => write('labelChange ' + e.id + ': ' + e.label));
diagram.on('viewportChange', (e) => write('viewportChange zoom ' + e.zoom.toFixed(2)));
write('ready: click a node');Snapshots de estado
getState() guarda o zoom, o deslocamento, a seleção e a geometria de cada nó; setState() os restaura. Clique em Save view, mova alguns nós e dê zoom, depois clique em Restore view.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
let saved = diagram.getState();
addButtons([
['Save view', () => { saved = diagram.getState(); }],
['Restore view', () => diagram.setState(saved)],
]);Desfazer e refazer
Cada edição é um passo de desfazer; os botões seguem o evento historyChange. Mova ou exclua um nó e depois desfaça e refaça (também com Ctrl+Z e Ctrl+Y).
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
const bar = addButtons([
['Undo', () => diagram.undo()],
['Redo', () => diagram.redo()],
['Delete selected', () => diagram.removeSelection()],
]);
const [undo, redo] = bar.querySelectorAll('button');
const sync = () => { undo.disabled = !diagram.canUndo(); redo.disabled = !diagram.canRedo(); };
diagram.on('historyChange', sync);
diagram.updateNode('ship', { label: 'Ship today' });
sync();Nós e conectores
Edição por código
O nó Code review foi adicionado a partir do código, teve a cor alterada, foi redimensionado, girado e conectado. Clique em Add a step para adicionar um nó conectado ao último.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, minimap: false });
const n = diagram.addNode({ label: 'Review', shape: 'rounded', x: 260, y: 300 });
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, -8);
const e = diagram.addEdge({ source: 'reject', target: n.id, label: 'next', arrowEnd: 'arrow' });
diagram.reconnectEdge(e.id, 'target', { node: n.id, port: 'right' });
let last = 'ship', count = 0;
addButtons([['Add a step', () => {
const prev = diagram.getNode(last);
const node = diagram.addNode({ label: 'Step ' + ++count, x: prev.x + 180, y: prev.y });
diagram.addEdge({ source: last, target: node.id });
last = node.id;
diagram.fitToContent(30);
}]]);
diagram.fitToContent(30);Interação do usuário
O nó Ship está selecionado: arraste as suas alças quadradas para redimensioná-lo e a alça redonda para girá-lo (Shift encaixa o ângulo). Arraste os nós sobre a grade com encaixe e guias inteligentes de alinhamento, desenhe um novo conector a partir de uma porta e selecione um conector e arraste as suas extremidades para reconectá-lo.
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
style: 'flowchart',
data,
grid: { show: true, size: 20, snap: true },
guides: true,
nodes: { resizable: true, rotatable: true, rotateStep: 15, minWidth: 60 },
edges: { router: 'ortho', reconnect: true },
canConnect: (e) => e.source !== e.target,
autoFit: true,
minimap: false,
});
diagram.select(['ship']);Organização
Cinco nós posicionados aleatoriamente estão selecionados. Alinhe-os, distribua-os uniformemente ou selecione alguns por conta própria (Shift+clique ou uma seleção por retângulo sobre o fundo) e organize-os.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const nodes = ['A', 'B', 'C', 'D', 'E'].map((id, i) => ({ id, label: 'Node ' + id, x: 30 + i * 130 + (i % 2) * 25, y: 40 + ((i * 53) % 150) }));
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data: { nodes, edges: [] }, minimap: false });
diagram.selectAll();
addButtons([
['Align top', () => diagram.alignNodes('top')],
['Align middle', () => diagram.alignNodes('middle')],
['Align left', () => diagram.alignNodes('left')],
['Distribute horizontally', () => diagram.distributeNodes('horizontal', null, { by: 'gap' })],
['Distribute vertically', () => diagram.distributeNodes('vertical', null, { by: 'gap' })],
['Bring to front', () => diagram.bringToFront()],
]);Conectores, roteadores e setas
Os três roteadores (straight, bezier, ortho contornando o nó do meio) e um conjunto de pontas de seta, incluindo as extremidades ER. Arraste o nó Obstacle e observe o conector ortogonal contorná-lo.
const nodes = [], edges = [];
// routers
nodes.push({ id: 's', label: 'Source', x: 20, y: 20 }, { id: 'obstacle', label: 'Obstacle', x: 200, y: 20 }, { id: 't', label: 'Target', x: 400, y: 20 });
edges.push({ source: 's', target: 't', router: 'ortho', label: 'ortho', arrowEnd: 'arrow' });
nodes.push({ id: 'b1', label: 'A', x: 20, y: 110, width: 60 }, { id: 'b2', label: 'B', x: 420, y: 150, width: 60 });
edges.push({ source: 'b1', target: 'b2', router: 'bezier', label: 'bezier' });
nodes.push({ id: 'l1', label: 'A', x: 20, y: 190, width: 60 }, { id: 'l2', label: 'B', x: 420, y: 230, width: 60 });
edges.push({ source: 'l1', target: 'l2', router: 'straight', label: 'straight' });
// arrow heads
const arrows = ['arrow', 'open', 'diamond', 'diamond-open', 'circle', 'triangle-open', 'cross', 'one-or-many', 'zero-or-one'];
arrows.forEach((arrow, i) => {
const x = 20 + Math.floor(i / 3) * 180, y = 320 + (i % 3) * 34;
nodes.push({ id: 'p' + i, label: '', shape: 'ellipse', width: 10, height: 10, x, y }, { id: 'q' + i, label: '', shape: 'ellipse', width: 10, height: 10, x: x + 150, y });
edges.push({ source: 'p' + i, target: 'q' + i, router: 'straight', arrowEnd: arrow, label: arrow });
});
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data: { nodes, edges }, autoFit: true, minimap: false });Formas, modelos e conjuntos de formas
Formas e modelos integrados
As formas integradas e dois nós desenhados por um modelo HTML a partir dos seus dados ({{data.name}}, o preenchimento vinculado a data.color). Passe o mouse sobre um cartão de pessoa para ver a sua dica de ferramenta.
const image = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><circle cx="20" cy="20" r="18" fill="#60a5fa"/><path d="M8 28l8-10 6 7 4-4 6 7z" fill="#fff"/></svg>');
const shapes = ['rect', 'rounded', 'ellipse', 'diamond', 'hexagon', 'cylinder'];
const nodes = shapes.map((shape, i) => ({ id: shape, shape, label: shape, x: 20 + i * 130, y: 20 }));
nodes.push({ id: 'img', shape: 'image', image, label: 'image', x: 20, y: 130, width: 60, height: 60 });
nodes.push({ id: 'group', shape: 'group', label: 'group', x: 120, y: 120, width: 200, height: 110 });
nodes.push({ id: 'inner', label: 'child', parent: 'group', x: 160, y: 160 });
nodes.push({ id: 'lane', shape: 'swimlane', label: 'swimlane', x: 350, y: 120, width: 400, height: 110 });
nodes.push({ id: 'p1', template: 'person', parent: 'lane', x: 400, y: 150, data: { name: 'Ann Lee', role: 'CEO', color: '#dbeafe', email: '[email protected]' } });
nodes.push({ id: 'p2', template: 'person', parent: 'lane', x: 590, y: 150, data: { name: 'Ben Ford', role: 'CTO', color: '#dcfce7', email: '[email protected]' } });
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
templates: {
person: {
shape: 'rounded', width: 140, height: 56,
html: '<b>{{data.name}}</b><br>{{data.role}}',
bind: { fill: 'data.color' },
tooltip: '{{data.email}}',
},
},
data: { nodes, edges: [{ source: 'p1', target: 'p2' }] },
autoFit: true,
minimap: false,
});Suas próprias formas
Duas formas adicionadas com registerShape(): uma etiqueta e uma estrela, cada uma um caminho SVG do tamanho do nó. Redimensione um nó: o contorno acompanha o novo tamanho.
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,
});
VibeFoxJSDiagram.registerShape('star', {
path: (w, h) => {
let d = '';
for (let i = 0; i < 10; i++) {
const r = i % 2 ? 0.4 : 1, a = Math.PI / 5 * i - Math.PI / 2;
d += (i ? 'L' : 'M') + (w / 2 + Math.cos(a) * r * w / 2).toFixed(1) + ' ' + (h / 2 + Math.sin(a) * r * h / 2).toFixed(1);
}
return d + 'Z';
},
width: 90, height: 90, keepRatio: true,
});
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
data: {
nodes: [
{ id: 'a', shape: 'tag', label: 'New', x: 40, y: 80 },
{ id: 'b', shape: 'tag', label: 'In progress', x: 220, y: 80, width: 150 },
{ id: 'c', shape: 'star', label: 'Done', x: 440, y: 55, style: { fill: '#fde68a' } },
],
edges: [{ source: 'a', target: 'b' }, { source: 'b', target: 'c' }],
},
autoFit: true,
minimap: false,
});
diagram.select(['c']);Conjuntos de formas
Um processo BPMN 2.0 do conjunto de formas bpmn, com a paleta dos conjuntos BPMN, UML e ER à esquerda. Arraste uma forma BPMN para o pool e conecte-a.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 190px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(panel, canvas);
const diagram = VibeFoxJSDiagram.createDiagram(canvas, {
data: {
nodes: [
{ id: 'pool', shape: 'bpmn:pool', label: 'Shop', x: 0, y: 0, width: 640, height: 200 },
{ id: 'start', shape: 'bpmn:start.message', label: 'Order received', parent: 'pool', x: 60, y: 80 },
{ id: 'check', shape: 'bpmn:task.user', label: 'Check order', parent: 'pool', x: 140, y: 64 },
{ id: 'gw', shape: 'bpmn:gateway', label: 'OK?', parent: 'pool', x: 300, y: 69 },
{ id: 'ship', shape: 'bpmn:task.service', label: 'Ship', parent: 'pool', x: 400, y: 20 },
{ id: 'note', shape: 'bpmn:task.send', label: 'Notify buyer', parent: 'pool', x: 400, y: 120 },
{ id: 'end', shape: 'bpmn:end', label: 'Done', parent: 'pool', x: 570, y: 80 },
],
edges: [
{ source: 'start', target: 'check', kind: 'bpmn:sequence' },
{ source: 'check', target: 'gw', kind: 'bpmn:sequence' },
{ source: 'gw', target: 'ship', kind: 'bpmn:sequence', label: 'yes' },
{ source: 'gw', target: 'note', kind: 'bpmn:default', label: 'no' },
{ source: 'ship', target: 'end', kind: 'bpmn:sequence' },
{ source: 'note', target: 'end', kind: 'bpmn:sequence' },
],
},
autoFit: true,
minimap: false,
});
diagram.mountPalette(panel, ['bpmn', 'uml', 'er']);Classes UML com herança e composição (kind: 'uml:inheritance' define a seta e a linha) e entidades ER com extremidades de pé de galinha.
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
data: {
nodes: [
{ id: 'shape', shape: 'uml:class', label: 'Shape', data: { attributes: ['+ x: number', '+ y: number'], methods: ['+ draw(): void'] }, x: 150, y: 10 },
{ id: 'circle', shape: 'uml:class', label: 'Circle', data: { attributes: ['+ r: number'] }, x: 40, y: 190 },
{ id: 'rect', shape: 'uml:class', label: 'Rect', data: { attributes: ['+ w: number', '+ h: number'] }, x: 250, y: 190 },
{ id: 'customer', shape: 'er:entity', label: 'Customer', data: { attributes: [{ name: 'id', type: 'int', key: 'pk' }, { name: 'name', type: 'varchar' }, { name: 'email', type: 'varchar' }] }, x: 470, y: 10 },
{ id: 'order', shape: 'er:entity', label: 'Order', data: { attributes: [{ name: 'id', type: 'int', key: 'pk' }, { name: 'customer_id', type: 'int', key: 'fk' }, { name: 'total', type: 'decimal' }] }, x: 470, y: 190 },
],
edges: [
{ source: 'circle', target: 'shape', kind: 'uml:inheritance' },
{ source: 'rect', target: 'shape', kind: 'uml:inheritance' },
{ source: 'customer', target: 'order', kind: 'er:one-to-many', label: 'places' },
],
},
autoFit: true,
minimap: false,
});Um diagrama de rede do conjunto network: dispositivos com ícones, conexões e uma linha VPN.
const n = (id, shape, label, x, y) => ({ id, shape: 'network:' + shape, label, x, y });
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
data: {
nodes: [
n('internet', 'internet', 'Internet', 260, 0),
n('fw', 'firewall', 'Firewall', 260, 110),
n('lb', 'load-balancer', 'Balancer', 260, 220),
n('web1', 'server', 'Web 1', 120, 330),
n('web2', 'server', 'Web 2', 400, 330),
n('db', 'database', 'Database', 260, 440),
n('office', 'desktop', 'Office', 560, 110),
],
edges: [
{ source: 'internet', target: 'fw', kind: 'network:link' },
{ source: 'fw', target: 'lb', kind: 'network:link' },
{ source: 'lb', target: 'web1', kind: 'network:link' },
{ source: 'lb', target: 'web2', kind: 'network:link' },
{ source: 'web1', target: 'db', kind: 'network:link' },
{ source: 'web2', target: 'db', kind: 'network:link' },
{ source: 'office', target: 'fw', kind: 'network:vpn', label: 'VPN' },
],
},
autoFit: true,
minimap: false,
});Contêineres
Duas raias (swimlanes) e um grupo: os elementos filhos se movem com o seu contêiner, e o contêiner cresce quando um filho é arrastado até a sua borda. Clique em Collapse / expand para recolher o grupo.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
containers: { autoSize: true, padding: 16 },
data: {
nodes: [
{ id: 'sales', shape: 'swimlane', label: 'Sales', x: 0, y: 0, width: 600, height: 110 },
{ id: 'stock', shape: 'swimlane', label: 'Warehouse', x: 0, y: 120, width: 600, height: 150 },
{ id: 'order', label: 'Take order', parent: 'sales', x: 60, y: 35 },
{ id: 'invoice', label: 'Send invoice', parent: 'sales', x: 400, y: 35 },
{ id: 'pack', shape: 'group', label: 'Packing', parent: 'stock', x: 180, y: 140, width: 330, height: 110 },
{ id: 'pick', label: 'Pick', parent: 'pack', x: 200, y: 175, width: 120 },
{ id: 'box', label: 'Box', parent: 'pack', x: 370, y: 175, width: 120 },
],
edges: [
{ source: 'order', target: 'pick' },
{ source: 'pick', target: 'box' },
{ source: 'box', target: 'invoice' },
],
},
autoFit: true,
minimap: false,
});
addButtons([['Collapse / expand', () => diagram.toggleCollapse('pack')]]);Layouts
Um grafo e os layouts automáticos. Escolha um layout e uma direção: os nós passam para as suas novas posições com uma animação (um passo de desfazer).
const names = ['Board', 'Sales', 'Product', 'Finance', 'North', 'South', 'Web', 'Mobile', 'Design', 'Audit', 'Tax'];
const nodes = names.map((label, i) => ({ id: 'n' + i, label, x: (i * 97) % 500, y: (i * 61) % 300 }));
const links = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8], [3, 9], [3, 10]];
const edges = links.map(([a, b]) => ({ source: 'n' + a, target: 'n' + b }));
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data: { nodes, edges }, layout: { animate: 400 } });
const bar = document.createElement('div');
const layout = document.createElement('select');
for (const name of ['layered', 'tree', 'radial', 'mindmap', 'force', 'circular', 'orthogonal', 'grid']) layout.add(new Option(name));
const dir = document.createElement('select');
for (const d of ['TB', 'LR', 'BT', 'RL']) dir.add(new Option(d));
const run = async () => {
await diagram.applyLayout(layout.value, { dir: dir.value, layerGap: 70, nodeGap: 24 });
diagram.fitToContent(30);
};
layout.onchange = dir.onchange = run;
bar.append(layout, dir);
document.getElementById('app').before(bar);
run();Janela de visualização
Um grafo maior com o minimapa no canto. Dê zoom com a roda do mouse ou com os botões, arraste o fundo para deslocar a área, arraste o quadro no minimapa ou centralize a visualização em um nó.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const nodes = [], edges = [];
for (let i = 0; i < 40; i++) {
nodes.push({ id: 'n' + i, label: 'Node ' + i, x: (i % 8) * 170, y: Math.floor(i / 8) * 110 });
if (i % 8) edges.push({ source: 'n' + (i - 1), target: 'n' + i });
if (i >= 8 && i % 3 === 0) edges.push({ source: 'n' + (i - 8), target: 'n' + i });
}
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data: { nodes, edges }, minimap: true, zoom: { min: 0.2, max: 3 } });
diagram.setZoom(0.8);
diagram.centerOn('n10');
addButtons([
['Zoom in', () => diagram.zoomIn()],
['Zoom out', () => diagram.zoomOut()],
['Fit', () => diagram.fitToContent(30)],
['Center on Node 20', () => { diagram.setZoom(1.5); diagram.centerOn('n20'); diagram.select(['n20']); }],
]);Ferramentas de edição
Paleta
A paleta de formas pesquisável com os itens integrados e dois itens próprios. Digite no campo de pesquisa e depois arraste um item para o diagrama.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 190px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(panel, canvas);
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram(canvas, { style: 'flowchart', data, autoFit: true, minimap: false });
diagram.mountPalette(panel, [
...VibeFoxJSDiagram.defaultPaletteItems(),
{ shape: 'rounded', label: 'Approval', group: 'My steps', width: 140, height: 50, style: { fill: '#dcfce7' } },
{ shape: 'ellipse', label: 'Escalation', group: 'My steps', width: 120, height: 60, style: { fill: '#fee2e2' } },
]);
diagram.on('paletteDrop', (e) => diagram.select([e.node.id]));Inspetor de propriedades e barra de ferramentas do nó
O inspetor à direita mostra as propriedades do nó selecionado, com um campo próprio Owner; a barra de ferramentas do nó fica ao lado dele. Altere o rótulo, as cores ou o Owner; selecione um conector para alterar o seu roteador e as setas.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 250px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(canvas, panel);
const 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' },
],
};
data.nodes[2].data = { owner: 'Ann' };
const diagram = VibeFoxJSDiagram.createDiagram(canvas, { style: 'flowchart', data, autoFit: true, minimap: false });
diagram.mountInspector(panel, {
fields: { node: [{ key: 'data.owner', type: 'text', label: 'Owner', section: 'data' }] },
});
diagram.select(['ship']);Menu de contexto e dicas de ferramenta
O menu de contexto do nó Order valid? com um item próprio no final. Clique com o botão direito em um nó, em um conector ou no fundo para abrir os seus menus; passe o mouse sobre um nó para ver a sua dica de ferramenta.
const 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' },
],
};
for (const n of data.nodes) n.tooltip = 'Step: ' + n.label;
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
style: 'flowchart',
data,
autoFit: true,
minimap: false,
tooltips: { delay: 200 },
contextMenu: {
node: [{ id: 'mail', label: 'Mail the owner', action: (ctx) => alert('Mail about ' + ctx.node.label) }],
canvas: [{ id: 'hello', label: 'Say hello', action: () => alert('Hello') }],
},
});
diagram.select(['check']);
diagram.showContextMenu({ id: 'check' });Ferramentas de análise
Tudo o que é alcançável a partir de Start fica destacado (traceFlow). Verifique o diagrama com o linter (um nó sem conexões, um conector duplicado) ou mostre as alterações em relação à versão anterior.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const output = document.createElement('div');
output.style.cssText = 'margin-top: 6px; min-height: 40px; font-size: 13px; white-space: pre-wrap';
document.getElementById('app').after(output);
const data = {
nodes: [
{ id: 'start', label: 'Start', shape: 'ellipse', x: 20, y: 100 },
{ id: 'a', label: 'Collect', x: 170, y: 40 },
{ id: 'b', label: 'Check', x: 170, y: 160 },
{ id: 'c', label: 'Pay', x: 350, y: 100 },
{ id: 'd', label: 'Archive', x: 530, y: 100 },
{ id: 'lone', label: 'Forgotten', x: 530, y: 220 },
],
edges: [
{ source: 'start', target: 'a' }, { source: 'start', target: 'b' },
{ source: 'a', target: 'c' }, { source: 'b', target: 'c' }, { source: 'b', target: 'c' },
],
};
const previous = JSON.parse(JSON.stringify(data));
previous.nodes = previous.nodes.filter((n) => n.id !== 'd');
previous.nodes.push({ id: 'old', label: 'Old step', x: 350, y: 220 });
previous.nodes.find((n) => n.id === 'a').label = 'Gather';
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data, autoFit: true, minimap: false });
const clear = () => { diagram.clearTrace(); diagram.clearLint(); diagram.clearDiff(); output.textContent = ''; };
addButtons([
['Trace from Start', () => { clear(); diagram.traceFlow('start', 'down'); }],
['Lint', () => {
clear();
output.textContent = diagram.lint({ highlight: true }).map((i) => i.severity + ': ' + i.message + ' (' + (i.nodeId || i.edgeId) + ')').join('\n');
}],
['Diff with previous', () => {
clear();
const d = diagram.showDiff(previous);
output.textContent = 'Nodes: added ' + d.addedNodes.length + ', removed ' + d.removedNodes.length + ', changed ' + d.changedNodes.length + '; edges: added ' + d.addedEdges.length + ', removed ' + d.removedEdges.length;
}],
['Clear', clear],
]);
diagram.traceFlow('start', 'down');Simulação de processo
Tokens percorrem o processo; uma etapa com uma fila longa é marcada como gargalo. Pause, avance passo a passo, altere a velocidade ou comece de novo; a lista abaixo do diagrama mostra as etapas mais lentas no final.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const output = document.createElement('div');
output.style.cssText = 'margin-top: 6px; min-height: 40px; font-size: 13px; white-space: pre-wrap';
document.getElementById('app').after(output);
const data = {
nodes: [
{ id: 'in', label: 'Orders', shape: 'ellipse', kind: 'start', x: 0, y: 100, width: 110 },
{ id: 'check', label: 'Check', x: 170, y: 100, width: 120, data: { duration: 600 } },
{ id: 'pack', label: 'Pack (slow)', x: 350, y: 100, width: 120, data: { duration: 2600 } },
{ id: 'ship', label: 'Ship', x: 530, y: 100, width: 120, data: { duration: 700 } },
{ id: 'out', label: 'Done', shape: 'ellipse', kind: 'end', x: 710, y: 100, width: 110 },
],
edges: [
{ source: 'in', target: 'check' }, { source: 'check', target: 'pack' },
{ source: 'pack', target: 'ship' }, { source: 'ship', target: 'out' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
const options = { tokens: 12, interval: 700, seed: 1, speed: 2, autoplay: true };
let sim = diagram.simulate(options);
diagram.on('simulationEnd', (e) => {
output.textContent = 'Done in ' + Math.round(e.stats.time / 1000) + ' s. Bottlenecks: ' + e.bottlenecks.map((b) => diagram.getNode(b.id).label + ' (max queue ' + b.maxQueue + ')').join(', ');
});
addButtons([
['Play', () => sim.play()],
['Pause', () => sim.pause()],
['Step', () => sim.step()],
['Speed ×4', () => sim.setSpeed(8)],
['Restart', () => { output.textContent = ''; sim = diagram.simulate(options); }],
]);Importação e exportação
Arquivos de diagrama
O texto Mermaid da caixa foi importado e organizado. Edite-o e clique em Import, ou escolha um formato e clique em Export para ver o diagrama como Mermaid, BPMN 2.0 XML, GraphML, draw.io ou JSON.
const box = document.createElement('textarea');
box.style.cssText = 'display: block; width: 100%; box-sizing: border-box; height: 120px; font: 12px ui-monospace, Consolas, monospace';
box.value = `flowchart LR
A([Order]) --> B{Paid?}
B -->|yes| C[Ship]
B -->|no| D[Remind]
D --> B
C --> E([Done])`;
const bar = document.createElement('div');
const importButton = document.createElement('button');
importButton.textContent = 'Import';
const format = document.createElement('select');
for (const f of ['mermaid', 'bpmn', 'graphml', 'drawio', 'json']) format.add(new Option(f));
const exportButton = document.createElement('button');
exportButton.textContent = 'Export';
bar.append(importButton, format, exportButton);
document.getElementById('app').before(box, bar);
document.getElementById('app').style.height = '300px';
const diagram = VibeFoxJSDiagram.createDiagram('#app', { minimap: false });
importButton.onclick = async () => {
const info = await diagram.importDiagram(box.value, { mode: 'replace' });
if (info.warnings.length) console.log(info.warnings);
};
exportButton.onclick = async () => { box.value = await diagram.exportDiagram(format.value); };
importButton.onclick();Imagens, PDF e impressão
Os botões baixam o diagrama como SVG, PNG (2×), JSON ou PDF vetorial em uma página A4, ou abrem a caixa de diálogo de impressão. Os arquivos são gerados no navegador.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
addButtons([
['SVG', () => diagram.exportSVG({ filename: 'flow.svg' })],
['PNG', () => diagram.exportPNG({ filename: 'flow.png', scale: 2 })],
['JSON', () => diagram.exportJSON({ filename: 'flow.json' })],
['PDF', () => diagram.exportPDF({ filename: 'flow.pdf', pageSize: 'A4', fit: 'page', header: 'Order flow', pageNumbers: true })],
['Print', () => diagram.print({ fit: 'width' })],
]);Grafos grandes
5.000 nós e 4.900 conectores criados no código. Com este zoom, o nível de detalhe do canvas desenha formas simplificadas; aumente o zoom com a roda e os nós voltam a ser SVG, e somente os visíveis são desenhados.
const nodes = [], edges = [];
const cols = 100;
for (let i = 0; i < 5000; i++) {
nodes.push({ id: 'n' + i, label: 'N' + i, x: (i % cols) * 150, y: Math.floor(i / cols) * 90, width: 110, height: 44 });
if (i % cols) edges.push({ source: 'n' + (i - 1), target: 'n' + i });
else if (i) edges.push({ source: 'n' + (i - cols), target: 'n' + i });
}
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
data: { nodes, edges },
edges: { router: 'straight' },
performance: { virtualize: 'auto' },
});
diagram.setZoom(0.35);
diagram.centerOn('n2550');
const status = document.createElement('div');
document.getElementById('app').after(status);
const count = () => {
status.textContent = 'In the page now: ' + document.querySelectorAll('.vfjs-diagram-node').length + ' node elements of ' + nodes.length + ', zoom ' + diagram.getZoom().toFixed(2);
};
diagram.on('viewportChange', () => setTimeout(count, 300));
setTimeout(count, 300);Colaboração
Dois participantes, Ann (à esquerda) e Ben (à direita), conectados por um pequeno transporte embutido na página que representa o seu WebSocket. Mova, adicione ou renomeie um nó de um lado: ele muda do outro lado; a seleção e o cursor do outro participante são mostrados.
// a stand-in for a server: delivers every message to the other participants after 60 ms
const listeners = new Set();
const transport = () => ({
send: (msg) => { const text = JSON.stringify(msg); for (const fn of listeners) setTimeout(() => fn(JSON.parse(text)), 60); },
onMessage: (fn) => { listeners.add(fn); return () => listeners.delete(fn); },
});
const 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' },
],
};
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 340px';
const sides = [document.createElement('div'), document.createElement('div')];
for (const el of sides) { el.style.cssText = 'flex: 1; min-width: 0; border: 1px solid #d0d7de'; app.append(el); }
const ann = VibeFoxJSDiagram.createDiagram(sides[0], { style: 'flowchart', data, autoFit: true, minimap: false, nodeToolbar: false });
const ben = VibeFoxJSDiagram.createDiagram(sides[1], { style: 'flowchart', data, autoFit: true, minimap: false, nodeToolbar: false });
ann.collaborate({ room: 'flow-42', user: { name: 'Ann' }, transport: transport() });
ben.collaborate({ room: 'flow-42', user: { name: 'Ben' }, transport: transport() });
ann.select(['ship']);
ben.select(['reject']);Do texto ao diagrama e explicações
O diagrama foi criado a partir do texto da caixa pelas regras integradas (sem modelo de linguagem); abaixo dele está o texto de explain(). Altere o texto — setas como A -> B ou frases simples — e clique em Build.
const box = document.createElement('textarea');
box.style.cssText = 'display: block; width: 100%; box-sizing: border-box; height: 64px; font: inherit';
box.value = 'Start, receive the order, check the payment. If paid — ship the order, otherwise send a reminder. End.';
const build = document.createElement('button');
build.textContent = 'Build';
document.getElementById('app').before(box, build);
document.getElementById('app').style.height = '300px';
const explanation = document.createElement('p');
document.getElementById('app').after(explanation);
const diagram = VibeFoxJSDiagram.createDiagram('#app', { minimap: false });
build.onclick = async () => {
await diagram.fromText(box.value, { layout: false });
await diagram.applyLayout('layered', { dir: 'LR', animate: 0 });
diagram.fitToContent(20);
explanation.textContent = diagram.explain();
};
build.onclick();Temas e estilização
Temas
Escolha um tema na lista acima do diagrama: os temas claro, escuro e de alto contraste integrados, ou um tema do pacote (vibefox-js-themes.css vinculado).
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
diagram.select(['check']);
const picker = document.createElement('select');
for (const name of ['light', 'dark', 'high-contrast', 'paper', 'glass', 'ocean', 'forest-dark', 'sunset', 'graphite-dark']) picker.add(new Option(name));
picker.onchange = () => diagram.setTheme(picker.value);
document.getElementById('app').before(picker);Variáveis CSS
A cor de preenchimento dos nós, a espessura e a cor dos conectores, os pontos da grade e a cor da seleção deste diagrama foram alterados com variáveis CSS no seu elemento.
const 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' },
],
};
const app = document.getElementById('app');
app.style.setProperty('--vfjs-diagram-node-fill', '#f0f9ff');
app.style.setProperty('--vfjs-diagram-node-stroke', '#0369a1');
app.style.setProperty('--vfjs-diagram-node-radius', '12px');
app.style.setProperty('--vfjs-diagram-edge-stroke', '#0369a1');
app.style.setProperty('--vfjs-diagram-edge-stroke-width', '2.5px');
app.style.setProperty('--vfjs-diagram-grid-dot', '#bae6fd');
app.style.setProperty('--vfjs-diagram-selection', '#f97316');
const diagram = VibeFoxJSDiagram.createDiagram('#app', { data, autoFit: true, minimap: false });
diagram.select(['ship']);Estilos prontos
Escolha um dos cinco estilos prontos na lista: flowchart, bpmn, org, blueprint ou sketch. Os nós têm tipos (start, decision, process), e os conectores, yes / no.
const 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' },
],
};
data.nodes.push({ id: 'done', label: 'Done', shape: 'ellipse', kind: 'end', x: 640, y: 140 });
data.edges.push({ source: 'ship', target: 'done' }, { source: 'reject', target: 'done' });
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
const picker = document.createElement('select');
for (const name of VibeFoxJSDiagram.DIAGRAM_STYLES) picker.add(new Option(name));
picker.onchange = () => diagram.setStyle(picker.value);
document.getElementById('app').before(picker);Densidade e tamanho
O mesmo diagrama com a paleta em três densidades definidas no contêiner. Escolha compact, normal ou comfortable: a paleta, as portas e as alças mudam de tamanho.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 190px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(panel, canvas);
const 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' },
],
};
app.dataset.vfjsDensity = 'compact';
const diagram = VibeFoxJSDiagram.createDiagram(canvas, { style: 'flowchart', data, autoFit: true, minimap: false });
diagram.mountPalette(panel);
diagram.select(['check']);
const picker = document.createElement('select');
for (const name of ['compact', 'normal', 'comfortable']) picker.add(new Option(name));
picker.onchange = () => { app.dataset.vfjsDensity = picker.value; };
app.before(picker);Seu próprio CSS
Regras CSS próprias superam as regras da biblioteca sem !important (elas estão em @layer vfjs): os nós do tipo risk ficam vermelhos, e todos os rótulos ficam em negrito.
const css = document.createElement('style');
css.textContent = `
.vfjs-diagram [data-kind="risk"] .vfjs-diagram-shape { fill: #fee2e2; stroke: #dc2626; }
.vfjs-diagram-label { font-weight: 600; }`;
document.head.append(css);
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
data: {
nodes: [
{ id: 'a', label: 'Plan', x: 20, y: 60 },
{ id: 'b', label: 'Build', x: 200, y: 60 },
{ id: 'c', label: 'Deadline', kind: 'risk', x: 380, y: 0 },
{ id: 'd', label: 'Budget', kind: 'risk', x: 380, y: 120 },
],
edges: [{ source: 'a', target: 'b' }, { source: 'b', target: 'c' }, { source: 'b', target: 'd' }],
},
autoFit: true,
minimap: false,
});Localização e RTL
Idiomas
O diagrama em russo: carregue o pacote de idioma vibefox-js-diagram.ru.js depois da biblioteca e defina locale: 'ru'. A paleta e o menu de contexto são traduzidos; os rótulos são os seus dados.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 190px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(panel, canvas);
const diagram = VibeFoxJSDiagram.createDiagram(canvas, {
locale: 'ru',
style: 'flowchart',
autoFit: true,
minimap: false,
data: {
nodes: [
{ id: 'a', label: 'Начало', shape: 'ellipse', kind: 'start', x: 20, y: 100 },
{ id: 'b', label: 'Проверка', shape: 'diamond', kind: 'decision', x: 180, y: 80 },
{ id: 'c', label: 'Отгрузка', x: 380, y: 30 },
{ id: 'd', label: 'Отказ', x: 380, y: 170 },
],
edges: [{ source: 'a', target: 'b' }, { source: 'b', target: 'c', label: 'да' }, { source: 'b', target: 'd', label: 'нет' }],
},
});
diagram.mountPalette(panel);
diagram.showContextMenu({ id: 'b' });Adição de um idioma
Um dicionário parcial de alemão adicionado com addLocale(): os textos traduzidos da paleta estão em alemão, e as chaves ausentes recorrem ao inglês.
const app = document.getElementById('app');
app.style.cssText = 'display: flex; gap: 8px; height: 400px';
const panel = document.createElement('div');
panel.style.cssText = 'flex: none; width: 190px; overflow: auto';
const canvas = document.createElement('div');
canvas.style.cssText = 'flex: 1; min-width: 0';
app.append(panel, canvas);
const 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' },
],
};
VibeFoxJSDiagram.addLocale('de', {
diagramSearchShapes: 'Formen suchen…',
diagramShapeRect: 'Rechteck',
diagramShapeRounded: 'Abgerundet',
diagramShapeEllipse: 'Ellipse',
diagramShapeDiamond: 'Entscheidung',
diagramShapeHexagon: 'Sechseck',
diagramShapeCylinder: 'Datenbank',
diagramShapeImage: 'Bild',
diagramShapeGroup: 'Gruppe',
diagramShapeSwimlane: 'Bahn',
});
const diagram = VibeFoxJSDiagram.createDiagram(canvas, { locale: 'de', style: 'flowchart', data, autoFit: true, minimap: false });
diagram.mountPalette(panel);Da direita para a esquerda
A opção rtl: true com rótulos em hebraico: o desenho não é espelhado, mas a interface ao seu redor é — o minimapa fica à esquerda e o menu de contexto abre para a esquerda. Cada rótulo mantém a direção do seu próprio texto, então rótulos latinos e mistos (Order valid?, API v2) também são lidos corretamente.
const data = {
nodes: [
{ id: 'start', label: 'התחלה', shape: 'ellipse', kind: 'start', x: 40, y: 140 },
{ id: 'check', label: 'ההזמנה תקינה?', shape: 'diamond', kind: 'decision', x: 220, y: 120 },
{ id: 'ship', label: 'משלוח', kind: 'process', x: 440, y: 60 },
{ id: 'reject', label: 'דחייה', kind: 'process', x: 440, y: 220 },
{ id: 'valid', label: 'Order valid?', shape: 'diamond', kind: 'decision', x: 640, y: 30 },
{ id: 'api', label: 'שליחה ל-API v2', kind: 'process', x: 640, y: 220 },
],
edges: [
{ source: 'start', target: 'check' },
{ source: 'check', target: 'ship', label: 'כן', kind: 'yes' },
{ source: 'check', target: 'reject', label: 'לא', kind: 'no' },
{ source: 'ship', target: 'valid' },
{ source: 'valid', target: 'api', label: 'yes!', kind: 'yes' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { rtl: true, style: 'flowchart', data, autoFit: true, minimap: true });
diagram.showContextMenu({ id: 'ship' });Acessibilidade
Teclado
O nó Order valid? tem o anel de foco do teclado. Clique no diagrama e use Tab, Alt+setas, as setas para mover um nó, Enter para editar e C para conectar.
const 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' },
],
};
const diagram = VibeFoxJSDiagram.createDiagram('#app', { style: 'flowchart', data, autoFit: true, minimap: false });
diagram.setKeyboardFocus('check', { announce: false });Ferramentas de IA
O ciclo de ferramentas com uma função de modelo substituta no código (o seu modelo entra ali): ele solicita a ferramenta diagram_apply_operations, e a etapa Testing é adicionada depois de Review. Clique em Ask de novo para mais uma etapa, ou em Explain para chamar diagram_explain.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const output = document.createElement('div');
output.style.cssText = 'margin-top: 6px; min-height: 40px; font-size: 13px; white-space: pre-wrap';
document.getElementById('app').after(output);
const diagram = VibeFoxJSDiagram.createDiagram('#app', {
autoFit: true,
minimap: false,
data: {
nodes: [{ id: 'start', label: 'Start', x: 20, y: 80 }, { id: 'review', label: 'Review', x: 200, y: 80 }, { id: 'done', label: 'Done', x: 380, y: 80 }],
edges: [{ source: 'start', target: 'review' }, { source: 'review', target: 'done' }],
},
});
const kit = VibeFoxJSDiagram.createToolKit({ flow: diagram });
// stand-in for your model: the first answer calls a tool, the second one is text
let added = 0;
const model = async (request) => {
if (request.messages.at(-1).role === 'tool') return { text: 'Added.' };
const id = 'step' + ++added, after = added > 1 ? 'step' + (added - 1) : 'review';
return { toolCalls: [{ name: 'flow_diagram_apply_operations', arguments: { ops: [
{ op: 'add', kind: 'node', id, set: { label: added > 1 ? 'Testing ' + added : 'Testing' } },
{ op: 'remove', kind: 'edge', id: diagram.getEdges().find((e) => e.source.node === after).id },
{ op: 'add', kind: 'edge', id: id + 'in', set: { source: after, target: id } },
{ op: 'add', kind: 'edge', id: id + 'out', set: { source: id, target: 'done' } },
] } }] };
};
const ask = async () => {
const answer = await kit.ask('Add a step Testing after Review', { model });
output.textContent = 'Tools: ' + kit.tools().map((t) => t.name).join(', ') + '\nCalls: ' + answer.calls.map((c) => c.name + (c.result.ok ? ' ok' : ' error')).join(', ') + '\nModel: ' + answer.text;
await diagram.applyLayout('layered', { dir: 'LR' });
diagram.fitToContent(30);
};
addButtons([
['Ask', ask],
['Explain', async () => { output.textContent = (await VibeFoxJSDiagram.callTool(diagram, 'diagram_explain', {})).result; }],
]);
ask();