@fragiola/flow-vue 0.0.0-stage → 0.0.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/dist/index.js ADDED
@@ -0,0 +1,2184 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { C as usePartNodeId, S as useFlowContext, _ as NodeKey, a as onClient, b as typedModel, d as useFlowValue, f as shallowEqual, h as FlowKey, i as elementRef, l as sameValue, m as EdgeLabelLayerKey, n as definePrimitive, o as px, p as EdgeKey, r as numberProp, s as renderElement, t as NUMBER_PROP, u as useDrawnLayers, v as eraseModel, x as useEdgeId, y as typedEngine } from "./primitive-h9jTIEeT.js";
3
+ import { ENGINE_EVENT_CALLBACKS, createFlowEngine, createFlowModel, edgesLayerAttributes, flag, partAttributes, sameFlowValue, staticGeometry, watchKeyPress } from "@fragiola/flow";
4
+ import { ErrorCodes, Teleport, computed, defineComponent, getCurrentInstance, h, handleError, inject, markRaw, nextTick, onBeforeUnmount, onMounted, onScopeDispose, onUnmounted, provide, queuePostFlushCb, readonly, shallowRef, toRaw, toValue, useId, watch, watchEffect } from "vue";
5
+ export * from "@fragiola/flow";
6
+ // src/composables/create-flow-ref.ts
7
+ /** the reactive value behind each flow ref, which only `Flow.Root` sets */
8
+ const values = /* @__PURE__ */ new WeakMap();
9
+ /**
10
+ * Creates a flow ref anywhere (a module, a test, `setup`, where `useFlowRef` says the same).
11
+ *
12
+ * ```ts
13
+ * const flow = createFlowRef<Types, typeof features>();
14
+ * // <Flow.Root :flow-ref="flow" :features="features" :default-nodes="nodes">…</Flow.Root>
15
+ * flow.value?.engine.run("fit-view");
16
+ * ```
17
+ */
18
+ function createFlowRef() {
19
+ const value = shallowRef(null);
20
+ const flow = markRaw({ get value() {
21
+ return value.value;
22
+ } });
23
+ values.set(flow, value);
24
+ return flow;
25
+ }
26
+ /** @internal what `Flow.Root` calls: attaches (or, with `null`, detaches) its model and engine */
27
+ function setFlowRef(flow, next) {
28
+ const current = values.get(toRaw(flow));
29
+ if (!current) throw new TypeError("Flow.Root: `flow-ref` takes a flow ref from useFlowRef or createFlowRef");
30
+ current.value = next;
31
+ }
32
+ // src/composables/use-connection.ts
33
+ /**
34
+ * The connection being drawn from a handle (`connection()`), or null, as a computed ref that
35
+ * changes with it: where it starts and ends, the handle it would end at and whether the drop would
36
+ * be accepted (`status`).
37
+ */
38
+ function useConnection() {
39
+ const context = useFlowContext("useConnection");
40
+ return useFlowValue(context, () => context.engine.value?.get("connection") ?? null, (a, b) => a === b || a !== null && b !== null && a.path === b.path && a.status === b.status && a.to === b.to && a.from === b.from && a.toSide === b.toSide);
41
+ }
42
+ // src/composables/use-edge.ts
43
+ /** Two edge paths that draw the same (`edge-path-by` builds a new one at every read). */
44
+ function sameEdgePath(a, b) {
45
+ if (a === b) return true;
46
+ if (!a || !b) return false;
47
+ return a.path === b.path && a.sourceSide === b.sourceSide && a.targetSide === b.targetSide && a.label.x === b.label.x && a.label.y === b.label.y && a.source.x === b.source.x && a.source.y === b.source.y && a.target.x === b.target.x && a.target.y === b.target.y;
48
+ }
49
+ /** An edge's state and the props of its element, for an edge drawn by hand (`Flow.Edge` uses it). */
50
+ function useEdge(edge) {
51
+ const context = useFlowContext("useEdge");
52
+ const current = () => toValue(edge);
53
+ const view = useFlowValue(context, () => {
54
+ const edgeId = current().id;
55
+ const engine = context.engine.value;
56
+ return engine ? {
57
+ attributes: engine.adapter.attributes("edge", { edgeId }),
58
+ path: engine.get("edge-path-by", { edgeId }),
59
+ reconnecting: engine.is("edge-reconnecting", { edgeId }),
60
+ focusable: engine.is("edge-focusable", { edgeId })
61
+ } : {
62
+ attributes: edgeAttributes(context, "edge", edgeId),
63
+ path: staticEdgePath(context, edgeId),
64
+ reconnecting: false,
65
+ focusable: false
66
+ };
67
+ }, (a, b) => a.reconnecting === b.reconnecting && a.focusable === b.focusable && sameEdgePath(a.path, b.path) && shallowEqual(a.attributes, b.attributes), "entity", () => ({
68
+ kind: "edge",
69
+ id: current().id
70
+ }));
71
+ return {
72
+ state: computed(() => {
73
+ const { attributes, path, reconnecting, focusable } = view.value;
74
+ const value = current();
75
+ return {
76
+ edgeId: value.id,
77
+ edge: value,
78
+ path,
79
+ selected: attributes["data-selected"] !== void 0,
80
+ reconnecting,
81
+ focusable,
82
+ attributes
83
+ };
84
+ }),
85
+ props: computed(() => ({
86
+ ...view.value.attributes,
87
+ tabindex: view.value.focusable ? 0 : void 0
88
+ }))
89
+ };
90
+ }
91
+ /** @internal an edge's path, triggering its readers when it changes (`Flow.EdgePath`, …) */
92
+ function useEdgePath(context, edgeId) {
93
+ return useFlowValue(context, () => {
94
+ const engine = context.engine.value;
95
+ return engine ? engine.get("edge-path-by", { edgeId: edgeId() }) : staticEdgePath(context, edgeId());
96
+ }, sameEdgePath, "entity", () => ({
97
+ kind: "edge",
98
+ id: edgeId()
99
+ }));
100
+ }
101
+ /** An edge's path before the engine exists: the static geometry's (absent until both sizes are known). */
102
+ function staticEdgePath(context, edgeId) {
103
+ return context.geometry.value?.edgePaths[edgeId];
104
+ }
105
+ /**
106
+ * @internal the attributes of an edge's part (`edge`, `edge-path`, `edge-label`): the engine's, or
107
+ * before it exists the same from the model (its id, `data-selected`, `data-animated`)
108
+ */
109
+ function edgeAttributes(context, part, edgeId) {
110
+ const engine = context.engine.value;
111
+ if (engine) return engine.adapter.attributes(part, { edgeId });
112
+ const edge = context.model.get("edge-by", { id: edgeId });
113
+ return {
114
+ ...partAttributes(part, edgeId),
115
+ "data-selected": flag(edge?.selected === true),
116
+ "data-animated": flag(edge?.animated === true)
117
+ };
118
+ }
119
+ // src/composables/use-edges.ts
120
+ /**
121
+ * Every edge of the enclosing `Flow.Root`, in drawing order, as a computed ref that changes on
122
+ * every change of one (the model's frozen list, never made reactive).
123
+ */
124
+ function useEdges() {
125
+ const context = useFlowContext("useEdges");
126
+ return useFlowValue(context, () => context.model.get("all-edges"), Object.is);
127
+ }
128
+ // src/composables/use-flow.ts
129
+ /**
130
+ * The model and the engine of the enclosing `Flow.Root`. Pass the registry and the features as the
131
+ * type arguments (`useFlow<Types, typeof features>()`): a child cannot infer them through
132
+ * injection. Call it in `setup`: another model remounts the root, so the values never change for
133
+ * a component.
134
+ */
135
+ function useFlow() {
136
+ const context = useFlowContext("useFlow");
137
+ return {
138
+ model: typedModel(context.model),
139
+ engine: typedEngine(context.publicEngine)
140
+ };
141
+ }
142
+ // src/composables/use-flow-ref.ts
143
+ /**
144
+ * A flow ref for this component: pass it as a `Flow.Root`'s `flow-ref`, and read `flow.value` in
145
+ * the template (a toolbar next to the flow, which re-renders when the root mounts) or in handlers.
146
+ * A template does not unwrap a flow ref: it reads `flow.value`, as a script does.
147
+ *
148
+ * ```vue
149
+ * <script setup lang="ts">
150
+ * const flow = useFlowRef<Types>();
151
+ * <\/script>
152
+ * <template>
153
+ * <button type="button" :disabled="!flow.value" @click="flow.value?.engine.run('fit-view')">
154
+ * Fit
155
+ * </button>
156
+ * <Flow.Root :flow-ref="flow" :default-nodes="nodes">…</Flow.Root>
157
+ * </template>
158
+ * ```
159
+ */
160
+ function useFlowRef() {
161
+ return createFlowRef();
162
+ }
163
+ // src/composables/use-flow-store.ts
164
+ /**
165
+ * A value selected from the model and the engine of the enclosing `Flow.Root`, as a computed ref
166
+ * that triggers its readers only when it changes (`equal`, default `Object.is`): `selector` runs
167
+ * again on every change of the model and every view change of the engine (a measurement, the
168
+ * viewport, a gesture), and when a reactive value it reads changes. Pass the registry and the
169
+ * features as the type arguments after the selected value's (`useFlowStore<number, Types, typeof
170
+ * features>(…)`). Keep a selector that builds an object or an array with an `equal` that compares
171
+ * it (`sameFlowValue`), or it changes on every change.
172
+ */
173
+ function useFlowStore(selector, equal = Object.is) {
174
+ const context = useFlowContext("useFlowStore");
175
+ const flow = {
176
+ model: typedModel(context.model),
177
+ engine: typedEngine(context.publicEngine)
178
+ };
179
+ return useFlowValue(context, () => selector(flow), equal);
180
+ }
181
+ // src/composables/use-handle.ts
182
+ /** A registration's identity: a change registers the handle again. */
183
+ function registrationKey(registration) {
184
+ return JSON.stringify([
185
+ registration.nodeId,
186
+ registration.handleId ?? null,
187
+ registration.type,
188
+ registration.side,
189
+ registration.connectable ?? null,
190
+ registration.connectableStart ?? null,
191
+ registration.connectableEnd ?? null
192
+ ]);
193
+ }
194
+ /**
195
+ * A handle's state and the props of its element, for a handle rendered by hand (`Flow.Handle`
196
+ * uses it): registered with the engine, which measures its centre relative to its node.
197
+ */
198
+ function useHandle(options) {
199
+ const context = useFlowContext("useHandle");
200
+ const nodeIdOf = usePartNodeId("Handle", () => toValue(options).nodeId);
201
+ const registration = computed((previous) => {
202
+ const { type, side, handleId, connectable, connectableStart, connectableEnd } = toValue(options);
203
+ const next = {
204
+ nodeId: nodeIdOf(),
205
+ handleId,
206
+ type,
207
+ side,
208
+ connectable,
209
+ connectableStart,
210
+ connectableEnd
211
+ };
212
+ return previous !== void 0 && registrationKey(previous) === registrationKey(next) ? previous : next;
213
+ });
214
+ const attributes = useFlowValue(context, () => {
215
+ const value = registration.value;
216
+ const engine = context.engine.value;
217
+ return engine ? engine.adapter.attributes("handle", value) : {
218
+ ...partAttributes("handle", value.handleId),
219
+ "data-handle-type": value.type,
220
+ "data-side": value.side
221
+ };
222
+ }, sameValue, "entity");
223
+ const ref = elementRef((element) => {
224
+ const engine = context.engine.value;
225
+ if (!engine) return void 0;
226
+ const value = registration.value;
227
+ engine.adapter.registerHandle(value, element);
228
+ return () => engine.adapter.registerHandle(value, null);
229
+ }, () => [context.engine.value, registrationKey(registration.value)]);
230
+ return {
231
+ state: computed(() => {
232
+ const value = registration.value;
233
+ const current = attributes.value;
234
+ return {
235
+ nodeId: value.nodeId,
236
+ handleId: value.handleId,
237
+ type: value.type,
238
+ side: value.side,
239
+ connectable: current["data-connectable"] !== void 0,
240
+ connectableStart: current["data-connectable-start"] !== void 0,
241
+ connectableEnd: current["data-connectable-end"] !== void 0,
242
+ connecting: current["data-connecting"] !== void 0,
243
+ valid: current["data-valid"] !== void 0,
244
+ invalid: current["data-invalid"] !== void 0,
245
+ attributes: current
246
+ };
247
+ }),
248
+ props: computed(() => {
249
+ context.engine.value;
250
+ return {
251
+ ...attributes.value,
252
+ ref
253
+ };
254
+ })
255
+ };
256
+ }
257
+ // src/composables/use-internal-node.ts
258
+ /**
259
+ * A node as the engine knows it on screen (`internal-node-by`), as a computed ref: the document's
260
+ * node, its absolute position and box (`nodeOrigin` applied), whether its size is known, its
261
+ * z-index and its handles with their centres; undefined while it does not exist or before the root
262
+ * is mounted. It changes only when one of them changes (compared by value): a pan does not. The
263
+ * id may be a ref or a getter.
264
+ */
265
+ function useInternalNode(nodeId) {
266
+ const context = useFlowContext("useInternalNode");
267
+ return useFlowValue(context, () => context.engine.value?.get("internal-node-by", { nodeId: toValue(nodeId) }), sameFlowValue);
268
+ }
269
+ // src/composables/use-key-press.ts
270
+ /**
271
+ * Whether a key, or a combo of keys, is held, as a ref that changes with it. `keys` is a combo or
272
+ * several (any of them): key names joined by `+`, held at once (`"Shift"`, `"Meta+s"`,
273
+ * `["Meta+z", "Control+z"]`); a name is a `KeyboardEvent.key` or `.code`, without case
274
+ * (`watchKeyPress`). The keys are read on `target`, by default the window of the enclosing
275
+ * `Flow.Root`'s element (never the global one): false before the root is mounted, or outside a
276
+ * root without a `target`. The keys and the options may be refs or getters.
277
+ */
278
+ function useKeyPress(keys, options = {}) {
279
+ const rootElement = inject(FlowKey, null)?.rootElement;
280
+ const pressed = shallowRef(false);
281
+ watchEffect((onCleanup) => {
282
+ const given = toValue(options).target;
283
+ const target = given === void 0 ? rootElement?.value?.ownerDocument.defaultView ?? null : given;
284
+ if (!target) return;
285
+ const value = toValue(keys);
286
+ const stop = watchKeyPress(target, typeof value === "string" ? [value] : [...value], (held) => {
287
+ pressed.value = held;
288
+ });
289
+ onCleanup(() => {
290
+ stop();
291
+ pressed.value = false;
292
+ });
293
+ });
294
+ return readonly(pressed);
295
+ }
296
+ // src/composables/use-node.ts
297
+ /** the node registrations of the current patch, made once it is done (`registerLater`) */
298
+ let pending = /* @__PURE__ */ new Set();
299
+ let scheduled = false;
300
+ /** Makes the patch's pending registrations; one that throws goes to Vue's error handling. */
301
+ function registerPending() {
302
+ scheduled = false;
303
+ const batch = pending;
304
+ pending = /* @__PURE__ */ new Set();
305
+ const failures = [];
306
+ for (const entry of batch) try {
307
+ entry.register();
308
+ } catch (error) {
309
+ failures.push([error, entry]);
310
+ }
311
+ for (const [error, entry] of failures) handleError(error, entry.instance, ErrorCodes.FUNCTION_REF);
312
+ }
313
+ /**
314
+ * Registers a node's element once Vue's patch is done, all the patch's nodes at once. Vue calls an
315
+ * element's function ref as soon as the element is inserted, and the engine measures a node when
316
+ * it is registered (`offsetWidth`): registered there, each node mounted in a patch (hundreds, on a
317
+ * zoom out) would force a layout of its own between the insertions, where React's refs (and these)
318
+ * come after every insertion, so the first measurement lays the page out once. The batch is a
319
+ * post-flush job with Vue's template-ref id (-1): it runs after the patch, before the mounted
320
+ * hooks and `flush: "post"` watchers, and before the patch's `nextTick` resolves, as a ref set
321
+ * during the patch would. Returns whether it was still pending (then it is cancelled).
322
+ */
323
+ function registerLater(register, instance) {
324
+ const entry = {
325
+ register,
326
+ instance
327
+ };
328
+ pending.add(entry);
329
+ if (!scheduled) {
330
+ scheduled = true;
331
+ queuePostFlushCb(Object.assign(() => registerPending(), { id: -1 }));
332
+ }
333
+ return () => pending.delete(entry);
334
+ }
335
+ /**
336
+ * A node's state and the props of its element, for a node rendered by hand (`Flow.Node` uses it).
337
+ * Bind `props` on the element (the engine resolves presses from its attributes), in a render that
338
+ * reads `props.value`.
339
+ */
340
+ function useNode(node) {
341
+ const context = useFlowContext("useNode");
342
+ const { model } = context;
343
+ const instance = getCurrentInstance();
344
+ const current = () => toValue(node);
345
+ const view = useFlowValue(context, () => {
346
+ const value = current();
347
+ const nodeId = value.id;
348
+ const engine = context.engine.value;
349
+ if (!engine) {
350
+ const geometry = context.geometry.value;
351
+ const rect = geometry?.nodeRects[nodeId];
352
+ const at = rect ? void 0 : model.get("absolute-position-by", { nodeId });
353
+ return {
354
+ attributes: {
355
+ ...partAttributes("node", nodeId),
356
+ "data-selected": flag(value.selected === true)
357
+ },
358
+ x: rect?.x ?? at?.x ?? value.position.x,
359
+ y: rect?.y ?? at?.y ?? value.position.y,
360
+ zIndex: geometry?.nodeZIndexes[nodeId],
361
+ focusable: false
362
+ };
363
+ }
364
+ const rect = engine.get("node-rect-by", { nodeId });
365
+ return {
366
+ attributes: engine.adapter.attributes("node", { nodeId }),
367
+ x: rect?.x ?? value.position.x,
368
+ y: rect?.y ?? value.position.y,
369
+ zIndex: engine.get("node-z-index-by", { nodeId }),
370
+ focusable: engine.is("node-focusable", { nodeId })
371
+ };
372
+ }, sameValue, "entity", () => ({
373
+ kind: "node",
374
+ id: current().id
375
+ }));
376
+ const ref = elementRef((element) => {
377
+ const engine = context.engine.value;
378
+ if (!engine) return void 0;
379
+ const nodeId = current().id;
380
+ const cancel = registerLater(() => engine.adapter.registerNode(nodeId, element), instance);
381
+ return () => {
382
+ if (!cancel()) engine.adapter.registerNode(nodeId, null);
383
+ };
384
+ }, () => [context.engine.value, current().id]);
385
+ return {
386
+ state: computed(() => {
387
+ const { attributes, x, y, focusable } = view.value;
388
+ const value = current();
389
+ return {
390
+ nodeId: value.id,
391
+ node: value,
392
+ x,
393
+ y,
394
+ selected: attributes["data-selected"] !== void 0,
395
+ dragging: attributes["data-dragging"] !== void 0,
396
+ resizing: attributes["data-resizing"] !== void 0,
397
+ measured: attributes["data-measured"] !== void 0,
398
+ focusable,
399
+ attributes
400
+ };
401
+ }),
402
+ props: computed(() => {
403
+ const { attributes, x, y, zIndex, focusable } = view.value;
404
+ context.engine.value;
405
+ const value = current();
406
+ return {
407
+ ...attributes,
408
+ ref,
409
+ tabindex: focusable ? 0 : void 0,
410
+ style: {
411
+ position: "absolute",
412
+ top: "0",
413
+ left: "0",
414
+ transform: `translate(${px(x)}, ${px(y)})`,
415
+ ...zIndex === void 0 ? {} : { zIndex: String(zIndex) },
416
+ ...value.width === void 0 ? {} : { width: px(value.width) },
417
+ ...value.height === void 0 ? {} : { height: px(value.height) }
418
+ }
419
+ };
420
+ })
421
+ };
422
+ }
423
+ // src/composables/use-node-connections.ts
424
+ /**
425
+ * The connections at a node (`node-connections-by`), as a computed ref: each edge that starts or
426
+ * ends at it, as its `edgeId`, `source`, `sourceHandle`, `target` and `targetHandle`, in the
427
+ * document's order. It changes only when they change (an edge added, removed or reconnected
428
+ * there), not when a node moves or an edge's data changes. The options may be a ref or a getter;
429
+ * outside a `Flow.Node`, give an `id`.
430
+ */
431
+ function useNodeConnections(options = {}) {
432
+ const context = useFlowContext("useNodeConnections");
433
+ const node = inject(NodeKey, null);
434
+ const nodeIdOf = () => {
435
+ const id = toValue(options).id ?? node?.nodeId();
436
+ if (id === void 0) throw new Error("useNodeConnections must be called inside Flow.Node (or be given an id)");
437
+ return id;
438
+ };
439
+ nodeIdOf();
440
+ return useFlowValue(context, () => {
441
+ const { handleId, type } = toValue(options);
442
+ return context.model.get("node-connections-by", {
443
+ nodeId: nodeIdOf(),
444
+ handleId,
445
+ handleType: type
446
+ });
447
+ }, sameFlowValue);
448
+ }
449
+ // src/composables/use-node-id.ts
450
+ /**
451
+ * The id of the node the component renders inside (`Flow.Node`), as a computed ref, or null
452
+ * outside one: a custom node's piece reads its own node without being given its id.
453
+ */
454
+ function useNodeId() {
455
+ const context = inject(NodeKey, null);
456
+ return computed(() => context?.nodeId() ?? null);
457
+ }
458
+ // src/composables/use-nodes.ts
459
+ /**
460
+ * Every node of the enclosing `Flow.Root`, in drawing order, as a computed ref that changes on
461
+ * every change of one (the model's frozen list, never made reactive).
462
+ */
463
+ function useNodes() {
464
+ const context = useFlowContext("useNodes");
465
+ return useFlowValue(context, () => context.model.get("all-nodes"), Object.is);
466
+ }
467
+ // src/composables/use-nodes-data.ts
468
+ function useNodesData(ids) {
469
+ const context = useFlowContext("useNodesData");
470
+ const list = useFlowValue(context, () => {
471
+ const value = toValue(ids);
472
+ return context.model.get("nodes-data-by", { nodeIds: typeof value === "string" ? [value] : [...value] });
473
+ }, sameFlowValue);
474
+ return computed(() => typeof toValue(ids) === "string" ? list.value[0] ?? null : list.value);
475
+ }
476
+ // src/composables/use-on-viewport-change.ts
477
+ /**
478
+ * Calls back on the viewport's changes of the enclosing `Flow.Root` (the engine's events), without
479
+ * rendering anything: `gesture` is true for a pan, the wheel, a pinch or auto-pan, false for an
480
+ * action. `options` is a value, a ref or a getter, and its callbacks are read at each event (a
481
+ * reactive object's, a ref's or a getter's latest).
482
+ */
483
+ function useOnViewportChange(options) {
484
+ const context = useFlowContext("useOnViewportChange");
485
+ watchEffect((onCleanup) => {
486
+ const engine = context.engine.value;
487
+ if (!engine) return;
488
+ onCleanup(engine.subscribe((event) => {
489
+ const now = toValue(options);
490
+ if (event.type === "viewport-change-start") now.onStart?.(event.viewport, event.gesture);
491
+ else if (event.type === "viewport-change") now.onChange?.(event.viewport, event.gesture);
492
+ else if (event.type === "viewport-change-end") now.onEnd?.(event.viewport, event.gesture);
493
+ }));
494
+ });
495
+ }
496
+ // src/composables/use-selection.ts
497
+ const NONE = Object.freeze([]);
498
+ /**
499
+ * The selected nodes and edges of the enclosing `Flow.Root` (`selection()`; none without it), as a
500
+ * computed ref that changes with them: a panel showing the selection, a Delete button.
501
+ */
502
+ function useSelection() {
503
+ const context = useFlowContext("useSelection");
504
+ const { model } = context;
505
+ return useFlowValue(context, () => ({
506
+ nodes: model.get("selected-nodes") ?? NONE,
507
+ edges: model.get("selected-edges") ?? NONE
508
+ }), (a, b) => a.nodes.length === b.nodes.length && a.edges.length === b.edges.length && a.nodes.every((node, i) => node === b.nodes[i]) && a.edges.every((edge, i) => edge === b.edges[i]));
509
+ }
510
+ // src/composables/use-viewport.ts
511
+ /**
512
+ * The viewport of the enclosing `Flow.Root` (`{ x, y, zoom }`), as a computed ref that changes
513
+ * with it: a zoom level readout, a control's state. Change it with `engine.run("set-viewport")`.
514
+ */
515
+ function useViewport() {
516
+ const context = useFlowContext("useViewport");
517
+ return useFlowValue(context, () => context.publicEngine.get("viewport"));
518
+ }
519
+ // src/components/background.ts
520
+ const BACKGROUND_STYLE = {
521
+ position: "absolute",
522
+ top: "0",
523
+ left: "0",
524
+ width: "100%",
525
+ height: "100%",
526
+ pointerEvents: "none"
527
+ };
528
+ const EMPTY_PATTERN = Object.freeze({
529
+ variant: "dots",
530
+ x: 0,
531
+ y: 0,
532
+ width: 0,
533
+ height: 0,
534
+ dot: void 0,
535
+ path: void 0,
536
+ strokeWidth: 0
537
+ });
538
+ /** A pair given as a reactive array, as the engine takes it (a plain one). */
539
+ function plainPair(value) {
540
+ return Array.isArray(value) ? [value[0], value[1]] : value;
541
+ }
542
+ /**
543
+ * The flow's background (`data-flow-part="background"`): an SVG pattern of dots, lines or crosses
544
+ * that pans and zooms with the viewport (`background-pattern`), inside `Flow.Root` before
545
+ * `Flow.Viewport`. The marks are drawn in `currentColor`: set the `color` (and the background
546
+ * itself) in your style.
547
+ */
548
+ const Background = definePrimitive("Background", [
549
+ "variant",
550
+ "gap",
551
+ "size",
552
+ "offset",
553
+ "as"
554
+ ], (props, { attrs, slots }) => {
555
+ const context = useFlowContext("Background");
556
+ const pattern = useFlowValue(context, () => context.engine.value?.get("background-pattern", {
557
+ variant: props.variant,
558
+ gap: plainPair(props.gap),
559
+ size: props.size,
560
+ offset: plainPair(props.offset)
561
+ }));
562
+ const id = `flow-background-${(useId() ?? "").replace(/[^a-zA-Z0-9_-]/g, "")}`;
563
+ return () => {
564
+ const tile = pattern.value;
565
+ return renderElement({
566
+ tag: "svg",
567
+ as: props.as,
568
+ attrs,
569
+ render: slots.render,
570
+ state: { pattern: tile ?? EMPTY_PATTERN },
571
+ props: { ...partAttributes("background") },
572
+ style: BACKGROUND_STYLE,
573
+ children: tile ? () => [h("pattern", {
574
+ "data-flow-part": "background-pattern",
575
+ id,
576
+ patternUnits: "userSpaceOnUse",
577
+ x: tile.x,
578
+ y: tile.y,
579
+ width: tile.width,
580
+ height: tile.height
581
+ }, [tile.dot ? h("circle", {
582
+ "data-flow-part": "background-mark",
583
+ cx: tile.dot.cx,
584
+ cy: tile.dot.cy,
585
+ r: tile.dot.r,
586
+ fill: "currentColor"
587
+ }) : h("path", {
588
+ "data-flow-part": "background-mark",
589
+ d: tile.path,
590
+ fill: "none",
591
+ stroke: "currentColor",
592
+ "stroke-width": tile.strokeWidth
593
+ })]), h("rect", {
594
+ "data-flow-part": "background-fill",
595
+ width: "100%",
596
+ height: "100%",
597
+ fill: `url(#${id})`
598
+ })] : void 0
599
+ });
600
+ };
601
+ });
602
+ // src/components/connection-line.ts
603
+ const LINE_STYLE = {
604
+ position: "absolute",
605
+ top: "0",
606
+ left: "0",
607
+ width: "100%",
608
+ height: "100%",
609
+ overflow: "visible",
610
+ pointerEvents: "none"
611
+ };
612
+ /**
613
+ * The connection being drawn (`data-flow-part="connection-line"`, `data-valid` / `data-invalid`,
614
+ * `connection()`): an SVG inside `Flow.Viewport`, rendered only while a connection is under way.
615
+ */
616
+ const ConnectionLine = definePrimitive("ConnectionLine", ["as"], (props, { attrs, slots }) => {
617
+ const context = useFlowContext("ConnectionLine");
618
+ const connection = useConnection();
619
+ const attributes = useFlowValue(context, () => context.engine.value?.adapter.attributes("connection-line") ?? {});
620
+ return () => {
621
+ const current = connection.value;
622
+ if (!current) return null;
623
+ const own = attributes.value;
624
+ const state = {
625
+ connection: current,
626
+ valid: own["data-valid"] !== void 0,
627
+ invalid: own["data-invalid"] !== void 0
628
+ };
629
+ return renderElement({
630
+ tag: "svg",
631
+ as: props.as,
632
+ attrs,
633
+ render: slots.render,
634
+ state,
635
+ props: {
636
+ ...own,
637
+ "data-flow-part": "connection-line"
638
+ },
639
+ style: LINE_STYLE,
640
+ children: () => slots.default ? slots.default({ connection: current }) : h("path", {
641
+ "data-flow-part": "connection-path",
642
+ d: current.path,
643
+ fill: "none"
644
+ })
645
+ });
646
+ };
647
+ });
648
+ // src/components/controls.ts
649
+ /**
650
+ * A group of the viewport's buttons (`data-flow-part="controls"`): `Flow.ZoomIn`, `Flow.ZoomOut`,
651
+ * `Flow.FitView`, `Flow.ToggleInteractive`, or your own. Inside `Flow.Root`, outside
652
+ * `Flow.Viewport`; presses and the wheel over it are left to it. Place it with your style.
653
+ */
654
+ const Controls = definePrimitive("Controls", ["as"], (props, { attrs, slots }) => () => renderElement({
655
+ tag: "div",
656
+ as: props.as,
657
+ attrs,
658
+ render: slots.render,
659
+ state: {},
660
+ props: { ...partAttributes("controls") },
661
+ children: () => slots.default?.({})
662
+ }));
663
+ // src/components/edge-path.ts
664
+ /**
665
+ * An edge's path (`data-flow-part="edge-path"`): an SVG `<path>` whose `d` is the engine's
666
+ * (`edge-path-by`, D9; before the engine exists, the static geometry's), unfilled. A `d` of your own draws an app type (from `state.path`'s ends).
667
+ * Several may share an edge: a wide transparent one is a bigger press target. Its default slot
668
+ * renders inside the `<path>` (an `<animate>`, a `<title>`), as React's children.
669
+ */
670
+ const EdgePath$1 = definePrimitive("EdgePath", ["edgeId", "as"], (props, { attrs, slots }) => {
671
+ const context = useFlowContext("EdgePath");
672
+ const edgeId = useEdgeId("EdgePath", () => props.edgeId);
673
+ const path = useEdgePath(context, edgeId);
674
+ const attributes = useFlowValue(context, () => edgeAttributes(context, "edge-path", edgeId()), sameValue, "entity", () => ({
675
+ kind: "edge",
676
+ id: edgeId()
677
+ }));
678
+ return () => {
679
+ const current = path.value;
680
+ const own = attributes.value;
681
+ if (!current || !own) return null;
682
+ const state = {
683
+ edgeId: edgeId(),
684
+ path: current,
685
+ selected: own["data-selected"] !== void 0
686
+ };
687
+ return renderElement({
688
+ tag: "path",
689
+ as: props.as,
690
+ attrs,
691
+ render: slots.render,
692
+ state,
693
+ props: {
694
+ ...own,
695
+ d: current.path,
696
+ fill: "none"
697
+ },
698
+ children: slots.default ? () => slots.default?.({ state }) : void 0
699
+ });
700
+ };
701
+ });
702
+ // src/components/edge.ts
703
+ const EDGE_STYLE = { pointerEvents: "visibleStroke" };
704
+ /**
705
+ * One edge (`data-flow-part="edge"`, `data-flow-id`): an SVG group inside `Flow.Edges`, drawn once
706
+ * both its nodes have a size (before the engine, the sizes its document gives: a server render
707
+ * draws it). Mounted again in another render level's layer, it takes back the focus it had. It renders its default slot (`Flow.EdgePath` by default,
708
+ * `Flow.EdgeLabel`, `Flow.ReconnectAnchor`); a press on its stroke selects it (`selection()`).
709
+ */
710
+ const Edge = definePrimitive("Edge", ["edge", "as"], (props, { attrs, slots }) => {
711
+ const context = useFlowContext("Edge");
712
+ const { state, props: own } = useEdge(() => props.edge);
713
+ provide(EdgeKey, { edgeId: () => props.edge.id });
714
+ const ref = elementRef((element) => {
715
+ const engine = context.engine.value;
716
+ if (engine) nextTick(() => engine.adapter.refocus(element));
717
+ }, () => [context.engine.value]);
718
+ return () => {
719
+ const current = state.value;
720
+ context.engine.value;
721
+ if (!current.path) return null;
722
+ return renderElement({
723
+ tag: "g",
724
+ as: props.as,
725
+ attrs,
726
+ render: slots.render,
727
+ state: current,
728
+ ref,
729
+ props: { ...own.value },
730
+ style: EDGE_STYLE,
731
+ children: () => slots.default ? slots.default({ state: current }) : h(EdgePath$1)
732
+ });
733
+ };
734
+ });
735
+ // src/components/edge-label.ts
736
+ let nextLabelKey = 0;
737
+ /**
738
+ * An edge's label (`data-flow-part="edge-label"`): HTML, centred on the path's label point in
739
+ * flow coordinates, in the HTML layer of `Flow.Edges` (SVG holds no HTML: it renders there, not
740
+ * where it is written). It renders only its default slot; a press on it selects its edge.
741
+ */
742
+ const EdgeLabel = definePrimitive("EdgeLabel", ["edgeId", "as"], (props, { attrs, slots }) => {
743
+ const context = useFlowContext("EdgeLabel");
744
+ const edgeId = useEdgeId("EdgeLabel", () => props.edgeId);
745
+ const layer = inject(EdgeLabelLayerKey, null);
746
+ const path = useEdgePath(context, edgeId);
747
+ const attributes = useFlowValue(context, () => edgeAttributes(context, "edge-label", edgeId()), sameValue, "entity", () => ({
748
+ kind: "edge",
749
+ id: edgeId()
750
+ }));
751
+ const version = shallowRef(0);
752
+ const render = () => {
753
+ const current = path.value;
754
+ const own = attributes.value;
755
+ if (!current || !own) return null;
756
+ const state = {
757
+ edgeId: edgeId(),
758
+ path: current,
759
+ selected: own["data-selected"] !== void 0
760
+ };
761
+ const { x, y } = current.label;
762
+ return renderElement({
763
+ tag: "div",
764
+ as: props.as,
765
+ attrs,
766
+ render: slots.render,
767
+ state,
768
+ props: { ...own },
769
+ style: {
770
+ position: "absolute",
771
+ top: "0",
772
+ left: "0",
773
+ transform: `translate(${px(x)}, ${px(y)}) translate(-50%, -50%)`,
774
+ pointerEvents: "all"
775
+ },
776
+ children: () => slots.default?.({ state })
777
+ });
778
+ };
779
+ onClient(() => {
780
+ if (!layer) return;
781
+ const remove = layer.add({
782
+ key: nextLabelKey++,
783
+ edgeId,
784
+ render,
785
+ version
786
+ });
787
+ onScopeDispose(remove);
788
+ });
789
+ let renders = 0;
790
+ return () => {
791
+ version.value = ++renders;
792
+ return null;
793
+ };
794
+ });
795
+ // src/components/edge-toolbar.ts
796
+ let nextToolbarKey = 0;
797
+ /**
798
+ * A toolbar on an edge (`data-flow-part="toolbar"`, `data-flow-id` its edge's id), outside the
799
+ * zoom: rendered in `Flow.Root` (a `Teleport`), centred at the point `edge-toolbar-by` gives (the
800
+ * edge's label point or one of its ends), so it keeps its size at any zoom. Inside `Flow.Edges`
801
+ * (SVG) it renders from the edges' HTML layer, whose `Teleport` creates HTML. Presses and the
802
+ * wheel over it are left to it. It renders only its default slot (your buttons).
803
+ */
804
+ const EdgeToolbar = definePrimitive("EdgeToolbar", [
805
+ "edgeId",
806
+ "position",
807
+ "point",
808
+ "offset",
809
+ "alignX",
810
+ "alignY",
811
+ "open",
812
+ "as"
813
+ ], (props, { attrs, slots }) => {
814
+ const context = useFlowContext("EdgeToolbar");
815
+ const { model } = context;
816
+ const edgeId = useEdgeId("EdgeToolbar", () => props.edgeId);
817
+ const layer = inject(EdgeLabelLayerKey, null);
818
+ const view = useFlowValue(context, () => {
819
+ const engine = context.engine.value;
820
+ if (!engine) return void 0;
821
+ const id = edgeId();
822
+ if (!(props.open ?? model.is("edge-selected", { edgeId: id }))) return void 0;
823
+ const anchor = engine.get("edge-toolbar-by", {
824
+ edgeId: id,
825
+ position: props.position ?? "label",
826
+ point: props.point,
827
+ offset: props.offset,
828
+ alignX: props.alignX,
829
+ alignY: props.alignY
830
+ });
831
+ return anchor ? {
832
+ anchor,
833
+ attributes: engine.adapter.attributes("toolbar", { edgeId: id })
834
+ } : void 0;
835
+ });
836
+ const render = () => {
837
+ const current = view.value;
838
+ const root = context.rootElement.value;
839
+ if (!current || !root) return null;
840
+ const state = {
841
+ edgeId: edgeId(),
842
+ position: props.position ?? "label",
843
+ anchor: current.anchor
844
+ };
845
+ const { x, y, anchorX, anchorY } = current.anchor;
846
+ return h(Teleport, { to: root }, [renderElement({
847
+ tag: "div",
848
+ as: props.as,
849
+ attrs,
850
+ render: slots.render,
851
+ state,
852
+ props: { ...current.attributes },
853
+ style: {
854
+ position: "absolute",
855
+ top: "0",
856
+ left: "0",
857
+ transform: `translate(${px(x)}, ${px(y)}) translate(${-anchorX * 100}%, ${-anchorY * 100}%)`
858
+ },
859
+ children: () => slots.default?.({ state })
860
+ })]);
861
+ };
862
+ if (!layer) return render;
863
+ const version = shallowRef(0);
864
+ onClient(() => {
865
+ const remove = layer.add({
866
+ key: `toolbar-${nextToolbarKey++}`,
867
+ edgeId,
868
+ render,
869
+ version
870
+ });
871
+ onScopeDispose(remove);
872
+ });
873
+ let renders = 0;
874
+ return () => {
875
+ version.value = ++renders;
876
+ return null;
877
+ };
878
+ }, { booleans: ["open"] });
879
+ // src/components/edges.ts
880
+ const LAYER_STYLE = {
881
+ position: "absolute",
882
+ top: "0",
883
+ left: "0",
884
+ width: "100%",
885
+ height: "100%",
886
+ overflow: "visible",
887
+ pointerEvents: "none"
888
+ };
889
+ /**
890
+ * One edge's drawing, again only when its edge changes, a reactive value its slot reads does, or
891
+ * the slot is a new one; its path renders again by itself (`Flow.EdgePath` follows `edge-path-by`).
892
+ */
893
+ const EdgeSlot = defineComponent({
894
+ name: "FlowEdgeSlot",
895
+ props: {
896
+ edge: {
897
+ type: Object,
898
+ required: true
899
+ },
900
+ slot: {
901
+ type: Function,
902
+ required: false
903
+ }
904
+ },
905
+ setup(props) {
906
+ return () => props.slot?.({ edge: props.edge });
907
+ }
908
+ });
909
+ /** A label in the HTML layer: its edge provided again, so its content sits in its edge. */
910
+ const EdgeLabelOutlet = defineComponent({
911
+ name: "FlowEdgeLabelOutlet",
912
+ props: { entry: {
913
+ type: Object,
914
+ required: true
915
+ } },
916
+ setup(props) {
917
+ provide(EdgeKey, { edgeId: () => props.entry.edgeId() });
918
+ return () => {
919
+ props.entry.version.value;
920
+ return props.entry.render();
921
+ };
922
+ }
923
+ });
924
+ /**
925
+ * The layer of the edges (`data-flow-part="edges"`), inside `Flow.Viewport`, before `Flow.Nodes`:
926
+ * an SVG (`data-flow-part="edges"` too) where the default slot draws each edge, once both its
927
+ * nodes have a size (before the engine exists, from the document's sizes: a server render draws
928
+ * them; with `onlyRenderVisible`, none: the view is not known yet), in the engine's drawing order (`drawn-edges`: by stack value), and the HTML layer edge
929
+ * labels render in. When some edges stand above nodes (`render-layers`, `zIndexMode`), each level
930
+ * gets its own layer (`data-flow-part="edges-layer"`, `data-level`, at the level's `z-index`) with
931
+ * its SVG and its labels, between the nodes below and above it. It lets presses through to the
932
+ * pane; the edges' own parts take them.
933
+ *
934
+ * ```vue
935
+ * <Flow.Edges v-slot="{ edge }"><Flow.Edge :edge="edge" /></Flow.Edges>
936
+ * ```
937
+ */
938
+ const Edges = definePrimitive("Edges", ["as"], (props, { attrs, slots }) => {
939
+ const context = useFlowContext("Edges");
940
+ const layers = useDrawnLayers(context);
941
+ const labels = shallowRef([]);
942
+ provide(EdgeLabelLayerKey, { add(entry) {
943
+ labels.value = [...labels.value, entry];
944
+ return () => {
945
+ labels.value = labels.value.filter((other) => other !== entry);
946
+ };
947
+ } });
948
+ const svg = (edges) => h("svg", {
949
+ ...partAttributes("edges"),
950
+ style: LAYER_STYLE
951
+ }, edges.map((edge) => h(EdgeSlot, {
952
+ key: edge.id,
953
+ edge,
954
+ slot: slots.default
955
+ })));
956
+ const outlets = (entries) => entries.map((entry) => h(EdgeLabelOutlet, {
957
+ key: entry.key,
958
+ entry
959
+ }));
960
+ const levels = (drawn) => {
961
+ const levelOf = /* @__PURE__ */ new Map();
962
+ for (const [index, { edges }] of drawn.entries()) for (const edge of edges) levelOf.set(edge.id, index);
963
+ const byLevel = drawn.map(() => []);
964
+ for (const entry of labels.value) byLevel[levelOf.get(entry.edgeId()) ?? 0]?.push(entry);
965
+ const engine = context.engine.value;
966
+ return drawn.map(({ level, zIndex, edges }, index) => h("div", {
967
+ key: level,
968
+ ...engine ? engine.adapter.attributes("edges-layer", { level }) : edgesLayerAttributes(level),
969
+ style: {
970
+ ...LAYER_STYLE,
971
+ ...zIndex === void 0 ? {} : { zIndex: String(zIndex) }
972
+ }
973
+ }, [svg(edges), ...outlets(byLevel[index] ?? [])]));
974
+ };
975
+ return () => {
976
+ const drawn = layers.value;
977
+ const count = drawn.reduce((sum, { edges }) => sum + edges.length, 0);
978
+ return renderElement({
979
+ tag: "div",
980
+ as: props.as,
981
+ attrs,
982
+ render: slots.render,
983
+ state: { count },
984
+ props: { ...partAttributes("edges") },
985
+ style: LAYER_STYLE,
986
+ children: () => drawn.length > 1 ? levels(drawn) : [svg(drawn[0]?.edges ?? []), ...outlets(labels.value)]
987
+ });
988
+ };
989
+ });
990
+ // src/composables/use-control-button.ts
991
+ /** @internal a control button's state and own props: it runs `action` when clicked */
992
+ function useControlButton(part, action, disabledProp, fields = () => ({})) {
993
+ const context = useFlowContext(part);
994
+ const payload = () => givenPayload(fields());
995
+ const allowed = useFlowValue(context, () => {
996
+ const engine = context.engine.value;
997
+ return engine ? engine.can(action, payload()) : false;
998
+ });
999
+ const state = useFlowValue(context, () => ({ disabled: disabledProp() === true || !allowed.value }));
1000
+ const onClick = () => {
1001
+ context.engine.value?.run(action, payload());
1002
+ };
1003
+ return {
1004
+ state,
1005
+ props: () => {
1006
+ const { disabled } = state.value;
1007
+ return {
1008
+ type: "button",
1009
+ "data-flow-part": partName(part),
1010
+ "data-disabled": disabled ? "" : void 0,
1011
+ disabled,
1012
+ onClick
1013
+ };
1014
+ }
1015
+ };
1016
+ }
1017
+ /** @internal a control's payload: the fields its props give (an absent one is the engine's default) */
1018
+ function givenPayload(fields) {
1019
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
1020
+ }
1021
+ /** `ZoomIn` → `zoom-in`. */
1022
+ function partName(part) {
1023
+ return part.replace(/[A-Z]/g, (letter, at) => `${at === 0 ? "" : "-"}${letter.toLowerCase()}`);
1024
+ }
1025
+ // src/components/fit-view.ts
1026
+ /**
1027
+ * A button (`data-flow-part="fit-view"`): Fits every node in the root, or its `nodeIds` (`fit-view`, with its props as the payload), disabled before a node is measured. It renders only its default slot (an icon,
1028
+ * a label).
1029
+ */
1030
+ const FitView = definePrimitive("FitView", [
1031
+ "disabled",
1032
+ "duration",
1033
+ "padding",
1034
+ "nodeIds",
1035
+ "includeHidden",
1036
+ "minZoom",
1037
+ "maxZoom",
1038
+ "as"
1039
+ ], (props, { attrs, slots }) => {
1040
+ const { state, props: own } = useControlButton("FitView", "fit-view", () => props.disabled, () => ({
1041
+ duration: numberProp(props.duration),
1042
+ padding: props.padding,
1043
+ nodeIds: props.nodeIds ? [...props.nodeIds] : void 0,
1044
+ includeHidden: props.includeHidden,
1045
+ minZoom: numberProp(props.minZoom),
1046
+ maxZoom: numberProp(props.maxZoom)
1047
+ }));
1048
+ return () => {
1049
+ const current = state.value;
1050
+ return renderElement({
1051
+ tag: "button",
1052
+ as: props.as,
1053
+ attrs,
1054
+ render: slots.render,
1055
+ state: current,
1056
+ props: own(),
1057
+ children: () => slots.default?.({ state: current })
1058
+ });
1059
+ };
1060
+ }, {
1061
+ booleans: ["disabled", "includeHidden"],
1062
+ types: {
1063
+ duration: NUMBER_PROP,
1064
+ minZoom: NUMBER_PROP,
1065
+ maxZoom: NUMBER_PROP
1066
+ }
1067
+ });
1068
+ // src/components/handle.ts
1069
+ /** Where a handle sits by default: centred on its side of the node (a style may move it). */
1070
+ const SIDE_STYLE = {
1071
+ top: {
1072
+ top: "0",
1073
+ left: "50%",
1074
+ transform: "translate(-50%, -50%)"
1075
+ },
1076
+ right: {
1077
+ top: "50%",
1078
+ left: "100%",
1079
+ transform: "translate(-50%, -50%)"
1080
+ },
1081
+ bottom: {
1082
+ top: "100%",
1083
+ left: "50%",
1084
+ transform: "translate(-50%, -50%)"
1085
+ },
1086
+ left: {
1087
+ top: "50%",
1088
+ left: "0",
1089
+ transform: "translate(-50%, -50%)"
1090
+ }
1091
+ };
1092
+ const HANDLE_STYLE = { position: "absolute" };
1093
+ /**
1094
+ * A node's connection point (`data-flow-part="handle"`, `data-handle-type`, `data-side`), inside
1095
+ * `Flow.Node`: registered with the engine (D8), which measures its centre; with `connection()`, a
1096
+ * press on it draws a connection. Absolutely positioned at the middle of its `side` by default;
1097
+ * your `style` may place it elsewhere on the node. Give it its size and look.
1098
+ */
1099
+ const Handle = definePrimitive("Handle", [
1100
+ "type",
1101
+ "side",
1102
+ "handleId",
1103
+ "connectable",
1104
+ "connectableStart",
1105
+ "connectableEnd",
1106
+ "nodeId",
1107
+ "as"
1108
+ ], (props, { attrs, slots }) => {
1109
+ const { state, props: own } = useHandle(() => ({
1110
+ type: props.type,
1111
+ side: props.side,
1112
+ handleId: props.handleId,
1113
+ connectable: props.connectable,
1114
+ connectableStart: props.connectableStart,
1115
+ connectableEnd: props.connectableEnd,
1116
+ nodeId: props.nodeId
1117
+ }));
1118
+ return () => {
1119
+ const current = state.value;
1120
+ const { ref, ...attributes } = own.value;
1121
+ return renderElement({
1122
+ tag: "div",
1123
+ as: props.as,
1124
+ attrs,
1125
+ render: slots.render,
1126
+ state: current,
1127
+ ref,
1128
+ props: attributes,
1129
+ style: HANDLE_STYLE,
1130
+ baseStyle: SIDE_STYLE[props.side],
1131
+ children: () => slots.default?.({ state: current })
1132
+ });
1133
+ };
1134
+ }, { booleans: [
1135
+ "connectable",
1136
+ "connectableStart",
1137
+ "connectableEnd"
1138
+ ] });
1139
+ // src/components/node.ts
1140
+ /**
1141
+ * One node (`data-flow-part="node"`, `data-flow-id`), absolutely positioned at its place in the
1142
+ * viewport (a structural `transform`), registered with the engine, which measures it and resolves
1143
+ * presses on it (drag, select, connect from its handles). It renders only its default slot: the
1144
+ * content, `Flow.Handle`s, a resizer, a toolbar.
1145
+ */
1146
+ const Node = definePrimitive("Node", ["node", "as"], (props, { attrs, slots }) => {
1147
+ const { state, props: own } = useNode(() => props.node);
1148
+ provide(NodeKey, { nodeId: () => props.node.id });
1149
+ return () => {
1150
+ const current = state.value;
1151
+ const { ref, style, ...attributes } = own.value;
1152
+ return renderElement({
1153
+ tag: "div",
1154
+ as: props.as,
1155
+ attrs,
1156
+ render: slots.render,
1157
+ state: current,
1158
+ ref,
1159
+ props: attributes,
1160
+ style,
1161
+ children: () => slots.default?.({ state: current })
1162
+ });
1163
+ };
1164
+ });
1165
+ // src/components/node-toolbar.ts
1166
+ /**
1167
+ * A toolbar next to a node, or beside several nodes' bounds (`nodeIds`; `data-flow-part="toolbar"`),
1168
+ * outside the zoom: rendered in
1169
+ * `Flow.Root` (a `Teleport`), at the anchor `node-toolbar-by` gives, so it keeps its size at any
1170
+ * zoom. Presses and the wheel over it are left to it. It renders only its default slot (your
1171
+ * buttons).
1172
+ */
1173
+ const NodeToolbar = definePrimitive("NodeToolbar", [
1174
+ "nodeId",
1175
+ "nodeIds",
1176
+ "side",
1177
+ "align",
1178
+ "offset",
1179
+ "open",
1180
+ "as"
1181
+ ], (props, { attrs, slots }) => {
1182
+ const context = useFlowContext("NodeToolbar");
1183
+ const { model } = context;
1184
+ const around = inject(NodeKey, null);
1185
+ const many = () => props.nodeIds !== void 0 && props.nodeIds.length > 0;
1186
+ const nodeId = () => {
1187
+ if (many()) return void 0;
1188
+ const id = props.nodeId ?? around?.nodeId();
1189
+ if (id === void 0) throw new Error("Flow.NodeToolbar must be rendered inside Flow.Node (or be given a nodeId or nodeIds)");
1190
+ return id;
1191
+ };
1192
+ const view = useFlowValue(context, () => {
1193
+ const engine = context.engine.value;
1194
+ if (!engine) return void 0;
1195
+ const id = nodeId();
1196
+ const nodeIds = id === void 0 ? [...props.nodeIds ?? []] : [id];
1197
+ if (!(props.open ?? nodeIds.every((node) => model.is("node-selected", { nodeId: node })))) return void 0;
1198
+ const position = engine.get("node-toolbar-by", {
1199
+ ...id === void 0 ? { nodeIds } : { nodeId: id },
1200
+ side: props.side ?? "top",
1201
+ align: props.align,
1202
+ offset: props.offset
1203
+ });
1204
+ return position ? {
1205
+ position,
1206
+ nodeIds,
1207
+ attributes: engine.adapter.attributes("toolbar", id === void 0 ? {} : { nodeId: id })
1208
+ } : void 0;
1209
+ });
1210
+ return () => {
1211
+ const current = view.value;
1212
+ const root = context.rootElement.value;
1213
+ if (!current || !root) return null;
1214
+ const state = {
1215
+ nodeId: nodeId(),
1216
+ nodeIds: current.nodeIds,
1217
+ position: current.position,
1218
+ side: props.side ?? "top"
1219
+ };
1220
+ const { x, y, anchorX, anchorY } = current.position;
1221
+ return h(Teleport, { to: root }, [renderElement({
1222
+ tag: "div",
1223
+ as: props.as,
1224
+ attrs,
1225
+ render: slots.render,
1226
+ state,
1227
+ props: { ...current.attributes },
1228
+ style: {
1229
+ position: "absolute",
1230
+ top: "0",
1231
+ left: "0",
1232
+ transform: `translate(${x}px, ${y}px) translate(${-anchorX * 100}%, ${-anchorY * 100}%)`
1233
+ },
1234
+ children: () => slots.default?.({ state })
1235
+ })]);
1236
+ };
1237
+ }, { booleans: ["open"] });
1238
+ // src/components/nodes.ts
1239
+ const NODES_STYLE = {
1240
+ position: "absolute",
1241
+ top: "0",
1242
+ left: "0",
1243
+ isolation: "isolate"
1244
+ };
1245
+ const LAYERED_NODES_STYLE = {
1246
+ position: "absolute",
1247
+ top: "0",
1248
+ left: "0"
1249
+ };
1250
+ /**
1251
+ * One node's rendering, again only when its node changes (the model shares the nodes a command
1252
+ * did not change: a drag step renders the moved nodes only), when a reactive value its slot reads
1253
+ * does, or when the slot is a new one.
1254
+ */
1255
+ const NodeSlot = defineComponent({
1256
+ name: "FlowNodeSlot",
1257
+ props: {
1258
+ node: {
1259
+ type: Object,
1260
+ required: true
1261
+ },
1262
+ slot: {
1263
+ type: Function,
1264
+ required: false
1265
+ }
1266
+ },
1267
+ setup(props) {
1268
+ return () => props.slot?.({ node: props.node });
1269
+ }
1270
+ });
1271
+ const NO_NODES = Object.freeze([]);
1272
+ function shownNodes(nodes) {
1273
+ return nodes.filter((node) => node.hidden !== true);
1274
+ }
1275
+ /**
1276
+ * The layer of the nodes (`data-flow-part="nodes"`), inside `Flow.Viewport`: renders its default
1277
+ * slot for each node that is not hidden (with `onlyRenderVisible`, each one in view,
1278
+ * `visible-nodes`; with it, none before the engine knows the view: the server render and the
1279
+ * first client render), in drawing order, keyed by its id (a node keeps its element when it moves).
1280
+ * You render each node. It is its own stacking context (`isolation`), but while some edges stand
1281
+ * above nodes (several `render-layers`), when the nodes' z-indexes interleave with the edges'
1282
+ * layers.
1283
+ *
1284
+ * ```vue
1285
+ * <Flow.Nodes v-slot="{ node }"><Flow.Node :node="node">…</Flow.Node></Flow.Nodes>
1286
+ * ```
1287
+ */
1288
+ const Nodes = definePrimitive("Nodes", ["as"], (props, { attrs, slots }) => {
1289
+ const context = useFlowContext("Nodes");
1290
+ const { model } = context;
1291
+ const list = useFlowValue(context, () => {
1292
+ const engine = context.engine.value;
1293
+ if (!engine) return context.onlyRenderVisible.value ? NO_NODES : shownNodes(model.get("all-nodes"));
1294
+ return engine.adapter.settings.onlyRenderVisible ? engine.get("visible-nodes") : shownNodes(model.get("all-nodes"));
1295
+ });
1296
+ const layers = useDrawnLayers(context);
1297
+ return () => {
1298
+ const nodes = list.value;
1299
+ const layered = layers.value.length > 1;
1300
+ return renderElement({
1301
+ tag: "div",
1302
+ as: props.as,
1303
+ attrs,
1304
+ render: slots.render,
1305
+ state: { count: nodes.length },
1306
+ props: { ...partAttributes("nodes") },
1307
+ style: layered ? LAYERED_NODES_STYLE : NODES_STYLE,
1308
+ children: () => nodes.map((node) => h(NodeSlot, {
1309
+ key: node.id,
1310
+ node,
1311
+ slot: slots.default
1312
+ }))
1313
+ });
1314
+ };
1315
+ });
1316
+ // src/components/nodes-selection.ts
1317
+ /**
1318
+ * The rectangle around the selected nodes (`data-flow-part="nodes-selection"`, `selection()`),
1319
+ * inside `Flow.Viewport` next to `Flow.Nodes` (it is in flow coordinates): rendered at
1320
+ * `selection-rect`, while two or more nodes are selected by a box (or always, with
1321
+ * `selection({ rect: "always" })`). A press on it drags the selection (`drag()`), its context
1322
+ * menu is the selection's. With `keyboard()` it takes focus (`tabindex`), and its keys are a
1323
+ * focused selected node's: the arrows move the selection, the delete keys remove it, Escape clears
1324
+ * it. Give it its look.
1325
+ */
1326
+ const NodesSelection = definePrimitive("NodesSelection", ["as"], (props, { attrs, slots }) => {
1327
+ const context = useFlowContext("NodesSelection");
1328
+ const rect = useFlowValue(context, () => context.engine.value?.get("selection-rect") ?? null);
1329
+ const attributes = useFlowValue(context, () => context.engine.value?.adapter.attributes("nodes-selection") ?? {});
1330
+ return () => {
1331
+ const current = rect.value;
1332
+ if (!current) return null;
1333
+ const own = attributes.value;
1334
+ const state = {
1335
+ rect: current,
1336
+ dragging: own["data-dragging"] !== void 0
1337
+ };
1338
+ return renderElement({
1339
+ tag: "div",
1340
+ as: props.as,
1341
+ attrs,
1342
+ render: slots.render,
1343
+ state,
1344
+ props: {
1345
+ ...own,
1346
+ "data-flow-part": "nodes-selection"
1347
+ },
1348
+ style: {
1349
+ position: "absolute",
1350
+ top: "0",
1351
+ left: "0",
1352
+ transform: `translate(${px(current.x)}, ${px(current.y)})`,
1353
+ width: px(current.width),
1354
+ height: px(current.height)
1355
+ },
1356
+ children: () => slots.default?.({ state })
1357
+ });
1358
+ };
1359
+ });
1360
+ // src/components/reconnect-anchor.ts
1361
+ /**
1362
+ * An edge end's grab area (`data-flow-part="reconnect-anchor"`, `data-end`): an SVG circle at the
1363
+ * end, inside `Flow.Edge`. With `reconnection()`, a press on it moves that end to another handle;
1364
+ * an end its edge's `reconnectable` keeps fixed (`false`, or the other end's name) draws none.
1365
+ * Transparent by default; give it its radius (`r`, default 10) and look.
1366
+ */
1367
+ const ReconnectAnchor = definePrimitive("ReconnectAnchor", [
1368
+ "end",
1369
+ "edgeId",
1370
+ "as"
1371
+ ], (props, { attrs, slots }) => {
1372
+ const context = useFlowContext("ReconnectAnchor");
1373
+ const edgeId = useEdgeId("ReconnectAnchor", () => props.edgeId);
1374
+ const path = useEdgePath(context, edgeId);
1375
+ const view = useFlowValue(context, () => {
1376
+ const engine = context.engine.value;
1377
+ const id = edgeId();
1378
+ if (!context.model.is("edge-reconnectable", {
1379
+ edgeId: id,
1380
+ end: props.end
1381
+ })) return;
1382
+ return engine ? {
1383
+ attributes: engine.adapter.attributes("reconnect-anchor", {
1384
+ edgeId: id,
1385
+ end: props.end
1386
+ }),
1387
+ reconnecting: engine.is("edge-reconnecting", { edgeId: id })
1388
+ } : void 0;
1389
+ }, sameValue, "entity", () => ({
1390
+ kind: "edge",
1391
+ id: edgeId()
1392
+ }));
1393
+ return () => {
1394
+ const current = path.value;
1395
+ const own = view.value;
1396
+ if (!current || !own) return null;
1397
+ const point = current[props.end];
1398
+ return renderElement({
1399
+ tag: "circle",
1400
+ as: props.as,
1401
+ attrs,
1402
+ render: slots.render,
1403
+ state: {
1404
+ edgeId: edgeId(),
1405
+ end: props.end,
1406
+ path: current,
1407
+ reconnecting: own.reconnecting
1408
+ },
1409
+ props: {
1410
+ ...own.attributes,
1411
+ cx: point.x,
1412
+ cy: point.y,
1413
+ r: 10,
1414
+ fill: "transparent"
1415
+ },
1416
+ style: { pointerEvents: "all" }
1417
+ });
1418
+ };
1419
+ });
1420
+ // src/utils/engine-facade.ts
1421
+ const NOT_MOUNTED = Object.freeze({
1422
+ ok: false,
1423
+ error: Object.freeze({
1424
+ code: "refused",
1425
+ message: "the flow is not mounted"
1426
+ })
1427
+ });
1428
+ /** A facade whose reads before the mount answer `viewport` with `initial`. */
1429
+ function createEngineFacade(initial) {
1430
+ let current = null;
1431
+ const listeners = /* @__PURE__ */ new Set();
1432
+ let unsubscribe = () => {};
1433
+ const empty = {
1434
+ viewport: Object.freeze({ ...initial }),
1435
+ "root-size": Object.freeze({
1436
+ width: 0,
1437
+ height: 0
1438
+ }),
1439
+ "handles-by": Object.freeze([]),
1440
+ "dragging-node-ids": Object.freeze([]),
1441
+ "selection-box": null,
1442
+ connection: null
1443
+ };
1444
+ const forward = (verb, fallback) => (key, payload) => current ? current[verb](key, payload) : fallback(key, payload);
1445
+ return {
1446
+ engine: Object.freeze({
1447
+ run: forward("run", () => NOT_MOUNTED),
1448
+ can: forward("can", () => false),
1449
+ check: forward("check", () => NOT_MOUNTED),
1450
+ get: forward("get", (key) => Object.hasOwn(empty, key) ? empty[key] : void 0),
1451
+ is: forward("is", () => false),
1452
+ subscribe(listener) {
1453
+ const wrapper = (event) => listener(event);
1454
+ listeners.add(wrapper);
1455
+ return () => {
1456
+ listeners.delete(wrapper);
1457
+ };
1458
+ },
1459
+ destroy() {},
1460
+ get adapter() {
1461
+ if (!current) throw new Error("the flow is not mounted");
1462
+ return current.adapter;
1463
+ }
1464
+ }),
1465
+ get current() {
1466
+ return current;
1467
+ },
1468
+ set(next) {
1469
+ if (next === current) return;
1470
+ unsubscribe();
1471
+ current = next;
1472
+ unsubscribe = next ? next.subscribe((event) => {
1473
+ for (const listener of [...listeners]) listener(event);
1474
+ }) : () => {};
1475
+ }
1476
+ };
1477
+ }
1478
+ // src/utils/flow-store.ts
1479
+ const keyOf = (entity) => `${entity.kind}\u0000${entity.id}`;
1480
+ /** @internal the store of a root's model (and its engine, once attached) */
1481
+ function createFlowStore(model) {
1482
+ const view = shallowRef(0);
1483
+ const entity = shallowRef(0);
1484
+ const measure = shallowRef(0);
1485
+ const records = /* @__PURE__ */ new Map();
1486
+ let engine = null;
1487
+ const tokenOf = ({ kind, id }) => !engine ? [] : kind === "node" ? [engine.get("node-rect-by", { nodeId: id }), engine.is("node-measured", { nodeId: id })] : [engine.get("edge-path-by", { edgeId: id })];
1488
+ const recordOf = (of) => {
1489
+ const key = keyOf(of);
1490
+ let record = records.get(key);
1491
+ if (!record) {
1492
+ record = {
1493
+ entity: {
1494
+ kind: of.kind,
1495
+ id: of.id
1496
+ },
1497
+ counter: shallowRef(0),
1498
+ readers: 0,
1499
+ token: tokenOf(of)
1500
+ };
1501
+ records.set(key, record);
1502
+ }
1503
+ return record;
1504
+ };
1505
+ /** A change: of the view only, only a measurement, or of everything. */
1506
+ const tell = (kind) => {
1507
+ view.value++;
1508
+ if (kind === "view") return;
1509
+ if (kind === "entity") {
1510
+ for (const record of records.values()) record.token = void 0;
1511
+ entity.value++;
1512
+ return;
1513
+ }
1514
+ measure.value++;
1515
+ for (const record of records.values()) {
1516
+ const token = tokenOf(record.entity);
1517
+ const was = record.token;
1518
+ if (was !== void 0 && token.length === was.length && token.every((value, i) => Object.is(value, was[i]))) continue;
1519
+ record.token = token;
1520
+ record.counter.value++;
1521
+ }
1522
+ };
1523
+ let nodes = model.get("all-nodes");
1524
+ let edges = model.get("all-edges");
1525
+ return {
1526
+ view,
1527
+ entity,
1528
+ measure,
1529
+ counterOf: (of) => records.get(keyOf(of))?.counter ?? measure,
1530
+ acquire(of) {
1531
+ const key = keyOf(of);
1532
+ const record = recordOf(of);
1533
+ record.readers += 1;
1534
+ let released = false;
1535
+ return () => {
1536
+ if (released) return;
1537
+ released = true;
1538
+ record.readers -= 1;
1539
+ if (record.readers <= 0 && records.get(key) === record) records.delete(key);
1540
+ };
1541
+ },
1542
+ commit() {
1543
+ const nextNodes = model.get("all-nodes");
1544
+ const nextEdges = model.get("all-edges");
1545
+ const changed = nextNodes !== nodes || nextEdges !== edges;
1546
+ nodes = nextNodes;
1547
+ edges = nextEdges;
1548
+ tell(changed ? "entity" : "view");
1549
+ },
1550
+ attach(created) {
1551
+ engine = created;
1552
+ for (const record of records.values()) record.token = void 0;
1553
+ const layered = () => created.get("render-layers").length > 1;
1554
+ let wasLayered = layered();
1555
+ const stop = created.adapter.subscribe((change) => {
1556
+ const isLayered = layered();
1557
+ const levels = isLayered || wasLayered;
1558
+ wasLayered = isLayered;
1559
+ if (change.gesture || levels) tell("entity");
1560
+ else if (change.measured) tell(change.viewport ? "entity" : "measured");
1561
+ else tell("view");
1562
+ });
1563
+ return () => {
1564
+ stop();
1565
+ if (engine === created) engine = null;
1566
+ };
1567
+ }
1568
+ };
1569
+ }
1570
+ // src/components/root.ts
1571
+ /** Each engine event's Vue event, from the core's table (`node-click` → `nodeClick`, `ready` → `init`). */
1572
+ const EVENT_EMITS = new Map(Object.entries(ENGINE_EVENT_CALLBACKS).map(([type, name]) => [type, `${name[0]?.toLowerCase()}${name.slice(1)}`]));
1573
+ const ENGINE_PROPS = [
1574
+ "minZoom",
1575
+ "maxZoom",
1576
+ "translateExtent",
1577
+ "panOnDrag",
1578
+ "panOnScroll",
1579
+ "zoomOnScroll",
1580
+ "zoomOnPinch",
1581
+ "zoomOnDoubleClick",
1582
+ "zoomStep",
1583
+ "interactive",
1584
+ "onlyRenderVisible",
1585
+ "pathOptions",
1586
+ "autoPan",
1587
+ "panActivationKey",
1588
+ "panOnScrollMode",
1589
+ "panOnScrollSpeed",
1590
+ "zoomActivationKey",
1591
+ "easing",
1592
+ "nodeOrigin",
1593
+ "nodeExtent",
1594
+ "elevateNodesOnSelect",
1595
+ "elevateEdgesOnSelect",
1596
+ "paneClickDistance",
1597
+ "nodeClickDistance",
1598
+ "preventScrolling",
1599
+ "nodesFocusable",
1600
+ "edgesFocusable",
1601
+ "zIndexMode"
1602
+ ];
1603
+ /** The engine props whose attribute's text is its number (`pane-click-distance="5"`). */
1604
+ const NUMBER_PROPS = /* @__PURE__ */ new Set([
1605
+ "panOnScrollSpeed",
1606
+ "paneClickDistance",
1607
+ "nodeClickDistance"
1608
+ ]);
1609
+ const ROOT_PROPS = [
1610
+ "model",
1611
+ "defaultNodes",
1612
+ "defaultEdges",
1613
+ "nodes",
1614
+ "edges",
1615
+ "features",
1616
+ "createId",
1617
+ "defaultEdgeOptions",
1618
+ "viewport",
1619
+ "defaultViewport",
1620
+ "fitView",
1621
+ "flowRef",
1622
+ ...ENGINE_PROPS,
1623
+ "as"
1624
+ ];
1625
+ /** The props a bare attribute turns on (`<Flow.Root pan-on-scroll>`). */
1626
+ const ROOT_BOOLEANS = [
1627
+ "panOnDrag",
1628
+ "panOnScroll",
1629
+ "zoomOnScroll",
1630
+ "zoomOnPinch",
1631
+ "zoomOnDoubleClick",
1632
+ "interactive",
1633
+ "onlyRenderVisible",
1634
+ "autoPan",
1635
+ "elevateNodesOnSelect",
1636
+ "elevateEdgesOnSelect",
1637
+ "preventScrolling",
1638
+ "nodesFocusable",
1639
+ "edgesFocusable"
1640
+ ];
1641
+ const ROOT_EMITS = [
1642
+ "update:nodes",
1643
+ "update:edges",
1644
+ "update:viewport",
1645
+ ...EVENT_EMITS.values()
1646
+ ];
1647
+ /** The `meta` of the commands that bring the model to the controlled props. */
1648
+ const CONTROLLED_META = Object.freeze({ source: "controlled" });
1649
+ const DEFAULT_VIEWPORT = Object.freeze({
1650
+ x: 0,
1651
+ y: 0,
1652
+ zoom: 1
1653
+ });
1654
+ const ROOT_STYLE = {
1655
+ position: "relative",
1656
+ overflow: "hidden"
1657
+ };
1658
+ /** A list of features by their names, in order: an equal new list is the same. */
1659
+ function featureNames(features) {
1660
+ return (features ?? []).map((feature) => feature.name).join(",");
1661
+ }
1662
+ /** Warns once per message and root: misuse that the root ignores. */
1663
+ function warnOnce() {
1664
+ const warned = /* @__PURE__ */ new Set();
1665
+ return (message) => {
1666
+ if (warned.has(message)) return;
1667
+ warned.add(message);
1668
+ console.warn(`[@fragiola/flow-vue] ${message}`);
1669
+ };
1670
+ }
1671
+ /**
1672
+ * Each engine option's value as a key: a new equal object (`pathOptions`) is the same, a function
1673
+ * (`easing`) is itself, and `null` (`:pan-activation-key="null"`: none) is not `undefined` (the
1674
+ * default).
1675
+ */
1676
+ function optionKeys(options) {
1677
+ return Object.fromEntries(Object.entries(options).map(([key, value]) => [key, typeof value === "function" || value === void 0 ? value : JSON.stringify(value)]));
1678
+ }
1679
+ /** A key that changes when an engine option's value does (but a function's: `easing` is watched). */
1680
+ function optionsKey(options) {
1681
+ return JSON.stringify(optionKeys(options), (_key, value) => value === void 0 ? "undefined" : value);
1682
+ }
1683
+ /**
1684
+ * A list the app owns, as the model takes it: the plain list, never a reactive proxy (a frozen
1685
+ * list, the model's own given back by `update:nodes`, is taken as it is).
1686
+ */
1687
+ function plainList(list) {
1688
+ if (list === void 0) return void 0;
1689
+ const raw = toRaw(list);
1690
+ return Object.isFrozen(raw) ? raw : raw.map((entry) => toRaw(entry));
1691
+ }
1692
+ /** A value the app owns, without its reactive proxy. */
1693
+ function plain(value) {
1694
+ return value !== null && typeof value === "object" ? toRaw(value) : value;
1695
+ }
1696
+ /** a key per object: another model remounts the flow (`-1` for none) */
1697
+ const modelKeys = /* @__PURE__ */ new WeakMap();
1698
+ let nextModelKey = 0;
1699
+ function keyOfModel(model) {
1700
+ if (model === void 0) return -1;
1701
+ const raw = toRaw(model);
1702
+ let key = modelKeys.get(raw);
1703
+ if (key === void 0) {
1704
+ key = nextModelKey++;
1705
+ modelKeys.set(raw, key);
1706
+ }
1707
+ return key;
1708
+ }
1709
+ /** The flow of one model: it owns the engine, so it lives as long as the model does. */
1710
+ const RootFlow = definePrimitive("RootFlow", ROOT_PROPS, (props, { attrs, slots, emit }) => {
1711
+ const given = props.model ? toRaw(props.model) : void 0;
1712
+ const ownModel = given ? null : createFlowModel({
1713
+ version: 1,
1714
+ nodes: [...plainList(props.nodes ?? props.defaultNodes) ?? []],
1715
+ edges: [...plainList(props.edges ?? props.defaultEdges) ?? []]
1716
+ }, {
1717
+ features: plain(props.features),
1718
+ createId: props.createId,
1719
+ defaultEdgeOptions: plain(props.defaultEdgeOptions)
1720
+ });
1721
+ const typed = given ?? ownModel;
1722
+ const model = eraseModel(typed);
1723
+ const warn = warnOnce();
1724
+ const firstFeatures = featureNames(props.features);
1725
+ watch(() => featureNames(props.features), (next) => {
1726
+ if (!props.model && next !== firstFeatures) warn("the features prop changed after the root created its model: the change is ignored (the features are fixed when the model is created)");
1727
+ });
1728
+ const engineProps = () => Object.fromEntries(ENGINE_PROPS.map((name) => [name, NUMBER_PROPS.has(name) ? numberProp(props[name]) : plain(props[name])]));
1729
+ const start = plain(props.viewport ?? props.defaultViewport ?? DEFAULT_VIEWPORT);
1730
+ const facade = createEngineFacade(start);
1731
+ const engine = shallowRef(null);
1732
+ const store = createFlowStore(model);
1733
+ const revision = store.view;
1734
+ const rootElement = shallowRef(null);
1735
+ let sentOptions = {};
1736
+ const stops = [];
1737
+ onMounted(() => {
1738
+ const options = engineProps();
1739
+ const created = createFlowEngine(model, {
1740
+ ...options,
1741
+ defaultViewport: {
1742
+ x: start.x,
1743
+ y: start.y,
1744
+ zoom: start.zoom
1745
+ },
1746
+ fitView: plain(props.fitView)
1747
+ });
1748
+ sentOptions = optionKeys(options);
1749
+ stops.push(store.attach(created), created.subscribe((event) => {
1750
+ if (event.type === "viewport-change") {
1751
+ emit("update:viewport", event.viewport, event.gesture);
1752
+ return;
1753
+ }
1754
+ const name = EVENT_EMITS.get(event.type);
1755
+ if (name) emit(name, event);
1756
+ }));
1757
+ facade.set(created);
1758
+ engine.value = created;
1759
+ holdFlowRef(props.flowRef);
1760
+ });
1761
+ onUnmounted(() => {
1762
+ for (const stop of stops.splice(0)) stop();
1763
+ const current = engine.value;
1764
+ facade.set(null);
1765
+ engine.value = null;
1766
+ current?.destroy();
1767
+ });
1768
+ const handle = {
1769
+ model: typed,
1770
+ engine: facade.engine
1771
+ };
1772
+ let heldRef;
1773
+ const holdFlowRef = (next) => {
1774
+ const ref = next ? toRaw(next) : void 0;
1775
+ if (ref === heldRef) return;
1776
+ if (heldRef) setFlowRef(heldRef, null);
1777
+ heldRef = ref;
1778
+ if (ref) setFlowRef(ref, handle);
1779
+ };
1780
+ watch(() => props.flowRef, (next) => {
1781
+ if (engine.value) holdFlowRef(next);
1782
+ });
1783
+ onBeforeUnmount(() => holdFlowRef(void 0));
1784
+ watch([() => optionsKey(engineProps()), () => props.easing], () => {
1785
+ const live = engine.value;
1786
+ if (!live) return;
1787
+ const options = engineProps();
1788
+ const next = optionKeys(options);
1789
+ const changed = Object.keys(next).filter((key) => next[key] !== sentOptions[key]);
1790
+ sentOptions = next;
1791
+ if (changed.length === 0) return;
1792
+ live.adapter.setOptions(Object.fromEntries(changed.map((key) => [key, options[key]])));
1793
+ });
1794
+ watch(() => [
1795
+ engine.value,
1796
+ props.viewport?.x,
1797
+ props.viewport?.y,
1798
+ props.viewport?.zoom
1799
+ ], () => {
1800
+ const live = engine.value;
1801
+ const viewport = props.viewport;
1802
+ if (!live || !viewport) return;
1803
+ const current = live.get("viewport");
1804
+ if (current.x !== viewport.x || current.y !== viewport.y || current.zoom !== viewport.zoom) live.run("set-viewport", {
1805
+ x: viewport.x,
1806
+ y: viewport.y,
1807
+ zoom: viewport.zoom
1808
+ });
1809
+ });
1810
+ let sent = ownModel ? {
1811
+ nodes: props.nodes,
1812
+ edges: props.edges
1813
+ } : {
1814
+ nodes: void 0,
1815
+ edges: void 0
1816
+ };
1817
+ const syncControlled = () => {
1818
+ const { nodes, edges } = props;
1819
+ const target = {
1820
+ nodes: nodes === sent.nodes ? void 0 : plainList(nodes),
1821
+ edges: edges === sent.edges ? void 0 : plainList(edges)
1822
+ };
1823
+ sent = {
1824
+ nodes,
1825
+ edges
1826
+ };
1827
+ if (target.nodes === void 0 && target.edges === void 0) return;
1828
+ const commands = model.get("commands-to", target);
1829
+ if (commands.length === 0) return;
1830
+ const options = { meta: CONTROLLED_META };
1831
+ if (!model.run("batch", { commands: [...commands] }, options).ok) {
1832
+ const refused = [];
1833
+ for (const entry of commands) {
1834
+ const result = model.run("batch", { commands: [entry] }, options);
1835
+ if (!result.ok) refused.push(`${entry.command}: ${result.error.message}`);
1836
+ }
1837
+ warn(`the controlled nodes / edges were not all applied (the model's are reported back):\n${refused.join("\n")}`);
1838
+ }
1839
+ if (target.nodes !== void 0 && model.get("commands-to", { nodes: target.nodes }).length > 0) emit("update:nodes", model.get("all-nodes"));
1840
+ if (target.edges !== void 0 && model.get("commands-to", { edges: target.edges }).length > 0) emit("update:edges", model.get("all-edges"));
1841
+ };
1842
+ watch([() => props.nodes, () => props.edges], syncControlled);
1843
+ onClient(() => {
1844
+ syncControlled();
1845
+ onScopeDispose(model.subscribe((event) => {
1846
+ store.commit();
1847
+ if (event.meta?.source === CONTROLLED_META.source) return;
1848
+ if (event.before.nodes !== event.after.nodes) emit("update:nodes", event.after.nodes);
1849
+ if (event.before.edges !== event.after.edges) emit("update:edges", event.after.edges);
1850
+ }));
1851
+ });
1852
+ let lastGeometry;
1853
+ const geometry = computed(() => {
1854
+ store.entity.value;
1855
+ if (engine.value) {
1856
+ lastGeometry = void 0;
1857
+ return null;
1858
+ }
1859
+ const options = {
1860
+ nodeOrigin: plain(props.nodeOrigin),
1861
+ pathOptions: plain(props.pathOptions),
1862
+ zIndexMode: props.zIndexMode,
1863
+ elevateNodesOnSelect: props.elevateNodesOnSelect,
1864
+ elevateEdgesOnSelect: props.elevateEdgesOnSelect
1865
+ };
1866
+ const nodes = model.get("all-nodes");
1867
+ const edges = model.get("all-edges");
1868
+ const key = optionsKey(options);
1869
+ if (lastGeometry && lastGeometry.nodes === nodes && lastGeometry.edges === edges && lastGeometry.key === key) return lastGeometry.value;
1870
+ const value = staticGeometry({
1871
+ nodes,
1872
+ edges
1873
+ }, options);
1874
+ lastGeometry = {
1875
+ nodes,
1876
+ edges,
1877
+ key,
1878
+ value
1879
+ };
1880
+ return value;
1881
+ });
1882
+ const context = {
1883
+ model,
1884
+ engine,
1885
+ publicEngine: facade.engine,
1886
+ rootElement,
1887
+ revision,
1888
+ store,
1889
+ onlyRenderVisible: computed(() => props.onlyRenderVisible === true),
1890
+ geometry
1891
+ };
1892
+ provide(FlowKey, context);
1893
+ const rootRef = elementRef((element) => {
1894
+ rootElement.value = element;
1895
+ const live = engine.value;
1896
+ if (live) live.adapter.attachRoot(element);
1897
+ return () => {
1898
+ if (live) live.adapter.detachRoot();
1899
+ rootElement.value = null;
1900
+ };
1901
+ }, () => [engine.value]);
1902
+ const attributes = useFlowValue(context, () => {
1903
+ const live = engine.value;
1904
+ return live ? live.adapter.attributes("root") : partAttributes("root");
1905
+ });
1906
+ return () => {
1907
+ const live = engine.value;
1908
+ const current = attributes.value;
1909
+ const state = {
1910
+ interactive: live ? current["data-interactive"] !== void 0 : true,
1911
+ panning: current["data-panning"] !== void 0,
1912
+ dragging: current["data-dragging"] !== void 0,
1913
+ connecting: current["data-connecting"] !== void 0,
1914
+ selecting: current["data-selecting"] !== void 0
1915
+ };
1916
+ return renderElement({
1917
+ tag: "div",
1918
+ as: props.as,
1919
+ attrs,
1920
+ render: slots.render,
1921
+ state,
1922
+ ref: rootRef,
1923
+ props: { ...current },
1924
+ style: ROOT_STYLE,
1925
+ children: () => slots.default?.({ state })
1926
+ });
1927
+ };
1928
+ }, {
1929
+ booleans: ROOT_BOOLEANS,
1930
+ types: {
1931
+ fitView: [Boolean, Object],
1932
+ panOnDrag: [Boolean, Array],
1933
+ autoPan: [Boolean, Object],
1934
+ panOnScrollSpeed: NUMBER_PROP,
1935
+ paneClickDistance: NUMBER_PROP,
1936
+ nodeClickDistance: NUMBER_PROP
1937
+ },
1938
+ emits: ROOT_EMITS
1939
+ });
1940
+ /**
1941
+ * The flow (`data-flow-part="root"`): owns the model (unless given) and the engine, attaches the
1942
+ * engine to its element (the engine listens to it: pointer, wheel, keys, focus) and re-renders
1943
+ * when the flow changes. It renders only its default slot; no provider is needed above it. Give
1944
+ * it a size (the flow fills it). Another `model` remounts the flow. It takes any features; give
1945
+ * it your registry and features with `typedFlow<Types, typeof features>().Root`.
1946
+ */
1947
+ const Root = defineComponent({
1948
+ name: "FlowRoot",
1949
+ inheritAttrs: false,
1950
+ props: [...ROOT_PROPS],
1951
+ emits: [...ROOT_EMITS],
1952
+ setup(props, { attrs, slots, emit }) {
1953
+ const forward = Object.fromEntries(ROOT_EMITS.map((event) => [`on${event[0]?.toUpperCase()}${event.slice(1)}`, (...args) => emit(event, ...args)]));
1954
+ return () => h(RootFlow, {
1955
+ ...attrs,
1956
+ ...props,
1957
+ ...forward,
1958
+ key: keyOfModel(props.model)
1959
+ }, slots);
1960
+ }
1961
+ });
1962
+ // src/components/selection-box.ts
1963
+ /**
1964
+ * The box selection being drawn (`data-flow-part="selection-box"`, `selection()`): absolutely
1965
+ * positioned in `Flow.Root` (outside `Flow.Viewport`: it is in screen pixels), rendered only
1966
+ * while a box is drawn. Give it its look.
1967
+ */
1968
+ const SelectionBox = definePrimitive("SelectionBox", ["as"], (props, { attrs, slots }) => {
1969
+ const context = useFlowContext("SelectionBox");
1970
+ const box = useFlowValue(context, () => context.engine.value?.get("selection-box") ?? null);
1971
+ const attributes = useFlowValue(context, () => context.engine.value?.adapter.attributes("selection-box") ?? {});
1972
+ return () => {
1973
+ const current = box.value;
1974
+ if (!current) return null;
1975
+ const state = { box: current };
1976
+ return renderElement({
1977
+ tag: "div",
1978
+ as: props.as,
1979
+ attrs,
1980
+ render: slots.render,
1981
+ state,
1982
+ props: {
1983
+ ...attributes.value,
1984
+ "data-flow-part": "selection-box"
1985
+ },
1986
+ style: {
1987
+ position: "absolute",
1988
+ left: px(current.x),
1989
+ top: px(current.y),
1990
+ width: px(current.width),
1991
+ height: px(current.height),
1992
+ pointerEvents: "none"
1993
+ },
1994
+ children: () => slots.default?.({ state })
1995
+ });
1996
+ };
1997
+ });
1998
+ // src/components/toggle-interactive.ts
1999
+ /** The switches the lock turns off and on (React Flow's: dragging, connecting, selecting). */
2000
+ const LOCKED_KINDS = [
2001
+ "drag",
2002
+ "connect",
2003
+ "select"
2004
+ ];
2005
+ /**
2006
+ * A toggle button (`data-flow-part="toggle-interactive"`, `aria-pressed` while the flow is locked,
2007
+ * `data-interactive`): locks and unlocks the flow, React Flow's interactive button: locking turns
2008
+ * dragging, connecting and selecting off (`set-interactive { drag, connect, select }`), unlocking
2009
+ * turns them and `interactive` on; pan and zoom stay. It renders only its default slot.
2010
+ */
2011
+ const ToggleInteractive = definePrimitive("ToggleInteractive", ["as"], (props, { attrs, slots }) => {
2012
+ const context = useFlowContext("ToggleInteractive");
2013
+ const interactive = useFlowValue(context, () => {
2014
+ const engine = context.engine.value;
2015
+ return engine ? LOCKED_KINDS.some((kind) => engine.is("interactive-by", { kind })) : true;
2016
+ });
2017
+ const onClick = () => {
2018
+ context.engine.value?.run("set-interactive", interactive.value ? {
2019
+ drag: false,
2020
+ connect: false,
2021
+ select: false
2022
+ } : {
2023
+ interactive: true,
2024
+ drag: true,
2025
+ connect: true,
2026
+ select: true
2027
+ });
2028
+ };
2029
+ return () => {
2030
+ const state = { interactive: interactive.value };
2031
+ return renderElement({
2032
+ tag: "button",
2033
+ as: props.as,
2034
+ attrs,
2035
+ render: slots.render,
2036
+ state,
2037
+ props: {
2038
+ type: "button",
2039
+ "data-flow-part": "toggle-interactive",
2040
+ "data-interactive": state.interactive ? "" : void 0,
2041
+ "aria-pressed": String(!state.interactive),
2042
+ disabled: context.engine.value === null,
2043
+ onClick
2044
+ },
2045
+ children: () => slots.default?.({ state })
2046
+ });
2047
+ };
2048
+ });
2049
+ // src/components/viewport.ts
2050
+ const VIEWPORT_STYLE = {
2051
+ position: "absolute",
2052
+ top: "0",
2053
+ left: "0",
2054
+ width: "100%",
2055
+ height: "100%",
2056
+ isolation: "isolate"
2057
+ };
2058
+ /**
2059
+ * The pannable, zoomable layer (`data-flow-part="viewport"`): what is inside is in flow
2060
+ * coordinates (`Flow.Edges`, `Flow.Nodes`, `Flow.ConnectionLine`). The engine writes its
2061
+ * `transform` itself (D4), never Vue: a pan or a zoom re-renders nothing inside it, nor the
2062
+ * viewport itself unless its state is read (its `render` slot, a `class` or `style` function).
2063
+ */
2064
+ const Viewport$1 = definePrimitive("Viewport", ["as"], (props, { attrs, slots }) => {
2065
+ const context = useFlowContext("Viewport");
2066
+ const viewport = useViewport();
2067
+ const ref = elementRef((element) => {
2068
+ const engine = context.engine.value;
2069
+ if (!engine) return void 0;
2070
+ engine.adapter.attachViewport(element);
2071
+ return () => engine.adapter.attachViewport(null);
2072
+ }, () => [context.engine.value]);
2073
+ const state = { get viewport() {
2074
+ return viewport.value;
2075
+ } };
2076
+ return () => {
2077
+ context.engine.value;
2078
+ return renderElement({
2079
+ tag: "div",
2080
+ as: props.as,
2081
+ attrs,
2082
+ render: slots.render,
2083
+ state,
2084
+ ref,
2085
+ props: { ...partAttributes("viewport") },
2086
+ style: VIEWPORT_STYLE,
2087
+ children: () => slots.default?.({ state })
2088
+ });
2089
+ };
2090
+ });
2091
+ // src/components/zoom-in.ts
2092
+ /**
2093
+ * A button (`data-flow-part="zoom-in"`): Zooms in by a step around the root's centre (`zoom-in`), disabled at the greatest zoom. It renders only its default slot (an icon,
2094
+ * a label).
2095
+ */
2096
+ const ZoomIn = definePrimitive("ZoomIn", [
2097
+ "disabled",
2098
+ "duration",
2099
+ "as"
2100
+ ], (props, { attrs, slots }) => {
2101
+ const { state, props: own } = useControlButton("ZoomIn", "zoom-in", () => props.disabled, () => ({ duration: numberProp(props.duration) }));
2102
+ return () => {
2103
+ const current = state.value;
2104
+ return renderElement({
2105
+ tag: "button",
2106
+ as: props.as,
2107
+ attrs,
2108
+ render: slots.render,
2109
+ state: current,
2110
+ props: own(),
2111
+ children: () => slots.default?.({ state: current })
2112
+ });
2113
+ };
2114
+ }, {
2115
+ booleans: ["disabled"],
2116
+ types: { duration: NUMBER_PROP }
2117
+ });
2118
+ // src/components/zoom-out.ts
2119
+ /**
2120
+ * A button (`data-flow-part="zoom-out"`): Zooms out by a step around the root's centre (`zoom-out`), disabled at the least zoom. It renders only its default slot (an icon,
2121
+ * a label).
2122
+ */
2123
+ const ZoomOut = definePrimitive("ZoomOut", [
2124
+ "disabled",
2125
+ "duration",
2126
+ "as"
2127
+ ], (props, { attrs, slots }) => {
2128
+ const { state, props: own } = useControlButton("ZoomOut", "zoom-out", () => props.disabled, () => ({ duration: numberProp(props.duration) }));
2129
+ return () => {
2130
+ const current = state.value;
2131
+ return renderElement({
2132
+ tag: "button",
2133
+ as: props.as,
2134
+ attrs,
2135
+ render: slots.render,
2136
+ state: current,
2137
+ props: own(),
2138
+ children: () => slots.default?.({ state: current })
2139
+ });
2140
+ };
2141
+ }, {
2142
+ booleans: ["disabled"],
2143
+ types: { duration: NUMBER_PROP }
2144
+ });
2145
+ // src/parts.ts
2146
+ var parts_exports = /* @__PURE__ */ __exportAll({
2147
+ Background: () => Background,
2148
+ ConnectionLine: () => ConnectionLine,
2149
+ Controls: () => Controls,
2150
+ Edge: () => Edge,
2151
+ EdgeLabel: () => EdgeLabel,
2152
+ EdgePath: () => EdgePath$1,
2153
+ EdgeToolbar: () => EdgeToolbar,
2154
+ Edges: () => Edges,
2155
+ FitView: () => FitView,
2156
+ Handle: () => Handle,
2157
+ Node: () => Node,
2158
+ NodeToolbar: () => NodeToolbar,
2159
+ Nodes: () => Nodes,
2160
+ NodesSelection: () => NodesSelection,
2161
+ ReconnectAnchor: () => ReconnectAnchor,
2162
+ Root: () => Root,
2163
+ SelectionBox: () => SelectionBox,
2164
+ ToggleInteractive: () => ToggleInteractive,
2165
+ Viewport: () => Viewport$1,
2166
+ ZoomIn: () => ZoomIn,
2167
+ ZoomOut: () => ZoomOut
2168
+ });
2169
+ // src/typed.ts
2170
+ /**
2171
+ * The `Flow` primitives typed by your registry and features: what React writes as type arguments
2172
+ * (`<Flow.Nodes<Types>>`), which a Vue template cannot pass. The same components, typed:
2173
+ *
2174
+ * ```ts
2175
+ * const Flow = typedFlow<Types, typeof features>();
2176
+ * // <Flow.Nodes v-slot="{ node }">: `node.data` is the registry's
2177
+ * ```
2178
+ */
2179
+ function typedFlow() {
2180
+ return parts_exports;
2181
+ }
2182
+ export { parts_exports as Flow, createFlowRef, typedFlow, useConnection, useEdge, useEdges, useFlow, useFlowRef, useFlowStore, useHandle, useInternalNode, useKeyPress, useNode, useNodeConnections, useNodeId, useNodes, useNodesData, useOnViewportChange, useSelection, useViewport };
2183
+
2184
+ //# sourceMappingURL=index.js.map