Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(graph): bundle community links in the Files view, and make it the default (#2503)

Raghav Chamadiyaf5797f5bbb15
diff --git a/packages/ui/__tests__/graph/community-colors.test.ts b/packages/ui/__tests__/graph/community-colors.test.ts
new file mode 100644
index 000000000..38bc3e6f1
--- /dev/null
+++ b/packages/ui/__tests__/graph/community-colors.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect } from "vitest";
+import { communityColorSlots } from "../../src/graph/community-colors";
+
+const LABELS = [
+ "ingestion",
+ "web/components",
+ "cli",
+ "persistence",
+ "health",
+ "server/routers",
+ "ui/graph",
+ "workspace",
+ "generation",
+ "analysis",
+ "mcp",
+ "distill",
+ "vscode",
+ "types",
+];
+
+describe("communityColorSlots", () => {
+ it("keeps a community's colour when a re-index renumbers it", () => {
+ const before = LABELS.map((label, i) => ({ communityId: i, label, size: 200 - i * 10 }));
+ // Same groups, ids shuffled (ids are size ranks, and two groups swapped).
+ const after = before.map((e, i) => ({ ...e, communityId: (i * 5 + 3) % LABELS.length }));
+ const a = communityColorSlots(before);
+ const b = communityColorSlots(after);
+ for (let i = 0; i < LABELS.length; i++) {
+ expect(b.get(after[i]!.communityId)).toBe(a.get(before[i]!.communityId));
+ }
+ });
+
+ it("gives the twelve largest communities twelve different colours", () => {
+ const slots = communityColorSlots(
+ LABELS.map((label, i) => ({ communityId: i, label, size: 500 - i })),
+ );
+ const top = new Set(LABELS.slice(0, 12).map((_, i) => slots.get(i)));
+ expect(top.size).toBe(12);
+ });
+
+ it("ignores the member-count suffix a duplicate label carries", () => {
+ const a = communityColorSlots([{ communityId: 4, label: "tests/unit (288)", size: 288 }]);
+ const b = communityColorSlots([{ communityId: 9, label: "tests/unit (301)", size: 301 }]);
+ expect(a.get(4)).toBe(b.get(9));
+ });
+});
diff --git a/packages/ui/__tests__/graph/constellation-adapter.test.ts b/packages/ui/__tests__/graph/constellation-adapter.test.ts
index b6079bdab..3c451ef5e 100644
--- a/packages/ui/__tests__/graph/constellation-adapter.test.ts
+++ b/packages/ui/__tests__/graph/constellation-adapter.test.ts
@@ -61,14 +61,15 @@ describe("architectureToGraphology", () => {
expect(g.hasNode(CORE_NODE_ID)).toBe(true);
});
- it("marks hubs with nodeType=hub, forceLabel, and an uppercase label", () => {
+ it("marks hubs with nodeType=hub, forceLabel, and the label in its own case", () => {
const g = architectureToGraphology(
makeArch([makeArchNode({ community_id: 0, label: "auth core" })]),
);
const attrs = g.getNodeAttributes(hubNodeId(0));
expect(attrs.nodeType).toBe("hub");
expect(attrs.forceLabel).toBe(true);
- expect(attrs.label).toBe("AUTH CORE");
+ // Drawn under the disc in full, so it is not shouted to fit inside it.
+ expect(attrs.label).toBe("auth core");
expect(attrs.memberCount).toBe(10);
});
@@ -78,12 +79,12 @@ describe("architectureToGraphology", () => {
makeArchNode({ community_id: 0, label: "", top_file: "src/payments/api.ts" }),
]),
);
- expect(fromFile.getNodeAttributes(hubNodeId(0)).label).toBe("PAYMENTS");
+ expect(fromFile.getNodeAttributes(hubNodeId(0)).label).toBe("payments");
const fromId = architectureToGraphology(
makeArch([makeArchNode({ community_id: 7, label: "", top_file: "" })]),
);
- expect(fromId.getNodeAttributes(hubNodeId(7)).label).toBe("COMMUNITY 7");
+ expect(fromId.getNodeAttributes(hubNodeId(7)).label).toBe("Community 7");
});
it("sizes hubs within the 14–32 sigma-unit range", () => {
@@ -100,23 +101,40 @@ describe("architectureToGraphology", () => {
expect(big).toBeGreaterThan(small);
});
- it("builds cross-community edges with crossCommunity kind and clamped size", () => {
+ it("folds both directions of a pair into one edge weighted by their sum", () => {
const g = architectureToGraphology(
makeArch(
+ [makeArchNode({ community_id: 0 }), makeArchNode({ community_id: 1 })],
[
- makeArchNode({ community_id: 0 }),
- makeArchNode({ community_id: 1 }),
+ { source: 0, target: 1, edge_count: 7 },
+ { source: 1, target: 0, edge_count: 3 },
],
- [{ source: 0, target: 1, edge_count: 7 }],
),
);
expect(g.size).toBe(1);
- const edgeKey = hubNodeId(0) + "→" + hubNodeId(1);
- const attrs = g.getEdgeAttributes(edgeKey);
+ const attrs = g.getEdgeAttributes(g.edges()[0]!);
expect(attrs.edgeKind).toBe("crossCommunity");
- expect(attrs.size).toBeGreaterThanOrEqual(1.5);
- expect(attrs.size).toBeLessThanOrEqual(2.5);
- expect(attrs.edgeCount).toBe(7);
+ expect(attrs.edgeCount).toBe(10);
+ // The heaviest pair: full weight, the widest stroke.
+ expect(attrs.weight).toBe(1);
+ expect(attrs.size).toBeCloseTo(9.8);
+ });
+
+ it("prunes weak pairs but keeps each community's two strongest ties", () => {
+ const nodes = [0, 1, 2, 3].map((id) => makeArchNode({ community_id: id }));
+ const g = architectureToGraphology(
+ makeArch(nodes, [
+ { source: 0, target: 1, edge_count: 1000 },
+ { source: 0, target: 2, edge_count: 900 },
+ // Both under 8% of the heaviest, but community 3's two strongest ties.
+ { source: 1, target: 3, edge_count: 50 },
+ { source: 2, target: 3, edge_count: 6 },
+ // Under 8%, community 0's third tie and community 3's third: dropped.
+ { source: 0, target: 3, edge_count: 5 },
+ ]),
+ );
+ const pairs = g.edges().map((e) => g.extremities(e).map((n) => n.replace("__community__", "")).sort().join("-"));
+ expect(pairs.sort()).toEqual(["0-1", "0-2", "1-3", "2-3"]);
});
it("skips edges referencing dropped communities", () => {
diff --git a/packages/ui/__tests__/graph/files-overview.test.ts b/packages/ui/__tests__/graph/files-overview.test.ts
new file mode 100644
index 000000000..33f38b132
--- /dev/null
+++ b/packages/ui/__tests__/graph/files-overview.test.ts
@@ -0,0 +1,158 @@
+import { describe, it, expect } from "vitest";
+import type { GraphLink, GraphNode } from "@repowise-dev/types/graph";
+import { fileGraphToGraphology } from "../../src/graph/sigma/graphology-adapter";
+import {
+ filterOverviewData,
+ getOverviewMeta,
+ layoutFilesOverview,
+ overviewFileLabel,
+} from "../../src/graph/sigma/files-overview";
+
+function node(id: string, community: number): GraphNode {
+ return {
+ node_id: id,
+ node_type: "file",
+ language: "python",
+ symbol_count: 1,
+ pagerank: 0,
+ betweenness: 0,
+ community_id: community,
+ is_test: false,
+ is_entry_point: false,
+ has_doc: false,
+ };
+}
+
+const dep = (source: string, target: string): GraphLink => ({
+ source,
+ target,
+ imported_names: ["x"],
+ edge_type: "imports",
+});
+
+describe("filterOverviewData", () => {
+ const nodes = [
+ node("a.py", 0),
+ node("b.py", 0),
+ node("orphan.py", 0),
+ node("cochange.py", 0),
+ node("external:rich.console", 0),
+ node("framework:django", 0),
+ ];
+ const links = [
+ dep("a.py", "b.py"),
+ dep("a.py", "external:rich.console"),
+ dep("b.py", "framework:django"),
+ { source: "cochange.py", target: "a.py", imported_names: [], edge_type: "co_changes" },
+ ];
+
+ it("leaves out third-party nodes and files with no dependency edge, counting both", () => {
+ const out = filterOverviewData({ nodes, links }, { showExternal: false });
+ expect(out.nodes.map((n) => n.node_id)).toEqual(["a.py", "b.py"]);
+ expect(out.hiddenExternal).toBe(2);
+ // orphan.py has no edge; cochange.py only a co-change, which is not one.
+ expect(out.hiddenUnlinked).toBe(2);
+ expect(out.links).toHaveLength(1);
+ });
+
+ it("draws third-party nodes when asked, and then hides none", () => {
+ const out = filterOverviewData({ nodes, links }, { showExternal: true });
+ expect(out.hiddenExternal).toBe(0);
+ expect(out.nodes.map((n) => n.node_id)).toContain("framework:django");
+ });
+
+ it("always draws a pinned file, third-party or unlinked, with its edges", () => {
+ const ext = filterOverviewData({ nodes, links }, { showExternal: false, pinned: "external:rich.console" });
+ expect(ext.nodes.map((n) => n.node_id)).toContain("external:rich.console");
+ expect(ext.shownExternal).toBe(1);
+ expect(ext.hiddenExternal).toBe(1);
+ const lone = filterOverviewData({ nodes, links }, { showExternal: false, pinned: "cochange.py" });
+ expect(lone.nodes.map((n) => n.node_id)).toContain("cochange.py");
+ expect(lone.links.some((l) => l.source === "cochange.py")).toBe(true);
+ });
+
+ it("keeps the edges between drawn files of every kind, for the toggles", () => {
+ const withCoChange = [...links, { source: "b.py", target: "a.py", imported_names: [], edge_type: "co_changes" }];
+ const out = filterOverviewData({ nodes, links: withCoChange }, { showExternal: false });
+ expect(out.links.some((l) => l.edge_type === "co_changes")).toBe(true);
+ });
+});
+
+describe("overviewFileLabel", () => {
+ it("gives a generic filename its folder and leaves a telling one alone", () => {
+ expect(overviewFileLabel("pkg/graph/__init__.py")).toBe("graph/__init__.py");
+ expect(overviewFileLabel("src/app/repos/page.tsx")).toBe("repos/page.tsx");
+ expect(overviewFileLabel("pkg/graph/use-sigma.ts")).toBe("use-sigma.ts");
+ });
+});
+
+/** Three communities of `size` files, each a chain, plus `cross` edges from
+ * community 0 to 1 and from 1 to 2, and one stray in its own community. */
+function repo(size: number, cross: number) {
+ const nodes: GraphNode[] = [];
+ const links: GraphLink[] = [];
+ for (let c = 0; c < 3; c++) {
+ for (let i = 0; i < size; i++) {
+ nodes.push(node(`c${c}/f${i}.py`, c));
+ if (i > 0) links.push(dep(`c${c}/f${i}.py`, `c${c}/f${i - 1}.py`));
+ }
+ }
+ for (let i = 0; i < cross; i++) {
+ links.push(dep(`c0/f${i}.py`, `c1/f${i}.py`));
+ links.push(dep(`c1/f${i}.py`, `c2/f${i}.py`));
+ }
+ nodes.push(node("stray/only.py", 9));
+ links.push(dep("stray/only.py", "c2/f0.py"));
+ links.push(dep("stray/only.py", "c2/f1.py"));
+ return { nodes, links };
+}
+
+describe("layoutFilesOverview", () => {
+ it("records clusters and one band per connected community pair", () => {
+ const graph = fileGraphToGraphology(repo(20, 6));
+ const meta = layoutFilesOverview(graph);
+ expect(meta.clusters.map((c) => c.communityId).sort()).toEqual([0, 1, 2]);
+ const pairs = meta.bundles.map((b) => `${b.a}-${b.b}:${b.count}`).sort();
+ expect(pairs).toEqual(["0-1:6", "1-2:6"]);
+ expect(getOverviewMeta(graph)).toBe(meta);
+ });
+
+ it("anchors each band on the clusters' rims, not their centres", () => {
+ const graph = fileGraphToGraphology(repo(20, 6));
+ const meta = layoutFilesOverview(graph);
+ for (const b of meta.bundles) {
+ const from = meta.clusters.find((c) => c.communityId === b.a)!;
+ const to = meta.clusters.find((c) => c.communityId === b.b)!;
+ expect(Math.hypot(b.x0 - from.cx, b.y0 - from.cy)).toBeCloseTo(from.r, 5);
+ expect(Math.hypot(b.x1 - to.cx, b.y1 - to.cy)).toBeCloseTo(to.r, 5);
+ }
+ });
+
+ it("seats a stray file on the rim of the cluster it links to", () => {
+ const graph = fileGraphToGraphology(repo(20, 6));
+ const meta = layoutFilesOverview(graph);
+ const host = meta.clusters.find((c) => c.communityId === 2)!;
+ const { x, y } = graph.getNodeAttributes("stray/only.py");
+ expect(Math.hypot(x - host.cx, y - host.cy)).toBeCloseTo(host.r * 1.15, 5);
+ // Placement only: it keeps its own community and colour.
+ expect(graph.getNodeAttribute("stray/only.py", "communityId")).toBe(9);
+ });
+
+ it("names a few ranked files at overview zoom and gives every file a short label", () => {
+ const graph = fileGraphToGraphology(repo(20, 6));
+ layoutFilesOverview(graph);
+ const forced = graph.filterNodes((_n, a) => !!a.forceLabel);
+ expect(forced.length).toBeGreaterThan(0);
+ expect(forced.length).toBeLessThanOrEqual(8 + 3);
+ expect(graph.getNodeAttribute("c0/f3.py", "label")).toBe("f3.py");
+ });
+
+ it("is idempotent: a second call neither moves nodes nor rebuilds the meta", () => {
+ const graph = fileGraphToGraphology(repo(20, 6));
+ const first = layoutFilesOverview(graph);
+ const before = graph.getNodeAttributes("c1/f5.py");
+ const second = layoutFilesOverview(graph);
+ expect(second).toBe(first);
+ expect(graph.getNodeAttributes("c1/f5.py").x).toBe(before.x);
+ });
+});
diff --git a/packages/ui/__tests__/graph/graph-flow.test.tsx b/packages/ui/__tests__/graph/graph-flow.test.tsx
index 7bb53e86c..40f560f5c 100644
--- a/packages/ui/__tests__/graph/graph-flow.test.tsx
+++ b/packages/ui/__tests__/graph/graph-flow.test.tsx
@@ -66,49 +66,46 @@ describe("GraphFlow shell", () => {
});
// Uses "language" as the controlled value because it is the one that is not
- // the default. Rendered in the file scope: the constellation colours hubs by
- // family whatever colorMode says, so the control is not offered there.
+ // the default. There is no colour control in the header any more, but the
+ // mode still arrives from the URL and the 1/2 keys, and the key row reports
+ // it. Rendered in the dead-code reading: the Files overview pins community.
it("reflects a controlled colorMode and reports changes without self-updating", () => {
const onColorModeChange = vi.fn();
render(
<GraphFlow
{...baseProps}
- initialViewMode="full"
+ initialViewMode="dead"
colorMode="language"
onColorModeChange={onColorModeChange}
/>,
);
- // Controlled value wins: Language is active, Community (the default) is not.
- expect(screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed")).toBe("true");
- expect(
- screen.getByRole("button", { name: "Community" }).getAttribute("aria-pressed"),
- ).toBe("false");
-
- // Clicking another mode reports out but does NOT change the displayed mode —
- // the host owns the value and hasn't pushed a new prop yet.
- fireEvent.click(screen.getByRole("button", { name: "Community" }));
+ expect(screen.getByText("Python")).toBeTruthy();
+ fireEvent.keyDown(window, { key: "2" });
expect(onColorModeChange).toHaveBeenCalledWith("community");
- expect(screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed")).toBe("true");
- expect(
- screen.getByRole("button", { name: "Community" }).getAttribute("aria-pressed"),
- ).toBe("false");
+ // The host owns the value and has not pushed a new one yet.
+ expect(screen.getByText("Python")).toBeTruthy();
});
it("tracks its own colorMode when uncontrolled (seeded by initialColorMode)", () => {
render(
- <GraphFlow {...baseProps} initialViewMode="full" initialColorMode="language" />,
+ <GraphFlow {...baseProps} initialViewMode="dead" initialColorMode="language" />,
);
- expect(
- screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed"),
- ).toBe("true");
+ expect(screen.getByText("Python")).toBeTruthy();
+ fireEvent.keyDown(window, { key: "2" });
+ expect(screen.queryByText("Python")).toBeNull();
+ });
- fireEvent.click(screen.getByRole("button", { name: "Community" }));
- expect(screen.getByRole("button", { name: "Community" }).getAttribute("aria-pressed")).toBe("true");
- expect(
- screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed"),
- ).toBe("false");
+ it("keeps the header row to Trace and Search: no layout, colour or fit glyphs", () => {
+ render(<GraphFlow {...baseProps} initialViewMode="full" />);
+ expect(screen.getByRole("button", { name: "Trace" })).toBeTruthy();
+ expect(screen.getByRole("textbox", { name: "Search graph nodes" })).toBeTruthy();
+ for (const gone of ["Hierarchical", "Force (FA2)", "Language", "Community", "Fit view"]) {
+ expect(screen.queryByRole("button", { name: gone })).toBeNull();
+ }
+ // Shortcuts moved to the key row; `?` still opens them.
+ expect(screen.getByRole("button", { name: "Keyboard shortcuts" })).toBeTruthy();
});
it("offers an exclusive All / Hot / Dead node filter", () => {
@@ -165,7 +162,7 @@ describe("GraphFlow shell", () => {
initialViewMode="full"
fullGraph={{
nodes: [fileNode("app.py", "python"), fileNode("core.py", "python")],
- links: [],
+ links: [{ source: "app.py", target: "core.py", imported_names: ["run"] }],
}}
executionFlows={{
total_entry_points: 1,
@@ -232,12 +229,13 @@ describe("GraphFlow shell", () => {
const nodes = flows.flows[0]!.trace.map((id) =>
fileNode(id.split("::")[0]!, "python"),
);
+ const links = [{ source: "app.py", target: "core.py", imported_names: ["run"] }];
rerender(
<GraphFlow
{...baseProps}
initialViewMode="full"
executionFlows={flows}
- fullGraph={{ nodes, links: [] }}
+ fullGraph={{ nodes, links }}
/>,
);
expect(focusNodeSpy).toHaveBeenCalledWith("app.py");
@@ -249,64 +247,87 @@ describe("GraphFlow shell", () => {
{...baseProps}
initialViewMode="full"
executionFlows={flows}
- fullGraph={{ nodes: [...nodes], links: [] }}
+ fullGraph={{ nodes: [...nodes], links }}
/>,
);
expect(focusNodeSpy).toHaveBeenCalledTimes(1);
});
- it("shows hierarchical layout as unavailable above the ELK cap, with the reason", () => {
- const nodes = Array.from({ length: 501 }, (_, i) =>
- fileNode(`f${i}.ts`, "typescript"),
- );
+});
+
+describe("GraphFlow Files overview", () => {
+ const nodes = [
+ fileNode("src/a.py", "python"),
+ fileNode("src/b.py", "python"),
+ fileNode("src/lonely.py", "python"),
+ fileNode("external:rich.console", "python"),
+ ];
+ const links = [
+ { source: "src/a.py", target: "src/b.py", imported_names: ["b"] },
+ { source: "src/a.py", target: "external:rich.console", imported_names: ["Console"] },
+ // Co-change is not a dependency: it holds nothing on the map.
+ { source: "src/lonely.py", target: "src/a.py", imported_names: [], edge_type: "co_changes" },
+ ];
+
+ it("hides third-party modules and unlinked files by default, and says how many", () => {
+ const onShowExternalChange = vi.fn();
render(
<GraphFlow
{...baseProps}
initialViewMode="full"
- fullGraph={{ nodes, links: [] }}
+ fullGraph={{ nodes, links }}
+ onShowExternalChange={onShowExternalChange}
/>,
);
+ expect(screen.getByText(/^2 files/)).toBeTruthy();
+ expect(screen.getByText(/1 third-party modules hidden/)).toBeTruthy();
+ expect(screen.getByText("1 unlinked files not drawn")).toBeTruthy();
+ const toggle = screen.getByRole("button", { name: "Show third-party modules" });
+ expect(toggle.getAttribute("aria-pressed")).toBe("false");
+ fireEvent.click(toggle);
+ expect(onShowExternalChange).toHaveBeenCalledWith(true);
+ });
- const button = screen.getByRole("button", { name: "Hierarchical" });
-
- // Unavailable up front rather than live-then-refusing. ELK's 500-node cap
- // sits below the graph loader's 1,500-node floor, and "load more" only
- // raises it — so on any repo past the cap this control could never act,
- // and used to say so only after you pressed it.
- expect(button.hasAttribute("disabled")).toBe(true);
- expect(button.getAttribute("title")).toContain(
- "Hierarchical layout needs 500 nodes or fewer",
+ it("keeps a pinned file the overview would leave out, with its edges", () => {
+ render(
+ <GraphFlow
+ {...baseProps}
+ initialViewMode="full"
+ fullGraph={{ nodes, links }}
+ initialSelectedNode="src/lonely.py"
+ />,
);
+ // lonely.py (held only by a co-change) and a.py, which it reaches.
+ expect(screen.queryByText("1 unlinked files not drawn")).toBeNull();
+ expect(screen.getByText(/^3 files/)).toBeTruthy();
+ });
- // The reason must not offer a remedy that cannot work. The module filter,
- // the community filter and search all dim rather than remove, so none of
- // them changes `graph.order`, which is the number this cap is measured
- // against — an earlier version told the reader to use exactly those.
- expect(button.getAttribute("title")).not.toMatch(
- /module filter|Modules scope|narrow the view/i,
+ it("draws the Files overview in community colours whatever colorMode says", () => {
+ render(
+ <GraphFlow {...baseProps} initialViewMode="full" colorMode="language" fullGraph={{ nodes, links }} />,
);
-
- // Clicking a disabled control changes nothing.
- fireEvent.click(button);
- expect(button.getAttribute("aria-pressed")).toBe("false");
+ expect(screen.queryByText("Python")).toBeNull();
});
- it("leaves hierarchical layout available when the graph fits under the cap", () => {
- const nodes = Array.from({ length: 40 }, (_, i) =>
- fileNode(`f${i}.ts`, "typescript"),
- );
+ it("draws them when the host asks", () => {
render(
<GraphFlow
{...baseProps}
initialViewMode="full"
- fullGraph={{ nodes, links: [] }}
+ fullGraph={{ nodes, links }}
+ showExternal
/>,
);
+ // Counted apart from the repo's own files, and co-change is no dependency.
+ expect(screen.getByText("2 files · 1 third-party · 2 dependencies")).toBeTruthy();
+ expect(screen.getByText("Third-party modules shown")).toBeTruthy();
+ });
- const button = screen.getByRole("button", { name: "Hierarchical" });
- expect(button.hasAttribute("disabled")).toBe(false);
- fireEvent.click(button);
- expect(button.getAttribute("aria-pressed")).toBe("true");
+ it("keys the direction a hovered file's edges point", () => {
+ render(<GraphFlow {...baseProps} initialViewMode="full" fullGraph={{ nodes, links }} />);
+ expect(screen.getByText("imports")).toBeTruthy();
+ expect(screen.getByText("imported by")).toBeTruthy();
+ expect(screen.getByText("Co-change")).toBeTruthy();
});
});
diff --git a/packages/ui/__tests__/graph/use-sigma-focus.test.tsx b/packages/ui/__tests__/graph/use-sigma-focus.test.tsx
index 671b02c36..2800d3543 100644
--- a/packages/ui/__tests__/graph/use-sigma-focus.test.tsx
+++ b/packages/ui/__tests__/graph/use-sigma-focus.test.tsx
@@ -18,8 +18,24 @@ class FakeSigma {
lastSigmaInstance = this as unknown as Record<string, unknown>;
}
getCamera() {
- return { animate: cameraAnimate, animatedReset: vi.fn(), animatedZoom: vi.fn(), animatedUnzoom: vi.fn() };
+ return {
+ animate: cameraAnimate,
+ animatedReset: vi.fn(),
+ animatedZoom: vi.fn(),
+ animatedUnzoom: vi.fn(),
+ on: vi.fn(),
+ };
}
+ // The Files overview's canvas layers (attached for every graph, blank
+ // unless the graph carries overview meta).
+ createCanvas() {
+ return document.createElement("canvas");
+ }
+ killLayer() {}
+ getDimensions() {
+ return { width: 800, height: 600 };
+ }
+ once() {}
getNodeDisplayData(id: string) {
return getNodeDisplayData(id);
}
diff --git a/packages/ui/src/graph/community-colors.ts b/packages/ui/src/graph/community-colors.ts
new file mode 100644
index 000000000..d614f4487
--- /dev/null
+++ b/packages/ui/src/graph/community-colors.ts
@@ -0,0 +1,80 @@
+"use client";
+
+import { createContext, useContext, useMemo } from "react";
+import {
+ COMMUNITY_FAMILY_COUNT,
+ useCommunityFamilies,
+ type CommunityFamily,
+} from "../shared/use-theme-tokens";
+
+/**
+ * Community colour keyed by something that survives a re-index.
+ *
+ * The family used to be `communityId % 12`. Community ids are size ranks
+ * (`detect_file_communities` re-indexes by member count), so one community
+ * growing past another renumbers both and every group on the map changes
+ * colour between two indexes of the same code. A colour a reader has learned
+ * is part of the map; it should move only when the group does.
+ *
+ * So the family is picked from the community's label, which is derived from
+ * its paths and does not depend on rank. Larger groups choose first and take
+ * their preferred family, or the next free one if a larger group already has
+ * it, so the twelve biggest always get twelve distinct colours; past twelve,
+ * groups share, as they always did.
+ *
+ * Ceiling: stable exactly as far as the label is. A community whose label
+ * changes (it gained a new dominant folder) changes colour. The upgrade is a
+ * persisted colour key on the index, which needs a wire field.
+ */
+export interface CommunityColorEntry {
+ communityId: number;
+ label: string;
+ size: number;
+}
+
+function labelHash(label: string): number {
+ // The dedup suffix (`tests/unit (288)`) is a member count and changes with
+ // the index, so it is not part of the name.
+ const key = label.replace(/\s*\(\d+\)\s*$/, "").trim().toLowerCase();
+ let h = 5381;
+ for (let i = 0; i < key.length; i++) h = ((h << 5) + h + key.charCodeAt(i)) | 0;
+ return Math.abs(h);
+}
+
+/** Community id → family slot (0..11). */
+export function communityColorSlots(
+ entries: readonly CommunityColorEntry[],
+): Map<number, number> {
+ const slots = new Map<number, number>();
+ const taken = new Set<number>();
+ const ranked = [...entries].sort(
+ (a, b) => b.size - a.size || a.label.localeCompare(b.label) || a.communityId - b.communityId,
+ );
+ for (const e of ranked) {
+ if (slots.has(e.communityId)) continue;
+ const preferred = labelHash(e.label) % COMMUNITY_FAMILY_COUNT;
+ let slot = preferred;
+ if (taken.size < COMMUNITY_FAMILY_COUNT) {
+ while (taken.has(slot)) slot = (slot + 1) % COMMUNITY_FAMILY_COUNT;
+ taken.add(slot);
+ }
+ slots.set(e.communityId, slot);
+ }
+ return slots;
+}
+
+/** Slot map for the graph below it. Null keeps the id-keyed default, so a
+ * surface rendered outside `GraphFlow` is unaffected. */
+export const CommunityColorContext = createContext<Map<number, number> | null>(null);
+
+/** `useCommunityFamilies`, keyed through the stable slots when a graph
+ * provides them. Every community colour in the graph module reads this, so
+ * the canvas, the key and the inspector cannot disagree. */
+export function useGraphCommunityFamilies(): (communityId: number) => CommunityFamily {
+ const families = useCommunityFamilies();
+ const slots = useContext(CommunityColorContext);
+ return useMemo(
+ () => (slots ? (cid: number) => families(slots.get(cid) ?? cid) : families),
+ [families, slots],
+ );
+}
diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsx
index f5b38f687..fa95a1a7d 100644
--- a/packages/ui/src/graph/graph-flow.tsx
+++ b/packages/ui/src/graph/graph-flow.tsx
@@ -9,7 +9,7 @@ import {
type ReactNode,
} from "react";
import { useTheme } from "next-themes";
-import { X } from "lucide-react";
+import { HelpCircle } from "lucide-react";
import { Skeleton } from "../ui/skeleton";
import { EmptyState } from "../shared/empty-state";
import { type Signal } from "./context";
@@ -31,7 +31,7 @@ import { useGraphSearch } from "./use-graph-search";
import { useCommunityFilter } from "./use-community-filter";
import { useModuleFilter, filterGraphToModule } from "./use-module-filter";
import { useGraphKeyboardShortcuts } from "./use-graph-keyboard-shortcuts";
-import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme } from "./graph-toolbar";
+import { GraphToolbar, type ColorMode, type ViewMode, type GraphTheme } from "./graph-toolbar";
import { GraphLegend } from "./graph-legend";
import { GraphNodeFilter } from "./graph-toolbar";
import { GraphCanvasShell } from "./graph-canvas-shell";
@@ -60,10 +60,11 @@ import {
UNCLUSTERED_COMMUNITY_ID,
} from "./sigma/constellation-adapter";
import { computeRadialLayout } from "./sigma/radial-layout";
-import { ELK_MAX_NODES, elkSkipReason } from "./sigma/use-elk-sigma-layout";
import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./sigma/types";
import type GraphologyGraph from "graphology";
import { useEgoFilter } from "./sigma/use-ego-filter";
+import { filterOverviewData, getOverviewMeta, layoutFilesOverview } from "./sigma/files-overview";
+import { CommunityColorContext, communityColorSlots } from "./community-colors";
export interface GraphFlowProps {
fullGraph: GraphExport | undefined;
@@ -99,6 +100,13 @@ export interface GraphFlowProps {
* supplied. */
population?: GraphPopulation | undefined;
onPopulationChange?: ((next: GraphPopulation) => void) | undefined;
+ /** Whether the whole-repo Files view draws third-party (`external:` /
+ * `framework:`) nodes. Off by default: on this repo they are a tenth of the
+ * drawn nodes and touch 40% of the drawn edges, none of it the repo's own
+ * structure. Controlled when supplied (a host URL-syncs it); otherwise the
+ * component tracks it. The key always says how many are hidden. */
+ showExternal?: boolean | undefined;
+ onShowExternalChange?: ((next: boolean) => void) | undefined;
/** Repo name for the constellation core label. */
repoName?: string;
deadCodeGraph: GraphExport | undefined;
@@ -196,6 +204,8 @@ export function GraphFlow(props: GraphFlowProps) {
activeCommunity: controlledActiveCommunity,
population,
onPopulationChange,
+ showExternal: controlledShowExternal,
+ onShowExternalChange,
onActiveCommunityChange,
communitySlice,
isLoadingCommunitySlice,
@@ -264,12 +274,15 @@ export function GraphFlow(props: GraphFlowProps) {
const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());
const [showPathFinder, setShowPathFinder] = useState(false);
const [showShortcutHelp, setShowShortcutHelp] = useState(false);
- // Explanation surfaced when the hierarchical layout refuses to run (too
- // many nodes) — otherwise the toggle looks active but does nothing.
- const [layoutNotice, setLayoutNotice] = useState<string | null>(null);
- // Constellation is the default scope → its fixed radial layout.
- const [layoutMode, setLayoutMode] = useState<LayoutMode>(
- (initialViewMode ?? "architecture") === "architecture" ? "radial" : "force",
+ // Third-party nodes in the Files overview. See `showExternal`.
+ const [showExternalState, setShowExternalState] = useState(false);
+ const showExternal = controlledShowExternal ?? showExternalState;
+ const setShowExternal = useCallback(
+ (next: boolean) => {
+ if (onShowExternalChange) onShowExternalChange(next);
+ else setShowExternalState(next);
+ },
+ [onShowExternalChange],
);
// The dependency graph follows the global app theme rather than a separate
@@ -565,6 +578,26 @@ export function GraphFlow(props: GraphFlowProps) {
return filterGraphToModule(scopeGraphData, controlledActiveModule ?? null);
}, [isInsideCommunity, communitySlice, scopeGraphData, controlledActiveModule]);
+ // The whole-repo Files view is the overview: clusters, bands, and a file's
+ // own edges on hover (see `sigma/files-overview.ts`). The dead/hot signals
+ // keep the plain reading: their payloads are sparse by design, and dropping
+ // unlinked files would drop most of a dead-code view.
+ const isFilesOverview = viewMode === "full" && !isInsideCommunity;
+ const overviewData = useMemo(
+ () =>
+ isFilesOverview && fileGraphData
+ ? filterOverviewData(fileGraphData, { showExternal, pinned: initialSelectedNode })
+ : undefined,
+ [isFilesOverview, fileGraphData, showExternal, initialSelectedNode],
+ );
+ // What is built and drawn: the overview's filtered set, or the payload.
+ const drawData = overviewData ?? fileGraphData;
+ // The overview speaks community: clusters, bands, names and the key are all
+ // community hues, so a Language reading (key 1, `?colorMode=language`) would
+ // repaint the files alone and leave the rest unkeyed. It applies to the
+ // other file readings; the Communities view never read it.
+ const drawnColorMode: ColorMode = isFilesOverview ? "community" : colorMode;
+
// Loading state
const isLoading =
isInsideCommunity ? !!isLoadingCommunitySlice :
@@ -601,7 +634,7 @@ export function GraphFlow(props: GraphFlowProps) {
// returns null and the effect below constructs them in chunks, keeping the
// loading state up until the first frame is ready.
const syncSigmaGraph = useMemo(() => {
- const graphData = fileGraphData;
+ const graphData = drawData;
if (!graphData) return null;
// Defer large file graphs to the async effect below.
@@ -615,7 +648,7 @@ export function GraphFlow(props: GraphFlowProps) {
{ nodes: graphData.nodes, links: graphData.links },
{ signals, ...(sliceBoundaryIds ? { boundaryNodeIds: sliceBoundaryIds } : {}) },
);
- }, [fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, sliceBoundaryIds]);
+ }, [drawData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, sliceBoundaryIds]);
// Async-built file graph for large graphs (built in chunks off the main
// thread critical path). Null while building / when the sync path applies.
@@ -626,7 +659,7 @@ export function GraphFlow(props: GraphFlowProps) {
const [isBuildingGraph, setIsBuildingGraph] = useState(false);
const needsAsyncBuild =
- !!fileGraphData && fileGraphData.nodes.length >= ASYNC_BUILD_THRESHOLD;
+ !!drawData && drawData.nodes.length >= ASYNC_BUILD_THRESHOLD;
// `isBuildingGraph` is only raised *inside* the effect below, which React
// runs after it has already painted. So on the commit where an async build
@@ -638,7 +671,7 @@ export function GraphFlow(props: GraphFlowProps) {
const isAwaitingAsyncBuild = needsAsyncBuild && !asyncSigmaGraph;
useEffect(() => {
- if (!needsAsyncBuild || !fileGraphData) {
+ if (!needsAsyncBuild || !drawData) {
setAsyncSigmaGraph(null);
setIsBuildingGraph(false);
return;
@@ -652,7 +685,7 @@ export function GraphFlow(props: GraphFlowProps) {
if (hasDeadSignal || isUnified) signals.deadNodeIds = deadNodeIds;
void fileGraphToGraphologyAsync(
- { nodes: fileGraphData.nodes, links: fileGraphData.links },
+ { nodes: drawData.nodes, links: drawData.links },
{ signals, ...(sliceBoundaryIds ? { boundaryNodeIds: sliceBoundaryIds } : {}) },
).then((graph) => {
if (cancelled) return;
@@ -663,11 +696,17 @@ export function GraphFlow(props: GraphFlowProps) {
return () => {
cancelled = true;
};
- }, [needsAsyncBuild, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, sliceBoundaryIds]);
-
- const sigmaGraph = isConstellation
- ? constellationSigmaGraph
- : (syncSigmaGraph ?? asyncSigmaGraph);
+ }, [needsAsyncBuild, drawData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, sliceBoundaryIds]);
+
+ const builtFileGraph = syncSigmaGraph ?? asyncSigmaGraph;
+ // The overview lays out the graph it was built from, once per build. It
+ // mutates positions in place and is idempotent (React may run this twice),
+ // and it runs before Sigma is handed the graph, so no frame shows the seed.
+ const sigmaGraph = useMemo(() => {
+ if (isConstellation) return constellationSigmaGraph;
+ if (builtFileGraph && isFilesOverview) layoutFilesOverview(builtFileGraph);
+ return builtFileGraph;
+ }, [isConstellation, constellationSigmaGraph, builtFileGraph, isFilesOverview]);
// Entering a community swaps the payload, and the slice is a round trip.
// Blanking to a skeleton in between would unmount the renderer, and with it
@@ -689,6 +728,46 @@ export function GraphFlow(props: GraphFlowProps) {
const displayGraph =
sigmaGraph ?? (isEnteringCommunity ? heldGraphRef.current : null);
+ // Community colours keyed by label rather than by id, which is a size rank
+ // and renumbers between indexes. See `community-colors.ts`. The summary list
+ // covers both scopes and the constellation payload fills in what it lacks.
+ // The drawn graph fills in the rest: a community on the canvas that neither
+ // lists (below the summary's floor, or before it has loaded) is keyed by its
+ // best-connected drawn file, so it still takes a free family instead of
+ // falling back to `id % 12` on top of one a listed community holds.
+ const colorSlots = useMemo(() => {
+ const entries: { communityId: number; label: string; size: number }[] = [];
+ const seen = new Set<number>();
+ for (const c of communities ?? []) {
+ seen.add(c.community_id);
+ entries.push({ communityId: c.community_id, label: c.label, size: c.member_count });
+ }
+ for (const n of constellationGraph?.nodes ?? []) {
+ if (seen.has(n.community_id)) continue;
+ seen.add(n.community_id);
+ entries.push({ communityId: n.community_id, label: n.label ?? "", size: n.member_count });
+ }
+ if (displayGraph && !isConstellation) {
+ const drawn = new Map<number, { top: string; rank: number; size: number }>();
+ displayGraph.forEachNode((node, a) => {
+ if (a.nodeType !== "file" || seen.has(a.communityId)) return;
+ const d = drawn.get(a.communityId);
+ if (!d) drawn.set(a.communityId, { top: node, rank: a.pagerank, size: 1 });
+ else {
+ d.size++;
+ if (a.pagerank > d.rank) {
+ d.top = node;
+ d.rank = a.pagerank;
+ }
+ }
+ });
+ for (const [communityId, d] of drawn) {
+ entries.push({ communityId, label: d.top, size: d.size });
+ }
+ }
+ return entries.length > 0 ? communityColorSlots(entries) : null;
+ }, [communities, constellationGraph, displayGraph, isConstellation]);
+
const { hiddenNodes, isActive: isEgoActive, visibleCount: egoVisibleCount } = useEgoFilter({
graph: displayGraph,
selectedNodeId,
@@ -1043,10 +1122,6 @@ export function GraphFlow(props: GraphFlowProps) {
setPathNotice(null);
}, []);
- const handleFitView = useCallback(() => {
- sigmaRef.current?.fitView();
- }, []);
-
// Everything a scope change has to clear, in one place. Scope can now arrive
// from the host (the section-header switcher, URL-synced) as well as from the
// toolbar's overlay buttons, so this reacts to the resolved value rather than
@@ -1057,9 +1132,6 @@ export function GraphFlow(props: GraphFlowProps) {
useEffect(() => {
if (appliedViewModeRef.current === viewMode) return;
appliedViewModeRef.current = viewMode;
- // Constellation is fixed-radial; other scopes default back to FA2.
- setLayoutMode(viewMode === "architecture" ? "radial" : "force");
- setLayoutNotice(null);
setHighlightedPath(new Set());
setHighlightedEdges(new Set());
// Measured against the graph being replaced, so it retires with it.
@@ -1070,19 +1142,6 @@ export function GraphFlow(props: GraphFlowProps) {
if (viewMode === "architecture") setActiveCommunity(null);
}, [viewMode, setActiveCommunity]);
- const handleLayoutModeChange = useCallback((mode: LayoutMode) => {
- // Refuse right at the click when ELK can't run: switching the mode anyway
- // would stop the force layout and leave an active-looking toggle doing
- // nothing (the canvas-side notice covers graphs that grow past the cap
- // after the mode is already active).
- if (mode === "hierarchical" && displayGraph && displayGraph.order > ELK_MAX_NODES) {
- setLayoutNotice(elkSkipReason(displayGraph.order));
- return;
- }
- setLayoutMode(mode);
- setLayoutNotice(null);
- }, [displayGraph]);
-
const handleEdgeTypeToggle = useCallback((edgeType: string) => {
setVisibleEdgeTypes((prev) => {
const next = new Set(prev);
@@ -1177,6 +1236,49 @@ export function GraphFlow(props: GraphFlowProps) {
return n;
}, [displayGraph, visibleEdgeTypes]);
+ // The overview's key. Memoized with the trailing button so the memoized
+ // legend does not re-render with every render of this shell.
+ const overviewLegend = useMemo(() => {
+ if (!overviewData || !displayGraph) return undefined;
+ // Dependencies only: co-change and low-confidence edges are revealed on a
+ // focused file, never counted as the map's structure.
+ let dependencies = 0;
+ displayGraph.forEachEdge((_, attrs) => {
+ if (
+ (attrs.edgeKind === "internal" || attrs.edgeKind === "crossCommunity") &&
+ visibleEdgeTypes.has(attrs.edgeKind)
+ ) {
+ dependencies++;
+ }
+ });
+ return {
+ hiddenExternal: overviewData.hiddenExternal,
+ shownExternal: overviewData.shownExternal,
+ hiddenUnlinked: overviewData.hiddenUnlinked,
+ omittedLinks: getOverviewMeta(displayGraph)?.omittedPairs ?? 0,
+ dependencies,
+ showExternal,
+ onShowExternalChange: setShowExternal,
+ };
+ }, [overviewData, displayGraph, visibleEdgeTypes, showExternal, setShowExternal]);
+
+ // Moved out of the header row, which now carries only what changes the
+ // picture. `?` still opens it from anywhere.
+ const shortcutsButton = useMemo(
+ () => (
+ <button
+ type="button"
+ onClick={handleToggleShortcutHelp}
+ title="Keyboard shortcuts (?)"
+ aria-label="Keyboard shortcuts"
+ className="flex h-7 w-7 items-center justify-center rounded-md text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <HelpCircle className="h-3.5 w-3.5" />
+ </button>
+ ),
+ [handleToggleShortcutHelp],
+ );
+
// Members vs the one-hop stubs around them, from the same payload the banner
// counts, so the two figures on screen cannot disagree.
const sliceCounts = useMemo(() => {
@@ -1331,6 +1433,7 @@ export function GraphFlow(props: GraphFlowProps) {
: null;
return (
+ <CommunityColorContext.Provider value={colorSlots}>
<GraphCanvasShell
breadcrumb={
isInsideCommunity && activeCommunityLabel ? (
@@ -1363,9 +1466,6 @@ export function GraphFlow(props: GraphFlowProps) {
)}
<GraphToolbar
viewMode={viewMode}
- colorMode={colorMode}
- onColorModeChange={setColorMode}
- onFitView={handleFitView}
showPathFinder={showPathFinder}
pathFinderAvailable={Boolean(renderPathFinder)}
onTogglePathFinder={() => {
@@ -1384,19 +1484,11 @@ export function GraphFlow(props: GraphFlowProps) {
searchMatchCount={searchResults.length}
searchTotalCount={displayGraph?.order ?? 0}
onSearchKeyDown={handleSearchKeyDown}
- layoutMode={isEnteringCommunity ? "radial" : layoutMode}
- onLayoutModeChange={handleLayoutModeChange}
- onToggleHelp={handleToggleShortcutHelp}
- hierarchicalDisabledReason={
- displayGraph && displayGraph.order > ELK_MAX_NODES
- ? elkSkipReason(displayGraph.order)
- : undefined
- }
/>
</div>
}
banner={
- banner || layoutNotice || sliceNotice || pathNotice ? (
+ banner || sliceNotice || pathNotice ? (
<div className="space-y-2">
{banner}
{(sliceNotice || pathNotice) && (
@@ -1408,22 +1500,6 @@ export function GraphFlow(props: GraphFlowProps) {
{[sliceNotice, pathNotice].filter(Boolean).join(" ")}
</p>
)}
- {layoutNotice && (
- <div
- role="status"
- aria-live="polite"
- className="flex items-center gap-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-bg-elevated)] px-3 py-1.5"
- >
- <span className="text-[11px] text-[var(--color-text-primary)]">{layoutNotice}</span>
- <button
- onClick={() => setLayoutNotice(null)}
- aria-label="Dismiss layout notice"
- className="shrink-0 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- <X className="w-3 h-3" />
- </button>
- </div>
- )}
</div>
) : undefined
}
@@ -1434,7 +1510,7 @@ export function GraphFlow(props: GraphFlowProps) {
nodeCount={displayGraph?.order ?? 0}
edgeCount={displayGraph?.size ?? 0}
visibleEdgeCount={visibleEdgeCount}
- colorMode={colorMode}
+ colorMode={drawnColorMode}
viewMode={viewMode}
{...(isInsideCommunity && activeCommunityLabel
? {
@@ -1473,6 +1549,8 @@ export function GraphFlow(props: GraphFlowProps) {
}
: undefined
}
+ overview={overviewLegend}
+ trailing={shortcutsButton}
/>
{hasCanvasStatus && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
@@ -1533,29 +1611,30 @@ export function GraphFlow(props: GraphFlowProps) {
<SigmaCanvas
ref={sigmaRef}
graph={displayGraph}
- layoutMode={isEnteringCommunity ? "radial" : layoutMode}
+ // The seed is the layout (see `buildFileGraph`): "force" only means
+ // "not the constellation", and FA2 skips a presettled graph.
+ layoutMode={isConstellation || isEnteringCommunity ? "radial" : "force"}
viewMode={viewMode}
selectedNodeId={selectedNodeId}
highlightedPath={highlightedPath}
highlightedEdges={highlightedEdges}
searchDimmedNodes={searchDimmedNodes}
communityDimmedNodes={communityDimmedNodes}
- colorMode={colorMode}
+ colorMode={drawnColorMode}
activeSignals={activeSignals}
graphTheme={graphTheme}
- fileNodes={fileGraphData?.nodes}
- fileEdges={fileGraphData?.links}
onNodeClick={handleSigmaNodeClick}
onNodeDoubleClick={handleSigmaDoubleClick}
onNodeContextMenu={handleSigmaNodeContextMenu}
onStageClick={() => setSelectedNodeId(null)}
- onLayoutSkipped={setLayoutNotice}
reducedMotion={prefersReducedMotion}
hiddenNodes={isEgoActive ? hiddenNodes : undefined}
visibleEdgeTypes={visibleEdgeTypes}
depthRingRadii={
isConstellation || isEnteringCommunity ? constellationRingRadii : null
}
+ communityLabels={communityLabels}
+ activeCommunities={activeCommunities}
/>
) : !isLoading ? (
<div className="flex items-center justify-center h-full">
@@ -1570,6 +1649,7 @@ export function GraphFlow(props: GraphFlowProps) {
) : null}
</div>
</GraphCanvasShell>
+ </CommunityColorContext.Provider>
);
}
diff --git a/packages/ui/src/graph/graph-inspection-panel.tsx b/packages/ui/src/graph/graph-inspection-panel.tsx
index 4cb6f6061..c15502ab6 100644
--- a/packages/ui/src/graph/graph-inspection-panel.tsx
+++ b/packages/ui/src/graph/graph-inspection-panel.tsx
@@ -25,7 +25,7 @@ import { formatNumber } from "../lib/format";
import type { FileNodeData, ModuleNodeData } from "./elk-layout";
import type Graph from "graphology";
import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./sigma/types";
-import { useCommunityFamilies } from "../shared/use-theme-tokens";
+import { useGraphCommunityFamilies } from "./community-colors";
interface NeighborInfo {
id: string;
@@ -114,7 +114,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({
onEgoDepthChange,
egoVisibleCount,
}: GraphInspectionPanelProps) {
- const communityFamily = useCommunityFamilies();
+ const communityFamily = useGraphCommunityFamilies();
const touchStartY = useRef<number | null>(null);
const neighbors = useMemo(() => {
if (!graph || !graph.hasNode(nodeId)) return [];
diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsx
index 982368c08..e970ed9aa 100644
--- a/packages/ui/src/graph/graph-legend.tsx
+++ b/packages/ui/src/graph/graph-legend.tsx
@@ -5,7 +5,7 @@ import type { ReactNode } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { LANGUAGE_COLORS } from "../lib/confidence";
import { edgeColorsForTheme } from "./sigma/constants";
-import { useCommunityFamilies } from "../shared/use-theme-tokens";
+import { useGraphCommunityFamilies } from "./community-colors";
import type { ColorMode, ViewMode } from "./graph-toolbar";
/** Community rows shown before the key folds into a "+N" line. */
@@ -14,6 +14,10 @@ const COMMUNITY_ROWS = 8;
/**
* Edge kinds, in the order they are keyed.
*
+ * `dynamic` is keyed "Co-change": it is the `co_changes` edge, two files that
+ * change together in git history, not a runtime dependency. Keyed "Dynamic",
+ * it read as dynamic imports, which is a different claim.
+ *
* There is no "Imports" row any more. `classifyEdge` returned that kind only
* for an edge with an endpoint missing from the graph, and those are dropped
* before they are drawn — so the swatch keyed zero marks in every state, and
@@ -23,7 +27,7 @@ const COMMUNITY_ROWS = 8;
const EDGE_KINDS = [
{ type: "crossCommunity", label: "Cross-community" },
{ type: "internal", label: "Internal" },
- { type: "dynamic", label: "Dynamic" },
+ { type: "dynamic", label: "Co-change" },
{ type: "lowConfidence", label: "Low confidence" },
] as const;
@@ -31,10 +35,16 @@ const EDGE_KINDS = [
const SCOPED_EDGE_KINDS = [
{ type: "internal", label: "Within this group" },
{ type: "crossCommunity", label: "Leaving this group" },
- { type: "dynamic", label: "Dynamic" },
+ { type: "dynamic", label: "Co-change" },
{ type: "lowConfidence", label: "Low confidence" },
] as const;
+/** The overview draws cross-community edges as bands between clusters. */
+const OVERVIEW_EDGE_LABELS: Partial<Record<string, string>> = {
+ crossCommunity: "Between communities",
+ internal: "Within a community",
+};
+
const LANGUAGE_LEGEND = [
{ lang: "python", color: LANGUAGE_COLORS.python, label: "Python" },
{ lang: "typescript", color: LANGUAGE_COLORS.typescript, label: "TypeScript" },
@@ -155,6 +165,42 @@ interface GraphLegendProps {
* summary list, which on a capped file graph names groups no node here
* belongs to; keying those offered a toggle that could not do anything. */
drawnCommunityIds?: Set<number> | undefined;
+ /**
+ * The whole-repo Files overview: what it leaves out, and the direction key
+ * for a focused file's edges. Its presence selects that reading.
+ */
+ overview?: OverviewLegend | undefined;
+ /** Rendered at the row's far end in every reading (the shortcuts button). */
+ trailing?: ReactNode | undefined;
+}
+
+export interface OverviewLegend {
+ /** Third-party nodes not drawn (0 while they are shown). */
+ hiddenExternal: number;
+ /** Third-party nodes drawn, counted apart from the repo's own files. */
+ shownExternal: number;
+ /** Files with no dependency edge to anything drawn. */
+ hiddenUnlinked: number;
+ /** Community pairs whose link is below the band floor, so not drawn. */
+ omittedLinks: number;
+ /** Dependency edges drawn (co-change and low confidence never count). */
+ dependencies: number;
+ showExternal: boolean;
+ onShowExternalChange: (next: boolean) => void;
+}
+
+/** Kinds the overview reveals only on a hovered or selected file. */
+const FOCUS_ONLY_KINDS = new Set(["dynamic", "lowConfidence"]);
+
+/** A short stroke, for keying a line rather than a node. */
+function LineSwatch({ color, dashed }: { color: string; dashed?: boolean }) {
+ return (
+ <span
+ aria-hidden="true"
+ className="inline-block h-0 w-3.5 shrink-0 border-t-2"
+ style={{ borderColor: color, borderStyle: dashed ? "dashed" : "solid" }}
+ />
+ );
}
export const GraphLegend = memo(function GraphLegend({
@@ -179,11 +225,13 @@ export const GraphLegend = memo(function GraphLegend({
visibleEdgeCount,
nodeFilter,
drawnCommunityIds,
+ overview,
+ trailing,
}: GraphLegendProps) {
// Open by default: every node is painted from this key, so a collapsed one
// ships a field of coloured circles with no way to read them.
const [expanded, setExpanded] = useState(true);
- const communityFamily = useCommunityFamilies();
+ const communityFamily = useGraphCommunityFamilies();
const edgeColors = edgeColorsForTheme(graphTheme);
const isConstellation = viewMode === "architecture";
@@ -244,6 +292,7 @@ export const GraphLegend = memo(function GraphLegend({
)}
</div>
)}
+ {trailing && <span className="ml-auto">{trailing}</span>}
</div>
);
}
@@ -332,19 +381,68 @@ export const GraphLegend = memo(function GraphLegend({
)}
</div>
)}
+ {trailing && <span className="ml-auto">{trailing}</span>}
</div>
);
}
return (
<div className={shellClass}>
- <button onClick={() => setExpanded((s) => !s)} className={headerClass}>
+ <button
+ onClick={() => setExpanded((s) => !s)}
+ className={headerClass}
+ aria-expanded={expanded}
+ >
<span className={countClass}>
- {nodeCount} nodes &middot; {drawnEdgeCount} edges
+ {overview
+ ? [
+ `${(nodeCount - overview.shownExternal).toLocaleString()} files`,
+ overview.shownExternal > 0
+ ? `${overview.shownExternal.toLocaleString()} third-party`
+ : null,
+ `${overview.dependencies.toLocaleString()} dependencies`,
+ ]
+ .filter(Boolean)
+ .join(" · ")
+ : `${nodeCount} nodes · ${drawnEdgeCount} edges`}
</span>
<Chevron expanded={expanded} />
</button>
{nodeFilter}
+ {overview && (
+ // What the picture leaves out, beside the count it changes. Rule:
+ // state what is not drawn.
+ <span className="inline-flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-[var(--color-text-secondary)]">
+ {(overview.hiddenExternal > 0 || overview.showExternal) && (
+ <span className="inline-flex items-center gap-1.5">
+ {overview.showExternal
+ ? "Third-party modules shown"
+ : `${overview.hiddenExternal.toLocaleString()} third-party modules hidden`}
+ <button
+ type="button"
+ onClick={() => overview.onShowExternalChange(!overview.showExternal)}
+ aria-pressed={overview.showExternal}
+ aria-label={
+ overview.showExternal ? "Hide third-party modules" : "Show third-party modules"
+ }
+ className="rounded px-1 py-0.5 font-medium text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {overview.showExternal ? "Hide" : "Show"}
+ </button>
+ </span>
+ )}
+ {overview.hiddenUnlinked > 0 && (
+ <span title="Files with no dependency edge to anything drawn have no place in the layout and nothing to reveal on hover.">
+ {overview.hiddenUnlinked.toLocaleString()} unlinked files not drawn
+ </span>
+ )}
+ {overview.omittedLinks > 0 && (
+ <span title="Pairs of communities with too few dependencies between them to band. Their edges still show on a hovered or selected file.">
+ {overview.omittedLinks.toLocaleString()} weaker community links not drawn
+ </span>
+ )}
+ </span>
+ )}
{expanded && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
@@ -435,27 +533,58 @@ export const GraphLegend = memo(function GraphLegend({
);
})()}
- {onEdgeTypeToggle && visibleEdgeTypes && (
- <>
- <p className={groupClass}>Edges</p>
- {EDGE_KINDS.map((et) => {
- const checked = visibleEdgeTypes.has(et.type);
- return (
- <div key={et.type} className={rowClass}>
- <SwatchToggle
- color={edgeColors[et.type]}
- checked={checked}
- label={`Toggle ${et.label} edges`}
- onToggle={() => onEdgeTypeToggle(et.type)}
- />
- <span className={`truncate ${checked ? "" : "opacity-45"}`}>
- {et.label}
- </span>
- </div>
- );
- })}
- </>
- )}
+ {onEdgeTypeToggle && visibleEdgeTypes && (() => {
+ const toggle = (et: (typeof EDGE_KINDS)[number]) => {
+ const checked = visibleEdgeTypes.has(et.type);
+ const label = (overview && OVERVIEW_EDGE_LABELS[et.type]) || et.label;
+ return (
+ <div key={et.type} className={rowClass}>
+ <SwatchToggle
+ // The overview draws these in community hues (bands,
+ // cluster texture) or in the direction hues on a focused
+ // file, never in the kind colours, so it keys none of them.
+ color={overview ? "var(--color-text-secondary)" : edgeColors[et.type]}
+ checked={checked}
+ label={`Toggle ${label} edges`}
+ onToggle={() => onEdgeTypeToggle(et.type)}
+ />
+ <span className={`truncate ${checked ? "" : "opacity-45"}`}>
+ {label}
+ </span>
+ </div>
+ );
+ };
+ if (!overview) {
+ return (
+ <>
+ <p className={groupClass}>Edges</p>
+ {EDGE_KINDS.map(toggle)}
+ </>
+ );
+ }
+ // The overview draws co-change and low-confidence edges only on a
+ // focused file, so their toggles sit under that heading rather
+ // than beside kinds that change the picture at rest.
+ return (
+ <>
+ <p className={groupClass}>Edges</p>
+ {EDGE_KINDS.filter((et) => !FOCUS_ONLY_KINDS.has(et.type)).map(toggle)}
+ {/* A focused file's edges carry direction, in two hues that
+ must be named: colour alone cannot say which way a
+ dependency points. */}
+ <p className={groupClass}>Hover or select a file</p>
+ <span className="inline-flex items-center gap-1.5 text-[11px] text-[var(--color-text-secondary)]">
+ <LineSwatch color="var(--color-accent-primary)" />
+ imports
+ </span>
+ <span className="inline-flex items-center gap-1.5 text-[11px] text-[var(--color-text-secondary)]">
+ <LineSwatch color="var(--color-accent-secondary)" />
+ imported by
+ </span>
+ {EDGE_KINDS.filter((et) => FOCUS_ONLY_KINDS.has(et.type)).map(toggle)}
+ </>
+ );
+ })()}
{viewMode !== "full" && (
<p className="text-[10px] text-[var(--color-text-tertiary)]">
@@ -466,6 +595,7 @@ export const GraphLegend = memo(function GraphLegend({
)}
</div>
)}
+ {trailing && <span className="ml-auto">{trailing}</span>}
</div>
);
});
diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsx
index be42bfbe6..64196c34e 100644
--- a/packages/ui/src/graph/graph-toolbar.tsx
+++ b/packages/ui/src/graph/graph-toolbar.tsx
@@ -1,23 +1,15 @@
"use client";
import {
- Palette,
- Network,
- Maximize,
Route,
Skull,
Flame,
Workflow,
Search,
X,
- GitBranch,
- Waypoints,
- SlidersHorizontal,
- HelpCircle,
ChevronDown,
} from "lucide-react";
import { memo, useState } from "react";
-import { Button } from "../ui/button";
import { Popover, PopoverTrigger, PopoverContent } from "../ui/popover";
/**
@@ -93,8 +85,17 @@ interface GraphToolbarProps {
* out-of-tree host compiles while it ports.
*/
onViewChange?: ((mode: ViewMode) => void) | undefined;
- colorMode: ColorMode;
- onColorModeChange: (mode: ColorMode) => void;
+ /**
+ * @deprecated The colour-by control is gone from the header. Community is
+ * the reading both scopes are drawn in (clusters, bands and the key all
+ * speak it), and a Language toggle in the Files row repainted the nodes
+ * while the bands and cluster names stayed in community hues. The mode
+ * itself still works (`?colorMode=language`, keys 1/2); accepted and
+ * ignored here so an out-of-tree host compiles while it ports.
+ */
+ colorMode?: ColorMode | undefined;
+ /** @deprecated See {@link GraphToolbarProps.colorMode}. */
+ onColorModeChange?: ((mode: ColorMode) => void) | undefined;
/**
* @deprecated Removed. The control was titled "Hide test files" and filtered
* *search results* only — `activeSignals` never reached the renderer, so
@@ -104,7 +105,10 @@ interface GraphToolbarProps {
hideTests?: boolean | undefined;
/** @deprecated See {@link GraphToolbarProps.hideTests}. */
onHideTestsChange?: ((v: boolean) => void) | undefined;
- onFitView: () => void;
+ /** @deprecated Fit lives with the zoom controls on the canvas
+ * (`SigmaControls`); a second copy in the header was one of the header
+ * row's seven controls. Accepted and ignored. */
+ onFitView?: (() => void) | undefined;
showPathFinder: boolean;
onTogglePathFinder: () => void;
/** Hosts without a path-finder implementation hide the toggle entirely. */
@@ -116,16 +120,18 @@ interface GraphToolbarProps {
searchMatchCount?: number;
searchTotalCount?: number;
onSearchKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
- layoutMode: LayoutMode;
- onLayoutModeChange: (mode: LayoutMode) => void;
- /** Opens the keyboard-shortcut help overlay (also bound to `?`). */
- onToggleHelp?: () => void;
- /** Why the hierarchical layout cannot run on this graph, if it cannot.
- * Renders the toggle disabled with the reason as its tooltip instead of
- * letting it look live and then refuse on click — ELK's 500-node cap sits
- * BELOW the graph loader's 1,500-node floor, so on any repo bigger than
- * that the button was unreachable by construction and said so only after
- * you pressed it. */
+ /**
+ * @deprecated The layout toggle is gone. Its only alternative to the seed
+ * was ELK, capped at 500 nodes, below the loader's 1,500-node floor: on any
+ * repo big enough to want it, it could never run. Accepted and ignored.
+ */
+ layoutMode?: LayoutMode | undefined;
+ /** @deprecated See {@link GraphToolbarProps.layoutMode}. */
+ onLayoutModeChange?: ((mode: LayoutMode) => void) | undefined;
+ /** @deprecated The shortcuts button moved to the key row under the canvas
+ * (`GraphLegend`'s `trailing`); `?` still opens it. Accepted and ignored. */
+ onToggleHelp?: (() => void) | undefined;
+ /** @deprecated See {@link GraphToolbarProps.layoutMode}. */
hierarchicalDisabledReason?: string | undefined;
}
@@ -144,39 +150,15 @@ const NODE_FILTERS: { id: Overlay | "all"; icon?: typeof Skull; label: string; h
{ id: "dead", icon: Skull, label: "Dead", hint: "Dead-code files" },
];
-const COLOR_MODES: { id: ColorMode; icon: typeof Palette; label: string }[] = [
- { id: "language", icon: Palette, label: "Language" },
- { id: "community", icon: Network, label: "Community" },
-];
-
-const LAYOUT_MODES: { id: LayoutMode; icon: typeof GitBranch; label: string }[] = [
- { id: "force", icon: Waypoints, label: "Force (FA2)" },
- { id: "hierarchical", icon: GitBranch, label: "Hierarchical" },
-];
-
-/**
- * Groups inside the one header cluster.
- *
- * A hairline *between* groups, not a box *around* them. This was a bordered
- * panel whose three groups stacked as blocks, so beside the scope controls it
- * read as a second toolbar. Every peer canvas puts exactly one cluster in the
- * header band: `health/triage-view` (lens switcher only), the Knowledge Graph
- * page (one hairline row), `workspace/system-map` (filters only) and
- * `coupling/coupling-explorer` (hairline rows, no box). DESIGN_LANGUAGE.md
- * reserves bordered containers for objects that can be selected, opened or
- * acted on; a cluster of loose toggles is not one.
- */
-const groupClass = "flex items-center gap-0.5";
-
-const dividerClass =
- "ml-0.5 border-l border-[var(--color-border-default)] pl-1.5";
-
+// Trace sits beside the scope switcher and reads as its peer: the same 12px
+// type and hairline border. It was a 10px tertiary glyph-and-word, which is
+// the size and tone the contrast audit fails.
const itemActiveClass =
- "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]";
+ "border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]";
const itemIdleClass =
- "text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-secondary)]";
+ "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]";
const itemClass =
- "flex items-center gap-1.5 rounded-md px-2 py-2 text-[10px] font-medium transition-colors sm:py-1";
+ "flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
/** Segmented control, matching `coupling-explorer`'s: counts live inside the
* segments rather than in a caption beside them. */
@@ -255,11 +237,16 @@ export function GraphNodeFilter({
);
}
+/**
+ * The header row's canvas controls: Trace (path finder, execution flows) and
+ * Search. The host puts the narrowing control and the scope switcher beside
+ * it, so the Files row reads Showing / Communities|Files / Trace / Search,
+ * with room for Export. It carried seven more (two layout glyphs, two colour
+ * glyphs, fit, help and a mobile disclosure for all of them); each is gone or
+ * moved, and the deprecated props say where.
+ */
export const GraphToolbar = memo(function GraphToolbar({
viewMode,
- colorMode,
- onColorModeChange,
- onFitView,
showPathFinder,
onTogglePathFinder,
pathFinderAvailable = true,
@@ -270,192 +257,94 @@ export const GraphToolbar = memo(function GraphToolbar({
searchMatchCount,
searchTotalCount,
onSearchKeyDown,
- layoutMode,
- onLayoutModeChange,
- onToggleHelp,
- hierarchicalDisabledReason,
}: GraphToolbarProps) {
- // Below sm the full control cluster is too much chrome — collapse it behind
- // a single toggle, keeping search always reachable.
- const [mobileOpen, setMobileOpen] = useState(false);
const [traceOpen, setTraceOpen] = useState(false);
- const clusterVisibility = mobileOpen ? "flex" : "hidden sm:flex";
// Derive scope from the legacy ViewMode so this component remains the single
// source of truth — callers can continue to round-trip the wire-format
// `viewMode` value through query params without translation.
const { scope: activeScope } = viewModeToScopeOverlays(viewMode);
- // The Knowledge Graph (constellation) scope is a fixed radial composition:
- // overlays / FA2 / hierarchical layout don't apply, so those controls are
- // hidden here rather than shown in a half-working state.
+ // The constellation has no file nodes to trace between, so Trace is hidden
+ // there rather than shown in a half-working state.
const isConstellation = activeScope === "architecture";
const traceActive = showPathFinder || showFlows;
return (
<div className="flex flex-wrap items-center justify-end gap-1.5">
- <div className={`${clusterVisibility} flex-wrap items-center gap-y-1`}>
- {!isConstellation && (
- <div className={groupClass}>
- {LAYOUT_MODES.map((m) => {
- const Icon = m.icon;
- const isActive = layoutMode === m.id;
- const disabledReason =
- m.id === "hierarchical" ? hierarchicalDisabledReason : undefined;
- return (
- <button
- key={m.id}
- onClick={() => onLayoutModeChange(m.id)}
- disabled={!!disabledReason}
- className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass} ${
- disabledReason ? "cursor-not-allowed opacity-40" : ""
- }`}
- title={disabledReason ?? m.label}
- aria-label={m.label}
- aria-disabled={!!disabledReason}
- aria-pressed={isActive}
- >
- <Icon className="w-3 h-3" />
- </button>
- );
- })}
- </div>
- )}
-
- {/* Colour-by. The active mode always carries its word: unlabelled
- glyphs gave no way to tell which vocabulary the circles were in.
- Hidden in the constellation, where hubs are family-coloured
- regardless of this setting. */}
- {!isConstellation && (
- <div className={`${groupClass} ${dividerClass}`}>
- <span className="hidden pr-0.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] lg:inline">
- Colour
- </span>
- {COLOR_MODES.map((m) => {
- const Icon = m.icon;
- const isActive = colorMode === m.id;
- return (
- <button
- key={m.id}
- onClick={() => onColorModeChange(m.id)}
- className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass}`}
- title={m.label}
- aria-label={m.label}
- aria-pressed={isActive}
- >
- <Icon className="w-3 h-3" />
- {isActive && <span>{m.label}</span>}
- </button>
- );
- })}
- </div>
- )}
-
- {/* No theme control here. It set the *global* theme, so it did exactly
- what the app's own toggle in the header does, a few hundred pixels
- away — two controls, one effect, and this one buried in a row of a
- dozen unlabelled icons.
-
- Path finding and execution flows are two uncommon actions that were
- two unlabelled glyphs. DESIGN_LANGUAGE.md: do not abbreviate an
- uncommon action to make it fit. One named control, opened on
- demand, carries both with their words. */}
- <div className={`${groupClass} ${isConstellation ? "" : dividerClass}`}>
- {!isConstellation && (
- <Popover open={traceOpen} onOpenChange={setTraceOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- className={`${itemClass} ${traceActive ? itemActiveClass : itemIdleClass}`}
- title={
- pathFinderAvailable
- ? "Trace a dependency path or an execution flow"
- : "Trace an execution flow"
- }
- // Not colour alone. The two buttons this replaced each
- // carried their own `aria-pressed`; without this a reader who
- // cannot see the accent has to open the menu to learn a trace
- // panel is already open.
- aria-label={
- showPathFinder
- ? "Trace — dependency path open"
- : showFlows
- ? "Trace — execution flows open"
- : "Trace"
- }
- >
- <Route className="w-3 h-3" />
- <span>Trace</span>
- <ChevronDown className="w-3 h-3" />
- </button>
- </PopoverTrigger>
- <PopoverContent align="end" className="w-56 p-1">
- {pathFinderAvailable && (
- <button
- type="button"
- onClick={() => {
- setTraceOpen(false);
- onTogglePathFinder();
- }}
- aria-pressed={showPathFinder}
- className={`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-wash-hover)] ${
- showPathFinder
- ? "text-[var(--color-accent-primary)]"
- : "text-[var(--color-text-primary)]"
- }`}
- >
- <Route className="h-3.5 w-3.5 shrink-0" />
- Find dependency path
- </button>
- )}
- <button
- type="button"
- onClick={() => {
- setTraceOpen(false);
- onToggleFlows();
- }}
- aria-pressed={showFlows}
- className={`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-wash-hover)] ${
- showFlows
- ? "text-[var(--color-accent-primary)]"
- : "text-[var(--color-text-primary)]"
- }`}
- >
- <Workflow className="h-3.5 w-3.5 shrink-0" />
- Execution flows
- </button>
- </PopoverContent>
- </Popover>
- )}
- <Button
- size="sm"
- variant="ghost"
- onClick={onFitView}
- className="h-8 w-8 sm:h-7 sm:w-7 p-0 text-[var(--color-text-tertiary)]"
- title="Fit view"
- aria-label="Fit view"
- >
- <Maximize className="w-3.5 h-3.5" />
- </Button>
- {onToggleHelp && (
- <Button
- size="sm"
- variant="ghost"
- onClick={onToggleHelp}
- className="h-8 w-8 sm:h-7 sm:w-7 p-0 text-[var(--color-text-tertiary)]"
- title="Keyboard shortcuts (?)"
- aria-label="Keyboard shortcuts"
+ {/* Path finding and execution flows are two uncommon actions that were
+ two unlabelled glyphs. DESIGN_LANGUAGE.md: do not abbreviate an
+ uncommon action to make it fit. One named control, opened on demand,
+ carries both with their words. */}
+ {!isConstellation && (
+ <Popover open={traceOpen} onOpenChange={setTraceOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className={`${itemClass} ${traceActive ? itemActiveClass : itemIdleClass}`}
+ title={
+ pathFinderAvailable
+ ? "Trace a dependency path or an execution flow"
+ : "Trace an execution flow"
+ }
+ // Not colour alone. The two buttons this replaced each carried
+ // their own `aria-pressed`; without this a reader who cannot see
+ // the accent has to open the menu to learn a trace panel is
+ // already open.
+ aria-label={
+ showPathFinder
+ ? "Trace: dependency path open"
+ : showFlows
+ ? "Trace: execution flows open"
+ : "Trace"
+ }
>
- <HelpCircle className="w-3.5 h-3.5" />
- </Button>
- )}
- </div>
- </div>
+ <Route className="w-3 h-3" />
+ <span>Trace</span>
+ <ChevronDown className="w-3 h-3" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-56 p-1">
+ {pathFinderAvailable && (
+ <button
+ type="button"
+ onClick={() => {
+ setTraceOpen(false);
+ onTogglePathFinder();
+ }}
+ aria-pressed={showPathFinder}
+ className={`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-wash-hover)] ${
+ showPathFinder
+ ? "text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-primary)]"
+ }`}
+ >
+ <Route className="h-3.5 w-3.5 shrink-0" />
+ Find dependency path
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => {
+ setTraceOpen(false);
+ onToggleFlows();
+ }}
+ aria-pressed={showFlows}
+ className={`flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-[var(--color-bg-wash-hover)] ${
+ showFlows
+ ? "text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-primary)]"
+ }`}
+ >
+ <Workflow className="h-3.5 w-3.5 shrink-0" />
+ Execution flows
+ </button>
+ </PopoverContent>
+ </Popover>
+ )}
- {/* Search stays visible at every width — it is the one control that
- still works when the rest of the cluster is collapsed on a phone. A
- bordered field of its own width, rather than a row of the old panel,
- so it stops stretching to whatever the widest stacked group needed. */}
+ {/* A bordered field of its own width, so it stops stretching to whatever
+ the widest neighbour needs. */}
<div className="relative">
<Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
<input
@@ -484,21 +373,6 @@ export const GraphToolbar = memo(function GraphToolbar({
)}
</span>
</div>
-
- {/* Mobile: single toggle for the control cluster */}
- <button
- onClick={() => setMobileOpen((s) => !s)}
- className={`flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-[10px] font-medium sm:hidden ${
- mobileOpen
- ? "text-[var(--color-accent-primary)]"
- : "text-[var(--color-text-secondary)]"
- }`}
- aria-expanded={mobileOpen}
- aria-label="Graph controls"
- >
- <SlidersHorizontal className="w-3 h-3" />
- Controls
- </button>
</div>
);
});
diff --git a/packages/ui/src/graph/sigma/constellation-adapter.ts b/packages/ui/src/graph/sigma/constellation-adapter.ts
index 3b8c04377..e9816598a 100644
--- a/packages/ui/src/graph/sigma/constellation-adapter.ts
+++ b/packages/ui/src/graph/sigma/constellation-adapter.ts
@@ -36,23 +36,25 @@ export const CORE_NODE_ID = "__repo_core__";
const PLACEHOLDER_HUB_COLOR = EDGE_COLORS.crossCommunity;
const PLACEHOLDER_CORE_COLOR = "#1a1320";
-/** Uppercase, trimmed community label; falls back to dirname / "Community N". */
+/**
+ * The community's own label, in its own case; falls back to dirname /
+ * "Community N". Drawn *outside* the disc now, so it no longer has to be
+ * shouted to fit: the disc carries the member count and the name sits under
+ * it, in full, the way the paths it is derived from are written.
+ */
function hubLabel(node: ArchitectureNode): string {
const raw = (node.label ?? "").trim();
- if (raw) return raw.toUpperCase();
+ if (raw) return raw;
const fromFile = (node.top_file ?? "").split("/").slice(-2, -1)[0];
- if (fromFile) return fromFile.toUpperCase();
- return `COMMUNITY ${node.community_id}`;
+ if (fromFile) return fromFile;
+ return `Community ${node.community_id}`;
}
-/** Curvature mirrors the file/module adapters (deterministic per edge key). */
-function computeEdgeCurvature(edgeKey: string): number {
- let hash = 5381;
- for (let i = 0; i < edgeKey.length; i++) {
- hash = ((hash << 5) + hash + (edgeKey.charCodeAt(i) ?? 0)) | 0;
- }
- return 0.12 + (Math.abs(hash) % 80) / 1000;
-}
+/** A pair of communities is drawn when it carries this share of the
+ * heaviest pair's edges... */
+const EDGE_KEEP_SHARE = 0.08;
+/** ...or is one of a community's this-many strongest ties. */
+const EDGE_KEEP_PARTNERS = 2;
export interface ConstellationOptions {
/** Repo name for the core label. Falls back to "REPO". */
@@ -143,7 +145,7 @@ export function architectureToGraphology(
y: layout.core.y + layout.ringRadii[2] * 1.18,
size: hubSizeFromMembers(unclustered.file_count),
color: PLACEHOLDER_HUB_COLOR,
- label: "NOT GROUPED",
+ label: "not grouped",
nodeType: "hub",
fullPath: "",
language: "",
@@ -161,24 +163,53 @@ export function architectureToGraphology(
});
}
- // Aggregated cross-community edges: thin plum spokes beneath the hubs.
- const maxEdgeCount = arch.edges.reduce((m, e) => Math.max(m, e.edge_count), 1);
+ // One weighted edge per pair of communities, the weak ones pruned.
+ //
+ // The payload is directed, so most pairs arrived as two edges drawn over
+ // each other at 1.5-2.5px: on this repo 130 near-identical plum strokes
+ // with no way to tell a 900-edge dependency from a 3-edge one. Folding the
+ // two directions together and sizing by sqrt(share of the heaviest) makes
+ // weight readable; pruning keeps every pair at 8% or more of the heaviest,
+ // plus each community's two strongest partners so none is left floating.
+ const pairs = new Map<string, { s: string; t: string; count: number }>();
for (const edge of arch.edges) {
- const src = hubNodeId(edge.source);
- const tgt = hubNodeId(edge.target);
- if (!result.hasNode(src) || !result.hasNode(tgt)) continue;
- const edgeKey = src + "→" + tgt;
- if (result.hasEdge(edgeKey)) continue;
- // 1.5–2.5px proportional to edge_count.
- const size = 1.5 + (edge.edge_count / maxEdgeCount);
- result.addEdgeWithKey(edgeKey, src, tgt, {
- size,
+ const a = hubNodeId(edge.source);
+ const b = hubNodeId(edge.target);
+ if (a === b || !result.hasNode(a) || !result.hasNode(b)) continue;
+ const [s0, t0] = a < b ? [a, b] : [b, a];
+ const key = s0 + "|" + t0;
+ const p = pairs.get(key);
+ if (p) p.count += edge.edge_count;
+ else pairs.set(key, { s: s0, t: t0, count: edge.edge_count });
+ }
+ const ranked = [...pairs.values()].sort(
+ (p, q) => q.count - p.count || (p.s + p.t < q.s + q.t ? -1 : 1),
+ );
+ const heaviest = ranked[0]?.count ?? 1;
+ const keep = new Set<string>();
+ const partners = new Map<string, number>();
+ for (const p of ranked) {
+ const key = p.s + "|" + p.t;
+ if (p.count >= heaviest * EDGE_KEEP_SHARE) keep.add(key);
+ for (const hub of [p.s, p.t]) {
+ const n = partners.get(hub) ?? 0;
+ if (n < EDGE_KEEP_PARTNERS) keep.add(key);
+ partners.set(hub, n + 1);
+ }
+ }
+ for (const p of ranked) {
+ const edgeKey = p.s + "|" + p.t;
+ if (!keep.has(edgeKey)) continue;
+ const weight = Math.sqrt(p.count / heaviest);
+ result.addEdgeWithKey(edgeKey, p.s, p.t, {
+ size: 0.8 + 9 * weight,
color: EDGE_COLORS.crossCommunity,
type: "curved",
- curvature: computeEdgeCurvature(edgeKey),
+ curvature: 0.18,
edgeKind: "crossCommunity",
importedNames: [],
- edgeCount: edge.edge_count,
+ edgeCount: p.count,
+ weight,
zIndex: 0,
});
}
diff --git a/packages/ui/src/graph/sigma/files-overview.ts b/packages/ui/src/graph/sigma/files-overview.ts
new file mode 100644
index 000000000..bc13f0d67
--- /dev/null
+++ b/packages/ui/src/graph/sigma/files-overview.ts
@@ -0,0 +1,416 @@
+/**
+ * The whole-repo Files view: communities as coloured clusters, one weighted
+ * band per pair of communities, a few ranked file labels, and each file's own
+ * edges revealed on hover or selection (drawn by `overview-layers.ts`).
+ *
+ * Two steps, both pure over their input:
+ * 1. `filterOverviewData` decides what is drawn at all (the data policy).
+ * 2. `layoutFilesOverview` adjusts positions and derives the clusters,
+ * bands and label ranking the canvas layers draw from.
+ *
+ * Measured on this repo's 1,500-node export: 153 nodes are third-party
+ * (`external:` / `framework:`) and touch 40% of drawn edges; 5 community pairs
+ * carry 81% of the cross-community traffic. That is why third-party is hidden
+ * by default and why cross-community structure is drawn as bands rather than
+ * as 1,900 individual chords.
+ */
+import type Graph from "graphology";
+import { isExternal } from "@repowise-dev/types";
+import type { GraphLink, GraphNode } from "@repowise-dev/types/graph";
+import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";
+import { isStructuralLink } from "./graphology-adapter";
+
+type SigmaGraph = Graph<SigmaNodeAttributes, SigmaEdgeAttributes>;
+
+// ---- 1. What is drawn ----------------------------------------------------
+
+export interface OverviewData {
+ nodes: GraphNode[];
+ links: GraphLink[];
+ /** Third-party nodes left out (only counted while they are hidden). */
+ hiddenExternal: number;
+ /** Third-party nodes drawn: all of them when shown, else only a pinned one. */
+ shownExternal: number;
+ /** Files with no dependency edge to anything drawn. */
+ hiddenUnlinked: number;
+}
+
+/**
+ * Drop third-party nodes unless asked for, then drop files left with no
+ * dependency edge. An unlinked file has no position the layout can justify
+ * and nothing to reveal on hover, so it is counted rather than drawn.
+ * Co-change and low-confidence edges do not count as a link here: they are
+ * off by default, so a file held only by them would be a dot with no line.
+ *
+ * `pinned` (a `?node=` link from a file page, a symbol, a dead-code finding)
+ * is always drawn, with every edge it has to a drawn file and the files at
+ * the far end of those edges, whatever the rules above say: a link that
+ * lands on nothing is worse than a node the overview would have left out.
+ */
+export function filterOverviewData(
+ data: { nodes: GraphNode[]; links: GraphLink[] },
+ options: { showExternal: boolean; pinned?: string | null | undefined },
+): OverviewData {
+ const pinned = options.pinned ?? null;
+ const external = new Set<string>();
+ if (!options.showExternal) {
+ for (const n of data.nodes) {
+ if (n.node_id !== pinned && isExternal(n.node_id)) external.add(n.node_id);
+ }
+ }
+ const present = new Set<string>();
+ for (const n of data.nodes) if (!external.has(n.node_id)) present.add(n.node_id);
+
+ const linked = new Set<string>();
+ if (pinned && present.has(pinned)) linked.add(pinned);
+ for (const l of data.links) {
+ if (l.source === l.target) continue;
+ if (!present.has(l.source) || !present.has(l.target)) continue;
+ if (!isStructuralLink(l) && l.source !== pinned && l.target !== pinned) continue;
+ linked.add(l.source);
+ linked.add(l.target);
+ }
+ const nodes = data.nodes.filter((n) => linked.has(n.node_id));
+ const links = data.links.filter((l) => linked.has(l.source) && linked.has(l.target));
+ let shownExternal = 0;
+ for (const n of nodes) if (isExternal(n.node_id)) shownExternal++;
+ return {
+ nodes,
+ links,
+ hiddenExternal: external.size,
+ shownExternal,
+ hiddenUnlinked: present.size - nodes.length,
+ };
+}
+
+// ---- 2. Layout and derived structure ------------------------------------
+
+export interface OverviewCluster {
+ communityId: number;
+ /** Centroid, graph coordinates. */
+ cx: number;
+ cy: number;
+ /** 85th-percentile member distance from the centroid, graph units. */
+ r: number;
+ count: number;
+}
+
+export interface OverviewBundle {
+ a: number;
+ b: number;
+ /** Structural file edges between the two communities, either direction. */
+ count: number;
+ /** sqrt(count / heaviest), 0..1: stroke width and opacity. */
+ weight: number;
+ /** Quadratic curve in graph coordinates: rim of `a`, control, rim of `b`.
+ * A Bezier survives the camera's scale-and-translate unchanged, so the
+ * per-frame work is three point transforms. */
+ x0: number;
+ y0: number;
+ cx: number;
+ cy: number;
+ x1: number;
+ y1: number;
+}
+
+export interface OverviewMeta {
+ clusters: OverviewCluster[];
+ bundles: OverviewBundle[];
+ /** Pairs the bands leave out (below the traffic floor), for the key. */
+ omittedPairs: number;
+}
+
+const META_KEY = "filesOverview";
+
+/** Read the overview meta a graph was laid out with, if any. */
+export function getOverviewMeta(graph: SigmaGraph | null | undefined): OverviewMeta | null {
+ if (!graph) return null;
+ return (graph.getAttribute(META_KEY as never) as OverviewMeta | undefined) ?? null;
+}
+
+/** A community needs this many drawn files to be a cluster, with a name and
+ * bands; a smaller one is seated beside the cluster it links to. */
+const CLUSTER_MIN = 8;
+/** Where a small community is seated, in multiples of its host's radius. */
+const STRAY_RIM = 1.15;
+/** Clusters are pushed apart by this factor about the origin, and each is
+ * opened up about its own centroid by `CLUSTER_OPEN`. Post-transform only:
+ * the golden-angle seed that places them (`buildFileGraph`) is unchanged,
+ * this rescales what it produced. Spreading opens room for bands and names
+ * between clusters; opening lowers the overlap inside them (the seed packs a
+ * community's files into a disc sized for density, not for reading), and
+ * keeps a cluster from reading as a dot in the space spreading made. */
+const CLUSTER_SPREAD = 1.3;
+const CLUSTER_OPEN = 1.35;
+/** Band floor: a pair needs at least this share of cross-community traffic. */
+const BUNDLE_MIN_SHARE = 0.015;
+const BUNDLE_MIN_COUNT = 3;
+const BUNDLE_MAX = 16;
+/** Labels at overview zoom: the global top N by degree, plus the top file of
+ * every community big enough to be read as a place. Collisions between them
+ * are resolved per frame by the label drawer (`use-sigma`). */
+const GLOBAL_LABELS = 6;
+const COMMUNITY_LABEL_MIN = 15;
+
+/** A filename that says nothing alone gets its folder. */
+const GENERIC_FILE =
+ /^(index\.[a-z]+|__init__\.py|__main__\.py|mod\.rs|lib\.rs|main\.[a-z]+|models?\.py|types?\.ts|utils?\.[a-z]+|constants\.[a-z]+|page\.tsx|layout\.tsx|route\.ts|app\.[a-z]+|base\.[a-z]+|common\.[a-z]+|helpers?\.[a-z]+|schemas?\.py|config\.[a-z]+|cli\.py|api\.[a-z]+)$/i;
+
+export function overviewFileLabel(path: string): string {
+ const parts = path.split("/");
+ const last = parts[parts.length - 1] ?? path;
+ return GENERIC_FILE.test(last) && parts.length >= 2 ? parts.slice(-2).join("/") : last;
+}
+
+function hash(s: string): number {
+ let h = 5381;
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0;
+ return Math.abs(h);
+}
+
+/**
+ * Lay a freshly built whole-repo file graph out for the overview and record
+ * what the canvas layers need. Mutates positions and labels in place, once:
+ * a second call returns the stored meta (React may run a memo twice).
+ */
+export function layoutFilesOverview(graph: SigmaGraph): OverviewMeta {
+ const existing = getOverviewMeta(graph);
+ if (existing) return existing;
+
+ // Degree over the dependency edges the overview reveals.
+ const degree = new Map<string, number>();
+ graph.forEachEdge((_e, attrs, s, t) => {
+ if (attrs.edgeKind !== "internal" && attrs.edgeKind !== "crossCommunity") return;
+ degree.set(s, (degree.get(s) ?? 0) + 1);
+ degree.set(t, (degree.get(t) ?? 0) + 1);
+ });
+
+ const members = new Map<number, string[]>();
+ graph.forEachNode((node, a) => {
+ const list = members.get(a.communityId);
+ if (list) list.push(node);
+ else members.set(a.communityId, [node]);
+ });
+ const centroid = (ids: string[]) => {
+ let x = 0;
+ let y = 0;
+ for (const id of ids) {
+ x += graph.getNodeAttribute(id, "x");
+ y += graph.getNodeAttribute(id, "y");
+ }
+ return { x: x / ids.length, y: y / ids.length };
+ };
+ const bigIds = [...members.keys()].filter((id) => members.get(id)!.length >= CLUSTER_MIN);
+ const big = new Set(bigIds);
+
+ // Spacing first, so everything below measures the final positions.
+ for (const id of bigIds) {
+ const ids = members.get(id)!;
+ const c = centroid(ids);
+ for (const node of ids) {
+ const a = graph.getNodeAttributes(node);
+ graph.mergeNodeAttributes(node, {
+ x: c.x * CLUSTER_SPREAD + (a.x - c.x) * CLUSTER_OPEN,
+ y: c.y * CLUSTER_SPREAD + (a.y - c.y) * CLUSTER_OPEN,
+ });
+ }
+ }
+
+ const clusters: OverviewCluster[] = [];
+ const clusterOf = new Map<number, OverviewCluster>();
+ for (const id of bigIds) {
+ const ids = members.get(id)!;
+ const c = centroid(ids);
+ const d = ids
+ .map((n) => {
+ const a = graph.getNodeAttributes(n);
+ return Math.hypot(a.x - c.x, a.y - c.y);
+ })
+ .sort((p, q) => p - q);
+ const cluster: OverviewCluster = {
+ communityId: id,
+ cx: c.x,
+ cy: c.y,
+ r: Math.max(d[Math.floor(d.length * 0.85)] ?? 0, 12),
+ count: ids.length,
+ };
+ clusters.push(cluster);
+ clusterOf.set(id, cluster);
+ }
+ clusters.sort((p, q) => q.count - p.count || p.communityId - q.communityId);
+
+ // Small communities sit on the far golden-angle ring, nowhere near what
+ // they touch, and a speck out there also sets the extent the camera frames.
+ // Seat each, as a group, just outside the rim of the cluster its files link
+ // to most. Placement only: membership and colour stay their own. Files whose
+ // group links to no cluster follow the first neighbour that found a seat.
+ const seated = new Set<string>();
+ const unseated: string[] = [];
+ for (const [cid, ids] of members) {
+ if (big.has(cid)) continue;
+ const pull = new Map<number, number>();
+ for (const node of ids) {
+ graph.forEachNeighbor(node, (_n, na) => {
+ if (big.has(na.communityId)) pull.set(na.communityId, (pull.get(na.communityId) ?? 0) + 1);
+ });
+ }
+ let best: number | null = null;
+ let bestN = 0;
+ for (const [c, n] of pull) {
+ if (n > bestN || (n === bestN && best !== null && c < best)) {
+ best = c;
+ bestN = n;
+ }
+ }
+ if (best === null) {
+ unseated.push(...ids);
+ continue;
+ }
+ const host = clusterOf.get(best)!;
+ const g = centroid(ids);
+ let spread = 0;
+ for (const node of ids) {
+ const a = graph.getNodeAttributes(node);
+ spread = Math.max(spread, Math.hypot(a.x - g.x, a.y - g.y));
+ }
+ const radius = host.r * STRAY_RIM + spread;
+ const angle = ((hash(`community:${cid}`) % 1000) / 1000) * Math.PI * 2;
+ const dx = host.cx + radius * Math.cos(angle) - g.x;
+ const dy = host.cy + radius * Math.sin(angle) - g.y;
+ for (const node of ids) {
+ const a = graph.getNodeAttributes(node);
+ graph.mergeNodeAttributes(node, { x: a.x + dx, y: a.y + dy });
+ seated.add(node);
+ }
+ }
+ for (const node of unseated) {
+ const anchor = graph.findNeighbor(node, (n) => seated.has(n));
+ if (!anchor) continue;
+ const a = graph.getNodeAttributes(anchor);
+ const angle = ((hash(node) % 1000) / 1000) * Math.PI * 2;
+ const step = 8 + a.size * 2;
+ graph.mergeNodeAttributes(node, { x: a.x + step * Math.cos(angle), y: a.y + step * Math.sin(angle) });
+ seated.add(node);
+ }
+
+ // Bands: one per unordered community pair, counted over structural edges.
+ const pairs = new Map<string, { a: number; b: number; count: number }>();
+ graph.forEachEdge((_e, attrs, _s, _t, sa, ta) => {
+ if (attrs.edgeKind !== "crossCommunity") return;
+ const ca = sa.communityId;
+ const cb = ta.communityId;
+ if (ca === cb || !big.has(ca) || !big.has(cb)) return;
+ const [lo, hi] = ca < cb ? [ca, cb] : [cb, ca];
+ const key = `${lo}:${hi}`;
+ const p = pairs.get(key);
+ if (p) p.count++;
+ else pairs.set(key, { a: lo, b: hi, count: 1 });
+ });
+ const ranked = [...pairs.values()].sort((p, q) => q.count - p.count || p.a - q.a || p.b - q.b);
+ const total = ranked.reduce((s, p) => s + p.count, 0);
+ const heaviest = ranked[0]?.count ?? 1;
+ const kept = ranked
+ .filter((p) => p.count >= Math.max(BUNDLE_MIN_COUNT, total * BUNDLE_MIN_SHARE))
+ .slice(0, BUNDLE_MAX);
+ const bundles = kept.map((p) =>
+ routeBundle(clusterOf.get(p.a)!, clusterOf.get(p.b)!, clusters, p.count, heaviest),
+ );
+
+ // Labels: every file gets its short name; only the ranked ones are forced
+ // at overview zoom, the rest appear as the reader zooms in.
+ const forced = new Set<string>();
+ const byDegree = [...degree.entries()].sort((p, q) => q[1] - p[1] || (p[0] < q[0] ? -1 : 1));
+ for (const [n] of byDegree.slice(0, GLOBAL_LABELS)) forced.add(n);
+ for (const cluster of clusters) {
+ if (cluster.count < COMMUNITY_LABEL_MIN) continue;
+ let top: string | null = null;
+ for (const n of members.get(cluster.communityId)!) {
+ if (top === null || (degree.get(n) ?? 0) > (degree.get(top) ?? 0)) top = n;
+ }
+ if (top) forced.add(top);
+ }
+ graph.updateEachNodeAttributes(
+ (node, a) => ({ ...a, label: overviewFileLabel(a.fullPath || node), forceLabel: forced.has(node) }),
+ { attributes: ["label", "forceLabel"] },
+ );
+
+ // No arrowheads at rest: direction is shown on the focused file's own
+ // edges, where it can be read. A curve program without the arrow is also
+ // the cheaper of the two.
+ graph.updateEachEdgeAttributes(
+ (_e, a) => (a.type === "curvedArrow" ? { ...a, type: "curved" } : a.type === "arrow" ? { ...a, type: "line" } : a),
+ { attributes: ["type"] },
+ );
+
+ const meta: OverviewMeta = { clusters, bundles, omittedPairs: ranked.length - kept.length };
+ graph.setAttribute(META_KEY as never, meta as never);
+ return meta;
+}
+
+/** Candidate bends, as a fraction of the chord, in order of preference. */
+const BENDS = [0.16, -0.16, 0.3, -0.3, 0.06, -0.06, 0.45, -0.45];
+
+/**
+ * Route one band. A straight chord between two clusters often crosses a third,
+ * which reads as a dependency on it. Try a few bends and keep the one whose
+ * curve passes through the fewest other clusters; ties keep the gentler bend.
+ * Eight candidates by twelve samples by the cluster count, once per layout.
+ */
+function routeBundle(
+ from: OverviewCluster,
+ to: OverviewCluster,
+ clusters: OverviewCluster[],
+ count: number,
+ heaviest: number,
+): OverviewBundle {
+ const dx = to.cx - from.cx;
+ const dy = to.cy - from.cy;
+ const len = Math.hypot(dx, dy) || 1;
+ const nx = -dy / len;
+ const ny = dx / len;
+ const mx = (from.cx + to.cx) / 2;
+ const my = (from.cy + to.cy) / 2;
+
+ let best = { cx: mx + nx * len * BENDS[0]!, cy: my + ny * len * BENDS[0]!, hits: Infinity };
+ for (const bend of BENDS) {
+ const cx = mx + nx * len * bend;
+ const cy = my + ny * len * bend;
+ let hits = 0;
+ for (let i = 2; i <= 10; i++) {
+ const t = i / 12;
+ const u = 1 - t;
+ const px = u * u * from.cx + 2 * u * t * cx + t * t * to.cx;
+ const py = u * u * from.cy + 2 * u * t * cy + t * t * to.cy;
+ for (const c of clusters) {
+ if (c === from || c === to) continue;
+ if (Math.hypot(px - c.cx, py - c.cy) < c.r) hits++;
+ }
+ }
+ if (hits < best.hits) best = { cx, cy, hits };
+ if (hits === 0) break;
+ }
+
+ // Leave each cluster at its rim, heading for the control point, so the band
+ // grows out of the cluster's edge instead of meeting its neighbours in the
+ // middle of it.
+ const rim = (c: OverviewCluster) => {
+ const ux = best.cx - c.cx;
+ const uy = best.cy - c.cy;
+ const ul = Math.hypot(ux, uy) || 1;
+ return { x: c.cx + (ux / ul) * c.r, y: c.cy + (uy / ul) * c.r };
+ };
+ const p0 = rim(from);
+ const p1 = rim(to);
+ return {
+ a: from.communityId,
+ b: to.communityId,
+ count,
+ weight: Math.sqrt(count / heaviest),
+ x0: p0.x,
+ y0: p0.y,
+ cx: best.cx,
+ cy: best.cy,
+ x1: p1.x,
+ y1: p1.y,
+ };
+}
diff --git a/packages/ui/src/graph/sigma/graphology-adapter.ts b/packages/ui/src/graph/sigma/graphology-adapter.ts
index 77832b9d4..514d9255e 100644
--- a/packages/ui/src/graph/sigma/graphology-adapter.ts
+++ b/packages/ui/src/graph/sigma/graphology-adapter.ts
@@ -40,13 +40,34 @@ function simpleHash(str: string): number {
return Math.abs(hash);
}
+/**
+ * True for an edge that says two files change together rather than that one
+ * depends on the other. The `"dynamic"` edge kind is this, keyed "Co-change".
+ *
+ * Read off `edge_type` when the payload carries it. On this repo's export
+ * 5,521 of the 5,655 edges with no imported names are `co_changes`; the other
+ * 134 (`framework`, `dynamic_uses`, name-less `imports`) are real dependencies
+ * that the old names-only rule filed under the same key. A payload without
+ * `edge_type` keeps that rule.
+ */
+export function isCoChangeLink(link: GraphLink): boolean {
+ if (link.edge_type !== undefined) return link.edge_type === "co_changes";
+ return link.imported_names.length === 0;
+}
+
+/** A dependency drawn by default: not co-change, not low confidence. */
+export function isStructuralLink(link: GraphLink): boolean {
+ if (link.confidence !== undefined && link.confidence < 0.5) return false;
+ return !isCoChangeLink(link);
+}
+
function classifyEdge(
link: GraphLink,
nodeMap: Map<string, GraphNode>,
): SigmaEdgeAttributes["edgeKind"] {
if (link.confidence !== undefined && link.confidence < 0.5)
return "lowConfidence";
- if (link.imported_names.length === 0) return "dynamic";
+ if (isCoChangeLink(link)) return "dynamic";
const sourceNode = nodeMap.get(link.source);
const targetNode = nodeMap.get(link.target);
if (
diff --git a/packages/ui/src/graph/sigma/overview-layers.ts b/packages/ui/src/graph/sigma/overview-layers.ts
new file mode 100644
index 000000000..b429b465e
--- /dev/null
+++ b/packages/ui/src/graph/sigma/overview-layers.ts
@@ -0,0 +1,363 @@
+/**
+ * Canvas layers for the Files overview, drawn inside Sigma's own layer stack
+ * so that anything compositing `sigma.getCanvases()` (the PNG export) gets
+ * them for free. A DOM SVG overlay would not be captured.
+ *
+ * Bottom to top, with Sigma's layers in brackets:
+ *
+ * overviewBands - one band per community pair, under the file edges
+ * [edges] [edgeLabels] [nodes] [labels]
+ * overviewFocus - community names; then, while a file is focused, a veil in
+ * the canvas colour and that file's own edges with direction
+ * [hovers] [hoverNodes] - the focused file and its neighbours, drawn by Sigma
+ * above the veil because the reducer marks them highlighted
+ *
+ * The veil is what makes focus cheap. Dimming the other ~1,300 nodes through
+ * the node reducer would re-reduce every node on every hover; painting one
+ * rectangle over them costs the same at any graph size, and the reducer only
+ * re-runs for the focused neighbourhood (see `use-sigma`).
+ *
+ * Per frame this draws at most 16 bands, the cluster labels, and the focused
+ * file's edges: no allocation beyond gradients, and no work at all when the
+ * layer has nothing to show.
+ */
+import type Sigma from "sigma";
+import type { CommunityFamily } from "../../shared/use-theme-tokens";
+import type { OverviewMeta } from "./files-overview";
+import { LABEL_FONT } from "./constants";
+
+export interface OverviewPalette {
+ /** The canvas plane, RGB. The veil and the label plates are this colour. */
+ bg: readonly [number, number, number];
+ text: string;
+ subtitle: string;
+ /** The focused file's own dependencies (it imports them). */
+ outgoing: string;
+ /** Files that depend on the focused file. */
+ incoming: string;
+ dark: boolean;
+}
+
+export interface OverviewFocus {
+ node: string;
+ /** Edges to draw, kept by the caller so the per-frame pass never filters. */
+ edges: { source: string; target: string; kind: string }[];
+}
+
+export interface OverviewLayerState {
+ meta: OverviewMeta;
+ family: (communityId: number) => CommunityFamily;
+ labelFor: (communityId: number) => string;
+ palette: OverviewPalette;
+ focus: OverviewFocus | null;
+ /** Bands stand for the cross-community edges, so that edge toggle owns them. */
+ showBands: boolean;
+ /** Communities the legend has switched off, or null for all on. */
+ activeCommunities: ReadonlySet<number> | null;
+}
+
+interface FocusStyle {
+ color: string;
+ dash: number[];
+ width: number;
+ lines: Path2D;
+ heads: Path2D | null;
+}
+
+const SOLID: number[] = [];
+const CO_CHANGE_DASH = [4, 3];
+const LOW_CONFIDENCE_DASH = [1.5, 2.5];
+/** Arrowhead length, px. */
+const ARROW = 7;
+
+/** A community this small is drawn but not named: its name would cover it. */
+const LABEL_MIN_MEMBERS = 8; // matches CLUSTER_MIN in files-overview.ts
+
+function sizeCanvas(sigma: Sigma, canvas: HTMLCanvasElement): CanvasRenderingContext2D | null {
+ const { width, height } = sigma.getDimensions();
+ const ratio = typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
+ const w = Math.round(width * ratio);
+ const h = Math.round(height * ratio);
+ if (canvas.width !== w) canvas.width = w;
+ if (canvas.height !== h) canvas.height = h;
+ canvas.style.width = `${width}px`;
+ canvas.style.height = `${height}px`;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return null;
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.clearRect(0, 0, width, height);
+ return ctx;
+}
+
+interface NamePlacement {
+ communityId: number;
+ name: string;
+ count: string;
+ countW: number;
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+/** Graph units → pixels. The camera is a similarity transform, so one factor
+ * serves every radius and every curve. */
+function pixelsPerUnit(sigma: Sigma, override?: CameraOverride): number {
+ const o = sigma.graphToViewport({ x: 0, y: 0 }, override);
+ const u = sigma.graphToViewport({ x: 100, y: 0 }, override);
+ return Math.hypot(u.x - o.x, u.y - o.y) / 100;
+}
+
+type CameraOverride = { cameraState: ReturnType<ReturnType<Sigma["getCamera"]>["getState"]> };
+
+/**
+ * Where each community's name goes this frame: above its cluster (below it
+ * when that would leave the canvas), largest first, a smaller cluster's name
+ * yielding to a larger one's.
+ */
+function placeNames(
+ sigma: Sigma,
+ ctx: CanvasRenderingContext2D,
+ state: OverviewLayerState,
+): NamePlacement[] {
+ const { width, height } = sigma.getDimensions();
+ // Placed on `beforeRender`, when Sigma still holds the previous frame's
+ // matrix: convert with the camera as it is now, or a camera jump leaves the
+ // names where the clusters were.
+ const override: CameraOverride = { cameraState: sigma.getCamera().getState() };
+ const scale = pixelsPerUnit(sigma, override);
+ if (!Number.isFinite(scale)) return [];
+ const active = state.activeCommunities;
+ const out: NamePlacement[] = [];
+ for (const c of state.meta.clusters) {
+ if (c.count < LABEL_MIN_MEMBERS || (active && !active.has(c.communityId))) continue;
+ const p = sigma.graphToViewport({ x: c.cx, y: c.cy }, override);
+ const r = c.r * scale;
+ const name = state.labelFor(c.communityId);
+ const count = String(c.count);
+ ctx.font = `600 12px ${LABEL_FONT}`;
+ const nameW = ctx.measureText(name).width;
+ ctx.font = `400 11px ${LABEL_FONT}`;
+ const countW = ctx.measureText(count).width;
+ // pad, swatch, gap, name, gap, count, pad
+ const w = 8 + 7 + 5 + nameW + 7 + countW + 8;
+ const h = 20;
+ let y = p.y - r - 14 - h / 2;
+ if (y < 4) y = p.y + r + 14 - h / 2;
+ const x = p.x - w / 2;
+ if (x + w < 0 || x > width || y + h < 0 || y > height) continue;
+ if (out.some((q) => x < q.x + q.w && x + w > q.x && y < q.y + q.h && y + h > q.y)) continue;
+ out.push({ communityId: c.communityId, name, count, countW, x, y, w, h });
+ }
+ return out;
+}
+
+/**
+ * Attach the two layers to a Sigma instance. Returns the detach function.
+ * `getState` is read once per frame; returning null leaves both layers blank.
+ * `reserve` is handed each community name's rectangle before Sigma draws its
+ * file labels, so a file label never lands under a community name.
+ */
+export function attachOverviewLayers(
+ sigma: Sigma,
+ getState: () => OverviewLayerState | null,
+ reserve?: (x: number, y: number, w: number, h: number) => void,
+): () => void {
+ const bands = sigma.createCanvas("overviewBands", { beforeLayer: "edges" });
+ const focus = sigma.createCanvas("overviewFocus", { beforeLayer: "hovers" });
+ for (const c of [bands, focus]) {
+ c.style.position = "absolute";
+ c.style.inset = "0";
+ c.style.pointerEvents = "none";
+ }
+
+ // Names are placed on `beforeRender`, where they can reserve their space
+ // ahead of the file labels, and drawn on `afterRender` from the same result.
+ let names: NamePlacement[] | null = null;
+ const place = () => {
+ // Sigma sizes itself inside `render`, after this event; a canvas that just
+ // changed size would otherwise place the names against the old one. A
+ // no-op when nothing changed.
+ sigma.resize();
+ const state = getState();
+ const ctx = focus.getContext("2d");
+ names = state && ctx ? placeNames(sigma, ctx, state) : null;
+ if (names && reserve) for (const n of names) reserve(n.x, n.y, n.w, n.h);
+ };
+
+ // Whether the layers hold pixels. A graph without overview meta (the
+ // Communities view, a drilled-in community) then costs nothing per frame
+ // after the one clear that leaving the overview needs.
+ let dirty = false;
+ const draw = () => {
+ const state = getState();
+ if (!state && !dirty) return;
+ const bctx = sizeCanvas(sigma, bands);
+ const fctx = sizeCanvas(sigma, focus);
+ dirty = !!state;
+ if (!state || !bctx || !fctx) return;
+ const { meta, palette } = state;
+ const { width, height } = sigma.getDimensions();
+ const ratio = sigma.getCamera().ratio;
+ // Sigma's zero-length camera animation (the reduced-motion path) renders
+ // one frame with a NaN camera. Nothing drawn from it could be right, and
+ // `createLinearGradient` throws on it.
+ if (!Number.isFinite(ratio) || !Number.isFinite(pixelsPerUnit(sigma))) {
+ names = null;
+ return;
+ }
+ const active = state.activeCommunities;
+ const on = (cid: number) => !active || active.has(cid);
+
+ // ---- Bands ----
+ if (state.showBands) {
+ // Width tracks zoom gently: bands must not fatten into blobs close up
+ // or vanish into hairlines far out.
+ const zoomWidth = Math.min(2.2, Math.max(0.7, 1 / Math.sqrt(ratio)));
+ bctx.lineCap = "round";
+ for (const b of meta.bundles) {
+ if (!on(b.a) || !on(b.b)) continue;
+ const p0 = sigma.graphToViewport({ x: b.x0, y: b.y0 });
+ const pc = sigma.graphToViewport({ x: b.cx, y: b.cy });
+ const p1 = sigma.graphToViewport({ x: b.x1, y: b.y1 });
+ const grad = bctx.createLinearGradient(p0.x, p0.y, p1.x, p1.y);
+ grad.addColorStop(0, state.family(b.a).hub);
+ grad.addColorStop(1, state.family(b.b).hub);
+ bctx.globalAlpha = (palette.dark ? 0.42 : 0.3) + (palette.dark ? 0.45 : 0.4) * b.weight;
+ bctx.strokeStyle = grad;
+ bctx.lineWidth = (1.5 + 14 * b.weight) * zoomWidth;
+ bctx.beginPath();
+ bctx.moveTo(p0.x, p0.y);
+ bctx.quadraticCurveTo(pc.x, pc.y, p1.x, p1.y);
+ bctx.stroke();
+ }
+ bctx.globalAlpha = 1;
+ }
+
+ // ---- Community names, above each cluster ----
+ const [br, bg, bb] = palette.bg;
+ const plate = `rgba(${br},${bg},${bb},0.86)`;
+ fctx.textBaseline = "middle";
+ fctx.textAlign = "left";
+ for (const n of names ?? placeNames(sigma, fctx, state)) {
+ fctx.fillStyle = plate;
+ fctx.beginPath();
+ fctx.roundRect(n.x, n.y, n.w, n.h, 5);
+ fctx.fill();
+ fctx.fillStyle = state.family(n.communityId).hub;
+ fctx.beginPath();
+ fctx.arc(n.x + 8 + 3.5, n.y + n.h / 2, 3.5, 0, Math.PI * 2);
+ fctx.fill();
+ fctx.fillStyle = palette.text;
+ fctx.font = `600 12px ${LABEL_FONT}`;
+ fctx.fillText(n.name, n.x + 8 + 7 + 5, n.y + n.h / 2);
+ fctx.fillStyle = palette.subtitle;
+ fctx.font = `400 11px ${LABEL_FONT}`;
+ fctx.fillText(n.count, n.x + n.w - 8 - n.countW, n.y + n.h / 2);
+ }
+ names = null;
+
+ // ---- Focus: veil, then the focused file's own edges ----
+ const f = state.focus;
+ if (!f) return;
+ // While the camera moves Sigma skips its hover layers (`hideLabelsOnMove`)
+ // but still fires `afterRender`, so a veil drawn now would cover the
+ // focused file and its neighbours until the camera settles. Same test
+ // Sigma uses to decide it is moving.
+ const captor = sigma.getMouseCaptor();
+ if (
+ sigma.getCamera().isAnimated() ||
+ captor.isMoving ||
+ captor.draggedEvents > 0 ||
+ captor.currentWheelDirection !== 0
+ ) {
+ return;
+ }
+ fctx.fillStyle = `rgba(${br},${bg},${bb},${palette.dark ? 0.76 : 0.72})`;
+ fctx.fillRect(0, 0, width, height);
+
+ // One path per stroke style, stroked once, and one path of arrowheads per
+ // colour, filled once: a hub file's few hundred edges are a handful of
+ // draw calls rather than two per edge. Drawn incoming first, so the
+ // file's own dependencies (the accent) sit on top.
+ const styles: FocusStyle[] = [
+ { color: palette.subtitle, dash: CO_CHANGE_DASH, width: 1.1, lines: new Path2D(), heads: null },
+ { color: palette.incoming, dash: LOW_CONFIDENCE_DASH, width: 1.6, lines: new Path2D(), heads: null },
+ { color: palette.incoming, dash: SOLID, width: 1.6, lines: new Path2D(), heads: new Path2D() },
+ { color: palette.outgoing, dash: LOW_CONFIDENCE_DASH, width: 1.6, lines: new Path2D(), heads: null },
+ { color: palette.outgoing, dash: SOLID, width: 1.6, lines: new Path2D(), heads: new Path2D() },
+ ];
+ const [coChangeStyle, inDotted, inSolid, outDotted, outSolid] = styles as [
+ FocusStyle, FocusStyle, FocusStyle, FocusStyle, FocusStyle,
+ ];
+ for (const e of f.edges) {
+ const s = sigma.getNodeDisplayData(e.source);
+ const t = sigma.getNodeDisplayData(e.target);
+ if (!s || !t || s.hidden || t.hidden) continue;
+ const a = sigma.framedGraphToViewport(s);
+ const b = sigma.framedGraphToViewport(t);
+ const dx = b.x - a.x;
+ const dy = b.y - a.y;
+ const len = Math.hypot(dx, dy);
+ if (len < 1) continue;
+ // A gentle bend, always to the same side of the travel direction, so an
+ // import and its reverse do not draw on top of each other.
+ const cx = (a.x + b.x) / 2 - dy * 0.12;
+ const cy = (a.y + b.y) / 2 + dx * 0.12;
+ // End at the target's rim, where the arrowhead goes.
+ const tx = b.x - cx;
+ const ty = b.y - cy;
+ const tl = Math.hypot(tx, ty) || 1;
+ const ux = tx / tl;
+ const uy = ty / tl;
+ const rim = sigma.scaleSize(t.size) + 1.5;
+ const ex = b.x - ux * rim;
+ const ey = b.y - uy * rim;
+
+ const outgoing = e.source === f.node;
+ const style =
+ e.kind === "dynamic"
+ ? coChangeStyle
+ : e.kind === "lowConfidence"
+ ? outgoing ? outDotted : inDotted
+ : outgoing ? outSolid : inSolid;
+ style.lines.moveTo(a.x, a.y);
+ style.lines.quadraticCurveTo(cx, cy, ex, ey);
+ // Co-change has no direction, so it gets no arrowhead; a dotted
+ // low-confidence edge borrows its colour's solid head.
+ const heads = e.kind === "dynamic" ? null : (outgoing ? outSolid : inSolid).heads;
+ if (heads) {
+ heads.moveTo(ex, ey);
+ heads.lineTo(ex - ux * ARROW - uy * ARROW * 0.5, ey - uy * ARROW + ux * ARROW * 0.5);
+ heads.lineTo(ex - ux * ARROW + uy * ARROW * 0.5, ey - uy * ARROW - ux * ARROW * 0.5);
+ heads.closePath();
+ }
+ }
+ for (const style of styles) {
+ fctx.strokeStyle = style.color;
+ fctx.lineWidth = style.width;
+ fctx.setLineDash(style.dash);
+ fctx.stroke(style.lines);
+ if (style.heads) {
+ fctx.fillStyle = style.color;
+ fctx.fill(style.heads);
+ }
+ }
+ fctx.setLineDash(SOLID);
+ };
+
+ sigma.on("beforeRender", place);
+ sigma.on("afterRender", draw);
+ draw();
+ return () => {
+ sigma.off("beforeRender", place);
+ sigma.off("afterRender", draw);
+ try {
+ sigma.killLayer("overviewBands");
+ sigma.killLayer("overviewFocus");
+ } catch {
+ // Sigma was already killed, and took its layers with it.
+ }
+ };
+}
+
diff --git a/packages/ui/src/graph/sigma/sigma-canvas.tsx b/packages/ui/src/graph/sigma/sigma-canvas.tsx
index 66481cf54..5e204da76 100644
--- a/packages/ui/src/graph/sigma/sigma-canvas.tsx
+++ b/packages/ui/src/graph/sigma/sigma-canvas.tsx
@@ -62,6 +62,10 @@ export interface SigmaCanvasProps {
/** Suppress the camera easings. Honour `prefers-reduced-motion` here rather
* than reading the media query inside the renderer. */
reducedMotion?: boolean | undefined;
+ /** Community names, drawn over each cluster in the Files overview. */
+ communityLabels?: Map<number, string> | undefined;
+ /** Communities the key has switched on (null/undefined = all). */
+ activeCommunities?: Set<number> | null | undefined;
}
export interface SigmaCanvasHandle {
@@ -99,6 +103,8 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(
hiddenNodes: props.hiddenNodes,
visibleEdgeTypes: props.visibleEdgeTypes,
reducedMotion: props.reducedMotion,
+ communityLabels: props.communityLabels,
+ activeCommunities: props.activeCommunities,
});
const { isRunning: isLayoutRunning } = useFA2Layout({
diff --git a/packages/ui/src/graph/sigma/types.ts b/packages/ui/src/graph/sigma/types.ts
index 4741c50fc..8d5edbc38 100644
--- a/packages/ui/src/graph/sigma/types.ts
+++ b/packages/ui/src/graph/sigma/types.ts
@@ -102,6 +102,9 @@ export interface SigmaEdgeAttributes {
// Original data
importedNames: string[];
edgeCount: number;
+ /** sqrt(edgeCount / heaviest edge), 0..1, on aggregated community edges:
+ * the colour pass reads it for opacity, as the adapter did for width. */
+ weight?: number | undefined;
confidence?: number | undefined;
// Interaction state
diff --git a/packages/ui/src/graph/sigma/use-sigma.ts b/packages/ui/src/graph/sigma/use-sigma.ts
index 169d07d35..09bcc314a 100644
--- a/packages/ui/src/graph/sigma/use-sigma.ts
+++ b/packages/ui/src/graph/sigma/use-sigma.ts
@@ -15,8 +15,11 @@ import {
type EdgeKind,
languageColor,
} from "./constants";
-import { resolveToken, useCommunityFamilies, useThemeVersion } from "../../shared/use-theme-tokens";
-import { UNCLUSTERED_COMMUNITY_ID } from "./constellation-adapter";
+import { resolveToken, useThemeVersion } from "../../shared/use-theme-tokens";
+import { useGraphCommunityFamilies } from "../community-colors";
+import { CORE_NODE_ID, UNCLUSTERED_COMMUNITY_ID } from "./constellation-adapter";
+import { getOverviewMeta, type OverviewMeta } from "./files-overview";
+import { attachOverviewLayers, type OverviewFocus } from "./overview-layers";
// ---- Color helpers (kept minimal — avoid regex in hot paths) ----
@@ -99,13 +102,70 @@ function discInkFor(fill: string): string {
}
/**
- * Hub/core disc-label drawer. Hub/core labels render centered *inside* the disc
- * (ROBOTICS-style) with a soft halo ring in the family hue; everything else
- * falls through to Sigma's stock side-label drawer.
+ * A label on a plate of the canvas colour, so it reads over clusters, bands
+ * and edges without a halo. Ink is the primary text token: over a plate of
+ * the plane at 0.85 it clears AA in both themes (the plane is the one colour
+ * the text tokens are tuned against).
+ */
+function drawPlatedLabel(
+ context: CanvasRenderingContext2D,
+ label: string,
+ x: number,
+ y: number,
+ align: "left" | "center",
+ font: string,
+ avoidOverlap = false,
+): void {
+ context.font = font;
+ const w = context.measureText(label).width;
+ const left = align === "center" ? x - w / 2 : x;
+ if (avoidOverlap && !reserveLabel(left - 4, y - 9, w + 8, 18)) return;
+ context.fillStyle = `rgba(${activeBg[0]},${activeBg[1]},${activeBg[2]},0.85)`;
+ context.beginPath();
+ context.roundRect(left - 4, y - 9, w + 8, 18, 4);
+ context.fill();
+ context.fillStyle = activeText;
+ context.textAlign = "left";
+ context.textBaseline = "middle";
+ context.fillText(label, left, y);
+}
+
+/**
+ * Plates placed so far this frame, flat `[x, y, w, h, ...]`. Sigma's label
+ * grid keeps its own picks apart, but a `forceLabel` bypasses the grid, and
+ * the overview forces the best-connected file of each community, which often
+ * sit side by side. First come keeps its place. Cleared on `beforeRender`.
+ */
+const placedLabels: number[] = [];
+
+function reserveLabel(x: number, y: number, w: number, h: number): boolean {
+ for (let i = 0; i < placedLabels.length; i += 4) {
+ if (
+ x < placedLabels[i]! + placedLabels[i + 2]! &&
+ x + w > placedLabels[i]! &&
+ y < placedLabels[i + 1]! + placedLabels[i + 3]! &&
+ y + h > placedLabels[i + 1]!
+ ) {
+ return false;
+ }
+ }
+ placedLabels.push(x, y, w, h);
+ return true;
+}
+
+/**
+ * Node label drawer.
*
- * Takes no palette: every colour it paints comes off the node itself (the halo
- * from `haloColor`, the ink from `labelInk`), both resolved by the colour pass.
- * That is what lets it survive a theme flip without being rebuilt.
+ * - File labels sit beside the disc on a plate.
+ * - Community hubs carry their member count inside the disc and their name
+ * outside it, in full. The name used to be fitted *inside* by shrinking the
+ * font until it fit, so a long label came out at 7px uppercase.
+ * - The repo core keeps its name inside its disc.
+ *
+ * Takes no palette: the halo and ink come off the node (`haloColor`,
+ * `labelInk`, resolved by the colour pass) and the plate and text from the
+ * module-level plane, which the theme pass re-points. That is what lets it
+ * survive a theme flip without being rebuilt.
*/
function makeDrawNodeLabel(
drawDisc: typeof drawDiscNodeLabel,
@@ -113,6 +173,12 @@ function makeDrawNodeLabel(
return (context, data, settings) => {
const extra = data as unknown as Record<string, unknown>;
const kind = extra.nodeType as string | undefined;
+ const font = settings.labelFont || "JetBrains Mono, monospace";
+ if (kind === "file") {
+ if (!data.label) return;
+ drawPlatedLabel(context, data.label, data.x + data.size + 5, data.y, "left", `500 ${settings.labelSize || 11}px ${font}`, true);
+ return;
+ }
if (kind !== "hub" && kind !== "core") {
drawDisc(context, data, settings);
return;
@@ -131,11 +197,28 @@ function makeDrawNodeLabel(
context.stroke();
context.globalAlpha = 1;
+ if (kind === "hub") {
+ const count = extra.memberCount as number | undefined;
+ if (count != null) {
+ context.font = `600 ${Math.max(9, Math.min(13, size * 0.5))}px ${font}`;
+ context.textAlign = "center";
+ context.textBaseline = "middle";
+ // See the note on `labelInk` below: resolved from the base fill.
+ context.fillStyle = (extra.labelInk as string) || discInkFor(data.color);
+ context.fillText(String(count), data.x, data.y);
+ }
+ if (data.label) {
+ // Yields to a name already placed. Hubs arrive largest first, and on
+ // a phone-width canvas the discs crowd; the key names every one.
+ drawPlatedLabel(context, data.label, data.x, data.y + size + 16, "center", `600 12px ${font}`, true);
+ }
+ return;
+ }
+
const label = data.label;
if (!label) return;
- // Fit the uppercase label inside the disc; shrink for long names.
- const font = settings.labelFont || "JetBrains Mono, monospace";
+ // The repo core: fit its uppercase name inside the disc.
let fontSize = Math.max(9, Math.min(13, size * 0.55));
context.font = `600 ${fontSize}px ${font}`;
const maxWidth = size * 1.9;
@@ -162,7 +245,12 @@ function makeDrawNodeLabel(
* init effect alongside makeDrawNodeLabel so the theme effect can re-set it on
* light/dark toggle (the closure must NOT capture a stale palette).
*/
-function makeDrawNodeHover(theme: VizPalette): NodeLabelDrawingFunction {
+function makeDrawNodeHover(
+ theme: VizPalette,
+ focus: { readonly current: FocusState | null },
+ hovered: { readonly current: string | null },
+ sigmaRef: { readonly current: Sigma | null },
+): NodeLabelDrawingFunction {
return (context, data, settings) => {
const label = data.label;
if (!label) return;
@@ -170,6 +258,22 @@ function makeDrawNodeHover(theme: VizPalette): NodeLabelDrawingFunction {
const extra = data as Record<string, unknown>;
const fullPath = (extra.fullPath as string) ?? undefined;
+ // Sigma calls this for every highlighted node, and in the Files overview
+ // a focused file highlights its whole neighbourhood. Those get a name
+ // plate (only the best-connected few, so a hub file does not bury itself
+ // in text); the card is for the focused or pointed-at file alone.
+ const f = focus.current;
+ const key = (extra.key as string | undefined) ?? "";
+ if (f && key !== f.node && key !== hovered.current) {
+ const rank = f.labelled.get(key);
+ if (rank === undefined) return;
+ const font = `500 ${settings.labelSize || 11}px ${settings.labelFont || "JetBrains Mono, monospace"}`;
+ const sigma = sigmaRef.current;
+ if (sigma && neighbourLabelBlocked(context, sigma, f, key, rank, data, font)) return;
+ drawPlatedLabel(context, label, data.x + data.size + 5, data.y, "left", font);
+ return;
+ }
+
// Hub/module tooltip: a small surface card. First disclosure layer —
// headline stats only; the full detail lives in the inspection panel.
if (extra.nodeType === "hub" || extra.nodeType === "module") {
@@ -322,6 +426,12 @@ interface VizPalette {
text: string;
subtitle: string;
tooltip: string;
+ /** A focused file's own dependencies. The link/selection accent, which as a
+ * stroke clears 3:1 on the plane in both themes (the fill tone does not in
+ * light). */
+ outgoing: string;
+ /** Files that depend on the focused one: the plum second accent. */
+ incoming: string;
}
function resolveVizPalette(theme: "light" | "dark"): VizPalette {
@@ -352,6 +462,8 @@ function resolveVizPalette(theme: "light" | "dark"): VizPalette {
text: resolveToken("--color-text-primary", dark ? "#f2f2f3" : "#241b2c"),
subtitle: resolveToken("--color-text-secondary", dark ? "#b4b4b9" : "#5e5360"),
tooltip: resolveToken("--color-bg-surface", dark ? "#141416" : "#ffffff"),
+ outgoing: resolveToken("--color-accent-primary", dark ? "#f59520" : "#a16215"),
+ incoming: resolveToken("--color-accent-secondary", dark ? "#a98fc4" : "#58436c"),
};
}
@@ -359,6 +471,134 @@ function resolveVizPalette(theme: "light" | "dark"): VizPalette {
// so it cannot take the palette as an argument. Kept in sync by the theme
// effect, which also drops the color caches keyed to the previous plane.
let activeBg: readonly [number, number, number] = [14, 14, 15];
+// Label ink for the plated labels, re-pointed with the plane for the same
+// reason: the label drawer runs outside React and is built once.
+let activeText = "#f2f2f3";
+
+/**
+ * `#rrggbb` at `alpha`, premultiplied. Sigma's WebGL programs blend with
+ * ONE / ONE_MINUS_SRC_ALPHA and never premultiply, so a plain `rgba()` adds
+ * its full colour and washes toward white on a light canvas. `additive` zeroes
+ * the alpha so overlapping strokes add light, which reads as density on the
+ * dark plane and would blow out on the light one.
+ */
+function premultiplied(hex: string, alpha: number, additive = false): string {
+ const v = parseInt(hex.slice(1, 7), 16);
+ const [r, g, b] = Number.isFinite(v) ? [(v >> 16) & 255, (v >> 8) & 255, v & 255] : [128, 128, 128];
+ const k = (c: number) => Math.round(c * alpha);
+ return `rgba(${k(r)},${k(g)},${k(b)},${additive ? 0 : alpha})`;
+}
+
+/** A focused file in the Files overview and what it reveals. */
+interface FocusState extends OverviewFocus {
+ /** The file and every neighbour: drawn above the veil. */
+ nodes: Set<string>;
+ /** Neighbours that get a name plate, by rank (best-connected first). */
+ labelled: Map<string, number>;
+ /** Measured plate text widths, filled as labels are first drawn. */
+ widths: Map<string, number>;
+}
+
+function plateRect(
+ x: number,
+ y: number,
+ size: number,
+ width: number,
+): [number, number, number, number] {
+ return [x + size + 1, y - 9, width + 8, 18];
+}
+
+function overlaps(a: readonly number[], b: readonly number[]): boolean {
+ return a[0]! < b[0]! + b[2]! && a[0]! + a[2]! > b[0]! && a[1]! < b[1]! + b[3]! && a[1]! + a[3]! > b[1]!;
+}
+
+/**
+ * Whether a neighbour's name plate would land on a better-connected
+ * neighbour's plate or on the focused file's card. Decided by rank rather than
+ * by draw order: Sigma draws highlighted nodes in set order, and repaints this
+ * layer on its own when the pointer moves, so there is no pass to reset a
+ * "placed so far" list on. At most 24 plates, so the pairwise check is ~300
+ * rectangle tests per repaint.
+ */
+function neighbourLabelBlocked(
+ context: CanvasRenderingContext2D,
+ sigma: Sigma,
+ f: FocusState,
+ key: string,
+ rank: number,
+ data: { x: number; y: number; size: number; label?: string | null },
+ font: string,
+): boolean {
+ context.font = font;
+ const widthOf = (node: string, label: string) => {
+ let w = f.widths.get(node);
+ if (w === undefined) {
+ w = context.measureText(label).width;
+ f.widths.set(node, w);
+ }
+ return w;
+ };
+ const mine = plateRect(data.x, data.y, data.size, widthOf(key, data.label ?? ""));
+ const focusData = sigma.getNodeDisplayData(f.node);
+ if (focusData) {
+ // The card: centred above the node, as tall as its two lines.
+ const p = sigma.framedGraphToViewport(focusData);
+ const half = Math.max(90, widthOf(f.node, focusData.label ?? "") / 2 + 12);
+ const top = p.y - sigma.scaleSize(focusData.size) - 12 - 36;
+ if (overlaps(mine, [p.x - half, top, half * 2, 40])) return true;
+ }
+ for (const [other, otherRank] of f.labelled) {
+ if (otherRank >= rank) continue;
+ const d = sigma.getNodeDisplayData(other);
+ if (!d || d.hidden) continue;
+ const p = sigma.framedGraphToViewport(d);
+ if (overlaps(mine, plateRect(p.x, p.y, sigma.scaleSize(d.size), widthOf(other, d.label ?? "")))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/** Name plates on a focused neighbourhood, best-connected first. */
+const FOCUS_LABELS = 24;
+
+function computeFocus(
+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>,
+ node: string,
+ visibleKinds: Set<string> | undefined,
+): FocusState {
+ const nodes = new Set<string>([node]);
+ const edges: OverviewFocus["edges"] = [];
+ graph.forEachEdge(node, (_e, attrs, source, target) => {
+ if (visibleKinds && !visibleKinds.has(attrs.edgeKind)) return;
+ edges.push({ source, target, kind: attrs.edgeKind });
+ nodes.add(source === node ? target : source);
+ });
+ const neighbours = [...nodes].filter((n) => n !== node);
+ neighbours.sort((a, b) => graph.degree(b) - graph.degree(a) || (a < b ? -1 : 1));
+ const labelled = new Map<string, number>();
+ neighbours.slice(0, FOCUS_LABELS).forEach((n, i) => labelled.set(n, i));
+ return { node, edges, nodes, labelled, widths: new Map() };
+}
+
+/** Camera ratio below which the overview shows file-level detail (every file
+ * label the grid allows, and the edges inside each community), and above
+ * which it goes back. Two thresholds, so a zoom resting near the line does
+ * not flip the whole canvas back and forth. */
+const NEAR_BELOW = 0.55;
+const FAR_ABOVE = 0.65;
+/** Canvas width (px) under which overview zoom names communities only. */
+const NARROW_CANVAS = 600;
+
+/**
+ * Room Sigma leaves around the graph when it frames it. The default 30px was
+ * sized for bare discs; the Communities view hangs each name below its disc
+ * and the Files overview floats each community's name above its cluster, so
+ * both need more or the outermost names clip at the canvas edge.
+ */
+function stagePaddingFor(graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>): number {
+ return graph.hasNode(CORE_NODE_ID) || getOverviewMeta(graph) ? 64 : 30;
+}
const dimColorCache = new Map<string, string>();
const brightenColorCache = new Map<string, string>();
@@ -435,6 +675,12 @@ export interface UseSigmaOptions {
/** Suppress the camera easings this hook drives. Read live, so a change to
* the OS setting takes effect without a remount. */
reducedMotion?: boolean | undefined;
+ /** Community names for the Files overview's cluster labels. Read live. */
+ communityLabels?: Map<number, string> | undefined;
+ /** Communities the legend has switched on, or null/undefined for all. The
+ * overview's bands and names follow it; the nodes already do, through
+ * {@link communityDimmedNodes}. */
+ activeCommunities?: Set<number> | null | undefined;
}
/** A camera position in Sigma's *framed* coordinate space (what
@@ -483,7 +729,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
// pass below used to call the raw `getCommunityFamily` per node, which is two
// getComputedStyle reads each — ~3,000 synchronous style reads for a
// 1,500-node load, repeated on every colorMode toggle and theme flip.
- const communityFamilies = useCommunityFamilies();
+ const communityFamilies = useGraphCommunityFamilies();
// Mirror of `viz` readable from Sigma's reducers, which run outside React.
const vizRef = useRef<VizPalette>(viz);
@@ -498,6 +744,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
activeBg = viz.bg;
clearColorCaches();
}
+ activeText = viz.text;
const sigmaRef = useRef<Sigma | null>(null);
const [sigmaReady, setSigmaReady] = useState<Sigma | null>(null);
@@ -513,6 +760,58 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
SigmaEdgeAttributes
> | null>(null);
+ // ---- Files overview (see files-overview.ts / overview-layers.ts) ----
+ // All of it lives in refs: hover must reach the canvas without a React
+ // render, and the reducers and layers run outside React anyway.
+ const overviewRef = useRef<OverviewMeta | null>(null);
+ const hoveredRef = useRef<string | null>(null);
+ const focusRef = useRef<FocusState | null>(null);
+ /** "near" once the camera is close enough for file-level detail. */
+ const bucketRef = useRef<"far" | "near">("far");
+ /** A phone-width canvas: the community names fill it, so at overview zoom
+ * the ranked file names are left out. Updated on Sigma's resize. */
+ const narrowRef = useRef(false);
+ const visibleEdgeTypesRef = useRef(options.visibleEdgeTypes);
+ visibleEdgeTypesRef.current = options.visibleEdgeTypes;
+ const communityLabelsRef = useRef(options.communityLabels);
+ communityLabelsRef.current = options.communityLabels;
+ const activeCommunitiesRef = useRef(options.activeCommunities ?? null);
+ activeCommunitiesRef.current = options.activeCommunities ?? null;
+ const familiesRef = useRef(communityFamilies);
+ familiesRef.current = communityFamilies;
+
+ /**
+ * Recompute which file is focused (the selection, else the hovered file)
+ * and repaint only what changed. The reducer marks the neighbourhood
+ * highlighted, which is what lifts it above the overview's veil, so a hover
+ * re-reduces the old and new neighbourhoods and nothing else: O(degree),
+ * not O(graph). `partial: false` leaves the repaint to a caller about to do
+ * a full refresh anyway.
+ */
+ const applyFocusRef = useRef((partial: boolean) => {
+ const graph = graphRef.current;
+ const next =
+ overviewRef.current && highlightedPathRef.current.size === 0
+ ? (selectedRef.current ?? hoveredRef.current)
+ : null;
+ const prev = focusRef.current;
+ if (partial && (prev?.node ?? null) === next) return;
+ focusRef.current =
+ next && graph?.hasNode(next) ? computeFocus(graph, next, visibleEdgeTypesRef.current) : null;
+ const sigma = sigmaRef.current;
+ if (!partial || !sigma) return;
+ const changed = new Set<string>(prev?.nodes);
+ for (const n of focusRef.current?.nodes ?? []) changed.add(n);
+ // Scheduled: a pointer moving from one file straight onto another fires
+ // leave and enter in the same event, and that should cost one frame.
+ try {
+ sigma.refresh({ partialGraph: { nodes: [...changed] }, skipIndexation: true, schedule: true });
+ } catch {
+ // A node not yet indexed (a graph swap is mid-flight): repaint it all.
+ sigma.scheduleRefresh();
+ }
+ });
+
// Sync interaction state refs (no color work here — that's in the graph effect)
useEffect(() => {
selectedRef.current = options.selectedNodeId;
@@ -522,6 +821,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
communityDimmedRef.current = options.communityDimmedNodes;
expandDimmedRef.current = options.expandDimmedNodes ?? null;
hiddenNodesRef.current = options.hiddenNodes;
+ applyFocusRef.current(false);
sigmaRef.current?.refresh();
}, [
options.selectedNodeId,
@@ -546,6 +846,8 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
},
{ attributes: ["hidden"] },
);
+ // The focused file's revealed edges follow the same toggles.
+ applyFocusRef.current(false);
}, [options.visibleEdgeTypes, options.graph]);
// Pre-apply node colors on the graphology graph (batch: 1 event instead of N)
@@ -621,19 +923,37 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
// Re-color edges by semantic kind for the active theme (canvas can't resolve
// var()). Build-time colors are placeholders; this is the source of truth.
+ //
+ // Two readings colour by community instead of by kind, because there the
+ // kind is already known and the community is the information:
+ // - the Communities view's aggregated edges (they carry `weight`): the
+ // larger community's hue, opacity by weight;
+ // - the Files overview's within-community edges: the community's own hue,
+ // faint, so a cluster reads as one texture when zoomed in.
+ // Both premultiplied; see `premultiplied`.
useEffect(() => {
const graph = options.graph;
if (!graph || graph.size === 0) return;
const edge = viz.edge;
+ const overview = !!getOverviewMeta(graph);
+ const dark = options.graphTheme === "dark";
graph.updateEachEdgeAttributes(
- (_edgeKey, attrs) => {
- const color = edge[attrs.edgeKind] ?? edge.internal;
+ (_edgeKey, attrs, _s, _t, sa, ta) => {
+ let color: string;
+ if (attrs.weight !== undefined) {
+ const big = (sa.memberCount ?? 0) >= (ta.memberCount ?? 0) ? sa : ta;
+ color = premultiplied(communityFamilies(big.communityId).hub, 0.22 + 0.6 * attrs.weight);
+ } else if (overview && attrs.edgeKind === "internal") {
+ color = premultiplied(communityFamilies(sa.communityId).hub, dark ? 0.22 : 0.3, dark);
+ } else {
+ color = edge[attrs.edgeKind] ?? edge.internal;
+ }
if (attrs.color === color) return attrs;
return { ...attrs, color };
},
{ attributes: ["color"] },
);
- }, [options.graph, viz]);
+ }, [options.graph, viz, communityFamilies, options.graphTheme]);
// Theme flip: publish the new palette to the reducers, re-point the canvas
// plane that `dimColor` blends toward (dropping the color caches keyed to the
@@ -648,7 +968,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
// Only the hover drawer needs rebuilding: it paints the tooltip card from
// the palette. The disc-label drawer takes its colours off the node and is
// theme-independent, so it is built once at init.
- sigma.setSetting("defaultDrawNodeHover", makeDrawNodeHover(viz));
+ sigma.setSetting("defaultDrawNodeHover", makeDrawNodeHover(viz, focusRef, hoveredRef, sigmaRef));
sigma.refresh();
}, [viz]);
@@ -679,6 +999,10 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
const graph =
options.graph ?? new graphologyModule.default() as Graph<SigmaNodeAttributes, SigmaEdgeAttributes>;
graphRef.current = options.graph;
+ overviewRef.current = getOverviewMeta(options.graph);
+ // A selection can arrive (a `?node=` link) before this async init lands,
+ // when there was no overview to focus it in yet.
+ applyFocusRef.current(false);
const sigma = new SigmaConstructor(graph, container, {
renderLabels: true,
@@ -709,6 +1033,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
// above, which already does the same for the edge programs.
hideLabelsOnMove: true,
zIndex: true,
+ stagePadding: stagePaddingFor(graph),
// Hub/core disc labels + hover tooltips. The label drawer is
// theme-independent (it reads colours off the node) and is built once.
@@ -717,7 +1042,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
// here because this effect depends only on the container, which would
// otherwise leave its `viz` closure stale.
defaultDrawNodeLabel: makeDrawNodeLabel(drawDiscNodeLabel),
- defaultDrawNodeHover: makeDrawNodeHover(vizRef.current),
+ defaultDrawNodeHover: makeDrawNodeHover(vizRef.current, focusRef, hoveredRef, sigmaRef),
// --- nodeReducer: ONLY handles interaction state (selection, search, path) ---
// Colors and sizes are pre-set on the graphology graph by the effect above.
@@ -727,7 +1052,28 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
const hiddenSet = hiddenNodesRef.current;
if (hiddenSet?.has(node)) return { ...data, hidden: true };
- const selected = selectedRef.current;
+ // Files overview. The copy Sigma hands the reducer is its own
+ // (`addNode` shallow-copies the attributes first), so it is edited
+ // in place rather than spread: this runs for every node on a full
+ // refresh.
+ const overview = overviewRef.current !== null;
+ if (overview && data.nodeType === "file") {
+ const focus = focusRef.current;
+ if (focus?.nodes.has(node)) {
+ // Highlighted is what draws it above the veil (Sigma's hover
+ // layers); the dimming of everything else is the veil itself.
+ data.highlighted = true;
+ data.size = (data.size || 6) * (node === focus.node ? 1.7 : 1.2);
+ data.zIndex = 2;
+ } else if (bucketRef.current === "far" && (!data.forceLabel || narrowRef.current)) {
+ // Far out, only the ranked files are named.
+ data.label = "";
+ }
+ }
+
+ // In the overview the selection is drawn by the focus above, not by
+ // dimming every other node.
+ const selected = overview ? null : selectedRef.current;
const pathNodes = highlightedPathRef.current;
const searchDimmed = searchDimmedRef.current;
const communityDimmed = communityDimmedRef.current;
@@ -790,6 +1136,25 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
const pathEdges = highlightedEdgesRef.current;
const pathNodes = highlightedPathRef.current;
+ // Files overview: cross-community structure is the bands, and a
+ // focused file's own edges are drawn on the focus layer with their
+ // direction. What the WebGL layer keeps is the texture inside each
+ // community, once the camera is close enough to read it, and a
+ // traced path.
+ if (overviewRef.current) {
+ if (pathEdges.size > 0 && pathEdges.has(edge)) {
+ data.color = vizRef.current.pathHighlight;
+ data.size = 3;
+ data.zIndex = 2;
+ data.type = "arrow";
+ return data;
+ }
+ if (pathEdges.size > 0 || data.edgeKind !== "internal" || bucketRef.current === "far") {
+ data.hidden = true;
+ }
+ return data;
+ }
+
// Fast path: nothing active — zero allocation
if (!selected && pathEdges.size === 0) return data;
@@ -821,6 +1186,72 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
},
});
+ sigma.on("beforeRender", () => {
+ placedLabels.length = 0;
+ });
+ const measureNarrow = () => {
+ const narrow = sigma.getDimensions().width < NARROW_CANVAS;
+ if (narrow === narrowRef.current) return;
+ narrowRef.current = narrow;
+ if (overviewRef.current) sigma.refresh({ schedule: true });
+ };
+ measureNarrow();
+ sigma.on("resize", measureNarrow);
+
+ // Files overview: hover focuses a file, and the zoom bucket decides
+ // how much file-level detail is drawn. Neither touches React.
+ sigma.on("enterNode", ({ node }) => {
+ if (!overviewRef.current) return;
+ if (graphRef.current?.getNodeAttribute(node, "nodeType") !== "file") return;
+ hoveredRef.current = node;
+ applyFocusRef.current(true);
+ });
+ sigma.on("leaveNode", () => {
+ if (hoveredRef.current === null) return;
+ hoveredRef.current = null;
+ applyFocusRef.current(true);
+ });
+ sigma.getCamera().on("updated", (state) => {
+ // The zero-length (reduced-motion) animation reports one NaN frame.
+ if (!Number.isFinite(state.ratio)) return;
+ const current = bucketRef.current;
+ const bucket =
+ current === "far" ? (state.ratio < NEAR_BELOW ? "near" : "far")
+ : state.ratio > FAR_ABOVE ? "far" : "near";
+ if (bucket === current) return;
+ bucketRef.current = bucket;
+ // Crossing the line changes which labels and edges exist, once.
+ if (overviewRef.current) sigma.refresh({ schedule: true });
+ });
+
+ const detachLayers = attachOverviewLayers(sigma, () => {
+ const meta = overviewRef.current;
+ if (!meta) return null;
+ const v = vizRef.current;
+ const labels = communityLabelsRef.current;
+ const kinds = visibleEdgeTypesRef.current;
+ return {
+ meta,
+ family: familiesRef.current,
+ labelFor: (cid) => labels?.get(cid) ?? `Community ${cid}`,
+ palette: {
+ bg: v.bg,
+ text: v.text,
+ subtitle: v.subtitle,
+ outgoing: v.outgoing,
+ incoming: v.incoming,
+ dark: v.bg[0] + v.bg[1] + v.bg[2] < 384,
+ },
+ focus: focusRef.current,
+ showBands: !kinds || kinds.has("crossCommunity"),
+ activeCommunities: activeCommunitiesRef.current,
+ };
+ }, (x, y, w, h) => {
+ // Registered after the reset above, so this frame's names go in first.
+ placedLabels.push(x, y, w, h);
+ });
+ sigma.once("kill", detachLayers);
+
sigmaInstance = sigma;
sigmaRef.current = sigma;
setSigmaReady(sigma);
@@ -852,6 +1283,11 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {
const sigma = sigmaRef.current;
if (!sigma || !options.graph) return;
graphRef.current = options.graph;
+ overviewRef.current = getOverviewMeta(options.graph);
+ hoveredRef.current = null;
+ focusRef.current = null;
+ applyFocusRef.current(false);
+ sigma.setSetting("stagePadding", stagePaddingFor(options.graph));
sigma.setGraph(options.graph);
const camera = sigma.getCamera();
const entry = entryCameraRef.current;
diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsx
index 1cc5ba643..c80f0a5e3 100644
--- a/packages/web/src/app/repos/[id]/architecture/page.tsx
+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx
@@ -29,7 +29,8 @@
* - `?community=` the community the file scope is drilled into. One axis with
* `?module=`: both narrow the file graph, so at most one is ever set.
* - `?show=` which non-production files the community views count
- * (`tests,examples,docs`); absent means production only.
+ * (`tests,examples,docs`); absent means production only. `external` in
+ * the same list draws third-party modules in the Files view.
*
* `?view=` and `?viewMode=` used to encode the same axis twice — `view=explore`
* and `viewMode=full` both meant "the file graph", and they could disagree.
@@ -106,10 +107,17 @@ const TABS: { id: string; label: string }[] = [
{ id: "symbols", label: "Symbols" },
];
-/** Landing view when a tab is clicked. Map opens on communities — the whole
- * repo at a size you can read, rather than 1,500 circles. */
+/** Landing view when a tab is clicked, and for the page with no `?view=`.
+ *
+ * Map opens on Files. It used to open on Communities, because Files was 1,500
+ * circles with nothing to read them by. Files now draws each community as a
+ * named cluster with its bands and ranked file names, and a hover shows one
+ * file's real edges, so it answers "what is this repo made of" and "what does
+ * this file touch" on first paint. `?view=communities` still lands there.
+ */
+const DEFAULT_VIEW: CanonicalView = "files";
const DEFAULT_VIEW_FOR_TAB: Record<string, CanonicalView> = {
- map: "communities",
+ map: DEFAULT_VIEW,
coupling: "coupling",
packages: "packages",
symbols: "symbols",
@@ -124,7 +132,7 @@ export default function ArchitecturePage({
const router = useRouter();
const [rawView, setView] = useQueryState(
"view",
- parseAsStringLiteral(VIEWS).withDefault("communities"),
+ parseAsStringLiteral(VIEWS).withDefault(DEFAULT_VIEW),
);
const [viewModeParam, setViewModeParam] = useQueryState("viewMode");
const [, setSignal] = useQueryState("signal");
@@ -163,7 +171,7 @@ export default function ArchitecturePage({
// reads it and nothing shows it.
const handleTabChange = useCallback(
(id: string) => {
- void setView(DEFAULT_VIEW_FOR_TAB[id] ?? "communities");
+ void setView(DEFAULT_VIEW_FOR_TAB[id] ?? DEFAULT_VIEW);
// `?focus=` means a file path in Coupling and the literal "relationships"
// in Third-party, so carrying it across pins one tab's value in the
// other's vocabulary. Cleared on every change, not just when leaving.
diff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsx
index 73d20d5bf..40bf477f5 100644
--- a/packages/web/src/components/architecture/graph-view.tsx
+++ b/packages/web/src/components/architecture/graph-view.tsx
@@ -25,14 +25,22 @@ type Scope = "communities" | "files";
// falls through to the "community" default rather than erroring.
const VALID_COLOR_MODES = new Set<ColorMode>(["language", "community"]);
-/** `?show=tests,docs` ↔ the population flags. Absent or empty = production only. */
+/** `?show=tests,docs` ↔ the population flags. Absent or empty = production only.
+ * `external` rides in the same list: it is the same question ("which files
+ * that are not this repo's own code are drawn"), asked of the Files view. */
const POPULATION_KEYS = ["tests", "examples", "docs"] as const;
-function parsePopulation(raw: string | null): GraphPopulation {
+function parseShow(raw: string | null): GraphPopulation & { external: boolean } {
const on = new Set((raw ?? "").split(",").map((s) => s.trim()));
- return { tests: on.has("tests"), examples: on.has("examples"), docs: on.has("docs") };
+ return {
+ tests: on.has("tests"),
+ examples: on.has("examples"),
+ docs: on.has("docs"),
+ external: on.has("external"),
+ };
}
-function serializePopulation(p: GraphPopulation): string | null {
- const on = POPULATION_KEYS.filter((k) => p[k]);
+function serializeShow(p: GraphPopulation, external: boolean): string | null {
+ const on: string[] = POPULATION_KEYS.filter((k) => p[k]);
+ if (external) on.push("external");
return on.length ? on.join(",") : null;
}
@@ -73,15 +81,25 @@ export function GraphView({
// stepping out of the community — the breadcrumb and Escape are the way up.
const [communityParam, setCommunityParam] = useQueryState("community");
const [showParam, setShowParam] = useQueryState("show");
+ const show = useMemo(() => parseShow(showParam), [showParam]);
const population = useMemo<GraphPopulation>(
- () => (showParam ? parsePopulation(showParam) : PRODUCTION_ONLY),
- [showParam],
+ () =>
+ showParam
+ ? { tests: show.tests, examples: show.examples, docs: show.docs }
+ : PRODUCTION_ONLY,
+ [showParam, show],
);
const handlePopulationChange = useCallback(
(next: GraphPopulation) => {
- void setShowParam(serializePopulation(next));
+ void setShowParam(serializeShow(next, show.external));
},
- [setShowParam],
+ [setShowParam, show.external],
+ );
+ const handleShowExternalChange = useCallback(
+ (next: boolean) => {
+ void setShowParam(serializeShow(population, next));
+ },
+ [setShowParam, population],
);
const [docNodeId, setDocNodeId] = useState<string | null>(null);
const [graphLimit, setGraphLimit] = useState<number | undefined>(undefined);
@@ -273,7 +291,7 @@ export function GraphView({
description={
isCommunities
? "Files that depend on each other more than on the rest of the repo, detected automatically. Circle size is how much code a group holds, and the nearer the centre, the nearer an entry point. Double-click a group to see the files inside it and what they depend on."
- : "Every file and how it depends on the others. Pick two files to trace a path between them."
+ : "Every file, grouped into the communities it depends on most, with a band for each strong link between communities. Hover or select a file to see exactly what it imports and what imports it."
}
headerActions={headerControls}
banner={
@@ -305,6 +323,8 @@ export function GraphView({
onActiveCommunityChange={handleActiveCommunityChange}
population={population}
onPopulationChange={handlePopulationChange}
+ showExternal={show.external}
+ onShowExternalChange={handleShowExternalChange}
// Same value the banner reports, so the caption and the canvas can
// never disagree about how many files are drawn.
graphLimit={graphLimit}
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
index cd931e454..b75f580f6 100644
--- a/packages/web/src/components/graph/graph-flow.tsx
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -45,6 +45,9 @@ export interface GraphFlowProps {
* via `?show=`. */
population?: GraphPopulation | undefined;
onPopulationChange?: ((next: GraphPopulation) => void) | undefined;
+ /** Third-party nodes in the Files view. The page owns it via `?show=`. */
+ showExternal?: GraphFlowShellProps["showExternal"];
+ onShowExternalChange?: GraphFlowShellProps["onShowExternalChange"];
/** Node cap for the full-graph fetch, stepped up by the truncation banner.
* Must be the SAME value the banner is reporting: this and the banner's own
* fetch share an SWR key, so a mismatch means the caption describes a
@@ -87,6 +90,8 @@ export function GraphFlow({
onActiveCommunityChange,
population,
onPopulationChange,
+ showExternal,
+ onShowExternalChange,
graphLimit,
onModuleGroupsChange,
initialColorMode,
@@ -166,6 +171,8 @@ export function GraphFlow({
onActiveCommunityChange={onActiveCommunityChange}
population={population}
onPopulationChange={onPopulationChange}
+ showExternal={showExternal}
+ onShowExternalChange={onShowExternalChange}
{...(resolvedRepoName ? { repoName: resolvedRepoName } : {})}
deadCodeGraph={deadGraph as GraphExport | undefined}
isLoadingDeadCodeGraph={deadLoading}