@luispm/zflow-graph 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +287 -0
- package/SECURITY.md +67 -0
- package/dist/adapters/yjs.esm.js +238 -0
- package/dist/adapters/yjs.esm.min.js +2 -0
- package/dist/adapters/yjs.umd.js +246 -0
- package/dist/webgl-renderer.esm.js +376 -0
- package/dist/webgl-renderer.esm.min.js +2 -0
- package/dist/webgl-renderer.umd.js +384 -0
- package/dist/zflow.esm.js +4365 -0
- package/dist/zflow.esm.js.map +1 -0
- package/dist/zflow.esm.min.js +2 -0
- package/dist/zflow.umd.js +4375 -0
- package/dist/zflow.umd.js.map +1 -0
- package/dist/zflow.umd.min.js +2 -0
- package/dist/zflow.wasm +0 -0
- package/docs/01-getting-started.md +210 -0
- package/docs/02-runtime.md +257 -0
- package/docs/03-kinds.md +282 -0
- package/docs/04-performance.md +218 -0
- package/docs/05-plugins.md +235 -0
- package/docs/06-multiplayer.md +180 -0
- package/docs/07-recipes.md +340 -0
- package/docs/08-api.md +436 -0
- package/docs/README.md +61 -0
- package/package.json +100 -0
|
@@ -0,0 +1,4375 @@
|
|
|
1
|
+
/*! @luispm/zflow-graph v0.1.0 | MIT | (c) 2026 */
|
|
2
|
+
(function (global, factory) {
|
|
3
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
4
|
+
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
|
5
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZFlow = {}));
|
|
6
|
+
})(this, (function (exports) { 'use strict';
|
|
7
|
+
|
|
8
|
+
// zflow — node-edge graph editor library (full version).
|
|
9
|
+
//
|
|
10
|
+
// Single ES module. Consumers do:
|
|
11
|
+
// import { ZFlow } from './dist/zflow.js';
|
|
12
|
+
// const flow = await ZFlow.create({ container, wasmUrl });
|
|
13
|
+
//
|
|
14
|
+
// Wraps a Zig WASM core (~200 KB) and a Canvas2D renderer. JS holds typed-
|
|
15
|
+
// array views over WASM linear memory for zero-copy reads. The memory
|
|
16
|
+
// contract: WASM allocates everything at init time and never grows again,
|
|
17
|
+
// so the views remain valid for the life of the instance.
|
|
18
|
+
|
|
19
|
+
// ── Default kinds shipped with the library ─────────────────────────────────
|
|
20
|
+
// Minimal flow primitives. Consumers extend with registerKind() for domain-
|
|
21
|
+
// specific kinds (service, database, queue, etc.).
|
|
22
|
+
const DEFAULT_KINDS = [
|
|
23
|
+
{ name: 'input', color: '#5b8def', badge: 'I', w: 140, h: 60, nin: 0, nout: 1, shape: 'rect' },
|
|
24
|
+
{ name: 'process', color: '#e8b04b', badge: 'P', w: 160, h: 80, nin: 1, nout: 1, shape: 'rect' },
|
|
25
|
+
{ name: 'filter', color: '#5be0d0', badge: 'F', w: 160, h: 80, nin: 1, nout: 1, shape: 'rect' },
|
|
26
|
+
{ name: 'decision', color: '#c062e8', badge: 'D', w: 130, h: 130, nin: 1, nout: 2, shape: 'diamond' },
|
|
27
|
+
{ name: 'output', color: '#5bd17a', badge: 'O', w: 140, h: 60, nin: 1, nout: 0, shape: 'rect' },
|
|
28
|
+
{ name: 'aggregator', color: '#f0b93a', badge: '∑', w: 160, h: 120, nin: 3, nout: 1, shape: 'hexagon' },
|
|
29
|
+
{ name: 'branch', color: '#e8462b', badge: 'B', w: 130, h: 130, nin: 1, nout: 3, shape: 'ellipse' },
|
|
30
|
+
// Built-in control-flow kinds (execute-enabled).
|
|
31
|
+
{ name: 'if', color: '#c062e8', badge: '?', w: 150, h: 70, nin: 1, nout: 2, shape: 'diamond',
|
|
32
|
+
portIn: ['value'], portOut: ['true', 'false'],
|
|
33
|
+
execute: (ctx, ins) => {
|
|
34
|
+
const v = ins.value ?? ins[0];
|
|
35
|
+
const cond = ctx.params?.condition;
|
|
36
|
+
let ok;
|
|
37
|
+
if (typeof cond === 'function') ok = cond(v);
|
|
38
|
+
else if (typeof cond === 'string') {
|
|
39
|
+
// Serializable: condition is a JS expression where `value` and `v` are bound.
|
|
40
|
+
try { ok = Function('value', 'v', `"use strict"; return (${cond});`)(v, v); }
|
|
41
|
+
catch { ok = false; }
|
|
42
|
+
} else ok = Boolean(v);
|
|
43
|
+
return ok ? { true: v } : { false: v };
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
{ name: 'forEach', color: '#5be0d0', badge: '↻', w: 160, h: 70, nin: 1, nout: 1, shape: 'rect',
|
|
47
|
+
portIn: ['array'], portOut: ['item'],
|
|
48
|
+
execute: async (ctx, ins) => {
|
|
49
|
+
const arr = ins.array ?? ins[0] ?? [];
|
|
50
|
+
if (!Array.isArray(arr) || arr.length === 0) return null;
|
|
51
|
+
for (let i = 0; i < arr.length; i++) {
|
|
52
|
+
if (ctx.signal.aborted) return;
|
|
53
|
+
ctx.setProgress((i + 1) / arr.length);
|
|
54
|
+
ctx.emit({ item: arr[i] });
|
|
55
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
56
|
+
}
|
|
57
|
+
return { item: arr[arr.length - 1] };
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
{ name: 'const', color: '#8b95a7', badge: 'K', w: 130, h: 56, nin: 0, nout: 1, shape: 'rect',
|
|
61
|
+
portOut: ['value'],
|
|
62
|
+
execute: (ctx) => ({ value: ctx.params?.value ?? 0 }),
|
|
63
|
+
},
|
|
64
|
+
{ name: 'log', color: '#5b8def', badge: '◷', w: 160, h: 60, nin: 1, nout: 0, shape: 'rect',
|
|
65
|
+
portIn: ['value'],
|
|
66
|
+
execute: (ctx, ins) => { ctx.log(ins.value ?? ins[0]); return { received: ins.value ?? ins[0] }; },
|
|
67
|
+
},
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
const DARK_THEME = {
|
|
71
|
+
bg: '#07090f', panel: 'rgba(20,28,40,0.92)', border: 'rgba(255,255,255,0.10)',
|
|
72
|
+
fg: '#e6edf3', muted: '#8b95a7', accent: '#f0b93a', hi: 'rgba(240,185,58,0.10)',
|
|
73
|
+
grid: 'rgba(255,255,255,0.04)', gridDot: 'rgba(255,255,255,0.10)',
|
|
74
|
+
};
|
|
75
|
+
const LIGHT_THEME = {
|
|
76
|
+
bg: '#f6f8fb', panel: 'rgba(255,255,255,0.96)', border: 'rgba(0,0,0,0.10)',
|
|
77
|
+
fg: '#1d2330', muted: '#5a6577', accent: '#b8860b', hi: 'rgba(184,134,11,0.12)',
|
|
78
|
+
grid: 'rgba(0,0,0,0.04)', gridDot: 'rgba(0,0,0,0.16)',
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const HANDLE_CORNERS = ['tl', 't', 'tr', 'r', 'br', 'b', 'bl', 'l'];
|
|
82
|
+
const HANDLE_LEFTS = new Set(['l', 'tl', 'bl']);
|
|
83
|
+
const HANDLE_RIGHTS = new Set(['r', 'tr', 'br']);
|
|
84
|
+
const HANDLE_TOPS = new Set(['t', 'tl', 'tr']);
|
|
85
|
+
const HANDLE_BOTS = new Set(['b', 'bl', 'br']);
|
|
86
|
+
const HANDLE_CURSOR = {
|
|
87
|
+
tl: 'nwse-resize', br: 'nwse-resize',
|
|
88
|
+
tr: 'nesw-resize', bl: 'nesw-resize',
|
|
89
|
+
t: 'ns-resize', b: 'ns-resize',
|
|
90
|
+
l: 'ew-resize', r: 'ew-resize',
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
class ZFlow {
|
|
94
|
+
/** Async constructor — loads the WASM and prepares the canvas. */
|
|
95
|
+
static async create(opts) {
|
|
96
|
+
const flow = new ZFlow();
|
|
97
|
+
await flow._init(opts);
|
|
98
|
+
return flow;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ── Lifecycle ─────────────────────────────────────────────────────────
|
|
102
|
+
async _init(opts) {
|
|
103
|
+
if (!opts || !opts.container) throw new Error('zflow: container is required');
|
|
104
|
+
this.container = opts.container;
|
|
105
|
+
this.options = Object.assign({
|
|
106
|
+
theme: 'dark', background: '#07090f',
|
|
107
|
+
edgeStyle: 'bezier', snapToGrid: false, gridSize: 20,
|
|
108
|
+
contextMenu: true, keyboard: true,
|
|
109
|
+
minimap: false, animateEdges: false, edgeFlowSpeed: 60,
|
|
110
|
+
commandPalette: true, search: true, inlineMarkdown: true,
|
|
111
|
+
}, opts);
|
|
112
|
+
this._theme = this.options.theme === 'light' ? LIGHT_THEME : DARK_THEME;
|
|
113
|
+
if (this.options.theme === 'light') this.options.background = this._theme.bg;
|
|
114
|
+
|
|
115
|
+
// Load WASM bytes.
|
|
116
|
+
let wasmBytes;
|
|
117
|
+
if (opts.wasmBytes) {
|
|
118
|
+
wasmBytes = opts.wasmBytes instanceof Uint8Array ? opts.wasmBytes : new Uint8Array(opts.wasmBytes);
|
|
119
|
+
} else if (opts.wasmUrl) {
|
|
120
|
+
wasmBytes = new Uint8Array(await (await fetch(opts.wasmUrl)).arrayBuffer());
|
|
121
|
+
} else {
|
|
122
|
+
throw new Error('zflow: pass either { wasmUrl } or { wasmBytes }');
|
|
123
|
+
}
|
|
124
|
+
const { instance } = await WebAssembly.instantiate(wasmBytes, {});
|
|
125
|
+
this.w = instance.exports;
|
|
126
|
+
if (this.w.init() === 0) throw new Error('zflow: WASM init OOM');
|
|
127
|
+
|
|
128
|
+
const cap = this.w.nodeCap();
|
|
129
|
+
const ecap = this.w.edgeCap();
|
|
130
|
+
this.V = {
|
|
131
|
+
posX: new Float32Array(this.w.memory.buffer, this.w.posXPtr(), cap),
|
|
132
|
+
posY: new Float32Array(this.w.memory.buffer, this.w.posYPtr(), cap),
|
|
133
|
+
sizeW: new Float32Array(this.w.memory.buffer, this.w.sizeWPtr(), cap),
|
|
134
|
+
sizeH: new Float32Array(this.w.memory.buffer, this.w.sizeHPtr(), cap),
|
|
135
|
+
kind: new Uint8Array (this.w.memory.buffer, this.w.kindPtr(), cap),
|
|
136
|
+
nIn: new Uint8Array (this.w.memory.buffer, this.w.nInPtr(), cap),
|
|
137
|
+
nOut: new Uint8Array (this.w.memory.buffer, this.w.nOutPtr(), cap),
|
|
138
|
+
selected: new Uint8Array (this.w.memory.buffer, this.w.selectedPtr(), cap),
|
|
139
|
+
edgeFromN: new Uint32Array (this.w.memory.buffer, this.w.edgeFromNodePtr(), ecap),
|
|
140
|
+
edgeToN: new Uint32Array (this.w.memory.buffer, this.w.edgeToNodePtr(), ecap),
|
|
141
|
+
edgeFromP: new Uint8Array (this.w.memory.buffer, this.w.edgeFromPortPtr(), ecap),
|
|
142
|
+
edgeToP: new Uint8Array (this.w.memory.buffer, this.w.edgeToPortPtr(), ecap),
|
|
143
|
+
edgeSel: new Uint8Array (this.w.memory.buffer, this.w.edgeSelectedPtr(), ecap),
|
|
144
|
+
queryRes: new Uint32Array (this.w.memory.buffer, this.w.queryResultsPtr(), cap),
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// Kinds + per-node JS overlays.
|
|
148
|
+
this.kinds = DEFAULT_KINDS.map((k) => ({ ...k }));
|
|
149
|
+
this.kindByName = new Map();
|
|
150
|
+
this.kinds.forEach((k, i) => this.kindByName.set(k.name, i));
|
|
151
|
+
this.titles = new Map();
|
|
152
|
+
this.colors = new Map();
|
|
153
|
+
this.descriptions = new Map();
|
|
154
|
+
this.tags = new Map();
|
|
155
|
+
this.status = new Map();
|
|
156
|
+
this.progress = new Map();
|
|
157
|
+
this.image = new Map(); // nodeId -> image url
|
|
158
|
+
this.checked = new Map(); // nodeId -> bool (optional checkbox)
|
|
159
|
+
this.tasks = new Map(); // nodeId -> [{text, done}]
|
|
160
|
+
this.icon = new Map(); // nodeId -> emoji/glyph
|
|
161
|
+
this.links = new Map(); // nodeId -> [{ url, label? }]
|
|
162
|
+
this.portIn = new Map(); // nodeId -> string[] (in port labels)
|
|
163
|
+
this.portOut = new Map(); // nodeId -> string[] (out port labels)
|
|
164
|
+
this.zOrder = new Map(); // nodeId -> z (default 0)
|
|
165
|
+
this.bookmarks = new Map(); // slot 1..9 -> nodeId
|
|
166
|
+
this.edgeLabels = new Map();
|
|
167
|
+
this._imageCache = new Map(); // url -> { img, ready }
|
|
168
|
+
this._nodeAddedAt = new Map(); // nodeId -> timestamp (pop animation)
|
|
169
|
+
this._dyingNodes = []; // [{ x,y,w,h,kind,color,t0 }] for fade-out
|
|
170
|
+
this._dyingEdges = [];
|
|
171
|
+
|
|
172
|
+
// Notes (sticky annotations) — JS-only entities.
|
|
173
|
+
this.notes = []; // [{ id, x, y, w, h, text, color }]
|
|
174
|
+
this._noteSeq = 0;
|
|
175
|
+
// Frames (groups) — JS-only entities.
|
|
176
|
+
this.frames = []; // [{ id, x, y, w, h, label, color }]
|
|
177
|
+
this._frameSeq = 0;
|
|
178
|
+
|
|
179
|
+
// Canvas + camera.
|
|
180
|
+
this.canvas = document.createElement('canvas');
|
|
181
|
+
this.canvas.style.cssText = `display:block;width:100%;height:100%;background:${this.options.background};cursor:default;outline:none;touch-action:none;user-select:none;`;
|
|
182
|
+
this.canvas.tabIndex = 0;
|
|
183
|
+
this.container.style.position = this.container.style.position || 'relative';
|
|
184
|
+
this.container.appendChild(this.canvas);
|
|
185
|
+
this.ctx = this.canvas.getContext('2d', { alpha: false });
|
|
186
|
+
this.cam = { x: 0, y: 0, zoom: 1 };
|
|
187
|
+
this._panVel = { x: 0, y: 0, lastTs: 0 };
|
|
188
|
+
this._clipboard = null;
|
|
189
|
+
this._nudgeTimer = null;
|
|
190
|
+
|
|
191
|
+
// Interaction state.
|
|
192
|
+
this.listeners = new Map();
|
|
193
|
+
this._mode = 'idle';
|
|
194
|
+
this._dragStart = null;
|
|
195
|
+
this._dragLast = null;
|
|
196
|
+
this._hoveredNode = -1;
|
|
197
|
+
this._hoveredEdge = -1;
|
|
198
|
+
this._hoveredNodeSince = 0;
|
|
199
|
+
this._previewedNode = -1;
|
|
200
|
+
this._resizingHandle = null;
|
|
201
|
+
this._marquee = null;
|
|
202
|
+
this._lasso = null;
|
|
203
|
+
this._alignGuides = null;
|
|
204
|
+
this._edgeStart = null;
|
|
205
|
+
this._edgeCursor = null;
|
|
206
|
+
this._draggingNote = -1;
|
|
207
|
+
this._noteDragLast = null;
|
|
208
|
+
this._draggingFrame = -1;
|
|
209
|
+
this._frameDragLast = null;
|
|
210
|
+
this._resizingFrame = null;
|
|
211
|
+
this._editingNote = -1;
|
|
212
|
+
this._editingNoteEl = null;
|
|
213
|
+
this._editingTitle = -1;
|
|
214
|
+
this._editingTitleEl = null;
|
|
215
|
+
this._focusFrame = -1; // subflow focus
|
|
216
|
+
this._htmlOverlays = new Map(); // nodeId -> DOM element
|
|
217
|
+
this._previewEl = null;
|
|
218
|
+
this._pathHighlightEnabled = false;
|
|
219
|
+
this._focusedSet = null;
|
|
220
|
+
this._lastFocusComputed = -2;
|
|
221
|
+
|
|
222
|
+
// Right-click menu element (lazy, removed on dispose).
|
|
223
|
+
this._menuEl = null;
|
|
224
|
+
|
|
225
|
+
// ── New: locks, read-only, snap, reachable, presence, palette ─────
|
|
226
|
+
this.locked = new Set(); // nodeId set — drag/resize blocked
|
|
227
|
+
this.readOnly = false;
|
|
228
|
+
this.snapToNodes = true; // edge-alignment magnet to other nodes
|
|
229
|
+
this._reachableSet = null; // Set<nodeId> from setReachableFrom
|
|
230
|
+
this.remoteCursors = new Map(); // userId -> { x, y, name, color, t }
|
|
231
|
+
this._edgeWaypoints = new Map(); // edgeIdx -> [{ x, y }] mid-bends
|
|
232
|
+
this._draggingWaypoint = null; // { edgeIdx, wpIdx }
|
|
233
|
+
this.frameCollapsed = new Set(); // frameIdx set
|
|
234
|
+
this._paletteGhost = null; // DOM element shown while dragging
|
|
235
|
+
|
|
236
|
+
// ── live metrics, animation, search, templates, validation ─────────
|
|
237
|
+
this.metrics = new Map(); // nodeId -> Float32Array rolling window
|
|
238
|
+
this.metricMax = new Map(); // nodeId -> max for normalization
|
|
239
|
+
this._metricCap = 32;
|
|
240
|
+
this.animatedEdges = new Set(); // edgeIdx set for per-edge animation
|
|
241
|
+
this._edgePhase = 0; // global phase for flow particles
|
|
242
|
+
this._connValidator = null; // fn(fromN, fromP, toN, toP) -> bool
|
|
243
|
+
this._templates = new Map(); // name -> { build(flow,x,y) }
|
|
244
|
+
this._searchEl = null; this._searchQuery = ''; this._searchHits = [];
|
|
245
|
+
this._cmdPaletteEl = null;
|
|
246
|
+
this._minimapEl = null; // canvas overlay
|
|
247
|
+
this._minimapCtx = null;
|
|
248
|
+
this._historyThumbs = []; // [{ png, t }] (best-effort)
|
|
249
|
+
if (this.options.minimap) this._setupMinimap();
|
|
250
|
+
|
|
251
|
+
// ── Plugin system ───────────────────────────────────────────────
|
|
252
|
+
this._plugins = [];
|
|
253
|
+
this._hooks = {
|
|
254
|
+
beforeRender: [], afterRender: [],
|
|
255
|
+
onNodeAdd: [], onNodeDelete: [], onEdgeAdd: [],
|
|
256
|
+
onBeforeExec: [], onAfterExec: [],
|
|
257
|
+
onConnect: [], onSelectionChange: [], onChange: [],
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
// ── Graph runtime (opt-in, dormant until first run) ───────────────
|
|
261
|
+
this._values = new Map(); // nodeId -> last output object
|
|
262
|
+
this._running = false;
|
|
263
|
+
this._runAbort = null; // AbortController
|
|
264
|
+
this._runSeq = 0;
|
|
265
|
+
this._runOrder = null; // cached topo order
|
|
266
|
+
this._execHooks = new Map(); // kindIdx -> execute fn
|
|
267
|
+
this._streamSrc = new Map(); // nodeId -> cancel fn
|
|
268
|
+
this._runStepDelay = 250; // ms pause between nodes (visible by default)
|
|
269
|
+
this._valueBubbles = []; // [{ nodeId, text, t0, dur }]
|
|
270
|
+
this._activeEdges = new Map(); // edgeIdx -> expiry timestamp
|
|
271
|
+
this._memoize = false; // skip nodes whose inputs hash unchanged
|
|
272
|
+
this._memoKeys = new Map(); // nodeId -> last hash
|
|
273
|
+
this._retryStats = new Map(); // nodeId -> attempt count for current run
|
|
274
|
+
this.breakpoints = new Set(); // nodeId set — pause before exec
|
|
275
|
+
this._paused = false; // step-through paused state
|
|
276
|
+
this._resumeNext = null; // resolver to continue from paused state
|
|
277
|
+
this._stepMode = false; // true → pause after each node
|
|
278
|
+
this._subflows = new Map(); // kindName -> { nodes, edges, inputs, outputs }
|
|
279
|
+
|
|
280
|
+
this._resize();
|
|
281
|
+
this._resizeObs = new ResizeObserver(() => this._resize());
|
|
282
|
+
this._resizeObs.observe(this.container);
|
|
283
|
+
this._attachEvents();
|
|
284
|
+
if (this.options.keyboard) this._attachKeyboard();
|
|
285
|
+
this._loop();
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
dispose() {
|
|
289
|
+
cancelAnimationFrame(this._raf);
|
|
290
|
+
this._resizeObs?.disconnect();
|
|
291
|
+
this.canvas?.remove();
|
|
292
|
+
this._menuEl?.remove();
|
|
293
|
+
if (this._keyHandler) window.removeEventListener('keydown', this._keyHandler);
|
|
294
|
+
this.listeners.clear();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ── Public mutation API ───────────────────────────────────────────────
|
|
298
|
+
addNode(spec = {}) {
|
|
299
|
+
if (this.readOnly) return -1;
|
|
300
|
+
this._runOrder = null;
|
|
301
|
+
const k = this._resolveKind(spec.kind ?? 'process');
|
|
302
|
+
const cat = this.kinds[k];
|
|
303
|
+
const id = this.w.addNode(
|
|
304
|
+
spec.x ?? 0, spec.y ?? 0,
|
|
305
|
+
spec.w ?? cat.w, spec.h ?? cat.h,
|
|
306
|
+
k, spec.nin ?? cat.nin, spec.nout ?? cat.nout,
|
|
307
|
+
);
|
|
308
|
+
if (id < 0) return -1;
|
|
309
|
+
if (spec.title) this.titles.set(id, spec.title);
|
|
310
|
+
if (spec.color) this.colors.set(id, spec.color);
|
|
311
|
+
if (spec.description) this.descriptions.set(id, spec.description);
|
|
312
|
+
if (spec.tags) this.tags.set(id, spec.tags.slice());
|
|
313
|
+
if (spec.status) this.status.set(id, spec.status);
|
|
314
|
+
if (spec.progress !== undefined) this.progress.set(id, spec.progress);
|
|
315
|
+
if (spec.image) this.image.set(id, spec.image);
|
|
316
|
+
if (spec.checked !== undefined) this.checked.set(id, !!spec.checked);
|
|
317
|
+
if (spec.tasks) this.tasks.set(id, spec.tasks.map((t) => ({ ...t })));
|
|
318
|
+
if (spec.icon) this.icon.set(id, spec.icon);
|
|
319
|
+
if (spec.links) this.links.set(id, spec.links.map((l) => ({ ...l })));
|
|
320
|
+
if (spec.portIn) this.portIn.set(id, spec.portIn.slice());
|
|
321
|
+
if (spec.portOut) this.portOut.set(id, spec.portOut.slice());
|
|
322
|
+
if (spec.animate !== false) this._nodeAddedAt.set(id, performance.now());
|
|
323
|
+
if (this._hooks) this._runHook('onNodeAdd', id, spec);
|
|
324
|
+
this._emit('change');
|
|
325
|
+
return id;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Insert many nodes at once. Skips per-node emit/hook overhead; emits once at end. */
|
|
329
|
+
addNodesBulk(specs) {
|
|
330
|
+
if (this.readOnly) return [];
|
|
331
|
+
this._runOrder = null;
|
|
332
|
+
const ids = new Array(specs.length);
|
|
333
|
+
const wasSilent = this._suspendEvents; this._suspendEvents = true;
|
|
334
|
+
for (let i = 0; i < specs.length; i++) {
|
|
335
|
+
const s = specs[i];
|
|
336
|
+
const k = this._resolveKind(s.kind);
|
|
337
|
+
const id = this.w.addNode(k, s.x ?? 0, s.y ?? 0);
|
|
338
|
+
if (id < 0) { ids[i] = -1; continue; }
|
|
339
|
+
if (s.w !== undefined) this.V.sizeW[id] = s.w;
|
|
340
|
+
if (s.h !== undefined) this.V.sizeH[id] = s.h;
|
|
341
|
+
if (s.title) this.titles.set(id, s.title);
|
|
342
|
+
if (s.color) this.colors.set(id, s.color);
|
|
343
|
+
ids[i] = id;
|
|
344
|
+
}
|
|
345
|
+
this._suspendEvents = wasSilent;
|
|
346
|
+
if (this._gl) this._gl.markAllDirty();
|
|
347
|
+
this._emit('change');
|
|
348
|
+
return ids;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Insert many edges at once. */
|
|
352
|
+
addEdgesBulk(specs) {
|
|
353
|
+
if (this.readOnly) return [];
|
|
354
|
+
this._runOrder = null;
|
|
355
|
+
const ids = new Array(specs.length);
|
|
356
|
+
const wasSilent = this._suspendEvents; this._suspendEvents = true;
|
|
357
|
+
for (let i = 0; i < specs.length; i++) {
|
|
358
|
+
const s = specs[i];
|
|
359
|
+
ids[i] = this.w.addEdge(s.from, s.fp ?? 0, s.to, s.tp ?? 0);
|
|
360
|
+
if (s.label && ids[i] >= 0) this.edgeLabels.set(ids[i], s.label);
|
|
361
|
+
}
|
|
362
|
+
this._suspendEvents = wasSilent;
|
|
363
|
+
if (this._gl) this._gl.markAllDirty();
|
|
364
|
+
this._adjDirty = true;
|
|
365
|
+
this._emit('change');
|
|
366
|
+
return ids;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
addEdge(spec = {}) {
|
|
370
|
+
if (this.readOnly) return -1;
|
|
371
|
+
this._runOrder = null;
|
|
372
|
+
this._adjDirty = true;
|
|
373
|
+
const eid = this.w.addEdge(spec.from, spec.fp ?? 0, spec.to, spec.tp ?? 0);
|
|
374
|
+
if (eid >= 0) {
|
|
375
|
+
if (spec.label) this.edgeLabels.set(eid, spec.label);
|
|
376
|
+
if (this._hooks) this._runHook('onEdgeAdd', eid, spec);
|
|
377
|
+
this._emit('change');
|
|
378
|
+
}
|
|
379
|
+
return eid;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
moveNode(id, x, y) { this.w.moveNode(id, x, y); this._emit('change'); }
|
|
383
|
+
_guardWrite() { return !this.readOnly; }
|
|
384
|
+
|
|
385
|
+
deleteSelection() {
|
|
386
|
+
if (this.readOnly) return;
|
|
387
|
+
this._runOrder = null;
|
|
388
|
+
// Capture dying entities for fade-out before WASM compacts the arrays.
|
|
389
|
+
this._captureDying();
|
|
390
|
+
const n = this.w.deleteSelected();
|
|
391
|
+
if (n > 0) { this.w.snapshot(); this._emit('change'); }
|
|
392
|
+
return n;
|
|
393
|
+
}
|
|
394
|
+
_captureDying() {
|
|
395
|
+
const now = performance.now();
|
|
396
|
+
const nodeWillDie = new Uint8Array(this.w.nodeCount_());
|
|
397
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) if (this.V.selected[i]) nodeWillDie[i] = 1;
|
|
398
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) {
|
|
399
|
+
if (!nodeWillDie[i]) continue;
|
|
400
|
+
const cat = this.kinds[this.V.kind[i]];
|
|
401
|
+
this._dyingNodes.push({
|
|
402
|
+
x: this.V.posX[i], y: this.V.posY[i],
|
|
403
|
+
w: this.V.sizeW[i], h: this.V.sizeH[i],
|
|
404
|
+
shape: cat.shape, color: this.colors.get(i) || cat.color, t0: now,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
for (let e = 0; e < this.w.edgeCount_(); e++) {
|
|
408
|
+
const a = this.V.edgeFromN[e], b = this.V.edgeToN[e];
|
|
409
|
+
if (!this.V.edgeSel[e] && !nodeWillDie[a] && !nodeWillDie[b]) continue;
|
|
410
|
+
const ap = this._portWorld(a, 1, this.V.edgeFromP[e]);
|
|
411
|
+
const bp = this._portWorld(b, 0, this.V.edgeToP[e]);
|
|
412
|
+
this._dyingEdges.push({
|
|
413
|
+
ap, bp,
|
|
414
|
+
colA: this.colors.get(a) || this.kinds[this.V.kind[a]].color,
|
|
415
|
+
colB: this.colors.get(b) || this.kinds[this.V.kind[b]].color,
|
|
416
|
+
t0: now,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
duplicateSelection(dx = 40, dy = 40) {
|
|
421
|
+
const n = this.w.duplicateSelected(dx, dy);
|
|
422
|
+
if (n > 0) { this.w.snapshot(); this._emit('change'); }
|
|
423
|
+
return n;
|
|
424
|
+
}
|
|
425
|
+
setSelected(id, on) { this.w.setSelected(id, on ? 1 : 0); this._emit('select', this.getSelection()); }
|
|
426
|
+
toggleSelected(id) { this.w.toggleSelected(id); this._emit('select', this.getSelection()); }
|
|
427
|
+
clearSelection() { this.w.clearSelection(); this._emit('select', []); }
|
|
428
|
+
selectAll() { this.w.selectAll(); this._emit('select', this.getSelection()); }
|
|
429
|
+
getSelection() {
|
|
430
|
+
const out = [];
|
|
431
|
+
const n = this.w.nodeCount_();
|
|
432
|
+
for (let i = 0; i < n; i++) if (this.V.selected[i]) out.push(i);
|
|
433
|
+
return out;
|
|
434
|
+
}
|
|
435
|
+
nodeCount() { return this.w.nodeCount_(); }
|
|
436
|
+
edgeCount() { return this.w.edgeCount_(); }
|
|
437
|
+
|
|
438
|
+
// ── Per-node setters (public API) ─────────────────────────────────────
|
|
439
|
+
setNodeTitle(id, t) { t ? this.titles.set(id, t) : this.titles.delete(id); this._emit('change'); }
|
|
440
|
+
setNodeColor(id, c) { c ? this.colors.set(id, c) : this.colors.delete(id); this._emit('change'); }
|
|
441
|
+
setNodeDescription(id, d) { d ? this.descriptions.set(id, d) : this.descriptions.delete(id); this._emit('change'); }
|
|
442
|
+
setNodeTags(id, tags) { (tags && tags.length) ? this.tags.set(id, tags.slice()) : this.tags.delete(id); this._emit('change'); }
|
|
443
|
+
setNodeStatus(id, s) { s ? this.status.set(id, s) : this.status.delete(id); this._emit('change'); }
|
|
444
|
+
setNodeProgress(id, p) { (p !== undefined && p !== null) ? this.progress.set(id, p) : this.progress.delete(id); this._emit('change'); }
|
|
445
|
+
setEdgeLabel(eid, label) { label ? this.edgeLabels.set(eid, label) : this.edgeLabels.delete(eid); this._emit('change'); }
|
|
446
|
+
setEdgeStyle(style) { this.options.edgeStyle = style === 'orthogonal' ? 'orthogonal' : 'bezier'; }
|
|
447
|
+
setSnapToGrid(on) { this.options.snapToGrid = !!on; }
|
|
448
|
+
setNodeImage(id, url) { url ? this.image.set(id, url) : this.image.delete(id); this._emit('change'); }
|
|
449
|
+
setNodeChecked(id, on) { on === null || on === undefined ? this.checked.delete(id) : this.checked.set(id, !!on); this._emit('change'); }
|
|
450
|
+
setNodeTasks(id, list) { (list && list.length) ? this.tasks.set(id, list.map((t) => ({ ...t }))) : this.tasks.delete(id); this._emit('change'); }
|
|
451
|
+
setNodeIcon(id, glyph) { glyph ? this.icon.set(id, glyph) : this.icon.delete(id); this._emit('change'); }
|
|
452
|
+
setNodeLinks(id, links) { (links && links.length) ? this.links.set(id, links.map((l) => ({ ...l }))) : this.links.delete(id); this._emit('change'); }
|
|
453
|
+
setPortInLabels(id, arr) { (arr && arr.some(Boolean)) ? this.portIn.set(id, arr.slice()) : this.portIn.delete(id); this._emit('change'); }
|
|
454
|
+
setPortOutLabels(id, arr) { (arr && arr.some(Boolean)) ? this.portOut.set(id, arr.slice()) : this.portOut.delete(id); this._emit('change'); }
|
|
455
|
+
|
|
456
|
+
// ── Z-order ───────────────────────────────────────────────────────────
|
|
457
|
+
_nextZ = 0;
|
|
458
|
+
bringToFront(ids) {
|
|
459
|
+
const sel = ids || this.getSelection();
|
|
460
|
+
for (const i of sel) this.zOrder.set(i, ++this._nextZ);
|
|
461
|
+
}
|
|
462
|
+
sendToBack(ids) {
|
|
463
|
+
const sel = ids || this.getSelection();
|
|
464
|
+
for (const i of sel) this.zOrder.set(i, --this._nextZ);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ── Bookmarks (slots 1..9) ───────────────────────────────────────────
|
|
468
|
+
setBookmark(slot, nodeId) { this.bookmarks.set(slot, nodeId ?? (this.getSelection()[0])); }
|
|
469
|
+
jumpBookmark(slot) {
|
|
470
|
+
const id = this.bookmarks.get(slot);
|
|
471
|
+
if (id === undefined || id >= this.w.nodeCount_()) return;
|
|
472
|
+
this.clearSelection(); this.w.setSelected(id, 1);
|
|
473
|
+
this.panTo(this.V.posX[id], this.V.posY[id]);
|
|
474
|
+
this._emit('select', this.getSelection());
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// ── Hover preview popover (consumer toggles via options.hoverPreview) ──
|
|
478
|
+
setHoverPreview(on) { this.options.hoverPreview = !!on; if (!on) this._hidePreview(); }
|
|
479
|
+
|
|
480
|
+
// ── Plugin API ──────────────────────────────────────────────────────
|
|
481
|
+
/** Install a plugin object with optional lifecycle hooks. Returns dispose fn. */
|
|
482
|
+
use(plugin) {
|
|
483
|
+
if (!plugin) throw new Error('use(plugin): plugin required');
|
|
484
|
+
if (typeof plugin === 'function') plugin = plugin(this) || {};
|
|
485
|
+
this._plugins.push(plugin);
|
|
486
|
+
for (const name of Object.keys(this._hooks)) {
|
|
487
|
+
if (typeof plugin[name] === 'function') this._hooks[name].push(plugin[name]);
|
|
488
|
+
}
|
|
489
|
+
if (typeof plugin.extendAPI === 'function') plugin.extendAPI(this);
|
|
490
|
+
if (typeof plugin.init === 'function') plugin.init(this);
|
|
491
|
+
if (Array.isArray(plugin.kinds)) for (const k of plugin.kinds) this.registerKind(k);
|
|
492
|
+
if (Array.isArray(plugin.commands)) {
|
|
493
|
+
this._extraCommands = (this._extraCommands || []).concat(plugin.commands);
|
|
494
|
+
}
|
|
495
|
+
this._emit('plugin:installed', plugin.name || plugin);
|
|
496
|
+
return () => this._removePlugin(plugin);
|
|
497
|
+
}
|
|
498
|
+
_removePlugin(plugin) {
|
|
499
|
+
const i = this._plugins.indexOf(plugin); if (i === -1) return;
|
|
500
|
+
this._plugins.splice(i, 1);
|
|
501
|
+
for (const name of Object.keys(this._hooks)) {
|
|
502
|
+
if (typeof plugin[name] === 'function') {
|
|
503
|
+
const arr = this._hooks[name];
|
|
504
|
+
const j = arr.indexOf(plugin[name]);
|
|
505
|
+
if (j !== -1) arr.splice(j, 1);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (typeof plugin.dispose === 'function') plugin.dispose(this);
|
|
509
|
+
}
|
|
510
|
+
_runHook(name, ...args) {
|
|
511
|
+
const arr = this._hooks[name]; if (!arr || !arr.length) return null;
|
|
512
|
+
let result;
|
|
513
|
+
for (const fn of arr) {
|
|
514
|
+
try { const r = fn(this, ...args); if (r === false) return false; if (r !== undefined) result = r; }
|
|
515
|
+
catch (e) { console.error(`plugin ${name} hook error`, e); }
|
|
516
|
+
}
|
|
517
|
+
return result;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// ── WebGL renderer (opt-in, hybrid: GL bodies + Canvas2D text overlay) ─
|
|
521
|
+
async enableWebGL(force = false) {
|
|
522
|
+
if (this._gl) return true;
|
|
523
|
+
if (!force && this.w.nodeCount_() < (this.options.webglThreshold || 2000)) return false;
|
|
524
|
+
try {
|
|
525
|
+
const mod = await Promise.resolve().then(function () { return webglRenderer; });
|
|
526
|
+
this._gl = new mod.WebGLRenderer(this);
|
|
527
|
+
if (this._gl.disabled) { this._gl = null; return false; }
|
|
528
|
+
this.options.renderer = 'webgl';
|
|
529
|
+
this._emit('renderer', 'webgl');
|
|
530
|
+
return true;
|
|
531
|
+
} catch (e) {
|
|
532
|
+
console.warn('zflow: WebGL renderer failed', e);
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
disableWebGL() {
|
|
537
|
+
if (!this._gl) return;
|
|
538
|
+
this._gl.dispose();
|
|
539
|
+
this._gl = null;
|
|
540
|
+
this.canvas.style.background = this.options.background;
|
|
541
|
+
this.canvas.style.zIndex = '';
|
|
542
|
+
this.canvas.style.position = '';
|
|
543
|
+
this.options.renderer = 'canvas2d';
|
|
544
|
+
this._emit('renderer', 'canvas2d');
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// ── Graph execution runtime ──────────────────────────────────────────
|
|
548
|
+
// Each kind may register an `execute(ctx, inputs) -> outputs | Promise`.
|
|
549
|
+
// The scheduler walks the graph in topological order, gathering inputs
|
|
550
|
+
// from upstream outputs via the edge connectivity. Status / progress /
|
|
551
|
+
// sparkline are updated automatically so the UI shows the run live.
|
|
552
|
+
|
|
553
|
+
/** Set how long the runtime pauses between nodes so propagation is visible. */
|
|
554
|
+
setRunStepDelay(ms) { this._runStepDelay = Math.max(0, ms|0); }
|
|
555
|
+
|
|
556
|
+
/** Enable input memoization globally — re-runs skip nodes whose inputs match the previous tick. */
|
|
557
|
+
setMemoization(on) { this._memoize = !!on; if (!on) this._memoKeys?.clear(); }
|
|
558
|
+
|
|
559
|
+
/** Evaluate an expression like "{{node_3.value}} * 2" against current runtime values. */
|
|
560
|
+
// ── Schema / type validation ────────────────────────────────────────
|
|
561
|
+
/** Returns null if the connection is OK, or a string reason if not. */
|
|
562
|
+
validateConnection(fromN, fromP, toN, toP) {
|
|
563
|
+
if (fromN === toN) return 'self-loop';
|
|
564
|
+
const fromCat = this.kinds[this.V.kind[fromN]];
|
|
565
|
+
const toCat = this.kinds[this.V.kind[toN]];
|
|
566
|
+
const outSchema = fromCat.outputs?.[fromP];
|
|
567
|
+
const inSchema = toCat.inputs?.[toP];
|
|
568
|
+
if (outSchema && inSchema) {
|
|
569
|
+
if (!isCompatibleType(outSchema.type, inSchema.type)) {
|
|
570
|
+
return `type mismatch: ${outSchema.type} → ${inSchema.type}`;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (this._connValidator) {
|
|
574
|
+
const v = this._connValidator(fromN, fromP, toN, toP);
|
|
575
|
+
if (v === false) return 'rejected by validator';
|
|
576
|
+
}
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// ── Inline expression editor with autocomplete ────────────────────
|
|
581
|
+
/** Open an inline editor that accepts {{node_X.field}} expressions with live preview. */
|
|
582
|
+
editNodeExpression(nodeId, field = 'title') {
|
|
583
|
+
if (this._exprEditorEl) this._closeExprEditor();
|
|
584
|
+
const cur = field === 'title' ? (this.titles.get(nodeId) || '')
|
|
585
|
+
: field === 'desc' ? (this.descriptions.get(nodeId) || '')
|
|
586
|
+
: '';
|
|
587
|
+
const wrap = document.createElement('div');
|
|
588
|
+
wrap.style.cssText = `position:absolute;z-index:600;background:#161b27;border:1px solid #f0b93a;border-radius:6px;box-shadow:0 8px 24px rgba(0,0,0,0.5);font-family:Inter, ui-sans-serif;font-size:12px;color:#e6edf3;width:280px;`;
|
|
589
|
+
wrap.innerHTML = `
|
|
590
|
+
<input id="zf-expr" type="text" style="width:260px;padding:8px 10px;background:transparent;border:0;color:#e6edf3;outline:none;font-family:ui-monospace,Consolas,monospace;font-size:12px;">
|
|
591
|
+
<div id="zf-expr-preview" style="padding:4px 10px;border-top:1px solid rgba(255,255,255,0.08);color:#5be0d0;font-family:ui-monospace,Consolas,monospace;font-size:11px;min-height:14px;"></div>
|
|
592
|
+
<div id="zf-expr-list" style="max-height:160px;overflow:auto;border-top:1px solid rgba(255,255,255,0.08);display:none;"></div>`;
|
|
593
|
+
this.container.appendChild(wrap);
|
|
594
|
+
this._exprEditorEl = wrap;
|
|
595
|
+
const cx = this.V.posX[nodeId], cy = this.V.posY[nodeId];
|
|
596
|
+
const hh = this.V.sizeH[nodeId] * 0.5;
|
|
597
|
+
const tl = this._w2s(cx - this.V.sizeW[nodeId] * 0.5, cy - hh);
|
|
598
|
+
const dpr = window.devicePixelRatio || 1;
|
|
599
|
+
wrap.style.left = (tl.x / dpr) + 'px';
|
|
600
|
+
wrap.style.top = Math.max(8, tl.y / dpr - 110) + 'px';
|
|
601
|
+
const input = wrap.querySelector('#zf-expr');
|
|
602
|
+
const list = wrap.querySelector('#zf-expr-list');
|
|
603
|
+
const prev = wrap.querySelector('#zf-expr-preview');
|
|
604
|
+
input.value = cur;
|
|
605
|
+
const refreshPreview = () => {
|
|
606
|
+
try { const r = this.evalExpression(input.value); prev.style.color = '#5be0d0'; prev.textContent = '= ' + formatRuntimeValue(r); }
|
|
607
|
+
catch (e) { prev.style.color = '#e8462b'; prev.textContent = String(e.message || e); }
|
|
608
|
+
};
|
|
609
|
+
const refreshSuggestions = () => {
|
|
610
|
+
const pos = input.selectionStart;
|
|
611
|
+
const m = input.value.slice(0, pos).match(/\{\{\s*([\w_.]*)$/);
|
|
612
|
+
if (!m) { list.style.display = 'none'; return; }
|
|
613
|
+
const prefix = m[1].toLowerCase();
|
|
614
|
+
const candidates = [];
|
|
615
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) {
|
|
616
|
+
if (i === nodeId) continue;
|
|
617
|
+
const title = this.titles.get(i) || this.kinds[this.V.kind[i]].name;
|
|
618
|
+
const val = this._values.get(i);
|
|
619
|
+
const expansions = (val && typeof val === 'object') ? Object.keys(val).map((k) => `node_${i}.${k}`) : [`node_${i}`];
|
|
620
|
+
for (const c of expansions) if (c.toLowerCase().startsWith(prefix)) candidates.push({ text: c, label: `${c} · ${title}` });
|
|
621
|
+
}
|
|
622
|
+
if (!candidates.length) { list.style.display = 'none'; return; }
|
|
623
|
+
list.style.display = 'block';
|
|
624
|
+
list._items = candidates.slice(0, 8);
|
|
625
|
+
list._cursor = 0;
|
|
626
|
+
list.innerHTML = list._items.map((c, i) =>
|
|
627
|
+
`<div data-i="${i}" data-text="${escapeHtml(c.text)}" style="padding:6px 10px;cursor:pointer;${i === 0 ? 'background:rgba(240,185,58,0.18);' : ''}">${escapeHtml(c.label)}</div>`).join('');
|
|
628
|
+
};
|
|
629
|
+
const insert = (txt) => {
|
|
630
|
+
const pos = input.selectionStart;
|
|
631
|
+
const before = input.value.slice(0, pos).replace(/\{\{\s*[\w_.]*$/, '{{') + txt + '}}';
|
|
632
|
+
input.value = before + input.value.slice(pos);
|
|
633
|
+
input.selectionStart = input.selectionEnd = before.length;
|
|
634
|
+
refreshPreview(); list.style.display = 'none';
|
|
635
|
+
};
|
|
636
|
+
const updateHi = () => list.querySelectorAll('[data-i]').forEach((r, i) =>
|
|
637
|
+
r.style.background = i === list._cursor ? 'rgba(240,185,58,0.18)' : 'transparent');
|
|
638
|
+
input.addEventListener('input', () => { refreshPreview(); refreshSuggestions(); });
|
|
639
|
+
input.addEventListener('keydown', (e) => {
|
|
640
|
+
const open = list.style.display !== 'none' && list._items;
|
|
641
|
+
if (open && e.code === 'ArrowDown') { list._cursor = (list._cursor + 1) % list._items.length; updateHi(); e.preventDefault(); return; }
|
|
642
|
+
if (open && e.code === 'ArrowUp') { list._cursor = (list._cursor - 1 + list._items.length) % list._items.length; updateHi(); e.preventDefault(); return; }
|
|
643
|
+
if (open && (e.code === 'Tab' || e.code === 'Enter')) { insert(list._items[list._cursor].text); e.preventDefault(); return; }
|
|
644
|
+
if (e.code === 'Enter') {
|
|
645
|
+
if (field === 'title') this.setNodeTitle(nodeId, input.value);
|
|
646
|
+
else if (field === 'desc') this.setNodeDescription(nodeId, input.value);
|
|
647
|
+
this._closeExprEditor();
|
|
648
|
+
}
|
|
649
|
+
if (e.code === 'Escape') this._closeExprEditor();
|
|
650
|
+
});
|
|
651
|
+
list.addEventListener('mousedown', (e) => {
|
|
652
|
+
const r = e.target.closest('[data-i]'); if (!r) return;
|
|
653
|
+
insert(r.dataset.text); input.focus(); e.preventDefault();
|
|
654
|
+
});
|
|
655
|
+
setTimeout(() => { input.focus(); input.select(); refreshPreview(); }, 10);
|
|
656
|
+
// Click outside closes the editor.
|
|
657
|
+
const closeOnOutside = (e) => {
|
|
658
|
+
if (this._exprEditorEl && !this._exprEditorEl.contains(e.target)) { this._closeExprEditor(); }
|
|
659
|
+
};
|
|
660
|
+
setTimeout(() => document.addEventListener('mousedown', closeOnOutside, { once: false }), 60);
|
|
661
|
+
this._exprEditorEl._cleanup = () => document.removeEventListener('mousedown', closeOnOutside);
|
|
662
|
+
}
|
|
663
|
+
_closeExprEditor() {
|
|
664
|
+
if (this._exprEditorEl) {
|
|
665
|
+
this._exprEditorEl._cleanup?.();
|
|
666
|
+
this._exprEditorEl.remove();
|
|
667
|
+
this._exprEditorEl = null;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
evalExpression(expr, extraScope = {}) {
|
|
672
|
+
if (typeof expr !== 'string') return expr;
|
|
673
|
+
const interp = expr.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_, path) => {
|
|
674
|
+
const [head, ...rest] = path.split('.');
|
|
675
|
+
let v;
|
|
676
|
+
if (/^node_(\d+)$/.test(head)) v = this._values.get(parseInt(head.slice(5), 10));
|
|
677
|
+
else if (head in extraScope) v = extraScope[head];
|
|
678
|
+
else return 'null';
|
|
679
|
+
for (const seg of rest) v = (v == null) ? undefined : v[seg];
|
|
680
|
+
return JSON.stringify(v ?? null);
|
|
681
|
+
});
|
|
682
|
+
if (interp === expr) return expr;
|
|
683
|
+
try { return Function(`"use strict"; return (${interp})`)(); }
|
|
684
|
+
catch { return interp; }
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Inject or replace the execute fn for a kind. Returns the previous fn. */
|
|
688
|
+
setKindExecutor(kindName, fn) {
|
|
689
|
+
const k = this.kindByName.get(kindName);
|
|
690
|
+
if (k === undefined) throw new Error(`unknown kind: ${kindName}`);
|
|
691
|
+
const prev = this.kinds[k].execute;
|
|
692
|
+
this.kinds[k].execute = fn;
|
|
693
|
+
this._runOrder = null;
|
|
694
|
+
return prev;
|
|
695
|
+
}
|
|
696
|
+
/** Force a specific input value for a node (useful for source nodes). */
|
|
697
|
+
setNodeInput(nodeId, outputs) {
|
|
698
|
+
this._values.set(nodeId, outputs);
|
|
699
|
+
this.setNodeStatus(nodeId, 'ok');
|
|
700
|
+
}
|
|
701
|
+
getNodeValue(nodeId) { return this._values.get(nodeId); }
|
|
702
|
+
clearRuntimeState() {
|
|
703
|
+
this._values.clear();
|
|
704
|
+
for (const sc of this._streamSrc.values()) try { sc(); } catch {}
|
|
705
|
+
this._streamSrc.clear();
|
|
706
|
+
const n = this.w.nodeCount_();
|
|
707
|
+
for (let i = 0; i < n; i++) { this.status.delete(i); this.progress.delete(i); }
|
|
708
|
+
this._emit('change');
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** Returns [nodeIds] in topological order, ignoring cycles. */
|
|
712
|
+
_topoOrder() {
|
|
713
|
+
if (this._runOrder) return this._runOrder;
|
|
714
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
715
|
+
const indeg = new Int32Array(n);
|
|
716
|
+
const out = Array.from({ length: n }, () => []);
|
|
717
|
+
for (let i = 0; i < m; i++) {
|
|
718
|
+
const a = this.V.edgeFromN[i], b = this.V.edgeToN[i];
|
|
719
|
+
if (a !== b) { indeg[b]++; out[a].push({ to: b, fp: this.V.edgeFromP[i], tp: this.V.edgeToP[i], idx: i }); }
|
|
720
|
+
}
|
|
721
|
+
const q = [];
|
|
722
|
+
for (let i = 0; i < n; i++) if (indeg[i] === 0) q.push(i);
|
|
723
|
+
const order = [];
|
|
724
|
+
while (q.length) {
|
|
725
|
+
const u = q.shift();
|
|
726
|
+
order.push(u);
|
|
727
|
+
for (const e of out[u]) if (--indeg[e.to] === 0) q.push(e.to);
|
|
728
|
+
}
|
|
729
|
+
// Cycle nodes: append in id order so they still get a chance to run once.
|
|
730
|
+
if (order.length < n) {
|
|
731
|
+
const seen = new Set(order);
|
|
732
|
+
for (let i = 0; i < n; i++) if (!seen.has(i)) order.push(i);
|
|
733
|
+
}
|
|
734
|
+
this._runOrder = order;
|
|
735
|
+
this._runOut = out;
|
|
736
|
+
return order;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** Gather inputs for a node by reading upstream node outputs through edges. */
|
|
740
|
+
_gatherInputs(nodeId) {
|
|
741
|
+
const inputs = {};
|
|
742
|
+
const cat = this.kinds[this.V.kind[nodeId]];
|
|
743
|
+
const portLabels = this.portIn.get(nodeId) || cat.portIn || [];
|
|
744
|
+
const m = this.w.edgeCount_();
|
|
745
|
+
for (let i = 0; i < m; i++) {
|
|
746
|
+
if (this.V.edgeToN[i] !== nodeId) continue;
|
|
747
|
+
const tp = this.V.edgeToP[i];
|
|
748
|
+
const src = this.V.edgeFromN[i], sp = this.V.edgeFromP[i];
|
|
749
|
+
const srcOut = this._values.get(src);
|
|
750
|
+
if (srcOut === undefined) continue;
|
|
751
|
+
let val;
|
|
752
|
+
if (srcOut && typeof srcOut === 'object' && !Array.isArray(srcOut)) {
|
|
753
|
+
const srcCat = this.kinds[this.V.kind[src]];
|
|
754
|
+
const srcPortLabels = this.portOut.get(src) || srcCat.portOut || [];
|
|
755
|
+
const key = srcPortLabels[sp];
|
|
756
|
+
// Conditional routing: if the source declared labeled outputs and THIS
|
|
757
|
+
// branch's labeled key isn't present, the branch didn't fire — skip.
|
|
758
|
+
if (key) {
|
|
759
|
+
if (!(key in srcOut)) continue;
|
|
760
|
+
val = srcOut[key];
|
|
761
|
+
} else if (sp in srcOut) val = srcOut[sp];
|
|
762
|
+
else if ('value' in srcOut) val = srcOut.value;
|
|
763
|
+
else if ('out' in srcOut) val = srcOut.out;
|
|
764
|
+
else val = srcOut;
|
|
765
|
+
if (val === undefined) continue;
|
|
766
|
+
} else val = srcOut;
|
|
767
|
+
const tkey = portLabels[tp] || `in${tp}`;
|
|
768
|
+
inputs[tkey] = val;
|
|
769
|
+
inputs[tp] = val;
|
|
770
|
+
}
|
|
771
|
+
return inputs;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** All transitive successors of nodeId in topological order. */
|
|
775
|
+
_collectDownstream(nodeId) {
|
|
776
|
+
const m = this.w.edgeCount_();
|
|
777
|
+
const out = [];
|
|
778
|
+
const seen = new Set();
|
|
779
|
+
const order = this._topoOrder();
|
|
780
|
+
const indexOf = new Map(order.map((id, i) => [id, i]));
|
|
781
|
+
const stack = [nodeId];
|
|
782
|
+
while (stack.length) {
|
|
783
|
+
const u = stack.pop();
|
|
784
|
+
for (let i = 0; i < m; i++) {
|
|
785
|
+
if (this.V.edgeFromN[i] === u && !seen.has(this.V.edgeToN[i])) {
|
|
786
|
+
seen.add(this.V.edgeToN[i]); out.push(this.V.edgeToN[i]); stack.push(this.V.edgeToN[i]);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
out.sort((a, b) => indexOf.get(a) - indexOf.get(b));
|
|
791
|
+
return out;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** Topological run of the whole graph (or from a starting subgraph). */
|
|
795
|
+
async run({ from = null, signal = null, filter = null } = {}) {
|
|
796
|
+
if (this._running) return;
|
|
797
|
+
this._running = true;
|
|
798
|
+
const mySeq = ++this._runSeq;
|
|
799
|
+
const ac = new AbortController();
|
|
800
|
+
this._runAbort = ac;
|
|
801
|
+
if (signal) signal.addEventListener('abort', () => ac.abort());
|
|
802
|
+
|
|
803
|
+
this._topoOrder();
|
|
804
|
+
let order = this._runOrder;
|
|
805
|
+
if (from !== null) {
|
|
806
|
+
const reach = new Set([from]); const q = [from];
|
|
807
|
+
while (q.length) {
|
|
808
|
+
const u = q.shift();
|
|
809
|
+
for (const e of this._runOut[u]) if (!reach.has(e.to)) { reach.add(e.to); q.push(e.to); }
|
|
810
|
+
}
|
|
811
|
+
order = order.filter((id) => reach.has(id));
|
|
812
|
+
}
|
|
813
|
+
if (typeof filter === 'function') order = order.filter(filter);
|
|
814
|
+
|
|
815
|
+
const result = { executed: 0, errors: [], values: new Map() };
|
|
816
|
+
this._emit('run:start', { order });
|
|
817
|
+
|
|
818
|
+
for (const id of order) {
|
|
819
|
+
if (ac.signal.aborted || mySeq !== this._runSeq) break;
|
|
820
|
+
const cat = this.kinds[this.V.kind[id]];
|
|
821
|
+
const exec = cat.execute;
|
|
822
|
+
if (typeof exec !== 'function') {
|
|
823
|
+
if (!this._values.has(id)) continue;
|
|
824
|
+
result.values.set(id, this._values.get(id));
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
const inputs = this._gatherInputs(id);
|
|
828
|
+
// Conditional-routing skip: if this node has declared inputs but no
|
|
829
|
+
// upstream supplied any (because the parent emitted on a different branch),
|
|
830
|
+
// skip exec entirely — the dead branch shouldn't fire.
|
|
831
|
+
if (cat.nin > 0 && Object.keys(inputs).length === 0) {
|
|
832
|
+
// Only skip if there is at least one incoming edge in the graph (else
|
|
833
|
+
// it's just a disconnected node and should still run if explicitly invoked).
|
|
834
|
+
let hasIncoming = false;
|
|
835
|
+
const m2 = this.w.edgeCount_();
|
|
836
|
+
for (let e = 0; e < m2; e++) if (this.V.edgeToN[e] === id) { hasIncoming = true; break; }
|
|
837
|
+
if (hasIncoming) continue;
|
|
838
|
+
}
|
|
839
|
+
// Memoization — skip if inputs hash unchanged (FNV-1a 32-bit, no JSON cost).
|
|
840
|
+
if (this._memoize) {
|
|
841
|
+
const hash = fnvHash(inputs);
|
|
842
|
+
if (this._memoKeys.get(id) === hash && this._values.has(id)) {
|
|
843
|
+
result.executed++;
|
|
844
|
+
this._emit('node:cached', { id });
|
|
845
|
+
continue;
|
|
846
|
+
}
|
|
847
|
+
this._memoKeys.set(id, hash);
|
|
848
|
+
}
|
|
849
|
+
// Light up the incoming edges so the user sees the data path.
|
|
850
|
+
const m2 = this.w.edgeCount_();
|
|
851
|
+
for (let e = 0; e < m2; e++) {
|
|
852
|
+
if (this.V.edgeToN[e] === id && this._values.has(this.V.edgeFromN[e])) {
|
|
853
|
+
this._activeEdges.set(e, performance.now() + 800);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
this.setNodeStatus(id, 'running');
|
|
857
|
+
this.setNodeProgress(id, 0);
|
|
858
|
+
this._emit('node:exec', { id, inputs });
|
|
859
|
+
if (this._hooks) {
|
|
860
|
+
const r = this._runHook('onBeforeExec', id, inputs);
|
|
861
|
+
if (r === false) { this.setNodeStatus(id, 'idle'); continue; }
|
|
862
|
+
}
|
|
863
|
+
// Breakpoint / step pause.
|
|
864
|
+
if (this.breakpoints.has(id) || this._stepMode) {
|
|
865
|
+
await this._awaitContinue(id);
|
|
866
|
+
if (ac.signal.aborted || mySeq !== this._runSeq) break;
|
|
867
|
+
}
|
|
868
|
+
if (this._runStepDelay > 0) {
|
|
869
|
+
await new Promise((r) => setTimeout(r, this._runStepDelay));
|
|
870
|
+
if (ac.signal.aborted || mySeq !== this._runSeq) break;
|
|
871
|
+
}
|
|
872
|
+
const ctx = {
|
|
873
|
+
nodeId: id,
|
|
874
|
+
signal: ac.signal,
|
|
875
|
+
params: this._nodeParams?.get(id) || {},
|
|
876
|
+
emit: (out) => { this._values.set(id, out); this._emit('node:emit', { id, outputs: out }); if (typeof out === 'number') this.pushNodeMetric(id, out); },
|
|
877
|
+
log: (...args) => this._emit('node:log', { id, args }),
|
|
878
|
+
setProgress: (p) => this.setNodeProgress(id, p),
|
|
879
|
+
metric: (v) => this.pushNodeMetric(id, v),
|
|
880
|
+
get: (otherId) => this._values.get(otherId),
|
|
881
|
+
};
|
|
882
|
+
const retryCfg = cat.retry || null;
|
|
883
|
+
const maxAttempts = retryCfg ? (retryCfg.n ?? 3) : 1;
|
|
884
|
+
const retryDelay = retryCfg ? (retryCfg.delay ?? 100) : 0;
|
|
885
|
+
let attempt = 0, out, lastErr = null, succeeded = false;
|
|
886
|
+
while (attempt < maxAttempts) {
|
|
887
|
+
attempt++;
|
|
888
|
+
this._retryStats.set(id, attempt);
|
|
889
|
+
try {
|
|
890
|
+
const outRaw = exec(ctx, inputs);
|
|
891
|
+
// Async generator → stream multiple emissions.
|
|
892
|
+
if (outRaw && typeof outRaw[Symbol.asyncIterator] === 'function') {
|
|
893
|
+
// For each emission, propagate through downstream chain synchronously
|
|
894
|
+
// before yielding the next. That way "stream → double → sink" really
|
|
895
|
+
// shows 5 ticks down the pipe instead of one.
|
|
896
|
+
let lastEmission;
|
|
897
|
+
const downstream = this._collectDownstream(id);
|
|
898
|
+
for await (const emission of outRaw) {
|
|
899
|
+
if (ac.signal.aborted) break;
|
|
900
|
+
lastEmission = emission;
|
|
901
|
+
this._values.set(id, emission);
|
|
902
|
+
this._emit('node:emit', { id, outputs: emission });
|
|
903
|
+
if (typeof emission === 'number') this.pushNodeMetric(id, emission);
|
|
904
|
+
this._valueBubbles.push({ nodeId: id, text: bubbleSummary(emission), t0: performance.now(), dur: 700 });
|
|
905
|
+
// Propagate through downstream nodes (skip if they have their own execute that should wait for full stream).
|
|
906
|
+
for (const dId of downstream) {
|
|
907
|
+
if (ac.signal.aborted) break;
|
|
908
|
+
const dCat = this.kinds[this.V.kind[dId]];
|
|
909
|
+
if (typeof dCat.execute !== 'function') continue;
|
|
910
|
+
if (dCat.execute.constructor.name === 'AsyncGeneratorFunction') continue;
|
|
911
|
+
const dIns = this._gatherInputs(dId);
|
|
912
|
+
// Light up the edge feeding this downstream node.
|
|
913
|
+
const m2b = this.w.edgeCount_();
|
|
914
|
+
for (let e = 0; e < m2b; e++) {
|
|
915
|
+
if (this.V.edgeToN[e] === dId && this.V.edgeFromN[e] === id) {
|
|
916
|
+
this._activeEdges.set(e, performance.now() + 500);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
this.setNodeStatus(dId, 'running');
|
|
920
|
+
try {
|
|
921
|
+
const dRaw = dCat.execute({ ...ctx, nodeId: dId, params: this._nodeParams?.get(dId) || {} }, dIns);
|
|
922
|
+
const dOut = (dRaw && typeof dRaw.then === 'function') ? await dRaw : dRaw;
|
|
923
|
+
if (dOut !== undefined && dOut !== null) {
|
|
924
|
+
this._values.set(dId, dOut);
|
|
925
|
+
this._emit('node:emit', { id: dId, outputs: dOut });
|
|
926
|
+
this._valueBubbles.push({ nodeId: dId, text: bubbleSummary(dOut), t0: performance.now(), dur: 700 });
|
|
927
|
+
if (typeof dOut === 'number') this.pushNodeMetric(dId, dOut);
|
|
928
|
+
}
|
|
929
|
+
this.setNodeStatus(dId, 'ok');
|
|
930
|
+
} catch (e) { this.setNodeStatus(dId, 'error'); }
|
|
931
|
+
}
|
|
932
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
933
|
+
}
|
|
934
|
+
out = lastEmission;
|
|
935
|
+
} else {
|
|
936
|
+
out = (outRaw && typeof outRaw.then === 'function') ? await outRaw : outRaw;
|
|
937
|
+
}
|
|
938
|
+
if (ac.signal.aborted || mySeq !== this._runSeq) break;
|
|
939
|
+
succeeded = true; lastErr = null; break;
|
|
940
|
+
} catch (err) {
|
|
941
|
+
lastErr = err;
|
|
942
|
+
this._emit('node:retry', { id, attempt, error: err });
|
|
943
|
+
if (attempt < maxAttempts) await new Promise((r) => setTimeout(r, retryDelay));
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
try {
|
|
947
|
+
if (!succeeded) throw lastErr;
|
|
948
|
+
if (ac.signal.aborted || mySeq !== this._runSeq) break;
|
|
949
|
+
if (out !== undefined && out !== null) {
|
|
950
|
+
this._values.set(id, out);
|
|
951
|
+
result.values.set(id, out);
|
|
952
|
+
// Show a floating value bubble above the node.
|
|
953
|
+
let summary;
|
|
954
|
+
if (typeof out === 'number') summary = formatRuntimeValue(out);
|
|
955
|
+
else if (out && typeof out === 'object') {
|
|
956
|
+
const entries = Object.entries(out).filter(([, v]) => v !== undefined && v !== null);
|
|
957
|
+
summary = entries.map(([k, v]) => `${k}: ${formatRuntimeValue(v)}`).join(' ');
|
|
958
|
+
} else summary = formatRuntimeValue(out);
|
|
959
|
+
this._valueBubbles.push({ nodeId: id, text: summary, t0: performance.now(), dur: 1400 });
|
|
960
|
+
if (typeof out === 'number') this.pushNodeMetric(id, out);
|
|
961
|
+
else if (out && typeof out === 'object') {
|
|
962
|
+
for (const v of Object.values(out)) if (typeof v === 'number') { this.pushNodeMetric(id, v); break; }
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
this.setNodeStatus(id, 'ok');
|
|
966
|
+
this.setNodeProgress(id, 1);
|
|
967
|
+
result.executed++;
|
|
968
|
+
if (this._hooks) this._runHook('onAfterExec', id, out);
|
|
969
|
+
this._emit('node:done', { id, outputs: out });
|
|
970
|
+
} catch (err) {
|
|
971
|
+
this.setNodeStatus(id, 'error');
|
|
972
|
+
result.errors.push({ id, error: err });
|
|
973
|
+
this._emit('node:error', { id, error: err });
|
|
974
|
+
if (this.options.stopOnError) break;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
this._running = false;
|
|
979
|
+
this._runAbort = null;
|
|
980
|
+
this._emit('run:done', result);
|
|
981
|
+
return result;
|
|
982
|
+
}
|
|
983
|
+
runFrom(nodeId) { return this.run({ from: nodeId }); }
|
|
984
|
+
|
|
985
|
+
// ── Debug: breakpoints + step-through ──────────────────────────────
|
|
986
|
+
setBreakpoint(nodeId, on = true) {
|
|
987
|
+
if (on) this.breakpoints.add(nodeId); else this.breakpoints.delete(nodeId);
|
|
988
|
+
}
|
|
989
|
+
toggleBreakpoint(nodeId) {
|
|
990
|
+
if (this.breakpoints.has(nodeId)) this.breakpoints.delete(nodeId);
|
|
991
|
+
else this.breakpoints.add(nodeId);
|
|
992
|
+
}
|
|
993
|
+
clearBreakpoints() { this.breakpoints.clear(); }
|
|
994
|
+
setStepMode(on) { this._stepMode = !!on; }
|
|
995
|
+
/** When paused at a breakpoint, advance one node. */
|
|
996
|
+
stepOver() {
|
|
997
|
+
if (this._resumeNext) { const r = this._resumeNext; this._resumeNext = null; r(); }
|
|
998
|
+
}
|
|
999
|
+
/** Resume normal execution. */
|
|
1000
|
+
resume() {
|
|
1001
|
+
this._paused = false; this._stepMode = false;
|
|
1002
|
+
if (this._resumeNext) { const r = this._resumeNext; this._resumeNext = null; r(); }
|
|
1003
|
+
}
|
|
1004
|
+
isPaused() { return this._paused; }
|
|
1005
|
+
_awaitContinue(nodeId) {
|
|
1006
|
+
return new Promise((resolve) => {
|
|
1007
|
+
this._paused = true;
|
|
1008
|
+
this._emit('run:paused', { nodeId });
|
|
1009
|
+
this._resumeNext = resolve;
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// ── Sub-flows: turn a frame into a reusable kind ───────────────────
|
|
1014
|
+
/** Snapshot a frame's contents as a callable kind. Returns the new kind name. */
|
|
1015
|
+
registerSubflowFromFrame(frameId, opts = {}) {
|
|
1016
|
+
const f = this.frames.find((ff) => ff.id === frameId);
|
|
1017
|
+
if (!f) throw new Error('frame not found');
|
|
1018
|
+
const inside = [];
|
|
1019
|
+
const n = this.w.nodeCount_();
|
|
1020
|
+
for (let i = 0; i < n; i++) {
|
|
1021
|
+
if (this.V.posX[i] >= f.x && this.V.posX[i] <= f.x + f.w &&
|
|
1022
|
+
this.V.posY[i] >= f.y && this.V.posY[i] <= f.y + f.h) inside.push(i);
|
|
1023
|
+
}
|
|
1024
|
+
if (!inside.length) throw new Error('frame is empty');
|
|
1025
|
+
const setIn = new Set(inside);
|
|
1026
|
+
// Capture node specs by current state.
|
|
1027
|
+
const localToSnap = new Map();
|
|
1028
|
+
const nodes = inside.map((id, i) => {
|
|
1029
|
+
localToSnap.set(id, i);
|
|
1030
|
+
return {
|
|
1031
|
+
kind: this.kinds[this.V.kind[id]].name,
|
|
1032
|
+
x: this.V.posX[id] - f.x, y: this.V.posY[id] - f.y,
|
|
1033
|
+
w: this.V.sizeW[id], h: this.V.sizeH[id],
|
|
1034
|
+
title: this.titles.get(id), color: this.colors.get(id),
|
|
1035
|
+
params: this._nodeParams?.get(id),
|
|
1036
|
+
};
|
|
1037
|
+
});
|
|
1038
|
+
const edges = [];
|
|
1039
|
+
const m = this.w.edgeCount_();
|
|
1040
|
+
for (let e = 0; e < m; e++) {
|
|
1041
|
+
if (setIn.has(this.V.edgeFromN[e]) && setIn.has(this.V.edgeToN[e])) {
|
|
1042
|
+
edges.push({
|
|
1043
|
+
from: localToSnap.get(this.V.edgeFromN[e]),
|
|
1044
|
+
to: localToSnap.get(this.V.edgeToN[e]),
|
|
1045
|
+
fp: this.V.edgeFromP[e], tp: this.V.edgeToP[e],
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
// Boundary detection: nodes with no inside-predecessor are inputs;
|
|
1050
|
+
// nodes with no inside-successor are outputs.
|
|
1051
|
+
const hasIncoming = new Set(), hasOutgoing = new Set();
|
|
1052
|
+
for (const ed of edges) { hasIncoming.add(ed.to); hasOutgoing.add(ed.from); }
|
|
1053
|
+
const inputs = inside.map((_, i) => i).filter((i) => !hasIncoming.has(i));
|
|
1054
|
+
const outputs = inside.map((_, i) => i).filter((i) => !hasOutgoing.has(i));
|
|
1055
|
+
|
|
1056
|
+
const kindName = opts.name || `subflow_${f.label || frameId}`.replace(/\s+/g, '_');
|
|
1057
|
+
// Surface inputs/outputs with the label from the node's title or kind.
|
|
1058
|
+
const inputLabels = inputs.map((idx) => {
|
|
1059
|
+
const local = inside[idx];
|
|
1060
|
+
const t = this.titles.get(local);
|
|
1061
|
+
return t || this.kinds[this.V.kind[local]].name;
|
|
1062
|
+
});
|
|
1063
|
+
const outputLabels = outputs.map((idx) => {
|
|
1064
|
+
const local = inside[idx];
|
|
1065
|
+
const t = this.titles.get(local);
|
|
1066
|
+
return t || this.kinds[this.V.kind[local]].name;
|
|
1067
|
+
});
|
|
1068
|
+
this._subflows.set(kindName, { nodes, edges, inputs, outputs, inputLabels, outputLabels });
|
|
1069
|
+
const self = this;
|
|
1070
|
+
this.registerKind({
|
|
1071
|
+
name: kindName, color: opts.color || '#5be0d0', badge: opts.badge || 'Σ',
|
|
1072
|
+
w: 180, h: 90, nin: Math.max(1, inputs.length), nout: Math.max(1, outputs.length),
|
|
1073
|
+
shape: 'rect',
|
|
1074
|
+
portIn: inputLabels,
|
|
1075
|
+
portOut: outputLabels,
|
|
1076
|
+
inputs: inputLabels.map((n) => ({ name: n, type: 'any' })),
|
|
1077
|
+
outputs: outputLabels.map((n) => ({ name: n, type: 'any' })),
|
|
1078
|
+
execute: async (ctx, ins) => {
|
|
1079
|
+
// Spawn ephemeral nodes for execution? Cheap path: rebuild a transient
|
|
1080
|
+
// value map inside this call using the snapshot's adjacency.
|
|
1081
|
+
const sf = self._subflows.get(kindName);
|
|
1082
|
+
const tmpVals = new Map();
|
|
1083
|
+
for (let i = 0; i < sf.inputs.length; i++) {
|
|
1084
|
+
const val = ins[i] ?? ins[`in${i}`] ?? ins[sf.inputLabels[i]];
|
|
1085
|
+
tmpVals.set(sf.inputs[i], val);
|
|
1086
|
+
}
|
|
1087
|
+
// Walk in topo order over snapshot edges.
|
|
1088
|
+
const indeg = sf.nodes.map(() => 0);
|
|
1089
|
+
const out = sf.nodes.map(() => []);
|
|
1090
|
+
for (const e of sf.edges) { indeg[e.to]++; out[e.from].push(e); }
|
|
1091
|
+
const q = [];
|
|
1092
|
+
for (let i = 0; i < sf.nodes.length; i++) if (indeg[i] === 0) q.push(i);
|
|
1093
|
+
while (q.length) {
|
|
1094
|
+
const u = q.shift();
|
|
1095
|
+
const node = sf.nodes[u];
|
|
1096
|
+
const cat = self.kinds[self.kindByName.get(node.kind)];
|
|
1097
|
+
let val;
|
|
1098
|
+
if (!tmpVals.has(u) && typeof cat?.execute === 'function') {
|
|
1099
|
+
const localIns = {};
|
|
1100
|
+
for (const e of sf.edges) {
|
|
1101
|
+
if (e.to === u && tmpVals.has(e.from)) {
|
|
1102
|
+
const srcVal = tmpVals.get(e.from);
|
|
1103
|
+
const v = (srcVal && typeof srcVal === 'object') ? (srcVal.value ?? srcVal[e.fp] ?? srcVal) : srcVal;
|
|
1104
|
+
localIns[`in${e.tp}`] = v;
|
|
1105
|
+
localIns[e.tp] = v;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
val = await cat.execute({ ...ctx, params: node.params || {} }, localIns);
|
|
1109
|
+
tmpVals.set(u, val);
|
|
1110
|
+
} else val = tmpVals.get(u);
|
|
1111
|
+
for (const e of out[u]) if (--indeg[e.to] === 0) q.push(e.to);
|
|
1112
|
+
}
|
|
1113
|
+
// Aggregated output keyed by BOTH index and label.
|
|
1114
|
+
const result = {};
|
|
1115
|
+
for (let i = 0; i < sf.outputs.length; i++) {
|
|
1116
|
+
const v = tmpVals.get(sf.outputs[i]);
|
|
1117
|
+
const unwrapped = (v && typeof v === 'object' && 'value' in v) ? v.value : v;
|
|
1118
|
+
result[i] = unwrapped;
|
|
1119
|
+
result[sf.outputLabels[i]] = unwrapped;
|
|
1120
|
+
}
|
|
1121
|
+
return result;
|
|
1122
|
+
},
|
|
1123
|
+
});
|
|
1124
|
+
return kindName;
|
|
1125
|
+
}
|
|
1126
|
+
runFrame(frameId) {
|
|
1127
|
+
const f = this.frames.find((ff) => ff.id === frameId);
|
|
1128
|
+
if (!f) return Promise.resolve({ executed: 0, errors: [] });
|
|
1129
|
+
const inside = new Set();
|
|
1130
|
+
const n = this.w.nodeCount_();
|
|
1131
|
+
for (let i = 0; i < n; i++) {
|
|
1132
|
+
if (this.V.posX[i] >= f.x && this.V.posX[i] <= f.x + f.w &&
|
|
1133
|
+
this.V.posY[i] >= f.y && this.V.posY[i] <= f.y + f.h) inside.add(i);
|
|
1134
|
+
}
|
|
1135
|
+
return this.run({ filter: (id) => inside.has(id) });
|
|
1136
|
+
}
|
|
1137
|
+
stop() { if (this._runAbort) this._runAbort.abort(); this._running = false; }
|
|
1138
|
+
isRunning() { return this._running; }
|
|
1139
|
+
|
|
1140
|
+
/** Set per-node runtime parameters (used by built-in kinds: const, if). */
|
|
1141
|
+
setNodeParams(nodeId, params) {
|
|
1142
|
+
if (!this._nodeParams) this._nodeParams = new Map();
|
|
1143
|
+
this._nodeParams.set(nodeId, params);
|
|
1144
|
+
}
|
|
1145
|
+
getNodeParams(nodeId) { return this._nodeParams?.get(nodeId); }
|
|
1146
|
+
|
|
1147
|
+
/** Long-running loop: re-run every `interval` ms until stopped. */
|
|
1148
|
+
startLoop(interval = 500) {
|
|
1149
|
+
this._loopStop = false;
|
|
1150
|
+
const tick = async () => {
|
|
1151
|
+
if (this._loopStop) return;
|
|
1152
|
+
await this.run();
|
|
1153
|
+
if (this._loopStop) return;
|
|
1154
|
+
setTimeout(tick, interval);
|
|
1155
|
+
};
|
|
1156
|
+
tick();
|
|
1157
|
+
}
|
|
1158
|
+
stopLoop() { this._loopStop = true; this.stop(); }
|
|
1159
|
+
|
|
1160
|
+
// ── Locks + read-only ────────────────────────────────────────────────
|
|
1161
|
+
lockNode(id, on = true) { if (on) this.locked.add(id); else this.locked.delete(id); }
|
|
1162
|
+
isLocked(id) { return this.locked.has(id); }
|
|
1163
|
+
setReadOnly(on) { this.readOnly = !!on; }
|
|
1164
|
+
|
|
1165
|
+
// ── Reachable highlight ──────────────────────────────────────────────
|
|
1166
|
+
setReachableFrom(nodeId) {
|
|
1167
|
+
if (nodeId === null || nodeId === undefined || nodeId < 0) { this._reachableSet = null; return; }
|
|
1168
|
+
const reach = new Set([nodeId]);
|
|
1169
|
+
const q = [nodeId];
|
|
1170
|
+
const m = this.w.edgeCount_();
|
|
1171
|
+
while (q.length) {
|
|
1172
|
+
const u = q.shift();
|
|
1173
|
+
for (let i = 0; i < m; i++) {
|
|
1174
|
+
if (this.V.edgeFromN[i] === u && !reach.has(this.V.edgeToN[i])) {
|
|
1175
|
+
reach.add(this.V.edgeToN[i]); q.push(this.V.edgeToN[i]);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
this._reachableSet = reach;
|
|
1180
|
+
}
|
|
1181
|
+
clearReachable() { this._reachableSet = null; }
|
|
1182
|
+
|
|
1183
|
+
// ── Remote cursor presence (collaboration UI primitive) ───────────────
|
|
1184
|
+
setRemoteCursor(userId, x, y, name = userId, color = '#5be0d0') {
|
|
1185
|
+
if (x === null) { this.remoteCursors.delete(userId); return; }
|
|
1186
|
+
this.remoteCursors.set(userId, { x, y, name, color, t: performance.now() });
|
|
1187
|
+
}
|
|
1188
|
+
clearRemoteCursors() { this.remoteCursors.clear(); }
|
|
1189
|
+
|
|
1190
|
+
// ── Edge waypoints ───────────────────────────────────────────────────
|
|
1191
|
+
setEdgeWaypoints(edgeIdx, points) {
|
|
1192
|
+
if (!points || !points.length) this._edgeWaypoints.delete(edgeIdx);
|
|
1193
|
+
else this._edgeWaypoints.set(edgeIdx, points.map((p) => ({ x: p.x, y: p.y })));
|
|
1194
|
+
}
|
|
1195
|
+
clearEdgeWaypoints(edgeIdx) { this._edgeWaypoints.delete(edgeIdx); }
|
|
1196
|
+
|
|
1197
|
+
// ── Frame collapse ───────────────────────────────────────────────────
|
|
1198
|
+
toggleFrameCollapse(frameIdx) {
|
|
1199
|
+
if (this.frameCollapsed.has(frameIdx)) this.frameCollapsed.delete(frameIdx);
|
|
1200
|
+
else this.frameCollapsed.add(frameIdx);
|
|
1201
|
+
this._emit('change');
|
|
1202
|
+
}
|
|
1203
|
+
isFrameCollapsed(idx) { return this.frameCollapsed.has(idx); }
|
|
1204
|
+
_nodeHiddenByCollapse(nodeId) {
|
|
1205
|
+
if (!this.frameCollapsed.size) return false;
|
|
1206
|
+
for (const fidx of this.frameCollapsed) {
|
|
1207
|
+
const f = this.frames[fidx]; if (!f) continue;
|
|
1208
|
+
if (this.V.posX[nodeId] >= f.x && this.V.posX[nodeId] <= f.x + f.w &&
|
|
1209
|
+
this.V.posY[nodeId] >= f.y + 26 && this.V.posY[nodeId] <= f.y + f.h) return true;
|
|
1210
|
+
}
|
|
1211
|
+
return false;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
// ── Palette: any DOM element can drag-drop into the canvas ───────────
|
|
1215
|
+
makeDraggable(el, spec) {
|
|
1216
|
+
if (!el || !spec || !spec.kind) throw new Error('makeDraggable: spec.kind required');
|
|
1217
|
+
el.style.cursor = 'grab';
|
|
1218
|
+
el.addEventListener('mousedown', (ev) => {
|
|
1219
|
+
ev.preventDefault();
|
|
1220
|
+
if (this.readOnly) return;
|
|
1221
|
+
const ghost = el.cloneNode(true);
|
|
1222
|
+
Object.assign(ghost.style, { position: 'fixed', pointerEvents: 'none', opacity: '0.75', zIndex: '900', transform: 'translate(-50%,-50%) scale(1.02)' });
|
|
1223
|
+
document.body.appendChild(ghost);
|
|
1224
|
+
const move = (e) => { ghost.style.left = e.clientX + 'px'; ghost.style.top = e.clientY + 'px'; };
|
|
1225
|
+
move(ev);
|
|
1226
|
+
const up = (e) => {
|
|
1227
|
+
window.removeEventListener('mousemove', move);
|
|
1228
|
+
window.removeEventListener('mouseup', up);
|
|
1229
|
+
ghost.remove();
|
|
1230
|
+
const r = this.canvas.getBoundingClientRect();
|
|
1231
|
+
if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) return;
|
|
1232
|
+
const wp = this._s2w(e.clientX, e.clientY);
|
|
1233
|
+
const nodeSpec = { ...spec, x: wp.x, y: wp.y };
|
|
1234
|
+
delete nodeSpec.element;
|
|
1235
|
+
const id = this.addNode(nodeSpec);
|
|
1236
|
+
this._emit('palette:drop', { id, x: wp.x, y: wp.y, spec });
|
|
1237
|
+
};
|
|
1238
|
+
window.addEventListener('mousemove', move);
|
|
1239
|
+
window.addEventListener('mouseup', up);
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// ── Theme ─────────────────────────────────────────────────────────────
|
|
1244
|
+
setTheme(name) {
|
|
1245
|
+
this._theme = name === 'light' ? LIGHT_THEME : DARK_THEME;
|
|
1246
|
+
this.options.theme = name;
|
|
1247
|
+
this.options.background = this._theme.bg;
|
|
1248
|
+
this.canvas.style.background = this._theme.bg;
|
|
1249
|
+
this._emit('theme', name);
|
|
1250
|
+
}
|
|
1251
|
+
toggleTheme() { this.setTheme(this.options.theme === 'light' ? 'dark' : 'light'); }
|
|
1252
|
+
|
|
1253
|
+
// ── Live metrics (sparkline) ──────────────────────────────────────────
|
|
1254
|
+
pushNodeMetric(id, value) {
|
|
1255
|
+
let buf = this.metrics.get(id);
|
|
1256
|
+
if (!buf) {
|
|
1257
|
+
buf = { data: new Float32Array(this._metricCap), idx: 0, count: 0 };
|
|
1258
|
+
this.metrics.set(id, buf);
|
|
1259
|
+
}
|
|
1260
|
+
buf.data[buf.idx] = value;
|
|
1261
|
+
buf.idx = (buf.idx + 1) % this._metricCap;
|
|
1262
|
+
if (buf.count < this._metricCap) buf.count++;
|
|
1263
|
+
const prev = this.metricMax.get(id) || 1;
|
|
1264
|
+
this.metricMax.set(id, Math.max(prev * 0.99, Math.abs(value), 1));
|
|
1265
|
+
}
|
|
1266
|
+
clearNodeMetric(id) { this.metrics.delete(id); this.metricMax.delete(id); }
|
|
1267
|
+
|
|
1268
|
+
// ── Edge animation ────────────────────────────────────────────────────
|
|
1269
|
+
setEdgeAnimated(edgeIdx, on) {
|
|
1270
|
+
if (on) this.animatedEdges.add(edgeIdx); else this.animatedEdges.delete(edgeIdx);
|
|
1271
|
+
}
|
|
1272
|
+
setAllEdgesAnimated(on) {
|
|
1273
|
+
if (!on) { this.animatedEdges.clear(); return; }
|
|
1274
|
+
const m = this.w.edgeCount_();
|
|
1275
|
+
for (let i = 0; i < m; i++) this.animatedEdges.add(i);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
// ── Connection validation ─────────────────────────────────────────────
|
|
1279
|
+
setConnectionValidator(fn) { this._connValidator = typeof fn === 'function' ? fn : null; }
|
|
1280
|
+
|
|
1281
|
+
// ── Templates ─────────────────────────────────────────────────────────
|
|
1282
|
+
registerTemplate(name, builder) { this._templates.set(name, builder); }
|
|
1283
|
+
insertTemplate(name, x = 0, y = 0) {
|
|
1284
|
+
const b = this._templates.get(name);
|
|
1285
|
+
if (!b) return -1;
|
|
1286
|
+
return b(this, x, y);
|
|
1287
|
+
}
|
|
1288
|
+
listTemplates() { return [...this._templates.keys()]; }
|
|
1289
|
+
|
|
1290
|
+
// ── Search ────────────────────────────────────────────────────────────
|
|
1291
|
+
search(query) {
|
|
1292
|
+
this._searchQuery = (query || '').toLowerCase();
|
|
1293
|
+
this._searchHits = [];
|
|
1294
|
+
if (!this._searchQuery) return [];
|
|
1295
|
+
const n = this.w.nodeCount_();
|
|
1296
|
+
for (let i = 0; i < n; i++) {
|
|
1297
|
+
const title = (this.titles.get(i) || '').toLowerCase();
|
|
1298
|
+
const desc = (this.descriptions.get(i) || '').toLowerCase();
|
|
1299
|
+
const kind = this.kinds[this.V.kind[i]].name.toLowerCase();
|
|
1300
|
+
const tagStr = (this.tags.get(i) || []).join(' ').toLowerCase();
|
|
1301
|
+
if (title.includes(this._searchQuery) || desc.includes(this._searchQuery) ||
|
|
1302
|
+
kind.includes(this._searchQuery) || tagStr.includes(this._searchQuery)) {
|
|
1303
|
+
this._searchHits.push(i);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
return this._searchHits.slice();
|
|
1307
|
+
}
|
|
1308
|
+
jumpToSearchHit(idx) {
|
|
1309
|
+
if (!this._searchHits.length) return;
|
|
1310
|
+
const i = this._searchHits[((idx % this._searchHits.length) + this._searchHits.length) % this._searchHits.length];
|
|
1311
|
+
this.clearSelection();
|
|
1312
|
+
this.w.setSelected(i, 1);
|
|
1313
|
+
this.panTo(this.V.posX[i], this.V.posY[i]);
|
|
1314
|
+
}
|
|
1315
|
+
clearSearch() { this._searchQuery = ''; this._searchHits = []; }
|
|
1316
|
+
|
|
1317
|
+
// ── Command palette ───────────────────────────────────────────────────
|
|
1318
|
+
openCommandPalette() {
|
|
1319
|
+
if (this._cmdPaletteEl) { this._cmdPaletteEl.remove(); this._cmdPaletteEl = null; return; }
|
|
1320
|
+
const cmds = this._builtinCommands();
|
|
1321
|
+
const el = document.createElement('div');
|
|
1322
|
+
el.style.cssText = `position:absolute;top:80px;left:50%;transform:translateX(-50%);width:480px;max-height:60vh;overflow:hidden;background:${this._theme.panel};border:1px solid ${this._theme.border};border-radius:10px;box-shadow:0 16px 48px rgba(0,0,0,0.6);z-index:500;color:${this._theme.fg};font-family:Inter, ui-sans-serif;`;
|
|
1323
|
+
el.innerHTML = `
|
|
1324
|
+
<input id="zf-cmd-q" type="text" placeholder="Type a command…" style="width:100%;padding:14px 16px;background:transparent;color:${this._theme.fg};border:0;border-bottom:1px solid ${this._theme.border};outline:none;font-size:14px;">
|
|
1325
|
+
<div id="zf-cmd-list" style="max-height:46vh;overflow:auto;"></div>`;
|
|
1326
|
+
this.container.appendChild(el);
|
|
1327
|
+
this._cmdPaletteEl = el;
|
|
1328
|
+
const input = el.querySelector('#zf-cmd-q'), list = el.querySelector('#zf-cmd-list');
|
|
1329
|
+
let cursor = 0, filtered = cmds;
|
|
1330
|
+
const render = () => {
|
|
1331
|
+
list.innerHTML = filtered.map((c, i) => `
|
|
1332
|
+
<div data-i="${i}" style="padding:9px 16px;cursor:pointer;display:flex;justify-content:space-between;align-items:center;background:${i === cursor ? this._theme.hi : 'transparent'};">
|
|
1333
|
+
<span>${escapeHtml(c.label)}</span>
|
|
1334
|
+
<span style="color:${this._theme.muted};font-family:ui-monospace,Consolas,monospace;font-size:11px;">${c.hotkey || ''}</span>
|
|
1335
|
+
</div>`).join('');
|
|
1336
|
+
};
|
|
1337
|
+
render();
|
|
1338
|
+
const run = (i) => { const cmd = filtered[i]; if (cmd) cmd.run(); this.openCommandPalette(); };
|
|
1339
|
+
list.addEventListener('mousedown', (e) => {
|
|
1340
|
+
const row = e.target.closest('[data-i]'); if (!row) return;
|
|
1341
|
+
run(parseInt(row.dataset.i, 10));
|
|
1342
|
+
});
|
|
1343
|
+
input.addEventListener('input', () => {
|
|
1344
|
+
const q = input.value.toLowerCase();
|
|
1345
|
+
filtered = q ? cmds.filter((c) => c.label.toLowerCase().includes(q)) : cmds;
|
|
1346
|
+
cursor = 0; render();
|
|
1347
|
+
});
|
|
1348
|
+
input.addEventListener('keydown', (e) => {
|
|
1349
|
+
if (e.code === 'ArrowDown') { cursor = Math.min(filtered.length - 1, cursor + 1); render(); e.preventDefault(); }
|
|
1350
|
+
if (e.code === 'ArrowUp') { cursor = Math.max(0, cursor - 1); render(); e.preventDefault(); }
|
|
1351
|
+
if (e.code === 'Enter') { run(cursor); }
|
|
1352
|
+
if (e.code === 'Escape') { this.openCommandPalette(); }
|
|
1353
|
+
});
|
|
1354
|
+
input.focus();
|
|
1355
|
+
}
|
|
1356
|
+
_builtinCommands() {
|
|
1357
|
+
return [
|
|
1358
|
+
{ label: 'Auto layout (Sugiyama)', hotkey: 'L', run: () => this.runAutoLayout() },
|
|
1359
|
+
{ label: 'Force layout', hotkey: 'F', run: () => this.runForceLayout() },
|
|
1360
|
+
{ label: 'Fit view', hotkey: '0', run: () => this.fitView() },
|
|
1361
|
+
{ label: 'Toggle theme (light/dark)', hotkey: 'Ctrl+T', run: () => this.toggleTheme() },
|
|
1362
|
+
{ label: 'Toggle minimap', hotkey: 'Ctrl+M', run: () => this.setMinimap(!this.options.minimap) },
|
|
1363
|
+
{ label: 'Toggle edge animation', hotkey: 'Ctrl+E', run: () => this.setAllEdgesAnimated(this.animatedEdges.size === 0) },
|
|
1364
|
+
{ label: 'Toggle edge style', hotkey: '', run: () => this.setEdgeStyle(this.options.edgeStyle === 'bezier' ? 'orthogonal' : 'bezier') },
|
|
1365
|
+
{ label: 'Toggle snap-to-grid', hotkey: 'G', run: () => this.setSnapToGrid(!this.options.snapToGrid) },
|
|
1366
|
+
{ label: 'Toggle path highlight', hotkey: '', run: () => this.setPathHighlight(!this._pathHighlightEnabled) },
|
|
1367
|
+
{ label: 'Toggle hover preview', hotkey: '', run: () => this.setHoverPreview(!this.options.hoverPreview) },
|
|
1368
|
+
{ label: 'Find…', hotkey: 'Ctrl+F', run: () => this.openSearch() },
|
|
1369
|
+
{ label: 'Highlight critical path', hotkey: '', run: () => { const e = this.criticalPath(); for (const i of e) this.w.setEdgeSelected_(i, 1); } },
|
|
1370
|
+
{ label: 'Find SCCs (cycle groups)', hotkey: '', run: () => { const sccs = this.findSCCs(); for (const g of sccs) for (const n of g) this.w.setSelected(n, 1); } },
|
|
1371
|
+
{ label: 'Color nodes by degree', hotkey: '', run: () => this.colorByDegree() },
|
|
1372
|
+
{ label: 'Clear node colors', hotkey: '', run: () => this.clearNodeColors() },
|
|
1373
|
+
{ label: 'Group selection', hotkey: 'Ctrl+G', run: () => this.groupSelection() },
|
|
1374
|
+
{ label: 'Add sticky note', hotkey: '', run: () => this.addNote(-this.cam.x, -this.cam.y) },
|
|
1375
|
+
{ label: 'Select all', hotkey: 'Ctrl+A', run: () => this.selectAll() },
|
|
1376
|
+
{ label: 'Duplicate selection', hotkey: 'Ctrl+D', run: () => this.duplicateSelection() },
|
|
1377
|
+
{ label: 'Delete selection', hotkey: 'Del', run: () => this.deleteSelection() },
|
|
1378
|
+
{ label: 'Export PNG', hotkey: '', run: async () => { const b = await this.exportPNG(); window.open(URL.createObjectURL(b)); } },
|
|
1379
|
+
{ label: 'Export SVG', hotkey: '', run: () => { const blob = new Blob([this.exportSVG()], { type: 'image/svg+xml' }); window.open(URL.createObjectURL(blob)); } },
|
|
1380
|
+
{ label: 'Export JSON', hotkey: '', run: () => { const blob = new Blob([JSON.stringify(this.toJSON(), null, 2)], { type: 'application/json' }); window.open(URL.createObjectURL(blob)); } },
|
|
1381
|
+
{ label: 'Undo', hotkey: 'Ctrl+Z', run: () => this.undo() },
|
|
1382
|
+
{ label: 'Redo', hotkey: 'Ctrl+Y', run: () => this.redo() },
|
|
1383
|
+
{ label: 'Run graph', hotkey: 'F5', run: () => this.run() },
|
|
1384
|
+
{ label: 'Stop run', hotkey: 'Shift+F5', run: () => this.stop() },
|
|
1385
|
+
{ label: 'Clear runtime state', hotkey: '', run: () => this.clearRuntimeState() },
|
|
1386
|
+
...[...this._templates.keys()].map((name) => ({
|
|
1387
|
+
label: `Insert template: ${name}`, hotkey: '',
|
|
1388
|
+
run: () => this.insertTemplate(name, -this.cam.x, -this.cam.y),
|
|
1389
|
+
})),
|
|
1390
|
+
...((this._extraCommands || []).map((c) => ({ label: c.label, hotkey: c.hotkey || '', run: c.run }))),
|
|
1391
|
+
];
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// ── Search UI ─────────────────────────────────────────────────────────
|
|
1395
|
+
openSearch() {
|
|
1396
|
+
if (this._searchEl) { this._searchEl.remove(); this._searchEl = null; this.clearSearch(); return; }
|
|
1397
|
+
const el = document.createElement('div');
|
|
1398
|
+
el.style.cssText = `position:absolute;top:14px;left:50%;transform:translateX(-50%);background:${this._theme.panel};color:${this._theme.fg};border:1px solid ${this._theme.border};border-radius:8px;padding:6px 10px;display:flex;align-items:center;gap:8px;z-index:500;font-family:Inter, ui-sans-serif;box-shadow:0 8px 24px rgba(0,0,0,0.4);`;
|
|
1399
|
+
el.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="${this._theme.muted}" stroke-width="2"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1400
|
+
<input id="zf-s" type="text" placeholder="Find nodes…" style="background:transparent;border:0;outline:none;color:${this._theme.fg};font-size:13px;width:240px;">
|
|
1401
|
+
<span id="zf-sn" style="color:${this._theme.muted};font-size:11px;font-family:ui-monospace,Consolas,monospace;"></span>`;
|
|
1402
|
+
this.container.appendChild(el);
|
|
1403
|
+
this._searchEl = el;
|
|
1404
|
+
const input = el.querySelector('#zf-s'), counter = el.querySelector('#zf-sn');
|
|
1405
|
+
let idx = 0;
|
|
1406
|
+
const onChange = () => {
|
|
1407
|
+
const hits = this.search(input.value);
|
|
1408
|
+
counter.textContent = hits.length ? `${idx + 1}/${hits.length}` : (input.value ? '0' : '');
|
|
1409
|
+
if (hits.length) this.jumpToSearchHit(idx);
|
|
1410
|
+
};
|
|
1411
|
+
input.addEventListener('input', () => { idx = 0; onChange(); });
|
|
1412
|
+
input.addEventListener('keydown', (e) => {
|
|
1413
|
+
if (e.code === 'Enter') { idx = (idx + (e.shiftKey ? -1 : 1) + this._searchHits.length) % Math.max(this._searchHits.length, 1); onChange(); e.preventDefault(); }
|
|
1414
|
+
if (e.code === 'Escape') { this.openSearch(); }
|
|
1415
|
+
});
|
|
1416
|
+
input.focus();
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// ── Minimap ───────────────────────────────────────────────────────────
|
|
1420
|
+
setMinimap(on) {
|
|
1421
|
+
this.options.minimap = !!on;
|
|
1422
|
+
if (on) this._setupMinimap();
|
|
1423
|
+
else if (this._minimapEl) { this._minimapEl.remove(); this._minimapEl = null; this._minimapCtx = null; }
|
|
1424
|
+
}
|
|
1425
|
+
_setupMinimap() {
|
|
1426
|
+
if (this._minimapEl) return;
|
|
1427
|
+
const el = document.createElement('canvas');
|
|
1428
|
+
el.width = 200 * (window.devicePixelRatio || 1);
|
|
1429
|
+
el.height = 140 * (window.devicePixelRatio || 1);
|
|
1430
|
+
el.style.cssText = `position:absolute;right:14px;bottom:14px;width:200px;height:140px;background:${this._theme.panel};border:1px solid ${this._theme.border};border-radius:8px;cursor:pointer;z-index:50;box-shadow:0 4px 16px rgba(0,0,0,0.4);`;
|
|
1431
|
+
this.container.appendChild(el);
|
|
1432
|
+
el.addEventListener('mousedown', (e) => {
|
|
1433
|
+
const r = el.getBoundingClientRect();
|
|
1434
|
+
const px = (e.clientX - r.left) / r.width, py = (e.clientY - r.top) / r.height;
|
|
1435
|
+
const bb = this._graphBounds(); if (!bb) return;
|
|
1436
|
+
this.cam.x = -(bb.minX + px * (bb.maxX - bb.minX));
|
|
1437
|
+
this.cam.y = -(bb.minY + py * (bb.maxY - bb.minY));
|
|
1438
|
+
});
|
|
1439
|
+
this._minimapEl = el;
|
|
1440
|
+
this._minimapCtx = el.getContext('2d', { alpha: false });
|
|
1441
|
+
}
|
|
1442
|
+
_graphBounds() {
|
|
1443
|
+
const n = this.w.nodeCount_(); if (n === 0) return null;
|
|
1444
|
+
let mnx = Infinity, mxx = -Infinity, mny = Infinity, mxy = -Infinity;
|
|
1445
|
+
for (let i = 0; i < n; i++) {
|
|
1446
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
1447
|
+
if (this.V.posX[i] - hw < mnx) mnx = this.V.posX[i] - hw;
|
|
1448
|
+
if (this.V.posX[i] + hw > mxx) mxx = this.V.posX[i] + hw;
|
|
1449
|
+
if (this.V.posY[i] - hh < mny) mny = this.V.posY[i] - hh;
|
|
1450
|
+
if (this.V.posY[i] + hh > mxy) mxy = this.V.posY[i] + hh;
|
|
1451
|
+
}
|
|
1452
|
+
const padX = (mxx - mnx) * 0.1 + 40, padY = (mxy - mny) * 0.1 + 40;
|
|
1453
|
+
return { minX: mnx - padX, maxX: mxx + padX, minY: mny - padY, maxY: mxy + padY };
|
|
1454
|
+
}
|
|
1455
|
+
_drawValueBubbles() {
|
|
1456
|
+
if (!this._valueBubbles.length) return;
|
|
1457
|
+
const now = performance.now();
|
|
1458
|
+
const ctx = this.ctx;
|
|
1459
|
+
for (let i = this._valueBubbles.length - 1; i >= 0; i--) {
|
|
1460
|
+
const b = this._valueBubbles[i];
|
|
1461
|
+
const t = (now - b.t0) / b.dur;
|
|
1462
|
+
if (t >= 1) { this._valueBubbles.splice(i, 1); continue; }
|
|
1463
|
+
const alpha = t < 0.15 ? t / 0.15 : t > 0.7 ? (1 - t) / 0.3 : 1;
|
|
1464
|
+
const rise = t * 30;
|
|
1465
|
+
const id = b.nodeId;
|
|
1466
|
+
if (id >= this.w.nodeCount_()) continue;
|
|
1467
|
+
const cx = this.V.posX[id], cy = this.V.posY[id];
|
|
1468
|
+
const hh = this.V.sizeH[id] * 0.5;
|
|
1469
|
+
const sp = this._w2s(cx, cy - hh);
|
|
1470
|
+
ctx.save();
|
|
1471
|
+
ctx.globalAlpha = alpha;
|
|
1472
|
+
ctx.font = `600 12px ui-monospace, Consolas, monospace`;
|
|
1473
|
+
const tw = ctx.measureText(b.text).width;
|
|
1474
|
+
const padX = 8;
|
|
1475
|
+
const bw = tw + padX * 2, bh = 22;
|
|
1476
|
+
const bx = sp.x - bw / 2, by = sp.y - bh - 10 - rise;
|
|
1477
|
+
ctx.shadowColor = 'rgba(0,0,0,0.5)';
|
|
1478
|
+
ctx.shadowBlur = 8;
|
|
1479
|
+
ctx.fillStyle = '#161b27';
|
|
1480
|
+
this._roundRect(bx, by, bw, bh, 5); ctx.fill();
|
|
1481
|
+
ctx.shadowBlur = 0;
|
|
1482
|
+
ctx.strokeStyle = '#5b8def'; ctx.lineWidth = 1.4;
|
|
1483
|
+
this._roundRect(bx, by, bw, bh, 5); ctx.stroke();
|
|
1484
|
+
ctx.fillStyle = '#5be0d0';
|
|
1485
|
+
ctx.textBaseline = 'middle'; ctx.textAlign = 'center';
|
|
1486
|
+
ctx.fillText(b.text, sp.x, by + bh / 2);
|
|
1487
|
+
// Tail.
|
|
1488
|
+
ctx.fillStyle = '#161b27';
|
|
1489
|
+
ctx.strokeStyle = '#5b8def';
|
|
1490
|
+
ctx.beginPath();
|
|
1491
|
+
ctx.moveTo(sp.x - 5, by + bh);
|
|
1492
|
+
ctx.lineTo(sp.x + 5, by + bh);
|
|
1493
|
+
ctx.lineTo(sp.x, by + bh + 6);
|
|
1494
|
+
ctx.closePath(); ctx.fill(); ctx.stroke();
|
|
1495
|
+
ctx.restore();
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
_drawWaypoints() {
|
|
1500
|
+
for (const [edgeIdx, list] of this._edgeWaypoints) {
|
|
1501
|
+
for (const p of list) {
|
|
1502
|
+
const sp = this._w2s(p.x, p.y);
|
|
1503
|
+
this.ctx.fillStyle = '#f0b93a';
|
|
1504
|
+
this.ctx.beginPath(); this.ctx.arc(sp.x, sp.y, 5, 0, Math.PI * 2); this.ctx.fill();
|
|
1505
|
+
this.ctx.strokeStyle = '#0b0f17'; this.ctx.lineWidth = 1.2; this.ctx.stroke();
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
_hitWaypoint(qx, qy) {
|
|
1511
|
+
const tol = 8 / this.cam.zoom;
|
|
1512
|
+
for (const [edgeIdx, list] of this._edgeWaypoints) {
|
|
1513
|
+
for (let i = 0; i < list.length; i++) {
|
|
1514
|
+
if (Math.hypot(list[i].x - qx, list[i].y - qy) < tol) return { edgeIdx, wpIdx: i };
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
return null;
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
_drawRemoteCursors() {
|
|
1521
|
+
if (!this.remoteCursors.size) return;
|
|
1522
|
+
const now = performance.now();
|
|
1523
|
+
for (const [id, c] of this.remoteCursors) {
|
|
1524
|
+
if (now - c.t > 30000) { this.remoteCursors.delete(id); continue; }
|
|
1525
|
+
const sp = this._w2s(c.x, c.y);
|
|
1526
|
+
const ctx = this.ctx;
|
|
1527
|
+
ctx.save();
|
|
1528
|
+
// Arrow.
|
|
1529
|
+
ctx.fillStyle = c.color;
|
|
1530
|
+
ctx.beginPath();
|
|
1531
|
+
ctx.moveTo(sp.x, sp.y);
|
|
1532
|
+
ctx.lineTo(sp.x + 12, sp.y + 4);
|
|
1533
|
+
ctx.lineTo(sp.x + 5, sp.y + 6);
|
|
1534
|
+
ctx.lineTo(sp.x + 4, sp.y + 13);
|
|
1535
|
+
ctx.closePath(); ctx.fill();
|
|
1536
|
+
// Name tag.
|
|
1537
|
+
ctx.font = '600 11px Inter, ui-sans-serif';
|
|
1538
|
+
const tw = ctx.measureText(c.name).width;
|
|
1539
|
+
ctx.fillStyle = c.color;
|
|
1540
|
+
this._roundRect(sp.x + 12, sp.y + 12, tw + 12, 16, 4); ctx.fill();
|
|
1541
|
+
ctx.fillStyle = '#0b0f17';
|
|
1542
|
+
ctx.textBaseline = 'middle';
|
|
1543
|
+
ctx.fillText(c.name, sp.x + 18, sp.y + 20);
|
|
1544
|
+
ctx.restore();
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
_getImage(url) {
|
|
1549
|
+
let entry = this._imageCache.get(url);
|
|
1550
|
+
if (!entry) {
|
|
1551
|
+
entry = { img: new Image(), ready: false };
|
|
1552
|
+
entry.img.crossOrigin = 'anonymous';
|
|
1553
|
+
entry.img.onload = () => { entry.ready = true; };
|
|
1554
|
+
entry.img.onerror = () => { entry.ready = false; };
|
|
1555
|
+
entry.img.src = url;
|
|
1556
|
+
this._imageCache.set(url, entry);
|
|
1557
|
+
}
|
|
1558
|
+
return entry;
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
_drawMinimap() {
|
|
1562
|
+
if (!this._minimapEl || !this._minimapCtx) return;
|
|
1563
|
+
const m = this._minimapCtx;
|
|
1564
|
+
const W = this._minimapEl.width, H = this._minimapEl.height;
|
|
1565
|
+
m.fillStyle = this._theme.panel;
|
|
1566
|
+
m.fillRect(0, 0, W, H);
|
|
1567
|
+
const bb = this._graphBounds();
|
|
1568
|
+
if (!bb) return;
|
|
1569
|
+
const sx = W / (bb.maxX - bb.minX), sy = H / (bb.maxY - bb.minY);
|
|
1570
|
+
const s = Math.min(sx, sy);
|
|
1571
|
+
const ox = (W - s * (bb.maxX - bb.minX)) * 0.5;
|
|
1572
|
+
const oy = (H - s * (bb.maxY - bb.minY)) * 0.5;
|
|
1573
|
+
const n = this.w.nodeCount_();
|
|
1574
|
+
for (let i = 0; i < n; i++) {
|
|
1575
|
+
const cat = this.kinds[this.V.kind[i]];
|
|
1576
|
+
const hw = this.V.sizeW[i] * 0.5 * s, hh = this.V.sizeH[i] * 0.5 * s;
|
|
1577
|
+
const x = ox + (this.V.posX[i] - bb.minX) * s, y = oy + (this.V.posY[i] - bb.minY) * s;
|
|
1578
|
+
m.fillStyle = this.colors.get(i) || cat.color;
|
|
1579
|
+
m.fillRect(x - hw, y - hh, Math.max(2, hw * 2), Math.max(2, hh * 2));
|
|
1580
|
+
}
|
|
1581
|
+
// Viewport rect.
|
|
1582
|
+
const dpr = window.devicePixelRatio || 1;
|
|
1583
|
+
const cw = this.canvas.width / dpr / this.cam.zoom;
|
|
1584
|
+
const ch = this.canvas.height / dpr / this.cam.zoom;
|
|
1585
|
+
const vx = ox + (-this.cam.x - cw * 0.5 - bb.minX) * s;
|
|
1586
|
+
const vy = oy + (-this.cam.y - ch * 0.5 - bb.minY) * s;
|
|
1587
|
+
m.strokeStyle = this._theme.accent;
|
|
1588
|
+
m.lineWidth = 2;
|
|
1589
|
+
m.strokeRect(vx, vy, cw * s, ch * s);
|
|
1590
|
+
}
|
|
1591
|
+
// Path-highlight on hover (Obsidian-style fade).
|
|
1592
|
+
setPathHighlight(on) { this._pathHighlightEnabled = !!on; if (!on) this._focusedSet = null; }
|
|
1593
|
+
|
|
1594
|
+
// ── Plugin API ────────────────────────────────────────────────────────
|
|
1595
|
+
registerKind(spec) {
|
|
1596
|
+
const idx = this.kinds.length;
|
|
1597
|
+
const cat = {
|
|
1598
|
+
name: spec.name ?? `custom${idx}`,
|
|
1599
|
+
color: spec.color ?? '#94a3b8',
|
|
1600
|
+
badge: spec.badge ?? 'C',
|
|
1601
|
+
w: spec.w ?? 140,
|
|
1602
|
+
h: spec.h ?? 60,
|
|
1603
|
+
nin: spec.nin ?? 1,
|
|
1604
|
+
nout: spec.nout ?? 1,
|
|
1605
|
+
shape: spec.shape ?? 'rect',
|
|
1606
|
+
html: spec.html === true,
|
|
1607
|
+
template: spec.template || null,
|
|
1608
|
+
execute: typeof spec.execute === 'function' ? spec.execute : null,
|
|
1609
|
+
portIn: Array.isArray(spec.portIn) ? spec.portIn.slice() : null,
|
|
1610
|
+
portOut: Array.isArray(spec.portOut) ? spec.portOut.slice() : null,
|
|
1611
|
+
// Schema declarations — each entry: { name, type, required?, default? }
|
|
1612
|
+
// Type is a string used by isCompatibleType(). Special: 'any' matches everything.
|
|
1613
|
+
inputs: Array.isArray(spec.inputs) ? spec.inputs.slice() : null,
|
|
1614
|
+
outputs: Array.isArray(spec.outputs) ? spec.outputs.slice() : null,
|
|
1615
|
+
retry: spec.retry || null,
|
|
1616
|
+
};
|
|
1617
|
+
this.kinds.push(cat);
|
|
1618
|
+
this.kindByName.set(cat.name, idx);
|
|
1619
|
+
this._runOrder = null;
|
|
1620
|
+
return idx;
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
// ── Sticky notes ──────────────────────────────────────────────────────
|
|
1624
|
+
addNote(x, y, text = '', opts = {}) {
|
|
1625
|
+
const palette = [
|
|
1626
|
+
{ fill: 'rgba(254,249,195,0.94)', text: '#5b3d12', border: '#caa54a' },
|
|
1627
|
+
{ fill: 'rgba(252,231,243,0.94)', text: '#831843', border: '#db5895' },
|
|
1628
|
+
{ fill: 'rgba(220,252,231,0.94)', text: '#14532d', border: '#5cad75' },
|
|
1629
|
+
{ fill: 'rgba(219,234,254,0.94)', text: '#1e3a8a', border: '#5b8def' },
|
|
1630
|
+
];
|
|
1631
|
+
const color = opts.color || palette[this.notes.length % palette.length];
|
|
1632
|
+
const note = { id: ++this._noteSeq, x, y, w: opts.w || 220, h: opts.h || 130, text, color };
|
|
1633
|
+
this.notes.push(note);
|
|
1634
|
+
this._emit('change');
|
|
1635
|
+
return note.id;
|
|
1636
|
+
}
|
|
1637
|
+
deleteNote(id) { this.notes = this.notes.filter((n) => n.id !== id); this._emit('change'); }
|
|
1638
|
+
|
|
1639
|
+
// ── Frames (groups) ───────────────────────────────────────────────────
|
|
1640
|
+
addFrame(x, y, w, h, label = 'Group', color = '#5b8def') {
|
|
1641
|
+
const f = { id: ++this._frameSeq, x, y, w, h, label, color };
|
|
1642
|
+
this.frames.push(f);
|
|
1643
|
+
this._emit('change');
|
|
1644
|
+
return f.id;
|
|
1645
|
+
}
|
|
1646
|
+
groupSelection(label) {
|
|
1647
|
+
const sel = this.getSelection();
|
|
1648
|
+
if (sel.length === 0) return -1;
|
|
1649
|
+
let mnx = Infinity, mxx = -Infinity, mny = Infinity, mxy = -Infinity;
|
|
1650
|
+
for (const i of sel) {
|
|
1651
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
1652
|
+
if (this.V.posX[i] - hw < mnx) mnx = this.V.posX[i] - hw;
|
|
1653
|
+
if (this.V.posX[i] + hw > mxx) mxx = this.V.posX[i] + hw;
|
|
1654
|
+
if (this.V.posY[i] - hh < mny) mny = this.V.posY[i] - hh;
|
|
1655
|
+
if (this.V.posY[i] + hh > mxy) mxy = this.V.posY[i] + hh;
|
|
1656
|
+
}
|
|
1657
|
+
const pad = 30;
|
|
1658
|
+
return this.addFrame(mnx - pad, mny - pad - 26, mxx - mnx + pad * 2, mxy - mny + pad * 2 + 26, label || `Group ${this.frames.length + 1}`);
|
|
1659
|
+
}
|
|
1660
|
+
deleteFrame(id) { this.frames = this.frames.filter((f) => f.id !== id); this._emit('change'); }
|
|
1661
|
+
|
|
1662
|
+
// Subflow drill-in: focus on a frame.
|
|
1663
|
+
enterSubflow(fid) {
|
|
1664
|
+
const idx = this.frames.findIndex((f) => f.id === fid);
|
|
1665
|
+
if (idx === -1) return;
|
|
1666
|
+
this._focusFrame = idx;
|
|
1667
|
+
const f = this.frames[idx];
|
|
1668
|
+
this.cam.x = -(f.x + f.w / 2); this.cam.y = -(f.y + f.h / 2);
|
|
1669
|
+
this.cam.zoom = Math.min(this.canvas.width / (f.w + 80), this.canvas.height / (f.h + 80)) * 0.9;
|
|
1670
|
+
this._emit('subflow', f.id);
|
|
1671
|
+
}
|
|
1672
|
+
exitSubflow() {
|
|
1673
|
+
if (this._focusFrame === -1) return;
|
|
1674
|
+
this._focusFrame = -1;
|
|
1675
|
+
this.fitView();
|
|
1676
|
+
this._emit('subflow', null);
|
|
1677
|
+
}
|
|
1678
|
+
_isInsideFocusFrame(nodeId) {
|
|
1679
|
+
if (this._focusFrame === -1) return true;
|
|
1680
|
+
const f = this.frames[this._focusFrame];
|
|
1681
|
+
return this.V.posX[nodeId] >= f.x && this.V.posX[nodeId] <= f.x + f.w &&
|
|
1682
|
+
this.V.posY[nodeId] >= f.y && this.V.posY[nodeId] <= f.y + f.h;
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
_resolveKind(k) {
|
|
1686
|
+
if (typeof k === 'number') return k;
|
|
1687
|
+
const idx = this.kindByName.get(k);
|
|
1688
|
+
if (idx === undefined) throw new Error(`zflow: unknown kind "${k}"`);
|
|
1689
|
+
return idx;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
// ── Layout / view ─────────────────────────────────────────────────────
|
|
1693
|
+
runAutoLayout() {
|
|
1694
|
+
const layers = this.w.autoLayout();
|
|
1695
|
+
this.w.snapshot();
|
|
1696
|
+
this._emit('change');
|
|
1697
|
+
return layers;
|
|
1698
|
+
}
|
|
1699
|
+
runForceLayout(maxFrames = 220) {
|
|
1700
|
+
if (this._forceRaf) cancelAnimationFrame(this._forceRaf);
|
|
1701
|
+
this.w.forceLayoutReset();
|
|
1702
|
+
let i = 0;
|
|
1703
|
+
const tick = () => {
|
|
1704
|
+
this.w.forceLayoutTick(0.05);
|
|
1705
|
+
i++;
|
|
1706
|
+
if (i < maxFrames) this._forceRaf = requestAnimationFrame(tick);
|
|
1707
|
+
else { this._forceRaf = null; this.w.snapshot(); this._emit('change'); }
|
|
1708
|
+
};
|
|
1709
|
+
this._forceRaf = requestAnimationFrame(tick);
|
|
1710
|
+
}
|
|
1711
|
+
fitView(padding = 80) {
|
|
1712
|
+
const n = this.w.nodeCount_();
|
|
1713
|
+
if (n === 0) return;
|
|
1714
|
+
let mnx = Infinity, mxx = -Infinity, mny = Infinity, mxy = -Infinity;
|
|
1715
|
+
for (let i = 0; i < n; i++) {
|
|
1716
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
1717
|
+
if (this.V.posX[i] - hw < mnx) mnx = this.V.posX[i] - hw;
|
|
1718
|
+
if (this.V.posX[i] + hw > mxx) mxx = this.V.posX[i] + hw;
|
|
1719
|
+
if (this.V.posY[i] - hh < mny) mny = this.V.posY[i] - hh;
|
|
1720
|
+
if (this.V.posY[i] + hh > mxy) mxy = this.V.posY[i] + hh;
|
|
1721
|
+
}
|
|
1722
|
+
const bw = mxx - mnx + padding * 2, bh = mxy - mny + padding * 2;
|
|
1723
|
+
this.cam.x = -(mnx + (mxx - mnx) / 2);
|
|
1724
|
+
this.cam.y = -(mny + (mxy - mny) / 2);
|
|
1725
|
+
this.cam.zoom = Math.min(this.canvas.width / bw, this.canvas.height / bh) * 0.85;
|
|
1726
|
+
}
|
|
1727
|
+
zoomTo(zoom) { this.cam.zoom = Math.max(0.2, Math.min(3.0, zoom)); }
|
|
1728
|
+
panTo(x, y) { this.cam.x = -x; this.cam.y = -y; }
|
|
1729
|
+
|
|
1730
|
+
// ── History ───────────────────────────────────────────────────────────
|
|
1731
|
+
undo() { if (this.w.undo()) this._emit('change'); }
|
|
1732
|
+
redo() { if (this.w.redo()) this._emit('change'); }
|
|
1733
|
+
snapshot() { this.w.snapshot(); }
|
|
1734
|
+
|
|
1735
|
+
// ── Algorithms ────────────────────────────────────────────────────────
|
|
1736
|
+
/** Longest path in the DAG via topo-sort + DP. Returns [edgeIds] or []. */
|
|
1737
|
+
criticalPath() {
|
|
1738
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
1739
|
+
if (n === 0) return [];
|
|
1740
|
+
const inDeg = new Uint32Array(n);
|
|
1741
|
+
for (let i = 0; i < m; i++) inDeg[this.V.edgeToN[i]]++;
|
|
1742
|
+
const queue = [];
|
|
1743
|
+
for (let i = 0; i < n; i++) if (inDeg[i] === 0) queue.push(i);
|
|
1744
|
+
const dist = new Int32Array(n);
|
|
1745
|
+
const predEdge = new Int32Array(n); predEdge.fill(-1);
|
|
1746
|
+
const adj = this._buildAdj();
|
|
1747
|
+
let head = 0;
|
|
1748
|
+
while (head < queue.length) {
|
|
1749
|
+
const u = queue[head++];
|
|
1750
|
+
for (const e of (adj.get(u) || [])) {
|
|
1751
|
+
if (dist[u] + 1 > dist[e.to]) { dist[e.to] = dist[u] + 1; predEdge[e.to] = e.edge; }
|
|
1752
|
+
inDeg[e.to]--;
|
|
1753
|
+
if (inDeg[e.to] === 0) queue.push(e.to);
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
let best = 0;
|
|
1757
|
+
for (let i = 1; i < n; i++) if (dist[i] > dist[best]) best = i;
|
|
1758
|
+
if (dist[best] === 0) return [];
|
|
1759
|
+
const path = [];
|
|
1760
|
+
let cur = best;
|
|
1761
|
+
while (predEdge[cur] !== -1) { path.push(predEdge[cur]); cur = this.V.edgeFromN[predEdge[cur]]; }
|
|
1762
|
+
return path;
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/** Tarjan's SCC. Returns array of arrays (each non-trivial SCC's node ids). */
|
|
1766
|
+
findSCCs() {
|
|
1767
|
+
const n = this.w.nodeCount_();
|
|
1768
|
+
const adj = this._buildAdj();
|
|
1769
|
+
const index = new Int32Array(n).fill(-1);
|
|
1770
|
+
const lowlink = new Int32Array(n);
|
|
1771
|
+
const onStack = new Uint8Array(n);
|
|
1772
|
+
const stack = [];
|
|
1773
|
+
const sccs = [];
|
|
1774
|
+
let counter = 0;
|
|
1775
|
+
for (let start = 0; start < n; start++) {
|
|
1776
|
+
if (index[start] !== -1) continue;
|
|
1777
|
+
const work = [{ v: start, child: 0 }];
|
|
1778
|
+
index[start] = counter; lowlink[start] = counter++;
|
|
1779
|
+
stack.push(start); onStack[start] = 1;
|
|
1780
|
+
while (work.length) {
|
|
1781
|
+
const top = work[work.length - 1];
|
|
1782
|
+
const out = adj.get(top.v) || [];
|
|
1783
|
+
if (top.child < out.length) {
|
|
1784
|
+
const wto = out[top.child++].to;
|
|
1785
|
+
if (index[wto] === -1) {
|
|
1786
|
+
index[wto] = counter; lowlink[wto] = counter++;
|
|
1787
|
+
stack.push(wto); onStack[wto] = 1;
|
|
1788
|
+
work.push({ v: wto, child: 0 });
|
|
1789
|
+
} else if (onStack[wto]) {
|
|
1790
|
+
if (index[wto] < lowlink[top.v]) lowlink[top.v] = index[wto];
|
|
1791
|
+
}
|
|
1792
|
+
} else {
|
|
1793
|
+
if (lowlink[top.v] === index[top.v]) {
|
|
1794
|
+
const scc = [];
|
|
1795
|
+
while (stack.length) {
|
|
1796
|
+
const x = stack.pop(); onStack[x] = 0; scc.push(x);
|
|
1797
|
+
if (x === top.v) break;
|
|
1798
|
+
}
|
|
1799
|
+
if (scc.length >= 2) sccs.push(scc);
|
|
1800
|
+
}
|
|
1801
|
+
const finished = top.v;
|
|
1802
|
+
work.pop();
|
|
1803
|
+
if (work.length && lowlink[finished] < lowlink[work[work.length - 1].v]) {
|
|
1804
|
+
lowlink[work[work.length - 1].v] = lowlink[finished];
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
return sccs;
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
/** Heatmap: color every node by its in+out degree. Pass null to clear. */
|
|
1813
|
+
colorByDegree() {
|
|
1814
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
1815
|
+
const deg = new Uint16Array(n);
|
|
1816
|
+
for (let i = 0; i < m; i++) { deg[this.V.edgeFromN[i]]++; deg[this.V.edgeToN[i]]++; }
|
|
1817
|
+
let max = 1;
|
|
1818
|
+
for (let i = 0; i < n; i++) if (deg[i] > max) max = deg[i];
|
|
1819
|
+
const ramp = ['#3b5fc4', '#5b8def', '#5be0d0', '#5bd17a', '#f0b93a', '#fb923c', '#e8462b'];
|
|
1820
|
+
const lerp = (t) => {
|
|
1821
|
+
if (t <= 0) return ramp[0]; if (t >= 1) return ramp[ramp.length - 1];
|
|
1822
|
+
const idx = t * (ramp.length - 1), i0 = Math.floor(idx), i1 = Math.min(ramp.length - 1, i0 + 1);
|
|
1823
|
+
const f = idx - i0; const a = parseHex$1(ramp[i0]), b = parseHex$1(ramp[i1]);
|
|
1824
|
+
return `rgb(${Math.round(a[0]*(1-f)+b[0]*f)},${Math.round(a[1]*(1-f)+b[1]*f)},${Math.round(a[2]*(1-f)+b[2]*f)})`;
|
|
1825
|
+
};
|
|
1826
|
+
for (let i = 0; i < n; i++) this.colors.set(i, lerp(deg[i] / max));
|
|
1827
|
+
this._emit('change');
|
|
1828
|
+
}
|
|
1829
|
+
clearNodeColors() {
|
|
1830
|
+
this.colors.clear();
|
|
1831
|
+
this._emit('change');
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
// ── Imports (Mermaid + DOT) ───────────────────────────────────────────
|
|
1835
|
+
importMermaid(text) {
|
|
1836
|
+
const parsed = parseMermaid(text);
|
|
1837
|
+
if (!parsed || parsed.nodes.size === 0) return 0;
|
|
1838
|
+
const shapeMap = { rect: 'process', rhombus: 'decision', circle: 'branch', round: 'process', subroutine: 'aggregator', default: 'process' };
|
|
1839
|
+
const idMap = new Map();
|
|
1840
|
+
let drop = 0;
|
|
1841
|
+
for (const [mid, def] of parsed.nodes) {
|
|
1842
|
+
const id = this.addNode({
|
|
1843
|
+
kind: shapeMap[def.shape] || 'process',
|
|
1844
|
+
x: (drop % 8) * 200 - 700, y: Math.floor(drop / 8) * 110,
|
|
1845
|
+
title: def.label,
|
|
1846
|
+
});
|
|
1847
|
+
if (id < 0) break;
|
|
1848
|
+
idMap.set(mid, id); drop++;
|
|
1849
|
+
}
|
|
1850
|
+
for (const e of parsed.edges) {
|
|
1851
|
+
const a = idMap.get(e.from), b = idMap.get(e.to);
|
|
1852
|
+
if (a === undefined || b === undefined) continue;
|
|
1853
|
+
this.addEdge({ from: a, to: b, label: e.label });
|
|
1854
|
+
}
|
|
1855
|
+
this.runAutoLayout();
|
|
1856
|
+
this.fitView();
|
|
1857
|
+
return parsed.nodes.size;
|
|
1858
|
+
}
|
|
1859
|
+
importDot(text) {
|
|
1860
|
+
const parsed = parseDot(text);
|
|
1861
|
+
if (!parsed || parsed.nodes.size === 0) return 0;
|
|
1862
|
+
const idMap = new Map();
|
|
1863
|
+
let drop = 0;
|
|
1864
|
+
for (const [mid, def] of parsed.nodes) {
|
|
1865
|
+
const id = this.addNode({ kind: 'process', x: (drop % 8) * 200 - 700, y: Math.floor(drop / 8) * 110, title: def.label });
|
|
1866
|
+
if (id < 0) break;
|
|
1867
|
+
idMap.set(mid, id); drop++;
|
|
1868
|
+
}
|
|
1869
|
+
for (const e of parsed.edges) {
|
|
1870
|
+
const a = idMap.get(e.from), b = idMap.get(e.to);
|
|
1871
|
+
if (a === undefined || b === undefined) continue;
|
|
1872
|
+
const eid = this.addEdge({ from: a, to: b });
|
|
1873
|
+
if (eid >= 0 && e.label) this.setEdgeLabel(eid, e.label);
|
|
1874
|
+
}
|
|
1875
|
+
this.runAutoLayout();
|
|
1876
|
+
this.fitView();
|
|
1877
|
+
return parsed.nodes.size;
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
/** Returns an array of edge indices forming the shortest path, or [] if unreachable. */
|
|
1881
|
+
shortestPathSafe(from, to) { return this.shortestPath(from, to) || []; }
|
|
1882
|
+
shortestPath(from, to) {
|
|
1883
|
+
const adj = this._buildAdj();
|
|
1884
|
+
const prev = new Map(); prev.set(from, null);
|
|
1885
|
+
const queue = [from];
|
|
1886
|
+
while (queue.length) {
|
|
1887
|
+
const u = queue.shift();
|
|
1888
|
+
if (u === to) break;
|
|
1889
|
+
for (const e of (adj.get(u) || [])) {
|
|
1890
|
+
if (!prev.has(e.to)) { prev.set(e.to, { from: u, edgeIdx: e.edge }); queue.push(e.to); }
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
if (!prev.has(to)) return [];
|
|
1894
|
+
const path = [];
|
|
1895
|
+
let cur = to;
|
|
1896
|
+
while (prev.get(cur)) { path.push(prev.get(cur).edgeIdx); cur = prev.get(cur).from; }
|
|
1897
|
+
return path.reverse();
|
|
1898
|
+
}
|
|
1899
|
+
findCycles() {
|
|
1900
|
+
const n = this.w.nodeCount_();
|
|
1901
|
+
const color = new Uint8Array(n);
|
|
1902
|
+
const result = new Set();
|
|
1903
|
+
const adj = this._buildAdj();
|
|
1904
|
+
for (let start = 0; start < n; start++) {
|
|
1905
|
+
if (color[start] !== 0) continue;
|
|
1906
|
+
const stack = [{ u: start, iter: (adj.get(start) || [])[Symbol.iterator]() }];
|
|
1907
|
+
color[start] = 1;
|
|
1908
|
+
while (stack.length) {
|
|
1909
|
+
const top = stack[stack.length - 1];
|
|
1910
|
+
const next = top.iter.next();
|
|
1911
|
+
if (next.done) { color[top.u] = 2; stack.pop(); continue; }
|
|
1912
|
+
const e = next.value;
|
|
1913
|
+
if (color[e.to] === 1) result.add(e.edge);
|
|
1914
|
+
else if (color[e.to] === 0) {
|
|
1915
|
+
color[e.to] = 1;
|
|
1916
|
+
stack.push({ u: e.to, iter: (adj.get(e.to) || [])[Symbol.iterator]() });
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
return [...result];
|
|
1921
|
+
}
|
|
1922
|
+
/** Build per-node edge-id adjacency for fast dirty-marking. */
|
|
1923
|
+
_ensureAdj() {
|
|
1924
|
+
if (!this._adjDirty && this._nodeAdj) return;
|
|
1925
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
1926
|
+
const adj = new Array(n);
|
|
1927
|
+
for (let i = 0; i < n; i++) adj[i] = [];
|
|
1928
|
+
for (let e = 0; e < m; e++) {
|
|
1929
|
+
const a = this.V.edgeFromN[e], b = this.V.edgeToN[e];
|
|
1930
|
+
if (a < n) adj[a].push(e);
|
|
1931
|
+
if (b < n && a !== b) adj[b].push(e);
|
|
1932
|
+
}
|
|
1933
|
+
this._nodeAdj = adj;
|
|
1934
|
+
this._adjDirty = false;
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
_buildAdj() {
|
|
1938
|
+
const m = this.w.edgeCount_();
|
|
1939
|
+
const adj = new Map();
|
|
1940
|
+
for (let i = 0; i < m; i++) {
|
|
1941
|
+
const a = this.V.edgeFromN[i];
|
|
1942
|
+
if (!adj.has(a)) adj.set(a, []);
|
|
1943
|
+
adj.get(a).push({ to: this.V.edgeToN[i], edge: i });
|
|
1944
|
+
}
|
|
1945
|
+
return adj;
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// ── Persistence ───────────────────────────────────────────────────────
|
|
1949
|
+
toJSON() {
|
|
1950
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
1951
|
+
const nodes = [];
|
|
1952
|
+
for (let i = 0; i < n; i++) {
|
|
1953
|
+
const node = {
|
|
1954
|
+
id: i, kind: this.kinds[this.V.kind[i]].name,
|
|
1955
|
+
x: this.V.posX[i], y: this.V.posY[i],
|
|
1956
|
+
w: this.V.sizeW[i], h: this.V.sizeH[i],
|
|
1957
|
+
nin: this.V.nIn[i], nout: this.V.nOut[i],
|
|
1958
|
+
};
|
|
1959
|
+
if (this.titles.has(i)) node.title = this.titles.get(i);
|
|
1960
|
+
if (this.colors.has(i)) node.color = this.colors.get(i);
|
|
1961
|
+
if (this.descriptions.has(i)) node.description = this.descriptions.get(i);
|
|
1962
|
+
if (this.tags.has(i)) node.tags = this.tags.get(i);
|
|
1963
|
+
if (this.status.has(i)) node.status = this.status.get(i);
|
|
1964
|
+
if (this.progress.has(i)) node.progress = this.progress.get(i);
|
|
1965
|
+
nodes.push(node);
|
|
1966
|
+
}
|
|
1967
|
+
const edges = [];
|
|
1968
|
+
for (let i = 0; i < m; i++) {
|
|
1969
|
+
const edge = { from: this.V.edgeFromN[i], fp: this.V.edgeFromP[i],
|
|
1970
|
+
to: this.V.edgeToN[i], tp: this.V.edgeToP[i] };
|
|
1971
|
+
if (this.edgeLabels.has(i)) edge.label = this.edgeLabels.get(i);
|
|
1972
|
+
edges.push(edge);
|
|
1973
|
+
}
|
|
1974
|
+
return {
|
|
1975
|
+
version: 1, nodes, edges,
|
|
1976
|
+
camera: { ...this.cam },
|
|
1977
|
+
edgeStyle: this.options.edgeStyle,
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
loadJSON(data) {
|
|
1981
|
+
this.w.reset();
|
|
1982
|
+
this.titles.clear(); this.colors.clear(); this.descriptions.clear();
|
|
1983
|
+
this.tags.clear(); this.status.clear(); this.progress.clear();
|
|
1984
|
+
this.edgeLabels.clear();
|
|
1985
|
+
const idMap = new Map();
|
|
1986
|
+
for (const node of (data.nodes || [])) {
|
|
1987
|
+
const id = this.addNode({
|
|
1988
|
+
kind: node.kind, x: node.x, y: node.y, w: node.w, h: node.h,
|
|
1989
|
+
title: node.title, color: node.color, description: node.description,
|
|
1990
|
+
tags: node.tags, status: node.status, progress: node.progress,
|
|
1991
|
+
});
|
|
1992
|
+
idMap.set(node.id ?? id, id);
|
|
1993
|
+
}
|
|
1994
|
+
for (const edge of (data.edges || [])) {
|
|
1995
|
+
this.addEdge({
|
|
1996
|
+
from: idMap.get(edge.from) ?? edge.from, fp: edge.fp,
|
|
1997
|
+
to: idMap.get(edge.to) ?? edge.to, tp: edge.tp,
|
|
1998
|
+
label: edge.label,
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
if (data.camera) Object.assign(this.cam, data.camera);
|
|
2002
|
+
if (data.edgeStyle) this.options.edgeStyle = data.edgeStyle;
|
|
2003
|
+
this.w.snapshot();
|
|
2004
|
+
this._emit('change');
|
|
2005
|
+
}
|
|
2006
|
+
async exportPNG() {
|
|
2007
|
+
return new Promise((resolve) => this.canvas.toBlob(resolve, 'image/png'));
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
/** Build a standalone SVG document representing the current graph. */
|
|
2011
|
+
exportSVG() {
|
|
2012
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
2013
|
+
if (n === 0) return '<svg xmlns="http://www.w3.org/2000/svg"/>';
|
|
2014
|
+
let mnx = Infinity, mxx = -Infinity, mny = Infinity, mxy = -Infinity;
|
|
2015
|
+
for (let i = 0; i < n; i++) {
|
|
2016
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
2017
|
+
if (this.V.posX[i] - hw < mnx) mnx = this.V.posX[i] - hw;
|
|
2018
|
+
if (this.V.posX[i] + hw > mxx) mxx = this.V.posX[i] + hw;
|
|
2019
|
+
if (this.V.posY[i] - hh < mny) mny = this.V.posY[i] - hh;
|
|
2020
|
+
if (this.V.posY[i] + hh > mxy) mxy = this.V.posY[i] + hh;
|
|
2021
|
+
}
|
|
2022
|
+
const pad = 40;
|
|
2023
|
+
const bw = mxx - mnx + pad * 2, bh = mxy - mny + pad * 2;
|
|
2024
|
+
const out = [`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${mnx - pad} ${mny - pad} ${bw} ${bh}" width="${bw}" height="${bh}" style="background:${this.options.background}">`];
|
|
2025
|
+
for (let i = 0; i < m; i++) {
|
|
2026
|
+
const a = this.V.edgeFromN[i], b = this.V.edgeToN[i];
|
|
2027
|
+
const ap = this._portWorld(a, 1, this.V.edgeFromP[i]);
|
|
2028
|
+
const bp = this._portWorld(b, 0, this.V.edgeToP[i]);
|
|
2029
|
+
const cA = this.colors.get(a) || this.kinds[this.V.kind[a]].color;
|
|
2030
|
+
const cB = this.colors.get(b) || this.kinds[this.V.kind[b]].color;
|
|
2031
|
+
const gid = `g${i}`;
|
|
2032
|
+
out.push(`<defs><linearGradient id="${gid}" x1="${ap.x}" y1="${ap.y}" x2="${bp.x}" y2="${bp.y}" gradientUnits="userSpaceOnUse"><stop offset="0%" stop-color="${cA}"/><stop offset="100%" stop-color="${cB}"/></linearGradient></defs>`);
|
|
2033
|
+
if (this.options.edgeStyle === 'orthogonal') {
|
|
2034
|
+
const path = this._orthoPath(ap, bp);
|
|
2035
|
+
const d = `M ${path[0].x} ${path[0].y} ` + path.slice(1).map((p) => `L ${p.x} ${p.y}`).join(' ');
|
|
2036
|
+
out.push(`<path d="${d}" stroke="url(#${gid})" stroke-width="1.7" fill="none" stroke-linejoin="round"/>`);
|
|
2037
|
+
} else {
|
|
2038
|
+
const dx = bp.x - ap.x, dy = bp.y - ap.y;
|
|
2039
|
+
const off = Math.max(50, Math.abs(dx) * 0.5 + Math.abs(dy) * 0.4);
|
|
2040
|
+
out.push(`<path d="M ${ap.x} ${ap.y} C ${ap.x + off} ${ap.y} ${bp.x - off} ${bp.y} ${bp.x} ${bp.y}" stroke="url(#${gid})" stroke-width="1.7" fill="none"/>`);
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
for (let i = 0; i < n; i++) {
|
|
2044
|
+
const cat = this.kinds[this.V.kind[i]];
|
|
2045
|
+
const color = this.colors.get(i) || cat.color;
|
|
2046
|
+
const x = this.V.posX[i] - this.V.sizeW[i] / 2;
|
|
2047
|
+
const y = this.V.posY[i] - this.V.sizeH[i] / 2;
|
|
2048
|
+
const w = this.V.sizeW[i], h = this.V.sizeH[i];
|
|
2049
|
+
if (cat.shape === 'diamond') {
|
|
2050
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
2051
|
+
out.push(`<polygon points="${cx},${y} ${x+w},${cy} ${cx},${y+h} ${x},${cy}" fill="#161b27" stroke="${color}" stroke-width="1.4"/>`);
|
|
2052
|
+
} else if (cat.shape === 'ellipse') {
|
|
2053
|
+
out.push(`<ellipse cx="${this.V.posX[i]}" cy="${this.V.posY[i]}" rx="${w/2}" ry="${h/2}" fill="#161b27" stroke="${color}" stroke-width="1.4"/>`);
|
|
2054
|
+
} else {
|
|
2055
|
+
out.push(`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="8" fill="#161b27" stroke="${color}" stroke-width="1.4"/>`);
|
|
2056
|
+
if (cat.shape === 'rect') out.push(`<rect x="${x}" y="${y}" width="${w}" height="22" rx="8" fill="${color}"/>`);
|
|
2057
|
+
}
|
|
2058
|
+
const title = this.titles.get(i) || `${cat.name} #${i}`;
|
|
2059
|
+
out.push(`<text x="${this.V.posX[i]}" y="${y + (cat.shape === 'rect' ? 14 : h/2)}" font-family="Inter, system-ui, sans-serif" font-size="11" font-weight="600" text-anchor="middle" fill="${cat.shape === 'rect' ? '#0b0f17' : color}">${escapeXml(title)}</text>`);
|
|
2060
|
+
}
|
|
2061
|
+
out.push('</svg>');
|
|
2062
|
+
return out.join('\n');
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
// ── Events ────────────────────────────────────────────────────────────
|
|
2066
|
+
on(event, fn) {
|
|
2067
|
+
if (!this.listeners.has(event)) this.listeners.set(event, []);
|
|
2068
|
+
this.listeners.get(event).push(fn);
|
|
2069
|
+
return () => { const arr = this.listeners.get(event); const i = arr.indexOf(fn); if (i >= 0) arr.splice(i, 1); };
|
|
2070
|
+
}
|
|
2071
|
+
_emit(event, ...args) {
|
|
2072
|
+
if (this._suspendEvents && event !== 'change') return;
|
|
2073
|
+
const arr = this.listeners.get(event);
|
|
2074
|
+
if (!arr) return;
|
|
2075
|
+
for (const fn of arr.slice()) try { fn(...args); } catch (e) { console.error(e); }
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
// ── Coordinate helpers ────────────────────────────────────────────────
|
|
2079
|
+
_resize() {
|
|
2080
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2081
|
+
const r = this.container.getBoundingClientRect();
|
|
2082
|
+
this.canvas.width = Math.floor(r.width * dpr);
|
|
2083
|
+
this.canvas.height = Math.floor(r.height * dpr);
|
|
2084
|
+
this.canvas.style.width = r.width + 'px';
|
|
2085
|
+
this.canvas.style.height = r.height + 'px';
|
|
2086
|
+
}
|
|
2087
|
+
_w2s(wx, wy) {
|
|
2088
|
+
return { x: this.canvas.width / 2 + (wx + this.cam.x) * this.cam.zoom,
|
|
2089
|
+
y: this.canvas.height / 2 + (wy + this.cam.y) * this.cam.zoom };
|
|
2090
|
+
}
|
|
2091
|
+
_s2w(cx, cy) {
|
|
2092
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2093
|
+
const r = this.canvas.getBoundingClientRect();
|
|
2094
|
+
const sx = (cx - r.left) * dpr, sy = (cy - r.top) * dpr;
|
|
2095
|
+
return { x: (sx - this.canvas.width / 2) / this.cam.zoom - this.cam.x,
|
|
2096
|
+
y: (sy - this.canvas.height / 2) / this.cam.zoom - this.cam.y };
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
// ── Interactions ──────────────────────────────────────────────────────
|
|
2100
|
+
_attachEvents() {
|
|
2101
|
+
const c = this.canvas;
|
|
2102
|
+
c.addEventListener('contextmenu', (e) => e.preventDefault());
|
|
2103
|
+
|
|
2104
|
+
c.addEventListener('mousedown', (e) => {
|
|
2105
|
+
this._hideMenu();
|
|
2106
|
+
if (this._editingNoteEl && this._editingNote !== -1) this._editingNoteEl.blur();
|
|
2107
|
+
if (this._editingTitleEl && this._editingTitle !== -1) this._editingTitleEl.blur();
|
|
2108
|
+
const wp = this._s2w(e.clientX, e.clientY);
|
|
2109
|
+
if (e.button === 2) { this._onRightClick(e, wp); return; }
|
|
2110
|
+
if (e.button === 1) { this._startPan(e); return; }
|
|
2111
|
+
// Port? (bidirectional)
|
|
2112
|
+
const ph = this.w.hitTestPort(wp.x, wp.y, 11);
|
|
2113
|
+
if (ph !== -1) {
|
|
2114
|
+
const side = (ph >>> 24) & 0xFF, idx = (ph >>> 16) & 0xFF, nid = ph & 0xFFFF;
|
|
2115
|
+
this._mode = 'connecting';
|
|
2116
|
+
this._edgeStart = { nodeId: nid, side, idx };
|
|
2117
|
+
this._edgeCursor = wp;
|
|
2118
|
+
this.canvas.style.cursor = 'crosshair';
|
|
2119
|
+
return;
|
|
2120
|
+
}
|
|
2121
|
+
// Resize handle?
|
|
2122
|
+
const handle = this._hitHandle(wp.x, wp.y);
|
|
2123
|
+
if (handle && !this.readOnly && !this.locked.has(handle.nodeId)) {
|
|
2124
|
+
this._mode = 'resize';
|
|
2125
|
+
this._resizingHandle = { ...handle, lastX: wp.x, lastY: wp.y };
|
|
2126
|
+
return;
|
|
2127
|
+
}
|
|
2128
|
+
// Edge waypoint drag?
|
|
2129
|
+
const wpHit = this._hitWaypoint(wp.x, wp.y);
|
|
2130
|
+
if (wpHit && !this.readOnly) {
|
|
2131
|
+
this._draggingWaypoint = wpHit;
|
|
2132
|
+
this._mode = 'drag-waypoint';
|
|
2133
|
+
return;
|
|
2134
|
+
}
|
|
2135
|
+
// Frame corner resize?
|
|
2136
|
+
const fc = this._hitFrameCorner(wp.x, wp.y);
|
|
2137
|
+
if (fc) {
|
|
2138
|
+
this._mode = 'resize-frame';
|
|
2139
|
+
this._resizingFrame = { ...fc, lastX: wp.x, lastY: wp.y };
|
|
2140
|
+
return;
|
|
2141
|
+
}
|
|
2142
|
+
// Frame header drag?
|
|
2143
|
+
const fh = this._hitFrameHeader(wp.x, wp.y);
|
|
2144
|
+
if (fh !== -1) {
|
|
2145
|
+
this._mode = 'drag-frame';
|
|
2146
|
+
this._draggingFrame = fh;
|
|
2147
|
+
this._frameDragLast = wp;
|
|
2148
|
+
return;
|
|
2149
|
+
}
|
|
2150
|
+
// Sticky note drag?
|
|
2151
|
+
const nh = this._hitNote(wp.x, wp.y);
|
|
2152
|
+
if (nh !== -1) {
|
|
2153
|
+
this._mode = 'drag-note';
|
|
2154
|
+
this._draggingNote = nh;
|
|
2155
|
+
this._noteDragLast = wp;
|
|
2156
|
+
return;
|
|
2157
|
+
}
|
|
2158
|
+
// Sub-task checkbox click?
|
|
2159
|
+
const taskHit = this._hitTaskCheckbox(wp.x, wp.y);
|
|
2160
|
+
if (taskHit) {
|
|
2161
|
+
const list = this.tasks.get(taskHit.nodeId);
|
|
2162
|
+
if (list && list[taskHit.taskIdx]) {
|
|
2163
|
+
list[taskHit.taskIdx].done = !list[taskHit.taskIdx].done;
|
|
2164
|
+
const done = list.filter((t) => t.done).length;
|
|
2165
|
+
this.progress.set(taskHit.nodeId, done / list.length);
|
|
2166
|
+
this._emit('change');
|
|
2167
|
+
}
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
// Node?
|
|
2171
|
+
const nid = this.w.hitTestNode(wp.x, wp.y);
|
|
2172
|
+
if (nid !== -1) {
|
|
2173
|
+
if (!e.shiftKey && this.V.selected[nid] === 0) { this.w.clearSelection(); this.w.setSelected(nid, 1); }
|
|
2174
|
+
else if (e.shiftKey) this.w.toggleSelected(nid);
|
|
2175
|
+
// Locked / read-only → select but do not drag.
|
|
2176
|
+
if (!this.readOnly && !this.locked.has(nid)) {
|
|
2177
|
+
this._mode = 'drag';
|
|
2178
|
+
this._dragLast = wp;
|
|
2179
|
+
}
|
|
2180
|
+
this._emit('select', this.getSelection());
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
// Edge click → select.
|
|
2184
|
+
const eid = this._hitTestEdge(wp.x, wp.y, 6 / this.cam.zoom);
|
|
2185
|
+
if (eid !== -1) {
|
|
2186
|
+
if (!e.shiftKey) this.w.clearSelection();
|
|
2187
|
+
this.w.setEdgeSelected(eid, 1);
|
|
2188
|
+
this._emit('select', this.getSelection());
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
// Alt-drag empty → lasso.
|
|
2192
|
+
if (e.altKey) {
|
|
2193
|
+
if (!e.shiftKey) this.w.clearSelection();
|
|
2194
|
+
this._mode = 'lasso';
|
|
2195
|
+
this._lasso = [{ x: wp.x, y: wp.y }];
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
// Empty space → marquee.
|
|
2199
|
+
if (!e.shiftKey) this.w.clearSelection();
|
|
2200
|
+
this._mode = 'marquee';
|
|
2201
|
+
this._marquee = { x0: wp.x, y0: wp.y, x1: wp.x, y1: wp.y };
|
|
2202
|
+
});
|
|
2203
|
+
|
|
2204
|
+
c.addEventListener('mousemove', (e) => {
|
|
2205
|
+
const wp = this._s2w(e.clientX, e.clientY);
|
|
2206
|
+
if (this._mode === 'pan') {
|
|
2207
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2208
|
+
const dxW = (e.clientX - this._dragStart.sx) * dpr / this.cam.zoom;
|
|
2209
|
+
const dyW = (e.clientY - this._dragStart.sy) * dpr / this.cam.zoom;
|
|
2210
|
+
this.cam.x += dxW; this.cam.y += dyW;
|
|
2211
|
+
const now = performance.now();
|
|
2212
|
+
const dt = Math.max(1, now - (this._panVel.lastTs || now)) / 1000;
|
|
2213
|
+
this._panVel.x = dxW / dt; this._panVel.y = dyW / dt; this._panVel.lastTs = now;
|
|
2214
|
+
this._dragStart.sx = e.clientX; this._dragStart.sy = e.clientY;
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
if (this._mode === 'resize' && this._resizingHandle) {
|
|
2218
|
+
const dx = wp.x - this._resizingHandle.lastX, dy = wp.y - this._resizingHandle.lastY;
|
|
2219
|
+
this._applyResize(this._resizingHandle.corner, dx, dy);
|
|
2220
|
+
this._resizingHandle.lastX = wp.x; this._resizingHandle.lastY = wp.y;
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (this._mode === 'drag-waypoint' && this._draggingWaypoint) {
|
|
2224
|
+
const { edgeIdx, wpIdx } = this._draggingWaypoint;
|
|
2225
|
+
const list = this._edgeWaypoints.get(edgeIdx);
|
|
2226
|
+
if (list && list[wpIdx]) { list[wpIdx].x = wp.x; list[wpIdx].y = wp.y; }
|
|
2227
|
+
return;
|
|
2228
|
+
}
|
|
2229
|
+
if (this._mode === 'drag') {
|
|
2230
|
+
if (this._gl) {
|
|
2231
|
+
this._ensureAdj();
|
|
2232
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) if (this.V.selected[i]) {
|
|
2233
|
+
this._gl.markNodeDirty(i);
|
|
2234
|
+
const edges = this._nodeAdj[i];
|
|
2235
|
+
if (edges) for (let k = 0; k < edges.length; k++) this._gl.markEdgeDirty(edges[k]);
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
let dx = wp.x - this._dragLast.x, dy = wp.y - this._dragLast.y;
|
|
2239
|
+
if (this.options.snapToGrid) {
|
|
2240
|
+
// Snap by the first selected node.
|
|
2241
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) {
|
|
2242
|
+
if (this.V.selected[i]) {
|
|
2243
|
+
const grid = this.options.gridSize;
|
|
2244
|
+
const nx = Math.round((this.V.posX[i] + dx) / grid) * grid;
|
|
2245
|
+
const ny = Math.round((this.V.posY[i] + dy) / grid) * grid;
|
|
2246
|
+
dx = nx - this.V.posX[i]; dy = ny - this.V.posY[i]; break;
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
this._alignGuides = null;
|
|
2250
|
+
} else {
|
|
2251
|
+
const sa = this._computeAlignSnap(dx, dy);
|
|
2252
|
+
dx += sa.dx; dy += sa.dy;
|
|
2253
|
+
this._alignGuides = { v: sa.guideX !== null ? [sa.guideX] : [],
|
|
2254
|
+
h: sa.guideY !== null ? [sa.guideY] : [] };
|
|
2255
|
+
}
|
|
2256
|
+
this.w.moveSelectedBy(dx, dy);
|
|
2257
|
+
this._dragLast = { x: this._dragLast.x + dx, y: this._dragLast.y + dy };
|
|
2258
|
+
return;
|
|
2259
|
+
}
|
|
2260
|
+
if (this._mode === 'drag-frame') {
|
|
2261
|
+
const dx = wp.x - this._frameDragLast.x, dy = wp.y - this._frameDragLast.y;
|
|
2262
|
+
const f = this.frames[this._draggingFrame];
|
|
2263
|
+
f.x += dx; f.y += dy;
|
|
2264
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) {
|
|
2265
|
+
if (this.V.posX[i] >= f.x && this.V.posX[i] <= f.x + f.w &&
|
|
2266
|
+
this.V.posY[i] >= f.y && this.V.posY[i] <= f.y + f.h) {
|
|
2267
|
+
this.V.posX[i] += dx; this.V.posY[i] += dy;
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
this._frameDragLast = wp;
|
|
2271
|
+
return;
|
|
2272
|
+
}
|
|
2273
|
+
if (this._mode === 'resize-frame' && this._resizingFrame) {
|
|
2274
|
+
const dx = wp.x - this._resizingFrame.lastX, dy = wp.y - this._resizingFrame.lastY;
|
|
2275
|
+
this._applyFrameResize(this._resizingFrame.idx, this._resizingFrame.corner, dx, dy);
|
|
2276
|
+
this._resizingFrame.lastX = wp.x; this._resizingFrame.lastY = wp.y;
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
if (this._mode === 'drag-note') {
|
|
2280
|
+
const dx = wp.x - this._noteDragLast.x, dy = wp.y - this._noteDragLast.y;
|
|
2281
|
+
const n = this.notes[this._draggingNote];
|
|
2282
|
+
n.x += dx; n.y += dy;
|
|
2283
|
+
this._noteDragLast = wp;
|
|
2284
|
+
return;
|
|
2285
|
+
}
|
|
2286
|
+
if (this._mode === 'connecting') {
|
|
2287
|
+
this._edgeCursor = wp;
|
|
2288
|
+
return;
|
|
2289
|
+
}
|
|
2290
|
+
if (this._mode === 'lasso' && this._lasso) {
|
|
2291
|
+
const last = this._lasso[this._lasso.length - 1];
|
|
2292
|
+
if (Math.hypot(wp.x - last.x, wp.y - last.y) > 6 / this.cam.zoom) {
|
|
2293
|
+
this._lasso.push({ x: wp.x, y: wp.y });
|
|
2294
|
+
}
|
|
2295
|
+
return;
|
|
2296
|
+
}
|
|
2297
|
+
if (this._mode === 'marquee') {
|
|
2298
|
+
this._marquee.x1 = wp.x; this._marquee.y1 = wp.y;
|
|
2299
|
+
this.w.selectInRect(this._marquee.x0, this._marquee.y0, this._marquee.x1, this._marquee.y1, 1);
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
// Idle hover.
|
|
2303
|
+
const newHover = this.w.hitTestNode(wp.x, wp.y);
|
|
2304
|
+
if (newHover !== this._hoveredNode) {
|
|
2305
|
+
this._hoveredNode = newHover;
|
|
2306
|
+
this._hoveredNodeSince = performance.now();
|
|
2307
|
+
this._lastFocusComputed = -2;
|
|
2308
|
+
}
|
|
2309
|
+
this._hoveredEdge = newHover === -1 ? this._hitTestEdge(wp.x, wp.y, 6 / this.cam.zoom) : -1;
|
|
2310
|
+
const handle = this._hitHandle(wp.x, wp.y);
|
|
2311
|
+
c.style.cursor = handle ? HANDLE_CURSOR[handle.corner] : '';
|
|
2312
|
+
});
|
|
2313
|
+
|
|
2314
|
+
c.addEventListener('mouseup', () => {
|
|
2315
|
+
if (this._mode === 'connecting' && this._edgeCursor) {
|
|
2316
|
+
// Bidirectional: accept either output→input or input→output drop.
|
|
2317
|
+
const ph = this.w.hitTestPort(this._edgeCursor.x, this._edgeCursor.y, 14);
|
|
2318
|
+
if (ph !== -1) {
|
|
2319
|
+
const ts = (ph >>> 24) & 0xFF, ti = (ph >>> 16) & 0xFF, tn = ph & 0xFFFF;
|
|
2320
|
+
if (ts !== this._edgeStart.side && tn !== this._edgeStart.nodeId) {
|
|
2321
|
+
const fromN = this._edgeStart.side === 1 ? this._edgeStart.nodeId : tn;
|
|
2322
|
+
const fromP = this._edgeStart.side === 1 ? this._edgeStart.idx : ti;
|
|
2323
|
+
const toN = this._edgeStart.side === 0 ? this._edgeStart.nodeId : tn;
|
|
2324
|
+
const toP = this._edgeStart.side === 0 ? this._edgeStart.idx : ti;
|
|
2325
|
+
const reason = this.validateConnection(fromN, fromP, toN, toP);
|
|
2326
|
+
if (reason === null) {
|
|
2327
|
+
this.addEdge({ from: fromN, fp: fromP, to: toN, tp: toP });
|
|
2328
|
+
} else {
|
|
2329
|
+
this._emit('connection:rejected', { fromN, fromP, toN, toP, reason });
|
|
2330
|
+
this._flashReject = { x: this._edgeCursor.x, y: this._edgeCursor.y, msg: reason, t0: performance.now() };
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
} else if (this._mode === 'lasso' && this._lasso && this._lasso.length > 2) {
|
|
2335
|
+
for (let i = 0; i < this.w.nodeCount_(); i++) {
|
|
2336
|
+
if (pointInPolygon(this.V.posX[i], this.V.posY[i], this._lasso)) this.w.setSelected(i, 1);
|
|
2337
|
+
}
|
|
2338
|
+
this._emit('select', this.getSelection());
|
|
2339
|
+
} else if (this._mode === 'drag-waypoint') {
|
|
2340
|
+
this._draggingWaypoint = null;
|
|
2341
|
+
this._emit('change');
|
|
2342
|
+
} else if (this._mode === 'drag' || this._mode === 'resize' ||
|
|
2343
|
+
this._mode === 'drag-frame' || this._mode === 'resize-frame' || this._mode === 'drag-note' ||
|
|
2344
|
+
this._mode === 'marquee') {
|
|
2345
|
+
if (this._mode !== 'marquee') { this.w.snapshot(); this._emit('change'); }
|
|
2346
|
+
this._emit('select', this.getSelection());
|
|
2347
|
+
}
|
|
2348
|
+
this._mode = 'idle';
|
|
2349
|
+
this._edgeStart = null; this._edgeCursor = null;
|
|
2350
|
+
this._marquee = null; this._lasso = null; this._alignGuides = null;
|
|
2351
|
+
this._resizingHandle = null; this._resizingFrame = null;
|
|
2352
|
+
this._draggingFrame = -1; this._draggingNote = -1;
|
|
2353
|
+
this.canvas.classList.remove('panning');
|
|
2354
|
+
this.canvas.style.cursor = '';
|
|
2355
|
+
});
|
|
2356
|
+
|
|
2357
|
+
// ── Touch: pinch zoom + two-finger pan ────────────────────────────
|
|
2358
|
+
const pointers = new Map(); // pointerId -> { x, y }
|
|
2359
|
+
let pinchPrev = null; // { dist, mid }
|
|
2360
|
+
let longPressTimer = null;
|
|
2361
|
+
// Track which mouse events came synthesized from pointer to suppress double-firing.
|
|
2362
|
+
this._pointerSynthesizing = false;
|
|
2363
|
+
c.addEventListener('pointerdown', (e) => {
|
|
2364
|
+
if (e.pointerType === 'mouse') return; // mouse already handled
|
|
2365
|
+
c.setPointerCapture(e.pointerId);
|
|
2366
|
+
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
2367
|
+
if (pointers.size === 2) {
|
|
2368
|
+
pinchPrev = pinchInfo(pointers);
|
|
2369
|
+
this._mode = 'pinch';
|
|
2370
|
+
} else if (pointers.size === 1) {
|
|
2371
|
+
// Start long-press timer for context menu.
|
|
2372
|
+
const x = e.clientX, y = e.clientY;
|
|
2373
|
+
longPressTimer = setTimeout(() => {
|
|
2374
|
+
longPressTimer = null;
|
|
2375
|
+
const wp = this._s2w(x, y);
|
|
2376
|
+
this._onRightClick({ clientX: x, clientY: y, preventDefault() {} }, wp);
|
|
2377
|
+
}, 550);
|
|
2378
|
+
// Simulate a left mousedown for taps.
|
|
2379
|
+
this._pointerSynthesizing = true;
|
|
2380
|
+
c.dispatchEvent(new MouseEvent('mousedown', { clientX: x, clientY: y, button: 0, bubbles: true }));
|
|
2381
|
+
this._pointerSynthesizing = false;
|
|
2382
|
+
}
|
|
2383
|
+
});
|
|
2384
|
+
c.addEventListener('pointermove', (e) => {
|
|
2385
|
+
if (e.pointerType === 'mouse') return;
|
|
2386
|
+
if (!pointers.has(e.pointerId)) return;
|
|
2387
|
+
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
2388
|
+
if (pointers.size === 2 && pinchPrev) {
|
|
2389
|
+
const cur = pinchInfo(pointers);
|
|
2390
|
+
const zoomFactor = cur.dist / pinchPrev.dist;
|
|
2391
|
+
const before = this._s2w(cur.mid.x, cur.mid.y);
|
|
2392
|
+
this.cam.zoom = Math.max(0.2, Math.min(3.0, this.cam.zoom * zoomFactor));
|
|
2393
|
+
const after = this._s2w(cur.mid.x, cur.mid.y);
|
|
2394
|
+
this.cam.x += after.x - before.x; this.cam.y += after.y - before.y;
|
|
2395
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2396
|
+
this.cam.x += (cur.mid.x - pinchPrev.mid.x) * dpr / this.cam.zoom;
|
|
2397
|
+
this.cam.y += (cur.mid.y - pinchPrev.mid.y) * dpr / this.cam.zoom;
|
|
2398
|
+
pinchPrev = cur;
|
|
2399
|
+
} else if (pointers.size === 1) {
|
|
2400
|
+
if (longPressTimer && Math.hypot(e.movementX || 0, e.movementY || 0) > 4) {
|
|
2401
|
+
clearTimeout(longPressTimer); longPressTimer = null;
|
|
2402
|
+
}
|
|
2403
|
+
this._pointerSynthesizing = true;
|
|
2404
|
+
c.dispatchEvent(new MouseEvent('mousemove', { clientX: e.clientX, clientY: e.clientY, button: 0, bubbles: true }));
|
|
2405
|
+
this._pointerSynthesizing = false;
|
|
2406
|
+
}
|
|
2407
|
+
});
|
|
2408
|
+
const endPointer = (e) => {
|
|
2409
|
+
if (e.pointerType === 'mouse') return;
|
|
2410
|
+
pointers.delete(e.pointerId);
|
|
2411
|
+
if (longPressTimer) { clearTimeout(longPressTimer); longPressTimer = null; }
|
|
2412
|
+
if (pointers.size < 2) { pinchPrev = null; if (this._mode === 'pinch') this._mode = 'idle'; }
|
|
2413
|
+
if (pointers.size === 0) {
|
|
2414
|
+
this._pointerSynthesizing = true;
|
|
2415
|
+
c.dispatchEvent(new MouseEvent('mouseup', { clientX: e.clientX, clientY: e.clientY, button: 0, bubbles: true }));
|
|
2416
|
+
this._pointerSynthesizing = false;
|
|
2417
|
+
}
|
|
2418
|
+
};
|
|
2419
|
+
c.addEventListener('pointerup', endPointer);
|
|
2420
|
+
c.addEventListener('pointercancel', endPointer);
|
|
2421
|
+
|
|
2422
|
+
c.addEventListener('wheel', (e) => {
|
|
2423
|
+
e.preventDefault();
|
|
2424
|
+
const isPinch = e.ctrlKey;
|
|
2425
|
+
if (isPinch || e.deltaMode === 1) {
|
|
2426
|
+
const before = this._s2w(e.clientX, e.clientY);
|
|
2427
|
+
this.cam.zoom = Math.max(0.2, Math.min(3.0,
|
|
2428
|
+
this.cam.zoom * Math.exp(-e.deltaY * (isPinch ? 0.012 : 0.05))));
|
|
2429
|
+
const after = this._s2w(e.clientX, e.clientY);
|
|
2430
|
+
this.cam.x += after.x - before.x; this.cam.y += after.y - before.y;
|
|
2431
|
+
return;
|
|
2432
|
+
}
|
|
2433
|
+
// Trackpad two-finger pan.
|
|
2434
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2435
|
+
this.cam.x -= e.deltaX * dpr / this.cam.zoom;
|
|
2436
|
+
this.cam.y -= e.deltaY * dpr / this.cam.zoom;
|
|
2437
|
+
}, { passive: false });
|
|
2438
|
+
|
|
2439
|
+
c.addEventListener('dblclick', (e) => {
|
|
2440
|
+
const wp = this._s2w(e.clientX, e.clientY);
|
|
2441
|
+
// Frame header → drill into subflow.
|
|
2442
|
+
const fh = this._hitFrameHeader(wp.x, wp.y);
|
|
2443
|
+
if (fh !== -1) { this.enterSubflow(this.frames[fh].id); return; }
|
|
2444
|
+
// Note → edit text.
|
|
2445
|
+
const nh = this._hitNote(wp.x, wp.y);
|
|
2446
|
+
if (nh !== -1) { this._startEditingNote(nh); return; }
|
|
2447
|
+
const nid = this.w.hitTestNode(wp.x, wp.y);
|
|
2448
|
+
if (nid !== -1) {
|
|
2449
|
+
if (this.options.dblclickEditsTitle !== false) this._startEditingTitle(nid);
|
|
2450
|
+
this._emit('node:dblclick', nid);
|
|
2451
|
+
return;
|
|
2452
|
+
}
|
|
2453
|
+
const eid = this._hitTestEdge(wp.x, wp.y, 6 / this.cam.zoom);
|
|
2454
|
+
if (eid !== -1) { this._emit('edge:dblclick', eid); return; }
|
|
2455
|
+
this._emit('canvas:dblclick', wp);
|
|
2456
|
+
});
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
_startPan(e) {
|
|
2460
|
+
this._mode = 'pan';
|
|
2461
|
+
this._dragStart = { sx: e.clientX, sy: e.clientY };
|
|
2462
|
+
this._panVel.x = 0; this._panVel.y = 0; this._panVel.lastTs = performance.now();
|
|
2463
|
+
this.canvas.style.cursor = 'grabbing';
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
_attachKeyboard() {
|
|
2467
|
+
const handler = (e) => {
|
|
2468
|
+
// Only handle when our container has focus (or the canvas).
|
|
2469
|
+
const inOwn = this.container.contains(document.activeElement) || document.activeElement === document.body;
|
|
2470
|
+
if (!inOwn) return;
|
|
2471
|
+
// Don't steal typing in inputs/textareas.
|
|
2472
|
+
const t = document.activeElement;
|
|
2473
|
+
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA')) return;
|
|
2474
|
+
const ctrl = e.ctrlKey || e.metaKey;
|
|
2475
|
+
|
|
2476
|
+
if (e.code === 'Delete' || e.code === 'Backspace') {
|
|
2477
|
+
if (this.deleteSelection() > 0) e.preventDefault();
|
|
2478
|
+
return;
|
|
2479
|
+
}
|
|
2480
|
+
if (ctrl && e.code === 'KeyZ' && !e.shiftKey) { this.undo(); e.preventDefault(); return; }
|
|
2481
|
+
if (ctrl && (e.code === 'KeyY' || (e.code === 'KeyZ' && e.shiftKey))) { this.redo(); e.preventDefault(); return; }
|
|
2482
|
+
if (ctrl && e.code === 'KeyA') { this.selectAll(); e.preventDefault(); return; }
|
|
2483
|
+
if (ctrl && e.code === 'KeyD') { this.duplicateSelection(); e.preventDefault(); return; }
|
|
2484
|
+
if (ctrl && e.code === 'KeyC') { this._copy(); e.preventDefault(); return; }
|
|
2485
|
+
if (ctrl && e.code === 'KeyV') { this._paste(); e.preventDefault(); return; }
|
|
2486
|
+
if (ctrl && e.code === 'KeyG') { this.groupSelection(); e.preventDefault(); return; }
|
|
2487
|
+
if (ctrl && e.code === 'BracketRight') { this.bringToFront(); e.preventDefault(); return; }
|
|
2488
|
+
if (ctrl && e.code === 'BracketLeft') { this.sendToBack(); e.preventDefault(); return; }
|
|
2489
|
+
if (ctrl && e.code === 'KeyK') { this.openCommandPalette(); e.preventDefault(); return; }
|
|
2490
|
+
if (ctrl && e.code === 'KeyF' && this.options.search) { this.openSearch(); e.preventDefault(); return; }
|
|
2491
|
+
if (ctrl && e.code === 'KeyT') { this.toggleTheme(); e.preventDefault(); return; }
|
|
2492
|
+
if (ctrl && e.code === 'KeyM') { this.setMinimap(!this.options.minimap); e.preventDefault(); return; }
|
|
2493
|
+
if (ctrl && e.code === 'KeyE') { this.setAllEdgesAnimated(this.animatedEdges.size === 0); e.preventDefault(); return; }
|
|
2494
|
+
if (!ctrl && e.code === 'Digit0') { this.fitView(); e.preventDefault(); return; }
|
|
2495
|
+
if (!ctrl && e.code === 'KeyL' && !this._editingTitle && this._editingNote === -1) { this.runAutoLayout(); e.preventDefault(); return; }
|
|
2496
|
+
if (e.code === 'F5' && !e.shiftKey) { this.run(); e.preventDefault(); return; }
|
|
2497
|
+
if (e.code === 'F5' && e.shiftKey) { this.stop(); e.preventDefault(); return; }
|
|
2498
|
+
if (e.code === 'Tab' && !ctrl) {
|
|
2499
|
+
const n = this.w.nodeCount_();
|
|
2500
|
+
if (n === 0) return;
|
|
2501
|
+
let cur = this.getSelection()[0] ?? -1;
|
|
2502
|
+
let next = e.shiftKey ? cur - 1 : cur + 1;
|
|
2503
|
+
if (cur === -1) next = 0;
|
|
2504
|
+
if (next < 0) next = n - 1;
|
|
2505
|
+
if (next >= n) next = 0;
|
|
2506
|
+
this.clearSelection(); this.w.setSelected(next, 1);
|
|
2507
|
+
this.panTo(this.V.posX[next], this.V.posY[next]);
|
|
2508
|
+
e.preventDefault();
|
|
2509
|
+
return;
|
|
2510
|
+
}
|
|
2511
|
+
if (!ctrl && /^Digit[1-9]$/.test(e.code)) {
|
|
2512
|
+
const slot = parseInt(e.code.slice(5), 10);
|
|
2513
|
+
if (e.altKey) this.jumpBookmark(slot);
|
|
2514
|
+
else this.setBookmark(slot);
|
|
2515
|
+
e.preventDefault();
|
|
2516
|
+
return;
|
|
2517
|
+
}
|
|
2518
|
+
if (e.code === 'Escape') {
|
|
2519
|
+
// Cancel an in-progress edge or exit subflow before falling through.
|
|
2520
|
+
if (this._mode === 'connecting') {
|
|
2521
|
+
this._mode = 'idle'; this._edgeStart = null; this._edgeCursor = null;
|
|
2522
|
+
this.canvas.style.cursor = '';
|
|
2523
|
+
return;
|
|
2524
|
+
}
|
|
2525
|
+
if (this._focusFrame !== -1) { this.exitSubflow(); return; }
|
|
2526
|
+
this.clearSelection(); this._hideMenu(); return;
|
|
2527
|
+
}
|
|
2528
|
+
if (e.code.startsWith('Arrow')) {
|
|
2529
|
+
const d = e.shiftKey ? 1 : 10;
|
|
2530
|
+
const dx = e.code === 'ArrowLeft' ? -d : e.code === 'ArrowRight' ? d : 0;
|
|
2531
|
+
const dy = e.code === 'ArrowUp' ? -d : e.code === 'ArrowDown' ? d : 0;
|
|
2532
|
+
if (this.getSelection().length > 0) {
|
|
2533
|
+
this.w.moveSelectedBy(dx, dy);
|
|
2534
|
+
if (this._nudgeTimer) clearTimeout(this._nudgeTimer);
|
|
2535
|
+
this._nudgeTimer = setTimeout(() => { this.w.snapshot(); this._emit('change'); }, 400);
|
|
2536
|
+
e.preventDefault();
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
};
|
|
2540
|
+
window.addEventListener('keydown', handler);
|
|
2541
|
+
this._keyHandler = handler;
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
// ── Clipboard ─────────────────────────────────────────────────────────
|
|
2545
|
+
_copy() {
|
|
2546
|
+
const sel = this.getSelection();
|
|
2547
|
+
if (sel.length === 0) return;
|
|
2548
|
+
const selSet = new Set(sel);
|
|
2549
|
+
const nodes = sel.map((i) => ({
|
|
2550
|
+
origId: i,
|
|
2551
|
+
kind: this.kinds[this.V.kind[i]].name,
|
|
2552
|
+
x: this.V.posX[i], y: this.V.posY[i], w: this.V.sizeW[i], h: this.V.sizeH[i],
|
|
2553
|
+
title: this.titles.get(i), color: this.colors.get(i),
|
|
2554
|
+
description: this.descriptions.get(i), tags: this.tags.get(i),
|
|
2555
|
+
status: this.status.get(i), progress: this.progress.get(i),
|
|
2556
|
+
}));
|
|
2557
|
+
const edges = [];
|
|
2558
|
+
for (let e = 0; e < this.w.edgeCount_(); e++) {
|
|
2559
|
+
if (selSet.has(this.V.edgeFromN[e]) && selSet.has(this.V.edgeToN[e])) {
|
|
2560
|
+
edges.push({ from: this.V.edgeFromN[e], fp: this.V.edgeFromP[e],
|
|
2561
|
+
to: this.V.edgeToN[e], tp: this.V.edgeToP[e],
|
|
2562
|
+
label: this.edgeLabels.get(e) });
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
2565
|
+
let minX = Infinity, minY = Infinity;
|
|
2566
|
+
for (const n of nodes) { if (n.x < minX) minX = n.x; if (n.y < minY) minY = n.y; }
|
|
2567
|
+
this._clipboard = { nodes, edges, anchor: { x: minX, y: minY } };
|
|
2568
|
+
}
|
|
2569
|
+
_paste() {
|
|
2570
|
+
if (!this._clipboard) return;
|
|
2571
|
+
const c = this._clipboard;
|
|
2572
|
+
const px = -this.cam.x, py = -this.cam.y;
|
|
2573
|
+
const dx = px - c.anchor.x, dy = py - c.anchor.y;
|
|
2574
|
+
const idMap = new Map();
|
|
2575
|
+
this.clearSelection();
|
|
2576
|
+
for (const n of c.nodes) {
|
|
2577
|
+
const id = this.addNode({
|
|
2578
|
+
kind: n.kind, x: n.x + dx, y: n.y + dy, w: n.w, h: n.h,
|
|
2579
|
+
title: n.title, color: n.color, description: n.description,
|
|
2580
|
+
tags: n.tags, status: n.status, progress: n.progress,
|
|
2581
|
+
});
|
|
2582
|
+
idMap.set(n.origId, id);
|
|
2583
|
+
this.w.setSelected(id, 1);
|
|
2584
|
+
}
|
|
2585
|
+
for (const e of c.edges) {
|
|
2586
|
+
const a = idMap.get(e.from), b = idMap.get(e.to);
|
|
2587
|
+
if (a !== undefined && b !== undefined) this.addEdge({ from: a, fp: e.fp, to: b, tp: e.tp, label: e.label });
|
|
2588
|
+
}
|
|
2589
|
+
this._clipboard = { ...c, anchor: { x: c.anchor.x - 24, y: c.anchor.y - 24 } };
|
|
2590
|
+
this.w.snapshot();
|
|
2591
|
+
this._emit('change');
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
// ── Resize handles ────────────────────────────────────────────────────
|
|
2595
|
+
// ── Frame hit-tests + resize ──────────────────────────────────────────
|
|
2596
|
+
_hitFrameHeader(qx, qy) {
|
|
2597
|
+
for (let i = this.frames.length - 1; i >= 0; i--) {
|
|
2598
|
+
const f = this.frames[i];
|
|
2599
|
+
if (qx < f.x || qx > f.x + f.w) continue;
|
|
2600
|
+
if (qy < f.y || qy > f.y + 26) continue;
|
|
2601
|
+
return i;
|
|
2602
|
+
}
|
|
2603
|
+
return -1;
|
|
2604
|
+
}
|
|
2605
|
+
_hitFrameCorner(qx, qy) {
|
|
2606
|
+
const tol = 14 / this.cam.zoom;
|
|
2607
|
+
for (let i = this.frames.length - 1; i >= 0; i--) {
|
|
2608
|
+
const f = this.frames[i];
|
|
2609
|
+
const corners = {
|
|
2610
|
+
tl: { x: f.x, y: f.y }, tr: { x: f.x + f.w, y: f.y },
|
|
2611
|
+
bl: { x: f.x, y: f.y + f.h }, br: { x: f.x + f.w, y: f.y + f.h },
|
|
2612
|
+
};
|
|
2613
|
+
for (const c of ['br', 'bl', 'tr', 'tl']) {
|
|
2614
|
+
const p = corners[c];
|
|
2615
|
+
if (Math.abs(qx - p.x) < tol && Math.abs(qy - p.y) < tol) return { idx: i, corner: c };
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
return null;
|
|
2619
|
+
}
|
|
2620
|
+
_applyFrameResize(idx, corner, dx, dy) {
|
|
2621
|
+
const f = this.frames[idx], MIN_W = 120, MIN_H = 80;
|
|
2622
|
+
if (corner === 'br') { f.w += dx; f.h += dy; }
|
|
2623
|
+
if (corner === 'bl') { f.x += dx; f.w -= dx; f.h += dy; }
|
|
2624
|
+
if (corner === 'tr') { f.w += dx; f.y += dy; f.h -= dy; }
|
|
2625
|
+
if (corner === 'tl') { f.x += dx; f.w -= dx; f.y += dy; f.h -= dy; }
|
|
2626
|
+
if (f.w < MIN_W) { if (corner === 'bl' || corner === 'tl') f.x -= (MIN_W - f.w); f.w = MIN_W; }
|
|
2627
|
+
if (f.h < MIN_H) { if (corner === 'tl' || corner === 'tr') f.y -= (MIN_H - f.h); f.h = MIN_H; }
|
|
2628
|
+
}
|
|
2629
|
+
_hitNote(qx, qy) {
|
|
2630
|
+
for (let i = this.notes.length - 1; i >= 0; i--) {
|
|
2631
|
+
const n = this.notes[i];
|
|
2632
|
+
if (qx >= n.x && qx <= n.x + n.w && qy >= n.y && qy <= n.y + n.h) return i;
|
|
2633
|
+
}
|
|
2634
|
+
return -1;
|
|
2635
|
+
}
|
|
2636
|
+
_hitTaskCheckbox(qx, qy) {
|
|
2637
|
+
const n = this.w.nodeCount_();
|
|
2638
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
2639
|
+
const list = this.tasks.get(i);
|
|
2640
|
+
if (!list || !list.length) continue;
|
|
2641
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
2642
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
2643
|
+
if (qx < cx - hw || qx > cx + hw || qy < cy - hh || qy > cy + hh) continue;
|
|
2644
|
+
// Rough layout: each row 14 world-units tall, starting ~30 from top.
|
|
2645
|
+
const innerLeft = cx - hw + 8;
|
|
2646
|
+
let curY = cy - hh + 32;
|
|
2647
|
+
if (this.descriptions.get(i)) curY += 30;
|
|
2648
|
+
const rowH = 14, boxS = 10;
|
|
2649
|
+
for (let t = 0; t < list.length; t++) {
|
|
2650
|
+
if (qx >= innerLeft && qx <= innerLeft + boxS && qy >= curY && qy <= curY + boxS) {
|
|
2651
|
+
return { nodeId: i, taskIdx: t };
|
|
2652
|
+
}
|
|
2653
|
+
curY += rowH;
|
|
2654
|
+
if (curY > cy + hh - 6) break;
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
return null;
|
|
2658
|
+
}
|
|
2659
|
+
|
|
2660
|
+
_hitHandle(qx, qy) {
|
|
2661
|
+
// Only when exactly 1 node selected.
|
|
2662
|
+
const sel = this.getSelection();
|
|
2663
|
+
if (sel.length !== 1) return null;
|
|
2664
|
+
const id = sel[0];
|
|
2665
|
+
const cx = this.V.posX[id], cy = this.V.posY[id];
|
|
2666
|
+
const hw = this.V.sizeW[id] * 0.5, hh = this.V.sizeH[id] * 0.5;
|
|
2667
|
+
const tol = 6 / this.cam.zoom;
|
|
2668
|
+
const pts = {
|
|
2669
|
+
tl: {x: cx-hw, y: cy-hh}, t: {x: cx, y: cy-hh}, tr: {x: cx+hw, y: cy-hh},
|
|
2670
|
+
r: {x: cx+hw, y: cy},
|
|
2671
|
+
br: {x: cx+hw, y: cy+hh}, b: {x: cx, y: cy+hh}, bl: {x: cx-hw, y: cy+hh},
|
|
2672
|
+
l: {x: cx-hw, y: cy},
|
|
2673
|
+
};
|
|
2674
|
+
for (const c of HANDLE_CORNERS) {
|
|
2675
|
+
const p = pts[c];
|
|
2676
|
+
if (Math.abs(qx - p.x) < tol && Math.abs(qy - p.y) < tol) return { nodeId: id, corner: c };
|
|
2677
|
+
}
|
|
2678
|
+
return null;
|
|
2679
|
+
}
|
|
2680
|
+
_applyResize(corner, dx, dy) {
|
|
2681
|
+
const id = this._resizingHandle.nodeId;
|
|
2682
|
+
const MIN = 60;
|
|
2683
|
+
let nw = this.V.sizeW[id], nh = this.V.sizeH[id];
|
|
2684
|
+
let dcx = 0, dcy = 0;
|
|
2685
|
+
if (HANDLE_LEFTS.has(corner)) { nw -= dx; dcx = dx * 0.5; }
|
|
2686
|
+
if (HANDLE_RIGHTS.has(corner)) { nw += dx; dcx = dx * 0.5; }
|
|
2687
|
+
if (HANDLE_TOPS.has(corner)) { nh -= dy; dcy = dy * 0.5; }
|
|
2688
|
+
if (HANDLE_BOTS.has(corner)) { nh += dy; dcy = dy * 0.5; }
|
|
2689
|
+
if (nw < MIN) { nw = MIN; dcx = 0; }
|
|
2690
|
+
if (nh < MIN) { nh = MIN; dcy = 0; }
|
|
2691
|
+
this.V.sizeW[id] = nw; this.V.sizeH[id] = nh;
|
|
2692
|
+
this.V.posX[id] += dcx; this.V.posY[id] += dcy;
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
// ── Alignment guides (during drag) ────────────────────────────────────
|
|
2696
|
+
_computeAlignSnap(deltaX, deltaY) {
|
|
2697
|
+
const ALIGN_EPS = 6;
|
|
2698
|
+
const n = this.w.nodeCount_();
|
|
2699
|
+
const xs = [], ys = [];
|
|
2700
|
+
for (let i = 0; i < n; i++) {
|
|
2701
|
+
if (this.V.selected[i]) continue;
|
|
2702
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
2703
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
2704
|
+
xs.push(cx, cx - hw, cx + hw);
|
|
2705
|
+
ys.push(cy, cy - hh, cy + hh);
|
|
2706
|
+
}
|
|
2707
|
+
let bestDX = 0, bestDY = 0, foundX = null, foundY = null;
|
|
2708
|
+
let bestX = ALIGN_EPS + 1, bestY = ALIGN_EPS + 1;
|
|
2709
|
+
for (let i = 0; i < n; i++) {
|
|
2710
|
+
if (!this.V.selected[i]) continue;
|
|
2711
|
+
const tcx = this.V.posX[i] + deltaX, tcy = this.V.posY[i] + deltaY;
|
|
2712
|
+
for (const x of xs) {
|
|
2713
|
+
const d = tcx - x;
|
|
2714
|
+
if (Math.abs(d) < bestX) { bestX = Math.abs(d); bestDX = -d; foundX = x; }
|
|
2715
|
+
}
|
|
2716
|
+
for (const y of ys) {
|
|
2717
|
+
const d = tcy - y;
|
|
2718
|
+
if (Math.abs(d) < bestY) { bestY = Math.abs(d); bestDY = -d; foundY = y; }
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
return { dx: bestX <= ALIGN_EPS ? bestDX : 0, dy: bestY <= ALIGN_EPS ? bestDY : 0,
|
|
2722
|
+
guideX: foundX, guideY: foundY };
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
// ── Edge hit-test (JS-side, samples bezier or polyline) ──────────────
|
|
2726
|
+
_hitTestEdge(qx, qy, tolWorld) {
|
|
2727
|
+
const tol2 = tolWorld * tolWorld;
|
|
2728
|
+
const m = this.w.edgeCount_();
|
|
2729
|
+
let bestIdx = -1, bestDist = tol2;
|
|
2730
|
+
for (let i = 0; i < m; i++) {
|
|
2731
|
+
const ap = this._portWorld(this.V.edgeFromN[i], 1, this.V.edgeFromP[i]);
|
|
2732
|
+
const bp = this._portWorld(this.V.edgeToN[i], 0, this.V.edgeToP[i]);
|
|
2733
|
+
const minx = Math.min(ap.x, bp.x) - tolWorld, maxx = Math.max(ap.x, bp.x) + tolWorld;
|
|
2734
|
+
const miny = Math.min(ap.y, bp.y) - tolWorld - 80, maxy = Math.max(ap.y, bp.y) + tolWorld + 80;
|
|
2735
|
+
if (qx < minx || qx > maxx || qy < miny || qy > maxy) continue;
|
|
2736
|
+
if (this.options.edgeStyle === 'orthogonal') {
|
|
2737
|
+
const path = this._orthoPath(ap, bp);
|
|
2738
|
+
for (let s = 0; s < path.length - 1; s++) {
|
|
2739
|
+
const d2 = distSeg2(qx, qy, path[s].x, path[s].y, path[s+1].x, path[s+1].y);
|
|
2740
|
+
if (d2 < bestDist) { bestDist = d2; bestIdx = i; }
|
|
2741
|
+
}
|
|
2742
|
+
} else {
|
|
2743
|
+
const dxe = bp.x - ap.x, dye = bp.y - ap.y;
|
|
2744
|
+
const off = Math.max(50, Math.abs(dxe) * 0.5 + Math.abs(dye) * 0.4);
|
|
2745
|
+
for (let s = 0; s <= 16; s++) {
|
|
2746
|
+
const t = s / 16;
|
|
2747
|
+
const pt = bezPt$1(t, ap.x, ap.y, ap.x + off, ap.y, bp.x - off, bp.y, bp.x, bp.y);
|
|
2748
|
+
const ddx = pt.x - qx, ddy = pt.y - qy;
|
|
2749
|
+
const d2 = ddx*ddx + ddy*ddy;
|
|
2750
|
+
if (d2 < bestDist) { bestDist = d2; bestIdx = i; }
|
|
2751
|
+
}
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
return bestIdx;
|
|
2755
|
+
}
|
|
2756
|
+
|
|
2757
|
+
// ── Right-click menu ──────────────────────────────────────────────────
|
|
2758
|
+
_onRightClick(e, wp) {
|
|
2759
|
+
if (!this.options.contextMenu) return;
|
|
2760
|
+
const nid = this.w.hitTestNode(wp.x, wp.y);
|
|
2761
|
+
const eid = nid === -1 ? this._hitTestEdge(wp.x, wp.y, 6 / this.cam.zoom) : -1;
|
|
2762
|
+
let items;
|
|
2763
|
+
if (nid !== -1) {
|
|
2764
|
+
if (this.V.selected[nid] === 0) { this.w.clearSelection(); this.w.setSelected(nid, 1); }
|
|
2765
|
+
items = [
|
|
2766
|
+
{ label: 'Duplicate', kbd: 'Ctrl+D', fn: () => this.duplicateSelection() },
|
|
2767
|
+
{ label: 'Delete', kbd: 'Del', danger: true, fn: () => this.deleteSelection() },
|
|
2768
|
+
{ sep: true },
|
|
2769
|
+
{ label: 'Deselect', kbd: 'Esc', fn: () => this.clearSelection() },
|
|
2770
|
+
];
|
|
2771
|
+
} else if (eid !== -1) {
|
|
2772
|
+
const a = this.V.edgeFromN[eid], b = this.V.edgeToN[eid];
|
|
2773
|
+
items = [
|
|
2774
|
+
{ label: 'Select endpoints', fn: () => { this.clearSelection(); this.w.setSelected(a,1); this.w.setSelected(b,1); this._emit('select', this.getSelection()); } },
|
|
2775
|
+
{ label: 'Set label…', fn: () => { const v = prompt('Edge label', this.edgeLabels.get(eid) || ''); if (v !== null) this.setEdgeLabel(eid, v); } },
|
|
2776
|
+
{ sep: true },
|
|
2777
|
+
{ label: 'Delete edge', danger: true, fn: () => { this.w.deleteEdge(eid); this.edgeLabels.delete(eid); this.w.snapshot(); this._emit('change'); } },
|
|
2778
|
+
];
|
|
2779
|
+
} else {
|
|
2780
|
+
items = [
|
|
2781
|
+
{ label: 'Add Process node here', fn: () => this.addNode({ kind: 'process', x: wp.x, y: wp.y }) },
|
|
2782
|
+
{ sep: true },
|
|
2783
|
+
{ label: 'Select all', kbd: 'Ctrl+A', fn: () => this.selectAll() },
|
|
2784
|
+
{ label: 'Auto-layout', fn: () => this.runAutoLayout() },
|
|
2785
|
+
{ label: 'Fit view', fn: () => this.fitView() },
|
|
2786
|
+
];
|
|
2787
|
+
}
|
|
2788
|
+
this._showMenu(e.clientX, e.clientY, items);
|
|
2789
|
+
}
|
|
2790
|
+
// ── Inline editors (title + note) ─────────────────────────────────────
|
|
2791
|
+
_startEditingTitle(nodeId) {
|
|
2792
|
+
this._editingTitle = nodeId;
|
|
2793
|
+
if (!this._editingTitleEl) {
|
|
2794
|
+
const el = document.createElement('input');
|
|
2795
|
+
el.type = 'text';
|
|
2796
|
+
Object.assign(el.style, {
|
|
2797
|
+
position: 'absolute', background: '#161b27', color: '#e6edf3',
|
|
2798
|
+
border: '1px solid #f0b93a', borderRadius: '4px',
|
|
2799
|
+
fontFamily: 'Inter, ui-sans-serif', fontSize: '12px', fontWeight: '600',
|
|
2800
|
+
padding: '4px 8px', outline: 'none', zIndex: '300',
|
|
2801
|
+
boxShadow: '0 4px 12px rgba(0,0,0,0.35)',
|
|
2802
|
+
});
|
|
2803
|
+
this.container.appendChild(el);
|
|
2804
|
+
el.addEventListener('blur', () => this._stopEditingTitle());
|
|
2805
|
+
el.addEventListener('keydown', (e) => { if (e.code === 'Enter' || e.code === 'Escape') el.blur(); });
|
|
2806
|
+
this._editingTitleEl = el;
|
|
2807
|
+
}
|
|
2808
|
+
this._positionTitleEditor();
|
|
2809
|
+
this._editingTitleEl.value = this.titles.get(nodeId) || '';
|
|
2810
|
+
this._editingTitleEl.placeholder = `${this.kinds[this.V.kind[nodeId]].name} #${nodeId}`;
|
|
2811
|
+
this._editingTitleEl.style.display = 'block';
|
|
2812
|
+
setTimeout(() => { this._editingTitleEl.focus(); this._editingTitleEl.select(); }, 20);
|
|
2813
|
+
}
|
|
2814
|
+
_positionTitleEditor() {
|
|
2815
|
+
if (this._editingTitle === -1 || !this._editingTitleEl) return;
|
|
2816
|
+
const i = this._editingTitle;
|
|
2817
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
2818
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
2819
|
+
const tl = this._w2s(cx - hw, cy - hh);
|
|
2820
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2821
|
+
this._editingTitleEl.style.left = (tl.x / dpr) + 'px';
|
|
2822
|
+
this._editingTitleEl.style.top = (tl.y / dpr - 32) + 'px';
|
|
2823
|
+
this._editingTitleEl.style.width = Math.max(120, this.V.sizeW[i] * this.cam.zoom / dpr) + 'px';
|
|
2824
|
+
}
|
|
2825
|
+
_stopEditingTitle() {
|
|
2826
|
+
if (this._editingTitle === -1) return;
|
|
2827
|
+
const v = this._editingTitleEl.value.trim();
|
|
2828
|
+
if (v) this.titles.set(this._editingTitle, v);
|
|
2829
|
+
else this.titles.delete(this._editingTitle);
|
|
2830
|
+
this._editingTitleEl.style.display = 'none';
|
|
2831
|
+
this._editingTitle = -1;
|
|
2832
|
+
this._emit('change');
|
|
2833
|
+
}
|
|
2834
|
+
_startEditingNote(idx) {
|
|
2835
|
+
this._editingNote = idx;
|
|
2836
|
+
if (!this._editingNoteEl) {
|
|
2837
|
+
const el = document.createElement('textarea');
|
|
2838
|
+
el.spellcheck = false;
|
|
2839
|
+
Object.assign(el.style, {
|
|
2840
|
+
position: 'absolute', resize: 'none', outline: 'none',
|
|
2841
|
+
border: '1px solid #f0b93a', borderRadius: '4px',
|
|
2842
|
+
padding: '8px 10px', fontFamily: 'Inter, ui-sans-serif',
|
|
2843
|
+
fontSize: '12px', lineHeight: '16px', zIndex: '300',
|
|
2844
|
+
});
|
|
2845
|
+
this.container.appendChild(el);
|
|
2846
|
+
el.addEventListener('blur', () => this._stopEditingNote());
|
|
2847
|
+
el.addEventListener('keydown', (e) => { if (e.code === 'Escape') el.blur(); });
|
|
2848
|
+
this._editingNoteEl = el;
|
|
2849
|
+
}
|
|
2850
|
+
this._positionNoteEditor();
|
|
2851
|
+
const n = this.notes[idx];
|
|
2852
|
+
this._editingNoteEl.style.background = n.color.fill;
|
|
2853
|
+
this._editingNoteEl.style.color = n.color.text;
|
|
2854
|
+
this._editingNoteEl.value = n.text;
|
|
2855
|
+
this._editingNoteEl.style.display = 'block';
|
|
2856
|
+
setTimeout(() => this._editingNoteEl.focus(), 20);
|
|
2857
|
+
}
|
|
2858
|
+
_positionNoteEditor() {
|
|
2859
|
+
if (this._editingNote === -1 || !this._editingNoteEl) return;
|
|
2860
|
+
const n = this.notes[this._editingNote];
|
|
2861
|
+
const tl = this._w2s(n.x, n.y);
|
|
2862
|
+
const dpr = window.devicePixelRatio || 1;
|
|
2863
|
+
this._editingNoteEl.style.left = (tl.x / dpr) + 'px';
|
|
2864
|
+
this._editingNoteEl.style.top = (tl.y / dpr) + 'px';
|
|
2865
|
+
this._editingNoteEl.style.width = (n.w * this.cam.zoom / dpr) + 'px';
|
|
2866
|
+
this._editingNoteEl.style.height = (n.h * this.cam.zoom / dpr) + 'px';
|
|
2867
|
+
}
|
|
2868
|
+
_stopEditingNote() {
|
|
2869
|
+
if (this._editingNote === -1) return;
|
|
2870
|
+
this.notes[this._editingNote].text = this._editingNoteEl.value;
|
|
2871
|
+
this._editingNoteEl.style.display = 'none';
|
|
2872
|
+
this._editingNote = -1;
|
|
2873
|
+
this._emit('change');
|
|
2874
|
+
}
|
|
2875
|
+
|
|
2876
|
+
_showMenu(x, y, items) {
|
|
2877
|
+
this._hideMenu();
|
|
2878
|
+
const m = document.createElement('div');
|
|
2879
|
+
m.style.cssText = 'position:fixed;min-width:200px;padding:4px;background:#161b27;border:1px solid rgba(255,255,255,0.16);border-radius:8px;box-shadow:0 12px 32px rgba(0,0,0,0.45);z-index:99999;color:#e6edf3;font:13px/1.45 ui-sans-serif, system-ui, sans-serif;';
|
|
2880
|
+
for (const it of items) {
|
|
2881
|
+
if (it.sep) { const d = document.createElement('div'); d.style.cssText = 'height:1px;background:rgba(255,255,255,0.08);margin:4px;'; m.appendChild(d); continue; }
|
|
2882
|
+
const d = document.createElement('div');
|
|
2883
|
+
d.style.cssText = `padding:6px 10px;border-radius:6px;cursor:pointer;display:flex;justify-content:space-between;gap:12px;${it.danger ? 'color:#ffb4a4;' : ''}`;
|
|
2884
|
+
d.innerHTML = `<span>${escapeHtml(it.label)}</span>${it.kbd ? `<span style="color:#5a6577;font-family:ui-monospace,Consolas,monospace;font-size:11px;">${escapeHtml(it.kbd)}</span>` : ''}`;
|
|
2885
|
+
d.onmouseenter = () => d.style.background = it.danger ? 'rgba(232,70,43,0.18)' : 'rgba(255,255,255,0.04)';
|
|
2886
|
+
d.onmouseleave = () => d.style.background = '';
|
|
2887
|
+
d.onclick = () => { it.fn(); this._hideMenu(); };
|
|
2888
|
+
m.appendChild(d);
|
|
2889
|
+
}
|
|
2890
|
+
m.style.left = Math.min(x, window.innerWidth - 220) + 'px';
|
|
2891
|
+
m.style.top = Math.min(y, window.innerHeight - 280) + 'px';
|
|
2892
|
+
document.body.appendChild(m);
|
|
2893
|
+
this._menuEl = m;
|
|
2894
|
+
setTimeout(() => {
|
|
2895
|
+
const off = (ev) => { if (!m.contains(ev.target)) { this._hideMenu(); document.removeEventListener('mousedown', off, true); } };
|
|
2896
|
+
document.addEventListener('mousedown', off, true);
|
|
2897
|
+
}, 0);
|
|
2898
|
+
}
|
|
2899
|
+
_hideMenu() { if (this._menuEl) { this._menuEl.remove(); this._menuEl = null; } }
|
|
2900
|
+
|
|
2901
|
+
// ── Render loop ───────────────────────────────────────────────────────
|
|
2902
|
+
_loop() { this._render(); this._raf = requestAnimationFrame(() => this._loop()); }
|
|
2903
|
+
|
|
2904
|
+
_render() {
|
|
2905
|
+
// Pan inertia.
|
|
2906
|
+
if (this._mode !== 'pan') {
|
|
2907
|
+
const v2 = this._panVel.x * this._panVel.x + this._panVel.y * this._panVel.y;
|
|
2908
|
+
if (v2 < 16) { this._panVel.x = 0; this._panVel.y = 0; }
|
|
2909
|
+
else {
|
|
2910
|
+
this.cam.x += this._panVel.x * (1/60); this.cam.y += this._panVel.y * (1/60);
|
|
2911
|
+
this._panVel.x *= 0.91; this._panVel.y *= 0.91;
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
|
|
2915
|
+
const ctx = this.ctx;
|
|
2916
|
+
if (this._hooks?.beforeRender?.length) this._runHook('beforeRender', ctx);
|
|
2917
|
+
if (this._gl) {
|
|
2918
|
+
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
|
2919
|
+
this._gl.render();
|
|
2920
|
+
} else {
|
|
2921
|
+
ctx.fillStyle = this.options.background;
|
|
2922
|
+
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
|
|
2923
|
+
}
|
|
2924
|
+
this._drawGrid();
|
|
2925
|
+
this._drawFrames();
|
|
2926
|
+
this._drawNotes();
|
|
2927
|
+
this._refreshFocus();
|
|
2928
|
+
this._refreshPreview();
|
|
2929
|
+
this._positionTitleEditor();
|
|
2930
|
+
this._positionNoteEditor();
|
|
2931
|
+
this._drawDying();
|
|
2932
|
+
this._drawWaypoints();
|
|
2933
|
+
this._drawRemoteCursors();
|
|
2934
|
+
this._drawValueBubbles();
|
|
2935
|
+
if (this.options.minimap) this._drawMinimap();
|
|
2936
|
+
|
|
2937
|
+
const n = this.w.nodeCount_(), m = this.w.edgeCount_();
|
|
2938
|
+
// Edges first.
|
|
2939
|
+
this._edgePhase = (this._edgePhase + (this.options.edgeFlowSpeed || 60) * (1 / 60)) % 1000;
|
|
2940
|
+
for (let i = 0; i < m; i++) {
|
|
2941
|
+
const a = this.V.edgeFromN[i], b = this.V.edgeToN[i];
|
|
2942
|
+
const ap = this._portWorld(a, 1, this.V.edgeFromP[i]);
|
|
2943
|
+
const bp = this._portWorld(b, 0, this.V.edgeToP[i]);
|
|
2944
|
+
let dim = false;
|
|
2945
|
+
if (this._focusedSet && (!this._focusedSet.has(a) || !this._focusedSet.has(b))) dim = true;
|
|
2946
|
+
if (this._hoveredEdge !== -1 && this._hoveredEdge !== i) dim = true;
|
|
2947
|
+
if (this._focusFrame !== -1 && !(this._isInsideFocusFrame(a) && this._isInsideFocusFrame(b))) dim = true;
|
|
2948
|
+
if (dim) ctx.globalAlpha = 0.18;
|
|
2949
|
+
this._currentEdgeIdx = i;
|
|
2950
|
+
this._drawEdge(ap, bp,
|
|
2951
|
+
this.colors.get(a) || this.kinds[this.V.kind[a]].color,
|
|
2952
|
+
this.colors.get(b) || this.kinds[this.V.kind[b]].color,
|
|
2953
|
+
this.V.edgeSel[i] !== 0, false, this.edgeLabels.get(i));
|
|
2954
|
+
ctx.globalAlpha = 1;
|
|
2955
|
+
}
|
|
2956
|
+
this._currentEdgeIdx = undefined;
|
|
2957
|
+
// Edge in-flight preview.
|
|
2958
|
+
// Show rejection toast briefly (auto-clear after expiry).
|
|
2959
|
+
if (this._flashReject && performance.now() - this._flashReject.t0 >= 1400) {
|
|
2960
|
+
this._flashReject = null;
|
|
2961
|
+
}
|
|
2962
|
+
if (this._flashReject && performance.now() - this._flashReject.t0 < 1400) {
|
|
2963
|
+
const r = this._flashReject;
|
|
2964
|
+
const sp = this._w2s(r.x, r.y);
|
|
2965
|
+
const ctx = this.ctx;
|
|
2966
|
+
const alpha = 1 - (performance.now() - r.t0) / 1400;
|
|
2967
|
+
ctx.save();
|
|
2968
|
+
ctx.globalAlpha = alpha;
|
|
2969
|
+
ctx.fillStyle = '#e8462b'; ctx.font = '600 12px Inter, ui-sans-serif';
|
|
2970
|
+
const tw = ctx.measureText(r.msg).width;
|
|
2971
|
+
const bx = sp.x - tw / 2 - 8, by = sp.y - 36, bw = tw + 16, bh = 22;
|
|
2972
|
+
ctx.fillStyle = '#1a0e0e';
|
|
2973
|
+
this._roundRect(bx, by, bw, bh, 4); ctx.fill();
|
|
2974
|
+
ctx.strokeStyle = '#e8462b'; ctx.lineWidth = 1.4;
|
|
2975
|
+
this._roundRect(bx, by, bw, bh, 4); ctx.stroke();
|
|
2976
|
+
ctx.fillStyle = '#e8462b';
|
|
2977
|
+
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
|
2978
|
+
ctx.fillText(r.msg, sp.x, by + bh / 2);
|
|
2979
|
+
ctx.restore();
|
|
2980
|
+
}
|
|
2981
|
+
if (this._mode === 'connecting' && this._edgeStart && this._edgeCursor) {
|
|
2982
|
+
const ap = this._portWorld(this._edgeStart.nodeId, 1, this._edgeStart.idx);
|
|
2983
|
+
this._drawEdge(ap, this._edgeCursor, '#8b95a7', '#8b95a7', false, true);
|
|
2984
|
+
}
|
|
2985
|
+
const halfW = this.canvas.width / (2 * this.cam.zoom);
|
|
2986
|
+
const halfH = this.canvas.height / (2 * this.cam.zoom);
|
|
2987
|
+
const viewMinX = -this.cam.x - halfW - 80, viewMaxX = -this.cam.x + halfW + 80;
|
|
2988
|
+
const viewMinY = -this.cam.y - halfH - 80, viewMaxY = -this.cam.y + halfH + 80;
|
|
2989
|
+
let order;
|
|
2990
|
+
if (n > 300) {
|
|
2991
|
+
const c = this.w.queryRect(viewMinX, viewMinY, viewMaxX, viewMaxY);
|
|
2992
|
+
order = Array.from(this.V.queryRes.subarray(0, c));
|
|
2993
|
+
} else {
|
|
2994
|
+
order = [];
|
|
2995
|
+
for (let i = 0; i < n; i++) order.push(i);
|
|
2996
|
+
}
|
|
2997
|
+
// Sort by z-order so bringToFront'd nodes paint last.
|
|
2998
|
+
order.sort((a, b) => {
|
|
2999
|
+
const za = this.zOrder.get(a) || 0, zb = this.zOrder.get(b) || 0;
|
|
3000
|
+
return za === zb ? a - b : za - zb;
|
|
3001
|
+
});
|
|
3002
|
+
for (const i of order) {
|
|
3003
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
3004
|
+
if (this.V.posX[i] + hw < viewMinX || this.V.posX[i] - hw > viewMaxX) continue;
|
|
3005
|
+
if (this.V.posY[i] + hh < viewMinY || this.V.posY[i] - hh > viewMaxY) continue;
|
|
3006
|
+
// Skip canvas render for HTML-overlay kinds (DOM handled separately).
|
|
3007
|
+
if (this.kinds[this.V.kind[i]].html) continue;
|
|
3008
|
+
if (this._nodeHiddenByCollapse(i)) continue;
|
|
3009
|
+
// Subflow / hovered-edge / focusedSet / reachable dimming.
|
|
3010
|
+
let dim = false;
|
|
3011
|
+
if (this._focusedSet && !this._focusedSet.has(i)) dim = true;
|
|
3012
|
+
if (this._reachableSet && !this._reachableSet.has(i)) dim = true;
|
|
3013
|
+
if (this._hoveredEdge !== -1) {
|
|
3014
|
+
const a = this.V.edgeFromN[this._hoveredEdge], b = this.V.edgeToN[this._hoveredEdge];
|
|
3015
|
+
if (i !== a && i !== b) dim = true;
|
|
3016
|
+
}
|
|
3017
|
+
if (this._focusFrame !== -1 && !this._isInsideFocusFrame(i)) dim = true;
|
|
3018
|
+
if (dim) ctx.globalAlpha = 0.22;
|
|
3019
|
+
// Pop-in animation.
|
|
3020
|
+
const popped = this._openPopAnim(i);
|
|
3021
|
+
if (this._gl) this._drawNodeOverlay(i); // GL handled body+border; only paint text/badges/ports/etc
|
|
3022
|
+
else this._drawNode(i);
|
|
3023
|
+
if (popped) ctx.restore();
|
|
3024
|
+
if (dim) ctx.globalAlpha = 1;
|
|
3025
|
+
}
|
|
3026
|
+
this._syncHTMLOverlays();
|
|
3027
|
+
this._drawMultiSelectBBox();
|
|
3028
|
+
this._drawMarquee();
|
|
3029
|
+
this._drawLasso();
|
|
3030
|
+
this._drawAlignGuides();
|
|
3031
|
+
this._drawResizeHandles();
|
|
3032
|
+
this._drawFrameHandles();
|
|
3033
|
+
}
|
|
3034
|
+
|
|
3035
|
+
_openPopAnim(i) {
|
|
3036
|
+
const at = this._nodeAddedAt.get(i);
|
|
3037
|
+
if (at === undefined) return false;
|
|
3038
|
+
const t = (performance.now() - at) / 280;
|
|
3039
|
+
if (t >= 1) { this._nodeAddedAt.delete(i); return false; }
|
|
3040
|
+
const e = 1 - Math.pow(1 - t, 3);
|
|
3041
|
+
const sp = this._w2s(this.V.posX[i], this.V.posY[i]);
|
|
3042
|
+
this.ctx.save();
|
|
3043
|
+
this.ctx.globalAlpha = e;
|
|
3044
|
+
this.ctx.translate(sp.x, sp.y);
|
|
3045
|
+
this.ctx.scale(0.85 + e * 0.15, 0.85 + e * 0.15);
|
|
3046
|
+
this.ctx.translate(-sp.x, -sp.y);
|
|
3047
|
+
return true;
|
|
3048
|
+
}
|
|
3049
|
+
|
|
3050
|
+
_drawDying() {
|
|
3051
|
+
const now = performance.now();
|
|
3052
|
+
for (let i = this._dyingEdges.length - 1; i >= 0; i--) {
|
|
3053
|
+
const d = this._dyingEdges[i];
|
|
3054
|
+
const t = (now - d.t0) / 220;
|
|
3055
|
+
if (t >= 1) { this._dyingEdges.splice(i, 1); continue; }
|
|
3056
|
+
this.ctx.save();
|
|
3057
|
+
this.ctx.globalAlpha = (1 - t) * 0.7;
|
|
3058
|
+
this._drawEdge(d.ap, d.bp, d.colA, d.colB, false, true);
|
|
3059
|
+
this.ctx.restore();
|
|
3060
|
+
}
|
|
3061
|
+
for (let i = this._dyingNodes.length - 1; i >= 0; i--) {
|
|
3062
|
+
const d = this._dyingNodes[i];
|
|
3063
|
+
const t = (now - d.t0) / 220;
|
|
3064
|
+
if (t >= 1) { this._dyingNodes.splice(i, 1); continue; }
|
|
3065
|
+
const ease = 1 - Math.pow(1 - t, 3);
|
|
3066
|
+
const alpha = 1 - ease, scale = 1 - ease * 0.18;
|
|
3067
|
+
const hw = d.w * 0.5 * scale, hh = d.h * 0.5 * scale;
|
|
3068
|
+
const tl = this._w2s(d.x - hw, d.y - hh);
|
|
3069
|
+
const sw = d.w * scale * this.cam.zoom, sh = d.h * scale * this.cam.zoom;
|
|
3070
|
+
this.ctx.save();
|
|
3071
|
+
this.ctx.globalAlpha = alpha;
|
|
3072
|
+
this.ctx.fillStyle = '#161b27';
|
|
3073
|
+
this._shapePath(d.shape, tl.x, tl.y, sw, sh);
|
|
3074
|
+
this.ctx.fill();
|
|
3075
|
+
this.ctx.strokeStyle = alphaize(d.color, 0.6);
|
|
3076
|
+
this.ctx.lineWidth = 1.4 * this.cam.zoom;
|
|
3077
|
+
this._shapePath(d.shape, tl.x, tl.y, sw, sh);
|
|
3078
|
+
this.ctx.stroke();
|
|
3079
|
+
this.ctx.restore();
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
|
|
3083
|
+
_drawMultiSelectBBox() {
|
|
3084
|
+
if (this._mode !== 'idle') return;
|
|
3085
|
+
const sel = this.getSelection();
|
|
3086
|
+
if (sel.length < 2) return;
|
|
3087
|
+
let mnx = Infinity, mxx = -Infinity, mny = Infinity, mxy = -Infinity;
|
|
3088
|
+
for (const i of sel) {
|
|
3089
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
3090
|
+
if (this.V.posX[i] - hw < mnx) mnx = this.V.posX[i] - hw;
|
|
3091
|
+
if (this.V.posX[i] + hw > mxx) mxx = this.V.posX[i] + hw;
|
|
3092
|
+
if (this.V.posY[i] - hh < mny) mny = this.V.posY[i] - hh;
|
|
3093
|
+
if (this.V.posY[i] + hh > mxy) mxy = this.V.posY[i] + hh;
|
|
3094
|
+
}
|
|
3095
|
+
const pad = 10;
|
|
3096
|
+
const a = this._w2s(mnx - pad, mny - pad), b = this._w2s(mxx + pad, mxy + pad);
|
|
3097
|
+
this.ctx.strokeStyle = 'rgba(240,185,58,0.55)';
|
|
3098
|
+
this.ctx.lineWidth = 1.2;
|
|
3099
|
+
this.ctx.setLineDash([5, 4]);
|
|
3100
|
+
this.ctx.strokeRect(a.x, a.y, b.x - a.x, b.y - a.y);
|
|
3101
|
+
this.ctx.setLineDash([]);
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
_drawLasso() {
|
|
3105
|
+
if (!this._lasso || this._lasso.length < 2) return;
|
|
3106
|
+
this.ctx.strokeStyle = 'rgba(192,98,232,0.85)';
|
|
3107
|
+
this.ctx.fillStyle = 'rgba(192,98,232,0.10)';
|
|
3108
|
+
this.ctx.lineWidth = 1.4;
|
|
3109
|
+
this.ctx.setLineDash([4, 4]);
|
|
3110
|
+
this.ctx.beginPath();
|
|
3111
|
+
const first = this._w2s(this._lasso[0].x, this._lasso[0].y);
|
|
3112
|
+
this.ctx.moveTo(first.x, first.y);
|
|
3113
|
+
for (let i = 1; i < this._lasso.length; i++) {
|
|
3114
|
+
const p = this._w2s(this._lasso[i].x, this._lasso[i].y);
|
|
3115
|
+
this.ctx.lineTo(p.x, p.y);
|
|
3116
|
+
}
|
|
3117
|
+
this.ctx.closePath();
|
|
3118
|
+
this.ctx.fill(); this.ctx.stroke();
|
|
3119
|
+
this.ctx.setLineDash([]);
|
|
3120
|
+
}
|
|
3121
|
+
|
|
3122
|
+
_drawFrames() {
|
|
3123
|
+
for (let fi = 0; fi < this.frames.length; fi++) {
|
|
3124
|
+
const f = this.frames[fi];
|
|
3125
|
+
const collapsed = this.frameCollapsed.has(fi);
|
|
3126
|
+
const tl = this._w2s(f.x, f.y);
|
|
3127
|
+
const sw = f.w * this.cam.zoom;
|
|
3128
|
+
const sh = (collapsed ? 26 : f.h) * this.cam.zoom;
|
|
3129
|
+
this.ctx.fillStyle = alphaize(f.color, 0.05);
|
|
3130
|
+
this._roundRect(tl.x, tl.y, sw, sh, 12 * this.cam.zoom);
|
|
3131
|
+
this.ctx.fill();
|
|
3132
|
+
this.ctx.strokeStyle = alphaize(f.color, 0.45);
|
|
3133
|
+
this.ctx.lineWidth = 1.4 * this.cam.zoom;
|
|
3134
|
+
this.ctx.setLineDash([8 * this.cam.zoom, 4 * this.cam.zoom]);
|
|
3135
|
+
this._roundRect(tl.x, tl.y, sw, sh, 12 * this.cam.zoom);
|
|
3136
|
+
this.ctx.stroke();
|
|
3137
|
+
this.ctx.setLineDash([]);
|
|
3138
|
+
const hH = 26 * this.cam.zoom;
|
|
3139
|
+
this.ctx.save();
|
|
3140
|
+
this._roundRect(tl.x, tl.y, sw, sh, 12 * this.cam.zoom);
|
|
3141
|
+
this.ctx.clip();
|
|
3142
|
+
this.ctx.fillStyle = alphaize(f.color, 0.16);
|
|
3143
|
+
this.ctx.fillRect(tl.x, tl.y, sw, hH);
|
|
3144
|
+
this.ctx.restore();
|
|
3145
|
+
if (this.cam.zoom > 0.4) {
|
|
3146
|
+
this.ctx.fillStyle = f.color;
|
|
3147
|
+
this.ctx.font = `600 ${12 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3148
|
+
this.ctx.textBaseline = 'middle';
|
|
3149
|
+
this.ctx.textAlign = 'left';
|
|
3150
|
+
const chev = collapsed ? '▸' : '▾';
|
|
3151
|
+
this.ctx.fillText(`${chev} ${f.label}`, tl.x + 10 * this.cam.zoom, tl.y + hH * 0.5);
|
|
3152
|
+
}
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
_drawFrameHandles() {
|
|
3156
|
+
for (const f of this.frames) {
|
|
3157
|
+
const tl = this._w2s(f.x, f.y);
|
|
3158
|
+
const br = this._w2s(f.x + f.w, f.y + f.h);
|
|
3159
|
+
const s = 6 * this.cam.zoom;
|
|
3160
|
+
this.ctx.fillStyle = f.color;
|
|
3161
|
+
for (const [x, y] of [[tl.x, tl.y], [br.x, tl.y], [tl.x, br.y], [br.x, br.y]]) {
|
|
3162
|
+
this.ctx.fillRect(x - s / 2, y - s / 2, s, s);
|
|
3163
|
+
}
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
|
|
3167
|
+
_drawNotes() {
|
|
3168
|
+
for (const n of this.notes) {
|
|
3169
|
+
const tl = this._w2s(n.x, n.y);
|
|
3170
|
+
const sw = n.w * this.cam.zoom, sh = n.h * this.cam.zoom;
|
|
3171
|
+
this.ctx.save();
|
|
3172
|
+
this.ctx.shadowColor = 'rgba(0,0,0,0.4)';
|
|
3173
|
+
this.ctx.shadowBlur = 12 * this.cam.zoom;
|
|
3174
|
+
this.ctx.shadowOffsetY = 4 * this.cam.zoom;
|
|
3175
|
+
this.ctx.fillStyle = n.color.fill;
|
|
3176
|
+
this._roundRect(tl.x, tl.y, sw, sh, 4 * this.cam.zoom);
|
|
3177
|
+
this.ctx.fill();
|
|
3178
|
+
this.ctx.restore();
|
|
3179
|
+
this.ctx.strokeStyle = n.color.border;
|
|
3180
|
+
this.ctx.lineWidth = 1 * this.cam.zoom;
|
|
3181
|
+
this._roundRect(tl.x, tl.y, sw, sh, 4 * this.cam.zoom);
|
|
3182
|
+
this.ctx.stroke();
|
|
3183
|
+
if (this.cam.zoom > 0.4 && n.text) {
|
|
3184
|
+
this.ctx.fillStyle = n.color.text;
|
|
3185
|
+
this.ctx.font = `500 ${12 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3186
|
+
this.ctx.textBaseline = 'top';
|
|
3187
|
+
this.ctx.textAlign = 'left';
|
|
3188
|
+
const lineH = 16 * this.cam.zoom;
|
|
3189
|
+
const padX = 10 * this.cam.zoom, padY = 8 * this.cam.zoom;
|
|
3190
|
+
const maxW = sw - padX * 2;
|
|
3191
|
+
let ty = tl.y + padY;
|
|
3192
|
+
for (const para of n.text.split('\n')) {
|
|
3193
|
+
const words = para.split(/\s+/);
|
|
3194
|
+
let line = '';
|
|
3195
|
+
for (const word of words) {
|
|
3196
|
+
const test = line ? line + ' ' + word : word;
|
|
3197
|
+
if (this.ctx.measureText(test).width > maxW && line) {
|
|
3198
|
+
this.ctx.fillText(line, tl.x + padX, ty); ty += lineH; line = word;
|
|
3199
|
+
if (ty > tl.y + sh - lineH) break;
|
|
3200
|
+
} else line = test;
|
|
3201
|
+
}
|
|
3202
|
+
if (line && ty < tl.y + sh - lineH * 0.5) { this.ctx.fillText(line, tl.x + padX, ty); ty += lineH; }
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3207
|
+
|
|
3208
|
+
// ── Path-highlight focus ──────────────────────────────────────────────
|
|
3209
|
+
_refreshFocus() {
|
|
3210
|
+
if (!this._pathHighlightEnabled) { this._focusedSet = null; return; }
|
|
3211
|
+
if (this._mode !== 'idle' || this._hoveredNode < 0) { this._focusedSet = null; this._lastFocusComputed = -2; return; }
|
|
3212
|
+
if (performance.now() - this._hoveredNodeSince < 200) return;
|
|
3213
|
+
if (this._hoveredNode === this._lastFocusComputed) return;
|
|
3214
|
+
const reach = new Set([this._hoveredNode]);
|
|
3215
|
+
const queue = [this._hoveredNode];
|
|
3216
|
+
const m = this.w.edgeCount_();
|
|
3217
|
+
while (queue.length) {
|
|
3218
|
+
const u = queue.shift();
|
|
3219
|
+
for (let i = 0; i < m; i++) {
|
|
3220
|
+
if (this.V.edgeFromN[i] === u && !reach.has(this.V.edgeToN[i])) { reach.add(this.V.edgeToN[i]); queue.push(this.V.edgeToN[i]); }
|
|
3221
|
+
if (this.V.edgeToN[i] === u && !reach.has(this.V.edgeFromN[i])) { reach.add(this.V.edgeFromN[i]); queue.push(this.V.edgeFromN[i]); }
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
this._focusedSet = reach;
|
|
3225
|
+
this._lastFocusComputed = this._hoveredNode;
|
|
3226
|
+
}
|
|
3227
|
+
|
|
3228
|
+
// ── Hover preview popover ────────────────────────────────────────────
|
|
3229
|
+
_refreshPreview() {
|
|
3230
|
+
if (!this.options.hoverPreview) { this._hidePreview(); return; }
|
|
3231
|
+
if (this._mode !== 'idle' || this._hoveredNode < 0) { this._hidePreview(); return; }
|
|
3232
|
+
if (performance.now() - this._hoveredNodeSince < 600) return;
|
|
3233
|
+
if (this._previewedNode === this._hoveredNode) { this._positionPreview(this._hoveredNode); return; }
|
|
3234
|
+
this._showPreview(this._hoveredNode);
|
|
3235
|
+
this._previewedNode = this._hoveredNode;
|
|
3236
|
+
}
|
|
3237
|
+
_showPreview(id) {
|
|
3238
|
+
if (!this._previewEl) {
|
|
3239
|
+
const el = document.createElement('div');
|
|
3240
|
+
el.style.cssText = 'position:absolute;width:260px;padding:12px 14px;background:#161b27;border:1px solid rgba(255,255,255,0.16);border-radius:8px;box-shadow:0 12px 32px rgba(0,0,0,0.45);color:#e6edf3;font:13px/1.45 ui-sans-serif, system-ui, sans-serif;pointer-events:none;opacity:0;transition:opacity 140ms;z-index:200;';
|
|
3241
|
+
this.container.appendChild(el);
|
|
3242
|
+
this._previewEl = el;
|
|
3243
|
+
}
|
|
3244
|
+
const cat = this.kinds[this.V.kind[id]];
|
|
3245
|
+
const title = this.titles.get(id) || cat.name;
|
|
3246
|
+
const desc = this.descriptions.get(id);
|
|
3247
|
+
const tags = this.tags.get(id) || [];
|
|
3248
|
+
const status = this.status.get(id);
|
|
3249
|
+
const progress = this.progress.get(id);
|
|
3250
|
+
const parts = [
|
|
3251
|
+
`<div style="display:flex;align-items:center;gap:8px;padding-bottom:8px;margin-bottom:8px;border-bottom:1px solid rgba(255,255,255,0.08);">
|
|
3252
|
+
<span style="width:24px;height:24px;border-radius:5px;background:${alphaize(cat.color, 0.18)};color:${cat.color};display:grid;place-items:center;font:700 12px Inter">${this.icon.get(id) || cat.badge}</span>
|
|
3253
|
+
<div><div style="font-weight:600">${escapeHtml(title)}</div><div style="color:#8b95a7;font-family:ui-monospace,Consolas,monospace;font-size:11px;">#${id} · ${cat.name}</div></div>
|
|
3254
|
+
</div>`,
|
|
3255
|
+
];
|
|
3256
|
+
if (desc) parts.push(`<div style="font-size:12px;color:#8b95a7;margin-bottom:8px;">${escapeHtml(desc)}</div>`);
|
|
3257
|
+
if (status || progress !== undefined) {
|
|
3258
|
+
const bits = [];
|
|
3259
|
+
if (status) bits.push(`<span style="padding:2px 7px;border-radius:10px;background:rgba(255,255,255,0.06);">${status}</span>`);
|
|
3260
|
+
if (progress !== undefined) bits.push(`<span style="padding:2px 7px;border-radius:10px;background:rgba(255,255,255,0.06);">${Math.round(progress * 100)}%</span>`);
|
|
3261
|
+
parts.push(`<div style="display:flex;gap:6px;margin-bottom:8px;font-size:11px;">${bits.join('')}</div>`);
|
|
3262
|
+
}
|
|
3263
|
+
if (tags.length) parts.push(`<div style="display:flex;flex-wrap:wrap;gap:4px;">${tags.map((t) => `<span style="font-size:10.5px;padding:2px 7px;border-radius:3px;background:${alphaize(cat.color, 0.18)};color:${cat.color};">${escapeHtml(t)}</span>`).join('')}</div>`);
|
|
3264
|
+
this._previewEl.innerHTML = parts.join('');
|
|
3265
|
+
this._positionPreview(id);
|
|
3266
|
+
this._previewEl.style.opacity = '1';
|
|
3267
|
+
}
|
|
3268
|
+
_positionPreview(id) {
|
|
3269
|
+
if (!this._previewEl) return;
|
|
3270
|
+
const cx = this.V.posX[id], cy = this.V.posY[id];
|
|
3271
|
+
const hw = this.V.sizeW[id] * 0.5, hh = this.V.sizeH[id] * 0.5;
|
|
3272
|
+
const tr = this._w2s(cx + hw, cy - hh), tl = this._w2s(cx - hw, cy - hh);
|
|
3273
|
+
const cr = this.container.getBoundingClientRect();
|
|
3274
|
+
const dpr = window.devicePixelRatio || 1;
|
|
3275
|
+
let lx = tr.x / dpr + 12, ty = tr.y / dpr;
|
|
3276
|
+
if (lx + 280 > cr.width) lx = tl.x / dpr - 280 - 12;
|
|
3277
|
+
if (lx < 8) lx = 8;
|
|
3278
|
+
this._previewEl.style.left = lx + 'px';
|
|
3279
|
+
this._previewEl.style.top = Math.max(8, ty) + 'px';
|
|
3280
|
+
}
|
|
3281
|
+
_hidePreview() {
|
|
3282
|
+
if (this._previewEl) this._previewEl.style.opacity = '0';
|
|
3283
|
+
this._previewedNode = -1;
|
|
3284
|
+
}
|
|
3285
|
+
|
|
3286
|
+
// ── HTML overlay nodes ────────────────────────────────────────────────
|
|
3287
|
+
_syncHTMLOverlays() {
|
|
3288
|
+
const seen = new Set();
|
|
3289
|
+
const n = this.w.nodeCount_();
|
|
3290
|
+
for (let i = 0; i < n; i++) {
|
|
3291
|
+
const cat = this.kinds[this.V.kind[i]];
|
|
3292
|
+
if (!cat.html) continue;
|
|
3293
|
+
seen.add(i);
|
|
3294
|
+
let el = this._htmlOverlays.get(i);
|
|
3295
|
+
if (!el) {
|
|
3296
|
+
el = document.createElement('div');
|
|
3297
|
+
el.className = 'zflow-html-node';
|
|
3298
|
+
el.style.cssText = 'position:absolute;border:1px solid rgba(255,255,255,0.16);border-radius:8px;background:#161b27;color:#e6edf3;overflow:hidden;font-family:Inter, ui-sans-serif;font-size:12px;transform-origin:top left;';
|
|
3299
|
+
// cat.template comes from the plugin author who registered the kind —
|
|
3300
|
+
// treat as trusted. cat.name passes through escape to be safe.
|
|
3301
|
+
el.innerHTML = cat.template || `<div style="padding:8px;">${escapeHtml(cat.name)} #${i}</div>`;
|
|
3302
|
+
this.container.appendChild(el);
|
|
3303
|
+
this._htmlOverlays.set(i, el);
|
|
3304
|
+
}
|
|
3305
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
3306
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
3307
|
+
const tl = this._w2s(cx - hw, cy - hh);
|
|
3308
|
+
const dpr = window.devicePixelRatio || 1;
|
|
3309
|
+
el.style.left = (tl.x / dpr) + 'px';
|
|
3310
|
+
el.style.top = (tl.y / dpr) + 'px';
|
|
3311
|
+
el.style.width = (this.V.sizeW[i] * this.cam.zoom / dpr) + 'px';
|
|
3312
|
+
el.style.height = (this.V.sizeH[i] * this.cam.zoom / dpr) + 'px';
|
|
3313
|
+
}
|
|
3314
|
+
for (const [id, el] of this._htmlOverlays) {
|
|
3315
|
+
if (!seen.has(id)) { el.remove(); this._htmlOverlays.delete(id); }
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
_drawGrid() {
|
|
3320
|
+
const ctx = this.ctx;
|
|
3321
|
+
const step = 40 * this.cam.zoom;
|
|
3322
|
+
if (step < 6) return;
|
|
3323
|
+
const cx = this.canvas.width / 2 + this.cam.x * this.cam.zoom;
|
|
3324
|
+
const cy = this.canvas.height / 2 + this.cam.y * this.cam.zoom;
|
|
3325
|
+
const startX = cx - Math.ceil(cx / step) * step;
|
|
3326
|
+
const startY = cy - Math.ceil(cy / step) * step;
|
|
3327
|
+
ctx.fillStyle = this.options.snapToGrid ? 'rgba(240,185,58,0.10)' : 'rgba(255,255,255,0.045)';
|
|
3328
|
+
const dpr = window.devicePixelRatio || 1;
|
|
3329
|
+
for (let x = startX; x < this.canvas.width; x += step) {
|
|
3330
|
+
for (let y = startY; y < this.canvas.height; y += step) {
|
|
3331
|
+
ctx.fillRect(x, y, 1.4 * dpr, 1.4 * dpr);
|
|
3332
|
+
}
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
|
|
3336
|
+
_drawMarquee() {
|
|
3337
|
+
if (!this._marquee) return;
|
|
3338
|
+
const a = this._w2s(this._marquee.x0, this._marquee.y0);
|
|
3339
|
+
const b = this._w2s(this._marquee.x1, this._marquee.y1);
|
|
3340
|
+
const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
|
|
3341
|
+
const w = Math.abs(b.x - a.x), h = Math.abs(b.y - a.y);
|
|
3342
|
+
const ctx = this.ctx;
|
|
3343
|
+
ctx.fillStyle = 'rgba(240,185,58,0.10)';
|
|
3344
|
+
ctx.fillRect(x, y, w, h);
|
|
3345
|
+
ctx.strokeStyle = 'rgba(240,185,58,0.7)';
|
|
3346
|
+
ctx.setLineDash([4, 4]);
|
|
3347
|
+
ctx.lineWidth = 1.2;
|
|
3348
|
+
ctx.strokeRect(x, y, w, h);
|
|
3349
|
+
ctx.setLineDash([]);
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
_drawAlignGuides() {
|
|
3353
|
+
if (!this._alignGuides) return;
|
|
3354
|
+
const ctx = this.ctx;
|
|
3355
|
+
ctx.strokeStyle = 'rgba(192,98,232,0.85)';
|
|
3356
|
+
ctx.lineWidth = 1.2;
|
|
3357
|
+
ctx.setLineDash([2, 4]);
|
|
3358
|
+
for (const g of this._alignGuides.v) {
|
|
3359
|
+
const x = this._w2s(g, 0).x;
|
|
3360
|
+
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, this.canvas.height); ctx.stroke();
|
|
3361
|
+
}
|
|
3362
|
+
for (const g of this._alignGuides.h) {
|
|
3363
|
+
const y = this._w2s(0, g).y;
|
|
3364
|
+
ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(this.canvas.width, y); ctx.stroke();
|
|
3365
|
+
}
|
|
3366
|
+
ctx.setLineDash([]);
|
|
3367
|
+
}
|
|
3368
|
+
|
|
3369
|
+
_drawResizeHandles() {
|
|
3370
|
+
if (this._mode !== 'idle') return;
|
|
3371
|
+
const sel = this.getSelection();
|
|
3372
|
+
if (sel.length !== 1) return;
|
|
3373
|
+
const id = sel[0];
|
|
3374
|
+
const cx = this.V.posX[id], cy = this.V.posY[id];
|
|
3375
|
+
const hw = this.V.sizeW[id] * 0.5, hh = this.V.sizeH[id] * 0.5;
|
|
3376
|
+
const pts = {
|
|
3377
|
+
tl: {x: cx-hw, y: cy-hh}, t: {x: cx, y: cy-hh}, tr: {x: cx+hw, y: cy-hh},
|
|
3378
|
+
r: {x: cx+hw, y: cy},
|
|
3379
|
+
br: {x: cx+hw, y: cy+hh}, b: {x: cx, y: cy+hh}, bl: {x: cx-hw, y: cy+hh},
|
|
3380
|
+
l: {x: cx-hw, y: cy},
|
|
3381
|
+
};
|
|
3382
|
+
const ctx = this.ctx;
|
|
3383
|
+
const s = 4 * this.cam.zoom;
|
|
3384
|
+
ctx.fillStyle = '#f0b93a';
|
|
3385
|
+
ctx.strokeStyle = '#07090f';
|
|
3386
|
+
ctx.lineWidth = 1 * this.cam.zoom;
|
|
3387
|
+
for (const c of HANDLE_CORNERS) {
|
|
3388
|
+
const sp = this._w2s(pts[c].x, pts[c].y);
|
|
3389
|
+
ctx.beginPath();
|
|
3390
|
+
ctx.rect(sp.x - s, sp.y - s, s * 2, s * 2);
|
|
3391
|
+
ctx.fill(); ctx.stroke();
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
|
|
3395
|
+
_portWorld(nodeId, side, idx) {
|
|
3396
|
+
const cx = this.V.posX[nodeId], cy = this.V.posY[nodeId];
|
|
3397
|
+
const hw = this.V.sizeW[nodeId] * 0.5, hh = this.V.sizeH[nodeId] * 0.5;
|
|
3398
|
+
const total = side === 0 ? this.V.nIn[nodeId] : this.V.nOut[nodeId];
|
|
3399
|
+
const t = (idx + 1) / (total + 1);
|
|
3400
|
+
const py = cy - hh + this.V.sizeH[nodeId] * t;
|
|
3401
|
+
return { x: side === 0 ? cx - hw : cx + hw, y: py };
|
|
3402
|
+
}
|
|
3403
|
+
|
|
3404
|
+
_orthoPath(p1, p2) {
|
|
3405
|
+
const minOff = 30, dx = p2.x - p1.x;
|
|
3406
|
+
if (dx > 2 * minOff) {
|
|
3407
|
+
const midX = (p1.x + p2.x) / 2;
|
|
3408
|
+
return [p1, { x: midX, y: p1.y }, { x: midX, y: p2.y }, p2];
|
|
3409
|
+
}
|
|
3410
|
+
const midY = (p1.y + p2.y) / 2;
|
|
3411
|
+
return [p1, { x: p1.x + minOff, y: p1.y }, { x: p1.x + minOff, y: midY },
|
|
3412
|
+
{ x: p2.x - minOff, y: midY }, { x: p2.x - minOff, y: p2.y }, p2];
|
|
3413
|
+
}
|
|
3414
|
+
|
|
3415
|
+
_drawEdge(ap, bp, colA, colB, selected, preview, label) {
|
|
3416
|
+
const as = this._w2s(ap.x, ap.y), bs = this._w2s(bp.x, bp.y);
|
|
3417
|
+
const ctx = this.ctx;
|
|
3418
|
+
const grad = ctx.createLinearGradient(as.x, as.y, bs.x, bs.y);
|
|
3419
|
+
grad.addColorStop(0, colA); grad.addColorStop(1, colB);
|
|
3420
|
+
const isActive = this._currentEdgeIdx !== undefined && this._activeEdges.has(this._currentEdgeIdx) &&
|
|
3421
|
+
this._activeEdges.get(this._currentEdgeIdx) > performance.now();
|
|
3422
|
+
ctx.strokeStyle = selected ? '#f0b93a' : isActive ? '#5b8def' : (preview ? '#8b95a7' : grad);
|
|
3423
|
+
ctx.lineWidth = (selected ? 2.4 : isActive ? 3.0 : 1.6) * this.cam.zoom;
|
|
3424
|
+
if (isActive) { ctx.shadowColor = '#5b8def'; ctx.shadowBlur = 10 * this.cam.zoom; }
|
|
3425
|
+
ctx.lineJoin = 'round';
|
|
3426
|
+
let midPt;
|
|
3427
|
+
if (this.options.edgeStyle === 'orthogonal') {
|
|
3428
|
+
const path = this._orthoPath(as, bs);
|
|
3429
|
+
ctx.beginPath();
|
|
3430
|
+
ctx.moveTo(path[0].x, path[0].y);
|
|
3431
|
+
for (let i = 1; i < path.length; i++) ctx.lineTo(path[i].x, path[i].y);
|
|
3432
|
+
ctx.stroke();
|
|
3433
|
+
midPt = path[Math.floor(path.length / 2)];
|
|
3434
|
+
} else {
|
|
3435
|
+
const dxe = bs.x - as.x, dye = bs.y - as.y;
|
|
3436
|
+
const off = Math.max(50, Math.abs(dxe) * 0.5 + Math.abs(dye) * 0.4);
|
|
3437
|
+
ctx.beginPath();
|
|
3438
|
+
ctx.moveTo(as.x, as.y);
|
|
3439
|
+
ctx.bezierCurveTo(as.x + off, as.y, bs.x - off, bs.y, bs.x, bs.y);
|
|
3440
|
+
ctx.stroke();
|
|
3441
|
+
midPt = bezPt$1(0.5, as.x, as.y, as.x + off, as.y, bs.x - off, bs.y, bs.x, bs.y);
|
|
3442
|
+
}
|
|
3443
|
+
// Flow particles (set per-edge via setEdgeAnimated or globally).
|
|
3444
|
+
if (!preview && this._currentEdgeIdx !== undefined && this.animatedEdges.has(this._currentEdgeIdx)) {
|
|
3445
|
+
const N = 4;
|
|
3446
|
+
for (let k = 0; k < N; k++) {
|
|
3447
|
+
const t = ((this._edgePhase / 1000) + k / N) % 1;
|
|
3448
|
+
let p;
|
|
3449
|
+
if (this.options.edgeStyle === 'orthogonal') {
|
|
3450
|
+
const dxe = bs.x - as.x, dye = bs.y - as.y;
|
|
3451
|
+
const off = Math.max(50, Math.abs(dxe) * 0.5 + Math.abs(dye) * 0.4);
|
|
3452
|
+
p = bezPt$1(t, as.x, as.y, as.x + off, as.y, bs.x - off, bs.y, bs.x, bs.y);
|
|
3453
|
+
} else {
|
|
3454
|
+
const dxe = bs.x - as.x, dye = bs.y - as.y;
|
|
3455
|
+
const off = Math.max(50, Math.abs(dxe) * 0.5 + Math.abs(dye) * 0.4);
|
|
3456
|
+
p = bezPt$1(t, as.x, as.y, as.x + off, as.y, bs.x - off, bs.y, bs.x, bs.y);
|
|
3457
|
+
}
|
|
3458
|
+
ctx.fillStyle = colB;
|
|
3459
|
+
ctx.beginPath(); ctx.arc(p.x, p.y, 3.2 * this.cam.zoom, 0, Math.PI * 2); ctx.fill();
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
// Edge label badge.
|
|
3463
|
+
if (!preview && label && this.cam.zoom > 0.45) {
|
|
3464
|
+
ctx.font = `600 ${10.5 * this.cam.zoom}px ui-monospace, Consolas, monospace`;
|
|
3465
|
+
const tw = ctx.measureText(label).width;
|
|
3466
|
+
const pad = 5 * this.cam.zoom;
|
|
3467
|
+
const bw = tw + pad * 2;
|
|
3468
|
+
const bh = 16 * this.cam.zoom;
|
|
3469
|
+
ctx.fillStyle = '#0b0f17';
|
|
3470
|
+
this._roundRect(midPt.x - bw / 2, midPt.y - bh / 2, bw, bh, 5 * this.cam.zoom);
|
|
3471
|
+
ctx.fill();
|
|
3472
|
+
ctx.strokeStyle = selected ? '#f0b93a' : alphaize(colA, 0.6);
|
|
3473
|
+
ctx.lineWidth = 1 * this.cam.zoom;
|
|
3474
|
+
ctx.stroke();
|
|
3475
|
+
ctx.fillStyle = '#e6edf3';
|
|
3476
|
+
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
|
3477
|
+
ctx.fillText(label, midPt.x, midPt.y);
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
|
|
3481
|
+
/** Slim overlay: only paints what WebGL didn't, with LOD gating. */
|
|
3482
|
+
_drawNodeOverlay(i) {
|
|
3483
|
+
const z = this.cam.zoom;
|
|
3484
|
+
// LOD: below 0.3 zoom (or with >5k nodes far out) skip text + ports entirely.
|
|
3485
|
+
if (z < 0.25) return;
|
|
3486
|
+
if (this.w.nodeCount_() > 5000 && z < 0.55) return;
|
|
3487
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
3488
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
3489
|
+
const tl = this._w2s(cx - hw, cy - hh);
|
|
3490
|
+
const sw = this.V.sizeW[i] * z;
|
|
3491
|
+
const sh = this.V.sizeH[i] * z;
|
|
3492
|
+
const cat = this.kinds[this.V.kind[i]];
|
|
3493
|
+
const color = this.colors.get(i) || cat.color;
|
|
3494
|
+
const ctx = this.ctx;
|
|
3495
|
+
if (z > 0.4) {
|
|
3496
|
+
const title = this.titles.get(i) || cat.name;
|
|
3497
|
+
ctx.font = `600 ${12 * z}px Inter, ui-sans-serif`;
|
|
3498
|
+
ctx.fillStyle = '#0b0f17';
|
|
3499
|
+
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
|
3500
|
+
ctx.fillText(title, tl.x + sw / 2, tl.y + 11 * z);
|
|
3501
|
+
}
|
|
3502
|
+
// Ports only when zoom is decent.
|
|
3503
|
+
if (z > 0.35) {
|
|
3504
|
+
for (let s = 0; s < 2; s++) {
|
|
3505
|
+
const count = s === 0 ? this.V.nIn[i] : this.V.nOut[i];
|
|
3506
|
+
for (let p = 0; p < count; p++) {
|
|
3507
|
+
const wp = this._portWorld(i, s, p);
|
|
3508
|
+
const sp = this._w2s(wp.x, wp.y);
|
|
3509
|
+
ctx.fillStyle = color;
|
|
3510
|
+
ctx.strokeStyle = '#07090f';
|
|
3511
|
+
ctx.lineWidth = 1.5 * z;
|
|
3512
|
+
ctx.beginPath(); ctx.arc(sp.x, sp.y, 4.5 * z, 0, Math.PI * 2);
|
|
3513
|
+
ctx.fill(); ctx.stroke();
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
if (this.breakpoints.has(i)) {
|
|
3518
|
+
ctx.fillStyle = '#e8462b';
|
|
3519
|
+
ctx.beginPath(); ctx.arc(tl.x - 4 * z, tl.y + sh / 2, 4.5 * z, 0, Math.PI * 2); ctx.fill();
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
|
|
3523
|
+
_drawNode(i) {
|
|
3524
|
+
const cx = this.V.posX[i], cy = this.V.posY[i];
|
|
3525
|
+
const hw = this.V.sizeW[i] * 0.5, hh = this.V.sizeH[i] * 0.5;
|
|
3526
|
+
const tl = this._w2s(cx - hw, cy - hh);
|
|
3527
|
+
const sw = this.V.sizeW[i] * this.cam.zoom;
|
|
3528
|
+
const sh = this.V.sizeH[i] * this.cam.zoom;
|
|
3529
|
+
const cat = this.kinds[this.V.kind[i]];
|
|
3530
|
+
const color = this.colors.get(i) || cat.color;
|
|
3531
|
+
const sel = this.V.selected[i] !== 0;
|
|
3532
|
+
const hov = this._hoveredNode === i && this._mode === 'idle';
|
|
3533
|
+
const ctx = this.ctx;
|
|
3534
|
+
|
|
3535
|
+
// Body shadow + fill.
|
|
3536
|
+
ctx.save();
|
|
3537
|
+
ctx.shadowColor = 'rgba(0,0,0,0.45)';
|
|
3538
|
+
ctx.shadowBlur = (hov ? 14 : 10) * this.cam.zoom;
|
|
3539
|
+
ctx.shadowOffsetY = 4 * this.cam.zoom;
|
|
3540
|
+
ctx.fillStyle = '#161b27';
|
|
3541
|
+
this._shapePath(cat.shape, tl.x, tl.y, sw, sh);
|
|
3542
|
+
ctx.fill();
|
|
3543
|
+
ctx.restore();
|
|
3544
|
+
|
|
3545
|
+
// Header strip (rect kinds only).
|
|
3546
|
+
if (cat.shape === 'rect') {
|
|
3547
|
+
ctx.save();
|
|
3548
|
+
this._shapePath(cat.shape, tl.x, tl.y, sw, sh);
|
|
3549
|
+
ctx.clip();
|
|
3550
|
+
ctx.fillStyle = color;
|
|
3551
|
+
ctx.fillRect(tl.x, tl.y, sw, 22 * this.cam.zoom);
|
|
3552
|
+
ctx.restore();
|
|
3553
|
+
}
|
|
3554
|
+
|
|
3555
|
+
// Running pulse — strong blue glow while exec is in flight.
|
|
3556
|
+
if (this.status.get(i) === 'running') {
|
|
3557
|
+
const pulse = 0.5 + 0.5 * Math.sin(performance.now() / 180);
|
|
3558
|
+
ctx.save();
|
|
3559
|
+
ctx.shadowColor = '#5b8def';
|
|
3560
|
+
ctx.shadowBlur = (18 + 14 * pulse) * this.cam.zoom;
|
|
3561
|
+
ctx.strokeStyle = `rgba(91,141,239,${0.6 + 0.4 * pulse})`;
|
|
3562
|
+
ctx.lineWidth = (2.2 + pulse) * this.cam.zoom;
|
|
3563
|
+
this._shapePath(cat.shape, tl.x - 2, tl.y - 2, sw + 4, sh + 4);
|
|
3564
|
+
ctx.stroke();
|
|
3565
|
+
ctx.restore();
|
|
3566
|
+
}
|
|
3567
|
+
|
|
3568
|
+
// Border / selection.
|
|
3569
|
+
if (sel) {
|
|
3570
|
+
ctx.save();
|
|
3571
|
+
ctx.shadowColor = 'rgba(240,185,58,0.55)';
|
|
3572
|
+
ctx.shadowBlur = 14 * this.cam.zoom;
|
|
3573
|
+
ctx.strokeStyle = '#f0b93a'; ctx.lineWidth = 1.6 * this.cam.zoom;
|
|
3574
|
+
this._shapePath(cat.shape, tl.x, tl.y, sw, sh); ctx.stroke();
|
|
3575
|
+
ctx.restore();
|
|
3576
|
+
} else {
|
|
3577
|
+
ctx.strokeStyle = hov ? alphaize(color, 0.55) : 'rgba(255,255,255,0.08)';
|
|
3578
|
+
ctx.lineWidth = (hov ? 1.3 : 1) * this.cam.zoom;
|
|
3579
|
+
this._shapePath(cat.shape, tl.x, tl.y, sw, sh); ctx.stroke();
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
// Title.
|
|
3583
|
+
if (this.cam.zoom > 0.42) {
|
|
3584
|
+
const title = this.titles.get(i) || `${cat.name} #${i}`;
|
|
3585
|
+
ctx.textBaseline = 'middle';
|
|
3586
|
+
ctx.font = `600 ${11 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3587
|
+
if (cat.shape === 'rect') {
|
|
3588
|
+
ctx.fillStyle = '#0b0f17'; ctx.textAlign = 'left';
|
|
3589
|
+
ctx.fillText(title, tl.x + 10 * this.cam.zoom, tl.y + 11 * this.cam.zoom);
|
|
3590
|
+
} else {
|
|
3591
|
+
ctx.fillStyle = color; ctx.textAlign = 'center';
|
|
3592
|
+
ctx.fillText(title, tl.x + sw / 2, tl.y + sh / 2);
|
|
3593
|
+
}
|
|
3594
|
+
}
|
|
3595
|
+
|
|
3596
|
+
|
|
3597
|
+
// Progress bar (bottom).
|
|
3598
|
+
const prog = this.progress.get(i);
|
|
3599
|
+
if (prog !== undefined && prog > 0) {
|
|
3600
|
+
const barH = 3 * this.cam.zoom;
|
|
3601
|
+
const barY = tl.y + sh - barH - 2 * this.cam.zoom;
|
|
3602
|
+
const barX = tl.x + 8 * this.cam.zoom;
|
|
3603
|
+
const barW = sw - 16 * this.cam.zoom;
|
|
3604
|
+
ctx.fillStyle = 'rgba(255,255,255,0.06)';
|
|
3605
|
+
ctx.fillRect(barX, barY, barW, barH);
|
|
3606
|
+
ctx.fillStyle = color;
|
|
3607
|
+
ctx.fillRect(barX, barY, barW * Math.min(1, Math.max(0, prog)), barH);
|
|
3608
|
+
}
|
|
3609
|
+
|
|
3610
|
+
// Tags.
|
|
3611
|
+
const tags = this.tags.get(i);
|
|
3612
|
+
if (tags && tags.length && this.cam.zoom > 0.5) {
|
|
3613
|
+
let tx = tl.x + 8 * this.cam.zoom;
|
|
3614
|
+
const ty = tl.y + sh - 24 * this.cam.zoom;
|
|
3615
|
+
ctx.font = `500 ${9 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3616
|
+
ctx.textBaseline = 'middle';
|
|
3617
|
+
for (const tag of tags) {
|
|
3618
|
+
const wText = ctx.measureText(tag).width;
|
|
3619
|
+
const w0 = wText + 10 * this.cam.zoom;
|
|
3620
|
+
if (tx + w0 > tl.x + sw - 8 * this.cam.zoom) break;
|
|
3621
|
+
ctx.fillStyle = alphaize(color, 0.18);
|
|
3622
|
+
this._roundRect(tx, ty, w0, 14 * this.cam.zoom, 3 * this.cam.zoom);
|
|
3623
|
+
ctx.fill();
|
|
3624
|
+
ctx.fillStyle = color;
|
|
3625
|
+
ctx.textAlign = 'left';
|
|
3626
|
+
ctx.fillText(tag, tx + 5 * this.cam.zoom, ty + 7 * this.cam.zoom);
|
|
3627
|
+
tx += w0 + 4 * this.cam.zoom;
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
|
|
3631
|
+
// Sparkline (live metric).
|
|
3632
|
+
const m = this.metrics.get(i);
|
|
3633
|
+
if (m && m.count > 1 && cat.shape === 'rect' && this.cam.zoom > 0.45) {
|
|
3634
|
+
const max = this.metricMax.get(i) || 1;
|
|
3635
|
+
const px = tl.x + 8 * this.cam.zoom, py = tl.y + sh - 22 * this.cam.zoom;
|
|
3636
|
+
const pw = sw - 16 * this.cam.zoom, ph = 16 * this.cam.zoom;
|
|
3637
|
+
ctx.strokeStyle = alphaize(color, 0.85);
|
|
3638
|
+
ctx.lineWidth = 1.5 * this.cam.zoom;
|
|
3639
|
+
ctx.beginPath();
|
|
3640
|
+
for (let k = 0; k < m.count; k++) {
|
|
3641
|
+
const v = m.data[(m.idx + this._metricCap - m.count + k) % this._metricCap];
|
|
3642
|
+
const xx = px + (k / Math.max(1, m.count - 1)) * pw;
|
|
3643
|
+
const yy = py + ph - (Math.min(Math.max(v / max, 0), 1)) * ph;
|
|
3644
|
+
if (k === 0) ctx.moveTo(xx, yy); else ctx.lineTo(xx, yy);
|
|
3645
|
+
}
|
|
3646
|
+
ctx.stroke();
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
// Breakpoint indicator (red filled circle on left edge).
|
|
3650
|
+
if (this.breakpoints.has(i)) {
|
|
3651
|
+
const bx = tl.x - 4 * this.cam.zoom, by = tl.y + sh / 2;
|
|
3652
|
+
ctx.save();
|
|
3653
|
+
ctx.shadowColor = '#e8462b'; ctx.shadowBlur = 8 * this.cam.zoom;
|
|
3654
|
+
ctx.fillStyle = '#e8462b';
|
|
3655
|
+
ctx.beginPath(); ctx.arc(bx, by, 4.5 * this.cam.zoom, 0, Math.PI * 2); ctx.fill();
|
|
3656
|
+
ctx.restore();
|
|
3657
|
+
}
|
|
3658
|
+
|
|
3659
|
+
// Status dot (top-right of header).
|
|
3660
|
+
const st = this.status.get(i);
|
|
3661
|
+
if (st && cat.shape === 'rect') {
|
|
3662
|
+
const sCol = STATUS_COLORS[st] || '#8b95a7';
|
|
3663
|
+
const dotX = tl.x + sw - 12 * this.cam.zoom;
|
|
3664
|
+
const dotY = tl.y + 11 * this.cam.zoom;
|
|
3665
|
+
ctx.save();
|
|
3666
|
+
ctx.shadowColor = sCol; ctx.shadowBlur = 6 * this.cam.zoom;
|
|
3667
|
+
ctx.fillStyle = sCol;
|
|
3668
|
+
ctx.beginPath(); ctx.arc(dotX, dotY, 3.5 * this.cam.zoom, 0, Math.PI * 2); ctx.fill();
|
|
3669
|
+
ctx.restore();
|
|
3670
|
+
}
|
|
3671
|
+
|
|
3672
|
+
// Locked indicator (small lock glyph top-left).
|
|
3673
|
+
if (this.locked.has(i)) {
|
|
3674
|
+
const lx = tl.x + 6 * this.cam.zoom, ly = tl.y + 6 * this.cam.zoom;
|
|
3675
|
+
const lz = 10 * this.cam.zoom;
|
|
3676
|
+
ctx.fillStyle = 'rgba(0,0,0,0.55)';
|
|
3677
|
+
this._roundRect(lx, ly, lz, lz, 2 * this.cam.zoom); ctx.fill();
|
|
3678
|
+
ctx.strokeStyle = '#f0b93a'; ctx.lineWidth = 1.2 * this.cam.zoom;
|
|
3679
|
+
ctx.strokeRect(lx + 2.5 * this.cam.zoom, ly + 5 * this.cam.zoom, lz - 5 * this.cam.zoom, lz - 6 * this.cam.zoom);
|
|
3680
|
+
ctx.beginPath();
|
|
3681
|
+
ctx.arc(lx + lz * 0.5, ly + 5 * this.cam.zoom, 2 * this.cam.zoom, Math.PI, 0);
|
|
3682
|
+
ctx.stroke();
|
|
3683
|
+
}
|
|
3684
|
+
|
|
3685
|
+
// Image thumbnail (top of body).
|
|
3686
|
+
const imgUrl = this.image.get(i);
|
|
3687
|
+
if (imgUrl && cat.shape === 'rect' && this.cam.zoom > 0.5) {
|
|
3688
|
+
const img = this._getImage(imgUrl);
|
|
3689
|
+
if (img && img.ready) {
|
|
3690
|
+
const ix = tl.x + 8 * this.cam.zoom;
|
|
3691
|
+
const iy = tl.y + 28 * this.cam.zoom;
|
|
3692
|
+
const iw = sw - 16 * this.cam.zoom;
|
|
3693
|
+
const ih = Math.min(54 * this.cam.zoom, sh * 0.45);
|
|
3694
|
+
ctx.save();
|
|
3695
|
+
this._roundRect(ix, iy, iw, ih, 4 * this.cam.zoom);
|
|
3696
|
+
ctx.clip();
|
|
3697
|
+
ctx.drawImage(img.img, ix, iy, iw, ih);
|
|
3698
|
+
ctx.restore();
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
// Inline markdown description (one line, runs).
|
|
3703
|
+
const desc = this.descriptions.get(i);
|
|
3704
|
+
if (desc && cat.shape === 'rect' && this.cam.zoom > 0.5 && !imgUrl) {
|
|
3705
|
+
const runs = this.options.inlineMarkdown !== false ? parseInlineMd(desc) : [{ t: desc, style: 'p' }];
|
|
3706
|
+
let dx = tl.x + 8 * this.cam.zoom;
|
|
3707
|
+
const dyy = tl.y + 44 * this.cam.zoom;
|
|
3708
|
+
ctx.font = `400 ${10 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3709
|
+
ctx.textBaseline = 'top';
|
|
3710
|
+
const maxX = tl.x + sw - 8 * this.cam.zoom;
|
|
3711
|
+
for (const run of runs) {
|
|
3712
|
+
let f = `${10 * this.cam.zoom}px `;
|
|
3713
|
+
if (run.style === 'b') f = `700 ${10 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3714
|
+
else if (run.style === 'i') f = `italic 400 ${10 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3715
|
+
else if (run.style === 'c') f = `${10 * this.cam.zoom}px ui-monospace, Consolas, monospace`;
|
|
3716
|
+
else if (run.style === 'a') f = `400 ${10 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3717
|
+
else f = `400 ${10 * this.cam.zoom}px Inter, ui-sans-serif`;
|
|
3718
|
+
ctx.font = f;
|
|
3719
|
+
ctx.fillStyle = run.style === 'a' ? '#5be0d0' : run.style === 'c' ? '#f0b93a' : '#c8d1de';
|
|
3720
|
+
const tw = ctx.measureText(run.t).width;
|
|
3721
|
+
if (dx + tw > maxX) break;
|
|
3722
|
+
ctx.fillText(run.t, dx, dyy);
|
|
3723
|
+
dx += tw;
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
|
|
3727
|
+
// Search hit glow.
|
|
3728
|
+
if (this._searchHits && this._searchHits.includes(i)) {
|
|
3729
|
+
ctx.save();
|
|
3730
|
+
ctx.shadowColor = '#5be0d0';
|
|
3731
|
+
ctx.shadowBlur = 18 * this.cam.zoom;
|
|
3732
|
+
ctx.strokeStyle = '#5be0d0';
|
|
3733
|
+
ctx.lineWidth = 1.6 * this.cam.zoom;
|
|
3734
|
+
this._shapePath(cat.shape, tl.x - 3, tl.y - 3, sw + 6, sh + 6);
|
|
3735
|
+
ctx.stroke();
|
|
3736
|
+
ctx.restore();
|
|
3737
|
+
}
|
|
3738
|
+
|
|
3739
|
+
// Ports.
|
|
3740
|
+
for (let s = 0; s < 2; s++) {
|
|
3741
|
+
const count = s === 0 ? this.V.nIn[i] : this.V.nOut[i];
|
|
3742
|
+
for (let p = 0; p < count; p++) {
|
|
3743
|
+
const wp = this._portWorld(i, s, p);
|
|
3744
|
+
const sp = this._w2s(wp.x, wp.y);
|
|
3745
|
+
ctx.fillStyle = color;
|
|
3746
|
+
ctx.strokeStyle = '#07090f';
|
|
3747
|
+
ctx.lineWidth = 1.5 * this.cam.zoom;
|
|
3748
|
+
ctx.beginPath(); ctx.arc(sp.x, sp.y, 4.5 * this.cam.zoom, 0, Math.PI * 2);
|
|
3749
|
+
ctx.fill(); ctx.stroke();
|
|
3750
|
+
}
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
|
|
3754
|
+
_shapePath(shape, x, y, w, h) {
|
|
3755
|
+
const ctx = this.ctx;
|
|
3756
|
+
if (shape === 'diamond') {
|
|
3757
|
+
const cx = x + w / 2, cy = y + h / 2;
|
|
3758
|
+
ctx.beginPath();
|
|
3759
|
+
ctx.moveTo(cx, y); ctx.lineTo(x + w, cy);
|
|
3760
|
+
ctx.lineTo(cx, y + h); ctx.lineTo(x, cy);
|
|
3761
|
+
ctx.closePath(); return;
|
|
3762
|
+
}
|
|
3763
|
+
if (shape === 'ellipse') {
|
|
3764
|
+
ctx.beginPath();
|
|
3765
|
+
ctx.ellipse(x + w / 2, y + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
|
|
3766
|
+
return;
|
|
3767
|
+
}
|
|
3768
|
+
if (shape === 'hexagon') {
|
|
3769
|
+
const cx = x + w / 2, cy = y + h / 2;
|
|
3770
|
+
const hw = w / 2, a = hw * 0.45;
|
|
3771
|
+
ctx.beginPath();
|
|
3772
|
+
ctx.moveTo(cx - hw + a, y); ctx.lineTo(cx + hw - a, y);
|
|
3773
|
+
ctx.lineTo(x + w, cy); ctx.lineTo(cx + hw - a, y + h);
|
|
3774
|
+
ctx.lineTo(cx - hw + a, y + h); ctx.lineTo(x, cy);
|
|
3775
|
+
ctx.closePath(); return;
|
|
3776
|
+
}
|
|
3777
|
+
this._roundRect(x, y, w, h, 8);
|
|
3778
|
+
}
|
|
3779
|
+
_roundRect(x, y, w, h, r) {
|
|
3780
|
+
const ctx = this.ctx;
|
|
3781
|
+
ctx.beginPath();
|
|
3782
|
+
ctx.moveTo(x + r, y); ctx.lineTo(x + w - r, y);
|
|
3783
|
+
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
|
|
3784
|
+
ctx.lineTo(x + w, y + h - r);
|
|
3785
|
+
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
|
|
3786
|
+
ctx.lineTo(x + r, y + h);
|
|
3787
|
+
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
|
|
3788
|
+
ctx.lineTo(x, y + r);
|
|
3789
|
+
ctx.quadraticCurveTo(x, y, x + r, y);
|
|
3790
|
+
ctx.closePath();
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
|
|
3794
|
+
// ── Free helpers ──────────────────────────────────────────────────────────
|
|
3795
|
+
function bezPt$1(t, x1, y1, cx1, cy1, cx2, cy2, x2, y2) {
|
|
3796
|
+
const mt = 1 - t, mt2 = mt * mt, t2 = t * t;
|
|
3797
|
+
const a = mt2 * mt, b = 3 * mt2 * t, c = 3 * mt * t2, d = t2 * t;
|
|
3798
|
+
return { x: a*x1 + b*cx1 + c*cx2 + d*x2, y: a*y1 + b*cy1 + c*cy2 + d*y2 };
|
|
3799
|
+
}
|
|
3800
|
+
function distSeg2(qx, qy, x1, y1, x2, y2) {
|
|
3801
|
+
const dx = x2 - x1, dy = y2 - y1;
|
|
3802
|
+
const len2 = dx*dx + dy*dy;
|
|
3803
|
+
if (len2 === 0) { const ddx = qx - x1, ddy = qy - y1; return ddx*ddx + ddy*ddy; }
|
|
3804
|
+
let t = ((qx - x1) * dx + (qy - y1) * dy) / len2;
|
|
3805
|
+
t = Math.max(0, Math.min(1, t));
|
|
3806
|
+
const px = x1 + t * dx, py = y1 + t * dy;
|
|
3807
|
+
const ddx = qx - px, ddy = qy - py;
|
|
3808
|
+
return ddx*ddx + ddy*ddy;
|
|
3809
|
+
}
|
|
3810
|
+
function alphaize(hex, a) {
|
|
3811
|
+
if (hex.startsWith('rgb')) return hex.replace(')', `, ${a})`).replace('rgb(', 'rgba(');
|
|
3812
|
+
const r = parseInt(hex.slice(1, 3), 16);
|
|
3813
|
+
const g = parseInt(hex.slice(3, 5), 16);
|
|
3814
|
+
const b = parseInt(hex.slice(5, 7), 16);
|
|
3815
|
+
return `rgba(${r},${g},${b},${a})`;
|
|
3816
|
+
}
|
|
3817
|
+
const STATUS_COLORS = {
|
|
3818
|
+
ok: '#5bd17a', live: '#5bd17a', running: '#5b8def', idle: '#8b95a7',
|
|
3819
|
+
warn: '#f0b93a', error: '#e8462b', failed: '#e8462b', stopped: '#8b95a7',
|
|
3820
|
+
};
|
|
3821
|
+
|
|
3822
|
+
function parseInlineMd(s) {
|
|
3823
|
+
if (!s) return [{ t: '', style: 'p' }];
|
|
3824
|
+
const runs = [];
|
|
3825
|
+
const re = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g;
|
|
3826
|
+
let last = 0, m;
|
|
3827
|
+
while ((m = re.exec(s)) !== null) {
|
|
3828
|
+
if (m.index > last) runs.push({ t: s.slice(last, m.index), style: 'p' });
|
|
3829
|
+
const tok = m[1];
|
|
3830
|
+
if (tok.startsWith('**')) runs.push({ t: tok.slice(2, -2), style: 'b' });
|
|
3831
|
+
else if (tok.startsWith('`')) runs.push({ t: tok.slice(1, -1), style: 'c' });
|
|
3832
|
+
else if (tok.startsWith('[')) {
|
|
3833
|
+
const close = tok.indexOf('](');
|
|
3834
|
+
runs.push({ t: tok.slice(1, close), style: 'a', href: tok.slice(close + 2, -1) });
|
|
3835
|
+
}
|
|
3836
|
+
else runs.push({ t: tok.slice(1, -1), style: 'i' });
|
|
3837
|
+
last = m.index + tok.length;
|
|
3838
|
+
}
|
|
3839
|
+
if (last < s.length) runs.push({ t: s.slice(last), style: 'p' });
|
|
3840
|
+
return runs;
|
|
3841
|
+
}
|
|
3842
|
+
|
|
3843
|
+
function pinchInfo(pointers) {
|
|
3844
|
+
const [a, b] = [...pointers.values()];
|
|
3845
|
+
const dx = b.x - a.x, dy = b.y - a.y;
|
|
3846
|
+
return { dist: Math.hypot(dx, dy) || 1, mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } };
|
|
3847
|
+
}
|
|
3848
|
+
|
|
3849
|
+
function isCompatibleType(out, inn) {
|
|
3850
|
+
if (!out || !inn) return true;
|
|
3851
|
+
if (out === inn) return true;
|
|
3852
|
+
if (out === 'any' || inn === 'any') return true;
|
|
3853
|
+
if (inn === 'string') return true; // anything stringifies
|
|
3854
|
+
const numerics = new Set(['number', 'int', 'float', 'integer']);
|
|
3855
|
+
if (numerics.has(out) && numerics.has(inn)) return true;
|
|
3856
|
+
return false;
|
|
3857
|
+
}
|
|
3858
|
+
|
|
3859
|
+
function fnvHash(v) {
|
|
3860
|
+
// Fast structural hash for primitives / shallow objects / arrays. Avoids JSON.
|
|
3861
|
+
let h = 0x811c9dc5;
|
|
3862
|
+
const visit = (x) => {
|
|
3863
|
+
if (x === null || x === undefined) { h = (h ^ 0xff) * 0x01000193 >>> 0; return; }
|
|
3864
|
+
const t = typeof x;
|
|
3865
|
+
if (t === 'number') { h = (h ^ ((x * 1e6) | 0)) * 0x01000193 >>> 0; return; }
|
|
3866
|
+
if (t === 'string') { for (let i = 0; i < x.length; i++) h = (h ^ x.charCodeAt(i)) * 0x01000193 >>> 0; return; }
|
|
3867
|
+
if (t === 'boolean') { h = (h ^ (x ? 1 : 0)) * 0x01000193 >>> 0; return; }
|
|
3868
|
+
if (Array.isArray(x)) { for (const e of x) visit(e); return; }
|
|
3869
|
+
if (t === 'object') { for (const k of Object.keys(x).sort()) { for (let i = 0; i < k.length; i++) h = (h ^ k.charCodeAt(i)) * 0x01000193 >>> 0; visit(x[k]); } return; }
|
|
3870
|
+
};
|
|
3871
|
+
visit(v);
|
|
3872
|
+
return h >>> 0;
|
|
3873
|
+
}
|
|
3874
|
+
|
|
3875
|
+
function bubbleSummary(v) {
|
|
3876
|
+
if (typeof v === 'number') return formatRuntimeValue(v);
|
|
3877
|
+
if (v && typeof v === 'object') {
|
|
3878
|
+
return Object.entries(v).filter(([, x]) => x != null).map(([k, x]) => `${k}: ${formatRuntimeValue(x)}`).join(' ');
|
|
3879
|
+
}
|
|
3880
|
+
return formatRuntimeValue(v);
|
|
3881
|
+
}
|
|
3882
|
+
|
|
3883
|
+
function formatRuntimeValue(v) {
|
|
3884
|
+
if (v === null || v === undefined) return '∅';
|
|
3885
|
+
if (typeof v === 'number') return Number.isInteger(v) ? String(v) : v.toFixed(2);
|
|
3886
|
+
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
|
3887
|
+
if (typeof v === 'string') return v.length > 22 ? v.slice(0, 22) + '…' : v;
|
|
3888
|
+
try { const s = JSON.stringify(v); return s.length > 30 ? s.slice(0, 30) + '…' : s; }
|
|
3889
|
+
catch { return '[obj]'; }
|
|
3890
|
+
}
|
|
3891
|
+
|
|
3892
|
+
function parseHex$1(h) {
|
|
3893
|
+
return [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
|
|
3894
|
+
}
|
|
3895
|
+
function pointInPolygon(px, py, poly) {
|
|
3896
|
+
let inside = false;
|
|
3897
|
+
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
|
|
3898
|
+
const xi = poly[i].x, yi = poly[i].y, xj = poly[j].x, yj = poly[j].y;
|
|
3899
|
+
const intersect = ((yi > py) !== (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi) + xi);
|
|
3900
|
+
if (intersect) inside = !inside;
|
|
3901
|
+
}
|
|
3902
|
+
return inside;
|
|
3903
|
+
}
|
|
3904
|
+
function escapeHtml(s) {
|
|
3905
|
+
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
3906
|
+
}
|
|
3907
|
+
function escapeXml(s) { return escapeHtml(s); }
|
|
3908
|
+
|
|
3909
|
+
// ── Mermaid + DOT importers ───────────────────────────────────────────────
|
|
3910
|
+
function parseMermaid(text) {
|
|
3911
|
+
const nodes = new Map(), edges = [];
|
|
3912
|
+
const lines = text.split('\n').map((l) => l.replace(/\/\/.*$/, '').trim()).filter(Boolean);
|
|
3913
|
+
let i0 = 0;
|
|
3914
|
+
if (lines[0] && /^(graph|flowchart)\b/i.test(lines[0])) i0 = 1;
|
|
3915
|
+
const NODE_RE = /([A-Za-z_][A-Za-z0-9_]*)(?:(\[\[)([^\]]+)\]\]|\[([^\]]+)\]|\(\(([^)]+)\)\)|\(([^)]+)\)|\{([^}]+)\})?/;
|
|
3916
|
+
function consume(s, pos) {
|
|
3917
|
+
const sub = s.slice(pos);
|
|
3918
|
+
const m = sub.match(NODE_RE);
|
|
3919
|
+
if (!m || m.index !== 0) return null;
|
|
3920
|
+
const id = m[1];
|
|
3921
|
+
let shape = 'default', label = id;
|
|
3922
|
+
if (m[2]) { shape = 'subroutine'; label = m[3]; }
|
|
3923
|
+
else if (m[4]) { shape = 'rect'; label = m[4]; }
|
|
3924
|
+
else if (m[5]) { shape = 'circle'; label = m[5]; }
|
|
3925
|
+
else if (m[6]) { shape = 'round'; label = m[6]; }
|
|
3926
|
+
else if (m[7]) { shape = 'rhombus';label = m[7]; }
|
|
3927
|
+
if (!nodes.has(id) || nodes.get(id).shape === 'default') nodes.set(id, { label, shape });
|
|
3928
|
+
return { id, end: pos + m[0].length };
|
|
3929
|
+
}
|
|
3930
|
+
for (let li = i0; li < lines.length; li++) {
|
|
3931
|
+
const ln = lines[li];
|
|
3932
|
+
const a = consume(ln, 0); if (!a) continue;
|
|
3933
|
+
let rest = ln.slice(a.end).trim();
|
|
3934
|
+
const arrow = rest.match(/^([-=.~]+>?|---|===)\s*(?:\|([^|]+)\|\s*)?/);
|
|
3935
|
+
if (!arrow) continue;
|
|
3936
|
+
rest = rest.slice(arrow[0].length).trim();
|
|
3937
|
+
const offset = ln.length - rest.length;
|
|
3938
|
+
const b = consume(ln, offset); if (!b) continue;
|
|
3939
|
+
edges.push({ from: a.id, to: b.id, label: arrow[2] || null });
|
|
3940
|
+
}
|
|
3941
|
+
return { nodes, edges };
|
|
3942
|
+
}
|
|
3943
|
+
function parseDot(text) {
|
|
3944
|
+
const nodes = new Map(), edges = [];
|
|
3945
|
+
text = text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*#.*$/gm, '').replace(/\/\/.*$/gm, '');
|
|
3946
|
+
text = text.replace(/^\s*(?:strict\s+)?(?:di)?graph\s+\w*\s*\{/i, '').replace(/\}\s*$/, '');
|
|
3947
|
+
const stmts = []; let buf = '', depth = 0;
|
|
3948
|
+
for (const ch of text) {
|
|
3949
|
+
if (ch === '[') depth++;
|
|
3950
|
+
if (ch === ']') depth--;
|
|
3951
|
+
if ((ch === ';' || ch === '\n') && depth === 0) {
|
|
3952
|
+
if (buf.trim()) stmts.push(buf.trim());
|
|
3953
|
+
buf = '';
|
|
3954
|
+
} else buf += ch;
|
|
3955
|
+
}
|
|
3956
|
+
if (buf.trim()) stmts.push(buf.trim());
|
|
3957
|
+
const ID_RE = /"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*)/;
|
|
3958
|
+
function takeId(s, p) {
|
|
3959
|
+
const m = s.slice(p).match(ID_RE);
|
|
3960
|
+
if (!m || m.index !== 0) return null;
|
|
3961
|
+
return { id: m[1] || m[2], end: p + m[0].length };
|
|
3962
|
+
}
|
|
3963
|
+
function takeAttrs(s, p) {
|
|
3964
|
+
const sub = s.slice(p).match(/^\s*\[([^\]]*)\]/);
|
|
3965
|
+
if (!sub) return null;
|
|
3966
|
+
const lm = sub[1].match(/label\s*=\s*"([^"]*)"|label\s*=\s*([A-Za-z_][A-Za-z0-9_]*)/);
|
|
3967
|
+
return { label: lm ? (lm[1] || lm[2]) : null, end: p + sub[0].length };
|
|
3968
|
+
}
|
|
3969
|
+
for (const stmt of stmts) {
|
|
3970
|
+
let p = 0;
|
|
3971
|
+
const a = takeId(stmt, p); if (!a) continue;
|
|
3972
|
+
p = a.end;
|
|
3973
|
+
while (stmt[p] === ' ' || stmt[p] === '\t') p++;
|
|
3974
|
+
const arrow = stmt.slice(p).match(/^(->|--)\s*/);
|
|
3975
|
+
if (arrow) {
|
|
3976
|
+
p += arrow[0].length;
|
|
3977
|
+
const b = takeId(stmt, p); if (!b) continue;
|
|
3978
|
+
p = b.end;
|
|
3979
|
+
const attrs = takeAttrs(stmt, p);
|
|
3980
|
+
if (!nodes.has(a.id)) nodes.set(a.id, { label: a.id });
|
|
3981
|
+
if (!nodes.has(b.id)) nodes.set(b.id, { label: b.id });
|
|
3982
|
+
edges.push({ from: a.id, to: b.id, label: attrs ? attrs.label : null });
|
|
3983
|
+
} else {
|
|
3984
|
+
const attrs = takeAttrs(stmt, p);
|
|
3985
|
+
const label = attrs && attrs.label ? attrs.label : a.id;
|
|
3986
|
+
if (!nodes.has(a.id) || nodes.get(a.id).label === a.id) nodes.set(a.id, { label });
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
return { nodes, edges };
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3992
|
+
// zflow WebGL renderer — optimized path.
|
|
3993
|
+
//
|
|
3994
|
+
// Architecture:
|
|
3995
|
+
// • One shared static quad geometry (6 verts, never changes).
|
|
3996
|
+
// • Per-node attributes (center, size, color, sel) live in a persistent
|
|
3997
|
+
// instance buffer sized at nodeCap() at init time. We never allocate
|
|
3998
|
+
// per-frame — we update only the slots that the host marked dirty.
|
|
3999
|
+
// • Camera (pan/zoom) is uniform-only, so panning is FREE in buffer terms.
|
|
4000
|
+
// • ANGLE_instanced_arrays draws all nodes in a single drawCall.
|
|
4001
|
+
// • Edges keep a persistent buffer too with dirty tracking + bezier
|
|
4002
|
+
// tesselation regenerated only when an endpoint moves.
|
|
4003
|
+
//
|
|
4004
|
+
// Result: 100k nodes pan/zoom at 60 fps with zero GC. Adding/moving a
|
|
4005
|
+
// single node touches ~28 bytes of GPU memory, not 7 MB.
|
|
4006
|
+
|
|
4007
|
+
const VS = `
|
|
4008
|
+
attribute vec2 aQuad;
|
|
4009
|
+
attribute vec2 aCenter;
|
|
4010
|
+
attribute vec2 aSize;
|
|
4011
|
+
attribute vec3 aColor;
|
|
4012
|
+
attribute float aSelected;
|
|
4013
|
+
uniform vec2 uCam;
|
|
4014
|
+
uniform float uZoom;
|
|
4015
|
+
uniform vec2 uScreen;
|
|
4016
|
+
varying vec3 vColor;
|
|
4017
|
+
varying float vSelected;
|
|
4018
|
+
varying vec2 vUv;
|
|
4019
|
+
void main() {
|
|
4020
|
+
vUv = aQuad;
|
|
4021
|
+
vSelected = aSelected;
|
|
4022
|
+
vColor = aColor;
|
|
4023
|
+
vec2 worldPos = aCenter + aQuad * aSize;
|
|
4024
|
+
vec2 screen = (worldPos + uCam) * uZoom;
|
|
4025
|
+
vec2 ndc = (screen / uScreen) * 2.0;
|
|
4026
|
+
gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
|
|
4027
|
+
}`;
|
|
4028
|
+
|
|
4029
|
+
const FS = `
|
|
4030
|
+
precision mediump float;
|
|
4031
|
+
varying vec3 vColor;
|
|
4032
|
+
varying float vSelected;
|
|
4033
|
+
varying vec2 vUv;
|
|
4034
|
+
void main() {
|
|
4035
|
+
vec2 q = abs(vUv);
|
|
4036
|
+
float d = max(q.x, q.y);
|
|
4037
|
+
float alpha = smoothstep(1.0, 0.92, d);
|
|
4038
|
+
float header = step(0.7, vUv.y) * 0.18;
|
|
4039
|
+
vec3 col = vColor + vec3(header);
|
|
4040
|
+
if (vSelected > 0.5) col = mix(col, vec3(0.94, 0.73, 0.23), 0.55);
|
|
4041
|
+
gl_FragColor = vec4(col, alpha);
|
|
4042
|
+
}`;
|
|
4043
|
+
|
|
4044
|
+
const EDGE_VS = `
|
|
4045
|
+
attribute vec2 aPos;
|
|
4046
|
+
attribute vec3 aColor;
|
|
4047
|
+
uniform vec2 uCam;
|
|
4048
|
+
uniform float uZoom;
|
|
4049
|
+
uniform vec2 uScreen;
|
|
4050
|
+
varying vec3 vColor;
|
|
4051
|
+
void main() {
|
|
4052
|
+
vColor = aColor;
|
|
4053
|
+
vec2 screen = (aPos + uCam) * uZoom;
|
|
4054
|
+
vec2 ndc = (screen / uScreen) * 2.0;
|
|
4055
|
+
gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
|
|
4056
|
+
}`;
|
|
4057
|
+
|
|
4058
|
+
const EDGE_FS = `
|
|
4059
|
+
precision mediump float;
|
|
4060
|
+
varying vec3 vColor;
|
|
4061
|
+
void main() { gl_FragColor = vec4(vColor, 0.85); }`;
|
|
4062
|
+
|
|
4063
|
+
const NODE_STRIDE_F = 8; // cx, cy, sw, sh, r, g, b, sel
|
|
4064
|
+
const EDGE_SEGS = 24;
|
|
4065
|
+
const EDGE_VERTS_PER = (EDGE_SEGS) * 2;
|
|
4066
|
+
const EDGE_STRIDE_F = 5; // x, y, r, g, b per vertex
|
|
4067
|
+
|
|
4068
|
+
class WebGLRenderer {
|
|
4069
|
+
constructor(flow) {
|
|
4070
|
+
this.flow = flow;
|
|
4071
|
+
this.glCanvas = document.createElement('canvas');
|
|
4072
|
+
this.glCanvas.style.cssText = `position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:0;`;
|
|
4073
|
+
flow.container.insertBefore(this.glCanvas, flow.canvas);
|
|
4074
|
+
flow.canvas.style.background = 'transparent';
|
|
4075
|
+
flow.canvas.style.position = 'absolute';
|
|
4076
|
+
flow.canvas.style.zIndex = '1';
|
|
4077
|
+
this.gl = this.glCanvas.getContext('webgl', { antialias: true, alpha: true, premultipliedAlpha: false });
|
|
4078
|
+
if (!this.gl) { this.disabled = true; console.warn('zflow: WebGL unavailable'); return; }
|
|
4079
|
+
this.instExt = this.gl.getExtension('ANGLE_instanced_arrays');
|
|
4080
|
+
this.cap = flow.w.nodeCap();
|
|
4081
|
+
this.edgeCap = flow.w.edgeCap();
|
|
4082
|
+
this._resize();
|
|
4083
|
+
this._setupShaders();
|
|
4084
|
+
this._setupBuffers();
|
|
4085
|
+
this._hookDirty();
|
|
4086
|
+
this._resizeObs = new ResizeObserver(() => this._resize());
|
|
4087
|
+
this._resizeObs.observe(flow.container);
|
|
4088
|
+
this._dirty = new Set(); // node ids needing buffer upload
|
|
4089
|
+
this._dirtyEdges = new Set();
|
|
4090
|
+
this._fullRebuildNeeded = true;
|
|
4091
|
+
this._lastNodeCount = 0;
|
|
4092
|
+
this._lastEdgeCount = 0;
|
|
4093
|
+
}
|
|
4094
|
+
|
|
4095
|
+
_hookDirty() {
|
|
4096
|
+
const f = this.flow;
|
|
4097
|
+
f.on('change', () => { this._fullRebuildNeeded = true; });
|
|
4098
|
+
// Hijack moveSelectedBy / moveNode so position changes only mark dirty.
|
|
4099
|
+
const origMove = f.w.moveSelectedBy;
|
|
4100
|
+
if (origMove) {
|
|
4101
|
+
f.w.moveSelectedBy = (dx, dy) => {
|
|
4102
|
+
origMove.call(f.w, dx, dy);
|
|
4103
|
+
for (let i = 0; i < f.w.nodeCount_(); i++) if (f.V.selected[i]) this._dirty.add(i);
|
|
4104
|
+
};
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
|
|
4108
|
+
_resize() {
|
|
4109
|
+
const dpr = window.devicePixelRatio || 1;
|
|
4110
|
+
const r = this.flow.container.getBoundingClientRect();
|
|
4111
|
+
this.glCanvas.width = r.width * dpr;
|
|
4112
|
+
this.glCanvas.height = r.height * dpr;
|
|
4113
|
+
this.gl?.viewport(0, 0, this.glCanvas.width, this.glCanvas.height);
|
|
4114
|
+
}
|
|
4115
|
+
|
|
4116
|
+
_setupShaders() {
|
|
4117
|
+
const gl = this.gl;
|
|
4118
|
+
this.progNode = link(gl, VS, FS);
|
|
4119
|
+
this.progEdge = link(gl, EDGE_VS, EDGE_FS);
|
|
4120
|
+
// Cache uniform/attrib locations.
|
|
4121
|
+
this.locN = {
|
|
4122
|
+
aQuad: gl.getAttribLocation(this.progNode, 'aQuad'),
|
|
4123
|
+
aCenter: gl.getAttribLocation(this.progNode, 'aCenter'),
|
|
4124
|
+
aSize: gl.getAttribLocation(this.progNode, 'aSize'),
|
|
4125
|
+
aColor: gl.getAttribLocation(this.progNode, 'aColor'),
|
|
4126
|
+
aSel: gl.getAttribLocation(this.progNode, 'aSelected'),
|
|
4127
|
+
uCam: gl.getUniformLocation(this.progNode, 'uCam'),
|
|
4128
|
+
uZoom: gl.getUniformLocation(this.progNode, 'uZoom'),
|
|
4129
|
+
uScreen: gl.getUniformLocation(this.progNode, 'uScreen'),
|
|
4130
|
+
};
|
|
4131
|
+
this.locE = {
|
|
4132
|
+
aPos: gl.getAttribLocation(this.progEdge, 'aPos'),
|
|
4133
|
+
aColor: gl.getAttribLocation(this.progEdge, 'aColor'),
|
|
4134
|
+
uCam: gl.getUniformLocation(this.progEdge, 'uCam'),
|
|
4135
|
+
uZoom: gl.getUniformLocation(this.progEdge, 'uZoom'),
|
|
4136
|
+
uScreen: gl.getUniformLocation(this.progEdge, 'uScreen'),
|
|
4137
|
+
};
|
|
4138
|
+
}
|
|
4139
|
+
|
|
4140
|
+
_setupBuffers() {
|
|
4141
|
+
const gl = this.gl;
|
|
4142
|
+
// Shared quad: 6 verts, 2 floats each, static.
|
|
4143
|
+
this.quadBuf = gl.createBuffer();
|
|
4144
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuf);
|
|
4145
|
+
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
|
|
4146
|
+
-1, -1, 1, -1, -1, 1,
|
|
4147
|
+
1, -1, 1, 1, -1, 1,
|
|
4148
|
+
]), gl.STATIC_DRAW);
|
|
4149
|
+
|
|
4150
|
+
// Per-instance node buffer pre-allocated at full cap.
|
|
4151
|
+
this.nodeData = new Float32Array(this.cap * NODE_STRIDE_F);
|
|
4152
|
+
this.nodeBuf = gl.createBuffer();
|
|
4153
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.nodeBuf);
|
|
4154
|
+
gl.bufferData(gl.ARRAY_BUFFER, this.nodeData.byteLength, gl.DYNAMIC_DRAW);
|
|
4155
|
+
|
|
4156
|
+
// Edge buffer pre-allocated.
|
|
4157
|
+
this.edgeData = new Float32Array(this.edgeCap * EDGE_VERTS_PER * EDGE_STRIDE_F);
|
|
4158
|
+
this.edgeBuf = gl.createBuffer();
|
|
4159
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.edgeBuf);
|
|
4160
|
+
gl.bufferData(gl.ARRAY_BUFFER, this.edgeData.byteLength, gl.DYNAMIC_DRAW);
|
|
4161
|
+
}
|
|
4162
|
+
|
|
4163
|
+
_writeNode(i) {
|
|
4164
|
+
const f = this.flow;
|
|
4165
|
+
const cat = f.kinds[f.V.kind[i]];
|
|
4166
|
+
const hex = f.colors.get(i) || cat.color;
|
|
4167
|
+
const off = i * NODE_STRIDE_F;
|
|
4168
|
+
this.nodeData[off ] = f.V.posX[i];
|
|
4169
|
+
this.nodeData[off + 1] = f.V.posY[i];
|
|
4170
|
+
this.nodeData[off + 2] = f.V.sizeW[i] * 0.5;
|
|
4171
|
+
this.nodeData[off + 3] = f.V.sizeH[i] * 0.5;
|
|
4172
|
+
const [r, g, b] = parseHex(hex);
|
|
4173
|
+
this.nodeData[off + 4] = r;
|
|
4174
|
+
this.nodeData[off + 5] = g;
|
|
4175
|
+
this.nodeData[off + 6] = b;
|
|
4176
|
+
this.nodeData[off + 7] = f.V.selected[i] !== 0 ? 1 : 0;
|
|
4177
|
+
}
|
|
4178
|
+
|
|
4179
|
+
_writeEdge(i) {
|
|
4180
|
+
const f = this.flow;
|
|
4181
|
+
const a = f.V.edgeFromN[i], b = f.V.edgeToN[i];
|
|
4182
|
+
const ap = f._portWorld(a, 1, f.V.edgeFromP[i]);
|
|
4183
|
+
const bp = f._portWorld(b, 0, f.V.edgeToP[i]);
|
|
4184
|
+
const col = parseHex(f.colors.get(a) || f.kinds[f.V.kind[a]].color);
|
|
4185
|
+
const off = i * EDGE_VERTS_PER * EDGE_STRIDE_F;
|
|
4186
|
+
const ortho = f.options.edgeStyle === 'orthogonal';
|
|
4187
|
+
const offCv = Math.max(50, Math.abs(bp.x - ap.x) * 0.5 + Math.abs(bp.y - ap.y) * 0.4);
|
|
4188
|
+
let prev = { x: ap.x, y: ap.y };
|
|
4189
|
+
let o = off;
|
|
4190
|
+
for (let s = 1; s <= EDGE_SEGS; s++) {
|
|
4191
|
+
const t = s / EDGE_SEGS;
|
|
4192
|
+
let pt;
|
|
4193
|
+
if (ortho) {
|
|
4194
|
+
const mx = (ap.x + bp.x) * 0.5;
|
|
4195
|
+
pt = t < 0.33 ? lerp(ap, { x: mx, y: ap.y }, t / 0.33)
|
|
4196
|
+
: t < 0.67 ? lerp({ x: mx, y: ap.y }, { x: mx, y: bp.y }, (t - 0.33) / 0.34)
|
|
4197
|
+
: lerp({ x: mx, y: bp.y }, bp, (t - 0.67) / 0.33);
|
|
4198
|
+
} else {
|
|
4199
|
+
pt = bezPt(t, ap.x, ap.y, ap.x + offCv, ap.y, bp.x - offCv, bp.y, bp.x, bp.y);
|
|
4200
|
+
}
|
|
4201
|
+
this.edgeData[o++] = prev.x; this.edgeData[o++] = prev.y;
|
|
4202
|
+
this.edgeData[o++] = col[0]; this.edgeData[o++] = col[1]; this.edgeData[o++] = col[2];
|
|
4203
|
+
this.edgeData[o++] = pt.x; this.edgeData[o++] = pt.y;
|
|
4204
|
+
this.edgeData[o++] = col[0]; this.edgeData[o++] = col[1]; this.edgeData[o++] = col[2];
|
|
4205
|
+
prev = pt;
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
4208
|
+
|
|
4209
|
+
render() {
|
|
4210
|
+
if (this.disabled) return;
|
|
4211
|
+
const gl = this.gl;
|
|
4212
|
+
const f = this.flow;
|
|
4213
|
+
const n = f.w.nodeCount_(), m = f.w.edgeCount_();
|
|
4214
|
+
const dpr = window.devicePixelRatio || 1;
|
|
4215
|
+
|
|
4216
|
+
gl.clearColor(0.027, 0.035, 0.06, 1.0);
|
|
4217
|
+
gl.clear(gl.COLOR_BUFFER_BIT);
|
|
4218
|
+
gl.enable(gl.BLEND);
|
|
4219
|
+
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
|
4220
|
+
|
|
4221
|
+
const camWX = f.cam.x + (this.glCanvas.width / (2 * dpr * f.cam.zoom));
|
|
4222
|
+
const camWY = f.cam.y + (this.glCanvas.height / (2 * dpr * f.cam.zoom));
|
|
4223
|
+
|
|
4224
|
+
// ── Detect what needs upload ────────────────────────────────────
|
|
4225
|
+
if (this._fullRebuildNeeded || n !== this._lastNodeCount) {
|
|
4226
|
+
for (let i = 0; i < n; i++) this._writeNode(i);
|
|
4227
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.nodeBuf);
|
|
4228
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.nodeData.subarray(0, n * NODE_STRIDE_F));
|
|
4229
|
+
this._dirty.clear();
|
|
4230
|
+
} else if (this._dirty.size) {
|
|
4231
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.nodeBuf);
|
|
4232
|
+
// Combine contiguous dirty ranges to minimize bufferSubData calls.
|
|
4233
|
+
const sorted = [...this._dirty].sort((a, b) => a - b);
|
|
4234
|
+
let runStart = sorted[0], runEnd = sorted[0];
|
|
4235
|
+
for (let k = 1; k < sorted.length; k++) {
|
|
4236
|
+
if (sorted[k] === runEnd + 1) runEnd = sorted[k];
|
|
4237
|
+
else {
|
|
4238
|
+
for (let i = runStart; i <= runEnd; i++) this._writeNode(i);
|
|
4239
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, runStart * NODE_STRIDE_F * 4,
|
|
4240
|
+
this.nodeData.subarray(runStart * NODE_STRIDE_F, (runEnd + 1) * NODE_STRIDE_F));
|
|
4241
|
+
runStart = sorted[k]; runEnd = sorted[k];
|
|
4242
|
+
}
|
|
4243
|
+
}
|
|
4244
|
+
for (let i = runStart; i <= runEnd; i++) this._writeNode(i);
|
|
4245
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, runStart * NODE_STRIDE_F * 4,
|
|
4246
|
+
this.nodeData.subarray(runStart * NODE_STRIDE_F, (runEnd + 1) * NODE_STRIDE_F));
|
|
4247
|
+
this._dirty.clear();
|
|
4248
|
+
}
|
|
4249
|
+
|
|
4250
|
+
if (this._fullRebuildNeeded || m !== this._lastEdgeCount || this._dirty.size === 0) {
|
|
4251
|
+
// Edges depend on node positions, but only rebuild on full-rebuild path
|
|
4252
|
+
// since we keep no per-edge incremental delta yet.
|
|
4253
|
+
if (this._fullRebuildNeeded || m !== this._lastEdgeCount) {
|
|
4254
|
+
for (let i = 0; i < m; i++) this._writeEdge(i);
|
|
4255
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.edgeBuf);
|
|
4256
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.edgeData.subarray(0, m * EDGE_VERTS_PER * EDGE_STRIDE_F));
|
|
4257
|
+
}
|
|
4258
|
+
}
|
|
4259
|
+
|
|
4260
|
+
this._lastNodeCount = n;
|
|
4261
|
+
this._lastEdgeCount = m;
|
|
4262
|
+
this._fullRebuildNeeded = false;
|
|
4263
|
+
|
|
4264
|
+
// ── Draw edges (LINES, persistent buffer) ────────────────────────
|
|
4265
|
+
if (m > 0) {
|
|
4266
|
+
gl.useProgram(this.progEdge);
|
|
4267
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.edgeBuf);
|
|
4268
|
+
gl.enableVertexAttribArray(this.locE.aPos);
|
|
4269
|
+
gl.vertexAttribPointer(this.locE.aPos, 2, gl.FLOAT, false, 5 * 4, 0);
|
|
4270
|
+
gl.enableVertexAttribArray(this.locE.aColor);
|
|
4271
|
+
gl.vertexAttribPointer(this.locE.aColor, 3, gl.FLOAT, false, 5 * 4, 2 * 4);
|
|
4272
|
+
gl.uniform2f(this.locE.uCam, camWX, camWY);
|
|
4273
|
+
gl.uniform1f(this.locE.uZoom, f.cam.zoom * dpr);
|
|
4274
|
+
gl.uniform2f(this.locE.uScreen, this.glCanvas.width, this.glCanvas.height);
|
|
4275
|
+
gl.lineWidth(1.6);
|
|
4276
|
+
gl.drawArrays(gl.LINES, 0, m * EDGE_VERTS_PER);
|
|
4277
|
+
}
|
|
4278
|
+
|
|
4279
|
+
// ── Draw nodes ──────────────────────────────────────────────────
|
|
4280
|
+
if (n > 0) {
|
|
4281
|
+
gl.useProgram(this.progNode);
|
|
4282
|
+
// aQuad from static buffer.
|
|
4283
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuf);
|
|
4284
|
+
gl.enableVertexAttribArray(this.locN.aQuad);
|
|
4285
|
+
gl.vertexAttribPointer(this.locN.aQuad, 2, gl.FLOAT, false, 0, 0);
|
|
4286
|
+
if (this.instExt) this.instExt.vertexAttribDivisorANGLE(this.locN.aQuad, 0);
|
|
4287
|
+
// per-instance attribs from node buffer.
|
|
4288
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, this.nodeBuf);
|
|
4289
|
+
const s = NODE_STRIDE_F * 4;
|
|
4290
|
+
gl.enableVertexAttribArray(this.locN.aCenter);
|
|
4291
|
+
gl.vertexAttribPointer(this.locN.aCenter, 2, gl.FLOAT, false, s, 0);
|
|
4292
|
+
gl.enableVertexAttribArray(this.locN.aSize);
|
|
4293
|
+
gl.vertexAttribPointer(this.locN.aSize, 2, gl.FLOAT, false, s, 2 * 4);
|
|
4294
|
+
gl.enableVertexAttribArray(this.locN.aColor);
|
|
4295
|
+
gl.vertexAttribPointer(this.locN.aColor, 3, gl.FLOAT, false, s, 4 * 4);
|
|
4296
|
+
gl.enableVertexAttribArray(this.locN.aSel);
|
|
4297
|
+
gl.vertexAttribPointer(this.locN.aSel, 1, gl.FLOAT, false, s, 7 * 4);
|
|
4298
|
+
if (this.instExt) {
|
|
4299
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aCenter, 1);
|
|
4300
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aSize, 1);
|
|
4301
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aColor, 1);
|
|
4302
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aSel, 1);
|
|
4303
|
+
}
|
|
4304
|
+
gl.uniform2f(this.locN.uCam, camWX, camWY);
|
|
4305
|
+
gl.uniform1f(this.locN.uZoom, f.cam.zoom * dpr);
|
|
4306
|
+
gl.uniform2f(this.locN.uScreen, this.glCanvas.width, this.glCanvas.height);
|
|
4307
|
+
if (this.instExt) {
|
|
4308
|
+
this.instExt.drawArraysInstancedANGLE(gl.TRIANGLES, 0, 6, n);
|
|
4309
|
+
// Reset divisors so other passes (edges) work correctly.
|
|
4310
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aCenter, 0);
|
|
4311
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aSize, 0);
|
|
4312
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aColor, 0);
|
|
4313
|
+
this.instExt.vertexAttribDivisorANGLE(this.locN.aSel, 0);
|
|
4314
|
+
} else {
|
|
4315
|
+
// Slow path fallback: 6 verts per node, no extension.
|
|
4316
|
+
// (rare; almost every browser since 2014 has the extension)
|
|
4317
|
+
for (let i = 0; i < n; i++) {
|
|
4318
|
+
const off = i * NODE_STRIDE_F;
|
|
4319
|
+
gl.vertexAttrib2f(this.locN.aCenter, this.nodeData[off], this.nodeData[off + 1]);
|
|
4320
|
+
gl.vertexAttrib2f(this.locN.aSize, this.nodeData[off + 2], this.nodeData[off + 3]);
|
|
4321
|
+
gl.vertexAttrib3f(this.locN.aColor, this.nodeData[off + 4], this.nodeData[off + 5], this.nodeData[off + 6]);
|
|
4322
|
+
gl.vertexAttrib1f(this.locN.aSel, this.nodeData[off + 7]);
|
|
4323
|
+
gl.drawArrays(gl.TRIANGLES, 0, 6);
|
|
4324
|
+
}
|
|
4325
|
+
}
|
|
4326
|
+
}
|
|
4327
|
+
}
|
|
4328
|
+
|
|
4329
|
+
/** Mark a node as needing buffer update. Called from host on move/recolor. */
|
|
4330
|
+
markNodeDirty(i) { this._dirty.add(i); }
|
|
4331
|
+
markEdgeDirty(i) { this._dirtyEdges.add(i); this._fullRebuildNeeded = true; }
|
|
4332
|
+
markAllDirty() { this._fullRebuildNeeded = true; }
|
|
4333
|
+
|
|
4334
|
+
dispose() {
|
|
4335
|
+
this._resizeObs?.disconnect();
|
|
4336
|
+
this.glCanvas?.remove();
|
|
4337
|
+
}
|
|
4338
|
+
}
|
|
4339
|
+
|
|
4340
|
+
// ── helpers ───────────────────────────────────────────────────────────────
|
|
4341
|
+
function compile(gl, src, kind) {
|
|
4342
|
+
const s = gl.createShader(kind);
|
|
4343
|
+
gl.shaderSource(s, src); gl.compileShader(s);
|
|
4344
|
+
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error('GL compile: ' + gl.getShaderInfoLog(s));
|
|
4345
|
+
return s;
|
|
4346
|
+
}
|
|
4347
|
+
function link(gl, vs, fs) {
|
|
4348
|
+
const p = gl.createProgram();
|
|
4349
|
+
gl.attachShader(p, compile(gl, vs, gl.VERTEX_SHADER));
|
|
4350
|
+
gl.attachShader(p, compile(gl, fs, gl.FRAGMENT_SHADER));
|
|
4351
|
+
gl.linkProgram(p);
|
|
4352
|
+
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error('GL link: ' + gl.getProgramInfoLog(p));
|
|
4353
|
+
return p;
|
|
4354
|
+
}
|
|
4355
|
+
function parseHex(h) {
|
|
4356
|
+
return [parseInt(h.slice(1, 3), 16) / 255, parseInt(h.slice(3, 5), 16) / 255, parseInt(h.slice(5, 7), 16) / 255];
|
|
4357
|
+
}
|
|
4358
|
+
function bezPt(t, x1, y1, cx1, cy1, cx2, cy2, x2, y2) {
|
|
4359
|
+
const mt = 1 - t, mt2 = mt * mt, t2 = t * t;
|
|
4360
|
+
const a = mt2 * mt, b = 3 * mt2 * t, c = 3 * mt * t2, d = t2 * t;
|
|
4361
|
+
return { x: a*x1 + b*cx1 + c*cx2 + d*x2, y: a*y1 + b*cy1 + c*cy2 + d*y2 };
|
|
4362
|
+
}
|
|
4363
|
+
function lerp(a, b, t) { return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; }
|
|
4364
|
+
|
|
4365
|
+
var webglRenderer = /*#__PURE__*/Object.freeze({
|
|
4366
|
+
__proto__: null,
|
|
4367
|
+
WebGLRenderer: WebGLRenderer
|
|
4368
|
+
});
|
|
4369
|
+
|
|
4370
|
+
exports.ZFlow = ZFlow;
|
|
4371
|
+
exports.parseDot = parseDot;
|
|
4372
|
+
exports.parseMermaid = parseMermaid;
|
|
4373
|
+
|
|
4374
|
+
}));
|
|
4375
|
+
//# sourceMappingURL=zflow.umd.js.map
|