sum + (signal.kind === "unlinked" ? signal.records.length : 0), 0)} not linked`}
info={{
text: "Records with no link to another record in the group. Often expected for standalone notes.",
display: "title",
diff --git a/web/bundled-views/group/briefing-contents.tsx b/web/bundled-views/group/briefing-contents.tsx
index ac3434192..3aa2738cf 100644
--- a/web/bundled-views/group/briefing-contents.tsx
+++ b/web/bundled-views/group/briefing-contents.tsx
@@ -19,11 +19,12 @@ export function Implementors({ model, member }: { model: GroupModel; member: Mem
return (
- {entries.map(([type, count]) => {
+ {entries.map(([type, count], index) => {
const labels = model.typeLabels.get(type);
return (
+ {index > 0 && · }
{labels ? typeLabel(labels, { prefix: model.labelPrefix }) : fieldLabel(type)}{" "}
{count}
diff --git a/web/bundled-views/group/briefing-motion.test.tsx b/web/bundled-views/group/briefing-motion.test.tsx
new file mode 100644
index 000000000..ff8b9184c
--- /dev/null
+++ b/web/bundled-views/group/briefing-motion.test.tsx
@@ -0,0 +1,10 @@
+import { expect, it } from "vitest";
+import { commonMotionMetadata } from "./briefing-motion";
+
+it("moves the shared type and folder to the heading while retaining exceptional metadata", () => {
+ const effort = { type: "Effort note", folder: "docs/efforts" };
+ expect(
+ commonMotionMetadata([effort, effort, { type: "Effort workspace", folder: "docs" }]),
+ ).toEqual(effort);
+ expect(commonMotionMetadata([effort, { type: "Spec", folder: "docs/specs" }])).toBeUndefined();
+});
diff --git a/web/bundled-views/group/briefing-motion.tsx b/web/bundled-views/group/briefing-motion.tsx
new file mode 100644
index 000000000..202be2a39
--- /dev/null
+++ b/web/bundled-views/group/briefing-motion.tsx
@@ -0,0 +1,39 @@
+import type { ChangeLine } from "./briefing-activity.tsx";
+
+export function commonMotionMetadata(lines: readonly Pick[]) {
+ const counts = new Map();
+
+ for (const line of lines) {
+ const key = `${line.type.toLowerCase()}:${line.folder}`;
+ const entry = counts.get(key);
+ counts.set(key, { line, count: (entry?.count ?? 0) + 1 });
+ }
+
+ return [...counts.values()].find((entry) => entry.count > lines.length / 2)?.line;
+}
+
+export function MotionCount({
+ count,
+ metadata,
+}: {
+ count: number;
+ metadata: ReturnType;
+}) {
+ return (
+ <>
+ {count}
+ {metadata && (
+
+ {" "}
+ · {metadata.type}
+ {metadata.folder && (
+ <>
+ {" "}
+ · {metadata.folder}/
+ >
+ )}
+
+ )}
+ >
+ );
+}
diff --git a/web/bundled-views/group/briefing-parts.tsx b/web/bundled-views/group/briefing-parts.tsx
index e1fed5525..84994bae1 100644
--- a/web/bundled-views/group/briefing-parts.tsx
+++ b/web/bundled-views/group/briefing-parts.tsx
@@ -1,6 +1,7 @@
// Small pieces the Briefing and Overview blocks share: running-text labels,
// the block frame and its loading body, and the "+N more" toggle.
import {
+ ValidationCheck,
MoreToggle,
orderedEnumValues,
Section as Block,
@@ -60,7 +61,7 @@ export function HealthyAttention({ info }: { info: string }) {
controls={
<>
- ✓ No issues
+
>
diff --git a/web/bundled-views/group/briefing-signal-examples.tsx b/web/bundled-views/group/briefing-signal-examples.tsx
new file mode 100644
index 000000000..d4d4b22f2
--- /dev/null
+++ b/web/bundled-views/group/briefing-signal-examples.tsx
@@ -0,0 +1,53 @@
+import { DisclosureIcon as DisclosureChevron } from "@rhizome/kit";
+import { useState, type ReactNode } from "react";
+
+export function SignalExamples({ label, children }: { label: string; children: ReactNode }) {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <>
+ setOpen(!open)}
+ >
+
+ {open ? "Hide" : "Show"} {label}
+
+ {open && children}
+ >
+ );
+}
+
+type SignalAction = { label: string; run: () => void };
+
+export function SignalRow({
+ count,
+ severity,
+ text,
+ action,
+ children,
+}: {
+ count: ReactNode;
+ severity: "risk" | "warning" | "ok" | "context";
+ text: ReactNode;
+ action?: SignalAction | null;
+ children?: ReactNode;
+}) {
+ return (
+
+ {count}
+ {text}
+ {action ? (
+
+ {action.label}
+
+ ) : (
+
+ )}
+ {children && {children}
}
+
+ );
+}
diff --git a/web/bundled-views/group/briefing.css b/web/bundled-views/group/briefing.css
new file mode 100644
index 000000000..1625ed665
--- /dev/null
+++ b/web/bundled-views/group/briefing.css
@@ -0,0 +1,193 @@
+.gv-facts-jumps {
+ padding-right: 12px;
+ border-right: 1px solid var(--border-strong);
+}
+.gv-coverage .gv-sig-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+}
+.gv-coverage .gv-sig-member {
+ margin: 6px 0 0;
+}
+.gv-coverage .gv-sig-row > span:first-child {
+ min-width: 0;
+}
+.gv-coverage .gv-inline {
+ white-space: normal;
+ text-align: left;
+}
+/* The Guide takes the strip's leftover width and truncates rather than
+ wrapping the strip onto a second line. */
+.gv-facts > .gv-facts-note {
+ flex: 1 1 0;
+ min-width: 160px;
+ overflow: hidden;
+ text-align: right;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.gv-coverage .gv-sig-rows[data-subtypes] .gv-sig-row {
+ grid-template-columns: minmax(0, 1fr) 140px auto;
+}
+.gv-coverage-subtype {
+ color: var(--text-muted);
+ font-size: 13px;
+ text-align: left;
+}
+.gv-coverage .gv-age {
+ text-align: right;
+}
+.gv-facts-list {
+ font-weight: 400;
+}
+.gv-facts-list b,
+.gv-facts .gv-num {
+ font-weight: 600;
+}
+.gv-facts-list .gv-ok,
+.gv-facts-list .gv-sub {
+ font-weight: 400;
+}
+.gv-hint summary.rz-info {
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+}
+.gv-spread-head,
+.gv-composition-head {
+ color: var(--text-muted);
+ font: 600 13px / 1.4 var(--font-sans);
+}
+.gv-spread-head > .gv-sub {
+ margin-left: auto;
+ font-weight: 400;
+}
+.gv-composition-head > .gv-num {
+ font-weight: 400;
+ text-align: right;
+}
+.gv-hist {
+ border-bottom-color: var(--border-strong);
+}
+.gv-hist i {
+ min-height: 4px;
+ flex-shrink: 0;
+}
+.gv-outside-totals {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 4px 20px;
+ font-size: 13px;
+}
+.gv-outside-totals > span {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ column-gap: 8px;
+ align-items: baseline;
+}
+.gv-outside-totals > span > span {
+ grid-column: 1;
+ grid-row: 1;
+}
+.gv-outside-totals b {
+ grid-column: 2;
+ grid-row: 1;
+ text-align: right;
+}
+.gv-hint:has(> summary.rz-info) .gv-hint-panel {
+ right: auto;
+ left: 0;
+}
+
+.gv-motion .rz-section-controls {
+ flex: 1;
+ margin-left: 0;
+}
+.gv-motion-age-label {
+ margin-left: auto;
+ color: var(--text-muted);
+ font-size: 13px;
+ font-weight: 500;
+ text-align: right;
+ white-space: nowrap;
+}
+
+.gv-motion-metadata,
+.gv-stage-note {
+ color: var(--text-muted);
+ font: 400 13px / 1.4 var(--font-sans);
+}
+.gv-stage-note {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin-top: 0;
+}
+.gv-change.gv-change-compact {
+ height: 36px;
+ box-sizing: border-box;
+ align-items: center;
+ padding: 0;
+}
+.gv-signal-toggle.disclosure-toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ min-height: 24px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--link);
+ font: 500 13px / 1.4 var(--font-sans);
+ cursor: pointer;
+}
+
+.gv-connection-bar {
+ height: 4px;
+ margin: 5px 0 4px;
+ background: var(--border-faint);
+}
+.gv-connection-bar i {
+ display: block;
+ height: 100%;
+}
+
+.gv-change .gv-age-repeat {
+ color: var(--text-faint);
+}
+
+.gv-stale-review {
+ display: inline-block;
+ position: relative;
+ margin-left: 8px;
+}
+.gv-stale-review summary {
+ display: inline-flex;
+ align-items: center;
+ min-width: 24px;
+ min-height: 24px;
+ gap: 4px;
+ list-style: none;
+ cursor: pointer;
+ color: var(--text-muted);
+}
+.gv-stale-review > div {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ z-index: 2;
+ width: 340px;
+ padding: 12px;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ font-weight: 400;
+}
+
+.gv-stale-review summary::-webkit-details-marker {
+ display: none;
+}
+.gv-stale-review[open] .rz-disclosure-icon {
+ transform: rotate(90deg);
+}
diff --git a/web/bundled-views/group/briefing.test.tsx b/web/bundled-views/group/briefing.test.tsx
index 1432f161d..2acf14c95 100644
--- a/web/bundled-views/group/briefing.test.tsx
+++ b/web/bundled-views/group/briefing.test.tsx
@@ -7,10 +7,10 @@ import {
OPEN_NODE_MESSAGE,
} from "../../src/lib/customViewMessages";
import { jsonReply } from "../../src/test/fakeFetch";
-import { NOW, PATHS, RECORDS_DATA, TYPE_DOCS } from "./__fixtures__/groups.ts";
+import { NOW, PATHS, RECORDS_DATA, TYPE_DOCS, TYPE_SUMMARIES } from "./__fixtures__/groups.ts";
import { VALIDATION_ENVELOPE } from "./__fixtures__/aggregate.ts";
import { groupRoutes, renderGroupView } from "./__fixtures__/harness.tsx";
-import { isJsonObject } from "./api.ts";
+import { isJsonObject, type JsonValue } from "./api.ts";
import { SIGNAL_RECORDS } from "./briefing-attention.tsx";
const loadBriefing = () => import("./briefing.tsx");
@@ -37,6 +37,11 @@ const opened = (posted: readonly { type: string }[]) =>
it("lists what needs attention with counts, records, and policy reasons", async () => {
await renderGroupView(loadBriefing);
const attention = await screen.findByRole("region", { name: "Needs attention" });
+ const guide = document.querySelector(".gv-facts-note button");
+
+ expect(guide).toHaveAttribute("title", expect.stringContaining("Shared by"));
+ expect(guide).toHaveAttribute("aria-description", guide?.getAttribute("title"));
+ expect(document.querySelector(".gv-facts-note")).not.toHaveTextContent("shared by");
expect(items(attention).map((entry) => entry.querySelector(".gv-sig-text")?.textContent)).toEqual(
[
@@ -58,7 +63,13 @@ it("lists what needs attention with counts, records, and policy reasons", async
expect(region("Review suggested").querySelector('[data-severity="warning"]')).toBeNull();
expect(attention).not.toHaveTextContent("Area empty");
// Update age is context, not evidence of an obligation.
- expect(item(region("Review suggested"), "unchanged for").getByText("40d")).toBeVisible();
+ const stale = item(region("Review suggested"), "unchanged for");
+ const toggle = stale.getByRole("button", { name: /^Show \d+ / });
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ expect(stale.queryByText("40d")).toBeNull();
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ expect(stale.getByText("40d")).toBeVisible();
// No clean line while a record has issues.
expect(within(attention).queryByText("No validation issues")).toBeNull();
@@ -88,10 +99,17 @@ it("gives every signal an action: its member's collection or issues, or each mem
it("names a bounded number of records per signal and reveals the rest in place", async () => {
// Areas without parents: Commerce, Loop A, and Loop B leave the tree and
// link with nothing else.
- const areas = (Array.isArray(RECORDS_DATA.Area) ? RECORDS_DATA.Area : []).map((area) =>
- isJsonObject(area) ? { ...area, parent: null } : area,
+ const areas: JsonValue[] = (Array.isArray(RECORDS_DATA.Area) ? RECORDS_DATA.Area : []).map(
+ (area) => (isJsonObject(area) ? { ...area, parent: null } : area),
);
+ areas.push({
+ path: "areas/extra.md",
+ title: "Extra area",
+ parent: null,
+ updatedAt: NOW / 1000,
+ issueCount: 0,
+ });
await renderGroupView(loadBriefing, {
routes: groupRoutes({
"POST /api/v1/graphql": () => jsonReply({ data: { ...RECORDS_DATA, Area: areas } }),
@@ -107,20 +125,28 @@ it("names a bounded number of records per signal and reveals the rest in place",
.filter((button) => button.className.includes("gv-inline"))
.map((button) => button.textContent);
- expect(named()).toEqual(["Gift cards", "Commerce", "Loop A"].slice(0, SIGNAL_RECORDS));
- fireEvent.click(unlinked.getByRole("button", { name: "Show 2 more unlinked notes" }));
expect(named()).toEqual(["Gift cards", "Commerce", "Loop A", "Loop B", "Winter release"]);
+ fireEvent.click(unlinked.getByRole("button", { name: "Show 1 more" }));
+ expect(named()).toEqual([
+ "Gift cards",
+ "Commerce",
+ "Loop A",
+ "Loop B",
+ "Extra area",
+ "Winter release",
+ ]);
fireEvent.click(unlinked.getByRole("button", { name: "Show fewer" }));
- expect(named()).toHaveLength(SIGNAL_RECORDS);
+ expect(named()).toHaveLength(SIGNAL_RECORDS + 2);
});
it("says there are no validation issues, and skips unlinked records in a group without links", async () => {
await renderGroupView(loadBriefing, { group: "Library" });
await screen.findByRole("region", { name: "Review suggested" });
- // The status strip says "✓ No issues" once; the body adds no Validation row.
- expect(screen.getByText("✓ No issues")).toBeVisible();
+ // The status strip says "No validation issues" once; the body adds no Validation row.
+ expect(screen.getByText("No validation issues")).toBeVisible();
expect(await screen.findByText("Checked 2h ago")).toBeVisible();
+ expect(document.querySelector(".gv-facts-list")).toHaveTextContent(/Last changed .* ago/);
expect(screen.queryByRole("region", { name: "Validation" })).toBeNull();
expect(screen.queryByRole("region", { name: "Needs attention" })).toBeNull();
expect(region("Review suggested")).toHaveTextContent("Term empty on 1 of 3 glossaries");
@@ -130,6 +156,7 @@ it("says there are no validation issues, and skips unlinked records in a group w
it("lists active-stage records newest first in flat rows with type metadata", async () => {
await renderGroupView(loadBriefing);
const motion = await screen.findByRole("region", { name: "In motion" });
+ expect(within(motion).getByText("Last changed")).toBeVisible();
expect(within(motion).queryByRole("heading", { level: 3 })).toBeNull();
expect(items(motion).map((entry) => within(entry).getByRole("button").textContent)).toEqual([
@@ -137,7 +164,14 @@ it("lists active-stage records newest first in flat rows with type metadata", as
"Tax rounding",
"Saved carts",
]);
- expect(items(motion).every((entry) => entry.querySelector(".gv-change-meta"))).toBe(true);
+ expect(
+ [...motion.parentElement!.querySelectorAll(":scope > section")].map(
+ (section) =>
+ section.getAttribute("aria-labelledby") && section.querySelector("h2 > span")?.textContent,
+ ),
+ ).toEqual(["Needs attention", "Review suggested", "In motion", "Link coverage"]);
+ expect(motion.querySelector(".gv-motion-metadata")).not.toBeNull();
+ expect(motion.querySelectorAll(".gv-change-meta")).toHaveLength(1);
expect(motion.querySelectorAll(".gv-mark").length).toBeGreaterThan(0);
expect(motion.querySelector(".gv-hint-lead")).toHaveTextContent(
"Areas, Checklists have no lifecycle.",
@@ -149,10 +183,15 @@ it("names lifecycles without an active stage", async () => {
const motion = await screen.findByRole("region", { name: "In motion" });
expect(within(motion).getByText("Nothing in an active stage.")).toBeVisible();
- // Setup notes wait behind a labelled Configuration disclosure in the heading row.
+ // Setup help stays attached to the heading, behind the info disclosure.
+ expect(motion.querySelector("h2 .gv-hint")).not.toBeNull();
+ expect(motion.querySelector(".gv-stage-note")).not.toHaveTextContent("shows active");
const config = motion.querySelector("details")!;
- expect(within(motion).getByText("Configuration")).toBeVisible();
+ const summary = within(motion).getByLabelText("Why some types are not listed");
+ expect(summary).toBeVisible();
expect(config).not.toHaveAttribute("open");
+ fireEvent.click(summary);
+ expect(config).toHaveAttribute("open");
expect(config.querySelector(".gv-hint-lead")).toHaveTextContent(
"Memos have no active stage configured. Glossaries have no lifecycle.",
);
@@ -194,7 +233,7 @@ it("does not call an out-of-date validation run clean", async () => {
});
expect(await screen.findByText("Validation out of date")).toBeVisible();
- expect(screen.queryByText("✓ No issues")).toBeNull();
+ expect(screen.queryByText("No validation issues")).toBeNull();
});
it("shows only activity: Needs attention, In motion, and Recent changes", async () => {
@@ -203,7 +242,7 @@ it("shows only activity: Needs attention, In motion, and Recent changes", async
expect(
screen.getAllByRole("region").map((block) => block.querySelector("h2 span")?.textContent),
).toEqual(["In motion", "Recent changes"]);
- expect(await screen.findByText("✓ No issues")).toBeVisible();
+ expect(await screen.findByText("No validation issues")).toBeVisible();
expect(await screen.findByText("Checked 2h ago")).toBeVisible();
expect(
within(region("Recent changes")).getByRole("button", { name: /Ada Lovelace/ }),
@@ -346,7 +385,7 @@ it("refreshes when records change", async () => {
data = { ...RECORDS_DATA, Story: [], Bug: [] };
await view.emit("node.changed");
- // The issues signal leaves; the strip, not the block, says "✓ No issues".
+ // The issues signal leaves; the strip, not the block, says "No validation issues".
await waitFor(() =>
expect(within(region("Needs attention")).queryByText("Validation issues")).toBeNull(),
);
@@ -414,3 +453,36 @@ it("retries type documentation that failed to load", async () => {
expect(within(region("In motion")).getByText("Checkout redesign")).toBeVisible(),
);
});
+
+it.each(["Area", "Special area"])("shows subtype metadata only when useful: %s", async (label) => {
+ const summaries = Array.isArray(TYPE_SUMMARIES) ? TYPE_SUMMARIES : [];
+ await renderGroupView(loadBriefing, {
+ routes: groupRoutes({
+ "POST /api/v1/graphql": () =>
+ jsonReply({
+ data: {
+ ...RECORDS_DATA,
+ Area: (Array.isArray(RECORDS_DATA.Area) ? RECORDS_DATA.Area : []).map((area) =>
+ isJsonObject(area) ? { ...area, parent: null } : area,
+ ),
+ },
+ }),
+ "GET /api/v1/ontology/types": () =>
+ jsonReply(
+ summaries.map((entry) =>
+ isJsonObject(entry) && entry.name === "Area" ? { ...entry, label } : entry,
+ ),
+ ),
+ }),
+ });
+ const coverage = await screen.findByRole("region", { name: "Link coverage" });
+ const areaGroup = within(coverage).getByRole("heading", { name: /^Areas/ }).parentElement;
+ const metadata = areaGroup?.querySelectorAll(".gv-coverage-subtype") ?? [];
+
+ if (label === "Area") expect(metadata).toHaveLength(0);
+ else {
+ expect(metadata.length).toBeGreaterThan(0);
+ expect(metadata[0]).toHaveTextContent(label);
+ expect(metadata[0]?.closest("ul")).toHaveAttribute("data-subtypes", "true");
+ }
+});
diff --git a/web/bundled-views/group/briefing.tsx b/web/bundled-views/group/briefing.tsx
index 68a3c8ce3..dcfd40d28 100644
--- a/web/bundled-views/group/briefing.tsx
+++ b/web/bundled-views/group/briefing.tsx
@@ -7,8 +7,9 @@
import { HighlightProvider, type ViewModuleProps } from "@rhizome/kit";
import { useMemo } from "react";
+import { MotionCount } from "./briefing-motion.tsx";
import { inMotion, needsAttention } from "./activity.ts";
-import { MotionList, RecentChanges, StageHints } from "./briefing-activity.tsx";
+import { useMotionMetadata, MotionList, RecentChanges, StageHints } from "./briefing-activity.tsx";
import { NeedsAttention } from "./briefing-attention.tsx";
import { Block, ModelBlock } from "./briefing-parts.tsx";
import { GroupFrame } from "./components.tsx";
@@ -46,20 +47,32 @@ function InMotion({ model }: { model: GroupModel }) {
.flatMap((group) => group.entries)
.sort((a, b) => (b.record.updatedAt ?? 0) - (a.record.updatedAt ?? 0));
+ const metadata = useMotionMetadata(model, entries);
+
+ const title =
+ motion.groups.length === 1 &&
+ model.memberIndex.get(motion.groups[0].member)?.pluralLabel.toLowerCase() === "efforts"
+ ? "Active efforts"
+ : "In motion";
+
return (
}
info={{
text: "Records whose lifecycle value is in the active stage, newest change first.",
display: "title",
}}
controls={
-
+ <>
+
+ Last changed
+ >
}
>
{motion.groups.length === 0 && Nothing in an active stage.
}
@@ -68,7 +81,13 @@ function InMotion({ model }: { model: GroupModel }) {
);
}
-function GroupAttention({ model, part }: { model: GroupModel; part: "attention" | "review" }) {
+function GroupAttention({
+ model,
+ part,
+}: {
+ model: GroupModel;
+ part: "attention" | "review" | "coverage";
+}) {
const signals = useMemo(() => needsAttention(model, linkGraph(model), Date.now()), [model]);
return (
@@ -82,10 +101,10 @@ function GroupAttention({ model, part }: { model: GroupModel; part: "attention"
}
/** Needs attention leads, then the optional review signals, then work in motion. */
-function AttentionBlock({ part }: { part: "attention" | "review" }) {
+function AttentionBlock({ part }: { part: "attention" | "review" | "coverage" }) {
const state = useGroupModel({ views: false, read: ATTENTION_READ });
- if (part === "review" && state.status !== "ready") return null;
+ if (part !== "attention" && state.status !== "ready") return null;
return (
@@ -125,6 +144,7 @@ export default function Briefing(_props: ViewModuleProps) {
+
diff --git a/web/bundled-views/group/components.tsx b/web/bundled-views/group/components.tsx
index c41451938..f54f7b312 100644
--- a/web/bundled-views/group/components.tsx
+++ b/web/bundled-views/group/components.tsx
@@ -11,7 +11,6 @@
// - openRecord(record), openMemberIssues(member): navigation helpers.
import {
Dash,
- RelativeTime,
StatusMark,
openCollection,
openIssues,
@@ -22,7 +21,8 @@ import {
import { createContext, useContext, type ReactNode } from "react";
import "./group.css";
-import { NoIssues, ValidationFreshness } from "./validation-freshness.tsx";
+import "./briefing.css";
+import { LastChanged, NoIssues, ValidationFreshness } from "./validation-freshness.tsx";
import { RECORD_CAP } from "./api.ts";
import type { GroupModelState } from "./load.ts";
import {
@@ -262,17 +262,15 @@ export function LifecycleCounts({ member }: { member: Member }) {
/**
* The strip under the host's title: what the view shows, then the group's
- * facts. A `collection` strip leaves out the type count and the guide, which
+ * facts. A `collection` strip leaves out counts and the guide, which
* the type Briefing's Guide block shows.
*/
export function GroupFacts({
model,
collection = false,
- children,
}: {
model: GroupModel;
collection?: boolean;
- children?: ReactNode;
}) {
const records = [...model.records.values()];
const withIssues = records.filter((record) => record.issueCount > 0).length;
@@ -282,38 +280,15 @@ export function GroupFacts({
return (
-
- {children}
- {model.guide && !collection && (
- <>
- {children && " "}
- Guide:{" "}
- openNote(model.guide?.path ?? "")}
- >
- {model.guide.title}
-
- {model.members.length > 1
- ? `, shared by ${model.guide.sharedBy} of ${model.members.length} types.`
- : "."}
- >
- )}
-
{/* A group counts every note its member types hold, ambiguous notes
included; Overview counts only typed records, so each names its scope. */}
-
- {records.length} {collection ? "record" : "note"}
- {records.length === 1 ? "" : "s"}
-
+ {!collection && (
+
+ {records.length} note
+ {records.length === 1 ? "" : "s"}
+
+ )}
{!collection && (
{model.members.length} {model.members.length === 1 ? "type" : "types"}
@@ -321,7 +296,7 @@ export function GroupFacts({
)}
{withIssues ? (
- {withIssues} {withIssues === 1 ? "record" : "records"} with issues
+ {withIssues} {withIssues === 1 ? "record" : "records"} with issues
) : (
<>
@@ -329,10 +304,30 @@ export function GroupFacts({
>
)}
- {latest > 0 && (
-
- changed
-
+ {latest > 0 && }
+
+
+ {model.guide && !collection && (
+ <>
+ Guide:{" "}
+ 1
+ ? `Shared by ${model.guide.sharedBy} of ${model.members.length} types`
+ : undefined
+ }
+ aria-description={
+ model.members.length > 1
+ ? `Shared by ${model.guide.sharedBy} of ${model.members.length} types`
+ : undefined
+ }
+ onClick={() => openNote(model.guide?.path ?? "")}
+ >
+ {model.guide.title}
+
+ >
)}
{refreshError && (
diff --git a/web/bundled-views/group/group.css b/web/bundled-views/group/group.css
index 9b89d80aa..75e31dbd3 100644
--- a/web/bundled-views/group/group.css
+++ b/web/bundled-views/group/group.css
@@ -148,7 +148,7 @@
display: flex;
flex-wrap: wrap;
align-items: baseline;
- gap: 4px 18px;
+ gap: 4px 12px;
padding: 7px 20px;
border-bottom: 1px solid var(--border);
background: var(--surface-alt);
@@ -156,6 +156,9 @@
}
.gv-facts-note {
+ order: 2;
+ margin-left: auto;
+ font-size: 13px;
color: var(--text-faint);
min-width: 0;
}
@@ -170,7 +173,6 @@
display: flex;
flex-wrap: wrap;
gap: 2px 8px;
- margin-left: auto;
font-size: var(--fs-sm);
font-variant-numeric: tabular-nums;
color: var(--text-muted);
@@ -183,17 +185,17 @@
content: "·";
}
-/* Section jump links: each member's name and count, near the tabs. */
+/* Section jump links keep counts in their accessible names. */
.gv-jump {
display: inline-flex;
flex-wrap: wrap;
gap: 2px 14px;
- margin-right: 18px;
+ margin-right: 0;
font-size: var(--fs-sm);
}
-.gv-jump .gv-num {
- margin-left: 2px;
+.gv-jump [data-empty] {
+ color: var(--text-faint);
}
.gv-facts-list b {
@@ -207,6 +209,7 @@
}
.gv-facts-warn {
+ order: 3;
flex-basis: 100%;
color: var(--warning-ink);
}
@@ -320,6 +323,11 @@
font-weight: 500;
}
+.gv-section .gv-table td.gv-col-type {
+ font-size: 14px;
+ font-weight: 400;
+}
+
.gv-section .gv-table td:not(:first-child) {
overflow: hidden;
text-overflow: ellipsis;
@@ -366,8 +374,12 @@
width: 1%;
}
-.gv-table .gv-age {
+.gv-section .gv-table .gv-age {
padding-top: 9px;
+ color: var(--text-muted);
+ font-size: var(--fs-base);
+ font-weight: 400;
+ font-variant-numeric: tabular-nums;
}
.gv-title {
@@ -827,7 +839,7 @@
.gv-kinds {
display: flex;
flex-wrap: wrap;
- gap: 2px 10px;
+ gap: 2px 4px;
margin: 5px 0 0;
color: var(--text-muted);
font: 500 13px / 1.4 var(--font-sans);
@@ -922,12 +934,12 @@
width: 100cqi;
}
-.gv-toolbar {
+.gv-trace-page > .gv-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 14px;
- padding: 7px 20px;
+ padding: 5px 20px;
border-bottom: 1px solid var(--border);
font-size: var(--fs-xs);
}
@@ -953,61 +965,45 @@
table-layout: fixed;
}
-/* About 40% for the rows, the rest shared by the linked columns; a column
- few rows fill keeps a fixed 260px. Plain lengths: Chrome treats a calc() or
- max() width on a table column as auto. */
+/* Leave room for related materials; use plain lengths for fixed table columns. */
.gv-col-spine,
.gv-trace thead th.gv-trace-spine {
- width: 40%;
+ width: 34%;
}
-
.gv-col-sparse,
.gv-trace thead th.gv-col-sparse {
width: 260px;
}
-
-/* The heading's second line: the relation, then the Key disclosure. */
-.gv-cov-row {
- display: flex;
- align-items: center;
- gap: 6px;
- min-width: 0;
+.gv-trace .gv-trace-related {
+ width: 300px;
}
-
-.gv-cov-row > .gv-cov {
- flex: 0 1 auto;
- min-width: 0;
+.gv-trace .gv-trace-related .gv-cov {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ white-space: normal;
}
-
-/* Each linked column's status key, always shown: mark and word per status
- its records hold, on a 13px line under the relation. */
-.gv-col-legend {
- display: flex;
- flex-wrap: wrap;
- gap: 2px 12px;
- margin-top: 2px;
- color: var(--text-muted);
- font: 500 13px / 1.4 var(--font-sans);
+/* Status marks stay inline with the relation caption. */
+.gv-trace .gv-col-legend {
+ display: inline;
+ font: inherit;
}
-
-.gv-trace td:has(> .rz-dash) {
- vertical-align: middle;
+.gv-trace .gv-head > .gv-num {
+ flex: none;
+ font-size: 14px;
+ font-weight: 400;
}
-
/* Linked titles are 14px teal quiet links, like every record link. */
.gv-trace td .gv-chip {
font-size: var(--fs-base);
}
-
.gv-trace td .gv-chip:not([data-indirect]) {
color: var(--text-muted);
}
-
.gv-trace td .gv-chip:is(:hover, :focus-visible) > span:not(.sr-only) {
text-decoration: underline;
text-underline-offset: 2px;
}
-
.gv-legend {
display: inline-flex;
flex-wrap: wrap;
@@ -1042,11 +1038,11 @@
position: sticky;
top: 0;
z-index: 2;
- padding: 8px 10px 7px;
+ padding: 9px 10px;
vertical-align: top;
border-bottom-color: var(--border-strong);
background: var(--surface);
- font: 500 13px / 1.4 var(--font-sans);
+ font: 400 13px / 1.4 var(--font-sans);
}
.gv-trace .gv-trace-spine {
@@ -1066,47 +1062,50 @@
background: color-mix(in srgb, var(--success-soft) 22%, var(--surface));
}
-.gv-head {
+.gv-trace .gv-head {
display: flex;
- flex-wrap: wrap;
+ flex-wrap: nowrap;
align-items: baseline;
gap: 6px;
min-width: 0;
white-space: nowrap;
}
-.gv-head > .gv-member,
-.gv-head > .gv-record {
+.gv-trace .gv-head > .gv-member,
+.gv-trace .gv-head > .gv-record {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.gv-trace .gv-member {
- font-size: var(--fs-base);
- font-weight: 500;
+ font-size: 14px;
+ font-weight: 600;
}
-.gv-cov-count {
+.gv-trace .gv-cov-count {
+ flex: none;
margin-left: auto;
- color: var(--text-faint);
- font: 500 13px / 1.4 var(--font-sans);
+ color: var(--text-muted);
+ font: 400 13px / 1.4 var(--font-sans);
font-variant-numeric: tabular-nums;
}
-.gv-cov-count b {
+.gv-trace .gv-cov-count b {
color: var(--text);
- font-weight: 600;
+ font-weight: 400;
}
-.gv-cov {
+.gv-trace .gv-cov {
+ overflow: hidden;
color: var(--text-muted);
- font: 500 13px / 1.4 var(--font-sans);
- white-space: normal;
+ font: 400 13px / 1.4 var(--font-sans);
+ white-space: nowrap;
+ text-overflow: ellipsis;
}
-.gv-cov-count .gv-thin {
- color: var(--text);
+.gv-trace tr > :last-child {
+ padding-right: 20px;
}
.gv-band th {
@@ -1308,7 +1307,7 @@
gap: 3px;
height: 56px;
margin-top: 6px;
- border-bottom: 1px solid var(--border);
+ border-bottom: 1px solid var(--border-faint);
}
.gv-hist > span {
diff --git a/web/bundled-views/group/map-labels.ts b/web/bundled-views/group/map-labels.ts
new file mode 100644
index 000000000..dc7583084
--- /dev/null
+++ b/web/bundled-views/group/map-labels.ts
@@ -0,0 +1,222 @@
+import type { Point, LabelPlacement, LayoutEdge } from "./map-layout.ts";
+
+const GLYPH = 7.5;
+
+/** Shorten only lines that cannot fit across the canvas, preserving the two-line style. */
+export function mapLabelLine(text: string, width: number): string {
+ const limit = Math.max(1, Math.floor((width - 48) / GLYPH));
+
+ return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;
+}
+
+export type Box = { x: number; y: number; w: number; h: number };
+
+const overlaps = (a: Box, b: Box) =>
+ a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
+
+/** Whether the segment from `a` to `b` passes through the box. */
+function crosses(box: Box, a: Point, b: Point) {
+ // Liang–Barsky clipping: the segment meets the box when some t in [0, 1] lies inside it.
+ let t0 = 0;
+ let t1 = 1;
+ const dx = b.x - a.x;
+ const dy = b.y - a.y;
+
+ for (const [p, q] of [
+ [-dx, a.x - box.x],
+ [dx, box.x + box.w - a.x],
+ [-dy, a.y - box.y],
+ [dy, box.y + box.h - a.y],
+ ]) {
+ if (p === 0) {
+ if (q < 0) return false;
+ continue;
+ }
+
+ const t = q / p;
+
+ if (p < 0) t0 = Math.max(t0, t);
+ else t1 = Math.min(t1, t);
+
+ if (t0 > t1) return false;
+ }
+
+ return true;
+}
+
+/** The least gap between a label and any other node or label. */
+const LABEL_CLEARANCE = 4;
+
+const grow = (box: Box, by: number): Box => ({
+ x: box.x - by,
+ y: box.y - by,
+ w: box.w + 2 * by,
+ h: box.h + 2 * by,
+});
+
+/** Label text height plus its halo. */
+const LABEL_HEIGHT = 34;
+
+type LabelItem = {
+ id: string;
+ radius: number;
+ label: string;
+ outward?: Point;
+ alignToNode?: boolean;
+};
+
+export function placeLabels(
+ positions: ReadonlyMap,
+ items: readonly LabelItem[],
+ segments: readonly [Point, Point][],
+ width: number,
+ height: number,
+ reserved: readonly Box[] = [],
+) {
+ const boxes: Box[] = items.flatMap((item) => {
+ const point = positions.get(item.id);
+
+ return point
+ ? [
+ {
+ x: point.x - item.radius,
+ y: point.y - item.radius,
+ w: item.radius * 2,
+ h: item.radius * 2,
+ },
+ ]
+ : [];
+ });
+
+ boxes.push(...reserved);
+ const labels = new Map();
+ const center = { x: width / 2, y: height / 2 };
+
+ const distance = (point: Point, box: Box) =>
+ Math.hypot(
+ point.x - Math.max(box.x, Math.min(point.x, box.x + box.w)),
+ point.y - Math.max(box.y, Math.min(point.y, box.y + box.h)),
+ );
+
+ for (const item of [...items].sort((a, b) => b.radius - a.radius || a.id.localeCompare(b.id))) {
+ const point = positions.get(item.id);
+
+ if (!point) continue;
+
+ const w =
+ Math.max(...item.label.split("\n").map((line) => mapLabelLine(line, width).length)) * GLYPH;
+
+ const h = LABEL_HEIGHT;
+ const angle = Math.atan2(point.y - center.y, point.x - center.x);
+
+ const candidates = [10, 16, 24, 36, 52, 72].flatMap((gap) =>
+ [0, -0.4, 0.4, -0.8, 0.8, -1.2, 1.2, -1.57, 1.57, -2, 2, -2.4, 2.4, Math.PI].map((turn) => {
+ const dx = Math.cos(angle + turn),
+ dy = Math.sin(angle + turn);
+
+ const reach = item.radius + gap;
+ const x = point.x + dx * reach - (dx < -0.25 ? w : dx > 0.25 ? 0 : w / 2);
+ const y = point.y + dy * reach - (dy < -0.25 ? h : dy > 0.25 ? 0 : h / 2);
+ const box = { x, y, w, h };
+ const own = distance(point, box);
+
+ const clear =
+ x >= 4 &&
+ y >= 4 &&
+ x + w <= width - 4 &&
+ y + h <= height - 4 &&
+ own >= item.radius + LABEL_CLEARANCE &&
+ !boxes.some((other) => overlaps(other, grow(box, LABEL_CLEARANCE))) &&
+ items.every((other) => {
+ const at = positions.get(other.id);
+
+ return other.id === item.id || !at || distance(at, box) >= own;
+ });
+
+ return {
+ box,
+ gap,
+ turn,
+ clear,
+ crossings: segments.filter(([a, b]) => crosses(grow(box, 2), a, b)).length,
+ };
+ }),
+ );
+
+ const open = candidates.filter((candidate) => candidate.clear);
+ const near = open.filter((candidate) => distance(point, candidate.box) <= item.radius + 12);
+ const chosen = near.find((candidate) => candidate.crossings === 0) ?? near[0] ?? open[0];
+
+ if (!chosen) continue;
+ const { box, turn } = chosen;
+ boxes.push(box);
+
+ const leader =
+ distance(point, box) > item.radius + 12 || turn !== 0
+ ? {
+ x: Math.max(box.x, Math.min(point.x, box.x + box.w)),
+ y: Math.max(box.y, Math.min(point.y, box.y + box.h)),
+ }
+ : undefined;
+
+ const left = item.alignToNode && box.x + box.w <= point.x;
+ labels.set(item.id, {
+ x: left ? box.x + box.w : box.x,
+ y: box.y + 12,
+ anchor: left ? "end" : "start",
+ leader,
+ });
+ }
+
+ return { labels, boxes: boxes.filter((box) => !reserved.includes(box)) };
+}
+
+/** Where along an edge its label may sit, nearest the middle first. */
+const EDGE_STOPS = [0.5, 0.4, 0.6, 0.3, 0.7];
+
+/**
+ * Each labeled edge's label at the first stop along it whose box clears
+ * `occupied` (node circles and labels) and the labels placed before it,
+ * preferring one no other segment crosses, heaviest edges first; an edge
+ * with no clear stop gets no label.
+ */
+export function placeEdgeLabels(
+ positions: ReadonlyMap,
+ edges: readonly LayoutEdge[],
+ occupied: readonly Box[],
+ segments: readonly [Point, Point][] = [],
+) {
+ const boxes = [...occupied];
+ const placed = new Map();
+ const labeled = edges.filter((edge) => edge.label);
+
+ for (const edge of labeled.sort((a, b) => b.links - a.links)) {
+ const a = positions.get(edge.a);
+ const b = positions.get(edge.b);
+
+ if (!a || !b || !edge.label) continue;
+ // The count's box covers the pill overview-map.tsx draws, centered on the edge.
+ const w = edge.label.text.length * GLYPH + 10;
+
+ const spots = EDGE_STOPS.flatMap((t) => {
+ const x = a.x + (b.x - a.x) * t;
+ const y = a.y + (b.y - a.y) * t;
+ const box = { x: x - w / 2, y: y - 9, w, h: 18 };
+
+ return boxes.some((other) => overlaps(other, box)) ? [] : [{ x, y, box }];
+ });
+
+ // Prefer a stop no other edge passes through, so a count reads as its own edge's.
+ const others = segments.filter(([from, to]) => !(from === a && to === b));
+
+ const spot =
+ spots.find((candidate) => !others.some(([from, to]) => crosses(candidate.box, from, to))) ??
+ undefined;
+
+ if (!spot) continue;
+ boxes.push(spot.box);
+ placed.set(edge.label.key, { x: spot.x, y: spot.y });
+ }
+
+ return placed;
+}
diff --git a/web/bundled-views/group/map-layout.ts b/web/bundled-views/group/map-layout.ts
index a8f4389eb..60d247ce3 100644
--- a/web/bundled-views/group/map-layout.ts
+++ b/web/bundled-views/group/map-layout.ts
@@ -1,16 +1,19 @@
+import { placeLabels, placeEdgeLabels, type Box } from "./map-labels.ts";
+
+export { placeEdgeLabels } from "./map-labels.ts";
// Positions for the Overview map (SPEC-0117 US1). Pure and deterministic: the
// same input always yields the same positions, with no randomness.
//
// Linked members get a small force layout seeded on a golden-angle spiral and
// stretched to the box, every node at least INSET inside it. Members with no
-// links at all, inside or outside the group, are left out of the drawing (the legend lists them),
+// links at all, inside or outside the group, are left out of the drawing (the side panel lists them),
// unless no member is linked, when they spread over the whole box. Outside
// neighbors sit on an ellipse at the edge, each at the angle of the members it
// links to, spread so none overlap. Each label goes on the first of eight
// sides of its node that clears the nodes, labels, and edges already placed,
// largest nodes first.
-export type LayoutNode = { id: string; radius: number; label: string };
+export type LayoutNode = { id: string; radius: number; label: string; alignToNode?: boolean };
export type LayoutEdge = {
a: string;
@@ -32,7 +35,25 @@ export type LayoutInput = {
export type Point = { x: number; y: number };
-export type LabelPlacement = Point & { anchor: "start" | "middle" | "end" };
+export function outsideOrigin(
+ positions: ReadonlyMap,
+ byMember: ReadonlyMap,
+): Point {
+ const total = [...byMember.values()].reduce((sum, count) => sum + count, 0) || 1;
+
+ return [...byMember].reduce(
+ (sum, [id, count]) => {
+ const point = positions.get(id);
+
+ return point
+ ? { x: sum.x + (point.x * count) / total, y: sum.y + (point.y * count) / total }
+ : sum;
+ },
+ { x: 0, y: 0 },
+ );
+}
+
+export type LabelPlacement = Point & { anchor: "start" | "middle" | "end"; leader?: Point };
export type MapLayout = {
height: number;
@@ -213,272 +234,6 @@ function placeRing(
}
}
-export type Box = { x: number; y: number; w: number; h: number };
-
-const overlaps = (a: Box, b: Box) =>
- a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
-
-/** Whether the segment from `a` to `b` passes through the box. */
-function crosses(box: Box, a: Point, b: Point) {
- // Liang–Barsky clipping: the segment meets the box when some t in [0, 1] lies inside it.
- let t0 = 0;
- let t1 = 1;
- const dx = b.x - a.x;
- const dy = b.y - a.y;
-
- for (const [p, q] of [
- [-dx, a.x - box.x],
- [dx, box.x + box.w - a.x],
- [-dy, a.y - box.y],
- [dy, box.y + box.h - a.y],
- ]) {
- if (p === 0) {
- if (q < 0) return false;
- continue;
- }
-
- const t = q / p;
-
- if (p < 0) t0 = Math.max(t0, t);
- else t1 = Math.min(t1, t);
-
- if (t0 > t1) return false;
- }
-
- return true;
-}
-
-/** The least gap between a label and any other node or label. */
-const LABEL_CLEARANCE = 4;
-
-const grow = (box: Box, by: number): Box => ({
- x: box.x - by,
- y: box.y - by,
- w: box.w + 2 * by,
- h: box.h + 2 * by,
-});
-
-/** Label text height plus its halo. */
-const LABEL_HEIGHT = 34;
-
-/** How far out a label may step from its node to clear the edges there. */
-const LABEL_GUTTER = 24;
-
-/** The gap between an outside neighbor and its name, on the side facing away from the members. */
-const OUTSIDE_LABEL_GAP = 12;
-
-type LabelItem = { id: string; radius: number; label: string; outward?: Point };
-
-function placeLabels(
- positions: ReadonlyMap,
- items: readonly LabelItem[],
- segments: readonly [Point, Point][],
- width: number,
- height: number,
- reserved: readonly Box[] = [],
-) {
- const boxes: Box[] = items.flatMap((item) => {
- const point = positions.get(item.id);
-
- return point
- ? [
- {
- x: point.x - item.radius - 3,
- y: point.y - item.radius - 3,
- w: 2 * item.radius + 6,
- h: 2 * item.radius + 6,
- },
- ]
- : [];
- });
-
- boxes.push(...reserved);
- const labels = new Map();
-
- for (const item of [...items].sort((a, b) => b.radius - a.radius || a.id.localeCompare(b.id))) {
- const point = positions.get(item.id);
-
- if (!point) continue;
- const { x, y } = point;
- const w = Math.max(...item.label.split("\n").map((line) => line.length)) * GLYPH;
- const h = LABEL_HEIGHT;
-
- // Beside the node first, then a label gutter further out, so a label can
- // step clear of the edges bundled at its node. On each ring: below,
- // above, right, left, then the four diagonals; `y` is the text baseline.
- // An outside neighbor's name goes on its own side, away from the spokes
- // running in from the members, 12px clear of the node.
- const outward = item.outward
- ? (() => {
- const r = item.radius + OUTSIDE_LABEL_GAP;
- const { x: ox, y: oy } = item.outward;
-
- if (Math.abs(ox) >= Math.abs(oy) * 0.25)
- return ox >= 0
- ? [
- {
- x: x + r,
- y: y + 4,
- anchor: "start" as const,
- box: { x: x + r, y: y - 8, w, h },
- },
- ]
- : [
- {
- x: x - r,
- y: y + 4,
- anchor: "end" as const,
- box: { x: x - r - w, y: y - 8, w, h },
- },
- ];
-
- return oy >= 0
- ? [
- {
- x,
- y: y + r + 11,
- anchor: "middle" as const,
- box: { x: x - w / 2, y: y + r, w, h },
- },
- ]
- : [
- {
- x,
- y: y - r - 4,
- anchor: "middle" as const,
- box: { x: x - w / 2, y: y - r - h, w, h },
- },
- ];
- })()
- : [];
-
- const candidates = [
- ...outward,
- ...[
- item.radius + (item.outward ? OUTSIDE_LABEL_GAP : 7),
- item.radius + LABEL_GUTTER,
- ...Array.from({ length: 12 }, (_, i) => item.radius + 40 + i * 18),
- ].flatMap((r) => {
- const d = r * Math.SQRT1_2;
-
- return [
- { x, y: y + r + 11, anchor: "middle" as const, box: { x: x - w / 2, y: y + r, w, h } },
- {
- x,
- y: y - r - 4,
- anchor: "middle" as const,
- box: { x: x - w / 2, y: y - r - h, w, h },
- },
- { x: x + r, y: y + 4, anchor: "start" as const, box: { x: x + r, y: y - 8, w, h } },
- { x: x - r, y: y + 4, anchor: "end" as const, box: { x: x - r - w, y: y - 8, w, h } },
- {
- x: x + d,
- y: y + d + 11,
- anchor: "start" as const,
- box: { x: x + d, y: y + d, w, h },
- },
- {
- x: x + d,
- y: y - d - 4,
- anchor: "start" as const,
- box: { x: x + d, y: y - d - h, w, h },
- },
- {
- x: x - d,
- y: y + d + 11,
- anchor: "end" as const,
- box: { x: x - d - w, y: y + d, w, h },
- },
- {
- x: x - d,
- y: y - d - 4,
- anchor: "end" as const,
- box: { x: x - d - w, y: y - d - h, w, h },
- },
- ];
- }),
- ].filter(
- ({ box }) =>
- box.x > 2 && box.x + box.w < width - 2 && box.y > 2 && box.y + box.h < height - 2,
- );
-
- // A label keeps LABEL_CLEARANCE from every node and label, so two never read as one stacked block.
- const clear = (box: Box) => !boxes.some((other) => overlaps(other, grow(box, LABEL_CLEARANCE)));
- const crossings = (box: Box) => segments.filter(([a, b]) => crosses(box, a, b)).length;
- // Clear of nodes and labels first, then crossing the fewest edges, then the earliest side.
- const open = candidates.filter(({ box }) => clear(box));
- const pool = open;
- const scored = pool.map((candidate) => ({ candidate, cost: crossings(candidate.box) }));
-
- const best = scored.reduce<(typeof scored)[number] | undefined>(
- (min, next) => (!min || next.cost < min.cost ? next : min),
- undefined,
- );
-
- const chosen = best?.candidate ?? {
- x,
- y: y + item.radius + 18,
- anchor: "middle" as const,
- box: { x, y, w: 0, h: 0 },
- };
-
- boxes.push(chosen.box);
- labels.set(item.id, { x: chosen.x, y: chosen.y, anchor: chosen.anchor });
- }
-
- return { labels, boxes: boxes.filter((box) => !reserved.includes(box)) };
-}
-
-/** Where along an edge its label may sit, nearest the middle first. */
-const EDGE_STOPS = [0.5];
-
-/**
- * Each labeled edge's label at the first stop along it whose box clears
- * `occupied` (node circles and labels) and the labels placed before it,
- * preferring one no other segment crosses, heaviest edges first; an edge
- * with no clear stop gets no label.
- */
-export function placeEdgeLabels(
- positions: ReadonlyMap,
- edges: readonly LayoutEdge[],
- occupied: readonly Box[],
- segments: readonly [Point, Point][] = [],
-) {
- const boxes = [...occupied];
- const placed = new Map();
- const labeled = edges.filter((edge) => edge.label);
-
- for (const edge of labeled.sort((a, b) => b.links - a.links)) {
- const a = positions.get(edge.a);
- const b = positions.get(edge.b);
-
- if (!a || !b || !edge.label) continue;
- // The count's box covers the pill overview-map.tsx draws, centered on the edge.
- const w = edge.label.text.length * GLYPH + 10;
-
- const spots = EDGE_STOPS.flatMap((t) => {
- const x = a.x + (b.x - a.x) * t;
- const y = a.y + (b.y - a.y) * t;
- const box = { x: x - w / 2, y: y - 9, w, h: 18 };
-
- return boxes.some((other) => overlaps(other, box)) ? [] : [{ x, y, box }];
- });
-
- // Prefer a stop no other edge passes through, so a count reads as its own edge's.
- const others = segments.filter(([from, to]) => !(from === a && to === b));
-
- const spot =
- spots.find((candidate) => !others.some(([from, to]) => crosses(candidate.box, from, to))) ??
- undefined;
-
- if (!spot) continue;
- boxes.push(spot.box);
- placed.set(edge.label.key, { x: spot.x, y: spot.y });
- }
-
- return placed;
-}
-
/** The share of the box the drawing, labels included, should fill. */
const FILL = 0.85;
@@ -505,11 +260,12 @@ function inset(
if (!point) continue;
const pad = node.radius + INSET;
point.x = Math.min(Math.max(point.x, pad), Math.max(pad, width - pad));
- point.y = Math.min(Math.max(point.y, pad), Math.max(pad, height - pad));
+ const padY = node.radius + 42;
+ point.y = Math.min(Math.max(point.y, padY), Math.max(padY, height - padY));
}
}
-export function layoutMap(input: LayoutInput): MapLayout {
+function layoutAtSize(input: LayoutInput): MapLayout {
const { width, height } = input;
// A member with only outside links still needs a position for its spokes.
@@ -526,6 +282,17 @@ export function layoutMap(input: LayoutInput): MapLayout {
const positions = forceLayout(drawn, input.edges, width, height);
const ring = input.outside.length > 0;
+ // Small maps stay convex so a pair never runs behind a third member.
+ if (!ring && drawn.length >= 3 && drawn.length <= 4) {
+ drawn.forEach((node, index) => {
+ const angle = Math.PI + (index * 2 * Math.PI) / drawn.length;
+ positions.set(node.id, {
+ x: width / 2 + width * 0.3 * Math.cos(angle),
+ y: height / 2 + height * 0.3 * Math.sin(angle),
+ });
+ });
+ }
+
if (positions.size)
fit(positions, width, height, ring ? 140 : spread ? 140 : 80, ring ? 70 : spread ? 60 : 30);
@@ -545,8 +312,11 @@ export function layoutMap(input: LayoutInput): MapLayout {
for (const edge of input.edges) segment(edge.a, edge.b);
- for (const neighbor of input.outside)
- for (const member of neighbor.byMember.keys()) segment(member, neighbor.id);
+ for (const neighbor of input.outside) {
+ const target = positions.get(neighbor.id);
+
+ if (target) list.push([outsideOrigin(positions, neighbor.byMember), target]);
+ }
return list;
};
@@ -579,6 +349,33 @@ export function layoutMap(input: LayoutInput): MapLayout {
}
}
+ // Outside marks need room for member labels as well as their circles.
+ for (let pass = 0; pass < 8; pass++) {
+ for (const neighbor of input.outside) {
+ const point = positions.get(neighbor.id);
+
+ if (!point) continue;
+
+ for (const node of drawn) {
+ const member = positions.get(node.id);
+
+ if (!member) continue;
+
+ const dx = point.x - member.x,
+ dy = point.y - member.y;
+
+ const distance = Math.hypot(dx, dy) || 1;
+ const gap = node.radius + OUTSIDE_RADIUS + 90;
+
+ if (distance >= gap) continue;
+ point.x += (dx / distance) * (gap - distance);
+ point.y += (dy / distance) * (gap - distance);
+ point.x = Math.max(INSET, Math.min(width - INSET, point.x));
+ point.y = Math.max(INSET, Math.min(height - INSET, point.y));
+ }
+ }
+ }
+
return placeLabels(
positions,
[
@@ -617,7 +414,7 @@ export function layoutMap(input: LayoutInput): MapLayout {
const bounds = union(placed.boxes);
if (!bounds) break;
- let sx = Math.min((FILL * width) / Math.max(bounds.w, 1), 2.5);
+ let sx = Math.min((width - 2 * INSET) / Math.max(bounds.w, 1), 2.5);
let sy = Math.min((FILL * height) / Math.max(bounds.h, 1), 2.5);
[sx, sy] = [Math.min(sx, sy * 3), Math.min(sy, sx * 3)];
@@ -634,7 +431,20 @@ export function layoutMap(input: LayoutInput): MapLayout {
placed = place();
}
- const { labels, boxes } = placed;
+ // Centre the complete drawing, including labels, rather than only its nodes.
+ const bounds = union(placed.boxes);
+ const dx = bounds ? (width - bounds.w) / 2 - bounds.x : 0;
+
+ for (const point of positions.values()) point.x += dx;
+
+ for (const label of placed.labels.values()) {
+ label.x += dx;
+
+ if (label.leader) label.leader.x += dx;
+ }
+
+ const labels = placed.labels;
+ const boxes = placed.boxes.map((box) => ({ ...box, x: box.x + dx }));
return {
height,
@@ -644,3 +454,18 @@ export function layoutMap(input: LayoutInput): MapLayout {
edgeLabels: placeEdgeLabels(positions, input.edges, boxes, segments()),
};
}
+
+/** Add room for crowded expansions rather than silently dropping their labels. */
+export function layoutMap(input: LayoutInput): MapLayout {
+ let result = layoutAtSize(input);
+
+ for (
+ let attempt = 1;
+ result.labels.size < result.positions.size && attempt <= result.positions.size;
+ attempt++
+ ) {
+ result = layoutAtSize({ ...input, height: input.height + attempt * 60 });
+ }
+
+ return result;
+}
diff --git a/web/bundled-views/group/members.test.ts b/web/bundled-views/group/members.test.ts
index ba47e01b0..c344a3de3 100644
--- a/web/bundled-views/group/members.test.ts
+++ b/web/bundled-views/group/members.test.ts
@@ -1,3 +1,4 @@
+import { mapLabelLine } from "./map-labels.ts";
import { expect, it } from "vitest";
import { AGGREGATE, SCOPE_GROUPS, SUMMARIES } from "./__fixtures__/aggregate.ts";
@@ -352,7 +353,7 @@ it("spreads the members over the box when none links to another", () => {
expect(Math.max(...ys) - Math.min(...ys)).toBeGreaterThan(40);
});
-it("places edge counts at the midpoint and omits obstructed counts", () => {
+it("puts edge counts on their stroke and finds a clear stretch before omitting obstructed counts", () => {
const positions = new Map([
["A", { x: 0, y: 100 }],
["B", { x: 200, y: 100 }],
@@ -362,12 +363,137 @@ it("places edge counts at the midpoint and omits obstructed counts", () => {
// A node label across the middle of the edge.
const middle = { x: 80, y: 80, w: 40, h: 30 };
- // 38% and 62% along still touch it; 28% clears it.
+ // The 40% and 60% stops touch it; the 30% stop clears it.
const moved = placeEdgeLabels(positions, [edge], [middle]).get("A|B");
- expect(moved).toBeUndefined();
+ expect(moved).toEqual({ x: 60, y: 100 });
expect(placeEdgeLabels(positions, [edge], []).get("A|B")).toEqual({ x: 100, y: 100 });
- const covered = { x: 0, y: 80, w: 200, h: 30 };
+ const covered = { x: 0, y: 50, w: 200, h: 100 };
expect(placeEdgeLabels(positions, [edge], [covered]).has("A|B")).toBe(false);
expect(placeEdgeLabels(positions, [{ ...edge, label: undefined }], []).size).toBe(0);
});
+
+it("anchors every label when three outside neighbors surround the largest member", () => {
+ const layout = layoutMap({
+ width: 652,
+ height: 236,
+ nodes: [
+ { id: "Specs", radius: 30, label: "Specs\n123 notes" },
+ { id: "Efforts", radius: 21.25, label: "Efforts\n52 notes" },
+ { id: "Materials", radius: 7.25, label: "Materials\n1 note" },
+ ],
+ edges: [
+ { a: "Specs", b: "Efforts", links: 127, label: { key: "se", text: "127" } },
+ { a: "Efforts", b: "Materials", links: 1, label: { key: "em", text: "1" } },
+ ],
+ outside: [
+ {
+ id: "Reference",
+ label: "Reference docs\n194 links",
+ byMember: new Map([
+ ["Specs", 170],
+ ["Efforts", 24],
+ ]),
+ },
+ {
+ id: "Untyped",
+ label: "Untyped notes\n173 links",
+ byMember: new Map([
+ ["Specs", 168],
+ ["Efforts", 5],
+ ]),
+ },
+ {
+ id: "People",
+ label: "People\n4 links",
+ byMember: new Map([
+ ["Specs", 1],
+ ["Efforts", 3],
+ ]),
+ },
+ ],
+ });
+
+ expect([...layout.labels.keys()].sort()).toEqual([...layout.positions.keys()].sort());
+});
+
+it("keeps small-map edges clear of every other node", () => {
+ const nodes = ["Delivery", "Knowledge", "Untyped", "People"].map((id) => ({
+ id,
+ radius: 30,
+ label: `${id}\n100 notes`,
+ }));
+
+ const edges = nodes.flatMap((a, i) =>
+ nodes.slice(i + 1).map((b) => ({
+ a: a.id,
+ b: b.id,
+ links: 100,
+ label: { key: `${a.id}|${b.id}`, text: "100" },
+ })),
+ );
+
+ const layout = layoutMap({ width: 652, height: 260, nodes, edges, outside: [] });
+ expect(layout.edgeLabels.size).toBe(edges.length);
+
+ for (const edge of edges) {
+ const a = layout.positions.get(edge.a)!;
+ const b = layout.positions.get(edge.b)!;
+
+ for (const node of nodes.filter((node) => node.id !== edge.a && node.id !== edge.b)) {
+ const p = layout.positions.get(node.id)!;
+
+ const t = Math.max(
+ 0,
+ Math.min(
+ 1,
+ ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) /
+ ((b.x - a.x) ** 2 + (b.y - a.y) ** 2),
+ ),
+ );
+
+ expect(Math.hypot(p.x - a.x - t * (b.x - a.x), p.y - a.y - t * (b.y - a.y))).toBeGreaterThan(
+ node.radius + 8,
+ );
+ }
+ }
+});
+
+it("aligns a label left of its node by its near end", async () => {
+ const { placeLabels } = await import("./map-labels.ts");
+
+ const { labels } = placeLabels(
+ new Map([["Knowledge", { x: 600, y: 130 }]]),
+ [
+ {
+ id: "Knowledge",
+ radius: 22,
+ label: "Knowledge\n166 notes · 3 member types",
+ alignToNode: true,
+ },
+ ],
+ [],
+ 652,
+ 260,
+ );
+
+ const label = labels.get("Knowledge")!;
+ expect(label.anchor).toBe("end");
+ expect(Math.hypot(600 - label.x, Math.max(0, label.y - 12 - 130)) - 22).toBeLessThanOrEqual(12);
+});
+
+it("fits a label wider than the canvas without adding height", () => {
+ const layout = layoutMap({
+ width: 380,
+ height: 260,
+ nodes: [{ id: "wide", radius: 20, label: "Long name ".repeat(30) }],
+ edges: [],
+ outside: [],
+ });
+
+ expect(mapLabelLine("Long name ".repeat(30), 380)).toBe(
+ "Long name Long name Long name Long name Lon…",
+ );
+ expect(layout.labels.has("wide")).toBe(true);
+ expect(layout.height).toBe(260);
+});
diff --git a/web/bundled-views/group/overview-folders.test.tsx b/web/bundled-views/group/overview-folders.test.tsx
new file mode 100644
index 000000000..dcf707e85
--- /dev/null
+++ b/web/bundled-views/group/overview-folders.test.tsx
@@ -0,0 +1,106 @@
+import { fireEvent, screen, within } from "@testing-library/react";
+import { expect, it } from "vitest";
+import { jsonReply } from "../../src/test/fakeFetch";
+import { AGGREGATE_PARTS } from "./__fixtures__/aggregate.ts";
+import { renderGroupView, scopeRoutes } from "./__fixtures__/harness.tsx";
+
+const loadOverview = () => import("./overview.tsx");
+
+const WORKSPACE = { kind: "workspace" } as const;
+
+const region = (name: string) => screen.getByRole("region", { name });
+
+function rowNamed(table: HTMLElement, name: string) {
+ const row = within(table)
+ .getAllByRole("row")
+ .find((candidate) => candidate.querySelector("td")?.textContent?.includes(name));
+
+ if (!row) throw new Error(`no row ${name}`);
+
+ return row;
+}
+
+it("lists untyped notes by folder and searches a folder, with the coverage line beneath", async () => {
+ const { posted } = await renderGroupView(loadOverview, {
+ context: WORKSPACE,
+ routes: scopeRoutes(),
+ embedded: true,
+ });
+
+ const folders = region("Untyped notes by folder");
+ expect(within(folders).getByText("17 untyped + 3 ambiguous")).toBeVisible();
+ const notes = rowNamed(within(folders).getByRole("table"), "Notes/");
+ // One line per row: the folder size and full link list live in titles.
+ expect(notes).toHaveTextContent("Notes/1240%Meetings 4, People 2");
+ expect(notes.querySelector("[title='12 of 30 notes in Notes/']")).not.toBeNull();
+ expect(notes.querySelector(".gv-ov-links")).toHaveAttribute("title", "Meetings 4, People 2");
+ expect(within(folders).queryByText("Work/")).toBeNull();
+
+ fireEvent.click(within(folders).getByRole("button", { name: "Inbox/" }));
+ expect(posted.filter((message) => message.type === "rhizome:open-search")).toEqual([
+ { type: "rhizome:open-search", folder: "Inbox" },
+ ]);
+
+ expect(region("Coverage")).toHaveTextContent(
+ "No recordsNoticesNo linksLibrary glossaries 3EmbeddedTasks 7 · items inside notes, not drawn",
+ );
+ expect(screen.queryByRole("region", { name: "Declared relations with no links" })).toBeNull();
+});
+
+it("searches the vault root's own untyped notes as folder /", async () => {
+ const { posted } = await renderGroupView(loadOverview, {
+ context: WORKSPACE,
+ embedded: true,
+ routes: scopeRoutes({
+ "GET /api/v1/ontology/shape": (request) =>
+ request.query.get("parts") === "folders"
+ ? jsonReply({
+ ...AGGREGATE_PARTS.folders,
+ folders: {
+ rows: [{ folder: "", total: 3, untyped: 2, typed: {}, untypedLinksTo: {} }],
+ },
+ })
+ : jsonReply(
+ request.query.get("parts") === "members"
+ ? AGGREGATE_PARTS.members
+ : AGGREGATE_PARTS.links,
+ ),
+ }),
+ });
+
+ fireEvent.click(within(region("Untyped notes by folder")).getByRole("button", { name: "/" }));
+
+ expect(posted.filter((message) => message.type === "rhizome:open-search")).toEqual([
+ { type: "rhizome:open-search", folder: "/" },
+ ]);
+});
+
+it("lists the eight largest folders before +N more", async () => {
+ const rows = Array.from({ length: 11 }, (_, index) => ({
+ folder: `F${index}`,
+ total: 20,
+ untyped: 20 - index,
+ typed: {},
+ untypedLinksTo: {},
+ }));
+
+ await renderGroupView(loadOverview, {
+ context: WORKSPACE,
+ embedded: true,
+ routes: scopeRoutes({
+ "GET /api/v1/ontology/shape": (request) =>
+ request.query.get("parts") === "folders"
+ ? jsonReply({ ...AGGREGATE_PARTS.folders, folders: { rows } })
+ : jsonReply(
+ request.query.get("parts") === "members"
+ ? AGGREGATE_PARTS.members
+ : AGGREGATE_PARTS.links,
+ ),
+ }),
+ });
+
+ const folders = within(region("Untyped notes by folder"));
+ expect(folders.getAllByRole("row")).toHaveLength(1 + 8);
+ fireEvent.click(folders.getByRole("button", { name: "Show 3 more" }));
+ expect(folders.getAllByRole("row")).toHaveLength(1 + 11);
+});
diff --git a/web/bundled-views/group/overview-map-parts.tsx b/web/bundled-views/group/overview-map-parts.tsx
new file mode 100644
index 000000000..fb96c0512
--- /dev/null
+++ b/web/bundled-views/group/overview-map-parts.tsx
@@ -0,0 +1,349 @@
+import { plural } from "./briefing-parts.tsx";
+import {
+ edgeKey,
+ type DeclaredRelation,
+ type LinkModel,
+ type MapEdge,
+ type OutsideNeighbor,
+ type ScopeModel,
+ type ScopeNode,
+} from "./scope.ts";
+import type { TypeSummary } from "./aggregate.ts";
+
+export const OUTSIDE_RING = 7;
+
+const fmt = (count: number) => count.toLocaleString("en-US");
+
+/** The neutral: interfaces, collapsed groups, and untyped notes. */
+const NEUTRAL = "var(--type-8)";
+
+/** A type's palette color, from the kit's `useTypeColors`. */
+export type TypeColor = (name: string) => string;
+
+/**
+ * A node's color. A type keeps the hue it has in the Atlas, Explorer, and
+ * type pages; interfaces, collapsed groups, and untyped notes are neutral, and
+ * the map rings an interface or group in its member types' hues.
+ */
+export function nodeHue(node: Pick, color: TypeColor) {
+ return node.kind === "type" || node.kind === "interface" ? color(node.name) : NEUTRAL;
+}
+
+/** The ring around a node that stands for several types: one arc per type, sized by records. */
+export function compositionArcs(
+ node: ScopeNode,
+ summaries: ReadonlyMap,
+ color: TypeColor,
+ radius = 30,
+) {
+ if (node.kind !== "group" && node.kind !== "interface") return [];
+
+ const parts = node.types
+ .map((name) => ({ name, count: summaries.get(name)?.count ?? 0 }))
+ .filter((part) => part.count > 0);
+
+ const total = parts.reduce((sum, part) => sum + part.count, 0);
+ const circumference = 2 * Math.PI * (radius - Math.max(4, radius * 0.32) / 2);
+ const minimum = Math.min(4 / circumference, 1 / parts.length);
+ let remaining = 1;
+ let weight = total;
+ const shares = new Map();
+
+ for (const part of [...parts].sort((a, b) => a.count - b.count)) {
+ const share = Math.max(minimum, (remaining * part.count) / weight);
+ shares.set(part.name, share);
+ remaining -= share;
+ weight -= part.count;
+ }
+
+ let start = 0;
+
+ return parts.map((part) => {
+ const arc = {
+ name: part.name,
+ color: color(part.name),
+ start,
+ share: shares.get(part.name) ?? 0,
+ };
+
+ start += arc.share;
+
+ return arc;
+ });
+}
+
+/** Declared relations no record uses between members with no edge, one hairline per pair. */
+export function unusedPairs(links: LinkModel, relations: readonly DeclaredRelation[]) {
+ const pairs = new Map();
+
+ for (const relation of relations) {
+ const key = edgeKey(relation.member, relation.target);
+
+ if (relation.count === 0 && !links.edgeIndex.has(key))
+ pairs.set(key, { a: relation.member, b: relation.target });
+ }
+
+ return [...pairs.values()];
+}
+
+export type Hot = { kind: "node"; id: string } | { kind: "edge"; key: string } | null;
+
+export type MapProps = {
+ model: ScopeModel;
+ links: LinkModel;
+ relations: readonly DeclaredRelation[];
+ summaries: ReadonlyMap;
+ /** Named groups expanded at All notes. */
+ expanded: ReadonlySet;
+ onExpand: (group: string, open: boolean) => void;
+};
+
+/** Node area follows record count. */
+export function nodeRadius(model: ScopeModel) {
+ const max = Math.max(1, ...model.nodes.map((node) => node.count));
+
+ return (node: ScopeNode) => 5 + 25 * Math.sqrt(node.count / max);
+}
+
+export const nodeText = (node: ScopeNode) =>
+ `${node.label}\n${fmt(node.count)} ${plural(node.count, "note", "notes")}${node.kind === "group" ? ` · ${node.members.length} member ${plural(node.members.length, "type", "types")}` : ""}`;
+
+const memberLinks = (links: LinkModel, id: string) =>
+ links.edges.reduce((sum, edge) => sum + (edge.a === id || edge.b === id ? edge.links : 0), 0);
+
+export function nodeName(model: ScopeModel, links: LinkModel, node: ScopeNode) {
+ const unit =
+ node.kind === "untyped"
+ ? plural(node.count, "note", "notes")
+ : plural(node.count, "record", "records");
+
+ const linked = memberLinks(links, node.id);
+ const inGroup = model.scope.kind === "group" ? " to other members" : "";
+
+ const state =
+ node.kind === "group"
+ ? `, collapsed group of ${node.members.length} ${plural(node.members.length, "type", "types")}`
+ : "";
+
+ return `${node.label}, ${fmt(node.count)} ${unit}, ${fmt(linked)} ${plural(linked, "link", "links")}${inGroup}${state}`;
+}
+
+export function NodeTip({
+ model,
+ links,
+ node,
+}: {
+ model: ScopeModel;
+ links: LinkModel;
+ node: ScopeNode;
+}) {
+ const own = links.self.get(node.id) ?? 0;
+ const linked = memberLinks(links, node.id);
+
+ return (
+ <>
+ {node.label}
+
+ {fmt(node.count)}{" "}
+ {node.kind === "untyped"
+ ? plural(node.count, "note", "notes")
+ : plural(node.count, "record", "records")}{" "}
+ · {fmt(linked)} {plural(linked, "link", "links")}
+ {model.scope.kind === "group" ? " in the group" : ""}
+
+ {own > 0 && (
+
+ {fmt(own)} {node.kind === "group" ? "links inside the group" : "among themselves"}
+
+ )}
+ {node.kind === "group" && Activate to expand }
+ >
+ );
+}
+
+export function EdgeTip({
+ edge,
+ label,
+ summaries,
+ trace,
+}: {
+ edge: MapEdge;
+ label: (id: string) => string;
+ summaries: ReadonlyMap;
+ trace: boolean;
+}) {
+ return (
+ <>
+
+ {label(edge.a)} — {label(edge.b)}
+
+
+ {fmt(edge.links)} {plural(edge.links, "link", "links")}
+
+ {edge.fields.map((field) => (
+
+ {summaries.get(field.type)?.label ?? field.type}.{field.field} {fmt(field.count)}
+
+ ))}
+ {edge.plainLinks > 0 && Plain links {fmt(edge.plainLinks)} }
+ {edge.plainLinks > 0 && edge.relationLinks > 0 && (
+ Mostly {edge.relation ? "relations" : "plain links"}
+ )}
+ {trace && Activate to open Trace }
+ >
+ );
+}
+
+export function OutsideTip({ model, neighbor }: { model: ScopeModel; neighbor: OutsideNeighbor }) {
+ return (
+ <>
+ {neighbor.label}
+
+ {fmt(neighbor.links)} {plural(neighbor.links, "link", "links")} to{" "}
+ {model.scope.kind === "group" ? model.scope.group : "the scope"} · outside the group
+
+ >
+ );
+}
+
+export function MapLegend({
+ model,
+ links,
+ drawn,
+ summaries,
+ color,
+ unused,
+ expanded,
+ onExpand,
+}: {
+ model: ScopeModel;
+ links: LinkModel;
+ /** The members drawn on the map; the legend keys only what they show. */
+ drawn: readonly ScopeNode[];
+ summaries: ReadonlyMap;
+ color: TypeColor;
+ unused: boolean;
+ expanded: ReadonlySet;
+ onExpand: (group: string, open: boolean) => void;
+}) {
+ const shown = Math.min(OUTSIDE_RING, links.outside.length);
+ // An interface's ring names its segments; a collapsed group's ring stays one key.
+ const rings = drawn.filter((node) => node.kind === "interface" || node.kind === "group");
+ const label = (name: string) => summaries.get(name)?.label ?? name;
+
+ const familyLabel = (name: string, family: ScopeNode) => {
+ const suffix = label(name).split(" ").at(-1);
+
+ return family.kind === "interface" &&
+ family.types.length > 1 &&
+ suffix &&
+ family.types.every((type) => label(type).endsWith(` ${suffix}`))
+ ? label(name).slice(0, -(suffix.length + 1))
+ : label(name);
+ };
+
+ const types = drawn
+ .filter((node) => node.kind !== "group" && node.kind !== "interface" && node.kind !== "untyped")
+ .map((node) => (
+
+
+ {node.label} {fmt(node.count)}
+
+ ));
+
+ const kinds = [
+ links.edges.some((edge) => edge.relation) && (
+
+
+ Relations
+
+ ),
+ links.edges.some((edge) => !edge.relation) && (
+
+
+ Plain links
+
+ ),
+ unused && (
+
+
+ declared, unused
+
+ ),
+ ].filter((item) => item !== false);
+
+ if (links.outside.length > 0)
+ kinds.push(
+
+
+ Outside links
+ {links.outside.length > shown && ` (top ${shown} of ${links.outside.length})`}
+ ,
+ );
+
+ const groups = [
+ ...rings.map((node) => ({
+ title: node.label,
+ // Types with no records draw no segment; Coverage already names them.
+ items: node.types
+ .filter((name) => (summaries.get(name)?.count ?? 0) > 0)
+ .map((name) => (
+
+
+ {familyLabel(
+ name,
+ node.kind === "group"
+ ? (node.members.find((member) => member.types.includes(name)) ?? node)
+ : node,
+ )}{" "}
+ {fmt(summaries.get(name)?.count ?? 0)}
+
+ )),
+ })),
+ { title: "Types", items: types },
+ {
+ title: "Untyped",
+ items: drawn.some((node) => node.kind === "untyped")
+ ? [
+
+
+ {model.untyped?.label ?? "Untyped notes"}
+ ,
+ ]
+ : [],
+ },
+ ...model.groupNames
+ .filter((name) => expanded.has(name))
+ .map((name) => ({
+ title: name,
+ items: [
+ onExpand(name, false)}
+ >
+ Collapse
+ ,
+ ],
+ })),
+ ].filter((group) => group.items.length > 0);
+
+ if (kinds.length) groups.push({ title: "Lines", items: kinds });
+
+ return (
+ <>
+
+ {groups.map((group) => (
+
+
{group.title}
+ {group.items}
+
+ ))}
+
+ {model.scope.kind === "group" && links.edges.length === 0 && (
+ No member records link to each other.
+ )}
+ >
+ );
+}
diff --git a/web/bundled-views/group/overview-map.tsx b/web/bundled-views/group/overview-map.tsx
index 425d08d17..99e8296db 100644
--- a/web/bundled-views/group/overview-map.tsx
+++ b/web/bundled-views/group/overview-map.tsx
@@ -1,42 +1,30 @@
+import { mapLabelLine } from "./map-labels.ts";
// The Overview map (SPEC-0117 US1, US3): one node per member, sized by its
// records, edges counting the record links between members, faded outside
-// neighbors on a ring, and members without links listed in the legend. Nodes take
+// neighbors on a ring, and members without links listed in the side panel. Nodes take
// keyboard focus most records first; hovering or focusing one highlights its
// edges and shows its figures. The Matrix is the text alternative.
import { openCollection, openView, useTypeColors } from "@rhizome/kit";
import { useEffect, useMemo, useRef, useState } from "react";
-import { layoutMap, OUTSIDE_RADIUS, type Point } from "./map-layout.ts";
-import { plural } from "./briefing-parts.tsx";
-import {
- edgeKey,
- type DeclaredRelation,
- type LinkModel,
- type MapEdge,
- type OutsideNeighbor,
- type ScopeModel,
- type ScopeNode,
-} from "./scope.ts";
-import type { TypeSummary } from "./aggregate.ts";
-
-/** Outside neighbors drawn on the ring; the legend counts the rest. */
-export const OUTSIDE_RING = 7;
+import { layoutMap, outsideOrigin, OUTSIDE_RADIUS, type Point } from "./map-layout.ts";
+import { edgeKey, type MapEdge, type ScopeNode } from "./scope.ts";
/** The layout width before the canvas is measured, and where it cannot be measured. */
const WIDTH = 760;
-/** The map's height: with its title and three-row legend the block stays within about 360px. */
-const HEIGHT = 236;
+/** The map's height: with its title and separate line-style legend the block stays within about 360px. */
+const HEIGHT = 260;
/** A count's pill: 5px of surface beside its digits, on the edge it counts. */
-const COUNT_PAD = 2;
+const COUNT_PAD = 4;
const COUNT_DIGIT = 7;
const COUNT_HEIGHT = 17;
/** Edge strokes run from 1px to this many, by link count, so no edge outweighs the nodes it joins. */
-const MAX_STROKE = 3.5;
+const MAX_STROKE = 2.75;
/** The canvas's width in CSS pixels, so the map fills its column and labels draw at their real size. */
function useCanvasWidth() {
@@ -65,168 +53,25 @@ function useCanvasWidth() {
return { ref, width };
}
-const fmt = (count: number) => count.toLocaleString("en-US");
-
-/** The neutral: interfaces, collapsed groups, and untyped notes. */
-const NEUTRAL = "var(--type-8)";
-
-/** A type's palette color, from the kit's `useTypeColors`. */
-export type TypeColor = (name: string) => string;
-
-/**
- * A node's color. A type keeps the hue it has in the Atlas, Explorer, and
- * type pages; interfaces, collapsed groups, and untyped notes are neutral, and
- * the map rings an interface or group in its member types' hues.
- */
-export function nodeHue(node: Pick, color: TypeColor) {
- return node.kind === "type" || node.kind === "interface" ? color(node.name) : NEUTRAL;
-}
-
-/** The ring around a node that stands for several types: one arc per type, sized by records. */
-function compositionArcs(
- node: ScopeNode,
- summaries: ReadonlyMap,
- color: TypeColor,
-) {
- if (node.kind !== "group" && node.kind !== "interface") return [];
-
- const parts = node.types
- .map((name) => ({ name, count: summaries.get(name)?.count ?? 0 }))
- .filter((part) => part.count > 0);
-
- const total = parts.reduce((sum, part) => sum + part.count, 0);
- let start = 0;
-
- return parts.map((part) => {
- const arc = { name: part.name, color: color(part.name), start, share: part.count / total };
- start += arc.share;
-
- return arc;
- });
-}
-
-/** Declared relations no record uses between members with no edge, one hairline per pair. */
-export function unusedPairs(links: LinkModel, relations: readonly DeclaredRelation[]) {
- const pairs = new Map();
-
- for (const relation of relations) {
- const key = edgeKey(relation.member, relation.target);
-
- if (relation.count === 0 && !links.edgeIndex.has(key))
- pairs.set(key, { a: relation.member, b: relation.target });
- }
-
- return [...pairs.values()];
-}
-
-type Hot = { kind: "node"; id: string } | { kind: "edge"; key: string } | null;
-
-type MapProps = {
- model: ScopeModel;
- links: LinkModel;
- relations: readonly DeclaredRelation[];
- summaries: ReadonlyMap;
- /** Named groups expanded at All notes. */
- expanded: ReadonlySet;
- onExpand: (group: string, open: boolean) => void;
-};
-
-/** Node area follows record count. */
-function nodeRadius(model: ScopeModel) {
- const max = Math.max(1, ...model.nodes.map((node) => node.count));
-
- return (node: ScopeNode) => 5 + 25 * Math.sqrt(node.count / max);
-}
-
-const nodeText = (node: ScopeNode) =>
- `${node.label}\n${fmt(node.count)} ${plural(node.count, "note", "notes")}${node.kind === "group" ? ` · ${node.members.length} ${plural(node.members.length, "type", "types")}` : ""}`;
-
-const memberLinks = (links: LinkModel, id: string) =>
- links.edges.reduce((sum, edge) => sum + (edge.a === id || edge.b === id ? edge.links : 0), 0);
-
-function nodeName(model: ScopeModel, links: LinkModel, node: ScopeNode) {
- const unit =
- node.kind === "untyped"
- ? plural(node.count, "note", "notes")
- : plural(node.count, "record", "records");
-
- const linked = memberLinks(links, node.id);
- const inGroup = model.scope.kind === "group" ? " to other members" : "";
-
- const state =
- node.kind === "group"
- ? `, collapsed group of ${node.members.length} ${plural(node.members.length, "type", "types")}`
- : "";
-
- return `${node.label}, ${fmt(node.count)} ${unit}, ${fmt(linked)} ${plural(linked, "link", "links")}${inGroup}${state}`;
-}
-
-function NodeTip({ model, links, node }: { model: ScopeModel; links: LinkModel; node: ScopeNode }) {
- const own = links.self.get(node.id) ?? 0;
- const linked = memberLinks(links, node.id);
-
- return (
- <>
- {node.label}
-
- {fmt(node.count)}{" "}
- {node.kind === "untyped"
- ? plural(node.count, "note", "notes")
- : plural(node.count, "record", "records")}{" "}
- · {fmt(linked)} {plural(linked, "link", "links")}
- {model.scope.kind === "group" ? " in the group" : ""}
-
- {own > 0 && (
-
- {fmt(own)} {node.kind === "group" ? "links inside the group" : "among themselves"}
-
- )}
- {node.kind === "group" && Activate to expand }
- >
- );
-}
-
-function EdgeTip({
- edge,
- label,
- summaries,
- trace,
-}: {
- edge: MapEdge;
- label: (id: string) => string;
- summaries: ReadonlyMap;
- trace: boolean;
-}) {
- return (
- <>
-
- {label(edge.a)} — {label(edge.b)}
-
-
- {fmt(edge.links)} {plural(edge.links, "link", "links")}
-
- {edge.fields.map((field) => (
-
- {summaries.get(field.type)?.label ?? field.type}.{field.field} {fmt(field.count)}
-
- ))}
- {edge.plainLinks > 0 && plain links {fmt(edge.plainLinks)} }
- {trace && Activate to open Trace }
- >
- );
-}
+import {
+ OUTSIDE_RING,
+ compositionArcs,
+ nodeHue,
+ unusedPairs,
+ nodeRadius,
+ nodeText,
+ nodeName,
+ NodeTip,
+ EdgeTip,
+ OutsideTip,
+ MapLegend,
+ type Hot,
+ type MapProps,
+} from "./overview-map-parts.tsx";
+
+export { nodeHue, unusedPairs, OUTSIDE_RING } from "./overview-map-parts.tsx";
-function OutsideTip({ model, neighbor }: { model: ScopeModel; neighbor: OutsideNeighbor }) {
- return (
- <>
- {neighbor.label}
-
- {fmt(neighbor.links)} {plural(neighbor.links, "link", "links")} to{" "}
- {model.scope.kind === "group" ? model.scope.group : "the scope"} · outside the group
-
- >
- );
-}
+const fmt = (count: number) => count.toLocaleString("en-US");
export function ScopeMap({ model, links, relations, summaries, expanded, onExpand }: MapProps) {
const [hot, setHot] = useState(null);
@@ -253,6 +98,7 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
id: node.id,
radius: size(node),
label: nodeText(node),
+ alignToNode: node.kind === "group",
})),
edges: links.edges.map((edge) => ({
...edge,
@@ -260,7 +106,7 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
})),
outside: links.outside.slice(0, OUTSIDE_RING).map((neighbor) => ({
...neighbor,
- label: `${neighbor.label} ${fmt(neighbor.links)} links`,
+ label: `${neighbor.label}\n${fmt(neighbor.links)} links`,
})),
});
}, [model, links, group, maxLinks, width]);
@@ -334,7 +180,6 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
.filter((node) => !looseIds.has(node.id))
.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
- const loose = model.nodes.filter((node) => looseIds.has(node.id));
const countAt = (edge: MapEdge) => layout.edgeLabels.get(edge.key);
return (
@@ -357,19 +202,57 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
y2={at(pair.b).y}
/>
))}
- {ring.flatMap((neighbor) =>
- [...neighbor.byMember].map(([member, count]) => (
-
- )),
+ {ring.map((neighbor) => {
+ const members = [...neighbor.byMember];
+ const from = outsideOrigin(layout.positions, neighbor.byMember);
+
+ const details =
+ hot?.kind === "node" && (hot.id === neighbor.id || neighbor.byMember.has(hot.id));
+
+ return (
+
+ {details ? (
+ members.map(([member, count]) => (
+
+ ))
+ ) : (
+
+
+ {neighbor.links} links to {neighbor.label}
+
+
+ )}
+
+ );
+ })}
+ {[...layout.labels].map(
+ ([id, place]) =>
+ place.leader && (
+
+ ),
)}
{links.edges.map((edge) => (
- setHot({ kind: "edge", key: edge.key })}
onMouseLeave={() => setHot(null)}
onClick={() => {
@@ -414,7 +294,7 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
onMouseLeave={() => setHot(null)}
>
{`${neighbor.label}, ${fmt(neighbor.links)} links, outside the group`}
-
+
);
})}
@@ -422,7 +302,7 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
const point = at(node.id);
const r = radius(node);
const hue = nodeHue(node, color);
- const arcs = compositionArcs(node, summaries, color);
+ const arcs = compositionArcs(node, summaries, color, r);
return (
- {neighbor.label}{" "}
+ {neighbor.label}
+ {mapLabelLine(neighbor.label, width)}{" "}
- {fmt(neighbor.links)} links
+ {mapLabelLine(`${fmt(neighbor.links)} links`, width)}
)
@@ -540,12 +421,10 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
y={place.y}
textAnchor={place.anchor}
>
- {node.label}{" "}
+ {node.label}
+ {mapLabelLine(node.label, width)}{" "}
- {fmt(node.count)} {plural(node.count, "note", "notes")}
- {node.kind === "group"
- ? ` · ${node.members.length} ${plural(node.members.length, "type", "types")}`
- : ""}
+ {mapLabelLine(nodeText(node).split("\n")[1] ?? "", width)}
)
@@ -578,153 +457,10 @@ export function ScopeMap({ model, links, relations, summaries, expanded, onExpan
drawn={ordered}
summaries={summaries}
color={color}
- loose={loose}
unused={drawnUnused.length > 0}
expanded={expanded}
onExpand={onExpand}
- onOpen={activate}
/>
);
}
-
-function MapLegend({
- model,
- links,
- drawn,
- summaries,
- color,
- loose,
- unused,
- expanded,
- onExpand,
- onOpen,
-}: {
- model: ScopeModel;
- links: LinkModel;
- /** The members drawn on the map; the legend keys only what they show. */
- drawn: readonly ScopeNode[];
- summaries: ReadonlyMap
;
- color: TypeColor;
- loose: readonly ScopeNode[];
- unused: boolean;
- expanded: ReadonlySet;
- onExpand: (group: string, open: boolean) => void;
- onOpen: (node: ScopeNode) => void;
-}) {
- const shown = Math.min(OUTSIDE_RING, links.outside.length);
- // An interface's ring names its segments; a collapsed group's ring stays one key.
- const rings = drawn.filter((node) => node.kind === "interface" || node.kind === "group");
- const label = (name: string) => summaries.get(name)?.label ?? name;
-
- const types = [
- ...drawn
- .filter(
- (node) => node.kind !== "group" && node.kind !== "interface" && node.kind !== "untyped",
- )
- .map((node) => (
-
-
- {node.label}
-
- )),
- ...rings.map((node) => (
-
-
- {node.label}:
- {compositionArcs(node, summaries, color).map((arc) => (
-
-
- {label(arc.name)}
-
- ))}
-
- )),
- drawn.some((node) => node.kind === "untyped") && (
-
-
- untyped
-
- ),
- ...model.groupNames.flatMap((name) =>
- expanded.has(name)
- ? [
-
- {name}{" "}
- onExpand(name, false)}>
- collapse
-
- ,
- ]
- : [],
- ),
- loose.length > 0 && (
-
- No member links:
- {loose.map((node) => (
- onOpen(node)}
- >
- {node.label} {fmt(node.count)}
-
- ))}
-
- ),
- ].filter(Boolean);
-
- const kinds = [
- links.edges.some((edge) => edge.relation) && (
-
-
- mostly relation links
-
- ),
- links.edges.some((edge) => !edge.relation) && (
-
-
- mostly plain links
-
- ),
- unused && (
-
-
- declared, unused
-
- ),
- ].filter(Boolean);
-
- if (links.outside.length > 0)
- kinds.push(
-
-
- {links.outside.length > shown
- ? `top ${shown} of ${links.outside.length} outside links`
- : "outside links"}
- ,
- );
-
- const groups = [
- { title: "Types", items: types },
- { title: "Links", items: kinds },
- ].filter((group) => group.items.length > 0);
-
- return (
- <>
-
- {groups.map((group) => (
-
-
{group.title}
- {group.items}
-
- ))}
-
- {model.scope.kind === "group" && links.edges.length === 0 && (
- No member records link to each other.
- )}
- >
- );
-}
diff --git a/web/bundled-views/group/overview-polish.test.tsx b/web/bundled-views/group/overview-polish.test.tsx
new file mode 100644
index 000000000..83b5564fb
--- /dev/null
+++ b/web/bundled-views/group/overview-polish.test.tsx
@@ -0,0 +1,120 @@
+import { fireEvent, screen, within } from "@testing-library/react";
+import { expect, it } from "vitest";
+import { fixtureModel, renderGroupView, scopeRoutes } from "./__fixtures__/harness.tsx";
+
+const loadOverview = () => import("./overview.tsx");
+
+it("places group Members across the columns before outside previews and guide", async () => {
+ await renderGroupView(loadOverview, { routes: scopeRoutes() });
+ const main = screen.getByRole("region", { name: "Map" }).closest(".gv-ov-main");
+
+ const members = screen.getByRole("region", { name: "Members" });
+ expect(main).not.toContainElement(members);
+ expect(members.closest(".gv-ov-members")?.parentElement).toHaveClass("gv-ov--group");
+ const below = screen.getByRole("region", { name: "Guide and views" }).closest(".gv-ov-below");
+ expect(below).toContainElement(screen.getByRole("region", { name: "Guide and views" }));
+ expect(
+ screen.getByRole("region", { name: "Outside the group" }).querySelectorAll("li"),
+ ).toHaveLength(3);
+ expect(screen.queryByRole("region", { name: "Outside notes" })).toBeNull();
+ expect(main).not.toContainElement(screen.getByRole("region", { name: "Outside the group" }));
+});
+
+it("nests a collapsed group's type swatches under its member families", async () => {
+ await renderGroupView(loadOverview, { context: { kind: "workspace" }, routes: scopeRoutes() });
+ const map = screen.getByRole("region", { name: "Map" });
+ const planning = within(map).getByText("Planning", { selector: "dt" }).parentElement;
+
+ expect(planning).toHaveTextContent("Story 4");
+ expect(planning?.querySelectorAll("dd > span").length).toBeGreaterThan(4);
+ expect(map).toHaveTextContent("4 member types");
+ expect(map).toHaveTextContent("Plain links");
+ expect(map).not.toHaveTextContent("mostly plain links");
+});
+
+it("keeps tiny nonempty ring segments at least four pixels while preserving the full circle", async () => {
+ const { compositionArcs } = await import("./overview-map-parts.tsx");
+ const { AGGREGATE, SCOPE_GROUPS, SUMMARIES } = await import("./__fixtures__/aggregate.ts");
+ const { scopeModel } = await import("./scope.ts");
+
+ if (!AGGREGATE.members) throw new Error("missing fixture members");
+
+ const model = scopeModel({
+ scope: { kind: "workspace" },
+ groups: SCOPE_GROUPS.groups,
+ members: AGGREGATE.members,
+ summaries: SUMMARIES,
+ expanded: new Set(),
+ });
+
+ const node = model?.nodes.find((item) => item.kind === "group" && item.types.length > 2);
+
+ if (!node) throw new Error("missing composite fixture");
+ const summaries = new Map(SUMMARIES);
+ node.types.forEach((name, index) => {
+ const summary = summaries.get(name);
+
+ if (summary) summaries.set(name, { ...summary, count: index ? 1 : 10000 });
+ });
+ const radius = 30;
+ const circumference = 2 * Math.PI * (radius - (radius * 0.32) / 2);
+ const arcs = compositionArcs(node, summaries, (name) => name, radius);
+ expect(arcs.reduce((sum, arc) => sum + arc.share, 0)).toBeCloseTo(1);
+
+ for (const arc of arcs) expect(arc.share * circumference).toBeGreaterThanOrEqual(4 - 1e-9);
+ expect(arcs[0].share).toBeGreaterThan(arcs[1].share);
+});
+
+it("names line keys separately and reconciles the combined untyped bucket", async () => {
+ await renderGroupView(loadOverview, { context: { kind: "workspace" }, routes: scopeRoutes() });
+ const members = screen.getByRole("region", { name: "Members" });
+
+ expect(members).toHaveTextContent("29 typed · 17 untyped + 3 ambiguous");
+ const row = within(members).getByRole("row", { name: /Untyped \+ ambiguous/ });
+
+ expect(within(row).getAllByRole("cell")[1]).toHaveTextContent("20");
+
+ const lines = within(screen.getByRole("region", { name: "Map" })).getByText("Lines", {
+ selector: "dt",
+ }).parentElement;
+
+ expect(lines).toHaveTextContent("Plain links");
+ expect(lines).not.toHaveTextContent("Untyped");
+});
+
+it("names a zero-row disclosure and puts its caveat in heading help", async () => {
+ const model = fixtureModel("Planning");
+
+ const notes = [
+ { key: "outside", path: "outside.md", title: "Outside", type: null, touches: ["record"] },
+ ];
+
+ await renderGroupView(async () => {
+ const { OutsideNotes } = await import("./overview-side-parts.tsx");
+
+ return {
+ default: () => (
+
+ ),
+ };
+ });
+ const outside = screen.getByRole("region", { name: "Outside the group" });
+
+ expect(outside.querySelectorAll("li")).toHaveLength(0);
+ expect(within(outside).getByRole("heading")).toHaveAttribute(
+ "title",
+ expect.stringContaining("More notes may link"),
+ );
+ expect(within(outside).getByRole("button", { name: "Search all notes" })).toBeVisible();
+ fireEvent.click(within(outside).getByRole("button", { name: "Show 1 note" }));
+ expect(outside.querySelectorAll("li")).toHaveLength(1);
+ fireEvent.click(within(outside).getByRole("button", { name: "Show fewer" }));
+ expect(outside.querySelectorAll("li")).toHaveLength(0);
+});
diff --git a/web/bundled-views/group/overview-side-parts.test.ts b/web/bundled-views/group/overview-side-parts.test.ts
new file mode 100644
index 000000000..841cce325
--- /dev/null
+++ b/web/bundled-views/group/overview-side-parts.test.ts
@@ -0,0 +1,9 @@
+import { expect, it } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+import { createElement } from "react";
+import { LinkSummary } from "./overview-side-parts.tsx";
+
+it("retains every destination and its count", () => {
+ const text = "Reference docs 53, Technical specs 41";
+ expect(renderToStaticMarkup(createElement(LinkSummary, { text }))).toContain(text);
+});
diff --git a/web/bundled-views/group/overview-side-parts.tsx b/web/bundled-views/group/overview-side-parts.tsx
new file mode 100644
index 000000000..33f823f54
--- /dev/null
+++ b/web/bundled-views/group/overview-side-parts.tsx
@@ -0,0 +1,182 @@
+import { openNote, openSearch, openView, typeLabel } from "@rhizome/kit";
+import { type Boundary } from "./activity.ts";
+import { readableTitle } from "./briefing-activity.tsx";
+import { Block, MoreToggle, lower, plural } from "./briefing-parts.tsx";
+import { fieldLabel, type GroupModel } from "./model.ts";
+import { useRememberedOpen } from "./remembered.ts";
+
+const folderOf = (path: string) => path.split("/").slice(0, -1).join("/");
+
+/** A note type's label, lowercased and counted. */
+function typeName(model: GroupModel, type: string, count: number) {
+ const labels = model.typeLabels.get(type);
+
+ return lower(labels ? typeLabel(labels, { count }) : fieldLabel(type));
+}
+
+/** A label at the start of a line, in sentence case: "Technical spec". */
+const sentence = (label: string) => label.charAt(0).toUpperCase() + label.slice(1);
+
+/** A note type's label outside the records, or "untyped note". */
+function outsideLabel(model: GroupModel, type: string | null, count: number) {
+ return type === null
+ ? plural(count, "untyped note", "untyped notes")
+ : typeName(model, type, count);
+}
+
+/**
+ * Notes outside the records that link with them, as `boundary()` finds them:
+ * counts by type, then the most connected notes.
+ */
+export function OutsideNotes({
+ model,
+ outside,
+ title,
+ info,
+ empty,
+ limit = 3,
+}: {
+ model: GroupModel;
+ outside: Boundary;
+ title: string;
+ info: string;
+ empty: string;
+ /** Notes listed before "Show N more". */
+ limit?: number;
+}) {
+ const expanded = useRememberedOpen("briefing.expanded");
+ const open = expanded.isOpen("outside", false);
+ const setOpen = (next: boolean) => expanded.setOpen("outside", next);
+ const shown = open ? outside.notes : outside.notes.slice(0, limit);
+
+ return (
+
+ {outside.byType.length > 0 && (
+
+ {outside.byType.map((entry) => (
+
+ {entry.count} {outsideLabel(model, entry.type, entry.count)}
+
+ ))}
+
+ )}
+ {outside.notes.length === 0 && {empty}
}
+
+ {shown.map((note) => {
+ // A timestamped file name reads by its slug; the file name stays as evidence.
+ const readable = readableTitle(note.title);
+
+ return (
+
+
+ openNote(note.path)}
+ >
+ {readable ?? note.title}
+
+
+ {sentence(outsideLabel(model, note.type, 1))}
+ {(readable || folderOf(note.path)) && (
+ <>
+ {" · "}
+
+ {readable ? note.path : `${folderOf(note.path)}/`}
+
+ >
+ )}
+
+
+
+ {note.touches.length}
+
+ {" "}
+ linked {plural(note.touches.length, "record", "records")}
+
+
+
+ );
+ })}
+
+
+ {outside.notes.length > limit &&
+ (!open && limit === 0 ? (
+ setOpen(true)}>
+ Show {outside.notes.length} {plural(outside.notes.length, "note", "notes")}
+
+ ) : (
+ setOpen(!open)}
+ />
+ ))}
+ {outside.incomplete && (
+ <>
+ {outside.notes.length > limit && · }
+ openSearch({ folder: "" })}>
+ Search all notes
+
+ >
+ )}
+
+
+ );
+}
+
+export function GuideAndViews({ model }: { model: GroupModel }) {
+ const { guide, views } = model;
+
+ return (
+
+ {!guide && !views.length && (
+ No guide note or authored views.
+ )}
+ {guide && (
+ <>
+ openNote(guide.path)}
+ >
+ {guide.title}
+
+
+ Guide shared by {guide.sharedBy} of {model.members.length}{" "}
+ {plural(model.members.length, "type", "types")}
+
+ >
+ )}
+ {views.map((view) => (
+ openView(view.id, { kind: "group", group: model.name })}
+ >
+ {view.name}
+
+ ))}
+
+ );
+}
+
+/** Keep every destination readable as the folder column wraps. */
+export function LinkSummary({ text }: { text: string }) {
+ return {text} ;
+}
diff --git a/web/bundled-views/group/overview-side.tsx b/web/bundled-views/group/overview-side.tsx
index 432d777e5..835ad4809 100644
--- a/web/bundled-views/group/overview-side.tsx
+++ b/web/bundled-views/group/overview-side.tsx
@@ -3,17 +3,17 @@
// declared but unused, the notes outside the group linking to the most of its
// records, and the group's guide and views.
import { openSearch } from "@rhizome/kit";
-import { Fragment, useMemo, type ReactNode } from "react";
+import { Fragment, useEffect, useRef, useState, useMemo, type ReactNode } from "react";
import { boundary } from "./activity.ts";
-import { OutsideNotes } from "./briefing-activity.tsx";
-import { GuideAndViews } from "./briefing-contents.tsx";
+import { LinkSummary, OutsideNotes } from "./overview-side-parts.tsx";
+import { GuideAndViews } from "./overview-side-parts.tsx";
import { Block, BlockBody, ModelBlock, MoreToggle, Rebuilding } from "./briefing-parts.tsx";
import { useGroupModel, type GroupRead } from "./load.ts";
import { coverage, folderLines } from "./members.ts";
import { fieldLabel, type GroupModel } from "./model.ts";
import { useRememberedOpen } from "./remembered.ts";
-import { declaredRelations, type DeclaredRelation, type ScopeModel } from "./scope.ts";
+import { declaredRelations, type ScopeModel } from "./scope.ts";
import {
blockStatus,
useAggregatePart,
@@ -42,7 +42,11 @@ export function FolderBlock() {
return (
Untyped
- Share of folder
+ Share
Untyped notes link to
@@ -90,29 +94,20 @@ export function FolderBlock() {
- {/* A whole folder untyped is the common case: the share recedes,
- and only a partial share draws its bar. */}
- {percent >= 100 ? (
- 100%
- ) : (
+ {line.share < 1 ? (
- {percent}%
+ {percent}%
+ ) : (
+ —
)}
{line.linksTo.length ? (
-
- {line.linksTo.map((target, index) => (
-
- {index > 0 && ", "}
- {target.label} {fmt(target.count)}
-
- ))}
-
+
) : (
no typed notes
)}
@@ -227,52 +222,43 @@ export function DeclaredUnused({
const label = (id: string) => model?.nodeIndex.get(id)?.label ?? id;
- // Field display labels by target ("Work log, Materials → Materials"); a
- // field named for its only target reads as the target alone.
- const relationsText = (relations: readonly DeclaredRelation[]) =>
- [...new Set(relations.map((relation) => relation.target))]
- .map((id) => {
- const target = label(id);
-
- const fields = relations.flatMap((relation) =>
- relation.target === id ? [fieldLabel(relation.field)] : [],
- );
-
- return fields.length === 1 && fields[0] === target
- ? target
- : `${fields.join(", ")} → ${target}`;
- })
- .join(" · ");
-
- const byMember = new Map();
-
- for (const relation of unused)
- byMember.set(relation.member, [...(byMember.get(relation.member) ?? []), relation]);
-
return (
`${relation.member}.${relation.field} → ${relation.target}`).join("; ")}`}
>
{() =>
unused.length ? (
-
- {[...byMember].map(([member, relations]) => (
-
-
- {label(member)}
- {model?.nodeIndex.get(member)?.count === 0 && (
- (empty)
- )}
-
-
- {relationsText(relations)}
-
-
- ))}
-
+ <>
+
+ {model && model.nodes.some((node) => node.count === 0) && (
+
+ {model.nodes
+ .filter((node) => node.count === 0)
+ .map((node) => `${node.label}: no records`)
+ .join(" · ")}
+
+ )}
+
+
+ Owner type
+ Field
+ Target type
+
+
+
+ {unused.map((relation) => (
+
+ {label(relation.member)}
+ {fieldLabel(relation.field)}
+ {label(relation.target)}
+
+ ))}
+
+
+ >
) : (
Records use every relation declared between members.
)
@@ -292,14 +278,36 @@ const OUTSIDE_READ: GroupRead = {
neighborCap: 10,
};
-/** Outside notes the Overview lists before "Show N more", so Members stays above the fold. */
+/** Outside notes shown before expanding the preview. */
const OVERVIEW_OUTSIDE_NOTES = 3;
/** Only the guide note. */
const GUIDE_READ: GroupRead = { records: false };
function GroupOutside({ model }: { model: GroupModel }) {
- // Records past the read cap may link to notes not listed, so the list is partial.
+ const ref = useRef(null);
+ const [limit, setLimit] = useState(OVERVIEW_OUTSIDE_NOTES);
+ useEffect(() => {
+ const element = ref.current;
+ const main = element?.closest(".gv-ov")?.querySelector(".gv-ov-main");
+
+ if (!element || !main || typeof ResizeObserver === "undefined") return;
+
+ const measure = () => {
+ if (main.getBoundingClientRect().height === 0) return;
+ const available = main.getBoundingClientRect().bottom - element.getBoundingClientRect().top;
+ setLimit(Math.max(0, Math.min(3, Math.floor((available - 155) / 64))));
+ };
+
+ const observer = new ResizeObserver(measure);
+ observer.observe(main);
+
+ if (element.previousElementSibling) observer.observe(element.previousElementSibling);
+ measure();
+
+ return () => observer.disconnect();
+ }, []);
+
const outside = useMemo(() => {
const found = boundary(model);
@@ -307,27 +315,35 @@ function GroupOutside({ model }: { model: GroupModel }) {
}, [model]);
return (
-
+
+
+
+ );
+}
+
+export function GroupOutsideSummary() {
+ const state = useGroupModel({ views: false, read: OUTSIDE_READ });
+
+ return (
+
+ {(model) => }
+
);
}
/** "Outside the group" and "Guide and views", each from its own read. */
export function GroupRecordsBlocks() {
- const outside = useGroupModel({ views: false, read: OUTSIDE_READ });
const guide = useGroupModel({ read: GUIDE_READ });
return (
<>
-
- {(model) => }
-
{(model) => }
diff --git a/web/bundled-views/group/overview-style.css b/web/bundled-views/group/overview-style.css
new file mode 100644
index 000000000..86bcafbac
--- /dev/null
+++ b/web/bundled-views/group/overview-style.css
@@ -0,0 +1,372 @@
+.gv-page .gv-map-legend .gv-map-legend-row {
+ grid-template-columns: 104px minmax(0, 1fr);
+}
+.gv-page .gv-map-legend dd {
+ gap: 8px;
+ font-weight: 500;
+}
+.gv-map-legend dd > span {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ white-space: nowrap;
+}
+.gv-page .gv-map-legend dt {
+ font-weight: 500;
+}
+.gv-map-leader {
+ stroke: var(--text-muted);
+ stroke-width: 1;
+}
+.gv-page .gv-ov-table td.num,
+.gv-page .gv-ov-table td.num .gv-issues {
+ font-family: var(--font-sans);
+ font-size: 14px;
+ font-weight: 500;
+ font-variant-numeric: tabular-nums;
+}
+.gv-ov-ring {
+ width: 10px;
+ height: 10px;
+ border: 0;
+ position: relative;
+}
+.gv-ov-ring::after {
+ content: "";
+ position: absolute;
+ inset: 3px;
+ border-radius: 50%;
+ background: var(--surface);
+}
+.gv-unused-table {
+ font-size: 13px;
+}
+.gv-unused-table th {
+ font-weight: 500;
+}
+
+.gv-page .gv-map-legend-row dt {
+ min-width: 0;
+}
+.gv-page .gv-map-legend-row dd {
+ min-width: 0;
+}
+.gv-overview-outside .gv-change-age {
+ font-family: var(--font-sans);
+ font-variant-numeric: tabular-nums;
+}
+
+.gv-unused-table {
+ table-layout: fixed;
+}
+.gv-unused-table th:first-child {
+ width: 24%;
+}
+.gv-unused-table th:nth-child(2) {
+ width: 38%;
+}
+.gv-unused-table th:nth-child(3) {
+ width: 38%;
+}
+
+.gv-page .gv-ov-table td.num > * {
+ font-size: 14px;
+ font-weight: 500;
+}
+
+.gv-ov-side {
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+}
+.gv-ov-side .rz-section-head {
+ margin-bottom: var(--section-gap, 10px);
+}
+.gv-ov-side .list-more {
+ display: block;
+ margin-top: 8px;
+}
+.gv-unused-table th:first-child,
+.gv-unused-table td:first-child {
+ padding-left: 0;
+}
+.gv-unused-table caption {
+ caption-side: bottom;
+ text-align: left;
+ padding-top: 8px;
+}
+.gv-map-edge[data-kind="plain"] line:first-child {
+ stroke-dasharray: 8 5;
+ stroke-linecap: butt;
+}
+.gv-map-legend s[data-kind="plain"] {
+ border-top-style: dashed;
+}
+.gv-map-legend s[data-kind="outside"] {
+ border-top-style: dotted;
+}
+.gv-map-legend .gv-legend-family {
+ display: grid;
+ grid-template-columns: 64px minmax(0, 1fr);
+ gap: 8px;
+ width: 100%;
+}
+.gv-legend-family-name {
+ color: var(--text-muted);
+ font: 500 13px/1.35 var(--font-sans);
+}
+.gv-legend-family-types {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+.gv-legend-family-types > span {
+ display: inline-flex;
+ align-items: center;
+ white-space: nowrap;
+}
+.gv-legend-family:not(:has(.gv-legend-family-name)) {
+ grid-template-columns: minmax(0, 1fr);
+}
+.gv-ov-side > .rz-section {
+ margin-top: 0;
+}
+.gv-ov-members {
+ overflow-x: auto;
+}
+
+.gv-ov--group > .gv-ov-members,
+.gv-ov-below {
+ grid-column: 1 / -1;
+ border-top: 1px solid var(--border);
+}
+.gv-ov--group .gv-ov-table th,
+.gv-ov--group .gv-ov-table td {
+ white-space: nowrap;
+ padding-inline: 6px;
+}
+.gv-ov--group .gv-ov-table th:first-child {
+ padding-left: 20px;
+}
+.gv-ov--group .gv-ov-table td {
+ padding-block: 5px;
+}
+.gv-ov--group .gv-ov-table tbody tr {
+ height: 32px;
+}
+.gv-ov-below {
+ display: grid;
+ grid-template-columns: minmax(0, 1.45fr) minmax(300px, 1fr);
+ gap: 24px;
+ padding: 24px 20px 16px;
+}
+.gv-ov-below .rz-section {
+ margin-top: 0;
+ min-width: 0;
+}
+.gv-ov-below .rz-section-head {
+ margin-bottom: 10px;
+ font-size: 15px;
+ font-weight: 600;
+}
+.gv-ov-below .rz-more {
+ display: block;
+ margin-top: 8px;
+}
+.gv-ov-below .gv-overview-outside .gv-outsum,
+.gv-ov-below .gv-overview-outside .gv-quiet:has(button) {
+ display: none;
+}
+@media (max-width: 959px) {
+ .gv-ov-below {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+.gv-ov:not(.gv-ov--group) .gv-legend-family:not(:has(.gv-legend-family-name)) {
+ padding-left: 72px;
+ box-sizing: border-box;
+}
+
+/* Compact, wrapping group keys keep every type beside its group label. */
+.gv-page .gv-map-legend .gv-map-legend-row {
+ display: grid;
+ grid-template-columns: 76px minmax(0, 1fr);
+ column-gap: 8px;
+ line-height: 1.5;
+}
+.gv-page .gv-map-legend dt,
+.gv-page .gv-map-legend dd {
+ margin: 0;
+ font: 500 13px/1.8 var(--font-sans);
+}
+.gv-page .gv-map-legend dt {
+ color: var(--text-muted);
+}
+.gv-map-legend dd > span {
+ white-space: nowrap;
+}
+.gv-page .gv-ov-table {
+ table-layout: fixed;
+ width: 100%;
+}
+.gv-ov-table .gv-col-number {
+ width: 96px;
+}
+.gv-ov-table .gv-col-stages {
+ width: 420px;
+}
+.gv-ov-table .gv-col-linked {
+ width: 116px;
+}
+.gv-ov-table .gv-col-gaps {
+ width: 180px;
+}
+.gv-page .gv-ov-table th,
+.gv-page .gv-ov-table td {
+ padding: 5px 8px;
+ white-space: nowrap;
+}
+.gv-page .gv-ov-table th:first-child {
+ padding-left: 46px;
+}
+.gv-page .gv-ov-table .gv-ov-chev,
+.gv-page .gv-ov-table .gv-ov-chev-button {
+ width: 24px;
+ min-width: 24px;
+ margin: 0;
+ padding: 0;
+ justify-content: flex-start;
+}
+.gv-ov-no-disclosure {
+ padding-left: 24px;
+}
+.gv-page .gv-ov-table .gv-ov-dot {
+ box-sizing: border-box;
+}
+.gv-page .gv-ov-table tbody tr {
+ height: 32px;
+}
+.gv-page .gv-ov-table .gv-record,
+.gv-page .gv-ov-table .gv-member {
+ font-size: 14px;
+ font-weight: 500;
+}
+.gv-ov--group .gv-ov-table {
+ min-width: 1140px;
+}
+.gv-ov-stage {
+ max-width: 100%;
+}
+.gv-ov-below {
+ display: block;
+}
+.gv-overview-outside .rz-section {
+ margin-top: 0;
+}
+.gv-overview-outside .gv-change {
+ padding-block: 4px;
+}
+.gv-overview-outside .gv-change-title {
+ color: var(--text);
+}
+.gv-ov-side {
+ overflow: visible;
+}
+.gv-page .gv-map-legend {
+ gap: 0;
+}
+.gv-page .gv-map-legend .gv-map-legend-row,
+.gv-page .gv-map-legend dt,
+.gv-page .gv-map-legend dd {
+ line-height: 1.5;
+}
+.gv-ov-table .gv-col-stages {
+ width: 440px;
+}
+.gv-ov-table .gv-ov-bar {
+ width: 60px;
+}
+
+.gv-page .gv-map-legend dd {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0 12px;
+}
+.gv-page .gv-ov-below {
+ padding: 0 20px;
+}
+.gv-overview-guide {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px 16px;
+ min-height: 34px;
+}
+.gv-ov-below .gv-overview-guide .rz-section-head {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-muted);
+}
+.gv-overview-guide > .gv-sub {
+ margin-left: auto;
+}
+
+.gv-overview-guide > .gv-link {
+ text-decoration: none;
+}
+
+.gv-ov .gv-link,
+.gv-ov .gv-outside-actions .list-more {
+ color: var(--link);
+ font: 400 14px/1.4 var(--font-sans);
+ text-decoration: none;
+}
+.gv-ov .gv-link:hover,
+.gv-ov .gv-link:focus-visible,
+.gv-ov .gv-outside-actions .list-more:hover {
+ text-decoration: underline;
+ text-underline-offset: 3px;
+}
+.gv-outside-actions {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ margin-top: 8px;
+}
+.gv-ov .gv-outside-actions .list-more {
+ margin: 0;
+}
+.gv-page .gv-ov-folders {
+ table-layout: fixed;
+}
+.gv-page .gv-ov-folders th:first-child {
+ width: 60px;
+}
+.gv-page .gv-ov-folders th:nth-child(2) {
+ width: 58px;
+}
+.gv-page .gv-ov-folders th:nth-child(3) {
+ width: 78px;
+}
+.gv-page .gv-ov-folders td {
+ height: 32px;
+ box-sizing: border-box;
+ padding-block: 5px;
+}
+.gv-page .gv-ov-folders td.gv-ov-links {
+ white-space: normal;
+ overflow: visible;
+ text-overflow: clip;
+}
+.gv-ov-folders .gv-ov-links-text {
+ display: block;
+ white-space: normal;
+ overflow: visible;
+ overflow-wrap: anywhere;
+ font-size: 13px;
+}
+.gv-ov-folders .gv-ov-mini {
+ width: 24px;
+}
diff --git a/web/bundled-views/group/overview-tables.tsx b/web/bundled-views/group/overview-tables.tsx
index 660afcf5e..e112084ae 100644
--- a/web/bundled-views/group/overview-tables.tsx
+++ b/web/bundled-views/group/overview-tables.tsx
@@ -1,3 +1,4 @@
+import type { TypeSummary } from "./aggregate.ts";
// The Overview's tables (SPEC-0117 US1-US3): the Matrix, a complete text
// alternative to the map, and the member table comparing every member's size,
// progress, completeness, and connection.
@@ -13,7 +14,7 @@ import { plural } from "./briefing-parts.tsx";
import { Dash } from "./components.tsx";
import type { LifecycleSummary, MemberRow, NodeRow } from "./members.ts";
import { firstSentence } from "./model.ts";
-import { nodeHue, unusedPairs } from "./overview-map.tsx";
+import { nodeHue, compositionArcs, unusedPairs } from "./overview-map-parts.tsx";
import {
edgeKey,
type DeclaredRelation,
@@ -164,8 +165,27 @@ function ShareCell({ share }: { share: number | null }) {
);
}
-function Dot({ node }: { model: ScopeModel; node: ScopeNode }) {
- const hue = nodeHue(node, useTypeColors());
+function Dot({
+ summaries,
+ node,
+}: {
+ summaries: ReadonlyMap;
+ node: ScopeNode;
+}) {
+ const color = useTypeColors();
+ const hue = nodeHue(node, color);
+ const arcs = compositionArcs(node, summaries, color);
+
+ if (arcs.length)
+ return (
+ `${arc.color} ${arc.start * 100}% ${(arc.start + arc.share) * 100}%`).join(",")})`,
+ }}
+ />
+ );
return (
;
row: NodeRow;
onToggle: (group: string, open: boolean) => void;
}) {
@@ -200,7 +220,7 @@ function NameCell({
onClick={() => onToggle(node.name, !row.expanded)}
>
-
+
{node.label}{" "}
· {plural(node.members.length, "1 type", `${node.members.length} types`)}
@@ -210,13 +230,13 @@ function NameCell({
const name = (
<>
-
+
{node.label}
- {node.count === 0 && node.kind !== "untyped" && empty }
>
);
- if (node.kind === "untyped") return {name} ;
+ if (node.kind === "untyped")
+ return {name} ;
const open = (
openNode(node)}>
@@ -225,7 +245,8 @@ function NameCell({
);
// An interface folds its implementing types under a chevron of its own.
- if (row.toggle === undefined) return open;
+ if (row.toggle === undefined)
+ return {open} ;
const { toggle } = row;
return (
@@ -247,14 +268,14 @@ function NameCell({
function IssuesCell({ node }: { node: ScopeNode }) {
if (node.kind === "untyped") return ;
- if (node.issueCount === 0) return 0 ;
+ if (node.issueCount === 0) return 0 ;
- if (node.kind === "group") return {node.issueCount} ;
+ if (node.kind === "group") return {node.issueCount} ;
return (
openIssues({ kind: node.kind === "interface" ? "interface" : "type", key: node.name })
@@ -305,11 +326,13 @@ const hasGaps = (row: NodeRow) =>
function DataRow({
model,
+ summaries,
row,
shown,
onToggle,
}: {
model: ScopeModel;
+ summaries: ReadonlyMap;
row: NodeRow;
shown: Shown;
onToggle: (group: string, open: boolean) => void;
@@ -322,10 +345,10 @@ function DataRow({
return (
{/* A nested row starts 16px past its parent's name, not its dot. */}
-
-
+
+
- {fmt(node.count)}
+ {fmt(node.count)}
{node.kind === "untyped" ? (
// Untyped notes are not records: no lifecycle, gaps, or linked share.
<>
@@ -373,12 +396,12 @@ function DataRow({
>
)}
{/* A nested implementor's figures roll up into its interface: a dash, not a blank. */}
- {brief ? : fmt(row.links)}
+ {brief ? : fmt(row.links)}
{!workspace && (
- {brief ? : fmt(row.outside ?? 0)}
+ {brief ? : fmt(row.outside ?? 0)}
)}
- {brief ? : }
-
+ {brief ? : }
+
{node.lastChanged !== null && !brief ? : }
@@ -388,10 +411,12 @@ function DataRow({
/** One row per member, an interface's implementors nested under it, named groups expanding at All notes. */
export function MemberTable({
model,
+ summaries,
rows,
onToggle,
}: {
model: ScopeModel;
+ summaries: ReadonlyMap;
rows: readonly MemberRow[];
onToggle: (group: string, open: boolean) => void;
}) {
@@ -409,6 +434,17 @@ export function MemberTable({
return (
+
+
+
+ {shown.stages && }
+ {shown.gaps && }
+ {shown.linked && }
+
+ {!workspace && }
+
+
+
{workspace ? "Group · type" : "Type"}
@@ -417,9 +453,9 @@ export function MemberTable({
{shown.stages && Stages }
{shown.gaps && Gaps (empty / records) }
- {shown.linked && {workspace ? "Linked" : "Linked in group"} }
+ {shown.linked && Records linked }
- {workspace ? "Links" : "Links in group"}
+ Links
{!workspace && (
@@ -449,6 +485,7 @@ export function MemberTable({
{
await renderGroupView(loadOverview, { routes: scopeRoutes() });
- const unused = region("Declared, unused");
+ const unused = region("Declared relations with no links");
expect(within(unused).getByText("1")).toBeVisible();
// Fields read by their display labels, not schema names.
- expect(unused).toHaveTextContent("ReleasesArea → Areas");
- // A long list truncates beside the name; the full list is its title.
- expect(within(unused).getByTitle("Area → Areas")).toBeVisible();
+ expect(unused).toHaveTextContent("ReleasesAreaAreas");
+ expect(within(unused).getByRole("columnheader", { name: "Owner type" })).toBeVisible();
+ expect(within(unused).getByRole("columnheader", { name: "Field" })).toBeVisible();
});
it("lists the notes outside the group most connected first, then the guide and views", async () => {
@@ -183,7 +183,7 @@ it("lists the notes outside the group most connected first, then the guide and v
const outside = region("Outside the group");
expect(within(outside).getByText("4 notes")).toBeVisible();
- expect(outside.querySelector(".gv-outsum")).toHaveTextContent("1 person3 untyped notes");
+ expect(region("Outside the group")).toHaveTextContent("1 person3 untyped notes");
expect([...outside.querySelectorAll("li")].map((entry) => entry.textContent)).toEqual([
"Ada LovelacePerson · people/2 linked records",
"KickoffUntyped note · notes/2 linked records",
@@ -248,19 +248,17 @@ it("states All notes' facts and draws named groups collapsed beside ungrouped ty
expect(screen.getByRole("button", { name: "Validation: 5 issues" })).toBeVisible(),
);
expect(document.querySelector(".gv-facts-list")).toHaveTextContent(
- "49 notes59% typed10 note typesTyping: 3 ambiguous notesValidation: 5 issues",
+ "49 notes59% decided types10 note typesTyping: 3 ambiguous notesValidation: 5 issues",
);
expect(nodeNames()).toEqual([
- "Untyped notes, 20 notes, 11 links",
+ "Untyped + ambiguous, 20 notes, 11 links",
"Planning, 15 records, 5 links, collapsed group of 4 types",
"Library, 5 records, 2 links, collapsed group of 2 types",
"Meetings, 5 records, 10 links",
"People, 2 records, 6 links, collapsed group of 1 type",
]);
- // A member with no links is listed in the legend, not drawn.
- expect(
- within(region("Map")).getByRole("button", { name: "Notices, 0 records, 0 links" }),
- ).toBeVisible();
+ expect(within(region("Map")).queryByText("No member links:")).toBeNull();
+ expect(rowNamed(within(region("Members")).getByRole("table"), "Notices")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Typing: 3 ambiguous notes" }));
expect(opened(posted)).toEqual([{ type: OPEN_ISSUES_MESSAGE }]);
@@ -278,96 +276,11 @@ it("expands a group in place on the map and in the table, and collapses it from
expect(within(rowNamed(table, "Planning")).getByRole("button", { expanded: true })).toBeVisible();
expect(rowNamed(table, "Areas")).toBeVisible();
- fireEvent.click(within(region("Map")).getByRole("button", { name: "collapse" }));
+ fireEvent.click(within(region("Map")).getByRole("button", { name: "Collapse" }));
await waitFor(() => expect(map().querySelector("[data-node='group:Planning']")).not.toBeNull());
expect(within(table).queryByText("Areas")).toBeNull();
});
-it("lists untyped notes by folder and searches a folder, with the coverage line beneath", async () => {
- const { posted } = await renderGroupView(loadOverview, {
- context: WORKSPACE,
- routes: scopeRoutes(),
- embedded: true,
- });
-
- const folders = region("Untyped notes by folder");
- expect(within(folders).getByText("20 notes")).toBeVisible();
- const notes = rowNamed(within(folders).getByRole("table"), "Notes/");
- // One line per row: the folder size and full link list live in titles.
- expect(notes).toHaveTextContent("Notes/1240%Meetings 4, People 2");
- expect(notes.querySelector("[title='12 of 30 notes in Notes/']")).not.toBeNull();
- expect(notes.querySelector(".gv-ov-links")).toHaveAttribute("title", "Meetings 4, People 2");
- expect(within(folders).queryByText("Work/")).toBeNull();
-
- fireEvent.click(within(folders).getByRole("button", { name: "Inbox/" }));
- expect(posted.filter((message) => message.type === "rhizome:open-search")).toEqual([
- { type: "rhizome:open-search", folder: "Inbox" },
- ]);
-
- expect(region("Coverage")).toHaveTextContent(
- "No recordsNoticesNo linksLibrary glossaries 3EmbeddedTasks 7 · items inside notes, not drawn",
- );
- expect(screen.queryByRole("region", { name: "Declared, unused" })).toBeNull();
-});
-
-it("searches the vault root's own untyped notes as folder /", async () => {
- const { posted } = await renderGroupView(loadOverview, {
- context: WORKSPACE,
- embedded: true,
- routes: scopeRoutes({
- "GET /api/v1/ontology/shape": (request) =>
- request.query.get("parts") === "folders"
- ? jsonReply({
- ...AGGREGATE_PARTS.folders,
- folders: {
- rows: [{ folder: "", total: 3, untyped: 2, typed: {}, untypedLinksTo: {} }],
- },
- })
- : jsonReply(
- request.query.get("parts") === "members"
- ? AGGREGATE_PARTS.members
- : AGGREGATE_PARTS.links,
- ),
- }),
- });
-
- fireEvent.click(within(region("Untyped notes by folder")).getByRole("button", { name: "/" }));
-
- expect(posted.filter((message) => message.type === "rhizome:open-search")).toEqual([
- { type: "rhizome:open-search", folder: "/" },
- ]);
-});
-
-it("lists the eight largest folders before +N more", async () => {
- const rows = Array.from({ length: 11 }, (_, index) => ({
- folder: `F${index}`,
- total: 20,
- untyped: 20 - index,
- typed: {},
- untypedLinksTo: {},
- }));
-
- await renderGroupView(loadOverview, {
- context: WORKSPACE,
- embedded: true,
- routes: scopeRoutes({
- "GET /api/v1/ontology/shape": (request) =>
- request.query.get("parts") === "folders"
- ? jsonReply({ ...AGGREGATE_PARTS.folders, folders: { rows } })
- : jsonReply(
- request.query.get("parts") === "members"
- ? AGGREGATE_PARTS.members
- : AGGREGATE_PARTS.links,
- ),
- }),
- });
-
- const folders = within(region("Untyped notes by folder"));
- expect(folders.getAllByRole("row")).toHaveLength(1 + 8);
- fireEvent.click(folders.getByRole("button", { name: "Show 3 more" }));
- expect(folders.getAllByRole("row")).toHaveLength(1 + 11);
-});
-
it("paints every block's heading at once and fills each in as its part arrives", async () => {
let release = () => {};
diff --git a/web/bundled-views/group/overview.tsx b/web/bundled-views/group/overview.tsx
index 3ebcb854d..d96a0ba96 100644
--- a/web/bundled-views/group/overview.tsx
+++ b/web/bundled-views/group/overview.tsx
@@ -23,7 +23,13 @@ import { Block, BlockBody, Rebuilding, plural } from "./briefing-parts.tsx";
import "./components.tsx";
import { memberRows } from "./members.ts";
import { ScopeMap } from "./overview-map.tsx";
-import { CoverageLine, DeclaredUnused, FolderBlock, GroupRecordsBlocks } from "./overview-side.tsx";
+import {
+ CoverageLine,
+ DeclaredUnused,
+ FolderBlock,
+ GroupOutsideSummary,
+ GroupRecordsBlocks,
+} from "./overview-side.tsx";
import { MemberTable, ScopeMatrix } from "./overview-tables.tsx";
import { useRememberedOpen } from "./remembered.ts";
import { declaredRelations, linkModel, scopeOf, type Scope } from "./scope.ts";
@@ -36,6 +42,8 @@ import {
type BlockStatus,
} from "./scope-load.ts";
+import "./overview-style.css";
+
type Mode = "map" | "matrix";
const MAP: Mode = "map";
@@ -70,7 +78,7 @@ function WorkspaceFacts({ data }: { data: ScopeData }) {
{fmt(facts.totalNotes)} notes
- {typed}% typed
+ {typed}% decided types
{data.model.types.size} note {plural(data.model.types.size, "type", "types")}
@@ -79,7 +87,7 @@ function WorkspaceFacts({ data }: { data: ScopeData }) {
openIssues()}
>
Typing: {" "}
@@ -282,13 +290,26 @@ function MembersBlock({ data, expanded, onToggle }: { data: ScopeData } & Expans
);
return (
-
+
{() =>
data.facts?.rebuilding ? (
) : data.model ? (
-
+
) : null
}
@@ -305,7 +326,23 @@ function OverviewPage({ scope }: { scope: Scope }) {
[remembered.choices],
);
- const data = useScopeModel(scope, expanded);
+ const source = useScopeModel(scope, expanded);
+
+ const model = useMemo(() => {
+ const original = source.model;
+
+ if (!original?.untyped || !source.facts?.ambiguousNotes) return original;
+ const untyped = { ...original.untyped, label: "Untyped + ambiguous" };
+
+ return {
+ ...original,
+ untyped,
+ nodes: original.nodes.map((node) => (node.id === untyped.id ? untyped : node)),
+ nodeIndex: new Map(original.nodeIndex).set(untyped.id, untyped),
+ };
+ }, [source.model, source.facts]);
+
+ const data = { ...source, model };
const status = blockStatus(data.reads);
const expansion: Expansion = { expanded, onToggle: remembered.setOpen };
@@ -314,9 +351,8 @@ function OverviewPage({ scope }: { scope: Scope }) {
{!data.missing && (
<>
- {/* All notes keeps Members under the map and the folder table beside them,
- so the side column's height never pushes Members below the fold. */}
-
+ {/* Group Members span both columns; All notes keeps its compact main column. */}
+
{scope.kind === "workspace" && (
@@ -334,16 +370,21 @@ function OverviewPage({ scope }: { scope: Scope }) {
) : (
<>
-
+
>
)}
+ {scope.kind === "group" && (
+ <>
+
+
+
+
+
+
+ >
+ )}
- {scope.kind !== "workspace" && (
-
-
-
- )}
>
)}
diff --git a/web/bundled-views/group/preferences.test.tsx b/web/bundled-views/group/preferences.test.tsx
index fa6007f9c..25a9780b1 100644
--- a/web/bundled-views/group/preferences.test.tsx
+++ b/web/bundled-views/group/preferences.test.tsx
@@ -5,7 +5,7 @@ import { FakeFetch, jsonReply } from "../../src/test/fakeFetch";
import { preferenceServer } from "../../src/viewPreferences/testServer";
import { DISPLAY_GROUPS, NOW, PATHS, RECORDS_DATA } from "./__fixtures__/groups.ts";
import { groupRoutes, renderGroupView } from "./__fixtures__/harness.tsx";
-import { isJsonObject } from "./api.ts";
+import { isJsonObject, type JsonValue } from "./api.ts";
import { withChoice } from "./remembered.ts";
const loadTrace = () => import("./trace.tsx");
@@ -112,10 +112,18 @@ it("ignores a remembered row type the group no longer has", async () => {
it("keeps a Briefing signal's records revealed after a reload", async () => {
// Areas without parents link with nothing else, so Not linked has more than it names.
- const areas = (Array.isArray(RECORDS_DATA.Area) ? RECORDS_DATA.Area : []).map((area) =>
- isJsonObject(area) ? { ...area, parent: null } : area,
+ const areas: JsonValue[] = (Array.isArray(RECORDS_DATA.Area) ? RECORDS_DATA.Area : []).map(
+ (area) => (isJsonObject(area) ? { ...area, parent: null } : area),
);
+ areas.push({
+ path: "areas/extra.md",
+ title: "Extra area",
+ parent: null,
+ updatedAt: NOW / 1000,
+ issueCount: 0,
+ });
+
const routes = groupRoutes({
"POST /api/v1/graphql": () => jsonReply({ data: { ...RECORDS_DATA, Area: areas } }),
});
@@ -133,7 +141,7 @@ it("keeps a Briefing signal's records revealed after a reload", async () => {
};
const first = await renderGroupView(loadBriefing, { routes, http });
- fireEvent.click((await unlinked()).getByRole("button", { name: "Show 2 more unlinked notes" }));
+ fireEvent.click((await unlinked()).getByRole("button", { name: "Show 1 more" }));
await waitFor(() => expect(server.read(SCOPE).values).toHaveProperty("briefing.expanded"));
first.unmount();
diff --git a/web/bundled-views/group/sections.test.tsx b/web/bundled-views/group/sections.test.tsx
index 5de247bcd..814bb4cdf 100644
--- a/web/bundled-views/group/sections.test.tsx
+++ b/web/bundled-views/group/sections.test.tsx
@@ -41,6 +41,20 @@ it("renders each member as a table in Trace column order, most advanced first",
]);
expect(screen.getByRole("navigation", { name: "Jump to section" })).toBeVisible();
+ const jump = screen.getByRole("navigation", { name: "Jump to section" });
+ const workLink = within(jump).getByRole("button", { name: "Work items 6" });
+ expect(workLink).toHaveTextContent(/^Work items 6$/);
+ expect(jump.closest(".gv-facts")).toBeNull();
+ expect(jump.previousElementSibling).toHaveClass("gv-facts");
+ expect(within(jump).getByText("Jump to")).toBeVisible();
+ expect(workLink).toHaveAttribute("title", "Work items 6");
+ const heading = section("Areas").querySelector(".gv-section-head");
+ expect(
+ Array.from(heading?.children ?? [])
+ .slice(0, 4)
+ .map((child) => child.textContent),
+ ).toEqual(["Areas", "6", "A product or platform area.", ""]);
+
const work = section("Work items");
expect(headers(work)).toEqual([
"Title",
@@ -123,6 +137,15 @@ it("keeps the lifecycle column and drops other columns empty on every shown row"
it("orders an unlinked group by size, drops the shared label prefix, and says when a member is empty", async () => {
const routes = groupRoutes({
"POST /api/v1/graphql": () => jsonReply({ data: { ...RECORDS_DATA, Memo: [] } }),
+ "GET /api/v1/display-groups": () =>
+ jsonReply({
+ groups: DISPLAY_GROUPS.groups.map((group) => ({
+ ...group,
+ members: group.members.map((member) =>
+ member.name === "Memo" ? { ...member, count: 0 } : member,
+ ),
+ })),
+ }),
});
await renderGroupView(loadSections, { group: "Library", routes });
@@ -133,6 +156,15 @@ it("orders an unlinked group by size, drops the shared label prefix, and says wh
"Memos",
]);
expect(screen.getByRole("navigation", { name: "Jump to section" })).toBeVisible();
+
+ const emptyLink = within(screen.getByRole("navigation", { name: "Jump to section" })).getByRole(
+ "button",
+ { name: "Memos 0" },
+ );
+
+ expect(emptyLink).toHaveTextContent("Memos 0");
+ expect(emptyLink).toHaveAttribute("data-empty");
+ expect(emptyLink).toBeDisabled();
expect(within(section("Memos")).getByText("None recorded yet.")).toBeVisible();
});
@@ -348,3 +380,22 @@ it("keeps showing the group while a type that joined it loads its documentation"
doc.resolve({ type: TYPE_DOCS.Glossary, count: 3 });
expect(await screen.findByRole("region", { name: "Library glossaries" })).toBeVisible();
});
+
+it("keeps Status when only the hidden records have another status", async () => {
+ const releases = Array.from({ length: SECTION_ROWS + 1 }, (_, index) => ({
+ path: `releases/${index}.md`,
+ title: `Release ${index}`,
+ releaseStatus: index < SECTION_ROWS ? "at_risk" : "planned",
+ }));
+
+ await renderGroupView(loadSections, {
+ routes: groupRoutes({
+ "POST /api/v1/graphql": () => jsonReply({ data: { ...RECORDS_DATA, Release: releases } }),
+ }),
+ });
+ const region = await screen.findByRole("region", { name: "Releases" });
+ expect(rowTitles(region)).toHaveLength(SECTION_ROWS);
+ expect(headers(region)).toContain("Status");
+ fireEvent.click(within(region).getByRole("button", { name: /Show .*more/ }));
+ expect(headers(region)).toContain("Status");
+});
diff --git a/web/bundled-views/group/sections.tsx b/web/bundled-views/group/sections.tsx
index 31012adfb..1e2a4260e 100644
--- a/web/bundled-views/group/sections.tsx
+++ b/web/bundled-views/group/sections.tsx
@@ -43,6 +43,8 @@ import {
type MemberField,
} from "./model.ts";
+import "./trace-sections.css";
+
/** True when one concrete type holds more than 90% of the member's records. */
function oneTypeDominates(member: Member) {
const counts = new Map
();
@@ -142,7 +144,13 @@ function Row({
{columns.map((column) => (
|
@@ -161,8 +169,7 @@ function Section({ model, member }: { model: GroupModel; member: Member }) {
const shown = open ? rows : rows.slice(0, SECTION_ROWS);
// A section whose records all share one status omits it: the heading's
- // counts already say it. Judged over every row, not just the shown ones, so
- // a section mixing Active and Complete always says which row is which.
+ // counts already say it, including records behind Show more.
const oneStatus =
Boolean(member.lifecycle) &&
new Set(rows.map((node) => lifecycleValue(member, node.record))).size <= 1;
@@ -185,22 +192,22 @@ function Section({ model, member }: { model: GroupModel; member: Member }) {
-
-
-
{member.count}
+ {member.description && {firstSentence(member.description)} }
+
+
+
{member.issueCount > 0 && (
openMemberIssues(member)}>
{member.issueCount} {member.issueCount === 1 ? "issue" : "issues"}
)}
- {member.description && {firstSentence(member.description)} }
{rows.length === 0 ? (
@@ -214,7 +221,13 @@ function Section({ model, member }: { model: GroupModel; member: Member }) {
{columnLabel(member, column)}
@@ -268,27 +281,31 @@ function SectionsBody({ model }: { model: GroupModel }) {
return (
<>
-
- {members.length > 1 && (
-
- {members.map((member) => (
-
- document
- .getElementById(sectionId(member))
- ?.scrollIntoView({ behavior: "smooth", block: "start" })
- }
- >
- {memberLabel(model, member, { plural: true })}{" "}
- {member.count}
-
- ))}
-
- )}
-
+
+ {members.length > 1 && (
+
+ Jump to
+ {members.map((member) => (
+
+ document
+ .getElementById(sectionId(member))
+ ?.scrollIntoView({ behavior: "smooth", block: "start" })
+ }
+ >
+ {memberLabel(model, member, { plural: true })}{" "}
+ {member.count}
+
+ ))}
+
+ )}
{members.map((member) => (
))}
diff --git a/web/bundled-views/group/trace-sections.css b/web/bundled-views/group/trace-sections.css
new file mode 100644
index 000000000..4b758bd50
--- /dev/null
+++ b/web/bundled-views/group/trace-sections.css
@@ -0,0 +1,105 @@
+/* Keep the spine wide enough for summaries beside linked columns. */
+.gv-trace .gv-col-spine,
+.gv-trace thead th.gv-trace-spine {
+ width: calc(34% + 80px);
+}
+
+/* Related titles and coverage need enough room to stay readable. */
+.gv-trace .gv-trace-related {
+ width: 280px;
+ min-width: 280px;
+}
+.gv-trace .gv-trace-related .gv-head > .gv-member {
+ flex: none;
+}
+
+.gv-jump {
+ display: flex;
+ align-items: center;
+ min-height: 32px;
+ padding: 0 20px;
+ gap: 0 8px;
+ font-size: 14px;
+}
+
+.gv-jump-label {
+ margin-right: 4px;
+ color: var(--text-muted);
+ font: 500 13px / 1.4 var(--font-sans);
+}
+
+.gv-jump > button + button::before {
+ content: "·";
+ margin-right: 8px;
+ color: var(--text-faint);
+}
+
+.gv-jump .num {
+ color: var(--text-muted);
+}
+
+.gv-trace-rows {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.gv-trace-rows-label {
+ color: var(--text-muted);
+ font: 500 13px / 1.4 var(--font-sans);
+}
+
+.gv-page .gv-trace thead th .gv-cov {
+ display: block;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+/* Materials carry no lifecycle: no placeholder mark, so their titles start
+ on the cell's inset like the empty-cell dash. */
+.gv-trace td .gv-square {
+ display: none;
+}
+
+.gv-jump > button:disabled,
+.gv-jump > button:disabled .num {
+ color: var(--text-faint);
+}
+
+.gv-section .gv-table td.gv-col-type,
+.gv-section .gv-table td.gv-col-type > span {
+ color: var(--text-muted);
+ font-size: 14px;
+ font-weight: 400;
+}
+
+.gv-trace-rows {
+ flex-wrap: wrap;
+}
+.gv-trace-rows-label {
+ flex: none;
+}
+.gv-page .gv-trace thead th .gv-col-legend {
+ display: flex;
+ gap: 12px;
+ margin-top: 4px;
+}
+.gv-trace thead th.gv-trace-related {
+ width: 280px;
+}
+
+.gv-trace .rz-dash {
+ color: var(--text-muted);
+ opacity: 1;
+}
+.gv-section .gv-summary {
+ max-width: 720px;
+}
+.gv-trace .gv-head {
+ flex-wrap: wrap;
+}
+.gv-trace .gv-cov-count {
+ white-space: normal;
+ flex: 0 1 auto;
+ max-width: 100%;
+}
diff --git a/web/bundled-views/group/trace.test.tsx b/web/bundled-views/group/trace.test.tsx
index 444c4988d..f81be75f5 100644
--- a/web/bundled-views/group/trace.test.tsx
+++ b/web/bundled-views/group/trace.test.tsx
@@ -40,11 +40,8 @@ async function chooseRows(label: string) {
fireEvent.click(await screen.findByRole("radio", { name: new RegExp(`^${label}`) }));
}
-/** A column's label: its first button's text without the record count. */
-const columnName = (header: HTMLElement) =>
- within(header)
- .getAllByRole("button")[0]
- .textContent?.replace(/\u00a0\d+$/, "");
+/** The visible column label, independent of toolbar controls. */
+const columnName = (header: HTMLElement) => header.querySelector(".gv-member")?.textContent;
const columnNames = () => screen.getAllByRole("columnheader").map(columnName);
@@ -115,7 +112,15 @@ it("defaults to the hierarchical member, nests its rows, and rolls subtrees up",
"Checklists 1",
]);
expect(screen.getByRole("radio", { name: /^Areas/ })).toBeChecked();
- // The toolbar holds only the row choice; why the default is the default sits in the footer.
+ expect(
+ screen.getByRole("radiogroup", { name: "Rows" }).querySelector(".gv-default-dot"),
+ ).toBeNull();
+ expect(columnHeader("Areas")).toHaveTextContent("— No link");
+ expect(screen.getByRole("radiogroup", { name: "Rows" }).closest("th")).toBeNull();
+ expect(document.querySelector(".gv-toolbar")).toContainElement(
+ screen.getByRole("radiogroup", { name: "Rows" }),
+ );
+ // Why the default is the default sits in the footer.
expect(
screen.getByText(/Areas are the default rows: the tree other types link to/),
).toBeVisible();
@@ -165,12 +170,15 @@ it("fills cells with records linked to anything in the row, marking indirect one
expect(within(row("Payments")).getAllByText("(indirect)")).toHaveLength(2);
// Coverage beside the name; under it, the field that joins the column to the rows.
- expect(columnHeader("Work items")).toHaveTextContent("3 of 6 areas linked");
- // Under that, the column's own status key, naming only the statuses it holds.
- expect(columnHeader("Work items")).toHaveTextContent(/linkedArea.*Doing.*Done/);
+ expect(columnHeader("Work items")).toHaveTextContent("3 of 6 areas have work items");
+ // The second line names only the mixed statuses the column holds.
+ expect(columnHeader("Work items")).toHaveTextContent(/itemsDoing.*Done/);
expect(columnHeader("Work items")).not.toHaveTextContent(/Backlog/);
- expect(columnHeader("Releases")).toHaveTextContent("1 of 6 areas linked");
- expect(columnHeader("Checklists")).toHaveTextContent("1 of 6 areas linkedthrough other columns");
+ expect(
+ within(columnHeader("Work items")).getByLabelText("Work items status marks"),
+ ).toBeVisible();
+ expect(columnHeader("Releases")).toHaveTextContent("1 of 6 areas have releases");
+ expect(columnHeader("Checklists")).toHaveTextContent("1 of 6 areas have checklists");
expect(screen.getByText("2 records appear in no row: 1 work item and 1 release.")).toBeVisible();
});
@@ -180,8 +188,8 @@ it("switches rows and orders columns by contract with outside links last", async
await chooseRows("Work items");
expect(screen.getByRole("radio", { name: /^Work items/ })).toBeChecked();
expect(columnNames()).toEqual(["Work items", "Areas", "Releases", "Checklists", "Owner"]);
- expect(columnHeader("Areas")).toHaveTextContent("5 of 6 work items linked");
- expect(columnHeader("Owner")).toHaveTextContent("1 of 6 work items linkedin People");
+ expect(columnHeader("Areas")).toHaveTextContent("5 of 6 work items have areas");
+ expect(columnHeader("Owner")).toHaveTextContent("1 of 6 work items have owner");
expect(cellTitles("Checkout redesign")).toEqual([
["Payments"],
["Fall release"],
@@ -190,7 +198,7 @@ it("switches rows and orders columns by contract with outside links last", async
]);
});
-it("bands rows by lifecycle, most advanced first and closed values last, naming empty values", async () => {
+it("bands rows by lifecycle, most advanced first and closed values last, summarizing held values", async () => {
const data = {
...RECORDS_DATA,
Story: changed("Story", (story) =>
@@ -202,8 +210,8 @@ it("bands rows by lifecycle, most advanced first and closed values last, naming
await chooseRows("Work items");
expect(bands()).toEqual(["Blocked1", "Doing2", "Done2", "No stage1"]);
- expect(columnHeader("Work items")).toHaveTextContent("by stage, most advanced first");
- expect(columnHeader("Work items")).toHaveTextContent("none Backlog, Dropped");
+ expect(columnHeader("Work items")).not.toHaveTextContent("most advanced first");
+ expect(columnHeader("Work items").querySelector(".gv-counts")).toBeNull();
expect(rowTitles().map(([title]) => title)).toEqual([
"Tax rounding",
"Checkout redesign",
@@ -350,9 +358,10 @@ it("opens records, outside notes, and collections through the workspace", async
fireEvent.click(screen.getByRole("button", { name: "Checkout redesign" }));
fireEvent.click(within(row("Checkout redesign")).getByRole("button", { name: "Payments" }));
fireEvent.click(within(row("Checkout redesign")).getByRole("button", { name: "Ada Lovelace" }));
- fireEvent.click(within(columnHeader("Work items")).getByRole("button", { name: "Work items" }));
fireEvent.click(within(columnHeader("Areas")).getByRole("button", { name: /^Areas/ }));
fireEvent.click(within(columnHeader("Owner")).getByRole("button", { name: "Owner" }));
+ await chooseRows("Areas");
+ fireEvent.click(within(columnHeader("Work items")).getByRole("button", { name: "Work items" }));
expect(posted.filter((message) => message.type.startsWith("rhizome:open-"))).toEqual([
{
@@ -361,8 +370,32 @@ it("opens records, outside notes, and collections through the workspace", async
},
{ type: OPEN_NODE_MESSAGE, ref: { notePath: PATHS.payments, kind: "NOTE", typeName: "Area" } },
{ type: OPEN_NOTE_MESSAGE, path: PATHS.ada, beside: false },
- { type: OPEN_COLLECTION_MESSAGE, name: "Work" },
{ type: OPEN_COLLECTION_MESSAGE, name: "Area" },
{ type: OPEN_COLLECTION_MESSAGE, name: "Person" },
+ { type: OPEN_COLLECTION_MESSAGE, name: "Work" },
]);
});
+
+it("gives a column joined by multiple fields room for its full relation caption", async () => {
+ const release = {
+ ...TYPE_DOCS.Release,
+ fields: TYPE_DOCS.Release.fields.flatMap((field) =>
+ field.name === "area"
+ ? [field, { ...field, name: "otherArea", label: "Other area" }]
+ : [field],
+ ),
+ };
+
+ const routes = groupRoutes({
+ "GET /api/v1/ontology/types/Release": () => jsonReply({ type: release, count: 2 }),
+ });
+
+ await renderGroupView(loadTrace, { routes });
+ await screen.findByRole("table");
+ const related = columnHeader("Related releases");
+ expect(related).toHaveClass("gv-trace-related");
+ expect(related).not.toHaveClass("gv-col-sparse");
+ expect(related.querySelector(".gv-cov")).toBeNull();
+ expect(related).toHaveTextContent(/have related releases$/);
+ expect(screen.getByRole("table").querySelector("col.gv-trace-related")).toBeInTheDocument();
+});
diff --git a/web/bundled-views/group/trace.tsx b/web/bundled-views/group/trace.tsx
index 6edc2b0d0..191d38235 100644
--- a/web/bundled-views/group/trace.tsx
+++ b/web/bundled-views/group/trace.tsx
@@ -13,12 +13,13 @@ import {
import { useMemo } from "react";
import { isString } from "./api.ts";
-import { GroupFacts, GroupPage, MemberHeading } from "./components.tsx";
+import { GroupFacts, GroupPage } from "./components.tsx";
import { linkGraph, spineChoices, type LinkGraph } from "./graph.ts";
import { useGroupModel } from "./load.ts";
import { traceMatrix, type MatrixColumn, type TraceMatrix } from "./matrix.ts";
import { fieldLabel, lifecycleValue, memberLabel, type GroupModel, type Member } from "./model.ts";
import { Band, inSentence } from "./traceRows.tsx";
+import "./trace-sections.css";
/** A closed band with more rows than this starts folded while other bands are open. */
const FOLD_CLOSED = 3;
@@ -32,12 +33,6 @@ const SPINE = {
validate: isSpine,
};
-const RELATION: Record["relation"], string> = {
- "linked-from-rows": "linked from rows",
- "links-to-rows": "link to rows",
- through: "through other columns",
-};
-
const list = new Intl.ListFormat("en", { type: "conjunction" });
function columnLabel(model: GroupModel, column: MatrixColumn, joining = 1) {
@@ -90,27 +85,6 @@ function heldValues(matrix: TraceMatrix, column: MatrixColumn & { kind: "member"
return held;
}
-/**
- * What the marks in a linked column mean, always on screen under its heading:
- * each status its records hold, mark and word ("● Active · ○ Proposed").
- */
-function ColumnLegend({ matrix, column }: { matrix: TraceMatrix; column: MatrixColumn }) {
- if (column.kind !== "member" || !column.member.lifecycle) return null;
- const values = column.member.lifecycle.values;
- const held = heldValues(matrix, column);
- const shown = orderedEnumValues(values).filter((value) => held.has(value.name));
-
- if (shown.length === 0) return null;
-
- return (
-
- {shown.map((value) => (
-
- ))}
-
- );
-}
-
function ColumnHead({
model,
matrix,
@@ -123,75 +97,60 @@ function ColumnHead({
const fields = relationFields(matrix, column);
const label = columnLabel(model, column, fields.length);
- const where =
- column.kind === "member"
- ? fields.length
- ? fields.join(" · ")
- : RELATION[column.relation]
- : column.link.targetGroup
- ? `in ${column.link.targetGroup}`
- : "outside the group";
-
- const thin = column.covered < matrix.rowCount / 3;
+ const values = column.kind === "member" ? (column.member.lifecycle?.values ?? []) : [];
+ const held = column.kind === "member" ? heldValues(matrix, column) : new Set();
+ const shown = orderedEnumValues(values).filter((value) => held.has(value.name));
return (
1 && "gv-trace-related",
+ ]
.filter(Boolean)
.join(" ") || undefined
}
>
- openColumn(column)}>
+ openColumn(column)}
+ >
{label}
- {column.kind === "member" && {column.member.count} }
+ {column.kind === "member" && {column.member.count} }
- {column.covered} of {matrix.rowCount}{" "}
- {inSentence(memberLabel(model, matrix.spine, { plural: true }))} linked
+ {column.covered} of {matrix.rowCount}{" "}
+ {inSentence(memberLabel(model, matrix.spine, { plural: true }))} have {inSentence(label)}
- {/* The name and coverage, the relation, then a persistent status key in
- words, so filled and hollow marks never need a lookup. */}
-
-
- {where}
+ {shown.length > 1 && (
+
+ {shown.map((value) => (
+
+ ))}
-
-
+ )}
);
}
function SpineHead({ model, matrix }: { model: GroupModel; matrix: TraceMatrix }) {
- const { spine } = matrix;
- const lifecycle = spine.lifecycle;
-
- const order = lifecycle
- ? `by ${fieldLabel(lifecycle.field).toLowerCase()}, most advanced first`
- : "most connected first";
-
- const empty = matrix.emptyValues.map((value) => value.label ?? value.name).join(", ");
-
return (
-
- {spine.count}
-
-
- {order}
- {matrix.hierarchical && ", nested under parents"}
- {empty && ` · none ${empty}`}
+ {memberLabel(model, matrix.spine, { plural: true })}
+ {matrix.spine.count}
+ — No link
);
}
@@ -229,7 +188,7 @@ function Footer({
}: {
model: GroupModel;
matrix: TraceMatrix;
- /** Why the dotted row choice is the default. */
+ /** Why the row choice is the default. */
defaultNote?: string;
}) {
const label = (member: Member, count?: number) =>
@@ -273,9 +232,9 @@ function Footer({
/** Columns that show; an empty column is named in the toolbar instead. */
const shownColumns = (matrix: TraceMatrix) => matrix.columns.filter((column) => !column.collapsed);
-/** The matrix's narrowest readable width, in pixels: a 340px spine and 220px columns. */
+/** Keep related materials readable alongside the spine and other linked columns. */
function matrixWidth(matrix: TraceMatrix) {
- return 340 + shownColumns(matrix).length * 220;
+ return 420 + shownColumns(matrix).length * 220;
}
/** A column few rows fill is held to a fifth of the width, so dense columns get the room. */
@@ -301,7 +260,13 @@ function Matrix({
{shownColumns(matrix).map((column) => (
1
+ ? "gv-trace-related"
+ : sparse(matrix, column)
+ ? "gv-col-sparse"
+ : undefined
+ }
/>
))}
@@ -356,10 +321,10 @@ function SpineSwitcher({
const fallback = choices[0];
return (
-
+
+
Rows
{
@@ -370,12 +335,7 @@ function SpineSwitcher({
return [
{
value: name,
- label: (
- <>
- {name === fallback && }
- {memberLabel(model, choice, { plural: true })}
- >
- ),
+ label: memberLabel(model, choice, { plural: true }),
count: choice.records.length,
description: name === fallback ? "(default)" : undefined,
},
@@ -419,7 +379,9 @@ function TraceBody({ model }: { model: GroupModel }) {
return (
-
+
+
+
span > span")].map(
+ (label) => label.textContent,
+ ),
+ ).toEqual(["Person", "Area", "Untyped note"]);
+
expect(itemTexts(linked)).toEqual([
expect.stringMatching(/^Kickoff/),
expect.stringMatching(/^Ada Lovelace/),
@@ -100,7 +117,7 @@ it("briefs an interface across its implementors and flags reverse links most rec
"No meetings link to 2 of 6 work items",
);
- const spread = await region("Shape");
+ const spread = await region("Composition");
expect(within(spread).getByRole("heading", { name: "Work item types" })).toBeVisible();
expect(within(spread).getByText("Story")).toBeVisible();
@@ -118,7 +135,7 @@ it("leaves out In motion for a lifecycle without an active stage", async () => {
// A contract-shaped type has nothing in motion by design; no hint to change the schema.
expect(
- within(await region("Shape")).getByRole("heading", { name: "Memo status lifecycle" }),
+ within(await region("Composition")).getByRole("heading", { name: "Memo status" }),
).toBeVisible();
expect(screen.queryByRole("region", { name: "In motion" })).toBeNull();
expect(screen.queryByText(/has no active stage/)).toBeNull();
@@ -127,17 +144,17 @@ it("leaves out In motion for a lifecycle without an active stage", async () => {
it("leaves out In motion for a type without a lifecycle", async () => {
await openType("Area");
- await region("Shape");
+ await region("Composition");
expect(screen.queryByRole("region", { name: "In motion" })).toBeNull();
expect(
- within(await region("Shape")).getByRole("heading", { name: "Category category" }),
+ within(await region("Composition")).getByRole("heading", { name: "Category category" }),
).toBeVisible();
});
it("charts a dated type's primary date by month and collapses a burst of changes", async () => {
await openType("Meeting");
- const spread = await region("Shape");
+ const spread = await region("Composition");
expect(
within(spread).getByRole("img", {
@@ -156,7 +173,7 @@ it("charts a dated type's primary date by month and collapses a burst of changes
const connections = await region("Connections");
expect(itemTexts(connections)[0]).toBe(
- "Attendees→ People4 of 5 meetings linkedAda Lovelace3Grace Hopper2",
+ "Attendees→ People4 of 5 meetings linkedLinked meetingsAda Lovelace3Grace Hopper2",
);
});
@@ -188,3 +205,40 @@ it("says which type it could not find", async () => {
expect(await screen.findByText("No type or interface named Gone in navigation.")).toBeVisible();
});
+
+it("opens the embedded identity from an unchanged record link", async () => {
+ const ref = {
+ kind: "EMBEDDED",
+ notePath: "work/items.md",
+ nodeId: "saved-carts",
+ fragment: "^saved-carts",
+ typeName: "Story",
+ };
+
+ const stories = COLLECTION_DATA.Story;
+
+ const data = {
+ ...COLLECTION_DATA,
+ Story: Array.isArray(stories)
+ ? stories.map((row) =>
+ isJsonObject(row) && row.title === "Saved carts"
+ ? { ...row, ref, path: ref.notePath }
+ : row,
+ )
+ : [],
+ };
+
+ const { posted } = await renderGroupView(loadBriefing, {
+ context: { kind: "type", type: "Story" },
+ routes: collectionRoutes({ "POST /api/v1/graphql": () => jsonReply({ data }) }),
+ embedded: true,
+ });
+
+ const motion = await region("In motion");
+ const details = motion.querySelector("details");
+
+ if (!details) throw new Error("No unchanged records");
+ details.open = true;
+ fireEvent.click(within(details).getByRole("button", { name: "Saved carts" }));
+ expect(posted.at(-1)).toMatchObject({ type: OPEN_NODE_MESSAGE, ref });
+});
diff --git a/web/bundled-views/group/type-briefing.tsx b/web/bundled-views/group/type-briefing.tsx
index 004b2eecf..f24afa0f4 100644
--- a/web/bundled-views/group/type-briefing.tsx
+++ b/web/bundled-views/group/type-briefing.tsx
@@ -5,11 +5,13 @@
// Briefing's loader and blocks over a one-member model, in the same three
// columns.
import {
+ DisclosureIcon,
HighlightProvider,
StatusMark,
openNote,
openView,
useViewContext,
+ useTypeColors,
type ViewContext,
type ViewModuleProps,
} from "@rhizome/kit";
@@ -17,9 +19,15 @@ import { useMemo } from "react";
import { boundary, inMotion, needsAttention, reverseGaps } from "./activity.ts";
import { REVERSE_SAMPLE } from "./api.ts";
-import { MotionList, OutsideNotes, RecentChanges } from "./briefing-activity.tsx";
+import {
+ useMotionMetadata,
+ MotionList,
+ OutsideNotes,
+ RecentChanges,
+} from "./briefing-activity.tsx";
import { NeedsAttention, type MemberAction } from "./briefing-attention.tsx";
import { Implementors } from "./briefing-contents.tsx";
+import { MotionCount } from "./briefing-motion.tsx";
import { Block, MoreToggle, lower, plural } from "./briefing-parts.tsx";
import {
dateMonths,
@@ -29,7 +37,7 @@ import {
type Distribution,
type FieldConnection,
} from "./collection.ts";
-import { GroupFacts, GroupPage } from "./components.tsx";
+import { GroupFacts, GroupPage, openRecord } from "./components.tsx";
import { linkGraph } from "./graph.ts";
import { useCollectionModel } from "./load.ts";
import { fieldLabel, type GroupModel, type Member } from "./model.ts";
@@ -39,12 +47,46 @@ function InMotion({ model }: { model: GroupModel }) {
const motion = useMemo(() => inMotion(model), [model]);
const entries = motion.groups[0]?.entries ?? [];
+ const metadata = useMotionMetadata(model, entries);
+
return (
Last changed}
+ count={
+ <>
+
+ {needsAttention(model, linkGraph(model), Date.now())
+ .filter((signal) => signal.kind === "stale")
+ .map(
+ (signal) =>
+ signal.kind === "stale" && (
+
+
+
+ {signal.records.length} unchanged
+
+
+ Active records unchanged for 30+ days. Review whether they still reflect
+ current work.
+
+ {signal.records.map((record) => (
+
+ openRecord(record)}>
+ {record.title}
+
+
+ ))}
+
+
+
+ ),
+ )}
+ >
+ }
info={{
- text: "Records whose lifecycle value is in the active stage, newest change first.",
+ text: "Records whose lifecycle value is in the active stage, newest change first. Unchanged records have had no update for 30 days; review whether they still reflect current work.",
display: "title",
}}
>
@@ -65,7 +107,7 @@ function DistributionRow({ distribution }: { distribution: Distribution }) {
return (
- {fieldLabel(field)} {role}
+ {fieldLabel(field)} {role !== "lifecycle" && {role} }
{values.map(({ value, count }) => (
@@ -184,7 +226,7 @@ function SpreadBlock({ model, member }: { model: GroupModel; member: Member }) {
return (
-
+
{fieldLabel(field)}
{direction === "forward" ? "→" : "←"} {targetLabel(model, connection.targetType)}
@@ -228,11 +271,12 @@ function ConnectionRow({ model, connection }: { model: GroupModel; connection: F
{filled} of {total} {lower(model.members[0].pluralLabel)} linked
-
-
+
+
{top.length > 0 ? (
<>
+
Linked {lower(model.members[0].pluralLabel)}
{shown.map(({ note, count }) => (
@@ -352,7 +396,7 @@ function BriefingBody({ model, member }: { model: GroupModel; member: Member })
signal.kind !== "stale")}
info="Validation issues and declared warning values."
memberAction={openTable}
/>
diff --git a/web/bundled-views/group/validation-freshness.tsx b/web/bundled-views/group/validation-freshness.tsx
index 8f38e2c39..c475cddf8 100644
--- a/web/bundled-views/group/validation-freshness.tsx
+++ b/web/bundled-views/group/validation-freshness.tsx
@@ -1,4 +1,4 @@
-import { useValidationSummaries } from "@rhizome/kit";
+import { RelativeTime, ValidationCheck, useValidationSummaries } from "@rhizome/kit";
import { useQuery } from "@tanstack/react-query";
import { isJsonObject, isNumber, isString, type JsonValue } from "./api.ts";
import { getJSON } from "./load.ts";
@@ -56,7 +56,7 @@ export function ValidationFreshness() {
}
/**
- * "✓ No issues" for a scope with none, but only when the last validation run
+ * "✓ No validation issues" for a scope with none, but only when the last validation run
* is current; a stale, running, or failed run would make an old zero look clean.
*/
export function NoIssues() {
@@ -65,7 +65,23 @@ export function NoIssues() {
if (health === null) return null;
if (health === "current_clean" || health === "current_issues")
- return ✓ No issues ;
+ return (
+
+
+
+ );
return Validation out of date ;
}
+
+export function LastChanged({ value }: { value: number }) {
+ const now = new Date();
+ const age = now.getTime() - value;
+
+ return (
+
+ Last changed
+ {age >= 60_000 && age < 60 * 86_400_000 && ago }
+
+ );
+}
diff --git a/web/bundled-views/group/workspace-briefing.test.tsx b/web/bundled-views/group/workspace-briefing.test.tsx
index 04b477d11..bc5a686cf 100644
--- a/web/bundled-views/group/workspace-briefing.test.tsx
+++ b/web/bundled-views/group/workspace-briefing.test.tsx
@@ -158,8 +158,11 @@ it("briefs All notes: issues by variant and work in motion, beside recent change
);
const motion = region("In motion");
+ expect(within(motion).getByText("Last changed")).toBeVisible();
expect(motion.querySelector("h3")).toBeNull();
- expect(motion.querySelectorAll(".gv-change-meta")).toHaveLength(MOTION_PER_TYPE);
+ expect(motion.querySelector(".rz-count")).toHaveTextContent("5");
+ expect(motion.querySelectorAll(".gv-change-meta")).toHaveLength(1);
+ expect(motion.querySelector(".gv-motion-metadata")).not.toBeNull();
// Doing and Shipping mix in this list, so each row carries its status.
expect(motion.querySelector(".gv-mark")).not.toBeNull();
expect(within(motion).queryByText(`Story ${MOTION_PER_TYPE + 1}`)).toBeNull();
@@ -286,16 +289,33 @@ it.each([
context: WORKSPACE,
routes: routes({
"GET /api/v2/validate": () => jsonReply({ ...VALIDATION_ENVELOPE, health }),
+ "POST /api/v1/validation/summaries": () =>
+ jsonReply({
+ generation: 3,
+ summaries: [
+ {
+ scope: { kind: "global" },
+ issueCount: 0,
+ affectedFileCount: 0,
+ affectedNoteCount: 0,
+ repairActionCount: 0,
+ },
+ ],
+ }),
"POST /api/v1/validation/groups": () => jsonReply({ generation: 3, groups: [] }),
}),
});
- if (clean) expect(await screen.findByText("No issues")).toBeVisible();
- else {
+ if (clean) {
+ const cleanState = await screen.findByText("No validation issues");
+ expect(cleanState.closest(".gv-facts")).not.toHaveTextContent("49 notes");
+ expect(cleanState.closest(".gv-facts")).toHaveTextContent("Checked");
+ expect(screen.queryByRole("region", { name: "Validation" })).toBeNull();
+ } else {
expect(
await screen.findByText("The last validation run is out of date or unfinished."),
).toBeVisible();
- expect(screen.queryByText("No issues")).toBeNull();
+ expect(screen.queryByText("No validation issues")).toBeNull();
}
});
@@ -334,3 +354,79 @@ it("says In motion waits while the index rebuilds, reading no records", async ()
expect(view.http.count("POST", "/api/v1/graphql")).toBe(0);
expect(view.http.count("GET", "/api/v1/ontology/types/Story")).toBe(0);
});
+
+it("states shared motion metadata once and keeps Recent changes metadata", async () => {
+ await renderGroupView(loadBriefing, {
+ context: WORKSPACE,
+ routes: routes({
+ "POST /api/v1/graphql": () =>
+ jsonReply({
+ data: {
+ Story: [record("Story", 1, { stage: "doing" }), record("Story", 2, { stage: "doing" })],
+ Bug: [],
+ Release: [],
+ },
+ }),
+ }),
+ });
+ const motion = region("In motion");
+ expect(motion.querySelectorAll(".gv-change-compact")).toHaveLength(2);
+ expect(motion.querySelector(".gv-change-meta")).toBeNull();
+ expect(motion.querySelector(".gv-motion-metadata")).toHaveTextContent("Story · story/");
+ expect(region("Recent changes").querySelectorAll(".gv-change-meta")).toHaveLength(3);
+});
+
+it("restores row metadata when expanding reveals another folder", async () => {
+ await renderGroupView(loadBriefing, {
+ context: WORKSPACE,
+ routes: routes({
+ "POST /api/v1/graphql": () =>
+ jsonReply({
+ data: {
+ Story: Array.from({ length: MOTION_PER_TYPE + 1 }, (_, index) =>
+ record("Story", index + 1, {
+ stage: "doing",
+ path: index === MOTION_PER_TYPE ? "archive/last.md" : `story/${index + 1}.md`,
+ }),
+ ),
+ Bug: [],
+ Release: [],
+ },
+ }),
+ }),
+ });
+ const motion = region("In motion");
+ expect(motion.querySelectorAll(".gv-change-compact")).toHaveLength(MOTION_PER_TYPE);
+ fireEvent.click(within(motion).getByRole("button", { name: "Show 1 more" }));
+ expect(motion.querySelector(".gv-motion-metadata")).toHaveTextContent("Story · story/");
+ expect(motion.querySelectorAll(".gv-change-meta")).toHaveLength(1);
+});
+
+it.each([14, 20, 23])("shows up to twenty motion rows when alone (%i records)", async (count) => {
+ await renderGroupView(loadBriefing, {
+ context: WORKSPACE,
+ routes: routes({
+ "GET /api/v2/validate": () => jsonReply({ ...VALIDATION_ENVELOPE, health: "current_clean" }),
+ "POST /api/v1/validation/groups": () => jsonReply({ generation: 3, groups: [] }),
+ "POST /api/v1/graphql": () =>
+ jsonReply({
+ data: {
+ Story: Array.from({ length: count }, (_, index) =>
+ record("Story", index + 1, { stage: "doing" }),
+ ),
+ Bug: [],
+ Release: [],
+ },
+ }),
+ }),
+ });
+ const motion = region("In motion");
+
+ expect(screen.queryByRole("region", { name: "Needs attention" })).toBeNull();
+ expect(motion.querySelectorAll(".gv-change")).toHaveLength(Math.min(count, 20));
+
+ if (count > 20) {
+ fireEvent.click(within(motion).getByRole("button", { name: `Show ${count - 20} more` }));
+ expect(motion.querySelectorAll(".gv-change")).toHaveLength(count);
+ } else expect(within(motion).queryByRole("button", { name: /Show .* more/ })).toBeNull();
+});
diff --git a/web/bundled-views/group/workspace-briefing.tsx b/web/bundled-views/group/workspace-briefing.tsx
index 070d27964..a3bf650b4 100644
--- a/web/bundled-views/group/workspace-briefing.tsx
+++ b/web/bundled-views/group/workspace-briefing.tsx
@@ -18,23 +18,18 @@ import {
useGraphQL,
useTypeDocs,
useValidationSummaries,
+ validationScopeKey,
type ViewModuleProps,
} from "@rhizome/kit";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo } from "react";
import { isString, parseRecords, type JsonObject, type JsonValue } from "./api.ts";
-import { ChangeRow } from "./briefing-activity.tsx";
-import {
- Block,
- BlockBody,
- HealthyAttention,
- MoreToggle,
- Rebuilding,
- lower,
- plural,
-} from "./briefing-parts.tsx";
+import { commonMotionMetadata, MotionCount } from "./briefing-motion.tsx";
+import { ageKey, ChangeRow } from "./briefing-activity.tsx";
+import { Block, BlockBody, MoreToggle, Rebuilding, lower, plural } from "./briefing-parts.tsx";
import "./components.tsx";
+import { LastChanged, NoIssues, ValidationFreshness } from "./validation-freshness.tsx";
import { getJSON, refetchFailedTypeDocs } from "./load.ts";
import { useRememberedOpen } from "./remembered.ts";
import {
@@ -138,7 +133,7 @@ function NeedsAttention() {
groups.data?.length === 0 &&
validation.health === "current_clean"
)
- return ;
+ return null;
return (
+ (pages?.get(entry.type)?.records ?? []).map((record) => ({
+ type: label(entry.type, false),
+ folder: record.path.split("/").slice(0, -1).join("/"),
+ time: record.updatedAt,
+ })),
+ )
+ .sort((a, b) => (b.time ?? 0) - (a.time ?? 0))
+ .slice(0, expanded.isOpen("in-motion", false) ? undefined : limit),
+ );
+
return (
Last changed}
+ count={
+ status.status === "ready" && !rebuilding ? (
+ sum + type.total, 0)}
+ metadata={metadata}
+ />
+ ) : undefined
+ }
info={{
text: "Records in an active lifecycle stage, any type, newest change first.",
display: "title",
@@ -271,7 +292,7 @@ function InMotion() {
.sort((a, b) => (b.record.updatedAt ?? 0) - (a.record.updatedAt ?? 0));
const open = expanded.isOpen("in-motion", false);
- const shown = open ? entries : entries.slice(0, MOTION_PER_TYPE);
+ const shown = open ? entries : entries.slice(0, limit);
const mixed =
new Set(entries.map(({ entry, record }) => record.values.get(entry.field))).size > 1;
@@ -279,12 +300,21 @@ function InMotion() {
return (
<>
- {shown.map(({ entry, record }) => {
+ {shown.map(({ entry, record }, index) => {
const value = record.values.get(entry.field);
return (
0 &&
+ ageKey(shown[index - 1].record.updatedAt) === ageKey(record.updatedAt)
+ }
line={{
key: record.key,
title: record.title,
@@ -307,9 +337,9 @@ function InMotion() {
);
})}
- {entries.length > MOTION_PER_TYPE && (
+ {entries.length > limit && (
expanded.setOpen("in-motion", !open)}
/>
@@ -357,9 +387,12 @@ function RecentChanges() {
{() =>
recent.data?.length ? (
{columns.map((column, columnIndex) => {
const direction = sortDirection(sort, column.field);
- const sortIndex = sort.findIndex((item) => item.field === column.field);
+ const sortIndex = visibleSort.findIndex((item) => item.field === column.field);
const label = columnLabel(column, capabilities);
const primary = columnIndex === primaryColumnIndex;
@@ -137,7 +139,7 @@ export function ConfiguredViewTableHeader({
}`}
title={
sortable
- ? `${direction ? `${label}: ${sortDescription(direction, sortIndex, sort.length)}. ` : `${label}. `}Shift-click to add a sort key`
+ ? `${direction ? `${label}: ${sortDescription(direction, sortIndex, visibleSort.length)}. ` : `${label}. `}Shift-click to add a sort key`
: label
}
// Cells announce this as their header; the sort button's
@@ -151,14 +153,16 @@ export function ConfiguredViewTableHeader({
onSort(column, event.shiftKey)}
- aria-label={`Sort ${label} ${direction === "asc" ? "descending" : "ascending"}${direction ? `; ${sortDescription(direction, sortIndex, sort.length)}` : ""}`}
+ aria-label={`Sort ${label} ${direction === "asc" ? "descending" : "ascending"}${direction ? `; ${sortDescription(direction, sortIndex, visibleSort.length)}` : ""}`}
>
{label}
{direction && (
{direction === "asc" ? "↑" : "↓"}
- {sort.length > 1 && (
- {sortIndex + 1}
+ {visibleSort.length > 1 && (
+
+ {sortIndex + 1}
+
)}
)}
diff --git a/web/src/components/ConfiguredViewTableModel.ts b/web/src/components/ConfiguredViewTableModel.ts
index 26b10fdef..4fcf89f0a 100644
--- a/web/src/components/ConfiguredViewTableModel.ts
+++ b/web/src/components/ConfiguredViewTableModel.ts
@@ -1,3 +1,4 @@
+import { type RefObject, useEffect, useState } from "react";
import type {
ViewExecuteRequest,
ViewExecuteResponse,
@@ -266,3 +267,25 @@ export function groupTone(capabilities: ViewFieldCapability[], group: Configured
function clamp(value: number, min: number, max: number) {
return Math.max(min, Math.min(max, value));
}
+
+/** The element's content width, or Infinity until it is measured. */
+export function useElementWidth(ref: RefObject) {
+ const [width, setWidth] = useState(Number.POSITIVE_INFINITY);
+
+ useEffect(() => {
+ const element = ref.current;
+
+ if (!element) return;
+
+ const observer = new ResizeObserver(() => {
+ // A hidden table measures zero; it keeps its columns until it shows.
+ if (element.clientWidth > 0) setWidth(element.clientWidth);
+ });
+
+ observer.observe(element);
+
+ return () => observer.disconnect();
+ }, [ref]);
+
+ return width;
+}
diff --git a/web/src/components/ConfiguredViewTableRows.tsx b/web/src/components/ConfiguredViewTableRows.tsx
index 0d1c980fc..bc9983ce1 100644
--- a/web/src/components/ConfiguredViewTableRows.tsx
+++ b/web/src/components/ConfiguredViewTableRows.tsx
@@ -133,6 +133,7 @@ export function ConfiguredViewTableGroup({
- Overdue
+
+ Overdue
+
) : columnIndex === primaryColumnIndex && dirty ? (
diff --git a/web/src/components/ConfiguredViewToolbar.tsx b/web/src/components/ConfiguredViewToolbar.tsx
index 700b0d7c1..52a3f1be6 100644
--- a/web/src/components/ConfiguredViewToolbar.tsx
+++ b/web/src/components/ConfiguredViewToolbar.tsx
@@ -1,3 +1,11 @@
+import {
+ initialDraftFilter,
+ draftsFromState,
+ filterSummary,
+ filterCapabilitiesForDraft,
+} from "./ConfiguredViewFilterDrafts";
+import { Filter } from "lucide-react";
+import { ConfiguredViewFind } from "./ConfiguredViewFind";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import type {
@@ -13,10 +21,9 @@ import {
FilterRow,
filterSpecForDraft,
opLabel,
- optionLabel,
} from "./ConfiguredViewFilterRow";
import { usePopoverDismiss } from "./focusManagement";
-import { capabilityOptions, viewFieldControl } from "./viewFieldControls";
+import { viewFieldControl } from "./viewFieldControls";
import {
capabilityFor,
dedupeCapabilitiesForControls,
@@ -67,12 +74,8 @@ type Props = {
placeTools: (tools: ReactNode) => ReactNode;
};
-type FilterSpec = NonNullable[number];
-
const FILTER_DEBOUNCE_MS = 300;
-let nextFilterID = 0;
-
export function ConfiguredViewToolbar({
state,
capabilities,
@@ -113,36 +116,10 @@ export function ConfiguredViewToolbar({
);
const filterRef = useRef(null);
- const searchRef = useRef(null);
const lastEmittedFiltersKeyRef = useRef(null);
usePopoverDismiss(filterOpen, filterRef, () => setFilterOpen(false));
- // ⌘F (Ctrl+F elsewhere) finds in the view while it shows.
- useEffect(() => {
- if (!active) return;
-
- const onKeyDown = (event: KeyboardEvent) => {
- const search = searchRef.current;
-
- if (
- event.key.toLowerCase() !== "f" ||
- !(event.metaKey || event.ctrlKey) ||
- event.shiftKey ||
- event.altKey ||
- !search?.isConnected
- )
- return;
- event.preventDefault();
- search.focus();
- search.select();
- };
-
- window.addEventListener("keydown", onKeyDown);
-
- return () => window.removeEventListener("keydown", onKeyDown);
- }, [active]);
-
useEffect(() => {
const stateFiltersKey = JSON.stringify(state.filters ?? []);
@@ -210,7 +187,12 @@ export function ConfiguredViewToolbar({
function updateFilterField(index: number, field: string) {
const capability = capabilityFor(displayCapabilities, field);
- updateFilter(index, { field, op: defaultFilterOp(capability), value: "", values: [] });
+ updateFilter(index, {
+ field,
+ op: viewFieldControl(capability).defaultOp,
+ value: "",
+ values: [],
+ });
}
function updateFilterOperator(index: number, op: string) {
@@ -247,20 +229,11 @@ export function ConfiguredViewToolbar({
const tools = (
<>
-
-
- onResetPage({ search: event.target.value })}
- />
- {!state.search && ⌘F }
-
+ onResetPage({ search })}
+ />
setFilterOpen((open) => !open)}
disabled={capabilities.length === 0 && presets.length === 0}
>
-
+
Filter
{activeCount > 0 && {activeCount} }
@@ -456,119 +429,3 @@ export function ConfiguredViewToolbar({
>
);
}
-
-function SearchIcon() {
- return (
-
-
-
-
- );
-}
-
-function FilterIcon() {
- return (
-
-
-
- );
-}
-
-function initialDraftFilter(capabilities: ViewFieldCapability[]): DraftFilter {
- const first = [...capabilities]
- .filter((capability) => viewFieldControl(capability).ops.length > 0)
- .sort((left, right) => draftFilterRank(right) - draftFilterRank(left))[0];
-
- return {
- id: newFilterID(),
- field: first?.key ?? capabilities[0]?.key ?? "",
- op: defaultFilterOp(first),
- value: "",
- values: [],
- };
-}
-
-function draftFilterRank(capability: ViewFieldCapability) {
- let rank = capabilityOptions(capability).length > 0 ? 100 : 0;
-
- const names = [
- capability.key,
- capability.label,
- capability.canonicalField,
- capability.edit?.field,
- ]
- .filter(Boolean)
- .join(" ");
-
- if (capability.semanticRole === "status" || /status/i.test(names)) rank += 80;
-
- if (viewFieldControl(capability).ops.includes("in")) rank += 10;
-
- if (capability.semanticRole === "identifier" || capability.key === "id") rank -= 60;
-
- return rank;
-}
-
-function draftsFromState(filters: FilterSpec[], capabilities: ViewFieldCapability[]) {
- return filters.map((filter) => {
- const values = (filter.values ?? []).map((value) => String(value));
-
- return {
- id: newFilterID(),
- field: filter.field,
- op: filter.op || defaultFilterOp(capabilityFor(capabilities, filter.field)),
- value: String(filter.value ?? values.join(", ")),
- values,
- };
- });
-}
-
-function newFilterID() {
- nextFilterID += 1;
-
- return `filter-${nextFilterID}`;
-}
-
-function defaultFilterOp(capability: ViewFieldCapability | undefined) {
- return viewFieldControl(capability).defaultOp;
-}
-
-function filterSummary(filter: FilterSpec, capability: ViewFieldCapability | undefined) {
- if (filter.op === "in") {
- return (filter.values ?? []).map((value) => optionLabel(capability, String(value))).join(", ");
- }
-
- if (filter.op === "exists" || filter.op === "missing") return "";
-
- if (viewFieldControl(capability).kind === "relation")
- return optionLabel(capability, String(filter.value ?? ""));
-
- return String(filter.value ?? "");
-}
-
-function filterCapabilitiesForDraft(
- display: ViewFieldCapability[],
- all: ViewFieldCapability[],
- field: string,
-) {
- if (capabilityFor(display, field)) return display;
- const selected = capabilityFor(all, field);
-
- return selected ? [...display, selected] : display;
-}
diff --git a/web/src/components/ExplorerHeader.tsx b/web/src/components/ExplorerHeader.tsx
new file mode 100644
index 000000000..941f7f866
--- /dev/null
+++ b/web/src/components/ExplorerHeader.tsx
@@ -0,0 +1,170 @@
+import { Info, Search } from "lucide-react";
+import type { GraphResponse, SearchResponse } from "../api/types";
+import { folderCoverage } from "./explorerNavigation";
+
+type Props = {
+ graph: GraphResponse;
+ focusedPath?: string;
+ filePath?: string;
+ graphScopeLabel: string;
+ displaySlot: (element: HTMLDivElement | null) => void;
+ searchActive: boolean;
+ searching: boolean;
+ searchError: boolean;
+ matchCount: number;
+ searchOnlyMatches: boolean;
+ setSearchOnlyMatches: (value: boolean) => void;
+ query: string;
+ setQuery: (value: string) => void;
+ clearSearch: () => void;
+ runSearch: () => void;
+ showSuggestions: boolean;
+ setShowSuggestions: (value: boolean) => void;
+ suggestions: NonNullable
;
+ onSelectFile: (path: string, kind?: string) => void;
+ retrySearch: () => void;
+};
+
+export function ExplorerHeader({
+ graph,
+ focusedPath,
+ filePath,
+ graphScopeLabel,
+ displaySlot: setDisplaySlot,
+ searchActive,
+ searching,
+ searchError,
+ matchCount,
+ searchOnlyMatches,
+ setSearchOnlyMatches,
+ query,
+ setQuery,
+ clearSearch,
+ runSearch,
+ showSuggestions,
+ setShowSuggestions,
+ suggestions,
+ onSelectFile,
+ retrySearch,
+}: Props) {
+ const counts = (path?: string) => {
+ const nodes = path
+ ? graph.nodes.filter((n) => (n.notePath || n.path || "").startsWith(`${path}/`))
+ : graph.nodes;
+
+ return `${nodes.filter((n) => n.kind === "note").length.toLocaleString("en-US")} notes · ${nodes.filter((n) => n.kind === "code").length.toLocaleString("en-US")} code files`;
+ };
+
+ return (
+
+
+
Explorer
+
+ {filePath && (
+
+ {filePath.split("/").pop()} neighbourhood ·{" "}
+
+ )}
+ {focusedPath && (
+
+ {focusedPath.split("/").join(" / ")} ·{" "}
+
+ )}
+ {graph.nodes.length ? counts(focusedPath) : ""}
+ {focusedPath && of {counts()} }
+
+
+
+
+
+
{
+ if (!event.currentTarget.contains(event.relatedTarget)) setShowSuggestions(false);
+ }}
+ >
+ {searchActive && !searching && !searchError ? (
+
+ {matchCount} {matchCount === 1 ? "match" : "matches"}
+
+ ) : null}
+ {searchActive ? (
+
+ setSearchOnlyMatches(e.target.checked)}
+ />
+ Only matches
+
+ ) : null}
+
+
+ {
+ setQuery(e.target.value);
+
+ if (e.target.value.trim() === "") {
+ clearSearch();
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ runSearch();
+ setShowSuggestions(false);
+ }
+
+ if (e.key === "Escape") {
+ setQuery("");
+ setShowSuggestions(false);
+ clearSearch();
+ }
+ }}
+ onFocus={() => {
+ setShowSuggestions(true);
+ }}
+ placeholder={searching ? "Searching…" : "Search notes and code"}
+ />
+
+ {showSuggestions && suggestions.length > 0 && (
+
+ {suggestions.map((suggestion) => (
+ {
+ e.preventDefault();
+ }}
+ onClick={() => {
+ if (suggestion.path) onSelectFile(suggestion.path, suggestion.kind);
+ setShowSuggestions(false);
+ }}
+ >
+ {suggestion.path}
+ {suggestion.kind}
+
+ ))}
+
+ )}
+ {searchError ? (
+
+ Search unavailable.{" "}
+ retrySearch()}>
+ Retry
+
+
+ ) : null}
+
+
+
+ );
+}
diff --git a/web/src/components/ExplorerListings.test.tsx b/web/src/components/ExplorerListings.test.tsx
new file mode 100644
index 000000000..767dd85cf
--- /dev/null
+++ b/web/src/components/ExplorerListings.test.tsx
@@ -0,0 +1,59 @@
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { expect, it } from "vitest";
+import { withFakeFetch, jsonReply } from "../test/fakeFetch";
+import { renderWithQueryClient } from "../test/renderWithQueryClient";
+import { TreeList } from "./TreeList";
+import { useExplorerListings } from "./useExplorerListings";
+
+const http = withFakeFetch();
+
+for (const path of ["", "folder"]) {
+ it(`pages a listing of 201 eligible entries at ${path || "root"}`, async () => {
+ const entries = Array.from({ length: 201 }, (_, i) => ({
+ name: `file${i}.go`,
+ path: `${path}/file${i}.go`,
+ kind: "code",
+ hasChildren: false,
+ }));
+
+ const limits: number[] = [];
+ http.on("GET", "/api/v1/files/tree", (request) => {
+ const requestedPath = request.query.get("path") ?? "";
+
+ if (requestedPath !== path) return jsonReply({ path: "", entries: [] });
+ const limit = Number(request.query.get("limit") ?? 200);
+ limits.push(limit);
+
+ return jsonReply({
+ path,
+ entries: entries.slice(0, limit),
+ truncated: limit < 201,
+ omitted: Math.max(0, 201 - limit),
+ });
+ });
+
+ function Listing() {
+ const listing = useExplorerListings(new Set(path ? [path] : []));
+
+ return (
+ {}}
+ onToggle={() => {}}
+ />
+ );
+ }
+
+ renderWithQueryClient( );
+ const more = await screen.findByText("Show 1 more (1 remaining)");
+ await waitFor(() => expect(more).toBeEnabled());
+ fireEvent.click(more);
+ expect(await screen.findByText("file200.go")).toBeVisible();
+ await waitFor(() => expect(screen.queryByText(/remaining/)).not.toBeInTheDocument());
+ expect(limits).toEqual([200, 400]);
+ });
+}
diff --git a/web/src/components/ExplorerWorkspace.layout.test.tsx b/web/src/components/ExplorerWorkspace.layout.test.tsx
new file mode 100644
index 000000000..02d34663a
--- /dev/null
+++ b/web/src/components/ExplorerWorkspace.layout.test.tsx
@@ -0,0 +1,88 @@
+import { act, fireEvent, screen, waitFor } from "@testing-library/react";
+import Sigma from "sigma";
+import { it, vi } from "vitest";
+import { expect } from "vitest";
+import type { GraphResponse } from "../api/types";
+import { withFakeFetch, deferredReply } from "../test/fakeFetch";
+import { installFakeWebGL } from "../test/fakeWebGL";
+import { renderWithQueryClient as render } from "../test/renderWithQueryClient";
+import { ExplorerWorkspace } from "./ExplorerWorkspace";
+
+const http = withFakeFetch();
+
+const graphWith = (...ids: string[]): GraphResponse => ({
+ nodes: ids.map((id) => ({ id, kind: "code", path: id, label: id })),
+ edges: [],
+});
+
+const tree = (entry: { path: string; name: string; kind: string; hasChildren: boolean }) => ({
+ path: "",
+ entries: [entry],
+});
+
+const fileView = (path: string) => ({
+ path,
+ kind: "code",
+ content: path,
+ links: [],
+ frontmatter: {},
+});
+
+function renderExplorer() {
+ const sigmaOn = vi.spyOn(Sigma.prototype, "on");
+ render( );
+
+ return {
+ async graph() {
+ await screen.findByRole("img", { name: /^Graph of / });
+ const sigma = sigmaOn.mock.contexts.at(-1);
+
+ if (!(sigma instanceof Sigma)) throw new Error("No renderer");
+
+ return sigma.getGraph();
+ },
+ };
+}
+
+it("preserves root folder positions across an uncached file visit", async () => {
+ const restore = installFakeWebGL();
+
+ try {
+ http.json("GET", "/api/v1/ontology/summary", { types: [], interfaces: [] });
+ const local = deferredReply();
+ http
+ .json("GET", "/api/v1/graphs/global", graphWith("a/one.go", "b/two.go", "c/three.go"))
+ .on("GET", "/api/v1/graphs/local", () => local.promise)
+ .json(
+ "GET",
+ "/api/v1/files/tree",
+ tree({ path: "main.go", name: "main.go", kind: "code", hasChildren: false }),
+ )
+ .json("GET", "/api/v1/files/view", fileView("main.go"));
+ const explorer = renderExplorer();
+
+ const positions = async () => {
+ const graph = await explorer.graph();
+
+ return graph
+ .filterNodes((id) => id.startsWith("folder:"))
+ .map((id) => [id, graph.getNodeAttribute(id, "x"), graph.getNodeAttribute(id, "y")]);
+ };
+
+ await waitFor(async () => expect((await positions()).length).toBeGreaterThan(1));
+ const before = await positions();
+ fireEvent.click(await screen.findByRole("button", { name: /main.go/i }));
+ await waitFor(() => expect(http.count("GET", "/api/v1/graphs/local")).toBe(1));
+ local.resolve(graphWith("main.go", "z/local.go"));
+ await waitFor(async () => expect((await explorer.graph()).hasNode("main.go")).toBe(true));
+ act(() => {
+ window.history.replaceState({}, "", "/explorer");
+ window.dispatchEvent(new PopStateEvent("popstate"));
+ });
+ await waitFor(async () => expect(await positions()).toEqual(before));
+ } finally {
+ vi.restoreAllMocks();
+ restore();
+ window.history.replaceState({}, "", "/explorer");
+ }
+});
diff --git a/web/src/components/ExplorerWorkspace.searchBounds.test.tsx b/web/src/components/ExplorerWorkspace.searchBounds.test.tsx
new file mode 100644
index 000000000..d8941d5dd
--- /dev/null
+++ b/web/src/components/ExplorerWorkspace.searchBounds.test.tsx
@@ -0,0 +1,139 @@
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import Sigma from "sigma";
+import { installFakeWebGL } from "../test/fakeWebGL";
+import { beforeAll, afterEach, expect, it, vi } from "vitest";
+import { withFakeFetch } from "../test/fakeFetch";
+import { renderWithQueryClient } from "../test/renderWithQueryClient";
+import { ExplorerWorkspace } from "./ExplorerWorkspace";
+
+beforeAll(async () => {
+ await import("./GraphView");
+});
+
+let restore = () => {};
+
+afterEach(() => {
+ restore();
+ vi.restoreAllMocks();
+});
+
+const http = withFakeFetch();
+
+it("keeps a large search aggregated before building the renderer graph", async () => {
+ restore = installFakeWebGL();
+ const sigmaOn = vi.spyOn(Sigma.prototype, "on");
+
+ const nodes = Array.from({ length: 10000 }, (_, i) => ({
+ id: `n${i}`,
+ path: `${i % 2 ? "docs" : "src"}/item${i}.${i % 2 ? "md" : "ts"}`,
+ kind: i % 2 ? "note" : "code",
+ label: `item${i}`,
+ }));
+
+ http
+ .json("GET", "/api/v1/ontology/summary", { types: [], interfaces: [] })
+ .json("GET", "/api/v1/files/tree", { path: "", entries: [] })
+ .json("GET", "/api/v1/graphs/global", { nodes, edges: [], truncated: false })
+ .json("GET", "/api/v1/search", {
+ count: 2,
+ matches: [
+ { path: "docs/item1.md", kind: "note" },
+ { path: "src/item0.ts", kind: "code" },
+ ],
+ })
+ .json("GET", "/api/v1/suggest", { count: 0, matches: [] });
+ renderWithQueryClient( );
+ await screen.findByRole("img", { name: /^Graph of / });
+ const sigma = sigmaOn.mock.contexts.at(-1);
+
+ if (!(sigma instanceof Sigma)) throw new Error("No graph renderer");
+ const before = sigma.getGraph().export();
+ const search = screen.getByRole("searchbox", { name: "Search notes and code" });
+ fireEvent.change(search, { target: { value: "item" } });
+ fireEvent.keyDown(search, { key: "Enter" });
+ await screen.findByText("2 matches");
+ await waitFor(() => {
+ const graph = sigma.getGraph();
+ expect(graph.order).toBeLessThan(40);
+ expect(graph.export().edges).toEqual(before.edges);
+ expect(graph.nodes()).toEqual(before.nodes.map((node) => node.key));
+
+ for (const node of before.nodes) {
+ expect(graph.getNodeAttributes(node.key)).toMatchObject({
+ x: node.attributes?.x,
+ y: node.attributes?.y,
+ });
+ }
+
+ expect(graph.getNodeAttribute("folder:docs", "searchMatchCount")).toBe(1);
+ expect(graph.getNodeAttribute("folder:src", "labelDetail")).toBe("1 match");
+ expect(graph.getNodeAttribute("folder:docs", "childCount")).toBe(5000);
+ expect(graph.getNodeAttribute("folder:src", "childCount")).toBe(5000);
+ });
+});
+
+it("keeps hidden file matches represented until the user reveals them", async () => {
+ restore = installFakeWebGL();
+ const sigmaOn = vi.spyOn(Sigma.prototype, "on");
+ window.history.replaceState(null, "", "?file=src/focus.ts");
+
+ const nodes = Array.from({ length: 40 }, (_, i) => ({
+ id: `n${i}`,
+ path: `src/item${String(i).padStart(2, "0")}.ts`,
+ kind: "code",
+ label: `item${i}`,
+ }));
+
+ const graph = {
+ nodes: [{ id: "focus", path: "src/focus.ts", kind: "code", label: "focus" }, ...nodes],
+ edges: [],
+ truncated: false,
+ };
+
+ http
+ .json("GET", "/api/v1/ontology/summary", { types: [], interfaces: [] })
+ .json("GET", "/api/v1/files/tree", { path: "", entries: [] })
+ .json("GET", "/api/v1/files/view", {
+ path: "src/focus.ts",
+ kind: "code",
+ content: "",
+ links: [],
+ frontmatter: {},
+ })
+ .json("GET", "/api/v1/graphs/global", graph)
+ .json("GET", "/api/v1/graphs/local", graph)
+ .json("GET", "/api/v1/search", {
+ count: 2,
+ matches: [{ path: nodes[38].path }, { path: nodes[39].path }],
+ })
+ .json("GET", "/api/v1/suggest", { count: 0, matches: [] });
+ renderWithQueryClient( );
+ await screen.findByRole("img", { name: /^Graph of / });
+ const sigma = sigmaOn.mock.contexts.at(-1);
+
+ if (!(sigma instanceof Sigma)) throw new Error("No graph renderer");
+ const before = sigma.getGraph().export();
+ const search = screen.getByRole("searchbox", { name: "Search notes and code" });
+ expect(sigma.getGraph().getNodeAttribute("file-more:Other code", "muted")).toBe(false);
+ fireEvent.change(search, { target: { value: "item" } });
+ fireEvent.keyDown(search, { key: "Enter" });
+ await screen.findByText("2 matches");
+ await waitFor(() =>
+ expect(sigma.getGraph().getNodeAttribute("file-more:Other code", "searchMatchCount")).toBe(2),
+ );
+ fireEvent.click(screen.getByRole("checkbox", { name: "Only matches" }));
+ await waitFor(() => {
+ const graph = sigma.getGraph();
+ expect(graph.getNodeAttributes("file-more:Other code")).toMatchObject({
+ searchMatchCount: 2,
+ labelDetail: "2 matches",
+ muted: false,
+ });
+ expect(graph.getNodeAttribute("file-group:Other code", "searchMatchCount")).toBe(2);
+ expect(graph.nodes()).toEqual(before.nodes.map((node) => node.key));
+ expect(graph.hasNode("n39")).toBe(false);
+ expect(sigma.getNodeDisplayData("file-more:Other code")?.hidden).toBe(false);
+ expect(sigma.getNodeDisplayData("file-group:Other code")?.hidden).toBe(false);
+ });
+ window.history.replaceState(null, "", "/");
+});
diff --git a/web/src/components/ExplorerWorkspace.test.tsx b/web/src/components/ExplorerWorkspace.test.tsx
index 5b1ff02e4..59a9ee56f 100644
--- a/web/src/components/ExplorerWorkspace.test.tsx
+++ b/web/src/components/ExplorerWorkspace.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
import Sigma from "sigma";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { FileView, GraphResponse, SearchResponse, TreeResponse } from "../api/types";
@@ -59,7 +59,6 @@ describe("ExplorerWorkspace", () => {
beforeEach(() => {
restoreWebGL = installFakeWebGL();
- // Empty, well-formed reads for everything a test does not care about.
http
.json("GET", "/api/v1/files/tree", tree())
.json("GET", "/api/v1/graphs/global", graphWith())
@@ -72,6 +71,7 @@ describe("ExplorerWorkspace", () => {
});
afterEach(() => {
+ cleanup();
vi.restoreAllMocks();
restoreWebGL();
window.history.replaceState({}, "", "/explorer");
@@ -83,7 +83,7 @@ describe("ExplorerWorkspace", () => {
const utils = render( );
async function renderer() {
- await screen.findByRole("img", { name: /^Graph of / });
+ await waitFor(() => expect(sigmaOn).toHaveBeenCalled());
const sigma = sigmaOn.mock.contexts.at(-1);
if (!(sigma instanceof Sigma)) throw new Error("graph pane never mounted a renderer");
@@ -189,14 +189,14 @@ describe("ExplorerWorkspace", () => {
});
});
- await waitFor(() =>
- expect(http.requests("GET", "/api/v1/graphs/expand").at(-1)?.query.get("module")).toBe("pkg"),
- );
+ await waitFor(() => expect(renderer.getGraph().hasNode("b")).toBe(true));
+ expect(http.count("GET", "/api/v1/graphs/expand")).toBe(0);
+ expect(http.requests("GET", "/api/v1/graphs/global")[0]?.query.get("limit")).toBe("200000");
expect(document.querySelector(".explorer-pane")).toBeNull();
expect(document.querySelector(".explorer-grid--with-pane")).toBeNull();
});
- it("keeps containment separate from links between a parent folder and its child", async () => {
+ it("keeps note links separate from containment edges", async () => {
http.json("GET", "/api/v1/graphs/global", {
nodes: [
{ id: "a", label: "a", kind: "note", path: "docs/a.md" },
@@ -208,13 +208,13 @@ describe("ExplorerWorkspace", () => {
const explorer = renderExplorer();
const graph = await explorer.graph();
- await waitFor(() => expect(graph.edges("folder:docs", "folder:docs/specs")).toHaveLength(2));
+ await waitFor(() => expect(graph.edges("more:docs", "folder:docs/specs")).toHaveLength(1));
expect(
graph
- .edges("folder:docs", "folder:docs/specs")
+ .edges("more:docs", "folder:docs/specs")
.map((edge) => graph.getEdgeAttribute(edge, "kind"))
.sort(),
- ).toEqual(["folder-containment", "folder-minor"]);
+ ).toEqual(["folder-crosslink"]);
});
it("opens an embedded graph node at its canonical target", async () => {
@@ -462,7 +462,7 @@ describe("ExplorerWorkspace", () => {
const oldSearch = deferredReply();
const currentSearch = deferredReply();
http
- .json("GET", "/api/v1/graphs/global", graphWith("specs/current.md", "specs/old.md"))
+ .json("GET", "/api/v1/graphs/global", graphWith("current/current.md", "old/old.md"))
.on("GET", "/api/v1/search", (request) =>
request.query.get("q") === "old" ? oldSearch.promise : currentSearch.promise,
);
@@ -477,13 +477,13 @@ describe("ExplorerWorkspace", () => {
fireEvent.keyDown(search, { key: "Enter" });
fireEvent.click(screen.getByLabelText("Only matches"));
- currentSearch.resolve({ count: 1, matches: [{ path: "specs/current.md", kind: "note" }] });
+ currentSearch.resolve({ count: 1, matches: [{ path: "current/current.md", kind: "note" }] });
// With "Only matches" on, the graph hides everything the submitted search
// did not return, so node visibility is the search set the pane is using.
- await waitFor(() => expect(displayHidden("specs/current.md")).toBe(false));
- expect(displayHidden("specs/old.md")).toBe(true);
+ await waitFor(() => expect(displayHidden("folder:current")).toBe(false));
+ expect(displayHidden("folder:old")).toBe(true);
- oldSearch.resolve({ count: 1, matches: [{ path: "specs/old.md", kind: "note" }] });
+ oldSearch.resolve({ count: 1, matches: [{ path: "old/old.md", kind: "note" }] });
await act(async () => {
await oldSearch.promise;
});
@@ -493,7 +493,7 @@ describe("ExplorerWorkspace", () => {
act(() => {
sigma.refresh();
});
- expect(displayHidden("specs/current.md")).toBe(false);
- expect(displayHidden("specs/old.md")).toBe(true);
+ expect(displayHidden("folder:current")).toBe(false);
+ expect(displayHidden("folder:old")).toBe(true);
});
});
diff --git a/web/src/components/ExplorerWorkspace.tsx b/web/src/components/ExplorerWorkspace.tsx
index dd0b3cfcb..df40cd5cc 100644
--- a/web/src/components/ExplorerWorkspace.tsx
+++ b/web/src/components/ExplorerWorkspace.tsx
@@ -1,131 +1,42 @@
-import { useQueries, useQuery } from "@tanstack/react-query";
-import { FolderOpen, Info, Search } from "lucide-react";
+import { EMPTY_GRAPH, type ExplorerSelection } from "./ExplorerWorkspaceState";
+import { useQuery } from "@tanstack/react-query";
+import { FolderOpen } from "lucide-react";
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
import {
- getExpandedModuleGraph,
getFileView,
getGlobalGraph,
getLocalGraph,
getSuggestions,
- getTree,
searchPaths as searchPathMatches,
} from "../api/client";
import { queryKeys } from "../api/queryKeys";
-import type { FileView, GraphNode, GraphResponse, TreeEntry } from "../api/types";
+import type { FileView, GraphNode, TreeEntry } from "../api/types";
import { vaultLabel } from "../lib/labels";
-import { encodeURLFragment } from "../lib/noteDeepLink";
import { useTypeAccentKey } from "../lib/typeAccent";
import { publicTypeName } from "../lib/typeNames";
-import { aggregateByFolder } from "./folderGraph";
+import { useDebouncedValue, useFolderExplorer } from "./useFolderExplorer";
+import { folderSearchMatches } from "./folderSearchMatches";
+import { useExplorerGraph, useRevealRail } from "./explorerGraph";
+import { ExplorerHeader } from "./ExplorerHeader";
import { buildTypeColors, graphNodeNavigationTarget, type GraphScope } from "./graphViewShared";
import { notifyLocationChange, useLocationSnapshot } from "./locationStore";
-import { NOTES_ROOT_PATH } from "./notesRoute";
import { TreeList } from "./TreeList";
+import { useExplorerListings } from "./useExplorerListings";
import { WorkbenchSidebar } from "./WorkbenchSidebar";
+import { isNoteTarget, openNoteWorkspace, explorerFileFromLocation } from "./explorerNavigation";
-const FilePanel = lazy(() =>
- import("./FilePanel").then((module) => ({
- default: module.FilePanel,
- })),
-);
+export { folderCoverage } from "./explorerNavigation";
-const GraphView = lazy(() =>
- import("./GraphView").then((module) => ({
- default: module.GraphView,
- })),
-);
+const FilePanel = lazy(() => import("./FilePanel").then((m) => ({ default: m.FilePanel })));
-function moduleKey(path: string, depth: number) {
- const cleaned = path.replace(/^\/+/, "");
- const parts = cleaned.split("/");
-
- if (parts.length === 0) return "root";
-
- if (parts.length < depth) return parts.join("/");
-
- return parts.slice(0, depth).join("/");
-}
-
-function isNoteTarget(path: string, kind?: string): boolean {
- if (kind) return ["note", "section", "embedded"].includes(kind.toLowerCase());
- const barePath = path.split("#", 1)[0] || path;
-
- return /\.(?:md|html?)$/i.test(barePath);
-}
-
-function openNoteWorkspace(path: string) {
- const hashIndex = path.indexOf("#");
- const notePath = hashIndex >= 0 ? path.slice(0, hashIndex) : path;
- const noteHash = hashIndex >= 0 ? path.slice(hashIndex) : "";
- const params = new URLSearchParams();
- params.set("note", notePath);
- window.history.pushState(
- {},
- "",
- `${NOTES_ROOT_PATH}?${params.toString()}${encodeURLFragment(noteHash)}`,
- );
- window.dispatchEvent(new PopStateEvent("popstate"));
-}
+const GraphView = lazy(() => import("./GraphView").then((m) => ({ default: m.GraphView })));
type ExplorerWorkspaceProps = {
- /** Vault name lifted from AppShell so this component avoids a redundant
- * `/api/v1/status` fetch. Empty string = still loading; renders the
- * "Vault" fallback on the tree's root row. */
vaultName: string;
sidebarTitle?: string | null;
sidebarHint?: string | null;
};
-type ExplorerSelection =
- | { kind: "root" }
- | { kind: "file"; path: string }
- | { kind: "module"; path: string };
-
-function explorerFileFromLocation(search: string): { path: string; line?: number } | null {
- const params = new URLSearchParams(search);
- const path = params.get("file")?.trim();
-
- if (!path) return null;
- const parsedLine = Number(params.get("line"));
-
- return {
- path,
- line: Number.isInteger(parsedLine) && parsedLine > 0 ? parsedLine : undefined,
- };
-}
-
-/**
- * What the folder view's counts cover. The graph can hold only part of a large
- * vault, so its note counts can run below Overview's; say so when it does.
- */
-export function folderCoverage(graph: GraphResponse) {
- const fmt = (count: number) => count.toLocaleString("en-US");
- const notes = graph.nodes.filter((node) => node.kind === "note").length;
- const files = graph.nodes.filter((node) => node.kind === "code").length;
- const counts = `Counts cover the ${fmt(notes)} notes and ${fmt(files)} code files in the graph`;
-
- return graph.truncated
- ? `${counts}, the best-connected part of the vault, so Overview can count more notes.`
- : `${counts}.`;
-}
-
-const EMPTY_GRAPH: GraphResponse = {
- nodes: [],
- edges: [],
- truncated: false,
-};
-
-function useDebouncedValue(value: string, delay: number) {
- const [debounced, setDebounced] = useState(value);
- useEffect(() => {
- const timer = window.setTimeout(() => setDebounced(value), delay);
-
- return () => window.clearTimeout(timer);
- }, [delay, value]);
-
- return debounced;
-}
-
export function ExplorerWorkspace({
vaultName,
sidebarTitle,
@@ -147,30 +58,7 @@ export function ExplorerWorkspace({
const [searchOnlyMatches, setSearchOnlyMatches] = useState(false);
const [graphZoomKey, setGraphZoomKey] = useState(0);
- const treeQuery = useQuery({
- queryKey: queryKeys.files.tree(undefined, 200),
- queryFn: ({ signal }) => getTree(undefined, 200, { signal }),
- });
-
- const tree = treeQuery.data?.entries ?? [];
-
- const expandedPathList = useMemo(() => Array.from(expandedPaths).sort(), [expandedPaths]);
-
- const expandedQueries = useQueries({
- queries: expandedPathList.map((path) => ({
- queryKey: queryKeys.files.tree(path, 200),
- queryFn: ({ signal }: { signal: AbortSignal }) => getTree(path, 200, { signal }),
- })),
- });
-
- const expanded = useMemo(() => {
- const result: Record = {};
- expandedPathList.forEach((path, index) => {
- result[path] = expandedQueries[index]?.data?.entries ?? [];
- });
-
- return result;
- }, [expandedPathList, expandedQueries]);
+ const { treeQuery, tree, expanded, more } = useExplorerListings(expandedPaths);
const selectedFilePath = selection.kind === "file" ? selection.path : "";
@@ -182,35 +70,25 @@ export function ExplorerWorkspace({
const file: FileView | null = selection.kind === "file" ? (fileQuery.data ?? null) : null;
- const graphQuery = useQuery({
- queryKey:
- selection.kind === "root"
- ? queryKeys.graph.global({})
- : selection.kind === "file"
- ? queryKeys.graph.local(selection.path, 200, {})
- : queryKeys.graph.expanded(selection.path, 600),
- queryFn: ({ signal }) => {
- if (selection.kind === "root") return getGlobalGraph({}, { signal });
-
- if (selection.kind === "file") {
- return getLocalGraph(selection.path, 200, {}, { signal });
- }
+ const globalGraphQuery = useQuery({
+ queryKey: queryKeys.graph.global({ limit: 200000 }),
+ queryFn: ({ signal }) => getGlobalGraph({ limit: 200000 }, { signal }),
+ });
- return getExpandedModuleGraph(selection.path, 600, { signal });
- },
+ const localGraphQuery = useQuery({
+ queryKey: queryKeys.graph.local(selectedFilePath, 200, {}),
+ queryFn: ({ signal }) => getLocalGraph(selectedFilePath, 200, {}, { signal }),
+ enabled: selection.kind === "file",
});
+ const graphQuery = selection.kind === "file" ? localGraphQuery : globalGraphQuery;
const graph = graphQuery.data ?? EMPTY_GRAPH;
- // The whole vault starts at folder level; picking a folder loads its own graph.
- const atRoot = selection.kind === "root";
+ const folderGraph = globalGraphQuery.data ?? EMPTY_GRAPH;
+ const atRoot = selection.kind !== "file";
const [displaySlot, setDisplaySlot] = useState(null);
const graphScope: GraphScope =
- selection.kind === "root"
- ? { mode: "global" }
- : selection.kind === "file"
- ? { mode: "local", label: selection.path }
- : { mode: "module", label: selection.path };
+ selection.kind === "file" ? { mode: "local", label: selection.path } : { mode: "global" };
const suggestionsQuery = useQuery({
queryKey: queryKeys.search.suggestions(debouncedQuery, 20),
@@ -230,18 +108,6 @@ export function ExplorerWorkspace({
match.path ? [match.path] : [],
);
- const searchModules = useMemo(() => {
- const modules = new Set();
-
- for (const path of searchPaths) {
- const key = moduleKey(path, 2);
-
- if (key) modules.add(key);
- }
-
- return Array.from(modules);
- }, [searchPaths]);
-
const searchActive = submittedSearch !== null;
const searching = searchQuery.isFetching;
@@ -271,7 +137,8 @@ export function ExplorerWorkspace({
const select = useCallback((next: ExplorerSelection, line?: number) => {
setSelection(next);
setSelectedLine(line);
- setGraphZoomKey((key) => key + 1);
+
+ if (next.kind !== "module") setGraphZoomKey((key) => key + 1);
if (next.kind === "file") {
const params = new URLSearchParams({ file: next.path });
@@ -298,6 +165,32 @@ export function ExplorerWorkspace({
[select],
);
+ const accentKey = useTypeAccentKey();
+
+ const typeColors = useMemo(
+ () =>
+ buildTypeColors([
+ ...new Set(
+ folderGraph.nodes.map((node) => publicTypeName(node.resolvedType)).filter(Boolean),
+ ),
+ ]),
+ // The summary decides each type's palette slot.
+ [folderGraph.nodes, accentKey],
+ );
+
+ const byFolder = atRoot;
+
+ const folderExplorer = useFolderExplorer(
+ folderGraph,
+ typeColors,
+ selection.kind === "module" ? selection.path : undefined,
+ );
+
+ useRevealRail(folderExplorer.initial, atRoot, selectedFilePath, setExpandedPaths);
+ const folders = byFolder ? folderExplorer.drawn : null;
+ const searchPathSet = useMemo(() => new Set(searchPaths), [searchPaths]);
+ const drawn = useExplorerGraph(folders, graph, selection, searchPathSet);
+
const focusModule = useCallback(
(path: string) => {
setExpandedPaths((previous) => {
@@ -308,20 +201,25 @@ export function ExplorerWorkspace({
return next;
});
+ folderExplorer.expand(path);
select({ kind: "module", path });
},
- [select],
+ [select, folderExplorer],
);
const onToggleDir = (entry: TreeEntry) => {
if (expandedPaths.has(entry.path)) {
setExpandedPaths((previous) => {
const next = new Set(previous);
- next.delete(entry.path);
+
+ for (const path of next)
+ if (path === entry.path || path.startsWith(`${entry.path}/`)) next.delete(path);
return next;
});
+ folderExplorer.collapse(entry.path);
+
return;
}
@@ -330,16 +228,25 @@ export function ExplorerWorkspace({
const onNodeClick = useCallback(
(node: GraphNode) => {
+ if (node.collapsed || drawn.reveal(node)) return;
+
if (node.kind === "module") {
- // Top-level files have no folder of their own to open.
- if (node.path) focusModule(node.path);
+ const path = node.path ?? "";
+
+ if (node.id.startsWith("more:")) folderExplorer.reveal(path);
+ else if (path) focusModule(path);
+ else {
+ folderExplorer.reset();
+ setExpandedPaths(new Set([...folderExplorer.initial].filter(Boolean)));
+ select({ kind: "root" });
+ }
} else if (node.kind === "embedded" || node.kind === "note" || node.kind === "code") {
const target = graphNodeNavigationTarget(node);
if (target) onSelectFile(target, node.kind);
}
},
- [focusModule, onSelectFile],
+ [focusModule, onSelectFile, folderExplorer, drawn],
);
const closePanel = useCallback(() => {
@@ -348,8 +255,10 @@ export function ExplorerWorkspace({
const onVaultRootClick = useCallback(() => {
clearSearch();
+ folderExplorer.reset();
+ setExpandedPaths(new Set([...folderExplorer.initial].filter(Boolean)));
select({ kind: "root" });
- }, [clearSearch, select]);
+ }, [clearSearch, select, folderExplorer]);
const resetGraphScope = useCallback(() => {
select({ kind: "root" });
@@ -368,38 +277,31 @@ export function ExplorerWorkspace({
}, [query, clearSearch]);
const hasPanel = selection.kind === "file";
- const searchPathSet = useMemo(() => new Set(searchPaths), [searchPaths]);
- const searchModuleSet = useMemo(() => new Set(searchModules), [searchModules]);
+
+ const searchCounts = useMemo(
+ () => folderSearchMatches(folders, graph, searchPathSet),
+ [folders, graph, searchPathSet],
+ );
+
+ const searchNodes = useMemo(() => {
+ if (!searchActive) return drawn.nodes;
+
+ return drawn.nodes.map((node) => ({
+ ...node,
+ searchMatchCount:
+ searchCounts.get(node.id) ??
+ node.searchMatchCount ??
+ (searchPathSet.has(node.notePath || node.path || "") ? 1 : 0),
+ }));
+ }, [drawn.nodes, searchActive, searchCounts, searchPathSet]);
const graphScopeLabel =
graphScope.mode === "global"
- ? "By folder; pick one to see its notes and code"
+ ? "By folder; click a folder to expand its contents"
: graphScope.mode === "module"
? `Folder ${graphScope.label}`
: `File ${graphScope.label || "graph"}`;
- // Notes take their type's color, as in the Atlas, so the legend can name every color.
- const accentKey = useTypeAccentKey();
-
- const typeColors = useMemo(
- () =>
- buildTypeColors([
- ...new Set(graph.nodes.map((node) => publicTypeName(node.resolvedType)).filter(Boolean)),
- ]),
- // The summary decides each type's palette slot.
- [graph.nodes, accentKey],
- );
-
- // A search shows its matches among the vault's own nodes, not folders.
- const byFolder = atRoot && !searchActive;
-
- const folders = useMemo(
- () => (byFolder ? aggregateByFolder(graph, (type) => typeColors.get(type)) : null),
- [byFolder, graph, typeColors],
- );
-
- const drawn = folders ?? graph;
-
return (
@@ -434,6 +336,8 @@ export function ExplorerWorkspace({
onSelectFile(entry.path, entry.kind)}
@@ -443,111 +347,30 @@ export function ExplorerWorkspace({
-
-
-
Explorer
-
- {graph.nodes.length
- ? `${graph.nodes.filter((node) => node.kind === "note").length.toLocaleString("en-US")} notes · ${graph.nodes.filter((node) => node.kind === "code").length.toLocaleString("en-US")} files shown of ${graph.nodes.length.toLocaleString("en-US")} nodes`
- : ""}
-
-
-
-
-
-
{
- if (!event.currentTarget.contains(event.relatedTarget)) setShowSuggestions(false);
- }}
- >
- {searchActive && !searching && !searchQuery.isError ? (
-
- {searchPathSet.size} {searchPathSet.size === 1 ? "match" : "matches"}
-
- ) : null}
- {searchActive ? (
-
- setSearchOnlyMatches(e.target.checked)}
- />
- Only matches
-
- ) : null}
-
-
- {
- setQuery(e.target.value);
-
- if (e.target.value.trim() === "") {
- clearSearch();
- }
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- runSearch();
- setShowSuggestions(false);
- }
-
- if (e.key === "Escape") {
- setQuery("");
- setShowSuggestions(false);
- clearSearch();
- }
- }}
- onFocus={() => {
- setShowSuggestions(true);
- }}
- placeholder={searching ? "Searching…" : "Search notes and code"}
- />
-
- {showSuggestions && suggestions.length > 0 && (
-
- {suggestions.map((suggestion) => (
- {
- e.preventDefault();
- }}
- onClick={() => {
- onSelectFile(suggestion.path, suggestion.kind);
- setShowSuggestions(false);
- }}
- >
- {suggestion.path}
- {suggestion.kind}
-
- ))}
-
- )}
- {searchQuery.isError ? (
-
- Search unavailable.{" "}
- searchQuery.refetch()}>
- Retry
-
-
- ) : null}
-
-
-
+
{
+ void searchQuery.refetch();
+ }}
+ />
@@ -573,19 +396,15 @@ export function ExplorerWorkspace({
}
>
node.searchMatchCount).map((node) => node.id),
+ )
+ }
searchOnlyMatches={searchOnlyMatches}
typeColors={typeColors}
showTypeLegend
@@ -647,6 +470,7 @@ export function ExplorerWorkspace({
>
{
+ it("closes details through the accessible shared pane icon", () => {
+ const onClose = vi.fn();
+ render(
+ ,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Close file details" }));
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it("groups relation kinds and collapses duplicate destinations within each relation", () => {
+ const onSelectFile = vi.fn();
+ render(
+ ,
+ );
+ expect(screen.getByRole("heading", { name: "Mentioned in1 note" })).toBeVisible();
+ expect(screen.getByRole("heading", { name: "Documented by1 note" })).toBeVisible();
+ expect(
+ screen.getAllByRole("heading", { level: 3 }).map((heading) => heading.textContent),
+ ).toEqual(["Documented by1 note", "Mentioned in1 note", "Related in graph1 note"]);
+ expect(screen.getByTitle("2 mentions")).toHaveAttribute("aria-label", "2 mentions");
+ const link = screen.getByRole("button", { name: /Guide/ });
+ expect(link).toHaveTextContent("docs/guide.md×2");
+ fireEvent.click(link);
+ expect(onSelectFile).toHaveBeenCalledWith("docs/guide.md", "note");
+ });
+
+ it("keeps graph items in the same note distinct and opens their full targets", () => {
+ const onSelectFile = vi.fn();
+ render(
+ ,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /First item/ }));
+ expect(onSelectFile).toHaveBeenLastCalledWith("docs/guide.md#^one", "note");
+ fireEvent.click(screen.getByRole("button", { name: /Second item/ }));
+ expect(onSelectFile).toHaveBeenLastCalledWith("docs/guide.md#^two", "note");
+ });
+
it("renders code HTML as text instead of injecting markup", () => {
const file: FileView = {
path: "src/example.ts",
diff --git a/web/src/components/FilePanel.tsx b/web/src/components/FilePanel.tsx
index e83a622ff..13ae65b44 100644
--- a/web/src/components/FilePanel.tsx
+++ b/web/src/components/FilePanel.tsx
@@ -1,7 +1,10 @@
import { useEffect, useMemo, useRef } from "react";
-import { FileText } from "lucide-react";
-import type { FileView } from "../api/types";
+import { FileText, X } from "lucide-react";
+import { graphNodeNavigationTarget } from "./graphViewShared";
+import { FILE_NOTE_RELATIONS } from "./fileFocusGraph";
+import type { FileView, GraphResponse } from "../api/types";
import { convertWikilinks, resolveLinkTarget, stripFrontmatter } from "../lib/content";
+import "./file-panel-preview.css";
import { Markdown } from "./markdown/Markdown";
const HIGHLIGHT_LANGS = new Map([
@@ -43,11 +46,13 @@ function getParentPath(path: string) {
export function FilePanel({
file,
+ graph,
line,
onClose,
onSelectFile,
}: {
file: FileView | null;
+ graph?: GraphResponse;
line?: number;
onClose: () => void;
onSelectFile: (path: string, kind?: string) => void;
@@ -60,31 +65,50 @@ export function FilePanel({
return convertWikilinks(stripFrontmatter(file.content || ""));
}, [file]);
- const topLinks = useMemo(() => {
+ const linkGroups = useMemo(() => {
if (!file) return [];
+ const groups = new Map>();
+
+ const add = (relation: string, path: string, label: string) => {
+ const rows = groups.get(relation) ?? new Map();
+ const previous = rows.get(path);
+ rows.set(path, { path, label: previous?.label ?? label, count: (previous?.count ?? 0) + 1 });
+ groups.set(relation, rows);
+ };
if (file.kind === "code") {
- return (file.relatedNotes || []).map((note) => ({
- label: note.title || note.path,
- path: note.path,
- }));
- }
+ for (const note of file.relatedNotes ?? [])
+ add(
+ note.reason === "coderef"
+ ? "Documented by"
+ : note.reason === "codeanchor"
+ ? "Mentioned in"
+ : "Related in graph",
+ note.path,
+ note.title || getFileName(note.path),
+ );
+ const known = new Set((file.relatedNotes ?? []).map((note) => note.path));
- if (file.kind === "note") {
- const links = file.links || [];
- const out: { label: string; path: string }[] = [];
- links.forEach((link) => {
- const target = resolveLinkTarget(link.target, file);
+ for (const node of graph?.nodes ?? []) {
+ const path = graphNodeNavigationTarget(node);
- if (!target) return;
- out.push({ label: link.text || target, path: target });
- });
+ if ((node.kind === "note" || node.kind === "embedded") && path && !known.has(path)) {
+ add("Related in graph", path, node.label || getFileName(path));
+ known.add(path);
+ }
+ }
+ } else {
+ for (const link of file.links ?? []) {
+ const target = resolveLinkTarget(link.target, file);
- return out;
+ if (target) add("Links to", target, link.text || getFileName(target));
+ }
}
- return [];
- }, [file]);
+ return [...groups]
+ .sort(([a], [b]) => FILE_NOTE_RELATIONS.indexOf(a) - FILE_NOTE_RELATIONS.indexOf(b))
+ .map(([relation, rows]) => ({ relation, rows: [...rows.values()] }));
+ }, [file, graph]);
const codeMarkdown = useMemo(() => {
if (file?.kind !== "code") return "";
@@ -118,22 +142,37 @@ export function FilePanel({
-
- Close
+
+
- {file && topLinks.length > 0 && (
-
+ {linkGroups.map(({ relation, rows }) => (
+
- Links
- {topLinks.length}
+ {relation}
+
+ {rows.length}{" "}
+ {file.kind === "code"
+ ? rows.length === 1
+ ? "note"
+ : "notes"
+ : rows.length === 1
+ ? "destination"
+ : "destinations"}
+
- {topLinks.map((note) => (
-
+ {rows.map((note) => (
+
- {note.label}
+
+ {note.label}
+
+ {note.path.length > 54
+ ? `${note.path.slice(0, 24)}…${note.path.slice(-29)}`
+ : note.path}
+
+
+ {note.count > 1 && (
+
+ ×{note.count}
+
+ )}
))}
- )}
+ ))}
{file?.kind === "note" && (
diff --git a/web/src/components/FinderPalette.tsx b/web/src/components/FinderPalette.tsx
index 9e946b5d5..9a7a0fca4 100644
--- a/web/src/components/FinderPalette.tsx
+++ b/web/src/components/FinderPalette.tsx
@@ -210,7 +210,6 @@ export function FinderPalette({
}}
onKeyDown={onKeyDown}
/>
- esc
{!query.trim() && recentHeading && items.length > 0 && (
diff --git a/web/src/components/GraphQLExplorer.tsx b/web/src/components/GraphQLExplorer.tsx
index 80a134b30..0a1814c13 100644
--- a/web/src/components/GraphQLExplorer.tsx
+++ b/web/src/components/GraphQLExplorer.tsx
@@ -244,7 +244,14 @@ function withIcon(button: ReactNode, Icon: LucideIcon, label?: string) {
if (!isValidElement<{ label?: string }>(button)) return button;
// The accessible name and tooltip start with the visible label (WCAG 2.5.3).
- const named = label ? { label: (button.props.label ?? "").replace(/^\S+/, label) } : undefined;
+ const named = label
+ ? {
+ label: (button.props.label ?? "").replace(
+ label === "Merge fragments" ? /^Merge fragments/ : /^\S+/,
+ label,
+ ),
+ }
+ : undefined;
return cloneElement(
button,
@@ -348,7 +355,7 @@ function GraphQLExplorer({
{({ prettify, merge, copy }) => (
<>
{withIcon(prettify, WandSparkles, "Format")}
- {withIcon(merge, Merge, "Merge")}
+ {withIcon(merge, Merge, "Merge fragments")}
{withIcon(copy, Copy)}
>
)}
diff --git a/web/src/components/GraphView.test.tsx b/web/src/components/GraphView.test.tsx
index 2c86c3ec6..7527d9bed 100644
--- a/web/src/components/GraphView.test.tsx
+++ b/web/src/components/GraphView.test.tsx
@@ -19,6 +19,61 @@ const baseProps = {
};
describe("GraphView", () => {
+ it("keys only drawn kinds and keeps the size toggle in Display", () => {
+ const onDisplayChange = vi.fn();
+
+ const view = render(
+ ,
+ );
+
+ const legend = screen.getByLabelText("Graph type legend");
+ expect(within(legend).queryByText("Types")).toBeNull();
+ expect(within(legend).queryByText(/Folder \(colour/)).toBeNull();
+ expect(within(legend).queryByText("+N more")).toBeNull();
+ expect(within(legend).queryByRole("checkbox")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Display" }));
+ expect(
+ screen.getByRole("checkbox", { name: "Size counts the notes and code files a folder holds" }),
+ ).toBeVisible();
+
+ const size = screen.getByRole("checkbox", {
+ name: "Size counts the notes and code files a folder holds",
+ });
+
+ expect(size).toBeChecked();
+ fireEvent.click(size);
+ expect(onDisplayChange).toHaveBeenCalledWith({ scaleByAuthority: false });
+ expect(size).toBeChecked();
+ view.unmount();
+ });
+
+ it("keys the folder edge kinds automatically", () => {
+ render(
+ ,
+ );
+ const legend = screen.getByLabelText("Graph link legend");
+ expect(within(legend).getByText("Contains")).toBeVisible();
+ expect(within(legend).getByText("Note–code links")).toBeVisible();
+ expect(within(legend).getByText("Other links on hover")).toBeVisible();
+ });
+
it("shows the index-needed notice without booting the graph", () => {
const restoreWebGL = installFakeWebGL();
const sigmaOn = vi.spyOn(Sigma.prototype, "on");
diff --git a/web/src/components/GraphView.tsx b/web/src/components/GraphView.tsx
index e90c9a0c5..c02810942 100644
--- a/web/src/components/GraphView.tsx
+++ b/web/src/components/GraphView.tsx
@@ -4,62 +4,23 @@ import { useMemo, useState } from "react";
import { humanizeName } from "../lib/labels";
import { publicTypeName } from "../lib/typeNames";
import type { GraphEdge, GraphNode } from "../api/types";
-import {
- CODE_COLOR,
- FOLDER_COLOR,
- type GraphScope,
- type GraphViewNode,
- kindLabel,
- truncatePath,
- UNTYPED_COLOR,
-} from "./graphViewShared";
+import { type GraphScope, type GraphViewNode, kindLabel } from "./graphViewShared";
import { type GraphDisplay, type GraphNodeClickOptions, useSigmaGraph } from "./useSigmaGraph";
-const UNTYPED_NODE_TYPE = "__untyped__";
-
-/** Legend keys for nodes that are not notes; their colors match `nodeColor` under a type-color map. */
-const CODE_NODE_TYPE = "__code__";
-
-const FOLDER_NODE_TYPE = "__module__";
-
-const KIND_ENTRIES = new Map([
- [UNTYPED_NODE_TYPE, { label: "Untyped notes", color: UNTYPED_COLOR }],
- [CODE_NODE_TYPE, { label: "Code files", color: CODE_COLOR }],
- [FOLDER_NODE_TYPE, { label: "Folders", color: FOLDER_COLOR }],
-]);
-
-/** Legend groups, in order: what the colors of notes mean, then code, then folders. */
-const LEGEND_GROUPS = [
- { key: "typed", title: "Notes by type" },
- { key: "code", title: "Code" },
- { key: "folder", title: "Folders" },
-] as const;
-
-function legendGroup(name: string) {
- if (name === CODE_NODE_TYPE) return "code";
-
- if (name === FOLDER_NODE_TYPE) return "folder";
-
- return "typed";
-}
-
-const EMPTY_PROBLEM_COUNTS: ReadonlyMap = new Map();
-
-type GraphTypeEntry = {
- name: string;
- label: string;
- count: number;
- color: string;
- selected: boolean;
-};
-
-function graphTypeName(node: GraphNode): string {
- if (node.kind === "code") return CODE_NODE_TYPE;
-
- if (node.kind === "module") return FOLDER_NODE_TYPE;
-
- return publicTypeName(node.resolvedType) || UNTYPED_NODE_TYPE;
-}
+import {
+ FolderLegend,
+ EdgeLegend,
+ LEGEND_GROUPS,
+ KIND_ENTRIES,
+ UNTYPED_NODE_TYPE,
+ CODE_NODE_TYPE,
+ FOLDER_NODE_TYPE,
+ EMPTY_PROBLEM_COUNTS,
+ graphTypeName,
+ legendGroup,
+ legendItem,
+ type GraphTypeEntry,
+} from "./graphLegend";
export function GraphView({
nodes,
@@ -87,6 +48,7 @@ export function GraphView({
folderCaption,
sizeCaption,
edgeCaption,
+ layoutExtent,
}: {
/** Nodes to draw; a summarized view may give each its own `fill`. */
nodes: GraphViewNode[];
@@ -122,6 +84,7 @@ export function GraphView({
sizeCaption?: string;
/** What a drawn line means, keyed beside the folders it joins. */
edgeCaption?: string;
+ layoutExtent?: number;
}) {
const [localShowProblems, setLocalShowProblems] = useState(false);
const showProblems = display?.showProblems ?? localShowProblems;
@@ -151,6 +114,8 @@ export function GraphView({
} = useSigmaGraph({
nodes,
edges,
+ layoutExtent,
+ explorer: scope.mode === "local" || nodes.some((node) => Boolean(node.fill)),
needsIndex,
onNodeClick,
scope,
@@ -194,7 +159,13 @@ export function GraphView({
Array.from(counts.entries())
.map(([name, count]) => {
const kind = KIND_ENTRIES.get(name);
- const color = kind?.color ?? (typeColors?.get(name) || "var(--text-faint)");
+
+ const color =
+ name === CODE_NODE_TYPE &&
+ scope.mode !== "local" &&
+ !nodes.some((node) => node.fill || node.x !== undefined)
+ ? "var(--graph-code)"
+ : (kind?.color ?? (typeColors?.get(name) || "var(--text-faint)"));
return {
name,
@@ -212,7 +183,7 @@ export function GraphView({
return rank(left) - rank(right) || left.label.localeCompare(right.label);
})
);
- }, [highlightTypes, legendNodes, nodes, typeColors, typeLabels]);
+ }, [highlightTypes, legendNodes, nodes, typeColors, typeLabels, scope.mode]);
const highlightedNodeCount = useMemo(() => {
if (!highlightTypes?.size) return nodes.length;
@@ -252,7 +223,7 @@ export function GraphView({
checked={scaleByAuthority}
onChange={(e) => setScaleByAuthority(e.target.checked)}
/>
- Size by authority
+ {sizeCaption || "Size by authority"}
)}
- {hover.path && {truncatePath(hover.path)}
}
+ {hover.path && {hover.path}
}
)}
{showTypeLegend &&
(legendNodes ? (
(node.fillKey ? [node.fillKey] : [])))}
+ shown={new Set(nodes.map((node) => node.fillKey || graphTypeName(node)))}
caption={folderCaption}
- sizeCaption={sizeCaption}
edgeCaption={edgeCaption}
+ edges={edges}
/>
) : (
{nodeCaption}
+
{LEGEND_GROUPS.map((group) => {
const entries = typeEntries.filter((entry) => legendGroup(entry.name) === group.key);
@@ -477,7 +450,9 @@ export function GraphView({
data-group={group.key}
>
{group.title}
- {entries.map(legendItem)}
+
+ {entries.map((entry) => legendItem(entry))}
+
);
})}
@@ -488,96 +463,6 @@ export function GraphView({
);
}
-function legendItem(entry: GraphTypeEntry) {
- return (
-
-
- {entry.label}
- {entry.count.toLocaleString("en-US")}
-
- );
-}
-
-/**
- * The folder view's key: the hues its folders actually take first, then what
- * size and lines mean; every type in the graph waits behind "All types".
- */
-function FolderLegend({
- entries,
- shown,
- caption,
- sizeCaption,
- edgeCaption,
-}: {
- entries: readonly GraphTypeEntry[];
- /** The fill keys the drawn folders use. */
- shown: ReadonlySet;
- caption?: string;
- sizeCaption?: string;
- edgeCaption?: string;
-}) {
- const [all, setAll] = useState(false);
- const inventory = entries.filter((entry) => entry.name !== FOLDER_NODE_TYPE);
-
- return (
-
- );
-}
-
function countLabel(count: number, noun: string) {
return `${count} ${count === 1 ? noun : `${noun}s`}`;
}
diff --git a/web/src/components/HTMLNoteViewer.tsx b/web/src/components/HTMLNoteViewer.tsx
index 59f0a6c8f..45c588662 100644
--- a/web/src/components/HTMLNoteViewer.tsx
+++ b/web/src/components/HTMLNoteViewer.tsx
@@ -642,7 +642,7 @@ export function HTMLNoteViewer({
setRefreshGeneration((value) => value + 1)}
@@ -658,6 +658,7 @@ export function HTMLNoteViewer({
>
+ Refresh
{bare ? (
diff --git a/web/src/components/HTMLRootMetadataPanel.test.tsx b/web/src/components/HTMLRootMetadataPanel.test.tsx
index 20da937f3..1ee777359 100644
--- a/web/src/components/HTMLRootMetadataPanel.test.tsx
+++ b/web/src/components/HTMLRootMetadataPanel.test.tsx
@@ -30,6 +30,8 @@ describe("HTMLRootMetadataPanel", () => {
fireEvent.click(screen.getByText("Metadata"));
expect(disclosure).toHaveAttribute("open");
+ expect(screen.getByText("type").querySelector("svg")).toHaveAttribute("aria-hidden", "true");
+
const type = screen.getByRole("textbox", { name: "type" });
fireEvent.change(type, { target: { value: "Report" } });
fireEvent.blur(type);
@@ -102,6 +104,7 @@ describe("HTMLRootMetadataPanel", () => {
fireEvent.click(screen.getByText("Metadata"));
expect(screen.queryByText("title")).not.toBeInTheDocument();
expect(screen.queryByText("tags")).not.toBeInTheDocument();
+ expect(screen.getByText("type").querySelector("svg")).toBeNull();
expect(screen.getByText("Report")).toBeVisible();
expect(screen.getByText("T")).toBeVisible();
});
diff --git a/web/src/components/HTMLRootMetadataPanel.tsx b/web/src/components/HTMLRootMetadataPanel.tsx
index 185955fb5..dc78986c8 100644
--- a/web/src/components/HTMLRootMetadataPanel.tsx
+++ b/web/src/components/HTMLRootMetadataPanel.tsx
@@ -1,3 +1,4 @@
+import { EditablePropertyMark } from "./body/EditablePropertyMark";
import { ChevronRight } from "lucide-react";
import type { ReactNode } from "react";
import type {
@@ -242,7 +243,10 @@ export function HTMLRootMetadataPanel({
data-field={field.key}
className={`ontology-properties__row${dirty ? " is-dirty" : ""}${field.present ? "" : " is-missing"}`}
>
- {field.key}
+
+ {field.key}
+ {editing && }
+
{children};
+ }
+
+ return {
+ onOpen,
+ ...render( , {
+ wrapper: Wrapper,
+ }),
+ };
+}
+
+async function advance(ms: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms);
+ });
+}
+
+import {
+ workspaceWithEmbeddedRelation,
+ workspaceWithSectionsAndNearby,
+} from "./body/noteInfoFixtures.test-support";
+
+function groupSection(title: string): HTMLElement {
+ const section = screen
+ .getByRole("heading", {
+ name: (name) => name.replace(/\d+\s*(materials?)?$/, "").trim() === title,
+ })
+ .closest("section, details");
+
+ if (!section) throw new Error(`no sidebar section rendered for ${title}`);
+
+ return section;
+}
+
+describe("NotesSidebarInfo note previews", () => {
+ const http = withFakeFetch();
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ setHover(true);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it("opens a related-note preview to the left and preserves click modes", async () => {
+ http.json("GET", "/api/v1/nodes/preview", preview);
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
+ function (this: HTMLElement) {
+ if (this.classList.contains("note-preview")) return new DOMRect(0, 0, 240, 180);
+
+ if (this.classList.contains("ontology-sidebar-info")) {
+ return new DOMRect(880, 0, 320, 700);
+ }
+
+ if (this instanceof HTMLButtonElement) return new DOMRect(900, 120, 100, 24);
+
+ return new DOMRect();
+ },
+ );
+
+ const view = renderSidebar(workspaceWithEmbeddedRelation());
+
+ const button = within(groupSection("Relations")).getByRole("button", {
+ name: "Decide rain-date contingency by end of May",
+ });
+
+ fireEvent.mouseEnter(button, { clientY: 125 });
+ await advance(100);
+ await advance(200);
+
+ const card = screen.getByRole("region", { name: "Preview of Pizza party" });
+ expect(card).toHaveStyle({ left: "634px", top: "120px" });
+ expect(button).toHaveAttribute("aria-describedby", card.id);
+ const request = http.requests("GET", "/api/v1/nodes/preview")[0];
+ expect(request?.query.get("ref")).toBe("docs/playground/pizza-party-2026.md#item-1030");
+ expect(request?.query.get("from")).toBe("docs/people/drew.md");
+
+ fireEvent.keyDown(window, { key: "Escape" });
+ expect(
+ screen.queryByRole("region", { name: "Preview of Pizza party" }),
+ ).not.toBeInTheDocument();
+
+ fireEvent.click(button);
+ expect(view.onOpen).toHaveBeenLastCalledWith(
+ "docs/playground/pizza-party-2026.md#item-1030",
+ "stack",
+ );
+ fireEvent.click(button, { metaKey: true });
+ expect(view.onOpen).toHaveBeenLastCalledWith(
+ "docs/playground/pizza-party-2026.md#item-1030",
+ "beside",
+ );
+ });
+
+ it("does not duplicate an anchor already present in a relation path", async () => {
+ http.json("GET", "/api/v1/nodes/preview", preview);
+ const workspace = workspaceWithEmbeddedRelation();
+ workspace.relations![0].items![0].path = "docs/playground/pizza-party-2026.md#item-1030";
+ const view = renderSidebar(workspace);
+
+ const button = within(groupSection("Relations")).getByRole("button", {
+ name: "Decide rain-date contingency by end of May",
+ });
+
+ fireEvent.mouseEnter(button);
+ await advance(300);
+
+ expect(http.requests("GET", "/api/v1/nodes/preview")[0]?.query.get("ref")).toBe(
+ "docs/playground/pizza-party-2026.md#item-1030",
+ );
+ fireEvent.click(button);
+ expect(view.onOpen).toHaveBeenCalledWith(
+ "docs/playground/pizza-party-2026.md#item-1030",
+ "stack",
+ );
+ });
+
+ it("previews and opens section and nearby refs by their stable targets", async () => {
+ http.json("GET", "/api/v1/nodes/preview", preview);
+ const view = renderSidebar(workspaceWithSectionsAndNearby());
+
+ const section = within(groupSection("Relations")).getByRole("button", {
+ name: "Old section heading",
+ });
+
+ fireEvent.mouseEnter(section);
+ await advance(300);
+
+ expect(http.requests("GET", "/api/v1/nodes/preview")[0]?.query.get("ref")).toBe(
+ "docs/sections.md#struct:section-stable",
+ );
+ fireEvent.keyDown(window, { key: "Escape" });
+ fireEvent.click(section, { ctrlKey: true });
+ expect(view.onOpen).toHaveBeenLastCalledWith(
+ "docs/sections.md#struct:section-stable",
+ "beside",
+ );
+
+ const nearby = within(groupSection("Nearby nodes")).getByRole("button", {
+ name: "Nearby section",
+ });
+
+ fireEvent.mouseEnter(nearby);
+ await advance(300);
+
+ expect(http.requests("GET", "/api/v1/nodes/preview")[1]?.query.get("ref")).toBe(
+ "docs/people/drew.md#struct:nearby-stable",
+ );
+ fireEvent.click(nearby);
+ expect(view.onOpen).toHaveBeenLastCalledWith(
+ "docs/people/drew.md#struct:nearby-stable",
+ "stack",
+ );
+ });
+
+ it("shrinks a left preview to remain outside a narrow rail", async () => {
+ http.json("GET", "/api/v1/nodes/preview", preview);
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
+ function (this: HTMLElement) {
+ if (this.classList.contains("note-preview")) return new DOMRect(0, 0, 440, 180);
+
+ if (this.classList.contains("ontology-sidebar-info")) {
+ return new DOMRect(400, 0, 300, 700);
+ }
+
+ if (this instanceof HTMLButtonElement) return new DOMRect(420, 120, 100, 24);
+
+ return new DOMRect();
+ },
+ );
+
+ renderSidebar(workspaceWithEmbeddedRelation());
+
+ const button = within(groupSection("Relations")).getByRole("button", {
+ name: "Decide rain-date contingency by end of May",
+ });
+
+ fireEvent.mouseEnter(button);
+ await advance(100);
+ await advance(200);
+
+ const card = screen.getByRole("region", { name: "Preview of Pizza party" });
+ expect(card).toHaveStyle({ left: "8px", maxWidth: "386px" });
+ expect(
+ Number.parseFloat(card.style.left) + Number.parseFloat(card.style.maxWidth),
+ ).toBeLessThan(400);
+ });
+
+ it("opens from focus, supports Tab transfer, and closes on blur", async () => {
+ http.json("GET", "/api/v1/nodes/preview", preview);
+ const view = renderSidebar(workspaceWithEmbeddedRelation());
+
+ const button = within(groupSection("Relations")).getByRole("button", {
+ name: "Decide rain-date contingency by end of May",
+ });
+
+ act(() => button.focus());
+ await advance(100);
+ await advance(200);
+
+ const card = screen.getByRole("region", { name: "Preview of Pizza party" });
+ fireEvent.keyDown(button, { key: "Tab" });
+ expect(card).toHaveFocus();
+ fireEvent.keyDown(card, { key: "Tab", shiftKey: true });
+ expect(button).toHaveFocus();
+
+ fireEvent.blur(button);
+ await advance(150);
+ expect(
+ screen.queryByRole("region", { name: "Preview of Pizza party" }),
+ ).not.toBeInTheDocument();
+ expect(view.onOpen).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/NotesLeftRail.tsx b/web/src/components/NotesLeftRail.tsx
index ff78099d9..b15f31089 100644
--- a/web/src/components/NotesLeftRail.tsx
+++ b/web/src/components/NotesLeftRail.tsx
@@ -154,11 +154,9 @@ export const NotesLeftRail = memo(function NotesLeftRail({
() => onSelectCollection(PSEUDO_TYPE_ISSUES),
issueCount == null ? (
- ) : (
- 0 ? " is-risk" : ""}`}>
- {issueCount}
-
- ),
+ ) : issueCount > 0 ? (
+ {issueCount}
+ ) : null,
" ontology-type-row--issues",
)}
{editSession?.hasUncommittedChanges &&
diff --git a/web/src/components/NotesRightRail.tsx b/web/src/components/NotesRightRail.tsx
index 705991c83..01b88140a 100644
--- a/web/src/components/NotesRightRail.tsx
+++ b/web/src/components/NotesRightRail.tsx
@@ -1,18 +1,14 @@
+import { GraphPanel } from "./body/NoteRailGraph";
import {
type KeyboardEvent,
type ReactNode,
- lazy,
- Suspense,
useCallback,
useEffect,
- useMemo,
useRef,
useState,
} from "react";
import type {
- NodeWorkspace,
- NodeWorkspaceGraph,
OntologyEditSessionResponse,
RenderedSection,
StructuralNode,
@@ -24,11 +20,6 @@ import { NotesSidebarInfo } from "./NotesSidebarInfo";
import { useFocusedWorkspaceGraphQuery } from "./useNotesQueries";
import { DisclosureChevron } from "./DisclosureChevron";
-// Sigma, graphology, and ForceAtlas2 load with the Graph tab, not the Notes entry.
-const OntologyLocalGraph = lazy(() =>
- import("./OntologyLocalGraph").then((module) => ({ default: module.OntologyLocalGraph })),
-);
-
type RailTab = "info" | "outline" | "graph";
type OpenTarget = "current" | "stack" | "beside";
@@ -67,30 +58,6 @@ function writeSessionValue(key: string, value: string): void {
}
}
-function graphHasContent(graph: NodeWorkspaceGraph | null | undefined): boolean {
- return Boolean(
- graph?.views?.localGraph &&
- ((graph.views.localGraph.nodeIds?.length || 0) > 0 ||
- (graph.nodes?.length || 0) > 0 ||
- (graph.edges?.length || 0) > 0),
- );
-}
-
-function graphWorkspace(
- workspace: NodeWorkspace,
- graph: NodeWorkspaceGraph | null | undefined,
-): NodeWorkspace | null {
- if (!graphHasContent(graph)) return null;
-
- return {
- ...workspace,
- focusedNodeId: graph?.focusedNodeId,
- nodes: graph?.nodes || [],
- edges: graph?.edges || [],
- views: graph?.views,
- };
-}
-
function containsSection(section: RenderedSection, id: string | null): boolean {
return (
id !== null &&
@@ -282,61 +249,6 @@ function OutlinePanel({ context }: { context: NoteTabContext }) {
);
}
-function GraphPanel({
- workspace,
- graph,
- graphLoading,
- graphError,
- onRetry,
- onOpen,
- onOpenNode,
-}: {
- workspace: NodeWorkspace;
- graph: NodeWorkspaceGraph | null | undefined;
- graphLoading: boolean;
- graphError: boolean;
- onRetry: () => void;
- onOpen: (path: string, target?: OpenTarget) => void;
- onOpenNode: (node: StructuralNode) => void;
- validationIssueCount?: number;
- validationHealth?: ValidationHealth;
-}) {
- const localWorkspace = useMemo(() => graphWorkspace(workspace, graph), [graph, workspace]);
-
- if (localWorkspace) {
- return (
-
-
- Loading local graph…
-
- }
- >
-
-
-
- );
- }
-
- return (
-
- {graphLoading ? (
- "Loading local graph…"
- ) : graphError ? (
- <>
- Unable to load local graph.
-
- Retry
-
- >
- ) : (
- "No local graph yet."
- )}
-
- );
-}
-
export type NotesRightRailProps = {
active?: boolean;
context: NoteTabContext | null;
@@ -494,6 +406,7 @@ export function NotesRightRail({
>
{activeTab === "info" ? (
{
committed = true;
save.resolve(session("clean"));
- await waitFor(() => expect(screen.getByText("Draft")).toBeVisible());
+ await waitFor(() => expect(screen.getByText("Unsaved changes")).toBeVisible());
expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Discard" })).toBeEnabled();
});
diff --git a/web/src/components/NotesShell.tsx b/web/src/components/NotesShell.tsx
index ee98c17f2..5b99bb4ee 100644
--- a/web/src/components/NotesShell.tsx
+++ b/web/src/components/NotesShell.tsx
@@ -1,3 +1,4 @@
+import { confirmDiscard } from "./editing/confirmDiscard";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -515,18 +516,7 @@ export function NotesShell({ active = true }: { active?: boolean }) {
}, [editSession, queryClient, refreshSidebar]);
const discard = useCallback(async () => {
- const { opCount, touchedPaths } = editSession.summary;
-
- // Discard drops every staged edit in every note, with no undo.
- if (
- opCount > 0 &&
- !window.confirm(
- `Discard ${opCount} staged change${opCount === 1 ? "" : "s"} to ${touchedPaths.size || 1} note${
- touchedPaths.size === 1 ? "" : "s"
- }? This cannot be undone.`,
- )
- )
- return;
+ if (!confirmDiscard(editSession.summary, editSession.vaultKey)) return;
clearPersistedEditorDrafts(editSession.vaultKey);
window.dispatchEvent(new Event("rhizome:discard-editor-drafts"));
diff --git a/web/src/components/NotesShell.views.fixtures.ts b/web/src/components/NotesShell.views.fixtures.ts
new file mode 100644
index 000000000..5a9d5e2e0
--- /dev/null
+++ b/web/src/components/NotesShell.views.fixtures.ts
@@ -0,0 +1,156 @@
+import type {
+ OntologyEditSessionResponse,
+ OntologyNoteListItem,
+ OntologySummaryResponse,
+ OntologyTypeResponse,
+ ViewCatalogEntry,
+ ViewExecuteResponse,
+ ViewFieldCapability,
+ ViewTableRow,
+} from "../api/types";
+
+export const emptyGraph = { nodes: [], edges: [], truncated: false };
+
+export const productType = {
+ name: "ProductSpec",
+ label: "ProductSpec",
+ count: 1,
+ issueCount: 0,
+};
+
+export const interfaceSummary = {
+ name: "SpecLike",
+ label: "SpecLike",
+ count: 1,
+ issueCount: 0,
+ implementors: ["ProductSpec"],
+};
+
+export function summary(overrides: Partial = {}): OntologySummaryResponse {
+ return {
+ schemaPresent: true,
+ totalNotes: 1,
+ typedNotes: 1,
+ untypedNotes: 0,
+ ambiguousNotes: 0,
+ issueNotes: 0,
+ types: [],
+ interfaces: [],
+ ...overrides,
+ };
+}
+
+export function typeResponse(name = "ProductSpec"): OntologyTypeResponse {
+ const row = noteRow(name === "ProductSpec" ? "specs/alpha.md" : "notes/all.md");
+
+ return {
+ count: 1,
+ issueCount: 0,
+ type: { name, label: name, fields: [] },
+ notes: [row],
+ };
+}
+
+export function noteRow(path: string, title = "Alpha Spec"): ViewTableRow & OntologyNoteListItem {
+ return {
+ ref: { notePath: path, kind: "NOTE" },
+ path,
+ title,
+ resolvedType: "ProductSpec",
+ updatedAt: 1_713_000_000,
+ hasIssues: false,
+ fields: {},
+ };
+}
+
+export function viewEntry(
+ id: string,
+ name: string,
+ mount: ViewCatalogEntry["mount"],
+ field = "title",
+): ViewCatalogEntry {
+ const source: ViewCatalogEntry["source"] = {
+ kind: mount.kind === "standalone" ? "query_recipe" : "ontology_type",
+ };
+
+ if (mount.type) source.type = mount.type;
+
+ if (mount.interface) source.interface = mount.interface;
+
+ const variants = {
+ table: { columns: [{ field, label: field === "status" ? "Status" : "Title" }] },
+ };
+
+ return {
+ id,
+ name,
+ source,
+ mount,
+ defaults: { variant: "table" },
+ variants,
+ definition: {
+ apiVersion: "rhizome.view.v1",
+ id,
+ name,
+ source,
+ mount,
+ variants,
+ },
+ };
+}
+
+export function capability(field: string, edit?: ViewFieldCapability["edit"]): ViewFieldCapability {
+ const result: ViewFieldCapability = {
+ key: field,
+ label: field === "status" ? "Status" : "Title",
+ valueKind: field === "status" ? "enum" : "string",
+ sortable: true,
+ groupable: false,
+ filterOps: ["eq", "contains"],
+ };
+
+ if (edit) result.edit = edit;
+
+ return result;
+}
+
+export function execution(
+ view: ViewCatalogEntry,
+ rows: ViewTableRow[],
+ capabilities: ViewFieldCapability[] = [],
+): ViewExecuteResponse {
+ return {
+ view,
+ variant: "table",
+ state: {},
+ capabilities,
+ columns: view.variants.table?.columns ?? [],
+ rows,
+ pageInfo: {
+ total: rows.length,
+ offset: 0,
+ first: 25,
+ returned: rows.length,
+ hasMore: false,
+ },
+ definitionFingerprint: "definition",
+ sourceFingerprint: "source",
+ executionFingerprint: `execution-${rows.map((row) => row.title).join(",")}`,
+ };
+}
+
+export function editSession(
+ status: "dirty" | "clean",
+ hasUncommittedChanges: boolean,
+): OntologyEditSessionResponse {
+ return {
+ sessionId: "edit-1",
+ status,
+ revision: 1,
+ ops: [],
+ hasUncommittedChanges,
+ touchedPaths: hasUncommittedChanges ? ["specs/alpha.md"] : [],
+ createdAt: "2026-09-06T00:00:00Z",
+ updatedAt: "2026-09-06T00:00:01Z",
+ };
+}
diff --git a/web/src/components/NotesShell.views.test.tsx b/web/src/components/NotesShell.views.test.tsx
index 3ea7e4b01..d0e3949e5 100644
--- a/web/src/components/NotesShell.views.test.tsx
+++ b/web/src/components/NotesShell.views.test.tsx
@@ -1,16 +1,7 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
-import type {
- OntologyEditSessionResponse,
- OntologyNoteListItem,
- OntologySummaryResponse,
- OntologyTypeResponse,
- ViewCatalogEntry,
- ViewExecuteResponse,
- ViewFieldCapability,
- ViewTableRow,
-} from "../api/types";
+import type { ViewCatalogEntry } from "../api/types";
import { jsonReply, withFakeFetch } from "../test/fakeFetch";
import { renderWithQueryClient as render } from "../test/renderWithQueryClient";
import { NotesShell } from "./NotesShell";
@@ -21,153 +12,20 @@ import {
type ViewMessage,
} from "../lib/customViewMessages";
-const http = withFakeFetch();
-
-const emptyGraph = { nodes: [], edges: [], truncated: false };
-
-const productType = {
- name: "ProductSpec",
- label: "ProductSpec",
- count: 1,
- issueCount: 0,
-};
-
-const interfaceSummary = {
- name: "SpecLike",
- label: "SpecLike",
- count: 1,
- issueCount: 0,
- implementors: ["ProductSpec"],
-};
-
-function summary(overrides: Partial = {}): OntologySummaryResponse {
- return {
- schemaPresent: true,
- totalNotes: 1,
- typedNotes: 1,
- untypedNotes: 0,
- ambiguousNotes: 0,
- issueNotes: 0,
- types: [],
- interfaces: [],
- ...overrides,
- };
-}
-
-function typeResponse(name = "ProductSpec"): OntologyTypeResponse {
- const row = noteRow(name === "ProductSpec" ? "specs/alpha.md" : "notes/all.md");
-
- return {
- count: 1,
- issueCount: 0,
- type: { name, label: name, fields: [] },
- notes: [row],
- };
-}
-
-function noteRow(path: string, title = "Alpha Spec"): ViewTableRow & OntologyNoteListItem {
- return {
- ref: { notePath: path, kind: "NOTE" },
- path,
- title,
- resolvedType: "ProductSpec",
- updatedAt: 1_713_000_000,
- hasIssues: false,
- fields: {},
- };
-}
-
-function viewEntry(
- id: string,
- name: string,
- mount: ViewCatalogEntry["mount"],
- field = "title",
-): ViewCatalogEntry {
- const source: ViewCatalogEntry["source"] = {
- kind: mount.kind === "standalone" ? "query_recipe" : "ontology_type",
- };
-
- if (mount.type) source.type = mount.type;
-
- if (mount.interface) source.interface = mount.interface;
-
- const variants = {
- table: { columns: [{ field, label: field === "status" ? "Status" : "Title" }] },
- };
-
- return {
- id,
- name,
- source,
- mount,
- defaults: { variant: "table" },
- variants,
- definition: {
- apiVersion: "rhizome.view.v1",
- id,
- name,
- source,
- mount,
- variants,
- },
- };
-}
-
-function capability(field: string, edit?: ViewFieldCapability["edit"]): ViewFieldCapability {
- const result: ViewFieldCapability = {
- key: field,
- label: field === "status" ? "Status" : "Title",
- valueKind: field === "status" ? "enum" : "string",
- sortable: true,
- groupable: false,
- filterOps: ["eq", "contains"],
- };
-
- if (edit) result.edit = edit;
-
- return result;
-}
-
-function execution(
- view: ViewCatalogEntry,
- rows: ViewTableRow[],
- capabilities: ViewFieldCapability[] = [],
-): ViewExecuteResponse {
- return {
- view,
- variant: "table",
- state: {},
- capabilities,
- columns: view.variants.table?.columns ?? [],
- rows,
- pageInfo: {
- total: rows.length,
- offset: 0,
- first: 25,
- returned: rows.length,
- hasMore: false,
- },
- definitionFingerprint: "definition",
- sourceFingerprint: "source",
- executionFingerprint: `execution-${rows.map((row) => row.title).join(",")}`,
- };
-}
+import {
+ emptyGraph,
+ productType,
+ interfaceSummary,
+ summary,
+ typeResponse,
+ noteRow,
+ viewEntry,
+ capability,
+ execution,
+ editSession,
+} from "./NotesShell.views.fixtures";
-function editSession(
- status: "dirty" | "clean",
- hasUncommittedChanges: boolean,
-): OntologyEditSessionResponse {
- return {
- sessionId: "edit-1",
- status,
- revision: 1,
- ops: [],
- hasUncommittedChanges,
- touchedPaths: hasUncommittedChanges ? ["specs/alpha.md"] : [],
- createdAt: "2026-09-06T00:00:00Z",
- updatedAt: "2026-09-06T00:00:01Z",
- };
-}
+const http = withFakeFetch();
function registerReads(catalog: ViewCatalogEntry[], summaryResponse = summary()) {
http
@@ -177,6 +35,33 @@ function registerReads(catalog: ViewCatalogEntry[], summaryResponse = summary())
.json("GET", "/api/v1/ontology/types/ProductSpec", typeResponse())
.json("POST", "/api/v1/ontology/types/ProductSpec", typeResponse())
.json("GET", "/api/v1/graphs/global", emptyGraph)
+ // Editing focuses the row and loads its record context, including after save.
+ .onGraphQL("PublicNodeDetail", () =>
+ jsonReply({
+ data: {
+ node: {
+ ref: {
+ ref: "specs/alpha.md",
+ kind: "NOTE",
+ notePath: "specs/alpha.md",
+ path: "specs/alpha.md",
+ },
+ nodeId: "note:specs/alpha.md",
+ nodeKind: "NOTE",
+ path: "specs/alpha.md",
+ title: "Alpha Spec",
+ locator: {
+ sourceLocator: "specs/alpha.md",
+ status: "linkable",
+ exists: true,
+ requiresFix: false,
+ },
+ content: "# Alpha Spec",
+ localGraph: emptyGraph,
+ },
+ },
+ }),
+ )
.json("GET", "/api/v1/views", {
views: catalog,
targets: catalog.map((view) => ({
@@ -311,6 +196,7 @@ describe("NotesShell configured views", () => {
window.history.replaceState({}, "", "/notes?view=editable.notes");
render( );
fireEvent.click(await screen.findByRole("button", { name: "Edit Status" }));
+ await waitFor(() => expect(http.count("POST", "/api/v1/graphql")).toBeGreaterThan(0));
fireEvent.change(await screen.findByRole("combobox", { name: "Edit Status" }), {
target: { value: "published" },
});
@@ -368,6 +254,7 @@ describe("NotesShell configured views", () => {
render( );
fireEvent.click(await screen.findByRole("button", { name: "Edit Status" }));
const statusEditor = await screen.findByRole("combobox", { name: "Edit Status" });
+ await waitFor(() => expect(http.count("POST", "/api/v1/graphql")).toBeGreaterThan(0));
fireEvent.change(statusEditor, { target: { value: "published" } });
await waitFor(() => expect(screen.getByRole("button", { name: "Save" })).not.toBeDisabled());
diff --git a/web/src/components/NotesSidebarInfo.test.tsx b/web/src/components/NotesSidebarInfo.test.tsx
index 0f44b089e..c70ffdeb3 100644
--- a/web/src/components/NotesSidebarInfo.test.tsx
+++ b/web/src/components/NotesSidebarInfo.test.tsx
@@ -1,243 +1,10 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { act, fireEvent, render, screen, within } from "@testing-library/react";
-import type { PropsWithChildren } from "react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { NodePreview, NodeWorkspace } from "../api/types";
-import { withFakeFetch } from "../test/fakeFetch";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
import { NotesSidebarInfo } from "./NotesSidebarInfo";
-
-const preview: NodePreview = {
- ref: "docs/playground/pizza-party-2026.md#item-1030",
- path: "docs/playground/pizza-party-2026.md",
- title: "Pizza party",
- typeLabel: "Event",
- format: "markdown",
- fragmentResolved: true,
- fields: [],
- hasIssues: false,
-};
-
-function setHover(enabled: boolean) {
- Object.defineProperty(window, "matchMedia", {
- configurable: true,
- writable: true,
- value: vi.fn().mockReturnValue({ matches: enabled }),
- });
-}
-
-function renderSidebar(workspace: NodeWorkspace, onOpen = vi.fn()) {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
-
- function Wrapper({ children }: PropsWithChildren) {
- return {children} ;
- }
-
- return {
- onOpen,
- ...render( , {
- wrapper: Wrapper,
- }),
- };
-}
-
-async function advance(ms: number) {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(ms);
- });
-}
-
-/** A person note whose only relation is an inbound action item inside another note. */
-function workspaceWithEmbeddedRelation(): NodeWorkspace {
- const ref = { notePath: "docs/people/drew.md", kind: "NOTE" };
-
- return {
- requestedRef: "docs/people/drew.md",
- focusedNodeId: "note:docs/people/drew.md",
- node: {
- ref,
- notePath: "docs/people/drew.md",
- title: "Drew Colthorp",
- locator: "docs/people/drew.md",
- nodeLocator: {
- ref,
- kind: "NOTE",
- sourceLocator: "docs/people/drew.md",
- status: "linkable",
- },
- },
- content: {
- path: "docs/people/drew.md",
- title: "Drew Colthorp",
- markdown: "",
- sourceCapabilities: [],
- },
- relations: [
- {
- key: "structural",
- label: "Structural relations",
- items: [
- {
- path: "docs/playground/pizza-party-2026.md",
- anchor: "item-1030",
- title: "Decide rain-date contingency by end of May",
- kind: "embedded",
- relationName: "assignee",
- provenance: "field",
- structural: true,
- },
- ],
- },
- ],
- nodes: [],
- edges: [],
- loaded: { rendered: true, assessment: true, structure: true, relations: true },
- capabilities: {
- canEdit: false,
- canEditFields: false,
- canEditCollections: false,
- canNavigateChildren: true,
- canSubscribe: true,
- },
- status: {
- dirty: false,
- validation: { issueCount: 0 },
- freshness: {},
- session: {},
- hasWarnings: false,
- },
- version: "v1",
- };
-}
-
-function workspaceWithNavigation(): NodeWorkspace {
- const workspace = workspaceWithEmbeddedRelation();
- workspace.requestedRef = "docs/efforts/example/plan.html";
- workspace.node.notePath = "docs/efforts/example/plan.html";
- workspace.content.path = "docs/efforts/example/plan.html";
- workspace.relations = [
- {
- key: "workspace:docs/efforts/example/effort.html",
- label: "In this effort",
- ownerTitle: "Schema-driven navigation",
- navigation: true,
- items: [
- {
- path: "docs/efforts/example/effort.html",
- title: "Overview",
- targetTitle: "Schema-driven navigation",
- kind: "note",
- },
- {
- path: "docs/efforts/example/plan.html",
- title: "Implementation plan",
- targetTitle: "Plan details",
- kind: "note",
- current: true,
- },
- {
- path: "docs/efforts/example/work-log.md",
- title: "Work log",
- targetTitle: "Execution history",
- kind: "note",
- },
- ],
- },
- {
- key: "structural",
- label: "Structural relations",
- items: [
- {
- path: "docs/specs/product/example.md",
- title: "Governing product behavior",
- kind: "note",
- relationName: "governingSpecs",
- structural: true,
- },
- ],
- },
- ];
-
- return workspace;
-}
-
-function workspaceWithSectionsAndNearby(): NodeWorkspace {
- const workspace = workspaceWithEmbeddedRelation();
-
- workspace.focusedNodeId = "focused-section";
- workspace.nodes = [
- {
- id: "parent-section",
- kind: "section",
- ref: {
- notePath: "docs/people/drew.md",
- fragment: "Overview",
- structuralFingerprint: "parent-stable",
- kind: "SECTION",
- },
- notePath: "docs/people/drew.md",
- status: workspace.status,
- capabilities: workspace.capabilities,
- data: { title: "Overview" },
- },
- {
- id: "focused-section",
- kind: "section",
- ref: {
- notePath: "docs/people/drew.md",
- fragment: "Current",
- structuralFingerprint: "current-stable",
- kind: "SECTION",
- },
- notePath: "docs/people/drew.md",
- parentId: "parent-section",
- status: workspace.status,
- capabilities: workspace.capabilities,
- data: { title: "Current" },
- },
- {
- id: "nearby-section",
- kind: "section",
- ref: {
- notePath: "docs/people/drew.md",
- fragment: "Old nearby heading",
- structuralFingerprint: "nearby-stable",
- kind: "SECTION",
- },
- notePath: "docs/people/drew.md",
- parentId: "parent-section",
- status: workspace.status,
- capabilities: workspace.capabilities,
- data: { title: "Nearby section" },
- },
- {
- id: "field-sections",
- kind: "field",
- ref: workspace.node.ref,
- notePath: "docs/people/drew.md",
- parentId: "focused-section",
- status: workspace.status,
- capabilities: workspace.capabilities,
- field: {
- name: "supportingSections",
- valueKind: "section-ref",
- present: true,
- values: [],
- range: { start: 0, end: 0 },
- sectionRefs: [
- {
- notePath: "docs/sections.md",
- fragment: "Old section heading",
- structuralFingerprint: "section-stable",
- kind: "SECTION",
- },
- ],
- },
- },
- ];
-
- return workspace;
-}
+import {
+ workspaceWithEmbeddedRelation,
+ workspaceWithNavigation,
+} from "./body/noteInfoFixtures.test-support";
function groupSection(title: string): HTMLElement {
const section = screen
@@ -252,9 +19,18 @@ function groupSection(title: string): HTMLElement {
}
describe("NotesSidebarInfo", () => {
+ it("preserves the collection record template by default", () => {
+ render( );
+ const relations = groupSection("Relations");
+ expect(within(relations).getByRole("heading", { name: "Outgoing" })).toBeVisible();
+ expect(within(relations).queryByRole("img", { name: "Links to" })).toBeNull();
+ });
+
it("keeps embedded relation targets with related notes and opens them at their anchor", () => {
const onOpen = vi.fn();
- render( );
+ render(
+ ,
+ );
const link = within(groupSection("Relations")).getByRole("button", {
name: "Decide rain-date contingency by end of May",
@@ -266,7 +42,7 @@ describe("NotesSidebarInfo", () => {
expect(onOpen).toHaveBeenCalledWith("docs/playground/pizza-party-2026.md#item-1030", "stack");
});
- it("groups field relations by direction and merges body links and backlinks per note", () => {
+ it("shows each field relation direction and merges body links and backlinks per note", () => {
const workspace = workspaceWithEmbeddedRelation();
workspace.relations = [
{
@@ -335,11 +111,14 @@ describe("NotesSidebarInfo", () => {
],
},
];
- render( );
+ render( );
const relations = groupSection("Relations");
- expect(relations).toHaveTextContent(/←\s*Incoming\s*Opportunities\s*Idea\s*1\s*Idea A/);
- expect(relations).toHaveTextContent(/→\s*Outgoing\s*Impacts\s*Impact\s*1\s*Impact B/);
+ expect(relations).toHaveTextContent(/Opportunities\s*1\s*Idea A\s*Idea/);
+ expect(relations).toHaveTextContent(/Impacts\s*1\s*Impact B\s*Impact/);
+
+ expect(relations.querySelector(".lucide-arrow-left")).toBeTruthy();
+ expect(relations.querySelector(".lucide-arrow-right")).toBeTruthy();
const linked = groupSection("Linked notes");
expect(within(linked).queryByRole("button", { name: "Idea A" })).toBeNull();
@@ -365,7 +144,7 @@ describe("NotesSidebarInfo", () => {
})),
},
];
- render( );
+ render( );
const linked = groupSection("Linked notes");
expect(within(linked).getAllByRole("listitem")).toHaveLength(5);
@@ -375,7 +154,7 @@ describe("NotesSidebarInfo", () => {
it("renders schema-declared workspace navigation separately and marks the current member", () => {
const onOpen = vi.fn();
- render( );
+ render( );
// An effort's materials start open.
const navigation = groupSection("Effort materials");
@@ -404,196 +183,16 @@ describe("NotesSidebarInfo", () => {
it("keeps an HTML page's effort materials closed, since the page links them", () => {
const workspace = workspaceWithNavigation();
workspace.content.format = "html";
- render( );
+ render( );
const navigation = groupSection("Effort materials");
expect(navigation).not.toHaveAttribute("open");
- expect(navigation.querySelector("summary")).toHaveTextContent(/materials?$/);
- expect(groupSection("Relations")).toBeVisible();
- });
-});
-
-describe("NotesSidebarInfo note previews", () => {
- const http = withFakeFetch();
-
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(0);
- setHover(true);
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- vi.useRealTimers();
- });
-
- it("opens a related-note preview to the left and preserves click modes", async () => {
- http.json("GET", "/api/v1/nodes/preview", preview);
- vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
- function (this: HTMLElement) {
- if (this.classList.contains("note-preview")) return new DOMRect(0, 0, 240, 180);
-
- if (this.classList.contains("ontology-sidebar-info")) {
- return new DOMRect(880, 0, 320, 700);
- }
-
- if (this instanceof HTMLButtonElement) return new DOMRect(900, 120, 100, 24);
-
- return new DOMRect();
- },
- );
-
- const view = renderSidebar(workspaceWithEmbeddedRelation());
-
- const button = within(groupSection("Relations")).getByRole("button", {
- name: "Decide rain-date contingency by end of May",
- });
-
- fireEvent.mouseEnter(button, { clientY: 125 });
- await advance(100);
- await advance(200);
-
- const card = screen.getByRole("region", { name: "Preview of Pizza party" });
- expect(card).toHaveStyle({ left: "634px", top: "120px" });
- expect(button).toHaveAttribute("aria-describedby", card.id);
- const request = http.requests("GET", "/api/v1/nodes/preview")[0];
- expect(request?.query.get("ref")).toBe("docs/playground/pizza-party-2026.md#item-1030");
- expect(request?.query.get("from")).toBe("docs/people/drew.md");
-
- fireEvent.keyDown(window, { key: "Escape" });
- expect(
- screen.queryByRole("region", { name: "Preview of Pizza party" }),
- ).not.toBeInTheDocument();
-
- fireEvent.click(button);
- expect(view.onOpen).toHaveBeenLastCalledWith(
- "docs/playground/pizza-party-2026.md#item-1030",
- "stack",
- );
- fireEvent.click(button, { metaKey: true });
- expect(view.onOpen).toHaveBeenLastCalledWith(
- "docs/playground/pizza-party-2026.md#item-1030",
- "beside",
- );
- });
-
- it("does not duplicate an anchor already present in a relation path", async () => {
- http.json("GET", "/api/v1/nodes/preview", preview);
- const workspace = workspaceWithEmbeddedRelation();
- workspace.relations![0].items![0].path = "docs/playground/pizza-party-2026.md#item-1030";
- const view = renderSidebar(workspace);
-
- const button = within(groupSection("Relations")).getByRole("button", {
- name: "Decide rain-date contingency by end of May",
- });
-
- fireEvent.mouseEnter(button);
- await advance(300);
-
- expect(http.requests("GET", "/api/v1/nodes/preview")[0]?.query.get("ref")).toBe(
- "docs/playground/pizza-party-2026.md#item-1030",
- );
- fireEvent.click(button);
- expect(view.onOpen).toHaveBeenCalledWith(
- "docs/playground/pizza-party-2026.md#item-1030",
- "stack",
- );
- });
-
- it("previews and opens section and nearby refs by their stable targets", async () => {
- http.json("GET", "/api/v1/nodes/preview", preview);
- const view = renderSidebar(workspaceWithSectionsAndNearby());
-
- const section = within(groupSection("Relations")).getByRole("button", {
- name: "Old section heading",
- });
-
- fireEvent.mouseEnter(section);
- await advance(300);
-
- expect(http.requests("GET", "/api/v1/nodes/preview")[0]?.query.get("ref")).toBe(
- "docs/sections.md#struct:section-stable",
- );
- fireEvent.keyDown(window, { key: "Escape" });
- fireEvent.click(section, { ctrlKey: true });
- expect(view.onOpen).toHaveBeenLastCalledWith(
- "docs/sections.md#struct:section-stable",
- "beside",
+ expect(navigation.querySelector("summary")).toHaveTextContent(/^Effort materials\s*3$/);
+ const heading = navigation.querySelector("summary h3");
+ expect(heading?.firstChild?.textContent).toBe("Effort materials");
+ expect(heading?.querySelector(".disclosure-toggle")?.nextElementSibling).toHaveClass(
+ "ontology-sidebar-context__count",
);
-
- const nearby = within(groupSection("Nearby nodes")).getByRole("button", {
- name: "Nearby section",
- });
-
- fireEvent.mouseEnter(nearby);
- await advance(300);
-
- expect(http.requests("GET", "/api/v1/nodes/preview")[1]?.query.get("ref")).toBe(
- "docs/people/drew.md#struct:nearby-stable",
- );
- fireEvent.click(nearby);
- expect(view.onOpen).toHaveBeenLastCalledWith(
- "docs/people/drew.md#struct:nearby-stable",
- "stack",
- );
- });
-
- it("shrinks a left preview to remain outside a narrow rail", async () => {
- http.json("GET", "/api/v1/nodes/preview", preview);
- vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
- function (this: HTMLElement) {
- if (this.classList.contains("note-preview")) return new DOMRect(0, 0, 440, 180);
-
- if (this.classList.contains("ontology-sidebar-info")) {
- return new DOMRect(400, 0, 300, 700);
- }
-
- if (this instanceof HTMLButtonElement) return new DOMRect(420, 120, 100, 24);
-
- return new DOMRect();
- },
- );
-
- renderSidebar(workspaceWithEmbeddedRelation());
-
- const button = within(groupSection("Relations")).getByRole("button", {
- name: "Decide rain-date contingency by end of May",
- });
-
- fireEvent.mouseEnter(button);
- await advance(100);
- await advance(200);
-
- const card = screen.getByRole("region", { name: "Preview of Pizza party" });
- expect(card).toHaveStyle({ left: "8px", maxWidth: "386px" });
- expect(
- Number.parseFloat(card.style.left) + Number.parseFloat(card.style.maxWidth),
- ).toBeLessThan(400);
- });
-
- it("opens from focus, supports Tab transfer, and closes on blur", async () => {
- http.json("GET", "/api/v1/nodes/preview", preview);
- const view = renderSidebar(workspaceWithEmbeddedRelation());
-
- const button = within(groupSection("Relations")).getByRole("button", {
- name: "Decide rain-date contingency by end of May",
- });
-
- act(() => button.focus());
- await advance(100);
- await advance(200);
-
- const card = screen.getByRole("region", { name: "Preview of Pizza party" });
- fireEvent.keyDown(button, { key: "Tab" });
- expect(card).toHaveFocus();
- fireEvent.keyDown(card, { key: "Tab", shiftKey: true });
- expect(button).toHaveFocus();
-
- fireEvent.blur(button);
- await advance(150);
- expect(
- screen.queryByRole("region", { name: "Preview of Pizza party" }),
- ).not.toBeInTheDocument();
- expect(view.onOpen).not.toHaveBeenCalled();
+ expect(groupSection("Relations")).toBeVisible();
});
});
diff --git a/web/src/components/NotesSidebarInfo.tsx b/web/src/components/NotesSidebarInfo.tsx
index e04ef680f..12697cb05 100644
--- a/web/src/components/NotesSidebarInfo.tsx
+++ b/web/src/components/NotesSidebarInfo.tsx
@@ -1,9 +1,27 @@
+import { RelationArrow } from "./body/RelationArrow";
+import {
+ railRow,
+ relationBuckets,
+ linkedBuckets,
+ RELATION_DIRECTIONS,
+ RELATION_DIRECTION_LABEL,
+ isNoteContent,
+ relationTarget,
+ humanizeRelationName,
+} from "./body/noteInfoBuckets";
import { sessionStateLabel } from "../staging/stagedState";
import { publicWorkspaceRef } from "../api/client";
import { displayTitle } from "../lib/labels";
import { publicTypeName } from "../lib/typeNames";
-import { ChevronRight } from "lucide-react";
-import { type ReactNode, useMemo, useState } from "react";
+import { DisclosureChevron } from "./DisclosureChevron";
+import {
+ DirectionLegend,
+ RailBucketList,
+ RailRowItem,
+ type OpenFn,
+ type RailBucket,
+} from "./body/NoteInfoRows";
+import { type ReactNode, useMemo } from "react";
import type {
NodeWorkspace,
NoteWorkspaceGroup,
@@ -14,26 +32,14 @@ import { isContentNode } from "../api/types";
import { selectWorkspaceRelationGroups } from "./workspaceGraph";
import { ValidationIssueBadge } from "./validation/ValidationIssueBadge";
import type { ValidationHealth } from "../api/types";
-import { useNotePreviewTrigger } from "./notePreview/NoteLinkPreview";
-import { type TypeLabelFn, useTypeLabel } from "./typeLabels";
+import { useTypeLabel } from "./typeLabels";
// Only genuine code evidence belongs under the Code rail. Section and embedded
// targets (headings, action items) are note content and stay with Related notes.
-const NOTE_CONTENT_KINDS = new Set(["note", "section", "embedded"]);
-
function isCodeContextGroup(group: NoteWorkspaceGroup): boolean {
return group.key === "code" || group.items?.some((item) => !isNoteContent(item)) || false;
}
-function isNoteContent(item: NoteWorkspaceLink): boolean {
- return NOTE_CONTENT_KINDS.has(item.kind);
-}
-
-// Anchored items address a node inside a note; the shell opens `path#anchor`.
-function relationTarget(item: NoteWorkspaceLink): string {
- return item.anchor && !item.path.includes("#") ? `${item.path}#${item.anchor}` : item.path;
-}
-
function relationItemKey(
group: NoteWorkspaceGroup,
item: NoteWorkspaceLink,
@@ -58,163 +64,6 @@ function compactRelationLabel(group: NoteWorkspaceGroup): string {
return group.label;
}
-// Link kinds carry an index qualifier ("note_link:wikilink:basic"); readers
-// only need the kind.
-function humanizeRelationName(name: string): string {
- const spaced = name
- .split(":", 1)[0]
- .trim()
- .replace(/[_-]+/g, " ")
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
- .toLowerCase();
-
- return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : name;
-}
-
-type Direction = "outgoing" | "incoming" | "both";
-
-// Servers before `direction` existed only marked backlinks.
-function itemDirection(item: NoteWorkspaceLink): Direction {
- if (item.direction) return item.direction;
-
- return item.provenance === "backlink" ? "incoming" : "outgoing";
-}
-
-const DIRECTION_GLYPH: Record = { outgoing: "→", incoming: "←", both: "↔" };
-
-const DIRECTION_LABEL: Record = {
- outgoing: "Links to",
- incoming: "Links here",
- both: "Linked both ways",
-};
-
-// Typed relations group by direction under compact labels.
-const RELATION_DIRECTIONS: Direction[] = ["incoming", "outgoing", "both"];
-
-const RELATION_DIRECTION_LABEL: Record = {
- incoming: "Incoming",
- outgoing: "Outgoing",
- both: "Both ways",
-};
-
-type RailRow = {
- key: string;
- target: string;
- label: string;
- title: string;
- typeName: string;
- direction: Direction;
- current?: boolean;
- openable: boolean;
- /** Folder shown beside an untyped note, in place of a type. */
- folder?: string;
-};
-
-type RailBucket = {
- key: string;
- label: string;
- hint?: string;
- direction?: Direction;
- rows: RailRow[];
-};
-
-function railRow(item: NoteWorkspaceLink, typeLabel: TypeLabelFn): RailRow {
- const target = relationTarget(item);
- const type = publicTypeName(item.resolvedType || item.structuralNode?.typeName);
-
- return {
- key: target,
- target,
- label: displayTitle(item.title) || target,
- title: item.targetTitle || item.title || target,
- typeName: type ? typeLabel(type) : "",
- direction: itemDirection(item),
- current: item.current,
- openable: isNoteContent(item),
- };
-}
-
-// Typed field relations, one bucket per field and direction ("Impacts →",
-// "← Opportunities"). The type moves to the header when every target shares it.
-function relationBuckets(items: NoteWorkspaceLink[], typeLabel: TypeLabelFn): RailBucket[] {
- const buckets = new Map();
-
- for (const item of items) {
- const row = railRow(item, typeLabel);
- const relation = item.relationName || item.provenance || "relation";
- const name = humanizeRelationName(relation);
- // Key by the schema field, not its label: `partOf` and `part_of` stay apart.
- const key = `${row.direction}:${relation}`;
- const bucket = buckets.get(key) ?? { key, label: name, direction: row.direction, rows: [] };
-
- if (!bucket.rows.some((existing) => existing.target === row.target)) bucket.rows.push(row);
- buckets.set(key, bucket);
- }
-
- return Array.from(buckets.values()).map((bucket) => {
- const types = new Set(bucket.rows.map((row) => row.typeName));
-
- if (types.size !== 1) return bucket;
-
- return {
- ...bucket,
- hint: bucket.rows[0].typeName,
- rows: bucket.rows.map((row) => ({ ...row, typeName: "" })),
- };
- });
-}
-
-// The folder that holds a note, shown beside an untyped link ("pkg/app/").
-function folderOf(target: string): string {
- const path = target.split("#", 1)[0];
- const slash = path.lastIndexOf("/");
-
- return slash > 0 ? path.slice(0, slash + 1) : "";
-}
-
-const UNTYPED_BUCKET_LABEL = "Other notes";
-
-// Body links and backlinks, one row per note with its direction, bucketed by
-// type; untyped notes share one bucket and show their folder instead.
-function linkedBuckets(
- items: NoteWorkspaceLink[],
- exclude: ReadonlySet,
- typeLabel: TypeLabelFn,
-): RailBucket[] {
- const rows = new Map();
-
- for (const item of items) {
- const row = railRow(item, typeLabel);
-
- if (exclude.has(row.target)) continue;
- const existing = rows.get(row.target);
-
- if (!existing) {
- rows.set(row.target, row);
- } else if (existing.direction !== row.direction) {
- existing.direction = "both";
- }
- }
-
- const buckets = new Map();
-
- for (const row of rows.values()) {
- const typed = Boolean(row.typeName);
- const label = row.typeName || UNTYPED_BUCKET_LABEL;
- const key = `${typed ? "type" : "untyped"}:${label}`;
- const bucket = buckets.get(key) ?? { key, label, typed, rows: [] };
- bucket.rows.push({ ...row, typeName: "", folder: typed ? undefined : folderOf(row.target) });
- buckets.set(key, bucket);
- }
-
- return Array.from(buckets.values()).sort(
- (a, b) =>
- Number(b.typed) - Number(a.typed) ||
- b.rows.length - a.rows.length ||
- a.label.localeCompare(b.label),
- );
-}
-
function nearbyStructuralNodes(workspace: NodeWorkspace): WorkspaceContentNode[] {
const focusedID = workspace.focusedNodeId;
@@ -244,152 +93,6 @@ function nearbyStructuralNodes(workspace: NodeWorkspace): WorkspaceContentNode[]
return output;
}
-function SidebarPreviewButton({
- target,
- label,
- title,
- current,
- from,
- onOpen,
-}: {
- target: string;
- label: string;
- title?: string;
- current?: boolean;
- from: string;
- onOpen: (path: string, target?: "current" | "stack" | "beside") => void;
-}) {
- const previewTrigger = useNotePreviewTrigger({
- target,
- from,
- placement: "left",
- placementBoundary: (trigger) =>
- trigger.closest(".ontology-sidebar-info")?.getBoundingClientRect() ?? null,
- open: (path, mode) => onOpen(path, mode),
- });
-
- return (
- <>
- {
- previewTrigger.close();
- onOpen(target, event.metaKey || event.ctrlKey ? "beside" : "stack");
- }}
- >
- {label}
-
- {previewTrigger.preview}
- >
- );
-}
-
-type OpenFn = (path: string, target?: "current" | "stack" | "beside") => void;
-
-function RailRowItem({
- row,
- showDirection,
- from,
- onOpen,
-}: {
- row: RailRow;
- showDirection: boolean;
- from: string;
- onOpen: OpenFn;
-}) {
- return (
-
- {showDirection && (
-
- {DIRECTION_GLYPH[row.direction]}
-
- )}
- {row.openable ? (
-
- ) : (
-
- {row.label}
-
- )}
- {row.typeName && {row.typeName} }
- {row.folder && (
- // Truncates from the start (CSS rtl) so the deepest folder stays; the
- // marks keep the path itself in left-to-right order.
-
- {`\u200e${row.folder}\u200e`}
-
- )}
-
- );
-}
-
-const BUCKET_LIMIT = 5;
-
-function RailBucketList({
- bucket,
- showDirection,
- from,
- onOpen,
-}: {
- bucket: RailBucket;
- showDirection: boolean;
- from: string;
- onOpen: OpenFn;
-}) {
- const [expanded, setExpanded] = useState(false);
- // Show everything when only one row would hide behind the toggle.
- const limit = bucket.rows.length <= BUCKET_LIMIT + 1 ? bucket.rows.length : BUCKET_LIMIT;
- const rows = expanded ? bucket.rows : bucket.rows.slice(0, limit);
- const hidden = bucket.rows.length - rows.length;
-
- return (
-
-
- {bucket.label}
- {bucket.hint && {bucket.hint} }
- {bucket.rows.length}
-
-
- {rows.map((row) => (
-
- ))}
-
- {bucket.rows.length > limit && (
-
setExpanded((value) => !value)}
- >
- {expanded ? "Show fewer" : `${hidden} more`}
-
- )}
-
- );
-}
-
// "In this effort" names its members as "Effort materials".
function materialsLabel(label: string): string {
const owner = /^In this (.+)$/.exec(label)?.[1];
@@ -397,28 +100,6 @@ function materialsLabel(label: string): string {
return owner ? `${owner[0].toUpperCase()}${owner.slice(1)} materials` : label;
}
-// Names the arrows that appear in a list, once, above it.
-function DirectionLegend({ buckets }: { buckets: RailBucket[] }) {
- const present = new Set(buckets.flatMap((bucket) => bucket.rows.map((row) => row.direction)));
-
- return (
-
- {(["incoming", "outgoing", "both"] as const).flatMap((direction) =>
- present.has(direction)
- ? [
-
-
- {DIRECTION_GLYPH[direction]}
-
- {DIRECTION_LABEL[direction]}
- ,
- ]
- : [],
- )}
-
- );
-}
-
// Empty groups stay hidden; the panel says once when nothing is indexed.
function SidebarContextGroup({
title,
@@ -435,7 +116,9 @@ function SidebarContextGroup({
{title}
- {count !== undefined && {count} }
+ {count !== undefined && (
+ {count}
+ )}
{children}
@@ -451,7 +134,9 @@ export function NotesSidebarInfo({
onOpen,
validationIssueCount,
validationHealth = "never_checked",
+ noteReader = false,
}: {
+ noteReader?: boolean;
workspace: NodeWorkspace | null;
onOpen: OpenFn;
validationIssueCount?: number;
@@ -495,6 +180,7 @@ export function NotesSidebarInfo({
const relationBucketsList = relationBuckets(
[...noteItems.filter((item) => item.structural), ...sectionItems],
typeLabel,
+ noteReader,
);
const relationTargets = new Set(
@@ -507,9 +193,10 @@ export function NotesSidebarInfo({
noteItems.filter((item) => !item.structural),
relationTargets,
typeLabel,
+ noteReader,
),
};
- }, [relationGroups, workspace, path, typeLabel]);
+ }, [relationGroups, workspace, path, typeLabel, noteReader]);
const nearbyNodes = useMemo(
() => (workspace ? nearbyStructuralNodes(workspace) : []),
@@ -535,7 +222,7 @@ export function NotesSidebarInfo({
);
return (
-
+
{focusedSection && isContentNode(focusedSection) && (
@@ -569,13 +256,20 @@ export function NotesSidebarInfo({
{materialsLabel(group.label)}
-
- {group.items?.length ?? 0}
-
- {group.items?.length === 1 ? " material" : " materials"}
+ {noteReader && (
+
+
+ )}
+
+ {group.items?.length ?? 0}
+ {!noteReader && (
+
+ {group.items?.length === 1 ? " material" : " materials"}
+
+ )}
-
+ {!noteReader && }
{group.ownerTitle && (
@@ -595,32 +289,42 @@ export function NotesSidebarInfo({
))}
- {relations.length > 0 &&
- RELATION_DIRECTIONS.map((direction) => {
- const buckets = relations.filter((bucket) => bucket.direction === direction);
-
- if (buckets.length === 0) return null;
-
- return (
-
-
-
- {DIRECTION_GLYPH[direction]}
-
- {RELATION_DIRECTION_LABEL[direction]}
-
- {buckets.map((bucket) => (
-
- ))}
-
- );
- })}
+ {noteReader
+ ? relations.map((bucket) => (
+
+ ))
+ : relations.length > 0 &&
+ RELATION_DIRECTIONS.map((direction) => {
+ const buckets = relations.filter((bucket) => bucket.direction === direction);
+
+ if (buckets.length === 0) return null;
+
+ return (
+
+
+
+
+
+ {RELATION_DIRECTION_LABEL[direction]}
+
+ {buckets.map((bucket) => (
+
+ ))}
+
+ );
+ })}
{linked.length > 0 && }
diff --git a/web/src/components/OntologyAtlasHome.test.tsx b/web/src/components/OntologyAtlasHome.test.tsx
index 96ed15678..b4e5faae4 100644
--- a/web/src/components/OntologyAtlasHome.test.tsx
+++ b/web/src/components/OntologyAtlasHome.test.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
+import { beforeEach, describe, expect, it } from "vitest";
import { withFakeLayout } from "../test/fakeLayout";
import { OntologyAtlasHome } from "./OntologyAtlasHome";
@@ -7,6 +7,11 @@ import { OntologyAtlasHome } from "./OntologyAtlasHome";
describe("OntologyAtlasHome", () => {
withFakeLayout();
+ beforeEach(async () => {
+ // Load the real lazy dependency before assertions, regardless of test order.
+ await import("./OntologyGraph");
+ });
+
it("uses the visualization as the atlas survey surface", async () => {
const { container } = render(
{
expect(screen.queryByRole("heading", { name: "Types" })).toBeNull();
expect(screen.queryByRole("heading", { name: "Interfaces" })).toBeNull();
// The header counts types and interfaces together, then names each.
- expect(screen.getByText("2")).toHaveClass("view-header__count");
+ expect(document.querySelector(".view-header__count")).toBeNull();
expect(screen.getByText("1 type and 1 interface · 3 records")).toBeVisible();
const find = await screen.findByRole("searchbox", { name: "Find a type" });
fireEvent.change(find, { target: { value: "spec" } });
diff --git a/web/src/components/OntologyAtlasHome.tsx b/web/src/components/OntologyAtlasHome.tsx
index 30ec76f50..d211ebc63 100644
--- a/web/src/components/OntologyAtlasHome.tsx
+++ b/web/src/components/OntologyAtlasHome.tsx
@@ -6,12 +6,11 @@ const OntologyGraph = lazy(() =>
import("./OntologyGraph").then((m) => ({ default: m.OntologyGraph })),
);
-function AtlasHeader({ count, about }: { count?: number; about?: string }) {
+function AtlasHeader({ about }: { about?: string }) {
return (
@@ -77,7 +76,6 @@ export function OntologyAtlasHome({ atlas, error, onRetry }: Props) {
return (
diff --git a/web/src/components/OntologyEditSessionPanel.test.tsx b/web/src/components/OntologyEditSessionPanel.test.tsx
index 87cc6e12f..ea8f686bf 100644
--- a/web/src/components/OntologyEditSessionPanel.test.tsx
+++ b/web/src/components/OntologyEditSessionPanel.test.tsx
@@ -4,6 +4,22 @@ import { describe, expect, it, vi } from "vitest";
import { OntologyEditSessionPanel } from "./OntologyEditSessionPanel";
describe("OntologyEditSessionPanel", () => {
+ it("explains why Save is disabled when editing has no changes", () => {
+ render(
+ ,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("Editing");
+ expect(screen.getByText("No changes")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Done" })).toBeEnabled();
+ });
it("offers Save and an explicit Discard while an unstaged local draft exists", () => {
const onCommit = vi.fn();
const onDiscard = vi.fn();
@@ -19,7 +35,7 @@ describe("OntologyEditSessionPanel", () => {
/>,
);
- expect(screen.getByRole("status")).toHaveTextContent("Draft");
+ expect(screen.getByRole("status")).toHaveTextContent("Unsaved changes");
expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
expect(screen.queryByRole("button", { name: "Review" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Done" })).not.toBeInTheDocument();
diff --git a/web/src/components/OntologyEditSessionPanel.tsx b/web/src/components/OntologyEditSessionPanel.tsx
index 406a45243..0f9d0ab24 100644
--- a/web/src/components/OntologyEditSessionPanel.tsx
+++ b/web/src/components/OntologyEditSessionPanel.tsx
@@ -50,9 +50,9 @@ export function OntologyEditSessionPanel({
: session?.status === "rebased"
? ["Rebased", "dirty"]
: hasStagedChanges
- ? ["Ready to save", "dirty"]
+ ? ["Unsaved changes", "dirty"]
: hasLocalDrafts
- ? ["Draft", "dirty"]
+ ? ["Unsaved changes", "dirty"]
: ["Editing", "idle"];
const messageKey = JSON.stringify([
@@ -126,6 +126,7 @@ export function OntologyEditSessionPanel({
)}
+ {!hasChanges && No changes }
{/* Review appears once there is something staged to review. */}
{hasStagedChanges && (
;
@@ -85,6 +86,7 @@ function FocusViewport({ ids, selected }: { ids: string[]; selected: string | nu
}
export function OntologyGraph({ atlas }: Props) {
+ const palette = useTypePalette();
const typeLabel = useTypeLabel();
const [selection, setSelected] = useState(null);
const [hovered, setHovered] = useState(null);
@@ -107,6 +109,13 @@ export function OntologyGraph({ atlas }: Props) {
setError(null);
const built = buildOntologyGraph(atlas);
+ for (const node of built.nodes) {
+ node.width = Math.max(node.width, typeLabel(node.id).length * 12 + 40);
+ const outgoing = built.edges.filter((edge) => edge.source === node.id).length;
+ const incoming = built.edges.filter((edge) => edge.target === node.id).length;
+ node.height = Math.max(node.height, Math.max(outgoing, incoming) * 18 + 20);
+ }
+
if (cancelled) return;
void layoutOntologyGraph(built)
.then((laidOut) => {
@@ -145,6 +154,7 @@ export function OntologyGraph({ atlas }: Props) {
sourceOffset: e.sourceOffset,
targetOffset: e.targetOffset,
kind,
+ fieldName: e.data?.fieldName,
accent: typeAccentColor(e.source),
},
};
@@ -164,7 +174,7 @@ export function OntologyGraph({ atlas }: Props) {
return () => {
cancelled = true;
};
- }, [atlas, attempt]);
+ }, [atlas, attempt, palette]);
const focusedIds = useMemo(() => {
if (!selected || !graph.nodes.some((node) => node.id === selected))
@@ -211,6 +221,9 @@ export function OntologyGraph({ atlas }: Props) {
return [
{
...edge,
+ label: lit ? edge.data?.fieldName : undefined,
+ labelStyle: { fill: "var(--text)", fontSize: 14 },
+ labelBgStyle: { fill: "var(--surface)" },
style: {
stroke: color,
strokeWidth: 1.5,
@@ -341,6 +354,9 @@ export function OntologyGraph({ atlas }: Props) {
Neighbor, shown while tracing
+
+ Self relation
+
Hover a card to trace it in its color
diff --git a/web/src/components/OntologyIdentityStrip.test.tsx b/web/src/components/OntologyIdentityStrip.test.tsx
index ade33191b..2e3c778a2 100644
--- a/web/src/components/OntologyIdentityStrip.test.tsx
+++ b/web/src/components/OntologyIdentityStrip.test.tsx
@@ -145,6 +145,10 @@ describe("OntologyIdentityStrip", () => {
expect(screen.getByText("Proposed")).toBeInTheDocument();
expect(screen.getByText("Apr 12, 2026")).toBeInTheDocument();
expect(screen.getByText("Updated")).toBeInTheDocument();
+ const separator = document.querySelector(".note-identity-separator");
+ expect(separator).toHaveTextContent("·");
+ expect(separator).toHaveAttribute("aria-hidden", "true");
+ expect(separator?.nextElementSibling).toHaveAttribute("data-field", "lastUpdated");
});
it("keeps the title visible when the note has no identity fields", () => {
diff --git a/web/src/components/OntologyIdentityStrip.tsx b/web/src/components/OntologyIdentityStrip.tsx
index d9e76f903..cd3428fe0 100644
--- a/web/src/components/OntologyIdentityStrip.tsx
+++ b/web/src/components/OntologyIdentityStrip.tsx
@@ -30,7 +30,7 @@ type Props = {
/**
* Top strip of the structural view. It condenses the identity-bearing facts
- * — type badge, preferred identifier, status pill, version, last-updated —
+ * — type badge, preferred identifier, status mark, version, last-updated —
* into a single row above the property panel. Clicking any widget in edit
* mode stages a setField op via onStageOps; all ops go through the same
* builder so the identity strip and the property panel stay interchangeable.
@@ -124,6 +124,11 @@ export function OntologyIdentityStrip({
/>
)}
{status}
+ {status && identity.lastUpdated && (
+
+ ·
+
+ )}
{identity.lastUpdated && (
+
{labelPrefix && {labelPrefix} }
{prefix && !editing && value && (
{prefix}
diff --git a/web/src/components/OntologyLocalGraph.tsx b/web/src/components/OntologyLocalGraph.tsx
index 7310836c7..870de7fed 100644
--- a/web/src/components/OntologyLocalGraph.tsx
+++ b/web/src/components/OntologyLocalGraph.tsx
@@ -1,3 +1,4 @@
+import { useTypePalette } from "../lib/typeAccent";
import { publicTypeName } from "../lib/typeNames";
import { useCallback, useMemo } from "react";
import type {
@@ -148,9 +149,11 @@ function HoverCard({ hover }: { hover: HoverInfo }) {
export function OntologyLocalGraph({ workspace, onOpen, onOpenNode }: Props) {
const { nodes, edges, emptyReason } = useMemo(() => buildLocalGraph(workspace), [workspace]);
+ const palette = useTypePalette();
+
const typeColors = useMemo(
() => buildTypeColors(nodes.flatMap((node) => (node.resolvedType ? [node.resolvedType] : []))),
- [nodes],
+ [nodes, palette],
);
const nodeMap = useMemo(
diff --git a/web/src/components/OntologyNotePane.test.tsx b/web/src/components/OntologyNotePane.test.tsx
index 32ba67de5..1088c6bcb 100644
--- a/web/src/components/OntologyNotePane.test.tsx
+++ b/web/src/components/OntologyNotePane.test.tsx
@@ -1875,8 +1875,8 @@ describe("OntologyNotePane", () => {
expect(screen.getByRole("heading", { name: "Summary" })).toBeInTheDocument();
// "Body." appears in the rendered markdown body and the canonical field value.
expect(screen.getAllByText("Body.")).toHaveLength(2);
- // The field's display name is rendered in the property panel above the body.
- expect(screen.getAllByText("Summary").length).toBeGreaterThanOrEqual(2);
+ // The property is labelled "Note summary" so it can't be confused with the body's Summary heading.
+ expect(screen.getByText("Note summary")).toBeInTheDocument();
});
it("renders collection rows from content nodes when owner field nodes share the same ref", () => {
diff --git a/web/src/components/OntologyNotePane.tsx b/web/src/components/OntologyNotePane.tsx
index c658aa54e..4080ccdd8 100644
--- a/web/src/components/OntologyNotePane.tsx
+++ b/web/src/components/OntologyNotePane.tsx
@@ -1,3 +1,4 @@
+import { TypeChip } from "./TypeChip";
import { publicTypeName } from "../lib/typeNames";
import type { MutableRefObject, ReactNode } from "react";
import { createElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -1566,9 +1567,9 @@ export function OntologyNotePane({
-
+
{resolvedType ? typeLabel(resolvedType) : "Untyped"}
-
+
{htmlHead ||
(toolbarPath && (
{
changedFieldNames={new Set()}
/>,
);
- expect(screen.getByText("Summary")).toBeInTheDocument();
+ expect(screen.getByText("Note summary")).toBeInTheDocument();
expect(screen.getByText("A short note")).toBeInTheDocument();
});
@@ -425,11 +425,11 @@ describe("OntologyPropertyPanel", () => {
const first = renderWithQueryClient(panel(false));
const terms = () => screen.getAllByRole("term").map((term) => term.textContent);
- expect(terms()).toEqual(["Summary", "Parent", "Flagged"]);
+ expect(terms()).toEqual(["Note summary", "Parent", "Flagged"]);
const toggle = screen.getByRole("button", { name: "Show 2 empty fields" });
expect(toggle).toHaveAttribute("aria-expanded", "false");
fireEvent.click(toggle);
- expect(terms()).toEqual(["Summary", "Parent", "Owner", "Blank", "Flagged"]);
+ expect(terms()).toEqual(["Note summary", "Parent", "Owner", "Blank", "Flagged"]);
expect(screen.getByRole("button", { name: "Hide 2 empty fields" })).toHaveAttribute(
"aria-expanded",
"true",
@@ -437,13 +437,13 @@ describe("OntologyPropertyPanel", () => {
first.unmount();
const { rerender } = renderWithQueryClient(panel(false));
- expect(terms()).toEqual(["Summary", "Parent", "Owner", "Blank", "Flagged"]);
+ expect(terms()).toEqual(["Note summary", "Parent", "Owner", "Blank", "Flagged"]);
fireEvent.click(screen.getByRole("button", { name: "Hide 2 empty fields" }));
- expect(terms()).toEqual(["Summary", "Parent", "Flagged"]);
+ expect(terms()).toEqual(["Note summary", "Parent", "Flagged"]);
// Editing keeps read mode's geometry: empty fields stay behind the toggle.
rerender(panel(true));
- expect(terms()).toEqual(["Summary", "Parent", "Flagged"]);
+ expect(terms()).toEqual(["Note summary", "Parent", "Flagged"]);
expect(screen.getByRole("button", { name: "Show 2 empty fields" })).toBeVisible();
});
@@ -723,7 +723,7 @@ describe("OntologyPropertyPanel parent preview", () => {
);
const rows = screen.getAllByRole("term").map((row) => row.textContent);
- expect(rows).toEqual(["Parent", "Locator", "Status", "Summary"]);
+ expect(rows).toEqual(["Parent", "Locator", "Status", "Note summary"]);
});
it("previews and opens the parent's canonical stable ref", async () => {
http.json("GET", "/api/v1/nodes/preview", preview);
diff --git a/web/src/components/OntologyPropertyPanel.tsx b/web/src/components/OntologyPropertyPanel.tsx
index 1504ce244..d7ccb0d16 100644
--- a/web/src/components/OntologyPropertyPanel.tsx
+++ b/web/src/components/OntologyPropertyPanel.tsx
@@ -1,13 +1,8 @@
import { DisclosureChevron } from "./DisclosureChevron";
+import { LocatorWidget } from "./body/PropertyLocatorWidget";
+import { EditablePropertyMark } from "./body/EditablePropertyMark";
import { ChevronRight } from "lucide-react";
-import {
- type KeyboardEvent,
- type ReactNode,
- useCallback,
- useEffect,
- useRef,
- useState,
-} from "react";
+import { type ReactNode, useEffect, useRef, useState } from "react";
import type {
NodeRef,
NodeWorkspace,
@@ -397,7 +392,12 @@ function PropertyRow({
data-field={name}
>
- {humanizeName(name)}
+ {name === "summary" ? "Note summary" : humanizeName(name)}
+ {editing &&
+ (isLocator ||
+ (node.field.capability?.writeOperation && !node.field.capability.readOnlyReason)) && (
+
+ )}
{preview ? (
@@ -495,81 +495,3 @@ function nodeRefPath(ref?: NodeRef): string {
return ref.notePath;
}
-
-function isValidLocator(value: string): boolean {
- return /^[A-Za-z0-9_-]+$/.test(value.trim());
-}
-
-function LocatorWidget({
- value,
- editing,
- dirty,
- present,
- onStage,
- ariaLabel,
-}: {
- value: string;
- editing: boolean;
- dirty: boolean;
- present: boolean;
- onStage: (value: string) => void;
- ariaLabel: string;
-}) {
- const [draft, setDraft] = useState(value);
- const inputRef = useRef(null);
- const valid = isValidLocator(draft);
-
- useEffect(() => {
- if (document.activeElement !== inputRef.current) {
- setDraft(value);
- }
- }, [value]);
-
- const commit = useCallback(() => {
- const next = draft.trim();
-
- if (next === value || !isValidLocator(next)) return;
- onStage(next);
- }, [draft, onStage, value]);
-
- const handleKeyDown = useCallback(
- (event: KeyboardEvent) => {
- if (event.key === "Enter") {
- event.preventDefault();
- commit();
- inputRef.current?.blur();
- } else if (event.key === "Escape") {
- event.preventDefault();
- setDraft(value);
- inputRef.current?.blur();
- }
- },
- [commit, value],
- );
-
- if (!editing) {
- if (!present || value.trim() === "") {
- return Empty ;
- }
-
- return ^{value} ;
- }
-
- return (
-
- ^
- setDraft(event.target.value.replace(/^\^+/, ""))}
- onBlur={commit}
- onKeyDown={handleKeyDown}
- />
-
- );
-}
diff --git a/web/src/components/OntologyTypeDetail.tsx b/web/src/components/OntologyTypeDetail.tsx
index b97dd4983..a9f1b0df4 100644
--- a/web/src/components/OntologyTypeDetail.tsx
+++ b/web/src/components/OntologyTypeDetail.tsx
@@ -1,30 +1,21 @@
-import { publicTypeName } from "../lib/typeNames";
+import "./ontology-refinements.css";
+
import type React from "react";
-import { type KeyboardEvent, useId, useMemo, useState } from "react";
+import { type KeyboardEvent, useId, useState } from "react";
-import { isJsonObject, type JsonObject, type JsonValue } from "../api/parse";
-import { publicOntologyListItemRef } from "../api/client";
-import type {
- EnumDoc,
- EnumValueDoc,
- OntologyAtlasResponse,
- OntologyAtlasTypeEntry,
- OntologyNoteListItem,
- OntologyTypeResponse,
- TypeDoc,
- TypeFieldDoc,
-} from "../api/types";
+import type { OntologyAtlasResponse, OntologyTypeResponse } from "../api/types";
import { humanizeName } from "../lib/labels";
-import { typeAccentColor } from "../lib/typeAccent";
-import { buildNoteWebHref } from "../lib/content";
+import { useTypeAccentColor } from "../lib/typeAccent";
+
import { tabKeyTarget } from "./focusManagement";
import { Markdown } from "./markdown/Markdown";
-import { notifyLocationChange } from "./locationStore";
-import { useNotePreviewTrigger, type OpenNote } from "./notePreview/NoteLinkPreview";
-import { buildNotesPath } from "./notesRoute";
+
import { useActiveEditSession } from "./useOntologyEditSession";
import { useOntologyTypeQuery } from "./useNotesQueries";
+import { SchemaPanel } from "./OntologyTypeSchema";
+import { TypeDetailBody } from "./OntologyTypeOverview";
+
type DetailTab = "overview" | "guide" | "schema";
const TAB_ORDER: DetailTab[] = ["overview", "guide", "schema"];
@@ -35,19 +26,6 @@ const TAB_LABELS: Record = {
schema: "Schema",
};
-const openNoteTarget: OpenNote = (target, mode) => {
- const href = buildNoteWebHref(target);
-
- if (mode === "beside") {
- window.open(href, "_blank", "noopener,noreferrer");
-
- return;
- }
-
- window.history.pushState({}, "", href);
- notifyLocationChange();
-};
-
type Props = {
name: string;
atlas: OntologyAtlasResponse | null;
@@ -75,7 +53,7 @@ export function OntologyTypeDetail({ name, atlas, onBack, onSelectType }: Props)
: String(typeQuery.error)
: null;
- const accent = typeAccentColor(name);
+ const accent = useTypeAccentColor(name);
return (
{humanizeName(name)}
- {data ? {data.count} : null}
+ {data ? (
+ {data.count} implementing records
+ ) : null}
{data?.type?.role ? (
{humanizeName(data.type.role.toLowerCase())}
) : null}
@@ -214,1044 +194,3 @@ function AuthoringGuidePanel({ data }: { data: OntologyTypeResponse }) {
);
}
-
-function SchemaPanel({ data }: { data: OntologyTypeResponse }) {
- const type = data.type;
-
- if (!type?.name) {
- return (
-
- No schema data available for this type.
-
- );
- }
-
- const enums = type.enums ?? [];
- const fields = type.fields ?? [];
-
- return (
-
-
-
-
- {(() => {
- const typeDirectives = Object.entries(type.annotations ?? {}).filter(
- ([name]) => name !== "guidance",
- );
-
- return typeDirectives.length > 0 ? (
-
-
Directives
-
- {typeDirectives.map(([name, args]) => (
-
- ))}
-
-
- ) : null;
- })()}
- {fields.length > 0 ? (
-
-
Fields
-
- {fields.map((field) => (
-
- ))}
-
-
- ) : null}
- {enums.length > 0 ? (
-
-
Enums
-
- {enums.map((enumDoc) => (
-
- ))}
-
-
- ) : null}
-
- );
-}
-
-type GuidanceBundle = {
- summary?: string;
- meaning?: string;
- authoring?: string;
- agentImplications?: string;
-};
-
-function guidanceFromType(type: TypeDoc): GuidanceBundle {
- return {
- summary: valueOrUndefined(type.summary),
- meaning: valueOrUndefined(type.meaning),
- authoring: valueOrUndefined(type.authoring),
- agentImplications: valueOrUndefined(type.agentImplications),
- };
-}
-
-function guidanceFromField(field: TypeFieldDoc): GuidanceBundle {
- return {
- summary: valueOrUndefined(field.summary),
- meaning: valueOrUndefined(field.meaning),
- authoring: valueOrUndefined(field.authoring),
- agentImplications: valueOrUndefined(field.agentImplications),
- };
-}
-
-function guidanceFromEnumLike(value: EnumDoc | EnumValueDoc): GuidanceBundle {
- return {
- summary: valueOrUndefined(value.summary),
- meaning: valueOrUndefined(value.meaning),
- authoring: valueOrUndefined(value.authoring),
- agentImplications: valueOrUndefined(value.agentImplications),
- };
-}
-
-function valueOrUndefined(s?: string): string | undefined {
- const trimmed = (s ?? "").trim();
-
- return trimmed === "" ? undefined : trimmed;
-}
-
-function hasGuidance(g: GuidanceBundle): boolean {
- return Boolean(g.summary || g.meaning || g.authoring || g.agentImplications);
-}
-
-function TypeSchemaHeader({ type }: { type: TypeDoc }) {
- const chips: Array<{ label: string; value: string; kind?: string }> = [];
-
- if (type.role) chips.push({ label: "role", value: type.role });
-
- if (type.semantics) chips.push({ label: "semantics", value: type.semantics });
-
- if (type.locator) chips.push({ label: "locator", value: type.locator });
-
- if (type.propertyCase) chips.push({ label: "propertyCase", value: type.propertyCase });
-
- if (type.keyField) chips.push({ label: "keyField", value: type.keyField });
-
- return (
-
-
- {type.role === "interface" ? "interface" : "type"}
- {type.name}
- {type.implements?.length ? (
- <>
- implements
- {type.implements.join(" & ")}
- >
- ) : null}
-
- {chips.length > 0 ? (
-
- {chips.map((chip) => (
-
- {chip.label}
- {chip.value}
-
- ))}
-
- ) : null}
- {type.description ? {type.description}
: null}
-
- );
-}
-
-function TypeMetaGrid({ type }: { type: TypeDoc }) {
- const rows: Array<{ label: string; body: React.ReactNode }> = [];
-
- if (type.label)
- rows.push({
- label: "Label",
- body: {type.label},
- });
-
- if (type.pluralLabel)
- rows.push({
- label: "Plural label",
- body: {type.pluralLabel},
- });
-
- if (type.color)
- rows.push({
- label: "Color",
- body: (
-
-
- {type.color}
-
- ),
- });
-
- if (type.paths?.length)
- rows.push({
- label: "Paths",
- body: (
-
- {type.paths.map((p) => (
-
- {p}
-
- ))}
-
- ),
- });
-
- if (type.matches?.length)
- rows.push({
- label: "Matches",
- body: (
-
- {type.matches.map((m) => (
-
- {m}
-
- ))}
-
- ),
- });
-
- if (type.companionDocs?.length)
- rows.push({
- label: "Companion docs",
- body: (
-
- {type.companionDocs.map((doc) => (
-
- {doc.path}
- {doc.purpose ? (
- · {doc.purpose}
- ) : null}
-
- ))}
-
- ),
- });
-
- if (rows.length === 0) return null;
-
- return (
-
- {rows.map((row) => (
-
-
{row.label}
- {row.body}
-
- ))}
-
- );
-}
-
-function GuidanceBlock({ guidance }: { guidance: GuidanceBundle }) {
- if (!hasGuidance(guidance)) return null;
-
- return (
-
- {guidance.summary ?
{guidance.summary}
: null}
- {guidance.meaning ?
: null}
- {guidance.authoring ?
: null}
- {guidance.agentImplications ? (
-
- ) : null}
-
- );
-}
-
-function GuidanceSection({ label, body }: { label: string; body: string }) {
- return (
-
- );
-}
-
-type SchemaDirective = { name: string; args: JsonObject };
-
-function DirectiveChip({ name, args }: { name: string; args: JsonObject }) {
- const entries = Object.entries(args ?? {}).filter(
- ([, v]) => v !== undefined && v !== null && v !== "",
- );
-
- return (
-
- @{name}
- {entries.length > 0 ? (
-
- (
- {entries.map(([key, value], i) => (
-
- {i > 0 ? ", " : ""}
- {key}
- {": "}
- {formatDirectiveValue(value)}
-
- ))}
- )
-
- ) : null}
-
- );
-}
-
-function formatDirectiveValue(value: JsonValue): string {
- if (Array.isArray(value)) return `[${value.map(formatDirectiveValue).join(", ")}]`;
-
- return JSON.stringify(value);
-}
-
-function fieldSignatureType(field: TypeFieldDoc): string {
- const inner = field.typeName || "?";
- const base = field.list ? `[${inner}]` : inner;
-
- return field.required ? `${base}!` : base;
-}
-
-function SchemaFieldCard({ field }: { field: TypeFieldDoc }) {
- const directives = collectFieldDirectives(field);
- const guidance = guidanceFromField(field);
- const enumDoc = field.enum;
-
- return (
-
-
-
- {field.name}
- :
- {fieldSignatureType(field)}
-
- {field.kind ? (
-
- {humanizeName(field.kind)}
-
- ) : null}
-
- {directives.length > 0 ? (
-
- {directives.map((d) => (
-
- ))}
-
- ) : null}
- {field.description && !guidance.summary ? (
- {field.description}
- ) : null}
-
- {enumDoc?.name && (enumDoc.values?.length ?? 0) > 0 ? (
-
-
Values
-
- {(enumDoc.values ?? []).map((v) => (
-
- {v.name}
-
- ))}
-
-
- ) : null}
-
- );
-}
-
-function collectFieldDirectives(field: TypeFieldDoc): SchemaDirective[] {
- const out: SchemaDirective[] = [];
- const seen = new Set();
- const fromAnnotations = field.annotations ?? {};
-
- for (const [name, args] of Object.entries(fromAnnotations)) {
- if (name === "guidance") continue;
- out.push({ name, args: isJsonObject(args) ? args : {} });
- seen.add(name);
- }
-
- // Synthesize directive summaries from typed columns when annotations are absent.
- if (field.kind === "link" && !seen.has("link")) {
- const args: JsonObject = {};
-
- if (field.direction) args.direction = field.direction;
-
- if (field.inverse) args.inverse = field.inverse;
- out.push({ name: "link", args });
- }
-
- if (field.kind === "reverse" && !seen.has("reverse")) {
- out.push({ name: "reverse", args: field.reverseField ? { field: field.reverseField } : {} });
- }
-
- if (field.kind === "neighbor" && !seen.has("neighbors")) {
- const args: JsonObject = {};
-
- if (field.direction) args.direction = field.direction;
-
- if (field.scope) args.scope = field.scope;
-
- if (field.includeBodyLinks) args.includeBodyLinks = true;
-
- if (field.includeBacklinks) args.includeBacklinks = true;
- out.push({ name: "neighbors", args });
- }
-
- if (field.kind === "section" && !seen.has("section")) {
- const args: JsonObject = {};
-
- if (field.sectionHeading) args.heading = field.sectionHeading;
-
- if (field.sectionLevel) args.level = field.sectionLevel;
-
- if (field.sectionRequired) args.required = true;
-
- if (field.sectionDisplay) args.display = field.sectionDisplay;
- out.push({ name: "section", args });
- }
-
- if (
- (field.kind === "scalar" || field.kind === "field") &&
- !seen.has("field") &&
- (field.source || field.sourceKind)
- ) {
- const args: JsonObject = {};
-
- if (field.source) args.source = field.source;
-
- if (field.sourceKind) args.sourceKind = field.sourceKind;
-
- if (field.sourceAliases?.length) args.aliases = field.sourceAliases;
- out.push({ name: "field", args });
- }
-
- if (field.semantics && !seen.has("semantics")) {
- out.push({ name: "semantics", args: { kind: field.semantics } });
- }
-
- if (isJsonObject(field.policy)) {
- out.push({ name: "policy", args: field.policy });
- }
-
- return out;
-}
-
-function SchemaEnumCard({ enum: enumDoc }: { enum: EnumDoc }) {
- const guidance = guidanceFromEnumLike(enumDoc);
- const values = enumDoc.values ?? [];
-
- return (
-
-
- enum
- {enumDoc.name}
-
-
- {values.length > 0 ? (
-
- {values.map((v) => {
- const vGuidance = guidanceFromEnumLike(v);
-
- return (
-
- {v.name}
- {vGuidance.summary ? (
- {vGuidance.summary}
- ) : null}
- {vGuidance.meaning || vGuidance.authoring || vGuidance.agentImplications ? (
-
-
-
- ) : null}
-
- );
- })}
-
- ) : null}
-
- );
-}
-
-function isRelationField(field: TypeFieldDoc): boolean {
- return (
- field.kind === "link" ||
- field.kind === "reverse" ||
- field.kind === "neighbor" ||
- field.kind === "section"
- );
-}
-
-type InboundRef = {
- fromType: string;
- fromRole?: string;
- fieldName: string;
- direction?: string;
- list?: boolean;
- description?: string;
-};
-
-function collectInboundRefs(atlas: OntologyAtlasResponse | null, targetName: string): InboundRef[] {
- if (!atlas) return [];
- const refs: InboundRef[] = [];
-
- const sources: Array<{ role: string; docs: TypeDoc[] }> = [
- {
- role: "note",
- docs: (atlas.types ?? []).flatMap((entry) => (entry.type ? [entry.type] : [])),
- },
- { role: "interface", docs: atlas.interfaces ?? [] },
- { role: "section", docs: atlas.sections ?? [] },
- ];
-
- for (const { role, docs } of sources) {
- for (const doc of docs) {
- if (!doc?.name || doc.name === targetName) continue;
-
- for (const field of doc.fields ?? []) {
- if (!isRelationField(field)) continue;
-
- if (field.typeName !== targetName) continue;
- refs.push({
- fromType: doc.name,
- fromRole: doc.role || role,
- fieldName: field.name ?? "",
- direction: field.direction,
- list: field.list,
- description: field.description,
- });
- }
- }
- }
-
- return refs.sort((a, b) => {
- if (a.fromType === b.fromType) return a.fieldName.localeCompare(b.fieldName);
-
- return a.fromType.localeCompare(b.fromType);
- });
-}
-
-function collectImplementors(
- atlas: OntologyAtlasResponse | null,
- interfaceName: string,
-): OntologyAtlasTypeEntry[] {
- if (!atlas) return [];
- const entries = atlas.types ?? [];
-
- return entries.filter((entry) => (entry.type?.implements ?? []).includes(interfaceName));
-}
-
-function TypeDetailBody({
- data,
- atlas,
- onSelectType,
-}: {
- data: OntologyTypeResponse;
- atlas: OntologyAtlasResponse | null;
- onSelectType: (name: string) => void;
-}) {
- const type = data.type;
- const typeName = type?.name ?? "";
-
- const isInterface = useMemo(() => {
- if (!typeName) return false;
-
- if (type?.role === "interface") return true;
-
- return (atlas?.interfaces ?? []).some((iface) => iface.name === typeName);
- }, [atlas, type?.role, typeName]);
-
- const implementors = useMemo(
- () => (isInterface ? collectImplementors(atlas, typeName) : []),
- [atlas, isInterface, typeName],
- );
-
- const inboundRefs = useMemo(
- () => (typeName ? collectInboundRefs(atlas, typeName) : []),
- [atlas, typeName],
- );
-
- if (!type?.name) {
- return Type not found.
;
- }
-
- const fields = type.fields ?? [];
- const scalarFields = fields.filter((f) => !isRelationField(f));
- const relationFields = fields.filter(isRelationField);
- // A Direction column shows only when some row has one.
- const relationDirections = relationFields.some((f) => f.direction);
- const inboundDirections = inboundRefs.some((ref) => ref.direction);
- const examples = (data.notes ?? []).slice(0, 6);
-
- return (
- <>
- {type.description ? (
-
-
-
- ) : null}
-
- {data.issueCount ? (
-
-
Issues
- {data.issueCount}
-
- ) : null}
- {type.locator ? (
-
-
Locator
-
- {type.locator}
-
-
- ) : null}
- {type.propertyCase ? (
-
-
Property case
- {type.propertyCase}
-
- ) : null}
- {type.implements?.length ? (
-
-
Implements
-
-
- {type.implements.map((iface) => (
- onSelectType(iface)}
- >
- {humanizeName(iface)}
-
- ))}
-
-
-
- ) : null}
-
-
- {isInterface ? (
-
- Implementors
- {implementors.length === 0 ? (
-
- No types declare implements {typeName} yet.
-
- ) : (
-
- {implementors.map((entry) => {
- const implType = entry.type;
-
- if (!implType?.name) return null;
- const implName = implType.name;
- const implAccent = typeAccentColor(implName);
-
- return (
-
- onSelectType(implName)}
- >
-
-
-
-
- {humanizeName(implType.name)}
-
-
- {implType.name}
-
-
- {entry.count ?? 0}
-
- {implType.description ? (
-
-
-
- ) : null}
-
-
- );
- })}
-
- )}
-
- ) : null}
-
- {type.matches?.length || type.paths?.length ? (
-
- How Rhizome recognizes it
-
- {type.paths?.length ? (
-
-
Paths
-
- {type.paths.map((p) => (
-
- {p}
-
- ))}
-
-
- ) : null}
- {type.matches?.length ? (
-
-
Matches
-
- {type.matches.map((m) => (
-
- {m}
-
- ))}
-
-
- ) : null}
-
-
- ) : null}
-
- {scalarFields.length ? (
-
- ) : null}
-
- {relationFields.length ? (
-
- Typed relations
-
-
-
- Field
- Target
- {relationDirections ? Direction : null}
- Description
-
-
-
- {relationFields.map((f) => (
-
-
- {humanizeName(f.name)} {" "}
- {humanizeName(f.name).toLowerCase() !== (f.name ?? "").toLowerCase() ? (
- {f.name}
- ) : null}
-
-
- {f.typeName ? (
-
- ) : (
- "—"
- )}
-
- {relationDirections ? {directionLabel(f.direction)} : null}
-
-
-
-
- ))}
-
-
-
- ) : null}
-
- {inboundRefs.length ? (
-
- Referenced by
-
-
-
- From type
- Field
- {inboundDirections ? Direction : null}
- Description
-
-
-
- {inboundRefs.map((ref) => (
-
-
-
-
-
-
- {ref.fieldName}
- {ref.list ? "[]" : ""}
-
-
- {inboundDirections ? {directionLabel(ref.direction)} : null}
-
-
-
-
- ))}
-
-
-
- ) : null}
-
- {type.companionDocs?.length ? (
-
- ) : null}
-
-
-
- Examples
- {data.count > examples.length ? (
-
- See all {data.count} →
-
- ) : null}
-
- {examples.length === 0 ? (
- No notes of this type are indexed yet.
- ) : (
-
- {examples.map((note) => (
-
- ))}
-
- )}
-
- >
- );
-}
-
-function TargetChip({
- name,
- list,
- onSelect,
- role,
-}: {
- name: string;
- list: boolean;
- onSelect: (name: string) => void;
- role?: string;
-}) {
- const accent = typeAccentColor(name);
-
- return (
- onSelect(name)}
- title={role ? `${role}: ${name}` : name}
- >
-
- {humanizeName(name)}
-
- {name}
- {list ? "[]" : ""}
-
-
- );
-}
-
-/** A relation's direction in lowercase with its arrow: "← inbound", "→ outbound". */
-function directionLabel(direction?: string) {
- if (!direction) return — ;
- const value = direction.toLowerCase();
-
- const arrow =
- value === "inbound" ? "← " : value === "outbound" ? "→ " : value === "both" ? "↔ " : "";
-
- return `${arrow}${value}`;
-}
-
-/**
- * Identifiers and example values inside schema prose: IDs such as
- * EFF-2026-08-05-14-32, file names, paths, camelCase names, and backticked
- * code. Each renders as one unbreakable mono span, so a column never splits
- * one mid-token.
- */
-const IDENTIFIER =
- /`[^`]+`|\b[A-Z][A-Z0-9]*-[\w-]*\d[\w-]*|[\w./-]*\.(?:html|md|ya?ml|json|go|tsx?)\b|\b[a-z]+[A-Z]\w*/g;
-
-function Prose({ text }: { text?: string }) {
- if (!text) return null;
- const parts: React.ReactNode[] = [];
- let last = 0;
-
- for (const match of text.matchAll(IDENTIFIER)) {
- const index = match.index ?? 0;
-
- if (index > last) parts.push(text.slice(last, index));
- parts.push(
-
- {match[0].replace(/^`|`$/g, "")}
- ,
- );
- last = index + match[0].length;
- }
-
- if (last < text.length) parts.push(text.slice(last));
-
- return <>{parts}>;
-}
-
-function FieldTable({ fields }: { fields: TypeFieldDoc[] }) {
- // Source shows only where it differs from the field's name.
- const renamed = fields.some((f) => f.source && f.source !== f.name);
-
- return (
-
-
-
- Name
- Type
- Required
- {renamed ? Source : null}
- Description
-
-
-
- {fields.map((f) => (
-
-
- {humanizeName(f.name)} {" "}
- {humanizeName(f.name).toLowerCase() !== (f.name ?? "").toLowerCase() ? (
- {f.name}
- ) : null}
-
-
- {humanizeName(f.typeName || f.kind || "string")}
- {f.typeName && humanizeName(f.typeName).toLowerCase() !== f.typeName.toLowerCase() ? (
- {f.typeName}
- ) : null}
- {f.list ? "[]" : ""}
- {f.enumValues?.length ? (
-
- {f.enumValues.map((value) => (
-
- {value}
-
- ))}
-
- ) : null}
-
- {f.required ? "yes" : "no"}
- {renamed ? (
-
- {f.source && f.source !== f.name ? (
- {f.source}
- ) : (
- —
- )}
-
- ) : null}
-
-
-
-
- ))}
-
-
- );
-}
-
-function ExampleCard({
- note,
- onSelectType,
-}: {
- note: OntologyNoteListItem;
- onSelectType: (name: string) => void;
-}) {
- const target = publicOntologyListItemRef(note);
- const href = buildNoteWebHref(target);
-
- const previewTrigger = useNotePreviewTrigger({
- target,
- open: openNoteTarget,
- });
-
- const resolved = publicTypeName(note.resolvedType);
- const resolvedAccent = resolved ? typeAccentColor(resolved) : undefined;
- const tags = (note.tags ?? []).slice(0, 3);
-
- return (
-
-
- {note.title || note.path}
-
- {previewTrigger.preview}
-
- {note.path}
-
-
- {resolved ? (
- onSelectType(resolved)}
- >
-
- {resolved}
-
- ) : null}
- {tags.map((tag) => (
-
- #{tag}
-
- ))}
- {note.relationCount ? (
- {note.relationCount} rel
- ) : null}
- {note.hasIssues ? (
-
- ⚠ issues
-
- ) : null}
-
-
- );
-}
diff --git a/web/src/components/OntologyTypeFields.tsx b/web/src/components/OntologyTypeFields.tsx
new file mode 100644
index 000000000..2af3c6d62
--- /dev/null
+++ b/web/src/components/OntologyTypeFields.tsx
@@ -0,0 +1,227 @@
+import "./ontology-refinements.css";
+import { publicTypeName } from "../lib/typeNames";
+import type React from "react";
+
+import { publicOntologyListItemRef } from "../api/client";
+import type { OntologyNoteListItem, TypeFieldDoc } from "../api/types";
+import { humanizeName } from "../lib/labels";
+import { typeAccentColor } from "../lib/typeAccent";
+import { buildNoteWebHref } from "../lib/content";
+
+import { notifyLocationChange } from "./locationStore";
+import { useNotePreviewTrigger, type OpenNote } from "./notePreview/NoteLinkPreview";
+
+const openNoteTarget: OpenNote = (target, mode) => {
+ const href = buildNoteWebHref(target);
+
+ if (mode === "beside") {
+ window.open(href, "_blank", "noopener,noreferrer");
+
+ return;
+ }
+
+ window.history.pushState({}, "", href);
+ notifyLocationChange();
+};
+
+export function TargetChip({
+ name,
+ list,
+ onSelect,
+ role,
+}: {
+ name: string;
+ list: boolean;
+ onSelect: (name: string) => void;
+ role?: string;
+}) {
+ const accent = typeAccentColor(name);
+
+ return (
+ onSelect(name)}
+ title={role ? `${role}: ${name}` : name}
+ >
+
+ {humanizeName(name)}
+
+ {name}
+ {list ? "[]" : ""}
+
+
+ );
+}
+
+/** A relation's direction in lowercase with its arrow: "← inbound", "→ outbound". */
+export function directionLabel(direction?: string) {
+ if (!direction) return — ;
+ const value = direction.toLowerCase();
+
+ const arrow =
+ value === "inbound" ? "← " : value === "outbound" ? "→ " : value === "both" ? "↔ " : "";
+
+ return `${arrow}${value}`;
+}
+
+/**
+ * Identifiers and example values inside schema prose: IDs such as
+ * EFF-2026-08-05-14-32, file names, paths, camelCase names, and backticked
+ * code. Each renders as one unbreakable mono span, so a column never splits
+ * one mid-token.
+ */
+const IDENTIFIER =
+ /`[^`]+`|\b[A-Z][A-Z0-9]*-[\w-]*\d[\w-]*|[\w./-]*\.(?:html|md|ya?ml|json|go|tsx?)\b|\b[a-z]+[A-Z]\w*/g;
+
+export function Prose({ text }: { text?: string }) {
+ if (!text) return null;
+ const parts: React.ReactNode[] = [];
+ let last = 0;
+
+ for (const match of text.matchAll(IDENTIFIER)) {
+ const index = match.index ?? 0;
+
+ if (index > last) parts.push(text.slice(last, index));
+ parts.push(
+
+ {match[0].replace(/^`|`$/g, "")}
+ ,
+ );
+ last = index + match[0].length;
+ }
+
+ if (last < text.length) parts.push(text.slice(last));
+
+ return <>{parts}>;
+}
+
+export function FieldTable({ fields }: { fields: TypeFieldDoc[] }) {
+ // Source shows only where it differs from the field's name.
+ const renamed = fields.some((f) => f.source && f.source !== f.name);
+
+ return (
+
+
+
+ Name
+ Type
+ Required
+ {renamed ? Source : null}
+ Description
+
+
+
+ {fields.map((f) => (
+
+
+ {humanizeName(f.name)} {" "}
+ {humanizeName(f.name).toLowerCase() !== (f.name ?? "").toLowerCase() ? (
+ {f.name}
+ ) : null}
+
+
+ {humanizeName(f.typeName || f.kind || "string")}
+ {f.typeName && humanizeName(f.typeName).toLowerCase() !== f.typeName.toLowerCase() ? (
+ {f.typeName}
+ ) : null}
+ {f.list ? "[]" : ""}
+ {f.enumValues?.length ? (
+
+ {f.enumValues.map((value) => (
+
+ {value}
+
+ ))}
+
+ ) : null}
+
+ {f.required ? "yes" : "no"}
+ {renamed ? (
+
+ {f.source && f.source !== f.name ? (
+ {f.source}
+ ) : (
+ —
+ )}
+
+ ) : null}
+
+
+
+
+ ))}
+
+
+ );
+}
+
+export function ExampleCard({
+ note,
+ onSelectType,
+}: {
+ note: OntologyNoteListItem;
+ onSelectType: (name: string) => void;
+}) {
+ const target = publicOntologyListItemRef(note);
+ const href = buildNoteWebHref(target);
+
+ const previewTrigger = useNotePreviewTrigger({
+ target,
+ open: openNoteTarget,
+ });
+
+ const resolved = publicTypeName(note.resolvedType);
+ const resolvedAccent = resolved ? typeAccentColor(resolved) : undefined;
+ const tags = (note.tags ?? []).slice(0, 3);
+
+ return (
+
+
+ {note.title || note.path}
+
+ {previewTrigger.preview}
+
+ {note.path}
+
+
+ {resolved ? (
+ onSelectType(resolved)}
+ >
+
+ {resolved}
+
+ ) : null}
+ {tags.map((tag) => (
+
+ #{tag}
+
+ ))}
+ {note.relationCount ? (
+ {note.relationCount} rel
+ ) : null}
+ {note.hasIssues ? (
+
+ ⚠ issues
+
+ ) : null}
+
+
+ );
+}
diff --git a/web/src/components/OntologyTypeNode.tsx b/web/src/components/OntologyTypeNode.tsx
index ef86b960e..0ce3e2ef4 100644
--- a/web/src/components/OntologyTypeNode.tsx
+++ b/web/src/components/OntologyTypeNode.tsx
@@ -1,10 +1,10 @@
import { Handle, type NodeProps, Position } from "@xyflow/react";
import { Repeat2 } from "lucide-react";
+import "./ontology-refinements.css";
import { Fragment } from "react";
import {
IMPL_SOURCE_LEFT_HANDLE,
IMPL_SOURCE_RIGHT_HANDLE,
- nameLines,
type OntologyNodeData,
relationSourceHandle,
TYPE_TARGET_LEFT_HANDLE,
@@ -98,11 +98,7 @@ export function OntologyTypeNode({ data }: Props) {
onClick={handleTypeLinkClick}
title={cardTitle(data)}
>
-
- {nameLines(typeLabel(data.name)).map((line, index) =>
- line ? {line} : null,
- )}
-
+ {typeLabel(data.name)}
{self.length > 0 ? (
= [
+ {
+ role: "note",
+ docs: (atlas.types ?? []).flatMap((entry) => (entry.type ? [entry.type] : [])),
+ },
+ { role: "interface", docs: atlas.interfaces ?? [] },
+ { role: "section", docs: atlas.sections ?? [] },
+ ];
+
+ for (const { role, docs } of sources) {
+ for (const doc of docs) {
+ if (!doc?.name || doc.name === targetName) continue;
+
+ for (const field of doc.fields ?? []) {
+ if (!isRelationField(field)) continue;
+
+ if (field.typeName !== targetName) continue;
+ refs.push({
+ fromType: doc.name,
+ fromRole: doc.role || role,
+ fieldName: field.name ?? "",
+ direction: field.direction,
+ list: field.list,
+ description: field.description,
+ });
+ }
+ }
+ }
+
+ return refs.sort((a, b) => {
+ if (a.fromType === b.fromType) return a.fieldName.localeCompare(b.fieldName);
+
+ return a.fromType.localeCompare(b.fromType);
+ });
+}
+
+function collectImplementors(
+ atlas: OntologyAtlasResponse | null,
+ interfaceName: string,
+): OntologyAtlasTypeEntry[] {
+ if (!atlas) return [];
+ const entries = atlas.types ?? [];
+
+ return entries.filter((entry) => (entry.type?.implements ?? []).includes(interfaceName));
+}
+
+export function TypeDetailBody({
+ data,
+ atlas,
+ onSelectType,
+}: {
+ data: OntologyTypeResponse;
+ atlas: OntologyAtlasResponse | null;
+ onSelectType: (name: string) => void;
+}) {
+ const type = data.type;
+ const typeName = type?.name ?? "";
+
+ const isInterface = useMemo(() => {
+ if (!typeName) return false;
+
+ if (type?.role === "interface") return true;
+
+ return (atlas?.interfaces ?? []).some((iface) => iface.name === typeName);
+ }, [atlas, type?.role, typeName]);
+
+ const implementors = useMemo(
+ () => (isInterface ? collectImplementors(atlas, typeName) : []),
+ [atlas, isInterface, typeName],
+ );
+
+ const inboundRefs = useMemo(
+ () => (typeName ? collectInboundRefs(atlas, typeName) : []),
+ [atlas, typeName],
+ );
+
+ if (!type?.name) {
+ return Type not found.
;
+ }
+
+ const fields = type.fields ?? [];
+ const scalarFields = fields.filter((f) => !isRelationField(f));
+ const relationFields = fields.filter(isRelationField);
+ // A Direction column shows only when some row has one.
+ const relationDirections = relationFields.some((f) => f.direction);
+ const inboundDirections = inboundRefs.some((ref) => ref.direction);
+ const examples = (data.notes ?? []).slice(0, 6);
+
+ return (
+ <>
+ {type.description ? (
+
+
+
+ ) : null}
+
+ {data.issueCount ? (
+
+
Issues
+ {data.issueCount}
+
+ ) : null}
+ {type.locator ? (
+
+
Locator
+
+ {type.locator}
+
+
+ ) : null}
+ {type.propertyCase ? (
+
+
Property case
+ {type.propertyCase}
+
+ ) : null}
+ {type.implements?.length ? (
+
+
Implements
+
+
+ {type.implements.map((iface) => (
+ onSelectType(iface)}
+ >
+ {humanizeName(iface)}
+
+ ))}
+
+
+
+ ) : null}
+
+
+ {isInterface ? (
+
+ Implementors
+ {implementors.length === 0 ? (
+
+ No types declare implements {typeName} yet.
+
+ ) : (
+
+ {implementors.map((entry) => {
+ const implType = entry.type;
+
+ if (!implType?.name) return null;
+ const implName = implType.name;
+ const implAccent = typeAccentColor(implName);
+
+ return (
+
+ onSelectType(implName)}
+ >
+
+
+
+
+ {humanizeName(implType.name)}
+
+
+ {implType.name}
+
+
+ {entry.count ?? 0}
+
+ {implType.description ? (
+
+
+
+ ) : null}
+
+
+ );
+ })}
+
+ )}
+
+ ) : null}
+
+ {type.matches?.length || type.paths?.length ? (
+
+ How Rhizome recognizes it
+
+ {type.paths?.length ? (
+
+
Paths
+
+ {type.paths.map((p) => (
+
+ {p}
+
+ ))}
+
+
+ ) : null}
+ {type.matches?.length ? (
+
+
Matches
+
+ {type.matches.map((m) => (
+
+ {m}
+
+ ))}
+
+
+ ) : null}
+
+
+ ) : null}
+
+ {scalarFields.length ? (
+
+ ) : null}
+
+ {relationFields.length ? (
+
+ Typed relations
+
+
+
+ Field
+ Target
+ {relationDirections ? Direction : null}
+ Description
+
+
+
+ {relationFields.map((f) => (
+
+
+ {humanizeName(f.name)} {" "}
+ {humanizeName(f.name).toLowerCase() !== (f.name ?? "").toLowerCase() ? (
+ {f.name}
+ ) : null}
+
+
+ {f.typeName ? (
+
+ ) : (
+ "—"
+ )}
+
+ {relationDirections ? {directionLabel(f.direction)} : null}
+
+
+
+
+ ))}
+
+
+
+ ) : null}
+
+ {inboundRefs.length ? (
+
+ Referenced by
+
+
+
+ From type
+ Field
+ {inboundDirections ? Direction : null}
+ Description
+
+
+
+ {inboundRefs.map((ref) => (
+
+
+
+
+
+
+ {ref.fieldName}
+ {ref.list ? "[]" : ""}
+
+
+ {inboundDirections ? {directionLabel(ref.direction)} : null}
+
+
+
+
+ ))}
+
+
+
+ ) : null}
+
+ {type.companionDocs?.length ? (
+
+ ) : null}
+
+
+
+ Examples
+ {data.count > examples.length ? (
+
+ See all {data.count} →
+
+ ) : null}
+
+ {examples.length === 0 ? (
+ No notes of this type are indexed yet.
+ ) : (
+
+ {examples.map((note) => (
+
+ ))}
+
+ )}
+
+ >
+ );
+}
diff --git a/web/src/components/OntologyTypeSchema.tsx b/web/src/components/OntologyTypeSchema.tsx
new file mode 100644
index 000000000..c9fbcc36b
--- /dev/null
+++ b/web/src/components/OntologyTypeSchema.tsx
@@ -0,0 +1,476 @@
+import "./ontology-refinements.css";
+
+import type React from "react";
+
+import { isJsonObject, type JsonObject, type JsonValue } from "../api/parse";
+
+import type {
+ EnumDoc,
+ EnumValueDoc,
+ OntologyTypeResponse,
+ TypeDoc,
+ TypeFieldDoc,
+} from "../api/types";
+import { humanizeName } from "../lib/labels";
+
+import { Markdown } from "./markdown/Markdown";
+
+export function SchemaPanel({ data }: { data: OntologyTypeResponse }) {
+ const type = data.type;
+
+ if (!type?.name) {
+ return (
+
+ No schema data available for this type.
+
+ );
+ }
+
+ const enums = type.enums ?? [];
+ const fields = type.fields ?? [];
+
+ return (
+
+
+
+
+ {(() => {
+ const typeDirectives = Object.entries(type.annotations ?? {}).filter(
+ ([name]) => name !== "guidance",
+ );
+
+ return typeDirectives.length > 0 ? (
+
+
Directives
+
+ {typeDirectives.map(([name, args]) => (
+
+ ))}
+
+
+ ) : null;
+ })()}
+ {fields.length > 0 ? (
+
+
Fields
+
+ {fields.map((field) => (
+
+ ))}
+
+
+ ) : null}
+ {enums.length > 0 ? (
+
+
Enums
+
+ {enums.map((enumDoc) => (
+
+ ))}
+
+
+ ) : null}
+
+ );
+}
+
+type GuidanceBundle = {
+ summary?: string;
+ meaning?: string;
+ authoring?: string;
+ agentImplications?: string;
+};
+
+function guidanceFromType(type: TypeDoc): GuidanceBundle {
+ return {
+ summary: valueOrUndefined(type.summary),
+ meaning: valueOrUndefined(type.meaning),
+ authoring: valueOrUndefined(type.authoring),
+ agentImplications: valueOrUndefined(type.agentImplications),
+ };
+}
+
+function guidanceFromField(field: TypeFieldDoc): GuidanceBundle {
+ return {
+ summary: valueOrUndefined(field.summary),
+ meaning: valueOrUndefined(field.meaning),
+ authoring: valueOrUndefined(field.authoring),
+ agentImplications: valueOrUndefined(field.agentImplications),
+ };
+}
+
+function guidanceFromEnumLike(value: EnumDoc | EnumValueDoc): GuidanceBundle {
+ return {
+ summary: valueOrUndefined(value.summary),
+ meaning: valueOrUndefined(value.meaning),
+ authoring: valueOrUndefined(value.authoring),
+ agentImplications: valueOrUndefined(value.agentImplications),
+ };
+}
+
+function valueOrUndefined(s?: string): string | undefined {
+ const trimmed = (s ?? "").trim();
+
+ return trimmed === "" ? undefined : trimmed;
+}
+
+function hasGuidance(g: GuidanceBundle): boolean {
+ return Boolean(g.summary || g.meaning || g.authoring || g.agentImplications);
+}
+
+function TypeSchemaHeader({ type }: { type: TypeDoc }) {
+ const chips: Array<{ label: string; value: string; kind?: string }> = [];
+
+ if (type.role) chips.push({ label: "role", value: type.role });
+
+ if (type.semantics) chips.push({ label: "semantics", value: type.semantics });
+
+ if (type.locator) chips.push({ label: "locator", value: type.locator });
+
+ if (type.propertyCase) chips.push({ label: "propertyCase", value: type.propertyCase });
+
+ if (type.keyField) chips.push({ label: "keyField", value: type.keyField });
+
+ return (
+
+
+ {type.role === "interface" ? "interface" : "type"}
+ {type.name}
+ {type.implements?.length ? (
+ <>
+ implements
+ {type.implements.join(" & ")}
+ >
+ ) : null}
+
+ {chips.length > 0 ? (
+
+ {chips.map((chip) => (
+
+ {chip.label}
+ {chip.value}
+
+ ))}
+
+ ) : null}
+ {type.description ? {type.description}
: null}
+
+ );
+}
+
+function TypeMetaGrid({ type }: { type: TypeDoc }) {
+ const rows: Array<{ label: string; body: React.ReactNode }> = [];
+
+ if (type.label)
+ rows.push({
+ label: "Label",
+ body: {type.label},
+ });
+
+ if (type.pluralLabel)
+ rows.push({
+ label: "Plural label",
+ body: {type.pluralLabel},
+ });
+
+ if (type.color)
+ rows.push({
+ label: "Color",
+ body: (
+
+
+ {type.color}
+
+ ),
+ });
+
+ if (type.paths?.length)
+ rows.push({
+ label: "Paths",
+ body: (
+
+ {type.paths.map((p) => (
+
+ {p}
+
+ ))}
+
+ ),
+ });
+
+ if (type.matches?.length)
+ rows.push({
+ label: "Matches",
+ body: (
+
+ {type.matches.map((m) => (
+
+ {m}
+
+ ))}
+
+ ),
+ });
+
+ if (type.companionDocs?.length)
+ rows.push({
+ label: "Companion docs",
+ body: (
+
+ {type.companionDocs.map((doc) => (
+
+ {doc.path}
+ {doc.purpose ? (
+ · {doc.purpose}
+ ) : null}
+
+ ))}
+
+ ),
+ });
+
+ if (rows.length === 0) return null;
+
+ return (
+
+ {rows.map((row) => (
+
+
{row.label}
+ {row.body}
+
+ ))}
+
+ );
+}
+
+function GuidanceBlock({ guidance }: { guidance: GuidanceBundle }) {
+ if (!hasGuidance(guidance)) return null;
+
+ return (
+
+ {guidance.summary ?
{guidance.summary}
: null}
+ {guidance.meaning ?
: null}
+ {guidance.authoring ?
: null}
+ {guidance.agentImplications ? (
+
+ ) : null}
+
+ );
+}
+
+function GuidanceSection({ label, body }: { label: string; body: string }) {
+ return (
+
+ );
+}
+
+type SchemaDirective = { name: string; args: JsonObject };
+
+function DirectiveChip({ name, args }: { name: string; args: JsonObject }) {
+ const entries = Object.entries(args ?? {}).filter(
+ ([, v]) => v !== undefined && v !== null && v !== "",
+ );
+
+ return (
+
+ @{name}
+ {entries.length > 0 ? (
+
+ (
+ {entries.map(([key, value], i) => (
+
+ {i > 0 ? ", " : ""}
+ {key}
+ {": "}
+ {formatDirectiveValue(value)}
+
+ ))}
+ )
+
+ ) : null}
+
+ );
+}
+
+function formatDirectiveValue(value: JsonValue): string {
+ if (Array.isArray(value)) return `[${value.map(formatDirectiveValue).join(", ")}]`;
+
+ return JSON.stringify(value);
+}
+
+function fieldSignatureType(field: TypeFieldDoc): string {
+ const inner = field.typeName || "?";
+ const base = field.list ? `[${inner}]` : inner;
+
+ return field.required ? `${base}!` : base;
+}
+
+function SchemaFieldCard({ field }: { field: TypeFieldDoc }) {
+ const directives = collectFieldDirectives(field);
+ const guidance = guidanceFromField(field);
+ const enumDoc = field.enum;
+
+ return (
+
+
+
+ {field.name}
+ :
+ {fieldSignatureType(field)}
+
+ {field.kind ? (
+
+ {humanizeName(field.kind)}
+
+ ) : null}
+
+ {directives.length > 0 ? (
+
+ {directives.map((d) => (
+
+ ))}
+
+ ) : null}
+ {field.description && !guidance.summary ? (
+ {field.description}
+ ) : null}
+
+ {enumDoc?.name && (enumDoc.values?.length ?? 0) > 0 ? (
+
+
Values
+
+ {(enumDoc.values ?? []).map((v) => (
+
+ {v.name}
+
+ ))}
+
+
+ ) : null}
+
+ );
+}
+
+function collectFieldDirectives(field: TypeFieldDoc): SchemaDirective[] {
+ const out: SchemaDirective[] = [];
+ const seen = new Set();
+ const fromAnnotations = field.annotations ?? {};
+
+ for (const [name, args] of Object.entries(fromAnnotations)) {
+ if (name === "guidance") continue;
+ out.push({ name, args: isJsonObject(args) ? args : {} });
+ seen.add(name);
+ }
+
+ // Synthesize directive summaries from typed columns when annotations are absent.
+ if (field.kind === "link" && !seen.has("link")) {
+ const args: JsonObject = {};
+
+ if (field.direction) args.direction = field.direction;
+
+ if (field.inverse) args.inverse = field.inverse;
+ out.push({ name: "link", args });
+ }
+
+ if (field.kind === "reverse" && !seen.has("reverse")) {
+ out.push({ name: "reverse", args: field.reverseField ? { field: field.reverseField } : {} });
+ }
+
+ if (field.kind === "neighbor" && !seen.has("neighbors")) {
+ const args: JsonObject = {};
+
+ if (field.direction) args.direction = field.direction;
+
+ if (field.scope) args.scope = field.scope;
+
+ if (field.includeBodyLinks) args.includeBodyLinks = true;
+
+ if (field.includeBacklinks) args.includeBacklinks = true;
+ out.push({ name: "neighbors", args });
+ }
+
+ if (field.kind === "section" && !seen.has("section")) {
+ const args: JsonObject = {};
+
+ if (field.sectionHeading) args.heading = field.sectionHeading;
+
+ if (field.sectionLevel) args.level = field.sectionLevel;
+
+ if (field.sectionRequired) args.required = true;
+
+ if (field.sectionDisplay) args.display = field.sectionDisplay;
+ out.push({ name: "section", args });
+ }
+
+ if (
+ (field.kind === "scalar" || field.kind === "field") &&
+ !seen.has("field") &&
+ (field.source || field.sourceKind)
+ ) {
+ const args: JsonObject = {};
+
+ if (field.source) args.source = field.source;
+
+ if (field.sourceKind) args.sourceKind = field.sourceKind;
+
+ if (field.sourceAliases?.length) args.aliases = field.sourceAliases;
+ out.push({ name: "field", args });
+ }
+
+ if (field.semantics && !seen.has("semantics")) {
+ out.push({ name: "semantics", args: { kind: field.semantics } });
+ }
+
+ if (isJsonObject(field.policy)) {
+ out.push({ name: "policy", args: field.policy });
+ }
+
+ return out;
+}
+
+function SchemaEnumCard({ enum: enumDoc }: { enum: EnumDoc }) {
+ const guidance = guidanceFromEnumLike(enumDoc);
+ const values = enumDoc.values ?? [];
+
+ return (
+
+
+ enum
+ {enumDoc.name}
+
+
+ {values.length > 0 ? (
+
+ {values.map((v) => {
+ const vGuidance = guidanceFromEnumLike(v);
+
+ return (
+
+ {v.name}
+ {vGuidance.summary ? (
+ {vGuidance.summary}
+ ) : null}
+ {vGuidance.meaning || vGuidance.authoring || vGuidance.agentImplications ? (
+
+
+
+ ) : null}
+
+ );
+ })}
+
+ ) : null}
+
+ );
+}
diff --git a/web/src/components/RailTree.tsx b/web/src/components/RailTree.tsx
index 7dc03989f..073d1499a 100644
--- a/web/src/components/RailTree.tsx
+++ b/web/src/components/RailTree.tsx
@@ -14,7 +14,7 @@ import {
useState,
} from "react";
-import { typeAccentColor } from "../lib/typeAccent";
+import { typeAccentColor, useTypePalette } from "../lib/typeAccent";
import { DisclosureChevron } from "./DisclosureChevron";
import { decodeJson, isBoolean, isJsonObject } from "../api/parse";
import { flattenRailNodes, label, type RailGroup, type RailNode } from "./noteRailGroups";
@@ -332,6 +332,7 @@ export function TypeTree({
validationScopes,
);
+ useTypePalette();
const health = validationHealth(validationQuery.data ?? null);
const renderNode = (node: RailNode, depth = 0) => {
diff --git a/web/src/components/SearchResults.tsx b/web/src/components/SearchResults.tsx
new file mode 100644
index 000000000..7a6d0fc49
--- /dev/null
+++ b/web/src/components/SearchResults.tsx
@@ -0,0 +1,404 @@
+import { useEffect, useId, useMemo, useState, type ReactNode } from "react";
+import { DisclosureChevron } from "./DisclosureChevron";
+import { MiddleTruncate } from "./MiddleTruncate";
+import { noteExcerptParts } from "./searchExcerpt";
+import { publicTypeName } from "../lib/typeNames";
+import { humanizeName } from "../lib/labels";
+import { publicOntologyListItemRef, publicWorkspaceRef } from "../api/client";
+import type { WorkspaceSearchMatch } from "../api/types";
+import { PSEUDO_TYPE_ALL } from "./notesRoute";
+import { useOntologyTypeQuery } from "./useNotesQueries";
+import { notifyLocationChange } from "./locationStore";
+import { useNotePreviewTrigger } from "./notePreview/NoteLinkPreview";
+import {
+ ROOT_FOLDER,
+ folderLabel,
+ inFolder,
+ normalizeSearchFilters,
+ normalizeSearchQuery,
+ useSearchScrollRestoration,
+} from "./searchState";
+import type { SearchWorkspaceProps } from "./SearchWorkspace";
+
+function highlightLiteral(text: string, query: string) {
+ const terms = normalizeSearchQuery(query)
+ .split(" ")
+ .filter(Boolean)
+ .map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
+
+ if (terms.length === 0) return text;
+ const matcher = new RegExp(`(${terms.join("|")})`, "gi");
+
+ return text
+ .split(matcher)
+ .map((part, index) => (index % 2 === 1 ? {part} : part));
+}
+
+function excerptFor(match: WorkspaceSearchMatch): string | null {
+ if (match.snippetStatus !== "available") return null;
+ const value = match.snippet || "";
+
+ return value.trim() ? value.trim() : null;
+}
+
+// A code preview joins a symbol's signature and its doc comment with " — ".
+// The signature keeps its source lines; the comment reads as one paragraph.
+function codeExcerptParts(excerpt: string) {
+ const at = excerpt.indexOf(" — ");
+
+ if (at < 0) return { signature: excerpt, doc: "" };
+
+ return { signature: excerpt.slice(0, at), doc: excerpt.slice(at + 3).replace(/\s+/g, " ") };
+}
+
+// What the match is, from the result itself: a code symbol's kind or a note
+// section. The payload carries no per-match retrieval evidence.
+function matchedAs(match: WorkspaceSearchMatch): string {
+ if (match.type === "code") return match.kind ? `${humanizeName(match.kind)} symbol` : "";
+
+ return match.nodeKind?.toUpperCase() === "SECTION" ? "Section" : "";
+}
+
+export function SearchBanner({
+ tone = "status",
+ details = [],
+ action,
+ children,
+}: {
+ tone?: "status" | "alert";
+ details?: string[];
+ action?: ReactNode;
+ children: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const detailsId = useId();
+
+ return (
+
+
+
+
+
+
+
+
+ {children}
+
+ {action}
+ {details.length > 0 ? (
+
setOpen((value) => !value)}
+ >
+ {open ? "Hide details" : "Details"}
+
+ ) : null}
+
+ {details.length > 0 ? (
+
+ {details.map((detail) => (
+ {detail}
+ ))}
+
+ ) : null}
+
+ );
+}
+
+function resultLabel(match: WorkspaceSearchMatch): string {
+ return match.title || match.symbol || match.fqn || match.path || "Untitled result";
+}
+
+/** A provenance path that gives way in the middle, keeping its file name and line. */
+function SourcePath({ path }: { path: string }) {
+ return ;
+}
+
+function sourceLabel(match: WorkspaceSearchMatch): string {
+ if (match.type === "code") return match.path || "Code source";
+
+ return match.path || "Note source";
+}
+
+function isNoteMatch(match: WorkspaceSearchMatch): boolean {
+ return match.type === "note" || match.path?.toLowerCase().endsWith(".md") === true;
+}
+
+function noteTargetForMatch(match: WorkspaceSearchMatch): string {
+ const ref = match.linkTarget?.ref || match.nodeRef;
+
+ return ref ? publicWorkspaceRef(ref) : match.path || "";
+}
+
+function openCodeSource(path: string, line?: number) {
+ if (!path) return;
+ const params = new URLSearchParams({ file: path });
+
+ if (line && line > 0) params.set("line", String(line));
+ window.history.pushState({}, "", `/explorer?${params.toString()}`);
+ notifyLocationChange();
+}
+
+function NoteResultLink({
+ target,
+ children,
+ onOpenNote,
+}: {
+ target: string;
+ children: ReactNode;
+ onOpenNote: SearchWorkspaceProps["onOpenNote"];
+}) {
+ const previewTrigger = useNotePreviewTrigger({
+ target,
+ open: (path, mode) => onOpenNote(path, mode === "beside" ? "beside" : "activate"),
+ });
+
+ return (
+ <>
+ {
+ previewTrigger.close();
+ onOpenNote(target, event.metaKey || event.ctrlKey ? "beside" : "activate");
+ }}
+ >
+ {children}
+
+ {previewTrigger.preview}
+ >
+ );
+}
+
+export function FolderNotesWorkspace({
+ tab,
+ active,
+ restoreReady = true,
+ editSession = null,
+ onRefineSearch,
+ onOpenNote,
+ onScrollPosition,
+}: SearchWorkspaceProps) {
+ const folder = tab.filters.folder || "";
+ const [folderDraft, setFolderDraft] = useState(folder);
+ const [queryDraft, setQueryDraft] = useState("");
+ const notesQuery = useOntologyTypeQuery(PSEUDO_TYPE_ALL, editSession, active);
+
+ const scrollRef = useSearchScrollRestoration(
+ tab,
+ active,
+ restoreReady && Boolean(notesQuery.data),
+ );
+
+ useEffect(() => {
+ setFolderDraft(folder);
+ }, [tab.id, folder]);
+
+ const notes = useMemo(
+ () =>
+ (notesQuery.data?.notes ?? [])
+ .filter((note) => inFolder(note.path, folder))
+ .sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0)),
+ [folder, notesQuery.data?.notes],
+ );
+
+ const applyFolder = () => {
+ // Clearing the folder would leave nothing to list, so the field reverts instead.
+ if (!normalizeSearchFilters({ folder: folderDraft }).folder) setFolderDraft(folder);
+ else onRefineSearch(tab.id, { ...tab.filters, folder: folderDraft });
+ };
+
+ const submitQuery = () => {
+ if (normalizeSearchQuery(queryDraft)) onRefineSearch(tab.id, tab.filters, queryDraft);
+ };
+
+ return (
+ {
+ if (active) onScrollPosition(tab.id, event.currentTarget.scrollTop);
+ }}
+ >
+
+ {notesQuery.isError && !notesQuery.data ? (
+
+ Notes unavailable
+ The workspace could not list this folder's notes.
+ void notesQuery.refetch()}>
+ Retry
+
+
+ ) : notesQuery.isPending ? (
+
+ Loading notes…
+
+ ) : notes.length === 0 ? (
+
+ No notes in {folderLabel(folder)}
+
+ ) : (
+
+ {notes.map((note) => (
+
+
+
+ {note.title || note.path}
+
+
+
+ Note ·{" "}
+ {humanizeName(publicTypeName(note.resolvedType)) || "Untyped"}
+
+ ·
+
+
+
+
+ ))}
+
+ )}
+
+ );
+}
+
+export function RankedResults({
+ matches,
+ query,
+ onOpenNote,
+}: {
+ matches: WorkspaceSearchMatch[];
+ query: string;
+ onOpenNote: SearchWorkspaceProps["onOpenNote"];
+}) {
+ return matches.map((match, index) => {
+ const excerpt = excerptFor(match);
+ const line = match.startLine && match.startLine > 0 ? match.startLine : undefined;
+
+ return (
+
+
+ {isNoteMatch(match) ? (
+
+ {highlightLiteral(resultLabel(match), query)}
+
+ ) : (
+ openCodeSource(match.path || "", line)}
+ >
+ {highlightLiteral(resultLabel(match), query)}
+
+ )}
+
+
+ {[
+ humanizeName(match.type) || "Source",
+ humanizeName(publicTypeName(match.noteType)),
+ matchedAs(match),
+ match.heading !== resultLabel(match) ? match.heading : "",
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+
+ ·
+
+
+ {excerpt && match.type === "code" ? (
+
+ ) : (
+
+ {excerpt
+ ? noteExcerptParts(excerpt).map((part, partIndex) =>
+ part.code ? (
+ // oxlint-disable-next-line react/no-array-index-key -- parts have no identity beyond order
+ {highlightLiteral(part.text, query)}
+ ) : (
+ highlightLiteral(part.text, query)
+ ),
+ )
+ : "Excerpt unavailable."}
+
+ )}
+
+
+ );
+ });
+}
+
+function CodeExcerpt({ excerpt, query }: { excerpt: string; query: string }) {
+ const { signature, doc } = codeExcerptParts(excerpt);
+ const [expanded, setExpanded] = useState(false);
+ const lines = signature.split("\n");
+ const truncated = lines.length > 3;
+ const visible = truncated && !expanded ? lines.slice(0, 3).join("\n") : signature;
+
+ return (
+ <>
+ {highlightLiteral(visible, query)}
+ {truncated && (
+ setExpanded((value) => !value)}
+ >
+
+ {expanded ? "Show less" : "Show more"}
+
+ )}
+ {doc && {highlightLiteral(doc, query)}
}
+ >
+ );
+}
diff --git a/web/src/components/SearchWorkspace.test.tsx b/web/src/components/SearchWorkspace.test.tsx
index c96a77c1c..669846a98 100644
--- a/web/src/components/SearchWorkspace.test.tsx
+++ b/web/src/components/SearchWorkspace.test.tsx
@@ -319,6 +319,7 @@ describe("SearchWorkspace", () => {
renderSearch({
count: 1,
total: 3,
+ policy: { candidateWindow: 3 },
targetStatus: "inferred_symbol",
confidence: { level: "medium", reason: "one strong source" },
coverage: { missing: ["tests"] },
@@ -334,7 +335,8 @@ describe("SearchWorkspace", () => {
});
const status = await screen.findByLabelText("Search status");
- expect(status).toHaveTextContent("Showing 1 of 3 results");
+ expect(status).toHaveTextContent("Showing 1");
+ expect(status).toHaveTextContent("Showing 1 of 3 results (search limit)");
expect(status).toHaveTextContent("Exact symbol");
expect(status).toHaveTextContent("Medium confidence");
expect(status).toHaveTextContent("Missing: tests");
diff --git a/web/src/components/SearchWorkspace.tsx b/web/src/components/SearchWorkspace.tsx
index b446dc11a..9e33dd842 100644
--- a/web/src/components/SearchWorkspace.tsx
+++ b/web/src/components/SearchWorkspace.tsx
@@ -1,43 +1,14 @@
-import { DisclosureChevron } from "./DisclosureChevron";
import { InfoTip } from "./InfoTip";
-import { MiddleTruncate } from "./MiddleTruncate";
-import { noteExcerptParts } from "./searchExcerpt";
-import { publicTypeName } from "../lib/typeNames";
-import { humanizeName } from "../lib/labels";
-import {
- useEffect,
- useEffectEvent,
- useId,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
- type ReactNode,
-} from "react";
+import { useEffect, useMemo, useState } from "react";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
-
-import {
- ApiError,
- publicOntologyListItemRef,
- publicWorkspaceRef,
- searchWorkspace,
-} from "../api/client";
-import type { OntologyTypeSummary, WorkspaceSearchMatch } from "../api/types";
+import { ApiError, searchWorkspace } from "../api/client";
+import type { OntologyTypeSummary } from "../api/types";
import { queryKeys } from "../api/queryKeys";
import type { StagedSession } from "../staging/stagedQuery";
-import { PSEUDO_TYPE_ALL } from "./notesRoute";
-import { useOntologyTypeQuery } from "./useNotesQueries";
-import { notifyLocationChange } from "./locationStore";
-import { useNotePreviewTrigger } from "./notePreview/NoteLinkPreview";
import type { OpenMode, SearchTab } from "./useNoteTabs";
-import {
- ROOT_FOLDER,
- folderLabel,
- inFolder,
- normalizeSearchFilters,
- normalizeSearchQuery,
- type SearchFilters,
-} from "./searchState";
+import { normalizeSearchFilters, type SearchFilters } from "./searchState";
+import { useSearchScrollRestoration } from "./searchState";
+import { SearchBanner, FolderNotesWorkspace, RankedResults } from "./SearchResults";
const PAGE_SIZE = 40;
@@ -50,168 +21,7 @@ const TARGET_STATUS_LABELS = new Map([
["unresolved", "Target unresolved"],
]);
-function highlightLiteral(text: string, query: string) {
- const terms = normalizeSearchQuery(query)
- .split(" ")
- .filter(Boolean)
- .map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
-
- if (terms.length === 0) return text;
- const matcher = new RegExp(`(${terms.join("|")})`, "gi");
-
- return text
- .split(matcher)
- .map((part, index) => (index % 2 === 1 ? {part} : part));
-}
-
-function excerptFor(match: WorkspaceSearchMatch): string | null {
- if (match.snippetStatus !== "available") return null;
- const value = match.snippet || "";
-
- return value.trim() ? value.trim() : null;
-}
-
-// A code preview joins a symbol's signature and its doc comment with " — ".
-// The signature keeps its source lines; the comment reads as one paragraph.
-function codeExcerptParts(excerpt: string) {
- const at = excerpt.indexOf(" — ");
-
- if (at < 0) return { signature: excerpt, doc: "" };
-
- return { signature: excerpt.slice(0, at), doc: excerpt.slice(at + 3).replace(/\s+/g, " ") };
-}
-
-// What the match is, from the result itself: a code symbol's kind or a note
-// section. The payload carries no per-match retrieval evidence.
-function matchedAs(match: WorkspaceSearchMatch): string {
- if (match.type === "code") return match.kind ? `${humanizeName(match.kind)} symbol` : "";
-
- return match.nodeKind?.toUpperCase() === "SECTION" ? "Section" : "";
-}
-
-function SearchBanner({
- tone = "status",
- details = [],
- action,
- children,
-}: {
- tone?: "status" | "alert";
- details?: string[];
- action?: ReactNode;
- children: ReactNode;
-}) {
- const [open, setOpen] = useState(false);
- const detailsId = useId();
-
- return (
-
-
-
-
-
-
-
-
- {children}
-
- {action}
- {details.length > 0 ? (
-
setOpen((value) => !value)}
- >
- {open ? "Hide details" : "Details"}
-
- ) : null}
-
- {details.length > 0 ? (
-
- {details.map((detail) => (
- {detail}
- ))}
-
- ) : null}
-
- );
-}
-
-function resultLabel(match: WorkspaceSearchMatch): string {
- return match.title || match.symbol || match.fqn || match.path || "Untitled result";
-}
-
-/** A provenance path that gives way in the middle, keeping its file name and line. */
-function SourcePath({ path }: { path: string }) {
- return ;
-}
-
-function sourceLabel(match: WorkspaceSearchMatch): string {
- if (match.type === "code") return match.path || "Code source";
-
- return match.path || "Note source";
-}
-
-function isNoteMatch(match: WorkspaceSearchMatch): boolean {
- return match.type === "note" || match.path?.toLowerCase().endsWith(".md") === true;
-}
-
-function noteTargetForMatch(match: WorkspaceSearchMatch): string {
- const ref = match.linkTarget?.ref || match.nodeRef;
-
- return ref ? publicWorkspaceRef(ref) : match.path || "";
-}
-
-function openCodeSource(path: string, line?: number) {
- if (!path) return;
- const params = new URLSearchParams({ file: path });
-
- if (line && line > 0) params.set("line", String(line));
- window.history.pushState({}, "", `/explorer?${params.toString()}`);
- notifyLocationChange();
-}
-
-function NoteResultLink({
- target,
- children,
- onOpenNote,
-}: {
- target: string;
- children: ReactNode;
- onOpenNote: SearchWorkspaceProps["onOpenNote"];
-}) {
- const previewTrigger = useNotePreviewTrigger({
- target,
- open: (path, mode) => onOpenNote(path, mode === "beside" ? "beside" : "activate"),
- });
-
- return (
- <>
- {
- previewTrigger.close();
- onOpenNote(target, event.metaKey || event.ctrlKey ? "beside" : "activate");
- }}
- >
- {children}
-
- {previewTrigger.preview}
- >
- );
-}
-
-type SearchWorkspaceProps = {
+export type SearchWorkspaceProps = {
tab: SearchTab;
active: boolean;
restoreReady?: boolean;
@@ -222,30 +32,6 @@ type SearchWorkspaceProps = {
onScrollPosition: (id: string, scrollTop: number) => void;
};
-function useSearchScrollRestoration(tab: SearchTab, active: boolean, ready: boolean) {
- const scrollRef = useRef(null);
-
- const restoreScroll = useEffectEvent(() => {
- if (scrollRef.current) scrollRef.current.scrollTop = tab.scrollTop;
- });
-
- // Restore on activation or refinement, after content loads. Scroll events only save
- // position: replaying them can rewind native scrolling before React catches up.
- useLayoutEffect(() => {
- if (active && ready) restoreScroll();
- }, [
- active,
- ready,
- tab.id,
- tab.query,
- tab.filters.folder,
- tab.filters.noteType,
- tab.filters.scope,
- ]);
-
- return scrollRef;
-}
-
/** A search tab with no query lists its folder's notes instead of running ranked search. */
export function SearchWorkspace(props: SearchWorkspaceProps) {
return props.tab.query ? (
@@ -255,135 +41,6 @@ export function SearchWorkspace(props: SearchWorkspaceProps) {
);
}
-function FolderNotesWorkspace({
- tab,
- active,
- restoreReady = true,
- editSession = null,
- onRefineSearch,
- onOpenNote,
- onScrollPosition,
-}: SearchWorkspaceProps) {
- const folder = tab.filters.folder || "";
- const [folderDraft, setFolderDraft] = useState(folder);
- const [queryDraft, setQueryDraft] = useState("");
- const notesQuery = useOntologyTypeQuery(PSEUDO_TYPE_ALL, editSession, active);
-
- const scrollRef = useSearchScrollRestoration(
- tab,
- active,
- restoreReady && Boolean(notesQuery.data),
- );
-
- useEffect(() => {
- setFolderDraft(folder);
- }, [tab.id, folder]);
-
- const notes = useMemo(
- () =>
- (notesQuery.data?.notes ?? [])
- .filter((note) => inFolder(note.path, folder))
- .sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0)),
- [folder, notesQuery.data?.notes],
- );
-
- const applyFolder = () => {
- // Clearing the folder would leave nothing to list, so the field reverts instead.
- if (!normalizeSearchFilters({ folder: folderDraft }).folder) setFolderDraft(folder);
- else onRefineSearch(tab.id, { ...tab.filters, folder: folderDraft });
- };
-
- const submitQuery = () => {
- if (normalizeSearchQuery(queryDraft)) onRefineSearch(tab.id, tab.filters, queryDraft);
- };
-
- return (
- {
- if (active) onScrollPosition(tab.id, event.currentTarget.scrollTop);
- }}
- >
-
- {notesQuery.isError && !notesQuery.data ? (
-
- Notes unavailable
- The workspace could not list this folder's notes.
- void notesQuery.refetch()}>
- Retry
-
-
- ) : notesQuery.isPending ? (
-
- Loading notes…
-
- ) : notes.length === 0 ? (
-
- No notes in {folderLabel(folder)}
-
- ) : (
-
- {notes.map((note) => (
-
-
-
- {humanizeName(publicTypeName(note.resolvedType)) || "Untyped"}
-
-
- {note.title || note.path}
-
-
-
-
-
-
- ))}
-
- )}
-
- );
-}
-
function RankedSearchWorkspace({
tab,
active,
@@ -483,10 +140,7 @@ function RankedSearchWorkspace({
const statusSegments: { text: string; info?: string }[] = [
{
- text:
- total !== null
- ? `Showing ${results.length} of ${total} results`
- : `${results.length} results loaded`,
+ text: `Showing ${results.length}${total === null ? "" : ` of ${total}`} results${total !== null && total === response?.policy?.candidateWindow ? " (search limit)" : ""}`,
},
];
@@ -662,65 +316,7 @@ function RankedSearchWorkspace({
{query.isFetching && !query.isFetchingNextPage ? Refreshing… : null}
- {results.map((match, index) => {
- const excerpt = excerptFor(match);
- const line = match.startLine && match.startLine > 0 ? match.startLine : undefined;
-
- return (
-
-
-
- {humanizeName(match.type) || "Source"}
- {publicTypeName(match.noteType)
- ? ` · ${humanizeName(publicTypeName(match.noteType))}`
- : ""}
- {matchedAs(match) ? (
- {matchedAs(match)}
- ) : null}
-
- {isNoteMatch(match) ? (
-
- {highlightLiteral(resultLabel(match), tab.query)}
-
- ) : (
- openCodeSource(match.path || "", line)}
- >
- {highlightLiteral(resultLabel(match), tab.query)}
-
- )}
-
-
- {match.heading && match.heading !== resultLabel(match) ? (
-
- {match.heading}
-
- ) : null}
-
- {excerpt && match.type === "code" ? (
-
- ) : (
-
- {excerpt
- ? noteExcerptParts(excerpt).map((part, partIndex) =>
- part.code ? (
- // oxlint-disable-next-line react/no-array-index-key -- parts have no identity beyond order
-
- {highlightLiteral(part.text, tab.query)}
-
- ) : (
- highlightLiteral(part.text, tab.query)
- ),
- )
- : "Excerpt unavailable."}
-
- )}
-
-
- );
- })}
+
{continuationStale ? (
);
}
-
-function CodeExcerpt({ excerpt, query }: { excerpt: string; query: string }) {
- const { signature, doc } = codeExcerptParts(excerpt);
- const [expanded, setExpanded] = useState(false);
- const lines = signature.split("\n");
- const truncated = lines.length > 3;
- const visible = truncated && !expanded ? lines.slice(0, 3).join("\n") : signature;
-
- return (
- <>
- {highlightLiteral(visible, query)}
- {truncated && (
- setExpanded((value) => !value)}
- >
-
- {expanded ? "Show less" : "Show more"}
-
- )}
- {doc && {highlightLiteral(doc, query)}
}
- >
- );
-}
diff --git a/web/src/components/StatusMark.tsx b/web/src/components/StatusMark.tsx
index ab7f2916a..b3ae64310 100644
--- a/web/src/components/StatusMark.tsx
+++ b/web/src/components/StatusMark.tsx
@@ -7,8 +7,33 @@ type Props = {
export function StatusMark({ tone, label }: Props) {
return (
-
-
+
+
+ {label}
+
+ );
+}
+
+/** A clean validation result; lifecycle success keeps its filled dot. */
+export function ValidationCheck({ label }: { label: string }) {
+ return (
+
+
+
+
+
{label}
);
@@ -27,3 +52,102 @@ export function normalizeStatusTone(tone: string | undefined): StatusTone {
return "neutral";
}
}
+
+/** Status words keep one mark across schema tones and lifecycle positions. */
+export function statusWordTone(word: string, fallback?: string): StatusTone {
+ switch (word.trim().toLowerCase()) {
+ case "active":
+ case "in progress":
+ return "progress";
+ case "complete":
+ case "completed":
+ case "done":
+ case "success":
+ return "success";
+ case "unsaved":
+ case "unsaved changes":
+ return "warning";
+ case "failed":
+ case "failure":
+ case "risk":
+ case "blocked":
+ return "risk";
+ case "draft":
+ case "planned":
+ case "proposed":
+ return "neutral";
+ case "archived":
+ case "dropped":
+ case "cancelled":
+ return "muted";
+ default:
+ return fallback === "danger" ? "risk" : normalizeStatusTone(fallback);
+ }
+}
+
+const TONE_COLOR: Record = {
+ neutral: "var(--text-faint)",
+ info: "var(--info)",
+ progress: "var(--info)",
+ success: "var(--success)",
+ warning: "var(--warning-ink)",
+ risk: "var(--accent)",
+ muted: "var(--text-faint)",
+};
+
+// The host's 9px shape set (DESIGN.md, Status Marks): a hollow ring, a
+// half-filled ring for progress, a filled dot for success, a triangle for a
+// warning, a disc with an exclamation cut out for risk (never the brand
+// diamond), and a dashed ring for a muted value.
+function ToneMark({ tone }: { tone: StatusTone }) {
+ switch (tone) {
+ case "warning":
+ return ;
+ case "risk":
+ // A disc with an exclamation cut out, as the host draws it (base.css).
+ return (
+
+ );
+ case "success":
+ return ;
+ case "info":
+ case "progress":
+ return (
+ <>
+
+
+ >
+ );
+ default:
+ return (
+
+ );
+ }
+}
+
+export function StatusIcon({ tone }: { tone: StatusTone }) {
+ return (
+
+
+
+ );
+}
diff --git a/web/src/components/TreeList.tsx b/web/src/components/TreeList.tsx
index 70dadbe2e..0dc962629 100644
--- a/web/src/components/TreeList.tsx
+++ b/web/src/components/TreeList.tsx
@@ -8,7 +8,11 @@ export function TreeList({
selectedPath,
onSelect,
onToggle,
+ more = {},
+ path = "",
}: {
+ more?: Record;
+ path?: string;
entries: TreeEntry[];
expanded: Record;
selectedPath: string | null;
@@ -57,6 +61,8 @@ export function TreeList({
{isExpanded && expanded[entry.path] && (
);
})}
+ {more[path]}
);
}
diff --git a/web/src/components/TypeChip.tsx b/web/src/components/TypeChip.tsx
new file mode 100644
index 000000000..d50978283
--- /dev/null
+++ b/web/src/components/TypeChip.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from "react";
+import { useTypeAccentColor } from "../lib/typeAccent";
+
+export function TypeChip({
+ name,
+ children,
+ className = "",
+}: {
+ name: string;
+ children: ReactNode;
+ className?: string;
+}) {
+ const color = useTypeAccentColor(name);
+
+ return (
+
+
+ {children}
+
+ );
+}
diff --git a/web/src/components/agent/AgentComposer.test.tsx b/web/src/components/agent/AgentComposer.test.tsx
new file mode 100644
index 000000000..41e1f9bab
--- /dev/null
+++ b/web/src/components/agent/AgentComposer.test.tsx
@@ -0,0 +1,49 @@
+import { createRef } from "react";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AgentComposer } from "./AgentComposer";
+
+const props = {
+ runningID: "",
+ onError: vi.fn(),
+ draft: "",
+ onChange: vi.fn(),
+ onSubmit: vi.fn(),
+ composerRef: createRef(),
+ busy: false,
+ blocked: false,
+ readOnly: false,
+ disabledReason: "",
+ harness: "claude" as const,
+ status: undefined,
+};
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("AgentComposer", () => {
+ it.each([
+ ["MacIntel", "⌘"],
+ ["Linux x86_64", "Ctrl"],
+ ])("shows the %s shortcut in keycaps", (platform, modifier) => {
+ vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
+ render( );
+ expect(screen.getByText(modifier).tagName).toBe("KBD");
+ expect(screen.getByText("↵").tagName).toBe("KBD");
+ expect(screen.getByText(/to send/)).toBeVisible();
+ });
+
+ it("uses the standard disabled button until a message can be sent", () => {
+ const { rerender } = render( );
+ const send = screen.getByRole("button", { name: "Send" });
+ expect(send).toBeDisabled();
+ expect(send).not.toHaveClass("button--primary");
+ rerender( );
+ expect(send).toBeEnabled();
+ expect(send).toHaveClass("button--primary");
+ fireEvent.click(send);
+ expect(props.onSubmit).toHaveBeenCalledWith("Explain this");
+ rerender( );
+ expect(send).toBeDisabled();
+ expect(send).not.toHaveClass("button--primary");
+ });
+});
diff --git a/web/src/components/agent/AgentComposer.tsx b/web/src/components/agent/AgentComposer.tsx
new file mode 100644
index 000000000..9dda315d8
--- /dev/null
+++ b/web/src/components/agent/AgentComposer.tsx
@@ -0,0 +1,104 @@
+import { interruptAgentSession } from "../../api/internalAgentClient";
+import { useLayoutEffect, type RefObject } from "react";
+import type { AgentHarnessKind, AgentHarnessStatus } from "../../api/types";
+import { AgentAvailability } from "./AgentStatusHeader";
+
+export function AgentComposer({
+ runningID,
+ onError,
+ draft,
+ onChange,
+ onSubmit,
+ composerRef,
+ busy,
+ blocked,
+ readOnly,
+ disabledReason,
+ harness,
+ status,
+}: {
+ runningID: string;
+ onError: (message: string) => void;
+ draft: string;
+ onChange: (text: string) => void;
+ onSubmit: (text: string) => void;
+ composerRef: RefObject;
+ busy: boolean;
+ blocked: boolean;
+ readOnly: boolean;
+ disabledReason: string;
+ harness: AgentHarnessKind | undefined;
+ status: AgentHarnessStatus | undefined;
+}) {
+ const canSend = !busy && !blocked && Boolean(draft.trim()) && !readOnly;
+ // The composer grows with its message; CSS caps it, then it scrolls.
+ useLayoutEffect(() => {
+ const field = composerRef.current;
+
+ if (!field) return;
+ field.style.height = "auto";
+ field.style.height = `${field.scrollHeight}px`;
+ }, [draft, composerRef]);
+
+ return (
+ <>
+ {runningID ? (
+ {
+ try {
+ await interruptAgentSession(runningID);
+ } catch (cause) {
+ onError(cause instanceof Error ? cause.message : String(cause));
+ }
+ }}
+ >
+ Interrupt
+
+ ) : null}
+ {
+ event.preventDefault();
+ onSubmit(draft);
+ }}
+ >
+
+
onChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ onSubmit(draft);
+ }
+ }}
+ />
+
+ {disabledReason ? (
+
{disabledReason}
+ ) : blocked || status?.loggedIn === false ? (
+
+ ) : (
+
+ {/Mac/i.test(navigator.platform) ? "⌘" : "Ctrl"} ↵ to send
+
+ )}
+
+ Send
+
+
+
+
+ >
+ );
+}
diff --git a/web/src/components/agent/AgentSettingsPanel.tsx b/web/src/components/agent/AgentSettingsPanel.tsx
index 78ef18a67..0f7876693 100644
--- a/web/src/components/agent/AgentSettingsPanel.tsx
+++ b/web/src/components/agent/AgentSettingsPanel.tsx
@@ -1,7 +1,25 @@
-import type { AgentHarnessKind, AgentHarnessStatus, AgentSettings } from "../../api/types";
+import type {
+ AgentHarnessKind,
+ AgentHarnessStatus,
+ AgentSettings,
+ AgentSettingsResponse,
+} from "../../api/types";
import { humanizeName } from "../../lib/labels";
import { DisclosureChevron } from "../DisclosureChevron";
+const defaultSettings: AgentSettings = {
+ harnesses: {
+ codex: { permissionMode: "approval-required" },
+ claude: { permissionMode: "approval-required" },
+ },
+};
+
+export const emptySettingsResponse: AgentSettingsResponse = {
+ settings: defaultSettings,
+ resolved: { reason: "none available" },
+ harnesses: [],
+};
+
type StatusEntry = { kind: AgentHarnessKind; status: AgentHarnessStatus };
type Props = {
@@ -109,11 +127,15 @@ export function AgentSettingsPanel({
{/* Effort and permission are per-session tuning: behind one disclosure
whose summary still names the active permission. */}
-
+
- Session settings
+ Settings
- {humanizeName(configured.permissionMode)}
+ {configured.permissionMode === "approval-required"
+ ? "Tool approval: ask first"
+ : `Tool approval: ${humanizeName(configured.permissionMode)}`}
diff --git a/web/src/components/agent/AgentStatusHeader.tsx b/web/src/components/agent/AgentStatusHeader.tsx
index ad5a707a1..ef0f426f4 100644
--- a/web/src/components/agent/AgentStatusHeader.tsx
+++ b/web/src/components/agent/AgentStatusHeader.tsx
@@ -1,3 +1,4 @@
+import { StatusMark } from "../StatusMark";
import { useState } from "react";
import { DisclosureChevron } from "../DisclosureChevron";
import type { AgentHarnessKind, AgentHarnessStatus, AgentSession } from "../../api/types";
@@ -8,6 +9,7 @@ type Props = {
status: AgentHarnessStatus | undefined;
resolutionReason: string;
messageCount: number;
+ model: string | undefined;
};
const harnessName = (kind?: AgentHarnessKind) =>
@@ -32,6 +34,7 @@ export function AgentStatusHeader({
status,
resolutionReason,
messageCount,
+ model,
}: Props) {
let state = "Checking harness status…";
@@ -68,7 +71,8 @@ export function AgentStatusHeader({
) : null}
- {harnessName(session?.harness || harness)} · {state}
+ {harnessName(session?.harness || harness)} · {model ? `${model} · ` : ""}
+ {state === "Ready" ? : state}
{details.length ? (
diff --git a/web/src/components/agent/ExamplePrompts.tsx b/web/src/components/agent/ExamplePrompts.tsx
new file mode 100644
index 000000000..f19cd166e
--- /dev/null
+++ b/web/src/components/agent/ExamplePrompts.tsx
@@ -0,0 +1,26 @@
+import { ArrowRight } from "lucide-react";
+
+const EXAMPLE_PROMPTS = [
+ "What changed in this repository this week?",
+ "Which notes explain how search ranks results?",
+ "List the open action items and who owns them.",
+];
+
+/** An empty thread offers a few starting questions; picking one fills the composer. */
+export function ExamplePrompts({ onPick }: { onPick: (text: string) => void }) {
+ return (
+
+
Try asking
+
+ {EXAMPLE_PROMPTS.map((prompt) => (
+
+ onPick(prompt)}>
+ {prompt}
+
+
+
+ ))}
+
+
+ );
+}
diff --git a/web/src/components/body/ChildSectionDisclosure.tsx b/web/src/components/body/ChildSectionDisclosure.tsx
index 19061d384..81b11668e 100644
--- a/web/src/components/body/ChildSectionDisclosure.tsx
+++ b/web/src/components/body/ChildSectionDisclosure.tsx
@@ -1,3 +1,4 @@
+import { EditablePropertyMark } from "./EditablePropertyMark";
import { ChevronRight } from "lucide-react";
import { createElement, type MouseEvent } from "react";
import { publicWorkspaceRef } from "../../api/client";
@@ -48,6 +49,7 @@ export function ChildSectionDisclosure({ block, context }: BodyRendererProps) {
{createElement(
headingTag(child),
{ className: "body-disclosure__heading" },
+ context.mode === "edit" && !editElsewhere &&
,
,
identity.id &&
{identity.id} ,
{identity.title} ,
diff --git a/web/src/components/body/ChildSectionInline.tsx b/web/src/components/body/ChildSectionInline.tsx
index 503b6642a..5d7b9f22b 100644
--- a/web/src/components/body/ChildSectionInline.tsx
+++ b/web/src/components/body/ChildSectionInline.tsx
@@ -1,3 +1,4 @@
+import { EditablePropertyMark } from "./EditablePropertyMark";
import { createElement } from "react";
import { isContentNode, type NodeBodyBlock, type WorkspaceNode } from "../../api/types";
import { BodyWalker } from "./BodyWalker";
@@ -40,6 +41,7 @@ export function ChildSectionInline({ block, context }: BodyRendererProps) {
createElement(
headingTag(child),
{ className: "body-section__title" },
+ context.mode === "edit" && !editElsewhere &&
,
title,
structural && (
+
+
+ );
+}
diff --git a/web/src/components/body/NoteInfoRows.tsx b/web/src/components/body/NoteInfoRows.tsx
new file mode 100644
index 000000000..1fac6dac6
--- /dev/null
+++ b/web/src/components/body/NoteInfoRows.tsx
@@ -0,0 +1,206 @@
+import { RelationArrow } from "./RelationArrow";
+import { useState } from "react";
+import { useNotePreviewTrigger } from "../notePreview/NoteLinkPreview";
+
+type Direction = "outgoing" | "incoming" | "both";
+
+const DIRECTION_LABEL: Record = {
+ outgoing: "Links to",
+ incoming: "Links here",
+ both: "Linked both ways",
+};
+
+export type RailRow = {
+ key: string;
+ target: string;
+ label: string;
+ title: string;
+ typeName: string;
+ direction: Direction;
+ current?: boolean;
+ openable: boolean;
+ /** Folder shown beside an untyped note, in place of a type. */
+ folder?: string;
+};
+
+export type RailBucket = {
+ key: string;
+ label: string;
+ hint?: string;
+ direction?: Direction;
+ rows: RailRow[];
+};
+
+function SidebarPreviewButton({
+ target,
+ label,
+ title,
+ current,
+ from,
+ onOpen,
+}: {
+ target: string;
+ label: string;
+ title?: string;
+ current?: boolean;
+ from: string;
+ onOpen: (path: string, target?: "current" | "stack" | "beside") => void;
+}) {
+ const previewTrigger = useNotePreviewTrigger({
+ target,
+ from,
+ placement: "left",
+ placementBoundary: (trigger) =>
+ trigger.closest(".ontology-sidebar-info")?.getBoundingClientRect() ?? null,
+ open: (path, mode) => onOpen(path, mode),
+ });
+
+ return (
+ <>
+ {
+ previewTrigger.close();
+ onOpen(target, event.metaKey || event.ctrlKey ? "beside" : "stack");
+ }}
+ >
+ {label}
+
+ {previewTrigger.preview}
+ >
+ );
+}
+
+export type OpenFn = (path: string, target?: "current" | "stack" | "beside") => void;
+
+export function RailRowItem({
+ row,
+ showDirection,
+ groupLabel,
+ from,
+ onOpen,
+}: {
+ row: RailRow;
+ showDirection: boolean;
+ /** The bucket's label; a type line that repeats it is left out. */
+ groupLabel?: string;
+ from: string;
+ onOpen: OpenFn;
+}) {
+ return (
+
+ {showDirection && (
+
+
+
+ )}
+ {row.openable ? (
+
+ ) : (
+
+ {row.label}
+
+ )}
+ {row.typeName && row.typeName !== groupLabel && (
+ {row.typeName}
+ )}
+ {row.folder && (
+ // Truncates from the start (CSS rtl) so the deepest folder stays; the
+ // marks keep the path itself in left-to-right order.
+
+ {`\u200e${row.folder}\u200e`}
+
+ )}
+
+ );
+}
+
+const BUCKET_LIMIT = 5;
+
+export function RailBucketList({
+ bucket,
+ showDirection,
+ from,
+ onOpen,
+}: {
+ bucket: RailBucket;
+ showDirection: boolean;
+ from: string;
+ onOpen: OpenFn;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ // Show everything when only one row would hide behind the toggle.
+ const limit = bucket.rows.length <= BUCKET_LIMIT + 1 ? bucket.rows.length : BUCKET_LIMIT;
+ const rows = expanded ? bucket.rows : bucket.rows.slice(0, limit);
+ const hidden = bucket.rows.length - rows.length;
+
+ return (
+
+
+ {bucket.label}
+ {bucket.hint && {bucket.hint} }
+ {bucket.rows.length}
+
+
+ {rows.map((row) => (
+
+ ))}
+
+ {bucket.rows.length > limit && (
+
setExpanded((value) => !value)}
+ >
+ {expanded ? "Show fewer" : `${hidden} more`}
+
+ )}
+
+ );
+}
+
+// Names the arrows that appear in a list, once, above it.
+export function DirectionLegend({ buckets }: { buckets: RailBucket[] }) {
+ const present = new Set(buckets.flatMap((bucket) => bucket.rows.map((row) => row.direction)));
+
+ return (
+
+ {(["incoming", "outgoing", "both"] as const).flatMap((direction) =>
+ present.has(direction)
+ ? [
+
+
+
+
+ {DIRECTION_LABEL[direction]}
+ ,
+ ]
+ : [],
+ )}
+
+ );
+}
diff --git a/web/src/components/body/NoteRailGraph.tsx b/web/src/components/body/NoteRailGraph.tsx
new file mode 100644
index 000000000..ff8ce6302
--- /dev/null
+++ b/web/src/components/body/NoteRailGraph.tsx
@@ -0,0 +1,93 @@
+import { lazy, Suspense, useMemo } from "react";
+import type {
+ NodeWorkspace,
+ NodeWorkspaceGraph,
+ StructuralNode,
+ ValidationHealth,
+} from "../../api/types";
+
+type OpenTarget = "current" | "stack" | "beside";
+
+function graphHasContent(graph: NodeWorkspaceGraph | null | undefined): boolean {
+ return Boolean(
+ graph?.views?.localGraph &&
+ ((graph.views.localGraph.nodeIds?.length || 0) > 0 ||
+ (graph.nodes?.length || 0) > 0 ||
+ (graph.edges?.length || 0) > 0),
+ );
+}
+
+function graphWorkspace(
+ workspace: NodeWorkspace,
+ graph: NodeWorkspaceGraph | null | undefined,
+): NodeWorkspace | null {
+ if (!graphHasContent(graph)) return null;
+
+ return {
+ ...workspace,
+ focusedNodeId: graph?.focusedNodeId,
+ nodes: graph?.nodes || [],
+ edges: graph?.edges || [],
+ views: graph?.views,
+ };
+}
+
+// Sigma, graphology, and ForceAtlas2 load with the Graph tab, not the Notes entry.
+const OntologyLocalGraph = lazy(() =>
+ import("../OntologyLocalGraph").then((module) => ({ default: module.OntologyLocalGraph })),
+);
+
+export function GraphPanel({
+ workspace,
+ graph,
+ graphLoading,
+ graphError,
+ onRetry,
+ onOpen,
+ onOpenNode,
+}: {
+ workspace: NodeWorkspace;
+ graph: NodeWorkspaceGraph | null | undefined;
+ graphLoading: boolean;
+ graphError: boolean;
+ onRetry: () => void;
+ onOpen: (path: string, target?: OpenTarget) => void;
+ onOpenNode: (node: StructuralNode) => void;
+ validationIssueCount?: number;
+ validationHealth?: ValidationHealth;
+}) {
+ const localWorkspace = useMemo(() => graphWorkspace(workspace, graph), [graph, workspace]);
+
+ if (localWorkspace) {
+ return (
+
+
+ Loading local graph…
+
+ }
+ >
+
+
+
+ );
+ }
+
+ return (
+
+ {graphLoading ? (
+ "Loading local graph…"
+ ) : graphError ? (
+ <>
+ Unable to load local graph.
+
+ Retry
+
+ >
+ ) : (
+ "No local graph yet."
+ )}
+
+ );
+}
diff --git a/web/src/components/body/PropertyLocatorWidget.tsx b/web/src/components/body/PropertyLocatorWidget.tsx
new file mode 100644
index 000000000..685a52015
--- /dev/null
+++ b/web/src/components/body/PropertyLocatorWidget.tsx
@@ -0,0 +1,79 @@
+import { type KeyboardEvent, useCallback, useEffect, useRef, useState } from "react";
+
+function isValidLocator(value: string): boolean {
+ return /^[A-Za-z0-9_-]+$/.test(value.trim());
+}
+
+export function LocatorWidget({
+ value,
+ editing,
+ dirty,
+ present,
+ onStage,
+ ariaLabel,
+}: {
+ value: string;
+ editing: boolean;
+ dirty: boolean;
+ present: boolean;
+ onStage: (value: string) => void;
+ ariaLabel: string;
+}) {
+ const [draft, setDraft] = useState(value);
+ const inputRef = useRef(null);
+ const valid = isValidLocator(draft);
+
+ useEffect(() => {
+ if (document.activeElement !== inputRef.current) {
+ setDraft(value);
+ }
+ }, [value]);
+
+ const commit = useCallback(() => {
+ const next = draft.trim();
+
+ if (next === value || !isValidLocator(next)) return;
+ onStage(next);
+ }, [draft, onStage, value]);
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commit();
+ inputRef.current?.blur();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ setDraft(value);
+ inputRef.current?.blur();
+ }
+ },
+ [commit, value],
+ );
+
+ if (!editing) {
+ if (!present || value.trim() === "") {
+ return Empty ;
+ }
+
+ return ^{value} ;
+ }
+
+ return (
+
+ ^
+ setDraft(event.target.value.replace(/^\^+/, ""))}
+ onBlur={commit}
+ onKeyDown={handleKeyDown}
+ />
+
+ );
+}
diff --git a/web/src/components/body/RelationArrow.tsx b/web/src/components/body/RelationArrow.tsx
new file mode 100644
index 000000000..ee5d67666
--- /dev/null
+++ b/web/src/components/body/RelationArrow.tsx
@@ -0,0 +1,15 @@
+import { ArrowLeft, ArrowRight, ArrowLeftRight } from "lucide-react";
+
+export function RelationArrow({ direction }: { direction: "incoming" | "outgoing" | "both" }) {
+ const Icon = { incoming: ArrowLeft, outgoing: ArrowRight, both: ArrowLeftRight }[direction];
+
+ return (
+
+ );
+}
diff --git a/web/src/components/body/noteInfoBuckets.ts b/web/src/components/body/noteInfoBuckets.ts
new file mode 100644
index 000000000..e3c82f493
--- /dev/null
+++ b/web/src/components/body/noteInfoBuckets.ts
@@ -0,0 +1,151 @@
+import type { NoteWorkspaceLink } from "../../api/types";
+import { displayTitle } from "../../lib/labels";
+import { publicTypeName } from "../../lib/typeNames";
+import type { TypeLabelFn } from "../typeLabels";
+import type { RailRow, RailBucket } from "./NoteInfoRows";
+
+const NOTE_CONTENT_KINDS = new Set(["note", "section", "embedded"]);
+
+export function isNoteContent(item: NoteWorkspaceLink): boolean {
+ return NOTE_CONTENT_KINDS.has(item.kind);
+}
+
+// Anchored items address a node inside a note; the shell opens `path#anchor`.
+export function relationTarget(item: NoteWorkspaceLink): string {
+ return item.anchor && !item.path.includes("#") ? `${item.path}#${item.anchor}` : item.path;
+}
+
+// Link kinds carry an index qualifier ("note_link:wikilink:basic"); readers
+// only need the kind.
+export function humanizeRelationName(name: string): string {
+ const spaced = name
+ .split(":", 1)[0]
+ .trim()
+ .replace(/[_-]+/g, " ")
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
+ .toLowerCase();
+
+ return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : name;
+}
+
+// Servers before `direction` existed only marked backlinks.
+function itemDirection(item: NoteWorkspaceLink): RailRow["direction"] {
+ if (item.direction) return item.direction;
+
+ return item.provenance === "backlink" ? "incoming" : "outgoing";
+}
+
+export const RELATION_DIRECTIONS: RailRow["direction"][] = ["incoming", "outgoing", "both"];
+
+export const RELATION_DIRECTION_LABEL = {
+ incoming: "Incoming",
+ outgoing: "Outgoing",
+ both: "Both ways",
+};
+
+export function railRow(item: NoteWorkspaceLink, typeLabel: TypeLabelFn): RailRow {
+ const target = relationTarget(item);
+ const type = publicTypeName(item.resolvedType || item.structuralNode?.typeName);
+
+ return {
+ key: target,
+ target,
+ label: displayTitle(item.title) || target,
+ title: item.targetTitle || item.title || target,
+ typeName: type ? typeLabel(type) : "",
+ direction: itemDirection(item),
+ current: item.current,
+ openable: isNoteContent(item),
+ };
+}
+
+// Typed field relations keep their target type on each record.
+export function relationBuckets(
+ items: NoteWorkspaceLink[],
+ typeLabel: TypeLabelFn,
+ noteReader: boolean,
+): RailBucket[] {
+ const buckets = new Map();
+
+ for (const item of items) {
+ const row = railRow(item, typeLabel);
+ const relation = item.relationName || item.provenance || "relation";
+ const name = humanizeRelationName(relation);
+ // Key by the schema field, not its label: `partOf` and `part_of` stay apart.
+ const key = `${row.direction}:${relation}`;
+ const bucket = buckets.get(key) ?? { key, label: name, direction: row.direction, rows: [] };
+
+ if (!bucket.rows.some((existing) => existing.target === row.target)) bucket.rows.push(row);
+ buckets.set(key, bucket);
+ }
+
+ if (noteReader) return Array.from(buckets.values());
+
+ return Array.from(buckets.values()).map((bucket) => {
+ const types = new Set(bucket.rows.map((row) => row.typeName));
+
+ if (types.size !== 1) return bucket;
+
+ return {
+ ...bucket,
+ hint: bucket.rows[0].typeName,
+ rows: bucket.rows.map((row) => ({ ...row, typeName: "" })),
+ };
+ });
+}
+
+// The folder that holds a note, shown beside an untyped link ("pkg/app/").
+function folderOf(target: string): string {
+ const path = target.split("#", 1)[0];
+ const slash = path.lastIndexOf("/");
+
+ return slash > 0 ? path.slice(0, slash + 1) : "";
+}
+
+const UNTYPED_BUCKET_LABEL = "Other notes";
+
+// Body links and backlinks, one row per note with its direction, bucketed by
+// type; untyped notes share one bucket and show their folder instead.
+export function linkedBuckets(
+ items: NoteWorkspaceLink[],
+ exclude: ReadonlySet,
+ typeLabel: TypeLabelFn,
+ noteReader: boolean,
+): RailBucket[] {
+ const rows = new Map();
+
+ for (const item of items) {
+ const row = railRow(item, typeLabel);
+
+ if (exclude.has(row.target)) continue;
+ const existing = rows.get(row.target);
+
+ if (!existing) {
+ rows.set(row.target, row);
+ } else if (existing.direction !== row.direction) {
+ existing.direction = "both";
+ }
+ }
+
+ const buckets = new Map();
+
+ for (const row of rows.values()) {
+ const typed = Boolean(row.typeName);
+ const label = row.typeName || UNTYPED_BUCKET_LABEL;
+ const key = `${typed ? "type" : "untyped"}:${label}`;
+ const bucket = buckets.get(key) ?? { key, label, typed, rows: [] };
+ bucket.rows.push({
+ ...row,
+ typeName: noteReader ? row.typeName : "",
+ folder: typed ? undefined : folderOf(row.target),
+ });
+ buckets.set(key, bucket);
+ }
+
+ return Array.from(buckets.values()).sort(
+ (a, b) =>
+ Number(b.typed) - Number(a.typed) ||
+ b.rows.length - a.rows.length ||
+ a.label.localeCompare(b.label),
+ );
+}
diff --git a/web/src/components/body/noteInfoFixtures.test-support.ts b/web/src/components/body/noteInfoFixtures.test-support.ts
new file mode 100644
index 000000000..aeb055e22
--- /dev/null
+++ b/web/src/components/body/noteInfoFixtures.test-support.ts
@@ -0,0 +1,193 @@
+import type { NodeWorkspace } from "../../api/types";
+
+/** A person note whose only relation is an inbound action item inside another note. */
+export function workspaceWithEmbeddedRelation(): NodeWorkspace {
+ const ref = { notePath: "docs/people/drew.md", kind: "NOTE" };
+
+ return {
+ requestedRef: "docs/people/drew.md",
+ focusedNodeId: "note:docs/people/drew.md",
+ node: {
+ ref,
+ notePath: "docs/people/drew.md",
+ title: "Drew Colthorp",
+ locator: "docs/people/drew.md",
+ nodeLocator: {
+ ref,
+ kind: "NOTE",
+ sourceLocator: "docs/people/drew.md",
+ status: "linkable",
+ },
+ },
+ content: {
+ path: "docs/people/drew.md",
+ title: "Drew Colthorp",
+ markdown: "",
+ sourceCapabilities: [],
+ },
+ relations: [
+ {
+ key: "structural",
+ label: "Structural relations",
+ items: [
+ {
+ path: "docs/playground/pizza-party-2026.md",
+ anchor: "item-1030",
+ title: "Decide rain-date contingency by end of May",
+ kind: "embedded",
+ relationName: "assignee",
+ provenance: "field",
+ structural: true,
+ },
+ ],
+ },
+ ],
+ nodes: [],
+ edges: [],
+ loaded: { rendered: true, assessment: true, structure: true, relations: true },
+ capabilities: {
+ canEdit: false,
+ canEditFields: false,
+ canEditCollections: false,
+ canNavigateChildren: true,
+ canSubscribe: true,
+ },
+ status: {
+ dirty: false,
+ validation: { issueCount: 0 },
+ freshness: {},
+ session: {},
+ hasWarnings: false,
+ },
+ version: "v1",
+ };
+}
+
+export function workspaceWithNavigation(): NodeWorkspace {
+ const workspace = workspaceWithEmbeddedRelation();
+ workspace.requestedRef = "docs/efforts/example/plan.html";
+ workspace.node.notePath = "docs/efforts/example/plan.html";
+ workspace.content.path = "docs/efforts/example/plan.html";
+ workspace.relations = [
+ {
+ key: "workspace:docs/efforts/example/effort.html",
+ label: "In this effort",
+ ownerTitle: "Schema-driven navigation",
+ navigation: true,
+ items: [
+ {
+ path: "docs/efforts/example/effort.html",
+ title: "Overview",
+ targetTitle: "Schema-driven navigation",
+ kind: "note",
+ },
+ {
+ path: "docs/efforts/example/plan.html",
+ title: "Implementation plan",
+ targetTitle: "Plan details",
+ kind: "note",
+ current: true,
+ },
+ {
+ path: "docs/efforts/example/work-log.md",
+ title: "Work log",
+ targetTitle: "Execution history",
+ kind: "note",
+ },
+ ],
+ },
+ {
+ key: "structural",
+ label: "Structural relations",
+ items: [
+ {
+ path: "docs/specs/product/example.md",
+ title: "Governing product behavior",
+ kind: "note",
+ relationName: "governingSpecs",
+ structural: true,
+ },
+ ],
+ },
+ ];
+
+ return workspace;
+}
+
+export function workspaceWithSectionsAndNearby(): NodeWorkspace {
+ const workspace = workspaceWithEmbeddedRelation();
+
+ workspace.focusedNodeId = "focused-section";
+ workspace.nodes = [
+ {
+ id: "parent-section",
+ kind: "section",
+ ref: {
+ notePath: "docs/people/drew.md",
+ fragment: "Overview",
+ structuralFingerprint: "parent-stable",
+ kind: "SECTION",
+ },
+ notePath: "docs/people/drew.md",
+ status: workspace.status,
+ capabilities: workspace.capabilities,
+ data: { title: "Overview" },
+ },
+ {
+ id: "focused-section",
+ kind: "section",
+ ref: {
+ notePath: "docs/people/drew.md",
+ fragment: "Current",
+ structuralFingerprint: "current-stable",
+ kind: "SECTION",
+ },
+ notePath: "docs/people/drew.md",
+ parentId: "parent-section",
+ status: workspace.status,
+ capabilities: workspace.capabilities,
+ data: { title: "Current" },
+ },
+ {
+ id: "nearby-section",
+ kind: "section",
+ ref: {
+ notePath: "docs/people/drew.md",
+ fragment: "Old nearby heading",
+ structuralFingerprint: "nearby-stable",
+ kind: "SECTION",
+ },
+ notePath: "docs/people/drew.md",
+ parentId: "parent-section",
+ status: workspace.status,
+ capabilities: workspace.capabilities,
+ data: { title: "Nearby section" },
+ },
+ {
+ id: "field-sections",
+ kind: "field",
+ ref: workspace.node.ref,
+ notePath: "docs/people/drew.md",
+ parentId: "focused-section",
+ status: workspace.status,
+ capabilities: workspace.capabilities,
+ field: {
+ name: "supportingSections",
+ valueKind: "section-ref",
+ present: true,
+ values: [],
+ range: { start: 0, end: 0 },
+ sectionRefs: [
+ {
+ notePath: "docs/sections.md",
+ fragment: "Old section heading",
+ structuralFingerprint: "section-stable",
+ kind: "SECTION",
+ },
+ ],
+ },
+ },
+ ];
+
+ return workspace;
+}
diff --git a/web/src/components/editing/FieldEditor.tsx b/web/src/components/editing/FieldEditor.tsx
index 34c110bdb..ca4b48cb3 100644
--- a/web/src/components/editing/FieldEditor.tsx
+++ b/web/src/components/editing/FieldEditor.tsx
@@ -347,7 +347,7 @@ export function FieldEditor({
present={node.field.present}
vaultKey={vaultKey}
operationTarget={operationTarget}
- placeholder="Empty"
+ placeholder="—"
onStage={(next) => {
if (stage(fieldValueFromScalar(next)))
clearPersistedEditorDraft(vaultKey, operationTarget);
diff --git a/web/src/components/editing/confirmDiscard.test.ts b/web/src/components/editing/confirmDiscard.test.ts
new file mode 100644
index 000000000..510ac3f1d
--- /dev/null
+++ b/web/src/components/editing/confirmDiscard.test.ts
@@ -0,0 +1,19 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { confirmDiscard } from "./confirmDiscard";
+import { writePersistedEditorDraft, readPersistedEditorDraft } from "./draftStorage";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ localStorage.clear();
+ sessionStorage.clear();
+});
+
+it("confirms drafts-only discard and preserves the draft when cancelled", () => {
+ writePersistedEditorDraft("vault", "note", "Unsaved work");
+ const confirm = vi.spyOn(window, "confirm").mockReturnValue(false);
+ expect(confirmDiscard({ opCount: 0, touchedPaths: new Set() }, "vault")).toBe(false);
+ expect(confirm).toHaveBeenCalledWith("Discard local drafts? This cannot be undone.");
+ expect(readPersistedEditorDraft("vault", "note")).toBe("Unsaved work");
+ confirm.mockReturnValue(true);
+ expect(confirmDiscard({ opCount: 0, touchedPaths: new Set() }, "vault")).toBe(true);
+});
diff --git a/web/src/components/editing/confirmDiscard.ts b/web/src/components/editing/confirmDiscard.ts
new file mode 100644
index 000000000..cb64ad876
--- /dev/null
+++ b/web/src/components/editing/confirmDiscard.ts
@@ -0,0 +1,14 @@
+import { hasPersistedEditorDrafts } from "./draftStorage";
+
+export function confirmDiscard(
+ { opCount, touchedPaths }: { opCount: number; touchedPaths: Set },
+ vaultKey: string | null,
+) {
+ if (opCount === 0 && !hasPersistedEditorDrafts(vaultKey)) return true;
+
+ return window.confirm(
+ opCount > 0
+ ? `Discard ${opCount} staged change${opCount === 1 ? "" : "s"} to ${touchedPaths.size || 1} note${touchedPaths.size === 1 ? "" : "s"}? This cannot be undone.`
+ : "Discard local drafts? This cannot be undone.",
+ );
+}
diff --git a/web/src/components/explorerGraph.test.ts b/web/src/components/explorerGraph.test.ts
new file mode 100644
index 000000000..b3f31383e
--- /dev/null
+++ b/web/src/components/explorerGraph.test.ts
@@ -0,0 +1,193 @@
+import Graph from "graphology";
+import { useState } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import {
+ drawTestEdges,
+ fileFocusGraph,
+ focusFolderNodes,
+ onBranch,
+ useRevealRail,
+} from "./explorerGraph";
+import { useFolderExplorer } from "./useFolderExplorer";
+
+describe("Explorer focus", () => {
+ it("retains the Vault totals at root and in an expanded branch", () => {
+ const root = {
+ id: "folder:",
+ kind: "module",
+ label: "Vault",
+ path: "",
+ labelDetail: "655 notes · 4,572 files",
+ };
+
+ expect(focusFolderNodes([root], "")[0].labelDetail).toBe(root.labelDetail);
+ expect(focusFolderNodes([root], "pkg/app")[0].labelDetail).toBe(root.labelDetail);
+ });
+ it("keeps positions while selecting a branch and retaining child counts", () => {
+ const nodes = [
+ {
+ id: "folder:pkg",
+ kind: "module",
+ label: "pkg",
+ path: "pkg",
+ labelDetail: "3 files",
+ x: 10,
+ y: 20,
+ },
+ {
+ id: "folder:pkg/app",
+ kind: "module",
+ label: "app",
+ path: "pkg/app",
+ labelDetail: "2 files",
+ x: 40,
+ y: 50,
+ },
+ {
+ id: "folder:docs",
+ kind: "module",
+ label: "docs",
+ path: "docs",
+ labelDetail: "1 note",
+ x: -20,
+ y: 0,
+ },
+ ];
+
+ expect(focusFolderNodes(nodes, "")).toEqual(nodes.map((node) => ({ ...node, center: false })));
+ expect(focusFolderNodes(nodes, "pkg")).toEqual([
+ { ...nodes[0], center: true },
+ { ...nodes[1], center: false },
+ { ...nodes[2], center: false },
+ ]);
+ expect(
+ ["", "pkg", "pkg/app", "docs", "pkg-other"].map((path) => onBranch(path, "pkg/app")),
+ ).toEqual([true, true, true, false, false]);
+ });
+ it("groups file neighbours deterministically and retains every edge and label", () => {
+ const graph = {
+ nodes: [
+ { id: "f", kind: "code", path: "pkg/a.go", label: "a.go" },
+ { id: "n", kind: "note", label: "Documenting note" },
+ { id: "c", kind: "code", path: "pkg/b.go", label: "b.go" },
+ { id: "t", kind: "code", path: "pkg/a_test.go", label: "a_test.go" },
+ ],
+ edges: [
+ { source: "n", target: "f", kind: "mentions" },
+ { source: "f", target: "t", kind: "calls" },
+ ],
+ truncated: false,
+ };
+
+ const focused = fileFocusGraph(graph, "pkg/a.go");
+ expect(focused).toEqual(fileFocusGraph(graph, "pkg/a.go"));
+ expect(focused.nodes.find((node) => node.id === "f")?.center).toBe(true);
+ expect(focused.nodes.every((node) => Boolean(node.label) && Number.isFinite(node.x))).toBe(
+ true,
+ );
+ expect(focused.nodes.map((node) => node.label)).toEqual(
+ expect.arrayContaining(["Tests", "Other code"]),
+ );
+ expect(focused.edges.some((edge) => edge.kind === "explorer-tests")).toBe(true);
+ });
+ it("preserves off-path automatic fans while expanding a folder", () => {
+ const graph = {
+ nodes: Array.from({ length: 20 }, (_, i) => [
+ { id: `n${i}`, kind: "note", path: `docs/topic/a${i}.md`, label: `a${i}` },
+ { id: `c${i}`, kind: "code", path: `pkg/app/cli/a${i}.go`, label: `a${i}` },
+ ]).flat(),
+ edges: [],
+ truncated: false,
+ };
+
+ const { result } = renderHook(() => useFolderExplorer(graph, new Map()));
+ expect(result.current.open.has("docs")).toBe(true);
+ const before = result.current.drawn.nodes.find((n) => n.id === "folder:docs/topic");
+ expect(before).toBeDefined();
+ act(() => result.current.expand("pkg/app/cli"));
+ expect([...result.current.open]).toEqual(["", "docs", "pkg", "pkg/app", "pkg/app/cli"]);
+ expect(result.current.drawn.nodes.find((n) => n.id === "folder:docs/topic")).toMatchObject({
+ x: before?.x,
+ y: before?.y,
+ });
+ act(() => result.current.reset());
+ expect(result.current.open.has("docs")).toBe(true);
+ });
+});
+
+it("draws one bracket when Sigma canonicalizes code edges toward the group", () => {
+ const graph = new Graph();
+ graph.addNode("focus", { selected: true });
+ graph.addNode("file-group:Tests");
+ graph.addNode("code:a");
+ graph.addNode("code:b");
+ graph.addNode("file-more:Tests");
+ graph.addEdge("file-group:Tests", "focus", { kind: "explorer-tests" });
+ graph.addEdge("code:a", "file-group:Tests", { kind: "explorer-tests" });
+ graph.addEdge("code:b", "file-group:Tests", { kind: "explorer-tests" });
+
+ graph.addEdge("file-group:Tests", "file-more:Tests", { kind: "explorer-tests" });
+
+ const points = new Map([
+ ["focus", { x: 0, y: 0 }],
+ ["file-group:Tests", { x: 100, y: 0 }],
+ ["code:a", { x: 130, y: 40 }],
+ ["code:b", { x: 130, y: 80 }],
+ ["file-more:Tests", { x: 130, y: 120 }],
+ ]);
+
+ const context = {
+ strokeStyle: "",
+ lineWidth: 1,
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ beginPath: vi.fn(),
+ stroke: vi.fn(),
+ setLineDash: vi.fn(),
+ };
+
+ const sigma = {
+ getGraph: () => graph,
+ getNodeDisplayData: (id: string) => points.get(id),
+ framedGraphToViewport: (point: { x: number; y: number }) => point,
+ };
+
+ drawTestEdges(sigma, context, "blue");
+ expect(context.moveTo.mock.calls).toEqual([
+ [0, 0],
+ [100, 0],
+ [118, 0],
+ [118, 40],
+ [118, 80],
+ ]);
+ expect(context.lineTo.mock.calls).toEqual([
+ [100, 0],
+ [118, 0],
+ [118, 80],
+ [130, 40],
+ [130, 80],
+ ]);
+});
+
+it("seeds the rail once and merges file ancestors without closing user folders", () => {
+ const { result, rerender } = renderHook(
+ ({ initial, path }) => {
+ const [expanded, setExpanded] = useState(new Set());
+ useRevealRail(initial, !path, path, setExpanded);
+
+ return { expanded, setExpanded };
+ },
+ { initialProps: { initial: new Set(["", "docs"]), path: "" } },
+ );
+
+ expect([...result.current.expanded]).toEqual(["docs"]);
+ act(() => result.current.setExpanded(new Set(["custom"])));
+ rerender({ initial: new Set(["", "docs", "new"]), path: "" });
+ expect([...result.current.expanded]).toEqual(["custom"]);
+ rerender({ initial: new Set(["docs"]), path: "pkg/app/main.go" });
+ expect([...result.current.expanded]).toEqual(["custom", "pkg", "pkg/app"]);
+ act(() => result.current.setExpanded(new Set(["custom"])));
+ rerender({ initial: new Set(["docs"]), path: "pkg/app/main.go" });
+ expect([...result.current.expanded]).toEqual(["custom"]);
+});
diff --git a/web/src/components/explorerGraph.ts b/web/src/components/explorerGraph.ts
new file mode 100644
index 000000000..69fb805df
--- /dev/null
+++ b/web/src/components/explorerGraph.ts
@@ -0,0 +1,212 @@
+import type Graph from "graphology";
+import { resolveCssColor } from "../lib/themeColors";
+import { useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { getFileView } from "../api/client";
+import { queryKeys } from "../api/queryKeys";
+import { fileFocusGraph, mergeFileNotes } from "./fileFocusGraph";
+import type { GraphNode } from "../api/types";
+import type { FolderGraph } from "./folderGraph";
+import type { GraphResponse } from "../api/types";
+import type { SigmaNodeAttrs } from "../lib/graphStyle";
+import type { GraphViewNode } from "./graphViewShared";
+
+export type ExplorerNodeAttrs = SigmaNodeAttrs & {
+ collapsed?: boolean;
+ selected?: boolean;
+ branch?: boolean;
+ muted?: boolean;
+};
+
+export function onBranch(path: string, branch: string) {
+ return !path || path === branch || path.startsWith(`${branch}/`) || branch.startsWith(`${path}/`);
+}
+
+export function focusFolderNodes(nodes: GraphViewNode[], path: string): GraphViewNode[] {
+ return nodes.map((node) => ({
+ ...node,
+ center: node.id === `folder:${path}`,
+ }));
+}
+
+export { fileFocusGraph } from "./fileFocusGraph";
+
+export function useRevealRail(
+ initial: Set,
+ atRoot: boolean,
+ path: string,
+ setExpanded: Dispatch>>,
+) {
+ const seeded = useRef(false);
+ useEffect(() => {
+ if (seeded.current || ![...initial].some(Boolean)) return;
+ seeded.current = true;
+ setExpanded((previous) => new Set([...previous, ...[...initial].filter(Boolean)]));
+ }, [initial, setExpanded]);
+ useEffect(() => {
+ if (atRoot) return;
+
+ const ancestors = path
+ .split("/")
+ .slice(0, -1)
+ .map((_, index, parts) => parts.slice(0, index + 1).join("/"));
+
+ setExpanded((previous) => new Set([...previous, ...ancestors]));
+ }, [atRoot, path, setExpanded]);
+ useEffect(() => {
+ if (atRoot) return;
+
+ const reveal = () =>
+ document
+ .querySelector('.explorer-rail .tree-row[aria-current="page"]')
+ ?.scrollIntoView?.({ block: "nearest" });
+
+ const observer = new MutationObserver(reveal);
+ observer.observe(document.body, { childList: true, subtree: true });
+ reveal();
+
+ return () => observer.disconnect();
+ }, [atRoot, path]);
+}
+
+export function useExplorerGraph(
+ folders: FolderGraph | null,
+ graph: GraphResponse,
+ selection: { kind: "root" } | { kind: "module" | "file"; path: string },
+ searchPaths: ReadonlySet = new Set(),
+) {
+ const path = selection.kind === "file" ? selection.path : "";
+
+ const { data: file } = useQuery({
+ queryKey: queryKeys.files.detail(path),
+ queryFn: ({ signal }) => getFileView(path, { signal }),
+ enabled: Boolean(path),
+ });
+
+ const [revealed, setRevealed] = useState<{ path: string; groups: Set }>({
+ path: "",
+ groups: new Set(),
+ });
+
+ const sourceGraph = useMemo(() => mergeFileNotes(graph, file), [graph, file]);
+
+ const drawn = useMemo & { nodes: GraphViewNode[] }>(
+ () =>
+ folders
+ ? {
+ ...folders,
+ nodes: focusFolderNodes(
+ folders.nodes,
+ selection.kind === "module" ? selection.path : "",
+ ),
+ }
+ : selection.kind === "file"
+ ? fileFocusGraph(
+ sourceGraph,
+ selection.path,
+ file,
+ revealed.path === path ? revealed.groups : new Set(),
+ searchPaths,
+ )
+ : graph,
+ [folders, graph, selection, sourceGraph, file, revealed, path, searchPaths],
+ );
+
+ const reveal = (node: GraphNode) => {
+ if (!node.id.startsWith("file-more:")) return false;
+ setRevealed((previous) => ({
+ path,
+ groups: new Set([
+ ...(previous.path === path ? previous.groups : []),
+ node.id.slice("file-more:".length),
+ ]),
+ }));
+
+ return true;
+ };
+
+ return { ...drawn, sourceGraph, reveal };
+}
+
+export function drawTestEdges(
+ sigma: {
+ getGraph: () => Graph;
+ getNodeDisplayData: (
+ id: string,
+ ) => { x: number; y: number; hidden?: boolean } | null | undefined;
+ framedGraphToViewport: (point: { x: number; y: number }) => { x: number; y: number };
+ },
+ context: Pick<
+ CanvasRenderingContext2D,
+ "strokeStyle" | "lineWidth" | "setLineDash" | "beginPath" | "moveTo" | "lineTo" | "stroke"
+ >,
+ color: string,
+) {
+ const graph = sigma.getGraph();
+
+ const point = (id: string) => {
+ const node = sigma.getNodeDisplayData(id);
+
+ return node && !node.hidden ? sigma.framedGraphToViewport(node) : null;
+ };
+
+ const line = (x1: number, y1: number, x2: number, y2: number) => {
+ context.moveTo(x1, y1);
+ context.lineTo(x2, y2);
+ };
+
+ graph.forEachNode((id) => {
+ if (!id.startsWith("file-group:")) return;
+ const heading = point(id);
+
+ if (!heading) return;
+ const items: { x: number; y: number }[] = [];
+ const focused: { x: number; y: number }[] = [];
+ let kind = "";
+ graph.forEachEdge(id, (_edge, attrs, source, target) => {
+ kind = attrs.kind;
+
+ const other = source === id ? target : source;
+ const position = point(other);
+
+ if (!position) return;
+
+ if (other.startsWith("file-more:")) return;
+
+ if (graph.getNodeAttribute(other, "selected")) focused.push(position);
+ else items.push(position);
+ });
+ context.strokeStyle =
+ kind === "explorer-documents"
+ ? resolveCssColor("var(--explorer-link-strong)")
+ : kind === "explorer-code"
+ ? resolveCssColor("var(--explorer-code)")
+ : kind === "explorer-tests"
+ ? resolveCssColor("var(--type-8)")
+ : color;
+ context.lineWidth = 1.5;
+ context.setLineDash(kind === "explorer-tests" ? [4, 3] : []);
+ context.beginPath();
+
+ for (const focus of focused) line(focus.x, focus.y, heading.x, heading.y);
+ const columns = new Map();
+
+ for (const item of items) {
+ const x = Math.round(item.x);
+ const column = columns.get(x) ?? [];
+ column.push(item);
+ columns.set(x, column);
+ }
+
+ for (const [x, column] of columns) {
+ const trunkX = x + (x < heading.x ? 12 : -12);
+ line(heading.x, heading.y, trunkX, heading.y);
+ line(trunkX, heading.y, trunkX, Math.max(...column.map((item) => item.y)));
+
+ for (const item of column) line(trunkX, item.y, item.x, item.y);
+ }
+
+ context.stroke();
+ });
+ context.setLineDash([]);
+}
diff --git a/web/src/components/explorerNavigation.ts b/web/src/components/explorerNavigation.ts
new file mode 100644
index 000000000..1d981f67f
--- /dev/null
+++ b/web/src/components/explorerNavigation.ts
@@ -0,0 +1,63 @@
+import type { GraphResponse } from "../api/types";
+import { encodeURLFragment } from "../lib/noteDeepLink";
+import { NOTES_ROOT_PATH } from "./notesRoute";
+
+export function moduleKey(path: string, depth: number) {
+ const cleaned = path.replace(/^\/+/, "");
+ const parts = cleaned.split("/");
+
+ if (parts.length === 0) return "root";
+
+ if (parts.length < depth) return parts.join("/");
+
+ return parts.slice(0, depth).join("/");
+}
+
+export function isNoteTarget(path: string, kind?: string): boolean {
+ if (kind) return ["note", "section", "embedded"].includes(kind.toLowerCase());
+ const barePath = path.split("#", 1)[0] || path;
+
+ return /\.(?:md|html?)$/i.test(barePath);
+}
+
+export function openNoteWorkspace(path: string) {
+ const hashIndex = path.indexOf("#");
+ const notePath = hashIndex >= 0 ? path.slice(0, hashIndex) : path;
+ const noteHash = hashIndex >= 0 ? path.slice(hashIndex) : "";
+ const params = new URLSearchParams();
+ params.set("note", notePath);
+ window.history.pushState(
+ {},
+ "",
+ `${NOTES_ROOT_PATH}?${params.toString()}${encodeURLFragment(noteHash)}`,
+ );
+ window.dispatchEvent(new PopStateEvent("popstate"));
+}
+
+export function explorerFileFromLocation(search: string): { path: string; line?: number } | null {
+ const params = new URLSearchParams(search);
+ const path = params.get("file")?.trim();
+
+ if (!path) return null;
+ const parsedLine = Number(params.get("line"));
+
+ return {
+ path,
+ line: Number.isInteger(parsedLine) && parsedLine > 0 ? parsedLine : undefined,
+ };
+}
+
+/**
+ * What the folder view's counts cover. The graph can hold only part of a large
+ * vault, so its note counts can run below Overview's; say so when it does.
+ */
+export function folderCoverage(graph: GraphResponse) {
+ const fmt = (count: number) => count.toLocaleString("en-US");
+ const notes = graph.nodes.filter((node) => node.kind === "note").length;
+ const files = graph.nodes.filter((node) => node.kind === "code").length;
+ const counts = `Counts cover the ${fmt(notes)} notes and ${fmt(files)} code files in the graph`;
+
+ return graph.truncated
+ ? `${counts}, the best-connected part of the vault, so Overview can count more notes.`
+ : `${counts}.`;
+}
diff --git a/web/src/components/file-panel-preview.css b/web/src/components/file-panel-preview.css
new file mode 100644
index 000000000..481f32ce5
--- /dev/null
+++ b/web/src/components/file-panel-preview.css
@@ -0,0 +1,5 @@
+.explorer-pane__code pre,
+.explorer-pane__code pre code {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
diff --git a/web/src/components/fileFocusGraph.test.ts b/web/src/components/fileFocusGraph.test.ts
new file mode 100644
index 000000000..d17e8466b
--- /dev/null
+++ b/web/src/components/fileFocusGraph.test.ts
@@ -0,0 +1,340 @@
+import { describe, expect, it } from "vitest";
+import { fileFocusGraph, mergeFileNotes } from "./fileFocusGraph";
+import type { GraphResponse } from "../api/types";
+
+const graph: GraphResponse = {
+ nodes: [
+ { id: "f", kind: "code", path: "src/main.go", label: "main.go" },
+ ...Array.from({ length: 30 }, (_, i) => ({
+ id: `c${i}`,
+ kind: "code",
+ path: `src/c${i}.go`,
+ label: `c${i}.go`,
+ })),
+ { id: "t", kind: "code", path: "src/main_test.go", label: "main_test.go" },
+ ],
+ edges: [
+ ...Array.from({ length: 30 }, (_, i) => ({ source: "f", target: `c${i}`, kind: "calls" })),
+ { source: "t", target: "f", kind: "calls" },
+ ],
+};
+
+describe("file neighbour groups", () => {
+ it("separates calls and tests behind labelled trunks and counts every aggregated file", () => {
+ const result = fileFocusGraph(graph, "src/main.go");
+ expect(result.nodes.find((n) => n.id === "f")).toMatchObject({ x: 0, y: 0 });
+ expect(result.nodes.find((n) => n.id === "file-group:Calls / imports")).toMatchObject({
+ label: "Calls / imports",
+ labelDetail: "30 files",
+ });
+ expect(result.nodes.find((n) => n.id === "file-more:Calls / imports")).toMatchObject({
+ label: "Show 22 more",
+ childCount: 22,
+ });
+ expect(result.edges.filter((edge) => edge.source === "f")).toHaveLength(2);
+ expect(result.edges).toContainEqual({
+ source: "file-group:Tests",
+ target: "t",
+ kind: "explorer-tests",
+ });
+ const expanded = fileFocusGraph(graph, "src/main.go", undefined, new Set(["Calls / imports"]));
+ expect(expanded.nodes.find((node) => node.id === "file-group:Calls / imports")).toMatchObject({
+ x: result.nodes.find((node) => node.id === "file-group:Calls / imports")?.x,
+ y: result.nodes.find((node) => node.id === "file-group:Calls / imports")?.y,
+ });
+ expect(expanded.nodes.filter((node) => node.path?.startsWith("src/c"))).toHaveLength(22);
+ expect(expanded.nodes.find((node) => node.id.startsWith("file-more:"))).toMatchObject({
+ childCount: 8,
+ });
+ const columns = new Map();
+
+ for (const node of expanded.nodes.filter((node) => node.path?.startsWith("src/c"))) {
+ const ys = columns.get(node.x) ?? [];
+ ys.push(node.y ?? 0);
+ columns.set(node.x, ys);
+ }
+
+ expect(columns.size).toBe(3);
+
+ for (const ys of columns.values()) {
+ ys.sort((a, b) => a - b);
+ expect(ys.slice(1).every((y, i) => y - ys[i] >= 24)).toBe(true);
+ }
+ });
+
+ it("keeps unrelated groups and their members fixed when calls are revealed", () => {
+ const input = {
+ nodes: [
+ ...graph.nodes.slice(0, 13),
+ { id: "other", kind: "code", path: "src/other.go", label: "other.go" },
+ graph.nodes[31],
+ ],
+ edges: graph.edges.slice(0, 12),
+ };
+
+ const before = fileFocusGraph(input, "src/main.go");
+ const after = fileFocusGraph(input, "src/main.go", undefined, new Set(["Calls / imports"]));
+
+ for (const id of ["file-group:Other code", "other", "file-group:Tests", "t"]) {
+ const anchor = before.nodes.find((node) => node.id === id);
+ expect(after.nodes.find((node) => node.id === id)).toMatchObject({
+ x: anchor?.x,
+ y: anchor?.y,
+ });
+ }
+
+ const positions = after.nodes
+ .filter((node) => node.id !== "f")
+ .map((node) => `${node.x}:${node.y}`);
+
+ expect(new Set(positions).size).toBe(positions.length);
+ });
+
+ it("keeps eleven tests in one lane when their disclosure expands", () => {
+ const tests = Array.from({ length: 11 }, (_, i) => ({
+ id: `t${i}`,
+ kind: "code",
+ path: `src/case${i}_test.go`,
+ label: `case${i}_test.go`,
+ }));
+
+ const result = fileFocusGraph(
+ { nodes: [graph.nodes[0], ...tests], edges: [] },
+ "src/main.go",
+ undefined,
+ new Set(["Tests"]),
+ );
+
+ expect(result.nodes.filter((node) => node.path?.endsWith("_test.go"))).toHaveLength(11);
+ expect(
+ new Set(result.nodes.filter((node) => node.path?.endsWith("_test.go")).map((node) => node.x))
+ .size,
+ ).toBe(1);
+ });
+
+ it("prepares 10,000 anchor neighbours with a bounded number of property reads", () => {
+ let reads = 0;
+
+ const counted = (value: T): T =>
+ new Proxy(value, {
+ get(target, key, receiver) {
+ reads++;
+
+ // Preserve normal property access while counting work on the input.
+ // oxlint-disable-next-line anti-slop/no-reflect-get
+ return Reflect.get(target, key, receiver);
+ },
+ });
+
+ const relatedNotes = Array.from({ length: 10_000 }, (_, i) =>
+ counted({
+ path: `notes/${i}.md`,
+ title: `Note ${i}`,
+ reason: "codeanchor",
+ }),
+ );
+
+ const nodes = [
+ graph.nodes[0],
+ ...relatedNotes.map((note, i) =>
+ counted({
+ id: `n${i}`,
+ kind: "note",
+ path: note.path,
+ label: note.title,
+ }),
+ ),
+ ];
+
+ const edges = relatedNotes.map((_, i) =>
+ counted({ source: `n${i}`, target: "f", kind: "codeanchor" }),
+ );
+
+ // Include neighbour links so representative lookup is covered too.
+ edges.push(
+ ...relatedNotes
+ .slice(1)
+ .map((_, i) => counted({ source: `n${i}`, target: `n${i + 1}`, kind: "link" })),
+ );
+ reads = 0;
+
+ const result = fileFocusGraph({ nodes, edges }, "src/main.go", {
+ path: "src/main.go",
+ kind: "code",
+ relatedNotes,
+ });
+
+ expect(result.nodes).toHaveLength(11);
+ expect(reads).toBeLessThan(2_000_000);
+
+ const merged = mergeFileNotes(
+ { nodes: [graph.nodes[0]], edges: [] },
+ { path: "src/main.go", kind: "code", relatedNotes },
+ );
+
+ expect(merged.nodes).toHaveLength(10_001);
+ expect(merged.edges).toHaveLength(10_000);
+ expect(reads).toBeLessThan(4_000_000);
+ });
+
+ it("reveals 10,000 notes in bounded batches with an exact clickable remainder", () => {
+ const file = {
+ path: "src/main.go",
+ kind: "code",
+ relatedNotes: Array.from({ length: 10_000 }, (_, i) => ({
+ path: `notes/${i}.md`,
+ title: `Note ${i}`,
+ reason: "codeanchor",
+ })),
+ };
+
+ const input = { nodes: [graph.nodes[0]], edges: [] };
+ const expanded = new Set();
+
+ for (let batch = 0; batch < 4; batch++) {
+ const result = fileFocusGraph(input, file.path, file, expanded);
+ const shown = result.nodes.filter((node) => !node.aggregate && !node.center);
+ expect(shown).toHaveLength(8 + batch * 14);
+ const more = result.nodes.find((node) => node.id.startsWith("file-more:"));
+ expect(more).toMatchObject({
+ label: `Show ${10_000 - shown.length} more`,
+ childCount: 10_000 - shown.length,
+ });
+ expect(
+ result.edges.every((edge) => result.nodes.some((node) => node.id === edge.target)),
+ ).toBe(true);
+ expanded.add(more!.id.slice("file-more:".length));
+ }
+ });
+
+ it("unions inspector anchor notes and references with graph notes, without duplicates", () => {
+ const input = {
+ ...graph,
+ nodes: [...graph.nodes, { id: "n", kind: "note", path: "related.md", label: "Related" }],
+ };
+
+ const file = {
+ path: "src/main.go",
+ kind: "code",
+ relatedNotes: [
+ { path: "anchor.md", title: "Anchor", reason: "codeanchor" },
+ { path: "anchor.md", title: "Anchor", reason: "codeanchor" },
+ { path: "spec.md", title: "Spec", reason: "coderef" },
+ ],
+ };
+
+ const merged = mergeFileNotes(input, file);
+ expect(merged.nodes.filter((node) => node.kind === "note")).toHaveLength(3);
+ const result = fileFocusGraph(input, file.path, file);
+ expect(result.nodes.map((node) => node.label)).toEqual(
+ expect.arrayContaining([
+ "Mentioned in",
+ "Documented by",
+ "Related in graph",
+ "Anchor",
+ "Spec",
+ "Related",
+ ]),
+ );
+ expect(
+ result.nodes
+ .filter((n) => n.id.startsWith("file-group:") && n.kind === "note")
+ .map((n) => n.label),
+ ).toEqual(["Documented by", "Mentioned in", "Related in graph"]);
+ expect(mergeFileNotes(merged, file)).toEqual(merged);
+ });
+});
+
+it("shows server omissions as a remainder that cannot be revealed", () => {
+ const result = fileFocusGraph(
+ {
+ nodes: [{ id: "main", kind: "code", path: "src/main.go", label: "main.go" }],
+ edges: [],
+ omittedNodes: 101,
+ omittedEdges: 123,
+ },
+ "src/main.go",
+ );
+
+ expect(result.nodes.find((node) => node.id === "file-omitted")).toMatchObject({
+ collapsed: true,
+ label: "+101 more not loaded",
+ labelDetail: "123 links not loaded",
+ aggregate: true,
+ });
+ expect(result.nodes.some((node) => node.id.startsWith("file-more:"))).toBe(false);
+});
+
+it("reconciles the omitted neighbour when file details load all 201 notes", () => {
+ const relatedNotes = Array.from({ length: 201 }, (_, i) => ({
+ path: `notes/${i}.md`,
+ title: `Note ${i}`,
+ reason: "coderef",
+ }));
+
+ const input = {
+ nodes: [
+ graph.nodes[0],
+ ...relatedNotes.slice(0, 200).map((note) => ({
+ id: `note:${note.path}`,
+ kind: "note",
+ path: note.path,
+ label: note.title,
+ })),
+ ],
+ edges: relatedNotes
+ .slice(0, 200)
+ .map((note) => ({ source: `note:${note.path}`, target: "f", kind: "coderef" })),
+ omittedNodes: 1,
+ omittedEdges: 1,
+ omittedNodeIDs: ["note:notes/200.md"],
+ };
+
+ const file = { path: "src/main.go", kind: "code", relatedNotes };
+ const result = fileFocusGraph(input, file.path, file);
+ expect(result.nodes.find((node) => node.id === "file-omitted")).toMatchObject({
+ label: "+0 more not loaded",
+ labelDetail: "1 links not loaded",
+ });
+ expect(result.nodes.find((node) => node.id === "file-group:Documented by")?.labelDetail).toBe(
+ "201 notes",
+ );
+ expect(mergeFileNotes(mergeFileNotes(input, file), file)).toEqual(mergeFileNotes(input, file));
+
+ const unrelated = {
+ ...file,
+ relatedNotes: [{ path: "anchor-only.md", title: "Extra", reason: "codeanchor" }],
+ };
+
+ expect(
+ fileFocusGraph(input, file.path, unrelated).nodes.find((node) => node.id === "file-omitted")
+ ?.label,
+ ).toBe("+1 more not loaded");
+});
+
+it("keeps the unreconciled floor when omitted identities are capped", () => {
+ const relatedNotes = Array.from({ length: 801 }, (_, i) => ({
+ path: `notes/${i}.md`,
+ title: `Note ${i}`,
+ reason: "coderef",
+ }));
+
+ const input = {
+ nodes: [graph.nodes[0]],
+ edges: [],
+ omittedNodes: 801,
+ omittedEdges: 801,
+ omittedNodeIDs: relatedNotes.slice(0, 200).map((note) => `note:${note.path}`),
+ // A legacy response's links must not reduce the conservative link count.
+ omittedLinks: [{ source: "note:notes/0.md", target: "f", kind: "coderef" }],
+ };
+
+ const file = { path: "src/main.go", kind: "code", relatedNotes };
+ const merged = mergeFileNotes(input, file);
+ expect(merged.omittedNodes).toBe(601);
+ expect(merged.omittedEdges).toBe(801);
+ expect(mergeFileNotes(merged, file).omittedNodes).toBe(601);
+ expect(
+ fileFocusGraph(input, file.path, file).nodes.find((n) => n.id === "file-omitted"),
+ ).toMatchObject({ label: "+601 more not loaded", labelDetail: "801 links not loaded" });
+});
diff --git a/web/src/components/fileFocusGraph.ts b/web/src/components/fileFocusGraph.ts
new file mode 100644
index 000000000..556a79fef
--- /dev/null
+++ b/web/src/components/fileFocusGraph.ts
@@ -0,0 +1,307 @@
+import type { FileView, GraphEdge, GraphNode, GraphResponse } from "../api/types";
+import type { GraphViewNode } from "./graphViewShared";
+import { fileFocusLabels, fileFocusRowHeight } from "./fileFocusLabels";
+
+/** File details include code-anchor matches that the graph projection does not. */
+export function mergeFileNotes(graph: GraphResponse, file?: FileView): GraphResponse {
+ if (file?.kind !== "code") return graph;
+ const focused = graph.nodes.find((node) => node.path === file.path);
+
+ if (!focused) return graph;
+ const nodes = [...graph.nodes];
+ const edges = [...graph.edges];
+
+ const notesByPath = new Map();
+
+ for (const node of nodes) {
+ const path = node.notePath || node.path;
+
+ if (node.kind === "note" && !notesByPath.has(path)) notesByPath.set(path, node);
+ }
+
+ const linked = new Set();
+
+ for (const edge of edges) {
+ if (edge.source === focused.id) linked.add(edge.target);
+
+ if (edge.target === focused.id) linked.add(edge.source);
+ }
+
+ for (const note of file.relatedNotes ?? []) {
+ let node = notesByPath.get(note.path);
+
+ if (!node) {
+ node = {
+ id: `note:${note.path}`,
+ kind: "note",
+ path: note.path,
+ label: note.title || note.path.split("/").pop() || note.path,
+ };
+ nodes.push(node);
+ notesByPath.set(note.path, node);
+ }
+
+ if (!linked.has(node.id)) {
+ edges.push({ source: node.id, target: focused.id, kind: note.reason || "related" });
+ linked.add(node.id);
+ }
+ }
+
+ const loadedIDs = new Set(nodes.map((node) => node.id));
+ const omittedNodeIDs = graph.omittedNodeIDs?.filter((id) => !loadedIDs.has(id));
+
+ return {
+ ...graph,
+ nodes,
+ edges,
+ omittedNodeIDs,
+ omittedNodes: Math.max(
+ 0,
+ (graph.omittedNodes ?? 0) -
+ ((graph.omittedNodeIDs?.length ?? 0) - (omittedNodeIDs?.length ?? 0)),
+ ),
+ };
+}
+
+export const FILE_NOTE_RELATIONS = ["Documented by", "Mentioned in", "Related in graph"];
+
+const GROUP_LIMIT = 8;
+
+const REVEAL_BATCH = 14;
+
+const GROUP_GAP = 80;
+
+const HEADING_GAP = 120;
+
+const isNote = (node: GraphNode) => node.kind === "note" || node.kind === "embedded";
+
+const isTest = (node: GraphNode) =>
+ /(^|[/_.-])(tests?|spec)([/_.-]|$)/i.test(node.path || node.label);
+
+export function fileFocusGraph(
+ input: GraphResponse,
+ path: string,
+ file?: FileView,
+ expanded: ReadonlySet = new Set(),
+ searchPaths: ReadonlySet = new Set(),
+): Omit & { nodes: GraphViewNode[] } {
+ const graph = mergeFileNotes(input, file);
+ const focused = graph.nodes.find((node) => node.path === path || node.notePath === path);
+
+ if (!focused)
+ return {
+ ...graph,
+ nodes: graph.nodes.map((node, index) => ({ ...node, x: index * 100, y: 0 })),
+ };
+ const groups = new Map();
+ const reasonsByPath = new Map>();
+
+ for (const note of file?.relatedNotes ?? []) {
+ const reasons = reasonsByPath.get(note.path) ?? new Set();
+
+ if (note.reason) reasons.add(note.reason);
+ reasonsByPath.set(note.path, reasons);
+ }
+
+ const calledIDs = new Set();
+ const testedIDs = new Set();
+
+ for (const edge of graph.edges) {
+ const other =
+ edge.source === focused.id
+ ? edge.target
+ : edge.target === focused.id
+ ? edge.source
+ : undefined;
+
+ if (other === undefined) continue;
+
+ if (/call|import|depend|reference/.test(edge.kind)) calledIDs.add(other);
+
+ if (edge.kind === "tests") testedIDs.add(other);
+ }
+
+ const groupByID = new Map();
+
+ for (const node of graph.nodes) {
+ if (node === focused) continue;
+
+ const reasons = reasonsByPath.get(node.notePath || node.path || "");
+ const called = calledIDs.has(node.id);
+ const tested = isTest(node) || testedIDs.has(node.id);
+
+ const label = isNote(node)
+ ? reasons?.has("coderef")
+ ? "Documented by"
+ : reasons?.has("codeanchor")
+ ? "Mentioned in"
+ : file?.kind === "code"
+ ? "Related in graph"
+ : "Linked notes"
+ : tested
+ ? "Tests"
+ : called
+ ? "Calls / imports"
+ : "Other code";
+
+ const members = groups.get(label) ?? [];
+ members.push(node);
+ groups.set(label, members);
+ groupByID.set(node.id, label);
+ }
+
+ const nodes: GraphViewNode[] = [
+ { ...focused, center: true, label: path.split("/").pop() || focused.label, x: 0, y: 0 },
+ ];
+
+ const edges: GraphEdge[] = [];
+ const moreIDs = new Map();
+ const batches = new Map();
+
+ for (const key of expanded) {
+ const label = key.split(":")[0];
+ batches.set(label, (batches.get(label) ?? 0) + 1);
+ }
+
+ for (const side of ["notes", "code"]) {
+ const entries = [...groups]
+ .filter(([, members]) => isNote(members[0]) === (side === "notes"))
+ .sort(([a], [b]) => FILE_NOTE_RELATIONS.indexOf(a) - FILE_NOTE_RELATIONS.indexOf(b));
+
+ const matchCount = (members: GraphNode[]) =>
+ new Set(
+ members.flatMap((node) => {
+ const path = node.notePath || node.path;
+
+ return path && searchPaths.has(path) ? [path] : [];
+ }),
+ ).size;
+
+ const visible = (members: GraphNode[], label: string): GraphViewNode[] => {
+ const batch = batches.get(label) ?? 0;
+ const limit = GROUP_LIMIT + batch * REVEAL_BATCH;
+
+ if (members.length <= limit) return members;
+ // The click handler stores this suffix; each batch gets its own disclosure key.
+ const id = `file-more:${label}${batch ? `:${batch}` : ""}`;
+ moreIDs.set(label, id);
+
+ return [
+ ...members.slice(0, limit),
+ {
+ id,
+ kind: side === "notes" ? "note" : "code",
+ label: `Show ${members.length - limit} more`,
+ childCount: members.length - limit,
+ searchMatchCount: searchPaths.size ? matchCount(members.slice(limit)) : undefined,
+ aggregate: true,
+ },
+ ];
+ };
+
+ const height = (members: GraphNode[], label: string, collapsed = false) => {
+ const shown = fileFocusLabels(
+ collapsed
+ ? members.slice(0, members.length > GROUP_LIMIT ? GROUP_LIMIT + 1 : GROUP_LIMIT)
+ : visible(members, label),
+ );
+
+ const rows = shown.length > 20 ? Math.ceil(shown.length / 2) : shown.length;
+
+ return (
+ HEADING_GAP +
+ Math.max(
+ ...[shown.slice(0, rows), shown.slice(rows)].map((column) =>
+ column.reduce((sum, node) => sum + fileFocusRowHeight(node), 0),
+ ),
+ ) +
+ GROUP_GAP
+ );
+ };
+
+ const totalHeight = entries.reduce(
+ (sum, [label, members]) => sum + height(members, label, true),
+ 0,
+ );
+
+ let top = totalHeight / 2 - (side === "code" ? 60 : 0);
+
+ for (const [label, members] of entries) {
+ members.sort((a, b) => (a.path || a.label).localeCompare(b.path || b.label));
+ const groupID = `file-group:${label}`;
+
+ const kind =
+ side === "notes"
+ ? "explorer-documents"
+ : label === "Tests"
+ ? "explorer-tests"
+ : "explorer-code";
+
+ const direction = side === "notes" ? -1 : 1;
+ const groupY = top;
+ nodes.push({
+ id: groupID,
+ kind: side === "notes" ? "note" : "code",
+ label,
+ searchMatchCount: searchPaths.size ? matchCount(members) : undefined,
+ labelDetail: `${members.length} ${side === "notes" ? "notes" : "files"}`,
+ aggregate: true,
+ x: direction * 210,
+ y: groupY,
+ });
+ edges.push({ source: focused.id, target: groupID, kind });
+
+ const shown = fileFocusLabels(visible(members, label));
+
+ // Keep column capacity fixed so revealing neighbours preserves existing positions.
+ const rows =
+ entries.at(-1)?.[0] !== label
+ ? Math.min(members.length, GROUP_LIMIT + 1)
+ : Math.min(members.length, 20);
+
+ let itemY = groupY - HEADING_GAP;
+ shown.forEach((node, index) => {
+ if (index % rows === 0) itemY = groupY - HEADING_GAP;
+ nodes.push({ ...node, x: direction * (280 + Math.floor(index / rows) * 1000), y: itemY });
+ itemY -= fileFocusRowHeight(node);
+ edges.push({ source: groupID, target: node.id, kind });
+ });
+ top -= height(members, label, true);
+ }
+ }
+
+ if (graph.omittedNodes || graph.omittedEdges) {
+ nodes.push({
+ id: "file-omitted",
+ collapsed: true,
+ kind: "module",
+ label: `+${graph.omittedNodes ?? 0} more not loaded`,
+ labelDetail: `${graph.omittedEdges ?? 0} links not loaded`,
+ aggregate: true,
+ x: 0,
+ y: Math.min(0, ...nodes.map((node) => node.y ?? 0)) - GROUP_GAP,
+ });
+ }
+
+ // Preserve neighbour-to-neighbour links, including links to aggregated members.
+ const drawnIDs = new Set(nodes.map((node) => node.id));
+
+ const aggregateID = (id: string) => {
+ if (drawnIDs.has(id)) return id;
+ const label = groupByID.get(id);
+
+ return (label && moreIDs.get(label)) || id;
+ };
+
+ for (const edge of graph.edges) {
+ if (edge.source === focused.id || edge.target === focused.id) continue;
+
+ const source = aggregateID(edge.source),
+ target = aggregateID(edge.target);
+
+ if (source !== target && drawnIDs.has(source) && drawnIDs.has(target))
+ edges.push({ ...edge, source, target });
+ }
+
+ return { ...graph, nodes, edges };
+}
diff --git a/web/src/components/fileFocusLabels.test.ts b/web/src/components/fileFocusLabels.test.ts
new file mode 100644
index 000000000..400de0f96
--- /dev/null
+++ b/web/src/components/fileFocusLabels.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+import { fileFocusLabels, fileFocusRowHeight } from "./fileFocusLabels";
+import { fileFocusGraph } from "./fileFocusGraph";
+
+const measure = (text: string) => text.length * 10;
+
+const code = (name: string) => ({ id: name, kind: "code", path: `src/${name}`, label: name });
+
+describe("file focus labels", () => {
+ it("keeps ordinary code names whole up to 240 pixels", () => {
+ expect(fileFocusLabels([code("intent_profiles.go")], measure)[0].label).toBe(
+ "intent_profiles.go",
+ );
+ });
+ it("trims a shared prefix or test suffix before distinctive stems", () => {
+ const prefix = "planner_shared_long_context_";
+ expect(
+ fileFocusLabels([code(`${prefix}alpha.go`), code(`${prefix}beta.go`)], measure).map(
+ (n) => n.label,
+ ),
+ ).toEqual(["…alpha.go", "…beta.go"]);
+ expect(
+ fileFocusLabels(
+ [code("long_distinctive_alpha_test.go"), code("long_distinctive_beta_test.go")],
+ measure,
+ ).map((n) => n.label),
+ ).toEqual(["…alpha…", "…beta…"]);
+ });
+ it("disambiguates identical titles with parent folders", () => {
+ expect(
+ fileFocusLabels(
+ [
+ { id: "a", kind: "note", label: "search", path: "docs/code-anchors/search.md" },
+ { id: "b", kind: "note", label: "search", path: "docs/subsystems/search.md" },
+ ],
+ measure,
+ ).map((n) => n.labelDetail),
+ ).toEqual(["code-anchors/", "subsystems/"]);
+ });
+ it("leaves room for both lines and a gap before the next group", () => {
+ const note = {
+ id: "a",
+ kind: "note",
+ label: "Search - Seed expansion strategies and retrieval",
+ };
+
+ expect(fileFocusRowHeight(note, measure)).toBe(134);
+
+ const graph = fileFocusGraph(
+ {
+ nodes: [
+ code("main.go"),
+ note,
+ { ...note, id: "b" },
+ { id: "c", kind: "note", label: "Other" },
+ ],
+ edges: [],
+ },
+ "src/main.go",
+ {
+ path: "src/main.go",
+ kind: "code",
+ relatedNotes: [{ path: "spec.md", title: "Spec", reason: "coderef" }],
+ },
+ );
+
+ const items = graph.nodes.filter((n) => ["a", "b", "c"].includes(n.id));
+ expect(
+ Math.abs(items.find((n) => n.id === "a")!.y! - items.find((n) => n.id === "b")!.y!),
+ ).toBeGreaterThanOrEqual(134);
+ const heading = graph.nodes.find((n) => n.id === "file-group:Documented by")!;
+ expect(Math.abs(heading.y! - items.at(-1)!.y!)).toBeGreaterThanOrEqual(80);
+ });
+});
diff --git a/web/src/components/fileFocusLabels.ts b/web/src/components/fileFocusLabels.ts
new file mode 100644
index 000000000..2904310d9
--- /dev/null
+++ b/web/src/components/fileFocusLabels.ts
@@ -0,0 +1,85 @@
+import type { GraphViewNode } from "./graphViewShared";
+import { noteLabelLines } from "./sigmaLabelText";
+
+const measure = (text: string) => {
+ const context =
+ typeof document === "undefined" ? null : document.createElement("canvas").getContext("2d");
+
+ if (!context?.measureText) return text.length * 7;
+ context.font = "500 14px Inter, -apple-system, system-ui, sans-serif";
+
+ return context.measureText(text).width;
+};
+
+/** Remove repeated context before sacrificing the part that distinguishes a file. */
+export function fileFocusLabels(nodes: GraphViewNode[], width = measure): GraphViewNode[] {
+ const names = nodes.map((node) =>
+ (node.kind === "code" && node.path
+ ? node.path.split("/").pop() || node.label
+ : node.label
+ ).replaceAll("...", "…"),
+ );
+
+ const codes = names.filter((_, i) => nodes[i].kind === "code" && !nodes[i].aggregate);
+ let prefix = codes[0] || "";
+
+ for (const name of codes) while (!name.startsWith(prefix)) prefix = prefix.slice(0, -1);
+ prefix = prefix.slice(0, Math.max(prefix.lastIndexOf("_"), prefix.lastIndexOf("-")) + 1);
+ let suffix = codes[0] || "";
+
+ for (const name of codes) while (!name.endsWith(suffix)) suffix = suffix.slice(1);
+ suffix = suffix.includes("_test.")
+ ? suffix.slice(suffix.indexOf("_test."))
+ : suffix.startsWith(".")
+ ? suffix
+ : "";
+
+ const labels = names.map((name, i) => {
+ if (nodes[i].kind !== "code" || width(name) <= 240) return name;
+ let label = name;
+
+ if (codes.length > 1 && prefix) label = `…${label.slice(prefix.length)}`;
+
+ if (codes.length > 1 && suffix) label = `${label.slice(0, -suffix.length)}…`;
+
+ while (width(label) > 240 && label.length > 2)
+ label = `${label.slice(0, Math.ceil(label.length / 2) - 1)}…${label.slice(-Math.floor(label.length / 2) + 1)}`;
+
+ return label;
+ });
+
+ return nodes.map((node, i) => {
+ const duplicates = nodes.filter((_, j) => labels[j] === labels[i]);
+ const path = node.notePath || node.path || "";
+ const parents = path.split("/").slice(0, -1);
+ let depth = 1;
+
+ while (
+ depth < parents.length &&
+ duplicates.some(
+ (other) =>
+ other.id !== node.id &&
+ (other.notePath || other.path || "").split("/").slice(0, -1).slice(-depth).join("/") ===
+ parents.slice(-depth).join("/"),
+ )
+ )
+ depth++;
+
+ return {
+ ...node,
+ label: labels[i],
+ labelDetail:
+ duplicates.length > 1 ? `${parents.slice(-depth).join("/") || "."}/` : node.labelDetail,
+ };
+ });
+}
+
+export function fileFocusRowHeight(node: GraphViewNode, width = measure) {
+ return (
+ (node.kind === "note" || node.kind === "embedded"
+ ? noteLabelLines(node.label, width).length
+ : 1) *
+ 42 +
+ 50
+ );
+}
diff --git a/web/src/components/fileFocusReveal.test.ts b/web/src/components/fileFocusReveal.test.ts
new file mode 100644
index 000000000..2db9f18d0
--- /dev/null
+++ b/web/src/components/fileFocusReveal.test.ts
@@ -0,0 +1,37 @@
+import { expect, it } from "vitest";
+import { fileFocusGraph } from "./fileFocusGraph";
+
+it("preserves existing neighbour positions across two reveals of the last group", () => {
+ const focused = { id: "f", kind: "code", path: "main.go", label: "main.go" };
+
+ const neighbours = Array.from({ length: 40 }, (_, i) => ({
+ id: `c${i}`,
+ kind: "code",
+ path: `c${String(i).padStart(2, "0")}.go`,
+ label: `c${i}.go`,
+ }));
+
+ const graph = {
+ nodes: [focused, ...neighbours],
+ edges: neighbours.map((node) => ({ source: "f", target: node.id, kind: "calls" })),
+ };
+
+ const expanded = new Set();
+ let before = fileFocusGraph(graph, focused.path, undefined, expanded);
+
+ for (let reveal = 0; reveal < 2; reveal++) {
+ const more = before.nodes.find((node) => node.id.startsWith("file-more:"));
+ expect(more).toBeDefined();
+ expanded.add(more!.id.slice("file-more:".length));
+ const after = fileFocusGraph(graph, focused.path, undefined, expanded);
+
+ for (const node of before.nodes.filter((node) => !node.aggregate)) {
+ expect(after.nodes.find((other) => other.id === node.id)).toMatchObject({
+ x: node.x,
+ y: node.y,
+ });
+ }
+
+ before = after;
+ }
+});
diff --git a/web/src/components/folderAnchorUpdates.test.tsx b/web/src/components/folderAnchorUpdates.test.tsx
new file mode 100644
index 000000000..6ed74355d
--- /dev/null
+++ b/web/src/components/folderAnchorUpdates.test.tsx
@@ -0,0 +1,41 @@
+import { act, renderHook } from "@testing-library/react";
+import { expect, it } from "vitest";
+import { useFolderExplorer } from "./useFolderExplorer";
+
+const graph = (paths: string[]) => ({
+ nodes: paths.map((path) => ({ id: path, path, label: path, kind: "code" })),
+ edges: [],
+ truncated: false,
+});
+
+it("retains root anchors across weight changes, additions and removals", () => {
+ const { result, rerender } = renderHook(
+ ({ paths }) => useFolderExplorer(graph(paths), new Map()),
+ {
+ initialProps: { paths: ["a/one.ts", "b/one.ts", "c/one.ts"] },
+ },
+ );
+
+ const before = result.current.drawn.nodes.filter((n) => n.id.startsWith("folder:"));
+ rerender({ paths: ["a/one.ts", "b/one.ts", "b/two.ts", "c/one.ts"] });
+
+ for (const node of before)
+ expect(result.current.drawn.nodes.find((n) => n.id === node.id)).toMatchObject({
+ x: node.x,
+ y: node.y,
+ });
+ const removed = before.find((n) => n.id === "folder:b")!;
+ rerender({ paths: ["a/one.ts", "c/one.ts"] });
+ rerender({ paths: ["a/one.ts", "c/one.ts", "d/one.ts"] });
+ expect(result.current.drawn.nodes.find((n) => n.id === "folder:d")).toMatchObject({
+ x: removed.x,
+ y: removed.y,
+ });
+ act(() => result.current.expand("a"));
+
+ for (const node of before.filter((n) => n.id !== "folder:b"))
+ expect(result.current.drawn.nodes.find((n) => n.id === node.id)).toMatchObject({
+ x: node.x,
+ y: node.y,
+ });
+});
diff --git a/web/src/components/folderEndpointLookup.test.ts b/web/src/components/folderEndpointLookup.test.ts
new file mode 100644
index 000000000..a80195111
--- /dev/null
+++ b/web/src/components/folderEndpointLookup.test.ts
@@ -0,0 +1,40 @@
+import { expect, it, vi } from "vitest";
+import { buildFolderTree } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+
+it("resolves 10,000 file pairs without scanning 10,000 visible folders per endpoint", () => {
+ const tree = buildFolderTree({
+ nodes: Array.from({ length: 10000 }, (_, i) => ({
+ id: `f${i}`,
+ path: `folder${i}/a.ts`,
+ label: "a.ts",
+ kind: "code",
+ })),
+ edges: Array.from({ length: 10000 }, (_, i) => ({
+ source: `f${i}`,
+ target: `f${(i + 1) % 10000}`,
+ kind: "calls",
+ })),
+ });
+
+ const scan = vi.spyOn(Array.prototype, "some");
+
+ try {
+ const graph = visibleFolderGraph(
+ tree,
+ { open: new Set([""]), explicit: new Set(), revealed: new Map([["", 1000]]) },
+ () => undefined,
+ );
+
+ expect(graph.nodes).toHaveLength(10001);
+ expect(graph.edges.filter((e) => e.kind === "folder-minor")).toHaveLength(10000);
+ expect(
+ scan.mock.contexts.reduce(
+ (sum, array) => sum + (Array.isArray(array) ? array.length : 0),
+ 0,
+ ),
+ ).toBeLessThan(100000);
+ } finally {
+ scan.mockRestore();
+ }
+});
diff --git a/web/src/components/folderFanLabels.test.ts b/web/src/components/folderFanLabels.test.ts
new file mode 100644
index 000000000..906471503
--- /dev/null
+++ b/web/src/components/folderFanLabels.test.ts
@@ -0,0 +1,158 @@
+import Sigma from "sigma";
+import { expect, it, vi } from "vitest";
+import { buildFolderTree } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+import { layoutFolderGraph } from "./folderLayout";
+import { buildSigmaGraph } from "./sigmaGraphData";
+import { createLabelPainter } from "./sigmaLabels";
+import { installFakeWebGL } from "../test/fakeWebGL";
+
+it.each([0, 1])(
+ "places the app fan outside the arc without overlapping names or counts (reveal %i)",
+ (reveal) => {
+ const restore = installFakeWebGL();
+ const container = document.createElement("div");
+ document.body.append(container);
+
+ const names = [
+ "validationproduct",
+ "views",
+ ...Array.from({ length: 38 }, (_, i) => `service${i}`),
+ ];
+
+ const tree = buildFolderTree({
+ nodes: [
+ ...Array.from({ length: 10 }, (_, i) => ({
+ id: `doc${i}`,
+ kind: "code",
+ path: `docs/sub/f${i}.ts`,
+ label: `doc${i}`,
+ })),
+ ...["validationproduct", "views"].map((name) => ({
+ id: `${name}extra`,
+ kind: "code",
+ path: `pkg/app/${name}/extra.ts`,
+ label: name,
+ })),
+ ...names.map((name) => ({
+ id: name,
+ kind: "code",
+ path: `pkg/app/${name}/file.ts`,
+ label: name,
+ })),
+ ],
+ edges: [],
+ });
+
+ const layout = layoutFolderGraph(
+ tree,
+ visibleFolderGraph(
+ tree,
+ {
+ open: new Set(["", "pkg", "pkg/app"]),
+ explicit: new Set(["pkg/app"]),
+ revealed: new Map([["pkg/app", reveal]]),
+ },
+ () => undefined,
+ "pkg/app",
+ ),
+ );
+
+ const fan = layout.nodes.filter(
+ (n) => (n.path === "pkg/app" && n.aggregate) || n.path?.startsWith("pkg/app/"),
+ );
+
+ expect(fan.length).toBeGreaterThanOrEqual(reveal ? 20 : 14);
+ expect(fan.some((n) => n.aggregate)).toBe(true);
+ const parent = layout.nodes.find((n) => n.id === "folder:pkg/app")!;
+ const ys = fan.map((n) => n.y ?? 0);
+ const scale = (reveal ? 800 : 600) / (Math.max(...ys) - Math.min(...ys));
+
+ const nodes = [parent, ...fan].map((n) => ({
+ ...n,
+ center: n.id === parent.id,
+ labelDetail: "2 notes · 62 files 11 links to docs",
+ x: (reveal ? 1300 : 568) + ((n.x ?? 0) - (parent.x ?? 0)) * scale,
+ y: (reveal ? 60 : 40) + ((n.y ?? 0) - Math.min(...ys)) * scale,
+ }));
+
+ const { graph } = buildSigmaGraph({
+ nodes,
+ edges: [],
+ scope: { mode: "global" },
+ fixed: true,
+ explorer: true,
+ connectionCounts: new Map(),
+ globalLayout: new Map(),
+ communityColors: new Map(),
+ problemCounts: new Map(),
+ edgeFaint: "#ccc",
+ });
+
+ const sigma = new Sigma(graph, container);
+ const context = document.createElement("canvas").getContext("2d")!;
+
+ try {
+ vi.spyOn(sigma, "getDimensions").mockReturnValue(
+ reveal ? { width: 1800, height: 1000 } : { width: 1170, height: 698 },
+ );
+ vi.spyOn(sigma, "framedGraphToViewport").mockImplementation((p) => p);
+ vi.spyOn(sigma, "scaleSize").mockReturnValue(6);
+ vi.spyOn(sigma, "getNodeDisplayData").mockImplementation((id) =>
+ graph.hasNode(id)
+ ? {
+ ...graph.getNodeAttributes(id),
+ forceLabel: true,
+ hidden: false,
+ highlighted: false,
+ zIndex: 0,
+ type: "circle",
+ }
+ : undefined,
+ );
+ const measure = context.measureText.bind(context);
+ vi.spyOn(context, "measureText").mockImplementation((text) => ({
+ ...measure(text),
+ width: text.length * 7,
+ }));
+ const drawn = vi.spyOn(context, "fillText");
+
+ const painter = createLabelPainter(
+ () => sigma,
+ () => ({ label: "black", canvas: "white" }),
+ );
+
+ for (const node of nodes)
+ painter.draw(
+ context,
+ { key: node.id, label: node.label, x: node.x, y: node.y, size: 6, color: "blue" },
+ sigma.getSettings(),
+ );
+ const boxes = painter.occupied();
+ expect(
+ nodes.flatMap((n) => (drawn.mock.calls.some(([text]) => text === n.label) ? [] : [n.id])),
+ ).toEqual([]);
+ expect(boxes).toHaveLength(nodes.length);
+
+ for (const node of nodes)
+ if (node.labelDetail)
+ expect(drawn.mock.calls.some(([text]) => text === node.labelDetail)).toBe(true);
+
+ for (let i = 0; i < boxes.length; i++) {
+ for (const b of boxes.slice(i + 1)) {
+ const a = boxes[i];
+ expect(a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]).toBe(false);
+ }
+ }
+
+ // The selected parent is placed first; every child is on its left-facing arc.
+ const children = nodes.slice(1).sort((a, b) => a.y - b.y || a.id.localeCompare(b.id));
+ children.forEach((node, i) => expect(boxes[i + 1][2]).toBeLessThan(node.x));
+ } finally {
+ sigma.kill();
+ container.remove();
+ vi.restoreAllMocks();
+ restore();
+ }
+ },
+);
diff --git a/web/src/components/folderGraph.test.ts b/web/src/components/folderGraph.test.ts
index 8c1a21a0f..e1d14ecb3 100644
--- a/web/src/components/folderGraph.test.ts
+++ b/web/src/components/folderGraph.test.ts
@@ -1,120 +1,413 @@
-import { describe, expect, it } from "vitest";
-
+import { describe, expect, it, vi } from "vitest";
import type { GraphNode } from "../api/types";
-import { aggregateByFolder } from "./folderGraph";
+import { buildFolderTree, initialOpenFolders } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+import { layoutFolderGraph } from "./folderLayout";
+
+const code = (path: string): GraphNode => ({ id: `code:${path}`, path, label: path, kind: "code" });
-const note = (path: string, resolvedType?: string): GraphNode => ({
+const note = (path: string): GraphNode => ({
id: `note:${path}`,
+ path,
label: path,
kind: "note",
- path,
- resolvedType,
+ resolvedType: "Spec",
});
-const code = (path: string): GraphNode => ({ id: `code:${path}`, label: path, kind: "code", path });
+const color = () => "red";
-describe("aggregateByFolder", () => {
- it("preserves a capped source graph's truncation warning", () => {
- expect(
- aggregateByFolder({ nodes: [note("a.md")], edges: [], truncated: true }, () => "red")
- .truncated,
- ).toBe(true);
- });
+const state = (paths: string[] = [], revealed: string[] = []) => ({
+ open: new Set(["", ...paths]),
+ explicit: new Set(paths),
+ revealed: new Map(revealed.map((path) => [path, 1])),
+});
- it("opens a dominant folder into subfolders, folds small ones back, and counts links between folders", () => {
- const nodes = [
- ...Array.from({ length: 40 }, (_, i) => note(`docs/specs/s${i}.md`, "Spec")),
- ...Array.from({ length: 30 }, (_, i) => code(`pkg/app/a${i}.go`)),
- ...Array.from({ length: 30 }, (_, i) => code(`pkg/store/s${i}.go`)),
- code("pkg/tiny/t.go"),
- note("README.md"),
- ];
-
- const edges = [
- { source: "note:docs/specs/s0.md", target: "code:pkg/app/a0.go", kind: "mentions" },
- { source: "note:docs/specs/s1.md", target: "code:pkg/app/a1.go", kind: "mentions" },
- { source: "code:pkg/app/a0.go", target: "code:pkg/app/a1.go", kind: "calls" },
- ];
-
- const graph = aggregateByFolder({ nodes, edges }, (type) => `var(--${type})`);
- const byPath = new Map(graph.nodes.map((node) => [node.path, node]));
-
- expect(graph.nodes.map((node) => node.id.slice("folder:".length)).sort()).toEqual([
- "",
- "docs",
- "docs/specs",
- "pkg",
- "pkg/(smaller folders)",
- "pkg/app",
- "pkg/store",
+describe("complete folder model", () => {
+ it("counts all files and note types, excluding embedded items, and deduplicates file pairs", () => {
+ const tree = buildFolderTree({
+ nodes: [
+ note("docs/a.md"),
+ code("src/a.ts"),
+ { id: "criterion", kind: "embedded", label: "criterion", notePath: "docs/a.md" },
+ ],
+ edges: [
+ { source: "note:docs/a.md", target: "criterion", kind: "embeds" },
+ { source: "criterion", target: "code:src/a.ts", kind: "mentions" },
+ { source: "note:docs/a.md", target: "code:src/a.ts", kind: "mentions" },
+ ],
+ });
+
+ expect(tree.root).toMatchObject({
+ notes: 1,
+ files: 1,
+ untyped: 0,
+ types: new Map([["Spec", 1]]),
+ });
+ expect(tree.files.size).toBe(2);
+ expect(tree.links).toEqual([
+ { source: "code:src/a.ts", target: "note:docs/a.md", noteCode: 1, other: 0 },
]);
- expect(byPath.get("docs/specs")?.fill).toBe("var(--Spec)");
- expect(byPath.get("pkg/app")?.fill).toBe("var(--graph-code)");
- expect(byPath.get("docs/specs")?.fillKey).toBe("Spec");
- expect(graph.nodes.find((node) => node.id === "folder:pkg/(smaller folders)")?.label).toBe(
- "1 smaller folders 1 file",
+ const graph = visibleFolderGraph(tree, state(), color);
+ expect(graph.edges.find((e) => e.kind === "folder-crosslink")).toMatchObject({
+ weight: 1,
+ relationLabel: "1 note–code links",
+ });
+ });
+ it("budgets children without losing any file and reveals another bounded batch", () => {
+ const tree = buildFolderTree({
+ nodes: Array.from({ length: 40 }, (_, i) => code(`src/part${i}/a.ts`)),
+ edges: [],
+ truncated: true,
+ });
+
+ const graph = visibleFolderGraph(tree, state(["src"]), color);
+ const children = graph.children.get("src") ?? [];
+ expect(children.length).toBeLessThanOrEqual(24);
+ expect(children.reduce((sum, c) => sum + c.members.length, 0)).toBe(40);
+ expect(children.find((c) => c.node.aggregate)?.node.id).toBe("more:src");
+ const all = visibleFolderGraph(tree, state(["src"], ["src"]), color);
+ expect(all.children.get("src")).toHaveLength(28);
+ expect(all.truncated).toBe(true);
+ });
+ it("makes direct files reachable even in a folder containing subfolders", () => {
+ const tree = buildFolderTree({
+ nodes: [code("src/sub/a.ts"), ...Array.from({ length: 35 }, (_, i) => code(`src/f${i}.ts`))],
+ edges: [],
+ });
+
+ const collapsed = visibleFolderGraph(tree, state(), color);
+ expect(collapsed.nodes.map((n) => n.id)).toEqual(["folder:", "folder:src"]);
+ const open = visibleFolderGraph(tree, state(["src"], ["src"]), color);
+ expect(open.nodes.filter((n) => n.kind === "code")).toHaveLength(22);
+ expect(open.children.get("src")?.reduce((sum, c) => sum + c.members.length, 0)).toBe(36);
+ });
+ it("folds root files into a labelled reachable aggregate beside folders", () => {
+ const tree = buildFolderTree({
+ nodes: [note("README.md"), ...Array.from({ length: 30 }, (_, i) => code(`part${i}/a.ts`))],
+ edges: [],
+ });
+
+ const graph = visibleFolderGraph(tree, state(), color);
+ expect(graph.nodes.find((node) => node.id === "more:")).toMatchObject({
+ label: "+21 folders · 1 note",
+ labelDetail: "total 1 note · 21 files",
+ childCount: 22,
+ });
+ expect(graph.children.get("")?.reduce((sum, child) => sum + child.members.length, 0)).toBe(31);
+ });
+ it("budgets top-level folders beside counted root files", () => {
+ const tree = buildFolderTree({
+ nodes: [note("README.md"), ...Array.from({ length: 30 }, (_, i) => code(`part${i}/a.ts`))],
+ edges: [],
+ });
+
+ const graph = visibleFolderGraph(tree, state(), color);
+ expect(graph.children.get("")?.filter((child) => child.folder)).toHaveLength(9);
+ });
+ it("auto-opens only dominant top-level folders", () => {
+ const tree = buildFolderTree({
+ nodes: [
+ ...Array.from({ length: 40 }, (_, i) => note(`docs/specs/nested/a${i}.md`)),
+ code("pkg/a.ts"),
+ ],
+ edges: [],
+ });
+
+ expect(initialOpenFolders(tree)).toEqual(new Set(["", "docs"]));
+ });
+});
+
+describe("stable radial containment", () => {
+ it("opening a folder preserves every coordinate outside its subtree and its own anchor", () => {
+ const tree = buildFolderTree({
+ nodes: [code("a/one.ts"), code("a/sub/two.ts"), note("b/readme.md"), code("c/main.ts")],
+ edges: [],
+ });
+
+ const before = layoutFolderGraph(tree, visibleFolderGraph(tree, state(), color));
+ const after = layoutFolderGraph(tree, visibleFolderGraph(tree, state(["a"]), color));
+
+ for (const node of before.nodes)
+ expect(after.nodes.find((n) => n.id === node.id)).toMatchObject({ x: node.x, y: node.y });
+ expect(after.layoutExtent).toBe(before.layoutExtent);
+ expect(after.nodes.every((n) => Math.hypot(n.x ?? 0, n.y ?? 0) <= after.layoutExtent)).toBe(
+ true,
);
- expect(byPath.get("")?.label).toBe("Vault 41 notes, 61 files");
- expect(
- graph.edges
- .filter((edge) => edge.kind === "folder-containment")
- .map(({ source, target }) => [source, target]),
- ).toEqual(
- expect.arrayContaining([
- ["folder:", "folder:docs"],
- ["folder:docs", "folder:docs/specs"],
- ["folder:", "folder:pkg"],
- ["folder:pkg", "folder:pkg/app"],
- ["folder:pkg", "folder:pkg/(smaller folders)"],
- ]),
+ expect(after.nodes.every((n) => Number.isFinite(n.x) && Number.isFinite(n.y))).toBe(true);
+ expect(after.edges.filter((e) => e.kind === "folder-containment")).toEqual(
+ expect.arrayContaining([expect.objectContaining({ source: "folder:", target: "folder:b" })]),
);
- expect(aggregateByFolder({ nodes, edges: [] }, () => "red").edges).toEqual(
- graph.edges.filter((edge) => edge.kind === "folder-containment"),
+ });
+ it("keeps both dominant fan anchors fixed when a descendant opens", () => {
+ const tree = buildFolderTree({
+ nodes: [
+ ...Array.from({ length: 40 }, (_, i) => code(`pkg/app/p${i}/a.ts`)),
+ ...Array.from({ length: 40 }, (_, i) => note(`docs/topic${i}/a.md`)),
+ ],
+ edges: [],
+ });
+
+ const open = initialOpenFolders(tree);
+
+ const before = layoutFolderGraph(
+ tree,
+ visibleFolderGraph(tree, { open, explicit: new Set(), revealed: new Map() }, color),
);
- // Links inside one folder are not drawn; links between folders add up.
- expect(graph.edges.filter((edge) => edge.kind === "folder-minor")).toEqual([
- expect.objectContaining({ source: "folder:docs/specs", target: "folder:pkg/app", weight: 2 }),
- ]);
+
+ const after = layoutFolderGraph(
+ tree,
+ visibleFolderGraph(
+ tree,
+ {
+ open: new Set([...open, "pkg/app"]),
+ explicit: new Set(["pkg/app"]),
+ revealed: new Map(),
+ },
+ color,
+ ),
+ );
+
+ for (const node of before.nodes)
+ expect(after.nodes.find((n) => n.id === node.id)).toMatchObject({ x: node.x, y: node.y });
+ expect(before.children.get("docs")).toHaveLength(10);
+ expect(before.children.get("docs")?.reduce((sum, child) => sum + child.members.length, 0)).toBe(
+ 40,
+ );
+ const pkg = before.nodes.find((n) => n.id === "folder:pkg")!;
+ const docs = before.nodes.find((n) => n.id === "folder:docs")!;
+ expect(pkg.x! * docs.x!).toBeLessThan(0);
});
+ it("deep expansions add local radii instead of amplifying narrow root wedges", () => {
+ const nodes = Array.from({ length: 20 }, (_, i) => code(`large/p${i}/a.ts`));
- it("counts notes, not embedded items, and keeps weak links for hover", () => {
- const criterion = (path: string, i: number): GraphNode => ({
- id: `embedded:${path}#c${i}`,
- label: `c${i}`,
- kind: "embedded",
- notePath: path,
- resolvedType: "AcceptanceCriterion",
+ const paths = Array.from(
+ { length: 12 },
+ (_, i) => "tiny/" + Array.from({ length: i }, () => "sub").join("/"),
+ );
+
+ nodes.push(code("tiny/" + "sub/".repeat(11) + "a.ts"));
+ const tree = buildFolderTree({ nodes, edges: [] });
+ const before = layoutFolderGraph(tree, visibleFolderGraph(tree, state(), color));
+ const after = layoutFolderGraph(tree, visibleFolderGraph(tree, state(paths), color));
+ expect(after.layoutExtent).toBe(before.layoutExtent);
+ expect(after.layoutExtent).toBeLessThan(10000);
+
+ for (const edge of after.edges.filter(
+ (e) => e.kind === "folder-containment" && e.source !== "folder:",
+ )) {
+ const parent = after.nodes.find((n) => n.id === edge.source)!;
+ const child = after.nodes.find((n) => n.id === edge.target)!;
+ expect(Math.hypot(child.x! - parent.x!, child.y! - parent.y!)).toBeLessThanOrEqual(1000);
+ }
+ });
+ it("places linked top-level siblings next to each other", () => {
+ const tree = buildFolderTree({
+ nodes: [note("docs/a.md"), code("web/a.ts"), code("pkg/a.go")],
+ edges: [{ source: "note:docs/a.md", target: "code:web/a.ts", kind: "mentions" }],
});
- const nodes = [
- note("docs/specs/a.md", "TechnicalSpec"),
- note("docs/specs/b.md", "TechnicalSpec"),
- ...Array.from({ length: 30 }, (_, i) => criterion("docs/specs/a.md", i)),
- ...Array.from({ length: 4 }, (_, i) => code(`pkg/a${i}.go`)),
- ...Array.from({ length: 4 }, (_, i) => code(`cmd/c${i}.go`)),
- ];
-
- const link = (source: string, target: string) => ({ source, target, kind: "mentions" });
-
- const edges = [
- ...Array.from({ length: 20 }, () => link("note:docs/specs/a.md", "code:pkg/a0.go")),
- ...Array.from({ length: 10 }, () => link("code:pkg/a1.go", "code:cmd/c0.go")),
- link("note:docs/specs/b.md", "code:cmd/c1.go"),
- ];
-
- const graph = aggregateByFolder({ nodes, edges }, (type) => `var(--${type})`);
- const specs = graph.nodes.find((node) => node.path === "docs/specs");
-
- // Thirty embedded criteria neither size nor color the folder.
- expect(specs).toMatchObject({ label: "docs/specs 2 notes", fillKey: "TechnicalSpec" });
- expect(
- graph.edges
- .filter((edge) => edge.kind === "folder-minor")
- .map((edge) => [edge.source, edge.target, edge.kind]),
- ).toEqual([
- ["folder:cmd", "folder:docs/specs", "folder-minor"],
- ["folder:cmd", "folder:pkg", "folder-minor"],
- ["folder:docs/specs", "folder:pkg", "folder-minor"],
- ]);
+ const graph = layoutFolderGraph(tree, visibleFolderGraph(tree, state(), color));
+
+ const angles = graph.nodes
+ .filter((n) => n.id !== "folder:")
+ .sort((a, b) => Math.atan2(a.y ?? 0, a.x ?? 0) - Math.atan2(b.y ?? 0, b.x ?? 0))
+ .map((n) => n.id);
+
+ expect(angles.slice(0, 2)).toEqual(["folder:docs", "folder:web"]);
+ });
+});
+
+it("bundles underlying links while keeping focused children separate", () => {
+ const tree = buildFolderTree({
+ nodes: [note("docs/a.md"), note("docs/b.md"), code("pkg/a/a.ts"), code("pkg/b/b.ts")],
+ edges: [
+ { source: "note:docs/a.md", target: "code:pkg/a/a.ts", kind: "mentions" },
+ { source: "note:docs/b.md", target: "code:pkg/a/a.ts", kind: "mentions" },
+ { source: "note:docs/b.md", target: "code:pkg/b/b.ts", kind: "mentions" },
+ ],
+ });
+
+ const open = state(["pkg", "docs"]);
+ expect(
+ visibleFolderGraph(tree, open, color).edges.filter((e) => e.kind === "folder-crosslink"),
+ ).toEqual([
+ {
+ source: "folder:docs",
+ target: "folder:pkg",
+ kind: "folder-crosslink",
+ weight: 3,
+ relationLabel: "3 note–code links",
+ },
+ ]);
+ const focused = visibleFolderGraph(tree, open, color, "pkg");
+ expect(focused.edges.filter((e) => e.kind === "folder-crosslink")).toEqual([
+ {
+ source: "folder:pkg",
+ target: "folder:docs",
+ kind: "folder-crosslink",
+ weight: 3,
+ relationLabel: "3 note–code links",
+ },
+ ]);
+ expect(focused.edges.filter((e) => e.kind === "folder-child-crosslink")).toHaveLength(2);
+ expect(focused.nodes.find((n) => n.id === "folder:pkg")?.labelDetail).toContain(
+ "3 links to docs",
+ );
+ expect(focused.nodes.find((n) => n.id === "folder:pkg/a")?.labelDetail).toContain(
+ "2 links to docs",
+ );
+ expect(focused.nodes.find((n) => n.id === "folder:pkg/b")?.labelDetail).toContain(
+ "1 link to docs",
+ );
+});
+
+it("overflow gives direct counts once and labels descendant totals explicitly", () => {
+ const tree = buildFolderTree({
+ nodes: [...Array.from({ length: 12 }, (_, i) => note(`n${i}.md`)), code("a.ts")],
+ edges: [],
+ });
+
+ expect(visibleFolderGraph(tree, state(), color).nodes.find((n) => n.aggregate)).toMatchObject({
+ label: "+12 notes · 1 file",
+ labelDetail: undefined,
+ });
+
+ const nested = buildFolderTree({
+ nodes: Array.from({ length: 20 }, (_, i) => note(`docs/f${i}/n.md`)),
+ edges: [],
+ });
+
+ expect(
+ visibleFolderGraph(nested, state(["docs"]), color).nodes.find((n) => n.aggregate),
+ ).toMatchObject({ label: "+7 folders", labelDetail: "total 7 notes" });
+});
+
+it("keeps repeated folder names and parent prefixes on one line, with counts separate", () => {
+ const tree = buildFolderTree({ nodes: [code("web/a.ts"), code("pkg/web/b.ts")], edges: [] });
+ const graph = visibleFolderGraph(tree, state(["pkg"]), color);
+ expect(graph.nodes.find((node) => node.id === "folder:web")).toMatchObject({
+ label: "Vault/ web",
+ labelDetail: "1 file",
+ });
+ expect(graph.nodes.find((node) => node.id === "folder:pkg/web")).toMatchObject({
+ label: "pkg/ web",
+ labelDetail: "1 file",
});
});
+
+it("computes only root affinity and preserves the linked root ordering", () => {
+ const tree = buildFolderTree({
+ nodes: ["a/x/one.ts", "b/x/one.ts", "c/x/one.ts"].map(code),
+ edges: [{ source: "code:a/x/one.ts", target: "code:c/x/one.ts", kind: "calls" }],
+ });
+
+ expect([...tree.affinity.keys()]).toEqual([""]);
+ expect(tree.affinity.get("")).toEqual(new Map([['["folder:a","folder:c"]', 1]]));
+ const graph = layoutFolderGraph(tree, visibleFolderGraph(tree, state(), color));
+
+ const order = graph.nodes
+ .filter((n) => ["folder:a", "folder:b", "folder:c"].includes(n.id))
+ .sort((a, b) => Math.atan2(a.y ?? 0, a.x ?? 0) - Math.atan2(b.y ?? 0, b.x ?? 0))
+ .map((n) => n.id);
+
+ expect(order).toEqual(["folder:a", "folder:c", "folder:b"]);
+});
+
+it("preserves server-collapsed modules, counts and links as terminal groups", () => {
+ const tree = buildFolderTree({
+ nodes: [
+ {
+ id: "module:pkg/app",
+ path: "pkg/app",
+ label: "pkg/app",
+ kind: "module",
+ collapsed: true,
+ childCount: 12500,
+ },
+ {
+ id: "module:docs/specs",
+ path: "docs/specs",
+ label: "docs/specs",
+ kind: "module",
+ collapsed: true,
+ childCount: 800,
+ },
+ note("README.md"),
+ ],
+ edges: [{ source: "module:pkg/app", target: "module:docs/specs", kind: "mentions", weight: 7 }],
+ truncated: true,
+ });
+
+ expect(tree.root.items).toBe(13300);
+ expect(tree.links).toEqual([
+ { source: "module:docs/specs", target: "module:pkg/app", noteCode: 7, other: 0 },
+ ]);
+ const graph = visibleFolderGraph(tree, state(["pkg", "docs", "pkg/app"]), color);
+
+ expect(graph.nodes.find((node) => node.id === "folder:pkg/app")).toMatchObject({
+ labelDetail: "12,500 items (collapsed)",
+ childCount: 12500,
+ collapsed: true,
+ });
+ expect(graph.children.get("pkg")?.[0].folder).toBeUndefined();
+ expect(graph.children.has("pkg/app")).toBe(false);
+ expect(graph.edges.find((edge) => edge.kind === "folder-crosslink")).toMatchObject({ weight: 7 });
+ expect(graph.truncated).toBe(true);
+
+ const overflowTree = buildFolderTree({
+ nodes: Array.from({ length: 16 }, (_, i) => ({
+ id: `module:src/m${i}`,
+ path: `src/m${i}`,
+ label: `m${i}`,
+ kind: "module",
+ collapsed: true,
+ childCount: 250,
+ })),
+ edges: [],
+ });
+
+ const overflow = visibleFolderGraph(overflowTree, state(["src"]), color);
+
+ expect(overflow.nodes.find((node) => node.aggregate)).toMatchObject({
+ label: "+3 folders",
+ labelDetail: "total 750 items (collapsed)",
+ childCount: 750,
+ });
+});
+
+it("reveals thousands of direct files in bounded batches and counts duplicate names linearly", () => {
+ const tree = buildFolderTree({
+ nodes: Array.from({ length: 4000 }, (_, i) => code(`f${i}.ts`)),
+ edges: [],
+ });
+
+ const before = visibleFolderGraph(tree, state(), color);
+ const first = visibleFolderGraph(tree, state([], [""]), color);
+ expect(first.nodes.length - before.nodes.length).toBeLessThanOrEqual(11);
+ expect(first.nodes.filter((n) => n.kind === "code")).toHaveLength(10);
+ expect(first.nodes.find((n) => n.aggregate)).toMatchObject({ childCount: 3990 });
+
+ const second = visibleFolderGraph(tree, { ...state(), revealed: new Map([["", 2]]) }, color);
+ expect(second.nodes.filter((n) => n.kind === "code")).toHaveLength(20);
+ expect(second.nodes.find((n) => n.aggregate)).toMatchObject({ childCount: 3980 });
+
+ // Count name-map lookups with many visible folders, independently of the file budget.
+ const folders = buildFolderTree({
+ nodes: Array.from({ length: 1000 }, (_, i) => code(`folder${i}/same.ts`)),
+ edges: [],
+ });
+
+ const get = vi.spyOn(Map.prototype, "get");
+
+ try {
+ const graph = visibleFolderGraph(
+ folders,
+ { ...state(), revealed: new Map([["", 100]]) },
+ color,
+ );
+
+ expect(get.mock.calls.length).toBeLessThan(graph.nodes.length * 20);
+ } finally {
+ get.mockRestore();
+ }
+});
diff --git a/web/src/components/folderGraph.ts b/web/src/components/folderGraph.ts
index c22267af7..d60381fb3 100644
--- a/web/src/components/folderGraph.ts
+++ b/web/src/components/folderGraph.ts
@@ -1,275 +1,330 @@
-import type { GraphEdge, GraphNode } from "../api/types";
-import { publicTypeName } from "../lib/typeNames";
+import type { GraphEdge } from "../api/types";
import { CODE_COLOR, type GraphViewNode, UNTYPED_COLOR } from "./graphViewShared";
+import {
+ filePath,
+ folderWeight,
+ nodeTotals,
+ sumTotals,
+ totalsLabel,
+ type Folder,
+ type FolderTree,
+ type FolderTotals,
+} from "./folderTree";
-/** A folder holding more than this share of the graph opens into its subfolders. */
-const SPLIT_SHARE = 0.15;
+export const MINOR_FOLDER_LINK = "folder-minor";
-/** Subfolders below this share of the graph and of its notes fold back into one node for their parent. */
-const MERGE_SHARE = 0.015;
+export const CODE_FILL_KEY = "__code__";
-/**
- * Notes are few beside code files, so their shares are larger: a folder
- * holding a fifth of the notes opens, and a subfolder below a twentieth of
- * them folds back.
- */
-const NOTE_SPLIT_SHARE = 0.2;
+export const UNTYPED_FILL_KEY = "__untyped__";
-const NOTE_MERGE_SHARE = 0.05;
+// Worker B owns the corresponding additive GraphViewNode fields.
+export type FolderViewNode = GraphViewNode & {
+ x?: number;
+ y?: number;
+ labelDetail?: string;
+ aggregate?: boolean;
+};
-/** Cross-folder links appear only while one of their folders is hovered. */
-export const MINOR_FOLDER_LINK = "folder-minor";
+export type FolderChild = {
+ node: FolderViewNode;
+ totals: FolderTotals;
+ members: string[];
+ folder?: Folder;
+};
+
+export type FolderGraph = {
+ nodes: FolderViewNode[];
+ edges: GraphEdge[];
+ truncated: boolean;
+ children: Map;
+};
+
+export type FolderExpansion = {
+ open: ReadonlySet;
+ explicit: ReadonlySet;
+ revealed: ReadonlyMap;
+};
+
+function fill(totals: FolderTotals, color: (type: string) => string | undefined) {
+ const [best] = [...totals.types].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
-function nodePath(node: GraphNode) {
- return (node.notePath || node.path || "").replace(/^\/+/, "");
+ if (best && best[1] >= totals.files && best[1] >= totals.untyped)
+ return { fillKey: best[0], fill: color(best[0]) ?? UNTYPED_COLOR };
+
+ return totals.files >= totals.untyped
+ ? { fillKey: CODE_FILL_KEY, fill: CODE_COLOR }
+ : { fillKey: UNTYPED_FILL_KEY, fill: UNTYPED_COLOR };
}
-/** The node's folder segments; a module node is its own folder. */
-function folderSegments(node: GraphNode) {
- const parts = nodePath(node).split("/").filter(Boolean);
+function folderChild(folder: Folder, color: (type: string) => string | undefined): FolderChild {
+ const collapsed = folder.direct.some((node) => node.kind === "module");
- return node.kind === "module" ? parts : parts.slice(0, -1);
+ return {
+ folder: collapsed ? undefined : folder,
+ totals: folder,
+ members: folder.members,
+ node: {
+ id: `folder:${folder.path}`,
+ kind: "module",
+ path: folder.path,
+ label: folder.path.split("/").pop() || "Vault",
+ labelDetail: totalsLabel(folder),
+ childCount: folder.notes + folder.files + (folder.items ?? 0),
+ collapsed,
+ ...fill(folder, color),
+ },
+ };
}
-/**
- * What a folder holds: its notes and code files. Embedded items (acceptance
- * criteria, user stories) live inside notes, so they neither size nor color it.
- */
-const weightOf = (node: GraphNode) =>
- node.kind === "module" ? Math.max(1, node.childCount ?? 1) : node.kind === "embedded" ? 0 : 1;
+export function visibleFolderChildren(
+ tree: FolderTree,
+ folder: Folder,
+ state: FolderExpansion,
+ color: (type: string) => string | undefined,
+): FolderChild[] {
+ const score = (child: FolderChild) =>
+ folderWeight(child.totals) +
+ child.members.reduce((sum, id) => sum + (tree.linkCounts.get(id)?.noteCode ?? 0), 0);
+
+ const folders = folder.folders
+ .map((f) => folderChild(f, color))
+ .sort((a, b) => score(b) - score(a) || a.node.id.localeCompare(b.node.id));
+
+ const files: FolderChild[] = folder.direct.map((node) => ({
+ node: {
+ ...node,
+ label: filePath(node).split("/").pop() || node.label,
+ labelDetail: totalsLabel(nodeTotals(node)),
+ },
+ totals: nodeTotals(node),
+ members: [node.id],
+ }));
+
+ files.sort((a, b) => {
+ const x = tree.linkCounts.get(a.node.id),
+ y = tree.linkCounts.get(b.node.id);
+
+ return (
+ (y?.noteCode ?? 0) - (x?.noteCode ?? 0) ||
+ (y?.other ?? 0) - (x?.other ?? 0) ||
+ a.node.id.localeCompare(b.node.id)
+ );
+ });
-const isNote = (node: GraphNode) => node.kind === "note";
+ const showFiles =
+ folder.path === "" || state.explicit.has(folder.path) || (!folders.length && files.length <= 8);
-const fmt = (count: number) => count.toLocaleString("en-US");
+ const budget = showFiles && state.explicit.has(folder.path) ? 14 : 10;
+ const fileSlots = showFiles ? Math.min(files.length, folders.length ? 8 : budget - 1) : 0;
-type Folder = { path: string; weight: number; members: GraphNode[]; merged: number };
+ const candidates: FolderChild[] =
+ folders.length + files.length <= budget
+ ? [...folders, ...(showFiles ? files : [])]
+ : [...folders.slice(0, budget - fileSlots - 1), ...files.slice(0, fileSlots)];
-/** What a folder's count counts: "76 notes", "1,295 files", or both. */
-function contents(members: readonly GraphNode[]) {
- const notes = members.filter(isNote).length;
- const files = members.reduce((sum, node) => sum + (isNote(node) ? 0 : weightOf(node)), 0);
- const noun = (n: number, one: string) => `${fmt(n)} ${n === 1 ? one : `${one}s`}`;
+ const allCount = folders.length + files.length;
- if (notes && files) return `${noun(notes, "note")}, ${noun(files, "file")}`;
+ const kept =
+ folder.path === ""
+ ? folders.slice(0, allCount > budget ? budget - 1 : budget)
+ : candidates.slice(0, allCount > budget ? budget - 1 : budget);
- return notes ? noun(notes, "note") : noun(files, "file");
-}
+ const keptIds = new Set(kept.map((c) => c.node.id));
+ const remaining = [...folders, ...files].filter((c) => !keptIds.has(c.node.id));
+ const revealedCount = (state.revealed.get(folder.path) ?? 0) * budget;
+ kept.push(...remaining.slice(0, revealedCount));
+ const selected = new Set();
-export type FolderGraph = { nodes: GraphViewNode[]; edges: GraphEdge[]; truncated: boolean };
-
-/**
- * The root Explorer view: one node per folder, sized by what it holds and
- * colored by what most of it is (a note type, code, or untyped notes), with
- * a containment tree and secondary links counted between folders. A folder
- * holding a large share of the vault
- * opens into its subfolders, and its small subfolders fold back into one node,
- * so no single node swallows the picture and none is noise. Selecting a folder
- * loads its own graph.
- */
-export function aggregateByFolder(
- graph: { nodes: readonly GraphNode[]; edges: readonly GraphEdge[]; truncated?: boolean },
- typeColor: (type: string) => string | undefined,
-): FolderGraph {
- const total = graph.nodes.reduce((sum, node) => sum + weightOf(node), 0);
- const totalNotes = graph.nodes.filter(isNote).length;
- const split = new Set();
+ for (const path of state.explicit) {
+ const parts = path.split("/");
- // The deepest folder prefix not marked for splitting.
- const leafFor = (node: GraphNode) => {
- const segments = folderSegments(node);
- let depth = 1;
+ parts.forEach((_, index) => selected.add(`folder:${parts.slice(0, index + 1).join("/")}`));
+ }
- while (depth < segments.length && split.has(segments.slice(0, depth).join("/"))) depth += 1;
+ const hidden = remaining.slice(revealedCount).filter((child) => {
+ if (!selected.has(child.node.id)) return true;
+ kept.push(child);
- return segments.slice(0, depth).join("/");
- };
+ return false;
+ });
- for (;;) {
- const weights = new Map();
+ if (hidden.length) {
+ const totals = sumTotals(hidden.map((c) => c.totals));
+ const hiddenFolders = hidden.filter((c) => c.node.kind === "module").length;
+
+ const hiddenNotes = hidden.filter((c) => !c.folder && c.node.kind === "note").length;
+ const hiddenFiles = hidden.length - hiddenFolders - hiddenNotes;
+ const noun = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
+
+ const label = [
+ hiddenFolders ? noun(hiddenFolders, "folder") : "",
+ hiddenNotes ? noun(hiddenNotes, "note") : "",
+ hiddenFiles ? noun(hiddenFiles, "file") : "",
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+ kept.push({
+ node: {
+ id: `more:${folder.path}`,
+ path: folder.path,
+ kind: "module",
+ label: `+${label}`,
+ labelDetail: hiddenFolders ? `total ${totalsLabel(totals)}` : undefined,
+ aggregate: true,
+ childCount: totals.notes + totals.files + (totals.items ?? 0),
+ ...fill(totals, color),
+ },
+ totals,
+ members: hidden.flatMap((c) => c.members),
+ });
+ }
- for (const node of graph.nodes) {
- const path = leafFor(node);
- const entry = weights.get(path) ?? { weight: 0, notes: 0, deeper: false };
- entry.weight += weightOf(node);
- entry.notes += isNote(node) ? 1 : 0;
- entry.deeper ||= folderSegments(node).length > (path ? path.split("/").length : 0);
- weights.set(path, entry);
+ return kept;
+}
+
+export function visibleFolderGraph(
+ tree: FolderTree,
+ state: FolderExpansion,
+ color: (type: string) => string | undefined,
+ focusedPath?: string,
+): FolderGraph {
+ const root = folderChild(tree.root, color);
+ const nodes = [root.node];
+ const edges: GraphEdge[] = [];
+ const children = new Map();
+ const representatives = new Map();
+
+ const visit = (child: FolderChild) => {
+ for (const id of child.members) representatives.set(id, child.node.id);
+
+ if (!child.folder || !state.open.has(child.folder.path)) return;
+ const list = visibleFolderChildren(tree, child.folder, state, color);
+ children.set(child.folder.path, list);
+
+ for (const next of list) {
+ nodes.push(next.node);
+ edges.push({
+ source: child.node.id,
+ target: next.node.id,
+ kind: "folder-containment",
+ weight: next.members.length,
+ relationLabel: totalsLabel(next.totals),
+ });
+ visit(next);
}
+ };
- const next = [...weights].filter(
- // A folder opens when it holds a large share of everything, or of the notes alone.
- ([path, entry]) =>
- path &&
- entry.deeper &&
- (entry.weight > total * SPLIT_SHARE || entry.notes > totalNotes * NOTE_SPLIT_SHARE),
- );
+ visit(root);
+ const aggregated = new Map();
- if (next.length === 0) break;
+ const visibleIds = new Set(nodes.map((node) => node.id));
- for (const [path] of next) split.add(path);
- }
+ const endpoint = (id: string) => {
+ const file = tree.files.get(id);
- const leaves = new Map();
+ if (!file) return representatives.get(id);
+ const path = filePath(file);
- for (const node of graph.nodes) {
- const path = leafFor(node);
- const folder = leaves.get(path) ?? { path, weight: 0, members: [], merged: 0 };
- folder.weight += weightOf(node);
- folder.members.push(node);
- leaves.set(path, folder);
- }
+ if (focusedPath && path.startsWith(`${focusedPath}/`)) return representatives.get(id);
+ const top = path.includes("/") ? `folder:${path.split("/")[0]}` : "more:";
- // Small subfolders of a split folder share one node, which opens the parent.
- const folders = new Map();
- const folderOf = new Map();
-
- for (const leaf of leaves.values()) {
- const parent = leaf.path.split("/").slice(0, -1).join("/");
- const notes = leaf.members.filter(isNote).length;
-
- const merge =
- parent !== "" &&
- split.has(parent) &&
- leaf.weight < total * MERGE_SHARE &&
- notes < totalNotes * NOTE_MERGE_SHARE;
-
- const path = merge ? parent : leaf.path;
- const key = merge ? `${parent}/(smaller folders)` : path;
- const folder = folders.get(key) ?? { path, weight: 0, members: [], merged: 0 };
- folder.weight += leaf.weight;
- folder.members.push(...leaf.members);
- folder.merged += merge ? 1 : 0;
- folders.set(key, folder);
-
- for (const node of leaf.members) folderOf.set(node.id, key);
- }
+ return visibleIds.has(top) ? top : representatives.get(id);
+ };
- // Retain every ancestor, even when all its contents were split into children.
- for (const folder of folders.values()) {
- const parts = folder.path.split("/").filter(Boolean);
-
- for (let depth = 0; depth <= parts.length; depth += 1) {
- const path = parts.slice(0, depth).join("/");
-
- if (!folders.has(path)) {
- const members = graph.nodes.filter(
- (node) =>
- !path ||
- folderSegments(node).join("/") === path ||
- folderSegments(node).join("/").startsWith(`${path}/`),
- );
-
- folders.set(path, {
- path,
- members,
- weight: members.reduce((sum, node) => sum + weightOf(node), 0),
- merged: 0,
- });
- }
+ for (const link of tree.links) {
+ let a = endpoint(link.source),
+ b = endpoint(link.target);
+
+ if (a === b) {
+ a = representatives.get(link.source);
+ b = representatives.get(link.target);
}
- }
- if (folders.has("")) {
- folders.set("", { path: "", members: [...graph.nodes], weight: total, merged: 0 });
+ if (!a || !b || a === b) continue;
+ const [source, target] = [a, b].sort();
+
+ for (const [kind, count] of [
+ ["folder-crosslink", link.noteCode],
+ [MINOR_FOLDER_LINK, link.other],
+ ] as const) {
+ if (!count) continue;
+ const key = JSON.stringify([source, target, kind]);
+ const edge = aggregated.get(key) ?? { source, target, kind, weight: 0 };
+ edge.weight = (edge.weight ?? 0) + count;
+ edge.relationLabel = `${edge.weight.toLocaleString("en-US")} ${kind === "folder-crosslink" ? "note–code links" : "other links"}`;
+ aggregated.set(key, edge);
+ }
}
- const nodes: GraphViewNode[] = [...folders.entries()].map(([key, folder]) => {
- const name = folder.path || "Vault";
- const label = folder.merged > 0 ? `${folder.merged} smaller folders` : name;
+ if (focusedPath) {
+ const local = new Set((children.get(focusedPath) ?? []).map((child) => child.node.id));
+ const bundles = new Map();
- const fill = folderFill(folder.members);
+ for (const edge of aggregated.values()) {
+ if (edge.kind !== "folder-crosslink") continue;
- return {
- id: `folder:${key}`,
- kind: "module",
- path: folder.path,
- label: `${label} ${contents(folder.members)}`,
- childCount: Math.max(1, folder.weight),
- fill: fill.type ? (typeColor(fill.type) ?? UNTYPED_COLOR) : fill.color,
- fillKey: fill.key,
- };
- });
+ const child = local.has(edge.source)
+ ? edge.source
+ : local.has(edge.target)
+ ? edge.target
+ : undefined;
- const weights = new Map();
+ const destination = child === edge.source ? edge.target : edge.source;
- for (const edge of graph.edges) {
- const a = folderOf.get(edge.source);
- const b = folderOf.get(edge.target);
+ if (!child || local.has(destination) || destination === `folder:${focusedPath}`) continue;
+ edge.kind = "folder-child-crosslink";
+ const node = nodes.find((node) => node.id === child);
+ const target = nodes.find((node) => node.id === destination);
- if (a === undefined || b === undefined || a === b) continue;
- const [source, target] = a < b ? [a, b] : [b, a];
- const key = `${source}|${target}`;
- const entry = weights.get(key) ?? { source, target, weight: 0 };
- entry.weight += edge.weight ?? 1;
- weights.set(key, entry);
- }
+ if (node && target)
+ node.labelDetail =
+ `${node.labelDetail || ""} ${edge.weight} ${edge.weight === 1 ? "link" : "links"} to ${target.label}`.trim();
- const edges: GraphEdge[] = [...folders.entries()].flatMap(([key, folder]) => {
- if (!key) return [];
+ const bundle = bundles.get(destination) ?? {
+ source: `folder:${focusedPath}`,
+ target: destination,
+ kind: "folder-crosslink",
+ weight: 0,
+ };
- const parent = folder.merged ? folder.path : folder.path.split("/").slice(0, -1).join("/");
+ bundle.weight = (bundle.weight ?? 0) + (edge.weight ?? 1);
+ bundle.relationLabel = `${bundle.weight} note–code links`;
+ bundles.set(destination, bundle);
+ }
- return [
- {
- source: `folder:${parent}`,
- target: `folder:${key}`,
- kind: "folder-containment",
- weight: 1,
- },
- ];
- });
+ for (const [destination, edge] of bundles) {
+ aggregated.set(`bundle:${destination}`, edge);
+ const opened = nodes.find((node) => node.id === `folder:${focusedPath}`);
+ const target = nodes.find((node) => node.id === destination);
- for (const [, entry] of [...weights].sort(([a], [b]) => a.localeCompare(b))) {
- edges.push({
- source: `folder:${entry.source}`,
- target: `folder:${entry.target}`,
- kind: MINOR_FOLDER_LINK,
- weight: entry.weight,
- relationLabel: `${fmt(entry.weight)} links`,
- });
+ if (opened && target)
+ opened.labelDetail =
+ `${opened.labelDetail || ""} ${edge.weight} ${edge.weight === 1 ? "link" : "links"} to ${target.label}`.trim();
+ }
}
- return { nodes, edges, truncated: graph.truncated ?? false };
-}
+ const overflows = nodes.filter((node) => node.aggregate);
-/** Legend keys for folders colored by code or untyped notes rather than a note type. */
-export const CODE_FILL_KEY = "__code__";
-
-export const UNTYPED_FILL_KEY = "__untyped__";
+ if (overflows.length > 1)
+ for (const node of overflows) node.label += ` in ${node.path?.split("/").pop() || "Vault"}`;
-type FolderFill = {
- /** The legend key: a type name, CODE_FILL_KEY, or UNTYPED_FILL_KEY. */
- key: string;
- /** The note type whose palette color the folder takes. */
- type?: string;
- /** The color when no type sets it. */
- color: string;
-};
+ const names = new Map();
-/**
- * A folder's color: its most common note type, or code or untyped notes when
- * they outnumber every type. `key` names it in the legend: the type, or one of
- * the fill keys above. Embedded items count for nothing here.
- */
-function folderFill(members: readonly GraphNode[]): FolderFill {
- const counts = new Map();
- let code = 0;
- let untyped = 0;
-
- for (const node of members) {
- const type = isNote(node) ? publicTypeName(node.resolvedType) : "";
-
- if (type) counts.set(type, (counts.get(type) ?? 0) + 1);
- else if (isNote(node)) untyped += 1;
- else code += weightOf(node);
+ for (const node of nodes) {
+ if (node.aggregate) continue;
+ const name = node.label.toLowerCase();
+ names.set(name, (names.get(name) ?? 0) + 1);
}
- const [best] = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
+ for (const node of nodes) {
+ if (node.aggregate) continue;
- if (best && best[1] >= code && best[1] >= untyped)
- return { key: best[0], type: best[0], color: UNTYPED_COLOR };
+ if ((names.get(node.label.toLowerCase()) ?? 0) > 1 && node.path) {
+ const parent = node.path.split("/").slice(0, -1).join("/");
+ node.label = `${parent || "Vault"}/ ${node.label}`;
+ }
+ }
- return code >= untyped
- ? { key: CODE_FILL_KEY, color: CODE_COLOR }
- : { key: UNTYPED_FILL_KEY, color: UNTYPED_COLOR };
+ return { nodes, edges: [...edges, ...aggregated.values()], truncated: tree.truncated, children };
}
diff --git a/web/src/components/folderLayout.ts b/web/src/components/folderLayout.ts
new file mode 100644
index 000000000..811e41e82
--- /dev/null
+++ b/web/src/components/folderLayout.ts
@@ -0,0 +1,228 @@
+import { folderWeight, initialOpenFolders, type FolderTree } from "./folderTree";
+import {
+ visibleFolderChildren,
+ visibleFolderGraph,
+ type FolderChild,
+ type FolderGraph,
+} from "./folderGraph";
+
+export type FolderAnchors = {
+ positions: Map;
+ free: { x: number; y: number }[];
+};
+
+const extents = new WeakMap();
+
+/** A stable camera frame sized for the overview, rather than every possible expansion. */
+export function folderLayoutExtent(tree: FolderTree) {
+ const cached = extents.get(tree);
+
+ if (cached !== undefined) return cached;
+ const open = initialOpenFolders(tree);
+
+ const overview = positionFolderGraph(
+ tree,
+ visibleFolderGraph(
+ tree,
+ {
+ open,
+ explicit: new Set(),
+ revealed: new Map(),
+ },
+ () => undefined,
+ ),
+ );
+
+ const extent = Math.max(640, ...overview.map((n) => Math.hypot(n.x ?? 0, n.y ?? 0))) * 2;
+ extents.set(tree, extent);
+
+ return extent;
+}
+
+function orderedChildren(tree: FolderTree, path: string, children: FolderChild[]) {
+ if (path)
+ return [...children].sort(
+ (a, b) =>
+ Number(Boolean(a.node.aggregate)) - Number(Boolean(b.node.aggregate)) ||
+ a.node.id.localeCompare(b.node.id),
+ );
+
+ const first = children.reduce(
+ (best, child) =>
+ !best ||
+ folderWeight(child.totals) > folderWeight(best.totals) ||
+ (folderWeight(child.totals) === folderWeight(best.totals) &&
+ child.node.id.localeCompare(best.node.id) < 0)
+ ? child
+ : best,
+ undefined,
+ );
+
+ const affinity = tree.affinity.get(path);
+
+ return [...children].sort(
+ (a, b) =>
+ Number(b === first) - Number(a === first) ||
+ (affinity?.get(JSON.stringify([first?.node.id, b.node.id].sort())) ?? 0) -
+ (affinity?.get(JSON.stringify([first?.node.id, a.node.id].sort())) ?? 0) ||
+ a.node.id.localeCompare(b.node.id),
+ );
+}
+
+/** Child fans depend only on their parent's anchor and child list. */
+function positionFolderGraph(
+ tree: FolderTree,
+ graph: FolderGraph,
+ anchorState: FolderAnchors = { positions: new Map(), free: [] },
+) {
+ const { positions: anchors, free } = anchorState;
+ const valid = new Set([...tree.root.folders.map((f) => `folder:${f.path}`), "more:"]);
+
+ for (const [id, point] of anchors) {
+ if (!valid.has(id)) {
+ free.push(point);
+ anchors.delete(id);
+ }
+ }
+
+ const updating = anchors.size > 0;
+ const positions = new Map([["folder:", { x: 0, y: 0 }]]);
+
+ const visit = (path: string, x: number, y: number, direction: number) => {
+ // Root anchors always use the overview; revealed files fan out from its overflow.
+ const children = orderedChildren(
+ tree,
+ path,
+ path === ""
+ ? visibleFolderChildren(
+ tree,
+ tree.root,
+ {
+ open: new Set([""]),
+ explicit: new Set(),
+ revealed: new Map(),
+ },
+ () => undefined,
+ )
+ : (graph.children.get(path) ?? []),
+ );
+
+ const n = children.length;
+
+ if (!n) return;
+ const root = path === "";
+ const width = Math.max(0.9, Math.min(1.6, n * 0.22));
+
+ const dominant = root
+ ? children.filter((c) => c.folder && initialOpenFolders(tree).has(c.folder.path))
+ : [];
+
+ const others = children.filter((c) => !dominant.includes(c));
+ const radius = root ? 600 : Math.max(220, (150 * (n - 1)) / width);
+
+ let start = -Math.PI;
+ children.forEach((child, index) => {
+ const major = dominant.indexOf(child);
+ const minor = others.indexOf(child);
+ const wedge = (Math.PI * 2) / Math.max(1, n);
+
+ const angle = root
+ ? dominant.length === 2
+ ? major >= 0
+ ? Math.PI - major * Math.PI
+ : (minor < others.length / 2 ? -Math.PI / 2 : Math.PI / 2) +
+ ((minor % Math.ceil(others.length / 2)) /
+ Math.max(1, Math.ceil(others.length / 2) - 1) -
+ 0.5) *
+ 2.4
+ : start + wedge / 2
+ : direction + (n === 1 ? 0 : (index / (n - 1) - 0.5) * width);
+
+ const distance = root && dominant.length === 2 && major < 0 ? 800 : radius;
+ const local = angle - direction;
+ const depth = path.split("/").length;
+ const axial = Math.cos(local) * distance * (depth > 2 ? 3.5 : depth > 1 ? 1.3 : 0.65);
+ const lateral = Math.sin(local) * distance * (depth > 1 ? 1.9 : 1.4);
+
+ let point = root
+ ? {
+ x: x + Math.cos(angle) * distance * (major < 0 && dominant.length === 2 ? 0.65 : 1),
+ y: y + Math.sin(angle) * distance,
+ }
+ : {
+ x: x + Math.cos(direction) * axial - Math.sin(direction) * lateral,
+ y: y + Math.sin(direction) * axial + Math.cos(direction) * lateral,
+ };
+
+ if (root) {
+ const existing = anchors.get(child.node.id);
+
+ if (existing) point = existing;
+ else if (updating || free.length) {
+ const vacant = free.shift();
+
+ if (vacant) point = vacant;
+ else {
+ let slot = 0;
+
+ do {
+ const radius = 800 + 200 * Math.floor(slot / 10);
+ const angle = slot++ * Math.PI * (3 - Math.sqrt(5));
+ point = { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
+ } while (
+ [...anchors.values()].some((p) => Math.hypot(p.x - point.x, p.y - point.y) < 100)
+ );
+ }
+ }
+
+ anchors.set(child.node.id, point);
+ }
+
+ positions.set(child.node.id, point);
+
+ if (child.folder)
+ visit(
+ child.folder.path,
+ point.x,
+ point.y,
+ root ? Math.atan2(point.y - y, point.x - x) : direction,
+ );
+ start += wedge;
+ });
+ };
+
+ visit("", 0, 0, 0);
+
+ const overflow = positions.get("more:");
+
+ if (overflow) {
+ const files = (graph.children.get("") ?? []).filter((child) => !positions.has(child.node.id));
+ files.forEach((child, index) => {
+ const angle = index * Math.PI * (3 - Math.sqrt(5));
+ const radius = 65 * Math.sqrt(index + 1);
+
+ const point = {
+ x: overflow.x + Math.cos(angle) * radius,
+ y: overflow.y + Math.sin(angle) * radius,
+ };
+
+ positions.set(child.node.id, point);
+
+ if (child.folder) visit(child.folder.path, point.x, point.y, angle);
+ });
+ }
+
+ return graph.nodes.map((node) => ({ ...node, ...positions.get(node.id) }));
+}
+
+export function layoutFolderGraph(
+ tree: FolderTree,
+ graph: FolderGraph,
+ anchors?: FolderAnchors,
+): FolderGraph & { layoutExtent: number } {
+ return {
+ ...graph,
+ nodes: positionFolderGraph(tree, graph, anchors),
+ layoutExtent: folderLayoutExtent(tree),
+ };
+}
diff --git a/web/src/components/folderObstacles.ts b/web/src/components/folderObstacles.ts
new file mode 100644
index 000000000..09a6d3125
--- /dev/null
+++ b/web/src/components/folderObstacles.ts
@@ -0,0 +1,43 @@
+export type Obstacle = { id: string; x: number; y: number; size: number };
+
+type Point = { x: number; y: number };
+
+export class FolderObstacles {
+ private cells = new Map();
+ readonly maxSize: number;
+ constructor(
+ points: Obstacle[],
+ private cellSize = 0.025,
+ ) {
+ this.maxSize = Math.max(0, ...points.map((point) => point.size));
+
+ for (const point of points) {
+ const key = this.key(point.x, point.y);
+ const cell = this.cells.get(key) ?? [];
+ cell.push(point);
+ this.cells.set(key, cell);
+ }
+ }
+ private key(x: number, y: number) {
+ return `${Math.floor(x / this.cellSize)},${Math.floor(y / this.cellSize)}`;
+ }
+ *nearRoute(a: Point, b: Point, padding: number): Generator {
+ const steps = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / this.cellSize));
+ const reach = Math.ceil(padding / this.cellSize) + 1;
+ const visited = new Set();
+
+ for (let step = 0; step <= steps; step++) {
+ const x = Math.floor((a.x + ((b.x - a.x) * step) / steps) / this.cellSize);
+ const y = Math.floor((a.y + ((b.y - a.y) * step) / steps) / this.cellSize);
+
+ for (let dx = -reach; dx <= reach; dx++)
+ for (let dy = -reach; dy <= reach; dy++) {
+ const key = `${x + dx},${y + dy}`;
+
+ if (visited.has(key)) continue;
+ visited.add(key);
+ yield* this.cells.get(key) ?? [];
+ }
+ }
+ }
+}
diff --git a/web/src/components/folderRevealLayout.test.ts b/web/src/components/folderRevealLayout.test.ts
new file mode 100644
index 000000000..d4164e369
--- /dev/null
+++ b/web/src/components/folderRevealLayout.test.ts
@@ -0,0 +1,54 @@
+import { expect, it } from "vitest";
+import { buildFolderTree } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+import { layoutFolderGraph } from "./folderLayout";
+
+it("root file reveals preserve every folder and descendant coordinate", () => {
+ for (const count of [3, 40]) {
+ const tree = buildFolderTree({
+ nodes: [
+ ...Array.from({ length: 30 }, (_, i) => ({
+ id: `root${i}`,
+ path: `root${i}.ts`,
+ label: `root${i}`,
+ kind: "code",
+ })),
+ ...["a", "b", "c"].flatMap((folder) =>
+ Array.from({ length: count }, (_, i) => ({
+ id: `${folder}/${i}`,
+ path: `${folder}/f${i}.ts`,
+ label: `f${i}`,
+ kind: "code",
+ })),
+ ),
+ ],
+ edges: [],
+ });
+
+ const draw = (batches: number) =>
+ layoutFolderGraph(
+ tree,
+ visibleFolderGraph(
+ tree,
+ {
+ open: new Set(["", "a", "b"]),
+ explicit: new Set(["a", "b"]),
+ revealed: new Map([["", batches]]),
+ },
+ () => undefined,
+ ),
+ );
+
+ const before = draw(0);
+
+ for (const batches of [1, 2, 3]) {
+ const after = draw(batches);
+
+ for (const node of before.nodes.filter((n) => !n.aggregate)) {
+ expect(after.nodes.find((n) => n.id === node.id)).toMatchObject({ x: node.x, y: node.y });
+ }
+
+ expect(after.nodes.every((n) => Number.isFinite(n.x) && Number.isFinite(n.y))).toBe(true);
+ }
+ }
+});
diff --git a/web/src/components/folderRootBudget.test.ts b/web/src/components/folderRootBudget.test.ts
new file mode 100644
index 000000000..c8a931af0
--- /dev/null
+++ b/web/src/components/folderRootBudget.test.ts
@@ -0,0 +1,65 @@
+import { expect, it, vi } from "vitest";
+import { buildFolderTree } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+import { layoutFolderGraph } from "./folderLayout";
+
+it("budgets 10,000 root folders with counted overflow and sorts the overview once", () => {
+ const tree = buildFolderTree({
+ nodes: Array.from({ length: 10000 }, (_, i) => ({
+ id: `f${i}`,
+ path: `folder${i}/a.ts`,
+ label: "a.ts",
+ kind: "code",
+ })),
+ edges: [],
+ });
+
+ const graph = visibleFolderGraph(
+ tree,
+ { open: new Set([""]), explicit: new Set(), revealed: new Map() },
+ () => undefined,
+ );
+
+ expect(graph.children.get("")).toHaveLength(10);
+ expect(graph.nodes.find((n) => n.aggregate)).toMatchObject({
+ label: "+9991 folders",
+ childCount: 9991,
+ });
+ expect(graph.children.get("")?.flatMap((c) => c.members)).toHaveLength(10000);
+ const compare = vi.spyOn(String.prototype, "localeCompare");
+
+ try {
+ const before = layoutFolderGraph(tree, graph);
+
+ const revealed = {
+ open: new Set([""]),
+ explicit: new Set(),
+ revealed: new Map([["", 1]]),
+ };
+
+ const next = visibleFolderGraph(tree, revealed, () => undefined);
+
+ const added = next.children
+ .get("")
+ ?.find((child) => child.folder && !graph.nodes.some((node) => node.id === child.node.id));
+
+ expect(added?.folder).toBeDefined();
+ revealed.open.add(added!.folder!.path);
+ revealed.explicit.add(added!.folder!.path);
+
+ const after = layoutFolderGraph(
+ tree,
+ visibleFolderGraph(tree, revealed, () => undefined),
+ );
+
+ expect(after.nodes.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))).toBe(
+ true,
+ );
+
+ for (const node of before.nodes)
+ expect(after.nodes.find((n) => n.id === node.id)).toMatchObject({ x: node.x, y: node.y });
+ expect(compare.mock.calls.length).toBeLessThan(300000);
+ } finally {
+ compare.mockRestore();
+ }
+});
diff --git a/web/src/components/folderSearchMatches.test.ts b/web/src/components/folderSearchMatches.test.ts
new file mode 100644
index 000000000..cdeb5e384
--- /dev/null
+++ b/web/src/components/folderSearchMatches.test.ts
@@ -0,0 +1,58 @@
+import { expect, it } from "vitest";
+import { folderSearchMatches } from "./folderSearchMatches";
+import { visibleFolderGraph } from "./folderGraph";
+import { buildFolderTree } from "./folderTree";
+import { buildSigmaGraph } from "./sigmaGraphData";
+
+it("counts matches on visible folders, files and overflow representatives without moving them", () => {
+ const graph = {
+ nodes: Array.from({ length: 20 }, (_, i) => ({
+ id: `note:${i}`,
+ kind: "note",
+ path: `docs/${i}.md`,
+ label: `${i}`,
+ })),
+ edges: [],
+ truncated: false,
+ };
+
+ const folders = visibleFolderGraph(
+ buildFolderTree(graph),
+ { open: new Set(["", "docs"]), explicit: new Set(["docs"]), revealed: new Map() },
+ () => undefined,
+ );
+
+ const counts = folderSearchMatches(folders, graph, new Set(graph.nodes.map((n) => n.path)));
+ expect(counts.get("folder:docs")).toBe(20);
+ expect(counts.get("more:docs")).toBeGreaterThan(0);
+ expect(counts.get("note:0")).toBe(1);
+
+ const { graph: rendered } = buildSigmaGraph({
+ nodes: folders.nodes.map((node, index) => ({
+ x: index * 10,
+ y: index * 20,
+ ...node,
+ searchMatchCount: counts.get(node.id) ?? 0,
+ })),
+ edges: folders.edges,
+ scope: { mode: "global" },
+ connectionCounts: new Map(),
+ globalLayout: new Map(),
+ communityColors: new Map(),
+ problemCounts: new Map(),
+ edgeFaint: "#ccc",
+ fixed: true,
+ explorer: true,
+ });
+
+ expect(rendered.getNodeAttributes("folder:docs")).toMatchObject({
+ searchMatchCount: 20,
+ labelDetail: "20 matches",
+ muted: false,
+ });
+ expect(rendered.getNodeAttributes("folder:")).toMatchObject({ muted: true });
+
+ folders.nodes.forEach((node, index) =>
+ expect(rendered.getNodeAttributes(node.id)).toMatchObject({ x: index * 10, y: index * 20 }),
+ );
+});
diff --git a/web/src/components/folderSearchMatches.ts b/web/src/components/folderSearchMatches.ts
new file mode 100644
index 000000000..790e23753
--- /dev/null
+++ b/web/src/components/folderSearchMatches.ts
@@ -0,0 +1,33 @@
+import type { GraphResponse } from "../api/types";
+import type { FolderGraph } from "./folderGraph";
+
+/** Highlight the visible representatives without expanding or moving the folder graph. */
+export function folderSearchMatches(
+ folders: FolderGraph | null,
+ graph: GraphResponse,
+ paths: Set,
+) {
+ const pathsByID = new Map(
+ graph.nodes
+ .filter((node) => paths.has(node.notePath || node.path || ""))
+ .map((node) => [node.id, node.notePath || node.path || node.id]),
+ );
+
+ const matches = new Map();
+
+ for (const children of folders?.children.values() ?? []) {
+ for (const child of children) {
+ const count = new Set(
+ child.members.flatMap((id) => {
+ const path = pathsByID.get(id);
+
+ return path ? [path] : [];
+ }),
+ ).size;
+
+ if (count) matches.set(child.node.id, count);
+ }
+ }
+
+ return matches;
+}
diff --git a/web/src/components/folderSelectionBounds.test.tsx b/web/src/components/folderSelectionBounds.test.tsx
new file mode 100644
index 000000000..c44169ab4
--- /dev/null
+++ b/web/src/components/folderSelectionBounds.test.tsx
@@ -0,0 +1,56 @@
+import { act, renderHook } from "@testing-library/react";
+import { expect, it, vi } from "vitest";
+import { useFolderExplorer } from "./useFolderExplorer";
+
+it("reveals the last of 10,000 siblings with bounded sorts and exact overflow", () => {
+ const graph = {
+ nodes: Array.from({ length: 10000 }, (_, i) => {
+ const path = `dir${String(i).padStart(5, "0")}/file.go`;
+
+ return { id: path, path, label: path, kind: "code" };
+ }),
+ edges: [],
+ truncated: false,
+ };
+
+ const colors = new Map();
+ const { result } = renderHook(() => useFolderExplorer(graph, colors));
+ const before = result.current.drawn.nodes;
+ const sort = Array.prototype.sort;
+ let largeSorts = 0;
+
+ const spy = vi
+ .spyOn(Array.prototype, "sort")
+ .mockImplementation(function (this: unknown[], compare) {
+ if (this.length === 10000) {
+ largeSorts++;
+
+ if (largeSorts > 2) throw new Error("Selection repeatedly sorts the whole directory");
+ }
+
+ return sort.call(this, compare);
+ });
+
+ try {
+ act(() => result.current.expand("dir09999"));
+ expect(largeSorts).toBeLessThanOrEqual(2);
+ const children = result.current.drawn.children.get("")!;
+
+ expect(children.length).toBeLessThanOrEqual(11);
+ expect(children.some((child) => child.node.id === "folder:dir09999")).toBe(true);
+ expect(children.find((child) => child.node.aggregate)).toMatchObject({
+ node: { label: "+9990 folders", childCount: 9990 },
+ members: expect.any(Array),
+ });
+ expect(children.reduce((total, child) => total + child.totals.files, 0)).toBe(10000);
+ expect(new Set(children.flatMap((child) => child.members)).size).toBe(10000);
+
+ for (const node of before)
+ expect(result.current.drawn.nodes.find((next) => next.id === node.id)).toMatchObject({
+ x: node.x,
+ y: node.y,
+ });
+ } finally {
+ spy.mockRestore();
+ }
+});
diff --git a/web/src/components/folderStableOrder.test.ts b/web/src/components/folderStableOrder.test.ts
new file mode 100644
index 000000000..d4e09b3ca
--- /dev/null
+++ b/web/src/components/folderStableOrder.test.ts
@@ -0,0 +1,34 @@
+import { expect, it } from "vitest";
+import { buildFolderTree } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+import { layoutFolderGraph } from "./folderLayout";
+
+it("keeps an open child fan fixed when another branch disambiguates its labels", () => {
+ const tree = buildFolderTree({
+ nodes: ["a/alpha/file.ts", "a/foo/file.ts", "b/foo/file.ts"].map((path) => ({
+ id: path,
+ path,
+ label: path,
+ kind: "code",
+ })),
+ edges: [],
+ });
+
+ const draw = (open: string[]) =>
+ layoutFolderGraph(
+ tree,
+ visibleFolderGraph(
+ tree,
+ { open: new Set(["", ...open]), explicit: new Set(open), revealed: new Map() },
+ () => undefined,
+ ),
+ );
+
+ const before = draw(["a"]);
+ const after = draw(["a", "b"]);
+ expect(before.nodes.find((n) => n.id === "folder:a/foo")?.label).toBe("foo");
+ expect(after.nodes.find((n) => n.id === "folder:a/foo")?.label).toBe("a/ foo");
+
+ for (const node of before.nodes)
+ expect(after.nodes.find((n) => n.id === node.id)).toMatchObject({ x: node.x, y: node.y });
+});
diff --git a/web/src/components/folderTree.ts b/web/src/components/folderTree.ts
new file mode 100644
index 000000000..fb219d5fd
--- /dev/null
+++ b/web/src/components/folderTree.ts
@@ -0,0 +1,205 @@
+import type { GraphNode, GraphEdge } from "../api/types";
+import { publicTypeName } from "../lib/typeNames";
+
+export type FolderTotals = {
+ items?: number;
+ notes: number;
+ files: number;
+ types: Map;
+ untyped: number;
+};
+
+export type Folder = FolderTotals & {
+ path: string;
+ folders: Folder[];
+ direct: GraphNode[];
+ members: string[];
+};
+
+export type FileLink = { source: string; target: string; noteCode: number; other: number };
+
+export type FolderTree = {
+ root: Folder;
+ folders: Map;
+ files: Map;
+ links: FileLink[];
+ linkCounts: Map;
+ affinity: Map>;
+ truncated: boolean;
+};
+
+export const filePath = (node: GraphNode) => (node.notePath || node.path || "").replace(/^\/+/, "");
+
+export const folderWeight = (folder: FolderTotals) =>
+ folder.notes * 3 + folder.files + (folder.items ?? 0);
+
+export function totalsLabel(totals: FolderTotals) {
+ const parts: string[] = [];
+
+ if (totals.notes)
+ parts.push(`${totals.notes.toLocaleString("en-US")} ${totals.notes === 1 ? "note" : "notes"}`);
+
+ if (totals.files)
+ parts.push(`${totals.files.toLocaleString("en-US")} ${totals.files === 1 ? "file" : "files"}`);
+
+ if (totals.items) parts.push(`${totals.items.toLocaleString("en-US")} items (collapsed)`);
+
+ return parts.join(" · ") || "0 files";
+}
+
+export function sumTotals(items: readonly FolderTotals[]): FolderTotals {
+ const result: FolderTotals = { notes: 0, files: 0, types: new Map(), untyped: 0 };
+
+ for (const item of items) {
+ result.items = (result.items ?? 0) + (item.items ?? 0);
+ result.notes += item.notes;
+ result.files += item.files;
+ result.untyped += item.untyped;
+
+ for (const [type, count] of item.types)
+ result.types.set(type, (result.types.get(type) ?? 0) + count);
+ }
+
+ return result;
+}
+
+export function nodeTotals(node: GraphNode): FolderTotals {
+ const type = publicTypeName(node.resolvedType);
+
+ return {
+ items: node.kind === "module" ? (node.childCount ?? 0) : 0,
+ notes: node.kind === "note" ? 1 : 0,
+ files: node.kind === "code" ? 1 : 0,
+ types: node.kind === "note" && type ? new Map([[type, 1]]) : new Map(),
+ untyped: node.kind === "note" && !type ? 1 : 0,
+ };
+}
+
+export function buildFolderTree(graph: {
+ nodes: readonly GraphNode[];
+ edges: readonly GraphEdge[];
+ truncated?: boolean;
+}): FolderTree {
+ const folders = new Map();
+
+ const ensure = (path: string): Folder => {
+ const existing = folders.get(path);
+
+ if (existing) return existing;
+ const folder: Folder = { path, folders: [], direct: [], members: [], ...sumTotals([]) };
+ folders.set(path, folder);
+
+ if (path) ensure(path.split("/").slice(0, -1).join("/")).folders.push(folder);
+
+ return folder;
+ };
+
+ const root = ensure("");
+ const files = new Map();
+ const notesByPath = new Map();
+
+ for (const node of graph.nodes) {
+ if (node.kind !== "note" && node.kind !== "code" && node.kind !== "module") continue;
+ files.set(node.id, node);
+
+ if (node.kind === "note") notesByPath.set(filePath(node), node.id);
+ ensure(
+ node.kind === "module" ? filePath(node) : filePath(node).split("/").slice(0, -1).join("/"),
+ ).direct.push(node);
+ }
+
+ const gather = (folder: Folder) => {
+ for (const child of folder.folders) gather(child);
+ Object.assign(folder, sumTotals([...folder.folders, ...folder.direct.map(nodeTotals)]));
+ folder.members = [
+ ...folder.direct.map((n) => n.id),
+ ...folder.folders.flatMap((f) => f.members),
+ ];
+ folder.folders.sort((a, b) => a.path.localeCompare(b.path));
+ };
+
+ gather(root);
+
+ const owners = new Map(
+ graph.nodes.map((n) => [
+ n.id,
+ n.kind === "embedded" ? notesByPath.get(filePath(n)) : files.has(n.id) ? n.id : undefined,
+ ]),
+ );
+
+ const pairs = new Map();
+
+ for (const edge of graph.edges) {
+ if (edge.kind === "embeds") continue;
+
+ const a = owners.get(edge.source),
+ b = owners.get(edge.target);
+
+ if (!a || !b || a === b) continue;
+ const [source, target] = [a, b].sort();
+ const key = JSON.stringify([source, target]);
+ const pair = pairs.get(key) ?? { source, target, noteCode: 0, other: 0 };
+ const category = edge.kind === "mentions" || edge.kind === "coderef" ? "noteCode" : "other";
+ // A file pair counts once in each category, even when embedded nodes repeat it.
+ pair[category] = Math.max(pair[category], edge.weight ?? 1);
+ pairs.set(key, pair);
+ }
+
+ const links = [...pairs.values()];
+ const linkCounts: FolderTree["linkCounts"] = new Map();
+
+ for (const link of links)
+ for (const id of [link.source, link.target]) {
+ const count = linkCounts.get(id) ?? { noteCode: 0, other: 0 };
+ count.noteCode += link.noteCode;
+ count.other += link.other;
+ linkCounts.set(id, count);
+ }
+
+ const affinity: FolderTree["affinity"] = new Map();
+
+ {
+ const folder = root;
+ const childOf = new Map();
+
+ for (const child of folder.folders)
+ for (const id of child.members) childOf.set(id, `folder:${child.path}`);
+
+ for (const file of folder.direct) childOf.set(file.id, file.id);
+ const weights = new Map();
+
+ for (const link of links) {
+ const a = childOf.get(link.source),
+ b = childOf.get(link.target);
+
+ if (a && b && a !== b) {
+ const key = JSON.stringify([a, b].sort());
+ weights.set(key, (weights.get(key) ?? 0) + link.noteCode * 3 + link.other);
+ }
+ }
+
+ affinity.set(folder.path, weights);
+ }
+
+ return { root, folders, files, links, linkCounts, affinity, truncated: graph.truncated ?? false };
+}
+
+export function initialOpenFolders(tree: FolderTree): Set {
+ const open = new Set([""]);
+
+ const visit = (folder: Folder) => {
+ for (const child of folder.folders) {
+ if (
+ child.folders.length &&
+ (child.notes + child.files > (tree.root.notes + tree.root.files) * 0.15 ||
+ child.notes > tree.root.notes * 0.2)
+ ) {
+ open.add(child.path);
+ }
+ }
+ };
+
+ visit(tree.root);
+
+ return open;
+}
diff --git a/web/src/components/graphClusters.ts b/web/src/components/graphClusters.ts
new file mode 100644
index 000000000..549dbf464
--- /dev/null
+++ b/web/src/components/graphClusters.ts
@@ -0,0 +1,32 @@
+import type { GraphViewNode } from "./graphViewShared";
+
+export function graphClusters(nodes: GraphViewNode[], communityColors: Map) {
+ const byCommunity = new Map();
+ nodes.forEach((node) => {
+ if (!node.community) return;
+
+ const current = byCommunity.get(node.community) || {
+ size: 0,
+ topLabel: "",
+ topAuthority: -1,
+ };
+
+ current.size += 1;
+
+ if (node.kind === "note" && (node.authority ?? -1) > current.topAuthority) {
+ current.topAuthority = node.authority ?? -1;
+ current.topLabel = node.label;
+ }
+
+ byCommunity.set(node.community, current);
+ });
+
+ return Array.from(byCommunity.entries())
+ .map(([id, data]) => ({
+ id,
+ size: data.size,
+ label: data.topLabel || `Cluster ${id}`,
+ color: communityColors.get(id) || "var(--type-8)",
+ }))
+ .sort((a, b) => b.size - a.size);
+}
diff --git a/web/src/components/graphLegend.tsx b/web/src/components/graphLegend.tsx
new file mode 100644
index 000000000..84011327f
--- /dev/null
+++ b/web/src/components/graphLegend.tsx
@@ -0,0 +1,247 @@
+import { useState } from "react";
+import { ChevronDown } from "lucide-react";
+import type { GraphEdge, GraphNode } from "../api/types";
+import { publicTypeName } from "../lib/typeNames";
+import { CODE_COLOR, FOLDER_COLOR, UNTYPED_COLOR } from "./graphViewShared";
+
+export const UNTYPED_NODE_TYPE = "__untyped__";
+
+/** Legend keys for nodes that are not notes; their colors match `nodeColor` under a type-color map. */
+export const CODE_NODE_TYPE = "__code__";
+
+export const FOLDER_NODE_TYPE = "__module__";
+
+export const KIND_ENTRIES = new Map([
+ [UNTYPED_NODE_TYPE, { label: "Untyped notes", color: UNTYPED_COLOR }],
+ [CODE_NODE_TYPE, { label: "Code files", color: CODE_COLOR }],
+ [FOLDER_NODE_TYPE, { label: "Folders", color: FOLDER_COLOR }],
+]);
+
+/** Legend groups, in order: what the colors of notes mean, then code, then folders. */
+export const LEGEND_GROUPS = [
+ { key: "typed", title: "Notes by type" },
+ { key: "code", title: "Code" },
+ { key: "folder", title: "Folders" },
+] as const;
+
+export function legendGroup(name: string) {
+ if (name === CODE_NODE_TYPE) return "code";
+
+ if (name === FOLDER_NODE_TYPE) return "folder";
+
+ return "typed";
+}
+
+export const EMPTY_PROBLEM_COUNTS: ReadonlyMap = new Map();
+
+export type GraphTypeEntry = {
+ name: string;
+ label: string;
+ count: number;
+ color: string;
+ selected: boolean;
+};
+
+export function graphTypeName(node: GraphNode): string {
+ if (node.kind === "code") return CODE_NODE_TYPE;
+
+ if (node.kind === "module") return FOLDER_NODE_TYPE;
+
+ return publicTypeName(node.resolvedType) || UNTYPED_NODE_TYPE;
+}
+
+export function legendItem(entry: GraphTypeEntry, folderCode = false) {
+ return (
+
+
+
+ {folderCode && entry.name === CODE_NODE_TYPE ? "Code-dominant folder" : entry.label}
+
+ {entry.count.toLocaleString("en-US")}
+
+ );
+}
+
+/**
+ * The folder view's key: the hues its folders actually take first, then what
+ * size and lines mean; every type in the graph waits behind "All types".
+ */
+export function FolderLegend({
+ entries,
+ shown,
+ caption,
+ sizeCaption,
+ edgeCaption,
+ edges,
+ nodes,
+}: {
+ entries: readonly GraphTypeEntry[];
+ /** The fill keys the drawn folders use. */
+ shown: ReadonlySet;
+ caption?: string;
+ sizeCaption?: string;
+ edgeCaption?: string;
+ edges: GraphEdge[];
+ nodes?: readonly (GraphNode & { aggregate?: boolean })[];
+}) {
+ const [all, setAll] = useState(false);
+ const inventory = entries.filter((entry) => entry.name !== FOLDER_NODE_TYPE);
+
+ const typed = inventory.filter(
+ (entry) => shown.has(entry.name) && legendGroup(entry.name) !== "code",
+ );
+
+ const folders = nodes?.some((node) => node.kind === "module" && !node.aggregate) ?? true;
+ const files = nodes?.some((node) => node.kind !== "module") ?? true;
+ const overflow = nodes?.some((node) => node.kind === "module" && node.aggregate) ?? true;
+
+ return (
+
+ );
+}
+
+export function EdgeLegend({ edges }: { edges: GraphEdge[] }) {
+ const kinds = new Set(edges.map((edge) => edge.kind));
+
+ if (
+ ![
+ "folder-containment",
+ "folder-crosslink",
+ "folder-minor",
+ "explorer-documents",
+ "explorer-code",
+ "explorer-tests",
+ ].some((kind) => kinds.has(kind))
+ )
+ return null;
+
+ return (
+
+
Lines
+ {[
+ ["folder-containment", "Contains"],
+ ["explorer-documents", "Documents / mentions"],
+ ["explorer-code", "Calls / imports"],
+ ["explorer-tests", "Tests"],
+ ["folder-crosslink", "Note–code links"],
+ ["folder-minor", "Other links on hover"],
+ ].flatMap(([kind, label]) =>
+ kinds.has(kind)
+ ? [
+
+
+ {label}
+ ,
+ ]
+ : [],
+ )}
+
+ );
+}
diff --git a/web/src/components/graphViewShared.ts b/web/src/components/graphViewShared.ts
index 6a79cc8d3..d1ab6765e 100644
--- a/web/src/components/graphViewShared.ts
+++ b/web/src/components/graphViewShared.ts
@@ -13,6 +13,17 @@ export type GraphViewNode = GraphNode & {
fill?: string;
/** What `fill` stands for in the legend: a type name, or the code or untyped-notes key. */
fillKey?: string;
+ /** A fixed position in layout units. When every node passed to GraphView has both,
+ * the renderer uses them as-is and runs no force layout. */
+ x?: number;
+ y?: number;
+ /** Secondary label text drawn after `label` in the muted label colour
+ * (for a count such as `1,295 files`). `label` is the name only. */
+ labelDetail?: string;
+ searchMatchCount?: number;
+ /** The node stands for several files or folders ("12 more folders"); drawn as
+ * a dashed or hollow ring in its fill colour so it reads as a group, not a file. */
+ aggregate?: boolean;
};
export type HoverInfo = {
@@ -79,7 +90,7 @@ const NEUTRAL_COLOR = "var(--type-8)";
*/
export const FOLDER_COLOR = "var(--text)";
-export const CODE_COLOR = "var(--graph-code)";
+export const CODE_COLOR = "var(--explorer-code)";
export const UNTYPED_COLOR = NEUTRAL_COLOR;
@@ -165,7 +176,7 @@ export function nodeColor(
if (node.kind === "module") return FOLDER_COLOR;
// Beside type colors, code is one neutral so the legend can name it.
- if (typeColors && node.kind === "code") return CODE_COLOR;
+ if (typeColors && node.kind === "code") return "var(--graph-code)";
if (node.kind === "embedded") return "var(--type-4)";
diff --git a/web/src/components/labelBlockers.ts b/web/src/components/labelBlockers.ts
new file mode 100644
index 000000000..dc565eca0
--- /dev/null
+++ b/web/src/components/labelBlockers.ts
@@ -0,0 +1,48 @@
+type Box = [number, number, number, number];
+
+type Blocker = { id: string; box: Box };
+
+/** Index discs and placed labels by viewport cell; query with the label clearance. */
+export class LabelBlockers {
+ private cells = new Map();
+ checks = 0;
+
+ constructor(blockers: Blocker[]) {
+ for (const blocker of blockers) this.add(blocker);
+ }
+
+ private *keys(box: Box, gap = 0) {
+ for (let y = Math.floor((box[1] - gap) / 64); y <= Math.floor((box[3] + gap) / 64); y++) {
+ for (let x = Math.floor((box[0] - gap) / 64); x <= Math.floor((box[2] + gap) / 64); x++)
+ yield `${x}:${y}`;
+ }
+ }
+
+ add(blocker: Blocker) {
+ for (const key of this.keys(blocker.box)) {
+ const cell = this.cells.get(key) ?? [];
+ cell.push(blocker);
+ this.cells.set(key, cell);
+ }
+ }
+
+ overlaps(box: Box, exclude: string) {
+ for (const key of this.keys(box, 8)) {
+ for (const blocker of this.cells.get(key) ?? []) {
+ this.checks++;
+ const b = blocker.box;
+
+ if (
+ blocker.id !== exclude &&
+ box[0] < b[2] + 8 &&
+ box[2] + 8 > b[0] &&
+ box[1] < b[3] + 8 &&
+ box[3] + 8 > b[1]
+ )
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/web/src/components/notePreview/NotePreviewCard.tsx b/web/src/components/notePreview/NotePreviewCard.tsx
index d91b2b591..332966022 100644
--- a/web/src/components/notePreview/NotePreviewCard.tsx
+++ b/web/src/components/notePreview/NotePreviewCard.tsx
@@ -1,3 +1,4 @@
+import { TypeChip } from "../TypeChip";
import { displayTitle } from "../../lib/labels";
import { publicTypeName } from "../../lib/typeNames";
import type { NodePreview, NodePreviewField } from "../../api/types";
@@ -75,11 +76,11 @@ export function NotePreviewCard({ target, open, preview, loading = false, error
<>
diff --git a/web/src/components/tasks/TasksWorkspace.test.tsx b/web/src/components/tasks/TasksWorkspace.test.tsx
index be3e76ad4..6984bfac7 100644
--- a/web/src/components/tasks/TasksWorkspace.test.tsx
+++ b/web/src/components/tasks/TasksWorkspace.test.tsx
@@ -58,10 +58,10 @@ describe("TasksWorkspace", () => {
const table = await screen.findByRole("table");
const rows = within(table).getAllByRole("row").slice(1);
expect(rows.map((row) => within(row).getByRole("rowheader").textContent)).toEqual([
- "Docs drift checkdocs-drift",
- "Dependency updatesdependency-updates",
- "Flaky test triageflaky-tests",
- "Changelog draftchangelog",
+ "Docs drift check",
+ "Dependency updates",
+ "Flaky test triage",
+ "Changelog draft",
]);
expect(screen.getByText(/1 failed run/)).toBeVisible();
@@ -120,7 +120,7 @@ describe("TasksWorkspace", () => {
// The notice folds into the task's row: a New tag, with schedule and purpose behind a toggle.
const row = (await screen.findByRole("rowheader", { name: /Changelog draft/ })).closest("tr")!;
- expect(within(row).getByText("New")).toBeVisible();
+ expect(within(row).getByText("New definition")).toBeVisible();
expect(screen.queryByText(/Drafts release notes/)).toBeNull();
fireEvent.click(within(row).getByRole("button", { name: "What it does" }));
expect(screen.getByText("Runs every 1 day in Off mode. Drafts release notes.")).toBeVisible();
diff --git a/web/src/components/tasks/taskFormat.test.ts b/web/src/components/tasks/taskFormat.test.ts
index a30e346f6..a3a4e02c7 100644
--- a/web/src/components/tasks/taskFormat.test.ts
+++ b/web/src/components/tasks/taskFormat.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { formatDue, formatEvery, formatRelative } from "./taskFormat";
+import { formatDue, formatEvery, formatRelative, formatRunAge } from "./taskFormat";
const now = Date.parse("2026-11-04T18:00:00Z");
@@ -17,3 +17,11 @@ describe("task schedule wording", () => {
expect(formatDue(new Date(now - day).toISOString(), false, now)).toBe("Due now");
});
});
+
+it("names run ages without reading as a duration", () => {
+ expect(formatRunAge(new Date(now - 27 * 3_600_000).toISOString(), now)).toBe("1d ago");
+ expect(formatRunAge(new Date(now - 13 * 3_600_000).toISOString(), now)).toBe("13h ago");
+ expect(formatRunAge(new Date(now - 3_600_000).toISOString(), now)).toBe("1h ago");
+ expect(formatRunAge(new Date(now - 10_000).toISOString(), now)).toBe("just now");
+ expect(formatRunAge(new Date(now + day).toISOString(), now)).toBe("just now");
+});
diff --git a/web/src/components/tasks/taskFormat.ts b/web/src/components/tasks/taskFormat.ts
index 812d9c342..8d405358d 100644
--- a/web/src/components/tasks/taskFormat.ts
+++ b/web/src/components/tasks/taskFormat.ts
@@ -42,6 +42,12 @@ export function formatAgo(value: string | undefined, now = Date.now()): string {
return delta < 60_000 ? "just now" : `${span(delta)} ago`;
}
+export function formatRunAge(value: string, now = Date.now()): string {
+ const days = (now - new Date(value).getTime()) / 86_400_000;
+
+ return days >= 1 ? `${Math.round(days)}d ago` : formatAgo(value, now);
+}
+
/** "3h ago" or "in 3 hours". */
export function formatRelative(value: string | undefined, now = Date.now()): string {
if (!value) return "";
@@ -140,7 +146,7 @@ export function itemStatePresentation(state: TaskItemState): StatusPresentation
return { label, tone };
}
-export const MODE_LABELS = { auto: "Auto", notify: "Notify", off: "Off" } as const;
+export const MODE_LABELS = { auto: "Auto", notify: "Notify before running", off: "Off" } as const;
const LOCAL_STATES = {
new: ["Local only", "info"],
diff --git a/web/src/components/useExplorerListings.test.tsx b/web/src/components/useExplorerListings.test.tsx
new file mode 100644
index 000000000..a18195efe
--- /dev/null
+++ b/web/src/components/useExplorerListings.test.tsx
@@ -0,0 +1,51 @@
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { it, expect } from "vitest";
+import { renderWithQueryClient } from "../test/renderWithQueryClient";
+import { withFakeFetch, jsonReply, deferredReply } from "../test/fakeFetch";
+import type { TreeResponse } from "../api/types";
+import { useExplorerListings } from "./useExplorerListings";
+
+const http = withFakeFetch();
+
+function Listing() {
+ const { tree, more } = useExplorerListings(new Set());
+
+ return (
+ <>
+ {tree.map((entry) => entry.name).join(",")}
+
+ >
+ );
+}
+
+it("keeps successful entries and retries the failed limit after repeated errors", async () => {
+ const requests: string[] = [];
+ let next = deferredReply();
+ http.on("GET", "/api/v1/files/tree", (request) => {
+ const limit = request.query.get("limit") || "";
+ requests.push(limit);
+
+ return limit === "200"
+ ? jsonReply({
+ path: "",
+ entries: [{ path: "loaded.go", name: "loaded.go", kind: "code" }],
+ omitted: 401,
+ })
+ : next.promise;
+ });
+ renderWithQueryClient( );
+ await screen.findByText("loaded.go");
+
+ for (let attempt = 0; attempt < 2; attempt++) {
+ fireEvent.click(screen.getByRole("button", { name: /Show .* more/ }));
+ await waitFor(() => expect(requests).toHaveLength(attempt + 2));
+ expect(screen.getByText("loaded.go")).toBeTruthy();
+ next.reject(new Error("listing unavailable"));
+ await screen.findByRole("alert");
+ expect(screen.getByText("loaded.go")).toBeTruthy();
+ expect(screen.getByRole("button", { name: /Show .* more/ })).toBeEnabled();
+ next = deferredReply();
+ }
+
+ expect(requests).toEqual(["200", "400", "400"]);
+});
diff --git a/web/src/components/useExplorerListings.tsx b/web/src/components/useExplorerListings.tsx
new file mode 100644
index 000000000..801391609
--- /dev/null
+++ b/web/src/components/useExplorerListings.tsx
@@ -0,0 +1,69 @@
+import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { getTree } from "../api/client";
+import { queryKeys } from "../api/queryKeys";
+import type { TreeEntry, TreeResponse } from "../api/types";
+
+export function useExplorerListings(expandedPaths: Set) {
+ const queryClient = useQueryClient();
+ const [limits, setLimits] = useState>({});
+
+ const previousPage = (path: string) =>
+ queryClient
+ .getQueriesData({ queryKey: [...queryKeys.files.all(), "tree", path] })
+ .sort(
+ ([a], [b]) =>
+ (queryClient.getQueryState(b)?.dataUpdatedAt ?? 0) -
+ (queryClient.getQueryState(a)?.dataUpdatedAt ?? 0),
+ )
+ .map(([, data]) => data)
+ .find((data) => data !== undefined);
+
+ const options = (path: string) => ({
+ queryKey: queryKeys.files.tree(path || undefined, limits[path] ?? 200),
+ queryFn: ({ signal }: { signal: AbortSignal }) =>
+ getTree(path || undefined, limits[path] ?? 200, { signal }),
+ placeholderData: () => previousPage(path),
+ });
+
+ const treeQuery = useQuery(options(""));
+ const paths = [...expandedPaths].sort();
+ const queries = useQueries({ queries: paths.map(options) });
+ const expanded: Record = {};
+ paths.forEach((path, i) => {
+ expanded[path] = (queries[i].data ?? previousPage(path))?.entries ?? [];
+ });
+ const more: Record = {};
+ ["", ...paths].forEach((path, i) => {
+ const query = i === 0 ? treeQuery : queries[i - 1];
+ const omitted = (query.data ?? previousPage(path))?.omitted ?? 0;
+
+ if (omitted > 0)
+ more[path] = (
+
+
+ query.isError
+ ? query.refetch()
+ : setLimits((previous) => ({ ...previous, [path]: (previous[path] ?? 200) + 200 }))
+ }
+ >
+ Show {Math.min(200, omitted)} more ({omitted} remaining)
+
+ {query.isError && (
+
+ Could not load more.{" "}
+ query.refetch()}>
+ Retry
+
+
+ )}
+
+ );
+ });
+
+ return { treeQuery, tree: (treeQuery.data ?? previousPage(""))?.entries ?? [], expanded, more };
+}
diff --git a/web/src/components/useFolderExplorer.ts b/web/src/components/useFolderExplorer.ts
new file mode 100644
index 000000000..20d68d2ae
--- /dev/null
+++ b/web/src/components/useFolderExplorer.ts
@@ -0,0 +1,93 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import type { GraphResponse } from "../api/types";
+import { buildFolderTree, initialOpenFolders } from "./folderTree";
+import { visibleFolderGraph } from "./folderGraph";
+import { layoutFolderGraph, type FolderAnchors } from "./folderLayout";
+
+export function useFolderExplorer(
+ graph: GraphResponse,
+ colors: Map,
+ focusedPath?: string,
+) {
+ const anchors = useRef({ positions: new Map(), free: [] });
+ const tree = useMemo(() => buildFolderTree(graph), [graph]);
+ const initial = useMemo(() => initialOpenFolders(tree), [tree]);
+ const [overrides, setOverrides] = useState(new Map());
+ const [revealed, setRevealed] = useState(new Map());
+
+ const [explicit, setExplicit] = useState(new Set());
+
+ const open = useMemo(() => {
+ const result = new Set(initial);
+
+ for (const [path, value] of overrides) {
+ if (value) result.add(path);
+ else result.delete(path);
+ }
+
+ result.add("");
+
+ return result;
+ }, [initial, overrides]);
+
+ const drawn = useMemo(
+ () =>
+ layoutFolderGraph(
+ tree,
+ visibleFolderGraph(
+ tree,
+ { open, explicit, revealed },
+ (type) => colors.get(type),
+ focusedPath,
+ ),
+ anchors.current,
+ ),
+ [tree, open, explicit, revealed, colors, focusedPath],
+ );
+
+ return {
+ drawn,
+ initial,
+ open,
+ reveal(path: string) {
+ setRevealed((previous) => new Map(previous).set(path, (previous.get(path) ?? 0) + 1));
+ },
+ expand(path: string) {
+ setExplicit((previous) => new Set([...previous, path]));
+ setOverrides((previous) => {
+ const next = new Map(previous);
+
+ const parts = path.split("/");
+ parts.forEach((_, index) => next.set(parts.slice(0, index + 1).join("/"), true));
+
+ return next;
+ });
+ },
+ collapse(path: string) {
+ setOverrides((previous) => {
+ const next = new Map(previous);
+
+ for (const child of tree.folders.keys())
+ if (child === path || child.startsWith(`${path}/`)) next.set(child, false);
+
+ return next;
+ });
+ },
+ reset() {
+ setOverrides(new Map());
+ setExplicit(new Set());
+ setRevealed(new Map());
+ },
+ };
+}
+
+export function useDebouncedValue(value: string, delay: number) {
+ const [debounced, setDebounced] = useState(value);
+ useEffect(() => {
+ const timer = window.setTimeout(() => setDebounced(value), delay);
+
+ return () => window.clearTimeout(timer);
+ }, [delay, value]);
+
+ return debounced;
+}
diff --git a/web/src/components/useSigmaGraph.lifecycle.test.tsx b/web/src/components/useSigmaGraph.lifecycle.test.tsx
index a858a065f..0043d7e82 100644
--- a/web/src/components/useSigmaGraph.lifecycle.test.tsx
+++ b/web/src/components/useSigmaGraph.lifecycle.test.tsx
@@ -1,9 +1,11 @@
-import { act, render } from "@testing-library/react";
+import { act, fireEvent, render } from "@testing-library/react";
import type { ReactNode } from "react";
import Sigma from "sigma";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { GraphEdge, GraphNode } from "../api/types";
import { installFakeWebGL } from "../test/fakeWebGL";
+import * as layouts from "./graphLayout";
+import type { GraphViewNode } from "./graphViewShared";
import { useSigmaGraph } from "./useSigmaGraph";
const firstNode: GraphNode = {
@@ -32,15 +34,18 @@ function Harness({
highlightTypes,
scope = globalScope,
problemCounts,
+ layoutExtent,
}: {
- nodes: GraphNode[];
+ nodes: GraphViewNode[];
+ layoutExtent?: number;
onNodeClick: (node: GraphNode) => void;
highlightTypes?: ReadonlySet;
scope?: { mode: "global" | "local"; label?: string };
problemCounts?: ReadonlyMap;
}): ReactNode {
- const { containerRef, hover } = useSigmaGraph({
+ const { containerRef, hover, handleFitToView } = useSigmaGraph({
nodes,
+ layoutExtent,
problemCounts,
edges: emptyEdges,
scope,
@@ -56,6 +61,7 @@ function Harness({
return (
<>
+ Fit
{hover && {hover.label}
}
>
);
@@ -91,6 +97,102 @@ describe("useSigmaGraph renderer lifecycle", () => {
vi.restoreAllMocks();
});
+ it("keeps fixed coordinates when expanding without running layout", () => {
+ const layout = vi.spyOn(layouts, "runLayout");
+ const onSpy = vi.spyOn(Sigma.prototype, "on");
+
+ const nodes = [
+ { ...firstNode, x: -100, y: 20 },
+ { ...secondNode, x: 80, y: -40 },
+ ];
+
+ const view = render( );
+ const renderer = Array.from(new Set(onSpy.mock.contexts)).filter(isSigma)[0];
+ const before = nodes.map((node) => renderer.getNodeDisplayData(node.id));
+ view.rerender(
+ ,
+ );
+
+ for (const node of nodes) {
+ expect(renderer.getGraph().getNodeAttribute(node.id, "x")).toBe(node.x);
+ expect(renderer.getGraph().getNodeAttribute(node.id, "y")).toBe(node.y);
+ }
+
+ expect(renderer.getCustomBBox()).toEqual({ x: [-500, 500], y: [-500, 500] });
+ expect(nodes.map((node) => renderer.getNodeDisplayData(node.id))).toEqual(before);
+ expect(layout).not.toHaveBeenCalled();
+ view.unmount();
+ });
+
+ it("preserves folder cameras on refresh and expansion, and fits navigation and Fit", () => {
+ vi.useFakeTimers();
+ const onSpy = vi.spyOn(Sigma.prototype, "on");
+ const scope = { mode: "global" } as const;
+ const root = { id: "folder:", label: "Vault", kind: "module", center: true, x: 0, y: 0 };
+ const folder = { id: "folder:pkg", label: "pkg", kind: "module", x: 100, y: 20 };
+ const view = render( );
+
+ try {
+ const renderer = Array.from(new Set(onSpy.mock.contexts)).filter(isSigma)[0];
+ act(() => vi.advanceTimersByTime(600));
+ const camera = renderer.getCamera();
+ camera.setState({ x: 0.23, y: 0.71, angle: 0.2, ratio: 1.7 });
+ const before = camera.getState();
+ view.rerender(
+ ,
+ );
+ act(() => vi.advanceTimersByTime(600));
+ expect(camera.getState()).toEqual(before);
+ view.rerender(
+ ,
+ );
+ act(() => vi.advanceTimersByTime(600));
+ expect(camera.getState()).not.toEqual(before);
+ camera.setState(before);
+ view.rerender(
+ ,
+ );
+ act(() => vi.advanceTimersByTime(600));
+ expect(camera.getState()).not.toEqual(before);
+ camera.setState(before);
+ view.rerender(
+ ,
+ );
+ act(() => vi.advanceTimersByTime(600));
+ expect(camera.getState()).not.toEqual(before);
+ camera.setState(before);
+ fireEvent.click(view.getByRole("button", { name: "Fit" }));
+ act(() => vi.advanceTimersByTime(600));
+ expect(camera.getState()).not.toEqual(before);
+ } finally {
+ view.unmount();
+ vi.useRealTimers();
+ }
+ });
+
it("installs problem counts that arrive while a worker lays the graph out", () => {
// WHY: a stand-in Worker holds the layout until the test answers it, so
// counts can change between the layout request and the install.
diff --git a/web/src/components/useSigmaGraph.ts b/web/src/components/useSigmaGraph.ts
index 37e5dd3f9..d10484030 100644
--- a/web/src/components/useSigmaGraph.ts
+++ b/web/src/components/useSigmaGraph.ts
@@ -1,35 +1,27 @@
-import { createNodeImageProgram } from "@sigma/node-image";
-import Graph from "graphology";
+import type { ExplorerNodeAttrs as SigmaNodeAttrs } from "./explorerGraph";
+import { graphClusters } from "./graphClusters";
+import {
+ mountSigmaRenderer,
+ readThemeColors,
+ rendererColorSettings,
+ type ThemeColors,
+} from "./sigmaRenderer";
+import type Graph from "graphology";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import Sigma from "sigma";
-import { drawDiscNodeLabel, type NodeHoverDrawingFunction } from "sigma/rendering";
+import type Sigma from "sigma";
import type { GraphEdge, GraphNode } from "../api/types";
-import { createLabelPainter } from "./sigmaLabels";
-import {
- computeEdgeStyle,
- computeNodeStyle,
- type GraphColors,
- graphNodeIdentityAttrs,
- lodFromRatio,
- mixColors,
- type ReducerState,
- type SigmaEdgeAttrs,
- type SigmaNodeAttrs,
-} from "../lib/graphStyle";
+import { type ReducerState, type SigmaEdgeAttrs } from "../lib/graphStyle";
import { resolveCssColor, subscribeColorScheme } from "../lib/themeColors";
import {
CAMERA,
communityColor,
- edgeKindLabel,
type GraphScope,
type GraphViewNode,
type HoverInfo,
- MIXED_EDGE_LABEL,
- NODE_SIZE,
- nodeColor,
- nodeIcon,
} from "./graphViewShared";
-import { type LayoutInput, type LayoutPositions, runLayout } from "./graphLayout";
+import { type LayoutPositions } from "./graphLayout";
+import { buildSigmaGraph, layoutSigmaGraph } from "./sigmaGraphData";
+import { fitFixedGraph, zoomGraph } from "./sigmaCamera";
type SigmaRenderer = Sigma;
@@ -56,137 +48,6 @@ export type GraphNodeClickOptions = {
beside: boolean;
};
-// WHY: the exported `NodeImageProgram` is typed for untyped graph attributes;
-// building it through the factory binds it to this graph's attribute types.
-const NodeImageProgram = createNodeImageProgram();
-
-// WHY: Sigma 3.0 keeps `getNodeAtPosition` private, and hover picking while the
-// pointer drags the camera has no public equivalent. Read the member through
-// element access (the sanctioned escape hatch for a private member, which the
-// published declaration leaves untyped), check that it is callable, and fall
-// back to enterNode/leaveNode events if a future Sigma drops it.
-type NodePicker = (position: { x: number; y: number }) => string | null;
-
-type ThemeColors = GraphColors & {
- label: string;
- edgeLabel: string;
- surface: string;
- /** The graph canvas behind node labels. */
- canvas: string;
-};
-
-/** Read the renderer colors from the current theme's tokens. */
-function readThemeColors(): ThemeColors {
- const border = resolveCssColor("var(--border)");
- const strong = resolveCssColor("var(--border-strong)");
- const faint = resolveCssColor("var(--text-faint)");
-
- return {
- neutral: resolveCssColor("var(--type-8)"),
- edgeFaint: border,
- edgeLight: mixColors(border, strong, 0.35),
- edgeStrong: mixColors(strong, faint, 0.35),
- label: resolveCssColor("var(--text)"),
- edgeLabel: faint,
- surface: resolveCssColor("var(--surface)"),
- canvas: resolveCssColor("var(--surface-alt)"),
- };
-}
-
-function rendererColorSettings(colors: ThemeColors) {
- return {
- defaultEdgeColor: colors.edgeFaint,
- labelColor: { color: colors.label },
- edgeLabelColor: { color: colors.edgeLabel },
- };
-}
-
-// WHY: Sigma's default hover box is hard-coded white, which hides the light
-// label text of the dark theme. This draws the same shape on the surface token.
-function themedNodeHover(
- colors: () => ThemeColors,
-): NodeHoverDrawingFunction {
- return (context, data, settings) => {
- const size = settings.labelSize;
- const padding = 2;
- context.font = `${settings.labelWeight} ${size}px ${settings.labelFont}`;
- context.fillStyle = colors().surface;
- context.shadowBlur = 8;
- context.shadowColor = "rgba(0, 0, 0, 0.35)";
-
- const radius = Math.max(data.size, size / 2) + padding;
- context.beginPath();
-
- if (data.label) {
- const boxWidth = Math.round(context.measureText(data.label).width + 5);
- const boxHeight = Math.round(size + 2 * padding);
- const angle = Math.asin(boxHeight / 2 / radius);
- const dx = Math.sqrt(Math.abs(radius ** 2 - (boxHeight / 2) ** 2));
- context.moveTo(data.x + dx, data.y + boxHeight / 2);
- context.lineTo(data.x + radius + boxWidth, data.y + boxHeight / 2);
- context.lineTo(data.x + radius + boxWidth, data.y - boxHeight / 2);
- context.lineTo(data.x + dx, data.y - boxHeight / 2);
- context.arc(data.x, data.y, radius, angle, -angle);
- } else {
- context.arc(data.x, data.y, data.size + padding, 0, Math.PI * 2);
- }
-
- context.closePath();
- context.fill();
- context.shadowBlur = 0;
- drawDiscNodeLabel(context, data, settings);
- };
-}
-
-/**
- * How many of the most-connected notes and folders keep a label at every zoom,
- * so the default view orients the reader. Code symbols are left out: their
- * short names ("types", "handle") do not say where the reader is.
- */
-const LANDMARKS = 20;
-
-/**
- * A node's radius before authority scaling. Notes and code start small so a
- * dense graph reads as structure, not a mass; a folder that summarizes its
- * contents grows with the square root of what it holds.
- */
-function nodeBaseSize(node: GraphViewNode) {
- const center = node.center ? 2 : 0;
-
- if (node.kind !== "module") return NODE_SIZE.base.normal + center;
-
- if (!node.childCount) return NODE_SIZE.base.module + center;
-
- return Math.min(28, 4 + Math.sqrt(node.childCount) * 0.55) + center;
-}
-
-/** Rebuild the API graph node a click refers to from its renderer attributes. */
-function graphNodeFromAttrs(id: string, attrs: SigmaNodeAttrs): GraphNode {
- return {
- id,
- label: attrs.label ?? id,
- kind: attrs.kind,
- lang: attrs.lang,
- path: attrs.path,
- notePath: attrs.notePath,
- nodeId: attrs.nodeId,
- nodeRef: attrs.nodeRef,
- sourceLocator: attrs.sourceLocator,
- module: attrs.module,
- community: attrs.community,
- resolvedType: attrs.resolvedType,
- childCount: attrs.childCount,
- hub: attrs.hub,
- authority: attrs.authority,
- pageRank: attrs.pageRank,
- score: attrs.score,
- };
-}
-
-function isNodePicker(value: unknown): value is NodePicker {
- return typeof value === "function";
-}
-
export function useSigmaGraph({
nodes,
edges,
@@ -203,7 +64,11 @@ export function useSigmaGraph({
problemCounts = EMPTY_PROBLEM_COUNTS,
showProblems = false,
display,
+ layoutExtent,
+ explorer = false,
}: {
+ layoutExtent?: number;
+ explorer?: boolean;
nodes: GraphViewNode[];
edges: GraphEdge[];
needsIndex?: boolean;
@@ -221,6 +86,13 @@ export function useSigmaGraph({
/** Display toggles a caller remembers; without them the toggles last as long as the graph. */
display?: Pick;
}) {
+ const fixed =
+ nodes.length > 0 && nodes.every((n) => Number.isFinite(n.x) && Number.isFinite(n.y));
+
+ const fixedRef = useRef(fixed);
+ fixedRef.current = fixed;
+ const didFit = useRef(false);
+ const fittedSubject = useRef(undefined);
const containerRef = useRef(null);
const sigmaRef = useRef(null);
const graphRef = useRef(null);
@@ -292,9 +164,10 @@ export function useSigmaGraph({
const path = node.path || "";
const matched =
+ searchModules.has(node.id) ||
(node.kind !== "module" && path && searchPaths.has(path)) ||
(node.kind === "module" &&
- (searchModules.has(path) || searchModules.has(node.label || "")));
+ (searchModules.has(node.id) || searchModules.has(path) || searchModules.has(node.label)));
if (matched) matches.add(node.id);
});
@@ -313,36 +186,7 @@ export function useSigmaGraph({
return colors;
}, [nodes]);
- const clusters = useMemo(() => {
- const byCommunity = new Map();
- nodes.forEach((node) => {
- if (!node.community) return;
-
- const current = byCommunity.get(node.community) || {
- size: 0,
- topLabel: "",
- topAuthority: -1,
- };
-
- current.size += 1;
-
- if (node.kind === "note" && (node.authority ?? -1) > current.topAuthority) {
- current.topAuthority = node.authority ?? -1;
- current.topLabel = node.label;
- }
-
- byCommunity.set(node.community, current);
- });
-
- return Array.from(byCommunity.entries())
- .map(([id, data]) => ({
- id,
- size: data.size,
- label: data.topLabel || `Cluster ${id}`,
- color: communityColors.get(id) || "var(--type-8)",
- }))
- .sort((a, b) => b.size - a.size);
- }, [communityColors, nodes]);
+ const clusters = useMemo(() => graphClusters(nodes, communityColors), [nodes, communityColors]);
const maxScore = useMemo(() => {
let max = 0;
@@ -391,9 +235,7 @@ export function useSigmaGraph({
showProblems,
};
- // WHY: type highlighting belongs in Sigma reducers so changing it refreshes
- // existing node and edge attributes without rebuilding the graph, rerunning
- // layout, or changing the camera state.
+ // Reducers refresh highlights without rebuilding the graph or moving the camera.
if (sigmaRef.current) {
sigmaRef.current.setSetting("renderEdgeLabels", showEdgeLabels);
scheduleRefresh();
@@ -413,418 +255,51 @@ export function useSigmaGraph({
showProblems,
]);
- // One renderer per mounted container. Data refreshes swap its graph (below)
- // instead of recreating it, so WebGL state and the camera survive a refresh.
+ // Swap graphs on one renderer to preserve the camera and WebGL state.
const empty = nodes.length === 0;
useEffect(() => {
const container = containerRef.current;
if (!container || needsIndex || empty) return;
- container.style.cursor = "grab";
-
- const labels = createLabelPainter(
- () => sigmaRef.current,
- () => colorsRef.current ?? readThemeColors(),
- );
-
- // WHY: allowInvalidContainer keeps Sigma from throwing when its container
- // has zero width at mount time — this can happen on the first commit
- // before flex layout has resolved cross-axis sizing. Sigma resizes itself
- // once layout settles, so the only effect is suppressing a fatal error
- // that would otherwise tear down the React tree without an error boundary.
- const sigma: SigmaRenderer = new Sigma(new Graph(), container, {
- renderEdgeLabels: stateRef.current.showEdgeLabels,
- labelDensity: 0.07,
- // Wider cells keep long labels from overlapping in dense clusters.
- labelGridCellSize: 140,
- labelRenderedSizeThreshold: 10,
- // The plotted bounds keep clear of the canvas edge and the zoom controls.
- stagePadding: 44,
- // Canvas text cannot read CSS variables; this is --font-sans.
- labelFont: "Inter, -apple-system, system-ui, sans-serif",
- edgeLabelFont: "Inter, -apple-system, system-ui, sans-serif",
- defaultNodeType: "circle",
- ...rendererColorSettings(colorsRef.current ?? readThemeColors()),
- defaultDrawNodeHover: themedNodeHover(() => colorsRef.current ?? readThemeColors()),
- defaultDrawNodeLabel: labels.draw,
- minCameraRatio: CAMERA.minRatio,
- maxCameraRatio: CAMERA.maxRatio,
- zIndex: true,
- enableEdgeEvents: true,
- edgeLabelSize: 9,
- edgeLabelWeight: "500",
- nodeProgramClasses: { image: NodeImageProgram },
- nodeHoverProgramClasses: { image: NodeImageProgram },
- allowInvalidContainer: true,
- });
-
- sigmaRef.current = sigma;
- sigma.on("beforeRender", labels.beginFrame);
- const outlines = sigma.createCanvas("outlines", { beforeLayer: "labels" });
- sigma.on("afterRender", () => {
- const context = outlines.getContext("2d");
-
- if (!context) return;
- const { width, height } = sigma.getDimensions();
- const ratio = window.devicePixelRatio || 1;
- outlines.width = width * ratio;
- outlines.height = height * ratio;
- outlines.style.width = `${width}px`;
- outlines.style.height = `${height}px`;
- context.save();
- context.scale(outlines.width / width, outlines.height / height);
- context.clearRect(0, 0, width, height);
- context.strokeStyle = (colorsRef.current ?? readThemeColors()).label;
- context.lineWidth = 1.5;
- sigma.getGraph().forEachNode((id) => {
- const node = sigma.getNodeDisplayData(id);
-
- if (!node || node.hidden) return;
- const point = sigma.framedGraphToViewport(node);
- context.beginPath();
- context.arc(point.x, point.y, sigma.scaleSize(node.size), 0, 2 * Math.PI);
- context.stroke();
- });
- context.restore();
- });
- const camera = sigma.getCamera();
- stateRef.current.cameraRatio = camera.getState().ratio;
-
- sigma.setSetting("nodeReducer", (nodeId, attrs) => {
- const lod = lodFromRatio(stateRef.current.cameraRatio);
- const result = computeNodeStyle({
- nodeId,
- attrs,
- state: stateRef.current,
- lod,
- });
-
- return {
- ...attrs,
- hidden: result.hidden,
- type: result.type,
- image: result.image,
- size: result.size,
- color: result.color,
- label: result.label,
- forceLabel: Boolean(attrs.landmark && result.label),
- };
+ const cleanup = mountSigmaRenderer({
+ container,
+ sigmaRef,
+ graphRef,
+ stateRef,
+ colorsRef,
+ onNodeClickRef,
+ connectionCountsRef,
+ setHover,
+ scheduleRefresh,
});
- sigma.setSetting("edgeReducer", (edgeId, attrs) => {
- const graph = sigma.getGraph();
- const source = graph.source(edgeId);
- const target = graph.target(edgeId);
- const sourceAttrs = graph.getNodeAttributes(source);
- const targetAttrs = graph.getNodeAttributes(target);
- const lod = lodFromRatio(stateRef.current.cameraRatio);
-
- const result = computeEdgeStyle({
- source,
- target,
- attrs,
- sourceAttrs,
- targetAttrs,
- state: stateRef.current,
- lod,
- });
-
- return {
- ...attrs,
- hidden: result.hidden,
- color: result.color,
- size: result.size,
- label: result.label,
- };
- });
-
- const pickCandidate = sigma["getNodeAtPosition"];
-
- const picker: NodePicker | null = isNodePicker(pickCandidate)
- ? pickCandidate.bind(sigma)
- : null;
-
- const mouseCaptor = sigma.getMouseCaptor();
- const mouseCanvas = sigma.getCanvases().mouse;
-
- const onWheel = (event: WheelEvent) => {
- // Trackpad pinches arrive as Ctrl+wheel and zoom; any other scroll pans.
- // Handle both before Sigma's own wheel listener zooms on every scroll.
- event.stopImmediatePropagation();
- event.preventDefault();
- const bounds = container.getBoundingClientRect();
- const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? bounds.height : 1;
-
- if (!event.ctrlKey) {
- const { width, height } = sigma.getDimensions();
-
- const center = sigma.viewportToFramedGraph({
- x: width / 2 + event.deltaX * scale,
- y: height / 2 + event.deltaY * scale,
- });
-
- camera.setState({ x: center.x, y: center.y });
-
- return;
- }
-
- const delta = event.deltaY * scale;
-
- const ratio = camera.getBoundedRatio(camera.getState().ratio * Math.exp(delta * 0.01));
- camera.setState(
- sigma.getViewportZoomedState(
- { x: event.clientX - bounds.left, y: event.clientY - bounds.top },
- ratio,
- ),
- );
- };
-
- mouseCanvas?.addEventListener("wheel", onWheel, { capture: true, passive: false });
- let hoverFrameID: number | null = null;
- let lastPointer: { x: number; y: number } | null = null;
-
- // Compare with the shared hover state, which a graph swap clears.
- const syncHoverNode = (nextNode: string | null) => {
- if (stateRef.current.hoverNodeID === nextNode) return;
-
- if (!nextNode) {
- container.style.cursor = "grab";
-
- if (mouseCanvas) mouseCanvas.style.cursor = "grab";
- stateRef.current.hoverNodeID = null;
- stateRef.current.hoverNeighbors = undefined;
- stateRef.current.hoverCommunity = null;
- setHover(null);
- scheduleRefresh();
-
- return;
- }
-
- const attrs = sigma.getGraph().getNodeAttributes(nextNode);
- container.style.cursor = "pointer";
-
- if (mouseCanvas) mouseCanvas.style.cursor = "pointer";
- stateRef.current.hoverNodeID = nextNode;
- stateRef.current.hoverNeighbors = new Set(sigma.getGraph().neighbors(nextNode));
- stateRef.current.hoverCommunity =
- attrs.kind === "code" && attrs.community ? attrs.community : null;
- setHover({
- label: attrs.label ?? nextNode,
- kind: attrs.kind,
- path: attrs.path,
- nodeId: attrs.nodeId || nextNode,
- resolvedType: attrs.resolvedType,
- connectionCount: connectionCountsRef.current.get(nextNode) || 0,
- problemCount: attrs.problemCount,
- });
- scheduleRefresh();
- };
-
- sigma.on("enterNode", ({ node }) => syncHoverNode(node));
- sigma.on("leaveNode", () => syncHoverNode(null));
-
- const clearHoverFrame = () => {
- if (hoverFrameID === null) return;
- window.cancelAnimationFrame(hoverFrameID);
- hoverFrameID = null;
- };
-
- const flushHoverFromPointer = () => {
- hoverFrameID = null;
-
- if (!lastPointer || !picker) return;
- const hovered = picker({ x: lastPointer.x, y: lastPointer.y });
- syncHoverNode(hovered ?? null);
- };
-
- const queueHoverFromPointer = (x: number, y: number) => {
- lastPointer = { x, y };
-
- if (hoverFrameID !== null) return;
- hoverFrameID = window.requestAnimationFrame(flushHoverFromPointer);
- };
-
- const onMouseMoveBody = ({ x, y }: { x: number; y: number }) => {
- if (!picker) return;
- const { width, height } = sigma.getDimensions();
- const inside = x >= 0 && y >= 0 && x <= width && y <= height;
-
- if (!inside) {
- lastPointer = null;
- clearHoverFrame();
- syncHoverNode(null);
-
- return;
- }
-
- queueHoverFromPointer(x, y);
- };
-
- if (picker) {
- mouseCaptor.on("mousemovebody", onMouseMoveBody);
- }
-
- const onCameraUpdated = () => {
- const nextRatio = camera.getState().ratio;
-
- if (stateRef.current.cameraRatio !== nextRatio) {
- stateRef.current.cameraRatio = nextRatio;
- scheduleRefresh();
- }
-
- if (picker && lastPointer) queueHoverFromPointer(lastPointer.x, lastPointer.y);
- };
-
- camera.on("updated", onCameraUpdated);
-
- sigma.on("clickNode", ({ node, event }) => {
- const attrs = sigma.getGraph().getNodeAttributes(node);
- const original = event.original;
-
- const beside =
- original instanceof MouseEvent && (original.metaKey || original.ctrlKey) ? true : false;
-
- onNodeClickRef.current(graphNodeFromAttrs(node, attrs), { beside });
- });
-
- return () => {
- camera.off("updated", onCameraUpdated);
- mouseCanvas?.removeEventListener("wheel", onWheel, true);
-
- if (picker) mouseCaptor.removeListener("mousemovebody", onMouseMoveBody);
- clearHoverFrame();
- container.style.cursor = "grab";
-
- if (mouseCanvas) mouseCanvas.style.cursor = "grab";
- sigma.kill();
- sigmaRef.current = null;
- graphRef.current = null;
- };
+ return cleanup;
}, [empty, needsIndex, scheduleRefresh]);
- // Builds the graph for the current data and installs it on the renderer once
- // laid out. Large layouts run in a worker; until one finishes, the renderer
- // keeps showing the previous graph.
+ // Keep the previous graph visible until this layout is ready.
useEffect(() => {
const sigma = sigmaRef.current;
if (!sigma || needsIndex || empty) return;
- const graph: SigmaGraph = new Graph({ multi: true });
-
- // A folder that summarizes its contents ranks by what it holds, and every
- // one is named; anything else ranks by its links.
- const rank = (node: GraphViewNode) =>
- node.kind === "module" && node.childCount
- ? node.childCount
- : (connectionCounts.get(node.id) ?? 0);
-
- const landmarks = new Set(
- nodes
- .filter((node) => node.kind !== "code")
- .sort((a, b) => rank(b) - rank(a) || a.id.localeCompare(b.id))
- .filter((node, index) => rank(node) > 0 && (index < LANDMARKS || Boolean(node.fill)))
- .map((node) => node.id),
- );
-
- const total = Math.max(1, nodes.length);
- const radius = Math.max(80, Math.sqrt(total) * 28);
-
- const hasCompleteGlobalLayout =
- scope.mode === "global" &&
- nodes.length > 0 &&
- nodes.every((node) => globalLayoutRef.current.has(node.id));
-
- nodes.forEach((n, index) => {
- const cached = scope.mode === "global" ? globalLayoutRef.current.get(n.id) : undefined;
- const angle = (index / total) * Math.PI * 2;
- const jitter = (Math.random() - 0.5) * 12;
- const x = cached ? cached.x : Math.cos(angle) * radius + jitter;
- const y = cached ? cached.y : Math.sin(angle) * radius + jitter;
-
- const baseSize = nodeBaseSize(n);
-
- const colorValue = n.fill ?? nodeColor(n, communityColors, typeColors);
- const baseColor = resolveCssColor(colorValue);
- graph.addNode(n.id, {
- label: n.label,
- kind: n.kind,
- center: Boolean(n.center),
- ...graphNodeIdentityAttrs(n),
- module: n.module,
- lang: n.lang,
- community: n.community,
- resolvedType: n.resolvedType,
- childCount: n.childCount,
- authority: n.authority,
- hub: n.hub,
- pageRank: n.pageRank,
- score: n.score,
- problemCount: problemCountsRef.current.get(n.id) ?? 0,
- landmark: landmarks.has(n.id),
- baseSize,
- colorValue,
- baseColor,
- size: baseSize,
- color: baseColor,
- type: "circle",
- image: nodeIcon(n.kind),
- x,
- y,
- });
- });
-
- const edgeAgg = new Map<
- string,
- {
- source: string;
- target: string;
- weight: number;
- kind: string;
- label?: string;
- }
- >();
-
- edges.forEach((e) => {
- if (!graph.hasNode(e.source) || !graph.hasNode(e.target)) return;
- const a = e.source <= e.target ? e.source : e.target;
- const b = e.source <= e.target ? e.target : e.source;
- const key = `${a}|${b}|${e.kind === "folder-containment" ? "containment" : "links"}`;
- const current = edgeAgg.get(key);
-
- if (!current) {
- edgeAgg.set(key, {
- source: a,
- target: b,
- weight: e.weight ?? 1,
- kind: e.kind,
- label: e.relationLabel || edgeKindLabel(e.kind),
- });
- } else {
- current.weight += e.weight ?? 1;
-
- if (current.kind !== e.kind) {
- current.kind = "mixed";
- current.label = MIXED_EDGE_LABEL;
- }
- }
- });
-
- Array.from(edgeAgg.values()).forEach((e, index) => {
- graph.addEdgeWithKey(`edge-${index}`, e.source, e.target, {
- size: Math.max(0.6, Math.min(4, Math.sqrt(e.weight))),
- weight: e.weight,
- color: stateRef.current.colors.edgeFaint,
- baseColor: stateRef.current.colors.edgeFaint,
- kind: e.kind,
- label: e.label || edgeKindLabel(e.kind),
- });
+ const { graph, hasCompleteGlobalLayout } = buildSigmaGraph({
+ nodes,
+ edges,
+ scope,
+ connectionCounts,
+ globalLayout: globalLayoutRef.current,
+ communityColors,
+ typeColors,
+ problemCounts: problemCountsRef.current,
+ edgeFaint: stateRef.current.colors.edgeFaint,
+ fixed,
+ explorer,
});
const shouldRunLayout =
- graph.order > 1 && (scope.mode !== "global" || !hasCompleteGlobalLayout);
+ !fixed && graph.order > 1 && (scope.mode !== "global" || !hasCompleteGlobalLayout);
const install = (positions?: LayoutPositions) => {
if (positions) {
@@ -843,7 +318,6 @@ export function useSigmaGraph({
globalLayoutRef.current = nextLayout;
}
- // Counts can arrive while a worker lays the graph out; install the latest.
graph.forEachNode((id) => {
graph.setNodeAttribute(id, "problemCount", problemCountsRef.current.get(id) ?? 0);
});
@@ -853,8 +327,33 @@ export function useSigmaGraph({
stateRef.current.hoverNodeID = null;
stateRef.current.hoverNeighbors = undefined;
graphRef.current = graph;
+ sigma.setCustomBBox(
+ fixed && layoutExtent !== undefined
+ ? { x: [-layoutExtent, layoutExtent], y: [-layoutExtent, layoutExtent] }
+ : null,
+ );
+ sigma.setSettings({
+ labelSize: explorer && scope.mode === "local" ? 13 : 14,
+ labelWeight: explorer || fixed ? "500" : "normal",
+ edgeLabelSize: explorer || fixed ? 13 : 9,
+ });
sigma.setGraph(graph);
- // Ready once the renderer has drawn this graph, not merely received it.
+
+ if (fixed) {
+ sigma.refresh();
+
+ const subject = JSON.stringify([
+ scope.mode,
+ scope.label,
+ nodes.find((node) => node.center)?.id,
+ ]);
+
+ if (!didFit.current || subject !== fittedSubject.current)
+ fitFixedGraph(sigma, !didFit.current);
+ fittedSubject.current = subject;
+ didFit.current = true;
+ }
+
sigma.once("afterRender", () => setDrawn(nodes));
scheduleRefresh();
};
@@ -865,35 +364,11 @@ export function useSigmaGraph({
return;
}
- const isWarmGlobal = scope.mode === "global" && globalLayoutRef.current.size > 0;
-
- // A small graph settles fully for a few hundred passes at no visible cost.
- const iterations = isWarmGlobal
- ? 28
- : graph.order > 400
- ? 50
- : graph.order > 200
- ? 80
- : graph.order > 80
- ? 120
- : 600;
-
- const layoutNodes: LayoutInput["nodes"] = [];
- graph.forEachNode((id, attrs) =>
- layoutNodes.push({ id, x: attrs.x, y: attrs.y, size: attrs.baseSize }),
- );
- const layoutEdges: LayoutInput["edges"] = [];
- // Hidden minor folder links do not pull their folders together.
- graph.forEachEdge(
- (_edge, attrs, source, target) =>
- attrs.kind !== "folder-minor" &&
- layoutEdges.push({ source, target, weight: attrs.weight ?? 1 }),
- );
-
- const radial = nodes.length > 0 && nodes.every((node) => node.kind === "module" && node.fill);
-
- return runLayout({ nodes: layoutNodes, edges: layoutEdges, iterations, radial }, install);
+ return layoutSigmaGraph(graph, nodes, scope, globalLayoutRef.current, install);
}, [
+ fixed,
+ explorer,
+ layoutExtent,
communityColors,
connectionCounts,
edges,
@@ -902,11 +377,11 @@ export function useSigmaGraph({
nodes,
scheduleRefresh,
scope.mode,
+ scope.label,
typeColors,
]);
- // A theme switch re-reads the token colors and repaints in place: no new
- // renderer, no layout run, and the camera stays where it was.
+ // Repaint theme colors without moving nodes or the camera.
useEffect(
() =>
subscribeColorScheme(() => {
@@ -947,6 +422,13 @@ export function useSigmaGraph({
sigma.refresh();
const camera = sigma.getCamera();
const state = camera.getState();
+
+ if (fixedRef.current) {
+ fitFixedGraph(sigma, false);
+
+ return;
+ }
+
camera.animate({ x: 0.5, y: 0.5, angle: 0, ratio: state.ratio }, { duration: 350 });
}, 120);
@@ -967,33 +449,25 @@ export function useSigmaGraph({
stateRef.current.hoverCommunity = null;
stateRef.current.hoverNodeID = null;
stateRef.current.hoverNeighbors = undefined;
- // A different subject starts from the default view; a refresh of the same
- // subject keeps the reader's camera.
+
+ if (fixedRef.current) return;
sigmaRef.current?.getCamera().setState({ x: 0.5, y: 0.5, ratio: 1, angle: 0 });
}, [scope.label, scope.mode]);
- const handleZoomIn = useCallback(() => {
- const sigma = sigmaRef.current;
-
- if (!sigma) return;
- const camera = sigma.getCamera();
- const ratio = Math.max(CAMERA.minRatio, camera.getState().ratio * CAMERA.zoomStep);
- camera.animate({ ratio }, { duration: 200 });
- }, []);
+ const handleZoomIn = useCallback(() => zoomGraph(sigmaRef.current, CAMERA.zoomStep), []);
+ const handleZoomOut = useCallback(() => zoomGraph(sigmaRef.current, 1 / CAMERA.zoomStep), []);
- const handleZoomOut = useCallback(() => {
+ const handleFitToView = useCallback(() => {
const sigma = sigmaRef.current;
if (!sigma) return;
- const camera = sigma.getCamera();
- const ratio = Math.min(CAMERA.maxRatio, camera.getState().ratio / CAMERA.zoomStep);
- camera.animate({ ratio }, { duration: 200 });
- }, []);
- const handleFitToView = useCallback(() => {
- const sigma = sigmaRef.current;
+ if (fixedRef.current) {
+ fitFixedGraph(sigma, false);
+
+ return;
+ }
- if (!sigma) return;
const camera = sigma.getCamera();
camera.animate({ x: 0.5, y: 0.5, ratio: 1, angle: 0 }, { duration: 300 });
}, []);
diff --git a/web/src/components/useViewLayout.ts b/web/src/components/useViewLayout.ts
index a1c4e0107..c597afe6a 100644
--- a/web/src/components/useViewLayout.ts
+++ b/web/src/components/useViewLayout.ts
@@ -78,6 +78,15 @@ export function useViewLayout(
slot,
);
+ const [boardDensityChoice, setBoardDensity] = useStoredViewChoice(
+ "boardDensity",
+ vaultKey,
+ view,
+ (value: unknown): value is "full" | "compact" => value === "full" || value === "compact",
+ context,
+ slot,
+ );
+
const [columnWidths, setColumnWidths] = useStoredViewChoice(
"widths",
vaultKey,
@@ -169,6 +178,8 @@ export function useViewLayout(
},
density,
densityChoice,
+ boardDensityChoice,
+ setBoardDensity,
setDensity,
columnWidths,
setColumnWidths,
diff --git a/web/src/components/validation/ValidationIssueDisclosure.tsx b/web/src/components/validation/ValidationIssueDisclosure.tsx
index 227cf48a0..f867d8a68 100644
--- a/web/src/components/validation/ValidationIssueDisclosure.tsx
+++ b/web/src/components/validation/ValidationIssueDisclosure.tsx
@@ -1,4 +1,5 @@
import type { ValidationCheckSnapshot, ValidationSnapshot } from "../../api/types";
+import { ValidationCheck } from "../StatusMark";
import { humanizeName } from "../../lib/labels";
export function ValidationIssueDisclosure({ snapshot }: { snapshot?: ValidationSnapshot }) {
@@ -73,10 +74,15 @@ export function CleanCheckList({ checks }: { checks: ValidationCheckSnapshot[] }
{humanizeName(check.check)}
-
- ✓
-
- {check.summary ? sentence(check.summary) : "Passed"}
+
))}
diff --git a/web/src/components/validation/ValidationStatusStrip.tsx b/web/src/components/validation/ValidationStatusStrip.tsx
index 625b6bb41..7e79aa406 100644
--- a/web/src/components/validation/ValidationStatusStrip.tsx
+++ b/web/src/components/validation/ValidationStatusStrip.tsx
@@ -1,4 +1,5 @@
import type { ValidateEnvelope } from "../../api/types";
+import { ValidationCheck } from "../StatusMark";
import {
CleanCheckList,
formatDuration,
@@ -29,10 +30,18 @@ export function ValidationStatusStrip({
const strip = (
-
- {mark(presentation.health)}
-
- {presentation.label}
+ {presentation.health === "current_clean" ? (
+
+
+
+ ) : (
+ <>
+
+ {mark(presentation.health)}
+
+ {presentation.label}
+ >
+ )}
{clean && snapshot && (
<>
·
diff --git a/web/src/components/widgets/DateWidget.test.tsx b/web/src/components/widgets/DateWidget.test.tsx
index 10bb9cbe9..617df492c 100644
--- a/web/src/components/widgets/DateWidget.test.tsx
+++ b/web/src/components/widgets/DateWidget.test.tsx
@@ -19,7 +19,7 @@ describe("DateWidget", () => {
it("renders an empty placeholder when missing", () => {
render( );
- expect(screen.getByText("Empty")).toBeInTheDocument();
+ expect(screen.getByText("—")).toBeInTheDocument();
});
it("renders a date input pre-populated with ISO form in edit mode", () => {
diff --git a/web/src/components/widgets/DateWidget.tsx b/web/src/components/widgets/DateWidget.tsx
index 45014bb07..d5a119604 100644
--- a/web/src/components/widgets/DateWidget.tsx
+++ b/web/src/components/widgets/DateWidget.tsx
@@ -41,7 +41,7 @@ const MS_PER_DAY = 1000 * 60 * 60 * 24;
/**
* Compact date display. A calendar date reads as words ("Oct 26, 2026"), the
* form collections use; the on-disk literal and the relative phrase ("3d ago")
- * are the tooltip. Edit mode swaps in an ISO text input.
+ * are the tooltip. Focus in edit mode reveals the ISO input and calendar.
*/
export function DateWidget({
value,
@@ -134,7 +134,7 @@ export function DateWidget({
if (!editing) {
if (!trimmed) {
- return Empty ;
+ return — ;
}
return (
@@ -157,6 +157,9 @@ export function DateWidget({
return (
+
+ {kind === "date" && isValidDate(draft) ? readableDate(draft) : draft || "—"}
+
svg {
display: none;
}
@@ -2944,11 +2941,11 @@ tr:focus-within .configured-view__boolean-editor .configured-view__cell-clear {
white-space: nowrap;
}
-/* An empty field says "Not set"; its edit affordance waits for hover or focus. */
+/* Empty values match the table; editors still appear on hover or focus. */
.view-record__fields .configured-view__relation-display:empty::before,
.view-record__fields dd:empty::before {
color: var(--text-faint);
- content: "Not set";
+ content: "—";
}
.view-record__reverse {
diff --git a/web/src/explorer-graph.css b/web/src/explorer-graph.css
new file mode 100644
index 000000000..cd66f4f3c
--- /dev/null
+++ b/web/src/explorer-graph.css
@@ -0,0 +1,403 @@
+:root {
+ --explorer-code: light-dark(#496a88, #90b2d3);
+ --explorer-link: light-dark(#16796f, #50b6aa);
+ --explorer-link-strong: light-dark(#00574f, #8be0d5);
+}
+/* ---- Graph canvas chrome (shared by every GraphView) ---- */
+
+/* Zoom: one stacked icon-button group, as on the Atlas canvas. */
+.graph-container .graph-zoom {
+ gap: 0;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--surface);
+ overflow: hidden;
+}
+
+.graph-container .zoom-btn {
+ width: 28px;
+ height: 28px;
+ border: 0;
+ border-radius: 0;
+ background: var(--surface);
+ backdrop-filter: none;
+}
+
+.graph-container .zoom-btn + .zoom-btn {
+ border-top: 1px solid var(--border);
+}
+
+/* The canvas is a column: the banner and the legend sit outside the plotted
+ area, so the camera fits nodes inside what is actually visible. */
+.graph-container {
+ display: flex;
+ flex-direction: column;
+}
+
+.graph-stage {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+}
+
+/* The banner: one 36px tinted band across the canvas top, with a mark and text. */
+.graph-container .graph-banner {
+ position: static;
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: var(--sp-2);
+ height: 36px;
+ padding: 0 var(--sp-4);
+ border: 0;
+ border-bottom: 1px solid color-mix(in srgb, var(--warning) 40%, transparent);
+ border-radius: 0;
+ font-size: var(--fs-sm);
+ font-weight: 500;
+ transform: none;
+}
+
+.graph-container .graph-banner svg {
+ flex: none;
+}
+
+/* Find and Display float at the stage's top right when the page has no header slot. */
+.graph-container .graph-tools {
+ top: var(--sp-3);
+ right: var(--sp-3);
+ flex-direction: row;
+ align-items: flex-start;
+ justify-content: flex-end;
+ gap: var(--sp-2);
+ width: auto;
+}
+
+.graph-find {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ width: 200px;
+}
+
+.graph-find .graph-search {
+ height: 30px;
+ margin: 0;
+ padding: 0 var(--sp-3);
+ font-size: var(--fs-base);
+}
+
+.graph-find .graph-search-meta {
+ margin: 0;
+ font-size: var(--fs-sm);
+}
+
+/* ---- Display menu: a header button with a popover of graph options ---- */
+
+.graph-display {
+ position: relative;
+}
+
+.graph-display__button {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--sp-1);
+ height: 30px;
+ padding: 0 var(--sp-3);
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--surface);
+ color: var(--text);
+ font-size: var(--fs-base);
+ font-weight: 500;
+ cursor: pointer;
+}
+
+.graph-display__button:hover,
+.graph-display__button[aria-expanded="true"] {
+ background: var(--bg-tint);
+}
+
+.graph-display__panel {
+ position: absolute;
+ z-index: 20;
+ top: calc(100% + 4px);
+ right: 0;
+ display: flex;
+ flex-direction: column;
+ width: 260px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--surface);
+ box-shadow: var(--shadow);
+}
+
+.graph-display__section {
+ display: flex;
+ flex-direction: column;
+ gap: var(--sp-1);
+ padding: var(--sp-3) var(--sp-4);
+}
+
+.graph-display__section + .graph-display__section {
+ border-top: 1px solid var(--border);
+}
+
+.graph-display .graph-toggle {
+ min-height: 28px;
+ margin: 0;
+ color: var(--text);
+ font-size: var(--fs-base);
+}
+
+.graph-display .cluster-item {
+ font-size: var(--fs-sm);
+}
+
+.explorer-bar__display {
+ display: flex;
+ flex: none;
+ margin-left: auto;
+}
+
+.explorer-header .explorer-bar__search {
+ margin-left: 0;
+}
+
+/* ---- Type legend: a band below the canvas, grouped by what the colors mean ---- */
+
+.graph-container .graph-type-legend {
+ position: static;
+ display: flex;
+ flex: none;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ gap: var(--sp-2) var(--sp-6);
+ max-height: none;
+ padding: var(--sp-3) var(--sp-5);
+ border: 0;
+ border-top: 1px solid var(--border);
+ border-radius: 0;
+ background: var(--surface);
+ box-shadow: none;
+ backdrop-filter: none;
+}
+
+.graph-type-legend__caption {
+ flex: 0 0 100%;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ text-align: left;
+}
+
+.graph-type-legend__group,
+.graph-type-legend--folders .graph-type-legend__all {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.graph-type-legend__group[data-group="typed"] {
+ flex: 1 1 100%;
+}
+
+.graph-type-legend__group .graph-type-legend__title,
+.graph-type-legend--folders .graph-type-legend__title {
+ margin: 0;
+ color: var(--label-color);
+ font: var(--label-font);
+}
+
+.graph-type-legend__group .graph-type-legend__list,
+.graph-type-legend--folders .graph-type-legend__list {
+ gap: 0 var(--sp-5);
+}
+
+.graph-type-legend__group .graph-type-legend__item,
+.graph-type-legend--folders .graph-type-legend__item {
+ grid-template-columns: 10px minmax(0, auto) auto;
+ gap: 6px;
+ min-height: 24px;
+ max-width: 240px;
+ color: var(--text);
+ font-size: var(--fs-sm);
+}
+
+.graph-type-legend__group .graph-type-legend__swatch,
+.graph-type-legend--folders .graph-type-legend__swatch {
+ width: 10px;
+ height: 10px;
+}
+
+/* Folders are the large filled nodes, in their most common type's color. */
+.graph-type-legend__group[data-group="folder"] .graph-type-legend__swatch {
+ width: 12px;
+ height: 12px;
+ background: var(--type-8);
+}
+
+/* A drawn link: the folder graph's neutral line, heavier where more links run. */
+.graph-type-legend__line {
+ display: inline-block;
+ width: 18px;
+ height: 0;
+ border-top: 2px solid var(--type-8);
+ border-radius: 1px;
+}
+
+.graph-type-legend__group .graph-type-legend__links {
+ grid-template-columns: 18px auto;
+ max-width: none;
+ margin-left: var(--sp-4);
+}
+
+.graph-type-legend__group .graph-type-legend__count,
+.graph-type-legend--folders .graph-type-legend__count {
+ color: var(--text-muted);
+ font-family: var(--font-sans);
+ font-size: var(--fs-sm);
+ font-variant-numeric: tabular-nums;
+}
+
+.graph-type-legend__note {
+ align-self: center;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+}
+
+/* The folder view's key: the colors its folders take, what size and lines
+ mean, and what the counts cover. Every type waits behind "All types". */
+.graph-container .graph-type-legend--folders {
+ flex-direction: column;
+ align-items: stretch;
+ gap: var(--sp-1);
+}
+
+.graph-type-legend__row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px var(--sp-5);
+}
+
+.graph-type-legend--folders .graph-type-legend__list {
+ flex: 0 1 auto;
+}
+
+.graph-type-legend__more {
+ display: inline-flex;
+ align-items: center;
+ height: 24px;
+ padding: 0 4px 0 0;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: none;
+ color: var(--link);
+ font: inherit;
+ font-size: var(--fs-sm);
+ cursor: pointer;
+}
+
+.graph-type-legend__more:is(:hover, :focus-visible) {
+ text-decoration: underline;
+ text-underline-offset: 2px;
+}
+
+.graph-type-legend__chevron {
+ display: inline-grid;
+ width: 24px;
+ height: 24px;
+ place-items: center;
+}
+
+.graph-type-legend__more[aria-expanded="true"] .graph-type-legend__chevron svg {
+ transform: rotate(180deg);
+}
+
+.graph-type-legend__key {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 24px;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+}
+
+/* A folder: an outlined disc, since its fill is one of the colors above. */
+.graph-type-legend__size {
+ box-sizing: border-box;
+ width: 12px;
+ height: 12px;
+ border: 1.5px solid var(--type-8);
+ border-radius: 50%;
+}
+
+.graph-type-legend--folders .graph-type-legend__caption {
+ flex: none;
+ margin: 0;
+ overflow: visible;
+ text-align: left;
+ white-space: normal;
+}
+
+.graph-type-legend--folders .graph-type-legend__all {
+ margin-top: var(--sp-1);
+ padding-top: var(--sp-2);
+ border-top: 1px solid var(--border);
+}
+
+.explorer-count-info {
+ border: 0;
+ background: none;
+ color: var(--text-muted);
+ cursor: help;
+ padding: 4px;
+}
+.graph-type-legend__keys .graph-type-legend__title {
+ min-width: 36px;
+}
+
+.graph-edge-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+}
+.graph-edge-legend__line {
+ width: 24px;
+ border-top: 1px solid var(--type-8);
+}
+.graph-edge-legend__line--folder-crosslink {
+ border-top: 3px solid var(--explorer-link);
+}
+.graph-edge-legend__line--folder-minor {
+ border-top: 1px dashed var(--type-8);
+}
+.graph-type-legend__key {
+ font-size: 13px;
+ font-weight: 500;
+}
+
+.explorer-focus .graph-type-legend__size {
+ border-radius: 3px;
+}
+.explorer-focus .graph-edge-legend__line--folder-containment {
+ border-top: 1.5px solid var(--type-8);
+}
+.explorer-focus .graph-edge-legend__line--explorer-documents {
+ border-top: 1.5px solid var(--explorer-link-strong);
+}
+.explorer-focus .graph-edge-legend__line--explorer-code {
+ border-top: 1.5px solid var(--explorer-code);
+}
+.explorer-focus .graph-edge-legend__line--explorer-tests {
+ border-top: 1.5px dashed var(--type-8);
+}
+
+.explorer-header__breadcrumb,
+.explorer-header__totals {
+ color: var(--text-muted);
+}
+.explorer-header__totals {
+ display: block;
+ font-size: 13px;
+}
diff --git a/web/src/explorer.css b/web/src/explorer.css
index 123705370..446c70b14 100644
--- a/web/src/explorer.css
+++ b/web/src/explorer.css
@@ -1,3 +1,4 @@
+@import "./explorer-graph.css";
/* ==========================================================================
Explorer workspace — vault tree sidebar · graph focus · file detail
The vault tree sits in the shared workbench sidebar (SPEC-0128); the inset
@@ -317,12 +318,12 @@
}
.explorer-pane__header h2 {
- font-family: var(--font-display);
- margin: 0 0 var(--sp-2);
- font-size: var(--fs-2xl);
- font-weight: 900;
- letter-spacing: -0.018em;
- line-height: 1.15;
+ font-family: var(--font-sans);
+ margin: 0 0 4px;
+ font-size: 16px;
+ font-weight: 600;
+ letter-spacing: normal;
+ line-height: 1.3;
color: var(--text);
word-break: break-word;
}
@@ -609,356 +610,32 @@
}
}
-/* ---- Graph canvas chrome (shared by every GraphView) ---- */
-
-/* Zoom: one stacked icon-button group, as on the Atlas canvas. */
-.graph-container .graph-zoom {
- gap: 0;
- border: 1px solid var(--border);
- border-radius: var(--r);
- background: var(--surface);
- overflow: hidden;
-}
-
-.graph-container .zoom-btn {
- width: 28px;
- height: 28px;
- border: 0;
- border-radius: 0;
- background: var(--surface);
- backdrop-filter: none;
-}
-
-.graph-container .zoom-btn + .zoom-btn {
- border-top: 1px solid var(--border);
-}
-
-/* The canvas is a column: the banner and the legend sit outside the plotted
- area, so the camera fits nodes inside what is actually visible. */
-.graph-container {
- display: flex;
- flex-direction: column;
-}
-
-.graph-stage {
- position: relative;
- flex: 1;
- min-height: 0;
-}
-
-/* The banner: one 36px tinted band across the canvas top, with a mark and text. */
-.graph-container .graph-banner {
- position: static;
- display: flex;
- flex: none;
- align-items: center;
- gap: var(--sp-2);
- height: 36px;
- padding: 0 var(--sp-4);
- border: 0;
- border-bottom: 1px solid color-mix(in srgb, var(--warning) 40%, transparent);
- border-radius: 0;
- font-size: var(--fs-sm);
- font-weight: 500;
- transform: none;
-}
-
-.graph-container .graph-banner svg {
- flex: none;
-}
-
-/* Find and Display float at the stage's top right when the page has no header slot. */
-.graph-container .graph-tools {
- top: var(--sp-3);
- right: var(--sp-3);
- flex-direction: row;
- align-items: flex-start;
- justify-content: flex-end;
- gap: var(--sp-2);
- width: auto;
-}
-
-.graph-find {
- display: flex;
- flex-direction: column;
- gap: 2px;
- width: 200px;
-}
-
-.graph-find .graph-search {
- height: 30px;
- margin: 0;
- padding: 0 var(--sp-3);
- font-size: var(--fs-base);
-}
-
-.graph-find .graph-search-meta {
- margin: 0;
- font-size: var(--fs-sm);
-}
-
-/* ---- Display menu: a header button with a popover of graph options ---- */
-
-.graph-display {
- position: relative;
-}
-
-.graph-display__button {
- display: inline-flex;
- align-items: center;
- gap: var(--sp-1);
- height: 30px;
- padding: 0 var(--sp-3);
- border: 1px solid var(--border);
- border-radius: var(--r);
- background: var(--surface);
- color: var(--text);
- font-size: var(--fs-base);
+.explorer-pane__section h3 {
+ font-family: var(--font-sans);
+ font-size: 13px;
font-weight: 500;
- cursor: pointer;
-}
-
-.graph-display__button:hover,
-.graph-display__button[aria-expanded="true"] {
- background: var(--bg-tint);
+ text-transform: none;
+ letter-spacing: normal;
}
-
-.graph-display__panel {
- position: absolute;
- z-index: 20;
- top: calc(100% + 4px);
- right: 0;
- display: flex;
- flex-direction: column;
- width: 260px;
- border: 1px solid var(--border);
- border-radius: var(--r-md);
- background: var(--surface);
- box-shadow: var(--shadow);
-}
-
-.graph-display__section {
- display: flex;
- flex-direction: column;
- gap: var(--sp-1);
- padding: var(--sp-3) var(--sp-4);
-}
-
-.graph-display__section + .graph-display__section {
- border-top: 1px solid var(--border);
-}
-
-.graph-display .graph-toggle {
- min-height: 28px;
- margin: 0;
- color: var(--text);
- font-size: var(--fs-base);
-}
-
-.graph-display .cluster-item {
- font-size: var(--fs-sm);
-}
-
-.explorer-bar__display {
- display: flex;
- flex: none;
- margin-left: auto;
-}
-
-.explorer-header .explorer-bar__search {
- margin-left: 0;
-}
-
-/* ---- Type legend: a band below the canvas, grouped by what the colors mean ---- */
-
-.graph-container .graph-type-legend {
- position: static;
- display: flex;
- flex: none;
- flex-wrap: wrap;
- align-items: flex-start;
- gap: var(--sp-2) var(--sp-6);
- max-height: none;
- padding: var(--sp-3) var(--sp-5);
- border: 0;
- border-top: 1px solid var(--border);
- border-radius: 0;
- background: var(--surface);
- box-shadow: none;
- backdrop-filter: none;
-}
-
-.graph-type-legend__caption {
- flex: 0 0 100%;
- color: var(--text-muted);
- font-size: var(--fs-sm);
- text-align: left;
-}
-
-.graph-type-legend__group,
-.graph-type-legend--folders .graph-type-legend__all {
- display: flex;
- flex-direction: column;
- gap: 2px;
- min-width: 0;
-}
-
-.graph-type-legend__group[data-group="typed"] {
- flex: 1 1 100%;
-}
-
-.graph-type-legend__group .graph-type-legend__title,
-.graph-type-legend--folders .graph-type-legend__title {
- margin: 0;
- color: var(--label-color);
- font: var(--label-font);
-}
-
-.graph-type-legend__group .graph-type-legend__list,
-.graph-type-legend--folders .graph-type-legend__list {
- gap: 0 var(--sp-5);
-}
-
-.graph-type-legend__group .graph-type-legend__item,
-.graph-type-legend--folders .graph-type-legend__item {
- grid-template-columns: 10px minmax(0, auto) auto;
- gap: 6px;
- min-height: 24px;
- max-width: 240px;
- color: var(--text);
- font-size: var(--fs-sm);
-}
-
-.graph-type-legend__group .graph-type-legend__swatch,
-.graph-type-legend--folders .graph-type-legend__swatch {
- width: 10px;
- height: 10px;
-}
-
-/* Folders are the large filled nodes, in their most common type's color. */
-.graph-type-legend__group[data-group="folder"] .graph-type-legend__swatch {
- width: 12px;
- height: 12px;
- background: var(--type-8);
-}
-
-/* A drawn link: the folder graph's neutral line, heavier where more links run. */
-.graph-type-legend__line {
- display: inline-block;
- width: 18px;
- height: 0;
- border-top: 2px solid var(--type-8);
- border-radius: 1px;
-}
-
-.graph-type-legend__group .graph-type-legend__links {
- grid-template-columns: 18px auto;
- max-width: none;
- margin-left: var(--sp-4);
-}
-
-.graph-type-legend__group .graph-type-legend__count,
-.graph-type-legend--folders .graph-type-legend__count {
- color: var(--text-muted);
+.explorer-pane__section h3 .num {
font-family: var(--font-sans);
- font-size: var(--fs-sm);
- font-variant-numeric: tabular-nums;
-}
-
-.graph-type-legend__note {
- align-self: center;
+ font-size: 13px;
color: var(--text-muted);
- font-size: var(--fs-sm);
-}
-
-/* The folder view's key: the colors its folders take, what size and lines
- mean, and what the counts cover. Every type waits behind "All types". */
-.graph-container .graph-type-legend--folders {
- flex-direction: column;
- align-items: stretch;
- gap: var(--sp-1);
-}
-
-.graph-type-legend__row {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 4px var(--sp-5);
-}
-
-.graph-type-legend--folders .graph-type-legend__list {
- flex: 0 1 auto;
-}
-
-.graph-type-legend__more {
- display: inline-flex;
- align-items: center;
- height: 24px;
- padding: 0 4px 0 0;
- border: 0;
- border-radius: var(--r-sm);
- background: none;
- color: var(--link);
- font: inherit;
- font-size: var(--fs-sm);
- cursor: pointer;
-}
-
-.graph-type-legend__more:is(:hover, :focus-visible) {
- text-decoration: underline;
- text-underline-offset: 2px;
-}
-
-.graph-type-legend__chevron {
- display: inline-grid;
- width: 24px;
- height: 24px;
- place-items: center;
}
-
-.graph-type-legend__more[aria-expanded="true"] .graph-type-legend__chevron svg {
- transform: rotate(180deg);
+.explorer-pane__link-text {
+ flex: 1;
+ min-width: 0;
+ display: grid;
+ gap: 3px;
}
-
-.graph-type-legend__key {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- min-height: 24px;
+.explorer-pane__link-path {
+ font: 12px var(--font-mono);
color: var(--text-muted);
- font-size: var(--fs-sm);
-}
-
-/* A folder: an outlined disc, since its fill is one of the colors above. */
-.graph-type-legend__size {
- box-sizing: border-box;
- width: 12px;
- height: 12px;
- border: 1.5px solid var(--type-8);
- border-radius: 50%;
-}
-
-.graph-type-legend--folders .graph-type-legend__caption {
- flex: none;
- margin: 0;
- overflow: visible;
- text-align: left;
- white-space: normal;
-}
-
-.graph-type-legend--folders .graph-type-legend__all {
- margin-top: var(--sp-1);
- padding-top: var(--sp-2);
- border-top: 1px solid var(--border);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-
-.explorer-count-info {
- border: 0;
- background: none;
+.explorer-pane__multiplicity {
color: var(--text-muted);
- cursor: help;
- padding: 4px;
-}
-.graph-type-legend__keys .graph-type-legend__title {
- min-width: 36px;
+ font-size: 13px;
}
diff --git a/web/src/finder.css b/web/src/finder.css
index 39afa330a..624f8219c 100644
--- a/web/src/finder.css
+++ b/web/src/finder.css
@@ -121,7 +121,7 @@
aligns. */
.finder__row {
display: grid;
- grid-template-columns: 16px minmax(0, 1fr) 112px;
+ grid-template-columns: 16px minmax(0, 1fr) auto;
grid-template-rows: auto auto;
column-gap: 12px;
align-items: center;
@@ -151,7 +151,7 @@
/* The title takes the whole first line; the path and the type label share
the second, so a long title is never cut short for a short path. */
.finder__title {
- grid-column: 2 / span 2;
+ grid-column: 2;
overflow: hidden;
font-weight: 500;
white-space: nowrap;
@@ -159,7 +159,7 @@
}
.finder__detail {
- grid-row: 2;
+ grid-row: 1;
grid-column: 3;
overflow: hidden;
color: var(--text-muted);
@@ -173,7 +173,7 @@
.finder__path {
display: flex;
grid-row: 2;
- grid-column: 2;
+ grid-column: 2 / span 2;
min-width: 0;
color: var(--text-muted);
font: var(--fs-xs) / 1.4 var(--font-mono);
diff --git a/web/src/html-note.css b/web/src/html-note.css
new file mode 100644
index 000000000..cc8652a3b
--- /dev/null
+++ b/web/src/html-note.css
@@ -0,0 +1,329 @@
+/* HTML notes: viewer, frame, refresh status, and the HTML note head.
+ Moved verbatim from notes-shell.css. */
+
+.ontology-markdown--html {
+ width: 100%;
+ max-width: none;
+}
+
+.ontology-pane__main--html {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.ontology-pane__main--html > * {
+ flex-shrink: 0;
+}
+
+.ontology-pane__main--html > .ontology-markdown--html {
+ display: flex;
+ flex: 1;
+ /* Cancel the pane padding so the viewer runs edge to edge and reaches the pane bottom. */
+ width: auto;
+ margin: 0 calc(-1 * var(--sp-6)) calc(-1 * var(--sp-6));
+ min-height: min(70vh, 640px);
+ max-width: none;
+}
+
+/* "Metadata" is the shared ghost disclosure: label, then the chevron. */
+.ontology-properties__html-summary {
+ gap: 2px;
+ padding: 0 4px 0 8px;
+ list-style: none;
+}
+
+.ontology-properties__html-summary::-webkit-details-marker {
+ display: none;
+}
+
+.ontology-properties__html-summary:hover {
+ color: var(--text);
+}
+
+.ontology-properties__html-summary:focus-visible {
+ outline: 2px solid var(--focus-ring);
+ outline-offset: 1px;
+}
+
+.html-note-viewer {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+ background: var(--surface-alt);
+}
+
+.html-note-viewer.is-hidden {
+ display: none;
+}
+
+/* Chrome-free note page (`?bare=1`): the viewer is the whole window. */
+.bare-html-note {
+ position: fixed;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ background: var(--surface-alt);
+}
+
+.html-note-viewer__toolbar,
+.html-note-viewer__action {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-3);
+ min-height: 32px;
+ padding: 0 var(--sp-3);
+ border-bottom: 1px solid var(--border);
+ color: var(--text-muted);
+ font-size: var(--fs-xs);
+}
+
+.html-note-viewer__format {
+ color: var(--text);
+ font-family: var(--font-mono);
+ font-weight: 600;
+}
+
+.html-note-viewer__state {
+ color: var(--text-faint);
+}
+
+.html-note-viewer__spacer {
+ flex: 1;
+}
+
+/* Viewer actions are neutral ghost buttons; red stays for risk. */
+.html-note-viewer__ghost,
+.html-note-viewer__action button {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ height: 26px;
+ padding: 0 var(--sp-2);
+ border: 0;
+ border-radius: var(--r-md);
+ background: transparent;
+ color: var(--text-muted);
+ font: 500 var(--fs-sm) / 1 var(--font-sans);
+ text-decoration: none;
+ white-space: nowrap;
+ cursor: pointer;
+}
+
+.html-note-viewer__ghost svg {
+ width: 14px;
+ height: 14px;
+}
+
+a.html-note-viewer__ghost svg {
+ margin-left: 5px;
+}
+
+button.html-note-viewer__ghost svg {
+ margin: 0 5px 0 0;
+}
+
+.html-note-viewer__ghost:hover,
+.html-note-viewer__action button:hover {
+ background: var(--bg-tint);
+ color: var(--text);
+}
+
+.html-note-viewer__problem {
+ padding: var(--sp-2) var(--sp-3);
+ border-bottom: 1px solid var(--border);
+ background: var(--accent-soft);
+ color: var(--accent-ink);
+ font-size: var(--fs-xs);
+}
+
+.html-note-viewer__action {
+ justify-content: flex-end;
+ background: var(--surface);
+}
+
+.html-note-viewer__action > span {
+ min-width: 0;
+ margin-right: auto;
+ overflow: hidden;
+ color: var(--text);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.html-note-viewer__frame {
+ flex: 1;
+ width: 100%;
+ height: 0;
+ min-height: 0;
+ border: 0;
+ background: var(--surface);
+}
+
+@media (max-width: 700px) {
+ .html-note-viewer__state {
+ display: none;
+ }
+}
+
+.ontology-pane__refresh-status {
+ position: sticky;
+ z-index: 2;
+ top: 0;
+ padding: 3px var(--sp-4);
+ border-bottom: 1px solid var(--border);
+ background: var(--surface-alt);
+ color: var(--text-faint);
+ font-size: var(--fs-xs);
+}
+
+/* The refreshing pill floats over the content so a refetch does not shift it. */
+.ontology-pane__refresh-status:not(.is-error) {
+ width: max-content;
+ height: 22px;
+ margin: 0 0 -22px auto;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ line-height: 14px;
+}
+
+.ontology-pane__refresh-status.is-error {
+ color: var(--accent-ink);
+ background: var(--accent-soft);
+}
+
+/* ---- HTML note head ----
+ With a preview showing, the host header lives in the 40px control row:
+ the type, a 14/600 title, its identity, the metadata disclosure, then the
+ presentation switch and the viewer's Refresh and Open. The authored page
+ starts right below and carries its own heading. */
+.notes-shell .ontology-pane__controls:has(> .ontology-pane__html-head) {
+ overflow: visible;
+ border-bottom: 1px solid var(--border);
+ background: var(--surface);
+}
+
+.notes-shell .ontology-pane__controls > .ontology-pane__html-head {
+ display: flex;
+ flex: 0 1 auto;
+ align-items: center;
+ gap: var(--sp-4);
+ min-width: 0;
+ white-space: nowrap;
+}
+
+.notes-shell .ontology-pane__html-head > .ontology-identity {
+ flex: 0 1 auto;
+ flex-flow: row nowrap;
+ align-items: center;
+ gap: var(--sp-3);
+ min-width: 0;
+ padding: 0;
+ background: transparent;
+}
+
+/* The tab and the authored page already carry the title, and Metadata lists
+ it in full, so the row keeps it for assistive tech only. */
+.notes-shell .ontology-pane__html-head .ontology-identity__title {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+}
+
+.notes-shell .ontology-pane__html-head .ontology-identity__row {
+ flex: 0 1 auto;
+ flex-wrap: nowrap;
+ min-width: 0;
+}
+
+/* With the title hidden, the short ID names the document beside its type
+ and status. It is the one part that gives way, before the actions do. */
+.notes-shell .ontology-pane__html-head .ontology-identity__slot--id {
+ flex: 0 1 auto;
+ min-width: 0;
+ overflow: hidden;
+}
+
+.notes-shell .ontology-pane__html-head .ontology-identity__slot--id * {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.notes-shell .ontology-pane__html-head .ontology-identity__flex {
+ display: none;
+}
+
+/* The metadata opens as a panel over the page instead of pushing it down. */
+.notes-shell .ontology-pane__html-head > .ontology-properties--html-root {
+ position: relative;
+ flex: none;
+ max-width: none;
+ margin: 0;
+ padding: 0;
+ border: 0;
+}
+
+/* The ghost button's padding bleeds into the row gap, so the ID keeps its
+ room. */
+.notes-shell .ontology-pane__html-head .ontology-properties__html-summary {
+ margin: 0 0 0 -8px;
+ color: var(--text-muted);
+}
+
+.notes-shell .ontology-pane__html-head .ontology-properties__html-body {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ z-index: 20;
+ width: min(520px, 80vw);
+ max-height: min(70vh, 640px);
+ padding: var(--sp-3) var(--sp-4);
+ overflow: auto;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-lg);
+ background: var(--surface);
+ box-shadow: var(--shadow);
+}
+
+.notes-shell
+ .ontology-pane__html-head
+ .ontology-properties__html-body
+ :is(input, select, textarea) {
+ max-width: 100%;
+}
+
+.notes-shell .ontology-pane__html-actions {
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: var(--sp-1);
+ margin-right: calc(-1 * var(--sp-2));
+ color: var(--text-faint);
+ font-size: var(--fs-sm);
+}
+
+.notes-shell .ontology-pane__html-actions:empty {
+ display: none;
+}
+
+/* The page starts directly under the control row. */
+.notes-shell .ontology-pane__main--html {
+ padding-top: 0;
+}
+
+.notes-shell .ontology-pane__main--html > .ontology-markdown--html {
+ margin-top: 0;
+}
+
+/* The authored page carries its own status. */
+.notes-shell .ontology-pane__html-head .ontology-identity__slot--status {
+ display: none;
+}
diff --git a/web/src/lib/graphStyle.test.ts b/web/src/lib/graphStyle.test.ts
index 9b06a7371..2778570bf 100644
--- a/web/src/lib/graphStyle.test.ts
+++ b/web/src/lib/graphStyle.test.ts
@@ -63,7 +63,7 @@ function edgeAttrs(overrides: Partial = {}): SigmaEdgeAttrs {
}
describe("graph style reducers", () => {
- it("keeps containment visible and reveals counted cross-folder links only on hover", () => {
+ it("leaves containment to the folder-link layer and reveals counted cross-folder links only on hover", () => {
const input = {
source: "folder:docs",
target: "folder:pkg",
@@ -79,9 +79,23 @@ describe("graph style reducers", () => {
expect(
computeEdgeStyle({ ...input, attrs, state: reducerState({ hoverNodeID: "folder:docs" }) }),
).toMatchObject({ hidden: false, label: "12 links" });
+
+ for (const semanticMatches of [
+ new Set(["folder:docs"]),
+ new Set(["folder:docs", "folder:pkg"]),
+ ]) {
+ expect(
+ computeEdgeStyle({
+ ...input,
+ attrs,
+ state: reducerState({ searchActive: true, semanticMatches }),
+ }),
+ ).toMatchObject({ hidden: true, label: "" });
+ }
+
expect(
computeEdgeStyle({ ...input, attrs: edgeAttrs({ kind: "folder-containment" }) }),
- ).toMatchObject({ hidden: false, label: "" });
+ ).toMatchObject({ hidden: true, label: "" }); // sigmaFolderLinks draws it, clipped to node edges
});
it("hides non-matching nodes when search-only filter is active", () => {
diff --git a/web/src/lib/graphStyle.ts b/web/src/lib/graphStyle.ts
index 18a424852..f2af8e600 100644
--- a/web/src/lib/graphStyle.ts
+++ b/web/src/lib/graphStyle.ts
@@ -1,9 +1,17 @@
+export { computeEdgeStyle } from "../components/sigmaEdgeStyle";
+
import type { GraphNode, NodeRef } from "../api/types";
export type SigmaNodeAttrs = {
label: string;
kind: string;
center?: boolean;
+ labelDetail?: string;
+ searchMatchCount?: number;
+ aggregate?: boolean;
+ fixed?: boolean;
+ explorerLabels?: boolean;
+ priority?: number;
path?: string;
notePath?: string;
nodeId?: string;
@@ -101,7 +109,7 @@ const NODE_ALPHA = {
deemphHover: { normal: 0.65, zoomed: 0.42 },
};
-const TYPE_HIGHLIGHT_ALPHA = {
+export const TYPE_HIGHLIGHT_ALPHA = {
node: 0.24,
edge: 0.28,
};
@@ -118,11 +126,11 @@ const DESAT = {
hover: { normal: 0.55, zoomed: 0.8 },
};
-function clamp(value: number, min: number, max: number) {
+export function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
-function lerp(a: number, b: number, t: number) {
+export function lerp(a: number, b: number, t: number) {
return a + (b - a) * t;
}
@@ -229,7 +237,7 @@ function colorWithAlpha(color: string, alpha: number) {
// Sigma blends with ONE, ONE_MINUS_SRC_ALPHA, so translucent colors must carry
// their alpha in RGB as well as in the alpha channel.
-function colorWithPremultipliedAlpha(color: string, alpha: number) {
+export function colorWithPremultipliedAlpha(color: string, alpha: number) {
const parsed = parseHexColor(color);
if (!parsed) {
@@ -239,7 +247,10 @@ function colorWithPremultipliedAlpha(color: string, alpha: number) {
return `rgba(${Math.round(parsed.r * alpha)}, ${Math.round(parsed.g * alpha)}, ${Math.round(parsed.b * alpha)}, ${alpha})`;
}
-function isTypeHighlighted(resolvedType: string | undefined, highlightTypes: ReadonlySet) {
+export function isTypeHighlighted(
+ resolvedType: string | undefined,
+ highlightTypes: ReadonlySet,
+) {
const typeName = resolvedType?.trim();
return Boolean(typeName && highlightTypes.has(typeName));
@@ -348,7 +359,7 @@ export function computeNodeStyle(input: NodeReducerInput): NodeReducerOutput {
alpha = Math.max(alpha, lerp(NODE_ALPHA.focus.normal, NODE_ALPHA.focus.zoomed, lod));
}
- let color = colorWithAlpha(mixedColor, alpha);
+ let color = attrs.explorerLabels ? baseColor : colorWithAlpha(mixedColor, alpha);
let label = attrs.label;
if (state.showProblems && attrs.problemCount) {
@@ -361,7 +372,7 @@ export function computeNodeStyle(input: NodeReducerInput): NodeReducerOutput {
const deemphAlpha = lerp(NODE_ALPHA.deemphHover.normal, NODE_ALPHA.deemphHover.zoomed, lod);
color = colorWithAlpha(deemphColor, Math.min(alpha, deemphAlpha));
label = "";
- } else if (hasHighlighting && !isFocus) {
+ } else if (hasHighlighting && !isFocus && attrs.searchMatchCount === undefined) {
const desatAmount = lerp(DESAT.normal.normal, DESAT.normal.zoomed, lod);
const deemphColor = mixColors(baseColor, neutral, desatAmount);
const deemphAlpha = lerp(NODE_ALPHA.deemph.normal, NODE_ALPHA.deemph.zoomed, lod);
@@ -396,6 +407,8 @@ export function computeNodeStyle(input: NodeReducerInput): NodeReducerOutput {
label = "";
}
+ if (attrs.fixed && attrs.kind === "module") label = attrs.label;
+
const dimmedByType = hasTypeHighlighting && !typeMatch && !isFocus && !inHoverCommunity;
const cameraSizeRatio = Math.sqrt(Math.max(state.cameraRatio, 0.0001));
@@ -441,115 +454,3 @@ export type EdgeReducerOutput = {
size: number;
label: string;
};
-
-export function computeEdgeStyle(input: EdgeReducerInput): EdgeReducerOutput {
- const { source, target, attrs, sourceAttrs, targetAttrs, state, lod } = input;
- const hasTypeHighlighting = state.highlightTypes.size > 0;
-
- const sourceTypeMatch =
- !hasTypeHighlighting || isTypeHighlighted(sourceAttrs.resolvedType, state.highlightTypes);
-
- const targetTypeMatch =
- !hasTypeHighlighting || isTypeHighlighted(targetAttrs.resolvedType, state.highlightTypes);
-
- const hasGraphMatches = state.graphMatches.size > 0;
-
- const filterActive =
- (state.searchActive && state.searchOnlyMatches) ||
- (state.graphFilter && hasGraphMatches) ||
- state.activeCommunity !== null;
-
- const sSemantic = state.semanticMatches.has(source);
- const tSemantic = state.semanticMatches.has(target);
- const sGraph = hasGraphMatches && state.graphMatches.has(source);
- const tGraph = hasGraphMatches && state.graphMatches.has(target);
- const sCluster = state.activeCommunity ? sourceAttrs.community === state.activeCommunity : true;
- const tCluster = state.activeCommunity ? targetAttrs.community === state.activeCommunity : true;
-
- if (filterActive) {
- let sAllowed = true;
- let tAllowed = true;
-
- if (state.searchActive && state.searchOnlyMatches) {
- sAllowed = sAllowed && sSemantic;
- tAllowed = tAllowed && tSemantic;
- }
-
- if (state.graphFilter && hasGraphMatches) {
- sAllowed = sAllowed && sGraph;
- tAllowed = tAllowed && tGraph;
- }
-
- if (state.activeCommunity) {
- sAllowed = sAllowed && sCluster;
- tAllowed = tAllowed && tCluster;
- }
-
- if (!sAllowed || !tAllowed) {
- return { hidden: true, color: state.colors.edgeFaint, size: 0.5, label: "" };
- }
- }
-
- const isHoverEdge =
- state.hoverNodeID !== null && (source === state.hoverNodeID || target === state.hoverNodeID);
-
- const isFocus =
- sSemantic ||
- tSemantic ||
- sGraph ||
- tGraph ||
- (state.activeCommunity && (sCluster || tCluster)) ||
- isHoverEdge;
-
- const hasHighlighting =
- (state.searchActive && state.semanticMatches.size > 0) ||
- hasGraphMatches ||
- state.activeCommunity !== null;
-
- const sizeScale = lerp(1.15, 0.82, lod);
- const size = Math.max(0.35, attrs.size * sizeScale);
- // Edge names show only for what the reader is looking at: a hovered node's or a match's links.
- const labelVisible = state.showEdgeLabels && Boolean(isFocus);
- let label = labelVisible ? attrs.label : "";
-
- let color: string;
-
- const { edgeFaint, edgeLight, edgeStrong } = state.colors;
-
- if (isFocus || isHoverEdge) {
- color = edgeStrong;
- } else if (hasHighlighting || state.hoverNodeID !== null) {
- color = edgeFaint;
- } else {
- color = lod > 0.3 ? edgeFaint : edgeLight;
- }
-
- if (hasTypeHighlighting && (!sourceTypeMatch || !targetTypeMatch) && !isFocus) {
- color = colorWithPremultipliedAlpha(edgeFaint, TYPE_HIGHLIGHT_ALPHA.edge);
- label = "";
- }
-
- // The folder overview draws few links, so each is essential: opaque in the
- // 3:1 neutral at 1–2px, fading only when the reader points at another folder.
- // Minor folder links (folderGraph's MINOR_FOLDER_LINK) wait for a hover on one of their folders.
- if (attrs.kind === "folder-minor" && !isFocus)
- return { hidden: true, color: edgeFaint, size: 0.5, label: "" };
-
- if (attrs.kind === "folder-containment" || attrs.kind === "folder-minor") {
- const faded = (hasHighlighting || state.hoverNodeID !== null) && !isFocus;
-
- return {
- hidden: false,
- color: faded ? edgeFaint : state.colors.neutral,
- size: clamp(attrs.size * 0.5, 1, 2),
- label: attrs.kind === "folder-containment" ? "" : label,
- };
- }
-
- return {
- hidden: false,
- color,
- size,
- label,
- };
-}
diff --git a/web/src/lib/themeColors.ts b/web/src/lib/themeColors.ts
index 3cdda7ef5..94489a957 100644
--- a/web/src/lib/themeColors.ts
+++ b/web/src/lib/themeColors.ts
@@ -22,6 +22,7 @@ function computed(token: string): string {
probe = document.createElement("span");
probe.setAttribute("aria-hidden", "true");
probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden";
+ probe.style.setProperty("transition", "none", "important");
document.body.append(probe);
}
diff --git a/web/src/lib/typeAccent.test.ts b/web/src/lib/typeAccent.test.ts
index 53a82a4c4..e5aabd50a 100644
--- a/web/src/lib/typeAccent.test.ts
+++ b/web/src/lib/typeAccent.test.ts
@@ -31,10 +31,21 @@ describe("typeAccent", () => {
expect(typeAccentIndex("T01")).not.toBe(typeAccentIndex("T00"));
});
- it("draws interfaces in the neutral and falls back to a hash for unknown names", () => {
+ it("shares an interface colour with its most represented implementor", () => {
+ appQueryClient.setQueryData(queryKeys.ontology.summary(), {
+ types: [
+ { name: "EffortNote", count: 20 },
+ { name: "EffortWorkspace", count: 2 },
+ ],
+ interfaces: [{ name: "Effort", implementors: ["EffortWorkspace", "EffortNote"] }],
+ });
+ expect(typeAccentColor("Effort")).toBe(typeAccentColor("EffortNote"));
+ });
+
+ it("uses vivid colours for interfaces and falls back to a hash for unknown names", () => {
setSummary([{ name: "Spec", count: 2 }], ["SpecLike"]);
- expect(typeAccentColor("SpecLike")).toBe("var(--type-8)");
+ expect(typeAccentColor("SpecLike")).not.toBe("var(--type-8)");
expect(typeAccentColor("Unlisted")).toMatch(/^var\(--type-(?:[1-79]|1[0-3])\)$/);
});
});
diff --git a/web/src/lib/typeAccent.ts b/web/src/lib/typeAccent.ts
index 7a41befe7..c0b4a1150 100644
--- a/web/src/lib/typeAccent.ts
+++ b/web/src/lib/typeAccent.ts
@@ -1,3 +1,4 @@
+import { useSyncExternalStore } from "react";
import { useOntologySummaryQuery } from "../components/useNotesQueries";
import { appQueryClient } from "../api/queryClient";
import { queryKeys } from "../api/queryKeys";
@@ -16,7 +17,7 @@ export function typeAccentIndex(name: string): number {
return typeSlot(summary(), name);
}
-/** A type's color as a CSS value. It marks dots, borders, and edges, never text. Interfaces take the neutral. */
+/** A type's color as a CSS value. It marks dots, borders, and edges, never text. Interfaces share their most represented implementor’s token. */
export function typeAccentColor(name: string): string {
return typeColor(summary(), name);
}
@@ -28,3 +29,12 @@ export function typeAccentColor(name: string): string {
export function useTypeAccentKey() {
return useOntologySummaryQuery().data;
}
+
+/** Observe the shared palette without requiring a query provider in leaf components. */
+export function useTypePalette() {
+ return useSyncExternalStore(appQueryClient.getQueryCache().subscribe, summary, summary);
+}
+
+export function useTypeAccentColor(name: string): string {
+ return typeColor(useTypePalette(), name);
+}
diff --git a/web/src/lib/typePalette.ts b/web/src/lib/typePalette.ts
index 034595a0d..43d31a3e9 100644
--- a/web/src/lib/typePalette.ts
+++ b/web/src/lib/typePalette.ts
@@ -7,17 +7,17 @@ import type { OntologySummaryResponse } from "../api/types";
*/
const TYPE_SLOTS = [1, 6, 7, 5, 2, 3, 4, 11, 10, 12, 13, 9];
-/** The neutral slot: interfaces, code, and untyped notes. */
+/** The neutral slot for untyped notes. */
export const NEUTRAL_TYPE_COLOR = "var(--type-8)";
/** The parts of the ontology summary that type colors follow. */
export type TypeSummaryInput = Pick | undefined;
-type TypeOrder = { types: Map; interfaces: Set };
+type TypeOrder = { types: Map; interfaces: Map };
const orders = new WeakMap();
-const EMPTY: TypeOrder = { types: new Map(), interfaces: new Set() };
+const EMPTY: TypeOrder = { types: new Map(), interfaces: new Map() };
/**
* Concrete types in name order with the types that have records first. Name
@@ -39,7 +39,15 @@ function typeOrder(summary: TypeSummaryInput): TypeOrder {
order = {
types: new Map(names.map((name, index) => [name, index])),
- interfaces: new Set((summary.interfaces ?? []).map((item) => item.name)),
+ interfaces: new Map(
+ (summary.interfaces ?? []).map((item) => {
+ const representative = types
+ .filter((type) => item.implementors.includes(type.name))
+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name))[0];
+
+ return [item.name, representative?.name ?? item.name];
+ }),
+ ),
};
orders.set(summary, order);
@@ -56,7 +64,9 @@ function hashName(name: string) {
/** A type's palette slot, the same on every surface; a name the ontology does not list falls back to a hash. */
export function typeSlot(summary: TypeSummaryInput, name: string): number {
- const position = typeOrder(summary).types.get(name) ?? hashName(name);
+ const order = typeOrder(summary);
+ const canonical = order.interfaces.get(name) ?? name;
+ const position = order.types.get(canonical) ?? hashName(canonical);
const lap = Math.floor(position / TYPE_SLOTS.length);
// Past twelve types hues repeat, starting halfway down the list so the
@@ -64,9 +74,7 @@ export function typeSlot(summary: TypeSummaryInput, name: string): number {
return TYPE_SLOTS[(position + lap * (TYPE_SLOTS.length / 2)) % TYPE_SLOTS.length];
}
-/** A type's color as a CSS value. It marks dots, borders, and edges, never text. Interfaces take the neutral. */
+/** A type's color as a CSS value. It marks dots, borders, and edges, never text. Interfaces share their most represented implementor’s token. */
export function typeColor(summary: TypeSummaryInput, name: string): string {
- if (typeOrder(summary).interfaces.has(name)) return NEUTRAL_TYPE_COLOR;
-
- return `var(--type-${typeSlot(summary, name)})`;
+ return name ? `var(--type-${typeSlot(summary, name)})` : NEUTRAL_TYPE_COLOR;
}
diff --git a/web/src/main.tsx b/web/src/main.tsx
index c4771cbba..1120bc16f 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -16,6 +16,10 @@ import "./configured-view.css";
import "./markdown-editor.css";
import "./workbench.css";
import "./notes-shell.css";
+import "./note-reader.css";
+import "./html-note.css";
+import "./search.css";
+import "./validation.css";
import "./finder.css";
import "./components/notePreview/notePreview.css";
diff --git a/web/src/markdown-editor.css b/web/src/markdown-editor.css
index 1ed1a26d9..31e34219d 100644
--- a/web/src/markdown-editor.css
+++ b/web/src/markdown-editor.css
@@ -13,34 +13,16 @@
margin: 0;
}
-/* In edit mode each editable section carries a pencil in the left gutter:
- faint at rest, muted on hover, full ink while its editor has focus. It
- marks what can be edited without boxing every section. */
-.notes-shell .body-narrative--editor:not(.body-narrative--meta) {
+/* Section marks align to the heading row, in the same gutter as properties. */
+.notes-shell :is(.body-section__title, .body-disclosure__heading):has(> .note-property-pencil) {
position: relative;
}
-.notes-shell .body-narrative--editor:not(.body-narrative--meta)::before {
- content: "";
+.notes-shell :is(.body-section__title, .body-disclosure__heading) > .note-property-pencil {
position: absolute;
- top: calc(var(--editor-bleed-block) - 2px);
- left: -28px;
- width: 16px;
- height: 16px;
- background: currentcolor;
- color: var(--text-faint);
- pointer-events: none;
- mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.4' stroke-linejoin='round'%3E%3Cpath d='M11.5 1.5l3 3L5 14H2v-3L11.5 1.5z'/%3E%3C/svg%3E")
- center / 16px 16px no-repeat;
- transition: color 120ms var(--ease);
-}
-
-.notes-shell .body-narrative--editor:not(.body-narrative--meta):hover::before {
- color: var(--text-muted);
-}
-
-.notes-shell .body-narrative--editor:not(.body-narrative--meta):focus-within::before {
- color: var(--text);
+ right: 100%;
+ top: 50%;
+ transform: translateY(-50%);
}
/* The lead metadata line keeps its quiet read-mode type while editing. */
diff --git a/web/src/note-info.css b/web/src/note-info.css
new file mode 100644
index 000000000..a05175f9f
--- /dev/null
+++ b/web/src/note-info.css
@@ -0,0 +1,241 @@
+/* Info sections outrank their muted type groups and 14px links. */
+.notes-right-rail .ontology-sidebar-context__group h3 {
+ margin-bottom: var(--section-gap);
+ font: var(--section-font);
+ color: var(--section-color);
+}
+
+.notes-right-rail .rail-bucket + .rail-bucket {
+ margin-top: var(--sp-3);
+}
+
+.notes-right-rail
+ :is(.rail-row__dir--incoming, .rail-row__dir--both, .rail-bucket__dir, .rail-direction__dir) {
+ color: var(--text-faint);
+}
+
+/* Type metadata consistently starts below its linked title. */
+.notes-right-rail .rail-row:has(> :is(.rail-row__type, .rail-row__path)) {
+ flex-wrap: wrap;
+ row-gap: 0;
+}
+
+.notes-right-rail .rail-row:has(> .rail-row__dir) {
+ position: relative;
+ padding-left: 20px;
+}
+
+.notes-right-rail .rail-row > .rail-row__dir {
+ position: absolute;
+ top: 2px;
+ left: 0;
+ line-height: 19px;
+}
+
+.notes-right-rail .rail-row:has(> :is(.rail-row__type, .rail-row__path)) > button {
+ flex: 1 0 auto;
+ max-width: 100%;
+}
+
+.notes-right-rail .rail-row > :is(.rail-row__type, .rail-row__path) {
+ max-width: 100%;
+}
+
+.notes-right-rail .rail-row > .rail-row__type {
+ flex-basis: 100%;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+}
+.notes-right-rail .rail-row > button {
+ text-decoration: none;
+}
+
+.notes-right-rail .rail-row > button:is(:hover, :focus-visible) {
+ text-decoration: underline;
+ text-decoration-color: var(--link-line);
+ text-underline-offset: 2px;
+}
+
+/* Workspace materials open from their heading row; the shared chevron
+ follows the heading and turns. Closed, the count names its unit. */
+.notes-right-rail .rail-materials > summary {
+ display: block;
+ list-style: none;
+ cursor: pointer;
+}
+
+.notes-right-rail .rail-materials > summary::-webkit-details-marker {
+ display: none;
+}
+
+.notes-right-rail .rail-materials > summary > h3 {
+ justify-content: flex-start;
+ gap: var(--sp-2);
+ min-height: 24px;
+ margin: 0;
+}
+
+.notes-right-rail .rail-materials > summary .ontology-sidebar-context__count {
+ margin-left: auto;
+}
+
+.notes-right-rail .rail-materials > summary .disclosure-chevron {
+ margin-right: -4px;
+ color: var(--text-muted);
+}
+
+.notes-right-rail .rail-materials[open] .rail-materials__unit {
+ display: none;
+}
+
+.notes-right-rail .rail-materials > summary:hover > h3 {
+ color: var(--text);
+}
+
+.notes-right-rail .rail-materials > summary:focus-visible {
+ outline: 2px solid var(--focus-ring);
+ outline-offset: 2px;
+ border-radius: var(--r-sm);
+}
+
+.notes-right-rail .rail-materials[open] > summary {
+ margin-bottom: var(--sp-1);
+}
+
+.notes-right-rail .rail-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px var(--sp-4);
+ margin: 0 0 var(--sp-2);
+ color: var(--text-faint);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+}
+
+.notes-right-rail .rail-legend__dir {
+ margin-right: 3px;
+ font-weight: 600;
+}
+
+/* An untyped note names its folder where a typed one names its type. */
+.notes-right-rail .rail-row__path {
+ flex: 0 1 auto;
+ max-width: 45%;
+ overflow: hidden;
+ color: var(--text-faint);
+ font-family: var(--font-mono);
+ font-size: var(--fs-xs);
+ direction: rtl;
+ text-align: left;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.notes-right-rail :is(.rail-row__dir, .rail-bucket__dir, .rail-direction__dir) {
+ width: 16px;
+ font-size: var(--fs-lg);
+ font-weight: 500;
+ line-height: 1;
+}
+
+.notes-right-rail .rail-bucket .rail-row:not(:has(.rail-row__dir)) {
+ padding-left: 20px;
+}
+
+/* Relations split into compact Incoming and Outgoing groups. */
+.notes-right-rail .rail-direction {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-1);
+ margin: 0 0 2px;
+ color: var(--text-faint);
+ font: 500 var(--fs-sm) / 1.3 var(--font-sans);
+}
+
+.notes-right-rail section + section > .rail-direction {
+ margin-top: var(--sp-3);
+}
+
+.notes-right-rail .rail-direction__dir {
+ text-align: center;
+}
+
+.notes-right-rail .rail-direction ~ .rail-bucket .rail-bucket__head {
+ padding-left: 20px;
+}
+
+.notes-right-rail .rail-bucket__head {
+ color: var(--text-muted);
+ font-weight: 500;
+}
+
+.notes-right-rail .note-info .rail-bucket__head {
+ margin-top: 14px;
+ font-weight: 500;
+}
+.notes-right-rail .note-info .rail-bucket + .rail-bucket {
+ margin-top: 0;
+}
+.notes-right-rail .note-info .rail-row {
+ min-height: 28px;
+ box-sizing: border-box;
+ row-gap: 4px;
+}
+/* Two-line rows (title over type or folder) keep 8px apart; one-line rows
+ sit on a plain 28px pitch. */
+.notes-right-rail .note-info .rail-row:has(> :is(.rail-row__type, .rail-row__path)) + .rail-row,
+.notes-right-rail .note-info .rail-row + .rail-row:has(> :is(.rail-row__type, .rail-row__path)) {
+ margin-top: 8px;
+}
+.notes-right-rail .note-info .rail-row:not(:has(> :is(.rail-row__type, .rail-row__path))) > button {
+ min-height: 28px;
+}
+.notes-right-rail .note-info .rail-row > .rail-row__dir {
+ top: 2px;
+}
+.notes-right-rail
+ .note-info
+ .rail-row:not(:has(> :is(.rail-row__type, .rail-row__path)))
+ > .rail-row__dir {
+ top: 6px;
+}
+.notes-right-rail .note-info .rail-materials > summary > h3 {
+ margin-bottom: 10px;
+}
+.notes-right-rail .note-info .rail-materials[open] > summary {
+ margin-bottom: 0;
+}
+.notes-right-rail .note-info .rail-materials > summary .disclosure-chevron {
+ margin: 0;
+}
+
+.notes-right-rail .note-info .rail-row__path {
+ flex: 0 0 100%;
+ max-width: 100%;
+}
+
+.relation-arrow {
+ display: inline-block;
+ vertical-align: middle;
+ flex-shrink: 0;
+ color: var(--text-faint);
+}
+
+.widget-date-editor:not(:focus-within) {
+ position: relative;
+}
+.widget-date-editor:not(:focus-within) > .widget-date--input {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ opacity: 0;
+}
+.widget-date-editor:focus-within > .widget-date-editor__rest,
+.widget-date-editor:not(:focus-within)
+ > :is(.widget-date-editor__picker, .widget-date-editor__offset) {
+ display: none;
+}
+.widget-date-editor__rest {
+ font-variant-numeric: tabular-nums;
+}
diff --git a/web/src/note-reader.css b/web/src/note-reader.css
new file mode 100644
index 000000000..b53fbc3a9
--- /dev/null
+++ b/web/src/note-reader.css
@@ -0,0 +1,306 @@
+@import "./note-info.css";
+
+/* Note reader: toolbar, measure, control bar, properties, and the Info pane.
+ Moved verbatim from notes-shell.css. */
+
+.ontology-pane__type {
+ flex: none;
+}
+
+/* The path takes the row's free width and truncates in the middle, so the
+ filename survives (MiddleTruncate). */
+.ontology-pane__toolbar-path {
+ flex: 0 1 auto;
+ min-width: 80px;
+ overflow: hidden;
+ color: var(--text-faint);
+ font-family: var(--font-mono);
+ font-size: var(--fs-xs);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* Section jumps share the .segmented look; the row scrolls when crowded. */
+.ontology-pane__section-tabs.segmented {
+ flex: 0 1 auto;
+ align-self: center;
+ overflow-x: auto;
+}
+
+.ontology-pane__section-tabs > button {
+ flex: none;
+}
+
+.ontology-pane__section-tabs > button:disabled {
+ color: var(--text-faint);
+ cursor: default;
+}
+
+.ontology-source {
+ display: block;
+ margin: calc(-1 * var(--sp-6));
+ padding: var(--sp-4) 0 var(--sp-8);
+ overflow: visible;
+ background: var(--surface);
+ color: var(--text);
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+ line-height: 1.55;
+ white-space: pre-wrap;
+}
+
+.ontology-source__line {
+ display: grid;
+ grid-template-columns: 42px minmax(0, 1fr);
+ min-height: 19px;
+}
+
+.ontology-source__number {
+ padding-right: var(--sp-3);
+ color: var(--border-strong);
+ text-align: right;
+ user-select: none;
+}
+
+.ontology-source__line code {
+ padding: 0 var(--sp-5);
+ color: inherit;
+ font: inherit;
+ overflow-wrap: anywhere;
+}
+
+/* ---- Note reader measure ----
+ The note reads in a 540px column centred in the panel (65–75 characters of
+ 15px Inter). Percentages resolve against the pane's width. HTML notes run
+ edge to edge. */
+.notes-shell .ontology-pane {
+ --note-gutter: max(var(--sp-6), calc((100% - 540px) / 2));
+}
+
+.notes-shell .ontology-pane__main:not(.ontology-pane__main--html) {
+ padding-inline: var(--note-gutter);
+}
+
+/* The control row is pane chrome, not prose: it runs edge to edge as an HTML
+ note's does, so the path has the free width. */
+.notes-shell .ontology-pane__controls {
+ padding-inline: var(--sp-6);
+ border-bottom: 1px solid var(--border);
+ background: var(--surface);
+}
+
+.notes-shell .ontology-pane__main:not(.ontology-pane__main--html) .ontology-markdown {
+ max-width: none;
+}
+
+/* Prose and the editor's lines share the column's 540px measure, so editing
+ keeps read mode's line breaks even where the column could grow. */
+.notes-shell .body-narrative :is(p, ul, ol, blockquote),
+.notes-shell .body-narrative--editor .cm-line {
+ max-width: 540px;
+}
+
+/* One vertical rhythm in both modes. A blank source line is the paragraph
+ gap (0.75em), list items sit on the 24px line grid, and a list that follows
+ its lead-in line directly keeps no gap, as the editor shows it. */
+.notes-shell .body-narrative--editor .cm-line:has(> br:only-child) {
+ line-height: 0.75em;
+}
+
+.notes-shell .body-narrative li {
+ margin: 0;
+}
+
+.notes-shell .body-narrative :is(ul, ol) {
+ margin: 0 0 0.75em;
+ padding-left: 2em;
+}
+
+.notes-shell .body-narrative p:has(+ :is(ul, ol)) {
+ margin-bottom: 0;
+}
+
+/* A wiki link in the editor takes read mode's metrics: the same hairline
+ underline and no trailing glyph, so a line wraps where it did in read mode. */
+.notes-shell .body-narrative--editor .cm-atomic-wiki-link {
+ text-decoration-color: var(--link-line);
+ text-decoration-thickness: 1px;
+ text-underline-offset: 2px;
+}
+
+.notes-shell .body-narrative--editor .cm-atomic-wiki-link .cm-atomic-link::after {
+ content: none;
+}
+
+/* The controls row is only as wide as the column: the path gives way, never
+ the controls. */
+.notes-shell
+ .ontology-pane__controls
+ > :not(.ontology-pane__toolbar-path, .ontology-pane__controls-spacer) {
+ flex: none;
+ white-space: nowrap;
+}
+
+/* ---- Note control bar ----
+ The note's presentations (Structure | Markdown, plus saved views) read as
+ one segmented control, like every other mode switch; the default view is
+ named by the segment's tooltip, so its dot is not drawn here. Copy link is
+ a ghost button, not a second bordered control. */
+.ontology-pane__controls .view-tabs {
+ flex: none;
+ gap: 2px;
+ align-items: stretch;
+ padding: 2px;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--surface-sunk);
+}
+
+/* The chosen presentation is the shared raised segment (base.css .segmented):
+ a surface fill with a border-strong edge on the tinted track, in both
+ themes. Never a solid ink fill. */
+.ontology-pane__controls .view-tabs > button {
+ height: 22px;
+ padding: 0 9px;
+ border: 1px solid transparent;
+ border-radius: var(--r);
+ font: 500 var(--fs-sm) / 1 var(--font-sans);
+}
+
+.ontology-pane__controls .view-tabs > button[aria-pressed="true"] {
+ border-color: var(--border-strong);
+ background: light-dark(var(--surface), var(--surface-strong));
+ color: var(--text);
+ font-weight: 600;
+}
+
+.ontology-pane__controls .view-tabs > button[aria-pressed="true"]::after,
+.ontology-pane__controls .view-selector__default {
+ display: none;
+}
+
+.ontology-pane__controls .ontology-link-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ height: 26px;
+ padding: 0 var(--sp-2);
+ border-color: transparent;
+ background: transparent;
+ color: var(--text-muted);
+}
+
+.ontology-pane__controls .ontology-link-button:hover {
+ border-color: transparent;
+ background: var(--bg-tint);
+ color: var(--text);
+}
+
+.ontology-pane__controls .ontology-link-button svg {
+ width: 14px;
+ height: 14px;
+}
+
+/* ---- Note properties ----
+ Properties share the prose measure, so the block's right edge lines up with
+ the paragraphs under it. Labels take a 120px column; long text (a summary)
+ runs full width under its label instead of in a narrow value column. */
+.notes-shell .ontology-pane .ontology-properties {
+ max-width: 540px;
+}
+
+.notes-shell .ontology-pane .ontology-properties__grid {
+ grid-template-columns: 120px minmax(0, 1fr);
+ column-gap: var(--sp-4);
+}
+
+.notes-shell .ontology-pane .ontology-properties__row.is-long > :is(dt, dd) {
+ grid-column: 1 / -1;
+}
+
+.notes-shell .ontology-pane .ontology-properties__row.is-long > dd {
+ padding-top: 0;
+}
+
+/* Only properties longer than six lines need an own-row disclosure. */
+.notes-shell .ontology-pane .ontology-properties__preview-text {
+ display: -webkit-box;
+ min-width: 0;
+ overflow: hidden;
+ color: var(--text);
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 6;
+ line-clamp: 6;
+}
+
+.notes-shell .ontology-pane .ontology-properties__preview-more {
+ margin-top: var(--sp-2);
+}
+
+/* Field labels stay roman; an empty field reads faint, not italic. */
+.notes-shell .ontology-pane .ontology-properties__row.is-missing .ontology-properties__key {
+ font-style: normal;
+}
+
+/* Inline code sits tight in its sentence: no padded gap inside parentheses. */
+.notes-shell .ontology-markdown :not(pre) > code {
+ margin: 0;
+ padding: 1px 3px;
+}
+
+/* Identity typography is local to the reader, including the HTML control row. */
+.ontology-pane .note-identity-id,
+.ontology-pane .ontology-identity__slot--id {
+ color: var(--text-muted);
+ font: 500 12px / 1.4 var(--font-mono);
+}
+.ontology-pane .ontology-identity .widget-date {
+ font-family: var(--font-sans);
+ font-variant-numeric: tabular-nums;
+}
+.ontology-pane .ontology-identity .widget-enum--badge {
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ font: 500 13px / 1.35 var(--font-sans);
+}
+.notes-shell
+ .ontology-pane
+ .ontology-properties__value
+ :is(.widget-text, .ontology-properties__preview-text) {
+ color: var(--text);
+ font: 400 14px / 1.45 var(--font-sans);
+}
+/* Property pencils sit beside their labels inside the property block. */
+.ontology-pane .ontology-properties__key:has(.note-property-pencil) {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+}
+.note-property-pencil {
+ width: 24px;
+ height: 16px;
+ padding-inline: 4px;
+ box-sizing: border-box;
+ color: var(--text-muted);
+}
+.ontology-pane .note-identity-separator {
+ color: var(--text-faint);
+}
+
+.ontology-edit-bar.is-idle .ontology-edit-bar__label {
+ background: var(--bg-tint);
+ color: var(--text-muted);
+}
+@media (max-width: 1100px) {
+ .notes-shell:has(.ontology-pane) .notes-shell__pane-toggle[aria-expanded="false"] {
+ width: auto;
+ gap: 6px;
+ padding-inline: 8px;
+ }
+ .notes-shell:has(.ontology-pane) .notes-shell__pane-toggle[aria-expanded="false"]::after {
+ content: "Info";
+ }
+}
diff --git a/web/src/notes-shell.css b/web/src/notes-shell.css
index ff46ba506..9c05550a4 100644
--- a/web/src/notes-shell.css
+++ b/web/src/notes-shell.css
@@ -185,7 +185,7 @@
align-items: center;
gap: 6px;
min-width: 96px;
- max-width: 220px;
+ max-width: 320px;
padding: 0 6px 0 10px;
color: var(--text-muted);
font-size: var(--fs-sm);
@@ -319,1947 +319,929 @@
display: none;
}
-/* ---- Search ----
- One centred column shared by the header, the banner, the status line, and
- the results. The header follows the shared view header: an 18/700 title,
- its count, and the query as the muted one-line description, then the
- filters on one row. */
-.search-workspace {
- --search-measure: 720px;
+/* ---- Sidebar: quick items, Views, and the type tree on the chrome ----
+ 30px rows, muted chrome text, and a light pill for the current row. */
+.notes-left-rail {
display: flex;
flex: 1;
flex-direction: column;
min-width: 0;
min-height: 0;
- overflow: auto;
- background: var(--surface);
-}
-
-.search-workspace > * {
- flex: none;
- width: min(100% - 2 * var(--gutter), 960px);
- margin-inline: var(--gutter) auto;
-}
-
-.search-workspace__header {
- display: flex;
- flex-direction: column;
- gap: var(--sp-3);
- padding: var(--sp-5) 0 var(--sp-4);
- border-bottom: 1px solid var(--border);
-}
-
-.search-workspace__title-row {
- display: flex;
- align-items: baseline;
- gap: var(--sp-3);
- min-width: 0;
-}
-
-.search-workspace h1 {
- flex: none;
- margin: 0;
- color: var(--text);
- font: 700 var(--fs-xl) / 1.2 var(--font-sans);
- letter-spacing: -0.01em;
-}
-
-.search-workspace__query {
- min-width: 0;
- margin: 0;
overflow: hidden;
- color: var(--text-muted);
+ color: var(--chrome-muted);
font-size: var(--fs-base);
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.search-workspace h1 mark {
- color: inherit;
- background: transparent;
-}
-
-.search-workspace__filters {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: var(--sp-3);
}
-.search-workspace__filters label {
- display: inline-flex;
- align-items: center;
- gap: var(--sp-2);
- color: var(--text-muted);
+/* A sidebar read that failed: a quiet line with a retry. */
+.notes-left-rail__state {
+ margin: 6px 18px;
+ color: var(--chrome-muted);
font-size: var(--fs-sm);
}
-.search-workspace__filters select {
- width: 180px;
-}
-
-.search-workspace__filters input {
- width: 220px;
-}
-
-/* "Anywhere" is a hint, not a value: faint, so it never reads as a choice. */
-.search-workspace__filters input::placeholder {
- color: var(--text-faint);
- opacity: 1;
-}
-
-.search-workspace__clear {
- height: 26px;
- padding: 0 var(--sp-2);
+.notes-left-rail__state button {
+ padding: 0;
border: 0;
- border-radius: var(--r-md);
- background: transparent;
- color: var(--text-muted);
- font: 500 var(--fs-sm) / 1 var(--font-sans);
+ background: none;
+ color: var(--chrome-text);
+ font: inherit;
+ text-decoration: underline;
cursor: pointer;
}
-.search-workspace__clear:hover {
- background: var(--bg-tint);
- color: var(--text);
+.notes-left-rail__collections {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 6px 0 16px;
+ scrollbar-color: var(--chrome-raised) transparent;
+ scrollbar-width: thin;
}
-/* The banner: one 36px tinted band with a mark, text, and its action; the
- individual source messages wait behind Details. */
-.search-workspace__warnings {
+.notes-left-rail .ontology-type-list,
+.notes-left-rail .ontology-type-group,
+.notes-left-rail__nested-views {
display: flex;
flex-direction: column;
- gap: var(--sp-2);
- margin-top: var(--sp-4);
-}
-
-.search-workspace__banner {
- border: 1px solid color-mix(in srgb, var(--warning) 55%, transparent);
- border-radius: var(--r-md);
- background: var(--warning-soft);
- color: var(--warning-ink);
- font-size: var(--fs-sm);
+ gap: 1px;
}
-.search-workspace__banner.is-alert {
- border-color: var(--accent-line);
- background: var(--accent-soft);
- color: var(--accent-ink);
+.notes-left-rail .ontology-type-list {
+ padding: 0 8px;
}
-.search-workspace__banner-row {
+.notes-left-rail .ontology-type-row-wrap {
display: flex;
align-items: center;
- gap: var(--sp-2);
- min-height: 34px;
- padding: 0 var(--sp-2) 0 var(--sp-3);
+ height: 30px;
+ transition: background-color 0.12s var(--ease);
+ /* Top-level types sit at depth 1, level with the section header. */
+ padding-left: calc(max(0, var(--ontology-type-depth, 1) - 1) * 16px);
+ border-radius: var(--r-md);
}
-.search-workspace__banner-mark {
- flex: none;
- width: 15px;
- height: 15px;
+.notes-left-rail .ontology-type-row-wrap:hover {
+ background: var(--chrome-raised);
}
-.search-workspace__banner-text {
- flex: 1;
- min-width: 0;
- padding: var(--sp-1) 0;
- color: var(--text);
+.notes-left-rail .ontology-type-row-wrap:has(> .is-selected) {
+ background: var(--chrome-pill);
+ color: var(--chrome-pill-text);
}
-.search-workspace__banner-row > button {
- flex: none;
- height: 24px;
- padding: 0 var(--sp-2);
+.notes-left-rail .ontology-type-row,
+.notes-left-rail .ontology-view-row {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ height: 100%;
+ padding: 0 10px 0 4px;
border: 0;
- border-radius: var(--r-sm);
+ border-radius: inherit;
background: transparent;
color: inherit;
- font: 600 var(--fs-sm) / 1 var(--font-sans);
+ font: inherit;
+ text-align: left;
cursor: pointer;
}
-.search-workspace__banner-row > button:hover {
- background: color-mix(in srgb, currentcolor 10%, transparent);
+.notes-left-rail .ontology-type-row:focus-visible,
+.notes-left-rail .ontology-view-row:focus-visible {
+ outline: 2px solid var(--chrome-text);
+ outline-offset: -2px;
}
-.search-workspace__banner-details {
- margin: 0;
- padding: 0 var(--sp-3) var(--sp-3) calc(var(--sp-3) + 15px + var(--sp-2));
- color: var(--text-muted);
- line-height: 1.45;
- list-style: none;
+.notes-left-rail .is-selected {
+ font-weight: 600;
}
-.search-workspace__banner-details li + li {
- margin-top: var(--sp-1);
+/* The selected pill is close to the chrome text in light themes, so its
+ focus ring takes the pill's own ink. */
+.notes-left-rail .is-selected:focus-visible {
+ outline-color: var(--chrome-pill-text);
}
-.search-workspace__meta,
-.search-workspace__state,
-.search-workspace__end {
- margin-top: var(--sp-4);
- color: var(--text-muted);
- font-size: var(--fs-sm);
+/* Rows without an icon or caret start where icon rows put their label. */
+.notes-left-rail .ontology-type-row--pseudo,
+.notes-left-rail .ontology-view-row {
+ padding-left: 8px;
}
-.search-workspace__meta {
- display: flex;
- justify-content: space-between;
- gap: var(--sp-3);
+.notes-left-rail .ontology-type-row--pseudo:not(.is-selected) {
+ color: var(--chrome-text);
}
-/* One plain line: "Showing 40 of 100 results · Medium confidence ⓘ", with
- figures in tabular Inter. It wraps rather than clipping the info tip. */
-.search-workspace__status {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- min-width: 0;
- font-variant-numeric: tabular-nums;
+.notes-left-rail__icon {
+ flex: none;
+ width: 16px;
+ height: 16px;
}
-.search-workspace__status > span {
+.notes-left-rail .ontology-type-row__collapse,
+.notes-left-rail .ontology-type-row__collapse-spacer {
display: inline-flex;
+ flex: 0 0 var(--disclosure-target);
align-items: center;
- gap: 2px;
+ justify-content: center;
+ height: 100%;
}
-.search-workspace__status > span:not(:first-child)::before {
- content: "·";
- margin: 0 var(--sp-2);
- color: var(--text-faint);
+.notes-left-rail .ontology-type-row__collapse {
+ padding: 0;
+ border: 0;
+ border-radius: var(--r-md);
+ background: transparent;
+ color: inherit;
+ cursor: pointer;
}
-.search-workspace__status .field-editor__info-tip {
- color: var(--text);
+.notes-left-rail .ontology-type-row__label,
+.notes-left-rail .ontology-view-row__label {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-.search-workspace__state {
- display: flex;
- align-items: center;
- flex-direction: column;
- gap: var(--sp-2);
- padding: var(--sp-8) var(--sp-4);
- text-align: center;
+.notes-left-rail .ontology-type-row__count {
+ flex: none;
+ color: inherit;
+ font-size: var(--fs-xs);
+ font-variant-numeric: tabular-nums;
+ font-weight: 400;
+ opacity: 0.85;
}
-.search-workspace__state strong {
- color: var(--text);
- font-size: var(--fs-lg);
+.notes-left-rail .ontology-type-row__count.is-risk {
+ color: var(--chrome-risk);
font-weight: 600;
+ opacity: 1;
}
-.search-workspace__state button,
-.search-workspace__load-more {
- height: 28px;
- padding: 0 11px;
- border: 1px solid var(--border-strong);
- border-radius: var(--r-md);
- background: var(--surface);
- color: var(--text);
- font-size: var(--fs-sm);
- font-weight: 500;
- cursor: pointer;
+.notes-left-rail .is-selected .ontology-type-row__count.is-risk {
+ color: var(--accent-ink);
}
-.search-workspace__state button:hover,
-.search-workspace__load-more:hover {
- background: var(--bg-tint);
+.notes-left-rail .validation-issue-badge {
+ color: var(--chrome-risk);
}
-.search-workspace__results {
- display: grid;
- grid-template-columns: minmax(0, 1fr);
- gap: 0;
- margin-top: var(--sp-2);
- padding: 0;
- border-top: 1px solid var(--border);
- list-style: none;
+.notes-left-rail .validation-issue-badge--presence {
+ background: var(--chrome-risk);
}
-.search-workspace__result {
- padding: var(--sp-4) 0;
- border-bottom: 1px solid var(--border-faint);
+.notes-left-rail .ontology-type-row--embedded {
+ opacity: 0.6;
+ font-style: italic;
+ cursor: default;
}
-.search-workspace__result-kind {
- display: flex;
- gap: var(--sp-2);
- font: var(--label-font);
- color: var(--label-color);
+.notes-left-rail .ontology-type-row-wrap:has(> .ontology-type-row--embedded):hover {
+ background: transparent;
}
-.search-workspace__result-why {
- color: var(--text-faint);
- font-weight: 500;
+/* Section headers: Views and each type group, collapsible. */
+.notes-left-rail__section {
+ margin-top: 14px;
}
-.search-workspace__result-why::before {
- content: "·";
- margin-right: var(--sp-2);
+.notes-left-rail .ontology-type-row--group {
+ padding-left: 2px;
+ font-weight: 500;
}
-.search-workspace__result-link {
- display: block;
- max-width: 100%;
- margin-top: 2px;
- padding: 0;
- overflow: hidden;
- border: 0;
- background: transparent;
- font: 500 var(--fs-lg) / 1.35 var(--font-sans);
- text-align: left;
- text-overflow: ellipsis;
- white-space: nowrap;
- cursor: pointer;
+.notes-left-rail
+ .notes-left-rail__section
+ .ontology-type-row__collapse
+ + .ontology-type-row--group {
+ padding-left: 0;
}
-/* A result title is a quiet link (.link-title): ink, underlined on hover
- and keyboard focus. */
-.search-workspace__result-link:hover,
-.search-workspace__result-link:focus-visible {
- text-decoration: underline;
- text-decoration-color: var(--link-line);
- text-underline-offset: 2px;
+/* The Views header's caret sits inside its one button. */
+.notes-left-rail .ontology-type-row--group > .ontology-type-row__collapse {
+ flex-basis: 18px;
+ margin-left: -2px;
}
-/* Results share one reading measure: the source line, note excerpts, and
- code all stop at about 720px. The path gives way in its middle, so the
- file name and line stay; the section is its own Inter label after it and
- gives way at its end. */
-.search-workspace__result-source {
- display: flex;
- align-items: baseline;
- gap: var(--sp-3);
- min-width: 0;
- max-width: var(--search-measure);
- margin-top: 2px;
- color: var(--text-faint);
- font-family: var(--font-mono);
- font-size: var(--fs-xs);
- white-space: nowrap;
-}
-
-.search-workspace__result-source > .middle-truncate {
- flex: 0 1 auto;
+.notes-left-rail .ontology-type-row--group.is-selected {
+ font-weight: 600;
}
-.search-workspace__result-heading {
- flex: 0 100 auto;
- min-width: 8ch;
- overflow: hidden;
- color: var(--text-muted);
- font: 500 var(--fs-sm) / 1.4 var(--font-sans);
- text-overflow: ellipsis;
+.notes-shell__panel {
+ grid-column: 1;
+ grid-row: 1;
+ position: absolute;
+ inset: 0;
+ min-width: 0;
+ min-height: 0;
+ height: 100%;
+ overflow: auto;
+ visibility: hidden;
+ pointer-events: none;
}
-.search-workspace__result-heading::before {
- content: "§";
- margin-right: var(--sp-1);
- color: var(--text-faint);
+/* ---- The one right pane: note context or a collection's record ---- */
+.notes-right-rail {
+ position: relative;
+ grid-column: 2;
+ grid-row: 1;
+ display: flex;
+ flex-direction: column;
+ width: var(--pane-width);
+ min-width: 0;
+ min-height: 0;
+ border-left: 1px solid var(--border);
+ background: var(--surface);
}
-/* Note excerpts read as prose at the shared measure, inline code as code. */
-.search-workspace__result p {
- max-width: var(--search-measure);
- margin: var(--sp-2) 0 0;
- color: var(--text-muted);
- font-size: var(--fs-base);
- line-height: 1.5;
+/* Below 1200px the pane covers the content so the table keeps its width. */
+.notes-right-rail.is-overlay {
+ position: absolute;
+ z-index: 6;
+ inset: 0 0 0 auto;
+ grid-column: 1 / -1;
+ width: min(var(--pane-width), 100%);
+ border-left-color: var(--border-strong);
+ box-shadow: var(--shadow-lg);
}
-.search-workspace__result p code {
- padding: 1px 3px;
- border-radius: var(--r-sm);
- background: var(--surface-sunk);
- color: var(--text);
- font-family: var(--font-mono);
- font-size: 0.9em;
+/* Over a collection, the overlay starts below the view header and toolbar so
+ Find, Filter, and Display stay usable while a record is open.
+ ponytail: fixed offset matching the header height; measure .view-header if it starts to vary. */
+.notes-shell__frame:has(.notes-shell__panel.is-active .configured-view)
+ .notes-right-rail.is-overlay {
+ top: var(--collection-header-height, 96px);
}
-.search-workspace__result p.is-missing {
- color: var(--text-faint);
- font-style: italic;
+.notes-right-rail__header {
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: var(--sp-3);
+ /* Matches the note's control bar beside it. */
+ height: 40px;
+ padding: 0 var(--sp-3) 0 var(--sp-5);
+ border-bottom: 1px solid var(--border);
}
-/* Code evidence keeps its source lines in mono on the tint: long lines
- scroll sideways instead of breaking into fragments. */
-.search-workspace__code {
- max-width: var(--search-measure);
- margin: var(--sp-2) 0 0;
- padding: var(--sp-2) var(--sp-3);
- overflow: auto;
- border-radius: var(--r-md);
- background: var(--bg-tint);
+.notes-right-rail__title {
+ flex: 1;
+ margin: 0;
color: var(--text);
- font: 400 var(--fs-sm) / 1.5 var(--font-mono);
- tab-size: 4;
- white-space: pre;
+ font-size: var(--fs-md);
+ font-weight: 600;
}
-/* Matches share Finder's weight; only navigable Finder titles underline. */
-.search-workspace__result mark {
- background: none;
- color: inherit;
- font-weight: 650;
- text-decoration: none;
+.notes-right-rail__close {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ margin-left: auto;
+ padding: 0;
+ border: 0;
+ border-radius: var(--r-md);
+ background: transparent;
+ color: var(--text-muted);
+ cursor: pointer;
}
-.search-workspace__load-more,
-.search-workspace__end {
- width: auto;
- margin-block: var(--sp-4) var(--sp-6);
+.notes-right-rail__close svg {
+ width: 15px;
+ height: 15px;
}
-.search-workspace__end {
- color: var(--text-faint);
- text-align: center;
+.notes-right-rail__close:hover {
+ background: var(--surface-sunk);
+ color: var(--text);
}
-/* ---- Sidebar: quick items, Views, and the type tree on the chrome ----
- 30px rows, muted chrome text, and a light pill for the current row. */
-.notes-left-rail {
+.notes-right-rail__tabs {
display: flex;
- flex: 1;
- flex-direction: column;
- min-width: 0;
- min-height: 0;
- overflow: hidden;
- color: var(--chrome-muted);
- font-size: var(--fs-base);
-}
-
-/* A sidebar read that failed: a quiet line with a retry. */
-.notes-left-rail__state {
- margin: 6px 18px;
- color: var(--chrome-muted);
- font-size: var(--fs-sm);
+ align-self: stretch;
+ gap: var(--sp-5);
}
-.notes-left-rail__state button {
+.notes-right-rail__tab {
padding: 0;
border: 0;
- background: none;
- color: var(--chrome-text);
+ background: transparent;
+ color: var(--text-muted);
font: inherit;
- text-decoration: underline;
+ font-size: var(--fs-sm);
+ font-weight: 500;
cursor: pointer;
}
-.notes-left-rail__collections {
+.notes-right-rail__tab:hover {
+ color: var(--text);
+}
+
+.notes-right-rail__tab[aria-selected="true"] {
+ color: var(--text);
+ box-shadow: inset 0 -2px var(--text);
+}
+
+.notes-right-rail__content,
+.notes-right-rail__content > [role="tabpanel"] {
flex: 1;
min-height: 0;
- overflow: auto;
- padding: 6px 0 16px;
- scrollbar-color: var(--chrome-raised) transparent;
- scrollbar-width: thin;
}
-.notes-left-rail .ontology-type-list,
-.notes-left-rail .ontology-type-group,
-.notes-left-rail__nested-views {
+.notes-right-rail__content {
display: flex;
flex-direction: column;
- gap: 1px;
+ overflow: auto;
}
-.notes-left-rail .ontology-type-list {
- padding: 0 8px;
+.notes-right-rail__content > [role="tabpanel"] {
+ width: 100%;
+ overflow: auto;
}
-.notes-left-rail .ontology-type-row-wrap {
- display: flex;
- align-items: center;
- height: 30px;
- transition: background-color 0.12s var(--ease);
- /* Top-level types sit at depth 1, level with the section header. */
- padding-left: calc(max(0, var(--ontology-type-depth, 1) - 1) * 16px);
- border-radius: var(--r-md);
+.notes-right-rail__outline {
+ padding: var(--sp-4) var(--sp-5);
}
-.notes-left-rail .ontology-type-row-wrap:hover {
- background: var(--chrome-raised);
+.notes-right-rail__graph {
+ height: 100%;
+ min-height: 0;
}
-.notes-left-rail .ontology-type-row-wrap:has(> .is-selected) {
- background: var(--chrome-pill);
- color: var(--chrome-pill-text);
+.notes-right-rail__graph .ontology-local-graph {
+ height: 100%;
+ margin: 0;
+ border: 0;
}
-.notes-left-rail .ontology-type-row,
-.notes-left-rail .ontology-view-row {
+.notes-right-rail__graph-status {
display: flex;
- flex: 1;
+ flex-direction: column;
align-items: center;
- gap: 8px;
- min-width: 0;
- height: 100%;
- padding: 0 10px 0 4px;
- border: 0;
- border-radius: inherit;
- background: transparent;
- color: inherit;
- font: inherit;
- text-align: left;
- cursor: pointer;
+ justify-content: center;
+ gap: var(--sp-3);
+ padding: var(--sp-5);
+ color: var(--text-faint);
+ text-align: center;
}
-.notes-left-rail .ontology-type-row:focus-visible,
-.notes-left-rail .ontology-view-row:focus-visible {
- outline: 2px solid var(--chrome-text);
- outline-offset: -2px;
+/* The frame on screen and, while one loads, its replacement stacked hidden on it. */
+.custom-view-frames {
+ display: grid;
+ grid-template: minmax(0, 1fr) / minmax(0, 1fr);
+ flex: 1;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
}
-.notes-left-rail .is-selected {
- font-weight: 600;
+.custom-view-frames > .custom-view-frame {
+ grid-area: 1 / 1;
}
-/* The selected pill is close to the chrome text in light themes, so its
- focus ring takes the pill's own ink. */
-.notes-left-rail .is-selected:focus-visible {
- outline-color: var(--chrome-pill-text);
+.custom-view-frame[data-incoming] {
+ visibility: hidden;
}
-/* Rows without an icon or caret start where icon rows put their label. */
-.notes-left-rail .ontology-type-row--pseudo,
-.notes-left-rail .ontology-view-row {
- padding-left: 8px;
+.custom-view-frame {
+ flex: 1;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ border: 0;
+ background: var(--bg);
}
-.notes-left-rail .ontology-type-row--pseudo:not(.is-selected) {
- color: var(--chrome-text);
+.notes-shell__panel.is-active {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ visibility: visible;
+ pointer-events: auto;
}
-.notes-left-rail__icon {
- flex: none;
- width: 16px;
- height: 16px;
+.notes-note-tab {
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ min-height: 0;
}
-
-.notes-left-rail .ontology-type-row__collapse,
-.notes-left-rail .ontology-type-row__collapse-spacer {
- display: inline-flex;
- flex: 0 0 var(--disclosure-target);
- align-items: center;
- justify-content: center;
- height: 100%;
-}
-
-.notes-left-rail .ontology-type-row__collapse {
- padding: 0;
- border: 0;
- border-radius: var(--r-md);
- background: transparent;
- color: inherit;
- cursor: pointer;
-}
-
-.notes-left-rail .ontology-type-row__label,
-.notes-left-rail .ontology-view-row__label {
- flex: 1 1 auto;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.notes-left-rail .ontology-type-row__count {
- flex: none;
- color: inherit;
- font-size: var(--fs-xs);
- font-variant-numeric: tabular-nums;
- font-weight: 400;
- opacity: 0.85;
-}
-
-.notes-left-rail .ontology-type-row__count.is-risk {
- color: var(--chrome-risk);
- font-weight: 600;
- opacity: 1;
-}
-
-.notes-left-rail .is-selected .ontology-type-row__count.is-risk {
- color: var(--accent-ink);
-}
-
-.notes-left-rail .validation-issue-badge {
- color: var(--chrome-risk);
-}
-
-.notes-left-rail .validation-issue-badge--presence {
- background: var(--chrome-risk);
-}
-
-.notes-left-rail .ontology-type-row--embedded {
- opacity: 0.6;
- font-style: italic;
- cursor: default;
-}
-
-.notes-left-rail .ontology-type-row-wrap:has(> .ontology-type-row--embedded):hover {
- background: transparent;
-}
-
-/* Section headers: Views and each type group, collapsible. */
-.notes-left-rail__section {
- margin-top: 14px;
-}
-
-.notes-left-rail .ontology-type-row--group {
- padding-left: 2px;
- font-weight: 500;
-}
-
-.notes-left-rail
- .notes-left-rail__section
- .ontology-type-row__collapse
- + .ontology-type-row--group {
- padding-left: 0;
-}
-
-/* The Views header's caret sits inside its one button. */
-.notes-left-rail .ontology-type-row--group > .ontology-type-row__collapse {
- flex-basis: 18px;
- margin-left: -2px;
-}
-
-.notes-left-rail .ontology-type-row--group.is-selected {
- font-weight: 600;
-}
-
-.notes-shell__panel {
- grid-column: 1;
- grid-row: 1;
- position: absolute;
- inset: 0;
- min-width: 0;
- min-height: 0;
- height: 100%;
- overflow: auto;
- visibility: hidden;
- pointer-events: none;
-}
-
-/* ---- The one right pane: note context or a collection's record ---- */
-.notes-right-rail {
- position: relative;
- grid-column: 2;
- grid-row: 1;
- display: flex;
- flex-direction: column;
- width: var(--pane-width);
- min-width: 0;
- min-height: 0;
- border-left: 1px solid var(--border);
- background: var(--surface);
-}
-
-/* Below 1200px the pane covers the content so the table keeps its width. */
-.notes-right-rail.is-overlay {
- position: absolute;
- z-index: 6;
- inset: 0 0 0 auto;
- grid-column: 1 / -1;
- width: min(var(--pane-width), 100%);
- border-left-color: var(--border-strong);
- box-shadow: var(--shadow-lg);
-}
-
-/* Over a collection, the overlay starts below the view header and toolbar so
- Find, Filter, and Display stay usable while a record is open.
- ponytail: fixed offset matching the header height; measure .view-header if it starts to vary. */
-.notes-shell__frame:has(.notes-shell__panel.is-active .configured-view)
- .notes-right-rail.is-overlay {
- top: var(--collection-header-height, 96px);
-}
-
-.notes-right-rail__header {
- display: flex;
- flex: none;
- align-items: center;
- gap: var(--sp-3);
- /* Matches the note's control bar beside it. */
- height: 40px;
- padding: 0 var(--sp-3) 0 var(--sp-5);
- border-bottom: 1px solid var(--border);
-}
-
-.notes-right-rail__title {
- flex: 1;
- margin: 0;
- color: var(--text);
- font-size: var(--fs-md);
- font-weight: 600;
-}
-
-.notes-right-rail__close {
- display: inline-flex;
- flex: none;
- align-items: center;
- justify-content: center;
- width: 28px;
- height: 28px;
- margin-left: auto;
- padding: 0;
- border: 0;
- border-radius: var(--r-md);
- background: transparent;
- color: var(--text-muted);
- cursor: pointer;
-}
-
-.notes-right-rail__close svg {
- width: 15px;
- height: 15px;
-}
-
-.notes-right-rail__close:hover {
- background: var(--surface-sunk);
- color: var(--text);
-}
-
-.notes-right-rail__tabs {
- display: flex;
- align-self: stretch;
- gap: var(--sp-5);
-}
-
-.notes-right-rail__tab {
- padding: 0;
- border: 0;
- background: transparent;
- color: var(--text-muted);
- font: inherit;
- font-size: var(--fs-sm);
- font-weight: 500;
- cursor: pointer;
-}
-
-.notes-right-rail__tab:hover {
- color: var(--text);
-}
-
-.notes-right-rail__tab[aria-selected="true"] {
- color: var(--text);
- box-shadow: inset 0 -2px var(--text);
-}
-
-.notes-right-rail__content,
-.notes-right-rail__content > [role="tabpanel"] {
- flex: 1;
- min-height: 0;
-}
-
-.notes-right-rail__content {
- display: flex;
- flex-direction: column;
- overflow: auto;
-}
-
-.notes-right-rail__content > [role="tabpanel"] {
- width: 100%;
- overflow: auto;
-}
-
-.notes-right-rail__outline {
- padding: var(--sp-4) var(--sp-5);
-}
-
-.notes-right-rail__graph {
- height: 100%;
- min-height: 0;
-}
-
-.notes-right-rail__graph .ontology-local-graph {
- height: 100%;
- margin: 0;
- border: 0;
-}
-
-.notes-right-rail__graph-status {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: var(--sp-3);
- padding: var(--sp-5);
- color: var(--text-faint);
- text-align: center;
-}
-
-.ontology-pane__type {
- flex: none;
-}
-
-/* The path takes the row's free width and truncates in the middle, so the
- filename survives (MiddleTruncate). */
-.ontology-pane__toolbar-path {
- flex: 0 1 auto;
- min-width: 80px;
- overflow: hidden;
- color: var(--text-faint);
- font-family: var(--font-mono);
- font-size: var(--fs-xs);
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Section jumps share the .segmented look; the row scrolls when crowded. */
-.ontology-pane__section-tabs.segmented {
- flex: 0 1 auto;
- align-self: center;
- overflow-x: auto;
-}
-
-.ontology-pane__section-tabs > button {
- flex: none;
-}
-
-.ontology-pane__section-tabs > button:disabled {
- color: var(--text-faint);
- cursor: default;
-}
-
-.ontology-source {
- display: block;
- margin: calc(-1 * var(--sp-6));
- padding: var(--sp-4) 0 var(--sp-8);
- overflow: visible;
- background: var(--surface);
- color: var(--text);
- font-family: var(--font-mono);
- font-size: var(--fs-sm);
- line-height: 1.55;
- white-space: pre-wrap;
-}
-
-.ontology-source__line {
- display: grid;
- grid-template-columns: 42px minmax(0, 1fr);
- min-height: 19px;
-}
-
-.ontology-source__number {
- padding-right: var(--sp-3);
- color: var(--border-strong);
- text-align: right;
- user-select: none;
-}
-
-.ontology-source__line code {
- padding: 0 var(--sp-5);
- color: inherit;
- font: inherit;
- overflow-wrap: anywhere;
-}
-
-.ontology-markdown--html {
- width: 100%;
- max-width: none;
-}
-
-.ontology-pane__main--html {
- display: flex;
- flex-direction: column;
- min-height: 0;
-}
-
-.ontology-pane__main--html > * {
- flex-shrink: 0;
-}
-
-.ontology-pane__main--html > .ontology-markdown--html {
- display: flex;
- flex: 1;
- /* Cancel the pane padding so the viewer runs edge to edge and reaches the pane bottom. */
- width: auto;
- margin: 0 calc(-1 * var(--sp-6)) calc(-1 * var(--sp-6));
- min-height: min(70vh, 640px);
- max-width: none;
-}
-
-/* "Metadata" is the shared ghost disclosure: label, then the chevron. */
-.ontology-properties__html-summary {
- gap: 2px;
- padding: 0 4px 0 8px;
- list-style: none;
-}
-
-.ontology-properties__html-summary::-webkit-details-marker {
- display: none;
-}
-
-.ontology-properties__html-summary:hover {
- color: var(--text);
-}
-
-.ontology-properties__html-summary:focus-visible {
- outline: 2px solid var(--focus-ring);
- outline-offset: 1px;
-}
-
-.html-note-viewer {
- display: flex;
- flex-direction: column;
- width: 100%;
- flex: 1;
- min-height: 0;
- overflow: hidden;
- background: var(--surface-alt);
-}
-
-.html-note-viewer.is-hidden {
- display: none;
-}
-
-/* Chrome-free note page (`?bare=1`): the viewer is the whole window. */
-.bare-html-note {
- position: fixed;
- inset: 0;
- display: flex;
- flex-direction: column;
- background: var(--surface-alt);
-}
-
-.html-note-viewer__toolbar,
-.html-note-viewer__action {
- display: flex;
- align-items: center;
- gap: var(--sp-3);
- min-height: 32px;
- padding: 0 var(--sp-3);
- border-bottom: 1px solid var(--border);
- color: var(--text-muted);
- font-size: var(--fs-xs);
-}
-
-.html-note-viewer__format {
- color: var(--text);
- font-family: var(--font-mono);
- font-weight: 600;
-}
-
-.html-note-viewer__state {
- color: var(--text-faint);
-}
-
-.html-note-viewer__spacer {
- flex: 1;
-}
-
-/* Viewer actions are neutral ghost buttons; red stays for risk. */
-.html-note-viewer__ghost,
-.html-note-viewer__action button {
- display: inline-flex;
- flex: none;
- align-items: center;
- height: 26px;
- padding: 0 var(--sp-2);
- border: 0;
- border-radius: var(--r-md);
- background: transparent;
- color: var(--text-muted);
- font: 500 var(--fs-sm) / 1 var(--font-sans);
- text-decoration: none;
- white-space: nowrap;
- cursor: pointer;
-}
-
-.html-note-viewer__ghost svg {
- width: 14px;
- height: 14px;
-}
-
-.html-note-viewer__ghost:not(.html-note-viewer__ghost--icon) svg {
- margin-left: 5px;
-}
-
-.html-note-viewer__ghost--icon {
- justify-content: center;
- width: 26px;
- padding: 0;
-}
-
-.html-note-viewer__ghost:hover,
-.html-note-viewer__action button:hover {
- background: var(--bg-tint);
- color: var(--text);
-}
-
-.html-note-viewer__problem {
- padding: var(--sp-2) var(--sp-3);
- border-bottom: 1px solid var(--border);
- background: var(--accent-soft);
- color: var(--accent-ink);
- font-size: var(--fs-xs);
-}
-
-.html-note-viewer__action {
- justify-content: flex-end;
- background: var(--surface);
-}
-
-.html-note-viewer__action > span {
- min-width: 0;
- margin-right: auto;
- overflow: hidden;
- color: var(--text);
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* The frame on screen and, while one loads, its replacement stacked hidden on it. */
-.custom-view-frames {
- display: grid;
- grid-template: minmax(0, 1fr) / minmax(0, 1fr);
- flex: 1;
- width: 100%;
- height: 100%;
- min-height: 0;
-}
-
-.custom-view-frames > .custom-view-frame {
- grid-area: 1 / 1;
-}
-
-.custom-view-frame[data-incoming] {
- visibility: hidden;
-}
-
-.custom-view-frame {
- flex: 1;
- width: 100%;
- height: 100%;
- min-height: 0;
- border: 0;
- background: var(--bg);
-}
-
-.html-note-viewer__frame {
- flex: 1;
- width: 100%;
- height: 0;
- min-height: 0;
- border: 0;
- background: white;
-}
-
-@media (max-width: 700px) {
- .html-note-viewer__state {
- display: none;
- }
-}
-
-.ontology-pane__refresh-status {
- position: sticky;
- z-index: 2;
- top: 0;
- padding: 3px var(--sp-4);
- border-bottom: 1px solid var(--border);
- background: var(--surface-alt);
- color: var(--text-faint);
- font-size: var(--fs-xs);
-}
-
-/* The refreshing pill floats over the content so a refetch does not shift it. */
-.ontology-pane__refresh-status:not(.is-error) {
- width: max-content;
- height: 22px;
- margin: 0 0 -22px auto;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- line-height: 14px;
-}
-
-.ontology-pane__refresh-status.is-error {
- color: var(--accent-ink);
- background: var(--accent-soft);
-}
-
-.notes-shell__panel.is-active {
- position: relative;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- visibility: visible;
- pointer-events: auto;
-}
-
-.notes-note-tab {
- display: flex;
- flex: 1 1 auto;
- flex-direction: column;
- min-height: 0;
-}
-.notes-crumbs {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 6px;
- margin-bottom: var(--sp-4);
- color: var(--text-muted);
- font-size: var(--fs-sm);
-}
-
-.notes-crumbs button {
- padding: 0;
- border: 0;
- background: transparent;
- color: var(--link);
- font: inherit;
- cursor: pointer;
-}
-
-.notes-crumbs button:hover {
- text-decoration: underline;
-}
-
-/* Notes Home keeps one graph mounted while the compact information band changes. */
-.home-workspace,
-.home-workspace__body,
-.home-graph-layout {
- width: 100%;
- height: 100%;
- min-width: 0;
- min-height: 0;
-}
-
-.home-workspace,
-.home-graph-layout {
- display: flex;
- flex-direction: column;
- overflow: hidden;
-}
-
-.home-workspace__header-slot:empty {
- display: none;
-}
-
-.home-workspace__header-slot {
- flex: none;
- min-width: 0;
-}
-
-/*
- * One fixed-height header serves Home, type homes, and type tables, so
- * switching between them never moves the body below it.
- */
-.ontology-home__hero {
- display: grid;
- /* The title keeps room; the stats and view switcher shrink into the rest. */
- grid-template-columns: minmax(min(16rem, 40%), 1fr) minmax(0, auto);
- align-items: center;
- gap: 20px;
- height: 68px;
- padding: 0 16px;
- border-bottom: 1px solid var(--border);
- background: var(--surface);
-}
-
-.ontology-home__hero-title {
- min-width: 0;
-}
-
-.ontology-home__hero-heading {
- display: flex;
- align-items: baseline;
- gap: 10px;
- min-width: 0;
-}
-
-.ontology-home__hero-title h2 {
- min-width: 0;
- margin: 0;
- overflow: hidden;
- color: var(--text);
- font-family: var(--font-display);
- font-size: var(--fs-xl);
- line-height: 1.2;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.ontology-home__hero-eyebrow {
- flex: none;
- color: var(--text-faint);
- font-size: var(--fs-xs);
-}
-
-.ontology-home__hero-link {
- color: var(--text-muted);
- font-family: var(--font-mono);
- text-decoration: none;
-}
-
-.ontology-home__hero-link:hover,
-.ontology-home__hero-link:focus-visible {
- color: var(--link);
- text-decoration: underline;
-}
-
-.ontology-home__hero-title p {
- display: -webkit-box;
- max-width: 110ch;
- margin: 3px 0 0;
- overflow: hidden;
- color: var(--text-muted);
- font-size: var(--fs-sm);
- line-height: 1.3;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-}
-
-.ontology-home__hero-stats {
- display: flex;
- align-items: center;
- justify-content: flex-end;
- gap: 14px;
- min-width: 0;
-}
-
-.ontology-home__stat {
- display: flex;
- align-items: baseline;
- gap: 4px;
- white-space: nowrap;
-}
-
-.ontology-home__stat b {
- color: var(--text);
- font-family: var(--font-mono);
- font-size: var(--fs-base);
- font-weight: 600;
-}
-
-.ontology-home__stat span {
- color: var(--text-faint);
- font-size: var(--fs-xs);
-}
-
-/* Recent / most linked / problems: three hairline-separated columns of fixed height. */
-.home-graph-layout > .ontology-home {
- flex: none;
- height: 98px;
- padding: 8px 16px 6px;
- overflow: hidden;
-}
-
-.ontology-home__band {
- display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
- height: 100%;
-}
-
-.ontology-home__section {
- min-width: 0;
- padding: 0 14px;
- border-left: 1px solid var(--border-faint);
-}
-
-.ontology-home__section:first-child {
- padding-left: 0;
- border-left: 0;
-}
-
-.ontology-home__section:last-child {
- padding-right: 0;
-}
-
-.ontology-home__card-head {
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- gap: 8px;
- margin-bottom: 2px;
-}
-
-.ontology-home__card-head h3 {
- margin: 0;
- font: var(--label-font);
- color: var(--label-color);
-}
-
-.ontology-home__link {
- padding: 0;
- border: 0;
- background: transparent;
- color: var(--text-muted);
- font: inherit;
- font-size: var(--fs-xs);
- cursor: pointer;
-}
-
-.ontology-home__link:hover,
-.ontology-home__link:focus-visible {
- color: var(--link);
- text-decoration: underline;
-}
-
-.ontology-home__list {
- display: flex;
- flex-direction: column;
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-.ontology-home__row {
- display: flex;
- align-items: center;
- gap: 8px;
- width: calc(100% + 8px);
- min-height: 22px;
- margin: 0 -4px;
- padding: 1px 4px;
- border: 0;
- border-radius: var(--r-sm);
- background: transparent;
- color: var(--text);
- font: inherit;
- font-size: var(--fs-sm);
- text-align: left;
- cursor: pointer;
-}
-
-.ontology-home__row:hover,
-.ontology-home__row:focus-visible {
- background: var(--bg-tint);
-}
-
-.ontology-home__row-title {
- flex: 1 1 auto;
- min-width: 0;
- overflow: hidden;
- font-weight: 500;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.ontology-home__row-pill {
- flex: none;
-}
-
-.ontology-home__row-meta {
- flex: none;
- color: var(--text-faint);
- font-family: var(--font-mono);
- font-size: var(--fs-xs);
- white-space: nowrap;
-}
-
-.ontology-home__section--problems .ontology-home__row-meta {
- color: var(--accent-ink);
-}
-
-.ontology-home__hero-loading,
-.ontology-home__empty-row {
- padding: 3px 0;
- color: var(--text-faint);
- font-size: var(--fs-sm);
-}
-
-.ontology-home__unavailable {
+.notes-crumbs {
display: flex;
+ flex-wrap: wrap;
align-items: center;
- justify-content: space-between;
- gap: 16px;
- padding: 8px 12px;
- border: 1px solid var(--warning);
- border-radius: var(--r-sm);
- background: var(--warning-soft);
- color: var(--warning-ink);
+ gap: 6px;
+ margin-bottom: var(--sp-4);
+ color: var(--text-muted);
font-size: var(--fs-sm);
}
-.ontology-home__unavailable p {
- margin: 2px 0 0;
-}
-
-.ontology-home__unavailable button {
- flex: none;
- padding: 3px 10px;
- border: 1px solid var(--warning-ink);
- border-radius: var(--r-sm);
- background: var(--surface);
- color: var(--warning-ink);
+.notes-crumbs button {
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--link);
font: inherit;
- font-weight: 700;
cursor: pointer;
}
-/* The graph is the dominant element: no card around it, only its own hairline frame. */
-.home-graph-layout__graph {
- position: relative;
- display: flex;
- flex: 1 1 auto;
- flex-direction: column;
- min-height: 0;
- margin: 0 16px 12px;
-}
-
-.home-graph-layout__graph > .ontology-home__card-head {
- flex: none;
- margin: 2px 0 4px;
-}
-
-.home-graph-layout__graph > .ontology-home__unavailable {
- flex: none;
- margin-bottom: 6px;
-}
-
-/* A refetch reports itself over the graph instead of pushing the canvas down. */
-.home-graph-layout__graph > .ontology-home__hero-loading {
- position: absolute;
- z-index: 3;
- top: 32px;
- left: 50%;
- padding: 2px 8px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--surface);
- font-size: var(--fs-xs);
- transform: translateX(-50%);
-}
-
-.ontology-home__hint {
- color: var(--text-faint);
- font-family: var(--font-mono);
- font-size: var(--fs-xs);
-}
-
-.ontology-home__graph-canvas {
- display: flex;
- flex: 1 1 auto;
- min-height: 0;
+.notes-crumbs button:hover {
+ text-decoration: underline;
}
-.home-graph-layout__graph .graph-container {
+/* Notes Home keeps one graph mounted while the compact information band changes. */
+.home-workspace,
+.home-workspace__body,
+.home-graph-layout {
+ width: 100%;
+ height: 100%;
+ min-width: 0;
min-height: 0;
}
-/* Keep the hover card above the two-line type legend at every Home width. */
-.home-graph-layout__graph .graph-type-legend {
- max-height: 82px;
- overflow-x: hidden;
- overflow-y: auto;
-}
-
-.home-graph-layout__graph .graph-hover {
- bottom: calc(var(--sp-3) + 82px + var(--sp-2));
- min-width: 0;
- width: min(280px, calc(100% - 2 * var(--sp-3)));
+.home-workspace,
+.home-graph-layout {
+ display: flex;
+ flex-direction: column;
overflow: hidden;
- z-index: 3;
}
-.home-graph-layout__graph .graph-hover-meta {
- min-width: 0;
- flex-wrap: wrap;
+.home-workspace__header-slot:empty {
+ display: none;
}
-.home-graph-layout__graph .graph-hover-kind,
-.home-graph-layout__graph .graph-hover-connections {
+.home-workspace__header-slot {
flex: none;
- white-space: nowrap;
-}
-
-.home-graph-layout__graph .graph-hover-id {
- min-width: 0;
- flex: 1 1 80px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-@media (prefers-reduced-motion: reduce) {
- .notes-tab,
- .panel-resize::after,
- .notes-left-rail .ontology-type-row-wrap,
- .notes-left-rail .ontology-type-row__collapse .notes-left-rail__icon {
- scroll-behavior: auto;
- transition: none;
- }
-}
-
-/* View switcher: standard views as segments, custom views behind one icon
- segment. Many or long names shrink and truncate instead of wrapping. */
-.view-selector {
- display: flex;
- flex: 0 1 auto;
min-width: 0;
}
-.view-selector > .segmented {
- max-width: 100%;
-}
-
-.view-selector > .view-preferences {
- margin-left: var(--sp-2);
- white-space: nowrap;
-}
-
-/* Controls for the selected view ("Reset to shared"), beside the selector. */
-.view-selector__trailing {
- display: inline-flex;
- flex: none;
+/*
+ * One fixed-height header serves Home, type homes, and type tables, so
+ * switching between them never moves the body below it.
+ */
+.ontology-home__hero {
+ display: grid;
+ /* The title keeps room; the stats and view switcher shrink into the rest. */
+ grid-template-columns: minmax(min(16rem, 40%), 1fr) minmax(0, auto);
align-items: center;
- gap: var(--sp-2);
- margin-left: var(--sp-2);
- white-space: nowrap;
-}
-
-.view-selector__trailing:empty {
- display: none;
-}
-
-.view-selector > .segmented > button {
- flex: 0 1 auto;
- min-width: 0;
-}
-
-.view-selector__label {
- min-width: 0;
- max-width: 24ch;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.view-selector__icon,
-.view-selector__check {
- flex: none;
- width: 12px;
- height: 12px;
-}
-
-.view-selector__chevron {
- flex: none;
- width: 10px;
- height: 10px;
- margin-right: -3px;
-}
-
-.view-selector__menu {
- position: fixed;
- z-index: 30;
- display: flex;
- flex-direction: column;
- min-width: 180px;
- max-width: 320px;
- padding: 3px;
- border: 1px solid var(--border-strong);
- border-radius: var(--r);
+ gap: 20px;
+ height: 68px;
+ padding: 0 16px;
+ border-bottom: 1px solid var(--border);
background: var(--surface);
- box-shadow: var(--shadow);
}
-.view-selector__menu > button {
- display: flex;
- align-items: center;
- gap: 6px;
- height: 26px;
- padding: 0 10px 0 6px;
- border: 0;
- border-radius: var(--r-sm);
- background: transparent;
- color: var(--text);
- font: 500 var(--fs-sm) / 1 var(--font-sans);
- text-align: left;
- white-space: nowrap;
- cursor: pointer;
-}
-
-.view-selector__menu > button:hover {
- background: var(--bg-tint);
-}
-
-.view-selector__menu > button:focus-visible {
- outline-offset: -2px;
-}
-
-.view-selector__menu > button[aria-checked="false"] .view-selector__check {
- visibility: hidden;
-}
-
-.view-selector__menu > button[aria-checked="true"] {
- font-weight: 700;
+.ontology-home__hero-title {
+ min-width: 0;
}
-/* Pane type scale (SPEC-0126 US6): a 16px semibold title, 13px labels,
- 14px values, and no 700 weights, for the record and the note's Info. */
-.notes-right-rail .view-record {
- padding: var(--sp-4) var(--sp-5) var(--sp-6);
- font-size: var(--fs-base);
+.ontology-home__hero-heading {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ min-width: 0;
}
-.notes-right-rail .view-record__title {
- font-size: var(--fs-lg);
- font-weight: 600;
- letter-spacing: -0.005em;
+.ontology-home__hero-title h2 {
+ min-width: 0;
+ margin: 0;
+ overflow: hidden;
+ color: var(--text);
+ font-family: var(--font-display);
+ font-size: var(--fs-xl);
+ line-height: 1.2;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-.notes-right-rail .view-record__fields dt,
-.notes-right-rail .view-record__reverse h4 {
- font-size: var(--fs-sm);
- font-weight: 500;
+.ontology-home__hero-eyebrow {
+ flex: none;
+ color: var(--text-faint);
+ font-size: var(--fs-xs);
}
-/* ---- Note reader measure ----
- The note reads in a 540px column centred in the panel (65–75 characters of
- 15px Inter). Percentages resolve against the pane's width. HTML notes run
- edge to edge. */
-.notes-shell .ontology-pane {
- --note-gutter: max(var(--sp-6), calc((100% - 540px) / 2));
+.ontology-home__hero-link {
+ color: var(--text-muted);
+ font-family: var(--font-mono);
+ text-decoration: none;
}
-.notes-shell .ontology-pane__main:not(.ontology-pane__main--html) {
- padding-inline: var(--note-gutter);
+.ontology-home__hero-link:hover,
+.ontology-home__hero-link:focus-visible {
+ color: var(--link);
+ text-decoration: underline;
}
-/* The control row is pane chrome, not prose: it runs edge to edge as an HTML
- note's does, so the path has the free width. */
-.notes-shell .ontology-pane__controls {
- padding-inline: var(--sp-6);
+.ontology-home__hero-title p {
+ display: -webkit-box;
+ max-width: 110ch;
+ margin: 3px 0 0;
+ overflow: hidden;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ line-height: 1.3;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
}
-.notes-shell .ontology-pane__main:not(.ontology-pane__main--html) .ontology-markdown {
- max-width: none;
+.ontology-home__hero-stats {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 14px;
+ min-width: 0;
}
-/* Prose and the editor's lines share the column's 540px measure, so editing
- keeps read mode's line breaks even where the column could grow. */
-.notes-shell .body-narrative :is(p, ul, ol, blockquote),
-.notes-shell .body-narrative--editor .cm-line {
- max-width: 540px;
+.ontology-home__stat {
+ display: flex;
+ align-items: baseline;
+ gap: 4px;
+ white-space: nowrap;
}
-/* One vertical rhythm in both modes. A blank source line is the paragraph
- gap (0.75em), list items sit on the 24px line grid, and a list that follows
- its lead-in line directly keeps no gap, as the editor shows it. */
-.notes-shell .body-narrative--editor .cm-line:has(> br:only-child) {
- line-height: 0.75em;
+.ontology-home__stat b {
+ color: var(--text);
+ font-family: var(--font-mono);
+ font-size: var(--fs-base);
+ font-weight: 600;
}
-.notes-shell .body-narrative li {
- margin: 0;
+.ontology-home__stat span {
+ color: var(--text-faint);
+ font-size: var(--fs-xs);
}
-.notes-shell .body-narrative :is(ul, ol) {
- margin: 0 0 0.75em;
- padding-left: 2em;
+/* Recent / most linked / problems: three hairline-separated columns of fixed height. */
+.home-graph-layout > .ontology-home {
+ flex: none;
+ height: 98px;
+ padding: 8px 16px 6px;
+ overflow: hidden;
}
-.notes-shell .body-narrative p:has(+ :is(ul, ol)) {
- margin-bottom: 0;
+.ontology-home__band {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ height: 100%;
}
-/* A wiki link in the editor takes read mode's metrics: the same hairline
- underline and no trailing glyph, so a line wraps where it did in read mode. */
-.notes-shell .body-narrative--editor .cm-atomic-wiki-link {
- text-decoration-color: var(--link-line);
- text-decoration-thickness: 1px;
- text-underline-offset: 2px;
+.ontology-home__section {
+ min-width: 0;
+ padding: 0 14px;
+ border-left: 1px solid var(--border-faint);
}
-.notes-shell .body-narrative--editor .cm-atomic-wiki-link .cm-atomic-link::after {
- content: none;
+.ontology-home__section:first-child {
+ padding-left: 0;
+ border-left: 0;
}
-/* Editing is a mode, cued by a neutral border-strong rule under the control
- row. The Editing chip names the mode; staged changes keep their
- separate labelled gold bar. */
-.notes-shell .ontology-pane.is-editing > .ontology-pane__header > .ontology-pane__controls {
- border-bottom: 2px solid var(--border-strong);
+.ontology-home__section:last-child {
+ padding-right: 0;
}
-/* The controls row is only as wide as the column: the path gives way, never
- the controls. */
-.notes-shell
- .ontology-pane__controls
- > :not(.ontology-pane__toolbar-path, .ontology-pane__controls-spacer) {
- flex: none;
- white-space: nowrap;
+.ontology-home__card-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 2px;
}
-/* ---- Note control bar ----
- The note's presentations (Structure | Markdown, plus saved views) read as
- one segmented control, like every other mode switch; the default view is
- named by the segment's tooltip, so its dot is not drawn here. Copy link is
- a ghost button, not a second bordered control. */
-.ontology-pane__controls .view-tabs {
- flex: none;
- gap: 2px;
- align-items: stretch;
- padding: 2px;
- overflow: hidden;
- border: 1px solid var(--border);
- border-radius: var(--r-md);
- background: var(--surface-sunk);
+.ontology-home__card-head h3 {
+ margin: 0;
+ font: var(--label-font);
+ color: var(--label-color);
}
-/* The chosen presentation is the shared raised segment (base.css .segmented):
- a surface fill with a border-strong edge on the tinted track, in both
- themes. Never a solid ink fill. */
-.ontology-pane__controls .view-tabs > button {
- height: 22px;
- padding: 0 9px;
- border: 1px solid transparent;
- border-radius: var(--r);
- font: 500 var(--fs-sm) / 1 var(--font-sans);
+.ontology-home__link {
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--text-muted);
+ font: inherit;
+ font-size: var(--fs-xs);
+ cursor: pointer;
}
-.ontology-pane__controls .view-tabs > button[aria-pressed="true"] {
- border-color: var(--border-strong);
- background: light-dark(var(--surface), var(--surface-strong));
- color: var(--text);
- font-weight: 600;
+.ontology-home__link:hover,
+.ontology-home__link:focus-visible {
+ color: var(--link);
+ text-decoration: underline;
}
-.ontology-pane__controls .view-tabs > button[aria-pressed="true"]::after,
-.ontology-pane__controls .view-selector__default {
- display: none;
+.ontology-home__list {
+ display: flex;
+ flex-direction: column;
+ margin: 0;
+ padding: 0;
+ list-style: none;
}
-.ontology-pane__controls .ontology-link-button {
- display: inline-flex;
+.ontology-home__row {
+ display: flex;
align-items: center;
- gap: 5px;
- height: 26px;
- padding: 0 var(--sp-2);
- border-color: transparent;
+ gap: 8px;
+ width: calc(100% + 8px);
+ min-height: 22px;
+ margin: 0 -4px;
+ padding: 1px 4px;
+ border: 0;
+ border-radius: var(--r-sm);
background: transparent;
- color: var(--text-muted);
+ color: var(--text);
+ font: inherit;
+ font-size: var(--fs-sm);
+ text-align: left;
+ cursor: pointer;
}
-.ontology-pane__controls .ontology-link-button:hover {
- border-color: transparent;
+.ontology-home__row:hover,
+.ontology-home__row:focus-visible {
background: var(--bg-tint);
- color: var(--text);
}
-.ontology-pane__controls .ontology-link-button svg {
- width: 14px;
- height: 14px;
+.ontology-home__row-title {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-/* ---- Note properties ----
- Properties share the prose measure, so the block's right edge lines up with
- the paragraphs under it. Labels take a 120px column; long text (a summary)
- runs full width under its label instead of in a narrow value column. */
-.notes-shell .ontology-pane .ontology-properties {
- max-width: 540px;
+.ontology-home__row-pill {
+ flex: none;
}
-.notes-shell .ontology-pane .ontology-properties__grid {
- grid-template-columns: 120px minmax(0, 1fr);
- column-gap: var(--sp-4);
+.ontology-home__row-meta {
+ flex: none;
+ color: var(--text-faint);
+ font-family: var(--font-mono);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
}
-.notes-shell .ontology-pane .ontology-properties__row.is-long > :is(dt, dd) {
- grid-column: 1 / -1;
+.ontology-home__section--problems .ontology-home__row-meta {
+ color: var(--accent-ink);
}
-.notes-shell .ontology-pane .ontology-properties__row.is-long > dd {
- padding-top: 0;
+.ontology-home__hero-loading,
+.ontology-home__empty-row {
+ padding: 3px 0;
+ color: var(--text-faint);
+ font-size: var(--fs-sm);
}
-/* Only properties longer than six lines need an own-row disclosure. */
-.notes-shell .ontology-pane .ontology-properties__preview-text {
- display: -webkit-box;
- min-width: 0;
- overflow: hidden;
- color: var(--text-muted);
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 6;
- line-clamp: 6;
+.ontology-home__unavailable {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 8px 12px;
+ border: 1px solid var(--warning);
+ border-radius: var(--r-sm);
+ background: var(--warning-soft);
+ color: var(--warning-ink);
+ font-size: var(--fs-sm);
}
-.notes-shell .ontology-pane .ontology-properties__preview-more {
- margin-top: var(--sp-2);
+.ontology-home__unavailable p {
+ margin: 2px 0 0;
}
-/* Field labels stay roman; an empty field reads faint, not italic. */
-.notes-shell .ontology-pane .ontology-properties__row.is-missing .ontology-properties__key {
- font-style: normal;
+.ontology-home__unavailable button {
+ flex: none;
+ padding: 3px 10px;
+ border: 1px solid var(--warning-ink);
+ border-radius: var(--r-sm);
+ background: var(--surface);
+ color: var(--warning-ink);
+ font: inherit;
+ font-weight: 700;
+ cursor: pointer;
}
-/* Inline code sits tight in its sentence: no padded gap inside parentheses. */
-.notes-shell .ontology-markdown :not(pre) > code {
- margin: 0;
- padding: 1px 3px;
+/* The graph is the dominant element: no card around it, only its own hairline frame. */
+.home-graph-layout__graph {
+ position: relative;
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ min-height: 0;
+ margin: 0 16px 12px;
}
-/* Info sections outrank their muted type groups and 14px links. */
-.notes-right-rail .ontology-sidebar-context__group h3 {
- margin-bottom: var(--section-gap);
- font: var(--section-font);
- color: var(--section-color);
+.home-graph-layout__graph > .ontology-home__card-head {
+ flex: none;
+ margin: 2px 0 4px;
}
-.notes-right-rail .rail-bucket + .rail-bucket {
- margin-top: var(--sp-3);
+.home-graph-layout__graph > .ontology-home__unavailable {
+ flex: none;
+ margin-bottom: 6px;
}
-.notes-right-rail
- :is(.rail-row__dir--incoming, .rail-row__dir--both, .rail-bucket__dir, .rail-direction__dir) {
- color: var(--text-faint);
+/* A refetch reports itself over the graph instead of pushing the canvas down. */
+.home-graph-layout__graph > .ontology-home__hero-loading {
+ position: absolute;
+ z-index: 3;
+ top: 32px;
+ left: 50%;
+ padding: 2px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--surface);
+ font-size: var(--fs-xs);
+ transform: translateX(-50%);
}
-/* Type metadata consistently starts below its linked title. */
-.notes-right-rail .rail-row:has(> :is(.rail-row__type, .rail-row__path)) {
- flex-wrap: wrap;
- row-gap: 0;
+.ontology-home__hint {
+ color: var(--text-faint);
+ font-family: var(--font-mono);
+ font-size: var(--fs-xs);
}
-.notes-right-rail .rail-row:has(> .rail-row__dir) {
- position: relative;
- padding-left: 20px;
+.ontology-home__graph-canvas {
+ display: flex;
+ flex: 1 1 auto;
+ min-height: 0;
}
-.notes-right-rail .rail-row > .rail-row__dir {
- position: absolute;
- top: 2px;
- left: 0;
- line-height: 19px;
+.home-graph-layout__graph .graph-container {
+ min-height: 0;
}
-.notes-right-rail .rail-row:has(> :is(.rail-row__type, .rail-row__path)) > button {
- flex: 1 0 auto;
- max-width: 100%;
+/* Keep the hover card above the two-line type legend at every Home width. */
+.home-graph-layout__graph .graph-type-legend {
+ max-height: 82px;
+ overflow-x: hidden;
+ overflow-y: auto;
}
-.notes-right-rail .rail-row > :is(.rail-row__type, .rail-row__path) {
- max-width: 100%;
+.home-graph-layout__graph .graph-hover {
+ bottom: calc(var(--sp-3) + 82px + var(--sp-2));
+ min-width: 0;
+ width: min(280px, calc(100% - 2 * var(--sp-3)));
+ overflow: hidden;
+ z-index: 3;
}
-.notes-right-rail .rail-row > .rail-row__type {
- flex-basis: 100%;
- color: var(--text-muted);
- font-size: var(--fs-sm);
- font-weight: 500;
+.home-graph-layout__graph .graph-hover-meta {
+ min-width: 0;
+ flex-wrap: wrap;
}
-.notes-right-rail .rail-row > button {
- text-decoration: none;
+
+.home-graph-layout__graph .graph-hover-kind,
+.home-graph-layout__graph .graph-hover-connections {
+ flex: none;
+ white-space: nowrap;
}
-.notes-right-rail .rail-row > button:is(:hover, :focus-visible) {
- text-decoration: underline;
- text-decoration-color: var(--link-line);
- text-underline-offset: 2px;
+.home-graph-layout__graph .graph-hover-id {
+ min-width: 0;
+ flex: 1 1 80px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-/* Workspace materials open from their heading row; the shared chevron
- follows the count and turns. Closed, the count names its unit. */
-.notes-right-rail .rail-materials > summary {
- display: block;
- list-style: none;
- cursor: pointer;
+@media (prefers-reduced-motion: reduce) {
+ .notes-tab,
+ .panel-resize::after,
+ .notes-left-rail .ontology-type-row-wrap,
+ .notes-left-rail .ontology-type-row__collapse .notes-left-rail__icon {
+ scroll-behavior: auto;
+ transition: none;
+ }
}
-.notes-right-rail .rail-materials > summary::-webkit-details-marker {
- display: none;
+/* View switcher: standard views as segments, custom views behind one icon
+ segment. Many or long names shrink and truncate instead of wrapping. */
+.view-selector {
+ display: flex;
+ flex: 0 1 auto;
+ min-width: 0;
}
-.notes-right-rail .rail-materials > summary > h3 {
- justify-content: flex-start;
- gap: var(--sp-2);
- min-height: 24px;
- margin: 0;
+.view-selector > .segmented {
+ max-width: 100%;
}
-.notes-right-rail .rail-materials > summary .ontology-sidebar-context__count {
- margin-left: auto;
+.view-selector > .view-preferences {
+ margin-left: var(--sp-2);
+ white-space: nowrap;
}
-.notes-right-rail .rail-materials > summary .disclosure-chevron {
- margin-right: -4px;
- color: var(--text-muted);
+/* Controls for the selected view ("Reset to shared"), beside the selector. */
+.view-selector__trailing {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ gap: var(--sp-2);
+ margin-left: var(--sp-2);
+ white-space: nowrap;
}
-.notes-right-rail .rail-materials[open] .rail-materials__unit {
+.view-selector__trailing:empty {
display: none;
}
-.notes-right-rail .rail-materials > summary:hover > h3 {
- color: var(--text);
+.view-selector > .segmented > button {
+ flex: 0 1 auto;
+ min-width: 0;
}
-.notes-right-rail .rail-materials > summary:focus-visible {
- outline: 2px solid var(--focus-ring);
- outline-offset: 2px;
- border-radius: var(--r-sm);
+.view-selector__label {
+ min-width: 0;
+ max-width: 24ch;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-.notes-right-rail .rail-materials[open] > summary {
- margin-bottom: var(--sp-1);
+.view-selector__icon,
+.view-selector__check {
+ flex: none;
+ width: 12px;
+ height: 12px;
}
-.notes-right-rail .rail-legend {
- display: flex;
- flex-wrap: wrap;
- gap: 2px var(--sp-4);
- margin: 0 0 var(--sp-2);
- color: var(--text-faint);
- font-size: var(--fs-sm);
- font-weight: 500;
+.view-selector__chevron {
+ flex: none;
+ width: 10px;
+ height: 10px;
+ margin-right: -3px;
}
-.notes-right-rail .rail-legend__dir {
- margin-right: 3px;
- font-weight: 600;
+.view-selector__menu {
+ position: fixed;
+ z-index: 30;
+ display: flex;
+ flex-direction: column;
+ min-width: 180px;
+ max-width: 320px;
+ padding: 3px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r);
+ background: var(--surface);
+ box-shadow: var(--shadow);
}
-/* An untyped note names its folder where a typed one names its type. */
-.notes-right-rail .rail-row__path {
- flex: 0 1 auto;
- max-width: 45%;
- overflow: hidden;
- color: var(--text-faint);
- font-family: var(--font-mono);
- font-size: var(--fs-xs);
- direction: rtl;
+.view-selector__menu > button {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ height: 26px;
+ padding: 0 10px 0 6px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: transparent;
+ color: var(--text);
+ font: 500 var(--fs-sm) / 1 var(--font-sans);
text-align: left;
- text-overflow: ellipsis;
white-space: nowrap;
+ cursor: pointer;
}
-.notes-right-rail :is(.rail-row__dir, .rail-bucket__dir, .rail-direction__dir) {
- width: 16px;
- font-size: var(--fs-lg);
- font-weight: 500;
- line-height: 1;
+.view-selector__menu > button:hover {
+ background: var(--bg-tint);
}
-.notes-right-rail .rail-bucket .rail-row:not(:has(.rail-row__dir)) {
- padding-left: 20px;
+.view-selector__menu > button:focus-visible {
+ outline-offset: -2px;
}
-/* Relations split into compact Incoming and Outgoing groups. */
-.notes-right-rail .rail-direction {
- display: flex;
- align-items: center;
- gap: var(--sp-1);
- margin: 0 0 2px;
- color: var(--text-faint);
- font: 500 var(--fs-sm) / 1.3 var(--font-sans);
+.view-selector__menu > button[aria-checked="false"] .view-selector__check {
+ visibility: hidden;
}
-.notes-right-rail section + section > .rail-direction {
- margin-top: var(--sp-3);
+.view-selector__menu > button[aria-checked="true"] {
+ font-weight: 700;
}
-.notes-right-rail .rail-direction__dir {
- text-align: center;
+/* Pane type scale (SPEC-0126 US6): a 16px semibold title, 13px labels,
+ 14px values, and no 700 weights, for the record and the note's Info. */
+.notes-right-rail .view-record {
+ padding: var(--sp-4) var(--sp-5) var(--sp-6);
+ font-size: var(--fs-base);
}
-.notes-right-rail .rail-direction ~ .rail-bucket .rail-bucket__head {
- padding-left: 20px;
+.notes-right-rail .view-record__title {
+ font-size: var(--fs-lg);
+ font-weight: 600;
+ letter-spacing: -0.005em;
}
-.notes-right-rail .rail-bucket__head {
- color: var(--text-muted);
+.notes-right-rail .view-record__fields dt,
+.notes-right-rail .view-record__reverse h4 {
+ font-size: var(--fs-sm);
font-weight: 500;
}
@@ -2433,174 +1415,3 @@
background: var(--surface);
box-shadow: 0 0 0 1px var(--focus-ring);
}
-
-/* ---- HTML note head ----
- With a preview showing, the host header lives in the 40px control row:
- the type, a 14/600 title, its identity, the metadata disclosure, then the
- presentation switch and the viewer's Refresh and Open. The authored page
- starts right below and carries its own heading. */
-.notes-shell .ontology-pane__controls:has(> .ontology-pane__html-head) {
- overflow: visible;
-}
-
-.notes-shell .ontology-pane__controls > .ontology-pane__html-head {
- display: flex;
- flex: 0 1 auto;
- align-items: center;
- gap: var(--sp-4);
- min-width: 0;
- white-space: nowrap;
-}
-
-.notes-shell .ontology-pane__html-head > .ontology-identity {
- flex: 0 1 auto;
- flex-flow: row nowrap;
- align-items: center;
- gap: var(--sp-3);
- min-width: 0;
- padding: 0;
- background: transparent;
-}
-
-/* The tab and the authored page already carry the title, and Metadata lists
- it in full, so the row keeps it for assistive tech only. */
-.notes-shell .ontology-pane__html-head .ontology-identity__title {
- position: absolute;
- width: 1px;
- height: 1px;
- overflow: hidden;
- clip-path: inset(50%);
- white-space: nowrap;
-}
-
-.notes-shell .ontology-pane__html-head .ontology-identity__row {
- flex: 0 1 auto;
- flex-wrap: nowrap;
- min-width: 0;
-}
-
-/* With the title hidden, the short ID names the document beside its type
- and status. It is the one part that gives way, before the actions do. */
-.notes-shell .ontology-pane__html-head .ontology-identity__slot--id {
- flex: 0 1 auto;
- min-width: 6ch;
- overflow: hidden;
-}
-
-.notes-shell .ontology-pane__html-head .ontology-identity__slot--id * {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.notes-shell .ontology-pane__html-head .ontology-identity__flex {
- display: none;
-}
-
-/* The metadata opens as a panel over the page instead of pushing it down. */
-.notes-shell .ontology-pane__html-head > .ontology-properties--html-root {
- position: relative;
- flex: none;
- max-width: none;
- margin: 0;
- padding: 0;
- border: 0;
-}
-
-/* The ghost button's padding bleeds into the row gap, so the ID keeps its
- room. */
-.notes-shell .ontology-pane__html-head .ontology-properties__html-summary {
- margin: 0 0 0 -8px;
- color: var(--text-muted);
-}
-
-.notes-shell .ontology-pane__html-head .ontology-properties__html-body {
- position: absolute;
- top: calc(100% + 6px);
- right: 0;
- z-index: 20;
- width: min(520px, 80vw);
- max-height: min(70vh, 640px);
- padding: var(--sp-3) var(--sp-4);
- overflow: auto;
- border: 1px solid var(--border-strong);
- border-radius: var(--r-lg);
- background: var(--surface);
- box-shadow: var(--shadow);
-}
-
-.notes-shell
- .ontology-pane__html-head
- .ontology-properties__html-body
- :is(input, select, textarea) {
- max-width: 100%;
-}
-
-.notes-shell .ontology-pane__html-actions {
- display: flex;
- flex: none;
- align-items: center;
- gap: var(--sp-1);
- margin-right: calc(-1 * var(--sp-2));
- color: var(--text-faint);
- font-size: var(--fs-sm);
-}
-
-.notes-shell .ontology-pane__html-actions:empty {
- display: none;
-}
-
-/* The page starts directly under the control row. */
-.notes-shell .ontology-pane__main--html {
- padding-top: 0;
-}
-
-.notes-shell .ontology-pane__main--html > .ontology-markdown--html {
- margin-top: 0;
-}
-
-/* Problems, clean: the checks that ran, listed in place of an empty panel.
- Each row leads with the check's name, then a compact success mark and what
- the check found; the zero issue count is already in the strip. */
-.validation-checks {
- padding: var(--sp-2) 0;
-}
-
-.validation-checks__list {
- display: grid;
- grid-template-columns: minmax(140px, max-content) minmax(0, 1fr);
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-.validation-checks__list li {
- display: contents;
-}
-
-.validation-checks__list li > * {
- display: flex;
- align-items: center;
- min-height: 34px;
- padding-right: var(--sp-7);
- border-bottom: 1px solid var(--border-faint);
- font-size: var(--fs-base);
-}
-
-.validation-checks__list strong {
- font-weight: 500;
-}
-
-.validation-checks__result {
- gap: var(--sp-2);
- overflow: hidden;
- color: var(--text-muted);
- white-space: nowrap;
-}
-
-.validation-checks__mark {
- flex: none;
- color: var(--success);
- font-weight: 700;
-}
diff --git a/web/src/search.css b/web/src/search.css
new file mode 100644
index 000000000..9cd99620a
--- /dev/null
+++ b/web/src/search.css
@@ -0,0 +1,373 @@
+/* Search workspace: moved verbatim from notes-shell.css. */
+
+/* ---- Search ----
+ One centred column shared by the header, the banner, the status line, and
+ the results. The header follows the shared view header: an 18/700 title,
+ its count, and the query as the muted one-line description, then the
+ filters on one row. */
+.search-workspace {
+ --search-measure: 720px;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+ overflow: auto;
+ background: var(--surface);
+}
+
+.search-workspace > * {
+ flex: none;
+ width: min(100% - 2 * var(--gutter), 960px);
+ margin-inline: auto;
+}
+
+.search-workspace__header {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: var(--sp-5) 0 var(--sp-4);
+ border-bottom: 1px solid var(--border);
+}
+
+.search-workspace__title-row {
+ display: flex;
+ align-items: baseline;
+ gap: var(--sp-3);
+ min-width: 0;
+}
+
+.search-workspace h1 {
+ flex: none;
+ margin: 0;
+ color: var(--text);
+ font: 700 var(--fs-xl) / 1.2 var(--font-sans);
+ letter-spacing: -0.01em;
+}
+
+.search-workspace__query {
+ min-width: 0;
+ margin: 0;
+ overflow: hidden;
+ color: var(--text-muted);
+ font-size: var(--fs-base);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.search-workspace h1 mark {
+ color: inherit;
+ background: transparent;
+}
+
+.search-workspace__filters {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--sp-3);
+}
+
+.search-workspace__filters label {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--sp-2);
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+}
+
+.search-workspace__filters select {
+ width: 180px;
+}
+
+.search-workspace__filters input {
+ width: 220px;
+}
+
+/* "Anywhere" is a hint, not a value: faint, so it never reads as a choice. */
+.search-workspace__filters input::placeholder {
+ color: var(--text-faint);
+ opacity: 1;
+}
+
+.search-workspace__clear {
+ height: 26px;
+ padding: 0 var(--sp-2);
+ border: 0;
+ border-radius: var(--r-md);
+ background: transparent;
+ color: var(--text-muted);
+ font: 500 var(--fs-sm) / 1 var(--font-sans);
+ cursor: pointer;
+}
+
+.search-workspace__clear:hover {
+ background: var(--bg-tint);
+ color: var(--text);
+}
+
+/* The banner: one 36px tinted band with a mark, text, and its action; the
+ individual source messages wait behind Details. */
+.search-workspace__warnings {
+ display: flex;
+ flex-direction: column;
+ gap: var(--sp-2);
+ margin-top: var(--sp-4);
+}
+
+.search-workspace__banner {
+ border: 1px solid color-mix(in srgb, var(--warning) 55%, transparent);
+ border-radius: var(--r-md);
+ background: var(--warning-soft);
+ color: var(--warning-ink);
+ font-size: var(--fs-sm);
+}
+
+.search-workspace__banner.is-alert {
+ border-color: var(--accent-line);
+ background: var(--accent-soft);
+ color: var(--accent-ink);
+}
+
+.search-workspace__banner-row {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-2);
+ min-height: 34px;
+ padding: 0 var(--sp-2) 0 var(--sp-3);
+}
+
+.search-workspace__banner-mark {
+ flex: none;
+ width: 15px;
+ height: 15px;
+}
+
+.search-workspace__banner-text {
+ flex: 1;
+ min-width: 0;
+ padding: var(--sp-1) 0;
+ color: var(--text);
+}
+
+.search-workspace__banner-row > button {
+ flex: none;
+ height: 24px;
+ padding: 0 var(--sp-2);
+ border: 0;
+ border-radius: var(--r-sm);
+ background: transparent;
+ color: inherit;
+ font: 600 var(--fs-sm) / 1 var(--font-sans);
+ cursor: pointer;
+}
+
+.search-workspace__banner-row > button:hover {
+ background: color-mix(in srgb, currentcolor 10%, transparent);
+}
+
+.search-workspace__banner-details {
+ margin: 0;
+ padding: 0 var(--sp-3) var(--sp-3) calc(var(--sp-3) + 15px + var(--sp-2));
+ color: var(--text-muted);
+ line-height: 1.45;
+ list-style: none;
+}
+
+.search-workspace__banner-details li + li {
+ margin-top: var(--sp-1);
+}
+
+.search-workspace__meta,
+.search-workspace__state,
+.search-workspace__end {
+ margin-top: var(--sp-4);
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+}
+
+.search-workspace__meta {
+ display: flex;
+ justify-content: space-between;
+ gap: var(--sp-3);
+}
+
+/* One plain line: "Showing 40 · Medium confidence ⓘ", with
+ figures in tabular Inter. It wraps rather than clipping the info tip. */
+.search-workspace__status {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ min-width: 0;
+ font-variant-numeric: tabular-nums;
+}
+
+.search-workspace__status > span {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.search-workspace__status > span:not(:first-child)::before {
+ content: "·";
+ margin: 0 var(--sp-2);
+ color: var(--text-faint);
+}
+
+.search-workspace__status .field-editor__info-tip {
+ color: var(--text);
+}
+
+.search-workspace__state {
+ display: flex;
+ align-items: center;
+ flex-direction: column;
+ gap: var(--sp-2);
+ padding: var(--sp-8) var(--sp-4);
+ text-align: center;
+}
+
+.search-workspace__state strong {
+ color: var(--text);
+ font-size: var(--fs-lg);
+ font-weight: 600;
+}
+
+.search-workspace__state button,
+.search-workspace__load-more {
+ height: 28px;
+ padding: 0 11px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-md);
+ background: var(--surface);
+ color: var(--text);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+ cursor: pointer;
+}
+
+.search-workspace__state button:hover,
+.search-workspace__load-more:hover {
+ background: var(--bg-tint);
+}
+
+.search-workspace__results {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: 0;
+ margin-top: var(--sp-2);
+ padding: 0;
+ border-top: 1px solid var(--border);
+ list-style: none;
+}
+
+.search-workspace__result {
+ padding: 12px 0;
+ border-bottom: 1px solid var(--border-faint);
+}
+
+.search-workspace__result-kind {
+ flex: 0 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font: 400 var(--fs-sm) / 1.4 var(--font-sans);
+}
+
+.search-workspace__result-link {
+ display: block;
+ max-width: 100%;
+ padding: 0;
+ overflow: hidden;
+ border: 0;
+ background: transparent;
+ font: 500 var(--fs-base) / 1.35 var(--font-sans);
+ text-align: left;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ cursor: pointer;
+}
+
+/* A result title is a quiet link (.link-title): ink, underlined on hover
+ and keyboard focus. */
+.search-workspace__result-link:hover,
+.search-workspace__result-link:focus-visible {
+ text-decoration: underline;
+ text-decoration-color: var(--link-line);
+ text-underline-offset: 2px;
+}
+
+.search-workspace__result-link--code {
+ font: 500 var(--fs-base) / 1.35 var(--font-mono);
+}
+
+/* Metadata shares one line; only the path uses mono and gives way in its middle. */
+.search-workspace__result-source {
+ display: flex;
+ align-items: baseline;
+ gap: 4px;
+ min-width: 0;
+ margin-top: 4px;
+ color: var(--text-muted);
+ font: 400 var(--fs-sm) / 1.4 var(--font-sans);
+ white-space: nowrap;
+}
+
+.search-workspace__result-source > .middle-truncate {
+ flex: 0 1 auto;
+ font: 400 var(--fs-xs) / 1.4 var(--font-mono);
+}
+
+/* Note excerpts read as prose at the shared measure, inline code as code. */
+.search-workspace__result p {
+ max-width: var(--search-measure);
+ margin: 8px 0 0;
+ color: var(--text-muted);
+ font-size: var(--fs-base);
+ line-height: 1.5;
+}
+
+.search-workspace__result p code {
+ color: var(--text-muted);
+ font-family: var(--font-mono);
+ font-size: 0.9em;
+}
+
+.search-workspace__result p.is-missing {
+ color: var(--text-faint);
+ font-style: italic;
+}
+
+/* Code evidence keeps its source lines in mono on the tint: long lines
+ scroll sideways instead of breaking into fragments. */
+.search-workspace__code {
+ box-sizing: border-box;
+ width: min(100%, var(--search-measure));
+ margin: 8px 0 0;
+ padding: var(--sp-3);
+ overflow: auto;
+ border-radius: var(--r-md);
+ background: var(--bg-tint);
+ color: var(--text);
+ font: 400 var(--fs-sm) / 1.5 var(--font-mono);
+ tab-size: 4;
+ white-space: pre;
+}
+
+/* Matches share Finder's weight; only navigable Finder titles underline. */
+.search-workspace__result mark {
+ background: none;
+ color: inherit;
+ font-weight: 650;
+ text-decoration: none;
+}
+
+.search-workspace__load-more,
+.search-workspace__end {
+ width: auto;
+ margin-block: var(--sp-4) var(--sp-6);
+}
+
+.search-workspace__end {
+ color: var(--text-faint);
+ text-align: center;
+}
diff --git a/web/src/tasks-detail.css b/web/src/tasks-detail.css
new file mode 100644
index 000000000..77f845a43
--- /dev/null
+++ b/web/src/tasks-detail.css
@@ -0,0 +1,304 @@
+/* ---- History and run, side by side ---- */
+
+.tasks-split {
+ display: grid;
+ flex: 1;
+ grid-template-columns: minmax(280px, 340px) minmax(0, 1fr);
+ min-height: 0;
+}
+
+.task-history {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ border-right: 1px solid var(--border);
+}
+
+.task-history__head,
+.task-timeline__head h3 {
+ margin: 0;
+ color: var(--label-color);
+ font: var(--label-font);
+}
+
+.task-history__head {
+ padding: 14px 18px 6px;
+}
+
+.task-history__head span {
+ margin-left: 4px;
+ font-weight: 500;
+ font-variant-numeric: tabular-nums;
+}
+
+.task-history__list {
+ flex: 1;
+ min-height: 0;
+ margin: 0;
+ padding: 0 8px 12px;
+ overflow: auto;
+ list-style: none;
+ scrollbar-width: thin;
+}
+
+.task-history__row {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 2px 10px;
+ width: 100%;
+ padding: 7px 10px;
+ border: 0;
+ border-radius: var(--r-md);
+ background: transparent;
+ color: var(--text);
+ text-align: left;
+ cursor: pointer;
+}
+
+.task-history__row:hover {
+ background: var(--bg-tint);
+}
+
+.task-history__row.is-selected {
+ background: var(--selection);
+ box-shadow: inset 3px 0 0 var(--selection-edge);
+}
+
+.task-history__mark {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.task-history__time {
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ font-variant-numeric: tabular-nums;
+}
+
+.task-history__facts {
+ display: flex;
+ grid-column: 1 / -1;
+ gap: 12px;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ font-variant-numeric: tabular-nums;
+}
+
+.task-history__facts:empty {
+ display: none;
+}
+
+/* A check that found nothing needed is a quiet single line. */
+.task-history__row.is-quiet {
+ padding-block: 3px;
+ color: var(--text-faint);
+}
+
+.task-history__row.is-quiet .status-mark {
+ font-weight: 400;
+}
+
+.task-history__row.is-quiet .task-history__time {
+ color: var(--text-faint);
+}
+
+/* ---- Run view ---- */
+
+.task-run {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+}
+
+.task-run--empty {
+ align-items: center;
+ justify-content: center;
+}
+
+.task-run__head {
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: 8px 14px;
+ min-height: 44px;
+ padding: 0 24px;
+ border-bottom: 1px solid var(--border-faint);
+}
+
+.task-run__stage,
+.task-run__when {
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ font-variant-numeric: tabular-nums;
+}
+
+.task-run__id {
+ margin-left: auto;
+ overflow: hidden;
+ color: var(--text-faint);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.task-run__scroll {
+ flex: 1;
+ min-height: 0;
+ padding: 18px 24px 40px;
+ overflow: auto;
+ scrollbar-color: var(--border-strong) transparent;
+ scrollbar-width: thin;
+}
+
+.task-result,
+.task-timeline {
+ max-width: 880px;
+}
+
+.task-result {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ padding-bottom: 18px;
+ border-bottom: 1px solid var(--border-faint);
+}
+
+.task-result__message {
+ max-width: 72ch;
+ font-size: var(--fs-md);
+ line-height: 1.6;
+}
+
+.task-result__message > :first-child,
+.task-message > :first-child,
+.task-thinking > :first-child {
+ margin-top: 0;
+}
+
+.task-result__message > :last-child,
+.task-message > :last-child,
+.task-thinking > :last-child {
+ margin-bottom: 0;
+}
+
+.task-result__message :is(h1, h2, h3, h4) {
+ margin: 18px 0 6px;
+ font-size: var(--fs-lg);
+ font-weight: 600;
+ line-height: 1.3;
+}
+
+.task-result__message p,
+.task-message p,
+.task-thinking p {
+ margin: 0 0 0.6em;
+}
+
+:is(.task-result__message, .task-message, .task-thinking) :is(ul, ol) {
+ margin: 0 0 0.6em;
+ padding-left: 22px;
+}
+
+:is(.task-result__message, .task-message, .task-thinking) code {
+ padding: 1px 4px;
+ border-radius: var(--r-sm);
+ background: var(--surface-sunk);
+ font-family: var(--font-mono);
+ font-size: 0.88em;
+}
+
+:is(.task-result__message, .task-message, .task-thinking) pre {
+ padding: 10px 12px;
+ overflow: auto;
+ border-radius: var(--r-md);
+ background: var(--surface-sunk);
+}
+
+:is(.task-result__message, .task-message, .task-thinking) pre code {
+ padding: 0;
+ background: none;
+}
+
+.task-result__pending {
+ margin: 0;
+ color: var(--text-muted);
+}
+
+.task-facts {
+ display: grid;
+ grid-template-columns: 112px minmax(0, 1fr);
+ gap: 0 12px;
+ margin: 0;
+}
+
+.task-facts dt,
+.task-facts dd {
+ min-height: 30px;
+ padding: 5px 0;
+}
+
+.task-facts dt {
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+ line-height: 20px;
+}
+
+.task-facts dd {
+ min-width: 0;
+ margin: 0;
+ line-height: 20px;
+}
+
+.task-facts code,
+.task-paths code,
+.task-copy code {
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+}
+
+.task-facts__number {
+ font-variant-numeric: tabular-nums;
+}
+
+.task-facts__aside {
+ margin-left: 10px;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+}
+
+.task-paths {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.task-paths li + li {
+ margin-top: 2px;
+}
+
+.task-copy {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ max-width: 100%;
+}
+
+.task-copy code {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.task-icon-button {
+ height: 24px;
+ margin-top: -2px;
+ padding: 0 5px;
+}
+
+.task-copy__done:empty {
+ display: none;
+}
diff --git a/web/src/tasks-overview.css b/web/src/tasks-overview.css
new file mode 100644
index 000000000..9456ba368
--- /dev/null
+++ b/web/src/tasks-overview.css
@@ -0,0 +1,169 @@
+/* ---- Overview table ---- */
+
+.tasks-overview {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.tasks-overview .view-header__title-row {
+ padding-right: var(--gutter);
+}
+
+.tasks-overview__body {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ scrollbar-width: thin;
+}
+
+.task-table {
+ width: 100%;
+ table-layout: fixed;
+ margin-top: 8px;
+ border-collapse: collapse;
+}
+
+.task-table thead th {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ height: 34px;
+ padding: 0 10px;
+ border-bottom: 1px solid var(--border);
+ background: var(--surface);
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+ text-align: left;
+ white-space: nowrap;
+}
+
+.task-table :is(th, td):first-child {
+ box-sizing: border-box;
+ width: clamp(280px, 32cqw, 440px);
+ padding-left: var(--gutter);
+}
+
+.task-table :is(th, td):nth-child(2) {
+ box-sizing: border-box;
+ width: 176px;
+ padding-right: 16px;
+}
+
+.task-table :is(th, td):last-child {
+ padding-right: var(--gutter);
+}
+
+/* Rows hold two lines: the task name over its id. */
+.task-table tbody :is(th, td) {
+ height: 52px;
+ padding: 8px 10px;
+ vertical-align: top;
+ border-bottom: 1px solid var(--border-faint);
+ font-weight: 400;
+ text-align: left;
+ white-space: nowrap;
+}
+
+.task-table tbody tr:hover {
+ background: var(--bg-tint);
+}
+
+/* The task name is a quiet teal link; its id is a muted mono second line. */
+.task-table__open {
+ display: inline-flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 1px;
+ max-width: 100%;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ font-weight: 500;
+ text-align: left;
+ cursor: pointer;
+}
+
+.task-table__open:is(:hover, :focus-visible) .link-quiet {
+ text-decoration: underline;
+ text-decoration-color: var(--link-line);
+ text-underline-offset: 2px;
+}
+
+/* The row's secondary line: the task id, then a new task's quiet "What it
+ does" disclosure, so the row's prominent action stays the inbox one. */
+.task-table__meta {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-2);
+ margin-top: 1px;
+ font-size: var(--fs-sm);
+}
+
+.task-table__meta code {
+ font-size: var(--fs-xs);
+ font-weight: 400;
+}
+
+.task-table__meta code,
+.task-table__aside,
+.task-table__none {
+ color: var(--text-muted);
+}
+
+/* Intervals and relative times are sans, like every relative time. */
+.task-table__time,
+.task-table__due {
+ font-variant-numeric: tabular-nums;
+}
+
+.task-table__due.is-due {
+ color: var(--info-ink);
+ font-weight: 500;
+}
+
+.task-table__last {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.task-table__aside {
+ font-size: var(--fs-sm);
+}
+
+.task-table__run-link {
+ font-weight: 500;
+ white-space: nowrap;
+}
+
+.task-table__local {
+ display: inline-flex;
+ margin-left: 12px;
+ vertical-align: baseline;
+ font-weight: 400;
+}
+
+/* A Test once run: the neutral chip, so a test never reads as a status. */
+.task-test-chip {
+ display: inline-flex;
+ align-items: center;
+ padding: 1px 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--surface-sunk);
+ color: var(--text-muted);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ line-height: 1.35;
+ white-space: nowrap;
+}
+
+.tasks-overview > * {
+ box-sizing: border-box;
+ width: 100%;
+ max-width: 1320px;
+ margin-inline: auto;
+}
diff --git a/web/src/tasks-timeline.css b/web/src/tasks-timeline.css
new file mode 100644
index 000000000..e5b810dd2
--- /dev/null
+++ b/web/src/tasks-timeline.css
@@ -0,0 +1,341 @@
+/* ---- Timeline ---- */
+
+.task-timeline {
+ padding-top: 16px;
+}
+
+.task-timeline__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ min-height: 28px;
+ margin-bottom: 4px;
+}
+
+.task-timeline__list {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.task-block {
+ border: 1px solid transparent;
+ border-radius: var(--r-md);
+}
+
+.task-block[open] {
+ margin-block: 4px;
+ border-color: var(--border);
+}
+
+.task-block__summary {
+ display: grid;
+ grid-template-columns: 16px 16px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 8px;
+ min-height: 34px;
+ padding: 0 10px 0 6px;
+ border-radius: calc(var(--r-md) - 1px);
+ color: var(--text);
+ list-style: none;
+ cursor: pointer;
+}
+
+.task-block__summary::-webkit-details-marker {
+ display: none;
+}
+
+.task-block__summary:hover {
+ background: var(--bg-tint);
+}
+
+.task-block__summary:focus-visible {
+ outline-offset: -2px;
+}
+
+.task-block[open] > .task-block__summary {
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+
+.task-block__chevron,
+.task-block__icon {
+ display: inline-flex;
+ color: var(--text-faint);
+}
+
+.task-block__title {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ min-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.task-block__label {
+ flex: none;
+ font-weight: 500;
+}
+
+.task-block__preview {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--text-muted);
+ text-overflow: ellipsis;
+}
+
+.task-block__preview--mono,
+.task-block__command {
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+}
+
+.task-block__command {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.task-block__meta {
+ display: inline-flex;
+ align-items: center;
+ gap: 12px;
+ font-size: var(--fs-sm);
+}
+
+.task-block__duration {
+ color: var(--text-muted);
+ font-variant-numeric: tabular-nums;
+}
+
+.task-block__body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px 12px 12px 36px;
+ border-top: 1px solid var(--border-faint);
+}
+
+.task-block__section h4 {
+ margin: 0 0 4px;
+ color: var(--label-color);
+ font: var(--label-font);
+}
+
+.task-block__empty,
+.task-block__cwd,
+.task-block__notice {
+ margin: 0;
+ color: var(--text-muted);
+ font-size: var(--fs-sm);
+}
+
+.task-block__cwd {
+ font-family: var(--font-mono);
+}
+
+.task-block__notice {
+ color: var(--warning-ink);
+}
+
+.task-output {
+ max-height: 380px;
+ margin: 0;
+ padding: 10px 12px;
+ overflow: auto;
+ border-radius: var(--r-md);
+ background: var(--surface-sunk);
+ color: var(--text);
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+ line-height: 1.55;
+ overflow-wrap: anywhere;
+ white-space: pre-wrap;
+ scrollbar-width: thin;
+}
+
+.task-thinking {
+ color: var(--text-muted);
+ line-height: 1.55;
+}
+
+.task-diff {
+ max-height: 420px;
+ overflow: auto;
+}
+
+.task-message {
+ max-width: 72ch;
+ padding: 6px 12px 8px 36px;
+ line-height: 1.55;
+}
+
+.task-message__label {
+ display: block;
+ margin-bottom: 2px;
+ color: var(--label-color);
+ font: var(--label-font);
+}
+
+.task-line {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0;
+ padding: 5px 12px 5px 36px;
+ font-size: var(--fs-sm);
+}
+
+.task-line--muted {
+ color: var(--text-muted);
+}
+
+.task-line .task-icon {
+ width: 14px;
+ height: 14px;
+ margin-left: -22px;
+}
+
+.task-line--live {
+ padding-top: 10px;
+}
+
+.task-error {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 4px 12px;
+ margin-block: 4px;
+ padding: 8px 12px;
+ border: 1px solid var(--accent-line);
+ border-radius: var(--r-md);
+ background: var(--accent-soft);
+}
+
+.task-error p {
+ flex: 1;
+ min-width: 200px;
+ margin: 0;
+ overflow-wrap: anywhere;
+}
+
+/* ---- Empty and loading ---- */
+
+.task-empty {
+ margin: 0;
+ padding: 14px 18px;
+ color: var(--text-muted);
+}
+
+.task-empty--page {
+ max-width: 60ch;
+ padding: 32px 24px;
+}
+
+.task-empty--page h3 {
+ margin: 0 0 6px;
+ color: var(--text);
+ font-size: var(--fs-lg);
+ font-weight: 600;
+}
+
+.task-empty--page p {
+ margin: 0 0 12px;
+}
+
+.task-empty code {
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+}
+
+.task-skeleton {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px 18px;
+ animation: task-skeleton-in 0.2s 0.15s both;
+}
+
+.task-skeleton span {
+ height: 14px;
+ border-radius: var(--r);
+ background: var(--placeholder);
+}
+
+.task-skeleton span:nth-child(2n) {
+ width: 72%;
+}
+
+.task-skeleton--page {
+ padding: 24px;
+}
+
+@keyframes task-skeleton-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .task-block__chevron .task-icon,
+ .task-skeleton {
+ transition: none;
+ animation: none;
+ }
+}
+
+/* A new task's row carries its notice: a "New" tag and a quiet "What it
+ does" toggle that opens the purpose in a full-width row below. "New" is
+ the neutral chip (as .type-chip): a fact, not a status. */
+.task-table__new-tag {
+ padding: 0 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--surface-sunk);
+ color: var(--text-muted);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ line-height: 16px;
+}
+
+.task-notice__more {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--text-muted);
+ font: inherit;
+ cursor: pointer;
+}
+
+.task-notice__more:is(:hover, :focus-visible) {
+ color: var(--text);
+}
+
+.task-table tr.is-expanded > * {
+ border-bottom-color: transparent;
+}
+
+.task-table tbody .task-table__purpose > td {
+ height: auto;
+ padding-top: 0;
+ padding-bottom: var(--sp-3);
+ white-space: normal;
+}
+
+.task-table__purpose:hover {
+ background: transparent;
+}
+
+.task-table__purpose p {
+ max-width: 72ch;
+ margin: 0 0 var(--sp-3);
+ color: var(--text-muted);
+}
+
+.task-notice__sentence::first-letter {
+ text-transform: uppercase;
+}
diff --git a/web/src/tasks.css b/web/src/tasks.css
index c8ee15d6a..7781e5d4a 100644
--- a/web/src/tasks.css
+++ b/web/src/tasks.css
@@ -1,3 +1,7 @@
+@import "./tasks-detail.css";
+@import "./tasks-timeline.css";
+@import "./tasks-overview.css";
+
/* ---- Tasks (SPEC-0127 US8) ----
The task list sits in the shared workbench sidebar; the panel holds the
overview table, or a task's header, history, and run view side by side.
@@ -22,8 +26,8 @@
.tasks-rail__failed {
flex: none;
- font-size: var(--fs-xs);
- font-weight: 600;
+ font-size: var(--fs-sm);
+ font-weight: 500;
}
.sidebar-nav__row:not([aria-current="page"]) .tasks-rail__failed {
@@ -163,151 +167,6 @@
padding-left: 18px;
}
-/* ---- Overview table ---- */
-
-.tasks-overview {
- display: flex;
- flex: 1;
- flex-direction: column;
- min-height: 0;
-}
-
-.tasks-overview__body {
- flex: 1;
- min-height: 0;
- overflow: auto;
- scrollbar-width: thin;
-}
-
-.task-table {
- width: 100%;
- margin-top: 8px;
- border-collapse: collapse;
-}
-
-.task-table thead th {
- position: sticky;
- top: 0;
- z-index: 1;
- height: 34px;
- padding: 0 10px;
- border-bottom: 1px solid var(--border);
- background: var(--surface);
- color: var(--text-muted);
- font-size: var(--fs-sm);
- font-weight: 500;
- text-align: left;
- white-space: nowrap;
-}
-
-.task-table :is(th, td):first-child {
- padding-left: var(--gutter);
-}
-
-/* Rows hold two lines: the task name over its id. */
-.task-table tbody :is(th, td) {
- height: 52px;
- padding: 0 10px;
- border-bottom: 1px solid var(--border-faint);
- font-weight: 400;
- text-align: left;
- white-space: nowrap;
-}
-
-.task-table tbody tr:hover {
- background: var(--bg-tint);
-}
-
-/* The task name is a quiet teal link; its id is a muted mono second line. */
-.task-table__open {
- display: inline-flex;
- flex-direction: column;
- align-items: flex-start;
- gap: 1px;
- max-width: 100%;
- padding: 0;
- border: 0;
- background: transparent;
- font-weight: 500;
- text-align: left;
- cursor: pointer;
-}
-
-.task-table__open:is(:hover, :focus-visible) .link-quiet {
- text-decoration: underline;
- text-decoration-color: var(--link-line);
- text-underline-offset: 2px;
-}
-
-/* The row's secondary line: the task id, then a new task's quiet "What it
- does" disclosure, so the row's prominent action stays the inbox one. */
-.task-table__meta {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- margin-top: 1px;
- font-size: var(--fs-sm);
-}
-
-.task-table__meta code {
- font-size: var(--fs-xs);
- font-weight: 400;
-}
-
-.task-table__meta code,
-.task-table__aside,
-.task-table__none {
- color: var(--text-muted);
-}
-
-/* Intervals and relative times are sans, like every relative time. */
-.task-table__time,
-.task-table__due {
- font-variant-numeric: tabular-nums;
-}
-
-.task-table__due.is-due {
- color: var(--info-ink);
- font-weight: 500;
-}
-
-.task-table__last {
- display: inline-flex;
- align-items: center;
- gap: 8px;
-}
-
-.task-table__aside {
- font-size: var(--fs-sm);
-}
-
-.task-table__run-link {
- font-weight: 500;
- white-space: nowrap;
-}
-
-.task-table__local {
- display: inline-flex;
- margin-left: 12px;
- vertical-align: baseline;
- font-weight: 400;
-}
-
-/* A Test once run: the neutral chip, so a test never reads as a status. */
-.task-test-chip {
- display: inline-flex;
- align-items: center;
- padding: 1px 6px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--surface-sunk);
- color: var(--text-muted);
- font-size: var(--fs-xs);
- font-weight: 600;
- line-height: 1.35;
- white-space: nowrap;
-}
-
/* ---- Inbox item ---- */
.task-item {
@@ -391,599 +250,9 @@
font-size: var(--fs-sm);
}
-/* ---- History and run, side by side ---- */
-
-.tasks-split {
- display: grid;
- flex: 1;
- grid-template-columns: minmax(280px, 340px) minmax(0, 1fr);
- min-height: 0;
-}
-
-.task-history {
- display: flex;
- flex-direction: column;
- min-height: 0;
- border-right: 1px solid var(--border);
-}
-
-.task-history__head,
-.task-timeline__head h3 {
- margin: 0;
- color: var(--label-color);
- font: var(--label-font);
-}
-
-.task-history__head {
- padding: 14px 18px 6px;
-}
-
-.task-history__head span {
- margin-left: 4px;
- font-weight: 500;
- font-variant-numeric: tabular-nums;
-}
-
-.task-history__list {
- flex: 1;
- min-height: 0;
- margin: 0;
- padding: 0 8px 12px;
- overflow: auto;
- list-style: none;
- scrollbar-width: thin;
-}
-
-.task-history__row {
- display: grid;
- grid-template-columns: minmax(0, 1fr) auto;
- align-items: center;
- gap: 2px 10px;
- width: 100%;
- padding: 7px 10px;
- border: 0;
- border-radius: var(--r-md);
- background: transparent;
- color: var(--text);
- text-align: left;
- cursor: pointer;
-}
-
-.task-history__row:hover {
- background: var(--bg-tint);
-}
-
-.task-history__row.is-selected {
- background: var(--selection);
- box-shadow: inset 3px 0 0 var(--selection-edge);
-}
-
-.task-history__mark {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- min-width: 0;
-}
-
-.task-history__time {
- color: var(--text-muted);
- font-size: var(--fs-sm);
- font-variant-numeric: tabular-nums;
-}
-
-.task-history__facts {
- display: flex;
- grid-column: 1 / -1;
- gap: 12px;
- color: var(--text-muted);
- font-size: var(--fs-sm);
- font-variant-numeric: tabular-nums;
-}
-
-.task-history__facts:empty {
- display: none;
-}
-
-/* A check that found nothing needed is a quiet single line. */
-.task-history__row.is-quiet {
- padding-block: 3px;
- color: var(--text-faint);
-}
-
-.task-history__row.is-quiet .status-mark {
- font-weight: 400;
-}
-
-.task-history__row.is-quiet .task-history__time {
- color: var(--text-faint);
-}
-
-/* ---- Run view ---- */
-
-.task-run {
- display: flex;
- flex-direction: column;
- min-width: 0;
- min-height: 0;
-}
-
-.task-run--empty {
- align-items: center;
- justify-content: center;
-}
-
-.task-run__head {
- display: flex;
- flex: none;
- align-items: center;
- gap: 8px 14px;
- min-height: 44px;
- padding: 0 24px;
- border-bottom: 1px solid var(--border-faint);
-}
-
-.task-run__stage,
-.task-run__when {
- color: var(--text-muted);
- font-size: var(--fs-sm);
- font-variant-numeric: tabular-nums;
-}
-
-.task-run__id {
- margin-left: auto;
- overflow: hidden;
- color: var(--text-faint);
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.task-run__scroll {
- flex: 1;
- min-height: 0;
- padding: 18px 24px 40px;
- overflow: auto;
- scrollbar-color: var(--border-strong) transparent;
- scrollbar-width: thin;
-}
-
-.task-result,
-.task-timeline {
- max-width: 880px;
-}
-
-.task-result {
- display: flex;
- flex-direction: column;
- gap: 14px;
- padding-bottom: 18px;
- border-bottom: 1px solid var(--border-faint);
-}
-
-.task-result__message {
- max-width: 72ch;
- font-size: var(--fs-md);
- line-height: 1.6;
-}
-
-.task-result__message > :first-child,
-.task-message > :first-child,
-.task-thinking > :first-child {
- margin-top: 0;
-}
-
-.task-result__message > :last-child,
-.task-message > :last-child,
-.task-thinking > :last-child {
- margin-bottom: 0;
-}
-
-.task-result__message :is(h1, h2, h3, h4) {
- margin: 18px 0 6px;
- font-size: var(--fs-lg);
- font-weight: 600;
- line-height: 1.3;
-}
-
-.task-result__message p,
-.task-message p,
-.task-thinking p {
- margin: 0 0 0.6em;
-}
-
-:is(.task-result__message, .task-message, .task-thinking) :is(ul, ol) {
- margin: 0 0 0.6em;
- padding-left: 22px;
-}
-
-:is(.task-result__message, .task-message, .task-thinking) code {
- padding: 1px 4px;
- border-radius: var(--r-sm);
- background: var(--surface-sunk);
- font-family: var(--font-mono);
- font-size: 0.88em;
-}
-
-:is(.task-result__message, .task-message, .task-thinking) pre {
- padding: 10px 12px;
- overflow: auto;
- border-radius: var(--r-md);
- background: var(--surface-sunk);
-}
-
-:is(.task-result__message, .task-message, .task-thinking) pre code {
- padding: 0;
- background: none;
-}
-
-.task-result__pending {
- margin: 0;
- color: var(--text-muted);
-}
-
-.task-facts {
- display: grid;
- grid-template-columns: 112px minmax(0, 1fr);
- gap: 0 12px;
- margin: 0;
-}
-
-.task-facts dt,
-.task-facts dd {
- min-height: 30px;
- padding: 5px 0;
-}
-
-.task-facts dt {
- color: var(--text-muted);
- font-size: var(--fs-sm);
- font-weight: 500;
- line-height: 20px;
-}
-
-.task-facts dd {
- min-width: 0;
- margin: 0;
- line-height: 20px;
-}
-
-.task-facts code,
-.task-paths code,
-.task-copy code {
- font-family: var(--font-mono);
- font-size: var(--fs-sm);
-}
-
-.task-facts__number {
- font-variant-numeric: tabular-nums;
-}
-
-.task-facts__aside {
- margin-left: 10px;
- color: var(--text-muted);
- font-size: var(--fs-sm);
-}
-
-.task-paths {
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-.task-paths li + li {
- margin-top: 2px;
-}
-
-.task-copy {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- max-width: 100%;
-}
-
-.task-copy code {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.task-icon-button {
- height: 24px;
- margin-top: -2px;
- padding: 0 5px;
-}
-
-.task-copy__done:empty {
- display: none;
-}
-
-/* ---- Timeline ---- */
-
-.task-timeline {
- padding-top: 16px;
-}
-
-.task-timeline__head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- min-height: 28px;
- margin-bottom: 4px;
-}
-
-.task-timeline__list {
- display: flex;
- flex-direction: column;
- gap: 2px;
-}
-
-.task-block {
- border: 1px solid transparent;
- border-radius: var(--r-md);
-}
-
-.task-block[open] {
- margin-block: 4px;
- border-color: var(--border);
-}
-
-.task-block__summary {
- display: grid;
- grid-template-columns: 16px 16px minmax(0, 1fr) auto;
- align-items: center;
- gap: 8px;
- min-height: 34px;
- padding: 0 10px 0 6px;
- border-radius: calc(var(--r-md) - 1px);
- color: var(--text);
- list-style: none;
- cursor: pointer;
-}
-
-.task-block__summary::-webkit-details-marker {
- display: none;
-}
-
-.task-block__summary:hover {
- background: var(--bg-tint);
-}
-
-.task-block__summary:focus-visible {
- outline-offset: -2px;
-}
-
-.task-block[open] > .task-block__summary {
- border-bottom-right-radius: 0;
- border-bottom-left-radius: 0;
-}
-
-.task-block__chevron,
-.task-block__icon {
- display: inline-flex;
- color: var(--text-faint);
-}
-
-.task-block__title {
- display: flex;
- align-items: baseline;
- gap: 10px;
- min-width: 0;
- overflow: hidden;
- white-space: nowrap;
-}
-
-.task-block__label {
- flex: none;
- font-weight: 500;
-}
-
-.task-block__preview {
- min-width: 0;
- overflow: hidden;
- color: var(--text-muted);
- text-overflow: ellipsis;
-}
-
-.task-block__preview--mono,
-.task-block__command {
- font-family: var(--font-mono);
- font-size: var(--fs-sm);
-}
-
-.task-block__command {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.task-block__meta {
- display: inline-flex;
- align-items: center;
- gap: 12px;
- font-size: var(--fs-sm);
-}
-
-.task-block__duration {
- color: var(--text-muted);
- font-variant-numeric: tabular-nums;
-}
-
-.task-block__body {
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 10px 12px 12px 36px;
- border-top: 1px solid var(--border-faint);
-}
-
-.task-block__section h4 {
- margin: 0 0 4px;
- color: var(--label-color);
- font: var(--label-font);
-}
-
-.task-block__empty,
-.task-block__cwd,
-.task-block__notice {
- margin: 0;
- color: var(--text-muted);
- font-size: var(--fs-sm);
-}
-
-.task-block__cwd {
- font-family: var(--font-mono);
-}
-
-.task-block__notice {
- color: var(--warning-ink);
-}
-
-.task-output {
- max-height: 380px;
- margin: 0;
- padding: 10px 12px;
- overflow: auto;
- border-radius: var(--r-md);
- background: var(--surface-sunk);
- color: var(--text);
- font-family: var(--font-mono);
- font-size: var(--fs-sm);
- line-height: 1.55;
- overflow-wrap: anywhere;
- white-space: pre-wrap;
- scrollbar-width: thin;
-}
-
-.task-thinking {
- color: var(--text-muted);
- line-height: 1.55;
-}
-
-.task-diff {
- max-height: 420px;
- overflow: auto;
-}
-
-.task-message {
- max-width: 72ch;
- padding: 6px 12px 8px 36px;
- line-height: 1.55;
-}
-
-.task-message__label {
- display: block;
- margin-bottom: 2px;
- color: var(--label-color);
- font: var(--label-font);
-}
-
-.task-line {
- display: flex;
- align-items: center;
- gap: 8px;
- margin: 0;
- padding: 5px 12px 5px 36px;
- font-size: var(--fs-sm);
-}
-
-.task-line--muted {
- color: var(--text-muted);
-}
-
-.task-line .task-icon {
- width: 14px;
- height: 14px;
- margin-left: -22px;
-}
-
-.task-line--live {
- padding-top: 10px;
-}
-
-.task-error {
- display: flex;
- flex-wrap: wrap;
- align-items: baseline;
- gap: 4px 12px;
- margin-block: 4px;
- padding: 8px 12px;
- border: 1px solid var(--accent-line);
- border-radius: var(--r-md);
- background: var(--accent-soft);
-}
-
-.task-error p {
- flex: 1;
- min-width: 200px;
- margin: 0;
- overflow-wrap: anywhere;
-}
-
-/* ---- Empty and loading ---- */
-
-.task-empty {
- margin: 0;
- padding: 14px 18px;
- color: var(--text-muted);
-}
-
-.task-empty--page {
- max-width: 60ch;
- padding: 32px 24px;
-}
-
-.task-empty--page h3 {
- margin: 0 0 6px;
- color: var(--text);
- font-size: var(--fs-lg);
- font-weight: 600;
-}
-
-.task-empty--page p {
- margin: 0 0 12px;
-}
-
-.task-empty code {
- font-family: var(--font-mono);
- font-size: var(--fs-sm);
-}
-
-.task-skeleton {
- display: flex;
- flex-direction: column;
- gap: 10px;
- padding: 14px 18px;
- animation: task-skeleton-in 0.2s 0.15s both;
-}
-
-.task-skeleton span {
- height: 14px;
- border-radius: var(--r);
- background: var(--placeholder);
-}
-
-.task-skeleton span:nth-child(2n) {
- width: 72%;
-}
-
-.task-skeleton--page {
- padding: 24px;
-}
-
-@keyframes task-skeleton-in {
- from {
- opacity: 0;
- }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .task-block__chevron .task-icon,
- .task-skeleton {
- transition: none;
- animation: none;
- }
-}
-
-/* ---- Narrow panels: list, then task, then run ---- */
+/* ---- Narrow panels: list, then task, then run ----
+ Keep this block last: it overrides base rules from this file and its
+ imports, so it must come after all of them in the cascade. */
@container tasks-panel (max-width: 780px) {
.tasks-split {
@@ -1023,58 +292,3 @@
padding-inline: 8px;
}
}
-
-/* A new task's row carries its notice: a "New" tag and a quiet "What it
- does" toggle that opens the purpose in a full-width row below. "New" is
- the neutral chip (as .type-chip): a fact, not a status. */
-.task-table__new-tag {
- padding: 0 5px;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- background: var(--surface-sunk);
- color: var(--text-muted);
- font-size: var(--fs-xs);
- font-weight: 600;
- line-height: 16px;
-}
-
-.task-notice__more {
- display: inline-flex;
- align-items: center;
- gap: 2px;
- padding: 0;
- border: 0;
- background: transparent;
- color: var(--text-muted);
- font: inherit;
- cursor: pointer;
-}
-
-.task-notice__more:is(:hover, :focus-visible) {
- color: var(--text);
-}
-
-.task-table tr.is-expanded > * {
- border-bottom-color: transparent;
-}
-
-.task-table tbody .task-table__purpose > td {
- height: auto;
- padding-top: 0;
- padding-bottom: var(--sp-3);
- white-space: normal;
-}
-
-.task-table__purpose:hover {
- background: transparent;
-}
-
-.task-table__purpose p {
- max-width: 72ch;
- margin: 0 0 var(--sp-3);
- color: var(--text-muted);
-}
-
-.task-notice__sentence::first-letter {
- text-transform: uppercase;
-}
diff --git a/web/src/test/fakeWebGL.ts b/web/src/test/fakeWebGL.ts
index 516d2ea3d..f3180c710 100644
--- a/web/src/test/fakeWebGL.ts
+++ b/web/src/test/fakeWebGL.ts
@@ -125,6 +125,8 @@ export function installFakeWebGL(size: ContextSize = { width: 800, height: 600 }
moveTo: () => undefined,
lineTo: () => undefined,
arc: () => undefined,
+ roundRect: () => undefined,
+ setLineDash: () => undefined,
fill: () => undefined,
stroke: () => undefined,
save: () => undefined,
diff --git a/web/src/tokens.css b/web/src/tokens.css
index 56773738c..493626527 100644
--- a/web/src/tokens.css
+++ b/web/src/tokens.css
@@ -55,6 +55,8 @@
--surface-alt: light-dark(#f5f5f3, #242321);
--surface-sunk: light-dark(#f5f5f3, #242321);
--surface-strong: light-dark(#ebeae7, #2d2c2a);
+ --panel-edge: light-dark(transparent, rgba(255, 255, 255, 0.08));
+ --card-border: light-dark(#e3e2de, #45433f);
--border: light-dark(#e3e2de, #33312f);
--border-strong: light-dark(#cfcdc8, #45433f);
--border-faint: light-dark(#edece9, #292826);
@@ -260,7 +262,7 @@
color-mix(in srgb, var(--chrome-pill) 45%, #1c1b1a)
);
--selection-edge: light-dark(var(--chrome-bg), var(--chrome-muted));
- --scrim: light-dark(rgba(31, 30, 29, 0.32), rgba(0, 0, 0, 0.55));
+ --scrim: light-dark(rgba(31, 30, 29, 0.4), rgba(0, 0, 0, 0.6));
}
:root,
diff --git a/web/src/validation.css b/web/src/validation.css
new file mode 100644
index 000000000..5873062a5
--- /dev/null
+++ b/web/src/validation.css
@@ -0,0 +1,55 @@
+/* Problems: moved verbatim from notes-shell.css. */
+
+/* Problems, clean: the checks that ran, listed in place of an empty panel.
+ Each row leads with the check's name, then a compact success mark and what
+ the check found; the zero issue count is already in the strip. */
+.validation-checks {
+ padding: var(--sp-2) 0;
+}
+
+.validation-checks__list {
+ display: grid;
+ grid-template-columns: 160px minmax(0, 1fr);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.validation-checks__list li {
+ display: contents;
+}
+
+.validation-checks__list li > * {
+ display: flex;
+ align-items: center;
+ min-height: 34px;
+ padding-right: var(--sp-7);
+ border-bottom: 1px solid var(--border-faint);
+ font-size: var(--fs-base);
+}
+
+.validation-checks__list strong {
+ color: var(--text);
+ font-weight: 500;
+}
+
+.validation-checks__list .validation-checks__result {
+ font-size: var(--fs-sm);
+ gap: var(--sp-2);
+ overflow: hidden;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+.validation-checks__mark {
+ flex: none;
+ font-size: var(--fs-base);
+ color: var(--success);
+ font-weight: 700;
+}
+
+.problems-workspace > * {
+ width: 100%;
+ max-width: 1320px;
+ margin-inline: auto;
+}
diff --git a/web/src/viewPreferences/native.ts b/web/src/viewPreferences/native.ts
index b1d9e7298..c527fd0aa 100644
--- a/web/src/viewPreferences/native.ts
+++ b/web/src/viewPreferences/native.ts
@@ -21,12 +21,11 @@ export const DURABLE_QUERY_FIELDS = [
"laneField",
] as const;
-export const LAYOUT_FIELDS = ["columns", "reshown", "density", "widths"] as const;
+export const LAYOUT_FIELDS = ["columns", "reshown", "density", "boardDensity", "widths"] as const;
export const NATIVE_EXPANSION_KEYS = [
"native.tableGroups",
"native.cardGroups",
- "native.boardColumns",
"native.boardLanes",
] as const;
@@ -70,6 +69,8 @@ export function validNativePreference(field: string, value: unknown): value is J
case "columns":
case "reshown":
return isStringArray(value);
+ case "boardDensity":
+ return value === "full" || value === "compact";
case "density":
return value === "two-line" || value === "one-line";
case "widths":
@@ -79,7 +80,6 @@ export function validNativePreference(field: string, value: unknown): value is J
);
case "tableGroups":
case "cardGroups":
- case "boardColumns":
case "boardLanes":
return (
isJsonObject(value) &&
diff --git a/web/src/views/BuiltinOverview.tsx b/web/src/views/BuiltinOverview.tsx
index e87b16e5c..679b66bbd 100644
--- a/web/src/views/BuiltinOverview.tsx
+++ b/web/src/views/BuiltinOverview.tsx
@@ -4,6 +4,7 @@ import { useCallback, useMemo } from "react";
import { isBoolean, isJsonObject } from "../api/parse";
import { HomeGraphLayout } from "../components/HomeGraphLayout";
import { buildTypeColors } from "../components/graphViewShared";
+import { useTypeAccentKey } from "../lib/typeAccent";
import {
useGlobalNotesGraphQuery,
useOntologySummaryQuery,
@@ -107,10 +108,17 @@ export function BuiltinOverview(props: ViewRuntimeProps) {
scopes,
);
- // Key on the names alone: a new colors map rebuilds the graph renderer, and a
- // summary refresh after any edit or validation run changes only counts.
+ const accentKey = useTypeAccentKey();
const typeNames = (summary.data?.types ?? []).map((type) => type.name).join("\n");
- const colors = useMemo(() => buildTypeColors(typeNames.split("\n")), [typeNames]);
+
+ // Key on the names and the shared palette's summary: a new colors map rebuilds
+ // the graph renderer, and a scope-summary refresh after any edit or validation
+ // run changes only counts. The palette key settles colors once it loads.
+ const colors = useMemo(
+ () => buildTypeColors(typeNames.split("\n")),
+ // The summary decides each type's palette slot.
+ [typeNames, accentKey],
+ );
const summaryError =
summary.isError && !summary.data
diff --git a/web/src/workbench.css b/web/src/workbench.css
index 2b69f21f7..072dcf3c2 100644
--- a/web/src/workbench.css
+++ b/web/src/workbench.css
@@ -55,6 +55,8 @@
overflow: hidden;
border-radius: var(--r-lg);
background: var(--surface);
+ outline: 1px solid var(--panel-edge);
+ outline-offset: -1px;
}
/* With the sidebar hidden the panel spans both columns, so it still fills
diff --git a/web/tests/e2e/agent.spec.ts b/web/tests/e2e/agent.spec.ts
index acffaa364..bbba0ccff 100644
--- a/web/tests/e2e/agent.spec.ts
+++ b/web/tests/e2e/agent.spec.ts
@@ -8,6 +8,47 @@ test("runs an approval and interrupt journey against the fake harness", async ({
await page.goto("/agent");
await expect(page.locator(".agent-thread__head")).toContainText("e2e-fake");
+ await page.getByLabel("Model", { exact: true }).selectOption({ index: 0 });
+
+ const model = await page
+ .getByLabel("Model", { exact: true })
+ .locator("option:checked")
+ .textContent();
+
+ await expect(page.locator(".agent-thread__head .view-header__about")).toContainText(
+ model?.replace(" (default)", "") || "",
+ );
+
+ const settings = page.getByLabel("Settings: Tool approval: ask first", { exact: true });
+ await expect(settings).toContainText("Settings");
+ await expect(settings).toHaveCSS("height", "28px");
+ const active = settings.locator(".agent-session-settings__active");
+ await expect(active).toHaveCSS("font-size", "13px");
+ await expect(active).toHaveCSS("font-weight", "500");
+ await expect(page.getByText("No sessions yet.", { exact: true })).toHaveCSS("font-size", "13px");
+ const rows = page.locator(".agent-examples button");
+ await expect(rows).toHaveCount(3);
+
+ // The arrow follows its question by 8px, so it reads as the row's action.
+ const gaps = await page.locator(".agent-examples button").evaluateAll((buttons) =>
+ buttons.map((button) => {
+ const text = button.querySelector("span")!.getBoundingClientRect();
+
+ const arrow = button.querySelector(".agent-examples__arrow")!.getBoundingClientRect();
+
+ return Math.round(arrow.left - text.right);
+ }),
+ );
+
+ expect(gaps).toEqual([8, 8, 8]);
+
+ await rows.first().focus();
+ await page.keyboard.press("Enter");
+ await expect(page.getByLabel("Message")).toHaveValue(
+ "What changed in this repository this week?",
+ );
+ await expect(page.getByLabel("Message")).toBeFocused();
+
await page.getByRole("button", { name: "New session", exact: true }).click();
await expect(page.getByRole("heading", { name: "Rhizome agent chat" })).toBeVisible();
diff --git a/web/tests/e2e/app.spec.ts b/web/tests/e2e/app.spec.ts
index 98d4ced86..306fd2b56 100644
--- a/web/tests/e2e/app.spec.ts
+++ b/web/tests/e2e/app.spec.ts
@@ -8,7 +8,10 @@ test("loads the graph and navigates notes/code from the tree", async ({ page })
await expect(page.getByText("Graph unavailable")).toHaveCount(0);
await expect(page.getByRole("heading", { name: "Explorer", exact: true })).toBeVisible();
- await rail.getByRole("button", { name: /notes/i }).click();
+ await expect(rail.getByRole("button", { name: "notes", exact: true })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
await rail.getByRole("button", { name: /task-flow\.md/i }).click();
await expect(page).toHaveURL(/\/notes\?note=notes%2Ftask-flow\.md$/);
await expect(page.locator(".ontology-identity__title")).toHaveText("Task Flow");
@@ -16,7 +19,10 @@ test("loads the graph and navigates notes/code from the tree", async ({ page })
await page.goto("/explorer");
await expect(page.getByRole("heading", { name: "Explorer", exact: true })).toBeVisible();
- await rail.getByRole("button", { name: /\bsrc$/i }).click();
+ await rail
+ .locator(".explorer-rail__body > .tree-list > .tree-item > .tree-row")
+ .filter({ hasText: /^src$/ })
+ .click();
await rail.getByRole("button", { name: /todoapp/i }).click();
await rail.getByRole("button", { name: /main\.py/i }).click();
await expect(page.getByRole("heading", { name: "main.py" })).toBeVisible();
@@ -27,11 +33,12 @@ test("focuses folders and supports search suggestions", async ({ page }) => {
await page.goto("/explorer");
const rail = page.locator(".explorer-rail");
- await rail.getByRole("button", { name: /\bsrc$/i }).click();
- await expect(rail.getByRole("button", { name: /\bsrc$/i })).toHaveAttribute(
- "aria-current",
- "page",
- );
+ const src = rail
+ .locator(".explorer-rail__body > .tree-list > .tree-item > .tree-row")
+ .filter({ hasText: /^src$/ });
+
+ await src.click();
+ await expect(src).toHaveAttribute("aria-current", "page");
await expect(page.locator(".explorer-pane")).toHaveCount(0);
const search = page.getByRole("searchbox", { name: "Search notes and code" });
@@ -52,7 +59,10 @@ test("does not revive a collapsed specs folder after a delayed read", async ({ p
await page.goto("/explorer");
const rail = page.locator(".explorer-rail");
- await rail.getByRole("button", { name: /notes/i }).click();
+ await expect(rail.getByRole("button", { name: "notes", exact: true })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
const specs = rail.getByRole("button", { name: /specs/i });
await specs.click();
await specs.click();
@@ -125,7 +135,7 @@ test("edits configured view enum checkbox and relation cells", async ({ page })
await assignee.selectOption({ value: bobValue! });
await expect(row.getByRole("link", { name: "Bob" })).toBeVisible();
- await expect(page.locator(".ontology-edit-bar")).toContainText("Ready to save");
+ await expect(page.locator(".ontology-edit-bar")).toContainText("Unsaved changes");
await expect(page.locator(".ontology-edit-bar")).toContainText("1 note");
await expect(page.locator(".ontology-edit-bar")).toContainText("3 changes");
diff --git a/web/tests/e2e/atlas.spec.ts b/web/tests/e2e/atlas.spec.ts
index 586241d7e..2e90008a8 100644
--- a/web/tests/e2e/atlas.spec.ts
+++ b/web/tests/e2e/atlas.spec.ts
@@ -13,6 +13,15 @@ async function expectAtlasGeometry(page: Page) {
const scale = cardRect.width / card.offsetWidth;
return {
+ nameFits: (() => {
+ const name = card.querySelector(".ontology-node__name");
+
+ return (
+ !!name &&
+ name.scrollWidth <= name.clientWidth + 1 &&
+ name.clientHeight <= Number.parseFloat(getComputedStyle(name).lineHeight) + 1
+ );
+ })(),
id: element.dataset.id,
width: card.offsetWidth,
height: card.offsetHeight,
@@ -41,6 +50,7 @@ async function expectAtlasGeometry(page: Page) {
expect(measurements.flatMap((node) => node.handles).length).toBeGreaterThan(4);
for (const node of measurements) {
+ expect(node.nameFits, `${node.id} name fits on one line`).toBe(true);
expect(node.width, `${node.id} card width`).toBe(node.declaredWidth);
expect(node.height, `${node.id} card height`).toBe(node.declaredHeight);
@@ -71,6 +81,8 @@ test("Atlas finder focuses types, searches without removing graph nodes, and ope
expect(originalIds).toContain("Spec");
await index.getByRole("button", { name: "Focus Person", exact: true }).click();
await expect(index.getByText("Tracing Person")).toBeVisible();
+ await expect(page.locator(".react-flow__edge-text").first()).toBeVisible();
+ await expect(page.getByLabel("Connection legend")).toContainText("Self relation");
await expect(person).toHaveClass(/atlas-node--focused/);
await expect(page.locator('.react-flow__node[data-id="Spec"]')).toHaveClass(/atlas-node--dimmed/);
await expect
diff --git a/web/tests/e2e/explorer.spec.ts b/web/tests/e2e/explorer.spec.ts
index 1d96dd1e5..692243f3a 100644
--- a/web/tests/e2e/explorer.spec.ts
+++ b/web/tests/e2e/explorer.spec.ts
@@ -3,10 +3,92 @@ import { expect, test } from "./fixtures";
test("root folder containment and folder focus", async ({ page }, testInfo) => {
await page.goto("/explorer");
await expect(page.locator('[data-graph-ready="true"]')).toBeVisible();
- await expect(page.getByText(/Lines follow folder containment/)).toBeVisible();
+ await expect(page.locator(".graph-type-legend input")).toHaveCount(0);
+ await page.getByRole("button", { name: "Display", exact: true }).click();
+
+ const sizeToggle = page.getByRole("checkbox", {
+ name: "Size counts the notes and code files a folder holds",
+ });
+
+ await expect(sizeToggle).toBeVisible();
+ const checked = await sizeToggle.isChecked();
+ await sizeToggle.click();
+ await expect(sizeToggle).toBeChecked({ checked: !checked });
+ await sizeToggle.click();
+ await page.getByRole("button", { name: "Display", exact: true }).click();
+ const complete = await page.request.get("/api/v1/graphs/global?limit=200000");
+ const data = await complete.json();
+ expect(data.truncated ?? false).toBe(false);
+ const notes = data.nodes.filter((n: { kind: string }) => n.kind === "note").length;
+ const code = data.nodes.filter((n: { kind: string }) => n.kind === "code").length;
+ await expect(page.locator(".view-header__count")).toHaveText(
+ `${notes.toLocaleString("en-US")} notes · ${code.toLocaleString("en-US")} code files`,
+ );
+ await expect(page.getByText("Part of the graph is hidden")).toHaveCount(0);
+
+ const initialSrc = page
+ .locator(".explorer-rail__body > .tree-list > .tree-item > .tree-row")
+ .filter({ hasText: /^src$/ });
+
+ if ((await initialSrc.getAttribute("aria-expanded")) === "true") {
+ await initialSrc.click();
+ await expect(page.locator('[data-graph-ready="true"]')).toBeVisible();
+ }
+
+ const before = await page.getByRole("img", { name: /^Graph of / }).getAttribute("aria-label");
+
+ const nodeCount = (label: string | null) =>
+ Number(label?.match(/Graph of ([\d,]+)/)?.[1]?.replaceAll(",", ""));
+
+ const initialNodes = nodeCount(before);
await page.screenshot({ path: testInfo.outputPath("explorer-root.png") });
- const src = page.locator(".explorer-rail").getByRole("button", { name: /\bsrc$/i });
+
+ const src = page
+ .locator(".explorer-rail__body > .tree-list > .tree-item > .tree-row")
+ .filter({ hasText: /^src$/ });
+
+ const started = performance.now();
await src.click();
+ await expect(page.locator('[data-graph-ready="true"]')).toBeVisible();
+ console.log(`Explorer folder click to ready: ${Math.round(performance.now() - started)} ms`);
+ await expect
+ .poll(async () =>
+ nodeCount(await page.getByRole("img", { name: /^Graph of / }).getAttribute("aria-label")),
+ )
+ .toBeGreaterThan(0);
+ await expect(src).toHaveAttribute("aria-expanded", "true");
+ await expect(page.getByRole("heading", { name: "Repository totals", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Lines", exact: true })).toBeVisible();
+ await expect(page.locator(".explorer-header__breadcrumb")).toHaveText("src ·");
+ await expect(page.locator(".explorer-header__totals")).toContainText(
+ `of ${notes.toLocaleString("en-US")} notes`,
+ );
+
+ const expandedNodes = nodeCount(
+ await page.getByRole("img", { name: /^Graph of / }).getAttribute("aria-label"),
+ );
+
+ await src.click();
+ await expect(page.locator('[data-graph-ready="true"]')).toBeVisible();
+ await expect
+ .poll(async () =>
+ nodeCount(await page.getByRole("img", { name: /^Graph of / }).getAttribute("aria-label")),
+ )
+ .toBeLessThan(expandedNodes);
+ await page.locator(".explorer-rail__root").click();
+ await expect(page.locator('[data-graph-ready="true"]')).toBeVisible();
+ await expect
+ .poll(async () =>
+ nodeCount(await page.getByRole("img", { name: /^Graph of / }).getAttribute("aria-label")),
+ )
+ .toBe(initialNodes);
+ await src.click();
+ await expect(page.locator('[data-graph-ready="true"]')).toBeVisible();
+ await expect
+ .poll(async () =>
+ nodeCount(await page.getByRole("img", { name: /^Graph of / }).getAttribute("aria-label")),
+ )
+ .toBe(expandedNodes);
await expect(src).toHaveAttribute("aria-current", "page");
await expect(page.locator(".explorer-pane")).toHaveCount(0);
await page
@@ -18,4 +100,9 @@ test("root folder containment and folder focus", async ({ page }, testInfo) => {
.getByRole("button", { name: /main\.py/i })
.click();
await expect(page.locator(".explorer-pane__code")).toBeVisible();
+ await expect(page.locator('.explorer-rail .tree-row[aria-current="page"]')).toHaveText(
+ /main\.py/i,
+ );
+ await expect(page.locator(".explorer-pane__header h2")).toHaveCSS("font-size", "16px");
+ await expect(page.locator(".explorer-pane__header h2")).toHaveCSS("font-weight", "600");
});
diff --git a/web/tests/e2e/finder.spec.ts b/web/tests/e2e/finder.spec.ts
index f028e5b93..b7d7b516c 100644
--- a/web/tests/e2e/finder.spec.ts
+++ b/web/tests/e2e/finder.spec.ts
@@ -13,6 +13,8 @@ test("⌘P finds a note by a typo'd query and opens it as a tab, then a code fil
const input = page.getByRole("combobox", { name: "Find a note or file" });
await expect(input).toBeFocused();
+ await expect(page.locator(".finder__input kbd")).toHaveCount(0);
+ await expect(page.locator(".finder__foot kbd").filter({ hasText: /esc/i })).toHaveCount(1);
// One swapped pair: "Stratgey" still finds "Sync Strategy".
await input.fill("sync stratgey");
const option = page.getByRole("option", { name: /Sync Strategy/ });
diff --git a/web/tests/e2e/graphql-disclosure.spec.ts b/web/tests/e2e/graphql-disclosure.spec.ts
new file mode 100644
index 000000000..09b51c71d
--- /dev/null
+++ b/web/tests/e2e/graphql-disclosure.spec.ts
@@ -0,0 +1,21 @@
+import { expect, test } from "./fixtures";
+
+test("opens variables and headers from one labelled disclosure row", async ({ page }) => {
+ await page.goto("/graphql");
+ const toggle = page.getByRole("button", { name: "Show editor tools", exact: true });
+ await expect(toggle).toBeVisible();
+ await expect(page.getByRole("button", { name: /^Merge fragments into query/ })).toBeVisible();
+
+ const variables = page
+ .locator(".graphiql-editor-tools > button")
+ .filter({ hasText: /^Variables$/ });
+
+ await expect(variables).toBeHidden();
+ const row = await page.locator(".graphiql-editor-tools").boundingBox();
+ const target = await toggle.boundingBox();
+ expect(target && row && target.width / row.width).toBeGreaterThan(0.9);
+ await toggle.click();
+ await expect(variables).toBeVisible();
+ await page.getByRole("button", { name: "Hide editor tools", exact: true }).click();
+ await expect(variables).toBeHidden();
+});
diff --git a/web/tests/e2e/group-overview.spec.ts b/web/tests/e2e/group-overview.spec.ts
new file mode 100644
index 000000000..f475cf85f
--- /dev/null
+++ b/web/tests/e2e/group-overview.spec.ts
@@ -0,0 +1,136 @@
+import { expect, test } from "./fixtures";
+import { customFrame, feedbackScreenshot, openGroup } from "./groupViewHelpers";
+import { chooseView, expectView } from "./workspaceView";
+
+test.use({ timezoneId: "America/Detroit", locale: "en-US" });
+
+// Synthetic groups from fixtures/group-views:
+// - E2E Planning: the Work items interface over Story and Bug, the
+// hierarchical Areas type that work items link to, and Releases that link to
+// work items, plus links out to E2E Contacts. A contact links back to a work
+// item, and a story names a contact in its body. One bug misses a required
+// field, so the group has an issue; Billing holds a risk-toned health value;
+// two areas leave the KEY lead field empty. The work stage enum declares
+// stages, and its warning-toned Blocked value is in the active stage.
+// - E2E Contacts: one root.
+// - E2E Library: two roots with no links.
+
+test("group Overview maps member types, lists members and outside notes, and switches to the matrix", async ({
+ page,
+}) => {
+ await page.goto("/notes");
+ await openGroup(page, "E2E Planning");
+ await chooseView(page, "Overview");
+ const frame = customFrame(page);
+
+ const map = frame.getByRole("region", { name: "Map" });
+ await expect(map.getByRole("group", { name: "E2E Planning map" })).toBeVisible();
+
+ for (const name of ["Areas", "Releases", "Work items"])
+ await expect(map.getByRole("button", { name: new RegExp(`^${name}\\b`) })).toHaveCount(1);
+
+ const arcs = map.locator(".gv-map-arc");
+ expect(await arcs.count()).toBeGreaterThan(0);
+
+ for (const arc of await arcs.all()) {
+ expect(
+ Number.parseFloat(await arc.evaluate((el) => getComputedStyle(el).strokeWidth)),
+ ).toBeGreaterThanOrEqual(4);
+ }
+
+ await expect(map.locator(".gv-legend-ring")).not.toContainText(["ring:"]);
+ await feedbackScreenshot(page, "map-light");
+ await page.emulateMedia({ colorScheme: "dark" });
+ await feedbackScreenshot(page, "map-dark");
+ await page.emulateMedia({ colorScheme: "light" });
+
+ const members = frame.getByRole("region", { name: "Members" });
+ await expect(
+ members.getByRole("columnheader", { name: "Records linked", exact: true }),
+ ).toBeVisible();
+ await expect(members.getByRole("columnheader", { name: "Links", exact: true })).toBeVisible();
+
+ for (const edge of await frame.locator(".gv-map-edge").all()) {
+ await expect(edge.locator("line")).toHaveCount(1);
+ await expect(edge.locator(".gv-map-hit")).toHaveCSS("stroke", "rgba(0, 0, 0, 0)");
+ }
+
+ for (const name of ["Areas", "Releases", "Work items"])
+ await expect(members.getByRole("button", { name, exact: true })).toBeVisible();
+
+ const layout = await members.evaluate((section) => {
+ const container = section.closest(".gv-ov--group")!;
+ const map = container.querySelector(".gv-ov-main")!;
+
+ return {
+ width: section.getBoundingClientRect().width,
+ containerWidth: container.getBoundingClientRect().width,
+ gap: section.getBoundingClientRect().top - map.getBoundingClientRect().bottom,
+ rows: [...section.querySelectorAll("tbody tr")].map(
+ (row) => row.getBoundingClientRect().height,
+ ),
+ };
+ });
+
+ expect(layout.width).toBe(layout.containerWidth);
+ expect(layout.gap).toBeLessThanOrEqual(40);
+
+ for (const height of layout.rows) expect(height).toBeLessThanOrEqual(36);
+
+ // Ada is the typed owner of one work item and watches another from outside;
+ // Lin is named only in a body link.
+ const outside = frame.getByRole("region", { name: "Outside the group" });
+ const more = outside.getByRole("button", { name: /Show \d+ (?:more|notes?)/ });
+
+ if (await more.isVisible()) await more.click();
+ await expect(outside).toContainText("Ada Example");
+ await expect(outside).toContainText("Lin Example");
+ await expect(outside.locator(".gv-changes")).toHaveCSS("max-height", "none");
+
+ await map.getByRole("radio", { name: "Matrix" }).locator("xpath=..").click();
+
+ const matrix = map.getByRole("table");
+ await expect(matrix.getByRole("rowheader", { name: "Work items" })).toBeVisible();
+
+ // A member name opens its collection.
+ await members.getByRole("button", { name: "Areas", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Areas", exact: true })).toBeVisible();
+});
+
+test("All notes opens on its Briefing and offers the Overview", async ({ page }) => {
+ await page.goto("/notes");
+ await expectView(page, "Briefing");
+ const frame = customFrame(page);
+
+ for (const name of ["Needs attention", "In motion", "Recent changes"])
+ await expect(frame.getByRole("region", { name })).toBeVisible();
+
+ await expect(page.locator("canvas")).toHaveCount(0);
+
+ await chooseView(page, "Overview");
+ await expect(frame.getByRole("region", { name: "Map" })).toBeVisible();
+ await expect(frame.getByRole("region", { name: "Untyped notes by folder" })).toBeVisible();
+ await expect(frame.getByRole("region", { name: "Members" })).toBeVisible();
+});
+
+for (const { time, heading } of [
+ { time: "2026-10-05T23:59:00-04:00", heading: "1m" },
+ { time: "2026-10-06T00:01:00-04:00", heading: "3m" },
+]) {
+ test(`Briefing dates a recent change by its age (${heading}) across midnight`, async ({
+ page,
+ }) => {
+ await page.clock.setFixedTime(new Date(time));
+ await page.goto("/notes");
+ await openGroup(page, "E2E Planning");
+ await expectView(page, "Briefing");
+
+ const recent = customFrame(page).getByRole("region", { name: "Recent changes" });
+ // One list on every scope: no day headings, the age in its own column.
+ await expect(recent.getByRole("heading")).toHaveText(["Recent changes"]);
+ // The heading also matches the outgoing All notes frame; wait for the group's one change.
+ await expect(recent.locator("time")).toHaveCount(1);
+ await expect(recent.locator("time")).toHaveAttribute("datetime", "2026-10-06T03:58:00.000Z");
+ await expect(recent.locator("time span[aria-hidden]")).toHaveText(heading);
+ });
+}
diff --git a/web/tests/e2e/group-views.spec.ts b/web/tests/e2e/group-views.spec.ts
index cc8d19f5a..c7958b2c8 100644
--- a/web/tests/e2e/group-views.spec.ts
+++ b/web/tests/e2e/group-views.spec.ts
@@ -1,6 +1,7 @@
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type APIRequestContext, type FrameLocator, type Page } from "./fixtures";
+import { customFrame, feedbackScreenshot, openGroup } from "./groupViewHelpers";
import { chooseView, expectView, workspaceView } from "./workspaceView";
test.use({ timezoneId: "America/Detroit", locale: "en-US" });
@@ -16,20 +17,9 @@ test.use({ timezoneId: "America/Detroit", locale: "en-US" });
// - E2E Contacts: one root.
// - E2E Library: two roots with no links.
-const customFrame = (page: Page) =>
- page.frameLocator("iframe.custom-view-frame:not([data-incoming])");
-
const viewChoice = (page: Page, name: string) =>
workspaceView(page).getByRole("button", { name, exact: true });
-async function openGroup(page: Page, group: string) {
- await page
- .getByRole("region", { name: "Collections" })
- .getByRole("button", { name: group, exact: true })
- .click();
- await expect(page.getByRole("heading", { name: group, exact: true })).toBeVisible();
-}
-
async function vaultFile(request: APIRequestContext, ...parts: string[]) {
const status = await (await request.get("/api/v1/status")).json();
@@ -52,17 +42,6 @@ const markFrame = (frame: FrameLocator) =>
const frameMarked = (frame: FrameLocator) =>
frame.locator("html").evaluate(() => "gvMarker" in window);
-async function feedbackScreenshot(page: Page, name: string) {
- const feedbackDir = process.env.RHIZOME_FEEDBACK_DIR;
-
- if (!feedbackDir) return;
- await mkdir(feedbackDir, { recursive: true });
- await page.screenshot({
- path: `${feedbackDir}/${process.env.RHIZOME_FEEDBACK_PHASE ?? "after"}-${name}.png`,
- fullPage: true,
- });
-}
-
test("a group opens the bundled view its shape calls for and remembers a choice", async ({
page,
}) => {
@@ -98,7 +77,15 @@ test("a group opens the bundled view its shape calls for and remembers a choice"
await page.reload();
await expectView(page, "Overview");
+ const saved = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === "/api/v1/view-preferences" &&
+ response.request().method() === "PATCH" &&
+ response.ok(),
+ );
+
await chooseView(page, "Sections");
+ await saved;
await expect(page.locator("iframe.custom-view-frame:not([data-incoming])")).toBeVisible();
await page.reload();
await expectView(page, "Sections");
@@ -244,95 +231,6 @@ test("Briefing summarizes the group from metadata and navigates to records, coll
await expect(problems.locator("[data-issue-key]")).toContainText("bug-crash.md");
});
-test("group Overview maps member types, lists members and outside notes, and switches to the matrix", async ({
- page,
-}) => {
- await page.goto("/notes");
- await openGroup(page, "E2E Planning");
- await chooseView(page, "Overview");
- const frame = customFrame(page);
-
- const map = frame.getByRole("region", { name: "Map" });
- await expect(map.getByRole("group", { name: "E2E Planning map" })).toBeVisible();
-
- for (const name of ["Areas", "Releases", "Work items"])
- await expect(map.getByRole("button", { name: new RegExp(`^${name}\\b`) })).toHaveCount(1);
-
- const arcs = map.locator(".gv-map-arc");
- expect(await arcs.count()).toBeGreaterThan(0);
-
- for (const arc of await arcs.all()) {
- expect(
- Number.parseFloat(await arc.evaluate((el) => getComputedStyle(el).strokeWidth)),
- ).toBeGreaterThanOrEqual(4);
- }
-
- await expect(map.locator(".gv-legend-ring")).not.toContainText(["ring:"]);
- await feedbackScreenshot(page, "map-light");
- await page.emulateMedia({ colorScheme: "dark" });
- await feedbackScreenshot(page, "map-dark");
- await page.emulateMedia({ colorScheme: "light" });
-
- const members = frame.getByRole("region", { name: "Members" });
-
- for (const name of ["Areas", "Releases", "Work items"])
- await expect(members.getByRole("button", { name, exact: true })).toBeVisible();
-
- // Ada is the typed owner of one work item and watches another from outside;
- // Lin is named only in a body link.
- const outside = frame.getByRole("region", { name: "Outside the group" });
- await expect(outside).toContainText("Ada Example");
- await expect(outside).toContainText("Lin Example");
- await expect(outside.locator(".gv-changes")).toHaveCSS("max-height", "none");
-
- await map.getByRole("radio", { name: "Matrix" }).locator("xpath=..").click();
-
- const matrix = map.getByRole("table");
- await expect(matrix.getByRole("rowheader", { name: "Work items" })).toBeVisible();
-
- // A member name opens its collection.
- await members.getByRole("button", { name: "Areas", exact: true }).click();
- await expect(page.getByRole("heading", { name: "Areas", exact: true })).toBeVisible();
-});
-
-test("All notes opens on its Briefing and offers the Overview", async ({ page }) => {
- await page.goto("/notes");
- await expectView(page, "Briefing");
- const frame = customFrame(page);
-
- for (const name of ["Needs attention", "In motion", "Recent changes"])
- await expect(frame.getByRole("region", { name })).toBeVisible();
-
- await expect(page.locator("canvas")).toHaveCount(0);
-
- await chooseView(page, "Overview");
- await expect(frame.getByRole("region", { name: "Map" })).toBeVisible();
- await expect(frame.getByRole("region", { name: "Untyped notes by folder" })).toBeVisible();
- await expect(frame.getByRole("region", { name: "Members" })).toBeVisible();
-});
-
-for (const { time, heading } of [
- { time: "2026-10-05T23:59:00-04:00", heading: "1m" },
- { time: "2026-10-06T00:01:00-04:00", heading: "3m" },
-]) {
- test(`Briefing dates a recent change by its age (${heading}) across midnight`, async ({
- page,
- }) => {
- await page.clock.setFixedTime(new Date(time));
- await page.goto("/notes");
- await openGroup(page, "E2E Planning");
- await expectView(page, "Briefing");
-
- const recent = customFrame(page).getByRole("region", { name: "Recent changes" });
- // One list on every scope: no day headings, the age in its own column.
- await expect(recent.getByRole("heading")).toHaveText(["Recent changes"]);
- // The heading also matches the outgoing All notes frame; wait for the group's one change.
- await expect(recent.locator("time")).toHaveCount(1);
- await expect(recent.locator("time")).toHaveAttribute("datetime", "2026-10-06T03:58:00.000Z");
- await expect(recent.locator("time span[aria-hidden]")).toHaveText(heading);
- });
-}
-
test("Trace defaults to the area tree, nests and rolls up rows, and switches its rows", async ({
page,
}) => {
@@ -348,7 +246,14 @@ test("Trace defaults to the area tree, nests and rolls up rows, and switches its
// Areas is the hierarchical type that work items link to, so it is the default.
await expect(rowsControl.getByRole("radio", { name: "Areas 3 (default)" })).toBeChecked();
- await expect(table.getByRole("columnheader")).toHaveText([/^Areas/, /^Work items/, /^Releases/]);
+ await expect(
+ frame.locator(".gv-toolbar").getByRole("radiogroup", { name: "Rows" }),
+ ).toBeVisible();
+ await expect(table.getByRole("radiogroup", { name: "Rows" })).toHaveCount(0);
+ await expect(table.locator("thead th:not(.gv-trace-spine)")).toHaveText([
+ /^Work items/,
+ /^Releases/,
+ ]);
// Search nests under Platform, whose cells roll up the subtree.
const platform = row("Rows under Platform Platform");
@@ -375,11 +280,10 @@ test("Trace defaults to the area tree, nests and rolls up rows, and switches its
// Rows switch to another member; the choice lasts for the session.
await rowsControl.getByText(/^Work items/).click();
await expect(rowsControl.getByRole("radio", { name: "Work items 4" })).toBeChecked();
- await expect(table.getByRole("columnheader")).toHaveText([
- /^Work items/,
+ await expect(table.locator("thead th:not(.gv-trace-spine)")).toHaveText([
/^Areas/,
/^Releases/,
- /^Owner.*in E2E Contacts/,
+ /^Owner.*1 of 4 work items have owner/,
]);
await expect(row("Faster indexing").getByRole("cell")).toHaveText([
"Search",
diff --git a/web/tests/e2e/groupViewHelpers.ts b/web/tests/e2e/groupViewHelpers.ts
new file mode 100644
index 000000000..07d17a297
--- /dev/null
+++ b/web/tests/e2e/groupViewHelpers.ts
@@ -0,0 +1,25 @@
+import { mkdir } from "node:fs/promises";
+import { expect, type Page } from "./fixtures";
+
+// Shared by the group view specs.
+export const customFrame = (page: Page) =>
+ page.frameLocator("iframe.custom-view-frame:not([data-incoming])");
+
+export async function openGroup(page: Page, group: string) {
+ await page
+ .getByRole("region", { name: "Collections" })
+ .getByRole("button", { name: group, exact: true })
+ .click();
+ await expect(page.getByRole("heading", { name: group, exact: true })).toBeVisible();
+}
+
+export async function feedbackScreenshot(page: Page, name: string) {
+ const feedbackDir = process.env.RHIZOME_FEEDBACK_DIR;
+
+ if (!feedbackDir) return;
+ await mkdir(feedbackDir, { recursive: true });
+ await page.screenshot({
+ path: `${feedbackDir}/${process.env.RHIZOME_FEEDBACK_PHASE ?? "after"}-${name}.png`,
+ fullPage: true,
+ });
+}
diff --git a/web/tests/e2e/narrative-edit.spec.ts b/web/tests/e2e/narrative-edit.spec.ts
index 9d8d3f30c..9117e7a83 100644
--- a/web/tests/e2e/narrative-edit.spec.ts
+++ b/web/tests/e2e/narrative-edit.spec.ts
@@ -58,3 +58,49 @@ test("replays queued narrative typing and discards back to disk", async ({ page
await page.getByRole("button", { name: "Edit", exact: true }).click();
await expect.poll(editorText).toBe(original);
});
+
+for (const width of [1440, 1100]) {
+ for (const appearance of ["light", "dark"]) {
+ test(`keeps note headings and property labels aligned while editing at ${width} ${appearance}`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/notes?note=notes%2Fspecs%2Fsearch-rewrite.md");
+ await page.evaluate(
+ (value) => (document.documentElement.dataset.appearance = value),
+ appearance,
+ );
+ const headings = page.locator(".body-section__title:visible");
+ await expect(headings.first()).toBeVisible();
+
+ const textPositions = () =>
+ headings.evaluateAll((elements) =>
+ elements.map((element) => {
+ const text = Array.from(element.childNodes).find(
+ (node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim(),
+ );
+
+ if (!text) throw new Error("Section heading has no title text");
+ const range = document.createRange();
+ range.selectNodeContents(text);
+
+ return range.getBoundingClientRect().x;
+ }),
+ );
+
+ const labels = page.locator(".ontology-properties__key:visible");
+
+ const labelPositions = () =>
+ labels.evaluateAll((elements) =>
+ elements.map((element) => element.getBoundingClientRect().x),
+ );
+
+ const before = await textPositions();
+ const labelsBefore = await labelPositions();
+ await page.getByRole("button", { name: "Edit", exact: true }).click();
+ await expect(page.locator(".note-property-pencil").first()).toBeVisible();
+ expect(await textPositions()).toEqual(before);
+ expect(await labelPositions()).toEqual(labelsBefore);
+ });
+ }
+}
diff --git a/web/tests/e2e/search.spec.ts b/web/tests/e2e/search.spec.ts
index 4a076bfbb..274e4c60b 100644
--- a/web/tests/e2e/search.spec.ts
+++ b/web/tests/e2e/search.spec.ts
@@ -68,7 +68,7 @@ test.beforeEach(async ({ page }) => {
title: "Search Rewrite",
noteType: noteType || "Spec",
snippetStatus: "available",
- snippet: "Stable typed retrieval preserves ranked search evidence.",
+ snippet: "Stable `typed retrieval` preserves ranked search evidence.",
nodeRef: { notePath: "notes/specs/search-rewrite.md", kind: "note" },
},
],
@@ -153,6 +153,13 @@ test("searches from shared chrome in a full-width page", async ({ page }, testIn
await expect
.poll(() => page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth))
.toBe(0);
+ const column = await page.locator(".search-workspace__header").boundingBox();
+ const results = await page.locator(".search-workspace__results").boundingBox();
+ expect(column?.width).toBe(960);
+ expect(results?.x).toBe(column?.x);
+ expect(results?.width).toBe(column?.width);
+ const workspace = await page.locator(".search-workspace").boundingBox();
+ expect(column!.x - workspace!.x).toBeCloseTo((workspace!.width - 960) / 2, 0);
await page.screenshot({ path: testInfo.outputPath("search-workspace-1280.png") });
const filteredRequestPromise = page.waitForRequest(
@@ -176,6 +183,38 @@ test("searches from shared chrome in a full-width page", async ({ page }, testIn
await page.getByRole("button", { name: "Load more results" }).click();
await expect(page.getByRole("button", { name: "main", exact: true })).toBeVisible();
+
+ const codeResult = page
+ .locator(".search-workspace__result")
+ .filter({ has: page.getByRole("button", { name: "main", exact: true }) });
+
+ const geometry = await codeResult.evaluate((result) => {
+ const title = result.querySelector(".search-workspace__result-link")!;
+ const meta = result.querySelector(".search-workspace__result-source")!;
+ const code = result.querySelector("pre")!;
+
+ return {
+ titleBottom: title.getBoundingClientRect().bottom,
+ metaTop: meta.getBoundingClientRect().top,
+ metaBottom: meta.getBoundingClientRect().bottom,
+ codeTop: code.getBoundingClientRect().top,
+ codeRight: code.getBoundingClientRect().right,
+ codeWidth: code.getBoundingClientRect().width,
+ resultWidth: result.getBoundingClientRect().width,
+ titleFont: getComputedStyle(title).fontFamily,
+ titleSize: getComputedStyle(title).fontSize,
+ };
+ });
+
+ expect(geometry.titleSize).toBe("14px");
+ expect(geometry.titleFont).toContain("JetBrains Mono");
+ expect(geometry.metaTop - geometry.titleBottom).toBeCloseTo(4, 0);
+ expect(geometry.codeTop - geometry.metaBottom).toBeCloseTo(8, 0);
+ expect(geometry.codeWidth).toBeCloseTo(Math.min(720, geometry.resultWidth), 0);
+ const inlineCode = page.locator(".search-workspace__result p code").first();
+ await expect(inlineCode).toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
+ await expect(inlineCode).toHaveCSS("padding", "0px");
+ await expect(inlineCode.locator("mark").first()).toHaveCSS("font-weight", "650");
await page.getByRole("button", { name: "main", exact: true }).click();
await expect(page).toHaveURL(/\/explorer\?file=src%2Ftodoapp%2Fmain.py&line=4/);
await expect(page.locator('[data-line="4"]')).toHaveAttribute("aria-current", "location");
diff --git a/web/tests/e2e/tasks-local-drafts.spec.ts b/web/tests/e2e/tasks-local-drafts.spec.ts
index e1868f90f..b0e92f76a 100644
--- a/web/tests/e2e/tasks-local-drafts.spec.ts
+++ b/web/tests/e2e/tasks-local-drafts.spec.ts
@@ -88,6 +88,35 @@ async function serveTasks(page: Page) {
test("tests a local-only task draft and reads its result", async ({ page }) => {
await serveTasks(page);
await page.goto("/tasks");
+ await expect(page.getByRole("columnheader", { name: "Action", exact: true })).toBeVisible();
+ await expect(page.getByRole("columnheader", { name: "Frequency", exact: true })).toBeVisible();
+ const panel = await page.locator(".tasks-overview").boundingBox();
+ const pause = await page.getByRole("button", { name: "Pause all" }).boundingBox();
+ const table = await page.locator(".task-table").boundingBox();
+
+ expect(panel && pause && panel.x + panel.width - pause.x - pause.width).toBe(22);
+ expect(panel && table && panel.x + panel.width - table.x - table.width).toBe(0);
+
+ await expect(page.locator(".task-table thead th").first()).toHaveCSS("padding-left", "22px");
+ await expect(page.locator(".task-table thead th").last()).toHaveCSS("padding-right", "22px");
+ await expect(page.locator(".task-table tbody tr").first().locator("th")).toHaveCSS(
+ "padding-left",
+ "22px",
+ );
+ await expect(page.locator(".task-table tbody tr").first().locator("td").last()).toHaveCSS(
+ "padding-right",
+ "22px",
+ );
+
+ for (const width of [1440, 1920]) {
+ await page.setViewportSize({ width, height: 900 });
+ const title = await page.getByRole("columnheader", { name: "Task", exact: true }).boundingBox();
+
+ expect(title?.width).toBeGreaterThanOrEqual(320);
+ expect(title?.width).toBeLessThanOrEqual(480);
+ }
+
+ await page.setViewportSize({ width: 1280, height: 720 });
const row = page.getByRole("row", { name: /Session mining/ });
await expect(row.getByText("Local only")).toBeVisible();
@@ -114,4 +143,10 @@ test("tests a local-only task draft and reads its result", async ({ page }) => {
const history = page.getByRole("region", { name: "Run history" });
await expect(history.getByText("Test", { exact: true })).toBeVisible();
await expect(strip.getByRole("button", { name: "Test once" })).toBeEnabled();
+
+ // A narrow panel shows the run alone; its History button must lead back to the list.
+ await page.setViewportSize({ width: 900, height: 900 });
+ await expect(history).toBeHidden();
+ await run.getByRole("button", { name: "History" }).click();
+ await expect(history).toBeVisible();
});
diff --git a/web/tests/e2e/type-cards.spec.ts b/web/tests/e2e/type-cards.spec.ts
index a14d0e468..a4b14d5e6 100644
--- a/web/tests/e2e/type-cards.spec.ts
+++ b/web/tests/e2e/type-cards.spec.ts
@@ -1,7 +1,9 @@
import { expect, test } from "./fixtures";
import { chooseView, expectViewSettled } from "./workspaceView";
-test("cards place metadata immediately below one-line and two-line titles", async ({ page }) => {
+test("cards place metadata below reserved two-line title areas and align grid row heights", async ({
+ page,
+}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/notes/tv-work-item");
await chooseView(page, "Cards");
@@ -34,10 +36,55 @@ test("cards place metadata immediately below one-line and two-line titles", asyn
});
expect(layout.textHeight).toBeCloseTo(layout.lineHeight * lines, 0);
- expect(layout.titleHeight).toBeCloseTo(layout.textHeight, 0);
+ expect(layout.titleHeight).toBeCloseTo(layout.lineHeight * 2, 0);
expect(layout.gap).toBeLessThanOrEqual(8);
}
+ expect(await short.evaluate((el) => el.getBoundingClientRect().height)).toBeCloseTo(
+ await long.evaluate((el) => el.getBoundingClientRect().height),
+ 0,
+ );
+
+ for (const [card, lines] of [
+ [short, 4],
+ [long, 3],
+ ] as const) {
+ const visibleLines = await card.evaluate((element) => {
+ const content = element.querySelector(".configured-card__content");
+ const summary = element.querySelector(".configured-card__summary");
+
+ if (!content || !summary) throw new Error("Missing summary budget");
+ summary.textContent = "Inspect every chain and rail before the storm season starts. ".repeat(
+ 12,
+ );
+
+ const style = getComputedStyle(summary);
+
+ if (style.overflow !== "hidden" || style.webkitBoxOrient !== "vertical")
+ throw new Error("Summary must clamp");
+
+ if (getComputedStyle(content).overflow === "hidden")
+ throw new Error("Content must not clip descenders");
+
+ return {
+ clamp: Number(style.webkitLineClamp),
+ height: summary.getBoundingClientRect().height,
+ lineHeight: Number.parseFloat(style.lineHeight),
+ padding: Number.parseFloat(style.paddingBottom),
+ contentBottom: content.getBoundingClientRect().bottom,
+ summaryBottom: summary.getBoundingClientRect().bottom,
+ };
+ });
+
+ expect(visibleLines.clamp).toBe(lines);
+ expect(visibleLines.height).toBeCloseTo(
+ lines * visibleLines.lineHeight + visibleLines.padding,
+ 0,
+ );
+ expect(visibleLines.padding).toBeGreaterThanOrEqual(2);
+ expect(visibleLines.contentBottom).toBeGreaterThanOrEqual(visibleLines.summaryBottom);
+ }
+
if (process.env.RHIZOME_CARDS_SCREENSHOT) {
await page.screenshot({ path: process.env.RHIZOME_CARDS_SCREENSHOT, fullPage: true });
}
diff --git a/web/tests/e2e/type-views.spec.ts b/web/tests/e2e/type-views.spec.ts
index cda459fd1..2ff68018c 100644
--- a/web/tests/e2e/type-views.spec.ts
+++ b/web/tests/e2e/type-views.spec.ts
@@ -213,7 +213,7 @@ test("the type Briefing reads a collection and opens its Table from a signal", a
frame.getByRole("region", { name: "In motion" }).locator(".gv-change-title"),
).toHaveCount(5);
await expect(
- frame.getByRole("region", { name: "Shape" }).getByRole("heading", { name: "Stage lifecycle" }),
+ frame.getByRole("region", { name: "Composition" }).getByRole("heading", { name: "Stage" }),
).toBeVisible();
const connections = frame.getByRole("region", { name: "Connections" });
@@ -223,9 +223,9 @@ test("the type Briefing reads a collection and opens its Table from a signal", a
await expect(connections.getByRole("listitem").filter({ hasText: /^Meetings/ })).toContainText(
"8 of 10 work items linked",
);
- await expect(frame.getByRole("region", { name: "Linked from outside" })).toContainText(
- "review meeting",
- );
+ await expect(
+ frame.getByRole("region", { name: "Linked from outside" }).locator(".gv-outside-totals"),
+ ).toHaveText("7 Review meeting");
await nextStep.getByRole("button", { name: "Open table" }).click();
await expect(selectedView(page)).toHaveText("Table");
@@ -236,3 +236,83 @@ test("the type Briefing reads a collection and opens its Table from a signal", a
await expect(frame.getByRole("img", { name: /^Date per month, Aug 2026 to / })).toBeVisible();
await expect(frame.getByRole("region", { name: "In motion" })).toHaveCount(0);
});
+
+for (const width of [1100, 1440]) {
+ test(`Record stays docked at ${width}px and footer expands named groups`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/notes/tv-work-item");
+ await chooseView(page, "Table");
+
+ const expand = footer(page)
+ .getByRole("button", { name: /^Expand / })
+ .first();
+
+ await expect(expand).toBeVisible();
+
+ const before = await rows(page).count();
+
+ await expand.click();
+ await expect.poll(() => rows(page).count()).toBeGreaterThan(before);
+ await rows(page)
+ .filter({ hasText: "Anchor chain inspection" })
+ .getByRole("button", { name: "Open Anchor chain inspection" })
+ .click();
+
+ const pane = page.locator("#notes-right-pane");
+
+ if (width === 1100) await page.getByRole("button", { name: "Show right pane" }).click();
+
+ await expect(pane).toBeVisible();
+
+ if (width === 1100) {
+ await page.getByRole("button", { name: "Find in view", exact: true }).click();
+ await expect(page.getByRole("searchbox", { name: "Search view" })).toBeFocused();
+ await page.keyboard.press("Escape");
+ await page.keyboard.press("Meta+f");
+ await expect(page.getByRole("searchbox", { name: "Search view" })).toBeFocused();
+ await page.keyboard.press("Escape");
+ }
+
+ const layout = await pane.evaluate((element) => ({
+ position: getComputedStyle(element).position,
+ shadow: getComputedStyle(element).boxShadow,
+ top: element.getBoundingClientRect().top,
+ frameTop: element.closest(".notes-shell__frame")?.getBoundingClientRect().top,
+ }));
+
+ expect(layout.position).toBe("relative");
+ expect(layout.shadow).toBe("none");
+ expect(layout.top).toBe(layout.frameTop);
+ await expect(page.getByRole("button", { name: "Display options" })).toBeVisible();
+ });
+}
+
+test("Action Items keep long action and source text within two lines", async ({ page }) => {
+ await page.goto("/notes?view=action-items");
+
+ const row = page.locator(".configured-view__row--action").first();
+
+ await expect(row).toBeVisible();
+
+ const layout = await row.evaluate((element) => {
+ const action = element.querySelector(".configured-view__scalar-cell");
+ const source = element.querySelector(".configured-view__source-link a");
+
+ if (!action || !source) throw new Error("Missing action or source");
+ action.textContent =
+ "Follow up on the harbor inspection before the next planning meeting. ".repeat(12);
+ source.textContent =
+ "Harbor planning decisions and inspection notes for the winter season".repeat(3);
+
+ return [action, source].map((cell) => ({
+ clamp: getComputedStyle(cell).webkitLineClamp,
+ height: cell.getBoundingClientRect().height,
+ lineHeight: Number.parseFloat(getComputedStyle(cell).lineHeight),
+ }));
+ });
+
+ for (const cell of layout) {
+ expect(cell.clamp).toBe("2");
+ expect(cell.height).toBeCloseTo(cell.lineHeight * 2, 0);
+ }
+});
diff --git a/web/tests/e2e/ui-consistency.spec.ts b/web/tests/e2e/ui-consistency.spec.ts
index 30c60d055..e2be8cb62 100644
--- a/web/tests/e2e/ui-consistency.spec.ts
+++ b/web/tests/e2e/ui-consistency.spec.ts
@@ -138,3 +138,26 @@ test("keeps Explorer suggestions available for keyboard activation", async ({ pa
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/notes\?note=notes%2Ftask-flow\.md/);
});
+
+test("date editors reveal ISO text and calendar only while focused", async ({ page }) => {
+ await page.goto("/notes?note=notes/type-views/meetings/2026-10-02-lantern.md");
+ await page.getByRole("button", { name: "Edit", exact: true }).first().click();
+ const editor = page.locator(".widget-date-editor").first();
+ const input = editor.locator(".widget-date--input");
+ const words = editor.locator(".widget-date-editor__rest");
+ const calendar = editor.getByRole("button", { name: /from a calendar/ });
+ await expect(words).toHaveText("Oct 2, 2026");
+ await expect(input).toHaveCSS("opacity", "0");
+ await expect(calendar).toBeHidden();
+ await input.focus();
+ await expect(input).toHaveValue("2026-10-02");
+ await expect(input).toHaveCSS("opacity", "1");
+ await expect(words).toBeHidden();
+ await expect(calendar).toBeVisible();
+ await calendar.focus();
+ await expect(words).toBeHidden();
+ await input.focus();
+ await page.keyboard.press("Escape");
+ await expect(words).toBeVisible();
+ await expect(calendar).toBeHidden();
+});
diff --git a/web/tests/e2e/validation.spec.ts b/web/tests/e2e/validation.spec.ts
index 7373bf540..f13587c3d 100644
--- a/web/tests/e2e/validation.spec.ts
+++ b/web/tests/e2e/validation.spec.ts
@@ -118,6 +118,24 @@ test("clean, stale, and failed validation stay calm and distinct at both desktop
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
true,
);
+ const column = await page.locator(".problems-workspace__header").boundingBox();
+ const strip = await page.locator(".validation-status-strip").boundingBox();
+ const checks = await page.locator(".validation-checks").boundingBox();
+
+ expect(column && column.width).toBeLessThanOrEqual(1320);
+ expect(strip?.x).toBe(column?.x);
+ expect(checks?.x).toBe(column?.x);
+ expect(strip?.width).toBe(column?.width);
+ expect(checks?.width).toBe(column?.width);
+ const name = await page.locator(".validation-checks__list strong").first().boundingBox();
+
+ expect(name?.width).toBe(160);
+ expect(name?.height).toBe(34);
+ await expect(page.locator(".validation-checks__list strong").first()).toHaveCSS(
+ "font-size",
+ "14px",
+ );
+ await expect(page.locator(".validation-checks__result").first()).toHaveCSS("font-size", "13px");
await page.screenshot({ path: test.info().outputPath(`validation-clean-${width}.png`) });
}
diff --git a/web/tests/e2e/view-variants.spec.ts b/web/tests/e2e/view-variants.spec.ts
index 85e3fece5..b58890087 100644
--- a/web/tests/e2e/view-variants.spec.ts
+++ b/web/tests/e2e/view-variants.spec.ts
@@ -37,9 +37,9 @@ test("moves a board card, reports the staged change, and opens a card", async ({
).toHaveCount(0);
await expect(
- page.locator(".configured-card", { hasText: movedTitle }).getByText("staged", {
- exact: true,
- }),
+ page
+ .locator(".configured-card", { hasText: movedTitle })
+ .getByRole("img", { name: "Staged changes" }),
).toBeVisible();
await expect(page.getByRole("button", { name: "Changes 1" })).toBeVisible();
await expect(page.getByText("1 staged change", { exact: true })).toBeVisible();