@principal-ai/subsystems-react 0.56.26 → 0.56.28

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.
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
19
- import type { CSSProperties, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
19
+ import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react';
20
20
  import {
21
21
  ReactFlow,
22
22
  ReactFlowProvider,
@@ -36,8 +36,10 @@ import { SUBSYSTEM_MODEL_DESCRIPTION_MAX } from '@principal-ai/subsystems-core';
36
36
  import { ArrowDown, ArrowRight, Boxes, Files, Route, Unlink, X } from 'lucide-react';
37
37
  import {
38
38
  buildSubsystemGraph,
39
+ componentPackageKey,
39
40
  deriveGraphEdges,
40
41
  buildBoundaryLayoutGroups,
42
+ cardFramesForAliases,
41
43
  isCardFrame,
42
44
  isConstructsOnlyModel,
43
45
  packageColor,
@@ -214,6 +216,38 @@ function edgeMatches(set: ReadonlySet<string>, e: Edge): boolean {
214
216
  return ids?.some((id) => set.has(id)) === true;
215
217
  }
216
218
 
219
+ /**
220
+ * Whether a boundary region holds any of `aliases` — i.e. whether hovering a
221
+ * trail should keep its container bright. Reads component membership directly
222
+ * (process / module / package / directory path) so nesting is transitive: a
223
+ * package lights when a leaf in its nested process is in the trail, even
224
+ * though the package's layout member list only holds the nested group id.
225
+ * This also covers trails folded into nothing (a step whose endpoints share
226
+ * one collapsed card leaves no edge for `endpointsOf` to find).
227
+ */
228
+ function regionTouchesTrailAliases(
229
+ region: SubsystemProcessRegion | undefined,
230
+ aliases: ReadonlySet<string> | null,
231
+ byAlias: ReadonlyMap<string, SubsystemComponent>,
232
+ ): boolean {
233
+ if (!region || !aliases || aliases.size === 0) return false;
234
+ for (const alias of aliases) {
235
+ const comp = byAlias.get(alias);
236
+ if (!comp) continue;
237
+ if (region.kind === 'process') {
238
+ if (comp.process === region.key) return true;
239
+ } else if (region.kind === 'module') {
240
+ if (comp.module?.trim() === region.key) return true;
241
+ } else if (region.kind === 'directory') {
242
+ const m = comp.module?.trim().replace(/\\/g, '/');
243
+ if (m === region.key || (m != null && m.startsWith(`${region.key}/`))) return true;
244
+ } else if (region.kind === 'package') {
245
+ if (componentPackageKey(comp) === region.key) return true;
246
+ }
247
+ }
248
+ return false;
249
+ }
250
+
217
251
  /** Screen-space rectangle of a component node, relative to the graph canvas box. */
218
252
  export interface SubsystemNodeRect {
219
253
  alias: string;
@@ -810,10 +844,41 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
810
844
  const [toggledGroupIds, setToggledGroupIds] = useState<ReadonlySet<string>>(
811
845
  () => new Set(persisted.toggledFrames ?? []),
812
846
  );
847
+ // Picking a trail opens the container cards that hold its cast, so the flow
848
+ // reads as its components instead of a row of folded boxes. Derived rather
849
+ // than written into the user's frame state: clearing the trail — or moving to
850
+ // another — restores exactly the frames they had open before.
851
+ const trailFrameIds = useMemo<ReadonlySet<string>>(() => {
852
+ if (!layoutTrailId) return new Set();
853
+ const trail = (trails ?? []).find((t) => t.id === layoutTrailId);
854
+ if (!trail) return new Set();
855
+ const aliases = new Set<string>();
856
+ for (const step of trail.steps) {
857
+ aliases.add(step.from);
858
+ aliases.add(step.to);
859
+ }
860
+ return cardFramesForAliases(
861
+ { components },
862
+ aliases,
863
+ { showSingletonFrames, moduleNesting, codeProcessKeys },
864
+ );
865
+ }, [layoutTrailId, trails, components, showSingletonFrames, moduleNesting, codeProcessKeys]);
866
+ // `framesCollapsed` is the default every card takes; a toggled id is the
867
+ // exception. Opening a trail's frames therefore means adding them to the
868
+ // default-collapsed set (or removing them from the default-open one).
869
+ const effectiveToggledGroupIds = useMemo<ReadonlySet<string>>(() => {
870
+ if (trailFrameIds.size === 0) return toggledGroupIds;
871
+ const next = new Set(toggledGroupIds);
872
+ for (const id of trailFrameIds) {
873
+ if (framesCollapsed) next.add(id);
874
+ else next.delete(id);
875
+ }
876
+ return next;
877
+ }, [toggledGroupIds, trailFrameIds, framesCollapsed]);
813
878
  const [committedCollapsed, setCommittedCollapsed] = useState<{
814
879
  framesCollapsed: boolean;
815
880
  toggled: ReadonlySet<string>;
816
- }>({ framesCollapsed, toggled: toggledGroupIds });
881
+ }>({ framesCollapsed, toggled: effectiveToggledGroupIds });
817
882
  const toggleCollapsed = useCallback((groupId: string) => {
818
883
  setToggledGroupIds((prev) => {
819
884
  const next = new Set(prev);
@@ -826,7 +891,7 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
826
891
  setFramesCollapsed(collapsed);
827
892
  setToggledGroupIds(new Set());
828
893
  }, []);
829
- const collapsedKey = `${framesCollapsed ? 'closed' : 'open'}:${Array.from(toggledGroupIds).sort().join(',')}`;
894
+ const collapsedKey = `${framesCollapsed ? 'closed' : 'open'}:${Array.from(effectiveToggledGroupIds).sort().join(',')}`;
830
895
  const committedCollapsedKey = `${committedCollapsed.framesCollapsed ? 'closed' : 'open'}:${Array.from(committedCollapsed.toggled).sort().join(',')}`;
831
896
 
832
897
  const changeLayoutDirection = useCallback(
@@ -874,7 +939,7 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
874
939
  if (reduceMotion) {
875
940
  setCommittedDirection(requestedDirection);
876
941
  setCommittedTrailId(layoutTrailId);
877
- setCommittedCollapsed({ framesCollapsed, toggled: toggledGroupIds });
942
+ setCommittedCollapsed({ framesCollapsed, toggled: effectiveToggledGroupIds });
878
943
  return;
879
944
  }
880
945
  flipSawPendingLayoutRef.current = false;
@@ -883,7 +948,7 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
883
948
  flipFadeTimerRef.current = null;
884
949
  setCommittedDirection(requestedDirection);
885
950
  setCommittedTrailId(layoutTrailId);
886
- setCommittedCollapsed({ framesCollapsed, toggled: toggledGroupIds });
951
+ setCommittedCollapsed({ framesCollapsed, toggled: effectiveToggledGroupIds });
887
952
  }, LAYOUT_FLIP_EDGE_MS);
888
953
  return () => {
889
954
  if (flipFadeTimerRef.current != null) {
@@ -898,7 +963,7 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
898
963
  requestedDirection,
899
964
  layoutTrailId,
900
965
  framesCollapsed,
901
- toggledGroupIds,
966
+ effectiveToggledGroupIds,
902
967
  ]);
903
968
 
904
969
  // Beat 3: the committed layout has settled → the node slide is over, fade
@@ -1795,6 +1860,33 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
1795
1860
  // eslint-disable-next-line react-hooks/exhaustive-deps
1796
1861
  [baseEdges, openedEdgeIds],
1797
1862
  );
1863
+ // Component aliases touched by the hovered trail — the whole flow when a
1864
+ // collapsed row is hovered, one step's endpoints otherwise. Drives container
1865
+ // dimming directly (rather than via rolled-up edge endpoints) so a parent
1866
+ // frame lights when any transitive member is in the trail, and a trail
1867
+ // folded entirely inside one collapsed card still dims the other cards.
1868
+ const hoverTrailAliases = useMemo(() => {
1869
+ if (!hoveredTrailStep || !trails) return null;
1870
+ const tl = trails.find((t) => t.id === hoveredTrailStep.trailId);
1871
+ if (!tl) return null;
1872
+ const ids = new Set<string>();
1873
+ if (hoveredTrailStep.stepIndex == null) {
1874
+ for (const s of tl.steps) {
1875
+ ids.add(s.from);
1876
+ ids.add(s.to);
1877
+ }
1878
+ } else {
1879
+ const step = tl.steps[hoveredTrailStep.stepIndex];
1880
+ if (!step) return null;
1881
+ ids.add(step.from);
1882
+ ids.add(step.to);
1883
+ }
1884
+ return ids.size > 0 ? ids : null;
1885
+ }, [trails, hoveredTrailStep]);
1886
+ const aliasToComponent = useMemo(
1887
+ () => new Map(components.map((c) => [c.alias, c])),
1888
+ [components],
1889
+ );
1798
1890
  // Endpoints of the bright set: the selected step's edge, or the whole flow
1799
1891
  // when no step is focused.
1800
1892
  const brightNodeIds = useMemo(
@@ -1840,13 +1932,20 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
1840
1932
  // there is no opened set, so dimming has to be driven from the
1841
1933
  // participants or nothing outside the focused step would dim.
1842
1934
  const dimSource = previewNodeIds ?? brightNodeIds ?? issueFocusNodeIds;
1935
+ // Hover keeps a container bright when any of its contents is in the
1936
+ // hovered trail — read off component membership so nesting is
1937
+ // transitive and internally-folded trails still count.
1938
+ const touchesHover = regionTouchesTrailAliases(region, hoverTrailAliases, aliasToComponent);
1939
+ const inSpotlight =
1940
+ memberAliases.some((alias) => dimSource?.has(alias) === true) || touchesHover;
1941
+ const anySpotlight = dimSource != null || hoverTrailAliases != null;
1843
1942
  const { hidden, dimmed } = flowNodeVisibility({
1844
1943
  inOpened: memberAliases.some((alias) => openedNodeIds?.has(alias) === true),
1845
1944
  inSelected: memberAliases.some((alias) => brightNodeIds?.has(alias) === true),
1846
- inSpotlight: memberAliases.some((alias) => dimSource?.has(alias) === true),
1945
+ inSpotlight,
1847
1946
  anyOpened: openedNodeIds != null,
1848
1947
  anySelected: brightNodeIds != null,
1849
- anySpotlight: dimSource != null,
1948
+ anySpotlight,
1850
1949
  });
1851
1950
  // Host override wins over the library's derived frame color.
1852
1951
  const color = region?.key != null ? boundaryColors?.[region.key] : undefined;
@@ -1878,10 +1977,10 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
1878
1977
  const { hidden, dimmed } = flowNodeVisibility({
1879
1978
  inOpened: openedNodeIds?.has(n.id) === true,
1880
1979
  inSelected: brightNodeIds?.has(n.id) === true,
1881
- inSpotlight: dimSource?.has(n.id) === true,
1980
+ inSpotlight: dimSource?.has(n.id) === true || (hoverTrailAliases?.has(n.id) === true),
1882
1981
  anyOpened: openedNodeIds != null,
1883
1982
  anySelected: brightNodeIds != null,
1884
- anySpotlight: dimSource != null,
1983
+ anySpotlight: dimSource != null || hoverTrailAliases != null,
1885
1984
  });
1886
1985
  // Component findings key by alias, boundary findings by region node id.
1887
1986
  // The two id spaces are disjoint (`module:` / `process:` are prefixed), so
@@ -1904,7 +2003,7 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
1904
2003
  },
1905
2004
  };
1906
2005
  });
