Skip to content

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

feat(health): zoomable folder map with lenses, held-out scope and a context rail (#4157)

Raghav Chamadiya09471b801bd9
diff --git a/packages/api-client/src/areas.ts b/packages/api-client/src/areas.ts
index a91549dc0..4c78041f7 100644
--- a/packages/api-client/src/areas.ts
+++ b/packages/api-client/src/areas.ts
@@ -1,5 +1,5 @@
/** Areas: directory rollups at any depth (`/areas/tree`, `/areas/{path}`). */
-import type { AreaDetail, AreaTree, AreaTreeQuery } from "@repowise-dev/types/areas";
+import type { AreaDetail, AreaTree, AreaTreeQuery, MapHoldQuery } from "@repowise-dev/types/areas";
import { apiGet } from "./client";
export type {
@@ -7,22 +7,35 @@ export type {
AreaDetail,
AreaFileRow,
AreaFinding,
+ AreaHeld,
AreaNode,
AreaOwner,
AreaTree,
AreaTreeQuery,
+ MapHoldQuery,
} from "@repowise-dev/types/areas";
+/** The hold parameters as query values; nothing when every file is read. */
+export function holdParams(opts: MapHoldQuery = {}): Record<string, string | undefined> {
+ if (opts.hold !== "map") return {};
+ // Sorted, so two orders of the same toggles are one request and one cache entry.
+ return { hold: "map", include: opts.include?.length ? [...opts.include].sort().join(",") : undefined };
+}
+
/** The root area's rollup plus every directory up to `depth` levels below it. */
export async function getAreaTree(repoId: string, opts: AreaTreeQuery = {}): Promise<AreaTree> {
return apiGet<AreaTree>(`/api/repos/${repoId}/areas/tree`, {
root: opts.root || undefined,
depth: opts.depth,
+ ...holdParams(opts),
});
}
/** One area's card; `""` is the repository root. */
-export async function getAreaDetail(repoId: string, area: string): Promise<AreaDetail> {
+export async function getAreaDetail(repoId: string, area: string, opts: MapHoldQuery = {}): Promise<AreaDetail> {
const path = area.split("/").filter(Boolean).map(encodeURIComponent).join("/");
- return apiGet<AreaDetail>(path ? `/api/repos/${repoId}/areas/${path}` : `/api/repos/${repoId}/areas`);
+ return apiGet<AreaDetail>(
+ path ? `/api/repos/${repoId}/areas/${path}` : `/api/repos/${repoId}/areas`,
+ holdParams(opts),
+ );
}
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index edb7e5ef6..52f40705a 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -4,6 +4,7 @@
* the hosted frontend and the bot read the same shapes); this module re-exports
* them for back-compat and keeps only the fetch functions.
*/
+import { holdParams } from "./areas";
import type {
ChurnComplexityResponse,
HealthFilesQuery,
@@ -189,6 +190,7 @@ export async function getHealthMap(
include_held: opts.include_held || undefined,
q: opts.q?.trim() || undefined,
area: opts.area || undefined,
+ ...holdParams(opts),
});
}
diff --git a/packages/core/src/repowise/core/analysis/finding_registry.py b/packages/core/src/repowise/core/analysis/finding_registry.py
index 4d26afefd..108c75f5a 100644
--- a/packages/core/src/repowise/core/analysis/finding_registry.py
+++ b/packages/core/src/repowise/core/analysis/finding_registry.py
@@ -212,6 +212,23 @@ FILE_HOLDS: dict[str, str] = {
#: The stored ``code_origin`` values a health finding is never served on.
HELD_ORIGINS: tuple[str, ...] = ("vendored", "generated")
+#: The stored ``code_origin`` values the area map leaves out until the reader
+#: brings them back: tests, docs examples and build files, plus everything no
+#: health finding is served on. Prose docs have no health row, so never appear.
+MAP_HELD_ORIGINS: tuple[str, ...] = ("test", "docs_example", "build", *HELD_ORIGINS)
+
+
+def stored_origin(code_origin: Any, is_test: Any) -> str:
+ """A row's origin, reading a row stamped before ``code_origin`` off ``is_test``."""
+ if isinstance(code_origin, str) and code_origin:
+ return code_origin
+ return "test" if is_test is True else "production"
+
+
+def map_held(include: Iterable[str]) -> frozenset[str]:
+ """The origins the map holds out when the reader has brought back *include*."""
+ return frozenset(MAP_HELD_ORIGINS) - frozenset(include)
+
def history_kinds() -> frozenset[str]:
"""The health markers read from git history alone (the history holds)."""
@@ -519,6 +536,7 @@ __all__ = [
"FILE_HOLDS",
"HELD_ORIGINS",
"LANGUAGE_GATES",
+ "MAP_HELD_ORIGINS",
"REGISTRY",
"UNVERIFIED_LABEL",
"FindingStatus",
@@ -537,6 +555,7 @@ __all__ = [
"is_shown",
"label_previews",
"language_of",
+ "map_held",
"preview_for",
"preview_label",
"preview_lines",
@@ -547,6 +566,7 @@ __all__ = [
"split_gated",
"split_held",
"status_of",
+ "stored_origin",
"verification_label",
"withheld_summary",
]
diff --git a/packages/core/src/repowise/core/persistence/index_cache.py b/packages/core/src/repowise/core/persistence/index_cache.py
index 8d64c10cd..73cab82b3 100644
--- a/packages/core/src/repowise/core/persistence/index_cache.py
+++ b/packages/core/src/repowise/core/persistence/index_cache.py
@@ -61,6 +61,14 @@ class IndexStampCache:
for key in [k for k in self._entries if k[1] == repo_id]:
del self._entries[key]
+ def drop_repo_except(self, repo_id: str, prefix: tuple[Any, ...]) -> None:
+ """Forget *repo_id*'s answers whose key does not start with *prefix*:
+ older states go, variants of the current state (a trailing key part)
+ stay."""
+ n = len(prefix)
+ for key in [k for k in self._entries if k[1] == repo_id and k[:n] != prefix]:
+ del self._entries[key]
+
def remember(self, key: tuple[Any, ...], value: Any) -> Any:
self._entries[key] = value
while len(self._entries) > self._size:
diff --git a/packages/server/src/repowise/server/routers/areas.py b/packages/server/src/repowise/server/routers/areas.py
index cf104cb84..9462a23be 100644
--- a/packages/server/src/repowise/server/routers/areas.py
+++ b/packages/server/src/repowise/server/routers/areas.py
@@ -14,11 +14,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.areas import ROOT_AREA, normalize_area
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.routers.held_origins import HOLD_QUERY, INCLUDE_QUERY
from repowise.server.schemas.areas import AreaDetailResponse, AreaTreeResponse
from repowise.server.services.areas import (
MAX_TREE_DEPTH,
area_detail_payload,
area_tree_payload,
+ held_origins,
load_area_model,
)
@@ -48,6 +50,8 @@ async def get_area_tree(
ROOT_AREA, max_length=1024, description="Area to unfold; the repo root by default."
),
depth: int = Query(1, ge=1, le=MAX_TREE_DEPTH, description="Levels below the root to include."),
+ hold: str = HOLD_QUERY,
+ include: str = INCLUDE_QUERY,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""The root area's rollup plus every directory up to *depth* levels below it.
@@ -56,7 +60,8 @@ async def get_area_tree(
"""
await _require_repo(session, repo_id)
area = normalize_area(root)
- payload = area_tree_payload(await load_area_model(session, repo_id), area, depth)
+ model = await load_area_model(session, repo_id, held_origins(hold, include))
+ payload = area_tree_payload(model, area, depth)
if payload is None:
raise _no_area(area)
return payload
@@ -67,12 +72,14 @@ async def get_area_tree(
async def get_area_detail(
repo_id: str,
area_path: str = ROOT_AREA,
+ hold: str = HOLD_QUERY,
+ include: str = INCLUDE_QUERY,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""One area's card: rollup, worst files, hotspots, owners, trend, findings, test reach."""
await _require_repo(session, repo_id)
area = normalize_area(area_path)
- model = await load_area_model(session, repo_id)
+ model = await load_area_model(session, repo_id, held_origins(hold, include))
payload = await area_detail_payload(session, repo_id, model, area)
if payload is None:
raise _no_area(area)
diff --git a/packages/server/src/repowise/server/routers/code_health/map_routes.py b/packages/server/src/repowise/server/routers/code_health/map_routes.py
index e77b2f162..06dd46e4c 100644
--- a/packages/server/src/repowise/server/routers/code_health/map_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/map_routes.py
@@ -14,6 +14,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.areas import normalize_area
from repowise.server.deps import get_db_session
+from repowise.server.routers.held_origins import HOLD_QUERY, INCLUDE_QUERY
+from repowise.server.services.areas import held_origins
from repowise.server.services.health_map import (
DEFAULT_MAP_CAP,
MAX_MAP_CAP,
@@ -57,6 +59,8 @@ async def get_health_map(
),
scope: str = ScopeQuery,
counts: str = CountsQuery,
+ hold: str = HOLD_QUERY,
+ include: str = INCLUDE_QUERY,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""One bounded field plus the exact scope of what the cap left out."""
@@ -68,5 +72,6 @@ async def get_health_map(
include_held=include_held,
query=q,
area=normalize_area(area) or None,
+ held=held_origins(hold, include) if hold == "map" else None,
)
return feed.payload()
diff --git a/packages/server/src/repowise/server/routers/held_origins.py b/packages/server/src/repowise/server/routers/held_origins.py
new file mode 100644
index 000000000..9d90c5acc
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/held_origins.py
@@ -0,0 +1,21 @@
+"""The two query parameters that narrow a map read to the files it shows.
+
+Shared by the area routes and the health map so the tree, the area cards and
+the drawn files always describe the same files. The held set itself is
+:data:`repowise.core.analysis.finding_registry.MAP_HELD_ORIGINS`.
+"""
+
+from __future__ import annotations
+
+from fastapi import Query
+
+HOLD_QUERY = Query(
+ "none",
+ pattern="^(none|map)$",
+ description="`map` leaves out the origins the area map holds by default; `none` (default) reads every file.",
+)
+INCLUDE_QUERY = Query(
+ "",
+ max_length=200,
+ description="With hold=map: comma-separated held origins to bring back, e.g. `test,build`.",
+)
diff --git a/packages/server/src/repowise/server/schemas/areas.py b/packages/server/src/repowise/server/schemas/areas.py
index d42203979..950424e2e 100644
--- a/packages/server/src/repowise/server/schemas/areas.py
+++ b/packages/server/src/repowise/server/schemas/areas.py
@@ -87,12 +87,25 @@ class AreaDeltaWindow(BaseModel):
baseline_at: str | None
+class AreaHeld(BaseModel):
+ """The origins the map holds out by default, and what this answer left out."""
+
+ #: ``MAP_HELD_ORIGINS``, in order: what ``hold=map`` leaves out.
+ default: list[str]
+ #: Origins left out of every figure in this answer; empty with ``hold=none``.
+ excluded: list[str]
+ #: Files per held origin, repository-wide, for a toggle's count.
+ counts: dict[str, int]
+
+
class AreaTreeResponse(BaseModel):
root: AreaNode
depth: int
#: Every area up to ``depth`` levels below the root, sorted by path.
nodes: list[AreaNode]
delta_window: AreaDeltaWindow
+ #: Absent on older servers.
+ held: AreaHeld | None = None
class AreaBandShare(BaseModel):
diff --git a/packages/server/src/repowise/server/services/areas.py b/packages/server/src/repowise/server/services/areas.py
index 13bf223d5..755fd20cb 100644
--- a/packages/server/src/repowise/server/services/areas.py
+++ b/packages/server/src/repowise/server/services/areas.py
@@ -33,6 +33,7 @@ from repowise.core.analysis.areas import (
nloc_weights,
)
from repowise.core.analysis.areas.trend import DELTA_WINDOW_DAYS
+from repowise.core.analysis.finding_registry import MAP_HELD_ORIGINS, map_held, stored_origin
from repowise.core.persistence import crud
from repowise.core.persistence.crud import code_file_rows
from repowise.core.persistence.database import get_session
@@ -52,6 +53,7 @@ __all__ = [
"area_detail_payload",
"area_tree_payload",
"clear_area_cache",
+ "held_origins",
"load_area_model",
"warm_area_model",
]
@@ -64,9 +66,9 @@ MAX_TREE_DEPTH = 4
#: Snapshots an area trend reads, newest last; the repo trend's default window.
TREND_POINTS = 20
-#: Folded indexes, one per repository (older states are dropped): a few MB
-#: each on a 6k-file repository.
-_models = IndexStampCache(4)
+#: Folded indexes per repository and held-origin set (older index states are
+#: dropped): a few MB each on a 6k-file repository.
+_models = IndexStampCache(8)
#: Area cards, the ones a reader opens.
_details = IndexStampCache(128)
#: One build per repository at a time; a concurrent caller waits and reads the
@@ -87,6 +89,35 @@ class AreaReadModel:
weights: dict[str, int]
latest_at: datetime | None
baseline_at: datetime | None
+ #: Origins left out of every figure, empty for the whole repository.
+ held: frozenset[str] = frozenset()
+ #: Files per held origin, repository-wide, so a toggle can name its count.
+ held_counts: dict[str, int] | None = None
+
+
+def held_origins(hold: str, include: str) -> frozenset[str]:
+ """The origins a request leaves out: none by default, or the map's held set
+ (:data:`MAP_HELD_ORIGINS`) less the ones the reader brought back."""
+ if hold != "map":
+ return frozenset()
+ return map_held(o.strip().lower() for o in include.split(",") if o.strip())
+
+
+def _origin(metric: Any) -> str:
+ return stored_origin(getattr(metric, "code_origin", None), getattr(metric, "is_test", None))
+
+
+def _held_counts(metrics: list[Any]) -> dict[str, int]:
+ counts = dict.fromkeys(MAP_HELD_ORIGINS, 0)
+ for m in metrics:
+ origin = _origin(m)
+ if origin in counts and (m.nloc or 0) > 0:
+ counts[origin] += 1
+ return counts
+
+
+def _keep(score_map: dict[str, float], kept: set[str] | None) -> dict[str, float]:
+ return score_map if kept is None else {p: s for p, s in score_map.items() if p in kept}
async def _area_stamp(session: AsyncSession, repo_id: str) -> tuple[Any, ...]:
@@ -143,40 +174,54 @@ async def _commit_rows(session: AsyncSession, repo_id: str) -> list[Any]:
return list((await session.execute(q)).all())
-async def _build(session: AsyncSession, repo_id: str) -> AreaReadModel:
- metrics = await crud.get_health_metrics(session, repo_id)
+async def _build(session: AsyncSession, repo_id: str, held: frozenset[str]) -> AreaReadModel:
+ every = await crud.get_health_metrics(session, repo_id)
+ # Held origins leave every figure, not just the drawing: scores, counts,
+ # findings, owners and the snapshot deltas all describe the kept files.
+ metrics = [m for m in every if _origin(m) not in held] if held else every
+ kept = {m.file_path for m in metrics} if held else None
+ findings = await crud.get_health_findings(session, repo_id)
+ if kept is not None:
+ findings = [f for f in findings if f.file_path in kept]
git_rows = await _git_rows(session, repo_id)
index = build_area_index(
metrics,
git_rows=git_rows,
owners=file_owners(git_rows, await _commit_rows(session, repo_id)),
- findings=await crud.get_health_findings(session, repo_id),
+ findings=findings,
deductions=await crud.get_deduction_by_path(session, repo_id),
)
weights = nloc_weights(metrics)
+ counts = _held_counts(every)
history = await crud.list_health_snapshots(session, repo_id, file_maps=False)
base = baseline_index([s.taken_at for s in history])
if base is None:
- return AreaReadModel(index, weights, None, None)
+ return AreaReadModel(index, weights, None, None, held, counts)
latest, baseline = history[-1], history[base]
attach_deltas(
index.nodes,
- area_scores(await _snapshot_map(session, latest), weights),
- area_scores(await _snapshot_map(session, baseline), weights),
+ area_scores(_keep(await _snapshot_map(session, latest), kept), weights),
+ area_scores(_keep(await _snapshot_map(session, baseline), kept), weights),
)
- return AreaReadModel(index, weights, latest.taken_at, baseline.taken_at)
+ return AreaReadModel(index, weights, latest.taken_at, baseline.taken_at, held, counts)
-async def load_area_model(session: AsyncSession, repo_id: str) -> AreaReadModel:
- """The folded area index for *repo_id*, built once per index and findings state."""
- key = await _models.key(session, repo_id, await _area_stamp(session, repo_id))
+async def load_area_model(
+ session: AsyncSession, repo_id: str, held: frozenset[str] = frozenset()
+) -> AreaReadModel:
+ """The folded area index for *repo_id*, built once per index and findings
+ state and per held-origin set."""
+ stamp = await _area_stamp(session, repo_id)
+ key = await _models.key(session, repo_id, stamp, tuple(sorted(held)))
if key in _models:
return _models.get(key)
async with _locks.setdefault(repo_id, asyncio.Lock()):
if key in _models:
return _models.get(key)
- model = await _build(session, repo_id)
- _models.drop_repo(repo_id)
+ model = await _build(session, repo_id, held)
+ # An older index state is never asked for again; other held sets of
+ # this state are, as the reader toggles groups back in.
+ _models.drop_repo_except(repo_id, key[:-1])
return _models.remember(key, model)
@@ -189,7 +234,8 @@ async def warm_area_model(
the CLI) is still folded on first read."""
try:
async with get_session(session_factory) as session:
- await load_area_model(session, repo_id)
+ # The map's default view, which is what the first reader opens.
+ await load_area_model(session, repo_id, frozenset(MAP_HELD_ORIGINS))
except Exception:
logger.warning("areas_warm_failed", repo_id=repo_id, exc_info=True)
@@ -224,6 +270,17 @@ def area_tree_payload(model: AreaReadModel, root: str, depth: int) -> dict[str,
"depth": depth,
"nodes": below,
"delta_window": _delta_window(model),
+ "held": _held_block(model),
+ }
+
+
+def _held_block(model: AreaReadModel) -> dict[str, Any]:
+ """Which origins the map holds by default, which this answer left out, and
+ how many files each holds, so a toggle can name its count."""
+ return {
+ "default": list(MAP_HELD_ORIGINS),
+ "excluded": sorted(model.held),
+ "counts": model.held_counts or {},
}
@@ -233,12 +290,15 @@ async def area_detail_payload(
"""The area card, its trend read from the newest :data:`TREND_POINTS` snapshots."""
if area not in model.index.nodes:
return None
- key = await _details.key(session, repo_id, area, await _area_stamp(session, repo_id))
+ key = await _details.key(
+ session, repo_id, area, await _area_stamp(session, repo_id), tuple(sorted(model.held))
+ )
if key in _details:
return _details.get(key)
trend = []
+ kept = set(model.weights) if model.held else None
for snap in await crud.list_health_snapshots(session, repo_id, limit=TREND_POINTS):
- score = area_score(_score_map(snap.per_file_scores_json), area, model.weights)
+ score = area_score(_keep(_score_map(snap.per_file_scores_json), kept), area, model.weights)
if score is not None:
trend.append({"taken_at": _iso(snap.taken_at), "health": score})
coupled = await coupling_answer(
diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.py
index 0ef52034d..478f50e2e 100644
--- a/packages/server/src/repowise/server/services/health_map.py
+++ b/packages/server/src/repowise/server/services/health_map.py
@@ -27,7 +27,7 @@ from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.areas import in_area
-from repowise.core.analysis.finding_registry import HELD_ORIGINS
+from repowise.core.analysis.finding_registry import HELD_ORIGINS, stored_origin
from repowise.core.analysis.health.counts import DEFAULT_COUNTS
from repowise.core.analysis.health.counts import project as project_counts
from repowise.core.analysis.health.perf.coverage import supported_perf_languages
@@ -149,6 +149,7 @@ class HealthMapService:
include_held: bool = False,
query: str | None = None,
area: str | None = None,
+ held: frozenset[str] | None = None,
) -> HealthMapFeed:
session, repo_id = self._session, self._repository_id
metrics = await crud.get_health_metrics(session, repo_id)
@@ -158,7 +159,17 @@ class HealthMapService:
# performance totals below describe the area, never the repository.
metrics = [m for m in metrics if in_area(m.file_path, area)]
rollups = [r for r in rollups if in_area(r.file_path, area)]
+ if held is not None:
+ # The area map's held origins (``hold=map``) leave the field before
+ # any count, as they leave the area rollups beside it; the held set
+ # then decides vendored and generated too, even when every group
+ # was brought back and the set is empty.
+ metrics = [m for m in metrics if stored_origin(m.code_origin, m.is_test) not in held]
+ include_held = True
languages = await crud.get_file_language_map(session, repo_id)
+ # The same set ``hotspot_health`` averages over, so the hotspot lens
+ # and that KPI can never disagree about which files are hotspots.
+ hotspots = await crud.get_hotspot_file_paths(session, repo_id)
summary = await crud.get_performance_summary(session, repo_id)
perf_languages = supported_perf_languages()
@@ -192,7 +203,7 @@ class HealthMapService:
for m in drawable
if include_held or m.code_origin not in HELD_ORIGINS or m.file_path in pinned
]
- held = len(drawable) - len(eligible)
+ held_out = len(drawable) - len(eligible)
eligible_paths = {m.file_path for m in eligible}
burden = {r.file_path: r for r in rollups}
@@ -253,7 +264,7 @@ class HealthMapService:
drawn = [by_path[path] for path in chosen]
files = [
- self._row(metric, burden.get(metric.file_path), languages, perf_languages)
+ self._row(metric, burden.get(metric.file_path), languages, perf_languages, hotspots)
for metric in drawn
]
@@ -269,7 +280,7 @@ class HealthMapService:
"opportunities": sum(r.opportunities - r.expected for r in undrawn_perf),
"observations": sum(r.observations for r in undrawn_perf),
# Drawable, and left out by the vendored/generated hold, not the cap.
- "held": held,
+ "held": held_out,
}
# What the bands after the pins admitted, split the way older readers
# count it: the performance band, and everything else.
@@ -334,6 +345,7 @@ class HealthMapService:
rollup: Any,
languages: dict[str, str | None],
perf_languages: Any,
+ hotspots: set[str],
) -> dict[str, Any]:
"""One node. The lens reads the rollup; everything else is geometry.
@@ -356,6 +368,7 @@ class HealthMapService:
"performance_opportunities": rollup.opportunities - rollup.expected if rollup else 0,
"performance_observations": rollup.observations if rollup else 0,
"code_origin": metric.code_origin,
+ "is_hotspot": metric.file_path in hotspots,
}
actionability = _leading_actionability(rollup)
if actionability is not None:
diff --git a/packages/types/src/areas.ts b/packages/types/src/areas.ts
index 546f4c17d..66e27da7d 100644
--- a/packages/types/src/areas.ts
+++ b/packages/types/src/areas.ts
@@ -12,12 +12,24 @@ export type {
AreaDetailResponse as AreaDetail,
AreaFileRow,
AreaFinding,
+ AreaHeld,
AreaNode,
AreaOwner,
AreaTreeResponse as AreaTree,
} from "./generated/http.js";
-export interface AreaTreeQuery {
+/**
+ * Which files a map read covers. `hold: "map"` leaves out the origins the
+ * area map holds by default (the server names them in `AreaTree.held`);
+ * `include` brings some of them back. Omitted: every file.
+ */
+export interface MapHoldQuery {
+ hold?: "none" | "map";
+ /** Held origins to bring back, e.g. `["test"]`. */
+ include?: readonly string[];
+}
+
+export interface AreaTreeQuery extends MapHoldQuery {
/** Area to unfold; the repository root by default. */
root?: string;
/** Levels below the root, 1-4. */
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index ec4325087..57879913d 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -320,6 +320,13 @@ export interface AreaFinding {
reason: string | null;
}
+/** The origins the map holds out by default, and what this answer left out. */
+export interface AreaHeld {
+ default: string[];
+ excluded: string[];
+ counts: Record<string, number>;
+}
+
export interface AreaHotspots {
total: number;
files: AreaFileRow[];
@@ -379,6 +386,7 @@ export interface AreaTreeResponse {
depth: number;
nodes: AreaNode[];
delta_window: AreaDeltaWindow;
+ held?: AreaHeld | null;
}
export interface AreaTrendPoint {
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 1c198b393..38fa70eea 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -338,6 +338,8 @@ export interface HealthFileMetric {
* unchanged; this is a display-only secondary distinguisher.
*/
total_deduction?: number | null;
+ /** Git flags this file a hotspot (heavy recent change). Map feed only; absent on older servers. */
+ is_hotspot?: boolean;
}
export interface HealthFinding {
@@ -1029,6 +1031,10 @@ export interface HealthMapQuery {
q?: string;
/** Narrow the field to this directory; the cap and every count then describe it. */
area?: string;
+ /** `map` leaves out the origins the area map holds by default. */
+ hold?: "none" | "map";
+ /** With `hold: "map"`, held origins to bring back. */
+ include?: readonly string[];
}
/* ------------------------------------------------------------------ *
diff --git a/packages/ui/__tests__/health/area-rail.test.tsx b/packages/ui/__tests__/health/area-rail.test.tsx
new file mode 100644
index 000000000..d41b43220
--- /dev/null
+++ b/packages/ui/__tests__/health/area-rail.test.tsx
@@ -0,0 +1,244 @@
+/**
+ * The context rail and the pure pieces behind it: which areas it points at,
+ * the area lenses, the area prompt, and the card a reader acts from.
+ */
+import { describe, it, expect, vi } from "vitest";
+import { render, fireEvent } from "@testing-library/react";
+import type { AreaDetail } from "@repowise-dev/types/areas";
+
+import { deriveAreaIndex, type AreaIndex, type MapArea } from "../../src/health/map/areas.js";
+import { areasNeedingAttention, mostImproved } from "../../src/health/map/area-rank.js";
+import { KNOWLEDGE_LENS, ownerLens, shareFill } from "../../src/health/map/area-lenses.js";
+import { OVERLAY_SPECS, lensAvailable, resolveLens } from "../../src/health/map/lens-registry.js";
+import { NEUTRAL_FILL, QUIET_FILL } from "../../src/health/map/lens.js";
+import { areaFills } from "../../src/health/map/fills.js";
+import { buildAreaAiPrompt } from "../../src/health/ai-prompts/area-prompt.js";
+import { AreaCard } from "../../src/health/area-rail/area-card.js";
+import { DEFAULT_AREA_RAIL_LABELS } from "../../src/health/area-rail/labels.js";
+import { NODE_RAMP_STOP, healthBandMapFill } from "../../src/health/tokens.js";
+import { formatScore } from "@repowise-dev/types/health";
+import { scoreText } from "../../src/health/map/lens.js";
+import { mapFile as f } from "./map-test-utils.js";
+
+/** An index whose areas carry the server's ownership and delta fields. */
+function withRollups(index: AreaIndex, patch: Record<string, Partial<MapArea>>): AreaIndex {
+ const areas = new Map(index.areas);
+ for (const [path, p] of Object.entries(patch)) areas.set(path, { ...areas.get(path)!, ...p });
+ return { ...index, areas };
+}
+
+const files = [
+ ...Array.from({ length: 6 }, (_, i) => f(`app/bad/x${i}.py`, 50, "app", { score: 3 })),
+ ...Array.from({ length: 6 }, (_, i) => f(`app/bad/inner/y${i}.py`, 50, "app", { score: 2 })),
+ ...Array.from({ length: 6 }, (_, i) => f(`app/ok/z${i}.py`, 50, "app", { score: 7 })),
+ ...Array.from({ length: 6 }, (_, i) => f(`lib/w${i}.py`, 50, "lib", { score: 9 })),
+ f("lib/tiny/t.py", 5, "lib", { score: 1 }),
+];
+const index = deriveAreaIndex(files);
+
+describe("where the rail points", () => {
+ it("names the worst places, never one nested in another and never a sliver", () => {
+ const picks = areasNeedingAttention(index).map((a) => a.path);
+ expect(picks[0]).toBe("app/bad/inner");
+ expect(picks).not.toContain("app/bad"); // contains the first pick
+ expect(picks).not.toContain("lib/tiny"); // one file is a detail
+ });
+
+ it("scopes to the selected area", () => {
+ expect(areasNeedingAttention(index, "lib").map((a) => a.path)).toEqual([]);
+ expect(areasNeedingAttention(index, "app").map((a) => a.path)).toContain("app/ok");
+ });
+
+ it("names the area that improved most, and nothing when none did", () => {
+ expect(mostImproved(index)).toBeNull();
+ const up = withRollups(index, { lib: { delta30d: 0.4 }, app: { delta30d: 0.9 } });
+ expect(mostImproved(up)!.path).toBe("app");
+ });
+});
+
+describe("area lenses", () => {
+ it("knowledge risk bands the share only one person has changed", () => {
+ const a = { ...index.areas.get("lib")!, busFactor1Count: 6 };
+ expect(KNOWLEDGE_LENS.areaFill!(a)).toBe(NODE_RAMP_STOP.alert);
+ expect(KNOWLEDGE_LENS.areaText!(a)).toBe("86%");
+ expect(shareFill(0.1, [0.25, 0.5, 0.75])).toBe(QUIET_FILL);
+ expect(shareFill(null, [0.25, 0.5, 0.75])).toBe(NEUTRAL_FILL);
+ });
+
+ it("main author colours each area by its lead and keys every colour by name", () => {
+ const owned = withRollups(index, {
+ app: { primaryOwner: { key: "ada", name: "Ada Lovelace", share: 0.8 } },
+ "app/bad": { primaryOwner: { key: "ada", name: "Ada Lovelace", share: 0.9 } },
+ lib: { primaryOwner: { key: "bob", name: "Bob", share: 0.6 } },
+ });
+ const lens = ownerLens(owned);
+ const ada = lens.areaFill!(owned.areas.get("app")!);
+ expect(ada).not.toBe(lens.areaFill!(owned.areas.get("lib")!));
+ expect(lens.legend.map((r) => r.label)).toContain("Ada Lovelace");
+ expect(lens.areaText!(owned.areas.get("app")!)).toBe("Ada 80%");
+ // An area with no owner signal at all says so, rather than borrowing a colour.
+ expect(lens.areaFill!(owned.areas.get("lib/tiny")!)).toBeNull();
+ });
+
+ it("offers an area lens only where the rollup carries its signal", () => {
+ expect(lensAvailable("owner", files, index)).toBe(false);
+ expect(lensAvailable("knowledge", files, withRollups(index, { lib: { busFactor1Count: 1 } }))).toBe(true);
+ expect(resolveLens("owner", index).id).toBe("owner");
+ });
+
+ it("colours an area by its rollup, else by its loaded files", () => {
+ const fills = areaFills(index, OVERLAY_SPECS.health, files).fill;
+ expect(fills.get("app/bad/inner")).toBe(healthBandMapFill("at_risk"));
+ const maint = areaFills(index, OVERLAY_SPECS.maintainability, files).fill;
+ expect(maint.get("lib")).toBe(NEUTRAL_FILL); // no maintainability on these rows
+ });
+});
+
+const detail: AreaDetail = {
+ area: {
+ path: "app",
+ name: "app",
+ depth: 1,
+ parent: "",
+ has_children: true,
+ direct_file_count: 0,
+ file_count: 18,
+ nloc: 900,
+ health: 4.2,
+ band: "needs_work",
+ band_counts: { at_risk: 12, needs_work: 0, fair: 0, good: 6, excellent: 0 },
+ worst_file: { path: "app/bad/inner/y0.py", score: 2 },
+ hotspot_count: 3,
+ bus_factor_1_count: 5,
+ primary_owner: { key: "ada", name: "Ada Lovelace", kind: "human", files: 15, share: 0.83 },
+ line_coverage_pct: null,
+ coverage_file_count: 0,
+ findings: { critical: 0, high: 2, medium: 0, low: 0 },
+ health_delta_30d: 0.42,
+ },
+ distribution: {
+ total_files: 18,
+ total_nloc: 900,
+ bands: {
+ at_risk: { files: 12, nloc: 600, pct: 66.7 },
+ needs_work: { files: 0, nloc: 0, pct: 0 },
+ fair: { files: 0, nloc: 0, pct: 0 },
+ good: { files: 6, nloc: 300, pct: 33.3 },
+ excellent: { files: 0, nloc: 0, pct: 0 },
+ },
+ },
+ worst_files: [{ path: "app/bad/inner/y0.py", score: 2, band: "at_risk", nloc: 50 }],
+ hotspots: { total: 3, files: [] },
+ owners: { total: 1, top: [{ key: "ada", name: "Ada Lovelace", kind: "human", files: 15, share: 0.83 }] },
+ trend: [
+ { taken_at: "2026-09-20T00:00:00", health: 3.8 },
+ { taken_at: "2026-10-18T00:00:00", health: 4.2 },
+ ],
+ top_findings: [
+ {
+ id: "f1",
+ file_path: "app/bad/inner/y0.py",
+ biomarker_type: "complex_method",
+ severity: "high",
+ function_name: "run",
+ line_start: 12,
+ health_impact: 1.2,
+ reason: "run branches 30 ways",
+ },
+ {
+ id: "f2",
+ file_path: "app/bad/x0.py",
+ biomarker_type: "large_method",
+ severity: "high",
+ function_name: "load",
+ line_start: 3,
+ health_impact: 0.8,
+ reason: "load is 400 lines",
+ },
+ ],
+ test_reach: { files: 18, with_test_file: 4, measured_files: 0, line_coverage_pct: null },
+ delta_window: { target_days: 30, latest_at: "2026-10-18T00:00:00", baseline_at: "2026-09-20T00:00:00" },
+};
+
+describe("the area prompt", () => {
+ it("names the area, groups findings by file and keeps the shared closing", () => {
+ const text = buildAreaAiPrompt({
+ area: "app",
+ score: 4.2,
+ fileCount: 18,
+ findings: detail.top_findings,
+ worstFiles: detail.worst_files,
+ flavor: "claude-code-mcp",
+ });
+ expect(text).toContain("`app/`");
+ expect(text).toContain("### `app/bad/inner/y0.py`");
+ expect(text).toContain("## Findings to work through (2)");
+ expect(text).toContain("get_health");
+ expect(text).toContain("## Hard constraints");
+ });
+});
+
+describe("the area card", () => {
+ const props = {
+ detail,
+ index,
+ nameOf: (p: string) => p,
+ labels: DEFAULT_AREA_RAIL_LABELS,
+ onSelectArea: vi.fn(),
+ onSelectFile: vi.fn(),
+ openPrompt: vi.fn(),
+ };
+
+ it("prints the root score exactly as the page headline does", () => {
+ // The headline and the overview both say 8.08. formatScore truncates so a
+ // figure never reads as a better band than it is; the map and rail must
+ // print the same digits, not round 8.08 up to 8.1 beside an 8.0 headline.
+ const repo = { ...detail, area: { ...detail.area, path: "", health: 8.08, band: "good" as const } };
+ const { getByText } = render(<AreaCard {...props} detail={repo} />);
+ expect(formatScore(8.08)).toBe("8.0");
+ expect(getByText("8.0")).toBeInTheDocument();
+ expect(OVERLAY_SPECS.health.areaText!({ ...index.areas.get("")!, health: 8.08 })).toBe("8.0");
+ expect(scoreText(f("a.py", 10, null, { score: 8.08 }))).toBe("8.0");
+ });
+
+ it("leads with the score, its band word and the good news when it improved", () => {
+ const { getByText, getByTestId } = render(<AreaCard {...props} />);
+ expect(getByText("4.2")).toBeInTheDocument();
+ expect(getByText("Needs work")).toBeInTheDocument();
+ expect(getByTestId("area-improved").textContent).toContain("+0.42");
+ });
+
+ it("makes the agent prompt for the area's findings its one filled action", () => {
+ const openPrompt = vi.fn();
+ const { getByRole } = render(<AreaCard {...props} openPrompt={openPrompt} />);
+ fireEvent.click(getByRole("button", { name: "Copy prompt for the top 2 findings" }));
+ const req = openPrompt.mock.calls[0]![0];
+ expect(req.getPrompt("generic")).toContain("app/bad/x0.py");
+ });
+
+ it("opens sub-areas on the map and files in the rail", () => {
+ const onSelectArea = vi.fn();
+ const onSelectFile = vi.fn();
+ const { getAllByRole } = render(<AreaCard {...props} onSelectArea={onSelectArea} onSelectFile={onSelectFile} />);
+ fireEvent.click(getAllByRole("button", { name: /app\/bad\/inner/ })[0]!);
+ expect(onSelectArea).toHaveBeenCalledWith("app/bad/inner");
+ fireEvent.click(getAllByRole("button", { name: /y0\.py/ })[0]!);
+ expect(onSelectFile).toHaveBeenCalledWith("app/bad/inner/y0.py");
+ });
+
+ it("names a clean area with its scope instead of offering an empty prompt", () => {
+ const { getByText, queryByRole } = render(<AreaCard {...props} detail={{ ...detail, top_findings: [] }} />);
+ expect(getByText("No open findings across 18 files.")).toBeInTheDocument();
+ expect(queryByRole("button", { name: /Copy prompt/ })).not.toBeInTheDocument();
+ });
+
+ it("links out only where the host gave a destination", () => {
+ const onNavigate = vi.fn();
+ const { getByRole, queryByRole } = render(
+ <AreaCard {...props} links={{ findings: "/f?area=app" }} onNavigate={onNavigate} />,
+ );
+ fireEvent.click(getByRole("link", { name: "Findings here" }));
+ expect(onNavigate).toHaveBeenCalledWith("/f?area=app");
+ expect(queryByRole("link", { name: "Contributors here" })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/health/area-source.test.tsx b/packages/ui/__tests__/health/area-source.test.tsx
new file mode 100644
index 000000000..76ae26af3
--- /dev/null
+++ b/packages/ui/__tests__/health/area-source.test.tsx
@@ -0,0 +1,90 @@
+/**
+ * The lazy area source: one request per need, a reveal that walks down to a
+ * deep link, and files that cover everything below where they were loaded.
+ */
+import { describe, it, expect, vi } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { AreaTree } from "@repowise-dev/types/areas";
+import type { HealthMapFeed } from "@repowise-dev/types/health";
+
+import { useAreaSource } from "../../src/health/map/use-area-source.js";
+
+function n(path: string, depth: number, hasChildren = true) {
+ return {
+ path,
+ name: path.split("/").pop() ?? "",
+ depth,
+ parent: depth === 0 ? null : path.split("/").slice(0, -1).join("/"),
+ has_children: hasChildren,
+ direct_file_count: hasChildren ? 0 : 1,
+ file_count: 1,
+ nloc: 10,
+ health: 8,
+ band: "good" as const,
+ band_counts: { at_risk: 0, needs_work: 0, fair: 0, good: 1, excellent: 0 },
+ worst_file: { path: null, score: 8 },
+ hotspot_count: 0,
+ bus_factor_1_count: 0,
+ primary_owner: null,
+ line_coverage_pct: null,
+ coverage_file_count: 0,
+ findings: { critical: 0, high: 0, medium: 0, low: 0 },
+ health_delta_30d: null,
+ };
+}
+
+/** A chain a/b/c/d/e/f below the root, served `depth` levels at a time. */
+const CHAIN = ["a", "a/b", "a/b/c", "a/b/c/d", "a/b/c/d/e", "a/b/c/d/e/f"];
+function serveTree(root: string, depth: number): Promise<AreaTree> {
+ const rootDepth = root ? root.split("/").length : 0;
+ const nodes = CHAIN.filter((p) => p.startsWith(root ? `${root}/` : "") && p !== root)
+ .map((p) => n(p, p.split("/").length, p !== "a/b/c/d/e/f"))
+ .filter((x) => x.depth <= rootDepth + depth);
+ return Promise.resolve({
+ root: n(root, rootDepth),
+ depth,
+ nodes,
+ delta_window: { target_days: 30, latest_at: null, baseline_at: null },
+ });
+}
+
+const feed = (paths: string[]) =>
+ Promise.resolve({ files: paths.map((file_path) => ({ file_path, nloc: 10, score: 8 })) } as unknown as HealthMapFeed);
+
+describe("useAreaSource", () => {
+ it("starts from the root and unfolds a reveal down to a deep area", async () => {
+ const getAreaTree = vi.fn(serveTree);
+ const { result } = renderHook(() =>
+ useAreaSource({ getAreaTree, getAreaFiles: vi.fn(() => feed([])) }, "k"),
+ );
+ await waitFor(() => expect(result.current.index.areas.has("")).toBe(true));
+ act(() => result.current.reveal("a/b/c/d/e/f"));
+ await waitFor(() => expect(result.current.index.areas.has("a/b/c/d/e/f")).toBe(true));
+ // Root first (two levels), then reveal steps of four from the deepest known.
+ expect(getAreaTree.mock.calls[0]).toEqual(["", 2]);
+ expect(getAreaTree.mock.calls.some(([root, depth]) => root === "a/b" && depth === 4)).toBe(true);
+ });
+
+ it("loads an area's files once, and that load covers what is under it", async () => {
+ const getAreaFiles = vi.fn(() => feed(["a/b/x.py", "a/y.py"]));
+ const { result } = renderHook(() => useAreaSource({ getAreaTree: serveTree, getAreaFiles }, "k"));
+ await waitFor(() => expect(result.current.index.areas.has("")).toBe(true));
+ act(() => result.current.request({ children: [], files: ["a"] }));
+ act(() => result.current.request({ children: [], files: ["a", "a/b"] }));
+ await waitFor(() => expect(result.current.files).toHaveLength(2));
+ expect(getAreaFiles).toHaveBeenCalledTimes(1);
+ expect(result.current.filesCovered("a/b/c")).toBe(true);
+ expect(result.current.filesCovered("z")).toBe(false);
+ });
+
+ it("starts over for a new repository or reading", async () => {
+ const getAreaTree = vi.fn(serveTree);
+ const fetchers = { getAreaTree, getAreaFiles: vi.fn(() => feed([])) };
+ const { result, rerender } = renderHook(({ key }) => useAreaSource(fetchers, key), {
+ initialProps: { key: "one" },
+ });
+ await waitFor(() => expect(result.current.index.areas.has("")).toBe(true));
+ rerender({ key: "two" });
+ await waitFor(() => expect(getAreaTree.mock.calls.filter(([r]) => r === "").length).toBeGreaterThanOrEqual(2));
+ });
+});
diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsx
index 2d7347bf8..19c792e61 100644
--- a/packages/ui/__tests__/health/code-health-map.test.tsx
+++ b/packages/ui/__tests__/health/code-health-map.test.tsx
@@ -5,14 +5,13 @@ import {
MapLegend,
NEUTRAL_FILL,
MapLensSwitcher,
- groupByModule,
performanceBurden,
performanceFill,
performanceSentence,
type CodeHealthMapFile,
} from "../../src/health/code-health-map.js";
import { NODE_RAMP_STOP } from "../../src/health/tokens.js";
-import { nodeAt, stubMapEnvironment } from "./map-test-utils.js";
+import { nextFrame, nodeAt, stubMapEnvironment } from "./map-test-utils.js";
function f(
file_path: string,
@@ -25,36 +24,13 @@ function f(
beforeAll(stubMapEnvironment);
-describe("groupByModule", () => {
- it("groups files by module, sums NLOC, sorts files biggest-first", () => {
- const galaxies = groupByModule([
- f("a/x.py", 100, "core"),
- f("a/y.py", 40, "core"),
- f("b/z.py", 60, "ui"),
- ]);
- const core = galaxies.find((g) => g.module === "core");
- expect(core?.files).toHaveLength(2);
- expect(core?.totalNloc).toBe(140);
- expect(core?.maxNloc).toBe(100);
- expect(core?.files.map((x) => x.nloc)).toEqual([100, 40]); // desc
- // Galaxies themselves are ordered by total size (core 140 > ui 60).
- expect(galaxies[0]?.module).toBe("core");
- });
-
- it("drops zero-NLOC files and buckets a null module as (ungrouped)", () => {
- const galaxies = groupByModule([f("a.py", 0, "core"), f("b.py", 20, null)]);
- expect(galaxies.find((g) => g.module === "core")).toBeUndefined();
- expect(galaxies.find((g) => g.module === "(ungrouped)")?.files).toHaveLength(1);
- });
-});
-
describe("CodeHealthMap", () => {
it("renders the empty state when there are no files", () => {
const { getByText } = render(<CodeHealthMap files={[]} />);
expect(getByText(/No files to map yet/i)).toBeInTheDocument();
});
- it("opens a file when its node is clicked", () => {
+ it("opens a file when its node is clicked", async () => {
const onSelectFile = vi.fn();
const files = [
f("core/a.py", 120, "core", 3),
@@ -62,6 +38,7 @@ describe("CodeHealthMap", () => {
f("ui/c.py", 40, "ui", 6),
];
const { getByTestId } = render(<CodeHealthMap files={files} onSelectFile={onSelectFile} />);
+ await nextFrame();
fireEvent.click(getByTestId("map-canvas"), nodeAt(files, "core/a.py"));
expect(onSelectFile).toHaveBeenCalledWith("core/a.py");
});
@@ -76,48 +53,49 @@ describe("CodeHealthMap", () => {
expect(container.querySelectorAll("canvas")).toHaveLength(2);
});
- it("zooms into a galaxy from its name and Escape returns to the overview", async () => {
+ it("opens an area from its name, and Escape returns to the repository", async () => {
const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
- const { getByText, queryByText, getByRole, findByRole } = render(<CodeHealthMap files={files} />);
- // Names are placed by the frame loop, and a field this small names all.
- fireEvent.click(await findByRole("button", { name: "core" }));
- expect(getByText("← Overview")).toBeInTheDocument();
+ const { getByRole, getByTestId } = render(<CodeHealthMap files={files} />);
+ await nextFrame();
+ fireEvent.click(getByTestId("map-field").parentElement!.querySelector('[data-area="core"]')!);
+ expect(getByTestId("map-field").getAttribute("data-area")).toBe("core");
+ expect(getByRole("navigation", { name: "Breadcrumb" }).textContent).toContain("core");
fireEvent.keyDown(getByRole("group", { name: /Code health map/ }), { key: "Escape" });
- expect(queryByText("← Overview")).not.toBeInTheDocument();
+ expect(getByTestId("map-field").getAttribute("data-area")).toBe("");
+ });
+
+ it("Backspace climbs one level and the breadcrumb climbs to any", () => {
+ const onAreaChange = vi.fn();
+ const files = [f("pkg/core/a.py", 120, "core"), f("pkg/core/b.py", 20, "core"), f("pkg/ui/c.py", 40, "ui")];
+ const { getByRole } = render(<CodeHealthMap files={files} area="pkg/core" onAreaChange={onAreaChange} />);
+ fireEvent.keyDown(getByRole("group", { name: /Code health map/ }), { key: "Backspace" });
+ expect(onAreaChange).toHaveBeenLastCalledWith("pkg");
+ fireEvent.click(getByRole("button", { name: "Repository" }));
+ expect(onAreaChange).toHaveBeenLastCalledWith("");
});
- it("leaves an Escape aimed at something else alone", async () => {
- // The listener used to be on the window, so dismissing anything else on
- // the page - the file drawer this map opens, most of all - also reset the
- // zoom underneath it.
+ it("leaves an Escape aimed at something else alone", () => {
+ const onAreaChange = vi.fn();
const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
- const { getByText, findByRole } = render(<CodeHealthMap files={files} />);
- fireEvent.click(await findByRole("button", { name: "core" }));
+ render(<CodeHealthMap files={files} area="core" onAreaChange={onAreaChange} />);
fireEvent.keyDown(document.body, { key: "Escape" });
- expect(getByText("← Overview")).toBeInTheDocument();
+ expect(onAreaChange).not.toHaveBeenCalled();
});
- it("keeps an Escape it used from reaching the drawer behind it", async () => {
- // The file drawer dismisses on a document-level capture listener; one
- // press must not both leave the galaxy and close the drawer.
+ it("keeps an Escape it used from reaching anything behind it", () => {
const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
- const { getByRole, findByRole, queryByText } = render(<CodeHealthMap files={files} />);
- fireEvent.click(await findByRole("button", { name: "core" }));
- const drawer = vi.fn();
- document.addEventListener("keydown", drawer, true);
- const field = getByRole("group", { name: /Code health map/ });
- fireEvent.keyDown(field, { key: "Escape" });
- expect(queryByText("← Overview")).not.toBeInTheDocument();
- expect(drawer).not.toHaveBeenCalled();
- // With nothing left to climb out of, the next Escape is the drawer's.
- fireEvent.keyDown(field, { key: "Escape" });
- expect(drawer).toHaveBeenCalledTimes(1);
- document.removeEventListener("keydown", drawer, true);
+ const { getByRole, getByTestId } = render(<CodeHealthMap files={files} area="core" onAreaChange={vi.fn()} />);
+ const behind = vi.fn();
+ document.addEventListener("keydown", behind, true);
+ fireEvent.keyDown(getByRole("group", { name: /Code health map/ }), { key: "Escape" });
+ expect(behind).not.toHaveBeenCalled();
+ document.removeEventListener("keydown", behind, true);
+ expect(getByTestId("map-field").getAttribute("data-area")).toBe("core");
});
it("offers zoom and fit controls with names", () => {
const { getByRole } = render(<CodeHealthMap files={[f("a.py", 30, "core")]} />);
- for (const name of ["Zoom in", "Zoom out", "Fit the whole field"]) {
+ for (const name of ["Zoom in", "Zoom out", "Frame the selected area"]) {
expect(getByRole("button", { name })).toBeInTheDocument();
}
});
@@ -125,7 +103,7 @@ describe("CodeHealthMap", () => {
it("shows the on-canvas health legend on the five canonical bands", () => {
const { getByText } = render(<CodeHealthMap files={[f("a.py", 30, "core")]} />);
expect(getByText("Code health")).toBeInTheDocument();
- expect(getByText(/galaxy = module/i)).toBeInTheDocument();
+ expect(getByText(/disc = folder/i)).toBeInTheDocument();
expect(getByText("Excellent · 8.5+")).toBeInTheDocument();
expect(getByText("Good · 7.0 to 8.5")).toBeInTheDocument();
expect(getByText("Fair · 5.5 to 7.0")).toBeInTheDocument();
@@ -257,10 +235,28 @@ describe("map chrome, off canvas", () => {
expect(onOverlayChange).toHaveBeenCalledWith("performance");
});
+ it("puts the lenses past the primary ones behind More, and keeps the active one visible", () => {
+ const onOverlayChange = vi.fn();
+ const lenses = ["health", "hotspot", "owner", "performance", "coverage"] as const;
+ const primary = ["health", "hotspot", "owner"] as const;
+ const { getByRole, queryByRole, rerender } = render(
+ <MapLensSwitcher overlay="health" onOverlayChange={onOverlayChange} lenses={[...lenses]} primary={[...primary]} />,
+ );
+ expect(queryByRole("radio", { name: "Performance" })).not.toBeInTheDocument();
+ fireEvent.click(getByRole("button", { name: "More" }));
+ fireEvent.click(getByRole("menuitemradio", { name: "Performance" }));
+ expect(onOverlayChange).toHaveBeenCalledWith("performance");
+ rerender(
+ <MapLensSwitcher overlay="performance" onOverlayChange={onOverlayChange} lenses={[...lenses]} primary={[...primary]} />,
+ );
+ expect(getByRole("radio", { name: "Performance" })).toBeChecked();
+ });
+
it("MapLegend renders the active lens's bands and caption", () => {
const { getByText } = render(<MapLegend overlay="performance" />);
expect(getByText("5 or more")).toBeInTheDocument();
- expect(getByText("Nothing surfaced")).toBeInTheDocument();
+ expect(getByText("Nothing surfaced or not analysed")).toBeInTheDocument();
+ expect(getByText("No issues found")).toBeInTheDocument();
// The caption refuses the runtime claim the colour could be read as making,
// and the rows are grouped so a flat column of swatches is not the whole key.
expect(getByText(/never a runtime measurement/i)).toBeInTheDocument();
diff --git a/packages/ui/__tests__/health/map-held.test.tsx b/packages/ui/__tests__/health/map-held.test.tsx
new file mode 100644
index 000000000..4baced48a
--- /dev/null
+++ b/packages/ui/__tests__/health/map-held.test.tsx
@@ -0,0 +1,58 @@
+/**
+ * The groups the map holds out by default: named with their counts in the
+ * canvas footer, each a toggle, and the scope the figures cover named in words.
+ */
+import { describe, it, expect, vi } from "vitest";
+import { render, fireEvent } from "@testing-library/react";
+import { LoadedNote } from "../../src/health/map/scope-note.js";
+import { DEFAULT_MAP_CANVAS_LABELS } from "../../src/health/map/canvas-labels.js";
+import { DEFAULT_AREA_RAIL_LABELS } from "../../src/health/area-rail/labels.js";
+import { scopeName } from "../../src/health/area-map-section.js";
+
+const held = {
+ default: ["test", "docs_example", "build", "vendored", "generated"],
+ counts: { test: 1755, docs_example: 27, build: 2, vendored: 0, generated: 0 },
+};
+
+describe("held groups in the canvas footer", () => {
+ it("offers a toggle per held group that has files, with its count", () => {
+ const onChange = vi.fn();
+ const { getByRole, queryByRole } = render(
+ <LoadedNote loaded={10} total={20} matches={null} labels={DEFAULT_MAP_CANVAS_LABELS} held={{ ...held, include: [], onChange }} />,
+ );
+ fireEvent.click(getByRole("button", { name: "Show test files (1,755)" }));
+ expect(onChange).toHaveBeenCalledWith(["test"]);
+ expect(getByRole("button", { name: "Show build files (2)" })).toBeInTheDocument();
+ // A group with no files offers nothing to show.
+ expect(queryByRole("button", { name: /vendored/ })).not.toBeInTheDocument();
+ });
+
+ it("turns a shown group back off", () => {
+ const onChange = vi.fn();
+ const { getByRole } = render(
+ <LoadedNote loaded={10} total={20} matches={null} labels={DEFAULT_MAP_CANVAS_LABELS} held={{ ...held, include: ["test", "build"], onChange }} />,
+ );
+ // The verb carries the state; aria-pressed beside it read as "Hide, pressed".
+ const hide = getByRole("button", { name: "Hide test files" });
+ expect(hide).not.toHaveAttribute("aria-pressed");
+ fireEvent.click(hide);
+ expect(onChange).toHaveBeenCalledWith(["build"]);
+ });
+});
+
+describe("the scope the figures cover", () => {
+ it("names production code, all code, or what was brought back", () => {
+ expect(scopeName(held, [], DEFAULT_AREA_RAIL_LABELS)).toBe("Production code");
+ expect(scopeName(held, ["test", "docs_example", "build"], DEFAULT_AREA_RAIL_LABELS)).toBe("All code");
+ expect(scopeName(held, ["test"], DEFAULT_AREA_RAIL_LABELS)).toBe("Production code and test files");
+ });
+});
+
+describe("the hold on the wire", () => {
+ it("sends the brought-back groups sorted, so two toggle orders are one request", async () => {
+ const { holdParams } = await import("../../../api-client/src/areas.js");
+ expect(holdParams({ hold: "map", include: ["test", "build"] })).toEqual({ hold: "map", include: "build,test" });
+ expect(holdParams({ hold: "map", include: ["build", "test"] })).toEqual({ hold: "map", include: "build,test" });
+ expect(holdParams({})).toEqual({});
+ });
+});
diff --git a/packages/ui/__tests__/health/map-layout.test.ts b/packages/ui/__tests__/health/map-layout.test.ts
index dfc30287b..30093fa83 100644
--- a/packages/ui/__tests__/health/map-layout.test.ts
+++ b/packages/ui/__tests__/health/map-layout.test.ts
@@ -1,116 +1,252 @@
/**
- * The field's geometry and picking, as pure functions: it must read for a
- * five-file repository and for an eight-thousand-file one, and stay cheap.
+ * The area map's geometry, semantic zoom and picking, as pure functions: it
+ * must read for a five-file repository and for an eight-thousand-file one,
+ * load lazily without moving anything already drawn, and stay cheap.
*/
import { describe, it, expect } from "vitest";
+import type { AreaNode, AreaTree } from "@repowise-dev/types/areas";
+import { WORLD, fitCamera } from "../../src/health/map/layout.js";
+import { EMPTY_AREA_INDEX, deriveAreaIndex, mergeAreaTree } from "../../src/health/map/areas.js";
import {
- MAX_GALAXIES,
- WORLD,
- fitCamera,
- galaxyKeyFor,
- layoutField,
-} from "../../src/health/map/layout.js";
+ areaTrail,
+ chainEnd,
+ displayChildren,
+ displayLabel,
+ displayParent,
+ hostOf,
+} from "../../src/health/map/area-paths.js";
+import { layoutAreas, layoutFiles, type Circle } from "../../src/health/map/area-layout.js";
+import { OPEN_PX, computeView, discAt } from "../../src/health/map/area-view.js";
import { buildHitGrid, hitTest } from "../../src/health/map/hit-test.js";
import { buildScene, groupBatches, parseCssColour } from "../../src/health/map/paint.js";
-import { OVERLAY_SPECS } from "../../src/health/map/lens.js";
+import { OVERLAY_SPECS } from "../../src/health/map/lens-registry.js";
import type { CodeHealthMapFile } from "../../src/health/map/types.js";
import { mapFile as f } from "./map-test-utils.js";
-/** A synthetic repository: `n` files over `modules` modules, sizes skewed. */
+/** A synthetic repository: `n` files over `modules` packages, sizes skewed. */
function synthetic(n: number, modules: number): CodeHealthMapFile[] {
return Array.from({ length: n }, (_, i) => {
const m = i % modules;
- return f(`pkg${m}/sub${i % 7}/file${i}.py`, 5 + ((i * 7919) % 900), `pkg${m}`, {
+ return f(`pkg${m}/sub${i % 7}/deep${i % 3}/file${i}.py`, 5 + ((i * 7919) % 900), `pkg${m}`, {
score: 1 + ((i * 31) % 90) / 10,
});
});
}
-const allNodes = (files: CodeHealthMapFile[]) => layoutField(files).flatMap((g) => g.nodes);
+const inside = (inner: Circle, outer: Circle, eps = 1e-6) =>
+ Math.hypot(inner.x - outer.x, inner.y - outer.y) + inner.r <= outer.r + eps;
+
+/** A server area node with the fields the map reads. */
+function node(path: string, parent: string | null, file_count: number, nloc: number, extra: Partial<AreaNode> = {}): AreaNode {
+ return {
+ path,
+ name: path.split("/").pop() ?? "",
+ depth: path ? path.split("/").length : 0,
+ parent,
+ has_children: false,
+ direct_file_count: 0,
+ file_count,
+ nloc,
+ health: 7,
+ band: "good",
+ band_counts: { at_risk: 0, needs_work: 0, fair: 0, good: file_count, excellent: 0 },
+ worst_file: { path: null, score: 7 },
+ hotspot_count: 0,
+ bus_factor_1_count: 0,
+ primary_owner: null,
+ line_coverage_pct: null,
+ coverage_file_count: 0,
+ findings: { critical: 0, high: 0, medium: 0, low: 0 },
+ health_delta_30d: null,
+ ...extra,
+ };
+}
+
+function tree(root: AreaNode, depth: number, nodes: AreaNode[]): AreaTree {
+ return { root, depth, nodes, delta_window: { target_days: 30, latest_at: null, baseline_at: null } };
+}
+
+describe("the area hierarchy", () => {
+ const files = [
+ f("README.md", 10, null),
+ f("packages/core/src/lib/a.py", 300, "core"),
+ f("packages/core/src/lib/b.py", 100, "core"),
+ f("packages/core/src/api.py", 50, "core"),
+ f("packages/ui/c.ts", 80, "ui"),
+ ];
+ const index = deriveAreaIndex(files);
+
+ it("derives every directory with its rollup from a flat feed", () => {
+ expect(index.areas.get("")!.fileCount).toBe(5);
+ expect(index.areas.get("packages/core")!.nloc).toBe(450);
+ expect(index.areas.get("packages/core/src")!.directFileCount).toBe(1);
+ // NLOC-weighted, the server's fold: every file here scores 7.
+ expect(index.areas.get("packages")!.health).toBe(7);
+ expect(index.areas.get("packages")!.band).toBe("good");
+ });
+
+ it("counts an empty file in its folders, as the server does, without weighing it as code", () => {
+ const withEmpty = deriveAreaIndex([
+ f("lib/a.py", 100, null, { score: 9 }),
+ f("lib/__init__.py", 0, null, { score: 1 }),
+ ]);
+ const lib = withEmpty.areas.get("lib")!;
+ expect([lib.fileCount, lib.directFileCount, lib.nloc]).toEqual([2, 2, 100]);
+ // Weighted with the floor of 1: (9 * 100 + 1 * 1) / 101.
+ expect(lib.health).toBe(8.92);
+ });
+
+ it("collapses a directory chain into one disc named by the whole chain", () => {
+ // packages/core holds only src: one disc, named "core/src".
+ expect(chainEnd(index, "packages/core")).toBe("packages/core/src");
+ expect(displayChildren(index, "packages")).toEqual(["packages/core/src", "packages/ui"]);
+ expect(displayParent(index, "packages/core/src")).toBe("packages");
+ expect(displayLabel(index, "packages/core/src", "Repo")).toBe("core/src");
+ expect(areaTrail(index, "packages/core/src/lib")).toEqual([
+ "",
+ "packages",
+ "packages/core/src",
+ "packages/core/src/lib",
+ ]);
+ });
+
+ it("hosts each file in its own directory's slot", () => {
+ expect(hostOf(index, "packages/core/src/api.py")).toEqual({ area: "packages/core/src", direct: true });
+ expect(hostOf(index, "README.md")).toEqual({ area: "", direct: true });
+ });
+
+ it("hosts a file under an area not unfolded yet in that area's whole disc", () => {
+ const lazy = mergeAreaTree(
+ EMPTY_AREA_INDEX,
+ tree(node("", null, 3, 300, { has_children: true }), 1, [
+ node("src", "", 3, 300, { has_children: true }),
+ ]),
+ );
+ expect(lazy.expanded.has("")).toBe(true);
+ expect(lazy.expanded.has("src")).toBe(false);
+ expect(hostOf(lazy, "src/deep/x.py")).toEqual({ area: "src", direct: false });
+ });
+});
+
+describe("nested layout", () => {
+ const files = synthetic(1200, 6);
+ const index = deriveAreaIndex(files);
+ const geo = layoutAreas(index);
-describe("layout for any size", () => {
it("is deterministic", () => {
- const files = synthetic(500, 9);
- expect(layoutField(files)).toEqual(layoutField([...files].reverse()));
+ expect([...layoutAreas(deriveAreaIndex(files)).circles]).toEqual([...geo.circles]);
});
- it("keeps every node inside the world square", () => {
- for (const n of allNodes(synthetic(2000, 30))) {
- expect(n.x - n.r).toBeGreaterThanOrEqual(-1e-6);
- expect(n.y - n.r).toBeGreaterThanOrEqual(-1e-6);
- expect(n.x + n.r).toBeLessThanOrEqual(WORLD + 1e-6);
- expect(n.y + n.r).toBeLessThanOrEqual(WORLD + 1e-6);
+ it("nests every disc inside its parent and keeps siblings apart", () => {
+ for (const [path, c] of geo.circles) {
+ const parent = displayParent(index, path);
+ if (parent === null) continue;
+ expect(inside(c, geo.circles.get(parent)!)).toBe(true);
+ const sibs = displayChildren(index, parent).filter((s) => s !== path);
+ for (const s of sibs) {
+ const o = geo.circles.get(s)!;
+ expect(Math.hypot(c.x - o.x, c.y - o.y)).toBeGreaterThanOrEqual(c.r + o.r - 1e-6);
+ }
}
});
- it("caps node size, so a tiny repository draws dots and not plates", () => {
- const files = [f("a.py", 400, "src"), f("b.py", 90, "src"), f("c.py", 12, "src")];
- const cam = fitCamera(900, 720);
- for (const n of allNodes(files)) expect(n.r * cam.scale).toBeLessThanOrEqual(18);
- });
-
- it("gives a file the same size in any galaxy", () => {
- const files = [
- f("big/a.py", 100, "big"),
- ...Array.from({ length: 50 }, (_, i) => f(`big/x${i}.py`, 300, "big")),
- f("small/b.py", 100, "small"),
- ];
- const nodes = allNodes(files);
- const a = nodes.find((n) => n.file.file_path === "big/a.py")!;
- const b = nodes.find((n) => n.file.file_path === "small/b.py")!;
- expect(a.r).toBeCloseTo(b.r, 9);
- });
-
- it("never lets two dots overlap", () => {
- // Circle packing guarantees it, so any overlap at all is a regression.
- const nodes = allNodes(synthetic(400, 4));
- let overlaps = 0;
- for (let i = 0; i < nodes.length; i++) {
- for (let j = i + 1; j < nodes.length; j++) {
- const a = nodes[i]!;
- const b = nodes[j]!;
- if (Math.hypot(a.x - b.x, a.y - b.y) < a.r + b.r - 1e-6) overlaps++;
+ it("unfolding a level fills a disc and moves nothing already drawn", () => {
+ const top = tree(node("", null, 4, 400, { has_children: true }), 1, [
+ node("a", "", 3, 300, { has_children: true }),
+ node("b", "", 1, 100, { direct_file_count: 1 }),
+ ]);
+ const before = layoutAreas(mergeAreaTree(EMPTY_AREA_INDEX, top));
+ const deeper = mergeAreaTree(
+ mergeAreaTree(EMPTY_AREA_INDEX, top),
+ tree(node("a", "", 3, 300, { has_children: true }), 1, [
+ node("a/x", "a", 2, 200, { direct_file_count: 2 }),
+ node("a/y", "a", 1, 100, { direct_file_count: 1 }),
+ ]),
+ );
+ const after = layoutAreas(deeper);
+ for (const [path, c] of before.circles) expect(after.circles.get(path)).toEqual(c);
+ expect(inside(after.circles.get("a/x")!, after.circles.get("a")!)).toBe(true);
+ });
+
+ it("places every drawable file exactly once, inside its host, never overlapping", () => {
+ const placed = layoutFiles(files, index, geo);
+ expect(placed.unplaced).toBe(0);
+ const paths = placed.nodes.map((n) => n.file.file_path);
+ expect(new Set(paths).size).toBe(files.length);
+ for (const h of placed.hosts) {
+ const ns = [...h.nodes].map((i) => placed.nodes[i]!);
+ for (const n of ns) expect(inside(n, h.circle, 1e-6)).toBe(true);
+ for (let i = 0; i < Math.min(ns.length, 40); i++) {
+ for (let j = i + 1; j < Math.min(ns.length, 40); j++) {
+ const a = ns[i]!;
+ const b = ns[j]!;
+ expect(Math.hypot(a.x - b.x, a.y - b.y)).toBeGreaterThanOrEqual(a.r + b.r - 1e-6);
+ }
}
}
- expect(overlaps).toBe(0);
});
+});
- it("groups one module by sub-folder so it separates into galaxies", () => {
- const files = ["api", "core", "db", "ui", "cli"].flatMap((area) =>
- Array.from({ length: 6 }, (_, i) => f(`src/${area}/f${i}.py`, 40, "src")),
- );
- const galaxies = layoutField(files);
- expect(galaxies.map((g) => g.module).sort()).toEqual([
- "src/api",
- "src/cli",
- "src/core",
- "src/db",
- "src/ui",
- ]);
+describe("semantic zoom", () => {
+ const files = synthetic(3000, 8);
+ const index = deriveAreaIndex(files);
+ const geo = layoutAreas(index);
+ const placed = layoutFiles(files, index, geo);
+ const view = { w: 800, h: 640, dpr: 1 };
+ const at = (cam: { cx: number; cy: number; scale: number }) =>
+ computeView({ index, geo, hosts: placed.hosts, hostIndex: placed.hostIndex, filesCovered: () => true, cam, view });
+
+ it("zoomed out, loaded files are texture inside faint folder containers", () => {
+ const v = at(fitCamera(view.w, view.h));
+ expect(v.drawnHosts.some((x) => x === 1)).toBe(true);
+ expect(v.discs.find((d) => d.path === "pkg0")!.state).toBe("open");
+ });
+
+ it("once a dot would be under a device pixel, folders are solid and draw no dots", () => {
+ const far = fitCamera(view.w, view.h);
+ const v = at({ ...far, scale: far.scale / 15 });
+ expect(v.drawnHosts.every((x) => x === 0)).toBe(true);
+ expect(v.discs.some((d) => d.state === "closed")).toBe(true);
});
- it("keeps the module grouping when there are enough modules", () => {
- const key = galaxyKeyFor(synthetic(100, 6));
- expect(key(f("pkg3/sub1/x.py", 10, "pkg3"))).toBe("pkg3");
+ it("zoomed into one leaf area, draws its files", () => {
+ const leaf = "pkg0/sub0/deep0";
+ const c = geo.circles.get(leaf)!;
+ const v = at({ cx: c.x, cy: c.y, scale: (view.h * 0.9) / (2 * c.r) });
+ const host = placed.hosts.findIndex((h) => h.area === leaf);
+ expect(v.drawnHosts[host]).toBe(1);
+ expect(v.discs.find((d) => d.path === leaf)!.state).toBe("open");
+ expect(discAt(v, view.w / 2, view.h / 2)!.path).toBe(leaf);
});
- it("folds the smallest of hundreds of modules, so galaxies stay readable", () => {
- const files = [
- ...Array.from({ length: 30 }, (_, m) =>
- Array.from({ length: 40 }, (_, i) => f(`apps/big${m}/f${i}.py`, 50, `apps/big${m}`)),
- ).flat(),
- ...Array.from({ length: 300 }, (_, m) => f(`libs/tiny${m}/x.py`, 20, `libs/tiny${m}`)),
- ];
- const galaxies = layoutField(files);
- expect(galaxies.length).toBeLessThanOrEqual(MAX_GALAXIES);
- const fold = galaxies.find((g) => g.members > 1);
- expect(fold?.label).toMatch(/modules$/);
- expect(galaxies.reduce((n, g) => n + g.fileCount, 0)).toBe(files.length);
+ it("asks for children when an area opens, and files from the shallowest area that fits", () => {
+ const lazy = mergeAreaTree(
+ EMPTY_AREA_INDEX,
+ tree(node("", null, 9000, 40000, { has_children: true }), 1, [
+ node("big", "", 300, 30000, { has_children: true }),
+ node("tiny", "", 8700, 10000, { has_children: true }),
+ ]),
+ );
+ const lgeo = layoutAreas(lazy);
+ const big = lgeo.circles.get("big")!;
+ const v = computeView({
+ index: lazy,
+ geo: lgeo,
+ hosts: [],
+ hostIndex: new Map(),
+ filesCovered: () => false,
+ cam: { cx: big.x, cy: big.y, scale: (OPEN_PX * 4) / big.r },
+ view,
+ });
+ expect(v.wantChildren).toContain("big");
+ expect(v.wantFiles).toEqual(["big"]);
});
});
describe("hit testing", () => {
- const nodes = allNodes(synthetic(3000, 12));
+ const files = synthetic(3000, 12);
+ const index = deriveAreaIndex(files);
+ const nodes = layoutFiles(files, index, layoutAreas(index)).nodes;
const grid = buildHitGrid(nodes);
it("finds the node under its own centre", () => {
@@ -120,22 +256,6 @@ describe("hit testing", () => {
}
});
- it("finds nothing in empty space and something within the slop", () => {
- expect(hitTest(grid, -50, -50)).toBe(-1);
- // Packed dots sit close, so probe each side of node 5 for a point just
- // outside it that no neighbour is within the slop of.
- const n = nodes[5]!;
- const clear = [0, 1, 2, 3, 4, 5, 6, 7]
- .map((k) => (k * Math.PI) / 4)
- .map((a) => ({ x: n.x + (n.r + 0.5) * Math.cos(a), y: n.y + (n.r + 0.5) * Math.sin(a) }))
- .find((p) =>
- nodes.every((m, i) => i === 5 || Math.hypot(p.x - m.x, p.y - m.y) - m.r > 1),
- );
- expect(clear).toBeDefined();
- expect(hitTest(grid, clear!.x, clear!.y, 0)).not.toBe(5);
- expect(hitTest(grid, clear!.x, clear!.y, 1)).toBe(5);
- });
-
it("agrees with a brute-force scan", () => {
for (let k = 0; k < 200; k++) {
const x = (k * 37) % WORLD;
@@ -170,27 +290,29 @@ describe("cost at size", () => {
it(`lays out, indexes and batches ${n.toLocaleString()} files quickly`, () => {
const files = synthetic(n, 40);
const t0 = performance.now();
- const galaxies = layoutField(files);
+ const index = deriveAreaIndex(files);
+ const geo = layoutAreas(index);
+ const placed = layoutFiles(files, index, geo);
const t1 = performance.now();
- const scene = buildScene(galaxies);
+ const scene = buildScene(placed);
const grid = buildHitGrid(scene.nodes);
- const t2 = performance.now();
const fills = scene.nodes.map((nd) => OVERLAY_SPECS.health.fill(nd.file));
- const batches = groupBatches(scene, fills, null, -1, () => true, () => [0, 0, 0]);
- const t3 = performance.now();
- let hits = 0;
- for (let k = 0; k < 10000; k++) {
- if (hitTest(grid, (k * 7.3) % WORLD, (k * 3.1) % WORLD, 2) >= 0) hits++;
+ const batches = groupBatches(scene, fills, null, () => true, () => [0, 0, 0]);
+ const t2 = performance.now();
+ const cam = fitCamera(800, 640);
+ const view = { w: 800, h: 640, dpr: 1 };
+ for (let k = 0; k < 100; k++) {
+ computeView({ index, geo, hosts: scene.hosts, hostIndex: scene.hostIndex, filesCovered: () => true, cam: { ...cam, scale: cam.scale * (1 + k / 10) }, view });
}
- const t4 = performance.now();
+ const t3 = performance.now();
console.info(
- `[map bench] n=${n} layout=${(t1 - t0).toFixed(1)}ms grid=${(t2 - t1).toFixed(1)}ms ` +
- `batches=${(t3 - t2).toFixed(1)}ms (${batches.length}) 10k hit-tests=${(t4 - t3).toFixed(1)}ms`,
+ `[map bench] n=${n} areas=${index.areas.size} layout=${(t1 - t0).toFixed(1)}ms ` +
+ `scene+batches=${(t2 - t1).toFixed(1)}ms (${batches.length}) view/frame=${((t3 - t2) / 100).toFixed(2)}ms`,
);
expect(scene.nodes).toHaveLength(n);
- expect(hits).toBeGreaterThan(0);
- expect(t1 - t0).toBeLessThan(1500);
- expect(t4 - t3).toBeLessThan(500);
+ expect(hitTest(grid, scene.nodes[0]!.x, scene.nodes[0]!.y)).toBe(0);
+ expect(t1 - t0).toBeLessThan(3000);
+ expect((t3 - t2) / 100).toBeLessThan(8);
});
}
});
diff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsx
index 3c8b7b4d9..06733017e 100644
--- a/packages/ui/__tests__/health/map-lens.test.tsx
+++ b/packages/ui/__tests__/health/map-lens.test.tsx
@@ -17,9 +17,16 @@ import {
} from "../../src/health/code-health-map.js";
import { MapFieldList } from "../../src/health/map/inspector.js";
import { buildScene, groupBatches } from "../../src/health/map/paint.js";
-import { layoutField } from "../../src/health/map/layout.js";
+import { deriveAreaIndex } from "../../src/health/map/areas.js";
+import { layoutAreas, layoutFiles } from "../../src/health/map/area-layout.js";
import { healthRampFill } from "../../src/health/tokens.js";
-import { mapFile as f, nodeAt, stubMapEnvironment } from "./map-test-utils.js";
+import { mapFile as f, nextFrame, nodeAt, stubMapEnvironment } from "./map-test-utils.js";
+
+/** The flat feed laid out as the map lays it out. */
+function placeAll(files: CodeHealthMapFile[]) {
+ const index = deriveAreaIndex(files);
+ return layoutFiles(files, index, layoutAreas(index));
+}
beforeAll(stubMapEnvironment);
@@ -129,31 +136,20 @@ describe("batches", () => {
f(`m${i % 3}/f${i}.py`, 20 + i, `m${i % 3}`, { score: i % 2 ? 9 : 3 }),
);
- it("groups the field by fill, so a frame is one fill per colour", () => {
- const scene = buildScene(layoutField(files));
+ it("groups each host's files by fill, so a frame is one fill per colour per drawn disc", () => {
+ const scene = buildScene(placeAll(files));
const fills = scene.nodes.map((n) => OVERLAY_SPECS.health.fill(n.file));
- const batches = groupBatches(scene, fills, null, -1, () => false, () => [0, 0, 0]);
- expect(batches).toHaveLength(new Set(fills).size);
+ const batches = groupBatches(scene, fills, null, () => false, () => [0, 0, 0]);
+ expect(batches).toHaveLength(scene.hosts.length * new Set(fills).size);
expect(batches.reduce((n, b) => n + b.nodes.length, 0)).toBe(files.length);
- });
-
- it("spends opacity on focus alone, never on data", () => {
- // A lens that also dimmed by burden left a reader unable to tell a quiet
- // file from one sitting in an unfocused galaxy.
- const scene = buildScene(layoutField(files));
- const fills = scene.nodes.map((n) => OVERLAY_SPECS.health.fill(n.file));
- expect(groupBatches(scene, fills, null, -1, () => false, () => [0, 0, 0]).every((b) => !b.faded)).toBe(true);
- const focused = groupBatches(scene, fills, null, 0, () => false, () => [0, 0, 0]);
- for (const b of focused) {
- for (const i of b.nodes) expect(b.faded).toBe(scene.galaxyOf[i] !== 0);
- }
+ for (const b of batches) for (const i of b.nodes) expect(scene.hostOfNode[i]).toBe(b.host);
});
it("pairs the old and new fill during a lens tween", () => {
- const scene = buildScene(layoutField(files));
+ const scene = buildScene(placeAll(files));
const health = scene.nodes.map((n) => OVERLAY_SPECS.health.fill(n.file));
const perf = scene.nodes.map((n) => OVERLAY_SPECS.performance.fill(n.file));
- const tween = groupBatches(scene, perf, health, -1, () => false, (c) => (c === perf[0] ? [1, 1, 1] : [0, 0, 0]));
+ const tween = groupBatches(scene, perf, health, () => false, (c) => (c === perf[0] ? [1, 1, 1] : [0, 0, 0]));
expect(tween.reduce((n, b) => n + b.nodes.length, 0)).toBe(files.length);
expect(new Set(tween.map((b) => `${b.from}|${b.to}`)).size).toBeGreaterThan(0);
});
@@ -263,7 +259,7 @@ describe("what the field costs to draw", () => {
const files = Array.from({ length: 300 }, (_, i) =>
f(`core/f${i}.py`, 200 - (i % 150), i % 2 ? "core" : "ui"),
);
- const placed = layoutField(files).flatMap((g) => g.nodes.map((n) => n.file.file_path));
+ const placed = placeAll(files).nodes.map((n) => n.file.file_path);
expect(placed).toHaveLength(300);
expect(new Set(placed).size).toBe(300);
});
@@ -280,11 +276,12 @@ describe("what the field costs to draw", () => {
describe("the hover card", () => {
const files = [f("core/deep/nested/alpha.py", 120, "core"), f("ui/beta.py", 60, "ui")];
- it("opens at the pointer rather than in a corner of the canvas", () => {
+ it("opens at the pointer rather than in a corner of the canvas", async () => {
// A card pinned to one corner makes every identification a round trip
// across the field, and the pointer has usually left the node by the time
// the eye gets back.
const { getByTestId } = render(<CodeHealthMap files={files} />);
+ await nextFrame();
fireEvent.mouseMove(getByTestId("map-canvas"), nodeAt(files, "core/deep/nested/alpha.py"));
const card = getByTestId("map-hover-card");
expect(card.textContent).toContain("alpha.py");
@@ -294,12 +291,13 @@ describe("the hover card", () => {
expect(card.getAttribute("style")).toMatch(/left:/);
});
- it("closes when the pointer leaves the node, and tells the host", () => {
+ it("closes when the pointer leaves the node, and tells the host", async () => {
const onHoverFile = vi.fn();
const { getByTestId, queryByTestId } = render(
<CodeHealthMap files={files} onHoverFile={onHoverFile} />,
);
const canvas = getByTestId("map-canvas");
+ await nextFrame();
fireEvent.mouseMove(canvas, nodeAt(files, "ui/beta.py"));
expect(queryByTestId("map-hover-card")).toBeInTheDocument();
fireEvent.mouseMove(canvas, { clientX: 2, clientY: 2 });
@@ -311,47 +309,45 @@ describe("the hover card", () => {
describe("keyboard", () => {
const files = [f("core/a.py", 120, "core"), f("core/b.py", 60, "core"), f("ui/c.py", 40, "ui")];
- it("reaches every file through one tab stop", () => {
+ it("reaches every area and file through one tab stop", () => {
const onSelectFile = vi.fn();
- const { getByRole, container, getByTestId } = render(
- <CodeHealthMap files={files} onSelectFile={onSelectFile} />,
+ const onAreaChange = vi.fn();
+ const { getByRole, container, getByTestId, rerender } = render(
+ <CodeHealthMap files={files} onSelectFile={onSelectFile} onAreaChange={onAreaChange} area="" />,
);
// One focusable region for the whole field. Thousands of tab stops is not
// navigation, and a canvas with none is not reachable.
expect(container.querySelectorAll('[tabindex="0"]')).toHaveLength(1);
const field = getByRole("group", { name: /Code health map/ });
+ // The cursor shows once the keys are used: right to ui, left back to core.
+ fireEvent.keyDown(field, { key: "ArrowRight" });
+ fireEvent.keyDown(field, { key: "ArrowLeft" });
+ expect(getByTestId("map-field").getAttribute("data-keyboard-cursor")).toBe("core"); // biggest first
+ fireEvent.keyDown(field, { key: "Enter" });
+ expect(onAreaChange).toHaveBeenCalledWith("core");
- fireEvent.keyDown(field, { key: "Enter" }); // into the first module
- fireEvent.keyDown(field, { key: "ArrowRight" }); // second file in it
+ rerender(<CodeHealthMap files={files} onSelectFile={onSelectFile} onAreaChange={onAreaChange} area="core" />);
+ fireEvent.keyDown(field, { key: "ArrowRight" }); // second file in core
expect(getByTestId("map-field").getAttribute("data-keyboard-cursor")).toBe("core/b.py");
fireEvent.keyDown(field, { key: "Enter" });
expect(onSelectFile).toHaveBeenCalledWith("core/b.py");
});
it("announces where the cursor is", () => {
- const { getByRole, container } = render(<CodeHealthMap files={files} />);
+ const { getByRole, container } = render(<CodeHealthMap files={files} area="core" onAreaChange={vi.fn()} />);
const field = getByRole("group", { name: /Code health map/ });
- fireEvent.keyDown(field, { key: "Enter" });
+ fireEvent.keyDown(field, { key: "ArrowRight" });
+ fireEvent.keyDown(field, { key: "ArrowLeft" });
const live = container.querySelector('[aria-live="polite"]');
expect(live?.textContent).toContain("core/a.py");
});
- it("Escape climbs back out to the modules", () => {
- const { getByRole, queryByText, getByTestId } = render(<CodeHealthMap files={files} />);
- const field = getByRole("group", { name: /Code health map/ });
- fireEvent.keyDown(field, { key: "Enter" });
- expect(queryByText("← Overview")).toBeInTheDocument();
- fireEvent.keyDown(field, { key: "Escape" });
- expect(getByTestId("map-field").hasAttribute("data-keyboard-cursor")).toBe(false);
- });
-
it("describes the field in words for a screen reader", () => {
const { container } = render(<CodeHealthMap files={files} />);
- expect(container.textContent).toMatch(/3 files drawn in \d+ groups/);
+ expect(container.textContent).toMatch(/3 files in 2 folders/);
});
});
-
describe("the navigable list beside the field", () => {
const files = [
f("core/a.py", 120, "core", {
diff --git a/packages/ui/__tests__/health/map-not-analysed.test.ts b/packages/ui/__tests__/health/map-not-analysed.test.ts
new file mode 100644
index 000000000..0c6741cd7
--- /dev/null
+++ b/packages/ui/__tests__/health/map-not-analysed.test.ts
@@ -0,0 +1,148 @@
+/**
+ * A file a lens has no signal for is not analysed, under every lens: grey,
+ * left out of every folder's fold, never read as the worst value. And a
+ * folder folds by share, so size alone never paints it red.
+ */
+import { describe, it, expect } from "vitest";
+import { deriveAreaIndex, type AreaIndex } from "../../src/health/map/areas.js";
+import { layoutAreas, layoutFiles } from "../../src/health/map/area-layout.js";
+import { areaFills, fileFills } from "../../src/health/map/fills.js";
+import { buildScene } from "../../src/health/map/paint.js";
+import { KNOWLEDGE_LENS, ownerLens } from "../../src/health/map/area-lenses.js";
+import { OVERLAY_SPECS, resolveLens } from "../../src/health/map/lens-registry.js";
+import { CLEAR_NEUTRAL_FILL, NEUTRAL_FILL, QUIET_FILL, type MapLens } from "../../src/health/map/lens.js";
+import { NODE_RAMP_STOP } from "../../src/health/tokens.js";
+import type { CodeHealthMapFile } from "../../src/health/map/types.js";
+import { mapFile as f } from "./map-test-utils.js";
+
+/** A file with every lens's signal absent. */
+const bare = (path: string): CodeHealthMapFile => ({
+ file_path: path,
+ nloc: 40,
+ score: null,
+ module: null,
+ line_coverage_pct: null,
+ has_test_file: false,
+});
+
+function paint(lens: MapLens, files: CodeHealthMapFile[]) {
+ const index = deriveAreaIndex(files);
+ const scene = buildScene(layoutFiles(files, index, layoutAreas(index)));
+ const { fill, analysed } = areaFills(index, lens, files);
+ return { index, fill, analysed, files: fileFills(scene, lens, fill) };
+}
+
+const FILE_LENSES = ["health", "maintainability", "performance", "coverage", "churn", "dead-code", "security"] as const;
+
+describe("not analysed is grey, under every lens", () => {
+ for (const id of FILE_LENSES) {
+ it(`${id}: a file without the signal, and a folder of only such files`, () => {
+ const { fill, files, analysed } = paint(OVERLAY_SPECS[id], [bare("pkg/a.py"), bare("pkg/b.py")]);
+ expect(files.every((x) => x === NEUTRAL_FILL)).toBe(true);
+ if (!OVERLAY_SPECS[id].areaFill) expect(fill.get("pkg")).toBe(NEUTRAL_FILL);
+ expect(analysed.get("pkg")).toEqual({ analysed: 0, loaded: 2 });
+ });
+ }
+
+ it("main author and knowledge risk: an area with no ownership signal is not coloured", () => {
+ const index: AreaIndex = deriveAreaIndex([bare("pkg/a.py")]);
+ const pkg = index.areas.get("pkg")!;
+ expect(ownerLens(index).areaFill!(pkg)).toBeNull();
+ expect(KNOWLEDGE_LENS.areaFill!(pkg)).toBe(NEUTRAL_FILL);
+ expect(areaFills(index, KNOWLEDGE_LENS, []).fill.get("pkg")).toBe(NEUTRAL_FILL);
+ });
+});
+
+describe("performance folds by share over analysed files", () => {
+ const analysed = (path: string, causes: number) =>
+ f(path, 40, null, { performance_analyzed: true, performance_opportunities: causes });
+
+ it("a big folder with a few causes is not painted worst", () => {
+ // packages/core: 78 of 1,527 analysed files carry a cause (5%).
+ const files = [
+ ...Array.from({ length: 95 }, (_, i) => analysed(`core/f${i}.py`, 0)),
+ ...Array.from({ length: 5 }, (_, i) => analysed(`core/c${i}.py`, 3)),
+ ];
+ const { fill } = paint(OVERLAY_SPECS.performance, files);
+ expect(fill.get("core")).toBe(NODE_RAMP_STOP.warning);
+ });
+
+ it("leaves unanalysed files out of the share and grey", () => {
+ const files = [analysed("core/c.py", 2), ...Array.from({ length: 30 }, (_, i) => bare(`core/u${i}.py`))];
+ const { fill, analysed: counts } = paint(OVERLAY_SPECS.performance, files);
+ // One analysed file, and it has a cause: the share is of what was analysed.
+ expect(fill.get("core")).toBe(NODE_RAMP_STOP.alert);
+ expect(counts.get("core")).toEqual({ analysed: 1, loaded: 31, flagged: 1 });
+ });
+
+ it("tells a checked, clear folder from an unchecked one, without claiming fast", () => {
+ const { fill, analysed: counts } = paint(OVERLAY_SPECS.performance, [analysed("core/a.py", 0)]);
+ expect(fill.get("core")).toBe(CLEAR_NEUTRAL_FILL);
+ expect(fill.get("core")).not.toBe(NEUTRAL_FILL);
+ expect(counts.get("core")).toEqual({ analysed: 1, loaded: 1, flagged: 0 });
+ });
+
+ it("dead code and security call a checked, clean folder clean", () => {
+ for (const [id, row] of [
+ ["dead-code", { dead_code_lines: 0 }],
+ ["security", { security_findings: 0 }],
+ ] as const) {
+ const { fill } = paint(OVERLAY_SPECS[id], [f("lib/a.py", 40, null, row)]);
+ expect(fill.get("lib")).toBe(QUIET_FILL);
+ }
+ });
+});
+
+describe("hotspot health", () => {
+ const hot = (path: string, score: number) => f(path, 40, null, { score, is_hotspot: true });
+ const calm = (path: string, score: number) => f(path, 40, null, { score, is_hotspot: false });
+
+ it("greys every file that is not a hotspot and keeps a hotspot's band", () => {
+ const lens = OVERLAY_SPECS.hotspot;
+ expect(lens.fill(calm("a.py", 2))).toBe(NEUTRAL_FILL);
+ expect(lens.fill(hot("b.py", 2))).toBe(OVERLAY_SPECS.health.fill(hot("b.py", 2)));
+ expect(lens.fill(hot("c.py", 9.5))).toBe(OVERLAY_SPECS.health.fill(hot("c.py", 9.5)));
+ });
+
+ it("colours a folder by its hotspots' health and names their count", () => {
+ const files = [hot("lib/a.py", 2), calm("lib/b.py", 9.5), calm("lib/c.py", 9.5)];
+ const index = deriveAreaIndex(files);
+ const { fill, text } = areaFills(index, OVERLAY_SPECS.hotspot, files);
+ expect(fill.get("lib")).toBe(OVERLAY_SPECS.health.fill(hot("x.py", 2)));
+ expect(text.get("lib")).toBe("1 hot · 2.0");
+ });
+
+ it("leaves a folder with no hotspot grey and unlabelled", () => {
+ const files = [calm("lib/b.py", 3)];
+ const { fill, text } = areaFills(deriveAreaIndex(files), OVERLAY_SPECS.hotspot, files);
+ expect(fill.get("lib")).toBe(NEUTRAL_FILL);
+ expect(text.get("lib")).toBeNull();
+ });
+});
+
+describe("one label per visual disc", () => {
+ it("drops a folder's label when one sub-folder fills it, and names the pair once", async () => {
+ const { mergeDominantLabels } = await import("../../src/health/map/field-notes.js");
+ const files = [
+ ...Array.from({ length: 40 }, (_, i) => f(`pkg/core/src/repowise/core/m${i}.py`, 300, null)),
+ f("pkg/core/alembic/v1.py", 5, null),
+ f("pkg/ui/a.ts", 40, null),
+ ];
+ const index = deriveAreaIndex(files);
+ const labels = mergeDominantLabels(index, layoutAreas(index), new Map(), "Repo");
+ const core = labels.find((l) => l.path === "pkg/core")!;
+ const chain = labels.find((l) => l.path === "pkg/core/src/repowise/core")!;
+ expect(core.dominated).toBe(true);
+ // pkg is filled by pkg/core in turn, so the one label names the whole run.
+ expect(chain.name).toBe("pkg/core/src/repowise/core");
+ expect(labels.find((l) => l.path === "pkg")!.dominated).toBe(true);
+ expect(labels.find((l) => l.path === "pkg/ui")!.dominated).toBe(false);
+ });
+
+ it("words the hotspot chip through the host's labels", () => {
+ const files = [f("lib/a.py", 40, null, { score: 2, is_hotspot: true })];
+ const index = deriveAreaIndex(files);
+ const lens = resolveLens("hotspot", index, { hotspotChip: (n, h) => `${n} 个热点 · ${h}` });
+ expect(areaFills(index, lens, files).text.get("lib")).toBe("1 个热点 · 2.0");
+ });
+});
diff --git a/packages/ui/__tests__/health/map-test-utils.ts b/packages/ui/__tests__/health/map-test-utils.ts
index b247dd171..2f2507f4e 100644
--- a/packages/ui/__tests__/health/map-test-utils.ts
+++ b/packages/ui/__tests__/health/map-test-utils.ts
@@ -4,8 +4,15 @@
* skips cleanly), and a node is found on screen through the same pure layout
* and fitted camera the component uses.
*/
+import { act } from "@testing-library/react";
import { vi } from "vitest";
-import { fitCamera, layoutField, type CodeHealthMapFile } from "../../src/health/code-health-map.js";
+import {
+ deriveAreaIndex,
+ fitCamera,
+ layoutAreas,
+ layoutFiles,
+ type CodeHealthMapFile,
+} from "../../src/health/code-health-map.js";
/** The stub measures 800 x 600; the map's 640px minHeight wins the height. */
export const W = 800;
@@ -31,20 +38,19 @@ export function stubMapEnvironment(): void {
null) as unknown as typeof HTMLCanvasElement.prototype.getContext;
}
+/** Let the frame loop run once, so the field it decides is there to pick from. */
+export async function nextFrame(): Promise<void> {
+ await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
+}
+
/** Where a file's node lands on screen at the fitted camera. */
export function nodeAt(files: CodeHealthMapFile[], path: string) {
const cam = fitCamera(W, H);
- for (const g of layoutField(files)) {
- for (const n of g.nodes) {
- if (n.file.file_path === path) {
- return {
- clientX: W / 2 + (n.x - cam.cx) * cam.scale,
- clientY: H / 2 + (n.y - cam.cy) * cam.scale,
- };
- }
- }
- }
- throw new Error(`no node for ${path}`);
+ const index = deriveAreaIndex(files);
+ const { nodes } = layoutFiles(files, index, layoutAreas(index));
+ const n = nodes.find((x) => x.file.file_path === path);
+ if (!n) throw new Error(`no node for ${path}`);
+ return { clientX: W / 2 + (n.x - cam.cx) * cam.scale, clientY: H / 2 + (n.y - cam.cy) * cam.scale };
}
export function mapFile(
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 57be40817..c5f71924d 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -90,6 +90,12 @@ export {
type FileHealthPromptInput,
type FileHealthPromptSignals,
} from "./ai-prompts/file-health-prompt";
+export {
+ buildAreaAiPrompt,
+ type AreaPromptFile,
+ type AreaPromptFinding,
+ type BuildAreaPromptOptions,
+} from "./ai-prompts/area-prompt";
export {
buildPerformanceAreaPrompt,
type BuildPerformanceAreaPromptOptions,
diff --git a/packages/ui/src/health/ai-prompts/area-prompt.ts b/packages/ui/src/health/ai-prompts/area-prompt.ts
new file mode 100644
index 000000000..4fc6e585e
--- /dev/null
+++ b/packages/ui/src/health/ai-prompts/area-prompt.ts
@@ -0,0 +1,123 @@
+/**
+ * The prompt for one area: its worst files and its highest-priority findings,
+ * handed to an agent as one bounded piece of work.
+ */
+
+import { splitByOrigin } from "../biomarker-glossary";
+import { formatScore } from "@repowise-dev/types/health";
+import { findingEntries, historyContextBlock, type PromptFinding } from "./findings";
+import {
+ bulletList,
+ closingSections,
+ joinSections,
+ pluralS,
+ preamble,
+ repoSuffix,
+ type AiPromptFlavor,
+} from "./shared";
+
+export interface AreaPromptFinding extends Omit<PromptFinding, "health_impact" | "reason"> {
+ file_path: string;
+ health_impact: number | null;
+ reason: string | null;
+}
+
+export interface AreaPromptFile {
+ path: string;
+ score: number;
+ nloc: number;
+}
+
+export interface BuildAreaPromptOptions {
+ /** The area's path; `""` is the repository. */
+ area: string;
+ score: number | null;
+ fileCount: number;
+ findings: AreaPromptFinding[];
+ worstFiles: AreaPromptFile[];
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+const PARTS = {
+ source:
+ "Repowise's static and git analysis flagged the findings below as the highest-priority work in one area of the codebase.",
+ open: "each file the findings name, its callers and its tests",
+ mcpTail:
+ "Pull what repowise already computed before reading by hand: `get_health([file])` for each file's scored findings, `get_context([file])` for its skeleton and `get_risk([file])` for blast radius and test gaps before editing.",
+};
+
+const CONSTRAINTS = [
+ "Work file by file, highest impact first. One focused, independently revertible change per file.",
+ "Confirm each finding in the code before changing anything. Skip a false positive and say why.",
+ "Preserve behaviour. Refactors only; add or update tests for any logic you touch.",
+ "Stay inside the area unless a fix needs a direct caller or test outside it.",
+];
+
+const EXPECTED = [
+ "1. A short plan listing the files you will change, in order, and why.",
+ "2. The edits, one file at a time.",
+ "3. For each finding: fixed, skipped as a false positive, or deferred with a reason.",
+];
+
+function asPromptFinding(f: AreaPromptFinding): PromptFinding {
+ return { ...f, health_impact: f.health_impact ?? 0, reason: f.reason ?? "" };
+}
+
+/** Findings grouped by file, files in first-seen (priority) order. */
+function byFile(findings: AreaPromptFinding[]): Map<string, PromptFinding[]> {
+ const out = new Map<string, PromptFinding[]>();
+ for (const f of findings) {
+ const list = out.get(f.file_path);
+ if (list) list.push(asPromptFinding(f));
+ else out.set(f.file_path, [asPromptFinding(f)]);
+ }
+ return out;
+}
+
+export function buildAreaAiPrompt({
+ area,
+ score,
+ fileCount,
+ findings,
+ worstFiles,
+ flavor = "generic",
+ repoName,
+}: BuildAreaPromptOptions): string {
+ const name = area ? `\`${area}/\`` : "the repository root";
+ const sections: string[] = [];
+ for (const [path, list] of byFile(findings)) {
+ const { codeShape, history } = splitByOrigin(list);
+ const historyBlock = historyContextBlock(history);
+ sections.push(
+ [
+ `### \`${path}\``,
+ "",
+ codeShape.length ? findingEntries(codeShape) : "No structural finding; history only.",
+ historyBlock ? `\n${historyBlock}` : "",
+ "",
+ ].join("\n"),
+ );
+ }
+ return joinSections([
+ preamble(flavor, PARTS),
+ "",
+ `## Area${repoSuffix(repoName)}`,
+ "",
+ bulletList([
+ `Path: ${name}`,
+ score != null ? `Health: **${formatScore(score)}/10** across ${fileCount} file${pluralS(fileCount)}` : null,
+ worstFiles.length
+ ? `Lowest-scoring files: ${worstFiles
+ .slice(0, 5)
+ .map((f) => `\`${f.path}\` (${formatScore(f.score)})`)
+ .join(", ")}`
+ : null,
+ ]),
+ "",
+ `## Findings to work through (${findings.length})`,
+ "",
+ ...sections,
+ ...closingSections(CONSTRAINTS, EXPECTED),
+ ]);
+}
diff --git a/packages/ui/src/health/area-map-section.tsx b/packages/ui/src/health/area-map-section.tsx
new file mode 100644
index 000000000..9b181eb9c
--- /dev/null
+++ b/packages/ui/src/health/area-map-section.tsx
@@ -0,0 +1,346 @@
+"use client";
+
+/**
+ * The area map and its context rail, as one section of the Code Health page.
+ *
+ * With the areas API on the adapter, the hierarchy and its files load as the
+ * reader zooms, and the rail reads the selection one level at a time: the
+ * repository, an area, a file. A host without it hands in a flat feed, the
+ * map derives the same hierarchy from it, and the rail falls back to the
+ * ranked file list with the file drawer beside it.
+ */
+
+import { useCallback, useMemo, useRef, useState } from "react";
+import type { CSSProperties } from "react";
+import { Search } from "lucide-react";
+import type { AreaHeld } from "@repowise-dev/types/areas";
+import type { HealthMapFeed } from "@repowise-dev/types/health";
+
+import { ApiError } from "../shared/api-error";
+import { toFriendlyMessage } from "../lib/errors";
+import { Skeleton } from "../ui/skeleton";
+import { OverviewSection } from "../overview/section";
+import { ROOT_AREA } from "../lib/areas";
+import { CodeHealthMap, MapLegend, MapLensSwitcher, type CodeHealthMapFile, type CodeHealthOverlay, type MapScope } from "./code-health-map";
+import { deriveAreaIndex, type AreaIndex } from "./map/areas";
+import { OVERLAY_SPECS, resolveLens } from "./map/lens-registry";
+import { useAreaSource, type AreaFetchers } from "./map/use-area-source";
+import { MapFieldList } from "./map/inspector";
+import { AreaRail } from "./area-rail/area-rail";
+import { DEFAULT_AREA_RAIL_LABELS, type AreaRailLabels } from "./area-rail/labels";
+import type { CodeHealthAdapter } from "./code-health-adapter";
+
+/** Map height. The rail is height-matched so it never outgrows the field beside it. */
+const MAP_HEIGHT = 720;
+/** The breadcrumb above the map and the legend under it, so the rail ends with them. */
+const CHROME_ROWS = 80;
+
+/** Optional flat-feed controls, passed through to the map untouched. */
+export type FlatMapExtras = Partial<
+ Pick<
+ Parameters<typeof CodeHealthMap>[0],
+ "lenses" | "overlayLoading" | "scope" | "highlightPaths" | "onDrawMore" | "drawMoreStep" | "onIncludeHeldChange" | "onFindUndrawn" | "pending"
+ >
+>;
+
+export interface AreaMapSectionProps {
+ adapter: CodeHealthAdapter;
+ overlay: CodeHealthOverlay;
+ onOverlayChange?: ((overlay: CodeHealthOverlay) => void) | undefined;
+ lenses?: CodeHealthOverlay[] | undefined;
+ /** Lenses shown as segments; the rest sit behind "More". All, when absent. */
+ primaryLenses?: CodeHealthOverlay[] | undefined;
+ /** The flat feed, for a host without the areas API. */
+ mapFeed?: HealthMapFeed | undefined;
+ mapScope?: MapScope | undefined;
+ mapError?: unknown;
+ onRetryMap?: (() => void) | undefined;
+ mapExtra: FlatMapExtras;
+ overlayLoading: boolean;
+ selected: string | null;
+ setSelected: (path: string | null) => void;
+ /** Selected area, owned by the host so it rides in the URL. Local otherwise. */
+ area?: string | undefined;
+ onAreaChange?: ((area: string) => void) | undefined;
+ /** Per-file signals the host joins onto the loaded rows (e.g. churn). */
+ fileExtras?: ReadonlyMap<string, Partial<CodeHealthMapFile>> | undefined;
+ railLabels?: Partial<AreaRailLabels> | undefined;
+ /**
+ * Held-out groups brought back (`["test"]`), owned by the host so it rides
+ * in the URL. With `onIncludeChange` the canvas footer offers a toggle per
+ * held group; the host's fetchers read the same list.
+ */
+ include?: readonly string[] | undefined;
+ onIncludeChange?: ((include: string[]) => void) | undefined;
+ /** Overrides the labels' description for this host. */
+ description?: string | undefined;
+}
+
+/** The areas fetchers, stable across renders: most hosts rebuild the adapter every render. */
+function useFetchers(adapter: CodeHealthAdapter): AreaFetchers | null {
+ const ref = useRef(adapter);
+ ref.current = adapter;
+ const has = Boolean(adapter.getAreaTree && adapter.getAreaFiles && adapter.getAreaDetail);
+ return useMemo(
+ () =>
+ has
+ ? {
+ getAreaTree: (root: string, depth: number) => ref.current.getAreaTree!(root, depth),
+ getAreaFiles: (area: string) => ref.current.getAreaFiles!(area),
+ }
+ : null,
+ [has],
+ );
+}
+
+/** What the map's figures cover, given the held groups brought back. */
+export function scopeName(
+ held: { default: readonly string[]; counts: Readonly<Record<string, number>> },
+ include: readonly string[],
+ labels: AreaRailLabels,
+): string {
+ const present = held.default.filter((o) => (held.counts[o] ?? 0) > 0);
+ const back = present.filter((o) => include.includes(o));
+ if (back.length === 0) return labels.scopeProduction;
+ if (back.length === present.length) return labels.scopeAll;
+ return labels.scopeWith(back.map((o) => labels.originName(o)).join(", "));
+}
+
+function SearchBox({ value, onChange, label }: { value: string; onChange: (v: string) => void; label: string }) {
+ return (
+ <div className="relative">
+ <Search
+ aria-hidden="true"
+ className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]"
+ />
+ <input
+ type="search"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={label}
+ aria-label={label}
+ className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] hover:border-[var(--color-border-hover)] focus-visible:border-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ />
+ </div>
+ );
+}
+
+/** The lazily loaded source with the host's per-file extras joined on, or none without the areas API. */
+function useJoinedSource(
+ adapter: CodeHealthAdapter,
+ fileExtras: AreaMapSectionProps["fileExtras"],
+ holdKey: string,
+) {
+ const fetchers = useFetchers(adapter);
+ // The held groups change which files every read covers, so they start the
+ // hierarchy over, like a new repository.
+ const raw = useAreaSource(fetchers, `${adapter.cacheKey}|${holdKey}`);
+ const files = useMemo(
+ () =>
+ fileExtras
+ ? raw.files.map((f) => {
+ const extra = fileExtras.get(f.file_path);
+ return extra ? { ...f, ...extra } : f;
+ })
+ : raw.files,
+ [raw.files, fileExtras],
+ );
+ return fetchers ? { ...raw, files } : undefined;
+}
+
+/**
+ * The selected area, the host's when it owns it. A file belongs to the level
+ * it was opened from, so changing area drops it; a host that owns the area
+ * drops it in the same URL write, since a second write clearing the file
+ * separately would race the first and undo it.
+ */
+function useAreaSelection(
+ owned: string | undefined,
+ onAreaChange: ((area: string) => void) | undefined,
+ setSelected: (path: string | null) => void,
+) {
+ const [local, setLocal] = useState(ROOT_AREA);
+ const setArea = useCallback(
+ (next: string) => {
+ if (onAreaChange) onAreaChange(next);
+ else {
+ setLocal(next);
+ setSelected(null);
+ }
+ },
+ [onAreaChange, setSelected],
+ );
+ return [owned ?? local, setArea] as const;
+}
+
+type MapPaneProps = Omit<Parameters<typeof CodeHealthMap>[0], "minHeight" | "chrome"> & {
+ failed: unknown;
+ waiting: boolean;
+ onRetry?: (() => void) | undefined;
+ errorTitle: string;
+};
+
+/** The canvas, or the state standing in for it while it loads or after it failed. */
+function MapPane({ failed, waiting, onRetry, errorTitle, ...map }: MapPaneProps) {
+ if (failed) {
+ return (
+ <div className="flex items-center justify-center" style={{ minHeight: MAP_HEIGHT }}>
+ <ApiError title={errorTitle} message={toFriendlyMessage(failed)} {...(onRetry ? { onRetry } : {})} />
+ </div>
+ );
+ }
+ if (waiting) return <Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />;
+ return <CodeHealthMap {...map} minHeight={MAP_HEIGHT} chrome="none" />;
+}
+
+/** The held groups the host brought back, as the canvas footer offers them and the rail names them. */
+function heldScope(
+ held: AreaHeld | null,
+ include: readonly string[],
+ onIncludeChange: ((include: string[]) => void) | undefined,
+ labels: AreaRailLabels,
+) {
+ const heldGroups =
+ held && onIncludeChange ? { default: held.default, counts: held.counts, include, onChange: onIncludeChange } : undefined;
+ return { heldGroups, scope: held ? scopeName(held, include, labels) : undefined };
+}
+
+/** The rail: the area cards with the areas API, the ranked file list without. */
+function SectionRail(
+ props: AreaMapSectionProps & {
+ source: AreaSourceLike | undefined;
+ index: AreaIndex | null;
+ flatFiles: CodeHealthMapFile[] | undefined;
+ area: string;
+ setArea: (area: string) => void;
+ labels: AreaRailLabels;
+ scope: string | undefined;
+ holdKey: string;
+ heldOut: boolean;
+ },
+) {
+ const { adapter, overlay, selected, setSelected, area, index, labels } = props;
+ if (props.source && adapter.getAreaDetail && index) {
+ return (
+ <AreaRail
+ cacheKey={adapter.cacheKey}
+ getAreaDetail={(p) => adapter.getAreaDetail!(p)}
+ area={area}
+ index={index}
+ nameOf={(p) => (area && p.startsWith(`${area}/`) ? p.slice(area.length + 1) : p)}
+ labels={labels}
+ selectedFile={selected}
+ fileDetail={adapter.renderFileDrawer({ filePath: selected, onClose: () => setSelected(null), lens: overlay, inline: true })}
+ onClearFile={() => setSelected(null)}
+ onSelectArea={props.setArea}
+ onSelectFile={setSelected}
+ areaLinks={adapter.areaLinks ? (p) => adapter.areaLinks!(p) : undefined}
+ onNavigate={(href) => adapter.navigate(href)}
+ scope={props.scope}
+ holdKey={props.holdKey}
+ {...(props.heldOut ? { errorHint: labels.heldOutHint } : {})}
+ />
+ );
+ }
+ if (!props.flatFiles) return null;
+ return (
+ <div className="min-h-0 flex-1 overflow-hidden border-t border-[var(--color-border-default)] pt-3">
+ <MapFieldList
+ files={props.flatFiles}
+ overlay={overlay}
+ selectedPath={selected}
+ onSelectFile={setSelected}
+ {...(props.mapScope ? { scope: props.mapScope } : {})}
+ />
+ </div>
+ );
+}
+
+type AreaSourceLike = ReturnType<typeof useJoinedSource>;
+
+export function AreaMapSection(props: AreaMapSectionProps) {
+ const { overlay, selected, setSelected } = props;
+ const labels = useMemo(() => ({ ...DEFAULT_AREA_RAIL_LABELS, ...props.railLabels }), [props.railLabels]);
+ const include = props.include ?? [];
+ // Sorted, so two orders of the same toggles are one read.
+ const holdKey = [...include].sort().join(",");
+ const source = useJoinedSource(props.adapter, props.fileExtras, holdKey);
+ const { heldGroups, scope } = heldScope(source?.held ?? null, include, props.onIncludeChange, labels);
+ const [area, setArea] = useAreaSelection(props.area, props.onAreaChange, setSelected);
+ const [query, setQuery] = useState("");
+
+ const flatFiles = props.mapFeed?.files as CodeHealthMapFile[] | undefined;
+ const derived = useMemo(() => (source || !flatFiles ? null : deriveAreaIndex(flatFiles)), [source, flatFiles]);
+ const index = source?.index ?? derived;
+ const lens = useMemo(() => (index ? resolveLens(overlay, index, labels) : undefined), [overlay, index, labels]);
+
+ const rail = (
+ <SectionRail
+ {...props}
+ source={source}
+ index={index}
+ flatFiles={flatFiles}
+ area={area}
+ setArea={setArea}
+ labels={labels}
+ scope={scope}
+ holdKey={holdKey}
+ heldOut={Boolean(heldGroups)}
+ />
+ );
+
+ return (
+ <OverviewSection
+ title={labels.mapTitle}
+ description={props.description ?? (source ? labels.mapDescription : labels.flatMapDescription)}
+ action={
+ props.onOverlayChange ? (
+ <MapLensSwitcher
+ overlay={overlay}
+ onOverlayChange={props.onOverlayChange}
+ {...(props.lenses ? { lenses: props.lenses } : {})}
+ {...(props.primaryLenses ? { primary: props.primaryLenses } : {})}
+ moreLabel={labels.moreLenses}
+ {...(labels.lensName ? { nameOf: (l: CodeHealthOverlay) => labels.lensName!(l) ?? OVERLAY_SPECS[l].label } : {})}
+ />
+ ) : undefined
+ }
+ >
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_380px]">
+ <div className="flex min-w-0 flex-col gap-2.5">
+ <MapPane
+ failed={source ? source.error : !flatFiles && props.mapError}
+ waiting={source ? source.loading : !flatFiles}
+ onRetry={source ? source.retry : props.onRetryMap}
+ errorTitle={labels.mapLoadError}
+ ariaLabel={labels.mapAriaLabel}
+ rootLabel={labels.repository}
+ labels={labels}
+ files={flatFiles ?? []}
+ {...(source ? { source } : {})}
+ area={area}
+ onAreaChange={setArea}
+ search={query}
+ selectedPath={selected}
+ onSelectFile={setSelected}
+ overlay={overlay}
+ {...(lens ? { lens } : {})}
+ {...(heldGroups ? { heldGroups } : {})}
+ {...props.mapExtra}
+ />
+ <MapLegend overlay={overlay} {...(lens ? { lens } : {})} loading={props.overlayLoading} />
+ </div>
+ {/* Separated from the canvas by space, not a rule: a vertical hairline
+ down the side of the canvas would turn the map into a trench. */}
+ <aside
+ aria-label="Map selection"
+ className="flex min-w-0 flex-col gap-4 lg:sticky lg:top-4 lg:h-[var(--rail-h)] lg:overflow-y-auto lg:pr-1"
+ style={{ "--rail-h": `${MAP_HEIGHT + CHROME_ROWS}px` } as CSSProperties}
+ >
+ <SearchBox value={query} onChange={setQuery} label={labels.searchPlaceholder} />
+ {rail}
+ </aside>
+ </div>
+ </OverviewSection>
+ );
+}
diff --git a/packages/ui/src/health/area-rail/area-card.tsx b/packages/ui/src/health/area-rail/area-card.tsx
new file mode 100644
index 000000000..dcd9ab645
--- /dev/null
+++ b/packages/ui/src/health/area-rail/area-card.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+/**
+ * One area, read top-down: its score and how it moved, the one action (hand
+ * the area's top findings to an agent), where inside it to look, its worst
+ * files, and a single line of facts. Hotspots, people and the findings
+ * themselves wait behind one disclosure. The repository is the root area and
+ * reads the same way.
+ */
+
+import { ChevronRight } from "lucide-react";
+import type { AreaDetail } from "@repowise-dev/types/areas";
+
+import { AiPromptButton } from "../ai-prompt-button";
+import type { AiPromptRequest } from "../ai-prompt-action";
+import { buildAreaAiPrompt } from "../ai-prompts/area-prompt";
+import type { AreaIndex } from "../map/areas";
+import { areasNeedingAttention, mostImproved } from "../map/area-rank";
+import { AreaHeader } from "./area-header";
+import { AreaRows, FileRows, FindingRows, RailSection } from "./area-sections";
+import type { AreaRailLabels } from "./labels";
+
+/** Where the card's secondary links go; each is optional. */
+export interface AreaLinks {
+ findings?: string;
+ fixFirst?: string;
+ contributors?: string;
+}
+
+const LIST_CAP = 5;
+
+export interface AreaCardProps {
+ detail: AreaDetail;
+ index: AreaIndex;
+ /** The disc's name as the map shows it. */
+ nameOf: (path: string) => string;
+ labels: AreaRailLabels;
+ selectedPath?: string | null;
+ onSelectArea: (path: string) => void;
+ onSelectFile: (path: string) => void;
+ openPrompt: (request: AiPromptRequest) => void;
+ links?: AreaLinks | undefined;
+ onNavigate?: ((href: string) => void) | undefined;
+ repoName?: string | undefined;
+ /** What the figures cover, named in the header. */
+ scope?: string | undefined;
+}
+
+function Links({ links, labels, onNavigate }: { links: AreaLinks; labels: AreaRailLabels; onNavigate?: ((href: string) => void) | undefined }) {
+ const items = [
+ { href: links.findings, label: labels.findingsLink },
+ { href: links.fixFirst, label: labels.fixFirstLink },
+ { href: links.contributors, label: labels.contributorsLink },
+ ].filter((l): l is { href: string; label: string } => Boolean(l.href));
+ if (items.length === 0) return null;
+ return (
+ <nav className="flex flex-wrap gap-x-4 gap-y-1 text-xs">
+ {items.map((l) => (
+ <a
+ key={l.label}
+ href={l.href}
+ onClick={(e) => {
+ if (!onNavigate) return;
+ e.preventDefault();
+ onNavigate(l.href);
+ }}
+ className="rounded text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {l.label}
+ </a>
+ ))}
+ </nav>
+ );
+}
+
+/** Hotspots, people and tests, as one line of facts with their counts. */
+function Facts({ detail, labels }: { detail: AreaDetail; labels: AreaRailLabels }) {
+ const a = detail.area;
+ const cov = detail.test_reach.line_coverage_pct;
+ const parts = [
+ labels.hotspots(detail.hotspots.total),
+ a.bus_factor_1_count > 0 ? labels.busFactorOne(a.bus_factor_1_count) : null,
+ cov != null ? labels.coverageLine(Math.round(cov), detail.test_reach.measured_files) : labels.noCoverage,
+ ].filter(Boolean);
+ return <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">{parts.join(" · ")}</p>;
+}
+
+export function AreaCard(props: AreaCardProps) {
+ const { detail, index, nameOf, labels, onSelectArea, onSelectFile } = props;
+ const path = detail.area.path;
+ const isRoot = path === "";
+ const findings = detail.top_findings;
+ const attention = areasNeedingAttention(index, path);
+ const improved = mostImproved(index, path);
+ const owner = detail.area.primary_owner;
+
+ const prompt = () =>
+ props.openPrompt({
+ title: labels.promptTitle,
+ description: labels.promptDescription,
+ filePath: isRoot ? null : `${path}/`,
+ getPrompt: (flavor) =>
+ buildAreaAiPrompt({
+ area: path,
+ score: detail.area.health,
+ fileCount: detail.area.file_count,
+ findings,
+ worstFiles: detail.worst_files,
+ flavor,
+ ...(props.repoName ? { repoName: props.repoName } : {}),
+ }),
+ });
+
+ return (
+ <div data-testid="area-card" data-area={path} className="flex flex-col gap-5">
+ <AreaHeader
+ detail={detail}
+ eyebrow={isRoot ? labels.repoEyebrow : labels.areaEyebrow}
+ scope={props.scope}
+ title={isRoot ? labels.repository : nameOf(path)}
+ labels={labels}
+ />
+
+ {findings.length > 0 ? (
+ <AiPromptButton label={labels.promptAction(findings.length)} onClick={prompt} className="self-start" />
+ ) : (
+ <p className="text-xs text-[var(--color-success)]">{labels.allClean(detail.area.file_count)}</p>
+ )}
+
+ {attention.length > 0 ? (
+ <RailSection title={isRoot ? labels.needsAttention : labels.subAreas}>
+ <AreaRows areas={attention} nameOf={nameOf} onSelect={onSelectArea} />
+ </RailSection>
+ ) : null}
+
+ {improved ? (
+ <RailSection title={labels.improvedMost}>
+ <AreaRows areas={[improved]} nameOf={nameOf} onSelect={onSelectArea} showDelta />
+ </RailSection>
+ ) : null}
+
+ {detail.worst_files.length > 0 ? (
+ <RailSection title={labels.worstFiles}>
+ <FileRows files={detail.worst_files.slice(0, LIST_CAP)} selectedPath={props.selectedPath} onSelect={onSelectFile} />
+ </RailSection>
+ ) : null}
+
+ <Facts detail={detail} labels={labels} />
+
+ <details className="group flex flex-col gap-4">
+ <summary className="flex cursor-pointer list-none items-center gap-1 rounded text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] [&::-webkit-details-marker]:hidden">
+ <ChevronRight aria-hidden className="h-3.5 w-3.5 transition-transform group-open:rotate-90" />
+ {labels.hotspots(detail.hotspots.total)} · {labels.owners} · {labels.topFindings}
+ </summary>
+ <div className="mt-3 flex flex-col gap-4">
+ {detail.hotspots.files.length > 0 ? (
+ <RailSection title={labels.hotspots(detail.hotspots.total)}>
+ <FileRows files={detail.hotspots.files.slice(0, LIST_CAP)} selectedPath={props.selectedPath} onSelect={onSelectFile} />
+ </RailSection>
+ ) : null}
+ <RailSection title={labels.owners}>
+ {owner ? (
+ <p className="text-xs text-[var(--color-text-secondary)]">{labels.ownerShare(owner.name, Math.round(owner.share * 100))}</p>
+ ) : null}
+ <ul className="flex flex-col gap-0.5 text-xs text-[var(--color-text-secondary)]">
+ {detail.owners.top.slice(0, LIST_CAP).map((o) => (
+ <li key={o.key} className="flex justify-between gap-2">
+ <span className="truncate">{o.name}</span>
+ <span className="font-mono tabular-nums text-[var(--color-text-tertiary)]">{labels.files(o.files)}</span>
+ </li>
+ ))}
+ </ul>
+ </RailSection>
+ <RailSection title={labels.topFindings}>
+ {findings.length ? (
+ <FindingRows findings={findings} onSelectFile={onSelectFile} />
+ ) : (
+ <p className="text-xs text-[var(--color-text-tertiary)]">{labels.noFindings}</p>
+ )}
+ </RailSection>
+ </div>
+ </details>
+
+ {props.links ? <Links links={props.links} labels={labels} onNavigate={props.onNavigate} /> : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/area-rail/area-header.tsx b/packages/ui/src/health/area-rail/area-header.tsx
new file mode 100644
index 000000000..e261c6075
--- /dev/null
+++ b/packages/ui/src/health/area-rail/area-header.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+/**
+ * The top of an area card: the score with its band word, how it moved, the
+ * trend, and the band mix. One figure and its reading, then the shape.
+ */
+
+import { HEALTH_BAND_LABEL, HEALTH_BAND_ORDER, formatScore, type HealthBand } from "@repowise-dev/types/health";
+import type { AreaDetail } from "@repowise-dev/types/areas";
+
+import { ProportionBar } from "../../shared/proportion-bar";
+import { Sparkline } from "../sparkline";
+import { HEALTH_BAND_SEGMENT, deltaColor, formatDelta, healthBandTextColor } from "../tokens";
+import type { AreaRailLabels } from "./labels";
+
+/** Days the delta window actually spans, rounded, or the target when unknown. */
+function windowDays(detail: AreaDetail): number {
+ const { latest_at, baseline_at, target_days } = detail.delta_window;
+ if (!latest_at || !baseline_at) return target_days;
+ const ms = Date.parse(latest_at) - Date.parse(baseline_at);
+ return Number.isFinite(ms) && ms > 0 ? Math.max(1, Math.round(ms / 86_400_000)) : target_days;
+}
+
+export function AreaHeader({
+ detail,
+ eyebrow,
+ scope,
+ title,
+ labels,
+}: {
+ detail: AreaDetail;
+ eyebrow: string;
+ /** What the figures cover ("Production code"), when the map holds files out. */
+ scope?: string | undefined;
+ title: string;
+ labels: AreaRailLabels;
+}) {
+ const a = detail.area;
+ const band = a.band as HealthBand;
+ const delta = a.health_delta_30d;
+ const days = windowDays(detail);
+ const trend = detail.trend.map((p) => p.health);
+ return (
+ <header className="flex flex-col gap-3">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {[eyebrow, scope, labels.files(a.file_count)].filter(Boolean).join(" · ")}
+ </span>
+ <h3 className="break-all font-mono text-[15px] font-semibold leading-snug text-[var(--color-text-primary)]">
+ {title}
+ </h3>
+ </div>
+ <div className="flex items-end justify-between gap-3">
+ <div className="flex min-w-0 flex-col">
+ <span className="flex items-baseline gap-2">
+ <span className={`font-mono text-[22px] font-semibold tabular-nums leading-none ${healthBandTextColor(band)}`}>
+ {formatScore(a.health)}
+ </span>
+ <span className={`text-xs font-medium ${healthBandTextColor(band)}`}>{HEALTH_BAND_LABEL[band]}</span>
+ </span>
+ <span className={`mt-1 font-mono text-xs tabular-nums ${deltaColor(delta)}`}>
+ {delta == null ? labels.noDelta : labels.deltaWindow(formatDelta(delta), days)}
+ </span>
+ </div>
+ {trend.length > 1 ? (
+ <span className="shrink-0 text-[var(--color-text-tertiary)]">
+ <Sparkline values={trend} width={96} height={28} />
+ </span>
+ ) : null}
+ </div>
+ {delta != null && delta > 0 ? (
+ <p data-testid="area-improved" className="text-xs text-[var(--color-success)]">
+ {labels.improved(formatDelta(delta), days)}
+ </p>
+ ) : null}
+ <ProportionBar
+ size="sm"
+ sort={false}
+ legend={false}
+ label="Lines by health band"
+ segments={HEALTH_BAND_ORDER.map((b) => ({
+ key: b,
+ label: HEALTH_BAND_LABEL[b],
+ value: detail.distribution.bands[b].nloc,
+ detail: `${detail.distribution.bands[b].pct}%`,
+ color: HEALTH_BAND_SEGMENT[b],
+ }))}
+ />
+ </header>
+ );
+}
diff --git a/packages/ui/src/health/area-rail/area-rail.tsx b/packages/ui/src/health/area-rail/area-rail.tsx
new file mode 100644
index 000000000..aed48627c
--- /dev/null
+++ b/packages/ui/src/health/area-rail/area-rail.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+/**
+ * The map's context rail: what the selection is, one level at a time.
+ * Nothing selected reads the repository; an area reads that area; a file
+ * shows the file's full health detail, with the way back to its area.
+ */
+
+import type { ReactNode } from "react";
+import useSWR from "swr";
+import type { AreaDetail } from "@repowise-dev/types/areas";
+
+import { ApiError } from "../../shared/api-error";
+import { toFriendlyMessage } from "../../lib/errors";
+import { Skeleton, SkeletonRegion } from "../../ui/skeleton";
+import { useAiPromptAction } from "../ai-prompt-action";
+import type { AreaIndex } from "../map/areas";
+import { AreaCard, type AreaLinks } from "./area-card";
+import type { AreaRailLabels } from "./labels";
+
+export interface AreaRailProps {
+ cacheKey: string;
+ getAreaDetail: (path: string) => Promise<AreaDetail>;
+ area: string;
+ index: AreaIndex;
+ nameOf: (path: string) => string;
+ labels: AreaRailLabels;
+ selectedFile: string | null;
+ /** The file's detail, rendered by the host, shown while a file is selected. */
+ fileDetail: ReactNode;
+ onClearFile: () => void;
+ onSelectArea: (path: string) => void;
+ onSelectFile: (path: string) => void;
+ areaLinks?: ((path: string) => AreaLinks) | undefined;
+ onNavigate?: ((href: string) => void) | undefined;
+ /** What the figures cover ("Production code"), when the map holds files out. */
+ scope?: string | undefined;
+ /** Said under a load error: the folder may hold only files the map leaves out. */
+ errorHint?: string | undefined;
+ /** Part of the cache key: a card read under one hold is not another's. */
+ holdKey?: string | undefined;
+}
+
+function CardSkeleton({ label }: { label: string }) {
+ return (
+ <SkeletonRegion className="flex flex-col gap-4" label={label}>
+ <Skeleton className="h-10 w-2/3" />
+ <Skeleton className="h-8 w-1/2" />
+ <Skeleton className="h-2 w-full" />
+ <Skeleton className="h-7 w-48" />
+ <Skeleton className="h-24 w-full" />
+ </SkeletonRegion>
+ );
+}
+
+export function AreaRail(props: AreaRailProps) {
+ const { cacheKey, getAreaDetail, area, labels } = props;
+ const { openPrompt, promptModal } = useAiPromptAction();
+ const { data, error, mutate, isLoading } = useSWR<AreaDetail>(
+ props.selectedFile ? null : `area-detail:${cacheKey}:${props.holdKey ?? ""}:${area}`,
+ () => getAreaDetail(area),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ if (props.selectedFile) {
+ return (
+ <div className="flex flex-col gap-3">
+ <button
+ type="button"
+ onClick={props.onClearFile}
+ className="self-start rounded font-mono text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ ← {labels.backToArea(area ? props.nameOf(area) : labels.repository)}
+ </button>
+ {props.fileDetail}
+ </div>
+ );
+ }
+ if (error && !data) {
+ return (
+ <ApiError
+ size="compact"
+ title={labels.loadError}
+ message={props.errorHint ?? toFriendlyMessage(error)}
+ onRetry={() => void mutate()}
+ />
+ );
+ }
+ if (!data || isLoading) return <CardSkeleton label={labels.loading} />;
+ return (
+ <>
+ <AreaCard
+ detail={data}
+ index={props.index}
+ nameOf={props.nameOf}
+ labels={labels}
+ onSelectArea={props.onSelectArea}
+ onSelectFile={props.onSelectFile}
+ openPrompt={openPrompt}
+ links={props.areaLinks?.(area)}
+ onNavigate={props.onNavigate}
+ scope={props.scope}
+ />
+ {promptModal}
+ </>
+ );
+}
diff --git a/packages/ui/src/health/area-rail/area-sections.tsx b/packages/ui/src/health/area-rail/area-sections.tsx
new file mode 100644
index 000000000..f397e72c0
--- /dev/null
+++ b/packages/ui/src/health/area-rail/area-sections.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+/**
+ * The rows an area card is made of. Every row that names a place is a real
+ * button, so the rail is the map's keyboard and screen-reader route: an area
+ * row opens that area on the map, a file row opens the file in the rail.
+ */
+
+import type { ReactNode } from "react";
+import { HEALTH_BAND_LABEL, bandForScore, formatScore } from "@repowise-dev/types/health";
+import type { AreaFileRow, AreaFinding } from "@repowise-dev/types/areas";
+
+import { cn } from "../../lib/cn";
+import { biomarkerInfo } from "../biomarker-glossary";
+import { formatDelta, scoreTextColor } from "../tokens";
+import type { MapArea } from "../map/areas";
+
+export function RailSection({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section className="flex flex-col gap-1.5">
+ <h4 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{title}</h4>
+ {children}
+ </section>
+ );
+}
+
+const ROW =
+ "flex w-full min-w-0 items-baseline gap-2 rounded px-1.5 py-1 text-left transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
+
+function Score({ score }: { score: number | null }) {
+ return (
+ <span
+ className={cn("shrink-0 font-mono text-xs tabular-nums", score == null ? "text-[var(--color-text-tertiary)]" : scoreTextColor(score))}
+ title={score == null ? undefined : HEALTH_BAND_LABEL[bandForScore(score)]}
+ >
+ {score == null ? "—" : formatScore(score)}
+ </span>
+ );
+}
+
+/** Files, worst first: name leads, the directory is the small fact beside it. */
+export function FileRows({
+ files,
+ selectedPath,
+ onSelect,
+}: {
+ files: AreaFileRow[];
+ selectedPath?: string | null | undefined;
+ onSelect: (path: string) => void;
+}) {
+ return (
+ <ul className="flex flex-col">
+ {files.map((f) => {
+ const cut = f.path.lastIndexOf("/");
+ return (
+ <li key={f.path}>
+ <button
+ type="button"
+ onClick={() => onSelect(f.path)}
+ aria-current={f.path === selectedPath ? "true" : undefined}
+ className={ROW}
+ title={f.path}
+ >
+ <span className="min-w-0 flex-1 truncate text-xs text-[var(--color-text-primary)]">
+ {f.path.slice(cut + 1)}
+ <span className="ml-1.5 font-mono text-[10px] text-[var(--color-text-tertiary)]">{f.path.slice(0, cut + 1)}</span>
+ </span>
+ <Score score={f.score} />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+/** Areas: name, size, and the score that put them on the list. */
+export function AreaRows({
+ areas,
+ nameOf,
+ onSelect,
+ showDelta = false,
+}: {
+ areas: MapArea[];
+ nameOf: (path: string) => string;
+ onSelect: (path: string) => void;
+ showDelta?: boolean;
+}) {
+ return (
+ <ul className="flex flex-col">
+ {areas.map((a) => (
+ <li key={a.path}>
+ <button type="button" onClick={() => onSelect(a.path)} className={ROW} title={a.path}>
+ <span className="min-w-0 flex-1 truncate font-mono text-xs text-[var(--color-text-primary)]">{nameOf(a.path)}</span>
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {a.fileCount.toLocaleString()}
+ </span>
+ {showDelta && a.delta30d != null ? (
+ <span className="shrink-0 font-mono text-xs tabular-nums text-[var(--color-success)]">{formatDelta(a.delta30d)}</span>
+ ) : (
+ <Score score={a.health} />
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+/** Findings: what it is, where, and the file it opens. */
+export function FindingRows({
+ findings,
+ onSelectFile,
+}: {
+ findings: AreaFinding[];
+ onSelectFile: (path: string) => void;
+}) {
+ return (
+ <ul className="flex flex-col">
+ {findings.map((f) => {
+ const name = f.file_path.slice(f.file_path.lastIndexOf("/") + 1);
+ return (
+ <li key={f.id}>
+ <button type="button" onClick={() => onSelectFile(f.file_path)} className={cn(ROW, "flex-col items-start gap-0")} title={f.file_path}>
+ <span className="text-xs text-[var(--color-text-primary)]">
+ {biomarkerInfo(f.biomarker_type).label}
+ <span className="ml-1.5 text-[10px] capitalize text-[var(--color-text-tertiary)]">{f.severity}</span>
+ </span>
+ <span className="max-w-full truncate font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {name}
+ {f.function_name ? ` · ${f.function_name}` : ""}
+ {f.line_start ? `:${f.line_start}` : ""}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/packages/ui/src/health/area-rail/labels.ts b/packages/ui/src/health/area-rail/labels.ts
new file mode 100644
index 000000000..a5f3d5afd
--- /dev/null
+++ b/packages/ui/src/health/area-rail/labels.ts
@@ -0,0 +1,111 @@
+import { DEFAULT_MAP_CANVAS_LABELS, type MapCanvasLabels } from "../map/canvas-labels";
+
+/** Every string the area map section, its canvas and its rail render, so a host can translate it. */
+export interface AreaRailLabels extends MapCanvasLabels {
+ mapTitle: string;
+ /** Under the title, with the areas API (lazy hierarchy, rail). */
+ mapDescription: string;
+ /** Under the title, for a flat feed. */
+ flatMapDescription: string;
+ searchPlaceholder: string;
+ mapLoadError: string;
+ /** The canvas's accessible name and key help, for the active lens. */
+ mapAriaLabel: (lens: string) => string;
+ /** What the map and rail cover: nothing held back in. */
+ scopeProduction: string;
+ /** Every held group brought back. */
+ scopeAll: string;
+ /** Some held groups brought back: "Production code and test files". */
+ scopeWith: (names: string) => string;
+ /** Under an area that failed to load while groups are held out. */
+ heldOutHint: string;
+ /** The lens switcher's menu of further lenses. */
+ moreLenses: string;
+ /** A lens's name in the switcher; `undefined` keeps the built-in English. */
+ lensName?: ((lens: string) => string | undefined) | undefined;
+ /** The rail's one filled action: what the N are. */
+ promptAction: (count: number) => string;
+ repository: string;
+ /** Eyebrow over the repository summary and over an area card. */
+ repoEyebrow: string;
+ areaEyebrow: string;
+ files: (count: number) => string;
+ /** "+0.42 in 30 days", the window the delta covers. */
+ deltaWindow: (delta: string, days: number) => string;
+ /** The calm good-news line under an improved score. */
+ improved: (delta: string, days: number) => string;
+ noDelta: string;
+ needsAttention: string;
+ subAreas: string;
+ improvedMost: string;
+ worstFiles: string;
+ hotspots: (count: number) => string;
+ owners: string;
+ ownerShare: (name: string, pct: number) => string;
+ busFactorOne: (count: number) => string;
+ coverage: string;
+ noCoverage: string;
+ coverageLine: (pct: number, files: number) => string;
+ topFindings: string;
+ noFindings: string;
+ allClean: (files: number) => string;
+ promptTitle: string;
+ promptDescription: string;
+ findingsLink: string;
+ fixFirstLink: string;
+ contributorsLink: string;
+ backToArea: (name: string) => string;
+ loading: string;
+ loadError: string;
+}
+
+const s = (n: number, one: string, many: string) => `${n.toLocaleString()} ${n === 1 ? one : many}`;
+
+export const DEFAULT_AREA_RAIL_LABELS: AreaRailLabels = {
+ ...DEFAULT_MAP_CANVAS_LABELS,
+ mapTitle: "Code health map",
+ mapDescription:
+ "Every folder is a disc sized by lines of code and coloured by the lens. Zoom in and folders open into their sub-folders, then their files. Click a folder to open it, a file to read it in the rail.",
+ flatMapDescription:
+ "Every file as a node, grouped into its folders and sized by lines of code. The lens re-marks the same field rather than redrawing it. Click a folder to zoom, a file to inspect it.",
+ searchPlaceholder: "Find a file in the map…",
+ moreLenses: "More",
+ heldOutHint:
+ "This folder may hold only files the map leaves out by default. Bring them back with the toggles under the map.",
+ scopeProduction: "Production code",
+ scopeAll: "All code",
+ scopeWith: (names) => `Production code and ${names}`,
+ mapLoadError: "Couldn't load the map",
+ mapAriaLabel: (lens) =>
+ `Code health map, ${lens} lens. Arrow keys move between the areas and files inside the selected area, Enter opens one, Backspace goes up a level, Escape returns to the repository, plus and minus zoom.`,
+ promptAction: (n) => (n === 1 ? "Copy prompt for the top finding" : `Copy prompt for the top ${n.toLocaleString()} findings`),
+ repository: "Repository",
+ repoEyebrow: "Repository",
+ areaEyebrow: "Area",
+ files: (n) => s(n, "file", "files"),
+ deltaWindow: (delta, days) => `${delta} in ${days} days`,
+ improved: (delta, days) => `Up ${delta} over the last ${days} days. The work here is paying off.`,
+ noDelta: "No earlier snapshot to compare with yet.",
+ needsAttention: "Needs attention",
+ subAreas: "Inside, lowest first",
+ improvedMost: "Improved most",
+ worstFiles: "Lowest-scoring files",
+ hotspots: (n) => `Hotspots · ${n.toLocaleString()}`,
+ owners: "Who knows it",
+ ownerShare: (name, pct) => `${name} leads ${pct}% of the files`,
+ busFactorOne: (n) => `${s(n, "file", "files")} only one person has changed`,
+ coverage: "Tests",
+ noCoverage: "No coverage report covers this area.",
+ coverageLine: (pct, files) => `${pct}% line coverage over ${s(files, "measured file", "measured files")}`,
+ topFindings: "Top findings",
+ noFindings: "No open findings here.",
+ allClean: (files) => `No open findings across ${s(files, "file", "files")}.`,
+ promptTitle: "Agent prompt for this area",
+ promptDescription: "The area's highest-priority findings, ready to paste into your agent.",
+ findingsLink: "Findings here",
+ fixFirstLink: "Fix first here",
+ contributorsLink: "Contributors here",
+ backToArea: (name) => `Back to ${name}`,
+ loading: "Loading area",
+ loadError: "Couldn't load this area.",
+};
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index a67933234..79b36bc9f 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -5,6 +5,7 @@ import type {
HealthScope,
HealthFilesResponse,
HealthFinding,
+ HealthMapFeed,
HealthOverviewResponse,
HealthWorkQueueQuery,
HealthWorkQueueResponse,
@@ -17,6 +18,8 @@ import type {
TestsReachingFile,
} from "@repowise-dev/types/health";
import type { Paginated } from "@repowise-dev/types";
+import type { AreaDetail, AreaTree } from "@repowise-dev/types/areas";
+import type { AreaLinks } from "./area-rail/area-card";
import type { AiPromptFlavor } from "./ai-prompts/shared";
import type { CodeHealthOverlay } from "./map/types";
import type { RelatedWorkHref } from "./related-work";
@@ -159,6 +162,18 @@ export interface CodeHealthAdapter {
/** Navigate to an href (host wires this to its router). */
navigate(href: string): void;
+ /**
+ * The areas API. With all three, the map loads its hierarchy and files as
+ * the reader zooms and the rail reads each area's card; without them the
+ * map derives its hierarchy from the flat `mapFeed` and the rail lists files.
+ */
+ getAreaTree?(root: string, depth: number): Promise<AreaTree>;
+ getAreaDetail?(path: string): Promise<AreaDetail>;
+ /** One area's complete file list, the map feed narrowed with `?area=`. */
+ getAreaFiles?(area: string): Promise<HealthMapFeed>;
+ /** Where an area card's secondary links go. */
+ areaLinks?(path: string): AreaLinks;
+
/**
* Render the app's file-detail drawer for the inspected path. Kept as a slot
* so each app supplies its own data fetch + toast wiring; pass `null` for
@@ -173,5 +188,7 @@ export interface CodeHealthAdapter {
filePath: string | null;
onClose: () => void;
lens?: CodeHealthOverlay;
+ /** Render the detail in place, in the map's rail, rather than in a sheet. */
+ inline?: boolean;
}): ReactNode;
}
diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsx
index 4c623a31a..89dc6e997 100644
--- a/packages/ui/src/health/code-health-map.tsx
+++ b/packages/ui/src/health/code-health-map.tsx
@@ -1,66 +1,57 @@
"use client";
/**
- * The Code Health galaxy: one field, one geometry, a switchable lens.
+ * The Code Health area map: every directory a disc inside its parent, one
+ * geometry, a switchable lens, and semantic zoom from the repository down to
+ * single files.
*
- * This module is the facade. The layout, the lens encodings, the hit grid, the
- * canvas painter and its frame loop, the camera, the pointer and keyboard
- * models, and the pieces of chrome are separate modules under `map/`, and
- * everything a host used to import is still re-exported here. What is left in
- * this file is composition: which hook owns what, and what each layer shows.
+ * This module is the facade. The hierarchy, its layout, the lens encodings,
+ * the per-frame zoom decisions, the painter and its frame loop, the camera,
+ * the pointer and keyboard models, and the pieces of chrome are separate
+ * modules under `map/`; what is left here is composition.
*
* The geometry is deterministic and lens-independent on purpose. A reader
* builds spatial memory of this field, and switching a lens must recolor it
* rather than redraw it, or that memory is worth nothing.
*
- * The field paints on a canvas. As SVG it was one element per file, so every
- * hover, zoom frame and lens switch reconciled thousands of nodes; on a canvas
- * the camera and the pointer live in refs, a frame is one transform and one
- * fill per colour, and React re-renders only for what it actually shows: the
- * galaxy labels, the hover card and the notes around the field.
+ * Two ways to feed it. A host with the areas API passes `source` (see
+ * `useAreaSource`): the hierarchy and its files load as the reader zooms, and
+ * the rollups are the server's. A host with a flat file feed passes `files`
+ * and the hierarchy is derived from them. Both draw the same map.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { EmptyState } from "../shared/empty-state";
+import { Breadcrumb } from "../shared/breadcrumb";
import { usePrefersReducedMotion } from "../hooks/use-prefers-reduced-motion";
-import {
- HEALTH_UNSUPPORTED_NOTICE,
- OVERLAY_ORDER,
- OVERLAY_SPECS,
- lensAvailable,
- noFileScored,
-} from "./map/lens";
-import { HoverCard } from "./map/overlay";
-import { GalaxyLabels } from "./map/labels";
-import { CanvasChrome, FocusCrumb, ZoomControls } from "./map/controls";
-import { MapScopeNote } from "./map/scope-note";
+import { ROOT_AREA } from "../lib/areas";
+import type { MapLens } from "./map/lens";
+import { OVERLAY_ORDER, lensAvailable, resolveLens } from "./map/lens-registry";
+import { deriveAreaIndex } from "./map/areas";
+import { chainEnd, displayLabel } from "./map/area-paths";
+import { AreaLabels } from "./map/labels";
+import { FieldHover, FieldNotes, useAreaChrome } from "./map/field-notes";
+import { CanvasChrome, ZoomControls } from "./map/controls";
import { useFieldModel } from "./map/use-field-model";
import { useFieldCanvas } from "./map/use-field-canvas";
import { ZOOM_STEP, useMapCamera } from "./map/use-map-camera";
import { useHover, useMapPointer } from "./map/use-map-pointer";
import { useKeyboardCursor, useMapKeyboard, type KeyboardCursor } from "./map/use-map-keyboard";
+import type { AreaSource } from "./map/use-area-source";
+import { DEFAULT_MAP_CANVAS_LABELS, type MapCanvasLabels } from "./map/canvas-labels";
+import type { HeldGroups } from "./map/scope-note";
import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./map/types";
-export type {
- CodeHealthMapFile,
- CodeHealthOverlay,
- FileNode,
- Galaxy,
- GalaxyAgg,
- MapScope,
- PerformanceActionability,
-} from "./map/types";
+export type { CodeHealthMapFile, CodeHealthOverlay, FileNode, MapScope, PerformanceActionability } from "./map/types";
export {
+ BAND_LEGEND,
HEALTH_UNSUPPORTED_LABEL,
HEALTH_UNSUPPORTED_NOTICE,
NEUTRAL_FILL,
- OVERLAY_ORDER,
- OVERLAY_SPECS,
PERFORMANCE_STATE_LABEL,
QUIET_FILL,
burdenBand,
- lensAvailable,
noFileScored,
performanceBurden,
performanceFill,
@@ -69,19 +60,40 @@ export {
} from "./map/lens";
export type {
LegendRow,
+ LensContext,
+ MapLens,
OverlaySpec,
PerformanceBurden,
PerformanceBurdenUnit,
PerformanceNodeState,
} from "./map/lens";
-export { WORLD, fitCamera, groupByModule, layoutField, moduleColorId, packGalaxies } from "./map/layout";
+export { OVERLAY_ORDER, OVERLAY_SPECS, lensAvailable, resolveLens } from "./map/lens-registry";
+export { KNOWLEDGE_LENS, ownerLens, rankOwners, shareFill } from "./map/area-lenses";
+export { EMPTY_AREA_INDEX, deriveAreaIndex, mergeAreaTree, type AreaIndex, type MapArea } from "./map/areas";
+export { areaTrail, chainEnd, displayChildren, displayLabel, displayParent } from "./map/area-paths";
+export { layoutAreas, layoutFiles } from "./map/area-layout";
+export { WORLD, fitCamera } from "./map/layout";
export { buildHitGrid, hitTest } from "./map/hit-test";
export { MapLegend, MapLensSwitcher } from "./map/legend";
export { SEARCH_MARK_CAP } from "./map/overlay";
-export { FIELD_LIST_CAP, MapFieldList } from "./map/inspector";
+export { useAreaSource, type AreaFetchers, type AreaSource } from "./map/use-area-source";
+export { DEFAULT_MAP_CANVAS_LABELS, type MapCanvasLabels } from "./map/canvas-labels";
+export type { HeldGroups } from "./map/scope-note";
+
+/** What the root disc is called in the breadcrumb and the key. */
+const ROOT_LABEL = "Repository";
+const DEFAULT_ARIA_LABEL = (lens: string) =>
+ `Code health map, ${lens} lens. Arrow keys move between the areas and files inside the selected area, Enter opens one, Backspace goes up a level, Escape returns to the repository, plus and minus zoom.`;
export interface CodeHealthMapProps {
+ /** The flat file feed. Ignored when `source` is given. */
files: CodeHealthMapFile[];
+ /** The lazily loaded hierarchy, for a host with the areas API. */
+ source?: AreaSource;
+ /** Selected area; `""` is the repository. The camera frames it. */
+ area?: string;
+ /** Area click, breadcrumb, Backspace (up) and Escape (root). */
+ onAreaChange?: (area: string) => void;
/** Selection ring on this file. Owned by the host so a link can set it. */
selectedPath?: string | null;
/** Filename substring. Matching nodes take a ring; the field is untouched. */
@@ -94,47 +106,62 @@ export interface CodeHealthMapProps {
onHoverFile?: (file: CodeHealthMapFile | null) => void;
/** Canvas min height in px. */
minHeight?: number;
- /** Which lens recolors the field. Defaults to `health`. */
+ /** Which built-in lens recolors the field. Defaults to `health`. */
overlay?: CodeHealthOverlay;
+ /**
+ * A lens of the host's own, which wins over `overlay`. This is how another
+ * surface (off-boarding, coupling) colours the same map: build a
+ * {@link MapLens} over its data and pass it here and to `MapLegend`.
+ */
+ lens?: MapLens;
/** When provided, the lens is switchable from the on-canvas chrome. */
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
/** Lenses offered in the switcher. Defaults to {@link OVERLAY_ORDER}. */
lenses?: CodeHealthOverlay[];
- /**
- * The active lens's per-file signal is still loading. The key says so, so an
- * all-neutral field reads as "fetching" rather than as "no data".
- */
+ /** The active lens's per-file signal is still loading. */
overlayLoading?: boolean;
- /**
- * What the server drew and what it left out. Rendered as one sentence over
- * the canvas, from the same response the field came from.
- */
+ /** What the server drew and what it left out, for a flat, capped feed. */
scope?: MapScope;
/**
- * Where the lens switcher and key live.
- *
- * `"canvas"` (default) floats them over the map, for a host with nowhere
- * else to put them. `"none"` renders neither, for a host that lays them out
- * around the canvas with {@link MapLensSwitcher} / {@link MapLegend}.
+ * Where the lens switcher and key live: `"canvas"` (default) floats them
+ * over the map, `"none"` leaves them to the host.
*/
chrome?: "canvas" | "none";
- /**
- * Ask the host for a bigger field. Offered in the scope note while the
- * field is capped; the host raises its cap by `drawMoreStep` and refetches.
- */
+ /** Ask the host for a bigger flat field. */
onDrawMore?: () => void;
- /** Files one "draw more" adds, for the button's label. Defaults to 2,000. */
drawMoreStep?: number;
- /** Ask the host to draw (or stop drawing) vendored and generated files. */
onIncludeHeldChange?: (include: boolean) => void;
- /** Ask the host to pin the files matching `search` that are not drawn. */
onFindUndrawn?: (query: string) => void;
- /** A host request for a new field is in flight; its buttons wait for it. */
+ /** A host request for a new field is in flight. */
pending?: boolean;
+ /** The root disc's name. */
+ rootLabel?: string;
+ /** The canvas's accessible name and key help, for the active lens's label. */
+ ariaLabel?: (lens: string) => string;
+ /** The words the canvas prints (folder chips, hover card), for translation. */
+ labels?: Partial<MapCanvasLabels>;
+ /** Groups held out of the map, toggled back from the canvas footer. */
+ heldGroups?: HeldGroups;
+}
+
+/** The selected area, owned by the host when it passes `onAreaChange`, local otherwise. */
+function useSelectedArea(area: string | undefined, onAreaChange: ((a: string) => void) | undefined) {
+ const [local, setLocal] = useState(ROOT_AREA);
+ const selected = area ?? local;
+ const ref = useRef(onAreaChange);
+ ref.current = onAreaChange;
+ const select = useCallback((next: string) => {
+ if (ref.current) ref.current(next);
+ else setLocal(next);
+ }, []);
+ return [selected, select] as const;
}
export function CodeHealthMap({
files,
+ source,
+ area,
+ onAreaChange,
selectedPath,
search,
highlightPaths,
@@ -142,6 +169,7 @@ export function CodeHealthMap({
onHoverFile,
minHeight = 640,
overlay = "health",
+ lens: hostLens,
onOverlayChange,
lenses = OVERLAY_ORDER,
overlayLoading = false,
@@ -152,61 +180,84 @@ export function CodeHealthMap({
onIncludeHeldChange,
onFindUndrawn,
pending = false,
+ rootLabel = ROOT_LABEL,
+ ariaLabel = DEFAULT_ARIA_LABEL,
+ labels: labelOverrides,
+ heldGroups,
}: CodeHealthMapProps) {
- const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
+ const words = useMemo(() => ({ ...DEFAULT_MAP_CANVAS_LABELS, ...labelOverrides }), [labelOverrides]);
const containerRef = useRef<HTMLDivElement>(null);
const baseRef = useRef<HTMLCanvasElement>(null);
const topRef = useRef<HTMLCanvasElement>(null);
const keyboardRef = useRef<HTMLDivElement>(null);
- const labelRefs = useRef<(HTMLButtonElement | null)[]>([]);
+ const labelRefs = useRef(new Map<string, HTMLElement>());
const reducedMotion = usePrefersReducedMotion();
- const model = useFieldModel(files, spec, search, highlightPaths);
- const { galaxies, scene } = model;
- const [focusModule, setFocusModule] = useState<string | null>(null);
- const focusIdx = focusModule ? galaxies.findIndex((g) => g.module === focusModule) : -1;
- const kb = useKeyboardCursor(galaxies);
+ const derived = useMemo(() => (source ? null : deriveAreaIndex(files)), [source, files]);
+ const index = source?.index ?? derived!;
+ const fieldFiles = source?.files ?? files;
+ const lens = useMemo(() => hostLens ?? resolveLens(overlay, index, words), [hostLens, overlay, index, words]);
+ const model = useFieldModel(index, fieldFiles, lens, search, highlightPaths);
+ const { scene, geo } = model;
+
+ const [rawArea, selectArea] = useSelectedArea(area, onAreaChange);
+ const selected = chainEnd(index, rawArea);
+ const reveal = source?.reveal;
+ useEffect(() => {
+ if (reveal && rawArea !== ROOT_AREA && !index.areas.has(rawArea)) reveal(rawArea);
+ }, [reveal, rawArea, index]);
+ const kb = useKeyboardCursor(index, scene, selected);
const { hover, setHovered } = useHover(onHoverFile);
- const hoverIdx = hover ? scene.index.get(hover.file.file_path) ?? -1 : -1;
- const selectedIdx = selectedPath ? scene.index.get(selectedPath) ?? -1 : -1;
- const cursorIdx = kb.node && kb.focused ? scene.index.get(kb.node.file.file_path) ?? -1 : -1;
+ const hoverIdx = hover?.kind === "file" ? (scene.index.get(hover.file.file_path) ?? -1) : -1;
+ const selectedIdx = selectedPath ? (scene.index.get(selectedPath) ?? -1) : -1;
+ const cursorItem = kb.focused ? kb.item : null;
+ const cursorIdx = cursorItem?.kind === "file" ? (scene.index.get(cursorItem.path) ?? -1) : -1;
- const { loop, invalidate } = useFieldCanvas({
+ const allFilesCovered = useCallback(() => true, []);
+ const { loop, invalidate, ready } = useFieldCanvas({
container: containerRef,
base: baseRef,
top: topRef,
labels: labelRefs,
minHeight,
reducedMotion,
- labelKey: `${kb.moduleIdx}:${kb.level}`,
+ labelKey: `${selected}:${cursorItem?.path ?? ""}:${lens.id}`,
live: {
+ index,
+ geo,
scene,
fills: model.fills,
- focusIdx,
+ areaFill: model.areaFill,
marked: model.marked,
selectedIdx,
cursorIdx,
hoverIdx,
+ selectedArea: selected === ROOT_AREA ? null : selected,
+ hoverArea: hover?.kind === "area" && !hover.slot && hover.path !== ROOT_AREA ? hover.path : null,
+ cursorArea: cursorItem?.kind === "area" ? cursorItem.path : null,
minNodeR: model.minNodeR,
- labelOrder: model.labelOrder,
+ filesCovered: source?.filesCovered ?? allFilesCovered,
+ onWants: source?.request,
},
});
- const camera = useMapCamera({ loop, invalidate, reducedMotion, galaxies, focusModule, setFocusModule });
-
- // A galaxy that left the field takes its focus with it.
- useEffect(() => {
- if (focusModule && focusIdx < 0) setFocusModule(null);
- }, [focusModule, focusIdx]);
+ const camera = useMapCamera({ loop, invalidate, reducedMotion, geo, area: selected, ready });
const onSelectRef = useRef(onSelectFile);
onSelectRef.current = onSelectFile;
- const handleSelect = useCallback((path: string) => {
+ const handleSelectFile = useCallback((path: string) => {
// Clicking a node hands focus to the field's keyboard region, so a reader
// who reached the map with a pointer can carry on with arrow keys.
- keyboardRef.current?.focus();
+ keyboardRef.current?.focus({ preventScroll: true });
onSelectRef.current?.(path);
}, []);
+ const handleSelectArea = useCallback(
+ (path: string) => {
+ keyboardRef.current?.focus({ preventScroll: true });
+ selectArea(chainEnd(index, path));
+ },
+ [index, selectArea],
+ );
const handlers = useMapPointer({
container: containerRef,
@@ -215,153 +266,142 @@ export function CodeHealthMap({
scene,
grid: model.grid,
minNodeR: model.minNodeR,
- galaxies,
- focusModule,
- focusOn: camera.focusOn,
- onSelect: handleSelect,
+ onSelectFile: handleSelectFile,
+ onSelectArea: handleSelectArea,
setHovered,
});
const onKeyDown = useMapKeyboard({
container: containerRef,
kb,
- galaxies,
+ index,
+ area: selected,
camera,
- focusModule,
- setFocusModule,
- onSelect: handleSelect,
+ onSelectArea: handleSelectArea,
+ onSelectFile: handleSelectFile,
});
- const offered = useMemo(() => lenses.filter((l) => lensAvailable(l, files)), [lenses, files]);
+ const { labels, trail } = useAreaChrome(index, geo, model.areaText, selected, rootLabel, handleSelectArea);
+ const offered = useMemo(
+ () => lenses.filter((l) => lensAvailable(l, fieldFiles, index)),
+ [lenses, fieldFiles, index],
+ );
- if (files.length === 0) {
+ if (!source && files.length === 0) {
return (
<div ref={containerRef} className="flex w-full items-center justify-center" style={{ minHeight }}>
- <EmptyState
- size="compact"
- title="No files to map yet"
- description="Index this repo to populate health."
- />
+ <EmptyState size="compact" title="No files to map yet" description="Index this repo to populate health." />
</div>
);
}
- const focusGalaxy = focusIdx >= 0 ? galaxies[focusIdx]! : null;
- const leave = () => {
- kb.setLevel("module");
- camera.fitAll();
- };
-
+ const root = index.areas.get(ROOT_AREA);
+ const flatActions = { drawMoreStep, pending, onDrawMore, onIncludeHeldChange, onFindUndrawn };
return (
- <div
- ref={containerRef}
- data-testid="map-field"
- data-matches={model.matches.length}
- data-selected={selectedIdx >= 0 ? selectedPath ?? undefined : undefined}
- data-keyboard-cursor={kb.node?.file.file_path}
- className="relative w-full overflow-hidden rounded-xl border border-[var(--color-border-default)] focus-within:ring-2 focus-within:ring-[var(--color-accent-primary)]"
- style={{
- minHeight,
- background:
- "radial-gradient(ellipse at 50% 42%, var(--color-bg-surface), var(--color-bg-root) 75%)",
- }}
- >
- {/* One tab stop for the whole field. Pointer events stay off so it never
- intercepts a click meant for the canvas. */}
+ <div className="flex min-w-0 flex-col gap-2">
+ <div data-testid="map-breadcrumb" className="min-h-5 min-w-0 font-mono text-xs">
+ <Breadcrumb segments={trail} />
+ </div>
<div
- ref={keyboardRef}
- tabIndex={0}
- role="group"
- aria-label={`Code health map, ${spec.label} lens. Arrow keys move between modules, Enter opens one, plus and minus zoom, 0 fits the field.`}
- onKeyDown={onKeyDown}
- onFocus={() => kb.setFocused(true)}
- onBlur={() => kb.setFocused(false)}
- className="pointer-events-none absolute inset-0 z-10 outline-none"
- />
- <span aria-live="polite" className="sr-only">
- {cursorLabel(kb, spec.label)}
- </span>
- <p className="sr-only">
- {`${scene.nodes.length.toLocaleString()} files drawn in ${galaxies.length} groups, sized by lines of code. ${model.attention.toLocaleString()} need attention under the ${spec.label.toLowerCase()} lens. The list beside the map reaches every one.`}
- </p>
-
- <canvas ref={baseRef} aria-hidden className="pointer-events-none absolute inset-0" />
- <canvas
- ref={topRef}
- aria-hidden
- data-testid="map-canvas"
- {...handlers}
- onPointerCancel={handlers.onPointerUp}
- className={`absolute inset-0 ${hover && onSelectFile ? "cursor-pointer" : "cursor-grab active:cursor-grabbing"}`}
- style={{ touchAction: "pan-y" }}
- />
-
- <GalaxyLabels
- galaxies={galaxies}
- refs={labelRefs}
- focusIdx={focusIdx}
- cursorIdx={kb.focused && kb.level === "module" && kb.galaxy ? galaxies.indexOf(kb.galaxy) : -1}
- onToggle={(m) => camera.focusOn(focusModule === m ? null : m)}
- />
-
- {chrome === "canvas" ? (
- <CanvasChrome
- overlay={overlay}
- spec={spec}
- lenses={offered}
- loading={overlayLoading}
- onOverlayChange={onOverlayChange}
+ ref={containerRef}
+ data-testid="map-field"
+ data-area={selected}
+ data-matches={model.matches.length}
+ data-selected={selectedIdx >= 0 ? (selectedPath ?? undefined) : undefined}
+ data-keyboard-cursor={cursorItem?.path}
+ className="relative w-full overflow-hidden rounded-xl border border-[var(--color-border-default)] has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-[var(--color-accent-primary)]"
+ style={{
+ minHeight,
+ background: "radial-gradient(ellipse at 50% 42%, var(--color-bg-surface), var(--color-bg-root) 75%)",
+ }}
+ >
+ {/* One tab stop for the whole field. Pointer events stay off so it never
+ intercepts a click meant for the canvas. */}
+ <div
+ ref={keyboardRef}
+ tabIndex={0}
+ role="group"
+ aria-label={ariaLabel(lens.label)}
+ onKeyDown={onKeyDown}
+ // The cursor ring answers to keys, so it shows only for keyboard focus.
+ onFocus={(e) => kb.setFocused(e.currentTarget.matches(":focus-visible"))}
+ onBlur={() => kb.setFocused(false)}
+ className="pointer-events-none absolute inset-0 z-10 outline-none"
/>
- ) : null}
+ <span aria-live="polite" className="sr-only">
+ {cursorLabel(kb, index, rootLabel)}
+ </span>
+ <p className="sr-only">
+ {`${root ? root.fileCount.toLocaleString() : fieldFiles.length.toLocaleString()} files in ${Math.max(index.areas.size - 1, 0)} folders, each folder a disc sized by lines of code. The list beside the map reaches every area and file.`}
+ </p>
- <div className="absolute right-3 top-3 z-20 flex flex-col items-end gap-1.5">
- {focusGalaxy ? <FocusCrumb label={focusGalaxy.label} onLeave={leave} /> : null}
- <ZoomControls
- onZoomIn={() => camera.zoomBy(ZOOM_STEP)}
- onZoomOut={() => camera.zoomBy(1 / ZOOM_STEP)}
- onFit={leave}
+ <canvas ref={baseRef} aria-hidden className="pointer-events-none absolute inset-0" />
+ <canvas
+ ref={topRef}
+ aria-hidden
+ data-testid="map-canvas"
+ {...handlers}
+ onPointerCancel={handlers.onPointerUp}
+ className={`absolute inset-0 ${hover ? "cursor-pointer" : "cursor-grab active:cursor-grabbing"}`}
+ style={{ touchAction: "pan-y" }}
/>
- </div>
- {scope ? (
- <MapScopeNote
- scope={scope}
- matches={model.matches.length}
- query={model.query}
- drawMoreStep={drawMoreStep}
- pending={pending}
- onDrawMore={onDrawMore}
- onIncludeHeldChange={onIncludeHeldChange}
- onFindUndrawn={onFindUndrawn}
+ <AreaLabels
+ labels={labels}
+ refs={labelRefs}
+ selected={selected}
+ cursor={cursorItem?.kind === "area" ? cursorItem.path : null}
+ onSelect={handleSelectArea}
/>
- ) : null}
- {noFileScored(files) ? (
- <div
- role="status"
- data-testid="map-unanalysed"
- className="pointer-events-none absolute bottom-3 left-3 max-w-[64%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-xs text-[var(--color-text-secondary)] shadow-sm backdrop-blur-sm sm:max-w-[44%]"
- >
- {HEALTH_UNSUPPORTED_NOTICE}
+ {chrome === "canvas" ? (
+ <CanvasChrome
+ overlay={overlay}
+ spec={lens}
+ lenses={offered}
+ loading={overlayLoading}
+ onOverlayChange={onOverlayChange}
+ />
+ ) : null}
+
+ <div className="absolute right-3 top-3 z-20">
+ <ZoomControls
+ onZoomIn={() => camera.zoomBy(ZOOM_STEP)}
+ onZoomOut={() => camera.zoomBy(1 / ZOOM_STEP)}
+ onFit={camera.reframe}
+ />
</div>
- ) : null}
- {hover ? (
- <HoverCard
- file={hover.file}
+ <FieldNotes
+ flat={source ? null : { files, scope, ...flatActions }}
+ loaded={source && root ? { loaded: scene.nodes.length, total: root.fileCount } : null}
+ matches={model.matches.length}
+ query={model.query}
+ held={heldGroups}
+ labels={words}
+ />
+ <FieldHover
+ hover={hover}
+ analysed={model.areaAnalysed}
+ areaText={model.areaText}
+ labels={words}
+ index={index}
+ lens={lens}
overlay={overlay}
- x={hover.x}
- y={hover.y}
+ rootLabel={rootLabel}
width={loop.current.view.w}
height={loop.current.view.h}
/>
- ) : null}
+ </div>
</div>
);
}
/** What the live region says about the keyboard cursor. */
-function cursorLabel(kb: KeyboardCursor, lens: string): string {
- if (kb.level === "file" && kb.node) return `${kb.node.file.file_path}, ${lens} lens`;
- return kb.galaxy ? `${kb.galaxy.label}, ${kb.galaxy.fileCount} files` : "";
+function cursorLabel(kb: KeyboardCursor, index: Parameters<typeof displayLabel>[0], rootLabel: string): string {
+ const item = kb.focused ? kb.item : null;
+ if (!item) return "";
+ if (item.kind === "file") return item.path;
+ const a = index.areas.get(item.path);
+ return a ? `${displayLabel(index, item.path, rootLabel)}, ${a.fileCount.toLocaleString()} files` : "";
}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 1cf48220f..3b585b8c0 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -94,6 +94,11 @@ export interface HealthDrawerMetric {
export interface HealthFileDrawerProps extends RelatedWorkSlotProps {
open: boolean;
+ /**
+ * Render the same content in place, for a host that has a rail for it (the
+ * area map), instead of in a sheet. `onClose` is then the host's to offer.
+ */
+ inline?: boolean;
onClose: () => void;
/**
* The file the reader asked for. Optional: without it the header follows
@@ -179,6 +184,35 @@ function drawerView(props: HealthFileDrawerProps) {
export function HealthFileDrawer(props: HealthFileDrawerProps) {
const { open, onClose, loading, metric } = props;
const { headerPath, stale } = drawerView(props);
+ const body = (
+ <div
+ className={cn(
+ "flex flex-col gap-6 transition-opacity motion-reduce:transition-none",
+ props.inline ? "py-2" : "px-4 py-4",
+ stale && "pointer-events-none opacity-60",
+ )}
+ aria-busy={stale || Boolean(loading && !metric)}
+ // The previous file's body is a placeholder, not a surface: a triage
+ // write from it would revalidate the new file's key and leave the old
+ // one's cache stale.
+ inert={stale}
+ >
+ <DrawerContent props={props} headerPath={headerPath} />
+ </div>
+ );
+ if (props.inline) {
+ if (!open) return null;
+ return (
+ <section data-testid="file-detail-inline" className="flex min-w-0 flex-col">
+ {headerPath ? (
+ <h3 className="flex min-w-0 flex-col gap-0.5">
+ <FileTitle path={headerPath} />
+ </h3>
+ ) : null}
+ {body}
+ </section>
+ );
+ }
return (
<AdaptivePanel
open={open}
@@ -194,19 +228,7 @@ export function HealthFileDrawer(props: HealthFileDrawerProps) {
titleClassName="mt-0.5 flex min-w-0 flex-col gap-0.5"
widthClassName="md:max-w-[560px]"
>
- <div
- className={cn(
- "flex flex-col gap-6 px-4 py-4 transition-opacity motion-reduce:transition-none",
- stale && "pointer-events-none opacity-60",
- )}
- aria-busy={stale || Boolean(loading && !metric)}
- // The previous file's body is a placeholder, not a surface: a triage
- // write from it would revalidate the new file's key and leave the old
- // one's cache stale.
- inert={stale}
- >
- <DrawerContent props={props} headerPath={headerPath} />
- </div>
+ {body}
</AdaptivePanel>
);
}
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 6b962460b..8d1834f2a 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -50,3 +50,5 @@ export * from "./inferred-tests-view";
export * from "./tests-reaching-list";
export * from "./trend-view";
export * from "./fix-first";
+export { DEFAULT_AREA_RAIL_LABELS, type AreaRailLabels } from "./area-rail/labels";
+export type { AreaLinks } from "./area-rail/area-card";
diff --git a/packages/ui/src/health/map/area-layout.ts b/packages/ui/src/health/map/area-layout.ts
new file mode 100644
index 000000000..a2bdf6cef
--- /dev/null
+++ b/packages/ui/src/health/map/area-layout.ts
@@ -0,0 +1,181 @@
+/**
+ * Nested circle packing over the area hierarchy, and the files placed in it.
+ *
+ * Each unfolded area packs its drawn children, plus one slot for the files
+ * directly in it, by lines of code (area is lines), then scales the pack into
+ * its own disc. A disc's place depends only on its parent's children, so
+ * unfolding a deeper level never moves anything already drawn: it fills a
+ * disc that was solid a moment ago. That is what lets the hierarchy load
+ * lazily without the field jumping under the reader.
+ *
+ * Pure.
+ */
+
+import { packEnclose, packSiblings } from "d3-hierarchy";
+import { ROOT_AREA } from "../../lib/areas";
+import type { AreaIndex } from "./areas";
+import { directNloc, displayChildren, hostKey, hostOf, type FileHost } from "./area-paths";
+import { WORLD, packCluster } from "./layout";
+import type { CodeHealthMapFile, FileNode } from "./types";
+
+export interface Circle {
+ x: number;
+ y: number;
+ r: number;
+}
+
+export interface AreaGeometry {
+ /** Every drawn area's disc, in world units. */
+ circles: ReadonlyMap<string, Circle>;
+ /** Each unfolded area's own-files slot, when it has files of its own. */
+ slots: ReadonlyMap<string, Circle>;
+}
+
+/** The root disc: the world square, with a margin. */
+export const ROOT_CIRCLE: Circle = { x: WORLD / 2, y: WORLD / 2, r: (WORLD / 2) * 0.96 };
+/** How much of its parent a pack fills, so a ring reads around its children. */
+const FILL = 0.9;
+/** Air between sibling discs, as a share of the median sibling radius. */
+const SIBLING_GAP = 0.08;
+const SLOT = "\u0000slot";
+
+interface Item {
+ key: string;
+ r: number;
+}
+
+/** Pack `items` into `parent`, biggest first. Returns each item's circle. */
+function packInto(parent: Circle, items: Item[]): Map<string, Circle> {
+ const out = new Map<string, Circle>();
+ if (items.length === 0) return out;
+ if (items.length === 1) {
+ // A lone child is its parent's disc, so unfolding a chain never shrinks it.
+ out.set(items[0]!.key, { ...parent });
+ return out;
+ }
+ items.sort((a, b) => b.r - a.r || (a.key < b.key ? -1 : 1));
+ const gap = (items[Math.floor(items.length / 2)]!.r || 1) * SIBLING_GAP;
+ const placed = packSiblings(items.map((it) => ({ ...it, r: it.r + gap })));
+ const enc = packEnclose(placed) ?? { x: 0, y: 0, r: 1 };
+ const k = (parent.r * FILL) / Math.max(enc.r, 1e-9);
+ for (const p of placed) {
+ out.set(p.key, {
+ x: parent.x + (p.x - enc.x) * k,
+ y: parent.y + (p.y - enc.y) * k,
+ r: (p.r - gap) * k,
+ });
+ }
+ return out;
+}
+
+export function layoutAreas(index: AreaIndex): AreaGeometry {
+ const circles = new Map<string, Circle>();
+ const slots = new Map<string, Circle>();
+ if (!index.areas.has(ROOT_AREA)) return { circles, slots };
+ circles.set(ROOT_AREA, ROOT_CIRCLE);
+ const queue = [ROOT_AREA];
+ while (queue.length) {
+ const path = queue.shift()!;
+ const area = index.areas.get(path);
+ const circle = circles.get(path);
+ if (!area || !circle || !index.expanded.has(path)) continue;
+ const kids = displayChildren(index, path);
+ // An area with files and no sub-areas hosts them in its whole disc.
+ if (kids.length === 0) {
+ if (area.directFileCount > 0) slots.set(path, circle);
+ continue;
+ }
+ const items: Item[] = kids.map((k) => ({
+ key: k,
+ r: Math.sqrt(Math.max(index.areas.get(k)?.nloc ?? 1, 1)),
+ }));
+ if (area.directFileCount > 0) {
+ items.push({ key: SLOT, r: Math.sqrt(directNloc(index, area)) });
+ }
+ const packed = packInto(circle, items);
+ for (const [key, c] of packed) {
+ if (key === SLOT) slots.set(path, c);
+ else {
+ circles.set(key, c);
+ queue.push(key);
+ }
+ }
+ }
+ return { circles, slots };
+}
+
+/** One disc's worth of files: what they sit in and which nodes they are. */
+export interface Host {
+ key: string;
+ area: string;
+ direct: boolean;
+ circle: Circle;
+ /** Indices into the scene's node list. */
+ nodes: Int32Array;
+ /** Mean dot radius in world units, for the "is a dot still visible" test. */
+ meanR: number;
+}
+
+export interface PlacedFiles {
+ nodes: FileNode[];
+ hosts: Host[];
+ /** Host key -> host index. */
+ hostIndex: ReadonlyMap<string, number>;
+ /** Node index -> host index. */
+ hostOfNode: Int32Array;
+ /** Files with nowhere to sit (no rollup covers their directory). */
+ unplaced: number;
+}
+
+/** Largest dot, as a share of its host's radius, so two files are not plates. */
+const MAX_DOT_SHARE = 0.32;
+
+/**
+ * Place every file in the disc that hosts it, packed by folder and scaled to
+ * fit. Files of a host keep their relative sizes; across hosts the scale
+ * follows each host's disc, as nested packs do.
+ */
+export function layoutFiles(
+ files: readonly CodeHealthMapFile[],
+ index: AreaIndex,
+ geo: AreaGeometry,
+): PlacedFiles {
+ const groups = new Map<string, { host: FileHost; circle: Circle; files: CodeHealthMapFile[] }>();
+ let unplaced = 0;
+ for (const f of files) {
+ if (f.nloc <= 0) continue;
+ const host = hostOf(index, f.file_path);
+ const circle = host ? (host.direct ? geo.slots.get(host.area) : geo.circles.get(host.area)) : undefined;
+ if (!host || !circle) {
+ unplaced += 1;
+ continue;
+ }
+ const key = hostKey(host);
+ const g = groups.get(key);
+ if (g) g.files.push(f);
+ else groups.set(key, { host, circle, files: [f] });
+ }
+ const nodes: FileNode[] = [];
+ const owner: number[] = [];
+ const hosts: Host[] = [];
+ for (const [key, g] of [...groups.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
+ const { nodes: local, R } = packCluster(g.files);
+ const maxR = local.reduce((m, n) => Math.max(m, n.r), 0);
+ const k = Math.min((g.circle.r * 0.94) / Math.max(R, 1e-9), (g.circle.r * MAX_DOT_SHARE) / Math.max(maxR, 1e-9));
+ const start = nodes.length;
+ for (const n of local) {
+ nodes.push({ file: n.file, x: g.circle.x + n.x * k, y: g.circle.y + n.y * k, r: n.r * k });
+ owner.push(hosts.length);
+ }
+ hosts.push({
+ key,
+ area: g.host.area,
+ direct: g.host.direct,
+ circle: g.circle,
+ nodes: Int32Array.from({ length: nodes.length - start }, (_, i) => start + i),
+ meanR: (local.reduce((sum, n) => sum + n.r, 0) / Math.max(local.length, 1)) * k,
+ });
+ }
+ const hostIndex = new Map(hosts.map((h, i) => [h.key, i]));
+ return { nodes, hosts, hostIndex, hostOfNode: Int32Array.from(owner), unplaced };
+}
diff --git a/packages/ui/src/health/map/area-lenses.ts b/packages/ui/src/health/map/area-lenses.ts
new file mode 100644
index 000000000..21b18e064
--- /dev/null
+++ b/packages/ui/src/health/map/area-lenses.ts
@@ -0,0 +1,102 @@
+/**
+ * Lenses that read the area rollup rather than the file rows: who leads each
+ * area, and how much of it only one person knows.
+ *
+ * Both are area-only. Their files take the colour of the area they sit in, so
+ * zooming in keeps the reading instead of turning the field grey.
+ */
+
+import { SERIES, SERIES_TAIL } from "../../shared/series";
+import type { AreaIndex, MapArea } from "./areas";
+import { NEUTRAL_FILL, QUIET_FILL, type LegendRow, type MapLens } from "./lens";
+import { NODE_RAMP_STOP } from "../tokens";
+
+/** A share of files mapped onto the three problem stops; quiet below the first. */
+export function shareFill(share: number | null, steps: readonly [number, number, number]): string {
+ if (share == null) return NEUTRAL_FILL;
+ if (share >= steps[2]) return NODE_RAMP_STOP.alert;
+ if (share >= steps[1]) return NODE_RAMP_STOP.serious;
+ if (share >= steps[0]) return NODE_RAMP_STOP.warning;
+ return QUIET_FILL;
+}
+
+const pct = (share: number) => `${Math.round(share * 100)}%`;
+
+function share(count: number | undefined, a: MapArea): number | null {
+ return count == null || a.fileCount <= 0 ? null : count / a.fileCount;
+}
+
+/** Bus-factor-1 share at which an area reads as a knowledge risk. */
+const KNOWLEDGE_STEPS = [0.25, 0.5, 0.75] as const;
+
+export const KNOWLEDGE_LENS: MapLens = {
+ id: "knowledge",
+ label: "Knowledge risk",
+ caption: "colour = share of the area's files only one person has changed",
+ areaFill: (a) => shareFill(share(a.busFactor1Count, a), KNOWLEDGE_STEPS),
+ areaText: (a) => {
+ const s = share(a.busFactor1Count, a);
+ return s == null ? null : pct(s);
+ },
+ legend: [
+ { fill: NODE_RAMP_STOP.alert, label: "75% or more known by one person" },
+ { fill: NODE_RAMP_STOP.serious, label: "50 to 75%" },
+ { fill: NODE_RAMP_STOP.warning, label: "25 to 50%" },
+ { fill: QUIET_FILL, label: "Under 25%" },
+ { fill: NEUTRAL_FILL, label: "No history" },
+ ],
+ available: ({ areas }) => [...areas.areas.values()].some((a) => a.busFactor1Count != null),
+};
+
+/**
+ * Owner colours: the series palette past its first step, which is the accent
+ * orange and already means "selected" on this map. Everyone past the palette
+ * shares the tail grey and is named "Others" in the key.
+ */
+const OWNER_FILLS = SERIES.slice(1);
+
+/** Levels the owner ranking reads: the first response always carries them. */
+const RANK_DEPTH = 2;
+
+/**
+ * The people leading the most files, most first, ranked over the top levels
+ * only, so a colour does not move to someone else as deeper areas load.
+ */
+export function rankOwners(index: AreaIndex): { key: string; name: string }[] {
+ const weight = new Map<string, { name: string; files: number }>();
+ for (const a of index.areas.values()) {
+ const o = a.primaryOwner;
+ if (!o || (a.path ? a.path.split("/").length : 0) > RANK_DEPTH) continue;
+ const w = weight.get(o.key) ?? { name: o.name, files: 0 };
+ w.files += a.fileCount;
+ weight.set(o.key, w);
+ }
+ return [...weight.entries()]
+ .sort((x, y) => y[1].files - x[1].files || (x[0] < y[0] ? -1 : 1))
+ .map(([key, w]) => ({ key, name: w.name }));
+}
+
+/** The main-author lens over the areas known so far. */
+export function ownerLens(index: AreaIndex): MapLens {
+ const ranked = rankOwners(index);
+ const colour = new Map(ranked.slice(0, OWNER_FILLS.length).map((o, i) => [o.key, OWNER_FILLS[i]!]));
+ const legend: LegendRow[] = ranked
+ .slice(0, OWNER_FILLS.length)
+ .map((o) => ({ fill: colour.get(o.key)!, label: o.name }));
+ if (ranked.length > OWNER_FILLS.length) legend.push({ fill: SERIES_TAIL, label: "Others" });
+ legend.push({ fill: NEUTRAL_FILL, label: "No owner on record" });
+ return {
+ id: "owner",
+ label: "Main author",
+ caption: "colour = the person who is primary owner of the most files in the area",
+ areaFill: (a) => {
+ if (a.primaryOwner === undefined) return null;
+ if (a.primaryOwner === null) return NEUTRAL_FILL;
+ return colour.get(a.primaryOwner.key) ?? SERIES_TAIL;
+ },
+ areaText: (a) =>
+ a.primaryOwner ? `${a.primaryOwner.name.split(" ")[0]} ${pct(a.primaryOwner.share)}` : null,
+ legend,
+ available: ({ areas }) => [...areas.areas.values()].some((a) => a.primaryOwner !== undefined),
+ };
+}
diff --git a/packages/ui/src/health/map/area-paths.ts b/packages/ui/src/health/map/area-paths.ts
new file mode 100644
index 000000000..d1bb4fb59
--- /dev/null
+++ b/packages/ui/src/health/map/area-paths.ts
@@ -0,0 +1,113 @@
+/**
+ * Walking the area hierarchy the way the map shows it.
+ *
+ * A directory holding one sub-directory and no files of its own is not worth a
+ * click (`packages/core/src/repowise/core` is four of them in a row), so a
+ * chain like that is drawn as one disc named by the whole chain, and every
+ * walk here steps over it. The geometry is unchanged by the collapse: a lone
+ * child fills its parent, so the disc is the same disc either way.
+ *
+ * Pure.
+ */
+
+import { ROOT_AREA, dirOf } from "../../lib/areas";
+import type { AreaIndex, MapArea } from "./areas";
+
+const childrenOf = (index: AreaIndex, path: string): readonly string[] =>
+ index.children.get(path) ?? [];
+
+/** An expanded area with one child and no files of its own: drawn as its child. */
+export function isPassThrough(index: AreaIndex, path: string): boolean {
+ const a = index.areas.get(path);
+ return (
+ a !== undefined &&
+ index.expanded.has(path) &&
+ a.directFileCount === 0 &&
+ childrenOf(index, path).length === 1
+ );
+}
+
+/** Where a chain starting at `path` ends: the area actually drawn for it. */
+export function chainEnd(index: AreaIndex, path: string): string {
+ let cur = path;
+ while (cur !== ROOT_AREA && isPassThrough(index, cur)) cur = childrenOf(index, cur)[0]!;
+ return cur;
+}
+
+/** The discs drawn inside `path`, biggest first. */
+export function displayChildren(index: AreaIndex, path: string): string[] {
+ return childrenOf(index, path).map((c) => chainEnd(index, c));
+}
+
+/** The disc that contains `path`'s disc, or `null` for the root. */
+export function displayParent(index: AreaIndex, path: string): string | null {
+ if (path === ROOT_AREA) return null;
+ let p = index.areas.get(path)?.parent ?? dirOf(path);
+ while (p !== ROOT_AREA && isPassThrough(index, p)) p = index.areas.get(p)?.parent ?? dirOf(p);
+ return p;
+}
+
+/** A disc's name: its path below the disc containing it, so a chain names itself. */
+export function displayLabel(index: AreaIndex, path: string, rootLabel: string): string {
+ if (path === ROOT_AREA) return rootLabel;
+ const parent = displayParent(index, path);
+ return parent ? path.slice(parent.length + 1) : path;
+}
+
+/** The discs from the root down to `path`'s, for a breadcrumb. */
+export function areaTrail(index: AreaIndex, path: string): string[] {
+ const out: string[] = [];
+ let cur: string | null = chainEnd(index, path);
+ while (cur !== null) {
+ out.push(cur);
+ cur = displayParent(index, cur);
+ }
+ return out.reverse();
+}
+
+/** Whether `path` is `area` or inside it. */
+export function isWithin(path: string, area: string): boolean {
+ return area === ROOT_AREA || path === area || path.startsWith(`${area}/`);
+}
+
+/**
+ * Lines in an area's own files, outside its sub-directories. Floored at one
+ * line a file, so a directory of tiny files still gets a visible slot.
+ */
+export function directNloc(index: AreaIndex, a: MapArea): number {
+ const kids = childrenOf(index, a.path).reduce((s, c) => s + (index.areas.get(c)?.nloc ?? 0), 0);
+ return Math.max(a.nloc - kids, a.directFileCount);
+}
+
+/** Where one file is drawn: its area's own-files slot, or a whole area not yet unfolded. */
+export interface FileHost {
+ area: string;
+ /** True: the area's own-files slot. False: the area's whole disc. */
+ direct: boolean;
+}
+
+export function hostKey(h: FileHost): string {
+ return `${h.direct ? "d" : "w"}:${h.area}`;
+}
+
+/**
+ * The host a file lands in: the deepest drawn area holding it. A file in a
+ * directory the hierarchy has not unfolded yet lands in the deepest unfolded
+ * area's disc; a file in a directory with no rollup at all (nothing in it is
+ * scored) lands in its nearest area's own-files slot when there is one.
+ * `null` when it has nowhere to go.
+ */
+export function hostOf(index: AreaIndex, filePath: string): FileHost | null {
+ const dir = dirOf(filePath);
+ let cur = ROOT_AREA;
+ if (!index.areas.has(cur)) return null;
+ for (;;) {
+ if (dir === cur) break;
+ if (!index.expanded.has(cur)) return { area: cur, direct: false };
+ const next = displayChildren(index, cur).find((c) => isWithin(dir, c));
+ if (next === undefined) break;
+ cur = next;
+ }
+ if (!index.expanded.has(cur)) return { area: cur, direct: false };
+ return index.areas.get(cur)!.directFileCount > 0 ? { area: cur, direct: true } : null;
+}
diff --git a/packages/ui/src/health/map/area-rank.ts b/packages/ui/src/health/map/area-rank.ts
new file mode 100644
index 000000000..9f00e82b7
--- /dev/null
+++ b/packages/ui/src/health/map/area-rank.ts
@@ -0,0 +1,52 @@
+/**
+ * Which areas the rail points at: the ones needing attention, and the one
+ * that improved most. Pure, over the areas the index knows.
+ *
+ * Only drawn discs count (a pass-through directory is its child), and a pick
+ * never nests inside another, so three suggestions are three places.
+ */
+
+import { ROOT_AREA } from "../../lib/areas";
+import type { AreaIndex, MapArea } from "./areas";
+import { chainEnd, isWithin } from "./area-paths";
+
+/** An area this small is a detail, not a place to send someone. */
+export const MIN_RANKED_FILES = 5;
+
+/** The drawn areas strictly inside `within`. */
+function drawnInside(index: AreaIndex, within: string): MapArea[] {
+ const out = new Map<string, MapArea>();
+ for (const a of index.areas.values()) {
+ if (a.path === within || !isWithin(a.path, within)) continue;
+ const end = chainEnd(index, a.path);
+ const drawn = index.areas.get(end);
+ if (drawn && end !== within) out.set(end, drawn);
+ }
+ return [...out.values()];
+}
+
+function pickDisjoint(sorted: MapArea[], n: number): MapArea[] {
+ const picked: MapArea[] = [];
+ for (const a of sorted) {
+ if (picked.length >= n) break;
+ if (picked.some((p) => isWithin(a.path, p.path) || isWithin(p.path, a.path))) continue;
+ picked.push(a);
+ }
+ return picked;
+}
+
+/** The lowest-scoring places inside `within`, worst first, none nested in another. */
+export function areasNeedingAttention(index: AreaIndex, within: string = ROOT_AREA, n = 3): MapArea[] {
+ const ranked = drawnInside(index, within)
+ .filter((a) => a.health != null && a.fileCount >= MIN_RANKED_FILES)
+ .sort((a, b) => a.health! - b.health! || b.nloc - a.nloc || (a.path < b.path ? -1 : 1));
+ return pickDisjoint(ranked, n);
+}
+
+/** The area inside `within` whose score rose most over the delta window, if any rose. */
+export function mostImproved(index: AreaIndex, within: string = ROOT_AREA): MapArea | null {
+ const ranked = drawnInside(index, within)
+ .filter((a) => (a.delta30d ?? 0) > 0 && a.fileCount >= MIN_RANKED_FILES)
+ .sort((a, b) => b.delta30d! - a.delta30d! || (a.path < b.path ? -1 : 1));
+ return ranked[0] ?? null;
+}
diff --git a/packages/ui/src/health/map/area-view.ts b/packages/ui/src/health/map/area-view.ts
new file mode 100644
index 000000000..ddbd419bf
--- /dev/null
+++ b/packages/ui/src/health/map/area-view.ts
@@ -0,0 +1,174 @@
+/**
+ * Semantic zoom, decided once per frame: which areas are solid discs, which
+ * are faint containers around what is inside, which hosts paint their file
+ * dots, and what the field should load next.
+ *
+ * Files are texture at every zoom: a folder's files load and draw as soon as
+ * a dot would be at least a device pixel across ({@link MIN_DOT_DEVICE_R}),
+ * so the root already shows every file coloured by the lens. Below that, or
+ * before the files arrive, a folder is one solid disc in its own colour. A
+ * folder also opens to show its sub-folders once it clears {@link OPEN_PX}.
+ *
+ * Pure: a camera, a box and the laid-out field in, a plain view out.
+ */
+
+import { ROOT_AREA } from "../../lib/areas";
+import type { AreaIndex } from "./areas";
+import type { AreaGeometry, Circle, Host } from "./area-layout";
+import { displayChildren } from "./area-paths";
+import type { Cam, View } from "./paint";
+
+/** An area this small on screen draws no disc of its own; its files may still show. */
+export const MIN_AREA_PX = 3;
+/** Screen radius at which an area opens to show its sub-areas without its files. */
+export const OPEN_PX = 90;
+/**
+ * Smallest dot worth drawing, as a radius in device pixels: half a device
+ * pixel is a dot one device pixel across. Below it a folder stays solid.
+ */
+export const MIN_DOT_DEVICE_R = 0.5;
+/** Share of a packed disc its dots cover, for estimating a dot's size before layout. */
+const PACK_FILL = 0.5;
+/** Largest area whose files are fetched in one request (the server's cap). */
+export const MAX_AREA_FILES = 8000;
+/** Pan slack, so discs just off screen are ready when they slide in. */
+const MARGIN_PX = 48;
+
+export type DiscState = "open" | "closed" | "slot";
+
+export interface DiscView {
+ path: string;
+ /** Screen centre and radius, in CSS px. */
+ x: number;
+ y: number;
+ r: number;
+ state: DiscState;
+}
+
+export interface FieldView {
+ /** Outer discs first, so a child paints over its parent. */
+ discs: DiscView[];
+ /** Per host: 1 when its file dots are drawn this frame. */
+ drawnHosts: Uint8Array;
+ /** Areas on screen and big enough to open whose children are not known yet. */
+ wantChildren: string[];
+ /** The shallowest areas dense enough on screen to show files not loaded yet. */
+ wantFiles: string[];
+}
+
+export interface ViewInput {
+ index: AreaIndex;
+ geo: AreaGeometry;
+ hosts: readonly Host[];
+ /** Host key -> index into `hosts`. */
+ hostIndex: ReadonlyMap<string, number>;
+ /** Areas whose complete file list is loaded or on its way (covers descendants). */
+ filesCovered: (path: string) => boolean;
+ cam: Cam;
+ view: View;
+}
+
+function toScreen(c: Circle, cam: Cam, view: View): { x: number; y: number; r: number } {
+ return {
+ x: view.w / 2 + (c.x - cam.cx) * cam.scale,
+ y: view.h / 2 + (c.y - cam.cy) * cam.scale,
+ r: c.r * cam.scale,
+ };
+}
+
+const offscreen = (s: { x: number; y: number; r: number }, view: View) =>
+ s.x + s.r < -MARGIN_PX ||
+ s.y + s.r < -MARGIN_PX ||
+ s.x - s.r > view.w + MARGIN_PX ||
+ s.y - s.r > view.h + MARGIN_PX;
+
+/** Whether dots of this world radius are at least a device pixel across. */
+const visibleDot = (worldR: number, cam: Cam, view: View) => worldR * cam.scale * view.dpr >= MIN_DOT_DEVICE_R;
+
+/** A disc of screen radius `r` holding `files` dots: would they be visible once loaded? */
+const dotsWouldShow = (r: number, files: number, view: View) =>
+ files > 0 && r * Math.sqrt(PACK_FILL / files) * view.dpr >= MIN_DOT_DEVICE_R;
+
+type Screen = { x: number; y: number; r: number };
+
+/** One frame's walk: the input, and the view it fills in. */
+interface Walk {
+ input: ViewInput;
+ out: FieldView;
+}
+
+/** Draw a host's dots when they are dense enough; true when drawn. */
+function tryHost(w: Walk, key: string): boolean {
+ const i = w.input.hostIndex.get(key);
+ if (i === undefined) return false;
+ const h = w.input.hosts[i]!;
+ if (!visibleDot(h.meanR, w.input.cam, w.input.view)) return false;
+ w.out.drawnHosts[i] = 1;
+ return true;
+}
+
+/**
+ * Record what this area needs loaded. Returns whether its files are covered
+ * for the areas below it, so only the shallowest dense area is fetched.
+ */
+function noteWants(w: Walk, path: string, s: Screen, covered: boolean): boolean {
+ const { index, view } = w.input;
+ const area = index.areas.get(path)!;
+ const big = s.r >= OPEN_PX;
+ if (big && area.hasChildren && !index.expanded.has(path)) w.out.wantChildren.push(path);
+ if (covered || w.input.filesCovered(path)) return true;
+ // Files load as soon as their dots would show, so the field has texture
+ // from the root down; the shallowest such area is the one fetched.
+ if (area.fileCount <= MAX_AREA_FILES && dotsWouldShow(s.r, area.fileCount, view)) {
+ w.out.wantFiles.push(path);
+ return true;
+ }
+ return false;
+}
+
+/** An area's own-files slot beside its sub-areas: dots when dense, else a quiet disc. */
+function visitSlot(w: Walk, path: string): void {
+ const slot = w.input.geo.slots.get(path);
+ if (!slot || tryHost(w, `d:${path}`)) return;
+ const ss = toScreen(slot, w.input.cam, w.input.view);
+ if (ss.r >= MIN_AREA_PX && !offscreen(ss, w.input.view)) w.out.discs.push({ path, ...ss, state: "slot" });
+}
+
+function visit(w: Walk, path: string, covered: boolean): void {
+ const { index, geo, cam, view } = w.input;
+ const circle = geo.circles.get(path);
+ if (!circle || !index.areas.has(path)) return;
+ const s = toScreen(circle, cam, view);
+ if (offscreen(s, view)) return;
+
+ const below = noteWants(w, path, s, covered);
+ const kids = index.expanded.has(path) ? displayChildren(index, path) : [];
+ const leafFiles = kids.length === 0 && (tryHost(w, `d:${path}`) || tryHost(w, `w:${path}`));
+ // A folder whose files are on the canvas is a faint container around them.
+ const textured = kids.length > 0 && below && dotsWouldShow(s.r, index.areas.get(path)!.fileCount, view);
+ const open = path === ROOT_AREA || (s.r >= OPEN_PX && kids.length > 0) || leafFiles || textured;
+ if (s.r >= MIN_AREA_PX) w.out.discs.push({ path, ...s, state: open ? "open" : "closed" });
+ if (!open || kids.length === 0) return;
+ for (const k of kids) visit(w, k, below);
+ visitSlot(w, path);
+}
+
+export function computeView(input: ViewInput): FieldView {
+ const out: FieldView = {
+ discs: [],
+ drawnHosts: new Uint8Array(input.hosts.length),
+ wantChildren: [],
+ wantFiles: [],
+ };
+ visit({ input, out }, ROOT_AREA, false);
+ return out;
+}
+
+/** The innermost disc under a screen point, or null. */
+export function discAt(view: FieldView, x: number, y: number): DiscView | null {
+ for (let i = view.discs.length - 1; i >= 0; i--) {
+ const d = view.discs[i]!;
+ if (Math.hypot(x - d.x, y - d.y) <= d.r) return d;
+ }
+ return null;
+}
diff --git a/packages/ui/src/health/map/areas.ts b/packages/ui/src/health/map/areas.ts
new file mode 100644
index 000000000..f8da9ac20
--- /dev/null
+++ b/packages/ui/src/health/map/areas.ts
@@ -0,0 +1,185 @@
+/**
+ * The area hierarchy the map draws: every directory, keyed by path, with the
+ * rollup the map colours and labels it by. `""` is the repository root.
+ *
+ * Two sources fill it. A host with the areas API merges `/areas/tree`
+ * responses in as the reader zooms ({@link mergeAreaTree}); the rollups are
+ * the server's, complete over the repository. A host with only a flat file
+ * feed derives the same hierarchy from those rows ({@link deriveAreaIndex}),
+ * so every host gets the same nested map from one code path.
+ *
+ * Pure: no React, no canvas, no fetch.
+ */
+
+import { bandForScore, type HealthBand } from "@repowise-dev/types/health";
+import type { AreaNode, AreaTree } from "@repowise-dev/types/areas";
+import { ROOT_AREA, dirOf } from "../../lib/areas";
+import type { CodeHealthMapFile } from "./types";
+
+
+/** The rollup of one directory, in the fields the map reads. */
+export interface MapArea {
+ path: string;
+ /** Last path segment; `""` for the root. */
+ name: string;
+ parent: string | null;
+ fileCount: number;
+ /** Files directly in this directory. */
+ directFileCount: number;
+ nloc: number;
+ hasChildren: boolean;
+ /** NLOC-weighted score, `null` when no file in it is scored. */
+ health: number | null;
+ band: HealthBand | null;
+ /** `undefined` when the source does not carry the signal at all. */
+ hotspotCount?: number;
+ busFactor1Count?: number;
+ primaryOwner?: { key: string; name: string; share: number } | null;
+ coveragePct?: number | null;
+ delta30d?: number | null;
+}
+
+export interface AreaIndex {
+ areas: ReadonlyMap<string, MapArea>;
+ /** Child paths per area, biggest first. Complete only for `expanded` areas. */
+ children: ReadonlyMap<string, readonly string[]>;
+ /** Areas whose child list is complete. */
+ expanded: ReadonlySet<string>;
+}
+
+export const EMPTY_AREA_INDEX: AreaIndex = {
+ areas: new Map(),
+ children: new Map(),
+ expanded: new Set(),
+};
+
+export function areaFromNode(n: AreaNode): MapArea {
+ return {
+ path: n.path,
+ name: n.name,
+ parent: n.parent,
+ fileCount: n.file_count,
+ directFileCount: n.direct_file_count,
+ nloc: n.nloc,
+ hasChildren: n.has_children,
+ health: n.health,
+ band: n.band,
+ hotspotCount: n.hotspot_count,
+ busFactor1Count: n.bus_factor_1_count,
+ primaryOwner: n.primary_owner
+ ? { key: n.primary_owner.key, name: n.primary_owner.name, share: n.primary_owner.share }
+ : null,
+ coveragePct: n.line_coverage_pct,
+ delta30d: n.health_delta_30d,
+ };
+}
+
+const bySize = (areas: ReadonlyMap<string, MapArea>) => (a: string, b: string) =>
+ (areas.get(b)?.nloc ?? 0) - (areas.get(a)?.nloc ?? 0) || (a < b ? -1 : 1);
+
+function indexChildren(areas: Map<string, MapArea>): Map<string, string[]> {
+ const children = new Map<string, string[]>();
+ for (const a of areas.values()) {
+ if (a.parent === null) continue;
+ const list = children.get(a.parent);
+ if (list) list.push(a.path);
+ else children.set(a.parent, [a.path]);
+ }
+ const order = bySize(areas);
+ for (const list of children.values()) list.sort(order);
+ return children;
+}
+
+/**
+ * Fold one `/areas/tree` response in. Every area above the response's last
+ * level arrives with all of its children, so those become expanded; a leaf
+ * the server says has no children is expanded trivially.
+ */
+export function mergeAreaTree(index: AreaIndex, tree: AreaTree): AreaIndex {
+ const areas = new Map(index.areas);
+ const expanded = new Set(index.expanded);
+ const deepest = tree.root.depth + tree.depth;
+ for (const n of [tree.root, ...tree.nodes]) {
+ areas.set(n.path, areaFromNode(n));
+ if (n.depth < deepest || !n.has_children) expanded.add(n.path);
+ }
+ return { areas, children: indexChildren(areas), expanded };
+}
+
+function lastSegment(path: string): string {
+ return path.slice(path.lastIndexOf("/") + 1);
+}
+
+/** Every ancestor directory of `dir`, root first, ending at `dir`. */
+function ancestry(dir: string): string[] {
+ const out = [ROOT_AREA];
+ if (!dir) return out;
+ const parts = dir.split("/");
+ for (let i = 1; i <= parts.length; i++) out.push(parts.slice(0, i).join("/"));
+ return out;
+}
+
+interface Acc {
+ files: number;
+ direct: number;
+ nloc: number;
+ scoredNloc: number;
+ weighted: number;
+ scored: number;
+}
+
+/**
+ * The hierarchy behind a flat file feed, for a host without the areas API.
+ * The same fold the server uses: every file counts, an empty one included,
+ * and health is the mean of the scored files weighted by NLOC floored at 1.
+ * Every directory is expanded because every file is here.
+ */
+export function deriveAreaIndex(files: readonly CodeHealthMapFile[]): AreaIndex {
+ const acc = new Map<string, Acc>();
+ const touch = (path: string) => {
+ let a = acc.get(path);
+ if (!a) {
+ a = { files: 0, direct: 0, nloc: 0, scoredNloc: 0, weighted: 0, scored: 0 };
+ acc.set(path, a);
+ }
+ return a;
+ };
+ for (const f of files) {
+ const nloc = Math.max(f.nloc, 0);
+ const weight = Math.max(nloc, 1);
+ const dir = dirOf(f.file_path);
+ const chain = ancestry(dir);
+ for (const p of chain) {
+ const a = touch(p);
+ a.files += 1;
+ a.nloc += nloc;
+ if (f.score != null) {
+ a.scored += 1;
+ a.scoredNloc += weight;
+ a.weighted += f.score * weight;
+ }
+ }
+ touch(dir).direct += 1;
+ }
+ const areas = new Map<string, MapArea>();
+ for (const [path, a] of acc) {
+ const health = a.scoredNloc > 0 ? Math.round((a.weighted / a.scoredNloc) * 100) / 100 : null;
+ areas.set(path, {
+ path,
+ name: path ? lastSegment(path) : "",
+ parent: path ? dirOf(path) : null,
+ fileCount: a.files,
+ directFileCount: a.direct,
+ nloc: a.nloc,
+ hasChildren: false,
+ health,
+ band: health == null ? null : bandForScore(health),
+ });
+ }
+ const children = indexChildren(areas);
+ for (const [path, list] of children) {
+ const a = areas.get(path);
+ if (a && list.length) areas.set(path, { ...a, hasChildren: true });
+ }
+ return { areas, children, expanded: new Set(areas.keys()) };
+}
diff --git a/packages/ui/src/health/map/canvas-labels.ts b/packages/ui/src/health/map/canvas-labels.ts
new file mode 100644
index 000000000..89baa2baa
--- /dev/null
+++ b/packages/ui/src/health/map/canvas-labels.ts
@@ -0,0 +1,48 @@
+/**
+ * The words the canvas itself prints (folder chips, the area hover card), so
+ * a host can translate them. English by default; the rail's labels extend
+ * this set, so one translated object serves both.
+ */
+export interface MapCanvasLabels {
+ /** A folder's chip under the hotspot lens: "12 hot · 6.4". */
+ hotspotChip: (count: number, health: string | null) => string;
+ /** File count on the hover card. */
+ fileCount: (count: number) => string;
+ openHint: string;
+ /** The own-files slot beside a folder's sub-folders. */
+ directFiles: (folder: string) => string;
+ notLoaded: string;
+ analysedFiles: (analysed: number, loaded: number) => string;
+ flaggedFiles: (flagged: number, analysed: number) => string;
+ /** A held-out origin's name, plural: "test files", "generated files". */
+ originName: (origin: string) => string;
+ /** The footer toggle that brings a held group back: "Show test files (1,755)". */
+ showHeld: (name: string, count: number) => string;
+ hideHeld: (name: string) => string;
+}
+
+/** Names for the stored code_origin values the map holds out. */
+const ORIGIN_NAMES: Record<string, string> = {
+ test: "test files",
+ docs_example: "docs examples",
+ build: "build files",
+ vendored: "vendored files",
+ generated: "generated files",
+ tooling: "tooling files",
+ production: "production files",
+};
+
+const n = (v: number) => v.toLocaleString();
+
+export const DEFAULT_MAP_CANVAS_LABELS: MapCanvasLabels = {
+ hotspotChip: (count, health) => (health == null ? `${n(count)} hot` : `${n(count)} hot · ${health}`),
+ fileCount: (count) => `${n(count)} ${count === 1 ? "file" : "files"}`,
+ openHint: "click to open",
+ directFiles: (folder) => `Files directly in ${folder}`,
+ notLoaded: "Files not loaded yet · zoom in to read them",
+ analysedFiles: (analysed, loaded) => `${n(analysed)} of ${n(loaded)} files analysed`,
+ flaggedFiles: (flagged, analysed) => `${n(flagged)} of ${n(analysed)} analysed files flagged`,
+ originName: (origin) => ORIGIN_NAMES[origin] ?? origin.replace(/_/g, " "),
+ showHeld: (name, count) => `Show ${name} (${n(count)})`,
+ hideHeld: (name) => `Hide ${name}`,
+};
diff --git a/packages/ui/src/health/map/colour.ts b/packages/ui/src/health/map/colour.ts
new file mode 100644
index 000000000..5883bc22d
--- /dev/null
+++ b/packages/ui/src/health/map/colour.ts
@@ -0,0 +1,75 @@
+/**
+ * Colours for the canvas: CSS strings (token `var()`s and `color-mix()`es)
+ * resolved to RGB once per theme through the browser's own computed style, so
+ * the key and the field read one source.
+ */
+
+export type Rgb = readonly [number, number, number];
+
+const FALLBACK: Rgb = [128, 128, 128];
+
+/** Parse a computed colour: `rgb()`, `rgba()`, `color(srgb …)` or hex. */
+export function parseCssColour(value: string): Rgb | null {
+ const v = value.trim();
+ let m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(v);
+ if (m) return [Number(m[1]), Number(m[2]), Number(m[3])];
+ m = /^color\(srgb\s+([\d.e-]+)\s+([\d.e-]+)\s+([\d.e-]+)/i.exec(v);
+ if (m) return [Number(m[1]) * 255, Number(m[2]) * 255, Number(m[3]) * 255];
+ m = /^#([0-9a-f]{6})$/i.exec(v);
+ if (m) {
+ const n = parseInt(m[1]!, 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+ }
+ return null;
+}
+
+/**
+ * A cached CSS-colour-to-RGB resolver bound to one element, so `var()` reads
+ * the theme in force there. Build a new one when the theme flips.
+ */
+export function createColourResolver(host: HTMLElement | null): (css: string) => Rgb {
+ const cache = new Map<string, Rgb>();
+ let probe: HTMLSpanElement | null = null;
+ return (css) => {
+ const hit = cache.get(css);
+ if (hit) return hit;
+ let rgb: Rgb | null = parseCssColour(css);
+ if (!rgb && host && typeof getComputedStyle !== "undefined") {
+ if (!probe) {
+ probe = document.createElement("span");
+ probe.style.display = "none";
+ host.appendChild(probe);
+ }
+ probe.style.color = "";
+ probe.style.color = css;
+ rgb = parseCssColour(getComputedStyle(probe).color);
+ }
+ const out = rgb ?? FALLBACK;
+ cache.set(css, out);
+ return out;
+ };
+}
+
+export function rgba([r, g, b]: Rgb, a = 1): string {
+ return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;
+}
+
+export function mixRgb(a: Rgb, b: Rgb, t: number): Rgb {
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
+}
+
+/** Theme colours the field paints with besides the node fills. */
+export interface Palette {
+ ink: Rgb;
+ ring: Rgb;
+ accent: Rgb;
+}
+
+export function resolvePalette(resolve: (css: string) => Rgb): Palette {
+ return {
+ ink: resolve("var(--color-text-primary)"),
+ ring: resolve("var(--color-border-default)"),
+ accent: resolve("var(--color-accent-primary)"),
+ };
+}
+
diff --git a/packages/ui/src/health/map/controls.tsx b/packages/ui/src/health/map/controls.tsx
index b490cc942..233586f9a 100644
--- a/packages/ui/src/health/map/controls.tsx
+++ b/packages/ui/src/health/map/controls.tsx
@@ -1,13 +1,12 @@
"use client";
/**
- * The few controls that sit on the canvas: zoom and fit, the way out of a
- * focused galaxy, and, for a host with nowhere else to put them, the lens
- * switcher and key.
+ * The few controls that sit on the canvas: zoom and fit, and, for a host with
+ * nowhere else to put them, the lens switcher and key.
*/
import { MapLegendRows, MapLensSwitcher } from "./legend";
-import type { OverlaySpec } from "./lens";
+import type { MapLens } from "./lens";
import type { CodeHealthOverlay } from "./types";
const GLASS =
@@ -25,7 +24,7 @@ export function ZoomControls({
const buttons = [
{ label: "Zoom in", text: "+", act: onZoomIn },
{ label: "Zoom out", text: "−", act: onZoomOut },
- { label: "Fit the whole field", text: "Fit", act: onFit },
+ { label: "Frame the selected area", text: "Fit", act: onFit },
];
return (
<div role="group" aria-label="Zoom" className={`flex overflow-hidden text-xs ${GLASS}`}>
@@ -47,24 +46,6 @@ export function ZoomControls({
);
}
-/** The focused galaxy's name and the way back to the whole field. */
-export function FocusCrumb({ label, onLeave }: { label: string; onLeave: () => void }) {
- return (
- <div className={`flex items-center gap-1.5 px-2.5 py-1.5 text-xs ${GLASS}`}>
- <span className="max-w-[180px] truncate font-medium text-[var(--color-text-primary)]">
- {label}
- </span>
- <button
- type="button"
- onClick={onLeave}
- className="ml-1 rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- >
- ← Overview
- </button>
- </div>
- );
-}
-
/** The lens switcher and key floated over the canvas (`chrome="canvas"`). */
export function CanvasChrome({
overlay,
@@ -74,7 +55,7 @@ export function CanvasChrome({
onOverlayChange,
}: {
overlay: CodeHealthOverlay;
- spec: OverlaySpec;
+ spec: MapLens;
lenses: CodeHealthOverlay[];
loading: boolean;
onOverlayChange?: ((overlay: CodeHealthOverlay) => void) | undefined;
@@ -101,7 +82,7 @@ export function CanvasChrome({
<div className="mt-2 border-t border-[var(--color-border-default)] pt-1.5 text-[var(--color-text-tertiary)]">
{spec.caption}
<br />
- click a galaxy to zoom
+ click an area to open it
</div>
</div>
</>
diff --git a/packages/ui/src/health/map/field-notes.tsx b/packages/ui/src/health/map/field-notes.tsx
new file mode 100644
index 000000000..648059582
--- /dev/null
+++ b/packages/ui/src/health/map/field-notes.tsx
@@ -0,0 +1,197 @@
+"use client";
+
+/**
+ * What sits over the field besides the marks: the scope sentence in the
+ * corner, the notice for a field nothing scored, and the hover card for the
+ * file or area under the pointer.
+ */
+
+import { useMemo } from "react";
+import type { AreaIndex } from "./areas";
+import { displayLabel, displayParent, areaTrail } from "./area-paths";
+import { truncatePath } from "../../lib/format";
+import type { AreaGeometry } from "./area-layout";
+import { HEALTH_UNSUPPORTED_NOTICE, noFileScored, type MapLens } from "./lens";
+import type { AreaLabel } from "./labels";
+import { AreaHoverCard, HoverCard } from "./overlay";
+import { LoadedNote, MapScopeNote, type HeldGroups } from "./scope-note";
+import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./types";
+import type { Hover } from "./use-map-pointer";
+import type { AreaAnalysed } from "./fills";
+import type { MapCanvasLabels } from "./canvas-labels";
+import { ROOT_AREA } from "../../lib/areas";
+
+/** A sub-folder at least this share of its parent's radius visually is the parent. */
+const DOMINANT_SHARE = 0.75;
+/** Longest merged name, before the shared path shortening keeps its tail. */
+const MERGED_NAME_CHARS = 32;
+
+/**
+ * One label per visual disc. When one sub-folder fills its parent, the
+ * parent's label is dropped while open and the sub-folder's label carries the
+ * joined name ("core/src/repowise/core"), shortened from the front if long.
+ * Decided from the layout, so no frame pays for it.
+ */
+export function mergeDominantLabels(
+ index: AreaIndex,
+ geo: AreaGeometry,
+ areaText: ReadonlyMap<string, string | null>,
+ rootLabel: string,
+): AreaLabel[] {
+ const dominated = new Map<string, string>();
+ for (const [path, c] of geo.circles) {
+ const parent = displayParent(index, path);
+ const pc = parent ? geo.circles.get(parent) : undefined;
+ if (parent && pc && c.r >= pc.r * DOMINANT_SHARE) dominated.set(parent, path);
+ }
+ const nameOf = (path: string): string => {
+ const own = displayLabel(index, path, rootLabel);
+ const parent = displayParent(index, path);
+ return parent && parent !== ROOT_AREA && dominated.get(parent) === path
+ ? truncatePath(`${nameOf(parent)}/${own}`, MERGED_NAME_CHARS)
+ : own;
+ };
+ return [...geo.circles.keys()]
+ .filter((p) => p !== ROOT_AREA)
+ .map((path) => ({
+ path,
+ name: nameOf(path),
+ text: areaText.get(path) ?? null,
+ dominated: dominated.has(path),
+ }));
+}
+
+/** The area names the canvas places and the breadcrumb above it. */
+export function useAreaChrome(
+ index: AreaIndex,
+ geo: AreaGeometry,
+ areaText: ReadonlyMap<string, string | null>,
+ selected: string,
+ rootLabel: string,
+ onSelectArea: (path: string) => void,
+) {
+ const labels = useMemo<AreaLabel[]>(() => mergeDominantLabels(index, geo, areaText, rootLabel), [
+ geo,
+ index,
+ areaText,
+ rootLabel,
+ ]);
+ const trail = useMemo(
+ () =>
+ areaTrail(index, selected).map((path, i, all) => ({
+ label: displayLabel(index, path, rootLabel),
+ ...(i < all.length - 1 ? { onSelect: () => onSelectArea(path) } : {}),
+ })),
+ [index, selected, rootLabel, onSelectArea],
+ );
+ return { labels, trail };
+}
+
+export interface FlatFieldNotes {
+ files: CodeHealthMapFile[];
+ scope: MapScope | undefined;
+ drawMoreStep: number;
+ pending: boolean;
+ onDrawMore?: (() => void) | undefined;
+ onIncludeHeldChange?: ((include: boolean) => void) | undefined;
+ onFindUndrawn?: ((query: string) => void) | undefined;
+}
+
+/** The scope sentence for a flat feed or a lazily loaded one, and the unscored notice. */
+export function FieldNotes({
+ flat,
+ loaded,
+ matches,
+ query,
+ held,
+ labels,
+}: {
+ flat: FlatFieldNotes | null;
+ loaded: { loaded: number; total: number } | null;
+ matches: number;
+ query: string;
+ held?: HeldGroups | undefined;
+ labels: MapCanvasLabels;
+}) {
+ return (
+ <>
+ {flat?.scope ? (
+ <MapScopeNote
+ scope={flat.scope}
+ matches={matches}
+ query={query}
+ drawMoreStep={flat.drawMoreStep}
+ pending={flat.pending}
+ onDrawMore={flat.onDrawMore}
+ onIncludeHeldChange={flat.onIncludeHeldChange}
+ onFindUndrawn={flat.onFindUndrawn}
+ />
+ ) : loaded ? (
+ <LoadedNote
+ loaded={loaded.loaded}
+ total={loaded.total}
+ matches={query ? matches : null}
+ held={held}
+ labels={labels}
+ />
+ ) : null}
+ {flat && noFileScored(flat.files) ? (
+ <div
+ role="status"
+ data-testid="map-unanalysed"
+ className="pointer-events-none absolute bottom-3 left-3 max-w-[64%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-xs text-[var(--color-text-secondary)] shadow-sm backdrop-blur-sm sm:max-w-[44%]"
+ >
+ {HEALTH_UNSUPPORTED_NOTICE}
+ </div>
+ ) : null}
+ </>
+ );
+}
+
+/** The card for whatever the pointer is over, in the active lens's terms. */
+export function FieldHover({
+ hover,
+ analysed,
+ areaText,
+ labels,
+ index,
+ lens,
+ overlay,
+ rootLabel,
+ width,
+ height,
+}: {
+ hover: Hover | null;
+ /** How many of each area's loaded files the active lens analysed. */
+ analysed: ReadonlyMap<string, AreaAnalysed>;
+ areaText: ReadonlyMap<string, string | null>;
+ labels: MapCanvasLabels;
+ index: AreaIndex;
+ lens: MapLens;
+ overlay: CodeHealthOverlay;
+ rootLabel: string;
+ width: number;
+ height: number;
+}) {
+ if (hover?.kind === "file") {
+ return <HoverCard file={hover.file} overlay={overlay} x={hover.x} y={hover.y} width={width} height={height} />;
+ }
+ const area = hover?.kind === "area" ? index.areas.get(hover.path) : undefined;
+ if (!hover || hover.kind !== "area" || !area) return null;
+ return (
+ <AreaHoverCard
+ area={area}
+ name={displayLabel(index, hover.path, rootLabel)}
+ slot={hover.slot}
+ figure={areaText.get(hover.path) ?? null}
+ lensLabel={lens.label}
+ analysed={analysed.get(hover.path) ?? null}
+ labels={labels}
+ lensCoversFiles={Boolean(lens.analysed) && (lens.areaFill?.(area) ?? null) === null}
+ x={hover.x}
+ y={hover.y}
+ width={width}
+ height={height}
+ />
+ );
+}
diff --git a/packages/ui/src/health/map/fills.ts b/packages/ui/src/health/map/fills.ts
new file mode 100644
index 000000000..900040a56
--- /dev/null
+++ b/packages/ui/src/health/map/fills.ts
@@ -0,0 +1,90 @@
+/**
+ * Every area's and every file's colour under one lens, as pure functions.
+ *
+ * This is the one place "not analysed" is decided, for every lens. A file
+ * the lens has no signal for is grey, whatever its other fields say. An area
+ * takes its rollup's reading when the lens has one, else the fold of its
+ * loaded files the lens analysed, else grey: a folder whose files are not
+ * loaded, or none of which were analysed, is unknown, not good and not bad.
+ */
+
+import { ROOT_AREA, dirOf } from "../../lib/areas";
+import type { AreaIndex } from "./areas";
+import type { FieldScene } from "./paint";
+import { NEUTRAL_FILL, type MapLens } from "./lens";
+import type { CodeHealthMapFile } from "./types";
+
+/** How many of an area's loaded files the lens analysed. */
+export interface AreaAnalysed {
+ analysed: number;
+ loaded: number;
+ /** Analysed files carrying something to fix, for a lens that flags. */
+ flagged?: number;
+}
+
+export interface AreaFills {
+ fill: Map<string, string>;
+ /** The lens's figure per area, from its rollup and its loaded, analysed files. */
+ text: Map<string, string | null>;
+ /** Per area with loaded files, for a lens that tells files apart; else empty. */
+ analysed: Map<string, AreaAnalysed>;
+}
+
+const isAnalysed = (lens: MapLens, f: CodeHealthMapFile) => !lens.analysed || lens.analysed(f);
+
+/** Every ancestor area of a file the index knows, deepest first. */
+function areasOf(index: AreaIndex, path: string): string[] {
+ const out: string[] = [];
+ let dir = dirOf(path);
+ for (;;) {
+ if (index.areas.has(dir)) out.push(dir);
+ if (dir === ROOT_AREA) return out;
+ dir = dirOf(dir);
+ }
+}
+
+/** Loaded files under every area, split into the analysed ones and a count of all. */
+function foldInputs(index: AreaIndex, lens: MapLens, files: readonly CodeHealthMapFile[]) {
+ const analysedFiles = new Map<string, CodeHealthMapFile[]>();
+ const counts = new Map<string, AreaAnalysed>();
+ for (const f of files) {
+ const ok = isAnalysed(lens, f);
+ for (const area of areasOf(index, f.file_path)) {
+ const c = counts.get(area) ?? { analysed: 0, loaded: 0 };
+ c.loaded += 1;
+ if (ok) {
+ c.analysed += 1;
+ if (lens.flagged) c.flagged = (c.flagged ?? 0) + (lens.flagged(f) ? 1 : 0);
+ const list = analysedFiles.get(area);
+ if (list) list.push(f);
+ else analysedFiles.set(area, [f]);
+ }
+ counts.set(area, c);
+ }
+ }
+ return { analysedFiles, counts };
+}
+
+export function areaFills(index: AreaIndex, lens: MapLens, files: readonly CodeHealthMapFile[]): AreaFills {
+ const fill = new Map<string, string>();
+ const text = new Map<string, string | null>();
+ const inputs = files.length > 0 ? foldInputs(index, lens, files) : null;
+ for (const a of index.areas.values()) {
+ const fromRollup = lens.areaFill?.(a) ?? null;
+ const analysed = inputs?.analysedFiles.get(a.path);
+ text.set(a.path, lens.areaText?.(a, analysed) ?? null);
+ if (fromRollup !== null) fill.set(a.path, fromRollup);
+ else if (analysed?.length && lens.areaFromFiles) fill.set(a.path, lens.areaFromFiles(analysed));
+ else fill.set(a.path, NEUTRAL_FILL);
+ }
+ return { fill, text, analysed: lens.analysed && inputs ? inputs.counts : new Map() };
+}
+
+export function fileFills(scene: FieldScene, lens: MapLens, areaFill: ReadonlyMap<string, string>): string[] {
+ return scene.nodes.map((n, i) => {
+ if (!isAnalysed(lens, n.file)) return NEUTRAL_FILL;
+ if (lens.fill) return lens.fill(n.file);
+ const host = scene.hosts[scene.hostOfNode[i]!];
+ return (host && areaFill.get(host.area)) ?? NEUTRAL_FILL;
+ });
+}
diff --git a/packages/ui/src/health/map/inspector.tsx b/packages/ui/src/health/map/inspector.tsx
index 8b5ddd879..68ee15bda 100644
--- a/packages/ui/src/health/map/inspector.tsx
+++ b/packages/ui/src/health/map/inspector.tsx
@@ -9,6 +9,7 @@
import { useMemo } from "react";
import { cn } from "../../lib/cn";
+import { formatScore } from "@repowise-dev/types/health";
import { performanceBurden, performanceSentence } from "./lens";
import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./types";
@@ -132,7 +133,7 @@ export function MapFieldList({
</span>
) : (
<span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-secondary)]">
- {f.score == null ? "—" : f.score.toFixed(1)}
+ {f.score == null ? "—" : formatScore(f.score)}
</span>
)}
</span>
diff --git a/packages/ui/src/health/map/labels.tsx b/packages/ui/src/health/map/labels.tsx
index 5c9642d8d..211703d3e 100644
--- a/packages/ui/src/health/map/labels.tsx
+++ b/packages/ui/src/health/map/labels.tsx
@@ -1,56 +1,55 @@
"use client";
/**
- * Galaxy names: real-px HTML over the canvas, crisp at any zoom.
+ * Area names: real-px HTML over the canvas, crisp at any zoom.
*
- * React renders one button per galaxy once per field; the frame loop places
- * them with {@link placeLabels}, writing styles directly, so a pan moves the
- * names without a React render. A name is also the way into its galaxy.
+ * React renders one button per laid-out area; the frame loop places them with
+ * {@link placeLabels}, writing styles directly, so a pan moves the names
+ * without a React render. A solid disc carries its name and figure inside it;
+ * an open one carries its name just above its ring. A name is also a way into
+ * its area.
*/
import type { MutableRefObject } from "react";
-import type { Cam } from "./paint";
-import type { Galaxy } from "./types";
+import type { DiscView, FieldView } from "./area-view";
-/** Label a galaxy once its on-screen radius clears this (px). */
-const LABEL_MIN_SCREEN_R = 28;
-/** A field this small names every galaxy, however small. */
-const NAME_ALL_BELOW = 12;
-/** Rough label box, for collision culling before a label has been measured. */
+/** A solid disc names itself once its radius clears this (px). */
+const INSIDE_MIN_R = 26;
+/** An open ring names itself once its radius clears this (px). */
+const ABOVE_MIN_R = 40;
+/** Rough label box, for collision culling. */
const LABEL_H = 18;
-/** Clear space kept between two names. */
const LABEL_GAP = 6;
-const labelWidth = (el: HTMLElement | null, text: string) =>
- el?.offsetWidth || Math.min(240, text.length * 6.6 + 14);
+export interface AreaLabel {
+ path: string;
+ name: string;
+ /** The lens's figure for the area, if any. */
+ text: string | null;
+ /** One sub-folder fills this folder: while open, its label speaks for both. */
+ dominated?: boolean;
+}
interface Box {
x: number;
y: number;
w: number;
+ h: number;
}
-export interface PlaceLabelsOptions {
- galaxies: { cx: number; cy: number; R: number; label: string }[];
- /** Galaxy indices, biggest first: the order names claim space in. */
- order: number[];
- /** Index of the focused galaxy, or -1. */
- focus: number;
- camera: Cam;
- view: { w: number; h: number };
- els: (HTMLElement | null)[];
-}
-
-/** Whether a galaxy is big enough on screen to carry its name. */
-function bigEnough(i: number, R: number, focus: number, minR: number): boolean {
- if (i === focus) return true;
- if (R < minR) return false;
- // Inside a focused galaxy only its larger neighbours keep a name.
- return focus < 0 || R >= minR * 2;
-}
-
-function onCanvas(box: Box, view: { w: number; h: number }): boolean {
- return box.x + box.w > 0 && box.x < view.w && box.y + LABEL_H > 0 && box.y < view.h;
+/** Label sizes are measured once and cached, so a frame rarely forces layout. */
+const sizes = new WeakMap<HTMLElement, { w: number; h: number }>();
+function sizeOf(el: HTMLElement): { w: number; h: number } {
+ // Keyed on the text and the state: an open folder lays its label out in a row.
+ const key = `${el.textContent ?? ""}|${el.dataset.state ?? ""}`;
+ const cached = sizes.get(el);
+ if (cached && el.dataset.measured === key) return cached;
+ const size = { w: el.offsetWidth || 120, h: el.offsetHeight || LABEL_H * 2 };
+ if (el.offsetWidth > 0) {
+ sizes.set(el, size);
+ el.dataset.measured = key;
+ }
+ return size;
}
function collides(box: Box, placed: Box[]): boolean {
@@ -58,76 +57,107 @@ function collides(box: Box, placed: Box[]): boolean {
(p) =>
box.x < p.x + p.w + LABEL_GAP &&
p.x < box.x + box.w + LABEL_GAP &&
- Math.abs(p.y - box.y) < LABEL_H + 2,
+ box.y < p.y + p.h &&
+ p.y < box.y + box.h,
);
}
-/** Where a galaxy's name sits: centred just above its ring. */
-function labelBox(g: PlaceLabelsOptions["galaxies"][number], el: HTMLElement, o: PlaceLabelsOptions): Box {
- const { camera, view } = o;
- const x = view.w / 2 + (g.cx - camera.cx) * camera.scale;
- let y = view.h / 2 + (g.cy - g.R - camera.cy) * camera.scale - 4 - LABEL_H;
- // A ring whose top is off the canvas carries its name just inside it.
- if (y < 4) y = Math.max(4, y + LABEL_H + 10);
- const w = labelWidth(el, g.label);
- return { x: x - w / 2, y, w };
+function boxFor(d: DiscView, el: HTMLElement, viewW: number): Box | null {
+ const { w, h } = sizeOf(el);
+ if (d.state === "closed") {
+ if (d.r < INSIDE_MIN_R || w > d.r * 1.9) return null;
+ return { x: d.x - w / 2, y: d.y - h / 2, w, h };
+ }
+ if (d.state !== "open" || d.r < ABOVE_MIN_R) return null;
+ let y = d.y - d.r - 4 - LABEL_H;
+ if (y < 4) y = Math.max(4, d.y - d.r + 8);
+ // A ring wider than the canvas keeps its name on the canvas.
+ const x = Math.min(Math.max(d.x - w / 2, 4), viewW - w - 4);
+ return { x, y, w, h: Math.max(h, LABEL_H) };
}
/**
- * Put each galaxy's name just above its ring, biggest galaxy first, and hide
- * any name that would land on one already placed or whose galaxy is too small
- * on screen to need one.
+ * Place each drawn area's name, biggest disc first, hiding any that would
+ * land on one already placed, fall off the canvas or not fit its disc.
+ * `shown` carries the visible set between frames, so only changes touch the DOM.
*/
-export function placeLabels(o: PlaceLabelsOptions): void {
+export function placeLabels(
+ field: FieldView,
+ els: ReadonlyMap<string, HTMLElement>,
+ view: { w: number; h: number },
+ shown: Set<HTMLElement>,
+): void {
const placed: Box[] = [];
- const minR = o.galaxies.length <= NAME_ALL_BELOW ? 4 : LABEL_MIN_SCREEN_R;
- for (const i of o.order) {
- const g = o.galaxies[i];
- const el = o.els[i];
- if (!g || !el) continue;
- const box = labelBox(g, el, o);
- const visible =
- bigEnough(i, g.R * o.camera.scale, o.focus, minR) &&
- onCanvas(box, o.view) &&
- !collides(box, placed);
- if (visible) placed.push(box);
- el.style.visibility = visible ? "visible" : "hidden";
+ const next = new Set<HTMLElement>();
+ const discs = field.discs.filter((d) => d.state !== "slot").sort((a, b) => b.r - a.r);
+ for (const d of discs) {
+ const el = els.get(d.path);
+ if (!el || next.has(el)) continue;
+ if (el.dataset.state !== d.state) el.dataset.state = d.state;
+ // One label per visual disc: an open folder its one big sub-folder fills
+ // is named by that sub-folder's label instead.
+ if (d.state === "open" && el.dataset.dominated === "true") continue;
+ const box = boxFor(d, el, view.w);
+ if (!box || box.x + box.w < 0 || box.x > view.w || box.y + box.h < 0 || box.y > view.h) continue;
+ if (collides(box, placed)) continue;
+ placed.push(box);
+ next.add(el);
+ el.style.visibility = "visible";
el.style.transform = `translate(${Math.round(box.x)}px, ${Math.round(box.y)}px)`;
}
+ for (const el of shown) if (!next.has(el)) el.style.visibility = "hidden";
+ shown.clear();
+ for (const el of next) shown.add(el);
}
-export function GalaxyLabels({
- galaxies,
+export function AreaLabels({
+ labels,
refs,
- focusIdx,
- cursorIdx,
- onToggle,
+ selected,
+ cursor,
+ onSelect,
}: {
- galaxies: Galaxy[];
- refs: MutableRefObject<(HTMLButtonElement | null)[]>;
- focusIdx: number;
- /** Galaxy the keyboard cursor is on, or -1 when the keyboard is idle. */
- cursorIdx: number;
- onToggle: (module: string) => void;
+ labels: AreaLabel[];
+ refs: MutableRefObject<Map<string, HTMLElement>>;
+ selected: string | null;
+ /** Area the keyboard cursor is on, or null when the keyboard is idle. */
+ cursor: string | null;
+ onSelect: (path: string) => void;
}) {
return (
- <div className="pointer-events-none absolute inset-0">
- {galaxies.map((g, i) => (
+ <div className="pointer-events-none absolute inset-0 overflow-hidden">
+ {labels.map((l) => (
<button
- key={g.module}
+ key={l.path}
ref={(el) => {
- refs.current[i] = el;
+ if (el) refs.current.set(l.path, el);
+ else refs.current.delete(l.path);
}}
type="button"
tabIndex={-1}
- title={`${g.label} · ${g.fileCount.toLocaleString()} files`}
- onClick={() => onToggle(g.module)}
- className={`pointer-events-auto absolute left-0 top-0 max-w-[240px] truncate rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] ${
- cursorIdx === i ? "ring-2 ring-[var(--color-accent-primary)]" : ""
- } ${focusIdx === i ? "font-medium text-[var(--color-text-primary)]" : ""}`}
+ title={l.path || l.name}
+ onClick={() => onSelect(l.path)}
+ data-area={l.path}
+ data-dominated={l.dominated ? "true" : undefined}
+ className={`group pointer-events-auto absolute left-0 top-0 flex max-w-[220px] flex-col items-center rounded px-1.5 py-0.5 text-center leading-tight bg-[var(--color-bg-glass)] data-[state=open]:flex-row data-[state=open]:gap-1.5 ${
+ cursor === l.path ? "ring-2 ring-[var(--color-accent-primary)]" : ""
+ }`}
style={{ visibility: "hidden" }}
>
- {g.label}
+ <span
+ className={`max-w-full truncate font-mono text-[10px] uppercase tracking-[0.12em] group-data-[state=closed]:text-[var(--color-text-primary)] ${
+ selected === l.path
+ ? "font-semibold text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {l.name}
+ </span>
+ {l.text ? (
+ <span className="font-mono text-xs font-semibold tabular-nums text-[var(--color-text-primary)] group-data-[state=open]:text-[10px]">
+ {l.text}
+ </span>
+ ) : null}
</button>
))}
</div>
diff --git a/packages/ui/src/health/map/layout.ts b/packages/ui/src/health/map/layout.ts
index c5ee51cab..753cdc9e6 100644
--- a/packages/ui/src/health/map/layout.ts
+++ b/packages/ui/src/health/map/layout.ts
@@ -1,200 +1,37 @@
/**
- * Where every node sits, as one pure function of the rows.
+ * Packing files into a disc, and the world square the map lives in.
*
* Deterministic on purpose. A reader builds spatial memory of this field, and
* that memory is only worth having if the same repository lays out the same
- * way every time, under every lens. Nothing here reads a lens, and nothing
- * here reads the canvas size either: the field is laid out once into a fixed
- * world square and the camera fits that square to whatever box it is given,
- * so a resize moves the camera and never re-runs the layout.
+ * way every time, under every lens. Nothing here reads a lens or the canvas
+ * size: the field is laid out once into a fixed world square and the camera
+ * fits that square to whatever box it is given.
*
- * A node's area is its line count everywhere on the field, so two files of
- * the same size are the same size in any galaxy. The grouping adapts to the
- * repository instead: a repository with one module is grouped by sub-folder,
- * and one with hundreds folds its smallest modules into one galaxy per parent,
- * so the field always lands on a readable number of galaxies.
+ * Where the discs go is `area-layout.ts`; this module fills one disc with the
+ * files it hosts, packed tight within each folder, biggest first, so related
+ * files sit side by side and nothing overlaps.
*/
import { packEnclose, packSiblings } from "d3-hierarchy";
-import type { CodeHealthMapFile, FileNode, Galaxy, GalaxyAgg } from "./types";
+import { dirOf } from "../../lib/areas";
+import type { CodeHealthMapFile } from "./types";
/** Side of the world square the field is laid out in. */
export const WORLD = 1000;
-/** Fewer galaxies than this and the field regroups by sub-folder. */
-const MIN_GALAXIES = 4;
-/** More than this and the smallest modules fold into one galaxy per parent. */
-export const MAX_GALAXIES = 40;
/** Lines below which a file is drawn at the floor size, so it stays a dot. */
const NLOC_FLOOR = 4;
/** Air around each dot, in floor radii, so neighbours never touch. */
const DOT_GAP = 0.45;
/** Air around each folder cluster, in floor radii, so folders read apart. */
const FOLDER_GAP = 1.6;
-/**
- * Largest node radius, in world units. At a fitted 720px canvas that is about
- * 17px, which keeps a five-file repository from drawing five dinner plates.
- */
-const MAX_NODE_WORLD = 24;
+const FLOOR_R = Math.sqrt(NLOC_FLOOR);
-const UNGROUPED = "(ungrouped)";
-const ROOT = "(root)";
-const OTHER = "Other modules";
-
-const byPath = (a: CodeHealthMapFile, b: CodeHealthMapFile) =>
+export const byNlocThenPath = (a: CodeHealthMapFile, b: CodeHealthMapFile) =>
b.nloc - a.nloc || (a.file_path < b.file_path ? -1 : 1);
-/**
- * Group flat file rows into per-module galaxies, dropping zero-NLOC files
- * (they cannot be sized). Files come back sorted biggest-first.
- */
-export function groupByModule(files: CodeHealthMapFile[]): GalaxyAgg[] {
- return aggregate(files, (f) => f.module ?? UNGROUPED);
-}
-
-function aggregate(
- files: CodeHealthMapFile[],
- keyOf: (f: CodeHealthMapFile) => string,
-): GalaxyAgg[] {
- const byKey = new Map<string, CodeHealthMapFile[]>();
- for (const f of files) {
- if (f.nloc <= 0) continue;
- const key = keyOf(f);
- const arr = byKey.get(key);
- if (arr) arr.push(f);
- else byKey.set(key, [f]);
- }
- const out: GalaxyAgg[] = [];
- for (const [module, group] of byKey) {
- group.sort(byPath);
- out.push({
- module,
- files: group,
- totalNloc: group.reduce((s, f) => s + f.nloc, 0),
- maxNloc: group[0]?.nloc ?? 1,
- });
- }
- // Biggest galaxies first -> stable z-order (small ones paint on top).
- out.sort((a, b) => b.totalNloc - a.totalNloc || (a.module < b.module ? -1 : 1));
- return out;
-}
-
-/** Stable, well-spread hash of a module name. Kept for hosts that key on it. */
-export function moduleColorId(module: string): number {
- let h = 0;
- for (let i = 0; i < module.length; i++) h = (h * 31 + module.charCodeAt(i)) | 0;
- return Math.abs(h);
-}
-
-function dirOf(path: string): string {
- const i = path.lastIndexOf("/");
- return i < 0 ? "" : path.slice(0, i);
-}
-
-function dirPrefix(dir: string, depth: number): string {
- if (!dir) return ROOT;
- return dir.split("/").slice(0, depth).join("/");
-}
-
-/**
- * How files group into galaxies: by module, or by sub-folder when the modules
- * are too few to separate anything.
- *
- * The folder depth is the shallowest one that yields a readable count, so a
- * repository whose one module is `src` groups by `src/<area>`. If no depth
- * lands in range the depth with the most groups wins, and if even the
- * shallowest useful depth overshoots the ceiling the folding below takes over.
- */
-export function galaxyKeyFor(files: CodeHealthMapFile[]): (f: CodeHealthMapFile) => string {
- const byModule = (f: CodeHealthMapFile) => f.module ?? UNGROUPED;
- const modules = new Set(files.map(byModule));
- if (modules.size >= MIN_GALAXIES) return byModule;
-
- const dirs = files.map((f) => dirOf(f.file_path));
- const deepest = dirs.reduce((m, d) => Math.max(m, d ? d.split("/").length : 0), 0);
- let chosen = 0;
- let chosenCount = modules.size;
- for (let depth = 1; depth <= deepest; depth++) {
- const count = new Set(dirs.map((d) => dirPrefix(d, depth))).size;
- if (count > MAX_GALAXIES) {
- if (chosen === 0) chosen = depth;
- break;
- }
- if (count > chosenCount) {
- chosen = depth;
- chosenCount = count;
- }
- if (count >= MIN_GALAXIES) break;
- }
- if (chosen === 0) return byModule;
- const depth = chosen;
- return (f) => dirPrefix(dirOf(f.file_path), depth);
-}
-
-/** One galaxy before placement: its files and how many modules it stands for. */
-interface Group {
- key: string;
- label: string;
- members: number;
- files: CodeHealthMapFile[];
-}
-
-function parentOf(key: string): string {
- const i = key.lastIndexOf("/");
- return i < 0 ? ROOT : key.slice(0, i);
-}
-
-/**
- * Bound the galaxy count. The biggest groups keep a galaxy of their own and
- * the rest fold into one galaxy per parent folder; if that still overshoots,
- * every folded group shares one. Two passes, so it always terminates.
- */
-export function foldGroups(aggs: GalaxyAgg[]): Group[] {
- const groups: Group[] = aggs.map((a) => ({
- key: a.module,
- label: a.module,
- members: 1,
- files: a.files,
- }));
- if (groups.length <= MAX_GALAXIES) return groups;
- const bySize = [...groups].sort(
- (a, b) => b.files.length - a.files.length || (a.key < b.key ? -1 : 1),
- );
- const keep = bySize.slice(0, MAX_GALAXIES - 1);
- const rest = bySize.slice(MAX_GALAXIES - 1);
- const fold = (keyOf: (g: Group) => string): Group[] => {
- const buckets = new Map<string, Group>();
- for (const g of rest) {
- const key = keyOf(g);
- const bucket = buckets.get(key);
- if (bucket) {
- bucket.files = bucket.files.concat(g.files);
- bucket.members += g.members;
- } else {
- buckets.set(key, { key, label: key, members: g.members, files: [...g.files] });
- }
- }
- return [...keep, ...buckets.values()];
- };
- const byParent = fold((g) => `${parentOf(g.key)}/…`);
- const out = byParent.length <= MAX_GALAXIES ? byParent : fold(() => OTHER);
- for (const g of out) {
- if (g.members > 1) {
- g.label = g.key === OTHER ? `${g.members} smaller modules` : `${g.key} · ${g.members} modules`;
- g.files.sort(byPath);
- }
- }
- return out;
-}
-
-/** The nloc a radius is computed from: floored, and capped at the 98th percentile. */
-function sizeCap(files: CodeHealthMapFile[]): number {
- const sizes = files.map((f) => f.nloc).sort((a, b) => a - b);
- return Math.max(NLOC_FLOOR, sizes[Math.floor((sizes.length - 1) * 0.98)] ?? NLOC_FLOOR);
-}
-
-/** A placed node relative to its galaxy's centre, before the field is scaled. */
-interface LocalNode {
+/** A file placed relative to its cluster's centre, before scaling. */
+export interface LocalNode {
file: CodeHealthMapFile;
x: number;
y: number;
@@ -202,18 +39,17 @@ interface LocalNode {
}
/**
- * Pack one galaxy: files packed tight within each folder, biggest first, then
- * the folders packed together. Related files sit side by side, nothing
- * overlaps, and the galaxy's disc is the smallest circle that holds them.
+ * Pack one disc's files: tight within each folder, then the folders packed
+ * together. `radius` maps lines to a radius; the result is centred on 0,0 and
+ * `R` is the smallest circle that holds it.
*/
-function packGalaxy(
- files: CodeHealthMapFile[],
- radius: (nloc: number) => number,
- floorR: number,
+export function packCluster(
+ files: readonly CodeHealthMapFile[],
+ radius: (nloc: number) => number = fileRadius,
): { nodes: LocalNode[]; R: number } {
- const dotPad = floorR * DOT_GAP;
+ const dotPad = FLOOR_R * DOT_GAP;
const byDir = new Map<string, CodeHealthMapFile[]>();
- for (const f of files) {
+ for (const f of [...files].sort(byNlocThenPath)) {
const d = dirOf(f.file_path);
const arr = byDir.get(d);
if (arr) arr.push(f);
@@ -222,11 +58,11 @@ function packGalaxy(
const clusters = [...byDir.entries()].map(([dir, group]) => {
const dots = packSiblings(group.map((file) => ({ file, r: radius(file.nloc) + dotPad })));
const enc = packEnclose(dots) ?? { x: 0, y: 0, r: dotPad };
- return { dir, dots, ex: enc.x, ey: enc.y, r: enc.r + (byDir.size > 1 ? floorR * FOLDER_GAP : 0) };
+ return { dir, dots, ex: enc.x, ey: enc.y, r: enc.r + (byDir.size > 1 ? FLOOR_R * FOLDER_GAP : 0) };
});
clusters.sort((a, b) => b.r - a.r || (a.dir < b.dir ? -1 : 1));
const placed = packSiblings(clusters);
- const enc = packEnclose(placed) ?? { x: 0, y: 0, r: floorR };
+ const enc = packEnclose(placed) ?? { x: 0, y: 0, r: FLOOR_R };
const nodes: LocalNode[] = [];
for (const c of placed) {
for (const d of c.dots) {
@@ -238,78 +74,12 @@ function packGalaxy(
});
}
}
- return { nodes, R: enc.r + floorR };
+ return { nodes, R: enc.r + FLOOR_R };
}
-/**
- * The whole field, in world units: galaxies placed by circle packing, and
- * files inside each packed by folder (see {@link packGalaxy}).
- *
- * Each file's radius is the square root of its lines, so area is lines.
- */
-export function layoutField(files: CodeHealthMapFile[]): Galaxy[] {
- const drawable = files.filter((f) => f.nloc > 0);
- if (drawable.length === 0) return [];
- const groups = foldGroups(aggregate(drawable, galaxyKeyFor(drawable)));
- const cap = sizeCap(drawable);
- const radius = (nloc: number) => Math.sqrt(Math.min(cap, Math.max(NLOC_FLOOR, nloc)));
- const floorR = Math.sqrt(NLOC_FLOOR);
-
- const local = groups.map((g) => {
- const { nodes, R } = packGalaxy(g.files, radius, floorR);
- const maxNode = nodes.reduce((m, n) => Math.max(m, n.r), 0);
- return { g, nodes, R, maxNode };
- });
-
- // Pack biggest first so the largest galaxy anchors the middle.
- const order = local.map((_, i) => i).sort((a, b) => local[b]!.R - local[a]!.R || a - b);
- const largest = local[order[0]!]!.R;
- const gap = floorR * 3 + largest * 0.03;
- const circles = packSiblings(order.map((i) => ({ r: local[i]!.R + gap, i })));
- const enclose = packEnclose(circles) ?? { x: 0, y: 0, r: largest };
-
- const maxNode = local.reduce((m, l) => Math.max(m, l.maxNode), 0);
- const scale = Math.min(((WORLD / 2) * 0.96) / Math.max(enclose.r, 1e-9), MAX_NODE_WORLD / maxNode);
- const half = WORLD / 2;
-
- return circles.map<Galaxy>((c) => {
- const { g, nodes, R } = local[c.i]!;
- const cx = half + (c.x - enclose.x) * scale;
- const cy = half + (c.y - enclose.y) * scale;
- return {
- module: g.key,
- label: g.label,
- members: g.members,
- cx,
- cy,
- R: R * scale,
- fileCount: nodes.length,
- colorId: moduleColorId(g.key),
- nodes: nodes.map<FileNode>((n) => ({
- file: n.file,
- x: cx + n.x * scale,
- y: cy + n.y * scale,
- r: n.r * scale,
- })),
- };
- });
-}
-
-/**
- * The same field fitted into an `S` square, for a host that draws it itself.
- * Returns an empty field for an empty input rather than throwing, because a
- * host renders before its data lands.
- */
-export function packGalaxies(files: CodeHealthMapFile[], S: number): Galaxy[] {
- if (S === 0) return [];
- const k = S / WORLD;
- return layoutField(files).map((g) => ({
- ...g,
- cx: g.cx * k,
- cy: g.cy * k,
- R: g.R * k,
- nodes: g.nodes.map((n) => ({ ...n, x: n.x * k, y: n.y * k, r: n.r * k })),
- }));
+/** A file's radius before scaling: area is lines, floored so a tiny file is a dot. */
+export function fileRadius(nloc: number): number {
+ return Math.sqrt(Math.max(NLOC_FLOOR, nloc));
}
/** The camera that shows the whole world square in a `w` by `h` box. */
diff --git a/packages/ui/src/health/map/legend.tsx b/packages/ui/src/health/map/legend.tsx
index 6a35a8cad..7428cff4a 100644
--- a/packages/ui/src/health/map/legend.tsx
+++ b/packages/ui/src/health/map/legend.tsx
@@ -9,11 +9,14 @@
*/
// Aliased: the bare name would shadow the DOM `KeyboardEvent`.
-import { Fragment } from "react";
-import type { KeyboardEvent as ReactKeyboardEvent } from "react";
-import { OVERLAY_ORDER, OVERLAY_SPECS, type LegendRow, type OverlaySpec } from "./lens";
+import { Fragment, useState } from "react";
+import { ChevronDown } from "lucide-react";
+import type { LegendRow, MapLens } from "./lens";
+import { OVERLAY_ORDER, OVERLAY_SPECS } from "./lens-registry";
import type { CodeHealthOverlay } from "./types";
import { ActivityDot } from "../../ui/activity-dot";
+import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
+import { Segmented } from "../../shared/segmented";
/** One key swatch: a disc in the row's fill, or a pill for a run of the ramp. */
function Swatch({ row, size }: { row: LegendRow; size: number }) {
@@ -47,7 +50,7 @@ function SizeKey({ className }: { className?: string }) {
}
/** The active lens's key rows, shared by both placements. */
-export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: boolean }) {
+export function MapLegendRows({ spec, loading }: { spec: MapLens; loading: boolean }) {
if (loading) {
return (
<div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
@@ -80,63 +83,80 @@ export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: b
}
/**
- * The lens switcher as a real segmented control.
+ * The lens switcher: the shared segmented control for the primary lenses, and
+ * the rest behind a "More" menu. A lens picked from the menu joins the row as
+ * the selected segment, so the active lens is always on screen. Without
+ * `primary`, every lens is a segment, as before.
*
- * A radiogroup rather than a row of pressed buttons: picking a lens is one
- * choice out of a set, and the roving-tabindex arrow-key behaviour comes free
- * with the role.
+ * Future lenses (off-boarding, coupling) join `lenses` and land in the menu.
*/
export function MapLensSwitcher({
overlay,
onOverlayChange,
lenses = OVERLAY_ORDER,
+ primary,
+ moreLabel = "More",
+ nameOf,
className,
}: {
overlay: CodeHealthOverlay;
onOverlayChange: (overlay: CodeHealthOverlay) => void;
lenses?: CodeHealthOverlay[];
+ /** Lenses shown as segments; the others go behind "More". */
+ primary?: CodeHealthOverlay[];
+ moreLabel?: string;
+ /** A lens's display name, for a host that translates them. */
+ nameOf?: (lens: CodeHealthOverlay) => string;
className?: string;
}) {
- const onKeyDown = (e: ReactKeyboardEvent) => {
- const i = lenses.indexOf(overlay);
- if (i < 0) return;
- let next = i;
- if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % lenses.length;
- else if (e.key === "ArrowLeft" || e.key === "ArrowUp")
- next = (i - 1 + lenses.length) % lenses.length;
- else return;
- e.preventDefault();
- const target = lenses[next];
- if (target) onOverlayChange(target);
- };
-
+ const [open, setOpen] = useState(false);
+ const name = (lens: CodeHealthOverlay) => nameOf?.(lens) ?? OVERLAY_SPECS[lens].label;
+ const main = primary ? lenses.filter((l) => primary.includes(l)) : lenses;
+ const rest = primary ? lenses.filter((l) => !primary.includes(l)) : [];
+ const shown = rest.includes(overlay) ? [...main, overlay] : main;
return (
- <div
- role="radiogroup"
- aria-label="Map lens"
- onKeyDown={onKeyDown}
- className={`inline-flex rounded-md border border-[var(--color-border-default)] p-0.5 ${className ?? ""}`}
- >
- {lenses.map((mode) => {
- const active = overlay === mode;
- return (
- <button
- key={mode}
- type="button"
- role="radio"
- aria-checked={active}
- tabIndex={active ? 0 : -1}
- onClick={() => onOverlayChange(mode)}
- className={`rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
- active
- ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
- : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- {OVERLAY_SPECS[mode].label}
- </button>
- );
- })}
+ <div className={`flex min-w-0 flex-wrap items-start gap-1.5 ${className ?? ""}`}>
+ <Segmented
+ label="Map lens"
+ value={overlay}
+ options={shown.map((value) => ({ value, label: name(value) }))}
+ onChange={onOverlayChange}
+ />
+ {rest.length > 0 ? (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ aria-haspopup="menu"
+ className="inline-flex items-center gap-1 rounded-md border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {moreLabel}
+ <ChevronDown aria-hidden className="h-3.5 w-3.5" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent role="menu" align="end" className="w-48 p-1">
+ {rest.map((lens) => (
+ <button
+ key={lens}
+ type="button"
+ role="menuitemradio"
+ aria-checked={lens === overlay}
+ onClick={() => {
+ setOpen(false);
+ onOverlayChange(lens);
+ }}
+ className={`flex w-full items-center rounded px-2 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ lens === overlay
+ ? "font-semibold text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {name(lens)}
+ </button>
+ ))}
+ </PopoverContent>
+ </Popover>
+ ) : null}
</div>
);
}
@@ -149,14 +169,17 @@ export function MapLensSwitcher({
*/
export function MapLegend({
overlay,
+ lens,
loading = false,
className,
}: {
overlay: CodeHealthOverlay;
+ /** A resolved or plug-in lens; wins over `overlay`. */
+ lens?: MapLens;
loading?: boolean;
className?: string;
}) {
- const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
+ const spec = lens ?? OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
return (
<div
className={`flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-[var(--color-text-tertiary)] ${className ?? ""}`}
diff --git a/packages/ui/src/health/map/lens-registry.ts b/packages/ui/src/health/map/lens-registry.ts
new file mode 100644
index 000000000..c2a8c7379
--- /dev/null
+++ b/packages/ui/src/health/map/lens-registry.ts
@@ -0,0 +1,268 @@
+/**
+ * The built-in lenses, by id, and the rules for which a switcher offers.
+ *
+ * Every entry is a {@link MapLens}. A surface with a lens of its own does not
+ * add it here: it builds a `MapLens` and passes it to the map's `lens` prop
+ * (see `lens.ts`), so this table stays the Code Health page's vocabulary.
+ */
+
+import { healthBandMapFill, NODE_RAMP_STOP } from "../tokens";
+import { formatScore } from "@repowise-dev/types/health";
+import { EMPTY_AREA_INDEX, type AreaIndex } from "./areas";
+import { KNOWLEDGE_LENS, ownerLens, shareFill } from "./area-lenses";
+import {
+ BAND_LEGEND,
+ BURDEN_FILL,
+ CLEAR_NEUTRAL_FILL,
+ HEALTH_UNSUPPORTED_LABEL,
+ NEUTRAL_FILL,
+ QUIET_FILL,
+ churnFill,
+ coverageFill,
+ performanceBurden,
+ performanceFill,
+ scoreFill,
+ type MapLens,
+} from "./lens";
+import type { CodeHealthMapFile, CodeHealthOverlay } from "./types";
+import { DEFAULT_MAP_CANVAS_LABELS, type MapCanvasLabels } from "./canvas-labels";
+
+/** NLOC-weighted mean of a per-file score, over the files that carry one. */
+function weightedMean(
+ files: readonly CodeHealthMapFile[],
+ pick: (f: CodeHealthMapFile) => number | null | undefined,
+): number | null {
+ let w = 0;
+ let sum = 0;
+ for (const f of files) {
+ const v = pick(f);
+ if (v == null || f.nloc <= 0) continue;
+ w += f.nloc;
+ sum += v * f.nloc;
+ }
+ return w > 0 ? sum / w : null;
+}
+
+/**
+ * Share of a folder's analysed files that carry something to fix, banded.
+ * A share, not a count: a count grows with the folder, so every big folder
+ * would read as worst. No green under these lenses, since an absence of
+ * findings is not a measurement of good: zero is the quiet neutral.
+ */
+const FLAGGED_STEPS = [0.1, 0.25] as const;
+function flaggedShareFill(
+ files: readonly CodeHealthMapFile[],
+ flagged: (f: CodeHealthMapFile) => boolean,
+ clear: string,
+): string {
+ const share = files.filter(flagged).length / files.length;
+ if (share <= 0) return clear;
+ if (share >= FLAGGED_STEPS[1]) return NODE_RAMP_STOP.alert;
+ if (share >= FLAGGED_STEPS[0]) return NODE_RAMP_STOP.serious;
+ return NODE_RAMP_STOP.warning;
+}
+/**
+ * A lens that folds folders by the share of analysed files flagged. `clear`
+ * is the analysed-and-nothing-found tone, distinct from not analysed.
+ */
+function flaggedLens(flagged: (f: CodeHealthMapFile) => boolean, clear: string) {
+ return {
+ flagged,
+ areaFromFiles: (files: readonly CodeHealthMapFile[]) => flaggedShareFill(files, flagged, clear),
+ };
+}
+const FOLDER_SHARE_LEGEND = (clear: string, clearLabel: string) => [
+ { group: "Folders", fill: NODE_RAMP_STOP.alert, label: "25% or more of analysed files flagged" },
+ { group: "Folders", fill: NODE_RAMP_STOP.serious, label: "10 to 25%" },
+ { group: "Folders", fill: NODE_RAMP_STOP.warning, label: "Under 10%" },
+ { group: "Folders", fill: clear, label: clearLabel },
+];
+
+/** A file a performance detector looked at: it has a count, and its language is covered. */
+const performanceAnalysed = (f: CodeHealthMapFile) => {
+ const state = performanceBurden(f).state;
+ return state !== "unsupported" && state !== "unknown";
+};
+const hasCause = (f: CodeHealthMapFile) => performanceBurden(f).count > 0;
+
+const pct = (v: number) => `${Math.round(v)}%`;
+const isHotspot = (f: CodeHealthMapFile) => f.is_hotspot === true;
+
+/** Hotspot share at which an area reads as churning. */
+const HOTSPOT_STEPS = [0.1, 0.25, 0.5] as const;
+
+/**
+ * Hotspot files in their health band, every other file grey, so red and
+ * amber appear only where heavy change meets weak health and a healthy
+ * hotspot stays green. `chip` words a folder's figure, for translation.
+ */
+export function hotspotLens(chip: MapCanvasLabels["hotspotChip"]): FileLens {
+ return {
+ id: "hotspot",
+ label: "Hotspot health",
+ caption:
+ "colour = health of files that change the most · grey = not a hotspot · folder = hotspot count and their health",
+ // Only where heavy change meets weak health does the field turn amber or
+ // red; a healthy hotspot stays green and every other file goes quiet.
+ fill: (f) => (f.is_hotspot ? scoreFill(f.score) : NEUTRAL_FILL),
+ analysed: (f) => f.score != null,
+ areaFromFiles: (files) => scoreFill(weightedMean(files.filter(isHotspot), (f) => f.score)),
+ areaText: (a, files) => {
+ const hot = files?.filter(isHotspot) ?? [];
+ const count = a.hotspotCount ?? hot.length;
+ if (count === 0) return null;
+ const health = weightedMean(hot, (f) => f.score);
+ return chip(count, health == null ? null : formatScore(health));
+ },
+ legend: [...BAND_LEGEND, { fill: NEUTRAL_FILL, label: "Grey = not a hotspot" }],
+ available: ({ files, areas }) =>
+ files.some((f) => f.is_hotspot != null) || [...areas.areas.values()].some((x) => x.hotspotCount !== undefined),
+ };
+}
+
+/** A lens that reads the file rows, so its `fill` is always there. */
+type FileLens = MapLens & { fill: NonNullable<MapLens["fill"]> };
+type AreaLensId = "owner" | "knowledge";
+
+export const OVERLAY_SPECS: Record<Exclude<CodeHealthOverlay, AreaLensId>, FileLens> &
+ Record<AreaLensId, MapLens> = {
+ health: {
+ id: "health",
+ label: "Code health",
+ caption: "disc = folder · size = lines of code · grey = not analysed",
+ fill: (f) => scoreFill(f.score),
+ analysed: (f) => f.score != null,
+ areaFill: (a) => (a.band ? healthBandMapFill(a.band) : NEUTRAL_FILL),
+ areaText: (a) => (a.health == null ? null : formatScore(a.health)),
+ legend: [...BAND_LEGEND, { fill: NEUTRAL_FILL, label: HEALTH_UNSUPPORTED_LABEL }],
+ },
+ hotspot: hotspotLens(DEFAULT_MAP_CANVAS_LABELS.hotspotChip),
+ maintainability: {
+ id: "maintainability",
+ label: "Maintainability",
+ caption: "color = maintainability score · folders show their loaded files · grey = not measured",
+ fill: (f) => scoreFill(f.maintainability_score),
+ analysed: (f) => f.maintainability_score != null,
+ areaFromFiles: (files) => scoreFill(weightedMean(files, (f) => f.maintainability_score)),
+ legend: [...BAND_LEGEND, { fill: NEUTRAL_FILL, label: "not measured" }],
+ },
+ performance: {
+ id: "performance",
+ label: "Performance",
+ caption:
+ "file = open causes · folder = share of its analysed files with one · never a runtime measurement · no green: nothing here is proven fast",
+ fill: performanceFill,
+ analysed: performanceAnalysed,
+ ...flaggedLens(hasCause, CLEAR_NEUTRAL_FILL),
+ legend: [
+ { group: "Open causes", fill: BURDEN_FILL[3], label: "5 or more" },
+ { group: "Open causes", fill: BURDEN_FILL[2], label: "2 to 4" },
+ { group: "Open causes", fill: BURDEN_FILL[1], label: "1" },
+ { group: "No open cause", fill: NEUTRAL_FILL, label: "Nothing surfaced or not analysed" },
+ ...FOLDER_SHARE_LEGEND(CLEAR_NEUTRAL_FILL, "No issues found"),
+ ],
+ },
+ coverage: {
+ id: "coverage",
+ label: "Coverage",
+ caption: "color = line coverage · grey = no coverage data",
+ fill: (f) => coverageFill(f.line_coverage_pct),
+ analysed: (f) => f.line_coverage_pct != null,
+ areaFill: (a) => (a.coveragePct === undefined ? null : coverageFill(a.coveragePct)),
+ areaFromFiles: (files) => coverageFill(weightedMean(files, (f) => f.line_coverage_pct)),
+ areaText: (a) => (a.coveragePct == null ? null : pct(a.coveragePct)),
+ legend: [
+ { fill: NODE_RAMP_STOP.alert, label: "<20%" },
+ { fill: NODE_RAMP_STOP.serious, label: "20-50%" },
+ { fill: NODE_RAMP_STOP.warning, label: "50-80%" },
+ { fill: QUIET_FILL, label: "≥80%" },
+ { fill: NEUTRAL_FILL, label: "no data" },
+ ],
+ },
+ churn: {
+ id: "churn",
+ label: "Churn",
+ caption: "file = 90-day churn percentile · folder = share of its files that are hotspots",
+ fill: (f) => churnFill(f.churn_percentile),
+ analysed: (f) => f.churn_percentile != null,
+ areaFill: (a) =>
+ a.hotspotCount === undefined || a.fileCount <= 0
+ ? null
+ : shareFill(a.hotspotCount / a.fileCount, HOTSPOT_STEPS),
+ areaFromFiles: (files) => churnFill(weightedMean(files, (f) => f.churn_percentile)),
+ areaText: (a) =>
+ a.hotspotCount === undefined || a.fileCount <= 0 ? null : pct((a.hotspotCount / a.fileCount) * 100),
+ legend: [
+ { fill: NODE_RAMP_STOP.alert, label: "Top 10%" },
+ { fill: NODE_RAMP_STOP.serious, label: "Top 30%" },
+ { fill: NODE_RAMP_STOP.warning, label: "Top 60%" },
+ { fill: QUIET_FILL, label: "Quiet" },
+ { fill: NEUTRAL_FILL, label: "no data" },
+ ],
+ },
+ "dead-code": {
+ id: "dead-code",
+ label: "Dead code",
+ caption: "red = reclaimable lines · grey = clean",
+ fill: (f) => ((f.dead_code_lines ?? 0) > 0 ? NODE_RAMP_STOP.alert : NEUTRAL_FILL),
+ analysed: (f) => f.dead_code_lines != null,
+ ...flaggedLens((f) => (f.dead_code_lines ?? 0) > 0, QUIET_FILL),
+ legend: [
+ { fill: NODE_RAMP_STOP.alert, label: "Has dead code" },
+ { fill: NEUTRAL_FILL, label: "Clean or not analysed" },
+ ...FOLDER_SHARE_LEGEND(QUIET_FILL, "No issues found"),
+ ],
+ available: ({ files }) => files.some((f) => f.dead_code_lines != null),
+ },
+ security: {
+ id: "security",
+ label: "Security",
+ caption: "red = open findings · grey = clean",
+ fill: (f) => ((f.security_findings ?? 0) > 0 ? NODE_RAMP_STOP.alert : NEUTRAL_FILL),
+ analysed: (f) => f.security_findings != null,
+ ...flaggedLens((f) => (f.security_findings ?? 0) > 0, QUIET_FILL),
+ legend: [
+ { fill: NODE_RAMP_STOP.alert, label: "Has findings" },
+ { fill: NEUTRAL_FILL, label: "Clean or not analysed" },
+ ...FOLDER_SHARE_LEGEND(QUIET_FILL, "No issues found"),
+ ],
+ available: ({ files }) => files.some((f) => f.security_findings != null),
+ },
+ owner: ownerLens(EMPTY_AREA_INDEX),
+ knowledge: KNOWLEDGE_LENS,
+};
+
+/**
+ * Default lenses offered in the switcher: the three co-equal health signals,
+ * all backed by a per-file signal that rides on the map payload itself.
+ *
+ * Churn is deliberately not in the default. It colors by `churn_percentile`,
+ * which arrives on a separate request the host has to join in, so offering it
+ * where nobody joined it paints an all-neutral field that reads as "no churn"
+ * rather than "no data". Hosts that do the join pass their own `lenses`.
+ */
+export const OVERLAY_ORDER: CodeHealthOverlay[] = ["health", "maintainability", "performance"];
+
+/** A built-in lens, built over the areas on hand when its key depends on them. */
+export function resolveLens(
+ id: CodeHealthOverlay,
+ areas: AreaIndex,
+ labels?: Pick<MapCanvasLabels, "hotspotChip">,
+): MapLens {
+ if (id === "owner") return ownerLens(areas);
+ if (id === "hotspot" && labels) return hotspotLens(labels.hotspotChip);
+ return OVERLAY_SPECS[id] ?? OVERLAY_SPECS.health;
+}
+
+/**
+ * Whether the data on hand backs a lens. A lens with no data draws every node
+ * grey, which reads as "clean" rather than as "not here", so it is not offered.
+ */
+export function lensAvailable(
+ lens: CodeHealthOverlay,
+ files: readonly CodeHealthMapFile[],
+ areas: AreaIndex = EMPTY_AREA_INDEX,
+): boolean {
+ const available = OVERLAY_SPECS[lens]?.available;
+ return available ? available({ files, areas }) : true;
+}
diff --git a/packages/ui/src/health/map/lens.ts b/packages/ui/src/health/map/lens.ts
index 9e436cf4b..974e36733 100644
--- a/packages/ui/src/health/map/lens.ts
+++ b/packages/ui/src/health/map/lens.ts
@@ -5,9 +5,15 @@
* cannot drift: both call the same spec.
*/
-import { HEALTH_BAND_LABEL, HEALTH_BAND_ORDER, HEALTH_BAND_RANGE_LABEL } from "@repowise-dev/types/health";
+import {
+ HEALTH_BAND_LABEL,
+ HEALTH_BAND_ORDER,
+ HEALTH_BAND_RANGE_LABEL,
+ formatScore,
+} from "@repowise-dev/types/health";
import { NODE_HEALTHY_FILL, NODE_RAMP_STOP, healthBandMapFill, healthRampFill } from "../tokens";
-import type { CodeHealthMapFile, CodeHealthOverlay, PerformanceActionability } from "./types";
+import type { AreaIndex, MapArea } from "./areas";
+import type { CodeHealthMapFile, PerformanceActionability } from "./types";
/** The one quiet tone every file that needs nothing takes, under every lens. */
export const QUIET_FILL = NODE_HEALTHY_FILL;
@@ -22,6 +28,13 @@ export const QUIET_FILL = NODE_HEALTHY_FILL;
*/
export const NEUTRAL_FILL = "var(--color-node-neutral)";
+/**
+ * A folder a lens checked and found nothing in, where green would overclaim
+ * (performance: no supported pattern is not proven fast). The neutral pulled
+ * toward the page, so "checked, clear" never reads as "not checked".
+ */
+export const CLEAR_NEUTRAL_FILL = "color-mix(in srgb, var(--color-node-neutral) 40%, var(--color-bg-surface))";
+
export interface LegendRow {
fill: string;
label: string;
@@ -34,28 +47,76 @@ export interface LegendRow {
}
/** Worst-first legend rows on the five canonical bands, as every score pill reads. */
-const BAND_LEGEND: LegendRow[] = HEALTH_BAND_ORDER.map((band) => ({
+export const BAND_LEGEND: LegendRow[] = HEALTH_BAND_ORDER.map((band) => ({
fill: healthBandMapFill(band),
label: `${HEALTH_BAND_LABEL[band]} · ${HEALTH_BAND_RANGE_LABEL[band]}`,
}));
-/** Lens metadata: how to fill a node and what the key reads. */
-export interface OverlaySpec {
+/**
+ * A lens: how the map colours and names what it draws, and what its key reads.
+ *
+ * This is the extension point other surfaces plug into without touching the
+ * canvas. A lens is plain data plus pure functions, so a host can build one
+ * over data only it holds (an off-boarding scenario, a coupling read) by
+ * closing over that data, and hand it to `CodeHealthMap`'s `lens` prop and to
+ * `MapLegend`. Every method is optional past the key: a lens that only knows
+ * files leaves `areaFill` out and areas fold their loaded files through
+ * `areaFromFiles`; a lens that only knows areas leaves `fill` out and each
+ * file takes the colour of the area it sits in.
+ *
+ * Colours are CSS strings (token `var()`s or `color-mix()`es), never raw hex.
+ */
+export interface MapLens {
+ /** Stable id, for a switcher and the URL. */
+ id: string;
label: string;
/** Caption shown under the legend key. */
caption: string;
- fill: (f: CodeHealthMapFile) => string;
legend: LegendRow[];
+ /** A file's fill. Absent: the file takes its area's fill. */
+ fill?: (f: CodeHealthMapFile) => string;
+ /** An area's fill from its rollup; `null` when the rollup lacks the signal. */
+ areaFill?: (a: MapArea) => string | null;
+ /**
+ * Whether a file carries this lens's signal at all. A file that does not is
+ * not analysed: it is drawn grey and left out of every folder's fold, never
+ * read as the worst value. Absent: every file carries it.
+ */
+ analysed?: (f: CodeHealthMapFile) => boolean;
+ /** Whether an analysed file carries something to fix, for "N of M flagged". */
+ flagged?: (f: CodeHealthMapFile) => boolean;
+ /**
+ * An area's fill from its loaded, analysed files, when `areaFill` cannot
+ * say. Never called with an empty list: a folder with no analysed file is
+ * grey. Fold by share, not by count, or every big folder reads as worst.
+ */
+ areaFromFiles?: (files: readonly CodeHealthMapFile[]) => string;
+ /**
+ * The short figure printed on an area's disc ("7.4", "62%"). `files` are
+ * the area's loaded files this lens analysed, when any are loaded.
+ */
+ areaText?: (a: MapArea, files?: readonly CodeHealthMapFile[]) => string | null;
+ /** Whether the data on hand backs this lens; an unbacked lens is not offered. */
+ available?: (ctx: LensContext) => boolean;
}
+/** What a lens's availability is judged against. */
+export interface LensContext {
+ files: readonly CodeHealthMapFile[];
+ areas: AreaIndex;
+}
+
+/** @deprecated The built-in lenses' old name; every lens is a {@link MapLens}. */
+export type OverlaySpec = MapLens;
+
/** Score: the map ramp, the neutral when the pillar is unscored. */
-function scoreFill(score: number | null | undefined): string {
+export function scoreFill(score: number | null | undefined): string {
if (score == null) return NEUTRAL_FILL;
return healthRampFill(score);
}
/** Coverage band: quiet when well covered, the ramp's stops below that. */
-function coverageFill(pct: number | null | undefined): string {
+export function coverageFill(pct: number | null | undefined): string {
if (pct == null) return NEUTRAL_FILL;
if (pct >= 80) return QUIET_FILL;
if (pct >= 50) return NODE_RAMP_STOP.warning;
@@ -64,7 +125,7 @@ function coverageFill(pct: number | null | undefined): string {
}
/** Churn band: quiet below the top 60%, the ramp's stops above it. */
-function churnFill(pctile: number | null | undefined): string {
+export function churnFill(pctile: number | null | undefined): string {
if (pctile == null) return NEUTRAL_FILL;
if (pctile >= 90) return NODE_RAMP_STOP.alert;
if (pctile >= 70) return NODE_RAMP_STOP.serious;
@@ -192,7 +253,7 @@ export function burdenBand(count: number): 0 | 1 | 2 | 3 {
* the same severity wherever it appears on this field. The quiet tone is
* deliberately absent: it is the one that would claim a file is fine.
*/
-const BURDEN_FILL: Record<1 | 2 | 3, string> = {
+export const BURDEN_FILL: Record<1 | 2 | 3, string> = {
1: NODE_RAMP_STOP.warning,
2: NODE_RAMP_STOP.serious,
3: NODE_RAMP_STOP.alert,
@@ -225,7 +286,7 @@ export function noFileScored(files: CodeHealthMapFile[]): boolean {
/** A file's score at one decimal, or the unsupported label. */
export function scoreText(f: CodeHealthMapFile): string {
- return f.score == null ? HEALTH_UNSUPPORTED_LABEL : f.score.toFixed(1);
+ return f.score == null ? HEALTH_UNSUPPORTED_LABEL : formatScore(f.score);
}
/** One sentence a hover card or inspector can print about a file. */
@@ -237,99 +298,3 @@ export function performanceSentence(f: CodeHealthMapFile): string {
}
return PERFORMANCE_STATE_LABEL[state];
}
-
-export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
- health: {
- label: "Code health",
- caption: "galaxy = module · size = lines of code · grey = not analysed",
- fill: (f) => scoreFill(f.score),
- legend: [...BAND_LEGEND, { fill: NEUTRAL_FILL, label: HEALTH_UNSUPPORTED_LABEL }],
- },
- maintainability: {
- label: "Maintainability",
- caption: "color = maintainability score · grey = not measured",
- fill: (f) => scoreFill(f.maintainability_score),
- legend: [...BAND_LEGEND, { fill: NEUTRAL_FILL, label: "not measured" }],
- },
- performance: {
- label: "Performance",
- caption: "colour = open causes, never a runtime measurement · no green: nothing here is proven fast",
- fill: performanceFill,
- legend: [
- { group: "Open causes", fill: BURDEN_FILL[3], label: "5 or more" },
- { group: "Open causes", fill: BURDEN_FILL[2], label: "2 to 4" },
- { group: "Open causes", fill: BURDEN_FILL[1], label: "1" },
- { group: "No open cause", fill: NEUTRAL_FILL, label: "Nothing surfaced" },
- ],
- },
- coverage: {
- label: "Coverage",
- caption: "color = line coverage · grey = no coverage data",
- fill: (f) => coverageFill(f.line_coverage_pct),
- legend: [
- { fill: NODE_RAMP_STOP.alert, label: "<20%" },
- { fill: NODE_RAMP_STOP.serious, label: "20-50%" },
- { fill: NODE_RAMP_STOP.warning, label: "50-80%" },
- { fill: QUIET_FILL, label: "≥80%" },
- { fill: NEUTRAL_FILL, label: "no data" },
- ],
- },
- churn: {
- label: "Churn",
- caption: "color = 90-day churn percentile",
- fill: (f) => churnFill(f.churn_percentile),
- legend: [
- { fill: NODE_RAMP_STOP.alert, label: "Top 10%" },
- { fill: NODE_RAMP_STOP.serious, label: "Top 30%" },
- { fill: NODE_RAMP_STOP.warning, label: "Top 60%" },
- { fill: QUIET_FILL, label: "Quiet" },
- { fill: NEUTRAL_FILL, label: "no data" },
- ],
- },
- "dead-code": {
- label: "Dead code",
- caption: "red = reclaimable lines · grey = clean",
- fill: (f) => ((f.dead_code_lines ?? 0) > 0 ? NODE_RAMP_STOP.alert : NEUTRAL_FILL),
- legend: [
- { fill: NODE_RAMP_STOP.alert, label: "Has dead code" },
- { fill: NEUTRAL_FILL, label: "Clean" },
- ],
- },
- security: {
- label: "Security",
- caption: "red = open findings · grey = clean",
- fill: (f) => ((f.security_findings ?? 0) > 0 ? NODE_RAMP_STOP.alert : NEUTRAL_FILL),
- legend: [
- { fill: NODE_RAMP_STOP.alert, label: "Has findings" },
- { fill: NEUTRAL_FILL, label: "Clean" },
- ],
- },
-};
-
-/**
- * Default lenses offered in the switcher: the three co-equal health signals,
- * all backed by a per-file signal that rides on the map payload itself.
- *
- * Churn is deliberately not in the default. It colors by `churn_percentile`,
- * which arrives on a separate request the host has to join in, so offering it
- * where nobody joined it paints an all-neutral field that reads as "no churn"
- * rather than "no data". Hosts that do the join pass their own `lenses`.
- */
-export const OVERLAY_ORDER: CodeHealthOverlay[] = [
- "health",
- "maintainability",
- "performance",
-];
-
-/**
- * Whether the rows carry the signal a lens colours by.
- *
- * Dead code and security colour from fields this feed does not serve, and a
- * lens with no data draws every node grey, which reads as "clean" rather than
- * as "not here". A lens the rows cannot back is not offered.
- */
-export function lensAvailable(lens: CodeHealthOverlay, files: CodeHealthMapFile[]): boolean {
- if (lens === "dead-code") return files.some((f) => f.dead_code_lines != null);
- if (lens === "security") return files.some((f) => f.security_findings != null);
- return true;
-}
diff --git a/packages/ui/src/health/map/overlay.tsx b/packages/ui/src/health/map/overlay.tsx
index 04331e2a7..d1a0eaf0b 100644
--- a/packages/ui/src/health/map/overlay.tsx
+++ b/packages/ui/src/health/map/overlay.tsx
@@ -8,6 +8,9 @@
*/
import { performanceSentence, scoreText } from "./lens";
+import type { MapArea } from "./areas";
+import type { AreaAnalysed } from "./fills";
+import type { MapCanvasLabels } from "./canvas-labels";
import type { CodeHealthMapFile, CodeHealthOverlay } from "./types";
/** Match rings drawn at once. Beyond this the field is the answer, not a mark. */
@@ -37,6 +40,77 @@ const CARD_GAP = 16;
* usually left the node it was asking about. The card flips to the other side
* of the pointer near an edge so it is never clipped by the container.
*/
+/** What a folder's colour was read from, in its own counts. */
+function analysedLine(a: AreaAnalysed | null, labels: MapCanvasLabels): string {
+ if (!a) return labels.notLoaded;
+ const read = labels.analysedFiles(a.analysed, a.loaded);
+ if (a.flagged === undefined || a.analysed === 0) return read;
+ return `${labels.flaggedFiles(a.flagged, a.analysed)} · ${read}`;
+}
+
+/** Where a card opens beside the pointer, flipped near an edge. */
+function cardPosition(x: number, y: number, width: number, height: number) {
+ const left = x + CARD_GAP + CARD_W > width ? x - CARD_GAP - CARD_W : x + CARD_GAP;
+ const top = y + CARD_GAP + CARD_H > height ? y - CARD_GAP - CARD_H : y + CARD_GAP;
+ return { left: Math.max(0, left), top: Math.max(0, top) };
+}
+
+const CARD =
+ "pointer-events-none absolute z-20 w-max max-w-[300px] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 shadow-md";
+
+/**
+ * An area under the pointer: its name, the lens's figure, and how big it is.
+ * A slot is the files sitting directly in the area, beside its sub-areas.
+ */
+export function AreaHoverCard({
+ area,
+ name,
+ slot,
+ figure,
+ lensLabel,
+ analysed,
+ lensCoversFiles,
+ labels,
+ x,
+ y,
+ width,
+ height,
+}: {
+ labels: MapCanvasLabels;
+ area: MapArea;
+ name: string;
+ slot: boolean;
+ figure: string | null;
+ lensLabel: string;
+ /** How many of its loaded files the lens analysed, or null when none are loaded. */
+ analysed: AreaAnalysed | null;
+ /** The lens tells analysed files apart, so the card says how many it read. */
+ lensCoversFiles: boolean;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}) {
+ const files = slot ? area.directFileCount : area.fileCount;
+ return (
+ <div data-testid="map-area-card" className={CARD} style={cardPosition(x, y, width, height)}>
+ <div className="break-all font-mono text-xs font-medium leading-snug text-[var(--color-text-primary)]">
+ {slot ? labels.directFiles(name || area.path) : name}
+ </div>
+ <div className="mt-0.5 text-[10px] leading-tight text-[var(--color-text-tertiary)] tabular-nums">
+ {labels.fileCount(files)}
+ {!slot && figure ? ` · ${lensLabel.toLowerCase()} ${figure}` : ""}
+ {!slot ? ` · ${labels.openHint}` : ""}
+ </div>
+ {lensCoversFiles && !slot ? (
+ <div className="mt-0.5 text-[10px] leading-tight text-[var(--color-text-tertiary)] tabular-nums">
+ {analysedLine(analysed, labels)}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
export function HoverCard({
file,
overlay,
@@ -57,8 +131,6 @@ export function HoverCard({
const slash = file.file_path.lastIndexOf("/");
const dir = slash < 0 ? "" : file.file_path.slice(0, slash + 1);
const name = slash < 0 ? file.file_path : file.file_path.slice(slash + 1);
- const left = x + CARD_GAP + CARD_W > width ? x - CARD_GAP - CARD_W : x + CARD_GAP;
- const top = y + CARD_GAP + CARD_H > height ? y - CARD_GAP - CARD_H : y + CARD_GAP;
return (
<div
data-testid="map-hover-card"
@@ -66,8 +138,8 @@ export function HoverCard({
// card. The name is the answer to "what am I pointing at" and is never
// truncated: it wraps instead, and the directory above it is the part
// that gives way when the path is long.
- className="pointer-events-none absolute z-20 w-max max-w-[300px] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 shadow-md"
- style={{ left: Math.max(0, left), top: Math.max(0, top) }}
+ className={CARD}
+ style={cardPosition(x, y, width, height)}
>
{dir ? (
<div className="truncate font-mono text-[10px] leading-tight text-[var(--color-text-tertiary)]">
diff --git a/packages/ui/src/health/map/paint.ts b/packages/ui/src/health/map/paint.ts
index 9ae12c7f8..d95dcc7fb 100644
--- a/packages/ui/src/health/map/paint.ts
+++ b/packages/ui/src/health/map/paint.ts
@@ -1,166 +1,97 @@
/**
* Painting the field onto a canvas, kept apart from React.
*
- * The field is a few thousand discs that only change colour when the lens
- * changes and only change place when the camera moves. So the nodes are
- * grouped once into batches that share a fill, each batch becomes one
- * `Path2D` in world units, and a frame is a transform plus one `fill()` per
- * batch: the browser rasterizes the discs and no JavaScript runs per node.
- * Hover, selection, search and the keyboard cursor paint on a second canvas
- * above it, so pointing at a node never repaints the field.
- *
- * Colours arrive as CSS strings (token `var()`s and `color-mix()`es, so the
- * key and the field read one source) and are resolved to RGB once per theme
- * through the browser's own computed style.
- */
-
-import type { FileNode, Galaxy } from "./types";
-
-export type Rgb = readonly [number, number, number];
-
-const FALLBACK: Rgb = [128, 128, 128];
-
-/** Parse a computed colour: `rgb()`, `rgba()`, `color(srgb …)` or hex. */
-export function parseCssColour(value: string): Rgb | null {
- const v = value.trim();
- let m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(v);
- if (m) return [Number(m[1]), Number(m[2]), Number(m[3])];
- m = /^color\(srgb\s+([\d.e-]+)\s+([\d.e-]+)\s+([\d.e-]+)/i.exec(v);
- if (m) return [Number(m[1]) * 255, Number(m[2]) * 255, Number(m[3]) * 255];
- m = /^#([0-9a-f]{6})$/i.exec(v);
- if (m) {
- const n = parseInt(m[1]!, 16);
- return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
- }
- return null;
-}
-
-/**
- * A cached CSS-colour-to-RGB resolver bound to one element, so `var()` reads
- * the theme in force there. Build a new one when the theme flips.
+ * Two kinds of mark. Area discs are a few hundred at most and are drawn in
+ * screen space every frame, so a hairline stays a hairline at any zoom. File
+ * dots are thousands that only change colour when the lens changes and only
+ * change place when the camera moves, so they are grouped once per host into
+ * batches that share a fill, each batch is one `Path2D` in world units, and a
+ * frame fills the batches of the hosts it shows: the browser rasterizes the
+ * dots and no JavaScript runs per file. Hover, selection, search and the
+ * keyboard cursor paint on a second canvas above, so pointing at something
+ * never repaints the field.
*/
-export function createColourResolver(host: HTMLElement | null): (css: string) => Rgb {
- const cache = new Map<string, Rgb>();
- let probe: HTMLSpanElement | null = null;
- return (css) => {
- const hit = cache.get(css);
- if (hit) return hit;
- let rgb: Rgb | null = parseCssColour(css);
- if (!rgb && host && typeof getComputedStyle !== "undefined") {
- if (!probe) {
- probe = document.createElement("span");
- probe.style.display = "none";
- host.appendChild(probe);
- }
- probe.style.color = "";
- probe.style.color = css;
- rgb = parseCssColour(getComputedStyle(probe).color);
- }
- const out = rgb ?? FALLBACK;
- cache.set(css, out);
- return out;
- };
-}
-export function rgba([r, g, b]: Rgb, a = 1): string {
- return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;
-}
-
-export function mixRgb(a: Rgb, b: Rgb, t: number): Rgb {
- return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
-}
+import type { Host, PlacedFiles } from "./area-layout";
+import type { DiscView, FieldView } from "./area-view";
+import { mixRgb, rgba, type Palette, type Rgb } from "./colour";
+import type { FileNode } from "./types";
-/** Theme colours the field paints with besides the node fills. */
-export interface Palette {
- ink: Rgb;
- ring: Rgb;
- accent: Rgb;
-}
+export {
+ createColourResolver,
+ mixRgb,
+ parseCssColour,
+ resolvePalette,
+ rgba,
+ type Palette,
+ type Rgb,
+} from "./colour";
-export function resolvePalette(resolve: (css: string) => Rgb): Palette {
- return {
- ink: resolve("var(--color-text-primary)"),
- ring: resolve("var(--color-border-default)"),
- accent: resolve("var(--color-accent-primary)"),
- };
-}
-
-/** The laid-out field flattened for drawing: one index space for every node. */
+/** The placed files flattened for drawing: one index space for every node. */
export interface FieldScene {
- galaxies: Galaxy[];
nodes: FileNode[];
- /** Node index -> galaxy index. */
- galaxyOf: Int32Array;
+ hosts: Host[];
+ hostIndex: ReadonlyMap<string, number>;
+ /** Node index -> host index. */
+ hostOfNode: Int32Array;
/** Path -> node index. */
index: Map<string, number>;
}
-export function buildScene(galaxies: Galaxy[]): FieldScene {
- const nodes: FileNode[] = [];
- const owner: number[] = [];
- galaxies.forEach((g, gi) => {
- for (const nd of g.nodes) {
- nodes.push(nd);
- owner.push(gi);
- }
- });
+export function buildScene(placed: PlacedFiles): FieldScene {
const index = new Map<string, number>();
- nodes.forEach((nd, i) => index.set(nd.file.file_path, i));
- return { galaxies, nodes, galaxyOf: Int32Array.from(owner), index };
+ placed.nodes.forEach((nd, i) => index.set(nd.file.file_path, i));
+ return { nodes: placed.nodes, hosts: placed.hosts, hostIndex: placed.hostIndex, hostOfNode: placed.hostOfNode, index };
}
-/** One fill: the nodes that share a colour (or a colour pair, mid-tween). */
+/** One fill within one host: the nodes that share a colour (or a pair, mid-tween). */
export interface Batch {
+ host: number;
from: Rgb;
to: Rgb;
/** Glow strength at each end, 0 or 1: only files that need attention glow. */
glowFrom: number;
glowTo: number;
- /** Nodes outside the focused galaxy, drawn dimmed. */
- faded: boolean;
nodes: Int32Array;
path: Path2D | null;
glow: Path2D | null;
}
/**
- * Group the nodes by what they are filled with. Pure apart from `resolve`,
- * which a test can stub. `from` is the previous lens's fills during a tween,
- * or null at rest; `loud` says whether a fill marks a problem.
+ * Group each host's nodes by what they are filled with, so a frame fills one
+ * path per colour per drawn host. Pure apart from `resolve`, which a test can
+ * stub. `from` is the previous lens's fills during a tween, or null at rest.
*/
export function groupBatches(
scene: FieldScene,
to: readonly string[],
from: readonly string[] | null,
- focus: number,
loud: (fill: string) => boolean,
resolve: (css: string) => Rgb,
): Batch[] {
- const groups = new Map<string, { list: number[]; f: string; t: string; faded: boolean }>();
+ const groups = new Map<string, { list: number[]; host: number; f: string; t: string }>();
for (let i = 0; i < scene.nodes.length; i++) {
const t = to[i]!;
const f = from ? from[i]! : t;
- const faded = focus >= 0 && scene.galaxyOf[i] !== focus;
- const key = `${faded ? 1 : 0}\u0000${f}\u0000${t}`;
+ const host = scene.hostOfNode[i]!;
+ const key = `${host}\u0000${f}\u0000${t}`;
const g = groups.get(key);
if (g) g.list.push(i);
- else groups.set(key, { list: [i], f, t, faded });
+ else groups.set(key, { list: [i], host, f, t });
}
const out: Batch[] = [];
for (const g of groups.values()) {
out.push({
+ host: g.host,
from: resolve(g.f),
to: resolve(g.t),
glowFrom: loud(g.f) ? 1 : 0,
glowTo: loud(g.t) ? 1 : 0,
- faded: g.faded,
nodes: Int32Array.from(g.list),
path: null,
glow: null,
});
}
- // Dimmed galaxies first, so the focused one paints over its neighbours.
- out.sort((a, b) => Number(b.faded) - Number(a.faded));
return out;
}
@@ -204,20 +135,24 @@ export interface View {
dpr: number;
}
-/** What one frame paints with: the field, the camera, the box, the theme. */
+/** What one frame paints with: the files, the camera, the box, the theme. */
export interface Frame {
scene: FieldScene;
cam: Cam;
view: View;
palette: Palette;
- /** Index of the focused galaxy, or -1. */
- focus: number;
+ /** Which areas show as what, decided for this camera. */
+ field: FieldView;
+ /** An area's resolved fill under the active lens. */
+ areaRgb: (path: string) => Rgb;
}
-/** Opacity of a node outside the focused galaxy. */
-const FADED_ALPHA = 0.16;
/** Peak opacity of a glow. Soft enough to read as light, not as a ring. */
const GLOW_ALPHA = 0.16;
+/** A solid area disc: the lens colour, a touch quieter than a file dot. */
+const CLOSED_ALPHA = 0.82;
+/** An own-files slot not yet showing its files. */
+const SLOT_ALPHA = 0.45;
function screen(cam: Cam, view: View, x: number, y: number): [number, number] {
return [view.w / 2 + (x - cam.cx) * cam.scale, view.h / 2 + (y - cam.cy) * cam.scale];
@@ -234,73 +169,59 @@ function clear(ctx: CanvasRenderingContext2D, view: View): void {
ctx.clearRect(0, 0, view.w, view.h);
}
-/** How a galaxy's cloud and ring read: dimmed, focused, or at rest. */
-function galaxyTone(gi: number, focus: number): { cloud: number; ring: number; width: number } {
- if (focus < 0) return { cloud: 0.04, ring: 0.6, width: 1 };
- if (gi === focus) return { cloud: 0.04, ring: 1, width: 1.25 };
- return { cloud: 0.012, ring: 0.3, width: 1 };
-}
-
/**
- * Galaxies are neutral: a soft cloud and a hairline, and no hue, because the
- * nodes inside already speak in red, amber and green.
+ * One area disc. A solid disc carries the lens colour; an open one is a ring
+ * with a breath of ink, so what is inside it does the talking.
*/
-function drawGalaxies(ctx: CanvasRenderingContext2D, f: Frame): void {
- const { cam, view, palette } = f;
- f.scene.galaxies.forEach((g, gi) => {
- const [sx, sy] = screen(cam, view, g.cx, g.cy);
- const R = g.R * cam.scale;
- if (R < 1 || offscreen(view, sx, sy, R)) return;
- const tone = galaxyTone(gi, f.focus);
- const cloud = ctx.createRadialGradient(sx, sy, 0, sx, sy, R * 1.12);
- cloud.addColorStop(0, rgba(palette.ink, tone.cloud));
- cloud.addColorStop(1, rgba(palette.ink, 0));
- ctx.fillStyle = cloud;
- ctx.beginPath();
- ctx.arc(sx, sy, R * 1.12, 0, Math.PI * 2);
+function drawDisc(ctx: CanvasRenderingContext2D, f: Frame, d: DiscView): void {
+ const { palette } = f;
+ ctx.beginPath();
+ ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2);
+ if (d.state === "open") {
+ ctx.fillStyle = rgba(palette.ink, 0.025);
ctx.fill();
- ctx.lineWidth = tone.width;
- ctx.strokeStyle = rgba(palette.ring, tone.ring);
- ctx.beginPath();
- ctx.arc(sx, sy, R, 0, Math.PI * 2);
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = rgba(palette.ring, 0.7);
ctx.stroke();
- });
+ return;
+ }
+ ctx.fillStyle = rgba(f.areaRgb(d.path), d.state === "slot" ? SLOT_ALPHA : CLOSED_ALPHA);
+ ctx.fill();
+ if (d.r >= 6) {
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = rgba(palette.ring, d.state === "slot" ? 0.35 : 0.6);
+ ctx.stroke();
+ }
}
-/** One batch at tween progress `t`: its glow, if it has one, then its discs. */
+/** One batch at tween progress `t`: its glow, if it has one, then its dots. */
function drawBatch(ctx: CanvasRenderingContext2D, b: Batch, t: number): void {
if (!b.path) return;
- const alpha = b.faded ? FADED_ALPHA : 1;
const fill = rgba(t >= 1 ? b.to : mixRgb(b.from, b.to, t));
const glow = b.glowFrom + (b.glowTo - b.glowFrom) * t;
ctx.fillStyle = fill;
if (b.glow && glow > 0) {
- ctx.globalAlpha = GLOW_ALPHA * glow * alpha;
+ ctx.globalAlpha = GLOW_ALPHA * glow;
ctx.fill(b.glow);
}
- ctx.globalAlpha = alpha;
+ ctx.globalAlpha = 1;
ctx.fill(b.path);
}
/**
- * The base layer: each galaxy's nebula and hairline, then the nodes.
- * `t` is the lens tween's progress, 1 at rest.
+ * The base layer: the area discs, then the file dots of every host this
+ * frame draws. `t` is the lens tween's progress, 1 at rest.
*/
-export function drawField(
- ctx: CanvasRenderingContext2D,
- f: Frame,
- batches: Batch[],
- t: number,
-): void {
- const { cam, view } = f;
+export function drawField(ctx: CanvasRenderingContext2D, f: Frame, batches: Batch[], t: number): void {
+ const { cam, view, field } = f;
clear(ctx, view);
- drawGalaxies(ctx, f);
+ for (const d of field.discs) drawDisc(ctx, f, d);
const s = cam.scale;
- const d = view.dpr;
- ctx.setTransform(d * s, 0, 0, d * s, d * (view.w / 2 - cam.cx * s), d * (view.h / 2 - cam.cy * s));
- for (const b of batches) drawBatch(ctx, b, t);
+ const dp = view.dpr;
+ ctx.setTransform(dp * s, 0, 0, dp * s, dp * (view.w / 2 - cam.cx * s), dp * (view.h / 2 - cam.cy * s));
+ for (const b of batches) if (field.drawnHosts[b.host]) drawBatch(ctx, b, t);
ctx.globalAlpha = 1;
- ctx.setTransform(d, 0, 0, d, 0, 0);
+ ctx.setTransform(dp, 0, 0, dp, 0, 0);
}
export interface Marks {
@@ -308,16 +229,20 @@ export interface Marks {
hovered: number;
cursor: number;
matches: readonly number[];
+ /** Discs to ring this frame, when drawn. */
+ selectedArea: DiscView | null;
+ hoveredArea: DiscView | null;
+ cursorArea: DiscView | null;
/** A node's resolved fill, for repainting it above its neighbours. */
fillOf: (i: number) => Rgb;
/** Smallest drawn radius, in px, so a ring hugs a floored dot. */
floorPx: number;
}
-/** Screen centre and radius of node `i`, or null when it does not exist. */
+/** Screen centre and radius of node `i`, or null when it is not drawn. */
function nodeOnScreen(f: Frame, i: number, floorPx: number): [number, number, number] | null {
const nd = f.scene.nodes[i];
- if (!nd) return null;
+ if (!nd || !f.field.drawnHosts[f.scene.hostOfNode[i]!]) return null;
const [sx, sy] = screen(f.cam, f.view, nd.x, nd.y);
return [sx, sy, Math.max(nd.r * f.cam.scale, floorPx)];
}
@@ -328,16 +253,19 @@ function nodeOnScreen(f: Frame, i: number, floorPx: number): [number, number, nu
*/
export function drawMarks(ctx: CanvasRenderingContext2D, f: Frame, marks: Marks): void {
clear(ctx, f.view);
- const ring = (i: number, pad: number, width: number, colour: string, dash: number[] = []) => {
- const at = nodeOnScreen(f, i, marks.floorPx);
- if (!at || offscreen(f.view, at[0], at[1], at[2] + pad)) return;
+ const circle = (x: number, y: number, r: number, width: number, colour: string, dash: number[] = []) => {
+ if (offscreen(f.view, x, y, r)) return;
ctx.setLineDash(dash);
ctx.lineWidth = width;
ctx.strokeStyle = colour;
ctx.beginPath();
- ctx.arc(at[0], at[1], at[2] + pad, 0, Math.PI * 2);
+ ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.stroke();
};
+ const ring = (i: number, pad: number, width: number, colour: string, dash: number[] = []) => {
+ const at = nodeOnScreen(f, i, marks.floorPx);
+ if (at) circle(at[0], at[1], at[2] + pad, width, colour, dash);
+ };
const solid = (i: number, grow: number) => {
const at = nodeOnScreen(f, i, marks.floorPx);
if (!at) return;
@@ -347,10 +275,15 @@ export function drawMarks(ctx: CanvasRenderingContext2D, f: Frame, marks: Marks)
ctx.fill();
};
const accent = rgba(f.palette.accent);
+ const ink = rgba(f.palette.ink, 0.85);
+ const { hoveredArea: hov, selectedArea: sel, cursorArea: cur } = marks;
+ if (hov && hov.path !== sel?.path) circle(hov.x, hov.y, hov.r + 1, 1.5, ink);
+ if (sel) circle(sel.x, sel.y, sel.r + 1.5, 2, accent);
+ if (cur) circle(cur.x, cur.y, cur.r + 4, 2, accent, [3, 2]);
for (const i of marks.matches) ring(i, 2.5, 1.5, accent);
if (marks.hovered >= 0 && marks.hovered !== marks.selected) {
solid(marks.hovered, 1);
- ring(marks.hovered, 2, 1.5, rgba(f.palette.ink, 0.85));
+ ring(marks.hovered, 2, 1.5, ink);
}
if (marks.selected >= 0) {
solid(marks.selected, 0);
diff --git a/packages/ui/src/health/map/scope-note.tsx b/packages/ui/src/health/map/scope-note.tsx
index ff8ee88fd..3c6562d01 100644
--- a/packages/ui/src/health/map/scope-note.tsx
+++ b/packages/ui/src/health/map/scope-note.tsx
@@ -13,6 +13,7 @@
import type { ReactNode } from "react";
import type { MapScope } from "./types";
+import type { MapCanvasLabels } from "./canvas-labels";
const ACTION =
"pointer-events-auto rounded px-1 text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] disabled:cursor-wait disabled:opacity-60";
@@ -162,3 +163,91 @@ export function MapScopeNote({
</div>
);
}
+
+/**
+ * The lazily loaded field's scope: how many files are drawn so far against
+ * the repository, and how to see the rest. Every area is complete once loaded,
+ * so the only thing to say is how far the reader has zoomed in.
+ */
+/**
+ * The groups the map holds out by default (tests, build files, ...), each a
+ * toggle that brings it back. The server names the groups and counts them;
+ * the host keeps which are brought back in the URL.
+ */
+export interface HeldGroups {
+ /** The held origins, in the server's order. */
+ default: readonly string[];
+ /** Files per held origin, repository-wide. */
+ counts: Readonly<Record<string, number>>;
+ /** Origins brought back. */
+ include: readonly string[];
+ onChange: (include: string[]) => void;
+}
+
+function HeldToggles({ groups, labels }: { groups: HeldGroups; labels: MapCanvasLabels }) {
+ const present = groups.default.filter((o) => (groups.counts[o] ?? 0) > 0);
+ if (present.length === 0) return null;
+ return (
+ <>
+ {present.map((origin) => {
+ const on = groups.include.includes(origin);
+ const name = labels.originName(origin);
+ const next = on ? groups.include.filter((o) => o !== origin) : [...groups.include, origin];
+ return (
+ <Part key={origin}>
+ <button
+ type="button"
+ onClick={() => groups.onChange(next)}
+ className={ACTION}
+ >
+ {on ? labels.hideHeld(name) : labels.showHeld(name, groups.counts[origin] ?? 0)}
+ </button>
+ </Part>
+ );
+ })}
+ </>
+ );
+}
+
+export function LoadedNote({
+ loaded,
+ total,
+ matches,
+ held,
+ labels,
+}: {
+ loaded: number;
+ total: number;
+ /** Search matches among the loaded files, or null with no search. */
+ matches: number | null;
+ held?: HeldGroups | undefined;
+ labels: MapCanvasLabels;
+}) {
+ return (
+ <div
+ data-testid="map-scope"
+ className="pointer-events-none absolute bottom-3 right-3 z-20 max-w-[64%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-right text-xs text-[var(--color-text-tertiary)] shadow-sm backdrop-blur-sm sm:max-w-[52%]"
+ >
+ {loaded === 0 ? (
+ <>
+ <span className="font-mono tabular-nums">{total.toLocaleString()}</span> files in folders ·
+ zoom into one to see its files
+ </>
+ ) : (
+ <>
+ <span className="font-mono tabular-nums">
+ {loaded.toLocaleString()} of {total.toLocaleString()}
+ </span>{" "}
+ files loaded{loaded < total ? " · zoom in for more" : ""}
+ </>
+ )}
+ {matches !== null ? (
+ <Part>
+ <span className="tabular-nums">{matches.toLocaleString()}</span>{" "}
+ {plural(matches, "match", "matches")} loaded
+ </Part>
+ ) : null}
+ {held ? <HeldToggles groups={held} labels={labels} /> : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/map/types.ts b/packages/ui/src/health/map/types.ts
index 3f37266e5..cda2fce6c 100644
--- a/packages/ui/src/health/map/types.ts
+++ b/packages/ui/src/health/map/types.ts
@@ -37,6 +37,8 @@ export interface CodeHealthMapFile {
/** Whether a performance detector runs on this file's language at all.
* `false` means nothing ever looked, which is not the same as clear. */
performance_analyzed?: boolean | null;
+ /** Git flags the file a hotspot; drives the hotspot health lens. */
+ is_hotspot?: boolean | null;
/** 0-100 churn percentile, drives the churn lens. */
churn_percentile?: number | null;
/** Reclaimable lines, drives the dead-code lens. */
@@ -61,15 +63,13 @@ export type CodeHealthOverlay =
| "coverage"
| "churn"
| "dead-code"
- | "security";
-
-/** One module = one galaxy: its files plus size aggregates. */
-export interface GalaxyAgg {
- module: string;
- files: CodeHealthMapFile[]; // NLOC-desc
- totalNloc: number;
- maxNloc: number;
-}
+ | "security"
+ /** Hotspot files in their health band, every other file grey. */
+ | "hotspot"
+ /** Area-level: who leads each folder. */
+ | "owner"
+ /** Area-level: share of a folder only one person has changed. */
+ | "knowledge";
export interface FileNode {
file: CodeHealthMapFile;
@@ -78,21 +78,6 @@ export interface FileNode {
r: number;
}
-export interface Galaxy {
- /** Grouping key: the module, a sub-folder, or a fold of small modules. */
- module: string;
- /** What the galaxy is called on the field. */
- label: string;
- /** Modules folded into this galaxy; 1 for an ordinary one. */
- members: number;
- cx: number;
- cy: number;
- R: number;
- fileCount: number;
- colorId: number;
- nodes: FileNode[];
-}
-
/**
* What the server drew and what it left out, as one object.
*
diff --git a/packages/ui/src/health/map/use-area-source.ts b/packages/ui/src/health/map/use-area-source.ts
new file mode 100644
index 000000000..cb44bfd3d
Binary files /dev/null and b/packages/ui/src/health/map/use-area-source.ts differ
diff --git a/packages/ui/src/health/map/use-field-canvas.ts b/packages/ui/src/health/map/use-field-canvas.ts
index f31dfd522..89d143104 100644
--- a/packages/ui/src/health/map/use-field-canvas.ts
+++ b/packages/ui/src/health/map/use-field-canvas.ts
@@ -5,8 +5,11 @@
*
* Everything a frame reads lives in one mutable loop state, so a frame never
* waits on React and React never re-renders for a frame. Callers mark which
- * layer changed with `invalidate`; a frame paints only those layers, and keeps
- * scheduling itself only while a camera flight or a lens recolor is running.
+ * layer changed with `invalidate`; a frame decides the semantic zoom for the
+ * current camera ({@link computeView}), paints only the layers that changed,
+ * and keeps scheduling itself only while a camera flight or a lens recolor is
+ * running. Once the camera rests, the frame tells the host what the view wants
+ * loaded next.
*/
import { useCallback, useEffect, useRef, useState } from "react";
@@ -15,6 +18,9 @@ import type { MutableRefObject, RefObject } from "react";
import { useThemeVersion } from "../../shared/use-theme-tokens";
import { easeInOutCubic, interpolateCamera } from "../../zoom/camera-anim";
import { isLoudFill } from "../tokens";
+import type { AreaIndex } from "./areas";
+import type { AreaGeometry } from "./area-layout";
+import { computeView, type DiscView, type FieldView } from "./area-view";
import { NEUTRAL_FILL } from "./lens";
import { WORLD, fitCamera } from "./layout";
import { placeLabels } from "./labels";
@@ -50,17 +56,29 @@ export interface Tween {
dur: number;
}
+/** What the view asks the host to load, reported once the camera rests. */
+export interface Wants {
+ children: string[];
+ files: string[];
+}
+
/** What the frame loop paints, refreshed by the component on every render. */
export interface FieldLive {
+ index: AreaIndex;
+ geo: AreaGeometry;
scene: FieldScene;
fills: string[];
- focusIdx: number;
+ areaFill: ReadonlyMap<string, string>;
marked: number[];
selectedIdx: number;
cursorIdx: number;
hoverIdx: number;
+ selectedArea: string | null;
+ hoverArea: string | null;
+ cursorArea: string | null;
minNodeR: number;
- labelOrder: number[];
+ filesCovered: (path: string) => boolean;
+ onWants?: ((wants: Wants) => void) | undefined;
}
export interface Dirty {
@@ -86,6 +104,10 @@ export interface LoopState {
raf: number | null;
resolve: (css: string) => Rgb;
palette: Palette | null;
+ /** The semantic zoom the last frame drew, for picking. */
+ field: FieldView | null;
+ /** Last frame's draw time in ms, for the perf readout. */
+ frameMs: number;
}
export type Invalidate = (what?: Partial<Dirty>) => void;
@@ -114,6 +136,8 @@ function initialLoop(): LoopState {
raf: null,
resolve: () => [128, 128, 128],
palette: null,
+ field: null,
+ frameMs: 0,
};
}
@@ -153,14 +177,7 @@ function floorFor(st: LoopState, live: FieldLive): number {
}
function rebuild(st: LoopState, live: FieldLive, floor: number): void {
- st.batches = groupBatches(
- live.scene,
- live.fills,
- st.colour?.from ?? null,
- live.focusIdx,
- isLoudFill,
- st.resolve,
- );
+ st.batches = groupBatches(live.scene, live.fills, st.colour?.from ?? null, isLoudFill, st.resolve);
attachPaths(st.batches, live.scene, floor);
st.floor = floor;
st.stale = false;
@@ -170,7 +187,47 @@ function rebuild(st: LoopState, live: FieldLive, floor: number): void {
interface Layers {
base: RefObject<HTMLCanvasElement | null>;
top: RefObject<HTMLCanvasElement | null>;
- labels: MutableRefObject<(HTMLElement | null)[]>;
+ labels: MutableRefObject<Map<string, HTMLElement>>;
+ shownLabels: Set<HTMLElement>;
+}
+
+const discOf = (field: FieldView, path: string | null): DiscView | null =>
+ path === null ? null : (field.discs.find((d) => d.path === path && d.state !== "slot") ?? null);
+
+/** The semantic zoom for this camera: recomputed when the camera or the field moved. */
+function decideField(st: LoopState, live: FieldLive, moved: boolean): FieldView {
+ if (!moved && !st.dirty.base && st.field) return st.field;
+ return computeView({
+ index: live.index,
+ geo: live.geo,
+ hosts: live.scene.hosts,
+ hostIndex: live.scene.hostIndex,
+ filesCovered: live.filesCovered,
+ cam: st.cam,
+ view: st.view,
+ });
+}
+
+/** The top layer's rings, for what is selected, hovered, under the cursor or matched. */
+function paintMarks(top: CanvasRenderingContext2D, st: LoopState, live: FieldLive, frame: Frame): void {
+ const { field } = frame;
+ drawMarks(top, frame, {
+ selected: live.selectedIdx,
+ hovered: live.hoverIdx,
+ cursor: live.cursorIdx,
+ matches: live.marked,
+ selectedArea: discOf(field, live.selectedArea),
+ hoveredArea: discOf(field, live.hoverArea),
+ cursorArea: discOf(field, live.cursorArea),
+ fillOf: (i) => st.resolve(live.fills[i] ?? NEUTRAL_FILL),
+ floorPx: MIN_NODE_PX,
+ });
+}
+
+/** Once the camera rests on a new view, tell the host what it wants loaded. */
+function reportWants(live: FieldLive, field: FieldView, settled: boolean): void {
+ const wants = field.wantChildren.length > 0 || field.wantFiles.length > 0;
+ if (settled && wants) live.onWants?.({ children: field.wantChildren, files: field.wantFiles });
}
/** One frame: advance the tweens, rebuild what went stale, paint what changed. */
@@ -184,37 +241,25 @@ function runFrame(st: LoopState, live: FieldLive, layers: Layers): boolean {
st.palette ??= resolvePalette(st.resolve);
if (st.stale && base) rebuild(st, live, floor);
+ const field = decideField(st, live, flight.moved);
+ const fieldChanged = field !== st.field;
+ st.field = field;
const frame: Frame = {
scene: live.scene,
cam: st.cam,
view: st.view,
palette: st.palette,
- focus: live.focusIdx,
+ field,
+ areaRgb: (path) => st.resolve(live.areaFill.get(path) ?? NEUTRAL_FILL),
};
- const moved = flight.moved;
- if (base && (st.dirty.base || moved)) drawField(base, frame, st.batches, colour.t);
- if (top && (st.dirty.top || moved)) {
- drawMarks(top, frame, {
- selected: live.selectedIdx,
- hovered: live.hoverIdx,
- cursor: live.cursorIdx,
- matches: live.marked,
- fillOf: (i) => st.resolve(live.fills[i] ?? NEUTRAL_FILL),
- floorPx: MIN_NODE_PX,
- });
- }
- if (st.dirty.labels || moved) {
- placeLabels({
- galaxies: live.scene.galaxies,
- order: live.labelOrder,
- focus: live.focusIdx,
- camera: st.cam,
- view: st.view,
- els: layers.labels.current,
- });
- }
+ if (base && (st.dirty.base || flight.moved)) drawField(base, frame, st.batches, colour.t);
+ if (top && (st.dirty.top || fieldChanged)) paintMarks(top, st, live, frame);
+ if (st.dirty.labels || fieldChanged) placeLabels(field, layers.labels.current, st.view, layers.shownLabels);
st.dirty = { base: false, top: false, labels: false };
- return flight.animating || colour.animating;
+ st.frameMs = now() - t0;
+ const animating = flight.animating || colour.animating;
+ reportWants(live, field, !animating && fieldChanged);
+ return animating;
}
/** Size both canvases to `w` by `h` CSS px at the current pixel ratio. */
@@ -305,7 +350,8 @@ function useRepaintTriggers(
invalidate: Invalidate,
): void {
const themeVersion = useThemeVersion();
- const { scene, fills, focusIdx, marked, selectedIdx, cursorIdx, hoverIdx } = live;
+ const { scene, fills, areaFill, geo, marked, selectedIdx, cursorIdx, hoverIdx } = live;
+ const { selectedArea, hoverArea, cursorArea } = live;
useEffect(() => {
const st = loop.current;
st.resolve = createColourResolver(container.current);
@@ -315,12 +361,11 @@ function useRepaintTriggers(
}, [themeVersion, container, loop, invalidate]);
useEffect(() => {
- // A new feed is a new field: no tween from the old one's colours.
+ // New files are a new set of paths: no tween from the old colours.
const st = loop.current;
st.shownFills = null;
st.colour = null;
st.stale = true;
- if (!st.userMoved && st.view.w > 0) st.cam = fitCamera(st.view.w, st.view.h);
invalidate();
}, [scene, loop, invalidate]);
@@ -335,14 +380,14 @@ function useRepaintTriggers(
invalidate();
}, [fills, reducedMotion, loop, invalidate]);
+ // A finished or failed load changes what the view should ask for next.
useEffect(() => {
- loop.current.stale = true;
invalidate();
- }, [focusIdx, loop, invalidate]);
+ }, [areaFill, geo, live.filesCovered, invalidate]);
useEffect(() => {
invalidate({ top: true });
- }, [marked, selectedIdx, cursorIdx, hoverIdx, invalidate]);
+ }, [marked, selectedIdx, cursorIdx, hoverIdx, selectedArea, hoverArea, cursorArea, invalidate]);
useEffect(() => {
invalidate({ labels: true });
@@ -353,7 +398,7 @@ export function useFieldCanvas(opts: {
container: RefObject<HTMLElement | null>;
base: RefObject<HTMLCanvasElement | null>;
top: RefObject<HTMLCanvasElement | null>;
- labels: MutableRefObject<(HTMLElement | null)[]>;
+ labels: MutableRefObject<Map<string, HTMLElement>>;
minHeight: number;
live: FieldLive;
reducedMotion: boolean;
@@ -364,7 +409,7 @@ export function useFieldCanvas(opts: {
const loop = useRef<LoopState>(initialLoop());
const liveRef = useRef(live);
liveRef.current = live;
- const layers = useRef<Layers>({ base, top, labels }).current;
+ const layers = useRef<Layers>({ base, top, labels, shownLabels: new Set() }).current;
const [ready, setReady] = useState(false);
const frame = useCallback(() => {
diff --git a/packages/ui/src/health/map/use-field-model.ts b/packages/ui/src/health/map/use-field-model.ts
index 41d4e7aa1..a8d75b214 100644
--- a/packages/ui/src/health/map/use-field-model.ts
+++ b/packages/ui/src/health/map/use-field-model.ts
@@ -1,42 +1,42 @@
"use client";
/**
- * The field as data: laid out once per feed, never per resize or lens, plus
- * the lens's fills and the search marks over it. Matching runs over the drawn
- * field only and produces a bounded list for the marks layer; neither the
- * layout nor the fills see the query, so typing repaints rings and nothing
- * else.
+ * The field as data: the area discs laid out once per hierarchy, the loaded
+ * files placed in them once per feed, and the lens's colours over both. None
+ * of it depends on the camera or the canvas size, and the search marks are
+ * computed apart from the fills, so typing repaints rings and nothing else.
*/
import { useMemo } from "react";
import { isLoudFill } from "../tokens";
+import type { AreaIndex } from "./areas";
+import { layoutAreas, layoutFiles } from "./area-layout";
+import { areaFills, fileFills } from "./fills";
import { buildHitGrid } from "./hit-test";
-import { layoutField } from "./layout";
-import type { OverlaySpec } from "./lens";
+import type { MapLens } from "./lens";
import { SEARCH_MARK_CAP } from "./overlay";
import { buildScene } from "./paint";
import type { CodeHealthMapFile } from "./types";
export function useFieldModel(
- files: CodeHealthMapFile[],
- spec: OverlaySpec,
+ index: AreaIndex,
+ files: readonly CodeHealthMapFile[],
+ lens: MapLens,
search: string | undefined,
highlightPaths: string[] | undefined,
) {
- const galaxies = useMemo(() => layoutField(files), [files]);
- const scene = useMemo(() => buildScene(galaxies), [galaxies]);
+ const geo = useMemo(() => layoutAreas(index), [index]);
+ const placed = useMemo(() => layoutFiles(files, index, geo), [files, index, geo]);
+ const scene = useMemo(() => buildScene(placed), [placed]);
const grid = useMemo(() => buildHitGrid(scene.nodes), [scene]);
const minNodeR = useMemo(
() => scene.nodes.reduce((m, n) => Math.min(m, n.r), Infinity),
[scene],
);
- // Galaxies biggest first, the order labels claim space in.
- const labelOrder = useMemo(
- () => galaxies.map((_, i) => i).sort((a, b) => galaxies[b]!.R - galaxies[a]!.R),
- [galaxies],
- );
- const fills = useMemo(() => scene.nodes.map((n) => spec.fill(n.file)), [scene, spec]);
+ const fold = useMemo(() => areaFills(index, lens, files), [index, lens, files]);
+ const areaFill = fold.fill;
+ const fills = useMemo(() => fileFills(scene, lens, areaFill), [scene, lens, areaFill]);
const attention = useMemo(() => fills.filter(isLoudFill).length, [fills]);
const query = (search ?? "").trim().toLowerCase();
@@ -56,5 +56,21 @@ export function useFieldModel(
return all.slice(0, SEARCH_MARK_CAP);
}, [highlightPaths, matches, scene]);
- return { galaxies, scene, grid, minNodeR, labelOrder, fills, attention, query, matches, marked };
+ return {
+ geo,
+ scene,
+ grid,
+ minNodeR,
+ areaFill,
+ areaAnalysed: fold.analysed,
+ areaText: fold.text,
+ fills,
+ attention,
+ unplaced: placed.unplaced,
+ query,
+ matches,
+ marked,
+ };
}
+
+export type FieldModel = ReturnType<typeof useFieldModel>;
diff --git a/packages/ui/src/health/map/use-map-camera.ts b/packages/ui/src/health/map/use-map-camera.ts
index 07242d67b..8420003b0 100644
--- a/packages/ui/src/health/map/use-map-camera.ts
+++ b/packages/ui/src/health/map/use-map-camera.ts
@@ -1,10 +1,12 @@
"use client";
/**
- * Moving the camera: flights, zoom steps, fitting the field, and focusing one
- * galaxy. Every way out of a focused galaxy is a state change only; the effect
- * here returns the camera, so a click, Escape and the breadcrumb all take the
- * same path.
+ * Moving the camera: flights, zoom steps, and framing the selected area.
+ *
+ * The camera follows the selection. Selecting an area is a state change only
+ * (the host keeps it in the URL); the effect here flies to whatever area is
+ * selected once its disc is laid out, so a click, a breadcrumb, Backspace,
+ * Escape, a deep link and the browser's back button all take the same path.
*/
import { useCallback, useEffect, useRef } from "react";
@@ -12,16 +14,20 @@ import type { MutableRefObject } from "react";
import { frameRect, zoomAbout } from "../../zoom/camera";
import { flyDuration } from "../../zoom/camera-anim";
+import { ROOT_AREA } from "../../lib/areas";
+import type { AreaGeometry } from "./area-layout";
import { WORLD, fitCamera } from "./layout";
import type { Cam } from "./paint";
-import type { Galaxy } from "./types";
import { now, type Invalidate, type LoopState } from "./use-field-canvas";
/** How far out and in the camera may go, relative to the fitted view. */
const MIN_ZOOM = 0.5;
-const MAX_ZOOM = 80;
+/** Deep enough for a leaf ten directories down. */
+const MAX_ZOOM = 20_000;
/** One step of the zoom buttons and keys. */
export const ZOOM_STEP = 1.6;
+/** How much of the shorter side a framed area fills. */
+const FRAME_FILL = 0.9;
/** Keep the camera within zoom bounds and near the field. */
export function clampCam(st: LoopState, c: Cam): Cam {
@@ -34,22 +40,20 @@ export function clampCam(st: LoopState, c: Cam): Cam {
export interface MapCamera {
zoomBy: (factor: number) => void;
- fitView: () => void;
- /** Focus a galaxy, or leave focus with `null`. */
- focusOn: (module: string | null) => void;
- /** Leave any focus and show the whole field. */
- fitAll: () => void;
+ /** Frame the selected area again, after the reader panned away. */
+ reframe: () => void;
}
export function useMapCamera(opts: {
loop: MutableRefObject<LoopState>;
invalidate: Invalidate;
reducedMotion: boolean;
- galaxies: Galaxy[];
- focusModule: string | null;
- setFocusModule: (module: string | null) => void;
+ geo: AreaGeometry;
+ /** The selected area; the camera frames it. */
+ area: string;
+ ready: boolean;
}): MapCamera {
- const { loop, invalidate, reducedMotion, galaxies, focusModule, setFocusModule } = opts;
+ const { loop, invalidate, reducedMotion, geo, area, ready } = opts;
/** Move the camera, flown unless the reader asked for no motion. */
const flyTo = useCallback(
@@ -68,11 +72,32 @@ export function useMapCamera(opts: {
[loop, invalidate, reducedMotion],
);
- const fitView = useCallback(() => {
- const st = loop.current;
- st.userMoved = false;
- flyTo(fitCamera(st.view.w, st.view.h));
- }, [loop, flyTo]);
+ const frameArea = useCallback(
+ (path: string, animate: boolean) => {
+ const st = loop.current;
+ if (st.view.w === 0) return false;
+ if (path === ROOT_AREA) {
+ st.userMoved = false;
+ flyTo(fitCamera(st.view.w, st.view.h), animate);
+ return true;
+ }
+ const c = geo.circles.get(path);
+ if (!c) return false;
+ st.userMoved = true;
+ flyTo(frameRect(st.view, { x: c.x - c.r, y: c.y - c.r, w: 2 * c.r, h: 2 * c.r }, FRAME_FILL), animate);
+ return true;
+ },
+ [geo, loop, flyTo],
+ );
+
+ // Fly to the selection whenever it changes, and once more when a deep-linked
+ // area's disc first appears. The first framing jumps rather than flies, so a
+ // shared link opens where it points instead of animating in from the root.
+ const framed = useRef<string | null>(null);
+ useEffect(() => {
+ if (!ready || framed.current === area) return;
+ if (frameArea(area, framed.current !== null)) framed.current = area;
+ }, [area, ready, frameArea]);
const zoomBy = useCallback(
(factor: number) => {
@@ -83,28 +108,9 @@ export function useMapCamera(opts: {
[loop, flyTo],
);
- const focusOn = useCallback(
- (module: string | null) => {
- setFocusModule(module);
- const g = module ? galaxies.find((x) => x.module === module) : null;
- if (!g) return;
- loop.current.userMoved = true;
- flyTo(frameRect(loop.current.view, { x: g.cx - g.R, y: g.cy - g.R, w: 2 * g.R, h: 2 * g.R }, 0.9));
- },
- [galaxies, loop, flyTo, setFocusModule],
- );
-
- const fitAll = useCallback(() => {
- if (focusModule) setFocusModule(null);
- else fitView();
- }, [focusModule, fitView, setFocusModule]);
-
- // Leaving a galaxy returns the camera to the whole field.
- const lastFocus = useRef<string | null>(null);
- useEffect(() => {
- if (lastFocus.current && !focusModule) fitView();
- lastFocus.current = focusModule;
- }, [focusModule, fitView]);
+ const reframe = useCallback(() => {
+ frameArea(area, true);
+ }, [area, frameArea]);
- return { zoomBy, fitView, focusOn, fitAll };
+ return { zoomBy, reframe };
}
diff --git a/packages/ui/src/health/map/use-map-keyboard.ts b/packages/ui/src/health/map/use-map-keyboard.ts
index d50342773..1caf6c5d9 100644
--- a/packages/ui/src/health/map/use-map-keyboard.ts
+++ b/packages/ui/src/health/map/use-map-keyboard.ts
@@ -2,132 +2,143 @@
/**
* The keyboard model: one tab stop reaches the whole field. Arrows move over
- * modules, Enter descends into one, arrows then move over its files, Enter
- * selects one. The alternative is a tab stop per node, which is thousands.
+ * what is inside the selected area (its sub-areas, then its own files once
+ * they are loaded), Enter opens the area or the file under the cursor,
+ * Backspace climbs one level and Escape returns to the repository. The
+ * alternative is a tab stop per node, which is thousands.
*
- * Escape climbs out of a focused galaxy (and the file level) while the focus
- * is inside the field, and only then. When it does that it is consumed: the
- * open file drawer listens on the document in the capture phase, so the map
- * listens on the window in the capture phase and stops the key there, or one
- * press would both zoom out and close the drawer. An Escape the map has no
- * use for passes through untouched.
+ * Escape and Backspace are consumed only while the focus is inside the field
+ * and there is somewhere to climb to: the map listens on the window in the
+ * capture phase and stops the key there, so one press never both climbs and
+ * closes something behind the map. A key the map has no use for passes on.
*/
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from "react";
-import type { FileNode, Galaxy } from "./types";
+import { ROOT_AREA } from "../../lib/areas";
+import type { AreaIndex } from "./areas";
+import { displayChildren, displayParent } from "./area-paths";
+import type { FieldScene } from "./paint";
import { ZOOM_STEP, type MapCamera } from "./use-map-camera";
-export type KeyboardLevel = "module" | "file";
+export type CursorItem = { kind: "area"; path: string } | { kind: "file"; path: string };
/** Step `i` forward or back around a ring of `n`. */
const cycle = (i: number, n: number, forward: boolean) =>
n === 0 ? 0 : (i + (forward ? 1 : n - 1)) % n;
-const at = <T,>(list: readonly T[], i: number): T | null =>
- list[Math.min(i, Math.max(0, list.length - 1))] ?? null;
+/** What the cursor walks inside `area`: sub-areas biggest first, then own files. */
+export function cursorItems(index: AreaIndex, scene: FieldScene, area: string): CursorItem[] {
+ const items: CursorItem[] = displayChildren(index, area).map((path) => ({ kind: "area", path }));
+ const host = scene.hosts.find((h) => h.area === area && h.direct);
+ if (host) for (const i of host.nodes) items.push({ kind: "file", path: scene.nodes[i]!.file.file_path });
+ return items;
+}
/** Where the keyboard cursor is, and whether it is in use. */
-export function useKeyboardCursor(galaxies: Galaxy[]) {
- const [level, setLevel] = useState<KeyboardLevel>("module");
- const [moduleIdx, setModuleIdx] = useState(0);
- const [fileIdx, setFileIdx] = useState(0);
+export function useKeyboardCursor(index: AreaIndex, scene: FieldScene, area: string) {
+ const items = useMemo(() => cursorItems(index, scene, area), [index, scene, area]);
+ const [pos, setPos] = useState(0);
// Drawn only while the field has keyboard focus, so a reader using a
// pointer never sees a ring that answers to keys they are not using.
const [focused, setFocused] = useState(false);
- const galaxy = at(galaxies, moduleIdx);
- const node: FileNode | null = level === "file" && galaxy ? at(galaxy.nodes, fileIdx) : null;
- return { level, setLevel, moduleIdx, setModuleIdx, setFileIdx, focused, setFocused, galaxy, node };
+ useEffect(() => setPos(0), [area]);
+ const item = items[Math.min(pos, items.length - 1)] ?? null;
+ return { items, item, setPos, focused, setFocused };
}
export type KeyboardCursor = ReturnType<typeof useKeyboardCursor>;
-/** The camera keys, shared by both levels. True when the key was one. */
-function cameraKey(e: ReactKeyboardEvent, camera: MapCamera, kb: KeyboardCursor): boolean {
- if (e.key === "+" || e.key === "=") camera.zoomBy(ZOOM_STEP);
- else if (e.key === "-" || e.key === "_") camera.zoomBy(1 / ZOOM_STEP);
- else if (e.key === "0") {
- kb.setLevel("module");
- camera.fitAll();
- } else return false;
- e.preventDefault();
- return true;
-}
+const hasChord = (e: { ctrlKey: boolean; metaKey: boolean; altKey: boolean }) => e.ctrlKey || e.metaKey || e.altKey;
-export function useMapKeyboard(opts: {
- container: RefObject<HTMLElement | null>;
- kb: KeyboardCursor;
- galaxies: Galaxy[];
- camera: MapCamera;
- focusModule: string | null;
- setFocusModule: (module: string | null) => void;
- onSelect: (path: string) => void;
-}) {
- const { container, kb, galaxies, camera, focusModule, setFocusModule, onSelect } = opts;
-
- const onModuleKey = useCallback(
- (e: ReactKeyboardEvent, forward: boolean, back: boolean) => {
- if (forward || back) {
- e.preventDefault();
- kb.setModuleIdx((i) => cycle(i, galaxies.length, forward));
- } else if (e.key === "Enter" && kb.galaxy) {
- e.preventDefault();
- kb.setLevel("file");
- kb.setFileIdx(0);
- camera.focusOn(kb.galaxy.module);
- }
- },
- [kb, galaxies.length, camera],
- );
+/** What one key does in the field, or null when it is not the map's. Pure. */
+export type KeyAction =
+ | { kind: "zoom"; factor: number }
+ | { kind: "root" }
+ | { kind: "move"; forward: boolean }
+ | { kind: "open" };
- const onFileKey = useCallback(
- (e: ReactKeyboardEvent, forward: boolean, back: boolean) => {
- if (forward || back) {
- e.preventDefault();
- const n = kb.galaxy?.nodes.length ?? 0;
- kb.setFileIdx((i) => cycle(i, n, forward));
- } else if (e.key === "Enter" && kb.node) {
- e.preventDefault();
- onSelect(kb.node.file.file_path);
- } else if (e.key === "Backspace" || e.key === "Escape") {
- e.preventDefault();
- kb.setLevel("module");
- setFocusModule(null);
- }
- },
- [kb, onSelect, setFocusModule],
- );
+const KEY_ACTIONS: Record<string, KeyAction> = {
+ "+": { kind: "zoom", factor: ZOOM_STEP },
+ "=": { kind: "zoom", factor: ZOOM_STEP },
+ "-": { kind: "zoom", factor: 1 / ZOOM_STEP },
+ _: { kind: "zoom", factor: 1 / ZOOM_STEP },
+ "0": { kind: "root" },
+ ArrowRight: { kind: "move", forward: true },
+ ArrowDown: { kind: "move", forward: true },
+ ArrowLeft: { kind: "move", forward: false },
+ ArrowUp: { kind: "move", forward: false },
+ Enter: { kind: "open" },
+};
- const onKeyDown = useCallback(
- (e: ReactKeyboardEvent) => {
- if (cameraKey(e, camera, kb)) return;
- const forward = e.key === "ArrowRight" || e.key === "ArrowDown";
- const back = e.key === "ArrowLeft" || e.key === "ArrowUp";
- if (kb.level === "module") onModuleKey(e, forward, back);
- else onFileKey(e, forward, back);
- },
- [camera, kb, onModuleKey, onFileKey],
- );
+/** Browser zoom and other chords stay the browser's. */
+export function keyAction(e: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }): KeyAction | null {
+ return hasChord(e) ? null : (KEY_ACTIONS[e.key] ?? null);
+}
- const escape = useRef({ focused: false, fileLevel: false });
- escape.current = { focused: focusModule != null, fileLevel: kb.level === "file" };
- const { setLevel } = kb;
+/** Escape and Backspace climb, but only from inside the field and never out of a text box. */
+function climbKey(e: KeyboardEvent, container: HTMLElement | null): "root" | "up" | null {
+ if ((e.key !== "Escape" && e.key !== "Backspace") || hasChord(e)) return null;
+ const t = e.target;
+ if (!container || !(t instanceof Node) || !container.contains(t)) return null;
+ if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement) return null;
+ return e.key === "Escape" ? "root" : "up";
+}
+
+/**
+ * Escape returns to the repository and Backspace climbs one level, consumed
+ * in the capture phase so one press never also closes something behind.
+ */
+function useClimbKeys(
+ container: RefObject<HTMLElement | null>,
+ index: AreaIndex,
+ area: string,
+ onSelectArea: (path: string) => void,
+) {
+ const climb = useRef({ area, parent: displayParent(index, area), select: onSelectArea });
+ climb.current = { area, parent: displayParent(index, area), select: onSelectArea };
useEffect(() => {
if (typeof window === "undefined") return;
const onKey = (e: KeyboardEvent) => {
- if (e.key !== "Escape") return;
- const node = container.current;
- if (!node || !(e.target instanceof Node) || !node.contains(e.target)) return;
- if (!escape.current.focused && !escape.current.fileLevel) return;
+ const which = climbKey(e, container.current);
+ const { area: here, parent, select } = climb.current;
+ if (!which || here === ROOT_AREA) return;
e.stopPropagation();
e.preventDefault();
- setLevel("module");
- setFocusModule(null);
+ select(which === "root" ? ROOT_AREA : (parent ?? ROOT_AREA));
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
- }, [container, setLevel, setFocusModule]);
+ }, [container]);
+}
- return onKeyDown;
+export function useMapKeyboard(opts: {
+ container: RefObject<HTMLElement | null>;
+ kb: KeyboardCursor;
+ index: AreaIndex;
+ area: string;
+ camera: MapCamera;
+ onSelectArea: (path: string) => void;
+ onSelectFile: (path: string) => void;
+}) {
+ const { container, kb, index, area, camera, onSelectArea, onSelectFile } = opts;
+ useClimbKeys(container, index, area, onSelectArea);
+
+ return useCallback(
+ (e: ReactKeyboardEvent) => {
+ const action = keyAction(e);
+ if (!action || (action.kind === "open" && !kb.item)) return;
+ e.preventDefault();
+ if (action.kind === "zoom") camera.zoomBy(action.factor);
+ else if (action.kind === "root") onSelectArea(ROOT_AREA);
+ else if (action.kind === "move") {
+ // A pointer-focused field shows the cursor once the keys are used.
+ kb.setFocused(true);
+ kb.setPos((i) => cycle(i, kb.items.length, action.forward));
+ } else if (kb.item!.kind === "area") onSelectArea(kb.item!.path);
+ else onSelectFile(kb.item!.path);
+ },
+ [camera, kb, onSelectArea, onSelectFile],
+ );
}
diff --git a/packages/ui/src/health/map/use-map-pointer.ts b/packages/ui/src/health/map/use-map-pointer.ts
index d526957fb..bd1f3222d 100644
--- a/packages/ui/src/health/map/use-map-pointer.ts
+++ b/packages/ui/src/health/map/use-map-pointer.ts
@@ -17,9 +17,10 @@ import type {
} from "react";
import { panByScreen, screenToWorld, zoomAbout } from "../../zoom/camera";
+import { discAt } from "./area-view";
import { hitTest, type HitGrid } from "./hit-test";
import type { FieldScene } from "./paint";
-import type { CodeHealthMapFile, Galaxy } from "./types";
+import type { CodeHealthMapFile } from "./types";
import { MIN_NODE_PX, type Invalidate, type LoopState } from "./use-field-canvas";
import { clampCam } from "./use-map-camera";
@@ -28,11 +29,10 @@ const HIT_SLOP_PX = 3;
/** Movement before a press counts as a drag rather than a click. */
const DRAG_PX = 4;
-export interface Hover {
- file: CodeHealthMapFile;
- x: number;
- y: number;
-}
+/** What the pointer is over: a file dot, or an area's disc. */
+export type Hover =
+ | { kind: "file"; file: CodeHealthMapFile; x: number; y: number }
+ | { kind: "area"; path: string; slot: boolean; x: number; y: number };
interface Point {
x: number;
@@ -47,19 +47,6 @@ interface Drag extends Point {
const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);
-/** The smallest galaxy whose ring contains a world point. */
-function galaxyAt(galaxies: Galaxy[], wx: number, wy: number): string | null {
- let inside: string | null = null;
- let best = Infinity;
- for (const g of galaxies) {
- if (Math.hypot(wx - g.cx, wy - g.cy) <= g.R && g.R < best) {
- inside = g.module;
- best = g.R;
- }
- }
- return inside;
-}
-
/** Scroll distance in px, whatever unit the device reported it in. */
function wheelPixels(e: WheelEvent, pageHeight: number): number {
if (e.deltaMode === 1) return e.deltaY * 16;
@@ -67,17 +54,26 @@ function wheelPixels(e: WheelEvent, pageHeight: number): number {
return e.deltaY;
}
-/** Hover state, and a setter that only re-renders when the file changes. */
+/** Hover state, and a setter that only re-renders when the target changes. */
export function useHover(onHoverFile: ((file: CodeHealthMapFile | null) => void) | undefined) {
const [hover, setHover] = useState<Hover | null>(null);
- const hovered = useRef<CodeHealthMapFile | null>(null);
+ const current = useRef<string | null>(null);
const onHoverRef = useRef(onHoverFile);
onHoverRef.current = onHoverFile;
- const setHovered = useCallback((file: CodeHealthMapFile | null, x = 0, y = 0) => {
- if (hovered.current === file) return;
- hovered.current = file;
- setHover(file ? { file, x, y } : null);
- onHoverRef.current?.(file);
+ const setHovered = useCallback((next: Hover | null) => {
+ const key = next ? (next.kind === "file" ? `f:${next.file.file_path}` : `a:${next.slot}:${next.path}`) : null;
+ if (current.current === key) {
+ // A big disc is hovered for a long way: let its card follow, coarsely.
+ setHover((prev) =>
+ next && prev && Math.hypot(next.x - prev.x, next.y - prev.y) > 24 ? next : prev,
+ );
+ return;
+ }
+ const wasFile = current.current?.startsWith("f:") ?? false;
+ current.current = key;
+ setHover(next);
+ if (next?.kind === "file") onHoverRef.current?.(next.file);
+ else if (wasFile) onHoverRef.current?.(null);
}, []);
return { hover, setHovered };
}
@@ -89,14 +85,11 @@ export function useMapPointer(opts: {
scene: FieldScene;
grid: HitGrid;
minNodeR: number;
- galaxies: Galaxy[];
- focusModule: string | null;
- focusOn: (module: string | null) => void;
- onSelect: (path: string) => void;
- setHovered: (file: CodeHealthMapFile | null, x?: number, y?: number) => void;
+ onSelectFile: (path: string) => void;
+ onSelectArea: (path: string) => void;
+ setHovered: (hover: Hover | null) => void;
}) {
- const { container, loop, invalidate, scene, grid, minNodeR, galaxies, focusModule, focusOn, onSelect, setHovered } =
- opts;
+ const { container, loop, invalidate, scene, grid, minNodeR, onSelectFile, onSelectArea, setHovered } = opts;
const pointers = useRef(new Map<number, Point>());
const drag = useRef<Drag | null>(null);
// The reader is working in the map, so the wheel zooms instead of scrolling.
@@ -111,14 +104,21 @@ export function useMapPointer(opts: {
[container],
);
+ /** The drawn file or area disc under a point, as the last frame drew them. */
const pick = useCallback(
- (p: Point) => {
- const { cam, view } = loop.current;
+ (p: Point): Hover | null => {
+ const { cam, view, field } = loop.current;
+ if (!field) return null;
const w = screenToWorld(cam, view, p.x, p.y);
const slop = (HIT_SLOP_PX + Math.max(0, MIN_NODE_PX - minNodeR * cam.scale)) / cam.scale;
- return { node: hitTest(grid, w.wx, w.wy, slop), world: w };
+ const node = hitTest(grid, w.wx, w.wy, slop);
+ if (node >= 0 && field.drawnHosts[scene.hostOfNode[node]!]) {
+ return { kind: "file", file: scene.nodes[node]!.file, x: p.x, y: p.y };
+ }
+ const disc = discAt(field, p.x, p.y);
+ return disc ? { kind: "area", path: disc.path, slot: disc.state === "slot", x: p.x, y: p.y } : null;
},
- [loop, grid, minNodeR],
+ [loop, grid, minNodeR, scene],
);
/** Apply a camera the pointer produced and repaint everything. */
@@ -200,11 +200,9 @@ export function useMapPointer(opts: {
const onMouseMove = useCallback(
(e: ReactMouseEvent) => {
if (drag.current?.moved) return;
- const p = localPoint(e.clientX, e.clientY);
- const { node } = pick(p);
- setHovered(node >= 0 ? scene.nodes[node]!.file : null, p.x, p.y);
+ setHovered(pick(localPoint(e.clientX, e.clientY)));
},
- [localPoint, pick, scene, setHovered],
+ [localPoint, pick, setHovered],
);
const onMouseLeave = useCallback(() => {
@@ -219,17 +217,11 @@ export function useMapPointer(opts: {
return;
}
engaged.current = true;
- const { node, world } = pick(localPoint(e.clientX, e.clientY));
- if (node >= 0) {
- onSelect(scene.nodes[node]!.file.file_path);
- return;
- }
- // Inside a galaxy's ring zooms to it; empty space returns to the whole.
- const inside = galaxyAt(galaxies, world.wx, world.wy);
- if (inside && inside !== focusModule) focusOn(inside);
- else if (focusModule) focusOn(null);
+ const hit = pick(localPoint(e.clientX, e.clientY));
+ if (hit?.kind === "file") onSelectFile(hit.file.file_path);
+ else if (hit) onSelectArea(hit.path);
},
- [localPoint, pick, onSelect, scene, galaxies, focusModule, focusOn],
+ [localPoint, pick, onSelectFile, onSelectArea],
);
// Wheel zooms once the reader is working in the map (or pinches a
diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsx
index 826102dc2..de596eb4f 100644
--- a/packages/ui/src/health/triage-view.tsx
+++ b/packages/ui/src/health/triage-view.tsx
@@ -23,9 +23,8 @@
*/
import { useCallback, useMemo, useRef, useState } from "react";
-import type { CSSProperties, ReactNode } from "react";
+import type { ReactNode } from "react";
import useSWR from "swr";
-import { Search } from "lucide-react";
import type {
HealthMapFeed,
HealthOverviewResponse,
@@ -35,26 +34,17 @@ import type {
import { Skeleton } from "../ui/skeleton";
import { ApiError } from "../shared/api-error";
import { toFriendlyMessage } from "../lib/errors";
-import { OverviewSection } from "../overview/section";
import { CodeHealthLede } from "./code-health-lede";
-import {
- CodeHealthMap,
- MapLegend,
- MapLensSwitcher,
- type CodeHealthMapFile,
- type CodeHealthOverlay,
- type MapScope,
-} from "./code-health-map";
-import { MapFieldList } from "./map/inspector";
+import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./code-health-map";
+import { AreaMapSection, type FlatMapExtras } from "./area-map-section";
+import type { AreaRailLabels } from "./area-rail/labels";
import type { CodeHealthAdapter } from "./code-health-adapter";
export type HealthPillar = "all" | "defect" | "maintainability" | "performance";
-/** Map height. The rail is height-matched so it never outgrows the field it lists. */
+/** Map height while the page around it loads. */
const MAP_HEIGHT = 720;
-/** The legend row under the map plus the gap above it, so the rail ends where the legend does. */
-const LEGEND_ROW = 52;
/** Read the server's own selection totals into the shape the map states. */
export function scopeFromFeed(feed: HealthMapFeed): MapScope {
@@ -108,6 +98,13 @@ export function TriageView({
mapPending,
mapError,
onRetryMap,
+ area,
+ onAreaChange,
+ fileExtras,
+ railLabels,
+ primaryLenses,
+ include,
+ onIncludeChange,
}: {
adapter: CodeHealthAdapter;
/** Trend fetched once by the host. Consumed by `trendSlot`; accepted here so
@@ -155,6 +152,22 @@ export function TriageView({
/** The field's request failed; the map shows it with a retry. */
mapError?: unknown;
onRetryMap?: () => void;
+ /**
+ * The map's selected area (`""` is the repository), owned by the host so it
+ * rides in the URL and the browser's back button climbs back out. The host
+ * drops the selected file in the same write.
+ */
+ area?: string;
+ onAreaChange?: (area: string) => void;
+ /** Per-file signals the host joins onto the area-loaded rows (e.g. churn). */
+ fileExtras?: ReadonlyMap<string, Partial<CodeHealthMapFile>>;
+ /** Translations for the map's rail. */
+ railLabels?: Partial<AreaRailLabels>;
+ /** Lenses shown as segments; the rest sit behind "More". */
+ primaryLenses?: CodeHealthOverlay[];
+ /** Held-out groups brought back into the map, and the toggle that changes them. */
+ include?: readonly string[];
+ onIncludeChange?: (include: string[]) => void;
}) {
const { cacheKey } = adapter;
const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
@@ -176,31 +189,15 @@ export function TriageView({
}, []);
const closeDrawer = useCallback(() => setSelected(null), [setSelected]);
- const [mapQuery, setMapQuery] = useState("");
-
- const files = mapFeed?.files as CodeHealthMapFile[] | undefined;
const scope = useMemo(() => (mapFeed ? scopeFromFeed(mapFeed) : undefined), [mapFeed]);
- // Only "is it drawn" is needed now that the drawer is the inspector.
- const selectedDrawn = useMemo(
- () => (selected ? (files?.some((f) => f.file_path === selected) ?? false) : false),
- [files, selected],
- );
+ // With the areas API the rail hosts the file detail; without it the drawer does.
+ const hasAreas = Boolean(adapter.getAreaTree && adapter.getAreaFiles && adapter.getAreaDetail);
// CodeHealthMap's optional props, omitted rather than passed as `undefined`
// (strict optional props in the shared lib). Memoized so the map sees the
// same object until one of them actually changes.
const mapExtra = useMemo(() => {
- const extra: {
- lenses?: CodeHealthOverlay[];
- overlayLoading?: boolean;
- scope?: MapScope;
- highlightPaths?: string[];
- onDrawMore?: () => void;
- drawMoreStep?: number;
- onIncludeHeldChange?: (include: boolean) => void;
- onFindUndrawn?: (query: string) => void;
- pending?: boolean;
- } = {};
+ const extra: FlatMapExtras = {};
if (lenses) extra.lenses = lenses;
if (overlayLoading !== undefined) extra.overlayLoading = overlayLoading;
if (scope) extra.scope = scope;
@@ -259,98 +256,35 @@ export function TriageView({
{isLoading ? (
<Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />
) : loaded ? (
- <OverviewSection
- title="Code health map"
- description="Every file as a node, clustered into module galaxies and sized by lines of code. The lens re-marks the same field rather than redrawing it. Click a galaxy to zoom, a file to inspect it."
- action={
- onOverlayChange ? (
- <MapLensSwitcher
- overlay={overlay}
- onOverlayChange={onOverlayChange}
- {...(lenses ? { lenses } : {})}
- />
- ) : undefined
- }
- >
- <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
- <div className="flex flex-col gap-2.5">
- {!files && mapError ? (
- // A failed field says so, rather than leaving the skeleton up.
- <div className="flex items-center justify-center" style={{ minHeight: MAP_HEIGHT }}>
- <ApiError
- title="Couldn't load the map"
- message={toFriendlyMessage(mapError)}
- {...(onRetryMap ? { onRetry: onRetryMap } : {})}
- />
- </div>
- ) : !files ? (
- <Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />
- ) : (
- <CodeHealthMap
- files={files}
- search={mapQuery}
- selectedPath={selected}
- onSelectFile={setSelected}
- minHeight={MAP_HEIGHT}
- overlay={overlay}
- chrome="none"
- {...mapExtra}
- />
- )}
- <MapLegend overlay={overlay} loading={overlayLoading ?? false} />
- </div>
-
- {/* The rail, height-matched to the map and its legend. Separated
- by space, not by a rule: a vertical hairline down the side of
- the canvas would turn the map into a trench. */}
- <aside
- className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[var(--rail-h)]"
- style={{ "--rail-h": `${MAP_HEIGHT + LEGEND_ROW}px` } as CSSProperties}
- >
- <div className="relative">
- <Search
- aria-hidden="true"
- className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]"
- />
- <input
- type="search"
- value={mapQuery}
- onChange={(e) => setMapQuery(e.target.value)}
- placeholder="Find a file in the map…"
- aria-label="Find a file in the map"
- className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] hover:border-[var(--color-border-hover)] focus-visible:border-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
- />
- </div>
-
- {selected && files && !selectedDrawn ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- <span className="break-all font-mono">{selected}</span> is not in the drawn
- field, so no node is marked. Its details are open in the file panel.
- </p>
- ) : null}
-
- {files ? (
- <div className="min-h-0 flex-1 overflow-hidden border-t border-[var(--color-border-default)] pt-3">
- <MapFieldList
- files={files}
- overlay={overlay}
- selectedPath={selected}
- onSelectFile={setSelected}
- {...(scope ? { scope } : {})}
- />
- </div>
- ) : null}
- </aside>
- </div>
- </OverviewSection>
+ <AreaMapSection
+ adapter={adapter}
+ overlay={overlay}
+ onOverlayChange={onOverlayChange}
+ lenses={lenses}
+ mapFeed={mapFeed}
+ mapScope={scope}
+ mapError={mapError}
+ onRetryMap={onRetryMap}
+ mapExtra={mapExtra}
+ overlayLoading={overlayLoading ?? false}
+ selected={selected}
+ setSelected={setSelected}
+ area={area}
+ onAreaChange={onAreaChange}
+ fileExtras={fileExtras}
+ railLabels={railLabels}
+ primaryLenses={primaryLenses}
+ include={include}
+ onIncludeChange={onIncludeChange}
+ />
) : null}
{loaded ? hotspotsSlot : null}
{loaded ? trendSlot : null}
{/* Outside the loaded branch, so a file linked by URL opens even while
- the overview is still on its way. */}
- {adapter.renderFileDrawer({
+ the overview is still on its way. The area rail hosts it inline. */}
+ {hasAreas ? null : adapter.renderFileDrawer({
filePath: selected,
onClose: closeDrawer,
lens: overlay,
diff --git a/packages/ui/src/shared/breadcrumb.tsx b/packages/ui/src/shared/breadcrumb.tsx
index d346b7b0b..be65c1921 100644
--- a/packages/ui/src/shared/breadcrumb.tsx
+++ b/packages/ui/src/shared/breadcrumb.tsx
@@ -5,6 +5,8 @@ import { ChevronRight } from "lucide-react";
export interface BreadcrumbSegment {
label: string;
href?: string;
+ /** In-page navigation instead of a link, e.g. climbing a zoomable map. */
+ onSelect?: () => void;
}
interface BreadcrumbProps {
@@ -30,8 +32,19 @@ export function Breadcrumb({ segments, LinkComponent = "a" }: BreadcrumbProps) {
{i > 0 && (
<ChevronRight className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />
)}
- {isLast || !segment.href ? (
- <span className="text-[var(--color-text-primary)] font-medium truncate">
+ {!isLast && segment.onSelect ? (
+ <button
+ type="button"
+ onClick={segment.onSelect}
+ className="rounded text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors truncate focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {segment.label}
+ </button>
+ ) : isLast || !segment.href ? (
+ <span
+ aria-current={isLast ? "location" : undefined}
+ className="text-[var(--color-text-primary)] font-medium truncate"
+ >
{segment.label}
</span>
) : (
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 2af0a97e7..1d27288c8 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -464,6 +464,80 @@
"findings": "Findings",
"deadCode": "Dead code",
"map": "Map"
+ },
+ "areaRail": {
+ "mapTitle": "Code health map",
+ "mapDescription": "Every folder is a disc sized by lines of code and coloured by the lens. Zoom in and folders open into their sub-folders, then their files. Click a folder to open it, a file to read it in the rail.",
+ "flatMapDescription": "Every file as a node, grouped into its folders and sized by lines of code. The lens re-marks the same field rather than redrawing it. Click a folder to zoom, a file to inspect it.",
+ "searchPlaceholder": "Find a file in the map…",
+ "mapLoadError": "Couldn't load the map",
+ "mapAriaLabel": "Code health map, {lens} lens. Arrow keys move between the areas and files inside the selected area, Enter opens one, Backspace goes up a level, Escape returns to the repository, plus and minus zoom.",
+ "promptAction": "{count, plural, one {Copy prompt for the top finding} other {Copy prompt for the top # findings}}",
+ "repository": "Repository",
+ "repoEyebrow": "Repository",
+ "areaEyebrow": "Area",
+ "files": "{count, plural, one {# file} other {# files}}",
+ "deltaWindow": "{delta} in {days} days",
+ "improved": "Up {delta} over the last {days} days. The work here is paying off.",
+ "noDelta": "No earlier snapshot to compare with yet.",
+ "needsAttention": "Needs attention",
+ "subAreas": "Inside, lowest first",
+ "improvedMost": "Improved most",
+ "worstFiles": "Lowest-scoring files",
+ "hotspots": "Hotspots · {count}",
+ "owners": "Who knows it",
+ "ownerShare": "{name} leads {pct}% of the files",
+ "busFactorOne": "{count, plural, one {# file} other {# files}} only one person has changed",
+ "coverage": "Tests",
+ "noCoverage": "No coverage report covers this area.",
+ "coverageLine": "{pct}% line coverage over {files, plural, one {# measured file} other {# measured files}}",
+ "topFindings": "Top findings",
+ "noFindings": "No open findings here.",
+ "allClean": "No open findings across {count, plural, one {# file} other {# files}}.",
+ "promptTitle": "Agent prompt for this area",
+ "promptDescription": "The area's highest-priority findings, ready to paste into your agent.",
+ "findingsLink": "Findings here",
+ "fixFirstLink": "Fix first here",
+ "contributorsLink": "Contributors here",
+ "backToArea": "Back to {name}",
+ "loading": "Loading area",
+ "loadError": "Couldn't load this area.",
+ "moreLenses": "More",
+ "lens": {
+ "health": "Code health",
+ "hotspot": "Hotspot health",
+ "owner": "Main author",
+ "maintainability": "Maintainability",
+ "performance": "Performance",
+ "coverage": "Coverage",
+ "churn": "Churn",
+ "knowledge": "Knowledge risk",
+ "dead-code": "Dead code",
+ "security": "Security"
+ },
+ "hotspotChip": "{count} hot",
+ "hotspotChipScored": "{count} hot · {health}",
+ "fileCount": "{count, plural, one {# file} other {# files}}",
+ "openHint": "click to open",
+ "directFiles": "Files directly in {folder}",
+ "notLoaded": "Files not loaded yet · zoom in to read them",
+ "analysedFiles": "{analysed} of {loaded} files analysed",
+ "flaggedFiles": "{flagged} of {analysed} analysed files flagged",
+ "scopeProduction": "Production code",
+ "scopeAll": "All code",
+ "scopeWith": "Production code and {names}",
+ "origin": {
+ "test": "test files",
+ "docs_example": "docs examples",
+ "build": "build files",
+ "vendored": "vendored files",
+ "generated": "generated files",
+ "tooling": "tooling files",
+ "production": "production files"
+ },
+ "showHeld": "Show {name} ({count})",
+ "hideHeld": "Hide {name}",
+ "heldOutHint": "This folder may hold only files the map leaves out by default. Bring them back with the toggles under the map."
}
},
"knowledgeGraph": {
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 3812a3586..5615464e4 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -464,6 +464,80 @@
"findings": "发现",
"deadCode": "死代码",
"map": "地图"
+ },
+ "areaRail": {
+ "mapTitle": "代码健康地图",
+ "mapDescription": "每个文件夹是一个圆盘,大小代表代码行数,颜色由当前视角决定。放大后文件夹会展开为子文件夹,再展开为文件。点击文件夹打开它,点击文件在侧栏中查看。",
+ "flatMapDescription": "每个文件是一个节点,按文件夹分组,大小代表代码行数。切换视角只会重新着色,不会重新布局。点击文件夹放大,点击文件查看详情。",
+ "searchPlaceholder": "在地图中查找文件…",
+ "mapLoadError": "无法加载地图",
+ "mapAriaLabel": "代码健康地图,{lens} 视角。方向键在所选区域内的子区域和文件之间移动,回车打开,退格键返回上一级,Esc 返回仓库,加号和减号缩放。",
+ "promptAction": "复制前 {count} 个问题的提示词",
+ "repository": "仓库",
+ "repoEyebrow": "仓库",
+ "areaEyebrow": "区域",
+ "files": "{count} 个文件",
+ "deltaWindow": "{days} 天内 {delta}",
+ "improved": "过去 {days} 天上升了 {delta}。这里的工作正在见效。",
+ "noDelta": "还没有更早的快照可供比较。",
+ "needsAttention": "需要关注",
+ "subAreas": "内部区域,由低到高",
+ "improvedMost": "提升最多",
+ "worstFiles": "得分最低的文件",
+ "hotspots": "热点 · {count}",
+ "owners": "谁了解这里",
+ "ownerShare": "{name} 主导了 {pct}% 的文件",
+ "busFactorOne": "{count} 个文件只有一个人修改过",
+ "coverage": "测试",
+ "noCoverage": "没有覆盖率报告涵盖此区域。",
+ "coverageLine": "{files} 个已测量文件的行覆盖率为 {pct}%",
+ "topFindings": "主要问题",
+ "noFindings": "这里没有未解决的问题。",
+ "allClean": "{count} 个文件中没有未解决的问题。",
+ "promptTitle": "此区域的智能体提示词",
+ "promptDescription": "此区域最优先的问题,可直接粘贴给你的智能体。",
+ "findingsLink": "此处的问题",
+ "fixFirstLink": "此处优先修复",
+ "contributorsLink": "此处的贡献者",
+ "backToArea": "返回 {name}",
+ "loading": "正在加载区域",
+ "loadError": "无法加载此区域。",
+ "moreLenses": "更多",
+ "lens": {
+ "health": "代码健康",
+ "hotspot": "热点健康",
+ "owner": "主要作者",
+ "maintainability": "可维护性",
+ "performance": "性能",
+ "coverage": "覆盖率",
+ "churn": "变更频率",
+ "knowledge": "知识风险",
+ "dead-code": "死代码",
+ "security": "安全"
+ },
+ "hotspotChip": "{count} 个热点",
+ "hotspotChipScored": "{count} 个热点 · {health}",
+ "fileCount": "{count} 个文件",
+ "openHint": "点击打开",
+ "directFiles": "直接位于 {folder} 的文件",
+ "notLoaded": "文件尚未加载 · 放大以查看",
+ "analysedFiles": "已分析 {loaded} 个文件中的 {analysed} 个",
+ "flaggedFiles": "已分析的 {analysed} 个文件中有 {flagged} 个被标记",
+ "scopeProduction": "生产代码",
+ "scopeAll": "全部代码",
+ "scopeWith": "生产代码及{names}",
+ "origin": {
+ "test": "测试文件",
+ "docs_example": "文档示例",
+ "build": "构建文件",
+ "vendored": "第三方文件",
+ "generated": "生成的文件",
+ "tooling": "工具文件",
+ "production": "生产文件"
+ },
+ "showHeld": "显示{name}({count})",
+ "hideHeld": "隐藏{name}",
+ "heldOutHint": "此文件夹可能只包含地图默认隐藏的文件。可使用地图下方的开关将它们显示出来。"
}
},
"knowledgeGraph": {
diff --git a/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx b/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx
index 156fc361e..c74cda289 100644
--- a/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/code-health-view.tsx
@@ -29,7 +29,7 @@
import dynamic from "next/dynamic";
import { useParams, useRouter, useSearchParams } from "next/navigation";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { HeartPulse, RotateCw } from "lucide-react";
import { PageShell } from "@repowise-dev/ui/shared/page-shell";
@@ -59,13 +59,9 @@ import { HotspotsSection } from "@/components/code-health/hotspots-section";
import { TrendSection } from "@/components/code-health/trend-tab";
import { getDeadCodeSummary } from "@/lib/api/dead-code";
import {
- getChurnComplexity,
- getHealthMap,
getHealthOverview,
getHealthTrend,
getPerformanceOpportunity,
- type ChurnComplexityResponse,
- type HealthMapFeed,
type HealthOverviewResponse,
type HealthTrendResponse,
} from "@/lib/api/code-health";
@@ -96,11 +92,19 @@ const DeadCodeTab = dynamic(
);
/**
- * Lenses on the map. The three co-equal health signals ride on the map payload
- * itself; churn arrives on its own request and is joined in below, which is why
- * it is listed here rather than in the map component's default.
+ * Lenses on the map. Three lead as segments; the rest sit behind "More",
+ * where later lenses (off-boarding, coupling) join. Churn percentiles are
+ * joined in by the map tab; owner and knowledge read the ownership rollup.
*/
-const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance", "churn"];
+const PRIMARY_LENSES: CodeHealthOverlay[] = ["health", "hotspot", "owner"];
+const OVERLAYS: CodeHealthOverlay[] = [
+ ...PRIMARY_LENSES,
+ "maintainability",
+ "performance",
+ "coverage",
+ "churn",
+ "knowledge",
+];
/**
* Tabs whose data honours `scope`. Dead code has no production/test split,
@@ -166,34 +170,6 @@ const COUNTS_LABEL_KEYS: Record<HealthCounts, string> = {
code_shape: "countsCodeShape",
};
-/**
- * Nodes the map draws at first. The server chooses which ones: pinned paths
- * first, a floor per module, then production before tooling, tests and
- * examples, with open performance causes and then the unhealthiest files
- * leading each tier. "Draw more" steps the cap up to the server's ceiling.
- */
-const MAP_CAP = 2000;
-const MAP_CAP_STEP = 2000;
-const MAP_CAP_MAX = 8000;
-/** Paths pinned for selections made outside the drawn field, at most. */
-const MAX_EXTRA_PINS = 20;
-/**
- * Churn points pulled for the churn lens. Deliberately larger than
- * `MAP_FILE_LIMIT`: the map ranks by NLOC and churn-complexity ranks by
- * `commit_count × max_ccn`, so the two windows do not contain the same files.
- * At the old default of 300 this repo joined churn onto 296 of the 1,935 mapped
- * files that have it, and the other ~1,700 nodes rendered as the legend's
- * "no data" swatch for data that exists. Matching the map's 2,000 would still
- * miss 445. 5,000 covers every churned file here with headroom; a repo that
- * exceeds it degrades back to the same partial join rather than breaking.
- *
- * Costs ~469 KB uncompressed on this repo (3,011 points), on a request that
- * only fires once the churn lens is selected. The hosted route still caps at
- * 1,000, so porting this page there needs that ceiling raised first or the
- * request 422s.
- */
-const CHURN_POINT_LIMIT = 5000;
-
export function CodeHealthView() {
const t = useTranslations("views.codeHealth");
const tc = useTranslations("common");
@@ -292,85 +268,6 @@ export function CodeHealthView() {
return [...new Set(paths.filter(Boolean))];
}, [opportunity]);
- // The bounded field: one pull, shared across lenses so switching never
- // refetches. The paths the page needs on screen ride along as `active`, which
- // is what makes the guarantee a server-side one rather than a hope that the
- // ranking happened to include them.
- //
- // A selection is pinned only when it is not already drawn, and a pin, once
- // made, stays: a click on a node the reader can see costs no request, and a
- // file pinned in does not drop out again on the refetch its own pin caused.
- // The deep-linked file is pinned from the first request.
- const [extraPins, setExtraPins] = useState<string[]>(() =>
- selectedPath ? [selectedPath] : [],
- );
- const [mapCap, setMapCap] = useState(MAP_CAP);
- const [includeHeld, setIncludeHeld] = useState(false);
- const [pinQuery, setPinQuery] = useState("");
- const activePaths = useMemo(
- () => [...new Set([...extraPins, ...(highlightPaths ?? [])])],
- [extraPins, highlightPaths],
- );
- const {
- data: mapFeed,
- error: mapError,
- isValidating: mapValidating,
- mutate: mutateMap,
- } = useSWR<HealthMapFeed>(
- `code-health-map:${repoId}${viewKey}:${mapCap}:${includeHeld ? "held" : ""}:${pinQuery}:${activePaths.join(",")}`,
- () =>
- getHealthMap(repoId, {
- cap: mapCap,
- ...(activePaths.length ? { active: activePaths } : {}),
- scope,
- counts,
- ...(includeHeld ? { include_held: true } : {}),
- ...(pinQuery ? { q: pinQuery } : {}),
- }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
- const drawnPaths = useMemo(
- () => new Set(mapFeed?.files.map((f) => f.file_path) ?? []),
- [mapFeed],
- );
- useEffect(() => {
- if (!selectedPath || !mapFeed || drawnPaths.has(selectedPath)) return;
- setExtraPins((pins) =>
- pins.includes(selectedPath) ? pins : [...pins, selectedPath].slice(-MAX_EXTRA_PINS),
- );
- }, [selectedPath, mapFeed, drawnPaths]);
- const canDrawMore = mapCap < MAP_CAP_MAX;
- const drawMore = useCallback(
- () => setMapCap((c) => Math.min(MAP_CAP_MAX, c + MAP_CAP_STEP)),
- [],
- );
- const retryMap = useCallback(() => void mutateMap(), [mutateMap]);
-
- // Churn percentiles for the churn lens. Fetched only once that lens is
- // selected: it is a second request, and the other three lenses color from
- // fields already on the map payload.
- const churnWanted = overlay === "churn";
- const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(
- churnWanted ? `health-churn-complexity:${repoId}` : null,
- () => getChurnComplexity(repoId, { limit: CHURN_POINT_LIMIT }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- // Join churn onto the map rows by path. Until it lands every node would be
- // neutral, so the legend is told it is loading rather than letting an
- // all-grey field read as "no churn anywhere".
- const mapFeedWithChurn: HealthMapFeed | undefined = useMemo(() => {
- if (!mapFeed || !churn) return mapFeed;
- const byPath = new Map(churn.points.map((p) => [p.file_path, p.churn_percentile]));
- return {
- ...mapFeed,
- files: mapFeed.files.map((file) => ({
- ...file,
- churn_percentile: byPath.get(file.file_path) ?? null,
- })),
- };
- }, [mapFeed, churn]);
-
// ---- Tab counts ----
// Dead code uses the same key + fetcher as its own tab, so this is a prefetch
// rather than a duplicate request.
@@ -529,19 +426,11 @@ export function CodeHealthView() {
overlay={overlay}
onOverlayChange={setOverlay}
lenses={OVERLAYS}
- mapFeed={mapFeedWithChurn}
- overlayLoading={churnWanted && churnLoading && !churn}
+ primaryLenses={PRIMARY_LENSES}
selectedPath={selectedPath}
onSelectPath={setSelectedPath}
highlightPaths={highlightPaths}
scope={scope}
- onDrawMore={canDrawMore ? drawMore : undefined}
- drawMoreStep={MAP_CAP_STEP}
- onIncludeHeldChange={setIncludeHeld}
- onFindUndrawn={setPinQuery}
- mapPending={mapValidating}
- mapError={mapError}
- onRetryMap={retryMap}
hotspotsSlot={<HotspotsSection repoId={repoId} />}
trendSlot={
<OverviewSection
diff --git a/packages/web/src/components/code-health/area-rail-labels.ts b/packages/web/src/components/code-health/area-rail-labels.ts
new file mode 100644
index 000000000..50fd05e05
--- /dev/null
+++ b/packages/web/src/components/code-health/area-rail-labels.ts
@@ -0,0 +1,68 @@
+"use client";
+
+import { useMemo } from "react";
+import { useTranslations } from "next-intl";
+import type { AreaRailLabels } from "@repowise-dev/ui/health";
+
+/** The area rail's copy from the catalog. */
+export function useAreaRailLabels(): AreaRailLabels {
+ const t = useTranslations("views.codeHealth.areaRail");
+ return useMemo<AreaRailLabels>(
+ () => ({
+ mapTitle: t("mapTitle"),
+ mapDescription: t("mapDescription"),
+ flatMapDescription: t("flatMapDescription"),
+ searchPlaceholder: t("searchPlaceholder"),
+ moreLenses: t("moreLenses"),
+ scopeProduction: t("scopeProduction"),
+ scopeAll: t("scopeAll"),
+ heldOutHint: t("heldOutHint"),
+ scopeWith: (names) => t("scopeWith", { names }),
+ originName: (origin) => (t.has(`origin.${origin}`) ? t(`origin.${origin}`) : origin.replace(/_/g, " ")),
+ showHeld: (name, count) => t("showHeld", { name, count: count.toLocaleString() }),
+ hideHeld: (name) => t("hideHeld", { name }),
+ hotspotChip: (count, health) =>
+ health == null ? t("hotspotChip", { count }) : t("hotspotChipScored", { count, health }),
+ fileCount: (count) => t("fileCount", { count }),
+ openHint: t("openHint"),
+ directFiles: (folder) => t("directFiles", { folder }),
+ notLoaded: t("notLoaded"),
+ analysedFiles: (analysed, loaded) => t("analysedFiles", { analysed, loaded }),
+ flaggedFiles: (flagged, analysed) => t("flaggedFiles", { flagged, analysed }),
+ lensName: (lens) => (t.has(`lens.${lens}`) ? t(`lens.${lens}`) : undefined),
+ mapLoadError: t("mapLoadError"),
+ mapAriaLabel: (lens) => t("mapAriaLabel", { lens }),
+ promptAction: (count) => t("promptAction", { count }),
+ repository: t("repository"),
+ repoEyebrow: t("repoEyebrow"),
+ areaEyebrow: t("areaEyebrow"),
+ files: (count) => t("files", { count }),
+ deltaWindow: (delta, days) => t("deltaWindow", { delta, days }),
+ improved: (delta, days) => t("improved", { delta, days }),
+ noDelta: t("noDelta"),
+ needsAttention: t("needsAttention"),
+ subAreas: t("subAreas"),
+ improvedMost: t("improvedMost"),
+ worstFiles: t("worstFiles"),
+ hotspots: (count) => t("hotspots", { count }),
+ owners: t("owners"),
+ ownerShare: (name, pct) => t("ownerShare", { name, pct }),
+ busFactorOne: (count) => t("busFactorOne", { count }),
+ coverage: t("coverage"),
+ noCoverage: t("noCoverage"),
+ coverageLine: (pct, files) => t("coverageLine", { pct, files }),
+ topFindings: t("topFindings"),
+ noFindings: t("noFindings"),
+ allClean: (count) => t("allClean", { count }),
+ promptTitle: t("promptTitle"),
+ promptDescription: t("promptDescription"),
+ findingsLink: t("findingsLink"),
+ fixFirstLink: t("fixFirstLink"),
+ contributorsLink: t("contributorsLink"),
+ backToArea: (name) => t("backToArea", { name }),
+ loading: t("loading"),
+ loadError: t("loadError"),
+ }),
+ [t],
+ );
+}
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index 0d6cd99e4..3c315075e 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -5,28 +5,115 @@
* `/repos/:id` routing, and the file-detail drawer. The composition itself
* lives in `@repowise-dev/ui/health`; this file only injects the app-specific
* pieces so web and hosted render the same view.
+ *
+ * The map is the areas map: the hierarchy and each area's files load as the
+ * reader zooms (`/areas/tree`, `/health/map?area=`), the rail reads
+ * `/areas/{path}`, and the selected area lives in `?area=` so a link opens it
+ * and the browser's back button climbs back out.
*/
-import type { ReactNode } from "react";
-import { useRouter } from "next/navigation";
+import { useCallback, useMemo, type ReactNode } from "react";
+import useSWR from "swr";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
TriageView,
type CodeHealthAdapter,
+ type CodeHealthMapFile,
type CodeHealthOverlay,
} from "@repowise-dev/ui/health";
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
+ getChurnComplexity,
+ getHealthMap,
getHealthOverview,
getHealthWorkQueue,
listHealthFindings,
getHealthCoverage,
updateFindingStatus,
+ type ChurnComplexityResponse,
type HealthTrendResponse,
- type HealthMapFeed,
} from "@/lib/api/code-health";
+import { getAreaDetail, getAreaTree } from "@/lib/api/areas";
import type { HealthCounts, HealthScope } from "@repowise-dev/types/health";
import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
import { FixFirstSection } from "@/components/code-health/fix-first-section";
+import { useAreaRailLabels } from "./area-rail-labels";
+
+/**
+ * Churn points pulled for the churn lens, joined onto the area-loaded rows by
+ * path. Large enough to cover every churned file in a repository this size;
+ * fetched only while the churn lens is on.
+ */
+const CHURN_POINT_LIMIT = 5000;
+
+/** The selected area in `?area=`, pushed so back and forward walk the levels. */
+function useAreaParam() {
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+ const area = searchParams.get("area") ?? "";
+ const setArea = useCallback(
+ (next: string) => {
+ // Re-selecting the open area is not a step to go back over.
+ if (next === area) return;
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next) sp.set("area", next);
+ else sp.delete("area");
+ // A file belongs to the level it was opened from.
+ sp.delete("file");
+ const qs = sp.toString();
+ router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
+ },
+ [router, pathname, searchParams, area],
+ );
+ return [area, setArea] as const;
+}
+
+/**
+ * Held-out groups brought back into the map, in `?include=` (e.g.
+ * `test,build`). Replaced rather than pushed: it is a view setting, not a
+ * place to go back to.
+ */
+function useIncludeParam() {
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+ const raw = searchParams.get("include") ?? "";
+ const include = useMemo(
+ () => raw.split(",").map((o) => o.trim().toLowerCase()).filter(Boolean),
+ [raw],
+ );
+ const setInclude = useCallback(
+ (next: string[]) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next.length) sp.set("include", next.join(","));
+ else sp.delete("include");
+ const qs = sp.toString();
+ router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
+ },
+ [router, pathname, searchParams],
+ );
+ return [include, setInclude] as const;
+}
+
+/** Churn percentiles by path, fetched only while the churn lens is on. */
+function useChurnExtras(repoId: string, wanted: boolean) {
+ const { data, isLoading } = useSWR<ChurnComplexityResponse>(
+ wanted ? `health-churn-complexity:${repoId}` : null,
+ () => getChurnComplexity(repoId, { limit: CHURN_POINT_LIMIT }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+ const extras = useMemo(
+ () =>
+ data
+ ? new Map<string, Partial<CodeHealthMapFile>>(
+ data.points.map((p) => [p.file_path, { churn_percentile: p.churn_percentile }]),
+ )
+ : undefined,
+ [data],
+ );
+ return { extras, loading: wanted && isLoading && !data };
+}
export function TriageTab({
repoId: id,
@@ -34,8 +121,7 @@ export function TriageTab({
overlay = "health",
onOverlayChange,
lenses,
- mapFeed,
- overlayLoading,
+ primaryLenses,
selectedPath,
onSelectPath,
highlightPaths,
@@ -43,13 +129,6 @@ export function TriageTab({
trendSlot,
scope,
counts,
- onDrawMore,
- drawMoreStep,
- onIncludeHeldChange,
- onFindUndrawn,
- mapPending,
- mapError,
- onRetryMap,
}: {
repoId: string;
/** Trend fetched once at the page level. */
@@ -57,12 +136,10 @@ export function TriageTab({
/** Active map lens, owned by the page so the spine is shared across tabs. */
overlay?: CodeHealthOverlay;
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
- /** Lenses offered in the switcher, including any the page joined in. */
+ /** Lenses offered in the switcher. */
lenses?: CodeHealthOverlay[];
- /** The bounded field, fetched once at the page level and shared by lenses. */
- mapFeed?: HealthMapFeed;
- /** The active lens's per-file signal is still loading (e.g. churn). */
- overlayLoading?: boolean;
+ /** Lenses shown as segments; the rest sit behind "More". */
+ primaryLenses?: CodeHealthOverlay[];
/** Selection, URL-synced by the page so a link can open one file. */
selectedPath?: string | null;
onSelectPath?: (path: string | null) => void;
@@ -75,16 +152,15 @@ export function TriageTab({
scope?: HealthScope;
/** Whether those figures count change history or code shape alone. */
counts?: HealthCounts;
- /** Map field controls the page backs with a refetch. */
- onDrawMore?: (() => void) | undefined;
- drawMoreStep?: number;
- onIncludeHeldChange?: (include: boolean) => void;
- onFindUndrawn?: (query: string) => void;
- mapPending?: boolean;
- mapError?: unknown;
- onRetryMap?: () => void;
}) {
const router = useRouter();
+ const [area, setArea] = useAreaParam();
+ const [include, setInclude] = useIncludeParam();
+ // The map holds tests, docs examples, build, vendored and generated files
+ // out by default (the server names the set); `include` brings some back.
+ const hold = { hold: "map" as const, include };
+ const railLabels = useAreaRailLabels();
+ const churn = useChurnExtras(id, overlay === "churn");
const prefix = `/repos/${id}`;
// Scope and counts ride in the cache key as well as the query: the views key
@@ -104,16 +180,30 @@ export function TriageTab({
updateFindingStatus: (findingId, status) =>
updateFindingStatus(id, findingId, status),
getCoverage: (opts) => getHealthCoverage(id, opts),
+ getAreaTree: (root, depth) => getAreaTree(id, { root, depth, ...hold }),
+ getAreaDetail: (path) => getAreaDetail(id, path, hold),
+ // The area's complete list: the server's cap is the most it serves.
+ getAreaFiles: (path) =>
+ getHealthMap(id, {
+ area: path,
+ cap: 8000,
+ ...hold,
+ ...(scope ? { scope } : {}),
+ ...(counts ? { counts } : {}),
+ }),
+ // No area links yet: neither the Findings tab nor the Contributors page
+ // reads `?area=`, and a link must not claim a scope its page drops.
fileHref: (path) => fileEntityPath(prefix, path),
symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),
navigate: (href) => router.push(href),
- renderFileDrawer: ({ filePath, onClose, lens }) => (
+ renderFileDrawer: ({ filePath, onClose, lens, inline }) => (
<HealthFileDrawerHost
repoId={id}
filePath={filePath}
onClose={onClose}
counts={counts}
{...(lens ? { lens } : {})}
+ {...(inline ? { inline } : {})}
/>
),
};
@@ -125,21 +215,20 @@ export function TriageTab({
overlay={overlay}
onOverlayChange={onOverlayChange}
lenses={lenses}
- mapFeed={mapFeed}
- overlayLoading={overlayLoading}
+ primaryLenses={primaryLenses}
+ overlayLoading={churn.loading}
selectedPath={selectedPath}
onSelectPath={onSelectPath}
highlightPaths={highlightPaths}
hotspotsSlot={hotspotsSlot}
trendSlot={trendSlot}
leadSlot={<FixFirstSection repoId={id} />}
- onDrawMore={onDrawMore}
- drawMoreStep={drawMoreStep}
- onIncludeHeldChange={onIncludeHeldChange}
- onFindUndrawn={onFindUndrawn}
- mapPending={mapPending}
- mapError={mapError}
- onRetryMap={onRetryMap}
+ area={area}
+ onAreaChange={setArea}
+ fileExtras={churn.extras}
+ railLabels={railLabels}
+ include={include}
+ onIncludeChange={setInclude}
/>
);
}
diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsx
index d6989ce48..caadb61ff 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -28,8 +28,11 @@ export function HealthFileDrawerHost({
onClose,
lens,
counts,
+ inline,
}: {
repoId: string;
+ /** Render in place (the map's rail) instead of in a sheet. */
+ inline?: boolean;
filePath: string | null;
onClose: () => void;
/** The reading the row that opened this drawer was scored under. */
@@ -81,6 +84,7 @@ export function HealthFileDrawerHost({
return (
<HealthFileDrawer
open={filePath !== null}
+ inline={inline ?? false}
opportunity={opportunity}
refactoringOpportunityHref={(id) => refactoringOpportunityHref(repoId, id)}
related={related.data?.files?.[0]}
diff --git a/packages/web/src/lib/api/areas.ts b/packages/web/src/lib/api/areas.ts
new file mode 100644
index 000000000..f31457b65
--- /dev/null
+++ b/packages/web/src/lib/api/areas.ts
@@ -0,0 +1,3 @@
+import "./client";
+
+export * from "@repowise-dev/api-client/areas";
diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.js
index 558c247a7..9a8f77b35 100644
--- a/plugins/claude-code/hooks/lens/lens.js
+++ b/plugins/claude-code/hooks/lens/lens.js
@@ -3275,6 +3275,12 @@ async function analyzeBlastRadius(repoId, body) {
);
}
+// ../api-client/src/areas.ts
+function holdParams(opts = {}) {
+ if (opts.hold !== "map") return {};
+ return { hold: "map", include: opts.include?.length ? [...opts.include].sort().join(",") : void 0 };
+}
+
// ../api-client/src/code-health.ts
async function getHealthMap(repoId, opts = {}) {
return apiGet(`/api/repos/${repoId}/health/map`, {
@@ -3284,7 +3290,8 @@ async function getHealthMap(repoId, opts = {}) {
counts: opts.counts,
include_held: opts.include_held || void 0,
q: opts.q?.trim() || void 0,
- area: opts.area || void 0
+ area: opts.area || void 0,
+ ...holdParams(opts)
});
}
diff --git a/tests/unit/server/test_areas_routes.py b/tests/unit/server/test_areas_routes.py
index 2d0d0e3e2..49484d3d0 100644
--- a/tests/unit/server/test_areas_routes.py
+++ b/tests/unit/server/test_areas_routes.py
@@ -158,5 +158,79 @@ async def test_a_warmed_model_serves_the_next_read_without_a_build(app, client,
raise AssertionError("the warm-up should have built the model")
monkeypatch.setattr(service, "_build", no_build)
- tree = await client.get(f"/api/repos/{repo_id}/areas/tree")
+ # The warm-up builds the map's default view, the one the first reader opens.
+ tree = await client.get(f"/api/repos/{repo_id}/areas/tree", params={"hold": "map"})
assert tree.status_code == 200
+
+
+async def _seed_origins(app, client: AsyncClient) -> str:
+ """Production code beside tests, a build file and a generated file."""
+ repo_id = (await create_test_repo(client))["id"]
+ rows = [
+ {**_metric("src/a.py", 4.0, 100), "code_origin": "production"},
+ {**_metric("src/b.py", 8.0, 300), "code_origin": "production"},
+ {**_metric("tests/test_a.py", 10.0, 200), "code_origin": "test", "is_test": True},
+ {**_metric("setup.py", 2.0, 40), "code_origin": "build"},
+ {**_metric("src/gen_pb2.py", 1.0, 400), "code_origin": "generated"},
+ ]
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(session, repo_id, rows)
+ await session.commit()
+ return repo_id
+
+
+async def test_hold_map_leaves_the_held_origins_out_of_every_figure(app, client):
+ repo_id = await _seed_origins(app, client)
+ tree = (await client.get(f"/api/repos/{repo_id}/areas/tree", params={"hold": "map", "depth": 2})).json()
+ root = tree["root"]
+ # Only the two production files: (4*100 + 8*300) / 400 = 7.0.
+ assert root["file_count"] == 2
+ assert root["health"] == 7.0
+ # A folder holding only tests is simply not there.
+ assert "tests" not in {n["path"] for n in tree["nodes"]}
+ held = tree["held"]
+ assert held["excluded"] == sorted(held["default"])
+ assert held["counts"]["test"] == 1 and held["counts"]["build"] == 1 and held["counts"]["generated"] == 1
+ feed = (await client.get(f"/api/repos/{repo_id}/health/map", params={"hold": "map"})).json()
+ assert {f["file_path"] for f in feed["files"]} == {"src/a.py", "src/b.py"}
+
+
+async def test_include_brings_one_held_origin_back(app, client):
+ repo_id = await _seed_origins(app, client)
+ params = {"hold": "map", "include": "test", "depth": 2}
+ tree = (await client.get(f"/api/repos/{repo_id}/areas/tree", params=params)).json()
+ assert tree["root"]["file_count"] == 3
+ assert "test" not in tree["held"]["excluded"]
+ detail = (await client.get(f"/api/repos/{repo_id}/areas/tests", params=params)).json()
+ assert detail["area"]["file_count"] == 1
+
+
+async def test_without_hold_the_root_equals_the_page_headline(app, client):
+ # The page's "All code" scope and the map's everything-included view are
+ # the same files, so the root and the headline are one number.
+ repo_id = await _seed_origins(app, client)
+ tree = (await client.get(f"/api/repos/{repo_id}/areas/tree")).json()
+ overview = (await client.get(f"/api/repos/{repo_id}/health/overview", params={"limit": 1})).json()
+ assert tree["root"]["health"] == overview["summary"]["average_health"]
+ assert tree["held"]["excluded"] == []
+
+
+async def test_bringing_every_held_group_back_is_the_whole_repository(app, client):
+ repo_id = await _seed_origins(app, client)
+ whole = (await client.get(f"/api/repos/{repo_id}/areas/tree")).json()
+ params = {"hold": "map", "include": ",".join(whole["held"]["default"])}
+ back = (await client.get(f"/api/repos/{repo_id}/areas/tree", params=params)).json()
+ overview = (await client.get(f"/api/repos/{repo_id}/health/overview", params={"limit": 1})).json()
+ assert back["root"]["health"] == whole["root"]["health"] == overview["summary"]["average_health"]
+ assert back["held"]["excluded"] == []
+
+
+async def test_every_group_back_draws_generated_files_too(app, client):
+ # With every held group brought back the set is empty, and the map must
+ # still read that as "hold nothing", not as the default vendored hold.
+ repo_id = await _seed_origins(app, client)
+ whole = (await client.get(f"/api/repos/{repo_id}/areas/tree")).json()
+ params = {"hold": "map", "include": " TEST, " + ",".join(whole["held"]["default"])}
+ feed = (await client.get(f"/api/repos/{repo_id}/health/map", params=params)).json()
+ assert "src/gen_pb2.py" in {f["file_path"] for f in feed["files"]}
+ assert feed["omitted"]["held"] == 0
diff --git a/tests/unit/server/test_health_map_feed.py b/tests/unit/server/test_health_map_feed.py
index e049b47e7..51decc22f 100644
--- a/tests/unit/server/test_health_map_feed.py
+++ b/tests/unit/server/test_health_map_feed.py
@@ -374,3 +374,18 @@ async def test_a_query_pins_the_files_whose_path_contains_it(app, client):
assert "src/needle_here.py" in [f["file_path"] for f in feed["files"]]
assert feed["selection"]["query_matches"] == 1
assert feed["selection"]["query_shown"] == 1
+
+
+async def test_rows_flag_the_hotspots_the_kpi_averages_over(app, client):
+ # The hotspot health lens greys every file that is not a hotspot, so the
+ # flag has to come from the same set ``hotspot_health`` averages over.
+ repo_id = await _seed(app, client)
+ async with app.state.session_factory() as session:
+ await crud.upsert_git_metadata(
+ session, repository_id=repo_id, file_path="src/big0.py", is_hotspot=True
+ )
+ await session.commit()
+ feed = await _feed(client, repo_id, cap=100)
+ flags = {f["file_path"]: f["is_hotspot"] for f in feed["files"]}
+ assert flags["src/big0.py"] is True
+ assert flags["src/tiny.py"] is False
diff --git a/tests/unit/test_no_hotspot_health_copies.py b/tests/unit/test_no_hotspot_health_copies.py
index aa93d3d4a..74b24083d 100644
--- a/tests/unit/test_no_hotspot_health_copies.py
+++ b/tests/unit/test_no_hotspot_health_copies.py
@@ -42,6 +42,9 @@ _PLUMBING: dict[str, str] = {
"repowise/core/persistence/models.py": "the column",
"repowise/core/persistence/crud/analysis/health/snapshots.py": "writes/reads the column",
"repowise/core/persistence/crud/git.py": "supplies the hotspot path set, not the score",
+ "repowise/server/services/health_map.py": (
+ "reads the hotspot path set for the map's hotspot lens, not the score"
+ ),
"repowise/core/persistence/stores/_sql_analysis.py": "passthrough to the crud writer",
"repowise/core/workspace/store.py": "copies the latest snapshot column into the workspace store",
"repowise/core/persistence/_interfaces/_analysis.py": "the store ABC's parameter name",