@flowgram.ai/free-auto-layout-plugin 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.
@@ -0,0 +1,2543 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
11
+
12
+ // src/dagre-lib/greedy-fas.js
13
+ import { Graph } from "@dagrejs/graphlib";
14
+
15
+ // src/dagre-lib/data/list.js
16
+ var List = class {
17
+ constructor() {
18
+ let sentinel = {};
19
+ sentinel._next = sentinel._prev = sentinel;
20
+ this._sentinel = sentinel;
21
+ }
22
+ dequeue() {
23
+ let sentinel = this._sentinel;
24
+ let entry = sentinel._prev;
25
+ if (entry !== sentinel) {
26
+ unlink(entry);
27
+ return entry;
28
+ }
29
+ }
30
+ enqueue(entry) {
31
+ let sentinel = this._sentinel;
32
+ if (entry._prev && entry._next) {
33
+ unlink(entry);
34
+ }
35
+ entry._next = sentinel._next;
36
+ sentinel._next._prev = entry;
37
+ sentinel._next = entry;
38
+ entry._prev = sentinel;
39
+ }
40
+ toString() {
41
+ let strs = [];
42
+ let sentinel = this._sentinel;
43
+ let curr = sentinel._prev;
44
+ while (curr !== sentinel) {
45
+ strs.push(JSON.stringify(curr, filterOutLinks));
46
+ curr = curr._prev;
47
+ }
48
+ return "[" + strs.join(", ") + "]";
49
+ }
50
+ };
51
+ function unlink(entry) {
52
+ entry._prev._next = entry._next;
53
+ entry._next._prev = entry._prev;
54
+ delete entry._next;
55
+ delete entry._prev;
56
+ }
57
+ function filterOutLinks(k, v) {
58
+ if (k !== "_next" && k !== "_prev") {
59
+ return v;
60
+ }
61
+ }
62
+ var list_default = List;
63
+
64
+ // src/dagre-lib/greedy-fas.js
65
+ var greedy_fas_default = greedyFAS;
66
+ var DEFAULT_WEIGHT_FN = () => 1;
67
+ function greedyFAS(g, weightFn) {
68
+ if (g.nodeCount() <= 1) {
69
+ return [];
70
+ }
71
+ let state = buildState(g, weightFn || DEFAULT_WEIGHT_FN);
72
+ let results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);
73
+ return results.flatMap((e) => g.outEdges(e.v, e.w));
74
+ }
75
+ function doGreedyFAS(g, buckets, zeroIdx) {
76
+ let results = [];
77
+ let sources = buckets[buckets.length - 1];
78
+ let sinks = buckets[0];
79
+ let entry;
80
+ while (g.nodeCount()) {
81
+ while (entry = sinks.dequeue()) {
82
+ removeNode(g, buckets, zeroIdx, entry);
83
+ }
84
+ while (entry = sources.dequeue()) {
85
+ removeNode(g, buckets, zeroIdx, entry);
86
+ }
87
+ if (g.nodeCount()) {
88
+ for (let i = buckets.length - 2; i > 0; --i) {
89
+ entry = buckets[i].dequeue();
90
+ if (entry) {
91
+ results = results.concat(removeNode(g, buckets, zeroIdx, entry, true));
92
+ break;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ return results;
98
+ }
99
+ function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) {
100
+ let results = collectPredecessors ? [] : void 0;
101
+ g.inEdges(entry.v).forEach((edge) => {
102
+ let weight = g.edge(edge);
103
+ let uEntry = g.node(edge.v);
104
+ if (collectPredecessors) {
105
+ results.push({ v: edge.v, w: edge.w });
106
+ }
107
+ uEntry.out -= weight;
108
+ assignBucket(buckets, zeroIdx, uEntry);
109
+ });
110
+ g.outEdges(entry.v).forEach((edge) => {
111
+ let weight = g.edge(edge);
112
+ let w = edge.w;
113
+ let wEntry = g.node(w);
114
+ wEntry["in"] -= weight;
115
+ assignBucket(buckets, zeroIdx, wEntry);
116
+ });
117
+ g.removeNode(entry.v);
118
+ return results;
119
+ }
120
+ function buildState(g, weightFn) {
121
+ let fasGraph = new Graph();
122
+ let maxIn = 0;
123
+ let maxOut = 0;
124
+ g.nodes().forEach((v) => {
125
+ fasGraph.setNode(v, { v, in: 0, out: 0 });
126
+ });
127
+ g.edges().forEach((e) => {
128
+ let prevWeight = fasGraph.edge(e.v, e.w) || 0;
129
+ let weight = weightFn(e);
130
+ let edgeWeight = prevWeight + weight;
131
+ fasGraph.setEdge(e.v, e.w, edgeWeight);
132
+ maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight);
133
+ maxIn = Math.max(maxIn, fasGraph.node(e.w)["in"] += weight);
134
+ });
135
+ let buckets = range(maxOut + maxIn + 3).map(() => new list_default());
136
+ let zeroIdx = maxIn + 1;
137
+ fasGraph.nodes().forEach((v) => {
138
+ assignBucket(buckets, zeroIdx, fasGraph.node(v));
139
+ });
140
+ return { graph: fasGraph, buckets, zeroIdx };
141
+ }
142
+ function assignBucket(buckets, zeroIdx, entry) {
143
+ if (!entry.out) {
144
+ buckets[0].enqueue(entry);
145
+ } else if (!entry["in"]) {
146
+ buckets[buckets.length - 1].enqueue(entry);
147
+ } else {
148
+ buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry);
149
+ }
150
+ }
151
+ function range(limit) {
152
+ const range3 = [];
153
+ for (let i = 0; i < limit; i++) {
154
+ range3.push(i);
155
+ }
156
+ return range3;
157
+ }
158
+
159
+ // src/dagre-lib/util.js
160
+ import { Graph as Graph2 } from "@dagrejs/graphlib";
161
+ var util = {
162
+ addBorderNode,
163
+ addDummyNode,
164
+ applyWithChunking,
165
+ asNonCompoundGraph,
166
+ buildLayerMatrix,
167
+ intersectRect,
168
+ mapValues,
169
+ maxRank,
170
+ normalizeRanks,
171
+ notime,
172
+ partition,
173
+ pick,
174
+ predecessorWeights,
175
+ range: range2,
176
+ removeEmptyRanks,
177
+ simplify,
178
+ successorWeights,
179
+ time,
180
+ uniqueId,
181
+ zipObject
182
+ };
183
+ var util_default = util;
184
+ function addDummyNode(g, type, attrs, name) {
185
+ let v;
186
+ do {
187
+ v = uniqueId(name);
188
+ } while (g.hasNode(v));
189
+ attrs.dummy = type;
190
+ g.setNode(v, attrs);
191
+ return v;
192
+ }
193
+ function simplify(g) {
194
+ let simplified = new Graph2().setGraph(g.graph());
195
+ g.nodes().forEach((v) => simplified.setNode(v, g.node(v)));
196
+ g.edges().forEach((e) => {
197
+ let simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 };
198
+ let label = g.edge(e);
199
+ simplified.setEdge(e.v, e.w, {
200
+ weight: simpleLabel.weight + label.weight,
201
+ minlen: Math.max(simpleLabel.minlen, label.minlen)
202
+ });
203
+ });
204
+ return simplified;
205
+ }
206
+ function asNonCompoundGraph(g) {
207
+ let simplified = new Graph2({ multigraph: g.isMultigraph() }).setGraph(g.graph());
208
+ g.nodes().forEach((v) => {
209
+ if (!g.children(v).length) {
210
+ simplified.setNode(v, g.node(v));
211
+ }
212
+ });
213
+ g.edges().forEach((e) => {
214
+ simplified.setEdge(e, g.edge(e));
215
+ });
216
+ return simplified;
217
+ }
218
+ function successorWeights(g) {
219
+ let weightMap = g.nodes().map((v) => {
220
+ let sucs = {};
221
+ g.outEdges(v).forEach((e) => {
222
+ sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight;
223
+ });
224
+ return sucs;
225
+ });
226
+ return zipObject(g.nodes(), weightMap);
227
+ }
228
+ function predecessorWeights(g) {
229
+ let weightMap = g.nodes().map((v) => {
230
+ let preds = {};
231
+ g.inEdges(v).forEach((e) => {
232
+ preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight;
233
+ });
234
+ return preds;
235
+ });
236
+ return zipObject(g.nodes(), weightMap);
237
+ }
238
+ function intersectRect(rect, point) {
239
+ let x = rect.x;
240
+ let y = rect.y;
241
+ let dx = point.x - x;
242
+ let dy = point.y - y;
243
+ let w = rect.width / 2;
244
+ let h = rect.height / 2;
245
+ if (!dx && !dy) {
246
+ throw new Error("Not possible to find intersection inside of the rectangle");
247
+ }
248
+ let sx, sy;
249
+ if (Math.abs(dy) * w > Math.abs(dx) * h) {
250
+ if (dy < 0) {
251
+ h = -h;
252
+ }
253
+ sx = h * dx / dy;
254
+ sy = h;
255
+ } else {
256
+ if (dx < 0) {
257
+ w = -w;
258
+ }
259
+ sx = w;
260
+ sy = w * dy / dx;
261
+ }
262
+ return { x: x + sx, y: y + sy };
263
+ }
264
+ function buildLayerMatrix(g) {
265
+ let layering = range2(maxRank(g) + 1).map(() => []);
266
+ g.nodes().forEach((v) => {
267
+ let node = g.node(v);
268
+ let rank2 = node.rank;
269
+ if (rank2 !== void 0) {
270
+ layering[rank2][node.order] = v;
271
+ }
272
+ });
273
+ return layering;
274
+ }
275
+ function normalizeRanks(g) {
276
+ let nodeRanks = g.nodes().map((v) => {
277
+ let rank2 = g.node(v).rank;
278
+ if (rank2 === void 0) {
279
+ return Number.MAX_VALUE;
280
+ }
281
+ return rank2;
282
+ });
283
+ let min = applyWithChunking(Math.min, nodeRanks);
284
+ g.nodes().forEach((v) => {
285
+ let node = g.node(v);
286
+ if (Object.hasOwn(node, "rank")) {
287
+ node.rank -= min;
288
+ }
289
+ });
290
+ }
291
+ function removeEmptyRanks(g) {
292
+ let nodeRanks = g.nodes().map((v) => g.node(v).rank);
293
+ let offset = applyWithChunking(Math.min, nodeRanks);
294
+ let layers = [];
295
+ g.nodes().forEach((v) => {
296
+ let rank2 = g.node(v).rank - offset;
297
+ if (!layers[rank2]) {
298
+ layers[rank2] = [];
299
+ }
300
+ layers[rank2].push(v);
301
+ });
302
+ let delta = 0;
303
+ let nodeRankFactor = g.graph().nodeRankFactor;
304
+ Array.from(layers).forEach((vs, i) => {
305
+ if (vs === void 0 && i % nodeRankFactor !== 0) {
306
+ --delta;
307
+ } else if (vs !== void 0 && delta) {
308
+ vs.forEach((v) => g.node(v).rank += delta);
309
+ }
310
+ });
311
+ }
312
+ function addBorderNode(g, prefix, rank2, order2) {
313
+ let node = {
314
+ width: 0,
315
+ height: 0
316
+ };
317
+ if (arguments.length >= 4) {
318
+ node.rank = rank2;
319
+ node.order = order2;
320
+ }
321
+ return addDummyNode(g, "border", node, prefix);
322
+ }
323
+ function splitToChunks(array, chunkSize = CHUNKING_THRESHOLD) {
324
+ const chunks = [];
325
+ for (let i = 0; i < array.length; i += chunkSize) {
326
+ const chunk = array.slice(i, i + chunkSize);
327
+ chunks.push(chunk);
328
+ }
329
+ return chunks;
330
+ }
331
+ var CHUNKING_THRESHOLD = 65535;
332
+ function applyWithChunking(fn, argsArray) {
333
+ if (argsArray.length > CHUNKING_THRESHOLD) {
334
+ const chunks = splitToChunks(argsArray);
335
+ return fn.apply(
336
+ null,
337
+ chunks.map((chunk) => fn.apply(null, chunk))
338
+ );
339
+ } else {
340
+ return fn.apply(null, argsArray);
341
+ }
342
+ }
343
+ function maxRank(g) {
344
+ const nodes = g.nodes();
345
+ const nodeRanks = nodes.map((v) => {
346
+ let rank2 = g.node(v).rank;
347
+ if (rank2 === void 0) {
348
+ return Number.MIN_VALUE;
349
+ }
350
+ return rank2;
351
+ });
352
+ return applyWithChunking(Math.max, nodeRanks);
353
+ }
354
+ function partition(collection, fn) {
355
+ let result = { lhs: [], rhs: [] };
356
+ collection.forEach((value) => {
357
+ if (fn(value)) {
358
+ result.lhs.push(value);
359
+ } else {
360
+ result.rhs.push(value);
361
+ }
362
+ });
363
+ return result;
364
+ }
365
+ function time(name, fn) {
366
+ let start = Date.now();
367
+ try {
368
+ return fn();
369
+ } finally {
370
+ console.log(name + " time: " + (Date.now() - start) + "ms");
371
+ }
372
+ }
373
+ function notime(name, fn) {
374
+ return fn();
375
+ }
376
+ var idCounter = 0;
377
+ function uniqueId(prefix) {
378
+ var id = ++idCounter;
379
+ return toString(prefix) + id;
380
+ }
381
+ function range2(start, limit, step = 1) {
382
+ if (limit == null) {
383
+ limit = start;
384
+ start = 0;
385
+ }
386
+ let endCon = (i) => i < limit;
387
+ if (step < 0) {
388
+ endCon = (i) => limit < i;
389
+ }
390
+ const range3 = [];
391
+ for (let i = start; endCon(i); i += step) {
392
+ range3.push(i);
393
+ }
394
+ return range3;
395
+ }
396
+ function pick(source, keys) {
397
+ const dest = {};
398
+ for (const key of keys) {
399
+ if (source[key] !== void 0) {
400
+ dest[key] = source[key];
401
+ }
402
+ }
403
+ return dest;
404
+ }
405
+ function mapValues(obj, funcOrProp) {
406
+ let func = funcOrProp;
407
+ if (typeof funcOrProp === "string") {
408
+ func = (val) => val[funcOrProp];
409
+ }
410
+ return Object.entries(obj).reduce((acc, [k, v]) => {
411
+ acc[k] = func(v, k);
412
+ return acc;
413
+ }, {});
414
+ }
415
+ function zipObject(props, values) {
416
+ return props.reduce((acc, key, i) => {
417
+ acc[key] = values[i];
418
+ return acc;
419
+ }, {});
420
+ }
421
+
422
+ // src/dagre-lib/acyclic.js
423
+ var acyclic = {
424
+ run,
425
+ undo
426
+ };
427
+ var acyclic_default = acyclic;
428
+ function run(g) {
429
+ let fas = g.graph().acyclicer === "greedy" ? greedy_fas_default(g, weightFn(g)) : dfsFAS(g);
430
+ fas.forEach((e) => {
431
+ let label = g.edge(e);
432
+ g.removeEdge(e);
433
+ label.forwardName = e.name;
434
+ label.reversed = true;
435
+ g.setEdge(e.w, e.v, label, uniqueId("rev"));
436
+ });
437
+ function weightFn(g2) {
438
+ return (e) => {
439
+ return g2.edge(e).weight;
440
+ };
441
+ }
442
+ }
443
+ function dfsFAS(g) {
444
+ let fas = [];
445
+ let stack = {};
446
+ let visited = {};
447
+ function dfs2(v) {
448
+ if (Object.hasOwn(visited, v)) {
449
+ return;
450
+ }
451
+ visited[v] = true;
452
+ stack[v] = true;
453
+ g.outEdges(v).forEach((e) => {
454
+ if (Object.hasOwn(stack, e.w)) {
455
+ fas.push(e);
456
+ } else {
457
+ dfs2(e.w);
458
+ }
459
+ });
460
+ delete stack[v];
461
+ }
462
+ g.nodes().forEach(dfs2);
463
+ return fas;
464
+ }
465
+ function undo(g) {
466
+ g.edges().forEach((e) => {
467
+ let label = g.edge(e);
468
+ if (label.reversed) {
469
+ g.removeEdge(e);
470
+ let forwardName = label.forwardName;
471
+ delete label.reversed;
472
+ delete label.forwardName;
473
+ g.setEdge(e.w, e.v, label, forwardName);
474
+ }
475
+ });
476
+ }
477
+
478
+ // src/dagre-lib/normalize.js
479
+ var normalize = {
480
+ run: run2,
481
+ undo: undo2
482
+ };
483
+ var normalize_default = normalize;
484
+ function run2(g) {
485
+ g.graph().dummyChains = [];
486
+ g.edges().forEach((edge) => normalizeEdge(g, edge));
487
+ }
488
+ function normalizeEdge(g, e) {
489
+ let v = e.v;
490
+ let vRank = g.node(v).rank;
491
+ let w = e.w;
492
+ let wRank = g.node(w).rank;
493
+ let name = e.name;
494
+ let edgeLabel = g.edge(e);
495
+ let labelRank = edgeLabel.labelRank;
496
+ if (wRank === vRank + 1) return;
497
+ g.removeEdge(e);
498
+ let dummy, attrs, i;
499
+ for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) {
500
+ edgeLabel.points = [];
501
+ attrs = {
502
+ width: 0,
503
+ height: 0,
504
+ edgeLabel,
505
+ edgeObj: e,
506
+ rank: vRank
507
+ };
508
+ dummy = util.addDummyNode(g, "edge", attrs, "_d");
509
+ if (vRank === labelRank) {
510
+ attrs.width = edgeLabel.width;
511
+ attrs.height = edgeLabel.height;
512
+ attrs.dummy = "edge-label";
513
+ attrs.labelpos = edgeLabel.labelpos;
514
+ }
515
+ g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);
516
+ if (i === 0) {
517
+ g.graph().dummyChains.push(dummy);
518
+ }
519
+ v = dummy;
520
+ }
521
+ g.setEdge(v, w, { weight: edgeLabel.weight }, name);
522
+ }
523
+ function undo2(g) {
524
+ g.graph().dummyChains.forEach((v) => {
525
+ let node = g.node(v);
526
+ let origLabel = node.edgeLabel;
527
+ let w;
528
+ g.setEdge(node.edgeObj, origLabel);
529
+ while (node.dummy) {
530
+ w = g.successors(v)[0];
531
+ g.removeNode(v);
532
+ origLabel.points.push({ x: node.x, y: node.y });
533
+ if (node.dummy === "edge-label") {
534
+ origLabel.x = node.x;
535
+ origLabel.y = node.y;
536
+ origLabel.width = node.width;
537
+ origLabel.height = node.height;
538
+ }
539
+ v = w;
540
+ node = g.node(v);
541
+ }
542
+ });
543
+ }
544
+
545
+ // src/dagre-lib/rank/util.js
546
+ function longestPath(g) {
547
+ var visited = {};
548
+ function dfs2(v) {
549
+ var label = g.node(v);
550
+ if (Object.hasOwn(visited, v)) {
551
+ return label.rank;
552
+ }
553
+ visited[v] = true;
554
+ let outEdgesMinLens = g.outEdges(v).map((e) => {
555
+ if (e == null) {
556
+ return Number.POSITIVE_INFINITY;
557
+ }
558
+ return dfs2(e.w) - g.edge(e).minlen;
559
+ });
560
+ var rank2 = applyWithChunking(Math.min, outEdgesMinLens);
561
+ if (rank2 === Number.POSITIVE_INFINITY) {
562
+ rank2 = 0;
563
+ }
564
+ return label.rank = rank2;
565
+ }
566
+ g.sources().forEach(dfs2);
567
+ }
568
+ function slack(g, e) {
569
+ return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen;
570
+ }
571
+
572
+ // src/dagre-lib/rank/feasible-tree.js
573
+ import { Graph as Graph3 } from "@dagrejs/graphlib";
574
+ var feasible_tree_default = feasibleTree;
575
+ function feasibleTree(g) {
576
+ var t = new Graph3({ directed: false });
577
+ var start = g.nodes()[0];
578
+ var size = g.nodeCount();
579
+ t.setNode(start, {});
580
+ var edge, delta;
581
+ while (tightTree(t, g) < size) {
582
+ edge = findMinSlackEdge(t, g);
583
+ delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
584
+ shiftRanks(t, g, delta);
585
+ }
586
+ return t;
587
+ }
588
+ function tightTree(t, g) {
589
+ function dfs2(v) {
590
+ g.nodeEdges(v).forEach((e) => {
591
+ var edgeV = e.v, w = v === edgeV ? e.w : edgeV;
592
+ if (!t.hasNode(w) && !slack(g, e)) {
593
+ t.setNode(w, {});
594
+ t.setEdge(v, w, {});
595
+ dfs2(w);
596
+ }
597
+ });
598
+ }
599
+ t.nodes().forEach(dfs2);
600
+ return t.nodeCount();
601
+ }
602
+ function findMinSlackEdge(t, g) {
603
+ const edges = g.edges();
604
+ return edges.reduce(
605
+ (acc, edge) => {
606
+ let edgeSlack = Number.POSITIVE_INFINITY;
607
+ if (t.hasNode(edge.v) !== t.hasNode(edge.w)) {
608
+ edgeSlack = slack(g, edge);
609
+ }
610
+ if (edgeSlack < acc[0]) {
611
+ return [edgeSlack, edge];
612
+ }
613
+ return acc;
614
+ },
615
+ [Number.POSITIVE_INFINITY, null]
616
+ )[1];
617
+ }
618
+ function shiftRanks(t, g, delta) {
619
+ t.nodes().forEach((v) => g.node(v).rank += delta);
620
+ }
621
+
622
+ // src/dagre-lib/rank/network-simplex.js
623
+ import { alg } from "@dagrejs/graphlib";
624
+ var { preorder, postorder } = alg;
625
+ var network_simplex_default = networkSimplex;
626
+ networkSimplex.initLowLimValues = initLowLimValues;
627
+ networkSimplex.initCutValues = initCutValues;
628
+ networkSimplex.calcCutValue = calcCutValue;
629
+ networkSimplex.leaveEdge = leaveEdge;
630
+ networkSimplex.enterEdge = enterEdge;
631
+ networkSimplex.exchangeEdges = exchangeEdges;
632
+ function networkSimplex(g) {
633
+ g = simplify(g);
634
+ longestPath(g);
635
+ var t = feasibleTree(g);
636
+ initLowLimValues(t);
637
+ initCutValues(t, g);
638
+ var e, f;
639
+ while (e = leaveEdge(t)) {
640
+ f = enterEdge(t, g, e);
641
+ exchangeEdges(t, g, e, f);
642
+ }
643
+ }
644
+ function initCutValues(t, g) {
645
+ var vs = postorder(t, t.nodes());
646
+ vs = vs.slice(0, vs.length - 1);
647
+ vs.forEach((v) => assignCutValue(t, g, v));
648
+ }
649
+ function assignCutValue(t, g, child) {
650
+ var childLab = t.node(child);
651
+ var parent = childLab.parent;
652
+ t.edge(child, parent).cutvalue = calcCutValue(t, g, child);
653
+ }
654
+ function calcCutValue(t, g, child) {
655
+ var childLab = t.node(child);
656
+ var parent = childLab.parent;
657
+ var childIsTail = true;
658
+ var graphEdge = g.edge(child, parent);
659
+ var cutValue = 0;
660
+ if (!graphEdge) {
661
+ childIsTail = false;
662
+ graphEdge = g.edge(parent, child);
663
+ }
664
+ cutValue = graphEdge.weight;
665
+ g.nodeEdges(child).forEach((e) => {
666
+ var isOutEdge = e.v === child, other = isOutEdge ? e.w : e.v;
667
+ if (other !== parent) {
668
+ var pointsToHead = isOutEdge === childIsTail, otherWeight = g.edge(e).weight;
669
+ cutValue += pointsToHead ? otherWeight : -otherWeight;
670
+ if (isTreeEdge(t, child, other)) {
671
+ var otherCutValue = t.edge(child, other).cutvalue;
672
+ cutValue += pointsToHead ? -otherCutValue : otherCutValue;
673
+ }
674
+ }
675
+ });
676
+ return cutValue;
677
+ }
678
+ function initLowLimValues(tree, root) {
679
+ if (arguments.length < 2) {
680
+ root = tree.nodes()[0];
681
+ }
682
+ dfsAssignLowLim(tree, {}, 1, root);
683
+ }
684
+ function dfsAssignLowLim(tree, visited, nextLim, v, parent) {
685
+ var low = nextLim;
686
+ var label = tree.node(v);
687
+ visited[v] = true;
688
+ tree.neighbors(v).forEach((w) => {
689
+ if (!Object.hasOwn(visited, w)) {
690
+ nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v);
691
+ }
692
+ });
693
+ label.low = low;
694
+ label.lim = nextLim++;
695
+ if (parent) {
696
+ label.parent = parent;
697
+ } else {
698
+ delete label.parent;
699
+ }
700
+ return nextLim;
701
+ }
702
+ function leaveEdge(tree) {
703
+ return tree.edges().find((e) => tree.edge(e).cutvalue < 0);
704
+ }
705
+ function enterEdge(t, g, edge) {
706
+ var v = edge.v;
707
+ var w = edge.w;
708
+ if (!g.hasEdge(v, w)) {
709
+ v = edge.w;
710
+ w = edge.v;
711
+ }
712
+ var vLabel = t.node(v);
713
+ var wLabel = t.node(w);
714
+ var tailLabel = vLabel;
715
+ var flip = false;
716
+ if (vLabel.lim > wLabel.lim) {
717
+ tailLabel = wLabel;
718
+ flip = true;
719
+ }
720
+ var candidates = g.edges().filter((edge2) => {
721
+ return flip === isDescendant(t, t.node(edge2.v), tailLabel) && flip !== isDescendant(t, t.node(edge2.w), tailLabel);
722
+ });
723
+ return candidates.reduce((acc, edge2) => {
724
+ if (slack(g, edge2) < slack(g, acc)) {
725
+ return edge2;
726
+ }
727
+ return acc;
728
+ });
729
+ }
730
+ function exchangeEdges(t, g, e, f) {
731
+ var v = e.v;
732
+ var w = e.w;
733
+ t.removeEdge(v, w);
734
+ t.setEdge(f.v, f.w, {});
735
+ initLowLimValues(t);
736
+ initCutValues(t, g);
737
+ updateRanks(t, g);
738
+ }
739
+ function updateRanks(t, g) {
740
+ var root = t.nodes().find((v) => !g.node(v).parent);
741
+ var vs = preorder(t, root);
742
+ vs = vs.slice(1);
743
+ vs.forEach((v) => {
744
+ var parent = t.node(v).parent, edge = g.edge(v, parent), flipped = false;
745
+ if (!edge) {
746
+ edge = g.edge(parent, v);
747
+ flipped = true;
748
+ }
749
+ g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen);
750
+ });
751
+ }
752
+ function isTreeEdge(tree, u, v) {
753
+ return tree.hasEdge(u, v);
754
+ }
755
+ function isDescendant(tree, vLabel, rootLabel) {
756
+ return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
757
+ }
758
+
759
+ // src/dagre-lib/rank/index.js
760
+ var rank_default = rank;
761
+ function rank(g) {
762
+ switch (g.graph().ranker) {
763
+ case "network-simplex":
764
+ networkSimplexRanker(g);
765
+ break;
766
+ case "tight-tree":
767
+ tightTreeRanker(g);
768
+ break;
769
+ case "longest-path":
770
+ longestPathRanker(g);
771
+ break;
772
+ default:
773
+ networkSimplexRanker(g);
774
+ }
775
+ }
776
+ var longestPathRanker = longestPath;
777
+ function tightTreeRanker(g) {
778
+ longestPath(g);
779
+ feasible_tree_default(g);
780
+ }
781
+ function networkSimplexRanker(g) {
782
+ network_simplex_default(g);
783
+ }
784
+
785
+ // src/dagre-lib/parent-dummy-chains.js
786
+ var parent_dummy_chains_default = parentDummyChains;
787
+ function parentDummyChains(g) {
788
+ let postorderNums = postorder2(g);
789
+ g.graph().dummyChains.forEach((v) => {
790
+ let node = g.node(v);
791
+ let edgeObj = node.edgeObj;
792
+ let pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);
793
+ let path = pathData.path;
794
+ let lca = pathData.lca;
795
+ let pathIdx = 0;
796
+ let pathV = path[pathIdx];
797
+ let ascending = true;
798
+ while (v !== edgeObj.w) {
799
+ node = g.node(v);
800
+ if (ascending) {
801
+ while ((pathV = path[pathIdx]) !== lca && g.node(pathV).maxRank < node.rank) {
802
+ pathIdx++;
803
+ }
804
+ if (pathV === lca) {
805
+ ascending = false;
806
+ }
807
+ }
808
+ if (!ascending) {
809
+ while (pathIdx < path.length - 1 && g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) {
810
+ pathIdx++;
811
+ }
812
+ pathV = path[pathIdx];
813
+ }
814
+ g.setParent(v, pathV);
815
+ v = g.successors(v)[0];
816
+ }
817
+ });
818
+ }
819
+ function findPath(g, postorderNums, v, w) {
820
+ let vPath = [];
821
+ let wPath = [];
822
+ let low = Math.min(postorderNums[v].low, postorderNums[w].low);
823
+ let lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);
824
+ let parent;
825
+ let lca;
826
+ parent = v;
827
+ do {
828
+ parent = g.parent(parent);
829
+ vPath.push(parent);
830
+ } while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
831
+ lca = parent;
832
+ parent = w;
833
+ while ((parent = g.parent(parent)) !== lca) {
834
+ wPath.push(parent);
835
+ }
836
+ return { path: vPath.concat(wPath.reverse()), lca };
837
+ }
838
+ function postorder2(g) {
839
+ let result = {};
840
+ let lim = 0;
841
+ function dfs2(v) {
842
+ let low = lim;
843
+ g.children(v).forEach(dfs2);
844
+ result[v] = { low, lim: lim++ };
845
+ }
846
+ g.children().forEach(dfs2);
847
+ return result;
848
+ }
849
+
850
+ // src/dagre-lib/nesting-graph.js
851
+ var nestingGraph = {
852
+ run: run3,
853
+ cleanup
854
+ };
855
+ var nesting_graph_default = nestingGraph;
856
+ function run3(g) {
857
+ let root = util.addDummyNode(g, "root", {}, "_root");
858
+ let depths = treeDepths(g);
859
+ let depthsArr = Object.values(depths);
860
+ let height = util.applyWithChunking(Math.max, depthsArr) - 1;
861
+ let nodeSep = 2 * height + 1;
862
+ g.graph().nestingRoot = root;
863
+ g.edges().forEach((e) => g.edge(e).minlen *= nodeSep);
864
+ let weight = sumWeights(g) + 1;
865
+ g.children().forEach((child) => dfs(g, root, nodeSep, weight, height, depths, child));
866
+ g.graph().nodeRankFactor = nodeSep;
867
+ }
868
+ function dfs(g, root, nodeSep, weight, height, depths, v) {
869
+ let children = g.children(v);
870
+ if (!children.length) {
871
+ if (v !== root) {
872
+ g.setEdge(root, v, { weight: 0, minlen: nodeSep });
873
+ }
874
+ return;
875
+ }
876
+ let top = util.addBorderNode(g, "_bt");
877
+ let bottom = util.addBorderNode(g, "_bb");
878
+ let label = g.node(v);
879
+ g.setParent(top, v);
880
+ label.borderTop = top;
881
+ g.setParent(bottom, v);
882
+ label.borderBottom = bottom;
883
+ children.forEach((child) => {
884
+ dfs(g, root, nodeSep, weight, height, depths, child);
885
+ let childNode = g.node(child);
886
+ let childTop = childNode.borderTop ? childNode.borderTop : child;
887
+ let childBottom = childNode.borderBottom ? childNode.borderBottom : child;
888
+ let thisWeight = childNode.borderTop ? weight : 2 * weight;
889
+ let minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;
890
+ g.setEdge(top, childTop, {
891
+ weight: thisWeight,
892
+ minlen,
893
+ nestingEdge: true
894
+ });
895
+ g.setEdge(childBottom, bottom, {
896
+ weight: thisWeight,
897
+ minlen,
898
+ nestingEdge: true
899
+ });
900
+ });
901
+ if (!g.parent(v)) {
902
+ g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
903
+ }
904
+ }
905
+ function treeDepths(g) {
906
+ var depths = {};
907
+ function dfs2(v, depth) {
908
+ var children = g.children(v);
909
+ if (children && children.length) {
910
+ children.forEach((child) => dfs2(child, depth + 1));
911
+ }
912
+ depths[v] = depth;
913
+ }
914
+ g.children().forEach((v) => dfs2(v, 1));
915
+ return depths;
916
+ }
917
+ function sumWeights(g) {
918
+ return g.edges().reduce((acc, e) => acc + g.edge(e).weight, 0);
919
+ }
920
+ function cleanup(g) {
921
+ var graphLabel = g.graph();
922
+ g.removeNode(graphLabel.nestingRoot);
923
+ delete graphLabel.nestingRoot;
924
+ g.edges().forEach((e) => {
925
+ var edge = g.edge(e);
926
+ if (edge.nestingEdge) {
927
+ g.removeEdge(e);
928
+ }
929
+ });
930
+ }
931
+
932
+ // src/dagre-lib/add-border-segments.js
933
+ var add_border_segments_default = addBorderSegments;
934
+ function addBorderSegments(g) {
935
+ function dfs2(v) {
936
+ let children = g.children(v);
937
+ let node = g.node(v);
938
+ if (children.length) {
939
+ children.forEach(dfs2);
940
+ }
941
+ if (Object.hasOwn(node, "minRank")) {
942
+ node.borderLeft = [];
943
+ node.borderRight = [];
944
+ for (let rank2 = node.minRank, maxRank2 = node.maxRank + 1; rank2 < maxRank2; ++rank2) {
945
+ addBorderNode2(g, "borderLeft", "_bl", v, node, rank2);
946
+ addBorderNode2(g, "borderRight", "_br", v, node, rank2);
947
+ }
948
+ }
949
+ }
950
+ g.children().forEach(dfs2);
951
+ }
952
+ function addBorderNode2(g, prop, prefix, sg, sgNode, rank2) {
953
+ let label = { width: 0, height: 0, rank: rank2, borderType: prop };
954
+ let prev = sgNode[prop][rank2 - 1];
955
+ let curr = util.addDummyNode(g, "border", label, prefix);
956
+ sgNode[prop][rank2] = curr;
957
+ g.setParent(curr, sg);
958
+ if (prev) {
959
+ g.setEdge(prev, curr, { weight: 1 });
960
+ }
961
+ }
962
+
963
+ // src/dagre-lib/coordinate-system.js
964
+ var coordinateSystem = {
965
+ adjust,
966
+ undo: undo3
967
+ };
968
+ var coordinate_system_default = coordinateSystem;
969
+ function adjust(g) {
970
+ let rankDir = g.graph().rankdir.toLowerCase();
971
+ if (rankDir === "lr" || rankDir === "rl") {
972
+ swapWidthHeight(g);
973
+ }
974
+ }
975
+ function undo3(g) {
976
+ let rankDir = g.graph().rankdir.toLowerCase();
977
+ if (rankDir === "bt" || rankDir === "rl") {
978
+ reverseY(g);
979
+ }
980
+ if (rankDir === "lr" || rankDir === "rl") {
981
+ swapXY(g);
982
+ swapWidthHeight(g);
983
+ }
984
+ }
985
+ function swapWidthHeight(g) {
986
+ g.nodes().forEach((v) => swapWidthHeightOne(g.node(v)));
987
+ g.edges().forEach((e) => swapWidthHeightOne(g.edge(e)));
988
+ }
989
+ function swapWidthHeightOne(attrs) {
990
+ let w = attrs.width;
991
+ attrs.width = attrs.height;
992
+ attrs.height = w;
993
+ }
994
+ function reverseY(g) {
995
+ g.nodes().forEach((v) => reverseYOne(g.node(v)));
996
+ g.edges().forEach((e) => {
997
+ let edge = g.edge(e);
998
+ edge.points.forEach(reverseYOne);
999
+ if (Object.hasOwn(edge, "y")) {
1000
+ reverseYOne(edge);
1001
+ }
1002
+ });
1003
+ }
1004
+ function reverseYOne(attrs) {
1005
+ attrs.y = -attrs.y;
1006
+ }
1007
+ function swapXY(g) {
1008
+ g.nodes().forEach((v) => swapXYOne(g.node(v)));
1009
+ g.edges().forEach((e) => {
1010
+ let edge = g.edge(e);
1011
+ edge.points.forEach(swapXYOne);
1012
+ if (Object.hasOwn(edge, "x")) {
1013
+ swapXYOne(edge);
1014
+ }
1015
+ });
1016
+ }
1017
+ function swapXYOne(attrs) {
1018
+ let x = attrs.x;
1019
+ attrs.x = attrs.y;
1020
+ attrs.y = x;
1021
+ }
1022
+
1023
+ // src/dagre-lib/order/init-order.js
1024
+ var init_order_default = initOrder;
1025
+ function initOrder(g) {
1026
+ let visited = {};
1027
+ let simpleNodes = g.nodes().filter((v) => !g.children(v).length);
1028
+ let simpleNodesRanks = simpleNodes.map((v) => g.node(v).rank);
1029
+ let maxRank2 = util.applyWithChunking(Math.max, simpleNodesRanks);
1030
+ let layers = util.range(maxRank2 + 1).map(() => []);
1031
+ function dfs2(v) {
1032
+ if (visited[v]) return;
1033
+ visited[v] = true;
1034
+ let node = g.node(v);
1035
+ layers[node.rank].push(v);
1036
+ g.successors(v).forEach(dfs2);
1037
+ }
1038
+ let orderedVs = simpleNodes.sort((a, b) => g.node(a).rank - g.node(b).rank);
1039
+ orderedVs.forEach(dfs2);
1040
+ return layers;
1041
+ }
1042
+
1043
+ // src/dagre-lib/order/cross-count.js
1044
+ var cross_count_default = crossCount;
1045
+ function crossCount(g, layering) {
1046
+ let cc = 0;
1047
+ for (let i = 1; i < layering.length; ++i) {
1048
+ cc += twoLayerCrossCount(g, layering[i - 1], layering[i]);
1049
+ }
1050
+ return cc;
1051
+ }
1052
+ function twoLayerCrossCount(g, northLayer, southLayer) {
1053
+ let southPos = zipObject(
1054
+ southLayer,
1055
+ southLayer.map((v, i) => i)
1056
+ );
1057
+ let southEntries = northLayer.flatMap((v) => {
1058
+ return g.outEdges(v).map((e) => {
1059
+ return { pos: southPos[e.w], weight: g.edge(e).weight };
1060
+ }).sort((a, b) => a.pos - b.pos);
1061
+ });
1062
+ let firstIndex = 1;
1063
+ while (firstIndex < southLayer.length) firstIndex <<= 1;
1064
+ let treeSize = 2 * firstIndex - 1;
1065
+ firstIndex -= 1;
1066
+ let tree = new Array(treeSize).fill(0);
1067
+ let cc = 0;
1068
+ southEntries.forEach((entry) => {
1069
+ let index = entry.pos + firstIndex;
1070
+ tree[index] += entry.weight;
1071
+ let weightSum = 0;
1072
+ while (index > 0) {
1073
+ if (index % 2) {
1074
+ weightSum += tree[index + 1];
1075
+ }
1076
+ index = index - 1 >> 1;
1077
+ tree[index] += entry.weight;
1078
+ }
1079
+ cc += entry.weight * weightSum;
1080
+ });
1081
+ return cc;
1082
+ }
1083
+
1084
+ // src/dagre-lib/order/barycenter.js
1085
+ var barycenter_default = barycenter;
1086
+ function barycenter(g, movable = []) {
1087
+ return movable.map((v) => {
1088
+ let inV = g.inEdges(v);
1089
+ if (!inV.length) {
1090
+ return { v };
1091
+ } else {
1092
+ let result = inV.reduce(
1093
+ (acc, e) => {
1094
+ let edge = g.edge(e), nodeU = g.node(e.v);
1095
+ return {
1096
+ sum: acc.sum + edge.weight * nodeU.order,
1097
+ weight: acc.weight + edge.weight
1098
+ };
1099
+ },
1100
+ { sum: 0, weight: 0 }
1101
+ );
1102
+ return {
1103
+ v,
1104
+ barycenter: result.sum / result.weight,
1105
+ weight: result.weight
1106
+ };
1107
+ }
1108
+ });
1109
+ }
1110
+
1111
+ // src/dagre-lib/order/resolve-conflicts.js
1112
+ var resolve_conflicts_default = resolveConflicts;
1113
+ function resolveConflicts(entries, cg) {
1114
+ let mappedEntries = {};
1115
+ entries.forEach((entry, i) => {
1116
+ let tmp = mappedEntries[entry.v] = {
1117
+ indegree: 0,
1118
+ in: [],
1119
+ out: [],
1120
+ vs: [entry.v],
1121
+ i
1122
+ };
1123
+ if (entry.barycenter !== void 0) {
1124
+ tmp.barycenter = entry.barycenter;
1125
+ tmp.weight = entry.weight;
1126
+ }
1127
+ });
1128
+ cg.edges().forEach((e) => {
1129
+ let entryV = mappedEntries[e.v];
1130
+ let entryW = mappedEntries[e.w];
1131
+ if (entryV !== void 0 && entryW !== void 0) {
1132
+ entryW.indegree++;
1133
+ entryV.out.push(mappedEntries[e.w]);
1134
+ }
1135
+ });
1136
+ let sourceSet = Object.values(mappedEntries).filter((entry) => !entry.indegree);
1137
+ return doResolveConflicts(sourceSet);
1138
+ }
1139
+ function doResolveConflicts(sourceSet) {
1140
+ let entries = [];
1141
+ function handleIn(vEntry) {
1142
+ return (uEntry) => {
1143
+ if (uEntry.merged) {
1144
+ return;
1145
+ }
1146
+ if (uEntry.barycenter === void 0 || vEntry.barycenter === void 0 || uEntry.barycenter >= vEntry.barycenter) {
1147
+ mergeEntries(vEntry, uEntry);
1148
+ }
1149
+ };
1150
+ }
1151
+ function handleOut(vEntry) {
1152
+ return (wEntry) => {
1153
+ wEntry["in"].push(vEntry);
1154
+ if (--wEntry.indegree === 0) {
1155
+ sourceSet.push(wEntry);
1156
+ }
1157
+ };
1158
+ }
1159
+ while (sourceSet.length) {
1160
+ let entry = sourceSet.pop();
1161
+ entries.push(entry);
1162
+ entry["in"].reverse().forEach(handleIn(entry));
1163
+ entry.out.forEach(handleOut(entry));
1164
+ }
1165
+ return entries.filter((entry) => !entry.merged).map((entry) => {
1166
+ return util_default.pick(entry, ["vs", "i", "barycenter", "weight"]);
1167
+ });
1168
+ }
1169
+ function mergeEntries(target, source) {
1170
+ let sum = 0;
1171
+ let weight = 0;
1172
+ if (target.weight) {
1173
+ sum += target.barycenter * target.weight;
1174
+ weight += target.weight;
1175
+ }
1176
+ if (source.weight) {
1177
+ sum += source.barycenter * source.weight;
1178
+ weight += source.weight;
1179
+ }
1180
+ target.vs = source.vs.concat(target.vs);
1181
+ target.barycenter = sum / weight;
1182
+ target.weight = weight;
1183
+ target.i = Math.min(source.i, target.i);
1184
+ source.merged = true;
1185
+ }
1186
+
1187
+ // src/dagre-lib/order/sort.js
1188
+ var sort_default = sort;
1189
+ function sort(entries, biasRight) {
1190
+ let parts = util_default.partition(entries, (entry) => {
1191
+ return Object.hasOwn(entry, "barycenter");
1192
+ });
1193
+ let sortable = parts.lhs, unsortable = parts.rhs.sort((a, b) => b.i - a.i), vs = [], sum = 0, weight = 0, vsIndex = 0;
1194
+ sortable.sort(compareWithBias(!!biasRight));
1195
+ vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
1196
+ sortable.forEach((entry) => {
1197
+ vsIndex += entry.vs.length;
1198
+ vs.push(entry.vs);
1199
+ sum += entry.barycenter * entry.weight;
1200
+ weight += entry.weight;
1201
+ vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
1202
+ });
1203
+ let result = { vs: vs.flat(true) };
1204
+ if (weight) {
1205
+ result.barycenter = sum / weight;
1206
+ result.weight = weight;
1207
+ }
1208
+ return result;
1209
+ }
1210
+ function consumeUnsortable(vs, unsortable, index) {
1211
+ let last;
1212
+ while (unsortable.length && (last = unsortable[unsortable.length - 1]).i <= index) {
1213
+ unsortable.pop();
1214
+ vs.push(last.vs);
1215
+ index++;
1216
+ }
1217
+ return index;
1218
+ }
1219
+ function compareWithBias(bias) {
1220
+ return (entryV, entryW) => {
1221
+ if (entryV.barycenter < entryW.barycenter) {
1222
+ return -1;
1223
+ } else if (entryV.barycenter > entryW.barycenter) {
1224
+ return 1;
1225
+ }
1226
+ return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
1227
+ };
1228
+ }
1229
+
1230
+ // src/dagre-lib/order/sort-subgraph.js
1231
+ var sort_subgraph_default = sortSubgraph;
1232
+ function sortSubgraph(g, v, cg, biasRight) {
1233
+ let movable = g.children(v);
1234
+ let node = g.node(v);
1235
+ let bl = node ? node.borderLeft : void 0;
1236
+ let br = node ? node.borderRight : void 0;
1237
+ let subgraphs = {};
1238
+ if (bl) {
1239
+ movable = movable.filter((w) => w !== bl && w !== br);
1240
+ }
1241
+ let barycenters = barycenter_default(g, movable);
1242
+ barycenters.forEach((entry) => {
1243
+ if (g.children(entry.v).length) {
1244
+ let subgraphResult = sortSubgraph(g, entry.v, cg, biasRight);
1245
+ subgraphs[entry.v] = subgraphResult;
1246
+ if (Object.hasOwn(subgraphResult, "barycenter")) {
1247
+ mergeBarycenters(entry, subgraphResult);
1248
+ }
1249
+ }
1250
+ });
1251
+ let entries = resolve_conflicts_default(barycenters, cg);
1252
+ expandSubgraphs(entries, subgraphs);
1253
+ let result = sort_default(entries, biasRight);
1254
+ if (bl) {
1255
+ result.vs = [bl, result.vs, br].flat(true);
1256
+ if (g.predecessors(bl).length) {
1257
+ let blPred = g.node(g.predecessors(bl)[0]), brPred = g.node(g.predecessors(br)[0]);
1258
+ if (!Object.hasOwn(result, "barycenter")) {
1259
+ result.barycenter = 0;
1260
+ result.weight = 0;
1261
+ }
1262
+ result.barycenter = (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2);
1263
+ result.weight += 2;
1264
+ }
1265
+ }
1266
+ return result;
1267
+ }
1268
+ function expandSubgraphs(entries, subgraphs) {
1269
+ entries.forEach((entry) => {
1270
+ entry.vs = entry.vs.flatMap((v) => {
1271
+ if (subgraphs[v]) {
1272
+ return subgraphs[v].vs;
1273
+ }
1274
+ return v;
1275
+ });
1276
+ });
1277
+ }
1278
+ function mergeBarycenters(target, other) {
1279
+ if (target.barycenter !== void 0) {
1280
+ target.barycenter = (target.barycenter * target.weight + other.barycenter * other.weight) / (target.weight + other.weight);
1281
+ target.weight += other.weight;
1282
+ } else {
1283
+ target.barycenter = other.barycenter;
1284
+ target.weight = other.weight;
1285
+ }
1286
+ }
1287
+
1288
+ // src/dagre-lib/order/build-layer-graph.js
1289
+ import { Graph as Graph4 } from "@dagrejs/graphlib";
1290
+ var build_layer_graph_default = buildLayerGraph;
1291
+ function buildLayerGraph(g, rank2, relationship) {
1292
+ let root = createRootNode(g), result = new Graph4({ compound: true }).setGraph({ root }).setDefaultNodeLabel((v) => g.node(v));
1293
+ g.nodes().forEach((v) => {
1294
+ let node = g.node(v), parent = g.parent(v);
1295
+ if (node.rank === rank2 || node.minRank <= rank2 && rank2 <= node.maxRank) {
1296
+ result.setNode(v);
1297
+ result.setParent(v, parent || root);
1298
+ g[relationship](v).forEach((e) => {
1299
+ let u = e.v === v ? e.w : e.v, edge = result.edge(u, v), weight = edge !== void 0 ? edge.weight : 0;
1300
+ result.setEdge(u, v, { weight: g.edge(e).weight + weight });
1301
+ });
1302
+ if (Object.hasOwn(node, "minRank")) {
1303
+ result.setNode(v, {
1304
+ borderLeft: node.borderLeft[rank2],
1305
+ borderRight: node.borderRight[rank2]
1306
+ });
1307
+ }
1308
+ }
1309
+ });
1310
+ return result;
1311
+ }
1312
+ function createRootNode(g) {
1313
+ var v;
1314
+ while (g.hasNode(v = util.uniqueId("_root"))) ;
1315
+ return v;
1316
+ }
1317
+
1318
+ // src/dagre-lib/order/add-subgraph-constraints.js
1319
+ var add_subgraph_constraints_default = addSubgraphConstraints;
1320
+ function addSubgraphConstraints(g, cg, vs) {
1321
+ let prev = {}, rootPrev;
1322
+ vs.forEach((v) => {
1323
+ let child = g.parent(v), parent, prevChild;
1324
+ while (child) {
1325
+ parent = g.parent(child);
1326
+ if (parent) {
1327
+ prevChild = prev[parent];
1328
+ prev[parent] = child;
1329
+ } else {
1330
+ prevChild = rootPrev;
1331
+ rootPrev = child;
1332
+ }
1333
+ if (prevChild && prevChild !== child) {
1334
+ cg.setEdge(prevChild, child);
1335
+ return;
1336
+ }
1337
+ child = parent;
1338
+ }
1339
+ });
1340
+ }
1341
+
1342
+ // src/dagre-lib/order/index.js
1343
+ import { Graph as Graph5 } from "@dagrejs/graphlib";
1344
+ var order_default = order;
1345
+ function order(g, opts) {
1346
+ if (opts && typeof opts.customOrder === "function") {
1347
+ opts.customOrder(g, order);
1348
+ return;
1349
+ }
1350
+ let maxRank2 = util.maxRank(g), downLayerGraphs = buildLayerGraphs(g, util.range(1, maxRank2 + 1), "inEdges"), upLayerGraphs = buildLayerGraphs(g, util.range(maxRank2 - 1, -1, -1), "outEdges");
1351
+ let layering = init_order_default(g);
1352
+ assignOrder(g, layering);
1353
+ if (opts && opts.disableOptimalOrderHeuristic) {
1354
+ return;
1355
+ }
1356
+ let bestCC = Number.POSITIVE_INFINITY, best;
1357
+ for (let i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
1358
+ sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
1359
+ layering = util.buildLayerMatrix(g);
1360
+ let cc = cross_count_default(g, layering);
1361
+ if (cc < bestCC) {
1362
+ lastBest = 0;
1363
+ best = Object.assign({}, layering);
1364
+ bestCC = cc;
1365
+ }
1366
+ }
1367
+ assignOrder(g, best);
1368
+ }
1369
+ function buildLayerGraphs(g, ranks, relationship) {
1370
+ return ranks.map(function(rank2) {
1371
+ return build_layer_graph_default(g, rank2, relationship);
1372
+ });
1373
+ }
1374
+ function sweepLayerGraphs(layerGraphs, biasRight) {
1375
+ let cg = new Graph5();
1376
+ layerGraphs.forEach(function(lg) {
1377
+ let root = lg.graph().root;
1378
+ let sorted = sort_subgraph_default(lg, root, cg, biasRight);
1379
+ sorted.vs.forEach((v, i) => lg.node(v).order = i);
1380
+ add_subgraph_constraints_default(lg, cg, sorted.vs);
1381
+ });
1382
+ }
1383
+ function assignOrder(g, layering) {
1384
+ Object.values(layering).forEach((layer) => layer.forEach((v, i) => g.node(v).order = i));
1385
+ }
1386
+
1387
+ // src/dagre-lib/position/bk.js
1388
+ import { Graph as Graph6 } from "@dagrejs/graphlib";
1389
+ function findType1Conflicts(g, layering) {
1390
+ let conflicts = {};
1391
+ function visitLayer(prevLayer, layer) {
1392
+ let k0 = 0, scanPos = 0, prevLayerLength = prevLayer.length, lastNode = layer[layer.length - 1];
1393
+ layer.forEach((v, i) => {
1394
+ let w = findOtherInnerSegmentNode(g, v), k1 = w ? g.node(w).order : prevLayerLength;
1395
+ if (w || v === lastNode) {
1396
+ layer.slice(scanPos, i + 1).forEach((scanNode) => {
1397
+ g.predecessors(scanNode).forEach((u) => {
1398
+ let uLabel = g.node(u), uPos = uLabel.order;
1399
+ if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g.node(scanNode).dummy)) {
1400
+ addConflict(conflicts, u, scanNode);
1401
+ }
1402
+ });
1403
+ });
1404
+ scanPos = i + 1;
1405
+ k0 = k1;
1406
+ }
1407
+ });
1408
+ return layer;
1409
+ }
1410
+ layering.length && layering.reduce(visitLayer);
1411
+ return conflicts;
1412
+ }
1413
+ function findType2Conflicts(g, layering) {
1414
+ let conflicts = {};
1415
+ function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {
1416
+ let v;
1417
+ util.range(southPos, southEnd).forEach((i) => {
1418
+ v = south[i];
1419
+ if (g.node(v).dummy) {
1420
+ g.predecessors(v).forEach((u) => {
1421
+ let uNode = g.node(u);
1422
+ if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
1423
+ addConflict(conflicts, u, v);
1424
+ }
1425
+ });
1426
+ }
1427
+ });
1428
+ }
1429
+ function visitLayer(north, south) {
1430
+ let prevNorthPos = -1, nextNorthPos, southPos = 0;
1431
+ south.forEach((v, southLookahead) => {
1432
+ if (g.node(v).dummy === "border") {
1433
+ let predecessors = g.predecessors(v);
1434
+ if (predecessors.length) {
1435
+ nextNorthPos = g.node(predecessors[0]).order;
1436
+ scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
1437
+ southPos = southLookahead;
1438
+ prevNorthPos = nextNorthPos;
1439
+ }
1440
+ }
1441
+ scan(south, southPos, south.length, nextNorthPos, north.length);
1442
+ });
1443
+ return south;
1444
+ }
1445
+ layering.length && layering.reduce(visitLayer);
1446
+ return conflicts;
1447
+ }
1448
+ function findOtherInnerSegmentNode(g, v) {
1449
+ if (g.node(v).dummy) {
1450
+ return g.predecessors(v).find((u) => g.node(u).dummy);
1451
+ }
1452
+ }
1453
+ function addConflict(conflicts, v, w) {
1454
+ if (v > w) {
1455
+ let tmp = v;
1456
+ v = w;
1457
+ w = tmp;
1458
+ }
1459
+ let conflictsV = conflicts[v];
1460
+ if (!conflictsV) {
1461
+ conflicts[v] = conflictsV = {};
1462
+ }
1463
+ conflictsV[w] = true;
1464
+ }
1465
+ function hasConflict(conflicts, v, w) {
1466
+ if (v > w) {
1467
+ let tmp = v;
1468
+ v = w;
1469
+ w = tmp;
1470
+ }
1471
+ return !!conflicts[v] && Object.hasOwn(conflicts[v], w);
1472
+ }
1473
+ function verticalAlignment(g, layering, conflicts, neighborFn) {
1474
+ let root = {}, align = {}, pos = {};
1475
+ layering.forEach((layer) => {
1476
+ layer.forEach((v, order2) => {
1477
+ root[v] = v;
1478
+ align[v] = v;
1479
+ pos[v] = order2;
1480
+ });
1481
+ });
1482
+ layering.forEach((layer) => {
1483
+ let prevIdx = -1;
1484
+ layer.forEach((v) => {
1485
+ let ws = neighborFn(v);
1486
+ if (ws.length) {
1487
+ ws = ws.sort((a, b) => pos[a] - pos[b]);
1488
+ let mp = (ws.length - 1) / 2;
1489
+ for (let i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {
1490
+ let w = ws[i];
1491
+ if (align[v] === v && prevIdx < pos[w] && !hasConflict(conflicts, v, w)) {
1492
+ align[w] = v;
1493
+ align[v] = root[v] = root[w];
1494
+ prevIdx = pos[w];
1495
+ }
1496
+ }
1497
+ }
1498
+ });
1499
+ });
1500
+ return { root, align };
1501
+ }
1502
+ function horizontalCompaction(g, layering, root, align, reverseSep) {
1503
+ let xs = {}, blockG = buildBlockGraph(g, layering, root, reverseSep), borderType = reverseSep ? "borderLeft" : "borderRight";
1504
+ function iterate(setXsFunc, nextNodesFunc) {
1505
+ let stack = blockG.nodes();
1506
+ let elem = stack.pop();
1507
+ let visited = {};
1508
+ while (elem) {
1509
+ if (visited[elem]) {
1510
+ setXsFunc(elem);
1511
+ } else {
1512
+ visited[elem] = true;
1513
+ stack.push(elem);
1514
+ stack = stack.concat(nextNodesFunc(elem));
1515
+ }
1516
+ elem = stack.pop();
1517
+ }
1518
+ }
1519
+ function pass1(elem) {
1520
+ xs[elem] = blockG.inEdges(elem).reduce((acc, e) => {
1521
+ return Math.max(acc, xs[e.v] + blockG.edge(e));
1522
+ }, 0);
1523
+ }
1524
+ function pass2(elem) {
1525
+ let min = blockG.outEdges(elem).reduce((acc, e) => {
1526
+ return Math.min(acc, xs[e.w] - blockG.edge(e));
1527
+ }, Number.POSITIVE_INFINITY);
1528
+ let node = g.node(elem);
1529
+ if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
1530
+ xs[elem] = Math.max(xs[elem], min);
1531
+ }
1532
+ }
1533
+ iterate(pass1, blockG.predecessors.bind(blockG));
1534
+ iterate(pass2, blockG.successors.bind(blockG));
1535
+ Object.keys(align).forEach((v) => xs[v] = xs[root[v]]);
1536
+ return xs;
1537
+ }
1538
+ function buildBlockGraph(g, layering, root, reverseSep) {
1539
+ let blockGraph = new Graph6(), graphLabel = g.graph(), sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep);
1540
+ layering.forEach((layer) => {
1541
+ let u;
1542
+ layer.forEach((v) => {
1543
+ let vRoot = root[v];
1544
+ blockGraph.setNode(vRoot);
1545
+ if (u) {
1546
+ var uRoot = root[u], prevMax = blockGraph.edge(uRoot, vRoot);
1547
+ blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0));
1548
+ }
1549
+ u = v;
1550
+ });
1551
+ });
1552
+ return blockGraph;
1553
+ }
1554
+ function findSmallestWidthAlignment(g, xss) {
1555
+ return Object.values(xss).reduce(
1556
+ (currentMinAndXs, xs) => {
1557
+ let max = Number.NEGATIVE_INFINITY;
1558
+ let min = Number.POSITIVE_INFINITY;
1559
+ Object.entries(xs).forEach(([v, x]) => {
1560
+ let halfWidth = width(g, v) / 2;
1561
+ max = Math.max(x + halfWidth, max);
1562
+ min = Math.min(x - halfWidth, min);
1563
+ });
1564
+ const newMin = max - min;
1565
+ if (newMin < currentMinAndXs[0]) {
1566
+ currentMinAndXs = [newMin, xs];
1567
+ }
1568
+ return currentMinAndXs;
1569
+ },
1570
+ [Number.POSITIVE_INFINITY, null]
1571
+ )[1];
1572
+ }
1573
+ function alignCoordinates(xss, alignTo) {
1574
+ let alignToVals = Object.values(alignTo), alignToMin = util.applyWithChunking(Math.min, alignToVals), alignToMax = util.applyWithChunking(Math.max, alignToVals);
1575
+ ["u", "d"].forEach((vert) => {
1576
+ ["l", "r"].forEach((horiz) => {
1577
+ let alignment = vert + horiz, xs = xss[alignment];
1578
+ if (xs === alignTo) return;
1579
+ let xsVals = Object.values(xs);
1580
+ let delta = alignToMin - util.applyWithChunking(Math.min, xsVals);
1581
+ if (horiz !== "l") {
1582
+ delta = alignToMax - util.applyWithChunking(Math.max, xsVals);
1583
+ }
1584
+ if (delta) {
1585
+ xss[alignment] = util.mapValues(xs, (x) => x + delta);
1586
+ }
1587
+ });
1588
+ });
1589
+ }
1590
+ function balance(xss, align) {
1591
+ return util.mapValues(xss.ul, (num, v) => {
1592
+ if (align) {
1593
+ return xss[align.toLowerCase()][v];
1594
+ } else {
1595
+ let xs = Object.values(xss).map((xs2) => xs2[v]).sort((a, b) => a - b);
1596
+ return (xs[1] + xs[2]) / 2;
1597
+ }
1598
+ });
1599
+ }
1600
+ function positionX(g) {
1601
+ let layering = util.buildLayerMatrix(g);
1602
+ let conflicts = Object.assign(findType1Conflicts(g, layering), findType2Conflicts(g, layering));
1603
+ let xss = {};
1604
+ let adjustedLayering;
1605
+ ["u", "d"].forEach((vert) => {
1606
+ adjustedLayering = vert === "u" ? layering : Object.values(layering).reverse();
1607
+ ["l", "r"].forEach((horiz) => {
1608
+ if (horiz === "r") {
1609
+ adjustedLayering = adjustedLayering.map((inner) => {
1610
+ return Object.values(inner).reverse();
1611
+ });
1612
+ }
1613
+ let neighborFn = (vert === "u" ? g.predecessors : g.successors).bind(g);
1614
+ let align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);
1615
+ let xs = horizontalCompaction(g, adjustedLayering, align.root, align.align, horiz === "r");
1616
+ if (horiz === "r") {
1617
+ xs = util.mapValues(xs, (x) => -x);
1618
+ }
1619
+ xss[vert + horiz] = xs;
1620
+ });
1621
+ });
1622
+ let smallestWidth = findSmallestWidthAlignment(g, xss);
1623
+ alignCoordinates(xss, smallestWidth);
1624
+ return balance(xss, g.graph().align);
1625
+ }
1626
+ function sep(nodeSep, edgeSep, reverseSep) {
1627
+ return (g, v, w) => {
1628
+ let vLabel = g.node(v);
1629
+ let wLabel = g.node(w);
1630
+ let sum = 0;
1631
+ let delta;
1632
+ sum += vLabel.width / 2;
1633
+ if (Object.hasOwn(vLabel, "labelpos")) {
1634
+ switch (vLabel.labelpos.toLowerCase()) {
1635
+ case "l":
1636
+ delta = -vLabel.width / 2;
1637
+ break;
1638
+ case "r":
1639
+ delta = vLabel.width / 2;
1640
+ break;
1641
+ }
1642
+ }
1643
+ if (delta) {
1644
+ sum += reverseSep ? delta : -delta;
1645
+ }
1646
+ delta = 0;
1647
+ sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
1648
+ sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
1649
+ sum += wLabel.width / 2;
1650
+ if (Object.hasOwn(wLabel, "labelpos")) {
1651
+ switch (wLabel.labelpos.toLowerCase()) {
1652
+ case "l":
1653
+ delta = wLabel.width / 2;
1654
+ break;
1655
+ case "r":
1656
+ delta = -wLabel.width / 2;
1657
+ break;
1658
+ }
1659
+ }
1660
+ if (delta) {
1661
+ sum += reverseSep ? delta : -delta;
1662
+ }
1663
+ delta = 0;
1664
+ return sum;
1665
+ };
1666
+ }
1667
+ function width(g, v) {
1668
+ return g.node(v).width;
1669
+ }
1670
+
1671
+ // src/dagre-lib/position/index.js
1672
+ var position_default = position;
1673
+ function position(g) {
1674
+ g = util_default.asNonCompoundGraph(g);
1675
+ positionY(g);
1676
+ Object.entries(positionX(g)).forEach(([v, x]) => g.node(v).x = x);
1677
+ }
1678
+ function positionY(g) {
1679
+ let layering = util_default.buildLayerMatrix(g);
1680
+ let rankSep = g.graph().ranksep;
1681
+ let prevY = 0;
1682
+ layering.forEach((layer) => {
1683
+ const maxHeight = layer.reduce((acc, v) => {
1684
+ const height = g.node(v).height;
1685
+ if (acc > height) {
1686
+ return acc;
1687
+ } else {
1688
+ return height;
1689
+ }
1690
+ }, 0);
1691
+ layer.forEach((v) => g.node(v).y = prevY + maxHeight / 2);
1692
+ prevY += maxHeight + rankSep;
1693
+ });
1694
+ }
1695
+
1696
+ // src/dagre-lib/layout.js
1697
+ import { Graph as Graph7 } from "@dagrejs/graphlib";
1698
+ function layout(g, opts) {
1699
+ let time2 = opts && opts.debugTiming ? util.time : util.notime;
1700
+ time2("layout", () => {
1701
+ let layoutGraph = time2(" buildLayoutGraph", () => buildLayoutGraph(g));
1702
+ time2(" runLayout", () => runLayout(layoutGraph, time2, opts));
1703
+ time2(" updateInputGraph", () => updateInputGraph(g, layoutGraph));
1704
+ });
1705
+ }
1706
+ function runLayout(g, time2, opts) {
1707
+ time2(" makeSpaceForEdgeLabels", () => makeSpaceForEdgeLabels(g));
1708
+ time2(" removeSelfEdges", () => removeSelfEdges(g));
1709
+ time2(" acyclic", () => acyclic_default.run(g));
1710
+ time2(" nestingGraph.run", () => nesting_graph_default.run(g));
1711
+ time2(" rank", () => rank_default(util.asNonCompoundGraph(g)));
1712
+ time2(" injectEdgeLabelProxies", () => injectEdgeLabelProxies(g));
1713
+ time2(" removeEmptyRanks", () => removeEmptyRanks(g));
1714
+ time2(" nestingGraph.cleanup", () => nesting_graph_default.cleanup(g));
1715
+ time2(" normalizeRanks", () => normalizeRanks(g));
1716
+ time2(" assignRankMinMax", () => assignRankMinMax(g));
1717
+ time2(" removeEdgeLabelProxies", () => removeEdgeLabelProxies(g));
1718
+ time2(" normalize.run", () => normalize_default.run(g));
1719
+ time2(" parentDummyChains", () => parent_dummy_chains_default(g));
1720
+ time2(" addBorderSegments", () => add_border_segments_default(g));
1721
+ time2(" order", () => order_default(g, opts));
1722
+ time2(" insertSelfEdges", () => insertSelfEdges(g));
1723
+ time2(" adjustCoordinateSystem", () => coordinate_system_default.adjust(g));
1724
+ time2(" position", () => position_default(g));
1725
+ time2(" positionSelfEdges", () => positionSelfEdges(g));
1726
+ time2(" removeBorderNodes", () => removeBorderNodes(g));
1727
+ time2(" normalize.undo", () => normalize_default.undo(g));
1728
+ time2(" fixupEdgeLabelCoords", () => fixupEdgeLabelCoords(g));
1729
+ time2(" undoCoordinateSystem", () => coordinate_system_default.undo(g));
1730
+ time2(" translateGraph", () => translateGraph(g));
1731
+ time2(" assignNodeIntersects", () => assignNodeIntersects(g));
1732
+ time2(" reversePoints", () => reversePointsForReversedEdges(g));
1733
+ time2(" acyclic.undo", () => acyclic_default.undo(g));
1734
+ }
1735
+ function updateInputGraph(inputGraph, layoutGraph) {
1736
+ inputGraph.nodes().forEach((v) => {
1737
+ let inputLabel = inputGraph.node(v);
1738
+ let layoutLabel = layoutGraph.node(v);
1739
+ if (inputLabel) {
1740
+ inputLabel.x = layoutLabel.x;
1741
+ inputLabel.y = layoutLabel.y;
1742
+ inputLabel.rank = layoutLabel.rank;
1743
+ if (layoutGraph.children(v).length) {
1744
+ inputLabel.width = layoutLabel.width;
1745
+ inputLabel.height = layoutLabel.height;
1746
+ }
1747
+ }
1748
+ });
1749
+ inputGraph.edges().forEach((e) => {
1750
+ let inputLabel = inputGraph.edge(e);
1751
+ let layoutLabel = layoutGraph.edge(e);
1752
+ inputLabel.points = layoutLabel.points;
1753
+ if (Object.hasOwn(layoutLabel, "x")) {
1754
+ inputLabel.x = layoutLabel.x;
1755
+ inputLabel.y = layoutLabel.y;
1756
+ }
1757
+ });
1758
+ inputGraph.graph().width = layoutGraph.graph().width;
1759
+ inputGraph.graph().height = layoutGraph.graph().height;
1760
+ }
1761
+ var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"];
1762
+ var graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" };
1763
+ var graphAttrs = ["acyclicer", "ranker", "rankdir", "align"];
1764
+ var nodeNumAttrs = ["width", "height"];
1765
+ var nodeDefaults = { width: 0, height: 0 };
1766
+ var edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"];
1767
+ var edgeDefaults = {
1768
+ minlen: 1,
1769
+ weight: 1,
1770
+ width: 0,
1771
+ height: 0,
1772
+ labeloffset: 10,
1773
+ labelpos: "r"
1774
+ };
1775
+ var edgeAttrs = ["labelpos"];
1776
+ function buildLayoutGraph(inputGraph) {
1777
+ let g = new Graph7({ multigraph: true, compound: true });
1778
+ let graph = canonicalize(inputGraph.graph());
1779
+ g.setGraph(
1780
+ Object.assign(
1781
+ {},
1782
+ graphDefaults,
1783
+ selectNumberAttrs(graph, graphNumAttrs),
1784
+ util.pick(graph, graphAttrs)
1785
+ )
1786
+ );
1787
+ inputGraph.nodes().forEach((v) => {
1788
+ let node = canonicalize(inputGraph.node(v));
1789
+ const newNode = selectNumberAttrs(node, nodeNumAttrs);
1790
+ Object.keys(nodeDefaults).forEach((k) => {
1791
+ if (newNode[k] === void 0) {
1792
+ newNode[k] = nodeDefaults[k];
1793
+ }
1794
+ });
1795
+ g.setNode(v, newNode);
1796
+ g.setParent(v, inputGraph.parent(v));
1797
+ });
1798
+ inputGraph.edges().forEach((e) => {
1799
+ let edge = canonicalize(inputGraph.edge(e));
1800
+ g.setEdge(
1801
+ e,
1802
+ Object.assign(
1803
+ {},
1804
+ edgeDefaults,
1805
+ selectNumberAttrs(edge, edgeNumAttrs),
1806
+ util.pick(edge, edgeAttrs)
1807
+ )
1808
+ );
1809
+ });
1810
+ return g;
1811
+ }
1812
+ function makeSpaceForEdgeLabels(g) {
1813
+ let graph = g.graph();
1814
+ graph.ranksep /= 2;
1815
+ g.edges().forEach((e) => {
1816
+ let edge = g.edge(e);
1817
+ edge.minlen *= 2;
1818
+ if (edge.labelpos.toLowerCase() !== "c") {
1819
+ if (graph.rankdir === "TB" || graph.rankdir === "BT") {
1820
+ edge.width += edge.labeloffset;
1821
+ } else {
1822
+ edge.height += edge.labeloffset;
1823
+ }
1824
+ }
1825
+ });
1826
+ }
1827
+ function injectEdgeLabelProxies(g) {
1828
+ g.edges().forEach((e) => {
1829
+ let edge = g.edge(e);
1830
+ if (edge.width && edge.height) {
1831
+ let v = g.node(e.v);
1832
+ let w = g.node(e.w);
1833
+ let label = { rank: (w.rank - v.rank) / 2 + v.rank, e };
1834
+ util.addDummyNode(g, "edge-proxy", label, "_ep");
1835
+ }
1836
+ });
1837
+ }
1838
+ function assignRankMinMax(g) {
1839
+ let maxRank2 = 0;
1840
+ g.nodes().forEach((v) => {
1841
+ let node = g.node(v);
1842
+ if (node.borderTop) {
1843
+ node.minRank = g.node(node.borderTop).rank;
1844
+ node.maxRank = g.node(node.borderBottom).rank;
1845
+ maxRank2 = Math.max(maxRank2, node.maxRank);
1846
+ }
1847
+ });
1848
+ g.graph().maxRank = maxRank2;
1849
+ }
1850
+ function removeEdgeLabelProxies(g) {
1851
+ g.nodes().forEach((v) => {
1852
+ let node = g.node(v);
1853
+ if (node.dummy === "edge-proxy") {
1854
+ g.edge(node.e).labelRank = node.rank;
1855
+ g.removeNode(v);
1856
+ }
1857
+ });
1858
+ }
1859
+ function translateGraph(g) {
1860
+ let minX = Number.POSITIVE_INFINITY;
1861
+ let maxX = 0;
1862
+ let minY = Number.POSITIVE_INFINITY;
1863
+ let maxY = 0;
1864
+ let graphLabel = g.graph();
1865
+ let marginX = graphLabel.marginx || 0;
1866
+ let marginY = graphLabel.marginy || 0;
1867
+ function getExtremes(attrs) {
1868
+ let x = attrs.x;
1869
+ let y = attrs.y;
1870
+ let w = attrs.width;
1871
+ let h = attrs.height;
1872
+ minX = Math.min(minX, x - w / 2);
1873
+ maxX = Math.max(maxX, x + w / 2);
1874
+ minY = Math.min(minY, y - h / 2);
1875
+ maxY = Math.max(maxY, y + h / 2);
1876
+ }
1877
+ g.nodes().forEach((v) => getExtremes(g.node(v)));
1878
+ g.edges().forEach((e) => {
1879
+ let edge = g.edge(e);
1880
+ if (Object.hasOwn(edge, "x")) {
1881
+ getExtremes(edge);
1882
+ }
1883
+ });
1884
+ minX -= marginX;
1885
+ minY -= marginY;
1886
+ g.nodes().forEach((v) => {
1887
+ let node = g.node(v);
1888
+ node.x -= minX;
1889
+ node.y -= minY;
1890
+ });
1891
+ g.edges().forEach((e) => {
1892
+ let edge = g.edge(e);
1893
+ edge.points.forEach((p) => {
1894
+ p.x -= minX;
1895
+ p.y -= minY;
1896
+ });
1897
+ if (Object.hasOwn(edge, "x")) {
1898
+ edge.x -= minX;
1899
+ }
1900
+ if (Object.hasOwn(edge, "y")) {
1901
+ edge.y -= minY;
1902
+ }
1903
+ });
1904
+ graphLabel.width = maxX - minX + marginX;
1905
+ graphLabel.height = maxY - minY + marginY;
1906
+ }
1907
+ function assignNodeIntersects(g) {
1908
+ g.edges().forEach((e) => {
1909
+ let edge = g.edge(e);
1910
+ let nodeV = g.node(e.v);
1911
+ let nodeW = g.node(e.w);
1912
+ let p1, p2;
1913
+ if (!edge.points) {
1914
+ edge.points = [];
1915
+ p1 = nodeW;
1916
+ p2 = nodeV;
1917
+ } else {
1918
+ p1 = edge.points[0];
1919
+ p2 = edge.points[edge.points.length - 1];
1920
+ }
1921
+ edge.points.unshift(util.intersectRect(nodeV, p1));
1922
+ edge.points.push(util.intersectRect(nodeW, p2));
1923
+ });
1924
+ }
1925
+ function fixupEdgeLabelCoords(g) {
1926
+ g.edges().forEach((e) => {
1927
+ let edge = g.edge(e);
1928
+ if (Object.hasOwn(edge, "x")) {
1929
+ if (edge.labelpos === "l" || edge.labelpos === "r") {
1930
+ edge.width -= edge.labeloffset;
1931
+ }
1932
+ switch (edge.labelpos) {
1933
+ case "l":
1934
+ edge.x -= edge.width / 2 + edge.labeloffset;
1935
+ break;
1936
+ case "r":
1937
+ edge.x += edge.width / 2 + edge.labeloffset;
1938
+ break;
1939
+ }
1940
+ }
1941
+ });
1942
+ }
1943
+ function reversePointsForReversedEdges(g) {
1944
+ g.edges().forEach((e) => {
1945
+ let edge = g.edge(e);
1946
+ if (edge.reversed) {
1947
+ edge.points.reverse();
1948
+ }
1949
+ });
1950
+ }
1951
+ function removeBorderNodes(g) {
1952
+ g.nodes().forEach((v) => {
1953
+ if (g.children(v).length) {
1954
+ let node = g.node(v);
1955
+ let t = g.node(node.borderTop);
1956
+ let b = g.node(node.borderBottom);
1957
+ let l = g.node(node.borderLeft[node.borderLeft.length - 1]);
1958
+ let r = g.node(node.borderRight[node.borderRight.length - 1]);
1959
+ node.width = Math.abs(r.x - l.x);
1960
+ node.height = Math.abs(b.y - t.y);
1961
+ node.x = l.x + node.width / 2;
1962
+ node.y = t.y + node.height / 2;
1963
+ }
1964
+ });
1965
+ g.nodes().forEach((v) => {
1966
+ if (g.node(v).dummy === "border") {
1967
+ g.removeNode(v);
1968
+ }
1969
+ });
1970
+ }
1971
+ function removeSelfEdges(g) {
1972
+ g.edges().forEach((e) => {
1973
+ if (e.v === e.w) {
1974
+ var node = g.node(e.v);
1975
+ if (!node.selfEdges) {
1976
+ node.selfEdges = [];
1977
+ }
1978
+ node.selfEdges.push({ e, label: g.edge(e) });
1979
+ g.removeEdge(e);
1980
+ }
1981
+ });
1982
+ }
1983
+ function insertSelfEdges(g) {
1984
+ var layers = util.buildLayerMatrix(g);
1985
+ layers.forEach((layer) => {
1986
+ var orderShift = 0;
1987
+ layer.forEach((v, i) => {
1988
+ var node = g.node(v);
1989
+ node.order = i + orderShift;
1990
+ (node.selfEdges || []).forEach((selfEdge) => {
1991
+ util.addDummyNode(
1992
+ g,
1993
+ "selfedge",
1994
+ {
1995
+ width: selfEdge.label.width,
1996
+ height: selfEdge.label.height,
1997
+ rank: node.rank,
1998
+ order: i + ++orderShift,
1999
+ e: selfEdge.e,
2000
+ label: selfEdge.label
2001
+ },
2002
+ "_se"
2003
+ );
2004
+ });
2005
+ delete node.selfEdges;
2006
+ });
2007
+ });
2008
+ }
2009
+ function positionSelfEdges(g) {
2010
+ g.nodes().forEach((v) => {
2011
+ var node = g.node(v);
2012
+ if (node.dummy === "selfedge") {
2013
+ var selfNode = g.node(node.e.v);
2014
+ var x = selfNode.x + selfNode.width / 2;
2015
+ var y = selfNode.y;
2016
+ var dx = node.x - x;
2017
+ var dy = selfNode.height / 2;
2018
+ g.setEdge(node.e, node.label);
2019
+ g.removeNode(v);
2020
+ node.label.points = [
2021
+ { x: x + 2 * dx / 3, y: y - dy },
2022
+ { x: x + 5 * dx / 6, y: y - dy },
2023
+ { x: x + dx, y },
2024
+ { x: x + 5 * dx / 6, y: y + dy },
2025
+ { x: x + 2 * dx / 3, y: y + dy }
2026
+ ];
2027
+ node.label.x = node.x;
2028
+ node.label.y = node.y;
2029
+ }
2030
+ });
2031
+ }
2032
+ function selectNumberAttrs(obj, attrs) {
2033
+ return util.mapValues(util.pick(obj, attrs), Number);
2034
+ }
2035
+ function canonicalize(attrs) {
2036
+ var newAttrs = {};
2037
+ if (attrs) {
2038
+ Object.entries(attrs).forEach(([k, v]) => {
2039
+ if (typeof k === "string") {
2040
+ k = k.toLowerCase();
2041
+ }
2042
+ newAttrs[k] = v;
2043
+ });
2044
+ }
2045
+ return newAttrs;
2046
+ }
2047
+
2048
+ // src/dagre-lib/index.js
2049
+ var dagreLib = {
2050
+ layout,
2051
+ buildLayoutGraph,
2052
+ updateInputGraph,
2053
+ makeSpaceForEdgeLabels,
2054
+ removeSelfEdges,
2055
+ acyclic: acyclic_default,
2056
+ nestingGraph: nesting_graph_default,
2057
+ rank: rank_default,
2058
+ util,
2059
+ injectEdgeLabelProxies,
2060
+ removeEmptyRanks,
2061
+ normalizeRanks,
2062
+ assignRankMinMax,
2063
+ removeEdgeLabelProxies,
2064
+ normalize: normalize_default,
2065
+ parentDummyChains: parent_dummy_chains_default,
2066
+ addBorderSegments: add_border_segments_default,
2067
+ order: order_default,
2068
+ insertSelfEdges,
2069
+ coordinateSystem: coordinate_system_default,
2070
+ position: position_default,
2071
+ positionSelfEdges,
2072
+ removeBorderNodes,
2073
+ fixupEdgeLabelCoords,
2074
+ translateGraph,
2075
+ assignNodeIntersects,
2076
+ reversePointsForReversedEdges
2077
+ };
2078
+
2079
+ // src/create-auto-layout-plugin.tsx
2080
+ import { definePluginCreator } from "@flowgram.ai/core";
2081
+
2082
+ // src/services.ts
2083
+ import { inject, injectable } from "inversify";
2084
+ import {
2085
+ WorkflowDocument,
2086
+ WorkflowNodeLinesData
2087
+ } from "@flowgram.ai/free-layout-core";
2088
+
2089
+ // src/layout/store.ts
2090
+ import { FlowNodeTransformData } from "@flowgram.ai/document";
2091
+ var LayoutStore = class {
2092
+ constructor() {
2093
+ this.init = false;
2094
+ }
2095
+ get initialized() {
2096
+ return this.init;
2097
+ }
2098
+ getNode(id) {
2099
+ return this.store.nodes.get(id);
2100
+ }
2101
+ getNodeByIndex(index) {
2102
+ const id = this.indexMap.get(index);
2103
+ return id ? this.getNode(id) : void 0;
2104
+ }
2105
+ getEdge(id) {
2106
+ return this.store.edges.get(id);
2107
+ }
2108
+ get nodes() {
2109
+ return Array.from(this.store.nodes.values());
2110
+ }
2111
+ get edges() {
2112
+ return Array.from(this.store.edges.values());
2113
+ }
2114
+ create(params) {
2115
+ this.store = this.createStore(params);
2116
+ this.indexMap = this.createIndexMap();
2117
+ this.init = true;
2118
+ }
2119
+ /** 创建布局数据 */
2120
+ createStore(params) {
2121
+ const { nodes, edges } = params;
2122
+ const store = {
2123
+ nodes: /* @__PURE__ */ new Map(),
2124
+ edges: /* @__PURE__ */ new Map()
2125
+ };
2126
+ nodes.forEach((node, index) => {
2127
+ const { bounds } = node.getData(FlowNodeTransformData);
2128
+ const layoutNode = {
2129
+ id: node.id,
2130
+ entity: node,
2131
+ index: "",
2132
+ // 初始化时,index 未计算
2133
+ rank: -1,
2134
+ // 初始化时,节点还未布局,层级为-1
2135
+ order: -1,
2136
+ // 初始化时,节点还未布局,顺序为-1
2137
+ position: { x: bounds.center.x, y: bounds.center.y },
2138
+ offset: { x: 0, y: 0 },
2139
+ size: { width: bounds.width, height: bounds.height },
2140
+ hasChildren: node.collapsedChildren?.length > 0
2141
+ };
2142
+ store.nodes.set(layoutNode.id, layoutNode);
2143
+ });
2144
+ edges.forEach((edge) => {
2145
+ const { from, to } = edge.info;
2146
+ if (!from || !to || edge.vertical) {
2147
+ return;
2148
+ }
2149
+ const layoutEdge = {
2150
+ id: edge.id,
2151
+ entity: edge,
2152
+ from,
2153
+ to,
2154
+ fromIndex: "",
2155
+ // 初始化时,index 未计算
2156
+ toIndex: "",
2157
+ // 初始化时,index 未计算
2158
+ name: edge.id
2159
+ };
2160
+ store.edges.set(layoutEdge.id, layoutEdge);
2161
+ });
2162
+ return store;
2163
+ }
2164
+ /** 创建节点索引映射 */
2165
+ createIndexMap() {
2166
+ const nodeIndexes = this.sortNodes();
2167
+ const nodeToIndex = /* @__PURE__ */ new Map();
2168
+ nodeIndexes.forEach((nodeId, nodeIndex) => {
2169
+ const node = this.getNode(nodeId);
2170
+ if (!node) {
2171
+ return;
2172
+ }
2173
+ const graphIndex = String(1e5 + nodeIndex);
2174
+ nodeToIndex.set(node.id, graphIndex);
2175
+ node.index = graphIndex;
2176
+ });
2177
+ this.edges.forEach((edge) => {
2178
+ const fromIndex = nodeToIndex.get(edge.from);
2179
+ const toIndex = nodeToIndex.get(edge.to);
2180
+ if (!fromIndex || !toIndex) {
2181
+ this.store.edges.delete(edge.id);
2182
+ return;
2183
+ }
2184
+ edge.fromIndex = fromIndex;
2185
+ edge.toIndex = toIndex;
2186
+ });
2187
+ const indexToNode = /* @__PURE__ */ new Map();
2188
+ nodeToIndex.forEach((index, id) => {
2189
+ indexToNode.set(index, id);
2190
+ });
2191
+ return indexToNode;
2192
+ }
2193
+ /** 节点排序 */
2194
+ sortNodes() {
2195
+ const nodeIdList = [];
2196
+ this.nodes.forEach((node) => {
2197
+ nodeIdList.push(node.id);
2198
+ });
2199
+ const sameFromEdges = /* @__PURE__ */ new Map();
2200
+ this.edges.forEach((edge) => {
2201
+ nodeIdList.push(edge.to);
2202
+ if (edge.entity.info.fromPort) {
2203
+ const edgesForFrom = sameFromEdges.get(edge.from) || [];
2204
+ sameFromEdges.set(edge.from, [...edgesForFrom, edge]);
2205
+ }
2206
+ });
2207
+ sameFromEdges.forEach((edges, from) => {
2208
+ const sortedEdges = edges.sort((a, b) => {
2209
+ const aPort = a.entity.fromPort;
2210
+ const bPort = b.entity.fromPort;
2211
+ if (aPort && bPort) {
2212
+ return aPort.point.y - bPort.point.y;
2213
+ }
2214
+ return 0;
2215
+ });
2216
+ sortedEdges.forEach((edge) => {
2217
+ nodeIdList.push(edge.to);
2218
+ });
2219
+ });
2220
+ const uniqueNodeIds = nodeIdList.reduceRight((acc, nodeId) => {
2221
+ if (!acc.includes(nodeId)) {
2222
+ acc.unshift(nodeId);
2223
+ }
2224
+ return acc;
2225
+ }, []);
2226
+ return uniqueNodeIds;
2227
+ }
2228
+ };
2229
+
2230
+ // src/layout/position.ts
2231
+ import { FlowNodeTransformData as FlowNodeTransformData2 } from "@flowgram.ai/document";
2232
+ import { startTween, TransformData } from "@flowgram.ai/core";
2233
+ var LayoutPosition = class {
2234
+ constructor(store) {
2235
+ this.store = store;
2236
+ }
2237
+ async position() {
2238
+ return new Promise((resolve) => {
2239
+ startTween({
2240
+ from: { d: 0 },
2241
+ to: { d: 100 },
2242
+ duration: 300,
2243
+ onUpdate: (v) => {
2244
+ this.store.nodes.forEach((layoutNode) => {
2245
+ this.updateNodePosition({ layoutNode, step: v.d });
2246
+ });
2247
+ },
2248
+ onComplete: () => {
2249
+ resolve();
2250
+ }
2251
+ });
2252
+ });
2253
+ }
2254
+ updateNodePosition(params) {
2255
+ const { layoutNode, step } = params;
2256
+ const transform = layoutNode.entity.getData(TransformData);
2257
+ const position2 = {
2258
+ x: layoutNode.position.x + layoutNode.offset.x,
2259
+ y: layoutNode.position.y + layoutNode.offset.y
2260
+ };
2261
+ const deltaX = (position2.x - transform.position.x) * step / 100;
2262
+ const deltaY = (position2.y - transform.bounds.height / 2 - transform.position.y) * step / 100;
2263
+ if (layoutNode.hasChildren) {
2264
+ layoutNode.entity.collapsedChildren.forEach((childNode) => {
2265
+ const childNodeTransformData = childNode.getData(FlowNodeTransformData2);
2266
+ childNodeTransformData.fireChange();
2267
+ });
2268
+ }
2269
+ transform.update({
2270
+ position: {
2271
+ x: transform.position.x + deltaX,
2272
+ y: transform.position.y + deltaY
2273
+ }
2274
+ });
2275
+ }
2276
+ };
2277
+
2278
+ // src/layout/dagre.ts
2279
+ import { FlowNodeTransformData as FlowNodeTransformData3 } from "@flowgram.ai/document";
2280
+ import { Graph as DagreGraph } from "@dagrejs/graphlib";
2281
+
2282
+ // src/layout/constant.ts
2283
+ var DagreLayoutOptions = {
2284
+ rankdir: "LR",
2285
+ nodesep: 100,
2286
+ ranksep: 100,
2287
+ ranker: "network-simplex"
2288
+ };
2289
+
2290
+ // src/layout/dagre.ts
2291
+ var DagreLayout = class {
2292
+ constructor(store) {
2293
+ this.store = store;
2294
+ this.graph = this.createGraph();
2295
+ }
2296
+ layout() {
2297
+ this.graphSetData();
2298
+ this.dagreLayout();
2299
+ this.layoutSetPosition();
2300
+ }
2301
+ dagreLayout() {
2302
+ let layoutGraph = dagreLib.buildLayoutGraph(this.graph);
2303
+ this.runLayout(layoutGraph);
2304
+ dagreLib.updateInputGraph(this.graph, layoutGraph);
2305
+ }
2306
+ runLayout(graph) {
2307
+ dagreLib.makeSpaceForEdgeLabels(graph);
2308
+ dagreLib.removeSelfEdges(graph);
2309
+ dagreLib.acyclic.run(graph);
2310
+ dagreLib.nestingGraph.run(graph);
2311
+ dagreLib.rank(dagreLib.util.asNonCompoundGraph(graph));
2312
+ dagreLib.injectEdgeLabelProxies(graph);
2313
+ dagreLib.removeEmptyRanks(graph);
2314
+ dagreLib.nestingGraph.cleanup(graph);
2315
+ dagreLib.normalizeRanks(graph);
2316
+ dagreLib.assignRankMinMax(graph);
2317
+ dagreLib.removeEdgeLabelProxies(graph);
2318
+ dagreLib.normalize.run(graph);
2319
+ dagreLib.parentDummyChains(graph);
2320
+ dagreLib.addBorderSegments(graph);
2321
+ dagreLib.order(graph);
2322
+ this.setOrderAndRank(graph);
2323
+ dagreLib.insertSelfEdges(graph);
2324
+ dagreLib.coordinateSystem.adjust(graph);
2325
+ dagreLib.position(graph);
2326
+ dagreLib.positionSelfEdges(graph);
2327
+ dagreLib.removeBorderNodes(graph);
2328
+ dagreLib.normalize.undo(graph);
2329
+ dagreLib.fixupEdgeLabelCoords(graph);
2330
+ dagreLib.coordinateSystem.undo(graph);
2331
+ dagreLib.translateGraph(graph);
2332
+ dagreLib.assignNodeIntersects(graph);
2333
+ dagreLib.reversePointsForReversedEdges(graph);
2334
+ dagreLib.acyclic.undo(graph);
2335
+ }
2336
+ createGraph() {
2337
+ const graph = new DagreGraph({ multigraph: true });
2338
+ graph.setDefaultEdgeLabel(() => ({}));
2339
+ graph.setGraph(DagreLayoutOptions);
2340
+ return graph;
2341
+ }
2342
+ graphSetData() {
2343
+ const nodes = Array.from(this.store.nodes.values());
2344
+ const edges = Array.from(this.store.edges.values()).sort((next, prev) => {
2345
+ if (next.fromIndex === prev.fromIndex) {
2346
+ return next.toIndex < prev.toIndex ? -1 : 1;
2347
+ }
2348
+ return next.fromIndex < prev.fromIndex ? -1 : 1;
2349
+ });
2350
+ nodes.forEach((layoutNode) => {
2351
+ this.graph.setNode(layoutNode.index, {
2352
+ originID: layoutNode.id,
2353
+ width: layoutNode.size.width,
2354
+ height: layoutNode.size.height
2355
+ });
2356
+ });
2357
+ edges.forEach((layoutEdge) => {
2358
+ this.graph.setEdge({
2359
+ v: layoutEdge.fromIndex,
2360
+ w: layoutEdge.toIndex,
2361
+ name: layoutEdge.name
2362
+ });
2363
+ });
2364
+ }
2365
+ layoutSetPosition() {
2366
+ this.store.nodes.forEach((layoutNode) => {
2367
+ const offsetX = this.getOffsetX(layoutNode);
2368
+ const graphNode = this.graph.node(layoutNode.index);
2369
+ if (!graphNode) {
2370
+ layoutNode.rank = -1;
2371
+ layoutNode.position = {
2372
+ x: layoutNode.position.x + offsetX,
2373
+ y: layoutNode.position.y
2374
+ };
2375
+ return;
2376
+ }
2377
+ layoutNode.rank = graphNode.rank ?? -1;
2378
+ layoutNode.position = {
2379
+ x: this.normalizeNumber(graphNode.x) + offsetX,
2380
+ y: this.normalizeNumber(graphNode.y)
2381
+ };
2382
+ });
2383
+ }
2384
+ normalizeNumber(number) {
2385
+ return Number.isNaN(number) ? 0 : number;
2386
+ }
2387
+ getOffsetX(layoutNode) {
2388
+ if (!layoutNode.hasChildren) {
2389
+ return 0;
2390
+ }
2391
+ const nodeTransform = layoutNode.entity.getData(FlowNodeTransformData3);
2392
+ const { bounds, padding } = nodeTransform;
2393
+ const leftOffset = -bounds.width / 2 + padding.left;
2394
+ return leftOffset;
2395
+ }
2396
+ setOrderAndRank(g) {
2397
+ this.followAdjust(g);
2398
+ this.normalizeOrder(g);
2399
+ return g;
2400
+ }
2401
+ /** 跟随调整 */
2402
+ followAdjust(g) {
2403
+ const rankGroup = this.rankGroup(g);
2404
+ g.nodes().forEach((i) => {
2405
+ const graphNode = g.node(i);
2406
+ const layoutNode = this.store.getNodeByIndex(i);
2407
+ if (!graphNode || !layoutNode?.followedBy) return;
2408
+ const { followedBy } = layoutNode;
2409
+ const { rank: targetRank, order: targetOrder } = graphNode;
2410
+ const followIndexes = followedBy.map((id) => this.store.getNode(id)?.index).filter(Boolean);
2411
+ const followSet = new Set(followIndexes);
2412
+ const rankIndexes = rankGroup.get(targetRank);
2413
+ if (!rankIndexes) return;
2414
+ const afterIndexes = Array.from(rankIndexes).filter((index) => {
2415
+ if (followSet.has(index)) return false;
2416
+ const graphNode2 = g.node(index);
2417
+ return graphNode2.order > targetOrder;
2418
+ });
2419
+ afterIndexes.forEach((index) => {
2420
+ const graphNode2 = g.node(index);
2421
+ graphNode2.order = graphNode2.order + followedBy.length;
2422
+ });
2423
+ followIndexes.forEach((followIndex, index) => {
2424
+ const graphNode2 = g.node(followIndex);
2425
+ graphNode2.order = targetOrder + index + 1;
2426
+ const originRank = graphNode2.rank;
2427
+ graphNode2.rank = targetRank;
2428
+ rankGroup.get(originRank)?.delete(followIndex);
2429
+ rankGroup.get(targetRank)?.add(followIndex);
2430
+ });
2431
+ });
2432
+ }
2433
+ /** rank 内 order 可能不连续,需要重新排序 */
2434
+ normalizeOrder(g) {
2435
+ const rankGroup = this.rankGroup(g);
2436
+ rankGroup.forEach((indexSet, rank2) => {
2437
+ const graphNodes = Array.from(indexSet).map((id) => g.node(id));
2438
+ graphNodes.sort((a, b) => a.order - b.order);
2439
+ graphNodes.forEach((node, index) => {
2440
+ node.order = index;
2441
+ });
2442
+ });
2443
+ }
2444
+ /** 获取 rank 分组 */
2445
+ rankGroup(g) {
2446
+ const rankGroup = /* @__PURE__ */ new Map();
2447
+ g.nodes().forEach((i) => {
2448
+ const graphNode = g.node(i);
2449
+ const rank2 = graphNode.rank;
2450
+ if (!rankGroup.has(rank2)) {
2451
+ rankGroup.set(rank2, /* @__PURE__ */ new Set());
2452
+ }
2453
+ rankGroup.get(rank2)?.add(i);
2454
+ });
2455
+ return rankGroup;
2456
+ }
2457
+ };
2458
+
2459
+ // src/layout/layout.ts
2460
+ var Layout = class {
2461
+ constructor() {
2462
+ this._store = new LayoutStore();
2463
+ this._layout = new DagreLayout(this._store);
2464
+ this._position = new LayoutPosition(this._store);
2465
+ }
2466
+ init(params, options = {}) {
2467
+ this._store.create(params);
2468
+ this.setFollowNode(options.getFollowNode);
2469
+ }
2470
+ layout() {
2471
+ if (!this._store.initialized) {
2472
+ return;
2473
+ }
2474
+ this._layout.layout();
2475
+ }
2476
+ async position() {
2477
+ if (!this._store.initialized) {
2478
+ return;
2479
+ }
2480
+ return await this._position.position();
2481
+ }
2482
+ setFollowNode(getFollowNode) {
2483
+ if (!getFollowNode) return;
2484
+ const context = { store: this._store };
2485
+ this._store.nodes.forEach((node) => {
2486
+ const followTo = getFollowNode(node, context)?.followTo;
2487
+ if (!followTo) return;
2488
+ const followToNode = this._store.getNode(followTo);
2489
+ if (!followToNode) return;
2490
+ if (!followToNode.followedBy) {
2491
+ followToNode.followedBy = [];
2492
+ }
2493
+ followToNode.followedBy.push(node.id);
2494
+ node.followTo = followTo;
2495
+ });
2496
+ }
2497
+ };
2498
+
2499
+ // src/services.ts
2500
+ var AutoLayoutService = class {
2501
+ async layout(options = {}) {
2502
+ await this.layoutNode(this.document.root, options);
2503
+ }
2504
+ async layoutNode(node, options) {
2505
+ const nodes = node.collapsedChildren;
2506
+ if (!nodes || !Array.isArray(nodes) || !nodes.length) {
2507
+ return;
2508
+ }
2509
+ const edges = node.collapsedChildren.map((child) => {
2510
+ const childLinesData = child.getData(WorkflowNodeLinesData);
2511
+ return childLinesData.outputLines.filter(Boolean);
2512
+ }).flat();
2513
+ await Promise.all(nodes.map(async (child) => this.layoutNode(child, options)));
2514
+ const layout2 = new Layout();
2515
+ layout2.init({ nodes, edges }, options);
2516
+ layout2.layout();
2517
+ await layout2.position();
2518
+ }
2519
+ };
2520
+ __decorateClass([
2521
+ inject(WorkflowDocument)
2522
+ ], AutoLayoutService.prototype, "document", 2);
2523
+ AutoLayoutService = __decorateClass([
2524
+ injectable()
2525
+ ], AutoLayoutService);
2526
+
2527
+ // src/create-auto-layout-plugin.tsx
2528
+ var createFreeAutoLayoutPlugin = definePluginCreator({
2529
+ onBind: ({ bind }) => {
2530
+ bind(AutoLayoutService).toSelf().inSingletonScope();
2531
+ }
2532
+ });
2533
+
2534
+ // src/index.ts
2535
+ import { Graph as Graph8 } from "@dagrejs/graphlib";
2536
+ export {
2537
+ AutoLayoutService,
2538
+ Graph8 as DagreGraph,
2539
+ Layout,
2540
+ createFreeAutoLayoutPlugin,
2541
+ dagreLib
2542
+ };
2543
+ //# sourceMappingURL=index.js.map