1907
- }, [xyflowNodesBase, openFile, selected, focusNodeIds, openedNodeIds, brightNodeIds, previewNodeIds, issueFocusNodeIds, issueBadgeByAlias, regionIssueByNodeId, boundaryColors, toggleCollapsed]);
2006
+ }, [xyflowNodesBase, openFile, selected, focusNodeIds, openedNodeIds, brightNodeIds, previewNodeIds, hoverTrailAliases, aliasToComponent, issueFocusNodeIds, issueBadgeByAlias, regionIssueByNodeId, boundaryColors, toggleCollapsed]);
1908
2007
 
1909
2008
  const baseNodesKey = useMemo(() => nodes.map((n) => n.id).sort().join(','), [nodes]);
1910
2009
  const baseEdgesKey = useMemo(
@@ -3702,6 +3801,58 @@ function Inner({ components, trails, graphifyRelations, orderByLine, layoutDirec
3702
3801
  );
3703
3802
  }
3704
3803
 
3804
+ /**
3805
+ * One option in the header's segmented sidebar-view switch. Owns the hover
3806
+ * state so every segment reacts the same way — the Issues segment is a
3807
+ * `SubsystemDiagnosticToggle` and already hovers; keeping the plain options
3808
+ * here means the switch has one hover affordance, not two.
3809
+ */
3810
+ function SidebarViewOption({
3811
+ active,
3812
+ ariaLabel,
3813
+ title,
3814
+ onClick,
3815
+ children,
3816
+ }: {
3817
+ active: boolean;
3818
+ ariaLabel: string;
3819
+ title?: string;
3820
+ onClick: () => void;
3821
+ children: ReactNode;
3822
+ }) {
3823
+ const { theme } = useTheme();
3824
+ const [hover, setHover] = useState(false);
3825
+ return (
3826
+ <button
3827
+ type="button"
3828
+ aria-label={ariaLabel}
3829
+ title={title}
3830
+ aria-pressed={active}
3831
+ onClick={onClick}
3832
+ onMouseEnter={() => setHover(true)}
3833
+ onMouseLeave={() => setHover(false)}
3834
+ style={{
3835
+ display: 'inline-flex',
3836
+ alignItems: 'center',
3837
+ justifyContent: 'center',
3838
+ gap: 4,
3839
+ height: 28,
3840
+ padding: '4px 16px',
3841
+ fontFamily: theme.fonts.monospace,
3842
+ fontSize: theme.fontSizes[0],
3843
+ border: 'none',
3844
+ borderRadius: 4,
3845
+ background: active || hover ? theme.colors.border : 'transparent',
3846
+ color: active ? theme.colors.text : (theme.colors.textMuted ?? theme.colors.textSecondary),
3847
+ cursor: 'pointer',
3848
+ transition: 'background 120ms ease',
3849
+ }}
3850
+ >
3851
+ {children}
3852
+ </button>
3853
+ );
3854
+ }
3855
+
3705
3856
  export function SubsystemComponentGraph(props: SubsystemComponentGraphProps) {
3706
3857
  const { theme } = useTheme();
3707
3858
  const wrapRef = useRef<HTMLDivElement>(null);
@@ -3761,22 +3912,6 @@ export function SubsystemComponentGraph(props: SubsystemComponentGraphProps) {
3761
3912
  props.diagnostic?.onToggle?.();
3762
3913
  }
3763
3914
  };
3764
- const viewButtonStyle = (active: boolean): CSSProperties => ({
3765
- display: 'inline-flex',
3766
- alignItems: 'center',
3767
- justifyContent: 'center',
3768
- gap: 4,
3769
- height: 28,
3770
- padding: '4px 16px',
3771
- fontFamily: theme.fonts.monospace,
3772
- fontSize: theme.fontSizes[0],
3773
- border: 'none',
3774
- borderRadius: 4,
3775
- background: active ? theme.colors.border : 'transparent',
3776
- color: active ? theme.colors.text : (theme.colors.textMuted ?? theme.colors.textSecondary),
3777
- cursor: 'pointer',
3778
- });
3779
-
3780
3915
  useEffect(() => {
3781
3916
  if (props.initialTrailId) setFilesOpen(false);
3782
3917
  }, [props.initialTrailId]);
@@ -3857,43 +3992,37 @@ export function SubsystemComponentGraph(props: SubsystemComponentGraphProps) {
3857
3992
  }}
