diff --git a/client/e2e/capabilities.spec.ts b/client/e2e/capabilities.spec.ts index c5d8e03a..c33c0260 100644 --- a/client/e2e/capabilities.spec.ts +++ b/client/e2e/capabilities.spec.ts @@ -35,7 +35,7 @@ function makeRepo(withMap: boolean): string { const files: Record = { "src/editor.ts": Array.from({ length: 40 }, (_, i) => `export const e${i} = ${i};`).join("\n") + "\n", "src/editor.test.ts": `import { e1 } from "./editor";\ntest("saves", () => expect(e1).toBe(1));\n`, - "src/export.ts": Array.from({ length: 20 }, (_, i) => `export const x${i} = ${i};`).join("\n") + "\n", + "src/export.ts": Array.from({ length: 200 }, (_, i) => `export const x${i} = ${i};`).join("\n") + "\n", "src/legacy.ts": "export const old = 1;\n", }; if (withMap) files["docs/capabilities/notes.yaml"] = AREA; @@ -73,9 +73,68 @@ test("a repo with a map opens on its capabilities; one without keeps the treemap await expect(page).toHaveURL(/cap=note-export/); await page.screenshot({ path: path.join(SHOTS, "capabilities.png") }); + // The rail at rest ranks the weak capability first; the weak filter and search keep it lit. + await page.keyboard.press("Escape"); + await expect(page.locator("[data-cap-weakest]")).toContainText("Export a note"); + await page.locator('[data-cap-weak="none"]').click(); + await expect(page.locator('[data-capability="note-editor"]')).toHaveClass(/cap-dim/); + await expect(page.locator('[data-capability="note-export"]')).not.toHaveClass(/cap-dim/); + await page.locator('[data-cap-weak="none"]').click(); + await page.keyboard.press("/"); + await page.keyboard.type("editor.ts"); + await expect(page.locator('[data-capability="note-export"]')).toHaveClass(/cap-dim/); + await page.keyboard.press("Enter"); + await expect(page.locator('[data-cap-detail="note-editor"]')).toBeVisible(); + + // An area with no code of its own is a search result too. + await page.locator("[data-cap-search] input").fill("Write and read notes"); + await expect(page.locator("[data-cap-matches]")).toHaveText("1"); + await page.keyboard.press("Enter"); + await expect(page.locator('[data-cap-detail="notes"]')).toBeVisible(); + await page.locator("[data-cap-search] input").fill(""); + + // An unclaimed folder tile opens that folder's files. + await page.locator('[data-cap-folder="src"]').click(); + await expect(page.locator('[data-cap-detail="unclaimed:src"]')).toContainText("legacy.ts"); + + // Back follows the URL: the previous selection comes back in the rail. + await page.locator('[data-capability="note-export"]').click(); + await page.locator('[data-view-option="treemap"]').click(); + await page.goBack(); + await expect(page.locator('[data-cap-detail="note-export"]')).toBeVisible(); + + // Picking Treemap on a mapped repo is kept in the URL, so a reload (or a shared link) stays there. + await page.locator('[data-view-option="treemap"]').click(); + await expect(page).toHaveURL(/view=treemap/); + await page.reload(); + await expect(page.locator('[data-view-option="treemap"]')).toHaveAttribute("aria-checked", "true", { timeout: 60_000 }); + await page.locator('[data-view-option="capabilities"]').click(); + await expect(page.locator('[data-view="capabilities"]')).toHaveAttribute("data-cap-status", "checked"); + const plain = makeRepo(false); await page.goto(`/?${new URLSearchParams({ repo: plain })}`); await expect(page.locator('[data-view-option="treemap"]')).toHaveAttribute("aria-checked", "true", { timeout: 60_000 }); await expect(page.locator('[data-view-option="capabilities"]')).toHaveCount(0); expect(errors).toEqual([]); }); + +test("narrow views open the overview on demand, and a failed map request says so", async ({ page }) => { + const mapped = makeRepo(true); + await page.setViewportSize({ width: 1100, height: 800 }); + await page.goto(`/?${new URLSearchParams({ repo: mapped, view: "capabilities" })}`); + await expect(page.locator('[data-view="capabilities"]')).toHaveAttribute("data-cap-status", "checked", { timeout: 60_000 }); + // The explorer takes part of the width, so the view is under 980 px: the rail waits for a click. + await expect(page.locator("[data-cap-overview]")).toHaveCount(0); + await page.locator("[data-cap-rail-toggle]").click(); + await expect(page.locator("[data-cap-weakest]")).toContainText("Export a note"); + await expect(page.locator("[data-cap-errors]")).toContainText("note-export"); + + // A request that fails: an explicit Capabilities URL stays and names the failure; a plain URL shows the treemap. + await page.route("**/api/capabilities**", (route) => route.abort()); + await page.goto(`/?${new URLSearchParams({ repo: mapped, view: "capabilities" })}`); + await expect(page.locator('[data-view="capabilities"]')).toHaveAttribute("data-cap-status", "unavailable", { timeout: 60_000 }); + await expect(page.locator('[data-view="capabilities"]')).toContainText("could not be read"); + await page.goto(`/?${new URLSearchParams({ repo: mapped })}`); + await expect(page.locator('[data-view-option="treemap"]')).toHaveAttribute("aria-checked", "true", { timeout: 60_000 }); + await expect(page.locator('[data-view-option="capabilities"]')).toHaveCount(0); +}); diff --git a/client/src/components/Treemap.tsx b/client/src/components/Treemap.tsx index 3bd88191..5df10f04 100644 --- a/client/src/components/Treemap.tsx +++ b/client/src/components/Treemap.tsx @@ -73,26 +73,26 @@ export default function Treemap(props: TreemapProps) { const showCapabilities = () => location().view === "capabilities"; // Until the map's status is known, a URL with no view could still land on Capabilities: // hold the treemap canvas (under a second) instead of flashing it and switching away. - const viewAsked = new URLSearchParams(window.location.search).has("view"); - const deciding = () => !viewAsked && !capMap() && capabilities.state !== "errored" && location().view === "treemap"; + const deciding = () => !location().pinned && !capMap() && capabilities.state !== "errored" && location().view === "treemap"; const covered = () => showDependencyGraph() || showScatter() || showChanges() || showCapabilities() || deciding(); // The capabilities map (docs/capabilities/*.yaml), read again with each new scan of the root. + // Keyed on the root, not the filtered tree: an Explorer filter that matches nothing must not stall it. const [capabilities] = createResource( - () => (props.data ? { root: props.rootPath, data: props.data } : null), - ({ root }) => fetchCapabilities(root), + () => props.rootPath || null, + (root) => fetchCapabilities(root), ); // Read the value only once it exists: a first read of a resource suspends the boundary above it. const capMap = () => (capabilities.state === "ready" || capabilities.state === "refreshing" ? capabilities.latest : undefined); const hasCapabilities = () => capMap()?.status === "checked"; // A repo with a map opens on it, unless the URL already names a view; one without stays on the treemap. - let landed = false; + let landedFor = ""; createEffect(() => { const map = capMap(); - if (!map || landed) return; - landed = true; - const asked = new URLSearchParams(window.location.search).has("view"); - if (map.status === "checked" && !asked && location().view === "treemap") replace({ view: "capabilities" }); - else if (map.status !== "checked" && location().view === "capabilities") replace({ view: "treemap" }); + if (!map || landedFor === props.rootPath) return; + landedFor = props.rootPath; + if (map.status === "checked" && !location().pinned && location().view === "treemap") replace({ view: "capabilities" }); + // Only a confirmed missing map leaves an explicit Capabilities URL; a failed request stays and says why. + else if (map.status === "no-map" && location().view === "capabilities") replace({ view: "treemap" }); }); const [menu, setMenu] = createSignal(null); @@ -272,7 +272,7 @@ export default function Treemap(props: TreemapProps) { showMetricPopover={showMetricPopover} setShowMetricPopover={setShowMetricPopover} view={() => location().view} - onViewChange={(view) => go({ view })} + onViewChange={(view) => go({ view, pinned: view === "treemap" })} hasCapabilities={hasCapabilities} /> diff --git a/client/src/navigation/location.test.ts b/client/src/navigation/location.test.ts index 0d191e26..0fc173ce 100644 --- a/client/src/navigation/location.test.ts +++ b/client/src/navigation/location.test.ts @@ -28,7 +28,9 @@ describe("parseLocation / toSearch", () => { expect(parseLocation(toSearch(picking))).toEqual(picking); // Imports mode has no flow param, and the treemap ignores one. expect(parseLocation(toSearch({ ...loc, flow: undefined }))).toEqual({ repo: "/r", at: "", view: "graph" }); - expect(parseLocation("?view=treemap&flow=route:abc")).toEqual({ repo: "", at: "", view: "treemap" }); + // An explicit view=treemap is a pinned choice (it outranks the capabilities landing view). + expect(parseLocation("?view=treemap&flow=route:abc")).toEqual({ repo: "", at: "", view: "treemap", pinned: true }); + expect(toSearch(parseLocation("?view=treemap"))).toBe("?view=treemap"); }); it("round-trips a selected origin and destination, which never make a new place", () => { @@ -56,7 +58,7 @@ describe("parseLocation / toSearch", () => { it("reads the legacy depFocus alias as the graph view", () => { expect(parseLocation("?depFocus=server%2Fapp")).toEqual({ repo: "", at: "server/app", view: "graph" }); expect(parseLocation("?depFocus=%2F")).toEqual({ repo: "", at: "", view: "graph" }); - expect(parseLocation("?depFocus=a&at=b&view=treemap")).toEqual({ repo: "", at: "b", view: "treemap" }); + expect(parseLocation("?depFocus=a&at=b&view=treemap")).toEqual({ repo: "", at: "b", view: "treemap", pinned: true }); }); it("keeps foreign params and drops the legacy one", () => { @@ -209,7 +211,7 @@ describe("anchor mode", () => { expect(search).not.toContain("flow="); // A broken anchor is ignored; the treemap ignores both. expect(parseLocation("?view=graph&anchor=nonsense")).toEqual({ repo: "", at: "", view: "graph" }); - expect(parseLocation(`?view=treemap&anchor=${anchor}&dir=forward`)).toEqual({ repo: "", at: "", view: "treemap" }); + expect(parseLocation(`?view=treemap&anchor=${anchor}&dir=forward`)).toEqual({ repo: "", at: "", view: "treemap", pinned: true }); // The direction and the anchor are part of the place: a new anchor is a new history entry, a new direction is not. const a = { repo: "", at: "", view: "graph" as const, anchor }; expect(samePlace(a, { ...a, anchor: "src/b.tsx:1:1-1:2" })).toBe(false); diff --git a/client/src/navigation/location.ts b/client/src/navigation/location.ts index a24aedb8..0694355f 100644 --- a/client/src/navigation/location.ts +++ b/client/src/navigation/location.ts @@ -19,6 +19,11 @@ export interface Location { repo: string; at: string; view: View; + /** + * The person picked the treemap themselves (`view=treemap` in the URL). A repo with a + * capabilities map otherwise lands on the Capabilities view; this keeps the choice in links. + */ + pinned?: boolean; /** * Graph only: folders and files opened in place (graph ids, which are `at` * values). Kept across focus changes, so a mixed-scale cut survives a drill. @@ -180,6 +185,7 @@ export function parseLocation(search: string): Location { repo: params.get(REPO_PARAM) ?? "", at: normalizeAt(rawAt), view, + ...(view === "treemap" && rawView === "treemap" ? { pinned: true } : {}), ...(open.length ? { open } : {}), ...(flow !== null ? { flow } : {}), ...(field ? { field } : {}), @@ -223,7 +229,7 @@ export function toSearch(loc: Location, currentSearch = ""): string { if (loc.view === "changes" && loc.changes) for (const [key, value] of new URLSearchParams(loc.changes)) params.set(key, value); if (loc.repo) params.set(REPO_PARAM, loc.repo); if (loc.at) params.set(AT_PARAM, loc.at); - if (loc.view !== "treemap") params.set(VIEW_PARAM, loc.view); + if (loc.view !== "treemap" || loc.pinned) params.set(VIEW_PARAM, loc.view); if (loc.open?.length) params.set(OPEN_PARAM, loc.open.join(",")); if (loc.view === "graph" && loc.anchor) { params.set(ANCHOR_PARAM, loc.anchor); diff --git a/client/src/viz/capabilities/CapabilitiesView.tsx b/client/src/viz/capabilities/CapabilitiesView.tsx index 15b01fa0..472d1301 100644 --- a/client/src/viz/capabilities/CapabilitiesView.tsx +++ b/client/src/viz/capabilities/CapabilitiesView.tsx @@ -1,20 +1,30 @@ -import { For, Show, createMemo, createSignal, onCleanup, onMount } from "solid-js"; -import { ChevronRight, FileCode, FlaskConical } from "lucide-solid"; +import { For, Show, createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js"; +import { Portal } from "solid-js/web"; +import { ChevronRight, FlaskConical, PanelRight, Search, X } from "lucide-solid"; import { ViewTools } from "../viewToolbar"; -import { Button } from "../../components/ui/Button"; import { LEVEL_STYLE, - TEST_LEVELS, UNCLAIMED, + WEAK_LEVELS, + isWeak, layout, + matches, testLevel, + unclaimedGroups, + weakest, type CapMap, type CapNode, type CapRef, + type TestLevel, } from "./model"; const fmt = (n: number) => Math.round(n).toLocaleString("en-US"); -const LABEL_PX = 18; +const LABEL_PX = 22; +/** Below this view width the rail leaves the layout and opens over the map. */ +const NARROW_PX = 980; +const HOVER_OPEN_MS = 420; +/** The scale end of the small test bars: 50 linked test lines per 100 LOC fills one. */ +const BAR_FULL = 50; function readParam(name: string): string | null { return new URLSearchParams(window.location.search).get(name); @@ -28,19 +38,44 @@ function writeParam(name: string, value: string | null) { window.history.replaceState(window.history.state, "", `${window.location.pathname}?${params}${window.location.hash}`); } +const folderOfUnclaimed = (id: string) => (id.startsWith(`${UNCLAIMED}:`) ? id.slice(UNCLAIMED.length + 1) : null); + +function splitPath(path: string): [string, string] { + const i = path.lastIndexOf("/"); + return i < 0 ? ["", path] : [path.slice(0, i + 1), path.slice(i + 1)]; +} + +/** How a node's tests read in one line. */ +function testsLine(n: CapNode): string { + const level = testLevel(n); + if (level === "group") return "No code of its own"; + if (level === "none") return n.tests.linked ? "Its linked tests do not resolve" : "No linked test"; + return `${n.tests.lines_per_100_loc} test lines per 100 LOC`; +} + /** - * The snapshot view of a repo's capabilities map: each product area is a box of its - * capabilities, sized by allocated LOC and colored by how much test code each links. A click - * selects a capability and the rail shows its promise, files and tests; an area's label zooms in. + * The snapshot view of a repo's capabilities map. Each product area is a box of its capabilities, + * sized by allocated LOC. Only weak tests get color, so they stand out at a glance. Hover a + * capability for its promise; click it for its files and tests in the rail. An area's label zooms in. */ export default function CapabilitiesView(props: { map: CapMap | undefined; onOpenAt: (at: string, line?: number) => void; }) { - let box: HTMLDivElement | undefined; + let canvas: HTMLDivElement | undefined; + let root: HTMLDivElement | undefined; + let searchInput: HTMLInputElement | undefined; const [size, setSize] = createSignal({ w: 0, h: 0 }); + const [viewWidth, setViewWidth] = createSignal(1600); const [zoom, setZoomSignal] = createSignal(readParam("capzoom")); const [selected, setSelectedSignal] = createSignal(readParam("cap")); + const [query, setQuery] = createSignal(""); + const [weakOnly, setWeakOnly] = createSignal<"thin" | "none" | null>(null); + const [hover, setHover] = createSignal<{ id: string; rect: DOMRect } | null>(null); + /** Narrow views: the rail is shown over the map on demand (always when something is selected). */ + const [railShown, setRailShown] = createSignal(false); + let hoverTimer: number | undefined; + const setZoom = (id: string | null) => { setZoomSignal(id); writeParam("capzoom", id); @@ -48,13 +83,44 @@ export default function CapabilitiesView(props: { const select = (id: string | null) => { setSelectedSignal(id); writeParam("cap", id); + setHover(null); + if (id === null) setRailShown(false); }; onMount(() => { - if (!box) return; - const ro = new ResizeObserver(([e]) => e && setSize({ w: e.contentRect.width, h: e.contentRect.height })); - ro.observe(box); - onCleanup(() => ro.disconnect()); + const ro = new ResizeObserver(() => { + if (canvas) setSize({ w: canvas.clientWidth, h: canvas.clientHeight }); + if (root) setViewWidth(root.clientWidth); + }); + if (canvas) ro.observe(canvas); + if (root) ro.observe(root); + const onKey = (e: KeyboardEvent) => { + const typing = e.target instanceof HTMLElement && e.target.closest("input, textarea, [contenteditable]"); + if (e.key === "/" && !typing) { + e.preventDefault(); + searchInput?.focus(); + } else if (e.key === "Escape") { + if (query()) setQuery(""); + else if (weakOnly()) setWeakOnly(null); + else if (selected()) select(null); + else if (zoom()) setZoom(null); + else return; + if (typing) (e.target as HTMLElement).blur(); + } + }; + // Back and Forward restore the URL; follow it, so the rail and zoom match. + const onPop = () => { + setSelectedSignal(readParam("cap")); + setZoomSignal(readParam("capzoom")); + }; + window.addEventListener("keydown", onKey); + window.addEventListener("popstate", onPop); + onCleanup(() => { + ro.disconnect(); + window.removeEventListener("popstate", onPop); + window.removeEventListener("keydown", onKey); + window.clearTimeout(hoverTimer); + }); }); const byId = createMemo(() => new Map((props.map?.nodes ?? []).map((n) => [n.id, n]))); @@ -68,6 +134,7 @@ export default function CapabilitiesView(props: { if (!m || m.status !== "checked" || w < 10 || h < 10) return null; return layout(m, focus(), w, h, LABEL_PX); }); + const narrow = () => viewWidth() < NARROW_PX; const current = (): CapNode | null => { const id = selected(); return (id && byId().get(id)) || null; @@ -77,46 +144,117 @@ export default function CapabilitiesView(props: { for (let n = id ? byId().get(id) : undefined; n; n = n.parent ? byId().get(n.parent) : undefined) out.unshift(n); return out; }; - const weak = createMemo(() => (props.map?.nodes ?? []).filter((n) => ["thin", "none"].includes(testLevel(n))).length); + const weakCounts = createMemo(() => { + const out = { thin: 0, none: 0 }; + for (const n of props.map?.nodes ?? []) { + const l = testLevel(n); + if (l === "thin" || l === "none") out[l]++; + } + return out; + }); + /** Weak descendants (and the node itself) under an area, for its header. */ + const weakUnder = (id: string): number => { + const n = byId().get(id); + if (!n) return 0; + return (isWeak(testLevel(n)) ? 1 : 0) + n.children.reduce((s, c) => s + weakUnder(c), 0); + }; + /** A tile is lit when it matches the search and the weak-tests filter; others fade back. */ + const lit = (id: string): boolean => { + const n = byId().get(id); + if (!n) return !query() && !weakOnly(); + if (weakOnly() && testLevel(n) !== weakOnly()) return false; + return matches(n, query()); + }; + const filtering = () => !!query().trim() || !!weakOnly(); + /** One result set for the count, the highlights and Enter: every matching capability, areas included. */ + const results = createMemo(() => (filtering() ? (props.map?.nodes ?? []).filter((n) => lit(n.id)) : [])); const errors = () => (props.map?.diagnostics ?? []).filter((d) => d.severity === "error"); + const hoverIn = (id: string, el: HTMLElement, now = false) => { + window.clearTimeout(hoverTimer); + const open = () => setHover({ id, rect: el.getBoundingClientRect() }); + if (now || hover()) open(); + else hoverTimer = window.setTimeout(open, HOVER_OPEN_MS); + }; + const hoverOut = () => { + window.clearTimeout(hoverTimer); + hoverTimer = window.setTimeout(() => setHover(null), 120); + }; + + const railOpen = () => !narrow() || selected() !== null || railShown(); + return ( -
+
+ -
- + {(n) => ( <> - -
- - {(loc) => ( - - {props.map!.nodes.length} capabilities · {loc().claimed_pct}% of code claimed · {weak()} with thin or no tests - - )} - -
- Tests / 100 LOC - + + +
+ {(l) => ( - - +