Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions client/e2e/capabilities.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Browser smoke for the Capabilities view: a repo with docs/capabilities/*.yaml opens on its
// capability treemap, a capability with no linked test is marked, a click shows its promise and
// files, and a repo with no map keeps normal Srcly (no Capabilities switch).
import { expect, test } from "@playwright/test";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const SHOTS = path.resolve(here, "../../tmp/e2e");
fs.mkdirSync(SHOTS, { recursive: true });

const AREA = `notes:
title: Notes
promise: Write and read notes.

note-editor:
parent: notes
title: Edit a note
promise: Typing in a note saves it.
implementation: [src/editor.ts]
tests: [src/editor.test.ts]

note-export:
parent: notes
title: Export a note
promise: Download a note as Markdown.
implementation: [src/export.ts]
`;

function makeRepo(withMap: boolean): string {
const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "srcly-e2e-caps-")), "repo");
const files: Record<string, string> = {
"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/legacy.ts": "export const old = 1;\n",
};
if (withMap) files["docs/capabilities/notes.yaml"] = AREA;
for (const [rel, text] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
fs.writeFileSync(path.join(dir, rel), text);
}
const git = (...args: string[]) => execFileSync("git", ["-C", dir, ...args], { stdio: "ignore" });
git("init", "-q", "-b", "main");
git("-c", "user.email=e2e@example.com", "-c", "user.name=e2e", "add", ".");
git("-c", "user.email=e2e@example.com", "-c", "user.name=e2e", "commit", "-q", "-m", "init");
return dir;
}

test("a repo with a map opens on its capabilities; one without keeps the treemap", async ({ page }) => {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
const mapped = makeRepo(true);

await page.goto(`/?${new URLSearchParams({ repo: mapped })}`);
const view = page.locator('[data-view="capabilities"]');
await expect(view).toHaveAttribute("data-cap-status", "checked", { timeout: 60_000 });
await expect(page).toHaveURL(/view=capabilities/);

// The editor links a test; the export claims code and links none.
await expect(page.locator('[data-capability="note-editor"]')).toHaveAttribute("data-test-level", /solid|some|thin/);
await expect(page.locator('[data-capability="note-export"]')).toHaveAttribute("data-test-level", "none");
await expect(page.locator('[data-cap-area="__unclaimed"]')).toBeVisible();
await expect(page.locator("[data-cap-errors]")).toContainText("note-export");

await page.locator('[data-capability="note-export"]').click();
const detail = page.locator('[data-cap-detail="note-export"]');
await expect(detail).toContainText("Download a note as Markdown.");
await expect(detail.locator('[data-cap-role="implementation"]')).toContainText("src/export.ts");
await expect(page).toHaveURL(/cap=note-export/);
await page.screenshot({ path: path.join(SHOTS, "capabilities.png") });

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([]);
});
34 changes: 32 additions & 2 deletions client/src/components/Treemap.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
createEffect,
createMemo,
createResource,
createSignal,
lazy,
onCleanup,
Expand All @@ -23,13 +24,15 @@ import { useTreemapTooltip } from "../viz/treemap/hooks/useTreemapTooltip";
import { atFromTreePath, baseName, folderOf } from "../navigation/location";
import { addAnchorPatch, refsPatch, tracePatch } from "../navigation/nodeActions";
import NodeActionsMenu, { type NodeMenuTarget } from "../navigation/NodeActionsMenu";
import { go, location } from "../navigation/store";
import { go, location, replace } from "../navigation/store";
import { fetchCapabilities } from "../viz/capabilities/model";
import { buildMetricsIndex } from "../viz/deps/metrics";
import { linkedPathFor, setHoverFrom } from "../utils/hoverLink";

const DependencyView = lazy(() => import("../viz/deps/DependencyView"));
const ScatterView = lazy(() => import("../viz/scatter/ScatterView"));
const ChangeLensView = lazy(() => import("../changelens/ChangeLensView"));
const CapabilitiesView = lazy(() => import("../viz/capabilities/CapabilitiesView"));

interface TreemapProps {
data: any;
Expand Down Expand Up @@ -67,7 +70,30 @@ export default function Treemap(props: TreemapProps) {
const showScatter = () => location().view === "scatter";
/** The treemap canvas is covered by another view. */
const showChanges = () => location().view === "changes";
const covered = () => showDependencyGraph() || showScatter() || showChanges();
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 covered = () => showDependencyGraph() || showScatter() || showChanges() || showCapabilities() || deciding();
// The capabilities map (docs/capabilities/*.yaml), read again with each new scan of the root.
const [capabilities] = createResource(
() => (props.data ? { root: props.rootPath, data: props.data } : 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;
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" });
});
const [menu, setMenu] = createSignal<NodeMenuTarget | null>(null);

const openTileMenu = (event: MouseEvent, tile: TreemapTile) => {
Expand Down Expand Up @@ -247,6 +273,7 @@ export default function Treemap(props: TreemapProps) {
setShowMetricPopover={setShowMetricPopover}
view={() => location().view}
onViewChange={(view) => go({ view })}
hasCapabilities={hasCapabilities}
/>

<div ref={containerRef} class="relative flex-1 overflow-hidden">
Expand All @@ -271,6 +298,9 @@ export default function Treemap(props: TreemapProps) {
<Show when={showChanges()}>
<ChangeLensView data={props.data} rootPath={props.rootPath} />
</Show>
<Show when={showCapabilities()}>
<CapabilitiesView map={capMap()} onOpenAt={props.onOpenAt} />
</Show>
</Suspense>
<Show when={!covered() && layoutRoot()}>
<TreemapCanvas
Expand Down
4 changes: 2 additions & 2 deletions client/src/navigation/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// The file part ends at the first "#". Scope names may contain "#" (TS private
// members); file names with "#" are not supported.

export type View = "treemap" | "graph" | "scatter" | "changes";
export type View = "treemap" | "graph" | "scatter" | "changes" | "capabilities";

export interface Location {
/** Absolute path of the analyzed codebase; "" before one is chosen. */
Expand Down Expand Up @@ -153,7 +153,7 @@ export function parseLocation(search: string): Location {
const rawAt = params.get(AT_PARAM) ?? (legacy !== null ? legacy : "");
const rawView = params.get(VIEW_PARAM);
const view: View =
rawView === "graph" || rawView === "treemap" || rawView === "scatter" || rawView === "changes"
rawView === "graph" || rawView === "treemap" || rawView === "scatter" || rawView === "changes" || rawView === "capabilities"
? rawView
: legacy !== null
? "graph"
Expand Down
Loading
Loading