@principal-ai/subsystems-react 0.56.22 → 0.56.23

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.
@@ -13,7 +13,7 @@
13
13
  * renders in a side panel.
14
14
  */
15
15
 
16
- import { useCallback, useEffect, useMemo, useState } from 'react';
16
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
17
17
  import {
18
18
  Edge,
19
19
  Handle,
@@ -80,6 +80,21 @@ export interface SubsystemAggregateGraphProps {
80
80
  title?: string;
81
81
  onSelectFrame?: (id: string | null) => void;
82
82
  onOpenFile?: (path: string) => void;
83
+ /**
84
+ * Fires once per layout pass with how long ELK took and what it laid out.
85
+ * Diagnostic: lets a host separate layout cost from React render cost.
86
+ */
87
+ onLayoutComplete?: (info: AggregateLayoutInfo) => void;
88
+ }
89
+
90
+ export interface AggregateLayoutInfo {
91
+ /** Wall time of `computeElkLayout`, in ms. */
92
+ layoutMs: number;
93
+ nodes: number;
94
+ edges: number;
95
+ groups: number;
96
+ /** ELK failed and the grid fallback was used. */
97
+ fallback: boolean;
83
98
  }
84
99
 
85
100
  const NODE_W = 232;
@@ -196,7 +211,7 @@ function AggregateHubNodeView(
196
211
 
197
212
  function AggregateFrameNodeView(
198
213
  props: NodeProps<
199
- Node<{ frame: AggregateFrameNode; selected: boolean; dimmed: boolean; nested?: boolean }>
214
+ Node<{ frame: AggregateFrameNode; selected: boolean; nested?: boolean }>
200
215
  >,
201
216
  ) {
202
217
  const { theme } = useTheme();
@@ -237,8 +252,7 @@ function AggregateFrameNodeView(
237
252
  data.selected ? theme.colors.primary : (theme.colors.border ?? '#333')
238
253
  }`,
239
254
  boxShadow: boundaryStyled ? 'none' : '0 1px 4px rgba(0,0,0,0.25)',
240
- opacity: data.dimmed ? 0.35 : 1,
241
- transition: 'opacity 120ms ease, border-color 120ms ease',
255
+ transition: 'border-color 120ms ease',
242
256
  cursor: 'pointer',
243
257
  fontFamily: theme.fonts.body,
244
258
  }}
@@ -293,6 +307,23 @@ function AggregateFrameNodeView(
293
307
  );
294
308
  }
295
309
 
310
+ const AGGREGATE_CLASS = 'subsystem-aggregate-graph';
311
+
312
+ /**
313
+ * Focus dimming lives in CSS keyed off a `data-dimmed` attribute that the
314
+ * canvas toggles on React Flow's node/edge wrappers directly. Hovering one
315
+ * frame changes the dim state of nearly every other node and edge, so routing
316
+ * it through React props re-rendered the whole canvas (~200 nodes, ~400 SVG
317
+ * edges) on each mouse move; attribute toggles cost a fraction of that and
318
+ * produce no React commit at all.
319
+ */
320
+ const AGGREGATE_FOCUS_CSS = `
321
+ .${AGGREGATE_CLASS} .react-flow__node { transition: opacity 120ms ease; }
322
+ .${AGGREGATE_CLASS} .react-flow__node[data-dimmed="true"] { opacity: 0.35; }
323
+ .${AGGREGATE_CLASS} .react-flow__edge { opacity: 0.9; }
324
+ .${AGGREGATE_CLASS} .react-flow__edge[data-dimmed="true"] { opacity: 0.12; }
325
+ `;
326
+
296
327
  const nodeTypes = {
297
328
  'aggregate-frame': AggregateFrameNodeView,
298
329
  'aggregate-frame-group': AggregateFrameGroupView,
@@ -306,6 +337,7 @@ function Inner({
306
337
  title,
307
338
  onSelectFrame,
308
339
  onOpenFile,
340
+ onLayoutComplete,
309
341
  }: SubsystemAggregateGraphProps) {
310
342
  const { theme } = useTheme();
311
343
  const { fitView } = useReactFlow();
@@ -315,8 +347,10 @@ function Inner({
315
347
  const [ready, setReady] = useState(false);
316
348
  const [selectedId, setSelectedId] = useState<string | null>(null);
317
349
  const [focusedBoundaryId, setFocusedBoundaryId] = useState<string | null>(null);
318
- const [hoveredId, setHoveredId] = useState<string | null>(null);
319
350
  const [legendOpen, setLegendOpen] = useState(true);
351
+ const hostRef = useRef<HTMLDivElement>(null);
352
+ // Hover is deliberately not React state: see AGGREGATE_FOCUS_CSS.
353
+ const hoveredRef = useRef<string | null>(null);
320
354
 
321
355
  const layoutKey = useMemo(
322
356
  () =>
@@ -373,7 +407,7 @@ function Inner({
373
407
  width: NODE_W,
374
408
  height: NODE_H,
375
409
  ...(f.group ? { parentId: groupIdFor(f.group.kind, f.group.key) } : {}),
376
- data: { frame: f, selected: false, dimmed: false },
410
+ data: { frame: f, selected: false },
377
411
  })),
378
412
  ...hubs.map((h) => ({
379
413
  id: h.id,
@@ -414,11 +448,24 @@ function Inner({
414
448
  },
415
449
  data: { edge: e },
416
450
  }));
451
+ const layoutStart = performance.now();
452
+ const report = (fallback: boolean) =>
453
+ onLayoutComplete?.({
454
+ layoutMs: performance.now() - layoutStart,
455
+ nodes: rfNodes.length,
456
+ edges: rfEdges.length,
457
+ groups: groups.length,
458
+ fallback,
459
+ });
417
460
  void computeElkLayout(rfNodes, rfEdges, {
418
461
  direction: 'RIGHT',
419
462
  // Reposition (never keep the placeholder grid) and lay out compound
420
463
  // process frames.
421
464
  preserveNodePositions: false,
465
+ // Frames are fixed-size boxes with no edge labels, so the extra sweeps
466
+ // buy nothing visible; ELK's default is ~3.5x faster at this scale.
467
+ thoroughness: 7,
468
+ edgeLabels: { enabled: false },
422
469
  groups,
423
470
  // Every process and external boundary is real, including one holding a
424
471
  // single frame — a quiet process still has components in it, and
@@ -465,6 +512,7 @@ function Inner({
465
512
  setNodes([...shells, ...leaves]);
466
513
  setRfEdges(rfEdges);
467
514
  setReady(true);
515
+ report(false);
468
516
  requestAnimationFrame(() => fitView({ padding: 0.15 }));
469
517
  })
470
518
  .catch((err) => {
@@ -473,6 +521,7 @@ function Inner({
473
521
  setNodes(rfNodes);
474
522
  setRfEdges(rfEdges);
475
523
  setReady(true);
524
+ report(true);
476
525
  requestAnimationFrame(() => fitView({ padding: 0.15 }));
477
526
  });
478
527
  return () => {
@@ -481,36 +530,83 @@ function Inner({
481
530
  // eslint-disable-next-line react-hooks/exhaustive-deps
482
531
  }, [layoutKey]);
483
532
 
484
- // A boundary is a container, not an endpoint: edges reference frame/hub
485
- // ids, never the group shell's. Hovering one therefore needs its own rule.
486
- // Treating the shell as the focus put *nothing* in its neighbour set, so the
487
- // boundary's own contents were the ones that dimmed. Instead: keep every node
488
- // lit and dim only the edges that do not touch the boundary.
489
- const boundaryMembers = useMemo(() => {
490
- const focus = hoveredId ?? selectedId;
491
- if (!focus) return null;
492
- if (nodes.find((n) => n.id === focus)?.type !== 'aggregate-frame-group') {
493
- return null;
494
- }
495
- const members = new Set<string>();
496
- for (const n of nodes) {
497
- if ((n as { parentId?: string }).parentId === focus) members.add(n.id);
498
- }
499
- return members;
500
- }, [hoveredId, selectedId, nodes]);
533
+ // Edge wrappers only expose their id in the DOM; endpoints come from here.
534
+ const edgeEndsRef = useRef(new Map<string, { source: string; target: string }>());
535
+ useEffect(() => {
536
+ edgeEndsRef.current = new Map(rfEdges.map((e) => [e.id, { source: e.source, target: e.target }]));
537
+ }, [rfEdges]);
501
538
 
502
- const neighborIds = useMemo(() => {
503
- // Boundary hover owns its own dimming (edges only) — no node focus set.
504
- if (boundaryMembers) return null;
505
- const focus = hoveredId ?? selectedId;
506
- if (!focus) return null;
507
- const set = new Set<string>([focus]);
508
- for (const e of edges) {
509
- if (e.from === focus) set.add(e.to);
510
- if (e.to === focus) set.add(e.from);
511
- }
512
- return set;
513
- }, [hoveredId, selectedId, edges, boundaryMembers]);
539
+ /**
540
+ * Which nodes/edges a focus (hover, else selection) keeps lit.
541
+ *
542
+ * A boundary is a container, not an endpoint: edges reference frame/hub
543
+ * ids, never the group shell's. Hovering one therefore needs its own rule:
544
+ * keep every node lit and dim only the edges not wholly inside it (treating
545
+ * the shell as a plain focus put *nothing* in its neighbour set, so the
546
+ * boundary's own contents were the ones that dimmed). Otherwise dim
547
+ * everything outside the focused node's neighbourhood.
548
+ */
549
+ const applyFocus = useCallback(
550
+ (focus: string | null) => {
551
+ const host = hostRef.current;
552
+ if (!host) return;
553
+ let nodeDim: ((id: string) => boolean) | null = null;
554
+ let edgeDim: ((source: string, target: string) => boolean) | null = null;
555
+ if (focus) {
556
+ const focusNode = nodes.find((n) => n.id === focus);
557
+ if (focusNode?.type === 'aggregate-frame-group') {
558
+ const members = new Set<string>();
559
+ for (const n of nodes) {
560
+ if ((n as { parentId?: string }).parentId === focus) members.add(n.id);
561
+ }
562
+ edgeDim = (a, b) => !(members.has(a) && members.has(b));
563
+ } else {
564
+ const near = new Set<string>([focus]);
565
+ for (const e of edges) {
566
+ if (e.from === focus) near.add(e.to);
567
+ if (e.to === focus) near.add(e.from);
568
+ }
569
+ nodeDim = (id) => !near.has(id);
570
+ edgeDim = (a, b) => !(near.has(a) && near.has(b));
571
+ }
572
+ }
573
+ for (const el of Array.from(host.querySelectorAll<HTMLElement>('.react-flow__node'))) {
574
+ const id = el.dataset.id ?? '';
575
+ const dim = nodeDim ? nodeDim(id) : false;
576
+ if (dim) el.dataset.dimmed = 'true';
577
+ else delete el.dataset.dimmed;
578
+ }
579
+ const ends = edgeEndsRef.current;
580
+ for (const el of Array.from(host.querySelectorAll<SVGGElement>('.react-flow__edge'))) {
581
+ const e = ends.get(el.dataset.id ?? '');
582
+ const dim = e && edgeDim ? edgeDim(e.source, e.target) : false;
583
+ if (dim) el.dataset.dimmed = 'true';
584
+ else delete el.dataset.dimmed;
585
+ }
586
+ },
587
+ [nodes, edges],
588
+ );
589
+
590
+ // Re-apply after layout (fresh DOM), after a selection change, and whenever
591
+ // the data the focus sets are derived from changes.
592
+ useEffect(() => {
593
+ applyFocus(hoveredRef.current ?? selectedId);
594
+ }, [applyFocus, selectedId, rfEdges]);
595
+
596
+ const displayNodes = useMemo(
597
+ () =>
598
+ nodes.map((n) => ({
599
+ ...n,
600
+ data: {
601
+ ...(n.data as object),
602
+ selected: selectedId === n.id,
603
+ // Surviving parentId means ELK built this node's process frame —
604
+ // the node renders nested, so a process box drops its redundant name.
605
+ nested: (n as { parentId?: string }).parentId != null,
606
+ },
607
+ })),
608
+ [nodes, selectedId],
609
+ );
514
610
 
515
611
  const selected = selectedId ? (frames.find((f) => f.id === selectedId) ?? null) : null;
516
612
 
@@ -557,59 +653,31 @@ function Inner({
557
653
  [focusedBoundaryId, fitView, nodes],
558
654
  );
559
655
 
560
- const displayNodes = useMemo(
561
- () =>
562
- nodes.map((n) => ({
563
- ...n,
564
- data: {
565
- ...(n.data as object),
566
- selected: selectedId === n.id,
567
- // Boundary hover dims everything outside the boundary; otherwise
568
- // dim anything outside the focused node's neighbourhood.
569
- dimmed: boundaryMembers
570
- ? !boundaryMembers.has(n.id)
571
- : neighborIds
572
- ? !neighborIds.has(n.id)
573
- : false,
574
- // Surviving parentId means ELK built this node's process frame —
575
- // the node renders nested, so a process box drops its redundant name.
576
- nested: (n as { parentId?: string }).parentId != null,
577
- },
578
- })),
579
- [nodes, selectedId, neighborIds, boundaryMembers],
580
- );
581
-
582
- const displayEdges = useMemo(
583
- () =>
584
- rfEdges.map((e) => {
585
- // Hovering a boundary keeps only the edges wholly inside it lit — a
586
- // boundary-crossing edge has an endpoint outside, so it dims with the
587
- // rest. Otherwise fall back to the node-focus rule.
588
- const dimmed = boundaryMembers
589
- ? !(boundaryMembers.has(e.source) && boundaryMembers.has(e.target))
590
- : neighborIds != null &&
591
- !(neighborIds.has(e.source) && neighborIds.has(e.target));
592
- return {
593
- ...e,
594
- style: { ...(e.style as object), opacity: dimmed ? 0.12 : 0.9 },
595
- };
596
- }),
597
- [rfEdges, neighborIds, boundaryMembers],
598
- );
599
656
 
600
657
  return (
601
- <div style={{ position: 'relative', width: '100%', height: '100%', background: theme.colors.background }}>
658
+ <div
659
+ ref={hostRef}
660
+ className={AGGREGATE_CLASS}
661
+ style={{ position: 'relative', width: '100%', height: '100%', background: theme.colors.background }}
662
+ >
602
663
  <GraphLayerStyle />
664
+ <style>{AGGREGATE_FOCUS_CSS}</style>
603
665
  <ReactFlow
604
666
  nodes={displayNodes}
605
- edges={displayEdges}
667
+ edges={rfEdges}
606
668
  nodeTypes={nodeTypes}
607
669
  className={GRAPH_CANVAS_CLASS}
608
670
  {...GRAPH_NAV_PROPS}
609
671
  onNodeClick={onNodeClick}
610
672
  onNodeDoubleClick={onNodeDoubleClick}
611
- onNodeMouseEnter={(_e, node) => setHoveredId(node.id)}
612
- onNodeMouseLeave={() => setHoveredId(null)}
673
+ onNodeMouseEnter={(_e, node) => {
674
+ hoveredRef.current = node.id;
675
+ applyFocus(node.id);
676
+ }}
677
+ onNodeMouseLeave={() => {
678
+ hoveredRef.current = null;
679
+ applyFocus(selectedId);
680
+ }}
613
681
  onPaneClick={() => {
614
682
  setSelectedId(null);
615
683
  setFocusedBoundaryId(null);
@@ -100,6 +100,18 @@ export interface ElkLayoutOptions {
100
100
  */
101
101
  direction?: 'RIGHT' | 'LEFT' | 'DOWN' | 'UP';
102
102
 
103
+ /**
104
+ * ELK layered `thoroughness` (1-100): how many crossing-minimization sweeps
105
+ * the layered algorithm runs. Cost grows roughly linearly with it and it
106
+ * dominates layout time on large graphs — a 219-node / 415-edge frame graph
107
+ * lays out in ~240ms at ELK's own default of 7 versus ~840ms at 50. The
108
+ * default here stays high because the component graph's edge routing was
109
+ * tuned against it; coarse canvases with fixed-size nodes and no labels
110
+ * should pass something lower.
111
+ * @default 50
112
+ */
113
+ thoroughness?: number;
114
+
103
115
  /**
104
116
  * Order same-layer nodes by their source line (ascending) instead of leaving
105
117
  * it to the crossing-minimizer. Nodes must carry a `data.component.line`
@@ -499,6 +511,7 @@ export function getElkOptions(options: ElkLayoutOptions): LayoutOptions {
499
511
  edgeLabels,
500
512
  direction = 'RIGHT',
501
513
  orderByLine = false,
514
+ thoroughness = 50,
502
515
  } = options;
503
516
 
504
517
  const baseOptions: LayoutOptions = {
@@ -527,8 +540,9 @@ export function getElkOptions(options: ElkLayoutOptions): LayoutOptions {
527
540
  'elk.layered.crossingMinimization.strategy': 'LAYER_SWEEP',
528
541
  // Merge edges going same direction for cleaner routing
529
542
  'elk.layered.mergeEdges': 'true',
530
- // Higher thoroughness = better edge routing (1-100)
531
- 'elk.layered.thoroughness': '50',
543
+ // Higher thoroughness = better edge routing (1-100); see the option doc
544
+ // for the cost trade-off.
545
+ 'elk.layered.thoroughness': String(thoroughness),
532
546
  };
533
547
 
534
548
  // Line order also wants model order respected where positions tie.