@dxos/react-ui-graph 0.9.1-staging.ee54ba693a → 0.11.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.
@@ -1,4427 +0,0 @@
1
- import {
2
- useDynamicRef,
3
- useStateRef,
4
- useTimestamp
5
- } from "./chunk-EASNZZ7B.mjs";
6
-
7
- // src/components/Graph/Graph.tsx
8
- import React, { forwardRef, useEffect as useEffect3, useImperativeHandle, useMemo as useMemo3, useRef as useRef3 } from "react";
9
- import { combine } from "@dxos/async";
10
- import { log as log12 } from "@dxos/log";
11
- import { mx } from "@dxos/ui-theme";
12
-
13
- // src/graph/markers.ts
14
- import { line, select } from "d3";
15
- var createLine = line();
16
- var createArrow = (length, offset, start) => (el) => {
17
- const height = length * 0.5;
18
- el.attr("markerWidth", length * 2).attr("markerHeight", height * 2).attr("viewBox", `-${length},-${height},${length * 2},${height * 2}`).attr("orient", "auto").attr("refX", offset).append("path").attr("fill", "none").attr("stroke", "context-stroke").attr("d", createLine([
19
- start ? [
20
- length,
21
- height
22
- ] : [
23
- -length,
24
- -height
25
- ],
26
- [
27
- 0,
28
- 0
29
- ],
30
- start ? [
31
- length,
32
- -height
33
- ] : [
34
- -length,
35
- height
36
- ]
37
- ]));
38
- };
39
- var createDot = (size) => (el) => {
40
- el.attr("markerWidth", size * 2).attr("markerHeight", size * 2).attr("viewBox", `-${size},-${size},${size * 2},${size * 2}`).attr("orient", "auto").append("circle").attr("fill", "context-stroke").attr("r", size / 2 - 1);
41
- };
42
- var createMarkers = ({ arrowSize = 12 } = {}) => (group) => {
43
- return group.selectAll("marker").data([
44
- {
45
- id: "marker-arrow-start",
46
- generator: createArrow(arrowSize, -0.5, true),
47
- className: "dx-arrow"
48
- },
49
- {
50
- id: "marker-arrow-end",
51
- generator: createArrow(arrowSize, 0.5, false),
52
- className: "dx-arrow"
53
- },
54
- {
55
- id: "marker-dot",
56
- generator: createDot(6),
57
- className: "dx-dot"
58
- }
59
- ]).join("marker").attr("id", (d) => d.id).attr("markerUnits", "strokeWidth").attr("class", (d) => d.className).each((d, i, nodes) => {
60
- select(nodes[i]).call(d.generator);
61
- });
62
- };
63
-
64
- // src/graph/projector/graph-bundle-projector.ts
65
- import { curveBundle, cluster as d3Cluster, hierarchy, lineRadial } from "d3";
66
- import { log as log2 } from "@dxos/log";
67
-
68
- // src/graph/projector/graph-radial-projector.ts
69
- import { easeCubic, timer } from "d3";
70
- import { log } from "@dxos/log";
71
-
72
- // src/graph/types.ts
73
- import { invariant } from "@dxos/invariant";
74
- var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/types.ts";
75
- var defaultIdAccessor = (node) => {
76
- invariant(node.id, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 10, S: void 0, A: ["node.id", ""] });
77
- return node.id;
78
- };
79
- var emptyGraph = {
80
- nodes: [],
81
- edges: []
82
- };
83
-
84
- // src/util/events.ts
85
- var EventEmitter = class {
86
- _listeners = /* @__PURE__ */ new Set();
87
- clear() {
88
- this._listeners.clear();
89
- }
90
- on(onEvent) {
91
- this._listeners.add(onEvent);
92
- return () => this._listeners.delete(onEvent);
93
- }
94
- emit(value) {
95
- this._listeners.forEach((listener) => listener(value));
96
- }
97
- };
98
-
99
- // src/util/fraction.ts
100
- import { invariant as invariant2 } from "@dxos/invariant";
101
- var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/util/fraction.ts";
102
- var FractionUtil = class _FractionUtil {
103
- /**
104
- * Convert number to fraction.
105
- * @param n
106
- */
107
- static toFraction = (n) => {
108
- return typeof n === "number" ? [
109
- n,
110
- 1
111
- ] : n;
112
- };
113
- static validate = (...fraction) => {
114
- fraction.forEach(([n, d]) => {
115
- if (!Number.isFinite(n) || !Number.isFinite(d) || d === 0) {
116
- throw new Error(`Invalid fraction: ${n}/${d}`);
117
- }
118
- });
119
- return fraction;
120
- };
121
- /**
122
- * @param {Fraction}
123
- * Convert to rounded-sm number.
124
- */
125
- static toNumber = ([n, d]) => {
126
- _FractionUtil.validate([
127
- n,
128
- d
129
- ]);
130
- return n / d;
131
- };
132
- /**
133
- * Round the number to the nearest fraction.
134
- * Example: 3/5 => 1/1; 3/5 (precision 2) => 1/2.
135
- * @param {Fraction}
136
- * @param p Precision (e.g., 1/2, 1/4, etc.)
137
- */
138
- static round = ([n, d], p = 1) => {
139
- _FractionUtil.validate([
140
- n,
141
- d
142
- ]);
143
- const v = Math.round(_FractionUtil.toNumber(_FractionUtil.divide([
144
- n,
145
- d
146
- ], [
147
- 1,
148
- p
149
- ])));
150
- return _FractionUtil.simplify([
151
- v,
152
- p
153
- ]);
154
- };
155
- //
156
- // Boolean.
157
- //
158
- /**
159
- * Tests if equals.
160
- * @param n1
161
- * @param n2
162
- */
163
- static equals = (n1, n2) => {
164
- return n1[0] * n2[1] === n1[1] * n2[0];
165
- };
166
- /**
167
- * @param {Fraction}
168
- * True if zero.
169
- */
170
- static isZero = ([n]) => {
171
- return n === 0;
172
- };
173
- //
174
- // Normalization.
175
- //
176
- /**
177
- * Simplify fraction finding LCDs.
178
- * @param n
179
- * @param d
180
- */
181
- static simplify = ([n, d]) => {
182
- _FractionUtil.validate([
183
- n,
184
- d
185
- ]);
186
- if (d < 1) {
187
- const t = n / d;
188
- if (Math.floor(t) === t) {
189
- n = t;
190
- d = 1;
191
- }
192
- }
193
- const fn = _FractionUtil.factors(n).reverse();
194
- const fd = _FractionUtil.factors(d).reverse();
195
- let c;
196
- for (let i = 0; i < fn.length; i++) {
197
- c = fd.find((n2) => n2 === fn[i]);
198
- if (c) {
199
- return [
200
- n / c,
201
- d / c
202
- ];
203
- }
204
- }
205
- return [
206
- n,
207
- d
208
- ];
209
- };
210
- /**
211
- * Return common factors.
212
- * @param n
213
- */
214
- static factors = (n) => {
215
- invariant2(Number.isFinite(n), `Invalid number: ${n}`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 113, S: this, A: ["Number.isFinite(n)", "`Invalid number: ${n}`"] });
216
- const factors = [
217
- 1
218
- ];
219
- if (Number.isSafeInteger(n)) {
220
- let f = 1;
221
- do {
222
- if (n % ++f === 0) {
223
- factors.push(f);
224
- }
225
- } while (n / f > 1 && f < 100);
226
- }
227
- return factors;
228
- };
229
- //
230
- // Basic arithmetic.
231
- //
232
- /**
233
- * @param n1
234
- * @param n2
235
- */
236
- static add = (n1, n2) => {
237
- _FractionUtil.validate(n1, n2);
238
- const d = n1[1] * n2[1];
239
- const n = n1[0] * n2[1] + n2[0] * n1[1];
240
- return _FractionUtil.simplify([
241
- n,
242
- d
243
- ]);
244
- };
245
- /**
246
- * @param n1
247
- * @param n2
248
- */
249
- static subtract = (n1, n2) => {
250
- _FractionUtil.validate(n1, n2);
251
- const d = n1[1] * n2[1];
252
- const n = n1[0] * n2[1] - n2[0] * n1[1];
253
- return _FractionUtil.simplify([
254
- n,
255
- d
256
- ]);
257
- };
258
- /**
259
- * @param n1
260
- * @param n2
261
- */
262
- static multiply = (n1, n2) => {
263
- _FractionUtil.validate(n1, n2);
264
- const n = n1[0] * n2[0];
265
- const d = n1[1] * n2[1];
266
- return _FractionUtil.simplify([
267
- n,
268
- d
269
- ]);
270
- };
271
- /**
272
- * @param n1
273
- * @param n2
274
- */
275
- static divide = (n1, n2) => {
276
- _FractionUtil.validate(n1, n2);
277
- const n = n1[0] * n2[1];
278
- const d = n1[1] * n2[0];
279
- return _FractionUtil.simplify([
280
- n,
281
- d
282
- ]);
283
- };
284
- };
285
-
286
- // src/util/points.ts
287
- var getCircumferencePoints = (p1, p2, r1 = 0, r2 = 0) => {
288
- const [x1, y1] = p1;
289
- const [x2, y2] = p2;
290
- const theta = Math.atan2(x2 - x1, y2 - y1);
291
- return [
292
- [
293
- // p1
294
- x1 + (r1 === 0 ? 0 : r1 * Math.sin(theta)),
295
- y1 + (r1 === 0 ? 0 : r1 * Math.cos(theta))
296
- ],
297
- [
298
- // p2
299
- x2 - (r2 === 0 ? 0 : r2 * Math.cos(Math.PI / 2 - theta)),
300
- y2 - (r2 === 0 ? 0 : r2 * Math.sin(Math.PI / 2 - theta))
301
- ]
302
- ];
303
- };
304
- var normal = (p1, p2) => {
305
- const dx = p2[0] - p1[0];
306
- const dy = p2[1] - p1[1];
307
- const len = Math.hypot(dx, dy);
308
- return [
309
- dy / len,
310
- -dx / len
311
- ];
312
- };
313
- var offsetPoints = (points, distance, closed) => {
314
- const len = points.length;
315
- const out = [];
316
- for (let i = 0; i < len; i++) {
317
- const p0 = points[(i - 1 + len) % len];
318
- const p1 = points[i];
319
- const p2 = points[(i + 1) % len];
320
- const n1 = normal(p0, p1);
321
- const n2 = normal(p1, p2);
322
- const nx = (n1[0] + n2[0]) / 2;
323
- const ny = (n1[1] + n2[1]) / 2;
324
- const norm = Math.hypot(nx, ny) || 1;
325
- out.push([
326
- p1[0] + distance * nx / norm,
327
- p1[1] + distance * ny / norm
328
- ]);
329
- if (!closed && (i === 0 || i === len - 1)) {
330
- out[i] = [
331
- p1[0] + distance * normal(p0, p1)[0],
332
- p1[1] + distance * normal(p0, p1)[1]
333
- ];
334
- }
335
- }
336
- return out;
337
- };
338
-
339
- // src/util/scale.ts
340
- import { zoomIdentity } from "d3";
341
- var Scale = class {
342
- _gridSize;
343
- _transform;
344
- constructor(_gridSize = 32) {
345
- this._gridSize = _gridSize;
346
- }
347
- get gridSize() {
348
- return this._gridSize;
349
- }
350
- get transform() {
351
- return this._transform || zoomIdentity;
352
- }
353
- setTransform(transform) {
354
- if (this._transform?.x === transform.x && this._transform?.y === transform.y && this._transform?.k === transform.k) {
355
- return false;
356
- }
357
- this._transform = transform;
358
- return true;
359
- }
360
- /**
361
- * Translate a screen point to a logical point.
362
- * @param point
363
- */
364
- translate(point) {
365
- const { x, y, k } = this._transform ?? {
366
- x: 0,
367
- y: 0,
368
- k: 1
369
- };
370
- return [
371
- (point[0] - x) / k,
372
- (point[1] - y) / k
373
- ];
374
- }
375
- /**
376
- * Map model to screen.
377
- * Model points are represented by fractions (to preserve precision) and use normal cartesian coordinates.
378
- */
379
- model = {
380
- // TODO(burdon): Precision depends on scale.
381
- snapValues: (array) => array.map((n) => FractionUtil.round(n)),
382
- snapVertex: ({ x, y }) => {
383
- const [sx, sy] = this.model.snapValues([
384
- x,
385
- y
386
- ]);
387
- return {
388
- x: sx,
389
- y: sy
390
- };
391
- },
392
- snapBounds: ({ x, y, width, height }) => {
393
- [x, y, width, height] = this.model.snapValues([
394
- x,
395
- y,
396
- width,
397
- height
398
- ]);
399
- return {
400
- x,
401
- y,
402
- width,
403
- height
404
- };
405
- },
406
- toValue: (value) => {
407
- return Math.round(FractionUtil.toNumber(value) * this._gridSize);
408
- },
409
- toValues: (values) => {
410
- return values.map((value) => Math.round(FractionUtil.toNumber(value) * this._gridSize));
411
- },
412
- toPoint: (point) => {
413
- const [x, y] = this.model.toValues([
414
- point.x,
415
- point.y
416
- ]);
417
- return [
418
- x,
419
- y === 0 ? 0 : -y
420
- ];
421
- },
422
- toBounds: ({ x, y, width, height }) => {
423
- const point = this.model.toPoint({
424
- x,
425
- y
426
- });
427
- const [width2, height2] = this.model.toValues([
428
- width,
429
- height
430
- ]);
431
- return {
432
- x: point[0],
433
- y: point[1] - height2,
434
- width: width2,
435
- height: height2
436
- };
437
- }
438
- };
439
- /**
440
- * Map screen to model.
441
- * Screen points are represented by floating numbers and use translated SVG coordinates (with the y-axis inverted).
442
- */
443
- screen = {
444
- snapValues: (array) => array.map((n) => Math.round(n / this._gridSize) * this._gridSize),
445
- snapPoint: ([x, y]) => [
446
- x,
447
- y
448
- ].map((n) => Math.round(n / this._gridSize) * this._gridSize),
449
- snapBounds: ({ x, y, width, height }) => {
450
- [x, y, width, height] = this.screen.snapValues([
451
- x,
452
- y,
453
- width,
454
- height
455
- ]);
456
- return {
457
- x,
458
- y,
459
- width,
460
- height
461
- };
462
- },
463
- toValue: (value) => {
464
- return FractionUtil.divide(FractionUtil.toFraction(value), [
465
- this._gridSize,
466
- 1
467
- ]);
468
- },
469
- toValues: (values) => {
470
- return values.map((value) => FractionUtil.divide(FractionUtil.toFraction(value), [
471
- this._gridSize,
472
- 1
473
- ]));
474
- },
475
- toVertex: (point) => {
476
- const [x, y] = point;
477
- return {
478
- x: FractionUtil.toFraction(x / this._gridSize),
479
- y: FractionUtil.toFraction(-y / this._gridSize)
480
- };
481
- },
482
- toBounds: (bounds) => {
483
- const { x, y } = this.screen.toVertex([
484
- bounds.x,
485
- bounds.y
486
- ]);
487
- const [width, height] = this.screen.toValues([
488
- bounds.width,
489
- bounds.height
490
- ]);
491
- return {
492
- x,
493
- y: FractionUtil.subtract(y, height),
494
- width,
495
- height
496
- };
497
- }
498
- };
499
- };
500
-
501
- // src/util/screen.ts
502
- var Screen = class {
503
- static createBounds = ([x1, y1], [x2, y2], mod = {}) => {
504
- const { constrain, center } = mod;
505
- const x = Math.min(x1, x2);
506
- const y = Math.min(y1, y2);
507
- let width = Math.abs(x2 - x1);
508
- let height = Math.abs(y2 - y1);
509
- if (constrain) {
510
- width = height = Math.max(width, height);
511
- }
512
- if (center) {
513
- return {
514
- x: x - width,
515
- y: y - height,
516
- width: width * 2,
517
- height: height * 2
518
- };
519
- } else {
520
- return {
521
- x,
522
- y,
523
- width,
524
- height
525
- };
526
- }
527
- };
528
- static center = ({ x, y, width, height }) => {
529
- return [
530
- x + width / 2,
531
- y + height / 2
532
- ];
533
- };
534
- static contains = (bounds, point) => {
535
- const [x, y] = point;
536
- if (x < bounds.x || y < bounds.y) {
537
- return false;
538
- }
539
- if (x > bounds.x + bounds.width || y > bounds.y + bounds.height) {
540
- return false;
541
- }
542
- return true;
543
- };
544
- /**
545
- * Distance between two points.
546
- * @param p1
547
- * @param p2
548
- */
549
- static len = (p1, p2) => {
550
- return Math.sqrt(Math.pow(Math.abs(p1[0] - p2[0]), 2) + Math.pow(Math.abs(p1[1] - p2[1]), 2));
551
- };
552
- /**
553
- * Distance to line segment.
554
- * https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment#1501725
555
- * @param v1
556
- * @param v2
557
- * @param p
558
- */
559
- static normal = (v1, v2, p) => {
560
- const d2 = (p1, p2) => Math.pow(Math.abs(p1[0] - p2[0]), 2) + Math.pow(Math.abs(p1[1] - p2[1]), 2);
561
- let d;
562
- const len2 = d2(v1, v2);
563
- if (len2 === 0) {
564
- d = d2(p, v1);
565
- } else {
566
- let t = ((p[0] - v1[0]) * (v2[0] - v1[0]) + (p[1] - v1[1]) * (v2[1] - v1[1])) / len2;
567
- t = Math.max(0, Math.min(1, t));
568
- d = d2(p, [
569
- v1[0] + t * (v2[0] - v1[0]),
570
- v1[1] + t * (v2[1] - v1[1])
571
- ]);
572
- }
573
- return Math.sqrt(d);
574
- };
575
- };
576
-
577
- // src/util/vector.ts
578
- var Vector = class {
579
- /**
580
- * Convert to Vertex.
581
- * @param x
582
- * @param y
583
- */
584
- static toVertex = ({ x, y }) => ({
585
- x: FractionUtil.toFraction(x),
586
- y: FractionUtil.toFraction(y)
587
- });
588
- /**
589
- * Convert to Bounds.
590
- * @param bounds
591
- */
592
- static toBounds = ({ x, y, width, height }) => ({
593
- x: FractionUtil.toFraction(x),
594
- y: FractionUtil.toFraction(y),
595
- width: FractionUtil.toFraction(width),
596
- height: FractionUtil.toFraction(height)
597
- });
598
- /**
599
- * Calculate center point.
600
- * @param bounds
601
- */
602
- static center = ({ x, y, width, height }) => {
603
- const cx = FractionUtil.add(x, FractionUtil.multiply(width, [
604
- 1,
605
- 2
606
- ]));
607
- const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
608
- 1,
609
- 2
610
- ]));
611
- return {
612
- x: cx,
613
- y: cy
614
- };
615
- };
616
- /**
617
- * Calculate centered left edge.
618
- * @param bounds
619
- */
620
- static left = ({ x, y, height }) => {
621
- const cx = x;
622
- const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
623
- 1,
624
- 2
625
- ]));
626
- return {
627
- x: cx,
628
- y: cy
629
- };
630
- };
631
- /**
632
- * Calculate centered right edge.
633
- * @param bounds
634
- */
635
- static right = ({ x, y, width, height }) => {
636
- const cx = FractionUtil.add(x, width);
637
- const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
638
- 1,
639
- 2
640
- ]));
641
- return {
642
- x: cx,
643
- y: cy
644
- };
645
- };
646
- };
647
-
648
- // src/graph/projector/projector.ts
649
- var Projector = class {
650
- _context;
651
- updated = new EventEmitter();
652
- _options;
653
- constructor(_context, options) {
654
- this._context = _context;
655
- this._options = Object.assign({
656
- idAccessor: defaultIdAccessor
657
- }, options);
658
- }
659
- get context() {
660
- return this._context;
661
- }
662
- get options() {
663
- return this._options;
664
- }
665
- refresh(dragging = false) {
666
- this.onRefresh(dragging);
667
- }
668
- updateData(data) {
669
- this.onUpdate(data);
670
- }
671
- emitUpdate(kind = "topology") {
672
- this.updated.emit({
673
- layout: this.layout,
674
- kind
675
- });
676
- }
677
- async clear() {
678
- await this.onClear();
679
- }
680
- async start() {
681
- await this.onStart();
682
- }
683
- async stop() {
684
- await this.onStop();
685
- }
686
- onRefresh(dragging = false) {
687
- }
688
- onUpdate(data) {
689
- }
690
- async onClear() {
691
- }
692
- async onStart() {
693
- }
694
- async onStop() {
695
- }
696
- };
697
-
698
- // src/graph/projector/graph-projector.ts
699
- var GraphProjector = class extends Projector {
700
- _selection;
701
- _layout;
702
- // TODO(burdon): Change to object props.
703
- constructor(context, options, _selection, layout) {
704
- super(context, options), this._selection = _selection;
705
- this._layout = {
706
- id: (Math.random() * 10).toString().slice(8),
707
- graph: {
708
- nodes: [
709
- ...layout?.graph.nodes ?? []
710
- ],
711
- edges: [
712
- ...layout?.graph.edges ?? []
713
- ]
714
- }
715
- };
716
- }
717
- get layout() {
718
- return this._layout;
719
- }
720
- get selection() {
721
- return this._selection;
722
- }
723
- numChildren(node) {
724
- return this._layout.graph.edges.filter((edge) => edge.source.id === this.options.idAccessor(node)).length;
725
- }
726
- reset() {
727
- this._layout.graph.nodes = [];
728
- this._layout.graph.edges = [];
729
- this.emitUpdate();
730
- }
731
- /**
732
- * Merge external data with internal representation (e.g., so force properties like position are preserved).
733
- * @param data
734
- */
735
- mergeData(data = emptyGraph) {
736
- const nodes = data.nodes.map((node) => {
737
- let current = this._layout.graph.nodes.find((n) => n.id === this.options.idAccessor(node));
738
- if (!current) {
739
- current = {
740
- id: this.options.idAccessor(node)
741
- };
742
- }
743
- current.data = node;
744
- current.hidden = false;
745
- return current;
746
- });
747
- const edges = data.edges.map((edge) => ({
748
- id: edge.id,
749
- type: edge.type,
750
- source: nodes.find((n) => n.id === edge.source),
751
- target: nodes.find((n) => n.id === edge.target),
752
- data: edge.data
753
- })).filter((edge) => edge.source && edge.target);
754
- Object.assign(this._layout, {
755
- graph: {
756
- nodes,
757
- edges
758
- }
759
- });
760
- }
761
- async onClear() {
762
- this.reset();
763
- }
764
- /**
765
- * Optional projector-owned click intercept. The Graph component invokes this BEFORE
766
- * forwarding to the consumer's `onSelect`, so projectors can implement built-in
767
- * interactions (e.g. cluster collapse) without each consumer wiring them. Returning
768
- * `true` indicates the click was handled — consumer's `onSelect` is suppressed.
769
- * Default no-op returns `false` so consumer handlers still run.
770
- */
771
- handleNodeClick(_node, _event) {
772
- return false;
773
- }
774
- };
775
-
776
- // src/graph/projector/graph-radial-projector.ts
777
- var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-radial-projector.ts";
778
- var GraphRadialProjector = class extends GraphProjector {
779
- _timer;
780
- findNode(x, y, radius) {
781
- return void 0;
782
- }
783
- onUpdate(graph) {
784
- log("onUpdate", {
785
- graph: {
786
- nodes: graph?.nodes.length,
787
- edges: graph?.edges.length
788
- }
789
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 13, S: this });
790
- this.mergeData(graph);
791
- this.emitUpdate("topology");
792
- this.doRadialLayout();
793
- }
794
- animate() {
795
- this._timer?.stop();
796
- this._timer = void 0;
797
- const start = Date.now();
798
- if (this.options.duration) {
799
- this._timer = timer(() => {
800
- const t = Math.min(1, (Date.now() - start) / this.options.duration);
801
- const d = easeCubic(t);
802
- this.layout.graph.nodes.forEach((node) => {
803
- node.x = node.sx + (node.tx - node.sx) * d;
804
- node.y = node.sy + (node.ty - node.sy) * d;
805
- node.r = node.sr + (node.tr - node.sr) * d;
806
- });
807
- this.onTickFrame(d);
808
- this.emitUpdate("positions");
809
- if (t >= 1) {
810
- this._timer.stop();
811
- this._timer = void 0;
812
- }
813
- });
814
- } else {
815
- this.layout.graph.nodes.forEach((node) => {
816
- node.x = node.tx;
817
- node.y = node.ty;
818
- node.r = node.tr;
819
- });
820
- this.onTickFrame(1);
821
- this.emitUpdate("positions");
822
- }
823
- }
824
- /**
825
- * Per-frame hook called after node x/y/r are interpolated and before the
826
- * 'positions' emit. Subclasses override to update edge geometry (`edge.path`)
827
- * so curves stay glued to moving endpoints. `t` is the eased progress in [0, 1].
828
- */
829
- onTickFrame(t) {
830
- }
831
- async onStop() {
832
- this._timer?.stop();
833
- this._timer = void 0;
834
- }
835
- doRadialLayout() {
836
- if (!this.context.size) {
837
- return;
838
- }
839
- const radial = layoutRadial(0, 0, this.options.radius ?? Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 80), this.layout.graph.nodes.length);
840
- this.layout.graph.nodes.forEach((node, i) => {
841
- const [tx, ty] = radial(i);
842
- updateNode(node, [
843
- tx,
844
- ty
845
- ]);
846
- });
847
- this.animate();
848
- }
849
- };
850
- var updateNode = (node, [tx, ty], tr = 8) => {
851
- const sx = node.x ?? tx;
852
- const sy = node.y ?? ty;
853
- const sr = node.r ?? tr;
854
- Object.assign(node, {
855
- initialized: true,
856
- // Start.
857
- sx,
858
- sy,
859
- sr,
860
- // Target.
861
- tx,
862
- ty,
863
- tr,
864
- // Current.
865
- x: sx,
866
- y: sy,
867
- r: sr
868
- });
869
- };
870
- var layoutRadial = (x, y, r, n, start = -Math.PI / 2) => {
871
- const da = 2 * Math.PI / n;
872
- return (i) => {
873
- const a = start + i * da;
874
- return [
875
- x + Math.cos(a) * r,
876
- y + Math.sin(a) * r
877
- ];
878
- };
879
- };
880
- var layoutHorizontal = (x, y, w, n) => {
881
- const dx = n > 1 ? w / (n - 1) : 0;
882
- const sx = x - (n - 1) * dx / 2;
883
- return (i) => {
884
- return [
885
- sx + i * dx,
886
- y
887
- ];
888
- };
889
- };
890
- var layoutVertical = (x, y, h, n) => {
891
- const dy = n > 1 ? h / (n - 1) : 0;
892
- const sy = y - (n - 1) * dy / 2;
893
- return (i) => {
894
- return [
895
- x,
896
- sy + i * dy
897
- ];
898
- };
899
- };
900
-
901
- // src/graph/projector/graph-bundle-projector.ts
902
- var __dxlog_file4 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-bundle-projector.ts";
903
- var ROOT_ID = "__bundle_root__";
904
- var GROUP_PREFIX = "__bundle_group__:";
905
- var cartesianToPolar = (x, y) => ({
906
- angle: Math.atan2(x, -y),
907
- radius: Math.hypot(x, y)
908
- });
909
- var GraphBundleProjector = class extends GraphRadialProjector {
910
- // Per-edge polar point arrays. Points 0 and N-1 are the source / target leaves and are
911
- // overwritten from current cartesian on every tick; intermediate points stay fixed at
912
- // their cluster-layout polar coordinates.
913
- #edgePoints = /* @__PURE__ */ new Map();
914
- #lineGen = lineRadial().radius((d) => d.radius).angle((d) => d.angle);
915
- onUpdate(graph) {
916
- log2("onUpdate", {
917
- graph: {
918
- nodes: graph?.nodes.length,
919
- edges: graph?.edges.length
920
- }
921
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 40, S: this });
922
- this.mergeData(graph);
923
- this.doBundleLayout();
924
- this.emitUpdate("topology");
925
- this.animate();
926
- }
927
- /**
928
- * Refresh leaf endpoint polar values from current cartesian so the curve tracks
929
- * its endpoints during the tween. Internal hierarchy positions stay constant.
930
- */
931
- onTickFrame(_t) {
932
- for (const edge of this.layout.graph.edges) {
933
- if (edge.type !== "bundle") {
934
- continue;
935
- }
936
- const points = this.#edgePoints.get(edge.id);
937
- if (!points || points.length < 2) {
938
- continue;
939
- }
940
- const s = cartesianToPolar(edge.source.x ?? 0, edge.source.y ?? 0);
941
- const t = cartesianToPolar(edge.target.x ?? 0, edge.target.y ?? 0);
942
- points[0] = {
943
- angle: s.angle,
944
- radius: s.radius
945
- };
946
- points[points.length - 1] = {
947
- angle: t.angle,
948
- radius: t.radius
949
- };
950
- edge.path = this.#lineGen(points) ?? void 0;
951
- }
952
- }
953
- doBundleLayout() {
954
- if (!this.context.size) {
955
- return;
956
- }
957
- const dataNodes = [
958
- ...this.layout.graph.nodes
959
- ];
960
- if (!dataNodes.length) {
961
- return;
962
- }
963
- const groupOf = this.options.groupOf;
964
- const items = [
965
- {
966
- id: ROOT_ID
967
- }
968
- ];
969
- const groupIds = /* @__PURE__ */ new Map();
970
- for (const node of dataNodes) {
971
- const key = groupOf?.(node);
972
- let parent = ROOT_ID;
973
- if (key !== void 0) {
974
- let groupId = groupIds.get(key);
975
- if (!groupId) {
976
- groupId = `${GROUP_PREFIX}${key}`;
977
- groupIds.set(key, groupId);
978
- items.push({
979
- id: groupId,
980
- parent: ROOT_ID
981
- });
982
- }
983
- parent = groupId;
984
- }
985
- items.push({
986
- id: node.id,
987
- parent,
988
- node
989
- });
990
- }
991
- const childrenByParent = /* @__PURE__ */ new Map();
992
- for (const item of items) {
993
- if (item.parent) {
994
- const list = childrenByParent.get(item.parent) ?? [];
995
- list.push(item);
996
- childrenByParent.set(item.parent, list);
997
- }
998
- }
999
- const root = hierarchy({
1000
- id: ROOT_ID
1001
- }, (d) => childrenByParent.get(d.id) ?? []);
1002
- const { width, height } = this.context.size;
1003
- const margin = this.options.margin ?? 120;
1004
- const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1005
- d3Cluster().size([
1006
- 2 * Math.PI,
1007
- ringRadius
1008
- ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1009
- const leafR = this.options.leafRadius ?? 4;
1010
- const tension = this.options.tension ?? 0.85;
1011
- this.#lineGen = lineRadial().curve(curveBundle.beta(tension)).radius((d) => d.radius).angle((d) => d.angle);
1012
- const hierById = /* @__PURE__ */ new Map();
1013
- root.each((d) => {
1014
- hierById.set(d.data.id, d);
1015
- });
1016
- root.leaves().forEach((d) => {
1017
- const angle = d.x;
1018
- const radius = d.y;
1019
- const x = Math.cos(angle - Math.PI / 2) * radius;
1020
- const y = Math.sin(angle - Math.PI / 2) * radius;
1021
- if (d.data.node) {
1022
- updateNode(d.data.node, [
1023
- x,
1024
- y
1025
- ], leafR);
1026
- }
1027
- });
1028
- this.layout.graph.nodes = dataNodes;
1029
- this.#edgePoints.clear();
1030
- const incomingEdges = [
1031
- ...this.layout.graph.edges
1032
- ];
1033
- const bundleEdges = [];
1034
- for (const edge of incomingEdges) {
1035
- const sourceHier = hierById.get(edge.source.id);
1036
- const targetHier = hierById.get(edge.target.id);
1037
- if (!sourceHier || !targetHier || sourceHier === targetHier) {
1038
- continue;
1039
- }
1040
- const pathNodes = sourceHier.path(targetHier);
1041
- const points = pathNodes.map((n) => ({
1042
- angle: n.x,
1043
- radius: n.y
1044
- }));
1045
- this.#edgePoints.set(edge.id, points);
1046
- bundleEdges.push({
1047
- id: edge.id,
1048
- type: "bundle",
1049
- source: edge.source,
1050
- target: edge.target,
1051
- data: edge.data
1052
- });
1053
- }
1054
- this.layout.graph.edges = bundleEdges;
1055
- this.onTickFrame(0);
1056
- }
1057
- };
1058
-
1059
- // src/graph/projector/graph-cluster-projector.ts
1060
- import { cluster as d3Cluster2, hierarchy as hierarchy2, linkRadial } from "d3";
1061
- import { log as log3 } from "@dxos/log";
1062
- var __dxlog_file5 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-cluster-projector.ts";
1063
- var ROOT_ID2 = "__cluster_root__";
1064
- var GROUP_PREFIX2 = "__group__:";
1065
- var HIER_EDGE_PREFIX = "__hier__:";
1066
- var CLUSTER_NODE_TYPE_LEAF = "leaf";
1067
- var CLUSTER_NODE_TYPE_GROUP = "group";
1068
- var CLUSTER_NODE_TYPE_ROOT = "root";
1069
- var linkPath = linkRadial().angle((d) => d.x).radius((d) => d.y);
1070
- var cartesianToPolar2 = (x, y) => ({
1071
- angle: Math.atan2(x, -y),
1072
- radius: Math.hypot(x, y)
1073
- });
1074
- var GraphClusterProjector = class extends GraphRadialProjector {
1075
- // Synthetic-node ids (root id, or `${GROUP_PREFIX}${key}`) whose subtree is currently
1076
- // hidden. Clicking the corresponding rendered circle calls toggleCollapsed to flip
1077
- // membership, then re-runs the layout so the renderer's exit transition fades the
1078
- // hidden leaves + hierarchy edges out (and back in on expand).
1079
- #collapsed = /* @__PURE__ */ new Set();
1080
- // Snapshot of the full data-node set as of the last mergeData. doClusterLayout always
1081
- // reads from this rather than `layout.graph.nodes` — the layout view is filtered (it
1082
- // drops hidden leaves so the renderer doesn't see them), so re-reading from there
1083
- // would permanently lose the hidden leaves and they couldn't reappear on expand.
1084
- #dataNodes = [];
1085
- /**
1086
- * Built-in click semantics: clicking a synthetic root / group node toggles its subtree.
1087
- * Leaf clicks fall through to the consumer's `onSelect` (returns `false`).
1088
- */
1089
- handleNodeClick(node, _event) {
1090
- if (node.type !== CLUSTER_NODE_TYPE_ROOT && node.type !== CLUSTER_NODE_TYPE_GROUP) {
1091
- return false;
1092
- }
1093
- this.toggleCollapsed(node.id);
1094
- return true;
1095
- }
1096
- /** Toggle collapse state for a synthetic node id. Triggers a topology re-emit. */
1097
- toggleCollapsed(id) {
1098
- if (this.#collapsed.has(id)) {
1099
- this.#collapsed.delete(id);
1100
- } else {
1101
- this.#collapsed.add(id);
1102
- }
1103
- this.doClusterLayout();
1104
- this.emitUpdate("topology");
1105
- this.animate();
1106
- }
1107
- /** Whether a synthetic-node id is currently collapsed. */
1108
- isCollapsed(id) {
1109
- return this.#collapsed.has(id);
1110
- }
1111
- onUpdate(graph) {
1112
- log3("onUpdate", {
1113
- graph: {
1114
- nodes: graph?.nodes.length,
1115
- edges: graph?.edges.length
1116
- }
1117
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 79, S: this });
1118
- this.mergeData(graph);
1119
- this.#dataNodes = [
1120
- ...this.layout.graph.nodes
1121
- ];
1122
- this.doClusterLayout();
1123
- this.emitUpdate("topology");
1124
- this.animate();
1125
- }
1126
- /**
1127
- * Recompute each hierarchy edge's `path` from current cartesian source/target positions,
1128
- * so the curves track moving endpoints during a cross-variant tween (e.g. force → cluster)
1129
- * instead of being pinned to the final polar layout.
1130
- */
1131
- onTickFrame(_t) {
1132
- for (const edge of this.layout.graph.edges) {
1133
- if (edge.type !== "hierarchy") {
1134
- continue;
1135
- }
1136
- const { source, target } = edge;
1137
- const s = cartesianToPolar2(source.x ?? 0, source.y ?? 0);
1138
- const t = cartesianToPolar2(target.x ?? 0, target.y ?? 0);
1139
- edge.path = linkPath({
1140
- source: {
1141
- x: s.angle,
1142
- y: s.radius
1143
- },
1144
- target: {
1145
- x: t.angle,
1146
- y: t.radius
1147
- }
1148
- });
1149
- }
1150
- }
1151
- doClusterLayout() {
1152
- if (!this.context.size) {
1153
- return;
1154
- }
1155
- const dataNodes = this.#dataNodes;
1156
- if (!dataNodes.length) {
1157
- return;
1158
- }
1159
- const groupOf = this.options.groupOf;
1160
- const rootId = this.options.rootId ?? ROOT_ID2;
1161
- const items = [
1162
- {
1163
- id: rootId
1164
- }
1165
- ];
1166
- const groupIds = /* @__PURE__ */ new Map();
1167
- const rootCollapsed = this.#collapsed.has(rootId);
1168
- if (!rootCollapsed) {
1169
- for (const node of dataNodes) {
1170
- const key = groupOf?.(node);
1171
- let parent = rootId;
1172
- if (key !== void 0) {
1173
- let groupId = groupIds.get(key);
1174
- if (!groupId) {
1175
- groupId = `${GROUP_PREFIX2}${key}`;
1176
- groupIds.set(key, groupId);
1177
- items.push({
1178
- id: groupId,
1179
- parent: rootId,
1180
- groupKey: key
1181
- });
1182
- }
1183
- parent = groupId;
1184
- }
1185
- if (this.#collapsed.has(parent)) {
1186
- continue;
1187
- }
1188
- items.push({
1189
- id: node.id,
1190
- parent,
1191
- node
1192
- });
1193
- }
1194
- }
1195
- const childrenByParent = /* @__PURE__ */ new Map();
1196
- for (const item of items) {
1197
- if (item.parent) {
1198
- const list = childrenByParent.get(item.parent) ?? [];
1199
- list.push(item);
1200
- childrenByParent.set(item.parent, list);
1201
- }
1202
- }
1203
- const root = hierarchy2({
1204
- id: rootId
1205
- }, (d) => childrenByParent.get(d.id) ?? []);
1206
- const { width, height } = this.context.size;
1207
- const margin = this.options.margin ?? 80;
1208
- const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1209
- d3Cluster2().size([
1210
- 2 * Math.PI,
1211
- ringRadius
1212
- ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1213
- const leafR = this.options.leafRadius ?? 4;
1214
- const groupR = this.options.groupRadius ?? 3;
1215
- const rootR = this.options.rootRadius ?? 5;
1216
- const prevStubsById = /* @__PURE__ */ new Map();
1217
- for (const node of this.layout.graph.nodes) {
1218
- if (node.type === CLUSTER_NODE_TYPE_ROOT || node.type === CLUSTER_NODE_TYPE_GROUP) {
1219
- prevStubsById.set(node.id, node);
1220
- }
1221
- }
1222
- const syntheticNodes = /* @__PURE__ */ new Map();
1223
- root.each((d) => {
1224
- const id = d.data.id;
1225
- const angle = d.x;
1226
- const radius = d.y;
1227
- const x = Math.cos(angle - Math.PI / 2) * radius;
1228
- const y = Math.sin(angle - Math.PI / 2) * radius;
1229
- if (d.data.node) {
1230
- updateNode(d.data.node, [
1231
- x,
1232
- y
1233
- ], leafR);
1234
- d.data.node.type = CLUSTER_NODE_TYPE_LEAF;
1235
- d.data.node.hidden = false;
1236
- } else {
1237
- const isRoot = id === rootId;
1238
- const stub = prevStubsById.get(id) ?? {
1239
- id,
1240
- x: 0,
1241
- y: 0
1242
- };
1243
- updateNode(stub, [
1244
- x,
1245
- y
1246
- ], isRoot ? rootR : groupR);
1247
- stub.type = isRoot ? CLUSTER_NODE_TYPE_ROOT : CLUSTER_NODE_TYPE_GROUP;
1248
- if (isRoot) {
1249
- stub.label = this.options.rootLabel;
1250
- } else if (d.data.groupKey !== void 0) {
1251
- stub.label = this.options.groupLabel ? this.options.groupLabel(d.data.groupKey) : d.data.groupKey;
1252
- }
1253
- syntheticNodes.set(id, stub);
1254
- }
1255
- });
1256
- const visibleLeafIds = /* @__PURE__ */ new Set();
1257
- for (const item of items) {
1258
- if (item.node) {
1259
- visibleLeafIds.add(item.id);
1260
- }
1261
- }
1262
- for (const node of dataNodes) {
1263
- if (visibleLeafIds.has(node.id)) {
1264
- continue;
1265
- }
1266
- const key = groupOf?.(node);
1267
- const parentId = key !== void 0 && groupIds.has(key) ? groupIds.get(key) : rootId;
1268
- const parentStub = syntheticNodes.get(parentId);
1269
- const targetX = parentStub?.tx ?? 0;
1270
- const targetY = parentStub?.ty ?? 0;
1271
- updateNode(node, [
1272
- targetX,
1273
- targetY
1274
- ], leafR);
1275
- node.type = CLUSTER_NODE_TYPE_LEAF;
1276
- node.hidden = true;
1277
- }
1278
- const nextNodes = [];
1279
- for (const stub of syntheticNodes.values()) {
1280
- nextNodes.push(stub);
1281
- }
1282
- for (const node of dataNodes) {
1283
- nextNodes.push(node);
1284
- }
1285
- this.layout.graph.nodes = nextNodes;
1286
- const hierarchyEdges = [];
1287
- root.links().forEach((link) => {
1288
- const sid = link.source.data.id;
1289
- const tid = link.target.data.id;
1290
- const sourceNode = link.source.data.node ?? syntheticNodes.get(sid);
1291
- const targetNode = link.target.data.node ?? syntheticNodes.get(tid);
1292
- hierarchyEdges.push({
1293
- id: `${HIER_EDGE_PREFIX}${sid}->${tid}`,
1294
- type: "hierarchy",
1295
- source: sourceNode,
1296
- target: targetNode,
1297
- data: void 0
1298
- });
1299
- });
1300
- this.layout.graph.edges = hierarchyEdges;
1301
- this.onTickFrame(0);
1302
- }
1303
- };
1304
-
1305
- // src/graph/projector/graph-drag.ts
1306
- import { drag, pointer, select as select2 } from "d3";
1307
- var defaultDragOptions = {
1308
- linkMod: "metaKey",
1309
- freezeMod: "shiftKey"
1310
- };
1311
- var createGraphDrag = (context, projector, options = defaultDragOptions) => {
1312
- let mode;
1313
- let source;
1314
- let target;
1315
- let offset;
1316
- let moved = false;
1317
- const keyMod = (event, key) => {
1318
- const modKey = options?.[key] ?? defaultDragOptions[key];
1319
- return modKey === void 0 || event[modKey];
1320
- };
1321
- return drag().filter((event) => !event.ctrlKey).on("start", function(event, d) {
1322
- source = d;
1323
- offset = pointer(event, this.parentElement);
1324
- if (options?.onDrop && keyMod(event.sourceEvent, "linkMod")) {
1325
- mode = 1;
1326
- } else if (keyMod(event.sourceEvent, "dragMod")) {
1327
- mode = 0;
1328
- }
1329
- }).on("drag", function(event, d) {
1330
- const parent = this.closest("g.node");
1331
- select2(parent).classed("dragging", true).raise();
1332
- const [dx, dy] = pointer(event, this.parentElement);
1333
- const x = d.x + dx - offset[0];
1334
- const y = d.y + dy - offset[1];
1335
- const point = [
1336
- x,
1337
- y
1338
- ];
1339
- switch (mode) {
1340
- case 0: {
1341
- select2(context.svg).attr("cursor", "grabbing");
1342
- event.subject.x = event.subject.fx = point[0];
1343
- event.subject.y = event.subject.fy = point[1];
1344
- projector.refresh(true);
1345
- moved = true;
1346
- break;
1347
- }
1348
- case 1: {
1349
- if (options?.onDrag) {
1350
- target = projector.findNode(event.x, event.y, 16);
1351
- if (source === target) {
1352
- select2(context.svg).attr("cursor", void 0);
1353
- options?.onDrag?.();
1354
- } else {
1355
- select2(context.svg).attr("cursor", target ? "alias" : "cell");
1356
- options?.onDrag?.(source, target, point);
1357
- }
1358
- }
1359
- }
1360
- }
1361
- }).on("end", function(event) {
1362
- select2(context.svg).attr("cursor", void 0);
1363
- select2(this.parentElement).classed("dragging", false);
1364
- switch (mode) {
1365
- case 1: {
1366
- options?.onDrop?.(source, target);
1367
- break;
1368
- }
1369
- }
1370
- if (!keyMod(event.sourceEvent, "freezeMod")) {
1371
- event.subject.fx = null;
1372
- event.subject.fy = null;
1373
- }
1374
- mode = void 0;
1375
- source = void 0;
1376
- target = void 0;
1377
- offset = void 0;
1378
- if (moved) {
1379
- projector.refresh(false);
1380
- moved = false;
1381
- }
1382
- });
1383
- };
1384
-
1385
- // src/graph/projector/graph-force-projector.ts
1386
- import { forceCenter, forceCollide, forceLink, forceManyBody, forceRadial, forceSimulation, forceX as forceX2, forceY as forceY2 } from "d3";
1387
- import { log as log4 } from "@dxos/log";
1388
-
1389
- // src/graph/projector/graph-forces.ts
1390
- import { forceX, forceY } from "d3";
1391
- var forcePoint = ({ x, y, strength = 0.01 }) => {
1392
- const fx = x != null ? forceX(x).strength(strength) : void 0;
1393
- const fy = y != null ? forceY(y).strength(strength) : void 0;
1394
- const force = (alpha) => {
1395
- fx?.(alpha);
1396
- fy?.(alpha);
1397
- };
1398
- force.initialize = (nodes, random) => {
1399
- fx?.initialize(nodes, random);
1400
- fy?.initialize(nodes, random);
1401
- };
1402
- return force;
1403
- };
1404
-
1405
- // src/graph/projector/graph-force-projector.ts
1406
- var __dxlog_file6 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-force-projector.ts";
1407
- var getValue = (valueOrFunction, invoker, defaultValue) => {
1408
- return (typeof valueOrFunction === "function" ? invoker(valueOrFunction) : valueOrFunction) ?? defaultValue;
1409
- };
1410
- var maybeForce = (options, cb, defaultValue = void 0) => {
1411
- const value = typeof options === "boolean" ? options ? {} : void 0 : options ?? defaultValue;
1412
- if (value) {
1413
- return cb(value);
1414
- }
1415
- };
1416
- var defaultForceOptions = {
1417
- link: true,
1418
- manyBody: true,
1419
- // center: true,
1420
- point: true
1421
- };
1422
- var GraphForceProjector = class extends GraphProjector {
1423
- // https://github.com/d3/d3-force
1424
- _simulation = forceSimulation();
1425
- _timeout;
1426
- get forces() {
1427
- return this.options.forces ?? defaultForceOptions;
1428
- }
1429
- get simulation() {
1430
- return this._simulation;
1431
- }
1432
- restart() {
1433
- this._simulation.alpha(1).restart();
1434
- }
1435
- findNode(x, y, radius) {
1436
- return this._simulation.find(x, y, radius);
1437
- }
1438
- async onStart() {
1439
- clearTimeout(this._timeout);
1440
- let propagating = true;
1441
- const { radial, ...forces } = this.forces;
1442
- const delay = typeof radial === "object" ? radial.delay : void 0;
1443
- if (delay) {
1444
- propagating = false;
1445
- this.updateForces(forces);
1446
- this._timeout = setTimeout(() => {
1447
- this.updateForces(this.forces);
1448
- this.restart();
1449
- this._timeout = setTimeout(() => {
1450
- propagating = true;
1451
- }, delay);
1452
- }, delay);
1453
- } else {
1454
- this.updateForces(this.forces);
1455
- }
1456
- this._simulation.on("tick", () => propagating && this.emitUpdate("positions")).velocityDecay(0.3).alphaDecay(1 - Math.pow(1e-3, 1 / 300)).alpha(1).restart();
1457
- }
1458
- async onStop() {
1459
- clearTimeout(this._timeout);
1460
- this._simulation.stop();
1461
- }
1462
- onRefresh(dragging = false) {
1463
- if (this.forces.center) {
1464
- if (dragging) {
1465
- this._simulation.force("center", null);
1466
- } else {
1467
- this.updateForces(this.forces);
1468
- }
1469
- }
1470
- this.restart();
1471
- }
1472
- onUpdate(graph) {
1473
- log4("onUpdate", {
1474
- graph: {
1475
- nodes: graph?.nodes.length,
1476
- edges: graph?.edges.length
1477
- }
1478
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 91, S: this });
1479
- this._simulation.stop();
1480
- this.mergeData(graph);
1481
- this.updateLayout();
1482
- this.updateForces(this.forces);
1483
- this.emitUpdate("topology");
1484
- this.restart();
1485
- }
1486
- updateLayout() {
1487
- this.layout.guides = this.options.guides ? [
1488
- {
1489
- id: "g-1",
1490
- type: "circle",
1491
- cx: 0,
1492
- cy: 0,
1493
- r: this.context.scale.model.toValue([
1494
- 10,
1495
- 1
1496
- ])
1497
- }
1498
- ] : void 0;
1499
- this.layout.graph.nodes.forEach((node) => {
1500
- if (!node.initialized) {
1501
- const a = 2 * Math.PI * Math.random();
1502
- const r = this.options.radius ?? 200;
1503
- Object.assign(node, {
1504
- initialized: true,
1505
- // TODO(burdon): Only when new nodes added to initial layout.
1506
- // Position around center or parent; must have delta to avoid spike.
1507
- // x: edge?.source?.x ?? Math.cos(a) * r,
1508
- // y: edge?.source?.y ?? Math.sin(a) * r,
1509
- x: Math.cos(a) * r,
1510
- y: Math.sin(a) * r
1511
- });
1512
- }
1513
- Object.assign(node, {
1514
- r: getValue(this.options?.attributes?.radius, (fn) => fn(node, this.numChildren(node)), 6)
1515
- });
1516
- });
1517
- this.layout.graph.edges.forEach((edge) => {
1518
- Object.assign(edge, {
1519
- linkForce: getValue(this.options.attributes?.linkForce, (fn) => fn(edge), true)
1520
- });
1521
- });
1522
- }
1523
- /**
1524
- * Update all forces.
1525
- */
1526
- updateForces(forces) {
1527
- log4("updateForces", {
1528
- forces
1529
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 153, S: this });
1530
- this._simulation.nodes(this.layout.graph.nodes).force("link", maybeForce(forces?.link, (config) => {
1531
- const force = forceLink().id((d) => d.id).links(this.layout.graph.edges.filter((edge) => edge.linkForce));
1532
- if (config.distance != null) {
1533
- force.distance(config.distance);
1534
- }
1535
- if (config.strength != null) {
1536
- force.strength(config.strength);
1537
- }
1538
- if (config.iterations != null) {
1539
- force.iterations(config.iterations);
1540
- }
1541
- return force;
1542
- }, forces?.link === false ? void 0 : {})).force("manyBody", maybeForce(forces?.manyBody, (config) => {
1543
- const force = forceManyBody();
1544
- if (config.distanceMax != null) {
1545
- force.distanceMax(config.distanceMax);
1546
- }
1547
- if (config.strength != null) {
1548
- force.strength(config.strength);
1549
- }
1550
- return force;
1551
- }, forces?.manyBody === false ? void 0 : {})).force("collide", maybeForce(forces?.collide, (config) => {
1552
- const force = forceCollide();
1553
- force.radius(config.radius ?? 8);
1554
- if (config.strength != null) {
1555
- force.strength(config.strength);
1556
- }
1557
- return force;
1558
- })).force("radial", maybeForce(forces?.radial, (config) => {
1559
- const force = forceRadial(config.radius ?? 100, config.x ?? 0, config.y ?? 0);
1560
- if (config.strength != null) {
1561
- force.strength(config.strength);
1562
- }
1563
- return force;
1564
- })).force("center", maybeForce(forces?.center, (config) => {
1565
- const force = forceCenter().x(config.x ?? 0).y(config.y ?? 0);
1566
- if (config.strength != null) {
1567
- force.strength(config.strength);
1568
- }
1569
- return force;
1570
- })).force("point", maybeForce(forces?.point, ({ x = 0, y = 0, strength }) => {
1571
- return forcePoint({
1572
- x,
1573
- y,
1574
- strength
1575
- });
1576
- })).force("x", maybeForce(forces?.x, (config) => {
1577
- const force = forceX2(config.x ?? 0);
1578
- if (config.strength != null) {
1579
- force.strength(config.strength);
1580
- }
1581
- return force;
1582
- })).force("y", maybeForce(forces?.y, (config) => {
1583
- const force = forceY2(config.y ?? 0);
1584
- if (config.strength != null) {
1585
- force.strength(config.strength);
1586
- }
1587
- return force;
1588
- }));
1589
- }
1590
- };
1591
-
1592
- // src/graph/projector/graph-hierarchical-projector.ts
1593
- import { log as log5 } from "@dxos/log";
1594
- var __dxlog_file7 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-hierarchical-projector.ts";
1595
- var GraphHierarchicalProjector = class extends GraphRadialProjector {
1596
- onUpdate(graph) {
1597
- log5("onUpdate", {
1598
- graph: {
1599
- nodes: graph?.nodes.length,
1600
- edges: graph?.edges.length
1601
- },
1602
- selection: this.selection?.getSelectedIds()
1603
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 8, S: this });
1604
- this.mergeData(graph);
1605
- this.emitUpdate("topology");
1606
- const selected = this.selection?.getSelectedIds()[0];
1607
- if (selected) {
1608
- const node = this.layout.graph.nodes.find((node2) => node2.id === selected);
1609
- if (node) {
1610
- this.doHierarchicalLayout(node);
1611
- return;
1612
- }
1613
- }
1614
- this.doRadialLayout();
1615
- }
1616
- doHierarchicalLayout(selected) {
1617
- if (!this.context.size) {
1618
- return;
1619
- }
1620
- const r2 = this.options.radius ?? Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 80);
1621
- const r1 = r2 / 2;
1622
- const children = this.layout.graph.edges.filter((edge) => edge.source.id === selected.id).map((edge) => edge.target);
1623
- updateNode(selected, [
1624
- 0,
1625
- 0
1626
- ], 20);
1627
- {
1628
- const radial = layoutRadial(0, 0, r1, children.length);
1629
- children.forEach((node, i) => {
1630
- const [tx, ty] = radial(i);
1631
- updateNode(node, [
1632
- tx,
1633
- ty
1634
- ]);
1635
- });
1636
- }
1637
- {
1638
- const radial = layoutRadial(0, 0, r2, this.layout.graph.nodes.length - 1 - children.length);
1639
- this.layout.graph.nodes.filter((node) => node.id !== selected.id && !children.includes(node)).forEach((node, i) => {
1640
- const [tx, ty] = radial(i);
1641
- updateNode(node, [
1642
- tx,
1643
- ty
1644
- ]);
1645
- });
1646
- }
1647
- this.animate();
1648
- }
1649
- };
1650
-
1651
- // src/graph/projector/graph-lattice-projector.ts
1652
- import { log as log6 } from "@dxos/log";
1653
- var __dxlog_file8 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-lattice-projector.ts";
1654
- var GraphLatticeProjector = class extends GraphRadialProjector {
1655
- onUpdate(graph) {
1656
- log6("onUpdate", {
1657
- graph: {
1658
- nodes: graph?.nodes.length,
1659
- edges: graph?.edges.length
1660
- }
1661
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 14, S: this });
1662
- this.mergeData(graph);
1663
- this.doLatticeLayout();
1664
- this.emitUpdate("topology");
1665
- this.animate();
1666
- }
1667
- doLatticeLayout() {
1668
- if (!this.context.size) {
1669
- return;
1670
- }
1671
- const nodes = this.layout.graph.nodes;
1672
- const count = nodes.length;
1673
- if (!count) {
1674
- return;
1675
- }
1676
- const sortBy = this.options.sortBy ?? ((n) => n.data?.label ?? n.id);
1677
- nodes.sort((a, b) => sortBy(a).localeCompare(sortBy(b)));
1678
- const columns = Math.max(1, Math.ceil(Math.sqrt(count)));
1679
- const rows = Math.ceil(count / columns);
1680
- const margin = this.options.margin ?? 16;
1681
- const { width, height } = this.context.size;
1682
- const innerW = Math.max(0, width - 2 * margin);
1683
- const innerH = Math.max(0, height - 2 * margin);
1684
- const r = this.options.radius ?? 6;
1685
- const fit = Math.min(innerW / columns, innerH / rows);
1686
- const cellSize = Math.max(0, Math.min(fit, r * 6));
1687
- const gridW = cellSize * columns;
1688
- const gridH = cellSize * rows;
1689
- const offsetX = -gridW / 2 + cellSize / 2;
1690
- const offsetY = -gridH / 2 + cellSize / 2;
1691
- nodes.forEach((node, i) => {
1692
- const tx = offsetX + i % columns * cellSize;
1693
- const ty = offsetY + Math.floor(i / columns) * cellSize;
1694
- updateNode(node, [
1695
- tx,
1696
- ty
1697
- ], r);
1698
- });
1699
- }
1700
- };
1701
-
1702
- // src/graph/projector/graph-plexus-projector.ts
1703
- import { cluster as d3Cluster3, hierarchy as hierarchy3, linkRadial as linkRadial2 } from "d3";
1704
- import { log as log7 } from "@dxos/log";
1705
- var __dxlog_file9 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-plexus-projector.ts";
1706
- var RELATION_PREFIX = "__plexus_relation__:";
1707
- var HIER_EDGE_PREFIX2 = "__plexus_hier__:";
1708
- var PLEXUS_NODE_TYPE_FOCUS = "plexus-focus";
1709
- var PLEXUS_NODE_TYPE_RELATION = "plexus-relation";
1710
- var PLEXUS_NODE_TYPE_OBJECT = "plexus-object";
1711
- var linkPath2 = linkRadial2().angle((d) => d.x).radius((d) => d.y);
1712
- var cartesianToPolar3 = (x, y) => ({
1713
- angle: Math.atan2(x, -y),
1714
- radius: Math.hypot(x, y)
1715
- });
1716
- var GraphPlexusProjector = class extends GraphRadialProjector {
1717
- // Full node / edge snapshots taken right after mergeData — doPlexusLayout reads from
1718
- // these because it overwrites layout.graph with the filtered focus-centric view.
1719
- #dataNodes = [];
1720
- #dataEdges = [];
1721
- onUpdate(graph) {
1722
- log7("onUpdate", {
1723
- graph: {
1724
- nodes: graph?.nodes.length,
1725
- edges: graph?.edges.length
1726
- }
1727
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file9, L: 48, S: this });
1728
- this.mergeData(graph);
1729
- this.#dataNodes = [
1730
- ...this.layout.graph.nodes
1731
- ];
1732
- this.#dataEdges = [
1733
- ...this.layout.graph.edges
1734
- ];
1735
- this.doPlexusLayout();
1736
- this.emitUpdate("topology");
1737
- this.animate();
1738
- }
1739
- /**
1740
- * Recompute each hierarchy edge's `path` from current cartesian endpoints so curves track
1741
- * moving nodes during the tween (identical strategy to the cluster projector).
1742
- */
1743
- onTickFrame(_t) {
1744
- for (const edge of this.layout.graph.edges) {
1745
- if (edge.type !== "hierarchy") {
1746
- continue;
1747
- }
1748
- const { source, target } = edge;
1749
- const s = cartesianToPolar3(source.x ?? 0, source.y ?? 0);
1750
- const t = cartesianToPolar3(target.x ?? 0, target.y ?? 0);
1751
- edge.path = linkPath2({
1752
- source: {
1753
- x: s.angle,
1754
- y: s.radius
1755
- },
1756
- target: {
1757
- x: t.angle,
1758
- y: t.radius
1759
- }
1760
- });
1761
- }
1762
- }
1763
- doPlexusLayout() {
1764
- if (!this.context.size) {
1765
- return;
1766
- }
1767
- const dataNodes = this.#dataNodes;
1768
- if (!dataNodes.length) {
1769
- return;
1770
- }
1771
- const focusId = this.options.focus;
1772
- const focusNode = focusId ? dataNodes.find((node) => node.id === focusId) : void 0;
1773
- if (!focusNode) {
1774
- const radial = layoutRadial(0, 0, Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 100), dataNodes.length);
1775
- dataNodes.forEach((node, index) => updateNode(node, radial(index), this.options.leafRadius ?? 5));
1776
- this.layout.graph.nodes = dataNodes;
1777
- this.layout.graph.edges = [];
1778
- this.animate();
1779
- return;
1780
- }
1781
- const relationOf = this.options.relationOf ?? defaultRelationOf;
1782
- const groups = /* @__PURE__ */ new Map();
1783
- const placed = /* @__PURE__ */ new Set([
1784
- focusId
1785
- ]);
1786
- for (const edge of this.#dataEdges) {
1787
- const relation = relationOf(edge, focusId);
1788
- if (!relation) {
1789
- continue;
1790
- }
1791
- const neighbour = edge.source.id === focusId ? edge.target : edge.source;
1792
- if (placed.has(neighbour.id)) {
1793
- continue;
1794
- }
1795
- placed.add(neighbour.id);
1796
- let group = groups.get(relation.key);
1797
- if (!group) {
1798
- group = {
1799
- id: `${RELATION_PREFIX}${relation.key}`,
1800
- label: relation.label,
1801
- leaves: []
1802
- };
1803
- groups.set(relation.key, group);
1804
- }
1805
- group.leaves.push(neighbour);
1806
- }
1807
- const items = [
1808
- {
1809
- id: focusId,
1810
- node: focusNode
1811
- }
1812
- ];
1813
- for (const group of groups.values()) {
1814
- items.push({
1815
- id: group.id,
1816
- parent: focusId,
1817
- relationLabel: group.label
1818
- });
1819
- for (const leaf of group.leaves) {
1820
- items.push({
1821
- id: leaf.id,
1822
- parent: group.id,
1823
- node: leaf
1824
- });
1825
- }
1826
- }
1827
- const childrenByParent = /* @__PURE__ */ new Map();
1828
- for (const item of items) {
1829
- if (item.parent) {
1830
- const list = childrenByParent.get(item.parent) ?? [];
1831
- list.push(item);
1832
- childrenByParent.set(item.parent, list);
1833
- }
1834
- }
1835
- const root = hierarchy3({
1836
- id: focusId,
1837
- node: focusNode
1838
- }, (d) => childrenByParent.get(d.id) ?? []);
1839
- const { width, height } = this.context.size;
1840
- const margin = this.options.margin ?? 100;
1841
- const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1842
- d3Cluster3().size([
1843
- 2 * Math.PI,
1844
- ringRadius
1845
- ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1846
- const leafR = this.options.leafRadius ?? 5;
1847
- const relationR = this.options.relationRadius ?? leafR;
1848
- const focusR = this.options.focusRadius ?? leafR * 2;
1849
- const prevStubsById = /* @__PURE__ */ new Map();
1850
- for (const node of this.layout.graph.nodes) {
1851
- if (node.type === PLEXUS_NODE_TYPE_RELATION) {
1852
- prevStubsById.set(node.id, node);
1853
- }
1854
- }
1855
- const relationStubs = /* @__PURE__ */ new Map();
1856
- root.each((d) => {
1857
- const angle = d.x;
1858
- const radius = d.y;
1859
- const x = Math.cos(angle - Math.PI / 2) * radius;
1860
- const y = Math.sin(angle - Math.PI / 2) * radius;
1861
- const id = d.data.id;
1862
- if (id === focusId) {
1863
- updateNode(focusNode, [
1864
- x,
1865
- y
1866
- ], focusR);
1867
- focusNode.type = PLEXUS_NODE_TYPE_FOCUS;
1868
- focusNode.hidden = false;
1869
- } else if (d.data.node) {
1870
- updateNode(d.data.node, [
1871
- x,
1872
- y
1873
- ], leafR);
1874
- d.data.node.type = PLEXUS_NODE_TYPE_OBJECT;
1875
- d.data.node.hidden = false;
1876
- } else {
1877
- const stub = prevStubsById.get(id) ?? {
1878
- id,
1879
- x: 0,
1880
- y: 0
1881
- };
1882
- updateNode(stub, [
1883
- x,
1884
- y
1885
- ], relationR);
1886
- stub.type = PLEXUS_NODE_TYPE_RELATION;
1887
- stub.label = d.data.relationLabel;
1888
- relationStubs.set(id, stub);
1889
- }
1890
- });
1891
- const nextNodes = [];
1892
- for (const stub of relationStubs.values()) {
1893
- nextNodes.push(stub);
1894
- }
1895
- for (const group of groups.values()) {
1896
- for (const leaf of group.leaves) {
1897
- nextNodes.push(leaf);
1898
- }
1899
- }
1900
- nextNodes.push(focusNode);
1901
- this.layout.graph.nodes = nextNodes;
1902
- const edges = [];
1903
- root.links().forEach((link) => {
1904
- const sid = link.source.data.id;
1905
- const tid = link.target.data.id;
1906
- const sourceNode = sid === focusId ? focusNode : link.source.data.node ?? relationStubs.get(sid);
1907
- const targetNode = link.target.data.node ?? relationStubs.get(tid);
1908
- if (!sourceNode || !targetNode) {
1909
- return;
1910
- }
1911
- edges.push({
1912
- id: `${HIER_EDGE_PREFIX2}${sid}->${tid}`,
1913
- type: "hierarchy",
1914
- source: sourceNode,
1915
- target: targetNode,
1916
- data: void 0
1917
- });
1918
- });
1919
- this.layout.graph.edges = edges;
1920
- this.onTickFrame(0);
1921
- }
1922
- };
1923
- var defaultRelationOf = (edge, focusId) => {
1924
- const outgoing = edge.source.id === focusId;
1925
- const incoming = edge.target.id === focusId;
1926
- if (!outgoing && !incoming) {
1927
- return void 0;
1928
- }
1929
- const type = edge.type ?? "edge";
1930
- const arrow = outgoing ? "\u2192" : "\u2190";
1931
- return {
1932
- key: `${type}:${outgoing ? "out" : "in"}`,
1933
- label: `${type} ${arrow}`
1934
- };
1935
- };
1936
-
1937
- // src/graph/projector/graph-relational-projector.ts
1938
- import { log as log8 } from "@dxos/log";
1939
- var __dxlog_file10 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-relational-projector.ts";
1940
- var GraphRelationalProjector = class extends GraphRadialProjector {
1941
- onUpdate(graph) {
1942
- log8("onUpdate", {
1943
- graph: {
1944
- nodes: graph?.nodes.length,
1945
- edges: graph?.edges.length
1946
- },
1947
- selection: this.selection?.getSelectedIds()
1948
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file10, L: 8, S: this });
1949
- this.mergeData(graph);
1950
- this.emitUpdate("topology");
1951
- const selected = this.selection?.getSelectedIds()[0];
1952
- if (selected) {
1953
- const node = this.layout.graph.nodes.find((node2) => node2.id === selected);
1954
- if (node) {
1955
- this.doRelationalLayout(node);
1956
- return;
1957
- }
1958
- }
1959
- this.doRadialLayout();
1960
- }
1961
- doRelationalLayout(selected) {
1962
- if (!this.context.size) {
1963
- return;
1964
- }
1965
- const r2 = this.options.radius ?? Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 80);
1966
- const r1 = r2 * 0.5;
1967
- this.layout.graph.nodes.forEach((node) => node.type = void 0);
1968
- this.layout.graph.edges.forEach((edge) => {
1969
- edge.order = 0;
1970
- edge.type = void 0;
1971
- });
1972
- const children = this.layout.graph.edges.filter((edge) => edge.source.id === selected.id).map((edge) => {
1973
- edge.order = 1;
1974
- edge.type = "1";
1975
- edge.target.type = "1";
1976
- return edge.target;
1977
- });
1978
- const parents = this.layout.graph.edges.filter((edge) => edge.target.id === selected.id).map((edge) => {
1979
- edge.order = 2;
1980
- edge.type = "2";
1981
- edge.source.type = "2";
1982
- return edge.source;
1983
- });
1984
- updateNode(selected, [
1985
- 0,
1986
- 0
1987
- ], 30);
1988
- {
1989
- const vertical = layoutHorizontal(0, r1, r1 * 2, children.length);
1990
- children.forEach((node, i) => {
1991
- const [tx, ty] = vertical(i);
1992
- updateNode(node, [
1993
- tx,
1994
- ty
1995
- ], 20);
1996
- });
1997
- }
1998
- {
1999
- const vertical = layoutHorizontal(0, -r1, r1, parents.length);
2000
- parents.forEach((node, i) => {
2001
- const [tx, ty] = vertical(i);
2002
- updateNode(node, [
2003
- tx,
2004
- ty
2005
- ], 20);
2006
- });
2007
- }
2008
- {
2009
- const radial = layoutRadial(0, 0, r2, this.layout.graph.nodes.length - 1 - children.length - parents.length);
2010
- this.layout.graph.nodes.filter((node) => node.id !== selected.id && !children.includes(node) && !parents.includes(node)).forEach((node, i) => {
2011
- const [tx, ty] = radial(i);
2012
- updateNode(node, [
2013
- tx,
2014
- ty
2015
- ]);
2016
- });
2017
- }
2018
- this.animate();
2019
- }
2020
- };
2021
-
2022
- // src/graph/projector/graph-swarm-projector.ts
2023
- import { timer as timer2 } from "d3";
2024
- import { log as log9 } from "@dxos/log";
2025
- var __dxlog_file11 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-swarm-projector.ts";
2026
- var SWARMMATE_RADIUS = 60;
2027
- var SEPARATION_DISTANCE = 30;
2028
- var DEFAULTS = {
2029
- spawnRadius: 200,
2030
- maxVelocity: 1.2,
2031
- alignment: 3,
2032
- cohesion: 3,
2033
- separation: 3,
2034
- cursorRepel: 120,
2035
- avoidance: 3,
2036
- trailLength: 30
2037
- };
2038
- var GraphSwarmProjector = class extends GraphProjector {
2039
- #timer;
2040
- /** Cursor in SVG model coordinates, or null when the pointer is outside the surface. */
2041
- #cursor = null;
2042
- findNode() {
2043
- return void 0;
2044
- }
2045
- /**
2046
- * Tell the projector where the pointer is, in SVG model coordinates (the same space
2047
- * `node.x/y` live in — center origin, post-zoom). Pass `null` (or omit args) on
2048
- * pointer-leave to disable cursor avoidance.
2049
- */
2050
- setCursor(x, y) {
2051
- if (x == null || y == null) {
2052
- this.#cursor = null;
2053
- } else {
2054
- this.#cursor = {
2055
- x,
2056
- y
2057
- };
2058
- }
2059
- }
2060
- onUpdate(graph) {
2061
- log9("onUpdate", {
2062
- graph: {
2063
- nodes: graph?.nodes.length,
2064
- edges: graph?.edges.length
2065
- }
2066
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file11, L: 54, S: this });
2067
- this.mergeData(graph);
2068
- this.initializeNodes();
2069
- this.emitUpdate("topology");
2070
- }
2071
- async onStart() {
2072
- this.startTimer();
2073
- }
2074
- async onStop() {
2075
- this.stopTimer();
2076
- }
2077
- onRefresh() {
2078
- if (!this.#timer) {
2079
- this.startTimer();
2080
- }
2081
- }
2082
- #opt(key) {
2083
- return this.options[key] ?? DEFAULTS[key];
2084
- }
2085
- initializeNodes() {
2086
- const spawnRadius = this.#opt("spawnRadius");
2087
- const maxVelocity = this.#opt("maxVelocity");
2088
- for (const node of this.layout.graph.nodes) {
2089
- if (!node.initialized) {
2090
- const theta = Math.random() * 2 * Math.PI;
2091
- const r = Math.random() * spawnRadius;
2092
- node.x = Math.cos(theta) * r;
2093
- node.y = Math.sin(theta) * r;
2094
- const phi = Math.random() * 2 * Math.PI;
2095
- const speed = (0.3 + Math.random() * 0.7) * maxVelocity;
2096
- node.vx = Math.cos(phi) * speed;
2097
- node.vy = Math.sin(phi) * speed;
2098
- node.ax = 0;
2099
- node.ay = 0;
2100
- node.initialized = true;
2101
- } else {
2102
- node.vx ??= 0;
2103
- node.vy ??= 0;
2104
- node.ax ??= 0;
2105
- node.ay ??= 0;
2106
- }
2107
- node.r ??= 6;
2108
- node.history = [
2109
- {
2110
- x: node.x ?? 0,
2111
- y: node.y ?? 0
2112
- }
2113
- ];
2114
- }
2115
- }
2116
- startTimer() {
2117
- this.stopTimer();
2118
- this.#timer = timer2(() => this.tick());
2119
- }
2120
- stopTimer() {
2121
- this.#timer?.stop();
2122
- this.#timer = void 0;
2123
- }
2124
- /**
2125
- * One simulation step. Modeled on `tick` in Swarm.tsx, but operating in the
2126
- * SVG centered-origin coordinate space and writing to `node.x/y` directly so
2127
- * the existing `GraphRenderer.applyPositions` reads them unchanged.
2128
- */
2129
- tick() {
2130
- const size = this.context.size;
2131
- if (!size) {
2132
- return;
2133
- }
2134
- const { width, height } = size;
2135
- const halfW = width / 2;
2136
- const halfH = height / 2;
2137
- const nodes = this.layout.graph.nodes;
2138
- const maxVelocity = this.#opt("maxVelocity");
2139
- const alignmentW = this.#opt("alignment") / 100;
2140
- const cohesionW = this.#opt("cohesion") / 100;
2141
- const separationW = this.#opt("separation") / 100;
2142
- const avoidanceW = this.#opt("avoidance") / 10;
2143
- const cursorRepel = this.#opt("cursorRepel");
2144
- const cursor = cursorRepel > 0 ? this.#cursor : null;
2145
- for (const b1 of nodes) {
2146
- let ax = 0;
2147
- let ay = 0;
2148
- let alignX = 0;
2149
- let alignY = 0;
2150
- let alignActive = false;
2151
- let cohX = 0;
2152
- let cohY = 0;
2153
- let cohActive = false;
2154
- let sepX = 0;
2155
- let sepY = 0;
2156
- let sepActive = false;
2157
- let avoidX = 0;
2158
- let avoidY = 0;
2159
- let avoidActive = false;
2160
- if (cursor) {
2161
- const dx = cursor.x - (b1.x ?? 0);
2162
- const dy = cursor.y - (b1.y ?? 0);
2163
- const distSq = dx * dx + dy * dy;
2164
- if (distSq > 0 && distSq < cursorRepel * cursorRepel) {
2165
- const dist = Math.sqrt(distSq);
2166
- avoidX = -dx / dist * (1 / dist);
2167
- avoidY = -dy / dist * (1 / dist);
2168
- avoidActive = true;
2169
- }
2170
- }
2171
- if (!avoidActive) {
2172
- for (const b2 of nodes) {
2173
- if (b1 === b2) {
2174
- continue;
2175
- }
2176
- const dx = (b2.x ?? 0) - (b1.x ?? 0);
2177
- const dy = (b2.y ?? 0) - (b1.y ?? 0);
2178
- const distSq = dx * dx + dy * dy;
2179
- if (distSq === 0) {
2180
- continue;
2181
- }
2182
- const dist = Math.sqrt(distSq);
2183
- if (dist < SEPARATION_DISTANCE) {
2184
- sepX += -dx / dist * (1 / dist);
2185
- sepY += -dy / dist * (1 / dist);
2186
- sepActive = true;
2187
- }
2188
- if (dist < SWARMMATE_RADIUS) {
2189
- cohX += dx;
2190
- cohY += dy;
2191
- cohActive = true;
2192
- alignX += b2.vx ?? 0;
2193
- alignY += b2.vy ?? 0;
2194
- alignActive = true;
2195
- }
2196
- }
2197
- }
2198
- const applyForce = (fx, fy, weight, active) => {
2199
- if (!active || weight === 0) {
2200
- return;
2201
- }
2202
- const len = Math.sqrt(fx * fx + fy * fy);
2203
- if (len === 0) {
2204
- return;
2205
- }
2206
- const sx = fx * maxVelocity / len - (b1.vx ?? 0);
2207
- const sy = fy * maxVelocity / len - (b1.vy ?? 0);
2208
- const slen = Math.sqrt(sx * sx + sy * sy);
2209
- if (slen > weight) {
2210
- ax += sx * weight / slen;
2211
- ay += sy * weight / slen;
2212
- } else {
2213
- ax += sx;
2214
- ay += sy;
2215
- }
2216
- };
2217
- applyForce(alignX, alignY, alignmentW, alignActive);
2218
- applyForce(cohX, cohY, cohesionW, cohActive);
2219
- applyForce(sepX, sepY, separationW, sepActive);
2220
- applyForce(avoidX, avoidY, avoidanceW, avoidActive);
2221
- b1.ax = ax;
2222
- b1.ay = ay;
2223
- }
2224
- const trailLength = Math.max(0, Math.round(this.#opt("trailLength")));
2225
- for (const b of nodes) {
2226
- let vx = (b.vx ?? 0) + (b.ax ?? 0);
2227
- let vy = (b.vy ?? 0) + (b.ay ?? 0);
2228
- const vlen = Math.sqrt(vx * vx + vy * vy);
2229
- if (vlen > maxVelocity) {
2230
- vx = vx * maxVelocity / vlen;
2231
- vy = vy * maxVelocity / vlen;
2232
- }
2233
- b.vx = vx;
2234
- b.vy = vy;
2235
- if (trailLength > 0) {
2236
- const history = b.history ?? (b.history = []);
2237
- history.push({
2238
- x: b.x ?? 0,
2239
- y: b.y ?? 0
2240
- });
2241
- if (history.length > trailLength) {
2242
- history.splice(0, history.length - trailLength);
2243
- }
2244
- }
2245
- let x = (b.x ?? 0) + vx;
2246
- let y = (b.y ?? 0) + vy;
2247
- let wrapped = false;
2248
- if (x > halfW) {
2249
- x -= width;
2250
- wrapped = true;
2251
- } else if (x < -halfW) {
2252
- x += width;
2253
- wrapped = true;
2254
- }
2255
- if (y > halfH) {
2256
- y -= height;
2257
- wrapped = true;
2258
- } else if (y < -halfH) {
2259
- y += height;
2260
- wrapped = true;
2261
- }
2262
- if (wrapped && b.history) {
2263
- b.history.length = 0;
2264
- }
2265
- b.x = x;
2266
- b.y = y;
2267
- }
2268
- for (const edge of this.layout.graph.edges) {
2269
- const sx = edge.source.x ?? 0;
2270
- const sy = edge.source.y ?? 0;
2271
- const tx = edge.target.x ?? 0;
2272
- const ty = edge.target.y ?? 0;
2273
- edge.path = `M ${sx} ${sy} Q 0 0 ${tx} ${ty}`;
2274
- }
2275
- this.emitUpdate("positions");
2276
- }
2277
- };
2278
-
2279
- // src/graph/projector/graph-tree-projector.ts
2280
- import { tree as d3Tree, hierarchy as hierarchy4, linkHorizontal } from "d3";
2281
- import { log as log10 } from "@dxos/log";
2282
- var __dxlog_file12 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-tree-projector.ts";
2283
- var TREE_NODE_TYPE_ROOT = "tree-root";
2284
- var TREE_NODE_TYPE_NODE = "tree-node";
2285
- var TREE_NODE_TYPE_INBOUND = "tree-inbound";
2286
- var HIER_EDGE_PREFIX3 = "__tree_hier__:";
2287
- var linkPath3 = linkHorizontal().x((d) => d.x).y((d) => d.y);
2288
- var GraphTreeProjector = class extends GraphRadialProjector {
2289
- // Snapshots taken right after mergeData — doTreeLayout reads from these because it overwrites
2290
- // layout.graph.edges with the synthesized hierarchy edges.
2291
- #dataNodes = [];
2292
- #dataEdges = [];
2293
- #resizeCleanup;
2294
- async onStart() {
2295
- this.#resizeCleanup = this.context.resized.on(() => {
2296
- if (this.#dataNodes.length) {
2297
- this.doTreeLayout();
2298
- this.emitUpdate("topology");
2299
- this.animate();
2300
- }
2301
- });
2302
- }
2303
- async onStop() {
2304
- this.#resizeCleanup?.();
2305
- this.#resizeCleanup = void 0;
2306
- await super.onStop();
2307
- }
2308
- onUpdate(graph) {
2309
- log10("onUpdate", {
2310
- graph: {
2311
- nodes: graph?.nodes.length,
2312
- edges: graph?.edges.length
2313
- }
2314
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file12, L: 46, S: this });
2315
- this.mergeData(graph);
2316
- this.#dataNodes = [
2317
- ...this.layout.graph.nodes
2318
- ];
2319
- this.#dataEdges = [
2320
- ...this.layout.graph.edges
2321
- ];
2322
- this.doTreeLayout();
2323
- this.emitUpdate("topology");
2324
- this.animate();
2325
- }
2326
- onTickFrame(_t) {
2327
- for (const edge of this.layout.graph.edges) {
2328
- if (edge.type !== "hierarchy") {
2329
- continue;
2330
- }
2331
- const { source, target } = edge;
2332
- edge.path = linkPath3({
2333
- source: {
2334
- x: source.x ?? 0,
2335
- y: source.y ?? 0
2336
- },
2337
- target: {
2338
- x: target.x ?? 0,
2339
- y: target.y ?? 0
2340
- }
2341
- }) ?? void 0;
2342
- }
2343
- }
2344
- doTreeLayout() {
2345
- if (!this.context.size) {
2346
- return;
2347
- }
2348
- const dataNodes = this.#dataNodes;
2349
- if (!dataNodes.length) {
2350
- return;
2351
- }
2352
- const focusId = this.options.focus;
2353
- const focusNode = focusId ? dataNodes.find((node) => node.id === focusId) : void 0;
2354
- if (!focusNode) {
2355
- this.doRadialLayout();
2356
- return;
2357
- }
2358
- const nodesById = new Map(dataNodes.map((node) => [
2359
- node.id,
2360
- node
2361
- ]));
2362
- const makeDatum = (id) => ({
2363
- id,
2364
- node: nodesById.get(id)
2365
- });
2366
- const outgoing = /* @__PURE__ */ new Map();
2367
- for (const edge of this.#dataEdges) {
2368
- const list = outgoing.get(edge.source.id) ?? [];
2369
- list.push(edge.target.id);
2370
- outgoing.set(edge.source.id, list);
2371
- }
2372
- const rightChildren = /* @__PURE__ */ new Map();
2373
- const visited = /* @__PURE__ */ new Set([
2374
- focusId
2375
- ]);
2376
- let frontier = [
2377
- focusId
2378
- ];
2379
- while (frontier.length) {
2380
- const next = [];
2381
- for (const id of frontier) {
2382
- for (const target of outgoing.get(id) ?? []) {
2383
- if (!visited.has(target)) {
2384
- visited.add(target);
2385
- const list = rightChildren.get(id) ?? [];
2386
- list.push(target);
2387
- rightChildren.set(id, list);
2388
- next.push(target);
2389
- }
2390
- }
2391
- }
2392
- frontier = next;
2393
- }
2394
- const leftSources = [];
2395
- for (const edge of this.#dataEdges) {
2396
- const source = edge.source.id;
2397
- if (edge.target.id === focusId && source !== focusId && !visited.has(source)) {
2398
- visited.add(source);
2399
- leftSources.push(source);
2400
- }
2401
- }
2402
- const rightRoot = hierarchy4(makeDatum(focusId), (d) => (rightChildren.get(d.id) ?? []).map(makeDatum));
2403
- const leftRoot = hierarchy4(makeDatum(focusId), (d) => d.id === focusId ? leftSources.map(makeDatum) : []);
2404
- const { width } = this.context.size;
2405
- const margin = this.options.margin ?? 80;
2406
- const rowGap = this.options.rowGap ?? 28;
2407
- const maxColumnGap = this.options.maxColumnGap ?? 300;
2408
- const sideDepth = Math.max(1, rightRoot.height, leftRoot.height);
2409
- const columnGap = Math.min(maxColumnGap, Math.max(0, (width / 2 - margin) / sideDepth));
2410
- const layoutTree = d3Tree().nodeSize([
2411
- rowGap,
2412
- columnGap
2413
- ]);
2414
- const rightPoint = layoutTree(rightRoot);
2415
- const leftPoint = layoutTree(leftRoot);
2416
- const nodeR = this.options.nodeRadius ?? 6;
2417
- const rootR = this.options.rootRadius ?? nodeR * 2;
2418
- const placed = [];
2419
- updateNode(focusNode, [
2420
- 0,
2421
- 0
2422
- ], rootR);
2423
- focusNode.type = TREE_NODE_TYPE_ROOT;
2424
- placed.push(focusNode);
2425
- const rightBreadth = rightPoint.x;
2426
- rightPoint.each((d) => {
2427
- if (d.data.id === focusId || !d.data.node) {
2428
- return;
2429
- }
2430
- updateNode(d.data.node, [
2431
- d.y,
2432
- d.x - rightBreadth
2433
- ], nodeR);
2434
- d.data.node.type = TREE_NODE_TYPE_NODE;
2435
- placed.push(d.data.node);
2436
- });
2437
- const leftBreadth = leftPoint.x;
2438
- leftPoint.each((d) => {
2439
- if (d.data.id === focusId || !d.data.node) {
2440
- return;
2441
- }
2442
- updateNode(d.data.node, [
2443
- -d.y,
2444
- d.x - leftBreadth
2445
- ], nodeR);
2446
- d.data.node.type = TREE_NODE_TYPE_INBOUND;
2447
- placed.push(d.data.node);
2448
- });
2449
- this.layout.graph.nodes = placed;
2450
- const edges = [];
2451
- const addLinks = (root, reverse = false) => {
2452
- root.links().forEach((link) => {
2453
- const parent = link.source.data;
2454
- const child = link.target.data;
2455
- const [from, to] = reverse ? [
2456
- child,
2457
- parent
2458
- ] : [
2459
- parent,
2460
- child
2461
- ];
2462
- if (!from.node || !to.node) {
2463
- return;
2464
- }
2465
- edges.push({
2466
- id: `${HIER_EDGE_PREFIX3}${from.id}->${to.id}`,
2467
- type: "hierarchy",
2468
- source: from.node,
2469
- target: to.node,
2470
- data: void 0
2471
- });
2472
- });
2473
- };
2474
- addLinks(rightPoint);
2475
- addLinks(leftPoint, true);
2476
- this.layout.graph.edges = edges;
2477
- this.onTickFrame(0);
2478
- }
2479
- };
2480
-
2481
- // src/graph/renderer/graph-renderer.ts
2482
- import { easeCubicOut, line as line2, polygonHull, select as select4 } from "d3";
2483
- import * as Clipper from "js-clipper";
2484
- import { log as log11 } from "@dxos/log";
2485
-
2486
- // src/graph/renderer/bullets.ts
2487
- import { easeLinear, interpolate, select as select3 } from "d3";
2488
- var createBullets = (group, nodeId, options = {}) => {
2489
- return (selection) => {
2490
- const { max = 32, radius = 3, delay = 50, minDuration = 100, maxDuration = 500 } = options;
2491
- selection.each(function(d, i, edges) {
2492
- const { source, target } = d;
2493
- if (source.id === nodeId) {
2494
- const path = select3(edges[i]);
2495
- const p = path.node().getPointAtLength(0);
2496
- const bullet = select3(group).append("circle").attr("class", "dx-bullet").attr("cx", p.x).attr("cy", p.y).attr("r", radius);
2497
- bullet.transition().delay(delay).duration(minDuration + Math.random() * maxDuration).ease(easeLinear).tween("pathTween", function() {
2498
- const length = path.node().getTotalLength();
2499
- const r = interpolate(0, length);
2500
- return (t) => {
2501
- const point = path.node().getPointAtLength(r(t));
2502
- select3(this).attr("cx", point.x).attr("cy", point.y);
2503
- };
2504
- }).on("end", function() {
2505
- select3(this).remove();
2506
- const num = select3(group).selectAll("circle.dx-bullet").size();
2507
- if (num < max) {
2508
- selection.call(createBullets(group, target.id));
2509
- }
2510
- });
2511
- }
2512
- });
2513
- };
2514
- };
2515
-
2516
- // src/graph/renderer/renderer.ts
2517
- var Renderer = class {
2518
- _context;
2519
- _root;
2520
- _options;
2521
- constructor(_context, _root, options) {
2522
- this._context = _context;
2523
- this._root = _root;
2524
- this._options = Object.assign({
2525
- idAccessor: defaultIdAccessor
2526
- }, options);
2527
- }
2528
- get context() {
2529
- return this._context;
2530
- }
2531
- /**
2532
- * Returns the SVG group root if mounted.
2533
- * The ref may be null between mount/unmount cycles or before the SVG container has sized.
2534
- * Callers should treat null as "skip this render" rather than as an error.
2535
- */
2536
- get root() {
2537
- return this._root.current;
2538
- }
2539
- get options() {
2540
- return this._options;
2541
- }
2542
- /**
2543
- * Fast path invoked when only positions changed.
2544
- * Default falls back to a full `render`; subclasses can override to skip
2545
- * enter/exit joins and attribute callbacks for per-tick updates.
2546
- */
2547
- applyPositions(layout) {
2548
- this.render(layout);
2549
- }
2550
- };
2551
-
2552
- // src/graph/renderer/graph-renderer.ts
2553
- var __dxlog_file13 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/graph-renderer.ts";
2554
- var createLine2 = line2();
2555
- var EDGE_FADE_MS = 300;
2556
- var NODE_HIDE_MS = 500;
2557
- var GraphRenderer = class extends Renderer {
2558
- // First render of this instance — used to clear DOM left behind by a previous
2559
- // renderer pointing at the same `<g>` (e.g. when the consumer swaps projectors
2560
- // and a new renderer is constructed for the same SVG root). Without this, the
2561
- // previous variant's node shapes (e.g. circles) would persist as d3.join sees
2562
- // them in the `update` set instead of `enter`.
2563
- #firstRender = true;
2564
- render(layout) {
2565
- if (!this.root) {
2566
- return;
2567
- }
2568
- if (this.#firstRender) {
2569
- this.#firstRender = false;
2570
- this.root.replaceChildren();
2571
- }
2572
- log11("render", layout, { "~LogMeta": "~LogMeta", F: __dxlog_file13, L: 35, S: this });
2573
- const root = select4(this.root);
2574
- if (layout.guides) {
2575
- root.selectAll("g.dx-guides").data([
2576
- {
2577
- id: "guides"
2578
- }
2579
- ]).join("g").classed("dx-guides", true).selectAll("circle").data(layout.guides ?? []).join((enter) => enter.append("circle").attr("r", 0), (update) => update, (exit) => exit.transition().duration(500).attr("r", 0).remove()).attr("cx", (d) => d.cx).attr("cy", (d) => d.cy).attr("r", (d) => d.r);
2580
- }
2581
- const scale = 100;
2582
- const offsetDistance = 24 * scale;
2583
- if (this._options.subgraphs) {
2584
- const components = this._options.subgraphs ? findConnectedComponents({
2585
- nodes: layout.graph?.nodes ?? [],
2586
- edges: (layout.graph?.edges ?? []).map(({ source, target }) => ({
2587
- source: source.id,
2588
- target: target.id
2589
- }))
2590
- }).filter((component) => component.length > 2).map((component, i) => ({
2591
- id: `subgraph-${i}`,
2592
- component
2593
- })) : [];
2594
- root.selectAll("g.dx-subgraphs").data([
2595
- {
2596
- id: "subgraphs"
2597
- }
2598
- ]).join("g").classed("dx-subgraphs", true).selectAll("path").data(components).join((enter) => enter.append("path").classed("dx-subgraph", true), (update) => {
2599
- return update.attr("d", ({ component }) => {
2600
- const points = layout.graph?.nodes.filter((node) => component.includes(node.id)).map((node) => [
2601
- node.x,
2602
- node.y
2603
- ]) ?? [];
2604
- const hullPoints = polygonHull(points);
2605
- const co = new Clipper.ClipperOffset();
2606
- const solution = [];
2607
- const clipperPath = hullPoints.map(([x, y]) => ({
2608
- X: x * scale,
2609
- Y: y * scale
2610
- }));
2611
- co.AddPath(clipperPath, Clipper.JoinType.jtRound, Clipper.EndType.etClosedPolygon);
2612
- co.Execute(solution, offsetDistance);
2613
- if (solution.length > 0) {
2614
- const offset = solution[0].map(({ X, Y }) => [
2615
- X / scale,
2616
- Y / scale
2617
- ]);
2618
- return createLine2([
2619
- ...offset,
2620
- offset[0]
2621
- ]);
2622
- }
2623
- });
2624
- });
2625
- }
2626
- const edgeGroup = root.selectAll("g.dx-edges").data([
2627
- {
2628
- id: "edges"
2629
- }
2630
- ], (d) => d.id).join("g").classed("dx-edges", true).style("opacity", this.options.edgeOpacity != null ? String(this.options.edgeOpacity) : null);
2631
- const nodeGroup = root.selectAll("g.dx-nodes").data([
2632
- {
2633
- id: "nodes"
2634
- }
2635
- ], (d) => d.id).join("g").classed("dx-nodes", true);
2636
- nodeGroup.selectAll("g.dx-node").data(layout.graph?.nodes ?? [], (d) => d.id).join((enter) => enter.append("g").attr("data-id", (d) => d.id).attr("opacity", (d) => d.hidden ? 0 : 1).classed("dx-node", true).call(createNode, this.options), (update) => update, (exit) => {
2637
- return exit.transition().ease(easeCubicOut).duration(300).attr("opacity", 0).on("end", function(d) {
2638
- select4(this).remove();
2639
- });
2640
- }).call(updateNode2, this.options).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
2641
- edgeGroup.selectAll("g.dx-edge").data(layout.graph?.edges ?? [], (d) => d.id).join(
2642
- (enter) => enter.append("g").attr("data-id", (d) => d.id).classed("dx-edge", true).call(createEdge, this.options),
2643
- (update) => update,
2644
- // Exit fade: edges removed by a topology change (e.g. variant switch from cluster
2645
- // back to force replaces hierarchy edges with data edges) ease out rather than pop.
2646
- (exit) => exit.transition().ease(easeCubicOut).duration(EDGE_FADE_MS).attr("opacity", 0).on("end", function() {
2647
- select4(this).remove();
2648
- })
2649
- ).call(updateEdge, this.options, nodeGroup).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
2650
- }
2651
- /**
2652
- * Fast positions-only update. Skips enter/exit, attribute callbacks, label sizing,
2653
- * and the subgraph hull pass; just writes `transform` per node and `d` per edge.
2654
- * Called per simulation tick / animation frame.
2655
- */
2656
- applyPositions(layout) {
2657
- if (!this.root) {
2658
- return;
2659
- }
2660
- const root = select4(this.root);
2661
- const applyNode = this.options.applyNode;
2662
- root.select("g.dx-nodes").selectAll("g.dx-node").attr("transform", (d) => d.x != null && d.y != null ? `translate(${d.x},${d.y})` : null).each(applyNode ? function(d) {
2663
- applyNode(this, d);
2664
- } : () => {
2665
- });
2666
- root.select("g.dx-edges").selectAll("g.dx-edge").selectAll("path").attr("d", function() {
2667
- const edge = select4(this.parentElement).datum();
2668
- if (edge.path) {
2669
- return edge.path;
2670
- }
2671
- const { source, target } = edge;
2672
- if (!source.initialized || !target.initialized) {
2673
- return null;
2674
- }
2675
- return createLine2(getCircumferencePoints([
2676
- source.x,
2677
- source.y
2678
- ], [
2679
- target.x,
2680
- target.y
2681
- ], source.r, target.r));
2682
- });
2683
- }
2684
- /**
2685
- * Trigger path bullets.
2686
- * @param node
2687
- */
2688
- fireBullet(node) {
2689
- if (!this.root) {
2690
- return;
2691
- }
2692
- select4(this.root).selectAll("g.dx-edges").selectAll("path").call(createBullets(this.root, node.id));
2693
- }
2694
- };
2695
- var SHAPE_CLASS = "dx-shape";
2696
- var renderCustomShape = (group, options) => {
2697
- group.each(function(d) {
2698
- const g = select4(this);
2699
- g.selectAll(`.${SHAPE_CLASS}`).remove();
2700
- const shapeGroup = g.append("g").classed(SHAPE_CLASS, true);
2701
- options.renderNode(shapeGroup, d);
2702
- });
2703
- };
2704
- var createNode = (group, options) => {
2705
- const useCustom = !!options.renderNode;
2706
- if (useCustom) {
2707
- renderCustomShape(group, options);
2708
- }
2709
- const hitTarget = useCustom ? group : group.append("circle");
2710
- if (options.drag) {
2711
- hitTarget.call(options.drag);
2712
- }
2713
- if (options.onNodeClick) {
2714
- group.on("click", (event, d) => {
2715
- options.onNodeClick(d, event);
2716
- });
2717
- }
2718
- if (options.labels && !options.onNodePointerEnter) {
2719
- const g = group.append("g").classed("dx-label", true);
2720
- g.append("line");
2721
- g.append("rect");
2722
- g.append("text").style("dominant-baseline", "middle");
2723
- }
2724
- if (options.onNodePointerEnter || options.onNodePointerLeave || options.highlightOnHover) {
2725
- hitTarget.on("pointerenter", function(event) {
2726
- const node = select4(useCustom ? this : this.parentElement).datum();
2727
- options.onNodePointerEnter?.(node, event);
2728
- if (options.highlightOnHover) {
2729
- applyHoverHighlight(this.closest("g.dx-graph"), node.id);
2730
- }
2731
- });
2732
- hitTarget.on("pointerleave", function(event) {
2733
- const node = select4(useCustom ? this : this.parentElement).datum();
2734
- options.onNodePointerLeave?.(node, event);
2735
- if (options.highlightOnHover) {
2736
- applyHoverHighlight(this.closest("g.dx-graph"), null);
2737
- }
2738
- });
2739
- group.attr("data-hover", "handled");
2740
- } else if (options.highlight !== false && !useCustom) {
2741
- hitTarget.on("pointerenter", function() {
2742
- select4(this.closest("g.dx-node")).raise();
2743
- if (options.labels) {
2744
- select4(this.parentElement).classed("dx-node-active", true).classed("dx-highlight", true);
2745
- }
2746
- });
2747
- group.on("pointerleave", function() {
2748
- if (options.labels) {
2749
- select4(this).classed("dx-node-active", false);
2750
- setTimeout(() => {
2751
- if (!select4(this).classed("dx-node-active")) {
2752
- select4(this).classed("dx-highlight", false);
2753
- }
2754
- }, 300);
2755
- }
2756
- });
2757
- }
2758
- };
2759
- var updateNode2 = (group, options) => {
2760
- group.attr("transform", (d) => {
2761
- return d.x != null && d.y != null ? `translate(${d.x},${d.y})` : void 0;
2762
- });
2763
- group.classed("dx-hidden", (d) => d.hidden ?? false);
2764
- group.transition("hide").ease(easeCubicOut).duration(NODE_HIDE_MS).attr("opacity", (d) => d.hidden ? 0 : 1);
2765
- if (options.renderNode) {
2766
- renderCustomShape(group, options);
2767
- }
2768
- if (options.attributes?.node) {
2769
- try {
2770
- group.each((d, i, nodes) => {
2771
- const node = select4(nodes[i]);
2772
- const { classes, data } = options.attributes?.node?.(d) ?? {};
2773
- if (classes) {
2774
- applyClasses(node, classes);
2775
- }
2776
- if (data) {
2777
- Object.entries(data).forEach(([key, value]) => {
2778
- node.attr(`data-${key}`, value);
2779
- });
2780
- }
2781
- });
2782
- } catch (error) {
2783
- log11.error("updateNode", {
2784
- error: error?.message
2785
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file13, L: 303, S: void 0 });
2786
- }
2787
- }
2788
- const groupOrTransition = options.transition ? group.transition(options.transition()) : group;
2789
- if (!options.renderNode) {
2790
- groupOrTransition.select("circle").attr("r", (d) => d.r ?? 16);
2791
- }
2792
- if (options.labels) {
2793
- const bx = 1;
2794
- const px = 4;
2795
- const py = 2;
2796
- const offset = 16;
2797
- const dx = (d, offset2 = 0) => (offset2 + (d.r ?? 0)) * (d.x > 0 ? 1 : -1);
2798
- groupOrTransition.select("text").text((d) => options.labels.text(d)).style("text-anchor", (d) => d.x > 0 ? "start" : "end").attr("dx", (d) => dx(d, offset)).attr("dy", 1).text((d) => options.labels.text(d)).each(function(d) {
2799
- let bbox = d.bbox;
2800
- if (!bbox) {
2801
- bbox = this.getBBox();
2802
- d.bbox = bbox;
2803
- }
2804
- const width = bbox.width + (bx + px) * 2;
2805
- const height = bbox.height + py * 2;
2806
- select4(this.parentElement).select("rect").attr("x", dx(d, offset - (bx + px)) + (d.x > 0 ? 0 : -1) * width).attr("y", -height / 2).attr("width", width).attr("height", height).attr("rx", 4);
2807
- select4(this.parentElement).select("line").attr("x1", dx(d, 1)).attr("y1", 0).attr("x2", dx(d, offset - (bx + px))).attr("y2", 0);
2808
- });
2809
- }
2810
- };
2811
- var createEdge = (group, options) => {
2812
- if (options.onLinkClick) {
2813
- group.append("path").classed("dx-click", true).on("click", (event) => {
2814
- const edge = select4(event.target).datum();
2815
- options.onLinkClick(edge, event);
2816
- });
2817
- }
2818
- group.append("path").attr("pointer-events", "none").attr("marker-start", () => options.arrows?.start ? "url(#marker-arrow-start)" : void 0).attr("marker-end", () => options.arrows?.end ? "url(#marker-arrow-end)" : void 0);
2819
- };
2820
- var updateEdge = (group, options, nodeGroup) => {
2821
- try {
2822
- group.each((d, i, edges) => {
2823
- const edge = select4(edges[i]);
2824
- edge.classed("dx-dashed", d.linkForce === false);
2825
- const { classes, data } = options.attributes?.edge?.(d) ?? {};
2826
- if (classes) {
2827
- applyClasses(edge, classes);
2828
- }
2829
- if (data) {
2830
- Object.entries(data).forEach(([key, value]) => {
2831
- edge.attr(`data-${key}`, value);
2832
- });
2833
- }
2834
- });
2835
- } catch (error) {
2836
- log11.error("updateEdge", {
2837
- error: error?.message
2838
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file13, L: 371, S: void 0 });
2839
- }
2840
- const groupOrTransition = options.transition ? group.transition(options.transition()) : group;
2841
- groupOrTransition.selectAll("path").attr("d", function() {
2842
- const edge = select4(this.parentElement).datum();
2843
- if (edge.path) {
2844
- return edge.path;
2845
- }
2846
- const { source, target } = edge;
2847
- if (!source.initialized || !target.initialized) {
2848
- return;
2849
- }
2850
- return createLine2(getCircumferencePoints([
2851
- source.x,
2852
- source.y
2853
- ], [
2854
- target.x,
2855
- target.y
2856
- ], source.r, target.r));
2857
- });
2858
- };
2859
- var applyHoverHighlight = (root, focusedId) => {
2860
- if (!root) {
2861
- return;
2862
- }
2863
- const r = select4(root);
2864
- const on = focusedId != null;
2865
- const outgoing = /* @__PURE__ */ new Set();
2866
- const incoming = /* @__PURE__ */ new Set();
2867
- if (on) {
2868
- r.select("g.dx-edges").selectAll("g.dx-edge").each((edge) => {
2869
- if (edge.source.id === focusedId) {
2870
- outgoing.add(edge.target.id);
2871
- }
2872
- if (edge.target.id === focusedId) {
2873
- incoming.add(edge.source.id);
2874
- }
2875
- });
2876
- }
2877
- r.select("g.dx-edges").selectAll("g.dx-edge").each(function(edge) {
2878
- const path = select4(this).select("path:not(.dx-click)");
2879
- if (!on) {
2880
- path.style("stroke", null).style("stroke-width", null).style("opacity", null);
2881
- return;
2882
- }
2883
- if (edge.source.id === focusedId) {
2884
- path.style("stroke", "var(--color-orange-500)").style("stroke-width", "1.5px").style("opacity", null);
2885
- } else if (edge.target.id === focusedId) {
2886
- path.style("stroke", "var(--color-sky-500)").style("stroke-width", "1.5px").style("opacity", null);
2887
- } else {
2888
- path.style("stroke", null).style("stroke-width", null).style("opacity", "0.8");
2889
- }
2890
- });
2891
- r.select("g.dx-nodes").selectAll("g.dx-node").each(function(node) {
2892
- const groupSel = select4(this);
2893
- const shape = groupSel.select("circle, rect");
2894
- if (node.hidden) {
2895
- return;
2896
- }
2897
- if (!on) {
2898
- groupSel.style("opacity", null);
2899
- shape.style("stroke", null).style("stroke-width", null);
2900
- return;
2901
- }
2902
- const connected = outgoing.has(node.id) || incoming.has(node.id);
2903
- if (node.id === focusedId) {
2904
- groupSel.style("opacity", null);
2905
- shape.style("stroke", null).style("stroke-width", null);
2906
- } else if (connected) {
2907
- groupSel.style("opacity", null);
2908
- shape.style("stroke", "var(--color-orange-400)").style("stroke-width", "2.5px");
2909
- } else {
2910
- groupSel.style("opacity", "0.4");
2911
- shape.style("stroke", null).style("stroke-width", null);
2912
- }
2913
- });
2914
- };
2915
- var applyClasses = (el, classes) => {
2916
- for (const [className, value] of Object.entries(classes)) {
2917
- el.classed(className, value);
2918
- }
2919
- };
2920
- var findConnectedComponents = (graph) => {
2921
- const adj = {};
2922
- for (const node of graph.nodes) {
2923
- adj[node.id] = [];
2924
- }
2925
- for (const { source, target } of graph.edges) {
2926
- adj[source].push(target);
2927
- adj[target].push(source);
2928
- }
2929
- const visited = /* @__PURE__ */ new Set();
2930
- const components = [];
2931
- for (const node of graph.nodes) {
2932
- if (visited.has(node.id)) {
2933
- continue;
2934
- }
2935
- const stack = [
2936
- node.id
2937
- ];
2938
- const componentIds = [];
2939
- while (stack.length) {
2940
- const current = stack.pop();
2941
- if (visited.has(current)) {
2942
- continue;
2943
- }
2944
- visited.add(current);
2945
- componentIds.push(current);
2946
- stack.push(...adj[current]);
2947
- }
2948
- components.push(componentIds);
2949
- }
2950
- return components;
2951
- };
2952
-
2953
- // src/graph/renderer/labels.ts
2954
- var DEFAULT_DURATION = 200;
2955
- var DEFAULT_OFFSET = 4;
2956
- var getTarget = (node) => {
2957
- const tx = node.tx;
2958
- const ty = node.ty;
2959
- return {
2960
- x: tx ?? node.x ?? 0,
2961
- y: ty ?? node.y ?? 0
2962
- };
2963
- };
2964
- var appendRadialLeafLabel = (group, node, label, r, options = {}) => {
2965
- if (!label) {
2966
- return;
2967
- }
2968
- const { delay = 0, duration = DEFAULT_DURATION, offset = DEFAULT_OFFSET, className = "dx-cluster-label" } = options;
2969
- const { x: targetX, y: targetY } = getTarget(node);
2970
- const angleDeg = Math.atan2(targetY, targetX) * 180 / Math.PI;
2971
- const flipped = angleDeg > 90 || angleDeg < -90;
2972
- group.append("text").attr("class", className).attr("dy", "0.32em").attr("transform", `rotate(${flipped ? angleDeg + 180 : angleDeg})`).attr("x", flipped ? -(r + offset) : r + offset).attr("text-anchor", flipped ? "end" : "start").attr("opacity", 0).style("cursor", "pointer").text(label).transition().delay(delay).duration(duration).attr("opacity", 1);
2973
- };
2974
- var appendRadialGroupLabel = (group, node, label, r, options = {}) => {
2975
- if (!label) {
2976
- return;
2977
- }
2978
- const { delay = 0, duration = DEFAULT_DURATION, offset = DEFAULT_OFFSET, className = "dx-cluster-label dx-cluster-label-group" } = options;
2979
- const { x: targetX, y: targetY } = getTarget(node);
2980
- const angleDeg = Math.atan2(targetY, targetX) * 180 / Math.PI;
2981
- const flipped = angleDeg > 90 || angleDeg < -90;
2982
- group.append("text").attr("class", className).attr("dy", "0.32em").attr("transform", `rotate(${flipped ? angleDeg + 180 : angleDeg})`).attr("x", flipped ? r + offset : -(r + offset)).attr("text-anchor", flipped ? "start" : "end").attr("opacity", 0).style("pointer-events", "none").text(label).transition().delay(delay).duration(duration).attr("opacity", 1);
2983
- };
2984
- var appendRootLabel = (group, label, r, options = {}) => {
2985
- if (!label) {
2986
- return;
2987
- }
2988
- const { delay = 0, duration = DEFAULT_DURATION, offset = 6, className = "dx-cluster-label dx-cluster-label-root" } = options;
2989
- group.append("text").attr("class", className).attr("text-anchor", "middle").attr("y", -(r + offset)).attr("opacity", 0).style("pointer-events", "none").text(label).transition().delay(delay).duration(duration).attr("opacity", 1);
2990
- };
2991
-
2992
- // src/graph/renderer/linker.ts
2993
- import { line as line3 } from "d3";
2994
- var createLine3 = line3();
2995
- var linkerRenderer = (root, { source, target, point } = {}) => {
2996
- root.selectAll("g.dx-linker").data([
2997
- {
2998
- id: "linker"
2999
- }
3000
- ]).join("g").attr("class", "dx-linker").selectAll("path").data(source ? [
3001
- {
3002
- id: "edge"
3003
- }
3004
- ] : []).join("path").attr("marker-end", () => target ? "url(#marker-arrow-end)" : "url(#marker-dot)").attr("d", () => {
3005
- return createLine3(getCircumferencePoints([
3006
- source.x,
3007
- source.y
3008
- ], target ? [
3009
- target.x,
3010
- target.y
3011
- ] : point, source.r, target ? target.r : 0));
3012
- });
3013
- };
3014
-
3015
- // src/hooks/useGrid.ts
3016
- import { line as line4, range, select as select5 } from "d3";
3017
- import { useEffect, useMemo, useRef } from "react";
3018
-
3019
- // src/hooks/useSvgContext.ts
3020
- import { createContext, useContext } from "react";
3021
- import { createRef } from "react";
3022
- import { raise } from "@dxos/debug";
3023
- var SVGContext = class {
3024
- _ref = createRef();
3025
- _scale;
3026
- _centered;
3027
- _size;
3028
- _center;
3029
- resized = new EventEmitter();
3030
- constructor({ scale = new Scale(), centered = true }) {
3031
- this._scale = scale;
3032
- this._centered = centered;
3033
- }
3034
- get ref() {
3035
- return this._ref;
3036
- }
3037
- get svg() {
3038
- return this._ref.current;
3039
- }
3040
- get scale() {
3041
- return this._scale;
3042
- }
3043
- get center() {
3044
- return this._center;
3045
- }
3046
- get size() {
3047
- return this._size;
3048
- }
3049
- /**
3050
- * https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
3051
- */
3052
- get viewBox() {
3053
- const [x, y] = this.center;
3054
- return `${x},${y},${this._size.width},${this._size.height}`;
3055
- }
3056
- setSize(size) {
3057
- this._size = {
3058
- ...size
3059
- };
3060
- this._center = this._centered ? [
3061
- -Math.floor(size.width / 2),
3062
- -Math.floor(size.height / 2)
3063
- ] : [
3064
- 0,
3065
- 0
3066
- ];
3067
- this.resized.emit(this);
3068
- }
3069
- setTransform(transform) {
3070
- if (this._scale.setTransform(transform)) {
3071
- this.resized.emit(this);
3072
- }
3073
- }
3074
- /**
3075
- * https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint
3076
- * @param point
3077
- */
3078
- elementFromPoint(point) {
3079
- const [x, y] = point;
3080
- const [cx, cy] = this._center;
3081
- return document.elementFromPoint(cx + x, cy + y);
3082
- }
3083
- };
3084
- var SVGContextType = createContext(void 0);
3085
- var SVGContextProvider = SVGContextType.Provider;
3086
- var useSvgContext = () => {
3087
- return useContext(SVGContextType) ?? raise(new Error("Missing SVGRoot"));
3088
- };
3089
-
3090
- // src/hooks/useGrid.ts
3091
- var createLine4 = line4();
3092
- var createGrid = (context, options) => {
3093
- if (!context.size) {
3094
- return [];
3095
- }
3096
- const paths = [];
3097
- const { width, height } = context.size;
3098
- const { x, y, k } = context.scale.transform;
3099
- const s = 1 / k;
3100
- const w = width * s;
3101
- const h = height * s;
3102
- const dx = -(x + width / 2) * s;
3103
- const dy = -(y + height / 2) * s;
3104
- if (options.axis) {
3105
- const axis = [
3106
- [
3107
- [
3108
- 0,
3109
- dy
3110
- ],
3111
- [
3112
- 0,
3113
- dy + h
3114
- ]
3115
- ],
3116
- [
3117
- [
3118
- dx,
3119
- 0
3120
- ],
3121
- [
3122
- dx + w,
3123
- 0
3124
- ]
3125
- ]
3126
- ];
3127
- paths.push({
3128
- id: "axis",
3129
- class: "dx-axis",
3130
- path: axis.map((line5) => createLine4(line5)).join()
3131
- });
3132
- }
3133
- if (options.grid) {
3134
- const mod = (n, size, delta = 0) => Math.floor(n / size + delta) * size;
3135
- const majorSize = context.scale.gridSize;
3136
- const xMajor = range(-mod((x + width / 2) * s, majorSize), mod((-x + width / 2) * s, majorSize, 1), majorSize);
3137
- const yMajor = range(-mod((y + height / 2) * s, majorSize), mod((-y + height / 2) * s, majorSize, 1), majorSize);
3138
- const major = [
3139
- ...xMajor.filter((x2) => !options.axis || x2).map((x2) => [
3140
- [
3141
- x2,
3142
- dy
3143
- ],
3144
- [
3145
- x2,
3146
- dy + h
3147
- ]
3148
- ]),
3149
- ...yMajor.filter((y2) => !options.axis || y2).map((y2) => [
3150
- [
3151
- dx,
3152
- y2
3153
- ],
3154
- [
3155
- dx + w,
3156
- y2
3157
- ]
3158
- ])
3159
- ];
3160
- paths.push({
3161
- id: "major",
3162
- class: "dx-major",
3163
- path: major.map((line5) => createLine4(line5)).join()
3164
- });
3165
- const minorSize = Math.pow(2, Math.round(Math.log2(s * context.scale.gridSize)));
3166
- if (majorSize > minorSize) {
3167
- const xMinor = range(-mod((x + width / 2) * s, minorSize), mod((-x + width / 2) * s, minorSize, 1), minorSize);
3168
- const yMinor = range(-mod((y + height / 2) * s, minorSize), mod((-y + height / 2) * s, minorSize, 1), minorSize);
3169
- const minor = [
3170
- ...xMinor.filter((x2) => xMajor.indexOf(x2) === -1).map((x2) => [
3171
- [
3172
- x2,
3173
- dy
3174
- ],
3175
- [
3176
- x2,
3177
- dy + h
3178
- ]
3179
- ]),
3180
- ...yMinor.filter((y2) => yMajor.indexOf(y2) === -1).map((y2) => [
3181
- [
3182
- dx,
3183
- y2
3184
- ],
3185
- [
3186
- dx + w,
3187
- y2
3188
- ]
3189
- ])
3190
- ];
3191
- paths.push({
3192
- id: "minor",
3193
- class: "dx-minor",
3194
- path: minor.map((line5) => createLine4(line5)).join()
3195
- });
3196
- }
3197
- }
3198
- return paths;
3199
- };
3200
- var defaultGridOptions = {
3201
- visible: true,
3202
- axis: true,
3203
- grid: true
3204
- };
3205
- var GridController = class {
3206
- _ref;
3207
- _context;
3208
- _options;
3209
- _visible = false;
3210
- constructor(_ref, _context, _options) {
3211
- this._ref = _ref;
3212
- this._context = _context;
3213
- this._options = _options;
3214
- this._visible = this._options.visible ?? true;
3215
- }
3216
- get ref() {
3217
- return this._ref;
3218
- }
3219
- get visible() {
3220
- return this._visible;
3221
- }
3222
- draw() {
3223
- if (!this._context.size) {
3224
- return;
3225
- }
3226
- const paths = this._visible ? createGrid(this._context, this._options) : [];
3227
- const root = select5(this._ref.current);
3228
- root.selectAll("path").data(paths, (path) => path.id).join("path").style("pointer-events", "none").attr("d", (d) => d.path).attr("class", (d) => d.class);
3229
- const transform = this._context.scale.transform;
3230
- if (transform) {
3231
- root.attr("transform", transform);
3232
- root.attr("stroke-width", 1 / transform.k);
3233
- }
3234
- }
3235
- setVisible(visible) {
3236
- this._visible = visible;
3237
- this.draw();
3238
- return this;
3239
- }
3240
- };
3241
- var useGrid = (options = defaultGridOptions) => {
3242
- const ref = useRef(null);
3243
- const context = useSvgContext();
3244
- const controller = useMemo(() => new GridController(ref, context, options), []);
3245
- useEffect(() => context.resized.on(() => controller.draw()), [
3246
- context,
3247
- controller
3248
- ]);
3249
- return controller;
3250
- };
3251
-
3252
- // src/hooks/useZoom.ts
3253
- import { select as select6, zoom, zoomIdentity as zoomIdentity2 } from "d3";
3254
- import defaultsDeep from "lodash.defaultsdeep";
3255
- import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2 } from "react";
3256
- var defaultZoomOptions = {
3257
- enabled: true,
3258
- extent: [
3259
- 1 / 4,
3260
- 4
3261
- ],
3262
- onDblClick: (zoom2) => zoom2.reset()
3263
- };
3264
- var ZoomHandler = class {
3265
- _ref;
3266
- _context;
3267
- _zoom;
3268
- _options;
3269
- _enabled;
3270
- constructor(_ref, _context, options) {
3271
- this._ref = _ref;
3272
- this._context = _context;
3273
- this._options = defaultsDeep({}, options, defaultZoomOptions);
3274
- this._enabled = this._options.enabled ?? true;
3275
- this._zoom = zoom().scaleExtent(this._options.extent ?? defaultZoomOptions.extent);
3276
- }
3277
- /**
3278
- * Gets the reference which the transform is applied to.
3279
- */
3280
- get ref() {
3281
- return this._ref;
3282
- }
3283
- get zoom() {
3284
- return this._zoom;
3285
- }
3286
- init() {
3287
- this.setEnabled(this._enabled);
3288
- this.reset(0);
3289
- return this;
3290
- }
3291
- setEnabled(enable) {
3292
- if (enable) {
3293
- select6(this._context.svg).call(this._zoom).on(
3294
- "dblclick.zoom",
3295
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3296
- // @ts-ignore
3297
- this._options?.onDblClick ? () => {
3298
- this._options?.onDblClick(this);
3299
- } : null
3300
- );
3301
- } else {
3302
- select6(this._context.svg).on(".zoom", null);
3303
- }
3304
- this._enabled = enable;
3305
- return this;
3306
- }
3307
- reset(duration = 500) {
3308
- const scale = 1;
3309
- const transform = zoomIdentity2.scale(scale);
3310
- select6(this._context.svg).transition().duration(duration).call(this._zoom.transform, transform);
3311
- return this;
3312
- }
3313
- };
3314
- var useZoom = (options = defaultZoomOptions) => {
3315
- const context = useSvgContext();
3316
- const ref = useRef2(null);
3317
- const handler = useMemo2(() => new ZoomHandler(ref, context, options), [
3318
- context,
3319
- options
3320
- ]);
3321
- useEffect2(() => {
3322
- handler.zoom.on("zoom", ({ transform }) => {
3323
- context.setTransform(transform);
3324
- select6(ref.current).attr("transform", transform);
3325
- });
3326
- handler.init();
3327
- }, [
3328
- handler
3329
- ]);
3330
- return handler;
3331
- };
3332
-
3333
- // src/components/Graph/Graph.tsx
3334
- var __dxlog_file14 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/components/Graph/Graph.tsx";
3335
- var GraphInner = ({ classNames, model, projector: projectorProp, renderer: rendererProp, drag: drag2, arrows, onSelect, onInspect, onPointerMove, onPointerLeave, ...props }, forwardedRef) => {
3336
- const context = useSvgContext();
3337
- const graphRef = useRef3(null);
3338
- const { projector, renderer } = useMemo3(() => {
3339
- let projector2 = projectorProp;
3340
- if (!projector2) {
3341
- projector2 = new GraphForceProjector(context);
3342
- }
3343
- let renderer2 = rendererProp;
3344
- if (!renderer2) {
3345
- renderer2 = new GraphRenderer(context, graphRef, {
3346
- ...props,
3347
- // TODO(burdon): Replace drag when projector is updated.
3348
- drag: drag2 ? createGraphDrag(context, projector2) : void 0,
3349
- arrows: {
3350
- end: arrows
3351
- },
3352
- // Projector intercept first so built-in interactions (e.g. cluster collapse) can
3353
- // run without consumers wiring them. Returning true suppresses the user handler.
3354
- onNodeClick: (node, event) => {
3355
- if (projector2.handleNodeClick(node, event)) {
3356
- return;
3357
- }
3358
- onSelect?.(node, event);
3359
- },
3360
- onNodePointerEnter: onInspect ? (node, event) => onInspect(node, event) : void 0,
3361
- // Pair pointerenter with leave so consumers can clear hover-driven previews.
3362
- // The callback receives `null` on leave (event still carries the source).
3363
- onNodePointerLeave: onInspect ? (_node, event) => onInspect(null, event) : void 0
3364
- });
3365
- }
3366
- return {
3367
- projector: projector2,
3368
- renderer: renderer2
3369
- };
3370
- }, [
3371
- context,
3372
- projectorProp,
3373
- rendererProp,
3374
- drag2,
3375
- arrows,
3376
- onSelect,
3377
- onInspect,
3378
- props.labels,
3379
- props.subgraphs,
3380
- props.attributes,
3381
- props.renderNode,
3382
- props.highlightOnHover,
3383
- props.applyNode,
3384
- props.edgeOpacity
3385
- ]);
3386
- useImperativeHandle(forwardedRef, () => ({
3387
- refresh: () => {
3388
- projector.updateData(model?.graph);
3389
- },
3390
- repaint: () => {
3391
- renderer.render(projector.layout);
3392
- },
3393
- findNode: (id) => {
3394
- return graphRef.current?.querySelector(`g[data-id="${id}"]`);
3395
- }
3396
- }), [
3397
- model,
3398
- projector,
3399
- renderer
3400
- ]);
3401
- useEffect3(() => {
3402
- const cleanup = combine(
3403
- // Subscribe to model changes if reactive model.
3404
- model ? model.subscribe(() => {
3405
- projector.updateData(model?.graph);
3406
- }) : void 0,
3407
- projector.updated.on(({ layout, kind }) => {
3408
- try {
3409
- if (kind === "positions") {
3410
- renderer.applyPositions(layout);
3411
- } else {
3412
- renderer.render(layout);
3413
- }
3414
- } catch (error) {
3415
- log12.catch(error, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file14, L: 95, S: void 0 });
3416
- void projector.stop();
3417
- }
3418
- })
3419
- );
3420
- projector.updateData(model?.graph);
3421
- return cleanup;
3422
- }, [
3423
- model,
3424
- projector,
3425
- renderer
3426
- ]);
3427
- useEffect3(() => {
3428
- void projector.start();
3429
- return () => {
3430
- void projector.stop();
3431
- };
3432
- }, [
3433
- projector
3434
- ]);
3435
- useEffect3(() => {
3436
- if (!onPointerMove && !onPointerLeave) {
3437
- return;
3438
- }
3439
- const svg = context.svg;
3440
- if (!svg) {
3441
- return;
3442
- }
3443
- const previousPointerEvents = svg.style.pointerEvents;
3444
- svg.style.pointerEvents = "all";
3445
- const handleMove = (event) => {
3446
- if (!onPointerMove) {
3447
- return;
3448
- }
3449
- const target = graphRef.current;
3450
- const ctm = target?.getScreenCTM();
3451
- if (!target || !ctm) {
3452
- return;
3453
- }
3454
- const point = svg.createSVGPoint();
3455
- point.x = event.clientX;
3456
- point.y = event.clientY;
3457
- const modelPoint = point.matrixTransform(ctm.inverse());
3458
- onPointerMove({
3459
- x: modelPoint.x,
3460
- y: modelPoint.y
3461
- }, event);
3462
- };
3463
- const handleLeave = (event) => {
3464
- onPointerLeave?.(event);
3465
- };
3466
- svg.addEventListener("pointermove", handleMove);
3467
- svg.addEventListener("pointerleave", handleLeave);
3468
- return () => {
3469
- svg.removeEventListener("pointermove", handleMove);
3470
- svg.removeEventListener("pointerleave", handleLeave);
3471
- svg.style.pointerEvents = previousPointerEvents;
3472
- };
3473
- }, [
3474
- context,
3475
- onPointerMove,
3476
- onPointerLeave
3477
- ]);
3478
- return /* @__PURE__ */ React.createElement("g", {
3479
- ref: graphRef,
3480
- className: mx("dx-graph", classNames)
3481
- });
3482
- };
3483
- var Graph = /* @__PURE__ */ forwardRef(GraphInner);
3484
-
3485
- // src/components/Mesh/Mesh.tsx
3486
- import { geoPath, select as select7 } from "d3";
3487
- import { useEffect as useEffect4 } from "react";
3488
- import { feature, mesh } from "topojson-client";
3489
- var Mesh = ({ radius = 16, value = 0.5 }) => {
3490
- const { svg, size } = useSvgContext();
3491
- useEffect4(() => {
3492
- if (!size) {
3493
- return;
3494
- }
3495
- const topology = hexTopology(size, radius, value);
3496
- const projection = hexProjection(radius);
3497
- const path = geoPath().projection(projection);
3498
- const root = select7(svg).selectAll("g.dx-mesh-root").data([
3499
- null
3500
- ]).join("g").classed("dx-mesh-root", true);
3501
- root.selectAll("*").remove();
3502
- root.append("g").attr("class", "hexagon").selectAll("path").data(topology.objects.hexagons.geometries).enter().append("path").attr("d", (d) => path(feature(topology, d))).attr("class", (d) => d.properties?.fill ? "fill" : null);
3503
- root.append("path").datum(mesh(topology, topology.objects.hexagons)).attr("class", "mesh").attr("d", path);
3504
- const redraw = (border) => {
3505
- border.attr("d", path(mesh(topology, topology.objects.hexagons, (a, b) => a.properties.fill !== b.properties.fill)));
3506
- };
3507
- root.append("path").attr("class", "border").call(redraw);
3508
- }, [
3509
- svg,
3510
- size,
3511
- value,
3512
- radius
3513
- ]);
3514
- return null;
3515
- };
3516
- var hexTopology = ({ width, height }, radius, value = 1) => {
3517
- const dx = radius * 2 * Math.sin(Math.PI / 3);
3518
- const dy = radius * 1.5;
3519
- const m = Math.ceil((height + radius) / dy) + 1;
3520
- const n = Math.ceil(width / dx) + 1;
3521
- const geometries = [];
3522
- const arcs = [];
3523
- for (let j = -1; j <= m; ++j) {
3524
- for (let i = -1; i <= n; ++i) {
3525
- const y = j * 2;
3526
- const x = (i + (j & 1) / 2) * 2;
3527
- arcs.push([
3528
- [
3529
- x,
3530
- y - 1
3531
- ],
3532
- [
3533
- 1,
3534
- 1
3535
- ]
3536
- ], [
3537
- [
3538
- x + 1,
3539
- y
3540
- ],
3541
- [
3542
- 0,
3543
- 1
3544
- ]
3545
- ], [
3546
- [
3547
- x + 1,
3548
- y + 1
3549
- ],
3550
- [
3551
- -1,
3552
- 1
3553
- ]
3554
- ]);
3555
- }
3556
- }
3557
- for (let j = 0, q = 3; j < m; ++j, q += 6) {
3558
- for (let i = 0; i < n; ++i, q += 3) {
3559
- geometries.push({
3560
- type: "Polygon",
3561
- arcs: [
3562
- [
3563
- q,
3564
- q + 1,
3565
- q + 2,
3566
- ~(q + (n + 2 - (j & 1)) * 3),
3567
- ~(q - 2),
3568
- ~(q - (n + 2 + (j & 1)) * 3 + 2)
3569
- ]
3570
- ],
3571
- properties: {
3572
- fill: Math.random() > i / n * (1 / value)
3573
- }
3574
- });
3575
- }
3576
- }
3577
- const hexagons = {
3578
- type: "GeometryCollection",
3579
- geometries
3580
- };
3581
- return {
3582
- type: "Topology",
3583
- transform: {
3584
- translate: [
3585
- 0,
3586
- 0
3587
- ],
3588
- scale: [
3589
- 1,
3590
- 1
3591
- ]
3592
- },
3593
- objects: {
3594
- hexagons
3595
- },
3596
- arcs
3597
- };
3598
- };
3599
- var hexProjection = (radius) => {
3600
- const dx = radius * 2 * Math.sin(Math.PI / 3);
3601
- const dy = radius * 1.5;
3602
- return {
3603
- stream: (stream) => ({
3604
- point: (x, y) => {
3605
- stream.point(x * dx / 2, (y - (2 - (y & 1)) / 3) * dy / 2);
3606
- },
3607
- lineStart: () => {
3608
- stream.lineStart();
3609
- },
3610
- lineEnd: () => {
3611
- stream.lineEnd();
3612
- },
3613
- polygonStart: () => {
3614
- stream.polygonStart();
3615
- },
3616
- polygonEnd: () => {
3617
- stream.polygonEnd();
3618
- }
3619
- })
3620
- };
3621
- };
3622
-
3623
- // src/components/SVG/FPS.tsx
3624
- import React2, { useEffect as useEffect5, useState } from "react";
3625
- import { mx as mx2 } from "@dxos/ui-theme";
3626
- var PADDING = 8;
3627
- var FPS = ({ classNames, corner = "top-right", margin = PADDING }) => {
3628
- const context = useSvgContext();
3629
- const [size, setSize] = useState(context.size);
3630
- const [fps, setFps] = useState(null);
3631
- useEffect5(() => {
3632
- setSize(context.size);
3633
- return context.resized.on((ctx) => setSize(ctx.size));
3634
- }, [
3635
- context
3636
- ]);
3637
- useEffect5(() => {
3638
- let frames = 0;
3639
- let windowStart = performance.now();
3640
- let rafId = 0;
3641
- const loop = (now) => {
3642
- frames++;
3643
- const elapsed = now - windowStart;
3644
- if (elapsed >= 1e3) {
3645
- setFps(frames * 1e3 / elapsed);
3646
- frames = 0;
3647
- windowStart = now;
3648
- }
3649
- rafId = requestAnimationFrame(loop);
3650
- };
3651
- rafId = requestAnimationFrame(loop);
3652
- return () => cancelAnimationFrame(rafId);
3653
- }, []);
3654
- if (!size) {
3655
- return null;
3656
- }
3657
- const halfW = size.width / 2;
3658
- const halfH = size.height / 2;
3659
- const left = corner === "top-left" || corner === "bottom-left";
3660
- const top = corner === "top-left" || corner === "top-right";
3661
- const x = left ? -halfW + margin : halfW - margin;
3662
- const y = top ? -halfH + margin : halfH - margin;
3663
- const textAnchor = left ? "start" : "end";
3664
- const dominantBaseline = top ? "hanging" : "alphabetic";
3665
- return /* @__PURE__ */ React2.createElement("g", {
3666
- className: "dx-fps",
3667
- style: {
3668
- pointerEvents: "none"
3669
- }
3670
- }, /* @__PURE__ */ React2.createElement("text", {
3671
- x,
3672
- y,
3673
- textAnchor,
3674
- dominantBaseline,
3675
- className: mx2("font-mono text-xs fill-neutral-500 tabular-nums", classNames)
3676
- }, fps == null ? "\u2014 fps" : `${fps.toFixed(0)} fps`));
3677
- };
3678
-
3679
- // src/components/SVG/Grid.tsx
3680
- import React3 from "react";
3681
- import { mx as mx3 } from "@dxos/ui-theme";
3682
- var Grid = ({ classNames, ...props }) => {
3683
- const { ref } = useGrid(props);
3684
- return /* @__PURE__ */ React3.createElement("g", {
3685
- ref,
3686
- className: mx3("dx-grid", classNames)
3687
- });
3688
- };
3689
-
3690
- // src/components/SVG/Markers.tsx
3691
- import { select as select8 } from "d3";
3692
- import React4, { useEffect as useEffect6, useRef as useRef4 } from "react";
3693
- var Markers = ({ arrowSize, className }) => {
3694
- const ref = useRef4(null);
3695
- useEffect6(() => {
3696
- select8(ref.current).call(createMarkers({
3697
- arrowSize
3698
- }));
3699
- }, [
3700
- ref
3701
- ]);
3702
- return /* @__PURE__ */ React4.createElement("defs", {
3703
- ref,
3704
- className
3705
- });
3706
- };
3707
-
3708
- // src/components/SVG/Root.tsx
3709
- import { select as select9 } from "d3";
3710
- import React5, { forwardRef as forwardRef2, useEffect as useEffect7, useImperativeHandle as useImperativeHandle2, useMemo as useMemo4, useState as useState2 } from "react";
3711
- import { composableProps } from "@dxos/react-ui";
3712
- import { mx as mx4 } from "@dxos/ui-theme";
3713
- var Root = /* @__PURE__ */ forwardRef2(({ children, scale, centered, ...props }, ref) => {
3714
- const [container, setContainer] = useState2(null);
3715
- const [size, setSize] = useState2({
3716
- width: 0,
3717
- height: 0
3718
- });
3719
- useEffect7(() => {
3720
- if (!container) {
3721
- return;
3722
- }
3723
- const rect = container.getBoundingClientRect();
3724
- setSize({
3725
- width: rect.width,
3726
- height: rect.height
3727
- });
3728
- const observer = new ResizeObserver((entries) => {
3729
- const entry = entries[0];
3730
- if (!entry) {
3731
- return;
3732
- }
3733
- const { width: width2, height: height2 } = entry.contentRect;
3734
- setSize((prev) => prev.width === width2 && prev.height === height2 ? prev : {
3735
- width: width2,
3736
- height: height2
3737
- });
3738
- });
3739
- observer.observe(container);
3740
- return () => observer.disconnect();
3741
- }, [
3742
- container
3743
- ]);
3744
- const { width, height } = size;
3745
- const context = useMemo4(() => {
3746
- return new SVGContext({
3747
- scale,
3748
- centered
3749
- });
3750
- }, [
3751
- scale,
3752
- centered
3753
- ]);
3754
- useImperativeHandle2(ref, () => context, [
3755
- context
3756
- ]);
3757
- useEffect7(() => {
3758
- if (width && height) {
3759
- context.setSize({
3760
- width,
3761
- height
3762
- });
3763
- select9(context.svg).attr("display", "block").attr("viewBox", context.viewBox).attr("width", width).attr("height", height);
3764
- }
3765
- }, [
3766
- context,
3767
- width,
3768
- height
3769
- ]);
3770
- const ready = width !== 0 && height !== 0;
3771
- return /* @__PURE__ */ React5.createElement(SVGContextProvider, {
3772
- value: context
3773
- }, /* @__PURE__ */ React5.createElement("div", {
3774
- ...composableProps(props, {
3775
- classNames: "dx-expander"
3776
- }),
3777
- ref: setContainer
3778
- }, /* @__PURE__ */ React5.createElement("svg", {
3779
- xmlns: "http://www.w3.org/2000/svg",
3780
- ref: context.ref,
3781
- className: mx4("transition-opacity opacity-0 duration-1000", ready && "opacity-100")
3782
- }, ready && children)));
3783
- });
3784
-
3785
- // src/components/SVG/Zoom.tsx
3786
- import React6, { memo, useMemo as useMemo5 } from "react";
3787
- var Zoom = /* @__PURE__ */ memo(({ extent, className, children }) => {
3788
- const options = useMemo5(() => ({
3789
- extent
3790
- }), [
3791
- JSON.stringify(extent)
3792
- ]);
3793
- const zoom2 = useZoom(options);
3794
- return /* @__PURE__ */ React6.createElement("g", {
3795
- ref: zoom2.ref,
3796
- className
3797
- }, children);
3798
- });
3799
-
3800
- // src/components/SVG/SVG.tsx
3801
- var SVG = {
3802
- Root,
3803
- Grid,
3804
- Markers,
3805
- Mesh,
3806
- Zoom,
3807
- Graph,
3808
- FPS
3809
- };
3810
-
3811
- // src/components/Tree/Tree.tsx
3812
- import React10, { useMemo as useMemo9 } from "react";
3813
-
3814
- // src/components/Tree/layout/HierarchicalEdgeBundling.tsx
3815
- import { cluster, curveBundle as curveBundle2, hierarchy as hierarchy5, lineRadial as lineRadial2, select as select10 } from "d3";
3816
- import React7, { useEffect as useEffect9, useMemo as useMemo6, useRef as useRef5 } from "react";
3817
- import { mx as mx5 } from "@dxos/ui-theme";
3818
-
3819
- // src/components/Tree/layout/slots.ts
3820
- var defaultTreeLayoutSlots = {
3821
- // Cursor + transition so the hover swap reads clearly; SVG circles support the `:hover` pseudo-class
3822
- // via Tailwind variants exactly like HTML elements.
3823
- node: "fill-blue-600 hover:fill-orange-500 cursor-pointer transition-colors",
3824
- // 0.5px is fine on a white background, but on a dark Storybook background the lines disappear.
3825
- // Use stroke-1 with opacity 50% so they read in both themes; dx-bundle-dim/out/in further tune on hover.
3826
- path: "fill-none stroke-blue-500/50 stroke-[1px] dark:stroke-blue-400/60",
3827
- text: "fill-neutral-700 dark:fill-neutral-300 text-xs hover:fill-orange-500 cursor-pointer transition-colors"
3828
- };
3829
-
3830
- // src/components/Tree/layout/useContainerSize.ts
3831
- import { useEffect as useEffect8, useState as useState3 } from "react";
3832
- var useContainerSize = () => {
3833
- const [el, setEl] = useState3(null);
3834
- const [size, setSize] = useState3({
3835
- width: 0,
3836
- height: 0
3837
- });
3838
- useEffect8(() => {
3839
- if (!el) {
3840
- return;
3841
- }
3842
- const rect = el.getBoundingClientRect();
3843
- setSize({
3844
- width: rect.width,
3845
- height: rect.height
3846
- });
3847
- const observer = new ResizeObserver((entries) => {
3848
- const entry = entries[0];
3849
- if (!entry) {
3850
- return;
3851
- }
3852
- const { width, height } = entry.contentRect;
3853
- setSize((prev) => prev.width === width && prev.height === height ? prev : {
3854
- width,
3855
- height
3856
- });
3857
- });
3858
- observer.observe(el);
3859
- return () => observer.disconnect();
3860
- }, [
3861
- el
3862
- ]);
3863
- return {
3864
- setRef: setEl,
3865
- width: size.width,
3866
- height: size.height
3867
- };
3868
- };
3869
-
3870
- // src/components/Tree/layout/HierarchicalEdgeBundling.tsx
3871
- var TRANSITION_MS = 350;
3872
- var HierarchicalEdgeBundling = ({ classNames, data, edges = [], label = (d) => d.label ?? d.id, padding = 120, tension = 0.85, r = 4, slots = defaultTreeLayoutSlots, onNodeHover }) => {
3873
- const svgRef = useRef5(null);
3874
- const { setRef, width, height } = useContainerSize();
3875
- const root = useMemo6(() => buildBundleHierarchy(data, edges), [
3876
- data,
3877
- edges
3878
- ]);
3879
- const handleHoverRef = useRef5(() => {
3880
- });
3881
- handleHoverRef.current = (node, event) => onNodeHover?.(node, event);
3882
- useEffect9(() => {
3883
- if (!svgRef.current || !width || !height) {
3884
- return;
3885
- }
3886
- const radius = Math.max(0, Math.min(width, height) / 2 - padding);
3887
- renderBundling(svgRef.current, root, {
3888
- radius,
3889
- r,
3890
- label,
3891
- slots,
3892
- tension,
3893
- onNodeHover: (n, e) => handleHoverRef.current(n, e)
3894
- });
3895
- }, [
3896
- root,
3897
- width,
3898
- height,
3899
- padding,
3900
- tension,
3901
- r,
3902
- label,
3903
- slots
3904
- ]);
3905
- return /* @__PURE__ */ React7.createElement("div", {
3906
- ref: setRef,
3907
- className: mx5("dx-expander relative", classNames)
3908
- }, width > 0 && height > 0 && /* @__PURE__ */ React7.createElement("svg", {
3909
- ref: svgRef,
3910
- xmlns: "http://www.w3.org/2000/svg",
3911
- width,
3912
- height,
3913
- viewBox: `${-width / 2} ${-height / 2} ${width} ${height}`
3914
- }));
3915
- };
3916
- var buildBundleHierarchy = (data, edges) => {
3917
- const root = hierarchy5(data);
3918
- const byId = /* @__PURE__ */ new Map();
3919
- for (const node of root.descendants()) {
3920
- byId.set(node.data.id, node);
3921
- node.outgoing = [];
3922
- node.incoming = [];
3923
- }
3924
- for (const edge of edges) {
3925
- const source = byId.get(edge.source);
3926
- const target = byId.get(edge.target);
3927
- if (!source || !target || source === target) {
3928
- continue;
3929
- }
3930
- source.outgoing.push([
3931
- source,
3932
- target,
3933
- edge
3934
- ]);
3935
- target.incoming.push([
3936
- source,
3937
- target,
3938
- edge
3939
- ]);
3940
- }
3941
- return root;
3942
- };
3943
- var renderBundling = (svgElement, root, options) => {
3944
- const { radius, r, tension, label, slots, onNodeHover } = options;
3945
- const svg = select10(svgElement);
3946
- if (!root.children?.length) {
3947
- svg.selectAll("g.dx-bundle-root").remove();
3948
- return;
3949
- }
3950
- cluster().size([
3951
- 2 * Math.PI,
3952
- radius
3953
- ])(root);
3954
- const g = svg.selectAll("g.dx-bundle-root").data([
3955
- null
3956
- ]).join("g").classed("dx-bundle-root", true);
3957
- const linksLayer = g.selectAll("g.dx-bundle-links").data([
3958
- null
3959
- ]).join("g").classed("dx-bundle-links", true);
3960
- const nodesLayer = g.selectAll("g.dx-bundle-nodes").data([
3961
- null
3962
- ]).join("g").classed("dx-bundle-nodes", true);
3963
- const line5 = lineRadial2().curve(curveBundle2.beta(tension)).radius((d) => d.y).angle((d) => d.x);
3964
- const leaves = root.leaves();
3965
- const flatEdges = leaves.flatMap((leaf) => leaf.outgoing ?? []);
3966
- const paths = linksLayer.selectAll("path").data(flatEdges, (d) => `${d[0].data.id}->${d[1].data.id}`).join((enter) => enter.append("path").attr("class", slots.path ?? "").attr("fill", "none").attr("opacity", 0), (update) => update, (exit) => exit.each(function() {
3967
- select10(this).interrupt();
3968
- }).transition().duration(TRANSITION_MS).attr("opacity", 0).remove());
3969
- paths.each(function(d) {
3970
- d[0].pathEl = this;
3971
- }).transition().duration(TRANSITION_MS).attr("opacity", 1).attr("d", ([s, t]) => line5(s.path(t)));
3972
- const labels = nodesLayer.selectAll("g.dx-bundle-leaf").data(leaves, (d) => d.data.id).join((enter) => {
3973
- const ge = enter.append("g").classed("dx-bundle-leaf", true).attr("opacity", 0);
3974
- ge.append("circle").style("cursor", "pointer");
3975
- ge.append("text").attr("dy", "0.32em").attr("paint-order", "stroke").style("cursor", "pointer");
3976
- return ge;
3977
- }, (update) => update, (exit) => exit.each(function() {
3978
- select10(this).interrupt();
3979
- }).transition().duration(TRANSITION_MS).attr("opacity", 0).remove());
3980
- labels.transition().duration(TRANSITION_MS).attr("opacity", 1).attr("transform", (d) => `rotate(${d.x * 180 / Math.PI - 90}) translate(${d.y},0)`);
3981
- const onEnter = function(event, d) {
3982
- onNodeHover(d.data, event);
3983
- hover(linksLayer, leaves, d, true);
3984
- };
3985
- const onLeave = function(event, d) {
3986
- onNodeHover(null);
3987
- hover(linksLayer, leaves, d, false);
3988
- };
3989
- labels.select("circle").attr("class", [
3990
- slots.node ?? "",
3991
- "dx-leaf"
3992
- ].filter(Boolean).join(" ")).attr("r", r).style("fill", (d) => slots.nodeFill?.(d.data.data) ?? null).each(function(d) {
3993
- d.circle = this;
3994
- }).on("pointerenter", onEnter).on("pointerleave", onLeave);
3995
- labels.select("text").attr("class", slots.text ?? "").attr("x", (d) => d.x < Math.PI ? r + 4 : -(r + 4)).attr("text-anchor", (d) => d.x < Math.PI ? "start" : "end").attr("transform", (d) => d.x >= Math.PI ? "rotate(180)" : null).each(function(d) {
3996
- d.text = this;
3997
- }).text((d) => label(d.data)).on("pointerenter", onEnter).on("pointerleave", onLeave);
3998
- };
3999
- var hover = (linksLayer, leaves, focused, on) => {
4000
- const outgoing = new Set((focused.outgoing ?? []).map(([, t]) => t));
4001
- const incoming = new Set((focused.incoming ?? []).map(([s]) => s));
4002
- linksLayer.selectAll("path").style("stroke", (d) => {
4003
- if (!on) {
4004
- return null;
4005
- }
4006
- if (d[0] === focused) {
4007
- return "var(--color-orange-500)";
4008
- }
4009
- if (d[1] === focused) {
4010
- return "var(--color-sky-500)";
4011
- }
4012
- return null;
4013
- }).style("stroke-width", (d) => on && (d[0] === focused || d[1] === focused) ? "1.5px" : null).style("opacity", (d) => on && d[0] !== focused && d[1] !== focused ? "0.08" : null);
4014
- for (const leaf of leaves) {
4015
- const isOut = outgoing.has(leaf);
4016
- const isIn = incoming.has(leaf);
4017
- const isConnected = isOut || isIn;
4018
- if (leaf.text) {
4019
- select10(leaf.text).style("fill", () => {
4020
- if (!on) {
4021
- return null;
4022
- }
4023
- if (leaf === focused) {
4024
- return "var(--color-neutral-900)";
4025
- }
4026
- if (isOut) {
4027
- return "var(--color-orange-500)";
4028
- }
4029
- if (isIn) {
4030
- return "var(--color-sky-500)";
4031
- }
4032
- return null;
4033
- }).style("font-weight", () => on && leaf === focused ? "600" : null);
4034
- }
4035
- if (leaf.circle) {
4036
- select10(leaf.circle).style("stroke", () => on && isConnected ? "var(--color-orange-400)" : null).style("stroke-width", () => on && isConnected ? "2.5px" : null).style("opacity", () => on && !isConnected && leaf !== focused ? "0.15" : null);
4037
- }
4038
- }
4039
- };
4040
-
4041
- // src/components/Tree/layout/RadialTree.tsx
4042
- import { cluster as d3Cluster4, tree as d3Tree2, linkRadial as linkRadial3, select as select11 } from "d3";
4043
- import React8, { useCallback, useEffect as useEffect10, useMemo as useMemo7, useRef as useRef6, useState as useState4 } from "react";
4044
- import { mx as mx6 } from "@dxos/ui-theme";
4045
-
4046
- // src/components/Tree/layout/hierarchy.ts
4047
- import { hierarchy as d3Hierarchy } from "d3";
4048
- var buildHierarchy = (data, collapsed = /* @__PURE__ */ new Set()) => {
4049
- return d3Hierarchy(data, (d) => {
4050
- if (!d.children?.length) {
4051
- return void 0;
4052
- }
4053
- return collapsed.has(d.id) ? void 0 : d.children;
4054
- });
4055
- };
4056
- var isCollapsed = (data, collapsed) => Boolean(data.children?.length) && collapsed.has(data.id);
4057
- var isLeaf = (data) => !data.children?.length;
4058
-
4059
- // src/components/Tree/layout/RadialTree.tsx
4060
- var TRANSITION_MS2 = 350;
4061
- var RadialTree = ({ classNames, data, label = (d) => d.label ?? d.id, slots = defaultTreeLayoutSlots, r = 4, padding = 80, initialCollapsed, cluster: cluster2 = false, onNodeClick, onNodeHover }) => {
4062
- const svgRef = useRef6(null);
4063
- const { setRef, width, height } = useContainerSize();
4064
- const [collapsed, setCollapsed] = useState4(() => new Set(initialCollapsed ?? []));
4065
- const toggle = useCallback((id) => {
4066
- setCollapsed((prev) => {
4067
- const next = new Set(prev);
4068
- if (next.has(id)) {
4069
- next.delete(id);
4070
- } else {
4071
- next.add(id);
4072
- }
4073
- return next;
4074
- });
4075
- }, []);
4076
- const handleClickRef = useRef6(() => {
4077
- });
4078
- handleClickRef.current = (node) => {
4079
- onNodeClick?.(node);
4080
- if (node.children?.length) {
4081
- toggle(node.id);
4082
- }
4083
- };
4084
- const handleHoverRef = useRef6(() => {
4085
- });
4086
- handleHoverRef.current = (node, event) => onNodeHover?.(node, event);
4087
- const root = useMemo7(() => buildHierarchy(data, collapsed), [
4088
- data,
4089
- collapsed
4090
- ]);
4091
- useEffect10(() => {
4092
- if (!svgRef.current || !width || !height) {
4093
- return;
4094
- }
4095
- const radius = Math.max(0, Math.min(width, height) / 2 - padding);
4096
- renderRadialTree(svgRef.current, root, {
4097
- radius,
4098
- r,
4099
- label,
4100
- slots,
4101
- collapsed,
4102
- cluster: cluster2,
4103
- onNodeClick: (n) => handleClickRef.current(n),
4104
- onNodeHover: (n, e) => handleHoverRef.current(n, e)
4105
- });
4106
- }, [
4107
- root,
4108
- width,
4109
- height,
4110
- r,
4111
- padding,
4112
- label,
4113
- slots,
4114
- collapsed,
4115
- cluster2
4116
- ]);
4117
- return /* @__PURE__ */ React8.createElement("div", {
4118
- ref: setRef,
4119
- className: mx6("dx-expander relative", classNames)
4120
- }, width > 0 && height > 0 && /* @__PURE__ */ React8.createElement("svg", {
4121
- ref: svgRef,
4122
- xmlns: "http://www.w3.org/2000/svg",
4123
- width,
4124
- height,
4125
- viewBox: `${-width / 2} ${-height / 2} ${width} ${height}`
4126
- }));
4127
- };
4128
- var renderRadialTree = (svgElement, root, options) => {
4129
- const { radius, r, label, slots, collapsed, cluster: cluster2, onNodeClick, onNodeHover } = options;
4130
- const svg = select11(svgElement);
4131
- const layout = cluster2 ? d3Cluster4() : d3Tree2();
4132
- layout.size([
4133
- 2 * Math.PI,
4134
- radius
4135
- ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
4136
- const g = svg.selectAll("g.dx-radial-root").data([
4137
- null
4138
- ]).join("g").classed("dx-radial-root", true);
4139
- const linksLayer = g.selectAll("g.dx-radial-links").data([
4140
- null
4141
- ]).join("g").classed("dx-radial-links", true);
4142
- const nodesLayer = g.selectAll("g.dx-radial-nodes").data([
4143
- null
4144
- ]).join("g").classed("dx-radial-nodes", true);
4145
- const linkPath4 = linkRadial3().angle((d) => d.x).radius((d) => d.y);
4146
- linksLayer.selectAll("path").data(root.links(), (d) => `${d.source.data.id}->${d.target.data.id}`).join((enter) => enter.append("path").attr("class", slots.path ?? "").attr("fill", "none").attr("opacity", 0), (update) => update, (exit) => exit.transition().duration(TRANSITION_MS2).attr("opacity", 0).remove()).transition().duration(TRANSITION_MS2).attr("opacity", 1).attr("d", linkPath4);
4147
- const node = nodesLayer.selectAll("g.dx-radial-node").data(root.descendants(), (d) => d.data.id);
4148
- const nodeEnter = node.enter().append("g").classed("dx-radial-node", true).attr("opacity", 0).attr("transform", (d) => `rotate(${d.x * 180 / Math.PI - 90}) translate(${d.y},0)`).style("cursor", (d) => d.data.children?.length ? "pointer" : "default").on("click", (_, d) => onNodeClick(d.data));
4149
- nodeEnter.append("circle").attr("r", r).on("pointerenter", (event, d) => onNodeHover(d.data, event)).on("pointerleave", (event) => onNodeHover(null, event));
4150
- nodeEnter.append("text").attr("dy", "0.32em").attr("paint-order", "stroke").text((d) => label(d.data));
4151
- const nodeMerge = nodeEnter.merge(node);
4152
- nodeMerge.transition().duration(TRANSITION_MS2).attr("opacity", 1).attr("transform", (d) => `rotate(${d.x * 180 / Math.PI - 90}) translate(${d.y},0)`);
4153
- nodeMerge.select("circle").attr("class", (d) => {
4154
- const collapsedHere = isCollapsed(d.data, collapsed);
4155
- const leaf = isLeaf(d.data);
4156
- return [
4157
- slots.node ?? "",
4158
- collapsedHere ? "dx-collapsed" : leaf ? "dx-leaf" : "dx-branch"
4159
- ].filter(Boolean).join(" ");
4160
- }).attr("r", r).style("fill", (d) => isLeaf(d.data) ? slots.nodeFill?.(d.data.data) ?? null : null);
4161
- nodeMerge.select("text").attr("class", slots.text ?? "").attr("transform", (d) => d.x >= Math.PI ? "rotate(180)" : null).attr("x", (d) => d.x < Math.PI === !d.children ? r + 4 : -(r + 4)).attr("text-anchor", (d) => d.x < Math.PI === !d.children ? "start" : "end").text((d) => label(d.data));
4162
- node.exit().transition().duration(TRANSITION_MS2).attr("opacity", 0).remove();
4163
- };
4164
-
4165
- // src/components/Tree/layout/TidyTree.tsx
4166
- import { curveBumpX, link as d3Link, tree as d3Tree3, select as select12 } from "d3";
4167
- import React9, { useCallback as useCallback2, useEffect as useEffect11, useMemo as useMemo8, useRef as useRef7, useState as useState5 } from "react";
4168
- import { mx as mx7 } from "@dxos/ui-theme";
4169
- var TRANSITION_MS3 = 350;
4170
- var TidyTree = ({ classNames, data, label = (d) => d.label ?? d.id, slots = defaultTreeLayoutSlots, r = 4, margin = 24, initialCollapsed, onNodeClick }) => {
4171
- const svgRef = useRef7(null);
4172
- const { setRef, width, height } = useContainerSize();
4173
- const [collapsed, setCollapsed] = useState5(() => new Set(initialCollapsed ?? []));
4174
- const toggle = useCallback2((id) => {
4175
- setCollapsed((prev) => {
4176
- const next = new Set(prev);
4177
- if (next.has(id)) {
4178
- next.delete(id);
4179
- } else {
4180
- next.add(id);
4181
- }
4182
- return next;
4183
- });
4184
- }, []);
4185
- const handleClickRef = useRef7(() => {
4186
- });
4187
- handleClickRef.current = (node) => {
4188
- onNodeClick?.(node);
4189
- if (node.children?.length) {
4190
- toggle(node.id);
4191
- }
4192
- };
4193
- const root = useMemo8(() => buildHierarchy(data, collapsed), [
4194
- data,
4195
- collapsed
4196
- ]);
4197
- useEffect11(() => {
4198
- if (!svgRef.current || !width || !height) {
4199
- return;
4200
- }
4201
- renderTidyTree(svgRef.current, root, {
4202
- width,
4203
- height,
4204
- r,
4205
- margin,
4206
- label,
4207
- slots,
4208
- collapsed,
4209
- onNodeClick: (n) => handleClickRef.current(n)
4210
- });
4211
- }, [
4212
- root,
4213
- width,
4214
- height,
4215
- r,
4216
- margin,
4217
- label,
4218
- slots,
4219
- collapsed
4220
- ]);
4221
- return /* @__PURE__ */ React9.createElement("div", {
4222
- ref: setRef,
4223
- className: mx7("dx-expander relative", classNames)
4224
- }, width > 0 && height > 0 && /* @__PURE__ */ React9.createElement("svg", {
4225
- ref: svgRef,
4226
- xmlns: "http://www.w3.org/2000/svg",
4227
- width,
4228
- height,
4229
- viewBox: `${-width / 2} ${-height / 2} ${width} ${height}`
4230
- }));
4231
- };
4232
- var renderTidyTree = (svgElement, root, options) => {
4233
- const { width, height, r, margin, label, slots, collapsed, onNodeClick } = options;
4234
- const svg = select12(svgElement);
4235
- const dx = 18;
4236
- const dy = Math.max(60, (width - margin * 2) / Math.max(1, root.height + 1));
4237
- d3Tree3().nodeSize([
4238
- dx,
4239
- dy
4240
- ])(root);
4241
- let x0 = Infinity;
4242
- let x1 = -x0;
4243
- root.each((d) => {
4244
- if (d.x > x1) {
4245
- x1 = d.x;
4246
- }
4247
- if (d.x < x0) {
4248
- x0 = d.x;
4249
- }
4250
- });
4251
- const treeWidth = width - margin * 2;
4252
- const treeHeight = x1 - x0;
4253
- const scaleY = treeHeight > 0 ? Math.min(1, (height - margin * 2) / treeHeight) : 1;
4254
- const offsetX = -treeWidth / 2;
4255
- const offsetY = -(x0 + x1) / 2;
4256
- const g = svg.selectAll("g.dx-tidy-root").data([
4257
- null
4258
- ]).join("g").classed("dx-tidy-root", true);
4259
- const linksLayer = g.selectAll("g.dx-tidy-links").data([
4260
- null
4261
- ]).join("g").classed("dx-tidy-links", true);
4262
- const nodesLayer = g.selectAll("g.dx-tidy-nodes").data([
4263
- null
4264
- ]).join("g").classed("dx-tidy-nodes", true);
4265
- const linkPath4 = d3Link(curveBumpX).x((d) => offsetX + d.y).y((d) => (d.x + offsetY) * scaleY);
4266
- linksLayer.selectAll("path").data(root.links(), (d) => `${d.source.data.id}->${d.target.data.id}`).join((enter) => enter.append("path").attr("class", slots.path ?? "").attr("fill", "none").attr("opacity", 0), (update) => update, (exit) => exit.transition().duration(TRANSITION_MS3).attr("opacity", 0).remove()).transition().duration(TRANSITION_MS3).attr("opacity", 1).attr("d", linkPath4);
4267
- const node = nodesLayer.selectAll("g.dx-tidy-node").data(root.descendants(), (d) => d.data.id);
4268
- const nodeEnter = node.enter().append("g").classed("dx-tidy-node", true).attr("transform", (d) => `translate(${offsetX + d.y},${(d.x + offsetY) * scaleY})`).attr("opacity", 0).style("cursor", (d) => d.data.children?.length ? "pointer" : "default").on("click", (_, d) => onNodeClick(d.data));
4269
- nodeEnter.append("circle").attr("r", r);
4270
- nodeEnter.append("text").attr("dy", "0.32em").attr("x", (d) => d.children ? -(r + 4) : r + 4).attr("text-anchor", (d) => d.children ? "end" : "start").text((d) => label(d.data));
4271
- const nodeMerge = nodeEnter.merge(node);
4272
- nodeMerge.transition().duration(TRANSITION_MS3).attr("opacity", 1).attr("transform", (d) => `translate(${offsetX + d.y},${(d.x + offsetY) * scaleY})`);
4273
- nodeMerge.select("circle").attr("class", (d) => {
4274
- const collapsedHere = isCollapsed(d.data, collapsed);
4275
- const leaf = isLeaf(d.data);
4276
- return [
4277
- slots.node ?? "",
4278
- collapsedHere ? "dx-collapsed" : leaf ? "dx-leaf" : "dx-branch"
4279
- ].filter(Boolean).join(" ");
4280
- }).attr("r", r);
4281
- nodeMerge.select("text").attr("class", slots.text ?? "").attr("x", (d) => d.children ? -(r + 4) : r + 4).attr("text-anchor", (d) => d.children ? "end" : "start").text((d) => label(d.data));
4282
- node.exit().each(function() {
4283
- select12(this).interrupt();
4284
- }).transition().duration(TRANSITION_MS3).attr("opacity", 0).remove();
4285
- };
4286
-
4287
- // src/components/Tree/Tree.tsx
4288
- var Tree = ({ classNames, data, edges, variant = "tidy", label, slots, margin, initialCollapsed, onNodeClick, onNodeHover }) => {
4289
- return useMemo9(() => {
4290
- switch (variant) {
4291
- case "tidy":
4292
- return /* @__PURE__ */ React10.createElement(TidyTree, {
4293
- classNames,
4294
- data,
4295
- label,
4296
- slots,
4297
- margin,
4298
- initialCollapsed,
4299
- onNodeClick
4300
- });
4301
- case "radial":
4302
- return /* @__PURE__ */ React10.createElement(RadialTree, {
4303
- classNames,
4304
- data,
4305
- label,
4306
- slots,
4307
- initialCollapsed,
4308
- onNodeClick,
4309
- onNodeHover
4310
- });
4311
- case "edge":
4312
- return /* @__PURE__ */ React10.createElement(HierarchicalEdgeBundling, {
4313
- classNames,
4314
- data,
4315
- edges: edges ?? [],
4316
- label,
4317
- slots,
4318
- onNodeHover
4319
- });
4320
- }
4321
- }, [
4322
- variant,
4323
- classNames,
4324
- data,
4325
- edges,
4326
- label,
4327
- slots,
4328
- initialCollapsed,
4329
- onNodeClick,
4330
- onNodeHover
4331
- ]);
4332
- };
4333
-
4334
- // src/fx/pulsar.ts
4335
- import { easeCubicOut as easeCubicOut2, select as select13 } from "d3";
4336
- var PROP_PULSAR_ACTIVE = "dx-pulsar-active";
4337
- (function(Pulsar2) {
4338
- Pulsar2.has = (group) => group.select("circle.dx-pulsar").empty();
4339
- Pulsar2.create = (group, r, options = {}) => {
4340
- const pulsar = group.append("circle").classed("dx-pulsar", true).classed("stroke-2 stroke-red-500 fill-none", true).property(PROP_PULSAR_ACTIVE, true);
4341
- startAnimation(pulsar, r, options);
4342
- };
4343
- Pulsar2.remove = (group) => {
4344
- group.select("circle.dx-pulsar").property(PROP_PULSAR_ACTIVE, false);
4345
- };
4346
- })(Pulsar || (Pulsar = {}));
4347
- var startAnimation = (pulsar, r, options = {}) => {
4348
- const { period = 1e3, duration = 800, ratio = 3 } = options;
4349
- return pulsar.attr("r", r).attr("opacity", 1).transition("pulsar").delay(period - Date.now() % period).duration(Math.min(duration, period - 20)).ease(easeCubicOut2).attr("r", r * ratio).attr("opacity", -0.1).on("end", function() {
4350
- if (select13(this).property(PROP_PULSAR_ACTIVE)) {
4351
- startAnimation(select13(this), r, options);
4352
- } else {
4353
- select13(this).remove();
4354
- }
4355
- });
4356
- };
4357
- var Pulsar;
4358
- export {
4359
- CLUSTER_NODE_TYPE_GROUP,
4360
- CLUSTER_NODE_TYPE_LEAF,
4361
- CLUSTER_NODE_TYPE_ROOT,
4362
- EventEmitter,
4363
- FractionUtil,
4364
- Graph,
4365
- GraphBundleProjector,
4366
- GraphClusterProjector,
4367
- GraphForceProjector,
4368
- GraphHierarchicalProjector,
4369
- GraphLatticeProjector,
4370
- GraphPlexusProjector,
4371
- GraphProjector,
4372
- GraphRadialProjector,
4373
- GraphRelationalProjector,
4374
- GraphRenderer,
4375
- GraphSwarmProjector,
4376
- GraphTreeProjector,
4377
- GridController,
4378
- HierarchicalEdgeBundling,
4379
- Mesh,
4380
- PLEXUS_NODE_TYPE_FOCUS,
4381
- PLEXUS_NODE_TYPE_OBJECT,
4382
- PLEXUS_NODE_TYPE_RELATION,
4383
- Projector,
4384
- Pulsar,
4385
- RadialTree,
4386
- Renderer,
4387
- SVG,
4388
- SVGContext,
4389
- SVGContextProvider,
4390
- Scale,
4391
- Screen,
4392
- TREE_NODE_TYPE_INBOUND,
4393
- TREE_NODE_TYPE_NODE,
4394
- TREE_NODE_TYPE_ROOT,
4395
- TidyTree,
4396
- Tree,
4397
- Vector,
4398
- ZoomHandler,
4399
- appendRadialGroupLabel,
4400
- appendRadialLeafLabel,
4401
- appendRootLabel,
4402
- buildHierarchy,
4403
- createGraphDrag,
4404
- createMarkers,
4405
- defaultForceOptions,
4406
- defaultIdAccessor,
4407
- defaultTreeLayoutSlots,
4408
- emptyGraph,
4409
- getCircumferencePoints,
4410
- isCollapsed,
4411
- isLeaf,
4412
- layoutHorizontal,
4413
- layoutRadial,
4414
- layoutVertical,
4415
- linkerRenderer,
4416
- normal,
4417
- offsetPoints,
4418
- updateNode,
4419
- useContainerSize,
4420
- useDynamicRef,
4421
- useGrid,
4422
- useStateRef,
4423
- useSvgContext,
4424
- useTimestamp,
4425
- useZoom
4426
- };
4427
- //# sourceMappingURL=index.mjs.map