Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ui): system map search, shortcuts and list view (#4623)
Raghav Chamadiya0c0d027bd2e9
diff --git a/packages/ui/__tests__/workspace/system-map-navigation.test.tsx b/packages/ui/__tests__/workspace/system-map-navigation.test.tsxnew file mode 100644index 000000000..fbdce3934--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-navigation.test.tsx@@ -0,0 +1,408 @@+import { describe, it, expect, vi, beforeAll } from "vitest";+import { render, screen, fireEvent, act, within } from "@testing-library/react";+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";+import { SystemMap } from "../../src/workspace/system-map/system-map";+import { buildSearchIndex, pickToView, routeHits, searchMap, type SystemMapRouteLink } from "../../src/workspace/system-map/search-index";+import { shortcutFor } from "../../src/workspace/system-map/shortcuts";+import { nextSort, serviceRows, sortServiceRows } from "../../src/workspace/system-map/service-rows";+import { levelAnnouncement } from "../../src/workspace/system-map/announce";+import { buildLevelView } from "../../src/workspace/system-map/levels";+import { DEFAULT_NAV_COPY } from "../../src/workspace/system-map/nav-copy";+import { ESTATE_VIEW, parseMapView, sameMapView, toLevelViewState, writeMapView, type MapViewState } from "../../src/workspace/system-map/view-state";++beforeAll(() => {+ class RO {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ vi.stubGlobal("ResizeObserver", RO);+});++function node(id: string, over: Partial<SystemNode> = {}): SystemNode {+ return {+ id,+ repo: id.split("::")[0] ?? id,+ service_path: null,+ name: id,+ kind: "service",+ provider_count: 0,+ consumer_count: 0,+ contract_types: [],+ is_orphan_provider: false,+ is_orphan_consumer: false,+ is_isolated: false,+ ...over,+ };+}++function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {+ return {+ id: `${source}->${target}`,+ source,+ target,+ kind: "http",+ match_type: "exact",+ confidence: 1,+ weight: 1,+ structural: true,+ contract_refs: [],+ ...over,+ };+}++const grouped: SystemGraph = {+ version: 1,+ generated_at: "2026-10-24T00:00:00Z",+ nodes: [+ node("webapp", { group: "tag:storefront", provider_count: 1, consumer_count: 4 }),+ node("mobile", { group: "tag:storefront" }),+ node("ordering.api", { group: "tag:ordering", provider_count: 6 }),+ node("ordering.worker", { group: "tag:ordering" }),+ node("shared.lib"),+ ],+ edges: [+ edge("webapp", "ordering.api", { weight: 2 }),+ edge("mobile", "ordering.api", { kind: "event" }),+ edge("ordering.worker", "ordering.api", { kind: "event" }),+ edge("ordering.api", "shared.lib", { id: "pkg", kind: "package", weight: 5 }),+ ],+ groups: [+ { id: "tag:storefront", label: "Storefront", source: "tag", member_count: 2 },+ { id: "tag:ordering", label: "Ordering", source: "tag", member_count: 2 },+ ],+};++const flat: SystemGraph = { ...grouped, nodes: grouped.nodes.map(({ group: _g, ...n }) => n), groups: [] };++describe("search ranking", () => {+ const index = buildSearchIndex(grouped);++ it("ranks the closest service name first, services before groups, and needs two characters", () => {+ const hits = searchMap(index, "ordering");+ expect(hits[0]).toMatchObject({ kind: "service", id: "ordering.api" });+ expect(hits.map((h) => h.kind)).toEqual(["service", "service", "group"]);+ expect(hits.at(-1)).toMatchObject({ kind: "group", id: "tag:ordering", label: "Ordering" });+ expect(searchMap(index, "o")).toEqual([]);+ expect(searchMap(index, " ")).toEqual([]);+ });++ it("finds a group by its label and a service by a typo", () => {+ expect(searchMap(index, "storefront")[0]).toMatchObject({ kind: "group", id: "tag:storefront" });+ expect(searchMap(index, "webap")[0]).toMatchObject({ kind: "service", id: "webapp" });+ });++ it("caps each section", () => {+ const many = { nodes: Array.from({ length: 20 }, (_, i) => node(`svc-${i}`)), groups: [] };+ expect(searchMap(buildSearchIndex(many), "svc", 4)).toHaveLength(4);+ });+});++describe("route hits", () => {+ const link = (contract_id: string, provider_repo: string, consumer_repo: string): SystemMapRouteLink => ({+ contract_id,+ contract_type: "http",+ provider_repo,+ provider_file: "a.cs",+ consumer_repo,+ consumer_file: "b.cs",+ });+ const resolve = buildSearchIndex(grouped).resolve;++ it("groups links per route and provider, names the top caller, and orders by links", () => {+ const hits = routeHits(+ [+ link("GET /orders", "ordering.api", "webapp"),+ link("GET /orders", "ordering.api", "webapp"),+ link("GET /orders", "ordering.api", "mobile"),+ link("GET /status", "ordering.api", "mobile"),+ ],+ resolve,+ );+ expect(hits).toEqual([+ expect.objectContaining({ kind: "route", label: "GET /orders", provider: "ordering.api", consumer: "webapp", otherConsumers: 1 }),+ expect.objectContaining({ label: "GET /status", consumer: "mobile", otherConsumers: 0 }),+ ]);+ });++ it("drops a caller in the provider's own service and a provider not on the map", () => {+ const hits = routeHits([link("GET /self", "ordering.api", "ordering.api"), link("GET /gone", "elsewhere", "webapp")], resolve);+ expect(hits).toEqual([expect.objectContaining({ label: "GET /self", consumer: null })]);+ });+});++describe("a pick is a level change", () => {+ it("focuses a service, opens a group, and compares a route's caller with its provider", () => {+ const from: MapViewState = { ...ESTATE_VIEW, between: { a: "x", b: "y" } };+ expect(pickToView(from, { kind: "service", id: "webapp", label: "webapp", detail: "" })).toMatchObject({ focus: "webapp", between: null });+ expect(pickToView({ ...ESTATE_VIEW, focus: "webapp" }, { kind: "group", id: "tag:ordering", label: "Ordering", detail: "" })).toMatchObject({+ open: ["tag:ordering"],+ focus: null,+ });+ const route = { kind: "route" as const, id: "r", label: "GET /orders", contractType: "http", provider: "ordering.api", otherConsumers: 0 };+ expect(pickToView(ESTATE_VIEW, { ...route, consumer: "webapp" }).between).toEqual({ a: "webapp", b: "ordering.api" });+ expect(pickToView(ESTATE_VIEW, { ...route, consumer: null })).toMatchObject({ focus: "ordering.api", between: null });+ });+});++describe("search on the map", () => {+ it("steps through results with the arrows and focuses the picked service", async () => {+ const onViewChange = vi.fn();+ render(<SystemMap graph={grouped} view={ESTATE_VIEW} onViewChange={onViewChange} />);+ const box = screen.getByRole("combobox", { name: /search services, groups and routes/i });+ fireEvent.change(box, { target: { value: "ordering" } });+ const first = await screen.findByRole("option", { name: /ordering\.api/ });+ expect(first).toHaveAttribute("aria-selected", "true");+ fireEvent.keyDown(box, { key: "ArrowDown" });+ expect(screen.getByRole("option", { name: /ordering\.worker/ })).toHaveAttribute("aria-selected", "true");+ fireEvent.keyDown(box, { key: "ArrowUp" });+ fireEvent.keyDown(box, { key: "Enter" });+ expect(onViewChange).toHaveBeenLastCalledWith({ ...ESTATE_VIEW, focus: "ordering.api", between: null });+ expect(box).toHaveValue("");+ });++ it("lists routes from the loader and compares a picked route's caller and provider", async () => {+ const onViewChange = vi.fn();+ const loadRoutes = vi.fn(async () => [+ { contract_id: "GET /orders", contract_type: "http", provider_repo: "ordering.api", provider_file: "a", consumer_repo: "webapp", consumer_file: "b" },+ ]);+ render(<SystemMap graph={grouped} view={ESTATE_VIEW} onViewChange={onViewChange} loadRoutes={loadRoutes} />);+ fireEvent.change(screen.getByRole("combobox"), { target: { value: "orders" } });+ const option = await screen.findByRole("option", { name: /GET \/orders/ });+ expect(within(option).getByText("webapp calls it")).toBeInTheDocument();+ expect(loadRoutes).toHaveBeenCalledWith("orders");+ fireEvent.click(option);+ expect(onViewChange).toHaveBeenLastCalledWith(expect.objectContaining({ between: { a: "webapp", b: "ordering.api" } }));+ });+});++describe("a route pick and the routes panel", () => {+ it("opens Between for the route's caller and provider with the routes panel filtered to the route", async () => {+ const load = vi.fn(async () => [+ { contract_id: "GET /orders", contract_type: "http", provider_repo: "ordering.api", provider_file: "a", consumer_repo: "webapp", consumer_file: "b" },+ ]);+ const loadLinksBetween = vi.fn(async (a: string, b: string) => ({ a, b, links: [], total: 0, totals: [] }));+ let view: MapViewState = ESTATE_VIEW;+ const onViewChange = (next: MapViewState) => {+ view = next;+ };+ const { rerender } = render(+ <SystemMap graph={flat} view={view} onViewChange={onViewChange} loadRoutes={load} loadLinksBetween={loadLinksBetween} />,+ );+ fireEvent.change(screen.getByRole("combobox"), { target: { value: "orders" } });+ fireEvent.click(await screen.findByRole("option", { name: /GET \/orders/ }));+ expect(view.between).toEqual({ a: "webapp", b: "ordering.api" });+ rerender(<SystemMap graph={flat} view={view} onViewChange={onViewChange} loadRoutes={load} loadLinksBetween={loadLinksBetween} />);+ expect(await screen.findByRole("searchbox", { name: "Filter routes" })).toHaveValue("GET /orders");+ });+});++describe("shortcut keys", () => {+ it("maps each key, and leaves typing and handled keys alone", () => {+ expect(shortcutFor({ key: "/" })).toBe("search");+ expect(shortcutFor({ key: "k", ctrlKey: true })).toBe("search");+ expect(shortcutFor({ key: "k", metaKey: true })).toBe("search");+ expect(shortcutFor({ key: "Escape" })).toBe("back");+ expect(shortcutFor({ key: "f" })).toBe("focus");+ expect(shortcutFor({ key: "b" })).toBe("between");+ expect(shortcutFor({ key: "l" })).toBe("list");+ expect(shortcutFor({ key: "?" })).toBe("help");+ expect(shortcutFor({ key: "x" })).toBeNull();+ expect(shortcutFor({ key: "f", ctrlKey: true })).toBeNull();+ expect(shortcutFor({ key: "f", altKey: true })).toBeNull();+ expect(shortcutFor({ key: "Escape", defaultPrevented: true })).toBeNull();+ expect(shortcutFor({ key: "f", target: document.createElement("input") })).toBeNull();+ // Ctrl+K reaches the map from any field; nothing reaches it from inside a dialog.+ expect(shortcutFor({ key: "k", ctrlKey: true, target: document.createElement("input") })).toBe("search");+ const dialog = document.createElement("div");+ dialog.setAttribute("role", "dialog");+ const inside = dialog.appendChild(document.createElement("button"));+ expect(shortcutFor({ key: "Escape", target: inside })).toBeNull();+ });+});++describe("shortcuts on the map", () => {+ const press = (key: string, init: KeyboardEventInit = {}) =>+ act(() => {+ window.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));+ });++ it("/ and Ctrl+K move to the search box", () => {+ render(<SystemMap graph={grouped} />);+ const box = screen.getByRole("combobox");+ press("/");+ expect(document.activeElement).toBe(box);+ box.blur();+ press("k", { ctrlKey: true });+ expect(document.activeElement).toBe(box);+ });++ it("f focuses the selected service", () => {+ const onViewChange = vi.fn();+ render(<SystemMap graph={flat} view={ESTATE_VIEW} onViewChange={onViewChange} selection={{ type: "node", id: "webapp" }} onSelectionChange={() => {}} />);+ press("f");+ expect(onViewChange).toHaveBeenLastCalledWith({ ...ESTATE_VIEW, focus: "webapp", between: null });+ });++ it("f does nothing without a selected service", () => {+ const onViewChange = vi.fn();+ render(<SystemMap graph={flat} view={ESTATE_VIEW} onViewChange={onViewChange} />);+ press("f");+ expect(onViewChange).not.toHaveBeenCalled();+ });++ it("b opens the Between picker from the selected service and says so; Escape drops the pick, then the picker", () => {+ const onSelectionChange = vi.fn();+ render(<SystemMap graph={flat} selection={{ type: "node", id: "webapp" }} onSelectionChange={onSelectionChange} />);+ press("b");+ expect(screen.getByRole("status")).toHaveTextContent("Pick a second service to compare with webapp");+ expect(screen.getByPlaceholderText("From service...")).toHaveValue("webapp");+ press("Escape");+ expect(screen.getByRole("status")).not.toHaveTextContent("Pick a second service");+ expect(screen.getByPlaceholderText("From service...")).toBeInTheDocument();+ press("Escape");+ expect(screen.queryByPlaceholderText("From service...")).toBeNull();+ expect(onSelectionChange).not.toHaveBeenCalled();+ press("Escape");+ expect(onSelectionChange).toHaveBeenLastCalledWith(null);+ });++ it("l shows the list; Escape steps back out of a level on the map but not in the list", () => {+ const onViewChange = vi.fn();+ const focused = { ...ESTATE_VIEW, focus: "webapp" };+ const { rerender } = render(<SystemMap graph={flat} view={focused} onViewChange={onViewChange} />);+ press("Escape");+ expect(onViewChange).toHaveBeenLastCalledWith({ ...ESTATE_VIEW });+ press("l");+ expect(onViewChange).toHaveBeenLastCalledWith({ ...focused, display: "list" });+ onViewChange.mockClear();+ rerender(<SystemMap graph={flat} view={{ ...focused, display: "list" }} onViewChange={onViewChange} />);+ press("Escape");+ expect(onViewChange).not.toHaveBeenCalled();+ press("l");+ expect(onViewChange).toHaveBeenLastCalledWith({ ...focused, display: "map" });+ });++ it("? opens the shortcut help, and Escape closes it before anything else", () => {+ const onViewChange = vi.fn();+ render(<SystemMap graph={flat} view={{ ...ESTATE_VIEW, focus: "webapp" }} onViewChange={onViewChange} />);+ press("?");+ const dialog = screen.getByRole("dialog", { name: "System map keyboard shortcuts" });+ expect(within(dialog).getByText("Focus the selected service")).toBeInTheDocument();+ press("Escape");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(onViewChange).not.toHaveBeenCalled();+ });+});++describe("between pick", () => {+ it("completes on the second service picked in the list, and opens the map", () => {+ const onViewChange = vi.fn();+ const onSelectionChange = vi.fn();+ const view = { ...ESTATE_VIEW, display: "list" as const };+ render(+ <SystemMap graph={flat} view={view} onViewChange={onViewChange} selection={{ type: "node", id: "webapp" }} onSelectionChange={onSelectionChange} />,+ );+ act(() => {+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "b" }));+ });+ fireEvent.click(within(screen.getByRole("table")).getByText("ordering.api").closest("tr")!);+ expect(onViewChange).toHaveBeenLastCalledWith({ ...view, display: "map", between: { a: "webapp", b: "ordering.api" } });+ expect(onSelectionChange).toHaveBeenLastCalledWith(null);+ });+});++describe("services list", () => {+ it("counts runtime links only, joins health and group, and keeps the contract counts", () => {+ const rows = serviceRows(grouped, new Map([["webapp", { score: 72 }]]));+ const web = rows.find((r) => r.id === "webapp")!;+ expect(web).toMatchObject({ group: "Storefront", health: 7.2, runtimeOut: 2, runtimeIn: 0, provided: 1, consumed: 4 });+ // The package edge is Build, not Runtime.+ expect(rows.find((r) => r.id === "ordering.api")).toMatchObject({ runtimeIn: 4, runtimeOut: 0 });+ expect(rows.find((r) => r.id === "shared.lib")).toMatchObject({ group: null, health: null, runtimeIn: 0 });+ });++ it("sorts by each column, puts missing values last either way, and ties on the name", () => {+ const rows = serviceRows(grouped, new Map([["webapp", { score: 72 }], ["mobile", { score: 41 }]]));+ const ids = (key: Parameters<typeof nextSort>[1], order: "asc" | "desc") => sortServiceRows(rows, { key, order }).map((r) => r.id);+ expect(ids("name", "asc")).toEqual(["mobile", "ordering.api", "ordering.worker", "shared.lib", "webapp"]);+ expect(ids("in", "desc")[0]).toBe("ordering.api");+ expect(ids("health", "desc").slice(0, 2)).toEqual(["webapp", "mobile"]);+ expect(ids("health", "asc").slice(0, 2)).toEqual(["mobile", "webapp"]);+ expect(ids("group", "asc").at(-1)).toBe("shared.lib");+ expect(ids("contracts", "desc")[0]).toBe("ordering.api");+ expect(ids("out", "desc")[0]).toBe("webapp");+ });++ it("flips the same column and starts figures largest first", () => {+ expect(nextSort({ key: "name", order: "asc" }, "name")).toEqual({ key: "name", order: "desc" });+ expect(nextSort({ key: "name", order: "asc" }, "in")).toEqual({ key: "in", order: "desc" });+ expect(nextSort({ key: "in", order: "desc" }, "group")).toEqual({ key: "group", order: "asc" });+ });++ it("toggles from the map to a sortable table and back, and a row selects its service", () => {+ const onViewChange = vi.fn();+ const onSelectionChange = vi.fn();+ const { rerender } = render(<SystemMap graph={grouped} view={ESTATE_VIEW} onViewChange={onViewChange} onSelectionChange={onSelectionChange} />);+ fireEvent.click(screen.getByRole("radio", { name: "List" }));+ expect(onViewChange).toHaveBeenLastCalledWith({ ...ESTATE_VIEW, display: "list" });++ rerender(<SystemMap graph={grouped} view={{ ...ESTATE_VIEW, display: "list" }} onViewChange={onViewChange} onSelectionChange={onSelectionChange} />);+ const table = screen.getByRole("table");+ const firstCell = () => within(table).getAllByRole("row")[1]!;+ expect(firstCell()).toHaveTextContent("mobile");+ fireEvent.click(within(table).getByRole("button", { name: /Runtime in/ }));+ expect(firstCell()).toHaveTextContent("ordering.api");+ fireEvent.click(firstCell());+ expect(onSelectionChange).toHaveBeenLastCalledWith({ type: "node", id: "ordering.api" });++ fireEvent.click(screen.getByRole("radio", { name: "Map" }));+ expect(onViewChange).toHaveBeenLastCalledWith({ ...ESTATE_VIEW, display: "map" });+ });+});++describe("Map | List in the URL", () => {+ it("reads and writes view=list, and leaves it out by default", () => {+ const p = new URLSearchParams("view=list&focus=webapp");+ const state = parseMapView((k) => p.get(k));+ expect(state.display).toBe("list");+ expect(parseMapView((k) => (k === "view" ? "grid" : null))).toEqual(ESTATE_VIEW);+ const out = new URLSearchParams();+ writeMapView(out, state);+ expect(out.toString()).toBe("focus=webapp&view=list");+ writeMapView(out, ESTATE_VIEW);+ expect(out.toString()).toBe("");+ expect(sameMapView(state, { ...state, display: "map" })).toBe(false);+ });+});++describe("level announcements", () => {+ const announce = (view: MapViewState, extra: Partial<Parameters<typeof levelAnnouncement>[0]> = {}) =>+ levelAnnouncement({+ levelView: buildLevelView(grouped, toLevelViewState(view)),+ view,+ display: "map",+ services: grouped.nodes.length,+ pendingFrom: null,+ name: (id) => id,+ groupLabel: (id) => grouped.groups!.find((g) => g.id === id)?.label ?? id,+ copy: DEFAULT_NAV_COPY,+ ...extra,+ });++ it("names each level in one sentence", () => {+ expect(announce({ ...ESTATE_VIEW, open: ["tag:ordering"] })).toBe("Ordering opened: 2 services");+ expect(announce({ ...ESTATE_VIEW, focus: "ordering.api" })).toBe("Focused on ordering.api: 3 callers, 0 dependencies");+ expect(announce({ ...ESTATE_VIEW, between: { a: "webapp", b: "ordering.api" } })).toBe("Showing the links between webapp and ordering.api");+ expect(announce(ESTATE_VIEW, { display: "list" })).toBe("List view: 5 services");+ expect(announce(ESTATE_VIEW, { pendingFrom: "webapp" })).toBe("Pick a second service to compare with webapp");+ });++ it("is said by the map's live region when the level changes", async () => {+ const { rerender } = render(<SystemMap graph={grouped} view={ESTATE_VIEW} onViewChange={() => {}} />);+ const live = screen.getByRole("status");+ expect(live).toHaveAttribute("aria-live", "polite");+ rerender(<SystemMap graph={grouped} view={{ ...ESTATE_VIEW, open: ["tag:storefront"] }} onViewChange={() => {}} />);+ expect(live).toHaveTextContent("Storefront opened: 2 services");+ });+});diff --git a/packages/ui/src/graph/graph-shortcut-help.tsx b/packages/ui/src/graph/graph-shortcut-help.tsxindex ef48e0221..c3c7da72c 100644--- a/packages/ui/src/graph/graph-shortcut-help.tsx+++ b/packages/ui/src/graph/graph-shortcut-help.tsx@@ -2,7 +2,17 @@import { X } from "lucide-react";-const SHORTCUTS: { keys: string[]; action: string }[] = [+export interface ShortcutRow {+ keys: string[];+ action: string;+}++export interface GestureRow {+ gesture: string;+ action: string;+}++const SHORTCUTS: ShortcutRow[] = [{ keys: ["f"], action: "Fit graph to view" },{ keys: ["/"], action: "Focus search" },{ keys: ["⌘K"], action: "Focus search" },@@ -14,25 +24,43 @@ const SHORTCUTS: { keys: string[]; action: string }[] = [{ keys: ["?"], action: "Toggle this help" },];-const GESTURES: { gesture: string; action: string }[] = [+const GESTURES: GestureRow[] = [{ gesture: "Click", action: "Select + inspect a node" },{ gesture: "Double-click", action: "Drill deeper (expand module / blossom hub / open doc)" },{ gesture: "Right-click", action: "Context menu (docs, explore, path from/to)" },];+export interface GraphShortcutHelpProps {+ onClose: () => void;+ /** Another surface's keys; the Architecture graph's by default. */+ shortcuts?: ShortcutRow[];+ /** Pointer gestures; an empty list drops the Mouse section. */+ gestures?: GestureRow[];+ /** The dialog's accessible name. */+ label?: string;+ /** The visible heading. */+ title?: string;+}+/** Keyboard + gesture cheatsheet, toggled with `?`. */-export function GraphShortcutHelp({ onClose }: { onClose: () => void }) {+export function GraphShortcutHelp({+ onClose,+ shortcuts = SHORTCUTS,+ gestures = GESTURES,+ label = "Graph keyboard shortcuts",+ title = "Keyboard shortcuts",+}: GraphShortcutHelpProps) {return (<div className="absolute inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/40 p-4" onClick={onClose}><divclassName="w-full max-w-sm rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 shadow-xl shadow-black/30"onClick={(e) => e.stopPropagation()}role="dialog"- aria-label="Graph keyboard shortcuts"+ aria-label={label}><div className="mb-3 flex items-center justify-between"><h3 className="text-sm font-semibold text-[var(--color-text-primary)]">- Keyboard shortcuts+ {title}</h3><buttononClick={onClose}@@ -43,7 +71,7 @@ export function GraphShortcutHelp({ onClose }: { onClose: () => void }) {</button></div><div className="space-y-1.5">- {SHORTCUTS.map((s) => (+ {shortcuts.map((s) => (<div key={s.keys.join("+") + s.action} className="flex items-center justify-between gap-3 text-xs"><span className="text-[var(--color-text-secondary)]">{s.action}</span><span className="flex shrink-0 gap-1">@@ -59,17 +87,21 @@ export function GraphShortcutHelp({ onClose }: { onClose: () => void }) {</div>))}</div>- <p className="mb-1.5 mt-3 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">- Mouse- </p>- <div className="space-y-1.5">- {GESTURES.map((g) => (- <div key={g.gesture} className="flex items-start justify-between gap-3 text-xs">- <span className="shrink-0 text-[var(--color-text-primary)]">{g.gesture}</span>- <span className="text-right text-[var(--color-text-secondary)]">{g.action}</span>+ {gestures.length > 0 && (+ <>+ <p className="mb-1.5 mt-3 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Mouse+ </p>+ <div className="space-y-1.5">+ {gestures.map((g) => (+ <div key={g.gesture} className="flex items-start justify-between gap-3 text-xs">+ <span className="shrink-0 text-[var(--color-text-primary)]">{g.gesture}</span>+ <span className="text-right text-[var(--color-text-secondary)]">{g.action}</span>+ </div>+ ))}</div>- ))}- </div>+ </>+ )}</div></div>);diff --git a/packages/ui/src/workspace/system-map/announce.ts b/packages/ui/src/workspace/system-map/announce.tsnew file mode 100644index 000000000..0c2b6a3af--- /dev/null+++ b/packages/ui/src/workspace/system-map/announce.ts@@ -0,0 +1,57 @@+/**+ * The sentence the map's live region says when the reader changes level:+ * "Ordering opened: 5 services", "Focused on ordering.api: 3 callers, 2+ * dependencies". It changes only when the level does, so a screen reader+ * hears each move once. Pure, no React.+ */++import type { LevelView } from "./levels";+import type { SystemMapNavCopy } from "./nav-copy";+import type { MapViewState } from "./view-state";+import { TRAY_OPEN_TOKEN } from "./view-state";++export interface AnnounceArgs {+ levelView: LevelView | null;+ view: MapViewState;+ /** The display the reader sees (the view's, or the phone default). */+ display: "map" | "list";+ services: number;+ /** Service picked with `b`, waiting for the second. */+ pendingFrom: string | null;+ name: (serviceId: string) => string;+ groupLabel: (groupId: string) => string;+ copy: SystemMapNavCopy;+}++function columnSize(view: LevelView, id: string): number {+ const col = view.focus?.columns.find((c) => c.id === id);+ return col ? col.entries.length + col.folded.length : 0;+}++/** The open container's sentence: the last opened group (or the tray) and its size. */+function groupSentence(v: LevelView, last: string, a: AnnounceArgs): string {+ const container = v.nodes.find((n) =>+ last === TRAY_OPEN_TOKEN ? n.type === "tray" : n.type === "group" && n.groupId === last,+ );+ const size = container && "serviceIds" in container ? container.serviceIds.length : 0;+ return a.copy.announceGroup(a.groupLabel(last), size);+}++/** The sentence for the level drawn. */+function levelSentence(v: LevelView, a: AnnounceArgs): string {+ const { view, copy } = a;+ if (v.level === "between" && view.between) return copy.announceBetween(a.name(view.between.a), a.name(view.between.b));+ if (v.level === "focus" && v.focus) {+ return copy.announceFocus(a.name(v.focus.focus), columnSize(v, "callers"), columnSize(v, "dependencies"));+ }+ const last = view.open[view.open.length - 1];+ if (v.level === "group" && last) return groupSentence(v, last, a);+ const groups = v.grouped ? v.nodes.filter((n) => n.type === "group").length : 0;+ return copy.announceEstate(a.services, groups);+}++export function levelAnnouncement(a: AnnounceArgs): string {+ if (a.pendingFrom) return a.copy.announcePick(a.name(a.pendingFrom));+ if (a.display === "list") return a.copy.announceList(a.services);+ return a.levelView ? levelSentence(a.levelView, a) : "";+}diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex a83f1cae4..c34e8da94 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -32,8 +32,41 @@ export {backOut,toEstate,sameMapView,+ focusService,+ compareServices,+ withDisplay,type MapViewState,+ type MapDisplay,} from "./view-state";+export { SystemMapSearch, type SystemMapSearchProps } from "./system-map-search";+export { useSystemMapSearch, type MapSearch } from "./use-system-map-search";+export {+ buildSearchIndex,+ searchMap,+ routeHits,+ pickToView,+ SEARCH_LIMIT,+ SEARCH_MIN_CHARS,+ type SearchHit,+ type MapSearchIndex,+ type SystemMapRouteLink,+ type SystemMapRouteLoader,+} from "./search-index";+export { shortcutFor, shortcutHelpRows, type MapShortcut, type ShortcutKey } from "./shortcuts";+export { useMapNavigation, type MapNavigation } from "./use-map-navigation";+export { SystemMapList, type SystemMapListProps } from "./system-map-list";+export {+ serviceRows,+ sortServiceRows,+ nextSort,+ DEFAULT_SERVICE_SORT,+ type ServiceRow,+ type ServiceSort,+ type ServiceSortKey,+} from "./service-rows";+export { SystemMapHealthMark } from "./system-map-health-mark";+export { levelAnnouncement, type AnnounceArgs } from "./announce";+export { DEFAULT_NAV_COPY, navCopyWith, type SystemMapNavCopy } from "./nav-copy";export { resolveSelection, type ResolvedSelection } from "./selection-fix";export { scopeCaption, hiddenFamiliesSentence, truncationSentence } from "./scope-caption";export {diff --git a/packages/ui/src/workspace/system-map/nav-copy.ts b/packages/ui/src/workspace/system-map/nav-copy.tsnew file mode 100644index 000000000..f2148228b--- /dev/null+++ b/packages/ui/src/workspace/system-map/nav-copy.ts@@ -0,0 +1,98 @@+/**+ * The words the map's navigation says: search, the Map | List switch, the+ * services table, the shortcut help and the level announcements. English+ * defaults here; a host with a message catalog passes its own through+ * `SystemMap`'s `navCopy` prop. Plain data and string builders, no React.+ */++export interface SystemMapNavCopy {+ searchLabel: string;+ searchPlaceholder: string;+ searchServices: string;+ searchGroups: string;+ searchRoutes: string;+ searchNone: string;+ searchRoutesLoading: string;+ /** Under a route hit: who calls it, e.g. "webapp calls it" or "webapp and 2 more call it". */+ routeCallers: (consumer: string, others: number) => string;+ /** Under a route hit nobody else calls: the provider alone. */+ routeProvider: (provider: string) => string;+ displayLabel: string;+ displayMap: string;+ displayList: string;+ helpOpen: string;+ helpTitle: string;+ keySearch: string;+ keyBack: string;+ keyFocus: string;+ keyBetween: string;+ keyList: string;+ keyHelp: string;+ keySteps: string;+ keyPick: string;+ listCaption: string;+ colService: string;+ colGroup: string;+ colHealth: string;+ colIn: string;+ colOut: string;+ colContracts: string;+ noScore: string;+ /** "provided · consumed" in the Contracts cell. */+ contractsCell: (provided: number, consumed: number) => string;+ announceEstate: (services: number, groups: number) => string;+ announceGroup: (label: string, services: number) => string;+ announceFocus: (name: string, callers: number, dependencies: number) => string;+ announceBetween: (a: string, b: string) => string;+ announceList: (services: number) => string;+ announcePick: (name: string) => string;+}++const n = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`;++export const DEFAULT_NAV_COPY: SystemMapNavCopy = {+ searchLabel: "Search services, groups and routes",+ searchPlaceholder: "Search the map",+ searchServices: "Services",+ searchGroups: "Groups",+ searchRoutes: "Routes",+ searchNone: "Nothing matches",+ searchRoutesLoading: "Searching routes",+ routeCallers: (consumer, others) => (others > 0 ? `${consumer} and ${others} more call it` : `${consumer} calls it`),+ routeProvider: (provider) => `served by ${provider}`,+ displayLabel: "Display",+ displayMap: "Map",+ displayList: "List",+ helpOpen: "Keyboard shortcuts",+ helpTitle: "System map keyboard shortcuts",+ keySearch: "Search services, groups and routes",+ keyBack: "Close details, then go back a level",+ keyFocus: "Focus the selected service",+ keyBetween: "Compare two services, starting from the selected one",+ keyList: "Switch between the map and the list",+ keyHelp: "Show or hide this help",+ keySteps: "Step through search results",+ keyPick: "Go to the highlighted result",+ listCaption: "Services in the estate, one row each",+ colService: "Service",+ colGroup: "Group",+ colHealth: "Health",+ colIn: "Runtime in",+ colOut: "Runtime out",+ colContracts: "Contracts",+ noScore: "No score",+ contractsCell: (provided, consumed) => `${provided} provided · ${consumed} consumed`,+ announceEstate: (services, groups) =>+ groups > 0 ? `Estate: ${n(groups, "group", "groups")}, ${n(services, "service", "services")}` : `Estate: ${n(services, "service", "services")}`,+ announceGroup: (label, services) => `${label} opened: ${n(services, "service", "services")}`,+ announceFocus: (name, callers, dependencies) =>+ `Focused on ${name}: ${n(callers, "caller", "callers")}, ${n(dependencies, "dependency", "dependencies")}`,+ announceBetween: (a, b) => `Showing the links between ${a} and ${b}`,+ announceList: (services) => `List view: ${n(services, "service", "services")}`,+ announcePick: (name) => `Pick a second service to compare with ${name}`,+};++/** The defaults with whatever the host overrides. */+export function navCopyWith(overrides: Partial<SystemMapNavCopy> | undefined): SystemMapNavCopy {+ return overrides ? { ...DEFAULT_NAV_COPY, ...overrides } : DEFAULT_NAV_COPY;+}diff --git a/packages/ui/src/workspace/system-map/search-index.ts b/packages/ui/src/workspace/system-map/search-index.tsnew file mode 100644index 000000000..f5cd0870f--- /dev/null+++ b/packages/ui/src/workspace/system-map/search-index.ts@@ -0,0 +1,146 @@+/**+ * Map search as data: services and groups matched over the loaded graph with+ * Fuse (the Architecture graph's search, `use-graph-search.ts`), routes from+ * contract links the host loads, resolved to the services that serve and call+ * them. A pick is a level change: a service is focused, a group opened, a+ * route compared between its top caller and its provider. Pure, no React.+ */++import Fuse from "fuse.js";+import type { SystemGraph, WorkspaceContractLinkEntry } from "@repowise-dev/types";+import { serviceResolver, type ServiceResolver } from "./system-map-model";+import { compareServices, focusService, openContainer, type MapViewState } from "./view-state";++/** The link fields a route hit reads; the contracts endpoint's link rows fit. */+export type SystemMapRouteLink = Pick<+ WorkspaceContractLinkEntry,+ "contract_id" | "contract_type" | "provider_repo" | "provider_file" | "consumer_repo" | "consumer_file"+>;++/** Loads the contract links matching a query (every term must match), e.g. `/api/workspace/contracts?q=`. */+export type SystemMapRouteLoader = (query: string) => Promise<readonly SystemMapRouteLink[]>;++export type SearchHit =+ | { kind: "service"; id: string; label: string; detail: string }+ | { kind: "group"; id: string; label: string; detail: string }+ | {+ kind: "route";+ id: string;+ label: string;+ contractType: string;+ provider: string;+ /** The service that calls the route most; null when only the provider's own service does. */+ consumer: string | null;+ /** Other calling services beyond `consumer`. */+ otherConsumers: number;+ };++interface Entry {+ id: string;+ label: string;+ detail: string;+}++export interface MapSearchIndex {+ services: Fuse<Entry>;+ groups: Fuse<Entry>;+ /** Owner of a file, kept only when it is a service on the map. */+ resolve: (repo: string, file: string) => string | null;+}++/** Search results per section, at most this many each. */+export const SEARCH_LIMIT = 6;+/** Below this many characters nothing is searched; one letter matches most of an estate. */+export const SEARCH_MIN_CHARS = 2;++const byLabel = (a: Entry, b: Entry) => (a.label < b.label ? -1 : a.label > b.label ? 1 : a.id < b.id ? -1 : 1);++/**+ * One index per graph. Entries are fed in label order, so equal scores keep+ * a stable, alphabetical order. The name weighs most; the id and repo let+ * `ordering.api::src` or a repo alias find a service too.+ */+export function buildSearchIndex(graph: Pick<SystemGraph, "nodes" | "groups">): MapSearchIndex {+ const services = graph.nodes+ .map((n) => ({ id: n.id, label: n.name, detail: n.service_path ? `${n.repo}/${n.service_path}` : n.repo }))+ .sort(byLabel);+ const groups = (graph.groups ?? [])+ .map((g) => ({ id: g.id, label: g.label, detail: `${g.member_count} services` }))+ .sort(byLabel);+ const options = {+ keys: [+ { name: "label", weight: 2 },+ { name: "id", weight: 1 },+ { name: "detail", weight: 1 },+ ],+ threshold: 0.4,+ ignoreLocation: true,+ };+ return {+ services: new Fuse(services, options),+ groups: new Fuse(groups, options),+ resolve: onMap(serviceResolver(graph), new Set(graph.nodes.map((n) => n.id))),+ };+}++function onMap(resolve: ServiceResolver, known: ReadonlySet<string>) {+ return (repo: string, file: string) => {+ const id = resolve(repo, file);+ return known.has(id) ? id : null;+ };+}++/** Services, then groups, best match first in each. */+export function searchMap(index: MapSearchIndex, query: string, limit = SEARCH_LIMIT): SearchHit[] {+ const q = query.trim();+ if (q.length < SEARCH_MIN_CHARS) return [];+ const services = index.services.search(q, { limit }).map(({ item }) => ({ kind: "service" as const, ...item }));+ const groups = index.groups.search(q, { limit }).map(({ item }) => ({ kind: "group" as const, ...item }));+ return [...services, ...groups];+}++/**+ * Route hits from contract links: one per (route, providing service), most+ * calling links first. The top caller is the service with the most links to+ * it, ties by id; a caller inside the provider's own service is not one, and+ * a side that resolves to no service on the map is dropped.+ */+export function routeHits(+ links: readonly SystemMapRouteLink[],+ resolve: MapSearchIndex["resolve"],+ limit = SEARCH_LIMIT,+): SearchHit[] {+ const routes = new Map<string, { link: SystemMapRouteLink; provider: string; callers: Map<string, number>; links: number }>();+ for (const link of links) {+ const provider = resolve(link.provider_repo, link.provider_file);+ if (!provider) continue;+ const key = `${link.contract_id}\u0000${provider}`;+ const row = routes.get(key) ?? { link, provider, callers: new Map<string, number>(), links: 0 };+ routes.set(key, row);+ row.links += 1;+ const consumer = resolve(link.consumer_repo, link.consumer_file);+ if (consumer && consumer !== provider) row.callers.set(consumer, (row.callers.get(consumer) ?? 0) + 1);+ }+ return [...routes.entries()]+ .sort(([ka, a], [kb, b]) => b.links - a.links || (ka < kb ? -1 : 1))+ .slice(0, limit)+ .map(([key, r]) => {+ const callers = [...r.callers.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));+ return {+ kind: "route" as const,+ id: key,+ label: r.link.contract_id,+ contractType: r.link.contract_type,+ provider: r.provider,+ consumer: callers[0]?.[0] ?? null,+ otherConsumers: Math.max(callers.length - 1, 0),+ };+ });+}++/** The level a pick lands on. */+export function pickToView(view: MapViewState, hit: SearchHit): MapViewState {+ if (hit.kind === "service") return focusService(view, hit.id);+ if (hit.kind === "group") return openContainer({ ...view, focus: null, between: null }, hit.id);+ return hit.consumer ? compareServices({ ...view, focus: null }, hit.consumer, hit.provider) : focusService(view, hit.provider);+}diff --git a/packages/ui/src/workspace/system-map/service-rows.ts b/packages/ui/src/workspace/system-map/service-rows.tsnew file mode 100644index 000000000..0cacff572--- /dev/null+++ b/packages/ui/src/workspace/system-map/service-rows.ts@@ -0,0 +1,115 @@+/**+ * The services table behind the map's List view: one row per service with+ * its group, its repository's health, its runtime links in and out, and its+ * contract counts; plus the table's sort. The text alternative to the canvas,+ * so it lists every service whatever level or family filter the map is on.+ * Pure, no React.+ */++import type { SystemEdge, SystemGraph } from "@repowise-dev/types";+import { edgeFamilyOf, linkWeight } from "./edge-families";+import type { RepoHealth } from "./types";++export interface ServiceRow {+ id: string;+ name: string;+ /** Where it lives: the repo, plus the service path when it has one. */+ location: string;+ /** Group label, null when the estate is not grouped or the service is in none. */+ group: string | null;+ /** 0-10 health of the service's repository; null when unscored. */+ health: number | null;+ /** Runtime links (calls and events) into and out of the service. */+ runtimeIn: number;+ runtimeOut: number;+ provided: number;+ consumed: number;+}++export type ServiceSortKey = "name" | "group" | "health" | "in" | "out" | "contracts";+export type SortOrder = "asc" | "desc";+export interface ServiceSort {+ key: ServiceSortKey;+ order: SortOrder;+}++export const DEFAULT_SERVICE_SORT: ServiceSort = { key: "name", order: "asc" };++type Edge = Pick<SystemEdge, "source" | "target" | "kind" | "weight" | "family">;++function runtimeLinks(edges: readonly Edge[]): { into: Map<string, number>; out: Map<string, number> } {+ const into = new Map<string, number>();+ const out = new Map<string, number>();+ for (const e of edges) {+ if (e.source === e.target || edgeFamilyOf(e) !== "runtime") continue;+ const w = linkWeight(e);+ out.set(e.source, (out.get(e.source) ?? 0) + w);+ into.set(e.target, (into.get(e.target) ?? 0) + w);+ }+ return { into, out };+}++export function serviceRows(+ graph: Pick<SystemGraph, "nodes" | "edges" | "groups">,+ healthByRepo?: ReadonlyMap<string, RepoHealth>,+): ServiceRow[] {+ const { into, out } = runtimeLinks(graph.edges);+ const groupLabel = new Map((graph.groups ?? []).map((g) => [g.id, g.label]));+ return graph.nodes.map((n) => {+ const h = healthByRepo?.get(n.repo);+ return {+ id: n.id,+ name: n.name,+ location: n.service_path ? `${n.repo}/${n.service_path}` : n.repo,+ group: (n.group && groupLabel.get(n.group)) || null,+ // Repo health arrives 0-100; the mark reads 0-10.+ health: h ? h.score / 10 : null,+ runtimeIn: into.get(n.id) ?? 0,+ runtimeOut: out.get(n.id) ?? 0,+ provided: n.provider_count,+ consumed: n.consumer_count,+ };+ });+}++const text = (a: string, b: string) => a.localeCompare(b, undefined, { sensitivity: "base" });++/** The column's value; null sorts last in either order. */+function value(row: ServiceRow, key: ServiceSortKey): string | number | null {+ switch (key) {+ case "name":+ return row.name;+ case "group":+ return row.group;+ case "health":+ return row.health;+ case "in":+ return row.runtimeIn;+ case "out":+ return row.runtimeOut;+ case "contracts":+ return row.provided + row.consumed;+ }+}++/** Rows in the given order; ties and missing values fall back to the name, so the order is stable. */+export function sortServiceRows(rows: readonly ServiceRow[], sort: ServiceSort): ServiceRow[] {+ const dir: 1 | -1 = sort.order === "asc" ? 1 : -1;+ return [...rows].sort(+ (a, b) => compareValues(value(a, sort.key), value(b, sort.key), dir) || text(a.name, b.name) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),+ );+}++/** Two column values in `dir` order; a missing value goes last whichever way. */+function compareValues(va: string | number | null, vb: string | number | null, dir: 1 | -1): number {+ if (va === vb) return 0;+ if (va === null) return 1;+ if (vb === null) return -1;+ return (typeof va === "number" && typeof vb === "number" ? va - vb : text(String(va), String(vb))) * dir;+}++/** A header click: the same column flips; a new one starts A to Z for words and largest first for figures. */+export function nextSort(current: ServiceSort, key: ServiceSortKey): ServiceSort {+ if (current.key === key) return { key, order: current.order === "asc" ? "desc" : "asc" };+ return { key, order: key === "name" || key === "group" ? "asc" : "desc" };+}diff --git a/packages/ui/src/workspace/system-map/shortcuts.ts b/packages/ui/src/workspace/system-map/shortcuts.tsnew file mode 100644index 000000000..284a9ea53--- /dev/null+++ b/packages/ui/src/workspace/system-map/shortcuts.ts@@ -0,0 +1,73 @@+/**+ * The map's keyboard shortcuts as data: which key does what, and the list the+ * help overlay prints. Modelled on the Architecture graph's+ * `useGraphKeyboardShortcuts`: `/` and Ctrl/Cmd+K search, Escape backs out,+ * `?` toggles help; the map adds `f` focus, `b` between and `l` list. Keys+ * typed into a field (Ctrl/Cmd+K aside), pressed inside a dialog, or with Alt+ * or a modifier other than Ctrl/Cmd+K, are not shortcuts. Pure, no React.+ */++import type { SystemMapNavCopy } from "./nav-copy";++export type MapShortcut = "search" | "back" | "focus" | "between" | "list" | "help";++/** The key event fields the map reads; a DOM `KeyboardEvent` fits. */+export interface ShortcutKey {+ key: string;+ ctrlKey?: boolean;+ metaKey?: boolean;+ altKey?: boolean;+ /** The element the key was pressed in. */+ target?: EventTarget | null;+ defaultPrevented?: boolean;+}++const PLAIN: Readonly<Record<string, MapShortcut>> = {+ "/": "search",+ Escape: "back",+ f: "focus",+ F: "focus",+ b: "between",+ B: "between",+ l: "list",+ L: "list",+ "?": "help",+};++function typing(target: EventTarget | null | undefined): boolean {+ const el = target as HTMLElement | null | undefined;+ if (!el || typeof el.tagName !== "string") return false;+ return el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT" || el.isContentEditable === true;+}++/** A key pressed inside a dialog (a sheet, a menu) belongs to that dialog, even when it does not mark it handled. */+function inDialog(target: EventTarget | null | undefined): boolean {+ const el = target as HTMLElement | null | undefined;+ return typeof el?.closest === "function" && el.closest('[role="dialog"],[role="alertdialog"]') !== null;+}++/**+ * The shortcut a key press asks for, or null. A press something else already+ * handled (the canvas's own Escape, a dialog) is left alone.+ */+export function shortcutFor(e: ShortcutKey): MapShortcut | null {+ if (e.defaultPrevented || e.altKey || inDialog(e.target)) return null;+ // Ctrl/Cmd+K works from any field: the map holds the shortcut while it is on screen.+ if (e.ctrlKey || e.metaKey) return e.key === "k" || e.key === "K" ? "search" : null;+ return typing(e.target) ? null : (PLAIN[e.key] ?? null);+}++/** The help overlay's rows, in reading order. */+export function shortcutHelpRows(copy: SystemMapNavCopy): { keys: string[]; action: string }[] {+ return [+ { keys: ["/"], action: copy.keySearch },+ { keys: ["Ctrl K"], action: copy.keySearch },+ { keys: ["↑", "↓"], action: copy.keySteps },+ { keys: ["Enter"], action: copy.keyPick },+ { keys: ["f"], action: copy.keyFocus },+ { keys: ["b"], action: copy.keyBetween },+ { keys: ["l"], action: copy.keyList },+ { keys: ["Esc"], action: copy.keyBack },+ { keys: ["?"], action: copy.keyHelp },+ ];+}diff --git a/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsx b/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsxindex ddf3ff501..69e974bfc 100644--- a/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsx+++ b/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsx@@ -8,13 +8,13 @@*/import type { SystemEdge, SystemNode } from "@repowise-dev/types";-import { healthMark } from "../../health/tokens";import { bandSentence, groupSourceLabel, healthCounts, healthSummaryText, kindMixText } from "./aggregate-facts";import { summarizeLinks } from "./bands";import type { DrawnBand, DrawnGroupNode, LinkSummary } from "./level-types";import { SystemMapRailFrame } from "./system-map-drawer";import { MICRO_LABEL } from "./system-map-filters";import { plural } from "./system-map-model";+import { SystemMapHealthMark } from "./system-map-health-mark";import type { RepoHealth, SystemMapSelection } from "./types";const ROW =@@ -64,26 +64,14 @@ export function GroupPanel({<section className="flex flex-col gap-1"><h3 className={MICRO_LABEL}>Services</h3><ul className="flex flex-col">- {group.serviceIds.map((id) => {- const s = score(id);- const mark = s == null ? null : healthMark(s);- return (- <li key={id}>- <button type="button" className={ROW} onClick={() => onSelect({ type: "node", id })}>- <span className="min-w-0 truncate text-xs text-[var(--color-text-primary)]">{nodesById.get(id)?.name ?? id}</span>- {mark ? (- <span className="inline-flex shrink-0 items-center gap-1.5 text-xs">- <span aria-hidden className="h-1.5 w-1.5 rounded-full" style={{ background: mark.color }} />- <span className="tabular-nums text-[var(--color-text-primary)]">{mark.value}</span>- <span className="text-[var(--color-text-secondary)]">{mark.label}</span>- </span>- ) : (- <span className="shrink-0 text-xs text-[var(--color-text-secondary)]">No score</span>- )}- </button>- </li>- );- })}+ {group.serviceIds.map((id) => (+ <li key={id}>+ <button type="button" className={ROW} onClick={() => onSelect({ type: "node", id })}>+ <span className="min-w-0 truncate text-xs text-[var(--color-text-primary)]">{nodesById.get(id)?.name ?? id}</span>+ <SystemMapHealthMark score={score(id)} />+ </button>+ </li>+ ))}</ul></section></SystemMapRailFrame>diff --git a/packages/ui/src/workspace/system-map/system-map-chrome.tsx b/packages/ui/src/workspace/system-map/system-map-chrome.tsxnew file mode 100644index 000000000..9b6f092bd--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-chrome.tsx@@ -0,0 +1,74 @@+"use client";++/**+ * The map's chrome for the level drawn: the breadcrumb, the family chips and+ * key above the canvas, and the Between picker in the title row. The list+ * view draws no level, so it gets no breadcrumb and no chips.+ */++import type { ReactNode } from "react";+import type { SystemGraph } from "@repowise-dev/types";+import type { LevelView } from "./levels";+import { SystemMapBetweenControl } from "./system-map-between-control";+import { SystemMapBreadcrumb } from "./system-map-breadcrumb";+import { SystemMapFilters } from "./system-map-filters";+import { SystemMapLegend, type SystemMapLegendProps } from "./system-map-legend";+import type { MapLevel } from "./use-map-level";+import type { MapNavigation } from "./use-map-navigation";+import { toggleFamily, type MapViewState } from "./view-state";++export interface ChromeArgs {+ graph: SystemGraph | null;+ level: MapLevel;+ view: MapViewState;+ setView: (next: MapViewState) => void;+ nav: MapNavigation;+ legend: SystemMapLegendProps;+ estateLabel?: string | undefined;+}++export interface MapChrome {+ breadcrumb: ReactNode;+ banner: ReactNode;+ betweenControl: ReactNode;+}++function betweenControl({ graph, level, nav }: ChromeArgs): ReactNode {+ const levelView = level.levelView;+ if (!graph || !levelView || graph.nodes.length < 2) return null;+ return (+ <SystemMapBetweenControl+ graph={graph}+ families={levelView.families}+ open={nav.picker.open}+ onOpenChange={(open) => nav.setPicker(open ? { ...nav.picker, open } : { open: false })}+ from={nav.picker.from}+ onBetween={nav.onBetween}+ />+ );+}++function levelChrome(a: ChromeArgs, graph: SystemGraph, levelView: LevelView): Omit<MapChrome, "betweenControl"> {+ const breadcrumb =+ levelView.level !== "estate" ? (+ <SystemMapBreadcrumb graph={graph} level={levelView.level} view={a.view} onViewChange={a.setView} estateLabel={a.estateLabel} />+ ) : undefined;+ const banner = (+ <div className="flex min-w-0 flex-col gap-2">+ <SystemMapFilters+ familyCounts={levelView.familyCounts}+ kindCounts={a.level.kindCounts}+ families={levelView.families}+ onToggleFamily={(f) => a.setView(toggleFamily(a.view, f))}+ />+ <SystemMapLegend {...a.legend} />+ </div>+ );+ return { breadcrumb, banner };+}++export function mapChrome(a: ChromeArgs): MapChrome {+ const levelView = a.level.levelView;+ const drawn = a.nav.display === "map" && a.graph && levelView ? levelChrome(a, a.graph, levelView) : null;+ return { breadcrumb: drawn?.breadcrumb, banner: drawn?.banner, betweenControl: betweenControl(a) };+}diff --git a/packages/ui/src/workspace/system-map/system-map-health-mark.tsx b/packages/ui/src/workspace/system-map/system-map-health-mark.tsxnew file mode 100644index 000000000..152a62aec--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-health-mark.tsx@@ -0,0 +1,19 @@+/**+ * A service's health in a row: the canonical dot, figure and band word+ * (`healthMark`), or "No score". Shared by the group panel and the services+ * table so both read the same.+ */++import { healthMark } from "../../health/tokens";++export function SystemMapHealthMark({ score, noScore = "No score" }: { score: number | null; noScore?: string }) {+ if (score == null) return <span className="shrink-0 text-xs text-[var(--color-text-secondary)]">{noScore}</span>;+ const mark = healthMark(score);+ return (+ <span className="inline-flex shrink-0 items-center gap-1.5 text-xs">+ <span aria-hidden className="h-1.5 w-1.5 rounded-full" style={{ background: mark.color }} />+ <span className="tabular-nums text-[var(--color-text-primary)]">{mark.value}</span>+ <span className="text-[var(--color-text-secondary)]">{mark.label}</span>+ </span>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-list.tsx b/packages/ui/src/workspace/system-map/system-map-list.tsxnew file mode 100644index 000000000..5fee0fd88--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-list.tsx@@ -0,0 +1,101 @@+"use client";++/**+ * The map's List view: every service as a sortable table row (name, group,+ * health, runtime links in and out, contracts), the text alternative to the+ * canvas. A row opens the service's details in the rail, as a click on its+ * card does.+ */++import { useMemo, useState } from "react";+import type { SystemGraph } from "@repowise-dev/types";+import { ResponsiveTable, type ResponsiveColumn } from "../../shared/responsive-table";+import type { SystemMapNavCopy } from "./nav-copy";+import {+ DEFAULT_SERVICE_SORT,+ nextSort,+ serviceRows,+ sortServiceRows,+ type ServiceRow,+ type ServiceSort,+ type ServiceSortKey,+} from "./service-rows";+import { SystemMapHealthMark } from "./system-map-health-mark";+import type { RepoHealth } from "./types";++export interface SystemMapListProps {+ graph: SystemGraph;+ healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;+ selectedId: string | null;+ onSelect: (serviceId: string) => void;+ copy: SystemMapNavCopy;+}++const FIGURE = "font-mono text-xs tabular-nums text-[var(--color-text-primary)]";++function columns(copy: SystemMapNavCopy, grouped: boolean): ResponsiveColumn<ServiceRow>[] {+ const cols: ResponsiveColumn<ServiceRow>[] = [+ {+ key: "name",+ header: copy.colService,+ sortable: true,+ priority: 1,+ render: (r) => (+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-xs font-medium text-[var(--color-text-primary)]">{r.name}</span>+ {r.location !== r.name && (+ <span className="truncate font-mono text-[10px] text-[var(--color-text-secondary)]">{r.location}</span>+ )}+ </span>+ ),+ },+ {+ key: "group",+ header: copy.colGroup,+ sortable: true,+ priority: 2,+ render: (r) => <span className="text-xs text-[var(--color-text-secondary)]">{r.group ?? "–"}</span>,+ },+ {+ key: "health",+ header: copy.colHealth,+ sortable: true,+ priority: 1,+ render: (r) => <SystemMapHealthMark score={r.health} noScore={copy.noScore} />,+ },+ { key: "in", header: copy.colIn, sortable: true, align: "right", priority: 1, render: (r) => <span className={FIGURE}>{r.runtimeIn}</span> },+ { key: "out", header: copy.colOut, sortable: true, align: "right", priority: 1, render: (r) => <span className={FIGURE}>{r.runtimeOut}</span> },+ {+ key: "contracts",+ header: copy.colContracts,+ sortable: true,+ align: "right",+ priority: 3,+ render: (r) => <span className="text-xs tabular-nums text-[var(--color-text-secondary)]">{copy.contractsCell(r.provided, r.consumed)}</span>,+ },+ ];+ return grouped ? cols : cols.filter((c) => c.key !== "group");+}++export function SystemMapList({ graph, healthByRepo, selectedId, onSelect, copy }: SystemMapListProps) {+ const [sort, setSort] = useState<ServiceSort>(DEFAULT_SERVICE_SORT);+ const rows = useMemo(() => serviceRows(graph, healthByRepo), [graph, healthByRepo]);+ const sorted = useMemo(() => sortServiceRows(rows, sort), [rows, sort]);+ const grouped = rows.some((r) => r.group !== null);+ return (+ <ResponsiveTable+ columns={columns(copy, grouped)}+ rows={sorted}+ rowKey={(r) => r.id}+ onRowClick={(r) => onSelect(r.id)}+ selectedKey={selectedId}+ sortField={sort.key}+ sortOrder={sort.order}+ onSort={(key) => setSort((s) => nextSort(s, key as ServiceSortKey))}+ caption={copy.listCaption}+ stacked="sm"+ virtualize={{ maxHeight: 640 }}+ bare+ />+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-model.ts b/packages/ui/src/workspace/system-map/system-map-model.tsindex 961bd641f..0bd71bb21 100644--- a/packages/ui/src/workspace/system-map/system-map-model.ts+++ b/packages/ui/src/workspace/system-map/system-map-model.ts@@ -44,7 +44,7 @@ export interface SystemMapRepoContracts {*/export type ServiceResolver = (repo: string, file: string) => string;-export function serviceResolver(graph: SystemGraph): ServiceResolver {+export function serviceResolver(graph: Pick<SystemGraph, "nodes">): ServiceResolver {const paths = new Map<string, string[]>();for (const n of graph.nodes) {if (!n.service_path) continue;diff --git a/packages/ui/src/workspace/system-map/system-map-nav-actions.tsx b/packages/ui/src/workspace/system-map/system-map-nav-actions.tsxnew file mode 100644index 000000000..ebfe51350--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-nav-actions.tsx@@ -0,0 +1,46 @@+"use client";++/**+ * The map's own title-row controls after the host's: search, the Map | List+ * switch and the shortcut help button.+ */++import { Keyboard } from "lucide-react";+import { Segmented } from "../../shared/segmented";+import type { SystemMapNavCopy } from "./nav-copy";+import { SystemMapSearch } from "./system-map-search";+import type { MapSearch } from "./use-system-map-search";+import type { MapNavigation } from "./use-map-navigation";++export interface SystemMapNavActionsProps {+ nav: MapNavigation;+ search: MapSearch;+ copy: SystemMapNavCopy;+ name: (serviceId: string) => string;+}++export function SystemMapNavActions({ nav, search, copy, name }: SystemMapNavActionsProps) {+ return (+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <SystemMapSearch search={search} inputRef={nav.searchRef} copy={copy} name={name} />+ <Segmented+ label={copy.displayLabel}+ value={nav.display}+ options={[+ { value: "map", label: copy.displayMap },+ { value: "list", label: copy.displayList },+ ]}+ onChange={nav.setDisplay}+ />+ <button+ type="button"+ onClick={() => nav.setHelp((open) => !open)}+ aria-label={copy.helpOpen}+ title={copy.helpOpen}+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <Keyboard aria-hidden className="h-4 w-4" />+ </button>+ </div>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-rail-content.tsx b/packages/ui/src/workspace/system-map/system-map-rail-content.tsxindex a1be61e38..d906b8b55 100644--- a/packages/ui/src/workspace/system-map/system-map-rail-content.tsx+++ b/packages/ui/src/workspace/system-map/system-map-rail-content.tsx@@ -28,6 +28,8 @@ export interface RailContentArgs {roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;drawer?: SystemMapDrawerData | undefined;loadLinksBetween?: LoadLinksBetween | undefined;+ /** The routes panel's starting filter (a route picked in search). */+ routeFilter?: string | undefined;onSelect: (selection: SystemMapSelection) => void;onOpenGroup: (groupId: string) => void;/** Map verbs the rail offers. */@@ -44,10 +46,14 @@ export interface RailVerbs {}/** The routes between the two services compared, when the level is Between and nothing is selected. */-function levelRail({ graph, levelView, drawer, loadLinksBetween, verbs }: RailContentArgs): ReactNode {+function levelRail({ graph, levelView, drawer, loadLinksBetween, routeFilter, verbs }: RailContentArgs): ReactNode {if (levelView.level !== "between" || !levelView.between) return null;+ const { a, b } = levelView.between;return (<SystemMapRoutesPanel+ // A new pair or a new route pick starts the panel over, with that filter.+ key={`${a}|${b}|${routeFilter ?? ""}`}+ initialFilter={routeFilter}graph={graph}between={levelView.between}families={levelView.families}diff --git a/packages/ui/src/workspace/system-map/system-map-routes-panel.tsx b/packages/ui/src/workspace/system-map/system-map-routes-panel.tsxindex bf3de5120..9bb7c0229 100644--- a/packages/ui/src/workspace/system-map/system-map-routes-panel.tsx+++ b/packages/ui/src/workspace/system-map/system-map-routes-panel.tsx@@ -40,6 +40,8 @@ export interface SystemMapRoutesPanelProps {between: BetweenResult;families: ReadonlySet<EdgeFamily>;loadLinksBetween?: LoadLinksBetween | undefined;+ /** The filter box's starting text, e.g. the route a search pick named. */+ initialFilter?: string | undefined;contractHref?: ((ref: ContractRef) => string) | undefined;/** The Contracts page filtered to one repository. */contractsHref?: ((repo: string) => string) | undefined;@@ -55,7 +57,7 @@ const BUTTON =export function SystemMapRoutesPanel(props: SystemMapRoutesPanelProps) {const { graph, between, families } = props;- const [filter, setFilter] = useState("");+ const [filter, setFilter] = useState(props.initialFilter ?? "");const q = useDebounce(filter.trim(), 250);const state = useRoutesBetween({ load: props.loadLinksBetween, a: between.a, b: between.b, families, q });const [prompting, setPrompting] = useState(false);diff --git a/packages/ui/src/workspace/system-map/system-map-search.tsx b/packages/ui/src/workspace/system-map/system-map-search.tsxnew file mode 100644index 000000000..7d39ec8a7--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-search.tsx@@ -0,0 +1,119 @@+"use client";++/**+ * The map's search: one combobox in the title row, results grouped as+ * Services, Groups and Routes. Arrow keys move through every result, Enter+ * picks, Escape clears then leaves. The input is reachable from anywhere on+ * the page with `/` or Ctrl/Cmd+K through the ref the map holds.+ */++import { useId, useState, type RefObject } from "react";+import { Search } from "lucide-react";+import type { SystemMapNavCopy } from "./nav-copy";+import { SEARCH_MIN_CHARS, type SearchHit } from "./search-index";+import type { MapSearch } from "./use-system-map-search";++export interface SystemMapSearchProps {+ search: MapSearch;+ inputRef: RefObject<HTMLInputElement | null>;+ copy: SystemMapNavCopy;+ /** Display name of a service id, for route hits. */+ name: (serviceId: string) => string;+}++const SECTIONS: { kind: SearchHit["kind"]; title: (c: SystemMapNavCopy) => string }[] = [+ { kind: "service", title: (c) => c.searchServices },+ { kind: "group", title: (c) => c.searchGroups },+ { kind: "route", title: (c) => c.searchRoutes },+];++function hitDetail(hit: SearchHit, copy: SystemMapNavCopy, name: (id: string) => string): string {+ if (hit.kind !== "route") return hit.detail;+ return hit.consumer ? copy.routeCallers(name(hit.consumer), hit.otherConsumers) : copy.routeProvider(name(hit.provider));+}++export function SystemMapSearch({ search, inputRef, copy, name }: SystemMapSearchProps) {+ const listId = useId();+ const [open, setOpen] = useState(false);+ const shown = open && search.query.trim().length >= SEARCH_MIN_CHARS;+ const optionId = (i: number) => `${listId}-o${i}`;+ const activeHit = search.hits[search.active];++ return (+ <div className="relative w-full min-w-0 sm:w-64" onBlur={(e) => !e.currentTarget.contains(e.relatedTarget) && setOpen(false)}>+ <Search aria-hidden className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />+ <input+ ref={inputRef}+ type="search"+ role="combobox"+ aria-label={copy.searchLabel}+ aria-expanded={shown}+ aria-controls={shown ? listId : undefined}+ aria-autocomplete="list"+ aria-activedescendant={shown && activeHit ? optionId(search.active) : undefined}+ placeholder={copy.searchPlaceholder}+ value={search.query}+ onChange={(e) => {+ search.setQuery(e.target.value);+ setOpen(true);+ }}+ onFocus={() => setOpen(true)}+ onKeyDown={search.onKeyDown}+ className="h-8 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] pl-7 pr-2 text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ />+ {shown && <SearchResults id={listId} optionId={optionId} search={search} copy={copy} name={name} />}+ </div>+ );+}++interface SearchResultsProps {+ id: string;+ optionId: (index: number) => string;+ search: MapSearch;+ copy: SystemMapNavCopy;+ name: (serviceId: string) => string;+}++/** The listbox: hits grouped by section, each an option the arrows highlight. */+function SearchResults({ id, optionId, search, copy, name }: SearchResultsProps) {+ const status = search.hits.length === 0 ? (search.routesLoading ? copy.searchRoutesLoading : copy.searchNone) : null;+ return (+ <div+ id={id}+ role="listbox"+ aria-label={copy.searchLabel}+ className="absolute right-0 top-full z-[var(--z-dropdown)] mt-1 max-h-80 w-full min-w-[16rem] overflow-y-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-1 shadow-lg shadow-black/20"+ >+ {status && <p className="px-2 py-1.5 text-xs text-[var(--color-text-secondary)]">{status}</p>}+ {SECTIONS.map(({ kind, title }) => {+ const rows = search.hits.map((hit, i) => ({ hit, i })).filter(({ hit }) => hit.kind === kind);+ if (rows.length === 0) return null;+ return (+ <div key={kind} role="group" aria-label={title(copy)}>+ <p aria-hidden className="px-2 pb-0.5 pt-1.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-secondary)]">+ {title(copy)}+ </p>+ {rows.map(({ hit, i }) => (+ <div+ key={`${hit.kind}:${hit.id}`}+ id={optionId(i)}+ role="option"+ aria-selected={i === search.active}+ // Keeps focus in the input, so the pick does not blur and close the list first.+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => search.pick(hit)}+ className={`flex cursor-pointer flex-col rounded px-2 py-1 ${i === search.active ? "bg-[var(--color-bg-inset)]" : "hover:bg-[var(--color-bg-inset)]"}`}+ >+ <span className={`truncate text-xs text-[var(--color-text-primary)] ${hit.kind === "route" ? "font-mono" : ""}`}>{hit.label}</span>+ <span className="truncate text-[10px] text-[var(--color-text-secondary)]">{hitDetail(hit, copy, name)}</span>+ </div>+ ))}+ </div>+ );+ })}+ {!status && search.routesLoading && (+ <p className="px-2 py-1 text-[10px] text-[var(--color-text-secondary)]">{copy.searchRoutesLoading}</p>+ )}+ </div>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsxindex 73f9f0065..0c4782a6e 100644--- a/packages/ui/src/workspace/system-map/system-map.tsx+++ b/packages/ui/src/workspace/system-map/system-map.tsx@@ -13,32 +13,42 @@* details in the rail, a grid peer of the canvas (a bottom sheet on phones).* The host supplies data, routes and the links loader through props only; it* may control the level state and the selection to keep them in its URL.+ * Search, the Map | List switch, keyboard shortcuts, comparing two services+ * and a live line announcing each level change come from+ * `use-map-navigation.ts`; card and rail verbs from `use-map-verbs.ts`.*/-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";+import { useCallback, useEffect, useMemo, useRef, type ReactNode, type RefObject } from "react";import { ReactFlowProvider } from "@xyflow/react";import type { NodeArchitectureRole, SystemGraph } from "@repowise-dev/types";import { GraphCanvasShell } from "../../graph/graph-canvas-shell";-import { activateEdge, activateNode, type Activation, type ActivateTrigger } from "./activate";+import { GraphShortcutHelp } from "../../graph/graph-shortcut-help";+import type { ActivateTrigger } from "./activate";+import { levelAnnouncement } from "./announce";import { toFlowElements, type FlowElements } from "./flow-elements";-import type { LevelView } from "./levels";+import { navCopyWith, type SystemMapNavCopy } from "./nav-copy";import { scopeCaption } from "./scope-caption";-import { SystemMapActionsContext, type SystemMapActions } from "./system-map-actions";-import { SystemMapBreadcrumb } from "./system-map-breadcrumb";+import type { SystemMapRouteLoader } from "./search-index";+import { shortcutHelpRows } from "./shortcuts";+import { SystemMapActionsContext } from "./system-map-actions";import { SystemMapCanvas } from "./system-map-canvas";+import { mapChrome } from "./system-map-chrome";import type { SystemMapDrawerData } from "./system-map-drawer";import { SystemMapCanvasEmpty } from "./system-map-empty";-import { SystemMapFilters } from "./system-map-filters";import { SystemMapFocusContext, createSystemMapFocusStore, type SystemMapFocusStore } from "./system-map-focus";-import { SystemMapLegend, legendKeyFor } from "./system-map-legend";+import { legendKeyFor } from "./system-map-legend";+import { SystemMapList } from "./system-map-list";+import { SystemMapNavActions } from "./system-map-nav-actions";import type { LoadLinksBetween } from "./routes-between";-import { SystemMapBetweenControl } from "./system-map-between-control";-import { railContent, type RailVerbs } from "./system-map-rail-content";+import { railContent } from "./system-map-rail-content";import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";import { useDropUndrawnAggregate, useMapLevel, type MapLevel } from "./use-map-level";+import { useMapNavigation, type MapNavigation } from "./use-map-navigation";+import { useMapInput, useRailVerbs } from "./use-map-verbs";import type { SystemMapPhase } from "./use-system-map-phases";+import { useSystemMapSearch } from "./use-system-map-search";import { useSystemMapState, type SystemMapState } from "./use-system-map-state";-import { backOut, closeContainer, openContainer, showFamily, toggleFamily, type MapViewState } from "./view-state";+import { TRAY_OPEN_TOKEN, type MapViewState } from "./view-state";/** The canvas's height, shared with the host's loading placeholder so nothing reflows. */export const SYSTEM_MAP_CANVAS_HEIGHT = "h-[420px] sm:h-[clamp(460px,calc(100dvh-240px),800px)]";@@ -81,6 +91,10 @@ export interface SystemMapProps {estateLabel?: string;/** Called as each render phase completes, for host-side timing. */onPhase?: (phase: SystemMapPhase) => void;+ /** Contract links matching a search, so search finds routes too; without it search covers services and groups. */+ loadRoutes?: SystemMapRouteLoader;+ /** The navigation's words (search, list, shortcuts, announcements); English by default. */+ navCopy?: Partial<SystemMapNavCopy>;}export function SystemMap(props: SystemMapProps) {@@ -104,82 +118,42 @@ function useFocusStore(level: MapLevel) {return { focus, canvasRef };}-/** Card verbs and the canvas's activate and Escape handlers, over the level state and the selection. */-function useMapInput(levelView: LevelView | null, state: SystemMapState, onShowFolded: SystemMapProps["onShowFolded"]) {- const { view, setView, selection, setSelection } = state;- const actions = useMemo<SystemMapActions>(- () => ({- openContainer: (id) => setView(openContainer(view, id)),- closeContainer: (id) => setView(closeContainer(view, id)),- showFolded: onShowFolded,- }),- [setView, view, onShowFolded],- );- const apply = useCallback(- (a: Activation) => {- if (a?.kind === "select") setSelection(a.selection);- else if (a?.kind === "open") actions.openContainer(a.id);- else if (a?.kind === "focus") setView(focusService(view, a.serviceId));- else if (a?.kind === "folded") actions.showFolded?.(a.serviceIds);- },- [setSelection, actions, setView, view],- );- const onActivate = useCallback(- (id: string, kind: "node" | "edge", trigger: ActivateTrigger) =>- apply(- kind === "edge"- ? activateEdge(levelView?.edges.find((e) => e.id === id))- : activateNode(levelView?.nodes.find((n) => n.id === id), trigger),- ),- [apply, levelView],- );- const onEscape = useCallback(() => {- if (selection) return setSelection(null);- const up = backOut(view);- if (up) setView(up);- }, [selection, setSelection, view, setView]);- return { actions, onActivate, onEscape };-}--/** The focus level around one service; leaves Between, keeps the families and open groups. */-function focusService(view: MapViewState, id: string): MapViewState {- return { ...view, focus: id, between: null };-}--/** The Between picker's state and the verbs the rail offers (focus, between, show a family). */-function useRailVerbs(state: SystemMapState) {- const { view, setView, setSelection } = state;- const [picker, setPicker] = useState<{ open: boolean; from?: string }>({ open: false });- const onBetween = useCallback(- (a: string, b: string) => {- setSelection(null);- setView({ ...view, between: { a, b } });- },- [view, setView, setSelection],- );- const verbs = useMemo<RailVerbs>(- () => ({- onFocus: (id) => setView(focusService(view, id)),- onRoutesFrom: (id) => setPicker({ open: true, from: id }),- onBetween,- onShowFamily: (f) => setView(showFamily(view, f)),- onLeaveBetween: () => setView({ ...view, between: null }),- }),- [view, setView, onBetween],+/** What the live region says: the level, the display, or a pending Between pick. */+function useAnnouncement(graph: SystemGraph | null, level: MapLevel, view: MapViewState, nav: MapNavigation, copy: SystemMapNavCopy) {+ const { levelView, nodesById } = level;+ return useMemo(+ () =>+ levelAnnouncement({+ levelView,+ view,+ display: nav.display,+ services: graph?.nodes.length ?? 0,+ pendingFrom: nav.pendingFrom,+ name: (id) => nodesById.get(id)?.name ?? id,+ groupLabel: (id) => (id === TRAY_OPEN_TOKEN ? "Not linked at runtime" : (graph?.groups?.find((g) => g.id === id)?.label ?? id)),+ copy,+ }),+ [graph, levelView, nodesById, view, nav.display, nav.pendingFrom, copy],);- return { verbs, picker, setPicker, onBetween };}function SystemMapInner(props: SystemMapProps) {const { graph, healthByRepo, overlay, roleByNodeId, toolbar, actions: extraActions } = props;- const state = useSystemMapState(props);+ const own = useSystemMapState(props);+ const nav = useMapNavigation(own);+ // Every input selects through the navigation, so a pending Between pick completes wherever the second service is picked.+ const state: SystemMapState = { ...own, setSelection: nav.setSelection };const { view, setView, selection, setSelection } = state;+ const copy = useMemo(() => navCopyWith(props.navCopy), [props.navCopy]);const level = useMapLevel(graph, view, selection, setView, props.onPhase);- useDropUndrawnAggregate(selection, level, setSelection);+ useDropUndrawnAggregate(selection, level, own.setSelection);const { nodesById, edgesById, levelView, layout } = level;const { focus, canvasRef } = useFocusStore(level);const input = useMapInput(levelView, state, props.onShowFolded);- const rail = useRailVerbs(state);+ const verbs = useRailVerbs(state, nav);+ const search = useSystemMapSearch(graph, nav.onSearchPick, props.loadRoutes);+ const announcement = useAnnouncement(graph, level, view, nav, copy);+ const listing = nav.display === "list";const selectedId = level.resolved?.drawnId ?? null;const flow = useMemo<FlowElements>(@@ -194,6 +168,7 @@ function SystemMapInner(props: SystemMapProps) {const legend = useMemo(() => legendKeyFor(levelView?.edges ?? [], edgesById), [levelView, edgesById]);const hasGraph = Boolean(graph && graph.nodes.length > 0);+ const showCaption = !listing && hasGraph && caption.length > 0;const railNode =graph && levelView? railContent({@@ -206,37 +181,13 @@ function SystemMapInner(props: SystemMapProps) {roleByNodeId,drawer: props.drawer,loadLinksBetween: props.loadLinksBetween,+ routeFilter: nav.routeFilter,onSelect: setSelection,onOpenGroup: input.actions.openContainer,- verbs: rail.verbs,+ verbs,}): null;- const betweenControl =- graph && levelView && graph.nodes.length > 1 ? (- <SystemMapBetweenControl- graph={graph}- families={levelView.families}- open={rail.picker.open}- onOpenChange={(open) => rail.setPicker(open ? { ...rail.picker, open } : { open: false })}- from={rail.picker.from}- onBetween={rail.onBetween}- />- ) : null;- const breadcrumb =- graph && levelView && levelView.level !== "estate" ? (- <SystemMapBreadcrumb graph={graph} level={levelView.level} view={view} onViewChange={setView} estateLabel={props.estateLabel} />- ) : undefined;- const banner = levelView ? (- <div className="flex min-w-0 flex-col gap-2">- <SystemMapFilters- familyCounts={levelView.familyCounts}- kindCounts={level.kindCounts}- families={levelView.families}- onToggleFamily={(f) => setView(toggleFamily(view, f))}- />- <SystemMapLegend {...legend} />- </div>- ) : undefined;+ const { breadcrumb, banner, betweenControl } = mapChrome({ graph, level, view, setView, nav, legend, estateLabel: props.estateLabel });const empty = (<SystemMapCanvasEmptyerror={props.error}@@ -253,22 +204,53 @@ function SystemMapInner(props: SystemMapProps) {variant="section"breadcrumb={breadcrumb}title={props.title}- titleActions={toolbar || extraActions || betweenControl ? <>{toolbar}{extraActions}{betweenControl}</> : undefined}+ titleActions={+ <>+ {toolbar}+ {extraActions}+ {betweenControl}+ <SystemMapNavActions nav={nav} search={search} copy={copy} name={name} />+ </>+ }banner={banner}rail={railNode}- footer={hasGraph && caption.length > 0 ? <p className="text-xs text-[var(--color-text-secondary)]">{caption.join(" ")}</p> : undefined}+ footer={showCaption ? <p className="text-xs text-[var(--color-text-secondary)]">{caption.join(" ")}</p> : undefined}>- <MapCanvas- canvasRef={canvasRef}- focus={focus}- flow={flow}- fitKey={[levelView?.level, view.open.join(","), view.focus, view.between?.a, view.between?.b].join("|")}- settled={!layout.loading}- onActivate={input.onActivate}- onEscape={input.onEscape}- onPaneClick={() => setSelection(null)}- empty={empty}- />+ <div className="relative min-w-0">+ {listing && graph ? (+ <SystemMapList+ graph={graph}+ healthByRepo={healthByRepo}+ selectedId={selection?.type === "node" ? selection.id : null}+ onSelect={(id) => setSelection({ type: "node", id })}+ copy={copy}+ />+ ) : (+ <MapCanvas+ canvasRef={canvasRef}+ focus={focus}+ flow={flow}+ fitKey={[levelView?.level, view.open.join(","), view.focus, view.between?.a, view.between?.b].join("|")}+ settled={!layout.loading}+ onActivate={input.onActivate}+ onEscape={nav.back}+ onPaneClick={() => setSelection(null)}+ empty={empty}+ />+ )}+ {nav.help && (+ <GraphShortcutHelp+ onClose={() => nav.setHelp(false)}+ shortcuts={shortcutHelpRows(copy)}+ gestures={[]}+ label={copy.helpTitle}+ title={copy.helpOpen}+ />+ )}+ <p role="status" aria-live="polite" className="sr-only">+ {announcement}+ </p>+ </div></GraphCanvasShell></SystemMapActionsContext.Provider></SystemMapFocusContext.Provider>@@ -283,7 +265,7 @@ interface MapCanvasProps {fitKey: string;settled: boolean;onActivate: (id: string, kind: "node" | "edge", trigger: ActivateTrigger) => void;- onEscape: () => void;+ onEscape: () => unknown;onPaneClick: () => void;empty: ReactNode;}diff --git a/packages/ui/src/workspace/system-map/use-map-navigation.ts b/packages/ui/src/workspace/system-map/use-map-navigation.tsnew file mode 100644index 000000000..dc55d915c--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-map-navigation.ts@@ -0,0 +1,243 @@+"use client";++/**+ * The map's navigation state over the level state and the selection: the+ * Map | List display (the table by default on phones), comparing two+ * services (the Between picker, the `b` pick, a route search pick and the+ * rail all complete through one `onBetween`), the shortcut help, the search+ * input's ref, and the keyboard shortcuts bound while the map is on screen.+ * Anything that lands on a level shows the map.+ */++import { useCallback, useEffect, useRef, useState, type Dispatch, type RefObject, type SetStateAction } from "react";+import { claimCommandPaletteShortcut } from "../../lib/command-palette-scope";+import type { SearchHit } from "./search-index";+import { pickToView } from "./search-index";+import { shortcutFor, type MapShortcut } from "./shortcuts";+import type { SystemMapSelection } from "./types";+import type { SystemMapState } from "./use-system-map-state";+import { backOut, compareServices, focusService, withDisplay, type MapDisplay, type MapViewState } from "./view-state";++/** Below Tailwind's `sm`, where the table reads better than the canvas. */+const NARROW = "(max-width: 639px)";++/** False on the server and the first client render, so both agree; the effect corrects it. */+function useNarrowViewport(): boolean {+ const [narrow, setNarrow] = useState(false);+ useEffect(() => {+ if (typeof window === "undefined" || !window.matchMedia) return;+ const mq = window.matchMedia(NARROW);+ setNarrow(mq.matches);+ const onChange = () => setNarrow(mq.matches);+ mq.addEventListener("change", onChange);+ return () => mq.removeEventListener("change", onChange);+ }, []);+ return narrow;+}++/** The Between picker in the title row: open or closed, and the From service it opens with. */+export interface BetweenPicker {+ open: boolean;+ from?: string;+}++export interface MapNavigation {+ display: MapDisplay;+ setDisplay: (display: MapDisplay) => void;+ /** A level change from the list shows the map, where the level is drawn. */+ toMap: (next: MapViewState) => MapViewState;+ /** Service picked with `b`, waiting for the second. */+ pendingFrom: string | null;+ /** The selection setter every input should use: it completes a pending Between pick. */+ setSelection: (next: SystemMapSelection) => void;+ picker: BetweenPicker;+ setPicker: (picker: BetweenPicker) => void;+ /** Compare two services: the one path the picker, the `b` pick and the rail all complete through. */+ onBetween: (a: string, b: string) => void;+ /** The routes panel's starting filter, when a route search pick opened the comparison drawn. */+ routeFilter: string | undefined;+ help: boolean;+ setHelp: Dispatch<SetStateAction<boolean>>;+ searchRef: RefObject<HTMLInputElement | null>;+ /** Escape, wherever it is pressed: help, a pending pick, the picker, the selection, then a level. */+ back: () => boolean;+ onSearchPick: (hit: SearchHit) => void;+}++/** Everything a shortcut can act on. */+interface ShortcutContext {+ view: MapViewState;+ setView: (next: MapViewState) => void;+ selection: SystemMapSelection;+ clearSelection: () => void;+ display: MapDisplay;+ setDisplay: (display: MapDisplay) => void;+ toMap: (next: MapViewState) => MapViewState;+ help: boolean;+ setHelp: Dispatch<SetStateAction<boolean>>;+ pendingFrom: string | null;+ setPendingFrom: (id: string | null) => void;+ picker: BetweenPicker;+ setPicker: (picker: BetweenPicker) => void;+ searchRef: RefObject<HTMLInputElement | null>;+}++/** Escape: the help, a pending pick, the picker, the selection, then one level up (on the map only). */+function backOne(c: ShortcutContext): boolean {+ if (c.help) c.setHelp(false);+ else if (c.pendingFrom) c.setPendingFrom(null);+ else if (c.picker.open) c.setPicker({ open: false });+ else if (c.selection) c.clearSelection();+ else {+ const up = c.display === "map" ? backOut(c.view) : null;+ if (!up) return false;+ c.setView(up);+ }+ return true;+}++/**+ * `b`: open the Between picker. With a service selected it is the From, and+ * the next service selected on the map completes the pair as well.+ */+function startBetween(c: ShortcutContext, node: string | null): boolean {+ c.setPendingFrom(node);+ c.setPicker(node ? { open: true, from: node } : { open: true });+ return true;+}++/** What each shortcut does; each returns whether it acted, and a shortcut that did nothing leaves the key alone. */+function shortcutHandlers(c: ShortcutContext): Record<MapShortcut, () => boolean> {+ const node = c.selection?.type === "node" ? c.selection.id : null;+ return {+ search: () => {+ c.searchRef.current?.focus();+ return true;+ },+ help: () => {+ c.setHelp((open) => !open);+ return true;+ },+ list: () => {+ c.setDisplay(c.display === "list" ? "map" : "list");+ return true;+ },+ focus: () => {+ if (node) c.setView(c.toMap(focusService(c.view, node)));+ return node !== null;+ },+ between: () => startBetween(c, node),+ back: () => backOne(c),+ };+}++/** Binds the shortcuts on the window once; the listener reads the latest handlers through a ref. */+function useShortcutKeys(handlers: Record<MapShortcut, () => boolean>): void {+ const live = useRef(handlers);+ live.current = handlers;+ useEffect(() => {+ // Ctrl/Cmd+K searches the map while it is on screen, so the app-wide palette stands down.+ const release = claimCommandPaletteShortcut("system-map");+ const onKeyDown = (e: KeyboardEvent) => {+ const action = shortcutFor(e);+ if (action && live.current[action]()) e.preventDefault();+ };+ window.addEventListener("keydown", onKeyDown);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ release();+ };+ }, []);+}++/**+ * Comparing two services: the picker, the pending `b` pick (the next service+ * selected anywhere completes it; clearing the selection drops it), and the+ * route filter a route search pick hands the routes panel.+ */+function useBetween(state: SystemMapState, toMap: (next: MapViewState) => MapViewState) {+ const { view, setView, selection } = state;+ const [pendingFrom, setPendingFrom] = useState<string | null>(null);+ const [picker, setPicker] = useState<BetweenPicker>({ open: false });+ const [route, setRoute] = useState<{ a: string; b: string; q: string } | null>(null);+ useEffect(() => {+ if (!selection) setPendingFrom(null);+ }, [selection]);+ const onBetween = useCallback(+ (a: string, b: string) => {+ setPendingFrom(null);+ setPicker({ open: false });+ state.setSelection(null);+ setView(toMap(compareServices(view, a, b)));+ },+ [state, setView, view, toMap],+ );+ const setSelection = useCallback(+ (next: SystemMapSelection) => {+ if (pendingFrom && next?.type === "node" && next.id !== pendingFrom) onBetween(pendingFrom, next.id);+ else state.setSelection(next);+ },+ [pendingFrom, state, onBetween],+ );+ const pair = view.between;+ const routeFilter = route && pair?.a === route.a && pair.b === route.b ? route.q : undefined;+ return { pendingFrom, setPendingFrom, picker, setPicker, onBetween, setSelection, setRoute, routeFilter };+}++export function useMapNavigation(state: SystemMapState): MapNavigation {+ const { view, setView } = state;+ const narrow = useNarrowViewport();+ const display: MapDisplay = view.display ?? (narrow ? "list" : "map");+ const [help, setHelp] = useState(false);+ const searchRef = useRef<HTMLInputElement>(null);++ const toMap = useCallback((next: MapViewState) => (display === "list" ? withDisplay(next, "map") : next), [display]);+ const setDisplay = useCallback((d: MapDisplay) => setView(withDisplay(view, d)), [setView, view]);+ const between = useBetween(state, toMap);+ const { setRoute } = between;++ const onSearchPick = useCallback(+ (hit: SearchHit) => {+ // A route opens the comparison with its routes panel filtered to that route.+ setRoute(hit.kind === "route" && hit.consumer ? { a: hit.consumer, b: hit.provider, q: hit.label } : null);+ state.setSelection(null);+ setView(toMap(pickToView(view, hit)));+ },+ [setRoute, state, setView, view, toMap],+ );++ const ctx: ShortcutContext = {+ view,+ setView,+ selection: state.selection,+ clearSelection: () => state.setSelection(null),+ display,+ setDisplay,+ toMap,+ help,+ setHelp,+ pendingFrom: between.pendingFrom,+ setPendingFrom: between.setPendingFrom,+ picker: between.picker,+ setPicker: between.setPicker,+ searchRef,+ };+ useShortcutKeys(shortcutHandlers(ctx));++ return {+ display,+ setDisplay,+ toMap,+ pendingFrom: between.pendingFrom,+ setSelection: between.setSelection,+ picker: between.picker,+ setPicker: between.setPicker,+ onBetween: between.onBetween,+ routeFilter: between.routeFilter,+ help,+ setHelp,+ searchRef,+ onSearchPick,+ back: () => backOne(ctx),+ };+}diff --git a/packages/ui/src/workspace/system-map/use-map-verbs.ts b/packages/ui/src/workspace/system-map/use-map-verbs.tsnew file mode 100644index 000000000..9b134e36a--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-map-verbs.ts@@ -0,0 +1,69 @@+"use client";++/**+ * What the reader can do to the map from a card, a connector or the rail:+ * select, open a group, focus a service, list what a "+N more" card folded,+ * and the rail's verbs (focus, routes to..., compare, show a family, leave+ * the comparison). Comparing goes through the navigation's one `onBetween`.+ */++import { useCallback, useMemo } from "react";+import { activateEdge, activateNode, type Activation, type ActivateTrigger } from "./activate";+import type { LevelView } from "./levels";+import type { SystemMapActions } from "./system-map-actions";+import type { RailVerbs } from "./system-map-rail-content";+import type { MapNavigation } from "./use-map-navigation";+import type { SystemMapState } from "./use-system-map-state";+import { closeContainer, focusService, openContainer, showFamily } from "./view-state";++/** Card verbs and the canvas's activate handler, over the level state and the selection. */+export function useMapInput(+ levelView: LevelView | null,+ state: SystemMapState,+ onShowFolded: ((serviceIds: readonly string[]) => void) | undefined,+) {+ const { view, setView, setSelection } = state;+ const actions = useMemo<SystemMapActions>(+ () => ({+ openContainer: (id) => setView(openContainer(view, id)),+ closeContainer: (id) => setView(closeContainer(view, id)),+ showFolded: onShowFolded,+ }),+ [setView, view, onShowFolded],+ );+ const apply = useCallback(+ (a: Activation) => {+ if (a?.kind === "select") setSelection(a.selection);+ else if (a?.kind === "open") actions.openContainer(a.id);+ else if (a?.kind === "focus") setView(focusService(view, a.serviceId));+ else if (a?.kind === "folded") actions.showFolded?.(a.serviceIds);+ },+ [setSelection, actions, setView, view],+ );+ const onActivate = useCallback(+ (id: string, kind: "node" | "edge", trigger: ActivateTrigger) =>+ apply(+ kind === "edge"+ ? activateEdge(levelView?.edges.find((e) => e.id === id))+ : activateNode(levelView?.nodes.find((n) => n.id === id), trigger),+ ),+ [apply, levelView],+ );+ return { actions, onActivate };+}++/** The verbs the rail offers. */+export function useRailVerbs(state: SystemMapState, nav: MapNavigation): RailVerbs {+ const { view, setView } = state;+ const { setPicker, onBetween, toMap } = nav;+ return useMemo<RailVerbs>(+ () => ({+ onFocus: (id) => setView(toMap(focusService(view, id))),+ onRoutesFrom: (id) => setPicker({ open: true, from: id }),+ onBetween,+ onShowFamily: (f) => setView(showFamily(view, f)),+ onLeaveBetween: () => setView({ ...view, between: null }),+ }),+ [view, setView, setPicker, onBetween, toMap],+ );+}diff --git a/packages/ui/src/workspace/system-map/use-system-map-search.ts b/packages/ui/src/workspace/system-map/use-system-map-search.tsnew file mode 100644index 000000000..326e5c5bf--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-system-map-search.ts@@ -0,0 +1,118 @@+"use client";++/**+ * Search state for the map's combobox, on the `useGraphSearch` pattern: a+ * debounced query, Fuse over services and groups, routes through the host's+ * loader, and arrow / Enter / Escape over one flat result list. Picking a+ * result hands the level it lands on to `onPick` and clears the box.+ */++import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";+import type { SystemGraph } from "@repowise-dev/types";+import { useDebounce } from "../../hooks/use-debounce";+import {+ SEARCH_MIN_CHARS,+ buildSearchIndex,+ routeHits,+ searchMap,+ type SearchHit,+ type SystemMapRouteLoader,+} from "./search-index";++const DEBOUNCE_MS = 150;++export interface MapSearch {+ query: string;+ setQuery: (q: string) => void;+ hits: SearchHit[];+ /** Index into `hits` of the highlighted result. */+ active: number;+ routesLoading: boolean;+ pick: (hit: SearchHit) => void;+ onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;+}++/** Routes for the debounced query; stale answers are dropped, a failed load is no routes. */+function useRouteHits(graphIndex: ReturnType<typeof buildSearchIndex> | null, query: string, load?: SystemMapRouteLoader) {+ const [state, setState] = useState<{ query: string; hits: SearchHit[] }>({ query: "", hits: [] });+ const asked = useRef("");+ useEffect(() => {+ asked.current = query;+ if (!load || !graphIndex || query.length < SEARCH_MIN_CHARS) return;+ // Through a resolved promise, so a loader that throws synchronously still reads as no routes.+ Promise.resolve()+ .then(() => load(query))+ .then((links) => routeHits(links, graphIndex.resolve))+ .catch(() => [] as SearchHit[])+ .then((hits) => {+ if (asked.current === query) setState({ query, hits });+ });+ }, [load, graphIndex, query]);+ const current = state.query === query;+ return {+ hits: current ? state.hits : [],+ loading: Boolean(load) && query.length >= SEARCH_MIN_CHARS && !current,+ };+}++/** The highlighted result after an arrow key, wrapping at both ends. */+function stepIndex(current: number, step: 1 | -1, count: number): number {+ if (count === 0) return 0;+ return (Math.min(current, count - 1) + step + count) % count;+}++export function useSystemMapSearch(+ graph: SystemGraph | null,+ onPick: (hit: SearchHit) => void,+ loadRoutes?: SystemMapRouteLoader,+): MapSearch {+ const [query, setQueryState] = useState("");+ const [active, setActive] = useState(0);+ const debounced = useDebounce(query.trim(), DEBOUNCE_MS);+ const index = useMemo(() => (graph ? buildSearchIndex(graph) : null), [graph]);+ const local = useMemo(() => (index ? searchMap(index, debounced) : []), [index, debounced]);+ const routes = useRouteHits(index, debounced, loadRoutes);+ const hits = useMemo(() => [...local, ...routes.hits], [local, routes.hits]);++ const setQuery = useCallback((q: string) => {+ setQueryState(q);+ setActive(0);+ }, []);+ const pick = useCallback(+ (hit: SearchHit) => {+ setQuery("");+ onPick(hit);+ },+ [onPick, setQuery],+ );+ const settled = query.trim() === debounced;+ const onKeyDown = useCallback(+ (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Escape") {+ // The first Escape clears the box, the next leaves it.+ e.preventDefault();+ if (query) setQuery("");+ else e.currentTarget.blur();+ } else if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ setActive((i) => stepIndex(i, e.key === "ArrowDown" ? 1 : -1, hits.length));+ } else if (e.key === "Enter") {+ e.preventDefault();+ // Results still belong to the text before the last keystroke; wait for them.+ const hit = settled ? hits[Math.min(active, hits.length - 1)] : undefined;+ if (hit) pick(hit);+ }+ },+ [hits, active, pick, query, setQuery, settled],+ );++ return {+ query,+ setQuery,+ hits,+ active: Math.min(active, Math.max(hits.length - 1, 0)),+ routesLoading: routes.loading,+ pick,+ onKeyDown,+ };+}diff --git a/packages/ui/src/workspace/system-map/view-state.ts b/packages/ui/src/workspace/system-map/view-state.tsindex b81a56bdc..577c03ae7 100644--- a/packages/ui/src/workspace/system-map/view-state.ts+++ b/packages/ui/src/workspace/system-map/view-state.ts@@ -3,7 +3,8 @@* is focused, which two services are compared, and which edge families are* drawn. A host keeps it in its URL (`open`, `focus`, `a`, `b`, `kinds`);* this module reads and writes those params and steps between levels, so- * every host walks the levels the same way. Pure, no React.+ * every host walks the levels the same way. The Map | List display rides+ * along as `view` (absent is the default). Pure, no React.*/import { DEFAULT_EDGE_FAMILIES, EDGE_FAMILY_ORDER, type EdgeFamily } from "./edge-families";@@ -21,12 +22,16 @@ export interface MapViewState {between: { a: string; b: string } | null;/** Families drawn; null is the default (Runtime and Data). */families: readonly EdgeFamily[] | null;+ /** Map or the services table; absent is the default (the map, the table on phones). */+ display?: MapDisplay;}+export type MapDisplay = "map" | "list";+export const ESTATE_VIEW: MapViewState = { open: [], focus: null, between: null, families: null };/** The URL params the map state owns. */-export const MAP_VIEW_PARAMS = ["open", "focus", "a", "b", "kinds"] as const;+export const MAP_VIEW_PARAMS = ["open", "focus", "a", "b", "kinds", "view"] as const;const KNOWN_FAMILIES: ReadonlySet<string> = new Set(EDGE_FAMILY_ORDER);@@ -45,11 +50,13 @@ export function parseMapView(get: (key: string) => string | null): MapViewStateconst families = list(get("kinds")).filter((f): f is EdgeFamily => KNOWN_FAMILIES.has(f));const a = get("a");const b = get("b");+ const display = get("view");return {open: list(get("open")),focus: get("focus") || null,between: a && b && a !== b ? { a, b } : null,families: families.length > 0 ? EDGE_FAMILY_ORDER.filter((f) => families.includes(f)) : null,+ ...(display === "map" || display === "list" ? { display } : {}),};}@@ -69,6 +76,7 @@ export function writeMapView(params: URLSearchParams, state: MapViewState): voidif (state.families && !sameFamilies(state.families, DEFAULT_EDGE_FAMILIES)) {params.set("kinds", EDGE_FAMILY_ORDER.filter((f) => state.families!.includes(f)).join(","));}+ if (state.display) params.set("view", state.display);}/** The families a state draws, as the levels model takes them. */@@ -124,7 +132,22 @@ export function backOut(state: MapViewState): MapViewState | null {/** The estate with the same families drawn: the breadcrumb's root. */export function toEstate(state: MapViewState): MapViewState {- return { ...ESTATE_VIEW, families: state.families };+ return { ...ESTATE_VIEW, families: state.families, ...(state.display ? { display: state.display } : {}) };+}++/** Focus one service (the focus level), leaving any comparison. */+export function focusService(state: MapViewState, id: string): MapViewState {+ return { ...state, focus: id, between: null };+}++/** Compare two services (the between level); the same id twice is no comparison. */+export function compareServices(state: MapViewState, a: string, b: string): MapViewState {+ return a === b ? state : { ...state, between: { a, b } };+}++/** Show the map or the services table. */+export function withDisplay(state: MapViewState, display: MapDisplay): MapViewState {+ return { ...state, display };}export function sameMapView(x: MapViewState, y: MapViewState): boolean {@@ -133,6 +156,7 @@ export function sameMapView(x: MapViewState, y: MapViewState): boolean {x.focus === y.focus &&x.between?.a === y.between?.a &&x.between?.b === y.between?.b &&- [...drawnFamilies(x)].sort().join(",") === [...drawnFamilies(y)].sort().join(",")+ [...drawnFamilies(x)].sort().join(",") === [...drawnFamilies(y)].sort().join(",") &&+ x.display === y.display);}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 14b22932e..96c367c2a 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -2054,6 +2054,47 @@"unmatched": "Unmatched consumers","unmatchedSub": "calls with no provider in the workspace","unmatchedHint": "Consumer contracts that matched no provider: missing, or a third-party host. Calls a repository makes to its own service are served and not counted."+ },+ "nav": {+ "searchLabel": "Search services, groups and routes",+ "searchPlaceholder": "Search the map",+ "searchServices": "Services",+ "searchGroups": "Groups",+ "searchRoutes": "Routes",+ "searchNone": "Nothing matches",+ "searchRoutesLoading": "Searching routes",+ "routeCaller": "{consumer} calls it",+ "routeCallers": "{consumer} and {others} more call it",+ "routeProvider": "served by {provider}",+ "displayLabel": "Display",+ "displayMap": "Map",+ "displayList": "List",+ "helpOpen": "Keyboard shortcuts",+ "helpTitle": "System map keyboard shortcuts",+ "keySearch": "Search services, groups and routes",+ "keyBack": "Close details, then go back a level",+ "keyFocus": "Focus the selected service",+ "keyBetween": "Compare two services, starting from the selected one",+ "keyList": "Switch between the map and the list",+ "keyHelp": "Show or hide this help",+ "keySteps": "Step through search results",+ "keyPick": "Go to the highlighted result",+ "listCaption": "Services in the estate, one row each",+ "colService": "Service",+ "colGroup": "Group",+ "colHealth": "Health",+ "colIn": "Runtime in",+ "colOut": "Runtime out",+ "colContracts": "Contracts",+ "noScore": "No score",+ "contractsCell": "{provided} provided · {consumed} consumed",+ "announceEstate": "Estate: {services, plural, one {# service} other {# services}}",+ "announceEstateGrouped": "Estate: {groups, plural, one {# group} other {# groups}}, {services, plural, one {# service} other {# services}}",+ "announceGroup": "{label} opened: {services, plural, one {# service} other {# services}}",+ "announceFocus": "Focused on {name}: {callers, plural, one {# caller} other {# callers}}, {dependencies, plural, one {# dependency} other {# dependencies}}",+ "announceBetween": "Showing the links between {a} and {b}",+ "announceList": "List view: {services, plural, one {# service} other {# services}}",+ "announcePick": "Pick a second service to compare with {name}"}},"linkCoverage": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex d126816dc..84c6312d9 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -2054,6 +2054,47 @@"unmatched": "未匹配的消费方","unmatchedSub": "工作区内没有提供方的调用","unmatchedHint": "没有匹配到提供方的消费方契约:缺失,或属于第三方主机。仓库对自身服务的调用已有提供方,不计入。"+ },+ "nav": {+ "searchLabel": "搜索服务、分组和路由",+ "searchPlaceholder": "搜索地图",+ "searchServices": "服务",+ "searchGroups": "分组",+ "searchRoutes": "路由",+ "searchNone": "没有匹配项",+ "searchRoutesLoading": "正在搜索路由",+ "routeCaller": "{consumer} 调用它",+ "routeCallers": "{consumer} 和另外 {others} 个服务调用它",+ "routeProvider": "由 {provider} 提供",+ "displayLabel": "显示",+ "displayMap": "地图",+ "displayList": "列表",+ "helpOpen": "键盘快捷键",+ "helpTitle": "系统地图键盘快捷键",+ "keySearch": "搜索服务、分组和路由",+ "keyBack": "关闭详情,然后返回上一层",+ "keyFocus": "聚焦所选服务",+ "keyBetween": "比较两个服务,从所选服务开始",+ "keyList": "在地图和列表之间切换",+ "keyHelp": "显示或隐藏此帮助",+ "keySteps": "逐个浏览搜索结果",+ "keyPick": "前往高亮的结果",+ "listCaption": "工作区中的服务,每行一个",+ "colService": "服务",+ "colGroup": "分组",+ "colHealth": "健康度",+ "colIn": "运行时调入",+ "colOut": "运行时调出",+ "colContracts": "契约",+ "noScore": "无评分",+ "contractsCell": "提供 {provided} · 使用 {consumed}",+ "announceEstate": "服务全景:{services, plural, other {# 个服务}}",+ "announceEstateGrouped": "服务全景:{groups, plural, other {# 个分组}},{services, plural, other {# 个服务}}",+ "announceGroup": "已展开 {label}:{services, plural, other {# 个服务}}",+ "announceFocus": "聚焦于 {name}:{callers, plural, other {# 个调用方}},{dependencies, plural, other {# 个依赖}}",+ "announceBetween": "显示 {a} 与 {b} 之间的链接",+ "announceList": "列表视图:{services, plural, other {# 个服务}}",+ "announcePick": "再选择一个服务,与 {name} 比较"}},"linkCoverage": {diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex 27c926edb..eb540d713 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -44,6 +44,7 @@ import { markSystemMap, useSystemMapPerfMarks } from "@/lib/system-map-perf";import { mapLede, mapRibbon, useListJoin, type Translator } from "./map-summary";import { useRepoContracts } from "./use-repo-contracts";import { useServiceLinks } from "./use-service-links";+import { loadRouteLinks, useSystemMapNavCopy } from "./use-system-map-nav";const LENSES: readonly SystemMapLens[] = ["none", "blast", "breaking", "conformance", "core"];/** URL params a selection is written to, one per selection type. */@@ -62,6 +63,7 @@ function contractsHref(repo: string): string {export default function SystemMapPage() {const t = useTranslations("systemMap");const tLinks = useTranslations("linkCoverage");+ const navCopy = useSystemMapNavCopy();const join = useListJoin();const router = useRouter();const searchParams = useSearchParams();@@ -258,6 +260,8 @@ export default function SystemMapPage() {onPhase={markSystemMap}drawer={drawer}loadLinksBetween={loadLinksBetween}+ loadRoutes={loadRouteLinks}+ navCopy={navCopy}toolbar={<SystemMapLensControlvalue={lens}diff --git a/packages/web/src/app/workspace/system-map/use-system-map-nav.ts b/packages/web/src/app/workspace/system-map/use-system-map-nav.tsnew file mode 100644index 000000000..ad9f8047a--- /dev/null+++ b/packages/web/src/app/workspace/system-map/use-system-map-nav.ts@@ -0,0 +1,64 @@+"use client";++import { useMemo } from "react";+import { useTranslations } from "next-intl";+import type { SystemMapNavCopy, SystemMapRouteLoader } from "@repowise-dev/ui/workspace/system-map";+import { getWorkspaceContracts } from "@/lib/api/workspace";++/**+ * Route search for the map: the contract links matching every term. Only the+ * links are read, so one contract row is enough. Ceiling: the endpoint sends+ * every matching link; a short query on a very large estate wants a link+ * limit on the endpoint.+ */+export const loadRouteLinks: SystemMapRouteLoader = async (q) =>+ (await getWorkspaceContracts({ q, limit: 1 })).links;++/** The map's navigation words from the catalog. */+export function useSystemMapNavCopy(): SystemMapNavCopy {+ const t = useTranslations("systemMap.nav");+ return useMemo(+ () => ({+ searchLabel: t("searchLabel"),+ searchPlaceholder: t("searchPlaceholder"),+ searchServices: t("searchServices"),+ searchGroups: t("searchGroups"),+ searchRoutes: t("searchRoutes"),+ searchNone: t("searchNone"),+ searchRoutesLoading: t("searchRoutesLoading"),+ routeCallers: (consumer, others) =>+ others > 0 ? t("routeCallers", { consumer, others }) : t("routeCaller", { consumer }),+ routeProvider: (provider) => t("routeProvider", { provider }),+ displayLabel: t("displayLabel"),+ displayMap: t("displayMap"),+ displayList: t("displayList"),+ helpOpen: t("helpOpen"),+ helpTitle: t("helpTitle"),+ keySearch: t("keySearch"),+ keyBack: t("keyBack"),+ keyFocus: t("keyFocus"),+ keyBetween: t("keyBetween"),+ keyList: t("keyList"),+ keyHelp: t("keyHelp"),+ keySteps: t("keySteps"),+ keyPick: t("keyPick"),+ listCaption: t("listCaption"),+ colService: t("colService"),+ colGroup: t("colGroup"),+ colHealth: t("colHealth"),+ colIn: t("colIn"),+ colOut: t("colOut"),+ colContracts: t("colContracts"),+ noScore: t("noScore"),+ contractsCell: (provided, consumed) => t("contractsCell", { provided, consumed }),+ announceEstate: (services, groups) =>+ groups > 0 ? t("announceEstateGrouped", { services, groups }) : t("announceEstate", { services }),+ announceGroup: (label, services) => t("announceGroup", { label, services }),+ announceFocus: (name, callers, dependencies) => t("announceFocus", { name, callers, dependencies }),+ announceBetween: (a, b) => t("announceBetween", { a, b }),+ announceList: (services) => t("announceList", { services }),+ announcePick: (name) => t("announcePick", { name }),+ }),+ [t],+ );+}