3858
3993
  >
3859
3994
  {containerCount > 0 && (
3860
- <button
3861
- type="button"
3862
- aria-label={`Containers (${containerCount} ${containerCount === 1 ? 'container' : 'containers'})`}
3995
+ <SidebarViewOption
3996
+ ariaLabel={`Containers (${containerCount} ${containerCount === 1 ? 'container' : 'containers'})`}
3863
3997
  title="Show containers"
3864
- aria-pressed={containersActive}
3998
+ active={containersActive}
3865
3999
  onClick={() => selectSidebarView('containers')}
3866
- style={viewButtonStyle(containersActive)}
3867
4000
  >
3868
4001
  <Boxes size={14} aria-hidden />
3869
4002
  <span>Containers</span>
3870
4003
  <span style={{ fontWeight: 600, marginLeft: 4 }}>{containerCount}</span>
3871
- </button>
4004
+ </SidebarViewOption>
3872
4005
  )}
3873
- <button
3874
- type="button"
3875
- aria-label={sidebarScope.trail ? 'Trail' : `Trails (${trailCount} ${trailCount === 1 ? 'trail' : 'trails'})`}
3876
- aria-pressed={!filesActive && !containersActive && !issuesActive}
4006
+ <SidebarViewOption
4007
+ ariaLabel={sidebarScope.trail ? 'Trail' : `Trails (${trailCount} ${trailCount === 1 ? 'trail' : 'trails'})`}
4008
+ active={!filesActive && !containersActive && !issuesActive}
3877
4009
  onClick={() => selectSidebarView('trails')}
