VibeFox JS Diagram — Демо
Швидкий старт
Звичайний HTML
Блок-схема швидкого старту з палітрою фігур ліворуч. Перетягніть фігуру з палітри на діаграму, перетягніть вузол, проведіть ребро від порту вузла, двічі клацніть вузол, щоб редагувати його підпис.
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);Основні поняття
Події
Кожен обробник події отримує один об'єкт payload; список під діаграмою показує останні події. Клацайте, переміщуйте та з'єднуйте вузли, редагуйте підпис або масштабуйте колесом миші.
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');Знімки стану
getState() зберігає масштаб, зсув, виділення та геометрію кожного вузла; setState() відновлює їх. Натисніть Save view, перемістіть кілька вузлів і змініть масштаб, потім натисніть 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)],
]);Відміна та повтор
Кожна правка — один крок відміни; кнопки відстежують подію historyChange. Перемістіть або видаліть вузол, потім відмініть і повторіть дію (також Ctrl+Z та 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();Вузли та ребра
Редагування з коду
Вузол Code review додано, перефарбовано, змінено розмір, повернуто та з'єднано з коду. Натисніть Add a step, щоб додати вузол, з'єднаний з останнім.
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);Взаємодія користувача
Вузол Ship виділено: перетягуйте його квадратні маркери, щоб змінити розмір, і круглий маркер, щоб повернути його (Shift прив'язує кут). Перетягуйте вузли по сітці прив'язки з напрямними вирівнювання, проводьте нове ребро від порту, виділяйте ребро та перетягуйте його кінці, щоб перез'єднати.
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']);Упорядкування
Виділено п'ять вузлів, розміщених випадково. Вирівняйте їх, розподіліть рівномірно або виділіть деякі самостійно (Shift+клік або рамкою виділення на фоні) і впорядкуйте їх.
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()],
]);Ребра, маршрутизація та стрілки
Три маршрутизатори (straight, bezier, ortho, який обходить вузол посередині) і набір наконечників стрілок, зокрема закінчення ER. Перетягніть вузол Obstacle і простежте, як ортогональне ребро його обходить.
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 });Фігури, шаблони та набори фігур
Вбудовані фігури та шаблони
Вбудовані фігури та два вузли, намальовані HTML-шаблоном за їхніми даними ({{data.name}}, заливка прив'язана до data.color). Наведіть курсор на картку людини, щоб побачити її підказку.
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,
});Власні фігури
Дві фігури, додані через registerShape(): ярлик і зірка, кожна — SVG-шлях розміром із вузол. Змініть розмір вузла: контур слідує за новим розміром.
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']);Набори фігур
Процес BPMN 2.0 з набору фігур bpmn з палітрою наборів BPMN, UML і ER ліворуч. Перетягніть фігуру BPMN у пул і з'єднайте її.
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']);Класи UML зі спадкуванням і композицією (kind: 'uml:inheritance' задає стрілку і лінію) та сутності ER із закінченнями «вороняча лапка».
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,
});Мережева діаграма з набору network: пристрої зі значками, зв'язки та лінія 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,
});Контейнери
Дві доріжки та група: дочірні вузли переміщуються разом із контейнером, а контейнер росте, коли дочірній вузол перетягують до його межі. Натисніть Collapse / expand, щоб згорнути групу.
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')]]);Компонування
Один граф і автоматичні варіанти компонування. Оберіть компонування та напрямок: вузли перейдуть на нові місця з анімацією (один крок відміни).
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();Область перегляду
Граф більшого розміру з міні-картою в кутку. Масштабуйте колесом миші або кнопками, перетягуйте фон для панорамування, перетягуйте рамку на міні-карті або центруйте вид на одному вузлі.
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']); }],
]);Інструменти редагування
Палітра
Палітра фігур із пошуком: вбудовані елементи та два власні. Введіть текст у полі пошуку, потім перетягніть елемент на діаграму.
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]));Інспектор властивостей і панель інструментів вузла
Інспектор праворуч показує властивості виділеного вузла, зокрема власне поле Owner; панель інструментів вузла розташована поруч із вузлом. Змініть підпис, кольори або власника; виділіть ребро, щоб змінити його маршрутизатор і стрілки.
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']);Контекстне меню та підказки
Контекстне меню вузла Order valid? з власним пунктом у кінці. Клацніть правою кнопкою миші на вузлі, ребрі або фоні, щоб відкрити їхні меню; наведіть курсор на вузол, щоб побачити його підказку.
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' });Інструменти аналізу
Усе, що досяжне з Start, підсвічується (traceFlow). Перевірте діаграму лінтером (вузол без зв'язків, дубльоване ребро) або покажіть зміни порівняно з попередньою версією.
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');Симуляція процесу
Токени проходять процес; крок із довгою чергою позначається як вузьке місце. Призупиніть, крокуйте, змініть швидкість або запустіть знову; список під діаграмою в кінці показує найповільніші кроки.
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); }],
]);Імпорт та експорт
Файли діаграм
Текст Mermaid з поля імпортовано й автоматично розміщено. Змініть його та натисніть Import, або оберіть формат і натисніть Export, щоб побачити діаграму у форматі Mermaid, BPMN 2.0 XML, GraphML, draw.io або 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();Зображення, PDF і друк
Кнопки завантажують діаграму як SVG, PNG (2×), JSON або векторний PDF на сторінці A4, або відкривають діалог друку. Файли створюються в браузері.
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' })],
]);Великі графи
5 000 вузлів і 4 900 ребер, створених у коді. За цього масштабу рівень деталізації полотна малює спрощені фігури; збільште колесом миші — вузли знову стануть SVG, і будуть намальовані лише видимі.
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);Спільна робота
Два учасники, Ann (ліворуч) і Ben (праворуч), з'єднані невеликим транспортом на сторінці, який замінює ваш WebSocket. Перемістіть, додайте або перейменуйте вузол з одного боку: він зміниться і з іншого; показано виділення та курсор іншого учасника.
// 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']);Текст у діаграму та пояснення
Діаграму побудовано з тексту в полі вбудованими правилами (без мовної моделі); під нею — текст explain(). Змініть текст — стрілки на кшталт A -> B або прості речення — і натисніть 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();Теми та стилізація
Теми
Оберіть тему зі списку над діаграмою: вбудовані світла, темна та з високою контрастністю, або тему з пакета (підключено vibefox-js-themes.css).
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);CSS-змінні
Заливка вузлів, товщина та колір ребер, точки сітки і колір виділення цієї діаграми задано CSS-змінними на її елементі.
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']);Готові стилі
Оберіть один із п'яти готових стилів у списку: flowchart, bpmn, org, blueprint або sketch. Вузли мають типи (start, decision, process), ребра — 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);Щільність і розмір
Та сама діаграма з палітрою в трьох щільностях, заданих на контейнері. Оберіть compact, normal або comfortable: палітра, порти й маркери змінюють розмір.
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);Власний CSS
Власні правила CSS мають перевагу над правилами бібліотеки без !important (вони в @layer vfjs): вузли типу risk червоні, а всі підписи виділено жирним.
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,
});Локалізація та RTL
Мови
Діаграма російською: підключіть мовний пакет vibefox-js-diagram.ru.js після бібліотеки та задайте locale: 'ru'. Палітра й контекстне меню перекладені, підписи — це ваші дані.
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' });Додавання мови
Неповний німецький словник, доданий через addLocale(): перекладені тексти палітри німецькою, а відсутні ключі повертаються до англійської.
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);Справа наліво (RTL)
Опція rtl: true з підписами на івриті: діаграма не віддзеркалюється, а інтерфейс навколо неї — так: міні-карта ліворуч, а контекстне меню відкривається ліворуч. Кожен підпис зберігає напрям свого тексту, тож латинські та змішані підписи (Order valid?, API v2) також читаються правильно.
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' });Доступність
Клавіатура
Вузол Order valid? має фокусну рамку клавіатури. Клацніть діаграму та використовуйте Tab, Alt+стрілки, клавіші зі стрілками для переміщення вузла, Enter для редагування, C для з'єднання.
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 });AI-інструменти
Цикл інструментів із функцією-заглушкою моделі в коді (тут має бути ваша модель): вона запитує інструмент diagram_apply_operations, і крок Testing додається після Review. Натисніть Ask ще раз, щоб додати ще один крок, або Explain, щоб викликати 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();