3878
- style={viewButtonStyle(!filesActive && !containersActive && !issuesActive)}
3879
4010
  >
3880
4011
  <Route size={14} aria-hidden />
3881
4012
  <span>{trailViewLabel}</span>
3882
4013
  {!sidebarScope.trail && <span style={{ fontWeight: 600, marginLeft: 4 }}>{trailCount}</span>}
3883
- </button>
4014
+ </SidebarViewOption>
3884
4015
  {hasFiles && (
3885
- <button
3886
- type="button"
3887
- aria-label={`Files (${fileCount} files)`}
4016
+ <SidebarViewOption
4017
+ ariaLabel={`Files (${fileCount} files)`}
3888
4018
  title="Show files"
3889
- aria-pressed={filesActive}
4019
+ active={filesActive}
3890
4020
  onClick={() => selectSidebarView('files')}
3891
- style={viewButtonStyle(filesActive)}
3892
4021
  >
3893
4022
  <Files size={14} aria-hidden />
3894
4023
  <span>Files</span>
3895
4024
  <span style={{ fontWeight: 600, marginLeft: 4 }}>{fileCount}</span>
3896
- </button>
4025
+ </SidebarViewOption>
3897
4026
  )}
3898
4027
  {hasIssues && (
3899
4028
  <SubsystemDiagnosticToggle
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
- import { buildSubsystemGraph, collapseBoundaryGroups, type BoundaryLayoutGroup, type SubsystemGraphEdge, type SubsystemGraphNode, type SubsystemProcessRegion } from './model';
2
+ import { buildSubsystemGraph, cardFramesForAliases, collapseBoundaryGroups, packageGroupNodeId, type BoundaryLayoutGroup, type SubsystemGraphEdge, type SubsystemGraphNode, type SubsystemProcessRegion } from './model';
3
3
  import { NODE_H, NODE_W } from './containerCard';
4
4
 
5
5
  function region(kind: SubsystemProcessRegion['kind'], key: string, members: string[]): SubsystemProcessRegion {
@@ -126,3 +126,37 @@ describe('buildSubsystemGraph collapsed frames', () => {
126
126
  expect(groupIds(built.nodes).sort()).toEqual([['process:A', true], ['process:B', false]]);
127
127
  });
128
128
  });
129
+
130
+ describe('cardFramesForAliases', () => {
131
+ const flatDoc = {
132
+ components: [
133
+ { alias: 'a1', name: 'a1', construct: 'function', file: 'a1.ts', purl: 'pkg:github/acme/app', process: 'A' },
134
+ { alias: 'a2', name: 'a2', construct: 'function', file: 'a2.ts', purl: 'pkg:github/acme/app', process: 'A' },
135
+ { alias: 'b1', name: 'b1', construct: 'function', file: 'b1.ts', purl: 'pkg:github/acme/app', process: 'B' },
136
+ { alias: 'b2', name: 'b2', construct: 'function', file: 'b2.ts', purl: 'pkg:github/acme/app', process: 'B' },
137
+ { alias: 'c1', name: 'c1', construct: 'function', file: 'c1.ts', purl: 'pkg:github/acme/app', process: 'C' },
138
+ ],
139
+ } as unknown as Parameters<typeof cardFramesForAliases>[0];
140
+
141
+ test('names the process card that holds a trail member', () => {
142
+ expect([...cardFramesForAliases(flatDoc, new Set(['a1']))]).toEqual(['process:A']);
143
+ });
144
+
145
+ test('opens every card ancestor of a nested module', () => {
146
+ const nestedDoc = {
147
+ components: [
148
+ { alias: 'a1', name: 'a1', construct: 'function', file: 'a1.ts', purl: 'pkg:github/acme/one', process: 'A', module: 'src/a.ts' },
149
+ { alias: 'a2', name: 'a2', construct: 'function', file: 'a2.ts', purl: 'pkg:github/acme/one', process: 'A', module: 'src/a.ts' },
150
+ { alias: 'b1', name: 'b1', construct: 'function', file: 'b1.ts', purl: 'pkg:github/acme/two', process: 'B', module: 'src/b.ts' },
151
+ { alias: 'b2', name: 'b2', construct: 'function', file: 'b2.ts', purl: 'pkg:github/acme/two', process: 'B', module: 'src/b.ts' },
152
+ ],
153
+ } as unknown as Parameters<typeof cardFramesForAliases>[0];
154
+ expect([...cardFramesForAliases(nestedDoc, new Set(['a1']))].sort()).toEqual(
155
+ ['process:A', packageGroupNodeId('pkg:github/acme/one')].sort(),
156
+ );
157
+ });
158
+
159
+ test('ignores aliases with no card frame and a singleton process', () => {
160
+ expect([...cardFramesForAliases(flatDoc, new Set(['c1', 'missing']))]).toEqual([]);
161
+ });
162
+ });
@@ -923,6 +923,34 @@ export function buildBoundaryLayoutGroups(
923
923
  return [...moduleGroups, ...processGroups, ...packageGroups];
924
924
  }
925
925
 
926
+ /**
927
+ * The card frames (process / package) that hold any of `aliases`, plus every
928
+ * card ancestor a nested module needs opened to become visible. This is the
929
+ * set a trail focus opens, so a picked flow reads as its components rather
930
+ * than a row of folded boxes.
931
+ */
932
+ export function cardFramesForAliases(
933
+ doc: Pick<SubsystemModelDocument, 'components'>,
934
+ aliases: ReadonlySet<string>,
935
+ opts: BoundaryFrameOptions = {},
936
+ ): Set<string> {
937
+ const groups = buildBoundaryLayoutGroups(doc, opts);
938
+ const byId = new Map(groups.map((g) => [g.id, g]));
939
+ const open = new Set<string>();
940
+ for (const group of groups) {
941
+ if (!group.memberAliases.some((alias) => aliases.has(alias))) continue;
942
+ if (isCardFrame(group.region)) open.add(group.id);
943
+ let parentId = group.parentId;
944
+ while (parentId) {
945
+ const parent = byId.get(parentId);
946
+ if (!parent) break;
947
+ if (isCardFrame(parent.region)) open.add(parent.id);
948
+ parentId = parent.parentId;
949
+ }
950
+ }
951
+ return open;
952
+ }
953
+
926
954
  /**
927
955
  * Path-nesting variant of {@link buildBoundaryLayoutGroups}.
928
956
  *