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(code-health): a clearer map, file drawer and trend for every repo size (#3879)

Raghav Chamadiya215776c2e77a
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index 08dbc2bf2..bfd8c4c7b 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -183,6 +183,8 @@ export async function getHealthMap(
active: opts.active?.length ? opts.active.join(",") : undefined,
scope: opts.scope,
counts: opts.counts,
+ include_held: opts.include_held || undefined,
+ q: opts.q?.trim() || undefined,
});
}
diff --git a/packages/core/src/repowise/core/analysis/finding_registry.py b/packages/core/src/repowise/core/analysis/finding_registry.py
index 79047dd7b..4d26afefd 100644
--- a/packages/core/src/repowise/core/analysis/finding_registry.py
+++ b/packages/core/src/repowise/core/analysis/finding_registry.py
@@ -32,6 +32,7 @@ from __future__ import annotations
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
+from functools import lru_cache
from pathlib import PurePosixPath
from typing import Any, Literal
@@ -250,9 +251,15 @@ def previews_on(layer: GateLayer) -> tuple[LanguageGate, ...]:
return tuple(g for g in LANGUAGE_GATES if g.layer == layer and g.state == "preview")
+@lru_cache(maxsize=1 << 16)
+def _suffix(path: str) -> str:
+ # Cached: a gate pass asks once per finding, so a file's path repeats.
+ return PurePosixPath(path).suffix.lower()
+
+
def language_of(path: str) -> str | None:
"""The language tag a stored path's extension maps to, or ``None``."""
- return EXTENSION_TO_LANGUAGE.get(PurePosixPath(path or "").suffix.lower())
+ return EXTENSION_TO_LANGUAGE.get(_suffix(path or ""))
def _match(
diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.py
index dad02d08f..43ce74f53 100644
--- a/packages/core/src/repowise/core/analysis/health/trends.py
+++ b/packages/core/src/repowise/core/analysis/health/trends.py
@@ -158,13 +158,19 @@ class _ScopedSnapshot:
taken_at: Any
average_health: float
- per_file_scores_json: str
+ #: The stored row, so the per-file map is read only by a caller that asks
+ #: for it: a route that deferred the maps loads just the rows it reads.
+ source: Any = field(default=None, repr=False)
hotspot_health: float | None = None
worst_performer_path: str | None = None
worst_performer_score: float | None = None
structure_average: float | None = None
history_average: float | None = None
+ @property
+ def per_file_scores_json(self) -> str:
+ return self.source.per_file_scores_json
+
def project_scope(history: list[Any], scope: str) -> list[Any]:
"""Re-read a snapshot series through one scope.
@@ -187,7 +193,7 @@ def project_scope(history: list[Any], scope: str) -> list[Any]:
_ScopedSnapshot(
taken_at=snap.taken_at,
average_health=float(value),
- per_file_scores_json=snap.per_file_scores_json,
+ source=snap,
)
)
return out
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 67b4f37cc..ef0307f17 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, NamedTuple
from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import defer
if TYPE_CHECKING:
from ....analysis.health.perf.coverage import PerfCoverage
@@ -1076,11 +1077,16 @@ async def list_health_snapshots(
repository_id: str,
*,
limit: int | None = None,
+ file_maps: bool = True,
) -> list[HealthSnapshot]:
"""Return snapshots **oldest-first** (the shape ``trends.diff_snapshots``
expects). Pass ``limit`` to cap the most recent N (still returned
oldest-first for stable iteration).
+ ``file_maps=False`` defers both per-file maps, for a caller that reads the
+ scalars of every row and the maps of a few: it loads those with
+ ``session.refresh(row, ["per_file_scores_json"])``.
+
``limit`` is pushed into SQL rather than applied to the fetched list. Every
row carries ``per_file_scores_json`` and ``per_file_deductions_json``, both
whole-repo ``{path: float}`` maps, and the table keeps
@@ -1088,19 +1094,18 @@ async def list_health_snapshots(
entire history off disk to throw most of it away. Taking the newest N
descending and reversing gives the same list for a fraction of the bytes.
"""
+ base = select(HealthSnapshot).where(HealthSnapshot.repository_id == repository_id)
+ if not file_maps:
+ base = base.options(
+ defer(HealthSnapshot.per_file_scores_json),
+ defer(HealthSnapshot.per_file_deductions_json),
+ )
if limit is not None:
newest_first = await session.execute(
- select(HealthSnapshot)
- .where(HealthSnapshot.repository_id == repository_id)
- .order_by(HealthSnapshot.taken_at.desc(), HealthSnapshot.id.desc())
- .limit(limit)
+ base.order_by(HealthSnapshot.taken_at.desc(), HealthSnapshot.id.desc()).limit(limit)
)
return list(reversed(newest_first.scalars().all()))
- q = (
- select(HealthSnapshot)
- .where(HealthSnapshot.repository_id == repository_id)
- .order_by(HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc())
- )
+ q = base.order_by(HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc())
result = await session.execute(q)
return list(result.scalars().all())
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 44974317e..9d2d623c6 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
@@ -37,12 +37,26 @@ async def get_health_map(
"them so the cap can never push the subject off its own map."
),
),
+ include_held: bool = Query(
+ False,
+ description="Also draw vendored and generated files, which are held out by default.",
+ ),
+ q: str | None = Query(
+ None,
+ max_length=200,
+ description="Pin the files whose path contains this substring, so search finds undrawn files.",
+ ),
scope: str = ScopeQuery,
counts: str = CountsQuery,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""One bounded field plus the exact scope of what the cap left out."""
feed = await HealthMapService(session, repo_id).feed(
- cap=cap, active=parse_active(active), scope=scope, counts=counts
+ cap=cap,
+ active=parse_active(active),
+ scope=scope,
+ counts=counts,
+ include_held=include_held,
+ query=q,
)
return feed.payload()
diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
index ac5f70dd3..45f814626 100644
--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
@@ -28,7 +28,7 @@ from ._router import router
from .counts import CountsQuery, project
from .loaders import _attach_symbol_ids
from .scope import ScopeQuery, narrow
-from .serializers import _finding_to_dict, _leads_by_file, _metric_to_dict
+from .serializers import _finding_to_dict, _leads_by_file, _metric_to_dict, _round_opt
def _resolve_last_indexed_at(
@@ -110,8 +110,16 @@ async def health_overview(
last_indexed_at = _resolve_last_indexed_at(snapshot.taken_at, repo.updated_at)
- leads = _leads_by_file(findings)
- metric_dicts = [_metric_to_dict(m, leads.get(m.file_path)) for m in metrics]
+ # The full row, and its lead, only for the files the response lists. The
+ # distribution and the defect-accuracy stat read path, score and NLOC off
+ # every file, at the same rounding the full row carries.
+ listed = metrics[:limit]
+ listed_paths = {m.file_path for m in listed}
+ leads = _leads_by_file([f for f in findings if f.file_path in listed_paths])
+ file_rows = [_metric_to_dict(m, leads.get(m.file_path)) for m in listed]
+ score_rows = [
+ {"file_path": m.file_path, "score": _round_opt(m.score), "nloc": m.nloc} for m in metrics
+ ]
# Repo-level band (from the NLOC-weighted average) + the per-band file
# distribution. Both derive purely from the existing score — no new data.
@@ -129,14 +137,14 @@ async def health_overview(
"band": headline_band(avg, summary.get("analysed_share")),
"gated": gated,
}
- distribution = health_distribution(metric_dicts)
+ distribution = health_distribution(score_rows)
# "Does the score find the bugs?" self-validation, derived from the same
# metrics + findings (prior_defect biomarker) already loaded above. ``None``
# when the repo lacks enough files / defect history to be honest.
#
# Fed the rows it actually reads. It reads ``file_path`` / ``score`` off the
- # metrics — so ``metric_dicts`` above serves, no second conversion — and
+ # metrics — so ``score_rows`` above serves, no second conversion — and
# only the ``prior_defect`` findings, so converting the other ~90% (which
# means a ``json.loads`` of every ``details_json``) was pure waste.
# Summed over every open finding, not the ``prior_defect`` slice below: a
@@ -145,7 +153,7 @@ async def health_overview(
# shared with the module rollup.
deductions = deduction_by_path(scored_findings)
defect_accuracy = compute_defect_accuracy(
- metric_dicts,
+ score_rows,
[_finding_to_dict(f) for f in scored_findings if f.biomarker_type == "prior_defect"],
deductions=deductions,
)
@@ -166,7 +174,7 @@ async def health_overview(
"summary": summary,
"distribution": distribution,
"defect_accuracy": defect_accuracy,
- "files": metric_dicts[:limit],
+ "files": file_rows,
"top_findings": top_findings,
"modules": module_rollups(metrics, deductions),
"biomarkers": biomarker_breakdown(findings),
diff --git a/packages/server/src/repowise/server/routers/code_health/trends_routes.py b/packages/server/src/repowise/server/routers/code_health/trends_routes.py
index 374b9416d..73399cc4e 100644
--- a/packages/server/src/repowise/server/routers/code_health/trends_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/trends_routes.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
@@ -28,6 +29,34 @@ from .serializers import _file_trend_to_dict
FILE_DELTA_LIMIT: int = 50
+async def _score_map(session: AsyncSession, snap: Any) -> dict:
+ """One snapshot's ``{path: score}`` map, loaded now because the list deferred it."""
+ row = getattr(snap, "source", None) or snap # a scoped projection reads through
+ await session.refresh(row, ["per_file_scores_json"])
+ return json.loads(row.per_file_scores_json or "{}")
+
+
+def _by_size(row: dict) -> tuple[float, str]:
+ return (-abs(row["delta"]), row["file_path"])
+
+
+def _slice_both_ways(deltas: list[dict]) -> list[dict]:
+ """The largest ``FILE_DELTA_LIMIT`` movements, with half the slice held for
+ each direction while that direction has rows to fill it.
+
+ The page lists "got worse" and "improved" as two groups, and a plain top-N
+ by size let a wave of small regressions leave the improved group empty
+ beside a count saying it has rows. Either direction still takes the whole
+ slice when the other has too few to use its half. Largest first.
+ """
+ worse = [d for d in deltas if d["delta"] < 0]
+ improved = [d for d in deltas if d["delta"] > 0]
+ half = FILE_DELTA_LIMIT // 2
+ keep_worse = min(len(worse), max(half, FILE_DELTA_LIMIT - len(improved)))
+ keep_improved = min(len(improved), FILE_DELTA_LIMIT - keep_worse)
+ return sorted(worse[:keep_worse] + improved[:keep_improved], key=_by_size)
+
+
@router.get(
"/api/repos/{repo_id}/health/files/trend",
response_model=FileHealthTrendResponse,
@@ -59,7 +88,11 @@ async def health_trend(
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
narrowed = parse_scope(scope) == "production"
- snapshots = project_scope(await crud.list_health_snapshots(session, repo_id), scope)
+ # Every row's scalars, but only the last two rows' per-file maps: each map
+ # is sized by the repository, and the movement list is all that reads them.
+ snapshots = project_scope(
+ await crud.list_health_snapshots(session, repo_id, file_maps=False), scope
+ )
summary = diff_snapshots(snapshots)
# Snapshots record per-file scores for the whole repository, so a narrowed
# response has to drop the test files from the movement list too.
@@ -69,8 +102,8 @@ async def health_trend(
file_deltas: list[dict] = []
if len(snapshots) >= 2:
try:
- prev = json.loads(snapshots[-2].per_file_scores_json or "{}")
- cur = json.loads(snapshots[-1].per_file_scores_json or "{}")
+ prev = await _score_map(session, snapshots[-2])
+ cur = await _score_map(session, snapshots[-1])
except Exception:
prev, cur = {}, {}
all_paths = set(prev) | set(cur)
@@ -87,10 +120,8 @@ async def health_trend(
# slicing made the block the N biggest *drops*: improvements only
# survived the cut while fewer than ``FILE_DELTA_LIMIT`` files had
# regressed, so the one render that most wants to show progress — the
- # index after a cleanup — is the one that hides it. The client
- # (``TrendSlopeChart``) already ranks by absolute delta before drawing,
- # so this is also the order it was asking for.
- file_deltas.sort(key=lambda r: (-abs(r["delta"]), r["file_path"]))
+ # index after a cleanup — is the one that hides it.
+ file_deltas.sort(key=_by_size)
return {
"history": (
@@ -122,10 +153,13 @@ async def health_trend(
}
for a in summary.alerts
],
- "file_deltas": file_deltas[:FILE_DELTA_LIMIT],
+ "file_deltas": _slice_both_ways(file_deltas),
# The true count behind the slice, so the UI can say "N of M" instead
# of presenting a truncated list as the whole story.
"file_deltas_total": len(file_deltas),
+ # Each direction's true count, so a "got worse" group can say "N of M".
+ "file_deltas_worse": sum(1 for d in file_deltas if d["delta"] < 0),
+ "file_deltas_improved": sum(1 for d in file_deltas if d["delta"] > 0),
"snapshot_count": len(snapshots),
"scope": scope,
}
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
index 9fcec48f9..7290637a9 100644
--- a/packages/server/src/repowise/server/schemas/code_health.py
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -159,6 +159,10 @@ class HealthTrendResponse(BaseModel):
file_deltas: list[HealthFileDelta] = []
#: The count behind the slice, so the UI can say "N of M".
file_deltas_total: int = 0
+ #: How many of ``file_deltas_total`` fell and rose; half the slice is held
+ #: for each direction while it has rows to fill it.
+ file_deltas_worse: int = 0
+ file_deltas_improved: int = 0
snapshot_count: int = 0
#: Which half of the repository these figures describe.
scope: str = "all"
diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.py
index db2426bfa..486539afd 100644
--- a/packages/server/src/repowise/server/services/health_map.py
+++ b/packages/server/src/repowise/server/services/health_map.py
@@ -6,20 +6,27 @@ for the health lens and the wrong one for the performance lens: on this
repository it hides tens of files that carry open opportunities, because a
small file can hold the worst cause in the tree.
-So the feed admits files in three bands - the caller's active selection first,
-then the files carrying open performance opportunities in rank order, then the
-lines-of-code sample fills whatever capacity is left - and states exactly what
-the cap pushed out. One response carries both the rendered set and the counts
-describing it, so a caption can never disagree with the field beside it.
+So the feed admits files in a fixed order - the caller's pinned paths first,
+then a small floor per module so a little module never vanishes behind a big
+one, then everything else by origin tier (production, tooling and build, test,
+docs examples), and inside a tier the files carrying open performance
+opportunities in rank order before a health-debt rank that puts unhealthy, large
+files ahead of clean ones. Vendored and generated files are held out unless the
+caller asks for them, because they are not the reader's to change. The response
+states exactly what the cap and the hold pushed out. One response carries both
+the rendered set and the counts describing it, so a caption can never disagree
+with the field beside it.
"""
from __future__ import annotations
+import math
from dataclasses import dataclass, field
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import HELD_ORIGINS
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
@@ -37,8 +44,9 @@ __all__ = [
DEFAULT_MAP_CAP = 2000
"""Nodes drawn by default. Above this the field stops separating anything."""
-MAX_MAP_CAP = 4000
-"""Ceiling a caller may raise the cap to. Beyond it the canvas is a texture."""
+MAX_MAP_CAP = 8000
+"""Ceiling a caller may raise the cap to. The client draws on a canvas, which
+holds this many nodes at frame rate; past it the field is a texture."""
_MAX_ACTIVE = 50
"""Guaranteed paths one request may pin. A deep link names one or a few."""
@@ -46,6 +54,26 @@ _MAX_ACTIVE = 50
_MODULE_ROLLUP_CAP = 200
"""Modules described in the textual alternative, worst performance first."""
+_MODULE_FLOOR = 2
+"""Files each module is guaranteed before the global ranking spends the cap."""
+
+_MODULE_FLOOR_SHARE = 0.2
+"""Most of the cap the per-module floor may take, so the ranking still leads."""
+
+_BASIS = "active_then_module_floor_then_origin_tier_then_performance_then_debt"
+
+#: Where a file's code comes from, as an admission tier. Lower draws first. A
+#: row written before ``code_origin`` existed falls back on ``is_test``.
+_ORIGIN_TIER: dict[str, int] = {
+ "production": 0,
+ "tooling": 1,
+ "build": 1,
+ "test": 2,
+ "docs_example": 3,
+ "vendored": 4,
+ "generated": 4,
+}
+
@dataclass
class HealthMapFeed:
@@ -114,6 +142,8 @@ class HealthMapService:
active: tuple[str, ...] = (),
scope: str = DEFAULT_SCOPE,
counts: str = DEFAULT_COUNTS,
+ include_held: bool = False,
+ query: str | None = None,
) -> HealthMapFeed:
session, repo_id = self._session, self._repository_id
metrics = await crud.get_health_metrics(session, repo_id)
@@ -143,10 +173,27 @@ class HealthMapService:
by_path = {m.file_path: m for m in metrics}
# A zero-NLOC file cannot be sized, and the map drops it on arrival.
# Counting it as eligible would promise a node that never appears.
- eligible = [m for m in metrics if (m.nloc or 0) > 0]
+ drawable = [m for m in metrics if (m.nloc or 0) > 0]
+ # Vendored and generated code is held out unless asked for, but a path
+ # the caller pinned is drawn whatever it is: a link names its subject.
+ pinned = set(active)
+ eligible = [
+ m
+ 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)
eligible_paths = {m.file_path for m in eligible}
burden = {r.file_path: r for r in rollups}
+ # A file whose only causes are ``expected`` has nothing to do; it earns no priority slot.
+ open_rollups = [r for r in rollups if r.opportunities > r.expected]
+ perf_position = {
+ r.file_path: i for i, r in enumerate(open_rollups) if r.file_path in eligible_paths
+ }
+ # One sort on one key, so every band below is a walk down one list.
+ ordered = sorted(eligible, key=lambda m: _admission_key(m, perf_position))
+
chosen: list[str] = []
taken: set[str] = set()
@@ -159,17 +206,40 @@ class HealthMapService:
active_shown = [path for path in active if admit(path)]
- # A file whose only causes are ``expected`` has nothing to do; it earns no priority slot.
- open_rollups = [r for r in rollups if r.opportunities > r.expected]
- performance_eligible = [r.file_path for r in open_rollups if r.file_path in eligible_paths]
- performance_shown = sum(1 for path in performance_eligible if admit(path))
-
- nloc_before = len(chosen)
- for metric in sorted(eligible, key=lambda m: (-(m.nloc or 0), m.file_path)):
+ # Search pins its matches, so the box can find a file the cap left out.
+ needle = (query or "").strip().lower()
+ query_matches = 0
+ query_shown = 0
+ if needle:
+ for metric in ordered:
+ if needle not in metric.file_path.lower():
+ continue
+ query_matches += 1
+ if query_shown < _MAX_ACTIVE and admit(metric.file_path):
+ query_shown += 1
+
+ # The floor walks the same ranked list once per guaranteed slot, so
+ # every module gets its most pressing file before any gets a second,
+ # and the modules holding the most pressing files go first when the
+ # budget cannot reach them all.
+ floor_budget = int(cap * _MODULE_FLOOR_SHARE)
+ floor_before = len(chosen)
+ per_module: dict[str, int] = {}
+ for slot in range(_MODULE_FLOOR):
+ for metric in ordered:
+ if len(chosen) - floor_before >= floor_budget:
+ break
+ key = metric.module or ""
+ if per_module.get(key, 0) == slot and admit(metric.file_path):
+ per_module[key] = slot + 1
+ floor_shown = len(chosen) - floor_before
+
+ ranked_before = len(chosen)
+ for metric in ordered:
if len(chosen) >= cap:
break
admit(metric.file_path)
- nloc_shown = len(chosen) - nloc_before
+ ranked_shown = len(chosen) - ranked_before
drawn = [by_path[path] for path in chosen]
files = [
@@ -188,7 +258,13 @@ class HealthMapService:
"performance_files": len(undrawn_perf),
"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,
}
+ # What the bands after the pins admitted, split the way older readers
+ # count it: the performance band, and everything else.
+ banded = chosen[floor_before:]
+ performance_shown = sum(1 for p in banded if p in perf_position)
return HealthMapFeed(
files=files,
@@ -197,19 +273,28 @@ class HealthMapService:
eligible_total=len(eligible),
repository_total=counted,
selection={
- "basis": "active_then_performance_then_nloc",
+ "basis": _BASIS,
"active_requested": list(active),
"active_shown": active_shown,
"active_missing": [p for p in active if p not in taken],
"performance_shown": performance_shown,
- "performance_eligible": len(performance_eligible),
- "nloc_shown": nloc_shown,
+ "performance_eligible": len(perf_position),
+ # Admitted by rank without an open cause. Kept under its old
+ # name, which predates the debt rank, for existing readers.
+ "nloc_shown": len(banded) - performance_shown,
+ "module_floor_shown": floor_shown,
+ "ranked_shown": ranked_shown,
+ "query": needle or None,
+ "query_matches": query_matches,
+ "query_shown": query_shown,
+ "include_held": include_held,
},
omitted=omitted,
recovery={
"guarantee_paths": (
"Re-request this feed with active=<comma-separated paths> to pin any "
- "file into the drawn field."
+ "file into the drawn field, or q=<substring> to pin up to "
+ f"{_MAX_ACTIVE} files whose path contains it."
),
"opportunity_queue": (
f"/api/repos/{repo_id}/health/performance-opportunities lists open "
@@ -217,6 +302,7 @@ class HealthMapService:
"context=all for every execution context."
),
"raise_cap": f"cap accepts up to {MAX_MAP_CAP}.",
+ "include_held": "include_held=true draws vendored and generated files too.",
},
modules=self._modules(drawn, burden),
# The stored performance summary is a repo-wide aggregate and there
@@ -225,7 +311,7 @@ class HealthMapService:
performance=(
None
if scope_narrowed
- else self._performance_block(rollups, summary, len(performance_eligible))
+ else self._performance_block(rollups, summary, len(perf_position))
),
scope=DEFAULT_SCOPE if not scope_narrowed else "production",
counts=counts,
@@ -258,6 +344,7 @@ class HealthMapService:
# What the default queue shows: ``expected`` causes have nothing to do.
"performance_opportunities": rollup.opportunities - rollup.expected if rollup else 0,
"performance_observations": rollup.observations if rollup else 0,
+ "code_origin": metric.code_origin,
}
actionability = _leading_actionability(rollup)
if actionability is not None:
@@ -333,6 +420,34 @@ class HealthMapService:
}
+def _origin_tier(metric: Any) -> int:
+ """Admission tier for one row; an unstamped row is read off ``is_test``."""
+ origin = metric.code_origin
+ if origin in _ORIGIN_TIER:
+ return _ORIGIN_TIER[origin]
+ return _ORIGIN_TIER["test"] if metric.is_test else _ORIGIN_TIER["production"]
+
+
+def _admission_key(metric: Any, perf_position: dict[str, int]) -> tuple[Any, ...]:
+ """Where one file sits in the admission order, as a total sort key.
+
+ Inside a tier, an open performance cause leads in queue order. Then health
+ debt, ``(10 - score) * sqrt(nloc)``: an unhealthy file outranks a clean one
+ of any size, and among equally unhealthy files the bigger one carries more.
+ A file health could not score has no debt to rank, so it follows the scored
+ ones by size. The path breaks every tie, so two reads agree.
+ """
+ nloc = metric.nloc or 0
+ tier = _origin_tier(metric)
+ position = perf_position.get(metric.file_path)
+ if position is not None:
+ return (tier, 0, position, 0, metric.file_path)
+ if metric.score is None:
+ return (tier, 2, 0, -nloc, metric.file_path)
+ debt = max(0.0, 10.0 - metric.score) * math.sqrt(nloc)
+ return (tier, 1, -debt, -nloc, metric.file_path)
+
+
def _leading_actionability(rollup: Any) -> str | None:
"""The best thing a reader could do about this file, or nothing.
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index ba69fd595..938ec25a8 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2262,6 +2262,8 @@ export interface HealthTrendResponse {
alerts?: HealthTrendAlert[];
file_deltas?: HealthFileDelta[];
file_deltas_total?: number;
+ file_deltas_worse?: number;
+ file_deltas_improved?: number;
snapshot_count?: number;
scope?: string;
}
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 39231acdd..ef26a41f0 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -132,6 +132,12 @@ export const GOOD_MIN = 7.0;
export const FAIR_MIN = 5.5;
export const NEEDS_WORK_MIN = 4.0;
+/**
+ * The canonical three-band reading beside a health mark: Healthy at 8 or
+ * above, Warning from 4, Alert below 4 (`NEEDS_WORK_MIN`).
+ */
+export const HEALTHY_MIN = 8.0;
+
/** Worst-first, matching how the surfaces list files. */
export const HEALTH_BAND_ORDER: readonly HealthBand[] = [
"at_risk",
@@ -276,6 +282,12 @@ export interface HealthFileMetric {
* without re-deriving the answer from the path on every surface.
*/
is_test?: boolean;
+ /**
+ * Where the file's code comes from (`production`, `test`, `vendored`,
+ * `generated`, `docs_example`, `tooling`, `build`). `null` on rows scored
+ * before the column existed; absent on payloads that do not carry it.
+ */
+ code_origin?: string | null;
/**
* Open performance-risk findings on this file. The performance lens on the
* code-health map colors by this count (+ `performance_analyzed`), not by the
@@ -871,7 +883,15 @@ export interface HealthFilesQuery {
* repository by size alone is a defensible sample for the health lens and the
* wrong one for performance, because a small file can hold the worst cause.
*/
-export type HealthMapSelectionBasis = "active_then_performance_then_nloc";
+export type HealthMapSelectionBasis =
+ | "active_then_performance_then_nloc"
+ /**
+ * The pins, then a floor of two files per module, then everything else by
+ * origin tier (production, tooling and build, test, docs examples) with open
+ * performance causes leading each tier and a health-debt rank after them.
+ * Vendored and generated files are held out unless `include_held` is set.
+ */
+ | "active_then_module_floor_then_origin_tier_then_performance_then_debt";
export interface HealthMapSelection {
basis: HealthMapSelectionBasis;
@@ -883,6 +903,16 @@ export interface HealthMapSelection {
performance_shown: number;
performance_eligible: number;
nloc_shown: number;
+ /** Files the per-module floor admitted. Absent on older servers. */
+ module_floor_shown?: number;
+ /** The search substring the field pinned matches for, or `null`. */
+ query?: string | null;
+ /** Eligible files whose path contains the query, drawn or not. */
+ query_matches?: number;
+ /** Matches the query pinned into the field (bounded). */
+ query_shown?: number;
+ /** Whether vendored and generated files were admitted. */
+ include_held?: boolean;
}
/** What the cap pushed out, in the units a reader would ask about. */
@@ -891,6 +921,11 @@ export interface HealthMapOmissions {
performance_files: number;
opportunities: number;
observations: number;
+ /**
+ * Drawable vendored and generated files held out of the field (not counted
+ * in `files`). Absent on servers that do not hold them out.
+ */
+ held?: number;
}
export interface HealthMapModuleRollup {
@@ -946,6 +981,10 @@ export interface HealthMapQuery {
active?: string[];
/** Which half of the repository to describe. Defaults to `"all"`. */
scope?: HealthScope;
+ /** Also draw vendored and generated files. */
+ include_held?: boolean;
+ /** Pin files whose path contains this substring. */
+ q?: string;
}
/* ------------------------------------------------------------------ *
@@ -1148,6 +1187,12 @@ export interface HealthTrendResponse {
* backend does not send it, so consumers fall back to `file_deltas.length`.
*/
file_deltas_total?: number;
+ /**
+ * How many of those fell and rose. The server holds half the slice for each
+ * direction while it has rows to fill it. Optional like the total.
+ */
+ file_deltas_worse?: number;
+ file_deltas_improved?: number;
snapshot_count: number;
/** Which half of the repository these figures describe. */
scope?: HealthScope;
diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsx
index ee849c727..2d7347bf8 100644
--- a/packages/ui/__tests__/health/code-health-map.test.tsx
+++ b/packages/ui/__tests__/health/code-health-map.test.tsx
@@ -11,6 +11,8 @@ import {
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";
function f(
file_path: string,
@@ -21,24 +23,7 @@ function f(
return { file_path, nloc, score, module, line_coverage_pct: null, has_test_file: false };
}
-// jsdom has no layout engine → stub ResizeObserver so the map can size itself.
-beforeAll(() => {
- class RO {
- cb: ResizeObserverCallback;
- constructor(cb: ResizeObserverCallback) {
- this.cb = cb;
- }
- observe() {
- this.cb(
- [{ contentRect: { width: 800, height: 600 } } as ResizeObserverEntry],
- this as unknown as ResizeObserver,
- );
- }
- unobserve() {}
- disconnect() {}
- }
- vi.stubGlobal("ResizeObserver", RO);
-});
+beforeAll(stubMapEnvironment);
describe("groupByModule", () => {
it("groups files by module, sums NLOC, sorts files biggest-first", () => {
@@ -69,125 +54,116 @@ describe("CodeHealthMap", () => {
expect(getByText(/No files to map yet/i)).toBeInTheDocument();
});
- it("renders file nodes and opens a file on click", () => {
+ it("opens a file when its node is clicked", () => {
const onSelectFile = vi.fn();
const files = [
f("core/a.py", 120, "core", 3),
f("core/b.py", 60, "core", 8),
f("ui/c.py", 40, "ui", 6),
];
- const { container } = render(<CodeHealthMap files={files} onSelectFile={onSelectFile} />);
- // Nodes carry their path on data-path (there is no <title>: it was ~2,000
- // extra nodes driving a native tooltip that duplicated the hover card).
- const target = container.querySelector('circle[data-path="core/a.py"]');
- expect(target).toBeTruthy();
- fireEvent.click(target!);
+ const { getByTestId } = render(<CodeHealthMap files={files} onSelectFile={onSelectFile} />);
+ fireEvent.click(getByTestId("map-canvas"), nodeAt(files, "core/a.py"));
expect(onSelectFile).toHaveBeenCalledWith("core/a.py");
});
- it("draws file nodes without a per-node <title> or non-scaling-stroke", () => {
- const files = [f("core/a.py", 120, "core"), f("core/b.py", 60, "core")];
+ it("draws no element per file", () => {
+ // The field paints on a canvas. As SVG it was a circle per file, and each
+ // hover, zoom frame and lens switch reconciled every one of them.
+ const files = Array.from({ length: 200 }, (_, i) => f(`core/f${i}.py`, 10 + i, "core"));
const { container } = render(<CodeHealthMap files={files} />);
- // Both were per-frame costs on a ~2,000 element layer that re-rasters
- // through a 460ms zoom transition. Asserted so neither creeps back.
+ expect(container.querySelectorAll("circle")).toHaveLength(0);
expect(container.querySelectorAll("title")).toHaveLength(0);
- expect(
- container.querySelectorAll("circle[data-path][vector-effect]"),
- ).toHaveLength(0);
- });
-
- it("keeps the node stroke at 0.5 device px by pre-dividing by the zoom scale", () => {
- const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
- const { container } = render(<CodeHealthMap files={files} />);
- const node = () => container.querySelector('circle[data-path="core/a.py"]');
- // Unzoomed, k === 1, so the raw stroke is the target width.
- expect(Number(node()!.getAttribute("stroke-width"))).toBeCloseTo(0.5, 5);
-
- // Zoom into a galaxy: k > 1, so the user-unit stroke has to shrink by the
- // same factor to land back on 0.5px once the transform scales it up.
- fireEvent.click(container.querySelector("circle[data-galaxy]")!);
- const zoomed = Number(node()!.getAttribute("stroke-width"));
- expect(zoomed).toBeLessThan(0.5);
- expect(zoomed).toBeGreaterThan(0);
+ expect(container.querySelectorAll("canvas")).toHaveLength(2);
});
- it("zooms into a galaxy and Escape returns to the overview", () => {
+ it("zooms into a galaxy from its name and Escape returns to the overview", async () => {
const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
- const { getByText, queryByText, container } = render(<CodeHealthMap files={files} />);
- // Click a galaxy nebula to focus it.
- const blob = container.querySelector("circle[data-galaxy]");
- expect(blob).toBeTruthy();
- fireEvent.click(blob!);
+ 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();
- fireEvent.keyDown(blob!, { key: "Escape" });
+ fireEvent.keyDown(getByRole("group", { name: /Code health map/ }), { key: "Escape" });
expect(queryByText("← Overview")).not.toBeInTheDocument();
});
- it("leaves an Escape aimed at something else alone", () => {
+ 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.
const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
- const { getByText, container } = render(<CodeHealthMap files={files} />);
- fireEvent.click(container.querySelector("circle[data-galaxy]")!);
+ const { getByText, findByRole } = render(<CodeHealthMap files={files} />);
+ fireEvent.click(await findByRole("button", { name: "core" }));
fireEvent.keyDown(document.body, { key: "Escape" });
expect(getByText("← Overview")).toBeInTheDocument();
});
- it("shows the on-canvas health legend", () => {
+ 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.
+ 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);
+ });
+
+ 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"]) {
+ expect(getByRole("button", { name })).toBeInTheDocument();
+ }
+ });
+
+ 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();
- // The legend names the band and the range it covers, on the same
- // vocabulary every other mark on the page uses.
expect(getByText("Excellent · 8.5+")).toBeInTheDocument();
+ expect(getByText("Good · 7.0 to 8.5")).toBeInTheDocument();
+ expect(getByText("Fair · 5.5 to 7.0")).toBeInTheDocument();
expect(getByText("Needs work · 4.0 to 5.5")).toBeInTheDocument();
+ expect(getByText("At risk · under 4.0")).toBeInTheDocument();
});
it("renders the coverage legend under the coverage lens", () => {
const { getByText } = render(
<CodeHealthMap files={[f("a.py", 30, "core")]} overlay="coverage" />,
);
- // Coverage caption + a coverage-specific legend band identify the lens.
expect(getByText(/line coverage/i)).toBeInTheDocument();
expect(getByText("≥80%")).toBeInTheDocument();
});
- it("never fills an analyzed-clear file green under the performance lens", () => {
+ it("never gives an analyzed-clear file a reassuring tone under the performance lens", () => {
// A detector that surfaced nothing has proved the absence of a *supported
- // pattern*, not that the file is fast. Green is the strongest reassurance
- // the surface has, and this is its weakest evidence.
- const files: CodeHealthMapFile[] = [
- { ...f("core/hot.py", 120, "core"), performance_opportunities: 7, performance_observations: 12, performance_actionability: "plan_ready", performance_analyzed: true },
- { ...f("core/clean.py", 80, "core"), performance_opportunities: 0, performance_analyzed: true },
- { ...f("core/leveldb.cc", 60, "core"), performance_opportunities: 0, performance_analyzed: false },
- ];
- const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
- const fillFor = (path: string) =>
- container.querySelector(`circle[data-path="${path}"]`)?.getAttribute("fill");
- for (const path of ["core/hot.py", "core/clean.py", "core/leveldb.cc"]) {
- expect(fillFor(path)).not.toBe("var(--color-node-good)");
- }
- // Both take the one neutral. Which of the two a file is cannot be read off
- // a shade of grey, so the field stops trying and the words carry it.
- expect(fillFor("core/clean.py")).toBe(NEUTRAL_FILL);
- expect(fillFor("core/leveldb.cc")).toBe(NEUTRAL_FILL);
- });
-
- it("carries the burden on the node's own colour, with no second mark", () => {
- const files: CodeHealthMapFile[] = [
- { ...f("core/planned.py", 120, "core"), performance_opportunities: 9, performance_actionability: "plan_ready", performance_analyzed: true },
- { ...f("core/one.py", 100, "core"), performance_opportunities: 1, performance_actionability: "investigate", performance_analyzed: true },
- { ...f("core/clean.py", 80, "core"), performance_opportunities: 0, performance_analyzed: true },
- ];
- const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
- const fillOf = (p: string) =>
- container.querySelector(`circle[data-path="${p}"]`)?.getAttribute("fill");
- expect(fillOf("core/planned.py")).toBe("var(--color-node-at-risk)");
- expect(fillOf("core/one.py")).toBe("var(--color-node-fair)");
- expect(fillOf("core/clean.py")).toBe(NEUTRAL_FILL);
- // Stored plan earns no mark of its own. It is said in words instead.
- expect(container.querySelectorAll("circle[data-plan]")).toHaveLength(0);
+ // pattern*, not that the file is fast. Both kinds of clear take the one
+ // neutral, never the healthy tone.
+ const hot: CodeHealthMapFile = {
+ ...f("core/hot.py", 120, "core"),
+ performance_opportunities: 7,
+ performance_actionability: "plan_ready",
+ performance_analyzed: true,
+ };
+ const clean: CodeHealthMapFile = {
+ ...f("core/clean.py", 80, "core"),
+ performance_opportunities: 0,
+ performance_analyzed: true,
+ };
+ const unsupported: CodeHealthMapFile = {
+ ...f("core/leveldb.cc", 60, "core"),
+ performance_opportunities: 0,
+ performance_analyzed: false,
+ };
+ expect(performanceFill(clean)).toBe(NEUTRAL_FILL);
+ expect(performanceFill(unsupported)).toBe(NEUTRAL_FILL);
+ expect(performanceFill(hot)).toBe(NODE_RAMP_STOP.alert);
});
it("counts observations and says so when the host serves no causal model", () => {
@@ -214,10 +190,7 @@ describe("CodeHealthMap", () => {
it("fires onOverlayChange when a lens-switch button is clicked", () => {
const onOverlayChange = vi.fn();
const { getByRole } = render(
- <CodeHealthMap
- files={[f("a.py", 30, "core")]}
- onOverlayChange={onOverlayChange}
- />,
+ <CodeHealthMap files={[f("a.py", 30, "core")]} onOverlayChange={onOverlayChange} />,
);
// One switcher implementation, on the canvas and off it, so the two can
// never disagree about what picking a lens means.
@@ -225,7 +198,7 @@ describe("CodeHealthMap", () => {
expect(onOverlayChange).toHaveBeenCalledWith("maintainability");
});
- it('offers only the lenses it was given', () => {
+ it("offers only the lenses it was given", () => {
const { getByRole, queryByRole } = render(
<CodeHealthMap
files={[f("a.py", 30, "core")]}
@@ -239,14 +212,25 @@ describe("CodeHealthMap", () => {
expect(queryByRole("radio", { name: "Maintainability" })).not.toBeInTheDocument();
});
- it('chrome="none" renders neither the switcher nor the legend', () => {
- const { queryByText, queryByRole } = render(
+ it("hides a lens the rows carry no data for", () => {
+ // Dead code and security colour from fields this feed does not serve; on
+ // offer they would paint every node grey and read as "clean".
+ const { queryByRole, getByRole } = render(
<CodeHealthMap
files={[f("a.py", 30, "core")]}
onOverlayChange={vi.fn()}
- chrome="none"
+ lenses={["health", "dead-code", "security"]}
/>,
);
+ expect(getByRole("radio", { name: "Code health" })).toBeInTheDocument();
+ expect(queryByRole("radio", { name: "Dead code" })).not.toBeInTheDocument();
+ expect(queryByRole("radio", { name: "Security" })).not.toBeInTheDocument();
+ });
+
+ it('chrome="none" renders neither the switcher nor the legend', () => {
+ const { queryByText, queryByRole } = render(
+ <CodeHealthMap files={[f("a.py", 30, "core")]} onOverlayChange={vi.fn()} chrome="none" />,
+ );
expect(queryByRole("radio", { name: "Maintainability" })).not.toBeInTheDocument();
expect(queryByText(/galaxy = module/i)).not.toBeInTheDocument();
});
diff --git a/packages/ui/__tests__/health/drawer-test-utils.ts b/packages/ui/__tests__/health/drawer-test-utils.ts
new file mode 100644
index 000000000..717574cbe
--- /dev/null
+++ b/packages/ui/__tests__/health/drawer-test-utils.ts
@@ -0,0 +1,66 @@
+/**
+ * Fixtures the file-drawer tests share: a metric row, a finding, a signals
+ * row, and opening a collapsed section by its toggle.
+ */
+
+import { fireEvent, screen } from "@testing-library/react";
+import type { FileSignals } from "@repowise-dev/types/health";
+import type {
+ HealthDrawerFinding,
+ HealthDrawerMetric,
+} from "../../src/health/health-file-drawer.js";
+
+export function drawerMetric(partial: Partial<HealthDrawerMetric> = {}): HealthDrawerMetric {
+ return {
+ file_path: "src/a.py",
+ score: 1.0,
+ max_ccn: 40,
+ max_nesting: 6,
+ nloc: 800,
+ module: "src",
+ has_test_file: false,
+ ...partial,
+ };
+}
+
+let seq = 0;
+export function drawerFinding(partial: Partial<HealthDrawerFinding> = {}): HealthDrawerFinding {
+ seq += 1;
+ return {
+ id: `f${seq}`,
+ biomarker_type: "brain_method",
+ severity: "high",
+ function_name: "_run_repo_checks",
+ line_start: 120,
+ line_end: 487,
+ health_impact: 1.5,
+ reason: "Oversized, deeply-nested function.",
+ ...partial,
+ };
+}
+
+export function drawerSignals(partial: Partial<FileSignals> = {}): FileSignals {
+ return {
+ prior_defect_count: 2,
+ change_entropy_pct: null,
+ lines_added_90d: null,
+ lines_deleted_90d: null,
+ commit_count_90d: 14,
+ age_days: null,
+ primary_owner_name: null,
+ primary_owner_commit_pct: null,
+ recent_owner_name: null,
+ recent_owner_commit_pct: null,
+ in_degree: 4,
+ out_degree: 1,
+ bug_magnet: false,
+ last_fix_at: null,
+ fix_symbol_counts: null,
+ ...partial,
+ };
+}
+
+/** Open a collapsed drawer section by its toggle. */
+export function openSection(name: RegExp) {
+ fireEvent.click(screen.getByRole("button", { name }));
+}
diff --git a/packages/ui/__tests__/health/file-health-prompt.test.tsx b/packages/ui/__tests__/health/file-health-prompt.test.tsx
index fead460ea..2d112e3b5 100644
--- a/packages/ui/__tests__/health/file-health-prompt.test.tsx
+++ b/packages/ui/__tests__/health/file-health-prompt.test.tsx
@@ -164,7 +164,17 @@ describe("the drawer's prompt affordance", () => {
};
it("opens a prompt built from the file the drawer is showing", () => {
- render(<HealthFileDrawer open onClose={() => {}} metric={m} findings={[]} />);
+ const f = {
+ id: "f1",
+ biomarker_type: "brain_method",
+ severity: "high" as const,
+ function_name: "run",
+ line_start: 10,
+ line_end: 90,
+ health_impact: 1.2,
+ reason: "Oversized function.",
+ };
+ render(<HealthFileDrawer open onClose={() => {}} metric={m} findings={[f]} />);
fireEvent.click(screen.getByRole("button", { name: /AI prompt/i }));
expect(screen.getByText(/AI prompt for this file/i)).toBeInTheDocument();
});
@@ -197,9 +207,10 @@ describe("the drawer's prompt affordance", () => {
);
const toggle = screen.getByRole("button", { name: /Why this score/i });
expect(toggle).toHaveAttribute("aria-expanded", "false");
- // The hint says what is inside, so collapsing costs no information.
- expect(toggle.textContent).toContain("−9.00");
- expect(toggle.textContent).toMatch(/1 category/);
+ // The hint says what is inside without restating the total, which is the
+ // body's arithmetic line.
+ expect(toggle.textContent).not.toContain("−9.00");
+ expect(toggle.textContent).toMatch(/1 category, 1 at its limit/);
fireEvent.click(toggle);
expect(toggle).toHaveAttribute("aria-expanded", "true");
diff --git a/packages/ui/__tests__/health/fix-first.test.tsx b/packages/ui/__tests__/health/fix-first.test.tsx
index 4ee5ebc51..5cce026b7 100644
--- a/packages/ui/__tests__/health/fix-first.test.tsx
+++ b/packages/ui/__tests__/health/fix-first.test.tsx
@@ -1,6 +1,6 @@
/**
- * Fix first renders core's queue as it arrives: the section starts open
- * with its count, the header states the scope exactly, exclusions sit in a
+ * Fix first renders core's queue as it arrives: the section starts closed
+ * with its count on the toggle, the header states the scope exactly, exclusions sit in a
* popover, each row is two scan
* lines that open onto the why, steps and Verify, and actions appear only
* where the item can back them.
@@ -39,10 +39,11 @@ function openRow(item: FixItem) {
}
describe("Fix first header", () => {
- it("starts open, with the title and the item count on the toggle", () => {
+ it("starts closed, with the title and the item count on the toggle", () => {
const { container } = renderList();
const details = container.querySelector("details")!;
- expect(details.open).toBe(true);
+ // Under the score: the headline keeps the first screen.
+ expect(details.open).toBe(false);
const summary = container.querySelector("summary")!;
expect(summary.textContent).toContain("Fix first");
expect(summary.textContent).toContain("3 items");
diff --git a/packages/ui/__tests__/health/health-file-drawer-flow.test.tsx b/packages/ui/__tests__/health/health-file-drawer-flow.test.tsx
new file mode 100644
index 000000000..2c1fd6958
--- /dev/null
+++ b/packages/ui/__tests__/health/health-file-drawer-flow.test.tsx
@@ -0,0 +1,493 @@
+/**
+ * The drawer as the map's one selection surface: non-modal, swapped in place,
+ * honest about a failed load, and built to be read in five seconds: a plain
+ * verdict, the top issues, vital signs, and everything else collapsed.
+ */
+
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
+import { HealthFileDrawer } from "../../src/health/health-file-drawer.js";
+import {
+ drawerFinding as finding,
+ drawerMetric as metric,
+ drawerSignals as signals,
+ openSection,
+} from "./drawer-test-utils.js";
+import { ScoreBreakdown } from "../../src/health/score-breakdown.js";
+import { fileVerdict } from "../../src/health/plain-language.js";
+
+const five = () => [
+ finding({ id: "a", biomarker_type: "nested_complexity", function_name: "one", health_impact: 0.5 }),
+ finding({ id: "b", biomarker_type: "brain_method", function_name: "two", health_impact: 3.0 }),
+ finding({ id: "c", biomarker_type: "complex_method", function_name: "three", health_impact: 1.0 }),
+ finding({ id: "d", biomarker_type: "large_method", function_name: "four", health_impact: 2.0 }),
+ finding({ id: "e", biomarker_type: "primitive_obsession", function_name: "five", health_impact: 0.1 }),
+];
+
+const whatsWrong = () => within(screen.getByRole("region", { name: "What's wrong" }));
+
+describe("HealthFileDrawer as one selection surface", () => {
+ it("stays open when the reader clicks the page behind it, and Escape closes it", () => {
+ const onClose = vi.fn();
+ render(
+ <>
+ <button type="button">next file on the map</button>
+ <HealthFileDrawer open onClose={onClose} metric={metric()} />
+ </>,
+ );
+ // Non-modal: a click behind is the reader picking the next file.
+ const behind = screen.getByRole("button", { name: "next file on the map" });
+ fireEvent.pointerDown(behind);
+ fireEvent.click(behind);
+ expect(onClose).not.toHaveBeenCalled();
+ fireEvent.keyDown(document.body, { key: "Escape" });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("names the next file at once and dims the previous one until it lands", () => {
+ const { rerender } = render(
+ <HealthFileDrawer open onClose={() => {}} filePath="src/a.py" metric={metric()} />,
+ );
+ const title = screen.getByRole("heading", { name: /a\.py/ });
+ expect(title).toHaveTextContent("a.py");
+ expect(title).toHaveTextContent("src/");
+ rerender(
+ <HealthFileDrawer open onClose={() => {}} filePath="src/b.py" loading metric={metric()} />,
+ );
+ expect(screen.getByRole("heading", { name: /b\.py/ })).toBeInTheDocument();
+ expect(document.querySelector('[aria-busy="true"]')).not.toBeNull();
+ expect(screen.getByText("1.0")).toBeInTheDocument();
+ });
+
+ it("makes the previous file's body inert while the next one loads", () => {
+ const onStatus = vi.fn(async () => {});
+ const findings = [finding({ id: "a", function_name: "one" })];
+ const { rerender } = render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ filePath="src/a.py"
+ metric={metric()}
+ findings={findings}
+ onFindingStatusChange={onStatus}
+ />,
+ );
+ const busy = () => document.querySelector('[aria-busy="true"]');
+ expect(busy()).toBeNull();
+ rerender(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ filePath="src/b.py"
+ loading
+ metric={metric()}
+ findings={findings}
+ onFindingStatusChange={onStatus}
+ />,
+ );
+ // A triage write from A's body would revalidate B's key, so nothing in it
+ // can be reached until B lands. jsdom does not prune inert subtrees, so
+ // the attribute is the contract.
+ expect(busy()).toHaveAttribute("inert");
+ expect(busy()?.className).toContain("pointer-events-none");
+ });
+
+ it("starts the next file with every disclosure closed again", () => {
+ const { rerender } = render(<HealthFileDrawer open onClose={() => {}} metric={metric()} />);
+ openSection(/Details/);
+ expect(screen.getByRole("button", { name: /Details/ })).toHaveAttribute("aria-expanded", "true");
+ rerender(
+ <HealthFileDrawer open onClose={() => {}} metric={metric({ file_path: "src/b.py" })} />,
+ );
+ expect(screen.getByRole("button", { name: /Details/ })).toHaveAttribute(
+ "aria-expanded",
+ "false",
+ );
+ });
+
+ it("says the request failed and offers a retry, not 'no metric yet'", () => {
+ const onRetry = vi.fn();
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ filePath="src/a.py"
+ error={new Error("Network down")}
+ onRetry={onRetry}
+ metric={null}
+ />,
+ );
+ expect(screen.getByRole("alert")).toHaveTextContent(/Couldn't load this file/);
+ expect(screen.queryByText(/No metric for this file yet/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /Retry/ }));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("HealthFileDrawer verdict", () => {
+ it("says how bad the file is and why in one plain sentence", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric()} findings={five()} />);
+ const verdict = within(screen.getByRole("region", { name: "Verdict" }));
+ expect(verdict.getByText("At risk")).toBeInTheDocument();
+ const sentence = verdict.getByText(/^Hard to change safely:/).textContent ?? "";
+ expect(sentence).toBe("Hard to change safely: three functions are too complex and no test file was found for it.");
+ // No detector jargon on the first screen.
+ for (const word of [/biomarker/i, /CCN/, /NLOC/, /pillar/i, /capped/i, /marker/i]) {
+ expect(sentence).not.toMatch(word);
+ }
+ });
+
+ it("tells a healthy file so, and offers no fix", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric({ score: 9.6, max_ccn: 4 })} findings={[]} />);
+ expect(screen.getByText("Nothing needs fixing here.")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /AI prompt/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole("region", { name: "What's wrong" })).not.toBeInTheDocument();
+ });
+
+ it("offers the points back only when the category is not held at its limit", () => {
+ const findings = [finding({ id: "x", biomarker_type: "large_method", health_impact: 0.8 })];
+ const breakdown = (capped: boolean) => ({
+ score: 9.2,
+ total_deduction: 0.8,
+ categories: [
+ {
+ category: "size_and_complexity",
+ cap: 1.5,
+ raw_deduction: 0.8,
+ applied_deduction: 0.8,
+ capped,
+ finding_count: 1,
+ findings: [],
+ },
+ ],
+ });
+ const { rerender } = render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric({ score: 9.2 })} findings={findings} breakdown={breakdown(false)} />,
+ );
+ expect(screen.getByText(/Fixing the top issue is worth about/).textContent).toContain("0.8 points");
+ rerender(
+ <HealthFileDrawer open onClose={() => {}} metric={metric({ score: 9.2 })} findings={findings} breakdown={breakdown(true)} />,
+ );
+ expect(screen.queryByText(/Fixing the top issue/)).not.toBeInTheDocument();
+ });
+
+ it("keeps the AI prompt primary and the stored plan a quiet link", () => {
+ const opportunity = { opportunity_id: "op1" } as unknown as RefactoringOpportunity;
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={five()}
+ opportunity={opportunity}
+ refactoringOpportunityHref={(id) => `/plan/${id}`}
+ />,
+ );
+ const plan = screen.getByRole("link", { name: /^Refactoring plan$/ });
+ expect(plan).toHaveAttribute("href", "/plan/op1");
+ // Ink, not accent: the accent is the primary action's alone (focus rings aside).
+ expect(plan.className).toContain("text-[var(--color-text-secondary)]");
+ expect(plan.className).not.toMatch(/(^|\s)text-\[var\(--color-accent/);
+ expect(screen.getAllByRole("button", { name: /Fix with AI prompt/ })).toHaveLength(1);
+ });
+});
+
+describe("HealthFileDrawer what's wrong", () => {
+ it("leads with three issues, one per kind, and keeps the rest collapsed", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={five()}
+ breakdown={{ score: 1, total_deduction: 6.6, categories: [] }}
+ signals={signals()}
+ />,
+ );
+ const titles = whatsWrong()
+ .getAllByRole("button", { expanded: false })
+ .map((b) => b.textContent);
+ expect(titles).toEqual([
+ expect.stringContaining("Function does too much"),
+ expect.stringContaining("Very long function"),
+ expect.stringContaining("Too many paths through one function"),
+ ]);
+ for (const name of [/Other issues \(2\)/, /Details/, /History & ownership/, /Dependencies/, /Why this score/]) {
+ expect(screen.getByRole("button", { name })).toHaveAttribute("aria-expanded", "false");
+ }
+ // Hints say what is behind a section without restating its numbers.
+ expect(screen.getByRole("button", { name: /Dependencies/ })).toHaveTextContent("others depend on it");
+ expect(screen.getByRole("button", { name: /Other issues/ })).toHaveTextContent("not repeating the 3 above");
+ });
+
+ it("folds repeats of one kind into a row that says how many more", () => {
+ const repeats = [272, 266, 240].map((line, i) =>
+ finding({ id: `r${i}`, biomarker_type: "error_handling", function_name: null, line_start: line, health_impact: 0.15 - i * 0.01 }),
+ );
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric({ score: 9.3 })} findings={repeats} />);
+ const rows = whatsWrong().getAllByRole("listitem");
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toHaveTextContent("Errors caught too broadly");
+ expect(rows[0]).toHaveTextContent("line 272");
+ expect(rows[0]).toHaveTextContent("and 2 more");
+ });
+
+ it("opens a row onto its evidence and suggested fix", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={[finding({ id: "a", reason: "Cyclomatic 40 across 120 lines." })]}
+ suggestions={{ brain_method: "Split the parsing out of the loop." }}
+ />,
+ );
+ expect(screen.queryByText(/Split the parsing/)).not.toBeInTheDocument();
+ fireEvent.click(whatsWrong().getByRole("button", { name: /Function does too much/ }));
+ expect(screen.getByText(/Cyclomatic 40 across 120 lines\./)).toBeInTheDocument();
+ expect(screen.getByText(/Split the parsing out of the loop\./)).toBeInTheDocument();
+ });
+
+ it("shows a location as plain text unless the host can link to the line", () => {
+ const one = [finding({ id: "a", function_name: "run", line_start: 12 })];
+ const { rerender } = render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={one} fileViewHref="/files/a.py" />,
+ );
+ expect(screen.queryByRole("link", { name: /run:12/ })).not.toBeInTheDocument();
+ rerender(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={one}
+ fileViewHrefFor={(line) => `/files/a.py#L${line}`}
+ />,
+ );
+ fireEvent.click(whatsWrong().getByRole("button", { name: /Function does too much/ }));
+ expect(screen.getByRole("link", { name: /run:12/ })).toHaveAttribute("href", "/files/a.py#L12");
+ });
+
+ it("puts triage behind one menu per row and drops a resolved issue from the lead", async () => {
+ const onStatus = vi.fn(async () => {});
+ render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={five()} onFindingStatusChange={onStatus} />,
+ );
+ expect(screen.queryByRole("button", { name: "Resolved" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Triage Function does too much at two:120" }));
+ // A labelled group of toggle buttons, not a menu without its keyboard.
+ const group = await screen.findByRole("group", { name: "Mark as" });
+ expect(within(group).getByRole("button", { name: "Open" })).toHaveAttribute("aria-pressed", "true");
+ fireEvent.click(within(group).getByRole("button", { name: "Resolved" }));
+ expect(onStatus).toHaveBeenCalledWith("b", "resolved");
+ await waitFor(() => expect(whatsWrong().queryByText("Function does too much")).not.toBeInTheDocument());
+ });
+
+ it("does not repeat the performance causes under the performance lens", () => {
+ const findings = [
+ finding({ id: "p", biomarker_type: "io_in_loop", dimension: "performance", health_impact: 2.0 }),
+ finding({ id: "s", biomarker_type: "large_method", health_impact: 0.5 }),
+ ];
+ const { rerender } = render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ );
+ expect(whatsWrong().getAllByRole("listitem")).toHaveLength(2);
+ rerender(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={findings}
+ lens="performance"
+ performance={{ items: [], total: 0 }}
+ />,
+ );
+ const rows = whatsWrong().getAllByRole("listitem");
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toHaveTextContent("Very long function");
+ });
+
+ it("says how many findings a language gate held back", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={[]}
+ heldBack={{ php: { count: 4, reason: "PHP findings are below the precision bar." } }}
+ />,
+ );
+ openSection(/All issues \(0\)/);
+ expect(screen.getByText(/held back/).textContent).toContain(
+ "4 more findings are held back: PHP findings are below the precision bar.",
+ );
+ });
+});
+
+describe("HealthFileDrawer vital signs", () => {
+ it("states the healthy-or-not picture as a dot and a word per fact", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric({ max_ccn: 40, line_coverage_pct: 12, has_test_file: true })}
+ signals={signals()}
+ />,
+ );
+ const vitals = within(screen.getByRole("list", { name: "Vital signs" }));
+ const read = (label: string) => vitals.getByText(label).nextElementSibling?.textContent;
+ expect(read("Complexity")).toBe("high");
+ expect(read("Test file")).toBe("found");
+ expect(read("Coverage")).toBe("12%");
+ expect(read("Changes often")).toBe("yes");
+ expect(read("Bug fixes")).toBe("a few");
+ });
+
+ it("drops code facts for a file health does not analyse", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric({ score: null, max_ccn: null })} signals={signals()} />);
+ const vitals = within(screen.getByRole("list", { name: "Vital signs" }));
+ expect(vitals.queryByText("Test file")).not.toBeInTheDocument();
+ expect(vitals.getByText("Changes often")).toBeInTheDocument();
+ });
+});
+
+describe("ScoreBreakdown without its finding lists", () => {
+ it("shows categories only when the surface already lists the findings", () => {
+ const categories = [
+ {
+ category: "structural_complexity",
+ cap: 2.5,
+ raw_deduction: 1,
+ applied_deduction: 1,
+ capped: false,
+ finding_count: 1,
+ findings: [
+ { id: "f", biomarker_type: "brain_method", severity: "high" as const, raw_impact: 1, applied_impact: 1, function_name: "run", reason: "" },
+ ],
+ },
+ ];
+ const { rerender } = render(<ScoreBreakdown score={9} totalDeduction={1} categories={categories} />);
+ expect(screen.getByText("run")).toBeInTheDocument();
+ rerender(<ScoreBreakdown score={9} totalDeduction={1} categories={categories} showFindings={false} />);
+ expect(screen.queryByText("run")).not.toBeInTheDocument();
+ expect(screen.getByText("Structural complexity")).toBeInTheDocument();
+ });
+});
+
+describe("fileVerdict", () => {
+ const brain = { biomarker_type: "brain_method", function_name: "run" };
+
+ it("says the file is history-only in plain words", () => {
+ expect(fileVerdict({ score: 7, top: [], historyOnly: true }).text).toMatch(
+ /score comes from change history/,
+ );
+ });
+
+ it("names the problem for an unscored file that still has findings", () => {
+ const v = fileVerdict({ score: null, top: [brain], historyOnly: false });
+ expect(v).toEqual({ text: "Worth a look: one function is too complex.", healthy: false });
+ });
+
+ it("calls a good file clean when what is left takes nothing off", () => {
+ const v = fileVerdict({
+ score: 9.8,
+ top: [],
+ historyOnly: false,
+ rest: { count: 1, impact: 0, historyImpact: 0 },
+ });
+ expect(v).toEqual({ text: "Nothing here takes points off its score.", healthy: true });
+ });
+
+ it("does not call a file clean while findings below still take points off", () => {
+ // The performance lens moves its findings out of the lead, but they still
+ // carry the deduction.
+ const v = fileVerdict({
+ score: 6.1,
+ top: [],
+ historyOnly: false,
+ rest: { count: 2, impact: 1.4, historyImpact: 0 },
+ });
+ expect(v.healthy).toBe(false);
+ expect(v.text).toBe("Its score comes from the issues listed in this panel.");
+ const history = fileVerdict({
+ score: 6.1,
+ top: [],
+ historyOnly: false,
+ rest: { count: 1, impact: 1.4, historyImpact: 1.4 },
+ });
+ expect(history.text).toMatch(/change history/);
+ });
+
+ it("makes no claim before the findings are known", () => {
+ const v = fileVerdict({ score: 3.2, top: [], historyOnly: false, findingsKnown: false });
+ expect(v).toEqual({ text: null, healthy: false });
+ });
+
+ it("does not call a low score clean once its issues are resolved in-session", () => {
+ const v = fileVerdict({ score: 3.2, top: [], historyOnly: false });
+ expect(v.healthy).toBe(false);
+ expect(v.text).not.toMatch(/Nothing needs fixing/);
+ });
+});
+
+describe("HealthFileDrawer honest states", () => {
+ it("keeps the prompt and makes no all-clear for a low score with nothing loaded", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric({ score: 3.2 })} />);
+ expect(screen.queryByText(/Nothing needs fixing/)).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Fix with AI prompt/ })).toBeInTheDocument();
+ });
+
+ it("does not call the file clean after its last issue is resolved here", async () => {
+ const onStatus = vi.fn(async () => {});
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric({ score: 3.2 })}
+ findings={[finding({ id: "only", function_name: "run" })]}
+ onFindingStatusChange={onStatus}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /^Triage / }));
+ fireEvent.click(
+ within(await screen.findByRole("group", { name: "Mark as" })).getByRole("button", { name: "Resolved" }),
+ );
+ await waitFor(() => expect(screen.queryByRole("region", { name: "What's wrong" })).not.toBeInTheDocument());
+ expect(screen.queryByText(/Nothing needs fixing/)).not.toBeInTheDocument();
+ expect(screen.getByText("No open issue on hand explains this score.")).toBeInTheDocument();
+ });
+
+ it("counts every place a row covers in the points it offers back", () => {
+ const findings = [0.3, 0.2].map((impact, i) =>
+ finding({ id: `l${i}`, biomarker_type: "large_method", function_name: `f${i}`, health_impact: impact }),
+ );
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric({ score: 9.5 })}
+ findings={findings}
+ breakdown={{
+ score: 9.5,
+ total_deduction: 0.5,
+ categories: [
+ { category: "size_and_complexity", cap: 1.5, raw_deduction: 0.5, applied_deduction: 0.5, capped: false, finding_count: 2, findings: [] },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getByText(/Fixing the top issue/).textContent).toBe(
+ "Fixing the top issue in all 2 places is worth about 0.5 points.",
+ );
+ });
+
+ it("points aria-controls only at a body that is mounted", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={metric()} findings={five()} />);
+ const row = whatsWrong().getAllByRole("button", { expanded: false })[0]!;
+ expect(row).not.toHaveAttribute("aria-controls");
+ fireEvent.click(row);
+ const id = row.getAttribute("aria-controls");
+ expect(id).toBeTruthy();
+ expect(document.getElementById(id!)).not.toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsx
index 2399e5420..7f47538cb 100644
--- a/packages/ui/__tests__/health/health-file-drawer.test.tsx
+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx
@@ -3,37 +3,20 @@ import { fireEvent, render, screen, within } from "@testing-library/react";
import {
HealthFileDrawer,
type HealthDrawerFinding,
- type HealthDrawerMetric,
} from "../../src/health/health-file-drawer.js";
import type { PerformanceOpportunity } from "@repowise-dev/types/health";
-
-function metric(partial: Partial<HealthDrawerMetric> = {}): HealthDrawerMetric {
- return {
- file_path: "packages/cli/doctor_cmd.py",
- score: 1.0,
- max_ccn: 40,
- max_nesting: 6,
- nloc: 800,
- module: "cli",
- has_test_file: false,
- ...partial,
- };
-}
-
-let seq = 0;
-function finding(partial: Partial<HealthDrawerFinding> = {}): HealthDrawerFinding {
- seq += 1;
- return {
- id: `f${seq}`,
- biomarker_type: "brain_method",
- severity: "high",
- function_name: "_run_repo_checks",
- line_start: 120,
- line_end: 487,
- health_impact: 1.5,
- reason: "Oversized, deeply-nested function.",
- ...partial,
- };
+import {
+ drawerFinding as finding,
+ drawerMetric as metric,
+ openSection,
+} from "./drawer-test-utils.js";
+
+/** Three heavier issues of other kinds, so the findings under test land in
+ * Other issues rather than leading What's wrong. */
+function lead(): HealthDrawerFinding[] {
+ return ["large_method", "complex_method", "primitive_obsession"].map((biomarker_type, i) =>
+ finding({ biomarker_type, function_name: "lead_fn", health_impact: 50 + i }),
+ );
}
describe("HealthFileDrawer finding grouping", () => {
@@ -44,12 +27,13 @@ describe("HealthFileDrawer finding grouping", () => {
finding({ biomarker_type: "deep_nesting", health_impact: 1.0 }),
];
render(
- <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={[...lead(), ...findings]} />,
);
+ openSection(/Other issues/);
// One group header names the function + its worst marker, and sums impact.
const header = screen.getByRole("button", { name: /_run_repo_checks/ });
- expect(within(header).getByText(/3 markers/)).toBeInTheDocument();
+ expect(within(header).getByText(/3 issues/)).toBeInTheDocument();
expect(within(header).getByText(/−6\.00/)).toBeInTheDocument();
});
@@ -65,9 +49,10 @@ describe("HealthFileDrawer finding grouping", () => {
}),
];
render(
- <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={[...lead(), ...findings]} />,
);
- expect(screen.getByRole("button", { name: /File-level signals/ })).toBeInTheDocument();
+ openSection(/Other issues/);
+ expect(screen.getByRole("button", { name: /Across the file/ })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /_run_repo_checks/ })).toBeInTheDocument();
});
@@ -94,19 +79,20 @@ describe("HealthFileDrawer finding grouping", () => {
}),
];
render(
- <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={[...lead(), ...findings]} />,
);
+ openSection(/Other issues/);
// The three error_handling markers collapse into one header carrying their
// subtotal — not three siblings, and not merged with change_entropy.
// Scoped to the group header: an expanded group also renders an
// "About Error handling" InfoTip button.
- const eh = screen.getByRole("button", { name: /Error handling · file-level/i });
- expect(within(eh).getByText(/3 markers/)).toBeInTheDocument();
+ const eh = screen.getByRole("button", { name: /Error handling · across the file/i });
+ expect(within(eh).getByText(/3 issues/)).toBeInTheDocument();
expect(within(eh).getByText(/−0\.45/)).toBeInTheDocument();
// The lone change_entropy marker stays in the pooled bucket rather than
// earning a group of its own.
- expect(screen.getByRole("button", { name: /File-level signals/ })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Across the file/ })).toBeInTheDocument();
});
it("renders and links the line for a file-level marker that has no function", () => {
@@ -131,7 +117,8 @@ describe("HealthFileDrawer finding grouping", () => {
);
// Gating the anchor on function_name hid the only field distinguishing one
// error_handling marker from the next, which is what made them read as
- // duplicates.
+ // duplicates. The link is in the opened row.
+ fireEvent.click(screen.getByRole("button", { name: /Errors caught too broadly/ }));
const link = screen.getByRole("link", { name: /line 202/ });
expect(link).toHaveAttribute("href", "/files/doctor_cmd.py#L202");
});
@@ -151,7 +138,7 @@ describe("HealthFileDrawer finding grouping", () => {
open
onClose={() => {}}
metric={metric()}
- findings={findings}
+ findings={[...lead(), ...findings]}
breakdown={{
score: 9.7,
total_deduction: 0.3,
@@ -169,10 +156,11 @@ describe("HealthFileDrawer finding grouping", () => {
}}
/>,
);
+ openSection(/Other issues/);
// Scoped to the group header: an expanded group also renders an
// "About Error handling" InfoTip button.
- const eh = screen.getByRole("button", { name: /Error handling · file-level/i });
- expect(within(eh).getByText("capped")).toBeInTheDocument();
+ const eh = screen.getByRole("button", { name: /Error handling · across the file/i });
+ expect(within(eh).getByText("at limit")).toBeInTheDocument();
});
it("does not claim 'capped' when other biomarkers share the capped category", () => {
@@ -213,7 +201,7 @@ describe("HealthFileDrawer finding grouping", () => {
open
onClose={() => {}}
metric={metric()}
- findings={findings}
+ findings={[...lead(), ...findings]}
breakdown={{
score: 9.5,
total_deduction: 0.5,
@@ -231,8 +219,9 @@ describe("HealthFileDrawer finding grouping", () => {
}}
/>,
);
- for (const label of [/Nested complexity · file-level/i, /Brain method · file-level/i]) {
- expect(within(screen.getByRole("button", { name: label })).queryByText("capped"))
+ openSection(/Other issues/);
+ for (const label of [/Nested complexity · across the file/i, /Brain method · across the file/i]) {
+ expect(within(screen.getByRole("button", { name: label })).queryByText("at limit"))
.not.toBeInTheDocument();
}
});
@@ -266,12 +255,13 @@ describe("HealthFileDrawer finding grouping", () => {
}),
];
render(
- <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={[...lead(), ...findings]} />,
);
- const pooled = screen.getByRole("button", { name: /File-level signals/ });
- expect(within(pooled).getByText(/3 markers/)).toBeInTheDocument();
+ openSection(/Other issues/);
+ const pooled = screen.getByRole("button", { name: /Across the file/ });
+ expect(within(pooled).getByText(/3 issues/)).toBeInTheDocument();
expect(
- screen.queryByRole("button", { name: /Dry violation · file-level/i }),
+ screen.queryByRole("button", { name: /Dry violation · across the file/i }),
).not.toBeInTheDocument();
});
@@ -302,12 +292,13 @@ describe("HealthFileDrawer finding grouping", () => {
}),
];
render(
- <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={[...lead(), ...findings]} />,
);
- const eh = screen.getByRole("button", { name: /Error handling · file-level/i });
- expect(within(eh).getByText(/3 markers/)).toBeInTheDocument();
- const pooled = screen.getByRole("button", { name: /File-level signals/ });
- expect(within(pooled).getByText(/2 markers/)).toBeInTheDocument();
+ openSection(/Other issues/);
+ const eh = screen.getByRole("button", { name: /Error handling · across the file/i });
+ expect(within(eh).getByText(/3 issues/)).toBeInTheDocument();
+ const pooled = screen.getByRole("button", { name: /Across the file/ });
+ expect(within(pooled).getByText(/2 issues/)).toBeInTheDocument();
});
/** A C++/Rust function can legitimately be named `file::read`, so the group
@@ -318,12 +309,13 @@ describe("HealthFileDrawer finding grouping", () => {
finding({ function_name: "file::read", biomarker_type: "nested_complexity" }),
];
render(
- <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={findings} />,
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} findings={[...lead(), ...findings]} />,
);
+ openSection(/Other issues/);
const group = screen.getByRole("button", { name: /file::read/ });
- expect(within(group).getByText(/2 markers/)).toBeInTheDocument();
+ expect(within(group).getByText(/2 issues/)).toBeInTheDocument();
expect(
- screen.queryByRole("button", { name: /· file-level/i }),
+ screen.queryByRole("button", { name: /· across the file/i }),
).not.toBeInTheDocument();
});
});
@@ -332,8 +324,12 @@ describe("HealthFileDrawer metrics", () => {
/** Read one cell of the metric list by its label, so these assertions do not
* move every time another field joins the grid. */
function cellValue(label: string): string {
- const dt = screen.getByText(label);
- return dt.parentElement?.querySelector("dd")?.textContent?.trim() ?? "";
+ // The Details grid's cell, not the vital-signs strip's word of the same name.
+ const cell = screen
+ .getAllByText(label)
+ .find((el) => el.closest("dt"))
+ ?.closest("div");
+ return cell?.querySelector("dd")?.textContent?.trim() ?? "";
}
it("says 'not measured' instead of 0 when structural counters are absent", () => {
@@ -344,9 +340,11 @@ describe("HealthFileDrawer metrics", () => {
metric={metric({ max_ccn: null, max_nesting: null, nloc: null })}
/>,
);
- expect(cellValue("Max CCN")).toBe("not measured");
- expect(cellValue("Nesting")).toBe("not measured");
- expect(cellValue("NLOC")).toBe("not measured");
+ // The collapsed toggle already says so, before it is opened.
+ openSection(/Details/);
+ expect(cellValue("Complexity")).toBe("not measured");
+ expect(cellValue("Nesting depth")).toBe("not measured");
+ expect(cellValue("Lines of code")).toBe("not measured");
});
it("still renders real zero values as numbers", () => {
@@ -357,18 +355,20 @@ describe("HealthFileDrawer metrics", () => {
metric={metric({ max_ccn: 0, max_nesting: 0, nloc: 12 })}
/>,
);
- expect(cellValue("Max CCN")).toBe("0");
- expect(cellValue("Nesting")).toBe("0");
- expect(cellValue("NLOC")).toBe("12");
+ openSection(/Details/);
+ expect(cellValue("Complexity")).toBe("0");
+ expect(cellValue("Nesting depth")).toBe("0");
+ expect(cellValue("Lines of code")).toBe("12");
});
it("applies the same rule to the pillar scores and the percentages", () => {
render(<HealthFileDrawer open onClose={() => {}} metric={metric()} />);
+ openSection(/Details/);
// An unscored pillar is not a zero-risk pillar, and no coverage data is not
// 0% coverage.
expect(cellValue("Maintainability")).toBe("not measured");
expect(cellValue("Performance")).toBe("not measured");
- expect(cellValue("Coverage")).toBe("not measured");
+ expect(cellValue("Line coverage")).toBe("not measured");
expect(cellValue("Duplication")).toBe("not measured");
});
@@ -429,7 +429,7 @@ describe("HealthFileDrawer bug history", () => {
fix_symbol_counts: { "pipeline.py::run_update": 4, "pipeline.py::persist": 2 },
};
- it("hides per-symbol counts behind a disclosure that names the last fix", () => {
+ it("files the fix counts under History & ownership, with the last fix on the toggle", () => {
render(
<HealthFileDrawer
open
@@ -440,15 +440,20 @@ describe("HealthFileDrawer bug history", () => {
/>,
);
- const toggle = screen.getByRole("button", { name: /Bug history/ });
+ const toggle = screen.getByRole("button", { name: /History & ownership/ });
// Recency rides on the toggle itself: the counts are collapsed, the "is
// this still happening?" answer is not.
- expect(toggle).toHaveTextContent(/last fix 3d ago/);
+ // The hint names what is inside rather than restating the counts.
+ expect(toggle).toHaveTextContent("change history · where fixes landed");
// Collapsed by default, because "where do the bugs cluster" is not a question
// every reader of the drawer has.
expect(screen.queryByText("run_update")).not.toBeInTheDocument();
fireEvent.click(toggle);
+ // The process row carries the count and recency once; the per-symbol
+ // list under it does not repeat them.
+ expect(screen.getByText("8 bug-fixes")).toBeInTheDocument();
+ expect(screen.getByText("Where the fixes landed")).toBeInTheDocument();
expect(screen.getByText("run_update")).toBeInTheDocument();
expect(screen.getByText("4 fixes")).toBeInTheDocument();
expect(screen.getByText("2 fixes")).toBeInTheDocument();
@@ -457,7 +462,7 @@ describe("HealthFileDrawer bug history", () => {
expect(screen.getByText(/lines move/)).toBeInTheDocument();
});
- it("stays silent without per-symbol data", () => {
+ it("drops the per-symbol list without per-symbol data", () => {
render(
<HealthFileDrawer
open
@@ -467,7 +472,8 @@ describe("HealthFileDrawer bug history", () => {
signals={{ ...signals, fix_symbol_counts: null }}
/>,
);
- expect(screen.queryByRole("button", { name: /Bug history/ })).not.toBeInTheDocument();
+ openSection(/History & ownership/);
+ expect(screen.queryByText("Where the fixes landed")).not.toBeInTheDocument();
});
});
@@ -618,7 +624,7 @@ describe("HealthFileDrawer under the performance lens", () => {
});
});
-describe("HealthFileDrawer leading cause", () => {
+describe("HealthFileDrawer verdict and history", () => {
it("passes over a history lead for the strongest code-shape finding", () => {
render(
<HealthFileDrawer
@@ -633,8 +639,10 @@ describe("HealthFileDrawer leading cause", () => {
);
// The server's lead is the history marker; the drawer must not present it
// as the thing to fix.
- expect(screen.getByText(/Brain method\./)).toBeInTheDocument();
- expect(screen.queryByText(/Co-change scatter\./)).not.toBeInTheDocument();
+ const rows = within(screen.getByRole("region", { name: "What's wrong" })).getAllByRole("listitem");
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toHaveTextContent("Function does too much");
+ expect(screen.queryByText(/Edits ripple to other files/)).not.toBeInTheDocument();
});
it("says so when a file's whole deduction is history", () => {
@@ -646,7 +654,7 @@ describe("HealthFileDrawer leading cause", () => {
findings={[finding({ biomarker_type: "co_change_scatter", health_impact: 1.8 })]}
/>,
);
- expect(screen.getByText(/Its deduction is all\s+history/)).toBeInTheDocument();
+ expect(screen.getByText(/score comes from change history/)).toBeInTheDocument();
});
it("marks a history finding as a watch item, not a pillar", () => {
@@ -658,6 +666,9 @@ describe("HealthFileDrawer leading cause", () => {
findings={[finding({ biomarker_type: "prior_defect", health_impact: 1.0 })]}
/>,
);
+ // A history marker is never offered as something to fix.
+ expect(screen.queryByRole("region", { name: "What's wrong" })).not.toBeInTheDocument();
+ openSection(/All issues/);
expect(screen.getAllByText("Watch").length).toBeGreaterThan(0);
// No pillar chip: the pillar colours mark where work belongs, and this is
// not work. The title is what distinguishes the chip from the score label.
diff --git a/packages/ui/__tests__/health/map-layout.test.ts b/packages/ui/__tests__/health/map-layout.test.ts
new file mode 100644
index 000000000..dfc30287b
--- /dev/null
+++ b/packages/ui/__tests__/health/map-layout.test.ts
@@ -0,0 +1,196 @@
+/**
+ * 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.
+ */
+import { describe, it, expect } from "vitest";
+import {
+ MAX_GALAXIES,
+ WORLD,
+ fitCamera,
+ galaxyKeyFor,
+ layoutField,
+} from "../../src/health/map/layout.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 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. */
+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}`, {
+ score: 1 + ((i * 31) % 90) / 10,
+ });
+ });
+}
+
+const allNodes = (files: CodeHealthMapFile[]) => layoutField(files).flatMap((g) => g.nodes);
+
+describe("layout for any size", () => {
+ it("is deterministic", () => {
+ const files = synthetic(500, 9);
+ expect(layoutField(files)).toEqual(layoutField([...files].reverse()));
+ });
+
+ 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("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++;
+ }
+ }
+ 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",
+ ]);
+ });
+
+ 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("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);
+ });
+});
+
+describe("hit testing", () => {
+ const nodes = allNodes(synthetic(3000, 12));
+ const grid = buildHitGrid(nodes);
+
+ it("finds the node under its own centre", () => {
+ for (const i of [0, 17, 999, 2999]) {
+ const n = nodes[i]!;
+ expect(hitTest(grid, n.x, n.y)).toBe(i);
+ }
+ });
+
+ 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;
+ const y = (k * 61) % WORLD;
+ let brute = -1;
+ let best = Infinity;
+ nodes.forEach((n, i) => {
+ const gap = Math.hypot(x - n.x, y - n.y) - n.r;
+ if (gap <= 0 && gap < best) {
+ brute = i;
+ best = gap;
+ }
+ });
+ expect(hitTest(grid, x, y)).toBe(brute);
+ }
+ });
+});
+
+describe("colour parsing", () => {
+ it("reads the forms a computed style returns", () => {
+ expect(parseCssColour("rgb(10, 20, 30)")).toEqual([10, 20, 30]);
+ expect(parseCssColour("rgba(10, 20, 30, 0.5)")).toEqual([10, 20, 30]);
+ expect(parseCssColour("color(srgb 1 0.5 0)")).toEqual([255, 127.5, 0]);
+ expect(parseCssColour("var(--x)")).toBeNull();
+ });
+});
+
+describe("cost at size", () => {
+ // Wall-clock budgets with wide headroom for a loaded CI box; the figures
+ // logged are what the report quotes.
+ for (const n of [2000, 8000]) {
+ it(`lays out, indexes and batches ${n.toLocaleString()} files quickly`, () => {
+ const files = synthetic(n, 40);
+ const t0 = performance.now();
+ const galaxies = layoutField(files);
+ const t1 = performance.now();
+ const scene = buildScene(galaxies);
+ 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 t4 = 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`,
+ );
+ expect(scene.nodes).toHaveLength(n);
+ expect(hits).toBeGreaterThan(0);
+ expect(t1 - t0).toBeLessThan(1500);
+ expect(t4 - t3).toBeLessThan(500);
+ });
+ }
+});
diff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsx
index 070688c5a..3c8b7b4d9 100644
--- a/packages/ui/__tests__/health/map-lens.test.tsx
+++ b/packages/ui/__tests__/health/map-lens.test.tsx
@@ -1,13 +1,13 @@
/**
- * The performance lens on the one galaxy: what the field says, what it refuses
- * to say, and what it costs to interact with.
+ * The lenses on the one galaxy: what the field says, what it refuses to say,
+ * and what it costs to interact with.
*/
import { describe, it, expect, vi, beforeAll } from "vitest";
import { render, fireEvent } from "@testing-library/react";
import {
CodeHealthMap,
OVERLAY_SPECS,
- SEARCH_MARK_CAP,
+ QUIET_FILL,
burdenBand,
performanceBurden,
performanceFill,
@@ -15,42 +15,13 @@ import {
type CodeHealthMapFile,
type MapScope,
} from "../../src/health/code-health-map.js";
-import { MapFieldList, MapInspector } from "../../src/health/map/inspector.js";
-
-function f(
- file_path: string,
- nloc: number,
- module: string | null,
- extra: Partial<CodeHealthMapFile> = {},
-): CodeHealthMapFile {
- return {
- file_path,
- nloc,
- score: 7,
- module,
- line_coverage_pct: null,
- has_test_file: false,
- ...extra,
- };
-}
-
-beforeAll(() => {
- class RO {
- cb: ResizeObserverCallback;
- constructor(cb: ResizeObserverCallback) {
- this.cb = cb;
- }
- observe() {
- this.cb(
- [{ contentRect: { width: 800, height: 600 } } as ResizeObserverEntry],
- this as unknown as ResizeObserver,
- );
- }
- unobserve() {}
- disconnect() {}
- }
- vi.stubGlobal("ResizeObserver", RO);
-});
+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 { healthRampFill } from "../../src/health/tokens.js";
+import { mapFile as f, nodeAt, stubMapEnvironment } from "./map-test-utils.js";
+
+beforeAll(stubMapEnvironment);
const scope: MapScope = {
shown: 2,
@@ -82,32 +53,28 @@ describe("burden encoding", () => {
expect(performanceSentence(row)).toContain("stored plan");
});
- it("colours the node on the health ramp, with no palette of its own", () => {
+ it("colours the node on the health ramp's stops, with no palette of its own", () => {
const at = (n: number) =>
performanceFill(f("a.py", 10, "core", {
performance_opportunities: n,
performance_analyzed: true,
}));
- // The same tokens the health lens paints with. An earlier cut mixed its
- // own tones toward the page, putting colours on this field that exist
- // nowhere else in the product and going muddy against a dark root.
+ // The Fair, Needs work and At risk fills, so one colour means one
+ // severity anywhere on this field.
const health = (score: number) => OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score });
- expect(at(1)).toBe(health(6)); // fair
- expect(at(3)).toBe(health(4.5)); // needs work
- expect(at(9)).toBe(health(1)); // at risk
+ expect(at(1)).toBe(health(6));
+ expect(at(3)).toBe(health(5));
+ expect(at(9)).toBe(health(1));
});
- it("never paints a file a green, whatever its state", () => {
- // Green means the code is fine on this map and no performance verdict is
- // that: a cleared file is one with no supported pattern in it, not one
- // measured to be fast. So the lens uses only the bands below green.
- const greens = [7, 9].map((score) =>
- OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score }),
- );
+ it("never paints a file the healthy tone, whatever its state", () => {
+ // The quiet tone means the code is fine on this map and no performance
+ // verdict is that: a cleared file is one with no supported pattern in it,
+ // not one measured to be fast.
const fills = [0, 1, 3, 9, 40].map((n) =>
performanceFill(f("a.py", 10, "core", { performance_opportunities: n })),
);
- for (const green of greens) expect(fills).not.toContain(green);
+ expect(fills).not.toContain(QUIET_FILL);
});
it("gives every file with no open cause the one neutral", () => {
@@ -126,21 +93,6 @@ describe("burden encoding", () => {
expect(performanceSentence(clear)).not.toBe(performanceSentence(unsupported));
});
- it("spends opacity on focus alone, never on data", () => {
- const files = [
- f("core/a.py", 100, "core", { performance_opportunities: 0, performance_analyzed: true }),
- f("core/b.py", 90, "core", { performance_opportunities: 6, performance_analyzed: true }),
- ];
- const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
- // A lens that also dimmed by burden left a reader unable to tell a quiet
- // file from one sitting in an unfocused galaxy, and dissolved the field
- // into a wash by dropping the separating stroke under it.
- for (const node of container.querySelectorAll("circle[data-path]")) {
- expect(node.getAttribute("fill-opacity")).toBe("0.9");
- expect(Number(node.getAttribute("stroke-width"))).toBeGreaterThan(0);
- }
- });
-
it("gives an unsupported language no clear verdict", () => {
const row = f("a.cc", 10, "core", {
performance_opportunities: 0,
@@ -151,6 +103,62 @@ describe("burden encoding", () => {
});
});
+describe("the health ramp", () => {
+ it("paints the five canonical bands, so a dot and its score pill agree", () => {
+ const fills = [9, 8.5, 7.5, 7, 6, 5.5, 5, 4, 3, 1].map(healthRampFill);
+ expect(fills[0]).toBe(fills[1]);
+ expect(fills[2]).toBe(fills[3]);
+ expect(fills[4]).toBe(fills[5]);
+ expect(fills[6]).toBe(fills[7]);
+ expect(fills[8]).toBe(fills[9]);
+ expect(new Set(fills).size).toBe(5);
+ });
+
+ it("uses the Good fill as the quiet tone banded lenses share", () => {
+ expect(healthRampFill(7.5)).toBe(QUIET_FILL);
+ });
+
+ it("stays five colours, so a canvas draws five batches", () => {
+ const fills = new Set(Array.from({ length: 901 }, (_, i) => healthRampFill(1 + i / 100)));
+ expect(fills.size).toBe(5);
+ });
+});
+
+describe("batches", () => {
+ const files = Array.from({ length: 60 }, (_, i) =>
+ 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));
+ 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);
+ 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);
+ }
+ });
+
+ it("pairs the old and new fill during a lens tween", () => {
+ const scene = buildScene(layoutField(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]));
+ 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);
+ });
+});
+
describe("scope disclosure", () => {
it("states the drawn count against the eligible count, not the repository", () => {
const { getByTestId } = render(
@@ -162,9 +170,7 @@ describe("scope disclosure", () => {
});
it("names the files with causes the cap pushed out", () => {
- const { getByTestId } = render(
- <CodeHealthMap files={[f("a.py", 10, "core")]} scope={scope} />,
- );
+ const { getByTestId } = render(<CodeHealthMap files={[f("a.py", 10, "core")]} scope={scope} />);
expect(getByTestId("map-scope").textContent).toContain("3 files with open causes not drawn");
});
@@ -179,88 +185,95 @@ describe("scope disclosure", () => {
"every file with an open cause is drawn",
);
});
+
+ it("offers to draw more while the field is capped, bounded by what is left", () => {
+ const onDrawMore = vi.fn();
+ const { getByRole } = render(
+ <CodeHealthMap files={[f("a.py", 10, "core")]} scope={scope} onDrawMore={onDrawMore} />,
+ );
+ fireEvent.click(getByRole("button", { name: "Draw 38 more" }));
+ expect(onDrawMore).toHaveBeenCalled();
+ });
+
+ it("offers no draw-more once everything is drawn", () => {
+ const { queryByRole } = render(
+ <CodeHealthMap
+ files={[f("a.py", 10, "core")]}
+ scope={{ ...scope, shown: 40 }}
+ onDrawMore={vi.fn()}
+ />,
+ );
+ expect(queryByRole("button", { name: /Draw .* more/ })).not.toBeInTheDocument();
+ });
+
+ it("names the held-out vendored and generated files and offers them", () => {
+ const onIncludeHeldChange = vi.fn();
+ const { getByRole } = render(
+ <CodeHealthMap
+ files={[f("a.py", 10, "core")]}
+ scope={{ ...scope, held: 12, includeHeld: false }}
+ onIncludeHeldChange={onIncludeHeldChange}
+ />,
+ );
+ fireEvent.click(getByRole("button", { name: "Include 12 vendored and generated files" }));
+ expect(onIncludeHeldChange).toHaveBeenCalledWith(true);
+ });
+
+ it("offers to find search matches the field left out, then counts them", () => {
+ const onFindUndrawn = vi.fn();
+ const files = [f("core/needle.py", 10, "core")];
+ const { getByRole, getByTestId, rerender } = render(
+ <CodeHealthMap files={files} scope={scope} search="needle" onFindUndrawn={onFindUndrawn} />,
+ );
+ fireEvent.click(getByRole("button", { name: "Find matches outside the field" }));
+ expect(onFindUndrawn).toHaveBeenCalledWith("needle");
+ rerender(
+ <CodeHealthMap
+ files={files}
+ scope={{ ...scope, query: { text: "needle", matches: 4, shown: 1 } }}
+ search="needle"
+ onFindUndrawn={onFindUndrawn}
+ />,
+ );
+ expect(getByTestId("map-scope").textContent).toContain("1 of 4 matches drawn");
+ });
});
describe("search", () => {
- const files = Array.from({ length: 40 }, (_, i) =>
- f(`core/file${i}.py`, 100 - i, "core"),
- );
+ const files = Array.from({ length: 40 }, (_, i) => f(`core/file${i}.py`, 100 - i, "core"));
- it("marks the matches instead of touching the field", () => {
- const { container, rerender } = render(<CodeHealthMap files={files} search="" />);
- const before = container.querySelector('circle[data-path="core/file7.py"]');
+ it("marks the matches without re-laying the field", () => {
+ const { getByTestId, rerender } = render(<CodeHealthMap files={files} search="" />);
+ const before = nodeAt(files, "core/file7.py");
rerender(<CodeHealthMap files={files} search="file7" />);
- const after = container.querySelector('circle[data-path="core/file7.py"]');
- // The same DOM node, with the same attributes: the base layer was not
- // reconciled, so typing costs the marks and nothing else.
- expect(after).toBe(before);
- expect(after!.getAttribute("fill-opacity")).toBe("0.9");
- expect(container.querySelectorAll("circle[data-match]").length).toBeGreaterThan(0);
- });
-
- it("does not re-lay the field when the query changes", () => {
- const { container, rerender } = render(<CodeHealthMap files={files} search="" />);
- const at = (p: string) => {
- const n = container.querySelector(`circle[data-path="${p}"]`)!;
- return `${n.getAttribute("cx")},${n.getAttribute("cy")},${n.getAttribute("r")}`;
- };
- const before = at("core/file3.py");
- rerender(<CodeHealthMap files={files} search="fi" />);
- rerender(<CodeHealthMap files={files} search="file" />);
- expect(at("core/file3.py")).toBe(before);
- });
-
- it("bounds how many matches it draws", () => {
- const many = Array.from({ length: SEARCH_MARK_CAP + 30 }, (_, i) =>
- f(`core/hit${i}.py`, 50, "core"),
- );
- const { container } = render(<CodeHealthMap files={many} search="hit" />);
- expect(container.querySelectorAll("circle[data-match]").length).toBe(SEARCH_MARK_CAP);
+ expect(getByTestId("map-field").getAttribute("data-matches")).toBe("1");
+ // The layout is a function of the rows alone; the query never reaches it.
+ expect(nodeAt(files, "core/file7.py")).toEqual(before);
});
- it("marks the paths a deep link asked for, with no query at all", () => {
- const { container } = render(
- <CodeHealthMap files={files} highlightPaths={["core/file2.py"]} />,
- );
- expect(container.querySelector('circle[data-match="core/file2.py"]')).toBeTruthy();
+ it("counts every match on the drawn field", () => {
+ const many = Array.from({ length: 300 }, (_, i) => f(`core/hit${i}.py`, 50, "core"));
+ const { getByTestId } = render(<CodeHealthMap files={many} search="hit" />);
+ expect(getByTestId("map-field").getAttribute("data-matches")).toBe("300");
});
});
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", {
- performance_opportunities: i % 5 === 0 ? (i % 9) + 1 : 0,
- performance_actionability: "advisory",
- performance_analyzed: true,
- }),
- );
-
- it("draws one circle per file and no second mark on top of it", () => {
- // A rare per-file annotation was tried as a ring outside the node and as a
- // core inside it. Neither read as belonging to one file on a body this
- // dense, so the lens spends one channel and the words carry the rest.
- const planned = files.map((row, i) =>
- i % 7 === 0 ? { ...row, performance_actionability: "plan_ready" as const } : row,
- );
- const { container } = render(<CodeHealthMap files={planned} overlay="performance" />);
- const nodes = container.querySelectorAll("circle[data-path]");
- expect(nodes).toHaveLength(300);
- // Nothing is drawn concentric with a node but smaller or larger than it,
- // which is the shape both rejected marks had.
- const centres = new Set([...nodes].map((n) => `${n.getAttribute("cx")},${n.getAttribute("cy")}`));
- const overlaid = [...container.querySelectorAll("circle:not([data-path])")].filter((c) =>
- centres.has(`${c.getAttribute("cx")},${c.getAttribute("cy")}`),
+ it("places every drawable file exactly once", () => {
+ const files = Array.from({ length: 300 }, (_, i) =>
+ f(`core/f${i}.py`, 200 - (i % 150), i % 2 ? "core" : "ui"),
);
- expect(overlaid).toHaveLength(0);
+ const placed = layoutField(files).flatMap((g) => g.nodes.map((n) => n.file.file_path));
+ expect(placed).toHaveLength(300);
+ expect(new Set(placed).size).toBe(300);
});
- it("keeps the safeguards that make thousands of nodes affordable", () => {
+ it("renders no DOM node per file and no SVG filter", () => {
+ const files = Array.from({ length: 300 }, (_, i) => f(`core/f${i}.py`, 50 + i, "core"));
const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
- // A native tooltip per node, an offscreen raster pass, and a per-frame
- // stroke recomputation. Each was measured and removed; none may return.
- expect(container.querySelectorAll("title")).toHaveLength(0);
+ expect(container.querySelectorAll("circle")).toHaveLength(0);
expect(container.querySelectorAll("filter")).toHaveLength(0);
- expect(container.querySelectorAll("circle[data-path][vector-effect]")).toHaveLength(0);
+ expect(container.querySelectorAll("title")).toHaveLength(0);
});
});
@@ -271,9 +284,8 @@ describe("the hover card", () => {
// 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 { container, getByTestId } = render(<CodeHealthMap files={files} />);
- const node = container.querySelector('circle[data-path="core/deep/nested/alpha.py"]')!;
- fireEvent.mouseEnter(node, { clientX: 120, clientY: 90 });
+ const { getByTestId } = render(<CodeHealthMap files={files} />);
+ fireEvent.mouseMove(getByTestId("map-canvas"), nodeAt(files, "core/deep/nested/alpha.py"));
const card = getByTestId("map-hover-card");
expect(card.textContent).toContain("alpha.py");
// The directory is present but subordinate: the filename is what is being
@@ -282,26 +294,26 @@ describe("the hover card", () => {
expect(card.getAttribute("style")).toMatch(/left:/);
});
- it("closes when the pointer leaves the node", () => {
- const { container, queryByTestId } = render(<CodeHealthMap files={files} />);
- const node = container.querySelector('circle[data-path="ui/beta.py"]')!;
- fireEvent.mouseEnter(node, { clientX: 10, clientY: 10 });
+ it("closes when the pointer leaves the node, and tells the host", () => {
+ const onHoverFile = vi.fn();
+ const { getByTestId, queryByTestId } = render(
+ <CodeHealthMap files={files} onHoverFile={onHoverFile} />,
+ );
+ const canvas = getByTestId("map-canvas");
+ fireEvent.mouseMove(canvas, nodeAt(files, "ui/beta.py"));
expect(queryByTestId("map-hover-card")).toBeInTheDocument();
- fireEvent.mouseLeave(node);
+ fireEvent.mouseMove(canvas, { clientX: 2, clientY: 2 });
expect(queryByTestId("map-hover-card")).not.toBeInTheDocument();
+ expect(onHoverFile).toHaveBeenLastCalledWith(null);
});
});
describe("keyboard", () => {
- const files = [
- f("core/a.py", 120, "core"),
- f("core/b.py", 60, "core"),
- f("ui/c.py", 40, "ui"),
- ];
+ 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", () => {
const onSelectFile = vi.fn();
- const { getByRole, container } = render(
+ const { getByRole, container, getByTestId } = render(
<CodeHealthMap files={files} onSelectFile={onSelectFile} />,
);
// One focusable region for the whole field. Thousands of tab stops is not
@@ -311,7 +323,7 @@ describe("keyboard", () => {
fireEvent.keyDown(field, { key: "Enter" }); // into the first module
fireEvent.keyDown(field, { key: "ArrowRight" }); // second file in it
- expect(container.querySelector("circle[data-keyboard-cursor]")).toBeTruthy();
+ expect(getByTestId("map-field").getAttribute("data-keyboard-cursor")).toBe("core/b.py");
fireEvent.keyDown(field, { key: "Enter" });
expect(onSelectFile).toHaveBeenCalledWith("core/b.py");
});
@@ -325,15 +337,21 @@ describe("keyboard", () => {
});
it("Escape climbs back out to the modules", () => {
- const { getByRole, container, queryByText } = render(<CodeHealthMap files={files} />);
+ 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(container.querySelector("circle[data-keyboard-cursor]")).toBeNull();
+ 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/);
});
});
+
describe("the navigable list beside the field", () => {
const files = [
f("core/a.py", 120, "core", {
@@ -390,59 +408,3 @@ describe("the navigable list beside the field", () => {
expect(getAllByRole("button")[0]!.textContent).toContain("b.py");
});
});
-
-describe("the inspector", () => {
- const row = f("core/a.py", 120, "core", {
- performance_opportunities: 5,
- performance_observations: 8,
- performance_actionability: "advisory",
- performance_analyzed: true,
- });
-
- it("describes the selection in the active lens's terms", () => {
- const { getByText } = render(
- <MapInspector file={row} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,
- );
- expect(getByText("Open opportunities")).toBeInTheDocument();
- expect(getByText("Observations behind them")).toBeInTheDocument();
- expect(getByText("Advisory")).toBeInTheDocument();
- });
-
- it("leads with the burden, not the defect score, under its own lens", () => {
- // The defect badge led here, so a file with a healthy score and a heavy
- // ring beside it opened an inspector that said the opposite of the mark.
- const { container, getByText } = render(
- <MapInspector file={row} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,
- );
- expect(getByText("Open opportunities")).toBeInTheDocument();
- expect(getByText(/code health 7\.0/)).toBeInTheDocument();
- // The score badge, which is the defect ramp, is not the leading mark.
- const leading = container.querySelector("section > div")?.firstElementChild;
- expect(leading?.textContent).toBe("");
- });
-
- it("keeps the defect score leading under a score lens", () => {
- const { getByText } = render(
- <MapInspector file={row} overlay="health" onOpen={vi.fn()} onClose={vi.fn()} />,
- );
- expect(getByText("7.0")).toBeInTheDocument();
- });
-
- it("says nothing about performance under another lens", () => {
- const { queryByText } = render(
- <MapInspector file={row} overlay="health" onOpen={vi.fn()} onClose={vi.fn()} />,
- );
- expect(queryByText("Open opportunities")).not.toBeInTheDocument();
- });
-
- it("never calls an analyzed-clear file fast", () => {
- const clear = f("core/clean.py", 10, "core", {
- performance_opportunities: 0,
- performance_analyzed: true,
- });
- const { getByText } = render(
- <MapInspector file={clear} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,
- );
- expect(getByText("Analyzed, nothing surfaced")).toBeInTheDocument();
- });
-});
diff --git a/packages/ui/__tests__/health/map-test-utils.ts b/packages/ui/__tests__/health/map-test-utils.ts
new file mode 100644
index 000000000..b247dd171
--- /dev/null
+++ b/packages/ui/__tests__/health/map-test-utils.ts
@@ -0,0 +1,65 @@
+/**
+ * Shared harness for the canvas map tests. jsdom has no layout engine and no
+ * canvas, so the map is given a fixed box and a null 2D context (the painter
+ * skips cleanly), and a node is found on screen through the same pure layout
+ * and fitted camera the component uses.
+ */
+import { vi } from "vitest";
+import { fitCamera, layoutField, 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;
+export const H = 640;
+
+export function stubMapEnvironment(): void {
+ class RO {
+ cb: ResizeObserverCallback;
+ constructor(cb: ResizeObserverCallback) {
+ this.cb = cb;
+ }
+ observe() {
+ this.cb(
+ [{ contentRect: { width: W, height: 600 } } as ResizeObserverEntry],
+ this as unknown as ResizeObserver,
+ );
+ }
+ unobserve() {}
+ disconnect() {}
+ }
+ vi.stubGlobal("ResizeObserver", RO);
+ HTMLCanvasElement.prototype.getContext = (() =>
+ null) as unknown as typeof HTMLCanvasElement.prototype.getContext;
+}
+
+/** 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}`);
+}
+
+export function mapFile(
+ file_path: string,
+ nloc: number,
+ module: string | null,
+ extra: Partial<CodeHealthMapFile> = {},
+): CodeHealthMapFile {
+ return {
+ file_path,
+ nloc,
+ score: 7,
+ module,
+ line_coverage_pct: null,
+ has_test_file: false,
+ ...extra,
+ };
+}
diff --git a/packages/ui/__tests__/health/related-work.test.tsx b/packages/ui/__tests__/health/related-work.test.tsx
index 72984ac90..1190dcd26 100644
--- a/packages/ui/__tests__/health/related-work.test.tsx
+++ b/packages/ui/__tests__/health/related-work.test.tsx
@@ -1,7 +1,11 @@
import { describe, it, expect, vi } from "vitest";
import { fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";
import type { RelatedWorkFile, RelatedWorkItem } from "@repowise-dev/types/health";
-import { RelatedWork, useRelatedWork } from "../../src/health/related-work.js";
+import {
+ RelatedWork,
+ useRelatedWork,
+ useRelatedWorkQuery,
+} from "../../src/health/related-work.js";
import { HealthFileDrawer } from "../../src/health/health-file-drawer.js";
const FILE: RelatedWorkFile = {
@@ -93,7 +97,10 @@ describe("HealthFileDrawer related work", () => {
onNavigate={onNavigate}
/>,
);
- expect(screen.getByText("Elsewhere for this file")).toBeInTheDocument();
+ // Collapsed, with the count on the toggle.
+ const toggle = screen.getByRole("button", { name: /Elsewhere for this file/ });
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ fireEvent.click(toggle);
fireEvent.click(screen.getByRole("link", { name: /Unused export/ }));
expect(onNavigate).toHaveBeenCalledWith("/go/dead_code/d1");
expect(screen.getByRole("link", { name: /Extract method/i })).toHaveAttribute(
@@ -127,3 +134,31 @@ describe("useRelatedWork", () => {
expect(none.result.current).toBeUndefined();
});
});
+
+describe("useRelatedWorkQuery", () => {
+ it("serves a path it already fetched from cache, even after a remount", async () => {
+ const fetcher = vi.fn(async (paths: string[]) => ({
+ files: paths.map((file_path) => ({ file_path, lenses: {} })),
+ per_lens_limit: 5,
+ }));
+ const first = renderHook(() => useRelatedWorkQuery(fetcher, ["cached.py"]));
+ await waitFor(() => expect(first.result.current.data?.files?.[0]?.file_path).toBe("cached.py"));
+ first.unmount();
+ const again = renderHook(() => useRelatedWorkQuery(fetcher, ["cached.py"]));
+ // Back on a file the reader already looked at: the answer is there at once.
+ expect(again.result.current.data?.files?.[0]?.file_path).toBe("cached.py");
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a failure instead of reading it as nothing elsewhere", async () => {
+ const fetcher = vi.fn(async () => {
+ throw new Error("boom");
+ });
+ const { result } = renderHook(() => useRelatedWorkQuery(fetcher, ["broken.py"]));
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
+ expect(result.current.data).toBeUndefined();
+ // The data-only hook stays silent on the same failure.
+ const plain = renderHook(() => useRelatedWork(fetcher, ["broken.py"]));
+ expect(plain.result.current).toBeUndefined();
+ });
+});
diff --git a/packages/ui/__tests__/health/trend-chart.test.tsx b/packages/ui/__tests__/health/trend-chart.test.tsx
new file mode 100644
index 000000000..3b37a0a48
--- /dev/null
+++ b/packages/ui/__tests__/health/trend-chart.test.tsx
@@ -0,0 +1,111 @@
+import { describe, it, expect } from "vitest";
+import { createEvent, fireEvent, render, screen } from "@testing-library/react";
+import { TrendChart, type TrendSeriesPoint } from "../../src/health/trend-chart.js";
+
+const history: TrendSeriesPoint[] = [
+ { taken_at: "2026-10-01T10:00:00Z", average_health: 3.2, hotspot_health: 2.5, worst_performer_score: 1, history_average: 1.4 },
+ { taken_at: "2026-10-02T10:00:00Z", average_health: 3.6, hotspot_health: 2.4, worst_performer_score: 1, history_average: 1.2 },
+ { taken_at: "2026-10-03T10:00:00Z", average_health: 3.5, hotspot_health: 2.9, worst_performer_score: 1.5, history_average: 1.1 },
+];
+
+/**
+ * React reads a pointer leave off the `pointerout` it pairs with, and jsdom has
+ * no PointerEvent to carry `pointerType`, so the field is set by hand.
+ */
+function leave(el: Element, pointerType: string) {
+ const event = createEvent.pointerOut(el, { relatedTarget: document.body });
+ Object.defineProperty(event, "pointerType", { value: pointerType });
+ fireEvent(el, event);
+}
+
+const live = (container: HTMLElement) => container.querySelector("[aria-live]")!.textContent ?? "";
+
+describe("TrendChart", () => {
+ it("names the health bands behind the lines instead of colouring the lines by health", () => {
+ const { container } = render(<TrendChart history={history} />);
+ for (const band of ["Healthy", "Warning", "Alert"]) expect(screen.getByText(band)).toBeInTheDocument();
+ const strokes = [...container.querySelectorAll("path")].map((p) => p.getAttribute("stroke"));
+ // A code-health line at 3 is not drawn in the Alert red or any verdict colour.
+ expect(strokes).toContain("var(--color-series-1)");
+ expect(strokes.some((s) => /success|warning|error/.test(s ?? ""))).toBe(false);
+ });
+
+ it("steps through snapshots from the keyboard and reads each one out", () => {
+ const { container } = render(<TrendChart history={history} />);
+ const plot = screen.getByRole("group", { name: /Arrow keys step through snapshots/ });
+
+ fireEvent.focus(plot);
+ expect(live(container)).toMatch(/snapshot 3 of 3/);
+ expect(live(container)).toMatch(/Code health 3\.5, -0\.10/);
+
+ fireEvent.keyDown(plot, { key: "ArrowLeft" });
+ expect(live(container)).toMatch(/snapshot 2 of 3/);
+ expect(live(container)).toMatch(/Code health 3\.6, \+0\.40/);
+ expect(live(container)).toMatch(/Change history takes 1\.20 points off code health\./);
+
+ fireEvent.keyDown(plot, { key: "Home" });
+ // The first snapshot has nothing before it, so it carries no delta.
+ expect(live(container)).toMatch(/Code health 3\.2;/);
+ });
+
+ it("toggles a series from its legend entry and never hides the last one", () => {
+ render(<TrendChart history={history} />);
+ const hotspot = screen.getByRole("button", { name: "Hotspot" });
+ fireEvent.click(hotspot);
+ expect(hotspot).toHaveAttribute("aria-pressed", "false");
+ fireEvent.click(screen.getByRole("button", { name: "Worst file" }));
+ expect(screen.getByRole("button", { name: "Code health" })).toBeDisabled();
+ fireEvent.click(hotspot);
+ expect(screen.getByRole("button", { name: "Code health" })).not.toBeDisabled();
+ });
+
+ it("leaves a hidden series out of the readout", () => {
+ const { container } = render(<TrendChart history={history} />);
+ fireEvent.click(screen.getByRole("button", { name: "Hotspot" }));
+ fireEvent.focus(screen.getByRole("group", { name: /Arrow keys/ }));
+ expect(live(container)).not.toMatch(/Hotspot/);
+ expect(live(container)).toMatch(/Worst file 1\.5/);
+ });
+ it("keeps a tapped readout open after the touch ends, and closes it on a press elsewhere", () => {
+ render(
+ <div>
+ <TrendChart history={history} />
+ <button type="button">elsewhere</button>
+ </div>,
+ );
+ const plot = screen.getByRole("group", { name: /Arrow keys/ });
+ const svg = plot.querySelector("svg")!;
+ fireEvent.focus(plot);
+ expect(screen.getByText("3 of 3")).toBeInTheDocument();
+ // Touch fires pointerleave straight after pointerup.
+ leave(svg, "touch");
+ expect(screen.getByText("3 of 3")).toBeInTheDocument();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "elsewhere" }));
+ expect(screen.queryByText("3 of 3")).toBeNull();
+ // A mouse leaving the plot still clears it.
+ fireEvent.focus(plot);
+ leave(svg, "mouse");
+ expect(screen.queryByText("3 of 3")).toBeNull();
+ });
+
+ it("draws every series again when a new history drops the only one left on", () => {
+ const withPillar = history.map((p) => ({ ...p, maintainability_average: 8.2 }));
+ const { container, rerender } = render(<TrendChart history={withPillar} />);
+ for (const name of ["Code health", "Hotspot", "Worst file"]) {
+ fireEvent.click(screen.getByRole("button", { name }));
+ }
+ expect(screen.getByRole("button", { name: "Maintainability" })).toBeDisabled();
+
+ rerender(<TrendChart history={history} />);
+
+ const strokes = [...container.querySelectorAll("path")].map((p) => p.getAttribute("stroke"));
+ expect(strokes).toContain("var(--color-series-1)");
+ const codeHealth = screen.getByRole("button", { name: "Code health" });
+ expect(codeHealth).toHaveAttribute("aria-pressed", "true");
+ expect(codeHealth).not.toBeDisabled();
+ // Hiding one from the fallback hides that one, not the others.
+ fireEvent.click(screen.getByRole("button", { name: "Hotspot" }));
+ expect(screen.getByRole("button", { name: "Hotspot" })).toHaveAttribute("aria-pressed", "false");
+ expect(codeHealth).toHaveAttribute("aria-pressed", "true");
+ });
+});
diff --git a/packages/ui/__tests__/health/trend-view.test.tsx b/packages/ui/__tests__/health/trend-view.test.tsx
index a9d3a5e1e..8ced48c29 100644
--- a/packages/ui/__tests__/health/trend-view.test.tsx
+++ b/packages/ui/__tests__/health/trend-view.test.tsx
@@ -1,5 +1,5 @@
-import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
import type { HealthTrendResponse } from "@repowise-dev/types/health";
import { TrendView } from "../../src/health/trend-view.js";
@@ -85,52 +85,81 @@ describe("TrendView — hotspot health stat", () => {
});
});
-describe("TrendView — largest score changes", () => {
- // Two caps sit between the response and the picture: the server slices its
- // list, and the chart draws only the largest few of what arrives. The block
- // is headed "Largest score changes since last index" with no total, so a
- // reader cannot tell all-of-them from a truncated tail.
+describe("TrendView — movers", () => {
+ const moved = [
+ { file_path: "src/core/a.py", before: 8, after: 5, delta: -3 },
+ { file_path: "src/web/b.ts", before: 4, after: 6.5, delta: 2.5 },
+ { file_path: "c.py", before: 7, after: 6.5, delta: -0.5 },
+ ];
- it("says how many of the total it is drawing", () => {
+ it("groups what got worse ahead of what improved, with name and folder apart", () => {
render(
- <TrendView data={response({ file_deltas: deltas(50), file_deltas_total: 183 })} isLoading={false} error={null} />,
+ <TrendView
+ data={response({ file_deltas: moved, file_deltas_total: 3, file_deltas_worse: 2, file_deltas_improved: 1 })}
+ isLoading={false}
+ error={null}
+ />,
);
- expect(screen.getByText(/Showing the 18 largest of 183 files that changed\./)).toBeInTheDocument();
+ const worse = screen.getByText("Got worse");
+ const improved = screen.getByText("Improved");
+ expect(worse.compareDocumentPosition(improved) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByText("a.py")).toBeInTheDocument();
+ expect(screen.getByText("src/core")).toBeInTheDocument();
+ expect(screen.getByText("2 got worse · 1 improved")).toBeInTheDocument();
});
- it("says so plainly when nothing was dropped", () => {
+ it("puts the code-health delta on the summary line", () => {
render(
- <TrendView data={response({ file_deltas: deltas(4), file_deltas_total: 4 })} isLoading={false} error={null} />,
+ <TrendView
+ data={response({
+ file_deltas: moved,
+ file_deltas_worse: 2,
+ file_deltas_improved: 1,
+ summary: { ...response({}).summary, average_delta: -0.3 },
+ })}
+ isLoading={false}
+ error={null}
+ />,
);
- expect(screen.getByText(/All 4 files that changed\./)).toBeInTheDocument();
+ expect(screen.getByText("2 got worse · 1 improved · code health -0.30")).toBeInTheDocument();
});
- it("claims no total when the server sends none", () => {
- // Hosted sends no `file_deltas_total` and caps its own list, so the list
- // length is not the total. Saying "all 3" would be a guess presented as
- // a fact; the sentence describes only what is drawn.
- render(<TrendView data={response({ file_deltas: deltas(3) })} isLoading={false} error={null} />);
- expect(screen.getByText(/Showing the 3 largest changes\./)).toBeInTheDocument();
- expect(screen.queryByText(/All 3/)).not.toBeInTheDocument();
+ it("counts only what arrived when the server sends no per-direction totals", () => {
+ // Hosted sends neither count and caps its list, so the sentence names the
+ // rows it counted rather than presenting them as every file that moved.
+ render(<TrendView data={response({ file_deltas: moved })} isLoading={false} error={null} />);
+ expect(screen.getByText("Among the 3 largest changes: 2 got worse · 1 improved")).toBeInTheDocument();
});
- it("does not claim completeness against a backend that caps silently", () => {
- // The concrete hosted shape: 50 rows arrive, capped server-side by a
- // backend that reports no total. "All 50 files that changed" would be
- // wrong whenever more than 50 moved.
- render(<TrendView data={response({ file_deltas: deltas(50) })} isLoading={false} error={null} />);
- expect(screen.getByText(/Showing the 18 largest changes\./)).toBeInTheDocument();
- expect(screen.queryByText(/of 50/)).not.toBeInTheDocument();
- expect(screen.queryByText(/All 50/)).not.toBeInTheDocument();
+ it("says how many of a group's total it lists", () => {
+ render(
+ <TrendView
+ data={response({ file_deltas: deltas(20), file_deltas_worse: 140, file_deltas_improved: 0 })}
+ isLoading={false}
+ error={null}
+ />,
+ );
+ expect(screen.getByText("8 of 140")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Show 12 more" }));
+ expect(screen.getByText("20 of 140")).toBeInTheDocument();
});
- it("still counts the chart's own cap when the server sent everything", () => {
- // 25 arrive, 18 are drawn, nothing was truncated server-side. Reporting
- // "All 25" here would describe the response rather than the picture.
- render(
- <TrendView data={response({ file_deltas: deltas(25), file_deltas_total: 25 })} isLoading={false} error={null} />,
+ it("opens a file from its row when the host can, and is plain text when it cannot", () => {
+ const onSelectFile = vi.fn();
+ const { rerender } = render(
+ <TrendView data={response({ file_deltas: moved })} isLoading={false} error={null} />,
+ );
+ expect(screen.queryByRole("button", { name: /a\.py/ })).toBeNull();
+ rerender(
+ <TrendView
+ data={response({ file_deltas: moved })}
+ isLoading={false}
+ error={null}
+ onSelectFile={onSelectFile}
+ />,
);
- expect(screen.getByText(/Showing the 18 largest of 25 files that changed\./)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /a\.py/ }));
+ expect(onSelectFile).toHaveBeenCalledWith("src/core/a.py");
});
it("keeps the empty state rather than reporting zero of zero", () => {
@@ -138,7 +167,7 @@ describe("TrendView — largest score changes", () => {
<TrendView data={response({ file_deltas: [], file_deltas_total: 0 })} isLoading={false} error={null} />,
);
expect(screen.getByText(/No file changed score between the last two snapshots\./)).toBeInTheDocument();
- expect(screen.queryByText(/Showing the/)).not.toBeInTheDocument();
+ expect(screen.queryByText("Got worse")).not.toBeInTheDocument();
});
});
diff --git a/packages/ui/__tests__/health/triage-view-lead.test.tsx b/packages/ui/__tests__/health/triage-view-lead.test.tsx
index 3b02f420a..d52c6b538 100644
--- a/packages/ui/__tests__/health/triage-view-lead.test.tsx
+++ b/packages/ui/__tests__/health/triage-view-lead.test.tsx
@@ -4,6 +4,7 @@
*/
import { describe, expect, it, vi } from "vitest";
+import { useEffect } from "react";
import { render, screen } from "@testing-library/react";
import { SWRConfig } from "swr";
import type { HealthOverviewResponse } from "@repowise-dev/types/health";
@@ -57,3 +58,36 @@ describe("TriageView lead", () => {
expect(screen.getByText("6.8").closest("details")).toBeNull();
});
});
+
+describe("TriageView selection", () => {
+ it("mounts the lead once, so it keeps its state when the overview lands", async () => {
+ const mounts = vi.fn();
+ function Lead() {
+ useEffect(() => {
+ mounts();
+ }, []);
+ return <section data-testid="lead">Fix first</section>;
+ }
+ renderView(<Lead />);
+ // Rendered while the overview is still loading, then still the same node.
+ expect(screen.getByTestId("lead")).toBeInTheDocument();
+ await screen.findByText("Maintainability");
+ expect(mounts).toHaveBeenCalledTimes(1);
+ });
+
+ it("opens the drawer for a linked file before the overview arrives", () => {
+ const renderFileDrawer = vi.fn(() => null);
+ render(
+ <SWRConfig value={{ provider: () => new Map() }}>
+ <TriageView
+ adapter={{ ...adapter(), renderFileDrawer } as unknown as CodeHealthAdapter}
+ selectedPath="src/a.py"
+ onSelectPath={() => {}}
+ />
+ </SWRConfig>,
+ );
+ expect(renderFileDrawer).toHaveBeenCalledWith(
+ expect.objectContaining({ filePath: "src/a.py", lens: "health" }),
+ );
+ });
+});
diff --git a/packages/ui/__tests__/health/unanalysed-files.test.tsx b/packages/ui/__tests__/health/unanalysed-files.test.tsx
index 0425a43c8..1cf5addad 100644
--- a/packages/ui/__tests__/health/unanalysed-files.test.tsx
+++ b/packages/ui/__tests__/health/unanalysed-files.test.tsx
@@ -16,7 +16,7 @@ import {
noFileScored,
type CodeHealthMapFile,
} from "../../src/health/code-health-map.js";
-import { MapFieldList, MapInspector } from "../../src/health/map/inspector.js";
+import { MapFieldList } from "../../src/health/map/inspector.js";
import { CodeHealthLede } from "../../src/health/code-health-lede.js";
function f(path: string, score: number | null, nloc = 100): CodeHealthMapFile {
@@ -76,19 +76,6 @@ describe("an unscored file on the health lens", () => {
expect(names[2]).toContain("Big.php");
expect(names[2]).toContain("—");
});
-
- it("is described, not scored, in the inspector", () => {
- render(
- <MapInspector
- file={f("src/Big.php", null)}
- overlay="health"
- onOpen={() => {}}
- onClose={() => {}}
- />,
- );
- expect(screen.getByText(HEALTH_UNSUPPORTED_LABEL)).toBeTruthy();
- expect(screen.queryByText("10.0")).toBeNull();
- });
});
describe("a field with no scored file", () => {
diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsx
index cd1ba0fa4..761de286f 100644
--- a/packages/ui/src/health/biomarker-details.tsx
+++ b/packages/ui/src/health/biomarker-details.tsx
@@ -70,7 +70,7 @@ function PartnerLink({
onPartnerSelect(path);
}
}}
- className="text-[var(--color-accent-primary)] hover:underline"
+ className="text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-2 hover:decoration-current"
>
{inner}
</a>
@@ -84,7 +84,7 @@ function PartnerLink({
e.stopPropagation();
onPartnerSelect(path);
}}
- className="text-[var(--color-accent-primary)] hover:underline text-left"
+ className="text-left text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-2 hover:decoration-current"
>
{inner}
</button>
diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsx
index 6ca6ea759..4c623a31a 100644
--- a/packages/ui/src/health/code-health-map.tsx
+++ b/packages/ui/src/health/code-health-map.tsx
@@ -3,31 +3,44 @@
/**
* The Code Health galaxy: one field, one geometry, a switchable lens.
*
- * This module is the facade. The layout, the lens encodings, the base node
- * layer, the pointer overlay, and the key are separate modules under `map/`,
- * and everything they export is re-exported here so a host's import path never
- * had to change. What is left in this file is composition: sizing, camera,
- * selection, keyboard navigation, and which layer sees which prop.
+ * 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.
*
* 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.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type {
- KeyboardEvent as ReactKeyboardEvent,
- MouseEvent as ReactMouseEvent,
-} from "react";
import { EmptyState } from "../shared/empty-state";
-import { useCommunityFamilies } from "../shared/use-theme-tokens";
-import { HEALTH_UNSUPPORTED_NOTICE, OVERLAY_ORDER, OVERLAY_SPECS, noFileScored } from "./map/lens";
-import { packGalaxies, rand } from "./map/layout";
-import { FileNodes } from "./map/node-layer";
-import { HoverCard, NodeHighlight, SearchMatches } from "./map/overlay";
-import { MapLegendRows, MapLensSwitcher } from "./map/legend";
-import type { CodeHealthMapFile, CodeHealthOverlay, FileNode, MapScope } from "./map/types";
+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 { 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 { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./map/types";
export type {
CodeHealthMapFile,
@@ -45,7 +58,9 @@ export {
OVERLAY_ORDER,
OVERLAY_SPECS,
PERFORMANCE_STATE_LABEL,
+ QUIET_FILL,
burdenBand,
+ lensAvailable,
noFileScored,
performanceBurden,
performanceFill,
@@ -59,10 +74,11 @@ export type {
PerformanceBurdenUnit,
PerformanceNodeState,
} from "./map/lens";
-export { groupByModule, moduleColorId, packGalaxies } from "./map/layout";
+export { WORLD, fitCamera, groupByModule, layoutField, moduleColorId, packGalaxies } 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, MapInspector } from "./map/inspector";
+export { FIELD_LIST_CAP, MapFieldList } from "./map/inspector";
export interface CodeHealthMapProps {
files: CodeHealthMapFile[];
@@ -74,7 +90,7 @@ export interface CodeHealthMapProps {
highlightPaths?: string[];
/** File click or keyboard selection. */
onSelectFile?: (path: string) => void;
- /** Hover feeds the host's inspector. */
+ /** Hover feeds the host's inspector. `null` when the pointer leaves a node. */
onHoverFile?: (file: CodeHealthMapFile | null) => void;
/** Canvas min height in px. */
minHeight?: number;
@@ -102,16 +118,21 @@ export interface CodeHealthMapProps {
* around the canvas with {@link MapLensSwitcher} / {@link MapLegend}.
*/
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.
+ */
+ 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. */
+ pending?: boolean;
}
-/** Label a galaxy once its on-screen footprint clears this radius (px). */
-const LABEL_MIN_SCREEN_R = 40;
-/** Spokes drawn from each hub to its N biggest files (overview / focused). */
-const SPOKES_OVERVIEW = 8;
-const SPOKES_FOCUSED = 36;
-
-type KeyboardLevel = "module" | "file";
-
export function CodeHealthMap({
files,
selectedPath,
@@ -126,222 +147,96 @@ export function CodeHealthMap({
overlayLoading = false,
scope,
chrome = "canvas",
+ onDrawMore,
+ drawMoreStep = 2000,
+ onIncludeHeldChange,
+ onFindUndrawn,
+ pending = false,
}: CodeHealthMapProps) {
- const overlaySpec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
+ const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
const containerRef = useRef<HTMLDivElement>(null);
+ const baseRef = useRef<HTMLCanvasElement>(null);
+ const topRef = useRef<HTMLCanvasElement>(null);
const keyboardRef = useRef<HTMLDivElement>(null);
- const [dims, setDims] = useState({ width: 0, height: 0 });
+ const labelRefs = useRef<(HTMLButtonElement | null)[]>([]);
+ const reducedMotion = usePrefersReducedMotion();
+
+ const model = useFieldModel(files, spec, search, highlightPaths);
+ const { galaxies, scene } = model;
const [focusModule, setFocusModule] = useState<string | null>(null);
- const [hovered, setHovered] = useState<CodeHealthMapFile | null>(null);
- // Where the hover card sits, in container-relative px. Tracked only while a
- // node is hovered: a card that follows the pointer needs the position, and
- // paying for it across the whole canvas would re-render the facade on every
- // frame of every sweep that identifies nothing.
- const [pointer, setPointer] = useState<{ x: number; y: number } | null>(null);
- const hoveredRef = useRef<CodeHealthMapFile | null>(null);
- hoveredRef.current = hovered;
- const moveRaf = useRef<number | null>(null);
- // Keyboard cursor. One tab stop reaches the whole field: arrows move over
- // modules, Enter descends into one, arrows then move over its files. The
- // alternative is a tab stop per node, which is thousands of them.
- const [kbLevel, setKbLevel] = useState<KeyboardLevel>("module");
- const [kbModule, setKbModule] = useState(0);
- const [kbFile, setKbFile] = useState(0);
- const famFor = useCommunityFamilies();
+ const focusIdx = focusModule ? galaxies.findIndex((g) => g.module === focusModule) : -1;
+ const kb = useKeyboardCursor(galaxies);
+
+ 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 { loop, invalidate } = useFieldCanvas({
+ container: containerRef,
+ base: baseRef,
+ top: topRef,
+ labels: labelRefs,
+ minHeight,
+ reducedMotion,
+ labelKey: `${kb.moduleIdx}:${kb.level}`,
+ live: {
+ scene,
+ fills: model.fills,
+ focusIdx,
+ marked: model.marked,
+ selectedIdx,
+ cursorIdx,
+ hoverIdx,
+ minNodeR: model.minNodeR,
+ labelOrder: model.labelOrder,
+ },
+ });
+ 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]);
- // Latest callbacks held in refs so the node-layer handlers stay referentially
- // stable across renders (the host re-renders on every hover to drive its
- // inspector). Stable handlers let the memoized layers skip reconciling their
- // thousands of circles when only a highlight changed.
const onSelectRef = useRef(onSelectFile);
onSelectRef.current = onSelectFile;
- const onHoverRef = useRef(onHoverFile);
- onHoverRef.current = onHoverFile;
const handleSelect = 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 instead
- // of having to tab back into it.
+ // who reached the map with a pointer can carry on with arrow keys.
keyboardRef.current?.focus();
onSelectRef.current?.(path);
}, []);
- /** Pointer position relative to the container, or null if it has no box. */
- const localPoint = useCallback((clientX: number, clientY: number) => {
- const rect = containerRef.current?.getBoundingClientRect();
- return rect ? { x: clientX - rect.left, y: clientY - rect.top } : null;
- }, []);
- const handleHoverEnter = useCallback(
- (f: CodeHealthMapFile, e: ReactMouseEvent) => {
- // Seed the position from the entering event rather than waiting for the
- // next move, so the card opens where the pointer is instead of wherever
- // it last was.
- setPointer(localPoint(e.clientX, e.clientY));
- setHovered(f);
- onHoverRef.current?.(f);
- },
- [localPoint],
- );
- const handleHoverLeave = useCallback((f: CodeHealthMapFile) => {
- setHovered((h) => (h === f ? null : h));
- }, []);
- const handleCanvasMove = useCallback(
- (e: ReactMouseEvent) => {
- if (!hoveredRef.current || moveRaf.current != null) return;
- const { clientX, clientY } = e;
- // One position per frame. A raw mousemove fires far more often than the
- // card can be repainted, and each one would be a facade render.
- moveRaf.current = requestAnimationFrame(() => {
- moveRaf.current = null;
- setPointer(localPoint(clientX, clientY));
- });
- },
- [localPoint],
- );
- useEffect(
- () => () => {
- if (moveRaf.current != null) cancelAnimationFrame(moveRaf.current);
- },
- [],
- );
-
- useEffect(() => {
- if (!containerRef.current) return;
- const observer = new ResizeObserver((es) => {
- const first = es[0];
- if (!first) return;
- const { width, height } = first.contentRect;
- setDims({ width, height: Math.max(height, minHeight) });
- });
- observer.observe(containerRef.current);
- return () => observer.disconnect();
- }, [minHeight]);
-
- // Escape exits a focused galaxy, while the focus is inside the field. It
- // used to be bound to the window, which meant dismissing anything else on
- // the page - the file drawer this map now opens, most of all - also reset
- // the zoom underneath it.
- useEffect(() => {
- const node = containerRef.current;
- if (!node) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") setFocusModule(null);
- };
- node.addEventListener("keydown", onKey);
- return () => node.removeEventListener("keydown", onKey);
- }, []);
-
- const S = Math.max(0, Math.min(dims.width, dims.height));
-
- const galaxies = useMemo(() => packGalaxies(files, S), [files, S]);
-
- const byModule = useMemo(() => new Map(galaxies.map((g) => [g.module, g])), [galaxies]);
-
- // path -> laid-out node, so the overlays can position themselves without
- // re-rendering the base layer on hover, selection, or a keystroke.
- const nodeIndex = useMemo(() => {
- const m = new Map<string, FileNode>();
- for (const g of galaxies) for (const nd of g.nodes) m.set(nd.file.file_path, nd);
- return m;
- }, [galaxies]);
-
- // Starfield: static, regenerated only on resize.
- const stars = useMemo(() => {
- const { width, height } = dims;
- if (width === 0) return [] as { x: number; y: number; r: number }[];
- const count = Math.min(160, Math.floor((width * height) / 9000));
- return Array.from({ length: count }, (_, i) => ({
- x: rand(i) * width,
- y: rand(i + 1000) * height,
- r: 0.4 + rand(i + 2000) * 1.3,
- }));
- }, [dims]);
-
- const q = (search ?? "").trim().toLowerCase();
- // Matching runs over the loaded field only and produces a bounded list of
- // paths for the overlay. Neither the layout nor the base layer sees the
- // query, so typing repaints the marks and nothing else.
- const matches = useMemo(() => {
- if (q.length === 0) return [] as string[];
- const out: string[] = [];
- for (const path of nodeIndex.keys()) {
- if (path.toLowerCase().includes(q)) out.push(path);
- }
- return out;
- }, [q, nodeIndex]);
-
- const marked = useMemo(() => {
- if (!highlightPaths?.length) return matches;
- return [...new Set([...highlightPaths, ...matches])];
- }, [highlightPaths, matches]);
-
- const focusGalaxy = focusModule ? byModule.get(focusModule) ?? null : null;
-
- const kbGalaxy = galaxies[Math.min(kbModule, Math.max(0, galaxies.length - 1))] ?? null;
- const kbNode =
- kbLevel === "file" && kbGalaxy
- ? kbGalaxy.nodes[Math.min(kbFile, Math.max(0, kbGalaxy.nodes.length - 1))] ?? null
- : null;
-
- const onCanvasKeyDown = useCallback(
- (e: ReactKeyboardEvent) => {
- const forward = e.key === "ArrowRight" || e.key === "ArrowDown";
- const back = e.key === "ArrowLeft" || e.key === "ArrowUp";
- if (kbLevel === "module") {
- if (forward || back) {
- e.preventDefault();
- setKbModule((i) => {
- const n = galaxies.length;
- return n === 0 ? 0 : (i + (forward ? 1 : n - 1)) % n;
- });
- } else if (e.key === "Enter" && kbGalaxy) {
- e.preventDefault();
- setKbLevel("file");
- setKbFile(0);
- setFocusModule(kbGalaxy.module);
- }
- return;
- }
- if (forward || back) {
- e.preventDefault();
- const n = kbGalaxy?.nodes.length ?? 0;
- setKbFile((i) => (n === 0 ? 0 : (i + (forward ? 1 : n - 1)) % n));
- } else if (e.key === "Enter" && kbNode) {
- e.preventDefault();
- handleSelect(kbNode.file.file_path);
- } else if (e.key === "Backspace" || e.key === "Escape") {
- e.preventDefault();
- setKbLevel("module");
- setFocusModule(null);
- }
- },
- [kbLevel, kbGalaxy, kbNode, galaxies.length, handleSelect],
- );
- const offX = (dims.width - S) / 2;
- const offY = (dims.height - S) / 2;
- const k = focusGalaxy ? (S * 0.9) / (2 * focusGalaxy.R) : 1;
- const camX = focusGalaxy ? focusGalaxy.cx : S / 2;
- const camY = focusGalaxy ? focusGalaxy.cy : S / 2;
- const tx = dims.width / 2 - k * (camX + offX);
- const ty = dims.height / 2 - k * (camY + offY);
- const toScreen = (x: number, y: number) => ({ x: k * (x + offX) + tx, y: k * (y + offY) + ty });
-
- if (S === 0) {
- return (
- <div
- ref={containerRef}
- className="w-full rounded-xl bg-[var(--color-bg-root)]"
- style={{ minHeight }}
- />
- );
- }
+ const handlers = useMapPointer({
+ container: containerRef,
+ loop,
+ invalidate,
+ scene,
+ grid: model.grid,
+ minNodeR: model.minNodeR,
+ galaxies,
+ focusModule,
+ focusOn: camera.focusOn,
+ onSelect: handleSelect,
+ setHovered,
+ });
+
+ const onKeyDown = useMapKeyboard({
+ container: containerRef,
+ kb,
+ galaxies,
+ camera,
+ focusModule,
+ setFocusModule,
+ onSelect: handleSelect,
+ });
+
+ const offered = useMemo(() => lenses.filter((l) => lensAvailable(l, files)), [lenses, files]);
if (files.length === 0) {
return (
- <div
- ref={containerRef}
- className="flex w-full items-center justify-center"
- style={{ minHeight }}
- >
+ <div ref={containerRef} className="flex w-full items-center justify-center" style={{ minHeight }}>
<EmptyState
size="compact"
title="No files to map yet"
@@ -351,355 +246,122 @@ export function CodeHealthMap({
);
}
- const labelled = galaxies.filter((g) => focusGalaxy === g || g.R * k >= LABEL_MIN_SCREEN_R);
- const spokeCap = focusGalaxy ? SPOKES_FOCUSED : SPOKES_OVERVIEW;
- const cursorLabel =
- kbLevel === "file" && kbNode
- ? `${kbNode.file.file_path}, ${overlaySpec.label} lens`
- : kbGalaxy
- ? `${kbGalaxy.module}, ${kbGalaxy.fileCount} files`
- : "";
+ const focusGalaxy = focusIdx >= 0 ? galaxies[focusIdx]! : null;
+ const leave = () => {
+ kb.setLevel("module");
+ camera.fitAll();
+ };
return (
<div
ref={containerRef}
- onMouseMove={handleCanvasMove}
+ 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 }}
+ 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. Arrows move over modules, Enter
- descends into one and then moves over its files, Enter again selects
- it and opens the same inspector a click opens. A tab stop per node
- would be thousands of them, which is not navigation. Pointer events
- stay off so it never intercepts a click meant for the canvas. */}
+ {/* 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={`Code health map, ${overlaySpec.label} lens. Arrow keys move between modules, Enter opens one.`}
- onKeyDown={onCanvasKeyDown}
+ 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}
+ {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" }}
+ />
- <svg
- width={dims.width}
- height={dims.height}
- role="img"
- aria-label={`Code universe: modules as galaxies, files radiating from each hub, sized by lines of code and marked by ${overlaySpec.label.toLowerCase()}`}
- className="block"
- >
- <defs>
- <radialGradient id="ch-mist" cx="50%" cy="42%" r="75%">
- <stop offset="0%" stopColor="var(--color-bg-surface)" />
- <stop offset="100%" stopColor="var(--color-bg-root)" />
- </radialGradient>
- {/* Nebula falloff. This was an feGaussianBlur, which is an offscreen
- raster pass per blob, and the blobs live inside the group whose
- transform animates on every galaxy zoom, so all of them
- re-rastered every frame of the transition. A gradient is painted
- directly and costs nothing to animate. `currentColor` resolves per
- blob, so one def serves every galaxy family. */}
- {/* The falloff starts early and runs the whole way out. Holding full
- opacity to seven tenths of the radius and dropping over the last
- three gave every galaxy a visible disc edge, so the field read as
- a page of hard circles with files inside them rather than as
- clouds the files sit in. */}
- <radialGradient id="ch-nebula">
- <stop offset="0%" stopColor="currentColor" stopOpacity="1" />
- <stop offset="40%" stopColor="currentColor" stopOpacity="0.72" />
- <stop offset="72%" stopColor="currentColor" stopOpacity="0.3" />
- <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
- </radialGradient>
- </defs>
+ <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)}
+ />
- {/* Misty backdrop + starfield (static; clicking it exits a galaxy). */}
- <rect
- x={0}
- y={0}
- width={dims.width}
- height={dims.height}
- fill="url(#ch-mist)"
- onClick={() => setFocusModule(null)}
+ {chrome === "canvas" ? (
+ <CanvasChrome
+ overlay={overlay}
+ spec={spec}
+ lenses={offered}
+ loading={overlayLoading}
+ onOverlayChange={onOverlayChange}
/>
- <g className="pointer-events-none">
- {stars.map((s, i) => (
- <circle key={`star-${i}`} cx={s.x} cy={s.y} r={s.r} fill="var(--color-canvas-dot)" />
- ))}
- </g>
-
- <g
- style={{ transition: "transform 460ms cubic-bezier(0.4,0,0.2,1)" }}
- transform={`translate(${tx},${ty}) scale(${k})`}
- >
- {/* Nebula blobs (back layer) */}
- {galaxies.map((g) => {
- const fam = famFor(g.colorId);
- const faded = focusGalaxy != null && focusGalaxy !== g;
- return (
- <circle
- key={`blob-${g.module}`}
- cx={g.cx + offX}
- cy={g.cy + offY}
- // The gradient stops inside its own radius, so the blob grows
- // to compensate; the softer the falloff, the more reach it
- // needs to end in the page rather than at a rim.
- r={g.R * 1.1}
- style={{ color: fam.hub }}
- fill="url(#ch-nebula)"
- fillOpacity={faded ? 0.04 : 0.13}
- data-galaxy={g.module}
- className="cursor-zoom-in"
- onClick={(e) => {
- e.stopPropagation();
- setFocusModule((m) => (m === g.module ? null : g.module));
- }}
- />
- );
- })}
-
- {/* Spokes: hub to its biggest files */}
- {galaxies.map((g) => {
- const fam = famFor(g.colorId);
- if (focusGalaxy != null && focusGalaxy !== g) return null;
- return (
- <g key={`spokes-${g.module}`} stroke={fam.hub} strokeOpacity={0.28}>
- {g.nodes.slice(0, spokeCap).map((nd) => (
- <line
- key={nd.file.file_path}
- x1={g.cx + offX}
- y1={g.cy + offY}
- x2={nd.x + offX}
- y2={nd.y + offY}
- strokeWidth={0.6 / k}
- />
- ))}
- </g>
- );
- })}
-
- <FileNodes
- galaxies={galaxies}
- focusModuleKey={focusGalaxy?.module ?? null}
- fill={overlaySpec.fill}
- offX={offX}
- offY={offY}
- strokeWidth={0.5 / k}
- interactive={!!onSelectFile}
- onSelect={handleSelect}
- onHoverEnter={handleHoverEnter}
- onHoverLeave={handleHoverLeave}
- />
-
- <SearchMatches paths={marked} nodeIndex={nodeIndex} offX={offX} offY={offY} />
-
- <NodeHighlight
- hovered={hovered}
- selectedPath={selectedPath ?? null}
- nodeIndex={nodeIndex}
- offX={offX}
- offY={offY}
- fill={overlaySpec.fill}
- />
-
- {/* Keyboard cursor, drawn like a focus ring so the one tab stop has
- a visible position on the field. */}
- {kbNode ? (
- <circle
- data-keyboard-cursor={kbNode.file.file_path}
- cx={kbNode.x + offX}
- cy={kbNode.y + offY}
- r={kbNode.r + 3.5}
- fill="none"
- stroke="var(--color-accent-primary)"
- strokeWidth={2 / k}
- strokeDasharray={`${3 / k} ${2 / k}`}
- className="pointer-events-none"
- />
- ) : null}
-
- {/* Hub markers */}
- {galaxies.map((g) => {
- const fam = famFor(g.colorId);
- const faded = focusGalaxy != null && focusGalaxy !== g;
- return (
- <circle
- key={`hub-${g.module}`}
- cx={g.cx + offX}
- cy={g.cy + offY}
- r={Math.max(2.5, g.R * 0.035)}
- fill={fam.hub}
- fillOpacity={faded ? 0.3 : 0.95}
- stroke="var(--color-bg-root)"
- strokeWidth={1 / k}
- className="pointer-events-none"
- />
- );
- })}
- </g>
- </svg>
+ ) : null}
- {/* Editorial galaxy labels: a real-px HTML overlay, crisp at any zoom. */}
- <div className="pointer-events-none absolute inset-0">
- {labelled.map((g) => {
- const fam = famFor(g.colorId);
- // toScreen already folds in offX/offY, so pass the raw pack coords.
- const p = toScreen(g.cx, g.cy);
- if (p.x < -40 || p.x > dims.width + 40 || p.y < 0 || p.y > dims.height) return null;
- const big = focusGalaxy === g;
- const cursor = kbLevel === "module" && kbGalaxy === g;
- return (
- <span
- key={`lbl-${g.module}`}
- // Mono, not serif. These are data-viz labels on a canvas overlay,
- // machine-produced names, which the type rules put in mono.
- className={`absolute -translate-x-1/2 -translate-y-1/2 inline-flex items-center gap-1.5 whitespace-nowrap rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-mono uppercase tracking-[0.12em] text-[var(--color-text-primary)] shadow-sm backdrop-blur-sm ${
- cursor
- ? "ring-2 ring-[var(--color-accent-primary)]"
- : "ring-1 ring-[var(--color-border-default)]"
- } ${big ? "text-[11px] font-medium" : "text-[10px]"}`}
- style={{ left: p.x, top: p.y }}
- >
- {/* Galaxy color as a dot; the text stays high-contrast so plum
- module hues remain legible in dark mode. */}
- <span
- className="h-1.5 w-1.5 shrink-0 rounded-full"
- style={{ backgroundColor: fam.hub }}
- aria-hidden
- />
- {g.module}
- </span>
- );
- })}
+ <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}
+ />
</div>
- {/* Lens switcher + key, floated over the canvas. Only for a host with
- nowhere else to put them. A host that lays them out around the map
- passes chrome="none", so the reader is not looking at the field
- through a stack of glass panels. */}
- {chrome === "canvas" ? (
- <>
- {onOverlayChange ? (
- <div className="absolute left-3 top-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] p-1 shadow-sm backdrop-blur-sm">
- <MapLensSwitcher
- overlay={overlay}
- onOverlayChange={onOverlayChange}
- lenses={lenses}
- className="border-0"
- />
- </div>
- ) : null}
-
- <div
- className={`absolute left-3 max-w-[220px] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-2 text-xs shadow-sm backdrop-blur-sm ${
- onOverlayChange ? "top-14" : "top-3"
- }`}
- >
- <div className="mb-1.5 font-medium text-[var(--color-text-secondary)]">
- {overlaySpec.label}
- </div>
- <MapLegendRows spec={overlaySpec} loading={overlayLoading} />
- <div className="mt-2 border-t border-[var(--color-border-default)] pt-1.5 text-[var(--color-text-tertiary)]">
- {overlaySpec.caption}
- <br />
- click a galaxy to zoom
- </div>
- </div>
- </>
- ) : null}
-
- {/* Zoom-out breadcrumb, only while a galaxy is focused. */}
- {focusGalaxy ? (
- <div className="absolute right-3 top-3 flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-xs shadow-sm backdrop-blur-sm">
- <span className="max-w-[180px] truncate font-medium text-[var(--color-text-primary)]">
- {focusGalaxy.module}
- </span>
- <button
- type="button"
- onClick={() => {
- setFocusModule(null);
- setKbLevel("module");
- }}
- 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>
+ {scope ? (
+ <MapScopeNote
+ scope={scope}
+ matches={model.matches.length}
+ query={model.query}
+ drawMoreStep={drawMoreStep}
+ pending={pending}
+ onDrawMore={onDrawMore}
+ onIncludeHeldChange={onIncludeHeldChange}
+ onFindUndrawn={onFindUndrawn}
+ />
) : null}
- {scope ? <MapScopeNote scope={scope} matches={matches.length} query={q} /> : 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-[11px] text-[var(--color-text-secondary)] shadow-sm backdrop-blur-sm sm:max-w-[44%]"
+ 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}
- {hovered && pointer ? (
+ {hover ? (
<HoverCard
- file={hovered}
+ file={hover.file}
overlay={overlay}
- x={pointer.x}
- y={pointer.y}
- width={dims.width}
- height={dims.height}
+ x={hover.x}
+ y={hover.y}
+ width={loop.current.view.w}
+ height={loop.current.view.h}
/>
) : null}
</div>
);
}
-/**
- * What this field is, in one sentence, from the response that drew it.
- *
- * A count and the visual it describes have to come from one source, so this
- * reads the server's own selection totals rather than the array length: a
- * caption saying "3,808 files" over a two-thousand node field is a claim the
- * reader has no way to check.
- */
-function MapScopeNote({
- scope,
- matches,
- query,
-}: {
- scope: MapScope;
- matches: number;
- query: string;
-}) {
- const capped = scope.shown < scope.eligible;
- const hiddenCauses = scope.omitted.performanceFiles;
- return (
- <div
- data-testid="map-scope"
- className="pointer-events-none absolute bottom-3 right-3 max-w-[64%] rounded-md sm:max-w-[52%] border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-right text-[11px] text-[var(--color-text-tertiary)] shadow-sm backdrop-blur-sm"
- >
- <span className="font-mono tabular-nums">
- {scope.shown.toLocaleString()} of {scope.eligible.toLocaleString()}
- </span>{" "}
- files drawn
- {capped ? (
- <>
- {" · "}
- {hiddenCauses == null
- ? `${scope.omitted.files.toLocaleString()} not drawn`
- : hiddenCauses > 0
- ? `${hiddenCauses.toLocaleString()} file${hiddenCauses === 1 ? "" : "s"} with open causes not drawn`
- : "every file with an open cause is drawn"}
- </>
- ) : null}
- {query ? (
- <>
- {" · "}
- <span className="tabular-nums">{matches.toLocaleString()}</span>
- {` match${matches === 1 ? "" : "es"} here`}
- </>
- ) : null}
- </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` : "";
}
diff --git a/packages/ui/src/health/file-drawer/issues.tsx b/packages/ui/src/health/file-drawer/issues.tsx
new file mode 100644
index 000000000..c2f504ea9
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/issues.tsx
@@ -0,0 +1,472 @@
+"use client";
+
+/**
+ * The file drawer's findings: "What's wrong" (the top kinds of problem, in
+ * plain words, each opening onto its evidence) and the collapsed "Other
+ * issues" below it, grouped by the function they fire on. Triage sits behind
+ * one menu per row.
+ */
+
+import { useId, useState } from "react";
+import type { ReactNode } from "react";
+import { ChevronRight, MoreHorizontal } from "lucide-react";
+import { InfoTip } from "../../shared/info-tip";
+import { CollapsibleSection } from "../../shared/collapsible-section";
+import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
+import { cn } from "../../lib/cn";
+import {
+ biomarkerInfo,
+ biomarkerLabel,
+ HISTORY_CHIP,
+ HISTORY_EXPLAINER,
+ HISTORY_LABEL,
+ isHistoryBiomarker,
+} from "../biomarker-glossary";
+import { BiomarkerDetails } from "../biomarker-details";
+import { plainIssue } from "../plain-language";
+import { SeverityMark } from "../severity-mark";
+import { VerificationTag } from "../verification-tag";
+import { LowerPriorityTag } from "../lower-priority-tag";
+import { PreviewBadge } from "../preview-badge";
+import { ImpactFigure } from "../impact-figure";
+import type { GatedByLanguage } from "@repowise-dev/types/health";
+import type { HealthDrawerFinding } from "../health-file-drawer";
+import {
+ findingLocation,
+ statusOf,
+ type FindingSection,
+ type StatusOverrides,
+ type TopIssue,
+} from "./model";
+import { MICRO_LABEL, POOLED_FILE_KEY, QUIET_LINK, STATUS_LABEL, TRIAGE_STATUSES } from "./shared";
+
+/** What every row needs from the drawer: links, triage, and its opened detail. */
+export interface RowContext {
+ fileViewHrefFor: ((lineStart: number) => string) | undefined;
+ savingId: string | null;
+ onStatusChange: ((id: string, status: string) => Promise<void>) | undefined;
+ overrides: StatusOverrides;
+ detail: (f: HealthDrawerFinding) => ReactNode;
+}
+
+/** The evidence and suggested fix a row opens onto. */
+export function FindingDetail({
+ finding: f,
+ suggestion,
+ onPartnerSelect,
+ onPartnerHref,
+}: {
+ finding: HealthDrawerFinding;
+ suggestion: string | undefined;
+ onPartnerSelect?: ((path: string) => void) | undefined;
+ onPartnerHref?: ((path: string) => string) | undefined;
+}) {
+ return (
+ <>
+ <BiomarkerDetails
+ biomarkerType={f.biomarker_type}
+ details={f.details}
+ onPartnerSelect={onPartnerSelect}
+ onPartnerHref={onPartnerHref}
+ />
+ {suggestion ? (
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ <span className="font-medium text-[var(--color-text-primary)]">Suggested fix: </span>
+ {suggestion}
+ </p>
+ ) : null}
+ </>
+ );
+}
+
+export function WhatsWrong({ issues, ctx }: { issues: TopIssue[]; ctx: RowContext }) {
+ if (issues.length === 0) return null;
+ return (
+ <section className="flex flex-col gap-1" aria-label="What's wrong">
+ <h3 className={MICRO_LABEL}>What&rsquo;s wrong</h3>
+ <ul className="flex flex-col">
+ {issues.map(({ lead, more }) => (
+ <IssueRow key={lead.id} finding={lead} more={more} ctx={ctx} />
+ ))}
+ </ul>
+ </section>
+ );
+}
+
+/**
+ * One "What's wrong" row: a plain title, where it is, a small impact figure and
+ * why it matters. Pressing the row opens the evidence and the suggested fix
+ * inline; triage stays behind the row's menu.
+ */
+function IssueRow({
+ finding: f,
+ more,
+ ctx,
+}: {
+ finding: HealthDrawerFinding;
+ /** Other places the same kind of problem fires, listed under Other issues. */
+ more: number;
+ ctx: RowContext;
+}) {
+ const [open, setOpen] = useState(false);
+ const plain = plainIssue(f.biomarker_type);
+ const location = findingLocation(f, ctx.fileViewHrefFor);
+ const bodyId = useId();
+ return (
+ <li className="border-t border-[var(--color-border-default)] first:border-t-0">
+ <div className="flex items-start gap-2">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ // Only while the body is mounted: an id that resolves to nothing is
+ // a broken reference for assistive tech.
+ {...(open ? { "aria-controls": bodyId } : {})}
+ className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-sm py-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <span className="flex min-w-0 items-baseline gap-2">
+ <ChevronRight
+ aria-hidden="true"
+ className={cn(
+ "h-3.5 w-3.5 shrink-0 self-center text-[var(--color-text-tertiary)] transition-transform motion-reduce:transition-none",
+ open && "rotate-90",
+ )}
+ />
+ <span className="min-w-0 flex-1 text-[15px] font-medium text-[var(--color-text-primary)]">
+ {plain.title}
+ </span>
+ <ImpactFigure impact={f.health_impact} tone="muted" className="text-xs" />
+ </span>
+ <span className="flex min-w-0 flex-wrap items-baseline gap-x-2 pl-[22px] text-xs">
+ {location ? (
+ <span className="font-mono text-[var(--color-text-secondary)]">{location.label}</span>
+ ) : null}
+ {more > 0 ? (
+ <span className="text-[var(--color-text-secondary)]">
+ {location ? `and ${more} more` : `in ${more + 1} places`}
+ </span>
+ ) : null}
+ <span className="min-w-0 text-[var(--color-text-tertiary)]">{plain.why}</span>
+ </span>
+ </button>
+ <span className="flex shrink-0 items-center gap-1 pt-2">
+ <RowActions
+ finding={f}
+ label={location ? `${plain.title} at ${location.label}` : plain.title}
+ ctx={ctx}
+ />
+ </span>
+ </div>
+ {open ? (
+ <div id={bodyId} className="flex flex-col gap-2 pb-3 pl-[22px]">
+ <IssueEvidence finding={f} href={location?.href} label={location?.label} />
+ {ctx.detail(f)}
+ </div>
+ ) : null}
+ </li>
+ );
+}
+
+/** The detector's own name and reason, its exception tags, and the line link. */
+function IssueEvidence({
+ finding: f,
+ href,
+ label,
+}: {
+ finding: HealthDrawerFinding;
+ href: string | undefined;
+ label: string | undefined;
+}) {
+ return (
+ <>
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {biomarkerLabel(f.biomarker_type)}.
+ </span>{" "}
+ {f.reason}
+ </p>
+ <span className="flex flex-wrap gap-1.5 empty:hidden">
+ <VerificationTag verification={f.verification} />
+ <LowerPriorityTag reason={f.lower_priority} />
+ <PreviewBadge note={f.preview} />
+ </span>
+ {href ? (
+ <a href={href} className={cn(QUIET_LINK, "font-mono")}>
+ Go to {label}
+ </a>
+ ) : null}
+ </>
+ );
+}
+
+/** A row's triage status, its save in flight, and the menu that changes it. */
+function RowActions({
+ finding: f,
+ label,
+ ctx,
+}: {
+ finding: HealthDrawerFinding;
+ label: string;
+ ctx: RowContext;
+}) {
+ const status = statusOf(f, ctx.overrides);
+ const saving = ctx.savingId === f.id;
+ const onStatusChange = ctx.onStatusChange;
+ return (
+ <>
+ {status !== "open" ? (
+ <span className="rounded border border-[var(--color-border-default)] px-1.5 text-[10px] text-[var(--color-text-secondary)]">
+ {STATUS_LABEL[status] ?? status}
+ </span>
+ ) : null}
+ {saving ? <span className="text-[10px] text-[var(--color-text-tertiary)]">Saving…</span> : null}
+ {onStatusChange ? (
+ <TriageMenu
+ label={label}
+ status={status}
+ disabled={saving}
+ onSelect={(next) => void onStatusChange(f.id, next).catch(() => {})}
+ />
+ ) : null}
+ </>
+ );
+}
+
+export function OtherIssues({
+ rest,
+ sections,
+ leading,
+ heldBack,
+ heldBackTotal,
+ ctx,
+}: {
+ rest: HealthDrawerFinding[];
+ sections: FindingSection[];
+ /** How many rows lead above, so the title says what this list leaves out. */
+ leading: number;
+ heldBack: GatedByLanguage | null | undefined;
+ heldBackTotal: number;
+ ctx: RowContext;
+}) {
+ if (rest.length === 0 && heldBackTotal === 0) return null;
+ const count = rest.length.toLocaleString();
+ return (
+ <CollapsibleSection
+ title={leading > 0 ? `Other issues (${count})` : `All issues (${count})`}
+ hint={otherIssuesHint(leading, sections.length)}
+ >
+ {heldBackTotal > 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ <span className="tabular-nums">{heldBackTotal.toLocaleString()}</span> more{" "}
+ {heldBackTotal === 1 ? "finding is" : "findings are"} held back:{" "}
+ {Object.values(heldBack ?? {})
+ .map((g) => g.reason)
+ .join(" ")}
+ </p>
+ ) : null}
+ <div className="flex flex-col">
+ {sections.map((s) => (
+ <CollapsibleSection
+ key={s.isFile ? `file:${s.key}` : `fn:${s.key}`}
+ dense
+ // Single-issue groups have nothing to collapse; the rest open as
+ // compact headers.
+ defaultOpen={s.group.length === 1}
+ title={<GroupTitle section={s} />}
+ hint={<GroupHint section={s} />}
+ >
+ <ul className="flex flex-col pl-5">
+ {s.group.map((f) => (
+ <FindingRow key={f.id} finding={f} ctx={ctx} />
+ ))}
+ </ul>
+ </CollapsibleSection>
+ ))}
+ </div>
+ </CollapsibleSection>
+ );
+}
+
+function otherIssuesHint(leading: number, groups: number): string | undefined {
+ if (leading > 0) return `not repeating the ${leading} above`;
+ return groups > 1 ? `in ${groups} places` : undefined;
+}
+
+/** A group's count and total, and its cap when the group is the whole category. */
+function GroupHint({ section: s }: { section: FindingSection }) {
+ return (
+ <>
+ <span>
+ {s.group.length} {s.group.length === 1 ? "issue" : "issues"}
+ </span>
+ <ImpactFigure impact={s.total} tone="muted" />
+ {/* Why 34 issues cost half a point. Without this the count reads as the
+ severity and the held total looks like a bug. The explanation rides
+ in the accessible name, because a bare `title` never reaches it. */}
+ {s.atCap !== null ? (
+ <span
+ className="rounded-sm border border-[var(--color-border-default)] px-1 text-[10px] text-[var(--color-text-tertiary)]"
+ aria-label={`at limit: held at its ${s.atCap.toFixed(2)}-point ceiling, so more issues of this kind take nothing further off`}
+ >
+ at limit
+ </span>
+ ) : null}
+ </>
+ );
+}
+
+/** A group's header: the function plus its worst marker, or the file-level biomarker. */
+function GroupTitle({ section: s }: { section: FindingSection }) {
+ const worstLabel = biomarkerLabel(s.worst.biomarker_type);
+ if (!s.isFile) {
+ return (
+ <span className="block truncate text-[var(--color-text-primary)]">
+ <span className="font-mono">{s.key}</span>
+ <span className="text-[var(--color-text-tertiary)]"> · {worstLabel}</span>
+ </span>
+ );
+ }
+ return (
+ <span className="block truncate text-[var(--color-text-primary)]">
+ {s.key === POOLED_FILE_KEY ? (
+ "Across the file"
+ ) : (
+ <>
+ {worstLabel}
+ <span className="text-[var(--color-text-tertiary)]"> · across the file</span>
+ </>
+ )}
+ </span>
+ );
+}
+
+/**
+ * One finding in "Other issues", as a hairline row with whatever the opened
+ * detail carries (evidence, suggestion).
+ *
+ * Chips mark exceptions only: a provisional type, a lower-priority reason, a
+ * preview cell, a history marker, a triaged status. Every row carrying its
+ * category and pillar communicated nothing.
+ */
+function FindingRow({ finding: f, ctx }: { finding: HealthDrawerFinding; ctx: RowContext }) {
+ const info = biomarkerInfo(f.biomarker_type);
+ const label = biomarkerLabel(f.biomarker_type);
+ const location = findingLocation(f, ctx.fileViewHrefFor);
+ return (
+ <li className="flex flex-col gap-1 border-t border-[var(--color-border-default)] py-2.5 first:border-t-0">
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
+ <SeverityMark severity={f.severity} />
+ <span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
+ {label}
+ {info.description ? <InfoTip content={info.description} label={`About ${label}`} /> : null}
+ </span>
+ <VerificationTag verification={f.verification} />
+ <LowerPriorityTag reason={f.lower_priority} />
+ <PreviewBadge note={f.preview} />
+ {isHistoryBiomarker(f.biomarker_type) ? <WatchChip /> : null}
+ <LocationText location={location} />
+ <span className="ml-auto inline-flex shrink-0 items-center gap-1">
+ <ImpactFigure impact={f.health_impact} tone="muted" className="text-xs" />
+ <RowActions
+ finding={f}
+ label={location ? `${label} at ${location.label}` : label}
+ ctx={ctx}
+ />
+ </span>
+ </div>
+ <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
+ {ctx.detail(f)}
+ </li>
+ );
+}
+
+/** Scored, but nothing in this file will clear it. */
+function WatchChip() {
+ return (
+ <span
+ className={`inline-flex items-center gap-1 rounded px-1.5 py-px text-[10px] font-medium ${HISTORY_CHIP}`}
+ >
+ {HISTORY_LABEL}
+ <InfoTip content={HISTORY_EXPLAINER} label="Why this is a watch item" />
+ </span>
+ );
+}
+
+function LocationText({ location }: { location: ReturnType<typeof findingLocation> }) {
+ if (!location) return null;
+ if (location.href) {
+ return (
+ <a href={location.href} className={cn(QUIET_LINK, "shrink-0 font-mono font-normal")}>
+ {location.label}
+ </a>
+ );
+ }
+ return (
+ <span className="shrink-0 font-mono text-xs text-[var(--color-text-tertiary)]">
+ {location.label}
+ </span>
+ );
+}
+
+/** Triage behind one overflow control, so a row has one visible verb at most. */
+function TriageMenu({
+ label,
+ status,
+ disabled,
+ onSelect,
+}: {
+ label: string;
+ status: string;
+ disabled: boolean;
+ onSelect: (status: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const headingId = useId();
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ aria-label={`Triage ${label}`}
+ disabled={disabled}
+ className="rounded-md p-1 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-selected)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] disabled:opacity-50"
+ >
+ <MoreHorizontal className="h-4 w-4" aria-hidden="true" />
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-44 p-1">
+ {/* A labelled group of toggle buttons, not a menu: it has no roving
+ focus, so it does not claim the menu keyboard contract. Tab moves
+ through the options and Escape closes the popover. */}
+ <div role="group" aria-labelledby={headingId}>
+ <p
+ id={headingId}
+ className="px-2 pb-1 pt-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"
+ >
+ Mark as
+ </p>
+ {TRIAGE_STATUSES.map((opt) => {
+ const current = opt.value === status;
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ aria-pressed={current}
+ disabled={current}
+ onClick={() => {
+ setOpen(false);
+ onSelect(opt.value);
+ }}
+ className={cn(
+ "block w-full rounded px-2 py-1.5 text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",
+ current
+ ? "font-medium text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-selected)] hover:text-[var(--color-text-primary)]",
+ )}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/ui/src/health/file-drawer/model.ts b/packages/ui/src/health/file-drawer/model.ts
new file mode 100644
index 000000000..27ae1c12a
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/model.ts
@@ -0,0 +1,367 @@
+/**
+ * Everything the file drawer derives from its props, in one hook, so the
+ * drawer itself is a composition of sections that only render.
+ *
+ * Pure functions do the work (which findings lead, how the rest group, what
+ * the verdict may honestly say, what fixing the top issue gives back); the
+ * hook memoizes them against the triage state the drawer keeps for the file.
+ */
+
+import { useCallback, useMemo, useState } from "react";
+import {
+ asBiomarkerDimension,
+ biomarkerInfo,
+ CATEGORY_CAP,
+ isHistoryBiomarker,
+} from "../biomarker-glossary";
+import type { ScoreBreakdownCategory } from "../score-breakdown";
+import { fileVerdict, type Verdict } from "../plain-language";
+import { relatedWorkCount, type RelatedLensName } from "../related-work";
+import type {
+ HealthDrawerFinding,
+ HealthDrawerMetric,
+ HealthFileDrawerProps,
+} from "../health-file-drawer";
+import { CLOSED_STATUSES, POOLED_FILE_KEY, TOP_FINDINGS } from "./shared";
+
+/** Stable empty list, so a host passing no findings does not churn the memos. */
+const NO_FINDINGS: HealthDrawerFinding[] = [];
+
+export type StatusOverrides = Readonly<Record<string, string>>;
+
+export function statusOf(f: HealthDrawerFinding, overrides: StatusOverrides): string {
+ return overrides[f.id] ?? f.status ?? "open";
+}
+
+function isOpen(f: HealthDrawerFinding, overrides: StatusOverrides): boolean {
+ return !CLOSED_STATUSES.has(statusOf(f, overrides));
+}
+
+/** One "What's wrong" row: the worst instance of a kind and every place it fires. */
+export interface TopIssue {
+ lead: HealthDrawerFinding;
+ /** Other places the same kind fires. */
+ more: number;
+ members: HealthDrawerFinding[];
+}
+
+/**
+ * Whether a finding may lead "What's wrong". History markers are scored but no
+ * edit here clears them; one that takes nothing off is not a reason the file
+ * scores low; a closed one is already decided; and under the performance lens
+ * its findings are the causes block above, so they do not lead a second time.
+ */
+function canLead(f: HealthDrawerFinding, overrides: StatusOverrides, lens: string | undefined) {
+ if (isHistoryBiomarker(f.biomarker_type)) return false;
+ if (!(f.health_impact > 0)) return false;
+ if (!isOpen(f, overrides)) return false;
+ const performanceHere =
+ lens === "performance" && asBiomarkerDimension(f.dimension, f.biomarker_type) === "performance";
+ return !performanceHere;
+}
+
+/**
+ * One row per kind of problem: three "Errors caught too broadly" rows read as
+ * three problems when they are one, so a kind shows its worst instance and
+ * says how many more places it fires.
+ */
+export function pickTopIssues(
+ findings: readonly HealthDrawerFinding[],
+ overrides: StatusOverrides,
+ lens: string | undefined,
+): TopIssue[] {
+ const byKind = new Map<string, HealthDrawerFinding[]>();
+ for (const f of findings) {
+ if (!canLead(f, overrides, lens)) continue;
+ const bucket = byKind.get(f.biomarker_type);
+ if (bucket) bucket.push(f);
+ else byKind.set(f.biomarker_type, [f]);
+ }
+ return [...byKind.values()]
+ .map((members) => ({ lead: worstOf(members), more: members.length - 1, members }))
+ .sort((a, b) => b.lead.health_impact - a.lead.health_impact)
+ .slice(0, TOP_FINDINGS);
+}
+
+function worstOf(group: readonly HealthDrawerFinding[]): HealthDrawerFinding {
+ return group.reduce((a, b) => (b.health_impact > a.health_impact ? b : a));
+}
+
+/** What the open findings below the lead still take off, and how much is history. */
+function tallyRest(rest: readonly HealthDrawerFinding[], overrides: StatusOverrides) {
+ let count = 0;
+ let impact = 0;
+ let historyImpact = 0;
+ for (const f of rest) {
+ if (!isOpen(f, overrides)) continue;
+ const off = Math.max(0, f.health_impact);
+ count += 1;
+ impact += off;
+ if (isHistoryBiomarker(f.biomarker_type)) historyImpact += off;
+ }
+ return { count, impact, historyImpact };
+}
+
+/**
+ * What fixing the top issue would give back, only when the numbers support
+ * saying so: its category must not be held at a cap (removing one of many
+ * capped issues changes nothing), and the score must not be clamped at the
+ * floor (then the deduction overshoots what the score shows).
+ */
+export function topIssueRecovery(
+ metric: HealthDrawerMetric,
+ breakdown: HealthFileDrawerProps["breakdown"],
+ members: readonly HealthDrawerFinding[] | undefined,
+): { points: number; places: number } | null {
+ if (!members?.length || !breakdown || metric.score == null) return null;
+ const cat = biomarkerInfo(members[0]!.biomarker_type).category;
+ const row = breakdown.categories.find((c) => String(c.category) === cat);
+ if (!row || row.capped) return null;
+ if (Math.abs(10 - breakdown.total_deduction - metric.score) > 0.05) return null;
+ // Every place the row covers, never more than the category actually took off
+ // or than the score has room to rise.
+ const sum = members.reduce((n, f) => n + Math.max(0, f.health_impact), 0);
+ const gain = Math.min(sum, row.applied_deduction, 10 - metric.score);
+ return gain >= 0.1 ? { points: Math.round(gain * 10) / 10, places: members.length } : null;
+}
+
+export interface FindingSection {
+ key: string;
+ group: HealthDrawerFinding[];
+ isFile: boolean;
+ total: number;
+ worst: HealthDrawerFinding;
+ /** The enforced cap when this group's category is holding at it, else null. */
+ atCap: number | null;
+}
+
+/** Categories the scorer held at their ceiling, per the server breakdown.
+ * `capped` is the server's verdict and is never recomputed here; the cap
+ * VALUE is display only, so it falls back to the glossary mirror. */
+function cappedCategories(categories: readonly ScoreBreakdownCategory[]) {
+ const capped = new Map<string, number | null>();
+ for (const c of categories) {
+ if (c.capped) capped.set(String(c.category), c.cap ?? null);
+ }
+ return capped;
+}
+
+/** By function, and file-level ones by biomarker. Two maps, never one keyed by
+ * a sentinel string: a C++ or Rust function can legitimately be `file::read`,
+ * so any "file" prefix is collidable. */
+function bucketFindings(findings: readonly HealthDrawerFinding[]) {
+ const byFunction = new Map<string, HealthDrawerFinding[]>();
+ const byBiomarker = new Map<string, HealthDrawerFinding[]>();
+ for (const f of findings) {
+ const map = f.function_name ? byFunction : byBiomarker;
+ const key = f.function_name ?? f.biomarker_type;
+ const bucket = map.get(key);
+ if (bucket) bucket.push(f);
+ else map.set(key, [f]);
+ }
+ return { byFunction, byBiomarker };
+}
+
+/** Repeating file-level biomarkers get a group each; one-offs pool into one. */
+function fileLevelGroups(byBiomarker: Map<string, HealthDrawerFinding[]>) {
+ const pooled: HealthDrawerFinding[] = [];
+ const groups: { key: string; group: HealthDrawerFinding[] }[] = [];
+ for (const [key, group] of byBiomarker) {
+ if (group.length > 1) groups.push({ key, group });
+ else pooled.push(...group);
+ }
+ if (pooled.length > 0) groups.push({ key: POOLED_FILE_KEY, group: pooled });
+ return groups;
+}
+
+/**
+ * The cap to name on a file-level group, or null. Claimed only when this group
+ * IS the category, decided from the findings on screen: a host may scope them
+ * differently from the server's subtotal (hosted excludes triaged findings
+ * from one).
+ */
+function groupCap(
+ key: string,
+ worst: HealthDrawerFinding,
+ allFindings: readonly HealthDrawerFinding[],
+ capped: Map<string, number | null>,
+): number | null {
+ if (key === POOLED_FILE_KEY) return null;
+ const cat = biomarkerInfo(worst.biomarker_type).category;
+ if (!capped.has(cat)) return null;
+ const owns = allFindings.every(
+ (f) =>
+ biomarkerInfo(f.biomarker_type).category !== cat ||
+ f.biomarker_type === worst.biomarker_type,
+ );
+ return owns ? (capped.get(cat) ?? CATEGORY_CAP[cat] ?? null) : null;
+}
+
+function describeSection(
+ key: string,
+ group: HealthDrawerFinding[],
+ isFile: boolean,
+ allFindings: readonly HealthDrawerFinding[],
+ capped: Map<string, number | null>,
+): FindingSection {
+ // Inside a single-biomarker group every marker carries the same label and
+ // impact, so the line is the only axis a reader can follow.
+ const ordered =
+ isFile && key !== POOLED_FILE_KEY
+ ? [...group].sort((a, b) => (a.line_start ?? Infinity) - (b.line_start ?? Infinity))
+ : group;
+ const total = ordered.reduce((s, f) => s + f.health_impact, 0);
+ const worst = worstOf(ordered);
+ const atCap = isFile ? groupCap(key, worst, allFindings, capped) : null;
+ return { key, group: ordered, isFile, total, worst, atCap };
+}
+
+/**
+ * Group findings by the function they fire on, so one oversized function reads
+ * as a single collapsible group instead of N sibling rows.
+ *
+ * A file-level biomarker gets its own group only when it actually repeats:
+ * `error_handling` sets no function_name and fires once per occurrence, so one
+ * file in this repo reaches 34 sibling rows worth 0.51 points. Splitting every
+ * file-level biomarker out was measurably worse (53% of files carry 2+
+ * distinct one-off file-level markers), so the one-offs stay pooled.
+ */
+export function groupFindings(
+ findings: readonly HealthDrawerFinding[],
+ categories: readonly ScoreBreakdownCategory[],
+ /** Every finding on the file, for the cap's ownership test. */
+ allFindings: readonly HealthDrawerFinding[] = findings,
+): FindingSection[] {
+ const capped = cappedCategories(categories);
+ const { byFunction, byBiomarker } = bucketFindings(findings);
+ return [
+ ...[...byFunction.entries()].map(([key, group]) =>
+ describeSection(key, group, false, allFindings, capped),
+ ),
+ ...fileLevelGroups(byBiomarker).map(({ key, group }) =>
+ describeSection(key, group, true, allFindings, capped),
+ ),
+ ].sort((a, b) => b.total - a.total);
+}
+
+/** Where a finding fires, and the link to it when the host has one. */
+export function findingLocation(
+ f: HealthDrawerFinding,
+ fileViewHrefFor: ((lineStart: number) => string) | undefined,
+): { label: string; href: string | undefined } | null {
+ // Anchored on line_start, not function_name: `error_handling` fires per
+ // occurrence with a precise line and no function, and withholding the line
+ // made its rows read as duplicates.
+ if (!f.function_name && f.line_start == null) return null;
+ const label = f.function_name
+ ? `${f.function_name}${f.line_start != null ? `:${f.line_start}` : ""}`
+ : `line ${f.line_start}`;
+ // A link only when it goes to the line. Falling back to the file page made
+ // every row link to one page, which "Open full page" already is.
+ const href =
+ f.line_start != null && fileViewHrefFor ? fileViewHrefFor(f.line_start) : undefined;
+ return { label, href };
+}
+
+/** The drawer's per-file triage state: in-session status changes and the write in flight. */
+export function useTriage(
+ onFindingStatusChange: HealthFileDrawerProps["onFindingStatusChange"],
+) {
+ const [overrides, setOverrides] = useState<StatusOverrides>({});
+ const [savingId, setSavingId] = useState<string | null>(null);
+ const setStatus = useCallback(
+ async (id: string, status: string) => {
+ if (!onFindingStatusChange) return;
+ setSavingId(id);
+ try {
+ await onFindingStatusChange(id, status);
+ setOverrides((m) => ({ ...m, [id]: status }));
+ } finally {
+ setSavingId(null);
+ }
+ },
+ [onFindingStatusChange],
+ );
+ return {
+ overrides,
+ savingId,
+ setStatus: onFindingStatusChange ? setStatus : undefined,
+ };
+}
+
+export interface DrawerModel {
+ findings: HealthDrawerFinding[];
+ topIssues: TopIssue[];
+ /** Everything not leading, for "Other issues". */
+ rest: HealthDrawerFinding[];
+ sections: FindingSection[];
+ verdict: Verdict;
+ recovers: { points: number; places: number } | null;
+ heldBackTotal: number;
+ /** The one primary action is offered unless the verdict is the all-clear. */
+ showPrompt: boolean;
+ relatedExclude: readonly RelatedLensName[];
+ relatedTally: { items: number; lenses: number };
+}
+
+export function useDrawerModel(
+ props: HealthFileDrawerProps & { metric: HealthDrawerMetric },
+ overrides: StatusOverrides,
+): DrawerModel {
+ const { metric, breakdown, loading, error, heldBack, lens, performance, related } = props;
+ const findings = props.findings ?? NO_FINDINGS;
+ // A host that has not handed findings over, or is still fetching or failed,
+ // has not shown the file is clean, so the verdict claims nothing.
+ const findingsKnown = props.findings !== undefined && !loading && error == null;
+
+ const topIssues = useMemo(
+ () => pickTopIssues(findings, overrides, lens),
+ [findings, overrides, lens],
+ );
+ // A row already in What's wrong is not drawn twice. The cap check still
+ // reads every finding, because a category is owned by the findings on the
+ // file, not by the ones left below.
+ const rest = useMemo(() => {
+ const shown = new Set(topIssues.map((i) => i.lead.id));
+ return findings.filter((f) => !shown.has(f.id));
+ }, [findings, topIssues]);
+ const sections = useMemo(
+ () => groupFindings(rest, breakdown?.categories ?? [], findings),
+ [rest, findings, breakdown],
+ );
+
+ const verdict = useMemo(() => {
+ const open = findings.filter((f) => isOpen(f, overrides));
+ return fileVerdict({
+ score: metric.score,
+ // Every place each leading kind fires, so "two functions" counts them all.
+ top: topIssues.flatMap((i) => i.members),
+ hasTestFile: metric.has_test_file,
+ historyOnly: open.length > 0 && open.every((f) => isHistoryBiomarker(f.biomarker_type)),
+ findingsKnown,
+ rest: tallyRest(rest, overrides),
+ });
+ }, [metric.score, metric.has_test_file, findings, topIssues, rest, overrides, findingsKnown]);
+
+ const heldBackTotal = useMemo(
+ () => Object.values(heldBack ?? {}).reduce((n, g) => n + g.count, 0),
+ [heldBack],
+ );
+
+ const relatedExclude: readonly RelatedLensName[] =
+ lens === "performance" ? ["findings", "performance"] : ["findings"];
+ const performanceCauses = lens === "performance" && (performance?.items.length ?? 0) > 0;
+
+ return {
+ findings,
+ topIssues,
+ rest,
+ sections,
+ verdict,
+ recovers: topIssueRecovery(metric, breakdown, topIssues[0]?.members),
+ heldBackTotal,
+ showPrompt: !verdict.healthy || topIssues.length > 0 || performanceCauses,
+ relatedExclude,
+ relatedTally: relatedWorkCount(related, relatedExclude),
+ };
+}
diff --git a/packages/ui/src/health/file-drawer/performance-causes.tsx b/packages/ui/src/health/file-drawer/performance-causes.tsx
new file mode 100644
index 000000000..60d2f1807
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/performance-causes.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import type { PerformanceOpportunity } from "@repowise-dev/types/health";
+import { biomarkerLabel } from "../biomarker-glossary";
+import { ACTIONABILITY_LABEL } from "../performance/presentation";
+import { MICRO_LABEL } from "./shared";
+
+/**
+ * The file's open performance causes, when the reader arrived from that lens.
+ *
+ * Counts and causes, not a score: the performance pillar compresses into a
+ * narrow band and a number from it says nothing about this file.
+ *
+ * A cause is titled by the shape the detector recognized and identified by
+ * where it fires, because on one file that is what tells two of them apart:
+ * this repository has files carrying thirty-six causes of a single marker. The
+ * section says plainly when the host never asked for the data, because an
+ * empty list would read as a clear file.
+ */
+export function PerformanceCauses({
+ page,
+ loading,
+ onSelect,
+}: {
+ page: { items: PerformanceOpportunity[]; total: number } | null;
+ loading: boolean;
+ onSelect?: ((opportunityId: string) => void) | undefined;
+}) {
+ const items = page?.items ?? [];
+ const withPlan = items.filter((o) => o.plan_id).length;
+ return (
+ <section className="flex flex-col gap-2">
+ <h3 className={MICRO_LABEL}>Performance causes</h3>
+ {loading ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">Loading causes…</p>
+ ) : page === null ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ This view has no performance data wired up, so nothing is claimed about this
+ file either way.
+ </p>
+ ) : items.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ No open cause names this file as the place to intervene. The detectors are
+ high precision and low recall, so that is not a measurement that it is fast.
+ </p>
+ ) : (
+ <>
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ <span className="tabular-nums">{page.total.toLocaleString()}</span> open cause
+ {page.total === 1 ? "" : "s"} name this file as the place to intervene
+ {items.length < page.total ? (
+ <>
+ , <span className="tabular-nums">{items.length}</span> shown
+ </>
+ ) : null}
+ . <span className="tabular-nums">{withPlan}</span> of those carry a stored plan.
+ </p>
+ <ul className="flex flex-col divide-y divide-[var(--color-border-default)]">
+ {items.map((o) => (
+ <CauseRow key={o.opportunity_id} opportunity={o} onSelect={onSelect} />
+ ))}
+ </ul>
+ </>
+ )}
+ </section>
+ );
+}
+
+/** Where a cause fires, from the evidence the queue already carries. */
+function causeLocation(o: PerformanceOpportunity): string | null {
+ if (o.terminal_sink) return o.terminal_sink;
+ if (o.intervention_symbol) return o.intervention_symbol;
+ const first = o.evidence[0];
+ if (!first) return null;
+ const name = first.function_name ?? null;
+ if (name && first.line_start != null) return `${name}:${first.line_start}`;
+ if (name) return name;
+ return first.line_start != null ? `line ${first.line_start}` : null;
+}
+
+function CauseRow({
+ opportunity: o,
+ onSelect,
+}: {
+ opportunity: PerformanceOpportunity;
+ onSelect?: ((opportunityId: string) => void) | undefined;
+}) {
+ const location = causeLocation(o);
+ const body = (
+ <>
+ <span className="flex items-baseline gap-2">
+ <span className="min-w-0 flex-1 text-xs font-medium text-[var(--color-text-primary)]">
+ {biomarkerLabel(o.biomarker_type)}
+ </span>
+ <span className="shrink-0 font-mono text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {ACTIONABILITY_LABEL[o.actionability_state]}
+ </span>
+ </span>
+ {location ? (
+ <span className="truncate font-mono text-[10px] text-[var(--color-text-secondary)]">
+ {location}
+ </span>
+ ) : null}
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {o.observations_total} observation{o.observations_total === 1 ? "" : "s"} ·{" "}
+ {o.affected_files_total} file{o.affected_files_total === 1 ? "" : "s"} ·{" "}
+ {o.plan_id ? "stored plan" : o.plan_reason}
+ </span>
+ </>
+ );
+ return (
+ <li>
+ {onSelect ? (
+ <button
+ type="button"
+ onClick={() => onSelect(o.opportunity_id)}
+ className="flex w-full flex-col gap-0.5 px-1 py-2 text-left transition-colors hover:bg-[var(--color-bg-selected)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {body}
+ </button>
+ ) : (
+ <div className="flex flex-col gap-0.5 px-1 py-2">{body}</div>
+ )}
+ </li>
+ );
+}
diff --git a/packages/ui/src/health/file-drawer/sections.tsx b/packages/ui/src/health/file-drawer/sections.tsx
new file mode 100644
index 000000000..042cdfa1d
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/sections.tsx
@@ -0,0 +1,312 @@
+"use client";
+
+/**
+ * The file drawer's collapsed sections below the fold: Details (the metric
+ * grid), History & ownership, Dependencies, Elsewhere for this file, and Why
+ * this score. Each hint names what is inside without restating its numbers.
+ */
+
+import { CollapsibleSection } from "../../shared/collapsible-section";
+import { ApiError } from "../../shared/api-error";
+import { InfoTip } from "../../shared/info-tip";
+import { toFriendlyMessage } from "../../lib/errors";
+import { bandForScore, formatScore } from "@repowise-dev/types/health";
+import type { FileSignals } from "@repowise-dev/types/health";
+import { FileSignalsPanel, hasAnySignal } from "../file-signals-panel";
+import { RelatedWork, type RelatedLensName, type RelatedWorkSlotProps } from "../related-work";
+import { ScoreBreakdown, type ScoreBreakdownCategory } from "../score-breakdown";
+import { healthBandColor } from "../tokens";
+import type { HealthDrawerMetric, HealthFileDrawerProps } from "../health-file-drawer";
+import { MICRO_LABEL } from "./shared";
+
+export function DetailsSection({ metric }: { metric: HealthDrawerMetric }) {
+ if (metric.score == null && metric.nloc == null) return null;
+ return (
+ <CollapsibleSection title="Details" hint="size, complexity, tests, module">
+ <MetricGrid metric={metric} />
+ </CollapsibleSection>
+ );
+}
+
+/**
+ * Process and people signals plus where the bug fixes landed, as one section:
+ * the fix count and its recency live in the process row, so the per-symbol
+ * list under it does not repeat them.
+ *
+ * The per-symbol counts are labelled approximate, because symbol spans are
+ * current-tree while each fix's line ranges are numbered on its own parent
+ * commit. No commit is named: file-level SZZ ran at 74.5% precision, enough to
+ * count fixes and not enough to say which commit caused one.
+ */
+export function HistorySection({ signals }: { signals: FileSignals | null | undefined }) {
+ if (!signals) return null;
+ const counts = signals.fix_symbol_counts;
+ const hasFixes = Boolean(counts && Object.keys(counts).length > 0);
+ if (!hasFixes && !hasAnySignal(signals, ["process", "people"])) return null;
+ const entries = hasFixes ? Object.entries(counts!).sort((a, b) => b[1] - a[1]) : [];
+
+ return (
+ <CollapsibleSection title="History & ownership" hint={historyHint(signals)}>
+ <FileSignalsPanel signals={signals} groups={["process", "people"]} hideHeading />
+ {hasFixes ? (
+ <div className="flex flex-col gap-1.5 border-t border-[var(--color-border-default)] pt-2.5">
+ <p className={MICRO_LABEL}>Where the fixes landed</p>
+ <ul className="space-y-1">
+ {entries.map(([symbolId, count]) => (
+ <li
+ key={symbolId}
+ className="flex items-baseline gap-2 text-xs text-[var(--color-text-secondary)]"
+ >
+ <code className="font-mono text-[var(--color-text-primary)]">
+ {symbolId.split("::").pop()}
+ </code>
+ <span className="ml-auto tabular-nums text-[var(--color-text-tertiary)]">
+ {count} {count === 1 ? "fix" : "fixes"}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="text-[10px] leading-tight text-[var(--color-text-tertiary)]">
+ Approximate: fixes are matched to symbols by line range, and lines move.
+ </p>
+ </div>
+ ) : null}
+ </CollapsibleSection>
+ );
+}
+
+export function DependenciesSection({ signals }: { signals: FileSignals | null | undefined }) {
+ if (!signals || !hasAnySignal(signals, ["topology"])) return null;
+ return (
+ <CollapsibleSection title="Dependencies" hint={dependencyHint(signals)}>
+ <FileSignalsPanel signals={signals} groups={["topology"]} hideHeading />
+ </CollapsibleSection>
+ );
+}
+
+export function ElsewhereSection({
+ related,
+ relatedWorkHref,
+ relatedError,
+ onRelatedRetry,
+ onNavigate,
+ exclude,
+ tally,
+}: RelatedWorkSlotProps & {
+ exclude: readonly RelatedLensName[];
+ tally: { items: number; lenses: number };
+}) {
+ const failed = relatedError != null && tally.items === 0;
+ if (!failed && tally.items === 0) return null;
+ return (
+ <CollapsibleSection
+ title="Elsewhere for this file"
+ hint={
+ failed
+ ? "couldn't load"
+ : `in ${tally.lenses} other ${tally.lenses === 1 ? "view" : "views"}`
+ }
+ >
+ {failed ? (
+ <ApiError
+ size="compact"
+ title="Couldn't load the other views"
+ message={toFriendlyMessage(relatedError)}
+ {...(onRelatedRetry ? { onRetry: onRelatedRetry } : {})}
+ />
+ ) : (
+ <RelatedWork
+ related={related}
+ relatedWorkHref={relatedWorkHref}
+ onNavigate={onNavigate}
+ exclude={exclude}
+ hideHeading
+ />
+ )}
+ </CollapsibleSection>
+ );
+}
+
+/** The arithmetic behind the number at the top, categories only: the findings
+ * under each are already listed above. */
+export function WhyScoreSection({ breakdown }: { breakdown: HealthFileDrawerProps["breakdown"] }) {
+ if (!breakdown) return null;
+ return (
+ <CollapsibleSection title="Why this score" hint={breakdownHint(breakdown.categories)}>
+ <ScoreBreakdown
+ score={breakdown.score}
+ totalDeduction={breakdown.total_deduction}
+ categories={breakdown.categories}
+ showFindings={false}
+ />
+ </CollapsibleSection>
+ );
+}
+
+/**
+ * What the history section holds, in words. Its counts are the body's
+ * headline, so the hint names the kinds of evidence rather than restating them.
+ */
+function historyHint(s: FileSignals): string | undefined {
+ const parts: string[] = [];
+ if (s.prior_defect_count != null || s.commit_count_90d != null || s.age_days != null) {
+ parts.push("change history");
+ }
+ if (s.primary_owner_name != null || s.recent_owner_name != null) parts.push("owners");
+ if (s.fix_symbol_counts && Object.keys(s.fix_symbol_counts).length > 0) {
+ parts.push("where fixes landed");
+ }
+ return parts.length > 0 ? parts.join(" · ") : undefined;
+}
+
+/** One plain fact about the file's place in the graph; the body has the counts. */
+function dependencyHint(s: FileSignals): string {
+ if (s.in_degree == null) return "what it depends on";
+ if (s.in_degree === 0) return "nothing depends on it";
+ return s.out_degree === 0 ? "others depend on it, it depends on nothing" : "others depend on it";
+}
+
+/** The total is the body's arithmetic line, so the hint names the categories. */
+function breakdownHint(categories: ScoreBreakdownCategory[]): string {
+ const n = categories.length;
+ const held = categories.filter((c) => c.capped).length;
+ const base = `${n} ${n === 1 ? "category" : "categories"}`;
+ return held > 0 ? `${base}, ${held} at ${held === 1 ? "its" : "their"} limit` : base;
+}
+
+/** A structural counter that may genuinely be unmeasured: say so instead of
+ * rendering a misleading 0. */
+function MeasuredNum({ v }: { v: number | null }) {
+ if (v == null) {
+ return (
+ <span
+ className="text-xs text-[var(--color-text-tertiary)]"
+ title="Not measured: no metric row is available for this file on this snapshot."
+ >
+ not measured
+ </span>
+ );
+ }
+ return <span className="text-[15px] font-semibold tabular-nums">{v}</span>;
+}
+
+/**
+ * The two co-pillars and the structural counters, as one hairline `<dl>`, in
+ * the words a developer uses, with the term of art one hover away. Scores
+ * carry their band colour; counters are plain, because a nesting depth of 3 is
+ * not good or bad news on its own.
+ */
+function MetricGrid({ metric }: { metric: HealthDrawerMetric }) {
+ const cells: { label: string; tip?: string; value: React.ReactNode }[] = [
+ {
+ label: "Maintainability",
+ value: <PillarScore v={metric.maintainability_score ?? null} />,
+ },
+ { label: "Performance", value: <PillarScore v={metric.performance_score ?? null} /> },
+ {
+ // "Line coverage", not "Tests": the paired-file flag below is the tests
+ // cell, and two cells named alike in one grid is the vocabulary failure.
+ label: "Line coverage",
+ tip: "Share of the file's lines a coverage report saw run.",
+ value: (
+ <PlainValue>
+ {metric.line_coverage_pct == null
+ ? "not measured"
+ : `${metric.line_coverage_pct.toFixed(0)}%`}
+ </PlainValue>
+ ),
+ },
+ {
+ label: "Complexity",
+ tip: "Cyclomatic complexity (CCN) of the most complex function: the number of independent paths through it.",
+ value: <MeasuredNum v={metric.max_ccn} />,
+ },
+ {
+ label: "Nesting depth",
+ tip: "The deepest level of nested blocks in any function.",
+ value: <MeasuredNum v={metric.max_nesting} />,
+ },
+ {
+ label: "Lines of code",
+ tip: "Non-blank, non-comment lines (NLOC).",
+ value: <MeasuredNum v={metric.nloc} />,
+ },
+ {
+ label: "Duplication",
+ tip: "Share of lines that repeat a block found elsewhere.",
+ value: (
+ <PlainValue>
+ {metric.duplication_pct == null
+ ? "not measured"
+ : `${metric.duplication_pct.toFixed(0)}%`}
+ </PlainValue>
+ ),
+ },
+ {
+ label: "Test file",
+ value: <PlainValue>{metric.has_test_file ? "Paired" : "None"}</PlainValue>,
+ },
+ {
+ label: "Module",
+ value: (
+ <span
+ className="block truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={metric.module ?? undefined}
+ >
+ {metric.module ?? "none"}
+ </span>
+ ),
+ },
+ ];
+
+ return (
+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-3">
+ {cells.map((c, i) => (
+ <div
+ key={c.label}
+ className={[
+ "min-w-0 px-3 py-2.5",
+ "border-[var(--color-border-default)]",
+ // Hairlines between cells only; the outer edges come from border-y
+ // on the wrapper, so cells never double up on a boundary.
+ i % 2 === 1 ? "border-l" : "",
+ i >= 2 ? "border-t" : "",
+ "sm:border-l sm:border-t-0",
+ i % 3 === 0 ? "sm:border-l-0" : "",
+ i >= 3 ? "sm:border-t" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ <dt className={`inline-flex items-center gap-1 ${MICRO_LABEL}`}>
+ <span>{c.label}</span>
+ {c.tip ? <InfoTip content={c.tip} label={`About ${c.label.toLowerCase()}`} /> : null}
+ </dt>
+ <dd className="mt-1">{c.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+/** A 0-10 pillar score, band-coloured, or an honest "not measured". */
+function PillarScore({ v }: { v: number | null }) {
+ if (v == null) {
+ return <span className="text-xs text-[var(--color-text-tertiary)]">not measured</span>;
+ }
+ return (
+ <span
+ className="text-[18px] font-semibold tabular-nums"
+ style={{ color: healthBandColor(bandForScore(v)) }}
+ >
+ {formatScore(v)}
+ <span className="text-xs font-normal text-[var(--color-text-tertiary)]">/10</span>
+ </span>
+ );
+}
+
+function PlainValue({ children }: { children: React.ReactNode }) {
+ return (
+ <span className="text-[15px] tabular-nums text-[var(--color-text-primary)]">{children}</span>
+ );
+}
diff --git a/packages/ui/src/health/file-drawer/shared.ts b/packages/ui/src/health/file-drawer/shared.ts
new file mode 100644
index 000000000..d462fb4c3
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/shared.ts
@@ -0,0 +1,34 @@
+/**
+ * Constants the file drawer's sections share: the triage vocabulary, the
+ * size of the lead, and the two text treatments that keep the accent off
+ * everything but the primary action.
+ */
+
+/** Bucket for one-off file-level markers, kept pooled so a file with several
+ * distinct singletons still reads as one collapsed row. Not a biomarker name,
+ * and never compared against one. */
+export const POOLED_FILE_KEY = "__file_level__";
+
+/** Kinds of problem the "What's wrong" list leads with. The rest are one click away. */
+export const TOP_FINDINGS = 3;
+
+export const TRIAGE_STATUSES: { value: string; label: string }[] = [
+ { value: "open", label: "Open" },
+ { value: "acknowledged", label: "Acknowledged" },
+ { value: "resolved", label: "Resolved" },
+ { value: "false_positive", label: "False positive" },
+];
+
+export const STATUS_LABEL: Record<string, string> = Object.fromEntries(
+ TRIAGE_STATUSES.map((s) => [s.value, s.label]),
+);
+
+/** Closed statuses leave "What's wrong": the reader already decided on them. */
+export const CLOSED_STATUSES = new Set(["resolved", "false_positive"]);
+
+/** A link in ink, not accent: the accent belongs to the one primary action. */
+export const QUIET_LINK =
+ "inline-flex w-fit items-center gap-1.5 rounded-sm text-xs font-medium text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-text-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
+
+export const MICRO_LABEL =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
diff --git a/packages/ui/src/health/file-drawer/verdict.tsx b/packages/ui/src/health/file-drawer/verdict.tsx
new file mode 100644
index 000000000..26348f48e
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/verdict.tsx
@@ -0,0 +1,236 @@
+"use client";
+
+/**
+ * The verdict at the top of the file drawer: how bad the file is (score, band,
+ * trend), why in one sentence, what fixing the top issue gives back when that
+ * can be said honestly, and the one thing to do. Plus the prompt that one
+ * action opens.
+ */
+
+import { ExternalLink, Wrench } from "lucide-react";
+import { bandForScore, formatScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";
+import type { FileHealthTrend } from "@repowise-dev/types/health";
+import { AiPromptButton } from "../ai-prompt-button";
+import { AiPromptModal, fileChatContext } from "../ai-prompt-modal";
+import { buildFileHealthAiPrompt } from "../ai-prompt-builder";
+import { Sparkline } from "../sparkline";
+import { HEALTH_UNSUPPORTED_LABEL } from "../map/lens";
+import { deltaColor, formatDelta, healthBandColor } from "../tokens";
+import type { Verdict } from "../plain-language";
+import type {
+ HealthDrawerMetric,
+ HealthFileDrawerProps,
+} from "../health-file-drawer";
+import type { DrawerModel, StatusOverrides } from "./model";
+import { QUIET_LINK } from "./shared";
+
+export function VerdictSection({
+ metric,
+ trend,
+ model,
+ planTarget,
+ fullPage,
+ onNavigate,
+ onPrompt,
+}: {
+ metric: HealthDrawerMetric;
+ trend: FileHealthTrend | null | undefined;
+ model: DrawerModel;
+ planTarget: string | null;
+ fullPage: string | undefined;
+ onNavigate: ((href: string) => void) | undefined;
+ onPrompt: () => void;
+}) {
+ return (
+ <section aria-label="Verdict" className="flex flex-col gap-3">
+ <ScoreRow metric={metric} trend={trend} />
+ <VerdictSentence
+ verdict={model.verdict}
+ show={metric.score != null || model.findings.length > 0}
+ />
+ <RecoveryLine recovers={model.recovers} />
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 pt-1">
+ {/* The prompt is the one primary action, withheld only when the
+ verdict is the all-clear and there is nothing for it to fix. */}
+ {model.showPrompt ? (
+ <AiPromptButton onClick={onPrompt} label="Fix with AI prompt" />
+ ) : null}
+ <PlanLink href={planTarget} onNavigate={onNavigate} />
+ {fullPage ? (
+ <a href={fullPage} className={QUIET_LINK}>
+ <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
+ Open full page
+ </a>
+ ) : null}
+ </div>
+ </section>
+ );
+}
+
+function ScoreRow({
+ metric,
+ trend,
+}: {
+ metric: HealthDrawerMetric;
+ trend: FileHealthTrend | null | undefined;
+}) {
+ if (metric.score == null) {
+ // Nothing measured this file, so there is no number and no band.
+ return (
+ <p className="text-[15px] text-[var(--color-text-secondary)]">
+ Not analysed. {HEALTH_UNSUPPORTED_LABEL}.
+ </p>
+ );
+ }
+ return (
+ <div className="flex flex-wrap items-end gap-x-4 gap-y-2">
+ <ScoreLede score={metric.score} />
+ {/* A flat line says nothing a "no change" would not, so it is left out. */}
+ {trend && moves(trend) ? <TrendMark trend={trend} /> : null}
+ </div>
+ );
+}
+
+function moves(trend: FileHealthTrend): boolean {
+ const first = trend.points[0];
+ return trend.points.length >= 2 && trend.points.some((p) => p.score !== first!.score);
+}
+
+function VerdictSentence({ verdict, show }: { verdict: Verdict; show: boolean }) {
+ if (!verdict.text || !show) return null;
+ return (
+ <p className="max-w-[52ch] text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {verdict.text}
+ </p>
+ );
+}
+
+function RecoveryLine({ recovers }: { recovers: DrawerModel["recovers"] }) {
+ if (recovers == null) return null;
+ return (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Fixing the top issue{recovers.places > 1 ? ` in all ${recovers.places} places` : ""} is
+ worth about <span className="tabular-nums">{recovers.points.toFixed(1)}</span>{" "}
+ {recovers.points === 1 ? "point" : "points"}.
+ </p>
+ );
+}
+
+function PlanLink({
+ href,
+ onNavigate,
+}: {
+ href: string | null;
+ onNavigate: ((href: string) => void) | undefined;
+}) {
+ if (!href) return null;
+ return (
+ <a
+ href={href}
+ onClick={
+ onNavigate
+ ? (e) => {
+ e.preventDefault();
+ onNavigate(href);
+ }
+ : undefined
+ }
+ className={QUIET_LINK}
+ >
+ <Wrench className="h-3.5 w-3.5" aria-hidden="true" />
+ Refactoring plan
+ </a>
+ );
+}
+
+/** The score in ink and its band as a dot and a word: the dot is the health colour. */
+function ScoreLede({ score }: { score: number }) {
+ const color = healthBandColor(bandForScore(score));
+ return (
+ <>
+ <div className="flex items-baseline gap-x-2">
+ <span className="text-[52px] font-semibold leading-none tracking-tight tabular-nums text-[var(--color-text-primary)]">
+ {formatScore(score)}
+ </span>
+ <span className="text-xs text-[var(--color-text-tertiary)]">out of 10</span>
+ </div>
+ <span className="inline-flex items-center gap-1.5 pb-1 text-[15px] font-medium text-[var(--color-text-primary)]">
+ <span aria-hidden className="h-2 w-2 rounded-full" style={{ background: color }} />
+ {HEALTH_BAND_LABEL[bandForScore(score)]}
+ </span>
+ </>
+ );
+}
+
+/** Direction, in neutral ink: the delta's sign carries the health colour. */
+function TrendMark({ trend }: { trend: FileHealthTrend }) {
+ return (
+ <div className="flex items-center gap-2 pb-1 text-[var(--color-text-tertiary)]">
+ <Sparkline
+ values={trend.points.map((p) => p.score)}
+ domain={[0, 10]}
+ width={72}
+ height={20}
+ stroke="currentColor"
+ />
+ {trend.delta != null && trend.delta !== 0 ? (
+ <span className={`text-xs font-semibold tabular-nums ${deltaColor(trend.delta)}`}>
+ {formatDelta(trend.delta)}
+ </span>
+ ) : null}
+ {trend.declining ? (
+ <span className="text-xs text-[var(--color-text-secondary)]">declining</span>
+ ) : null}
+ </div>
+ );
+}
+
+/**
+ * Everything the drawer knows about this file, as one prompt. The modal
+ * renders through a portal, so it sits with the drawer for locality rather
+ * than for layout.
+ */
+export function FilePromptModal({
+ open,
+ onOpenChange,
+ props,
+ model,
+ overrides,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ props: HealthFileDrawerProps & { metric: HealthDrawerMetric };
+ model: DrawerModel;
+ overrides: StatusOverrides;
+}) {
+ const { metric, breakdown, signals, performance, trend, suggestions = {}, repoName } = props;
+ return (
+ <AiPromptModal
+ open={open}
+ onOpenChange={onOpenChange}
+ filePath={metric.file_path}
+ chatContext={fileChatContext(metric.file_path)}
+ title="AI prompt for this file"
+ description="Every scored finding, category ceiling, open performance cause and change signal this drawer holds, written up so an agent can triage the file before it edits anything."
+ getPrompt={(flavor) =>
+ buildFileHealthAiPrompt({
+ file: metric,
+ findings: model.findings.map((f) => ({
+ ...f,
+ // Triage applied in this session but not yet refetched, so a
+ // finding just marked resolved leaves the prompt.
+ status: overrides[f.id] ?? f.status,
+ details: f.details as Record<string, unknown> | null | undefined,
+ })),
+ categories: breakdown?.categories ?? [],
+ signals: signals ?? null,
+ performance: performance ?? null,
+ trendDelta: trend?.delta ?? null,
+ suggestions,
+ flavor,
+ ...(repoName ? { repoName } : {}),
+ })
+ }
+ />
+ );
+}
diff --git a/packages/ui/src/health/file-drawer/vital-signs.tsx b/packages/ui/src/health/file-drawer/vital-signs.tsx
new file mode 100644
index 000000000..493af8b34
--- /dev/null
+++ b/packages/ui/src/health/file-drawer/vital-signs.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+/**
+ * Four or five facts with a dot and a word, so healthy against unhealthy reads
+ * at a glance. Thresholds are the conventional ones (complexity 10 and 20, the
+ * usual McCabe bands); an unmeasured fact says so in a neutral mark rather
+ * than borrowing a band.
+ */
+
+import { useMemo } from "react";
+import type { FileSignals } from "@repowise-dev/types/health";
+import type { HealthDrawerMetric } from "../health-file-drawer";
+
+type Tone = "good" | "warn" | "bad" | "unknown";
+type Vital = { label: string; value: string; tone: Tone };
+
+const VITAL_DOT: Record<Tone, string> = {
+ good: "bg-[var(--color-success)]",
+ warn: "bg-[var(--color-caution)]",
+ bad: "bg-[var(--color-error)]",
+ unknown: "bg-[var(--color-text-tertiary)]",
+};
+
+type Sign = (m: HealthDrawerMetric, s: FileSignals | null | undefined) => Vital | null;
+
+/** Pick the tone for a value against two ascending limits. */
+function band(value: number, warnAbove: number, badAbove: number): Tone {
+ if (value > badAbove) return "bad";
+ return value > warnAbove ? "warn" : "good";
+}
+
+const complexity: Sign = (m) => {
+ if (m.max_ccn == null) return null;
+ const tone = band(m.max_ccn, 10, 20);
+ const value = tone === "bad" ? "high" : tone === "warn" ? "moderate" : "low";
+ return { label: "Complexity", value, tone };
+};
+
+const testFile: Sign = (m) => ({
+ label: "Test file",
+ value: m.has_test_file ? "found" : "not found",
+ tone: m.has_test_file ? "good" : "warn",
+});
+
+const coverage: Sign = (m) => {
+ const pct = m.line_coverage_pct;
+ if (pct == null) return { label: "Coverage", value: "not measured", tone: "unknown" };
+ const tone: Tone = pct >= 80 ? "good" : pct >= 50 ? "warn" : "bad";
+ return { label: "Coverage", value: `${pct.toFixed(0)}%`, tone };
+};
+
+const churn: Sign = (_m, s) => {
+ if (s?.commit_count_90d == null) return null;
+ const often = s.commit_count_90d >= 10;
+ return { label: "Changes often", value: often ? "yes" : "no", tone: often ? "warn" : "good" };
+};
+
+const bugFixes: Sign = (_m, s) => {
+ const n = s?.prior_defect_count;
+ if (n == null) return null;
+ if (n === 0) return { label: "Bug fixes", value: "none", tone: "good" };
+ return n >= 3
+ ? { label: "Bug fixes", value: "frequent", tone: "bad" }
+ : { label: "Bug fixes", value: "a few", tone: "warn" };
+};
+
+/** Code facts only where health measures the code; an unanalysed file keeps
+ * its history facts and drops the rest, rather than "Test file: not found"
+ * on a Makefile. */
+const CODE_SIGNS: Sign[] = [complexity, testFile, coverage];
+const HISTORY_SIGNS: Sign[] = [churn, bugFixes];
+
+function vitalSigns(m: HealthDrawerMetric, s: FileSignals | null | undefined): Vital[] {
+ const signs = m.score != null ? [...CODE_SIGNS, ...HISTORY_SIGNS] : HISTORY_SIGNS;
+ return signs.map((sign) => sign(m, s)).filter((v): v is Vital => v !== null);
+}
+
+export function VitalSigns({
+ metric,
+ signals,
+}: {
+ metric: HealthDrawerMetric;
+ signals: FileSignals | null | undefined;
+}) {
+ const vitals = useMemo(() => vitalSigns(metric, signals), [metric, signals]);
+ if (vitals.length === 0) return null;
+ return (
+ <ul
+ aria-label="Vital signs"
+ className="flex flex-wrap gap-x-5 gap-y-2 border-t border-[var(--color-border-default)] pt-3"
+ >
+ {vitals.map((v) => (
+ <li key={v.label} className="flex items-center gap-1.5 text-xs">
+ <span aria-hidden className={`h-1.5 w-1.5 shrink-0 rounded-full ${VITAL_DOT[v.tone]}`} />
+ <span className="text-[var(--color-text-tertiary)]">{v.label}</span>
+ <span className="font-medium text-[var(--color-text-primary)]">{v.value}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/packages/ui/src/health/file-signals-panel.tsx b/packages/ui/src/health/file-signals-panel.tsx
index bf0c7fa7d..611578a6e 100644
--- a/packages/ui/src/health/file-signals-panel.tsx
+++ b/packages/ui/src/health/file-signals-panel.tsx
@@ -7,8 +7,15 @@ export interface FileSignalsPanelProps {
signals: FileSignals | null | undefined;
/** Hide the section heading (e.g. when the host supplies its own). */
hideHeading?: boolean;
+ /** The groups to draw, for a host that files them under separate headings.
+ * Default all three. */
+ groups?: readonly SignalGroup[];
}
+export type SignalGroup = "process" | "people" | "topology";
+
+const ALL_GROUPS: readonly SignalGroup[] = ["process", "people", "topology"];
+
/**
* The per-file process / people / topology signals, grouped and captioned.
* Pure surfacing of data we already compute — no scoring, no recompute. Each
@@ -18,8 +25,12 @@ export interface FileSignalsPanelProps {
* history nor a graph node. Shared by the dashboard drawer and the file-page
* Health tab so both render identically.
*/
-export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPanelProps) {
- if (!signals || !hasAnySignal(signals)) return null;
+export function FileSignalsPanel({
+ signals,
+ hideHeading = false,
+ groups = ALL_GROUPS,
+}: FileSignalsPanelProps) {
+ if (!signals || !hasAnySignal(signals, groups)) return null;
const ownerHandoff =
signals.recent_owner_name != null &&
@@ -33,7 +44,12 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
Signals
</h3>
)}
- <div className="grid gap-3 sm:grid-cols-3">
+ <div
+ className={`grid gap-3 ${
+ groups.length >= 3 ? "sm:grid-cols-3" : groups.length === 2 ? "sm:grid-cols-2" : ""
+ }`}
+ >
+ {groups.includes("process") ? (
<Group label="Process">
<Row
value={priorDefectValue(signals.prior_defect_count)}
@@ -61,7 +77,9 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
present={signals.age_days != null}
/>
</Group>
+ ) : null}
+ {groups.includes("people") ? (
<Group label="People">
<Row
value={ownerValue(signals.primary_owner_name, signals.primary_owner_commit_pct)}
@@ -81,7 +99,9 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
emphasize={ownerHandoff}
/>
</Group>
+ ) : null}
+ {groups.includes("topology") ? (
<Group label="Topology">
<Row
value={
@@ -102,21 +122,25 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
present={signals.out_degree != null}
/>
</Group>
+ ) : null}
</div>
</section>
);
}
-function hasAnySignal(s: FileSignals): boolean {
+export function hasAnySignal(
+ s: FileSignals,
+ groups: readonly SignalGroup[] = ALL_GROUPS,
+): boolean {
return (
- s.prior_defect_count != null ||
- s.change_entropy_pct != null ||
- s.commit_count_90d != null ||
- s.age_days != null ||
- s.primary_owner_name != null ||
- s.recent_owner_name != null ||
- s.in_degree != null ||
- s.out_degree != null
+ (groups.includes("process") &&
+ (s.prior_defect_count != null ||
+ s.change_entropy_pct != null ||
+ s.commit_count_90d != null ||
+ s.age_days != null)) ||
+ (groups.includes("people") &&
+ (s.primary_owner_name != null || s.recent_owner_name != null)) ||
+ (groups.includes("topology") && (s.in_degree != null || s.out_degree != null))
);
}
@@ -207,7 +231,7 @@ function Row({
className={`flex items-center gap-1.5 text-xs font-semibold tabular-nums ${
present
? emphasize
- ? "text-[var(--color-accent-primary)]"
+ ? "text-[var(--color-text-primary)] underline decoration-dotted underline-offset-2"
: "text-[var(--color-text-primary)]"
: "text-[var(--color-text-tertiary)]"
}`}
diff --git a/packages/ui/src/health/fix-first/fix-first-list.tsx b/packages/ui/src/health/fix-first/fix-first-list.tsx
index 2970b2bfc..05952bc99 100644
--- a/packages/ui/src/health/fix-first/fix-first-list.tsx
+++ b/packages/ui/src/health/fix-first/fix-first-list.tsx
@@ -38,7 +38,8 @@ export interface FixFirstListProps {
LinkComponent?: ElementType | undefined;
/** Drop the section's top hairline when it opens the page. */
flush?: boolean | undefined;
- /** Open by default: the items are what the page asks the reader to do. */
+ /** Closed by default, under the score: the headline keeps the first screen
+ * and the toggle's count says how much is behind it. */
defaultOpen?: boolean | undefined;
}
@@ -55,7 +56,7 @@ export function FixFirstList({
loadPrompt,
LinkComponent,
flush = false,
- defaultOpen = true,
+ defaultOpen = false,
}: FixFirstListProps) {
// Every row starts as its one or two scan lines; the detail opens per row.
const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 776df83c1..228f401de 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -1,59 +1,52 @@
"use client";
+/**
+ * One file's health, beside the map or list it was opened from.
+ *
+ * Built so a developer who has never seen Repowise knows in five seconds how
+ * bad the file is, what is wrong in plain words, and what to do next: the
+ * verdict (score, band, trend, one sentence, one action), the top three issues,
+ * and a strip of vital signs. Everything else is one click away, collapsed,
+ * each disclosure with a hint that does not repeat its body.
+ *
+ * Colour is health state only. The accent sits on the one primary action;
+ * links are ink. It is non-modal, so the surface behind it stays live and
+ * picking another file swaps the content in place.
+ *
+ * This file is the shell and the public types; the sections live in
+ * `./file-drawer/`, and `useDrawerModel` derives everything they show.
+ */
+
import { useState } from "react";
-import { ChevronDown, ChevronRight, ExternalLink } from "lucide-react";
import { AdaptivePanel } from "../shared/adaptive-panel";
-import { InfoTip } from "../shared/info-tip";
-import {
- biomarkerLabel,
- biomarkerInfo,
- asBiomarkerDimension,
- CATEGORY_CAP,
- CATEGORY_LABEL,
- DIMENSION_CHIP,
- DIMENSION_LABEL,
- HISTORY_CHIP,
- HISTORY_EXPLAINER,
- HISTORY_LABEL,
- isHistoryBiomarker,
- type BiomarkerDimension,
-} from "./biomarker-glossary";
-import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
-import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";
-import { AiPromptButton } from "./ai-prompt-button";
-import { AiPromptModal, fileChatContext } from "./ai-prompt-modal";
-import { buildFileHealthAiPrompt } from "./ai-prompt-builder";
-import { FileSignalsPanel } from "./file-signals-panel";
-import { FindingOpportunityLink } from "./file-opportunity";
-import { RelatedWork, type RelatedWorkSlotProps } from "./related-work";
-import { CollapsibleSection } from "../shared/collapsible-section";
-import { formatRelativeTimeOrNull } from "../lib/format";
-import { Sparkline } from "./sparkline";
-import { ACTIONABILITY_LABEL } from "./performance/presentation";
-import { HEALTH_UNSUPPORTED_LABEL } from "./map/lens";
-import {
- SEVERITY_CHIP,
- SEVERITY_LABEL,
- deltaColor,
- formatDelta,
- healthBandColor,
- type Severity,
-} from "./tokens";
-// The shared bands, never a local threshold: this pill sits beside marks that
-// all derive from `bandForScore`, and two of them disagreeing about where a
-// band starts describes one file two ways in one viewport.
-import { bandForScore, formatScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";
+import { ApiError } from "../shared/api-error";
+import { Skeleton, SkeletonRegion } from "../ui/skeleton";
+import { toFriendlyMessage } from "../lib/errors";
+import { cn } from "../lib/cn";
+import type { BiomarkerDimension } from "./biomarker-glossary";
+import type { BiomarkerDetailsRecord } from "./biomarker-details";
+import type { ScoreBreakdownCategory } from "./score-breakdown";
+import type { RelatedWorkSlotProps } from "./related-work";
import type {
FileHealthTrend,
FileSignals,
+ GatedByLanguage,
PerformanceOpportunity,
} from "@repowise-dev/types/health";
import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
-import { SeverityMark } from "./severity-mark";
-import { VerificationTag } from "./verification-tag";
-import { LowerPriorityTag } from "./lower-priority-tag";
-import { PreviewBadge } from "./preview-badge";
-import { ImpactFigure } from "./impact-figure";
+import type { Severity } from "./tokens";
+import { useDrawerModel, useTriage } from "./file-drawer/model";
+import { FilePromptModal, VerdictSection } from "./file-drawer/verdict";
+import { FindingDetail, OtherIssues, WhatsWrong, type RowContext } from "./file-drawer/issues";
+import { VitalSigns } from "./file-drawer/vital-signs";
+import {
+ DependenciesSection,
+ DetailsSection,
+ ElsewhereSection,
+ HistorySection,
+ WhyScoreSection,
+} from "./file-drawer/sections";
+import { PerformanceCauses } from "./file-drawer/performance-causes";
export interface HealthDrawerFinding {
id: string;
@@ -80,7 +73,7 @@ export interface HealthDrawerMetric {
file_path: string;
/** `null` when health has no dialect for the file's language. */
score: number | null;
- /** Structural counters — null when the host has no metric row for the
+ /** Structural counters: null when the host has no metric row for the
* file, so the drawer can say "not measured" instead of a misleading 0. */
max_ccn: number | null;
max_nesting: number | null;
@@ -102,7 +95,17 @@ export interface HealthDrawerMetric {
export interface HealthFileDrawerProps extends RelatedWorkSlotProps {
open: boolean;
onClose: () => void;
+ /**
+ * The file the reader asked for. Optional: without it the header follows
+ * `metric`. With it the header names the new file at once while the body
+ * still shows the previous one, dimmed, until its data lands, which is
+ * what a host that keeps previous data on a key change wants.
+ */
+ filePath?: string | null | undefined;
loading?: boolean;
+ /** The breakdown request failed. Shown with a retry instead of "no metric". */
+ error?: unknown;
+ onRetry?: (() => void) | undefined;
metric?: HealthDrawerMetric | null;
breakdown?: {
score: number;
@@ -111,16 +114,19 @@ export interface HealthFileDrawerProps extends RelatedWorkSlotProps {
} | null;
findings?: HealthDrawerFinding[];
suggestions?: Record<string, string>;
+ /** What a language gate held back from `findings`, so the list can say so. */
+ heldBack?: GatedByLanguage | null | undefined;
/**
* The file's composed refactoring opportunity, when the host can supply one.
- * Findings whose cause it addresses get a link to it; the rest do not, so the
- * drawer never offers a plan for a problem the plan does not answer.
+ * It becomes the lede's primary action, and findings whose cause it
+ * addresses link to it; the rest do not, so the drawer never offers a plan
+ * for a problem the plan does not answer.
*/
opportunity?: RefactoringOpportunity | null | undefined;
refactoringOpportunityHref?: ((opportunityId: string) => string) | undefined;
/** Per-file score trajectory; renders a compact sparkline when populated. */
trend?: FileHealthTrend | null;
- /** Process / people / topology signals; the panel is silent when absent. */
+ /** Process / people / topology signals; their sections are silent when absent. */
signals?: FileSignals | null;
fileViewHref?: string;
/**
@@ -133,14 +139,14 @@ export interface HealthFileDrawerProps extends RelatedWorkSlotProps {
permalinkHref?: string;
onPartnerSelect?: ((path: string) => void) | undefined;
onPartnerHref?: ((path: string) => string) | undefined;
- /** Triage callback — PATCH the finding status. Buttons hide when absent. */
+ /** Triage callback: PATCH the finding status. The row menu hides when absent. */
onFindingStatusChange?:
| ((findingId: string, status: string) => Promise<void> | void)
| undefined;
/**
* The surface this file was opened from. In `performance` the drawer leads
- * with the file's causes rather than with its defect score, because that is
- * what the reader was looking at. Anything else renders as before.
+ * with the file's causes, because that is what the reader was looking at.
+ * Anything else renders the default.
*/
lens?: string;
/**
@@ -156,940 +162,205 @@ export interface HealthFileDrawerProps extends RelatedWorkSlotProps {
repoName?: string;
}
-/** Bucket for one-off file-level markers, kept pooled so a file with several
- * distinct singletons still reads as one collapsed row. Not a biomarker name,
- * and never compared against one. */
-const POOLED_FILE_KEY = "__file_level__";
-
-const TRIAGE_STATUSES: { value: string; label: string }[] = [
- { value: "open", label: "Open" },
- { value: "acknowledged", label: "Acknowledged" },
- { value: "resolved", label: "Resolved" },
- { value: "false_positive", label: "False positive" },
-];
-
-export function HealthFileDrawer({
- open,
- onClose,
- loading,
- metric,
- breakdown,
- findings = [],
- suggestions = {},
- opportunity,
- refactoringOpportunityHref,
- related,
- relatedWorkHref,
- onNavigate,
- trend,
- signals,
- fileViewHref,
- fileViewHrefFor,
- permalinkHref,
- onPartnerSelect,
- onPartnerHref,
- onFindingStatusChange,
- lens,
- performance,
- performanceLoading = false,
- onOpportunitySelect,
- repoName,
-}: HealthFileDrawerProps) {
- const [statusOverride, setStatusOverride] = useState<Record<string, string>>({});
- const [promptOpen, setPromptOpen] = useState(false);
- const [savingId, setSavingId] = useState<string | null>(null);
- const setStatus = async (id: string, status: string) => {
- if (!onFindingStatusChange) return;
- setSavingId(id);
- try {
- await onFindingStatusChange(id, status);
- setStatusOverride((m) => ({ ...m, [id]: status }));
- } finally {
- setSavingId(null);
- }
- };
-
- // A single finding row. Rendered inside a function group; kept as a closure
- // (not a component) so it reads the drawer's triage state without threading
- // it through props on every collapsible group.
- const renderFinding = (f: HealthDrawerFinding) => {
- const info = biomarkerInfo(f.biomarker_type);
- const isHistory = isHistoryBiomarker(f.biomarker_type);
- return (
- // A hairline row, not a card inside a card. These sat as bordered boxes
- // inside a bordered group inside the drawer: three frames deep for one
- // marker.
- <li
- key={f.id}
- className="space-y-1 border-t border-[var(--color-border-default)] px-3 py-2.5 first:border-t-0"
- >
- <div className="flex items-center gap-2 flex-wrap">
- <SeverityMark severity={f.severity} />
- <span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
- {biomarkerLabel(f.biomarker_type)}
- {info.description ? (
- <InfoTip
- content={info.description}
- label={`About ${biomarkerLabel(f.biomarker_type)}`}
- />
- ) : null}
- </span>
- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {CATEGORY_LABEL[info.category]}
- </span>
- <VerificationTag verification={f.verification} />
- <LowerPriorityTag reason={f.lower_priority} />
- <PreviewBadge note={f.preview} />
- {(() => {
- // A history marker wears a neutral "Watch" chip instead of its
- // pillar's: it is scored, but nothing in this file will clear it.
- if (isHistory) {
- return (
- <span
- className={`inline-flex items-center gap-1 rounded px-1.5 py-px text-[10px] font-medium ${HISTORY_CHIP}`}
- >
- {HISTORY_LABEL}
- <InfoTip content={HISTORY_EXPLAINER} label="Why this is a watch item" />
- </span>
- );
- }
- const dim = asBiomarkerDimension(f.dimension, f.biomarker_type);
- return (
- <span
- className={`inline-flex items-center rounded px-1.5 py-px text-[10px] font-medium ${DIMENSION_CHIP[dim]}`}
- title={`${DIMENSION_LABEL[dim]} pillar`}
- >
- {DIMENSION_LABEL[dim]}
- </span>
- );
- })()}
- {/* Anchor on line_start, not function_name. Gating the whole anchor on
- the function dropped the line for every file-level marker that has
- one — `error_handling` fires per occurrence with a precise line and
- no function, so 34 markers on one file rendered as 34 rows whose
- only distinguishing field was the one being withheld. That is what
- made them read as duplicates. */}
- {f.function_name || f.line_start != null ? (() => {
- const label = f.function_name
- ? `${f.function_name}${f.line_start != null ? `:${f.line_start}` : ""}`
- : `line ${f.line_start}`;
- const lineHref =
- f.line_start != null && fileViewHrefFor
- ? fileViewHrefFor(f.line_start)
- : f.line_start != null
- ? fileViewHref
- : undefined;
- return lineHref ? (
- <a
- href={lineHref}
- className="text-xs font-mono text-[var(--color-accent-primary)] hover:underline"
- >
- {label}
- </a>
- ) : (
- <span className="text-xs font-mono text-[var(--color-text-tertiary)]">
- {label}
- </span>
- );
- })() : null}
- <ImpactFigure impact={f.health_impact} className="ml-auto text-xs" />
- </div>
- <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
- <BiomarkerDetails
- biomarkerType={f.biomarker_type}
- details={f.details}
- onPartnerSelect={onPartnerSelect}
- onPartnerHref={onPartnerHref}
- />
- {suggestions[f.biomarker_type] ? (
- <p className="text-xs text-[var(--color-text-tertiary)] italic">
- {suggestions[f.biomarker_type]}
- </p>
- ) : null}
- <FindingOpportunityLink
- opportunity={opportunity}
- biomarkerType={f.biomarker_type}
- href={refactoringOpportunityHref}
- />
- {onFindingStatusChange ? (
- <div className="flex flex-wrap items-center gap-1.5 pt-1">
- {TRIAGE_STATUSES.map((opt) => {
- const current = statusOverride[f.id] ?? f.status ?? "open";
- return (
- <button
- key={opt.value}
- type="button"
- disabled={savingId === f.id || current === opt.value}
- onClick={() => setStatus(f.id, opt.value)}
- className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
- current === opt.value
- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
- : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]"
- }`}
- >
- {opt.label}
- </button>
- );
- })}
- </div>
- ) : null}
- </li>
- );
- };
-
- // Categories the scorer held at their ceiling, per the server breakdown.
- // `capped` is the server's verdict and is never recomputed here. The cap
- // VALUE is only ever displayed, so it falls back to the glossary mirror the
- // way `score-breakdown.tsx` does — older payloads carry `capped` without
- // `cap`, and losing the chip over a missing display number helps nobody.
- const cappedCategories = new Map<string, number | null>();
- for (const c of breakdown?.categories ?? []) {
- if (c.capped) cappedCategories.set(String(c.category), c.cap ?? null);
- }
-
- // Group findings by the function they fire on, so one oversized function
- // reads as a single collapsible group instead of N sibling rows.
- //
- // Markers with no function used to pool into one "File-level signals" list,
- // which defeated that fix for the biomarker that needs it most:
- // `error_handling` sets no function_name and fires once per occurrence, so a
- // single file in this repo reaches 34 sibling rows repeating one 12-word
- // reason — worth 0.51 points, because the category caps at 0.5.
- //
- // So a file-level biomarker gets its own group only when it actually repeats.
- // Splitting *every* file-level biomarker out was measurably worse: singleton
- // groups render expanded, and 53% of files carry 2+ distinct one-off
- // file-level markers (`dry_violation` alone fires exactly once on ~1,500
- // files), so it turned one collapsed row into several expanded ones. The
- // one-offs stay pooled; only the floods split.
- const findingSections = (() => {
- const byFunction = new Map<string, HealthDrawerFinding[]>();
- const byBiomarker = new Map<string, HealthDrawerFinding[]>();
- for (const f of findings) {
- // Two separate maps, never one keyed by a sentinel string: a C++ or Rust
- // function_name can legitimately be `file::read`, so any "file" prefix is
- // collidable and would silently strip that function's name from its
- // header.
- const map = f.function_name ? byFunction : byBiomarker;
- const key = f.function_name ?? f.biomarker_type;
- const bucket = map.get(key);
- if (bucket) bucket.push(f);
- else map.set(key, [f]);
- }
-
- const pooled: HealthDrawerFinding[] = [];
- const fileGroups: { key: string; group: HealthDrawerFinding[] }[] = [];
- for (const [key, group] of byBiomarker) {
- if (group.length > 1) fileGroups.push({ key, group });
- else pooled.push(...group);
- }
- if (pooled.length > 0) fileGroups.push({ key: POOLED_FILE_KEY, group: pooled });
-
- const sections = [
- ...[...byFunction.entries()].map(([key, group]) => ({ key, group, isFile: false })),
- ...fileGroups.map(({ key, group }) => ({ key, group, isFile: true })),
- ];
-
- return sections
- .map(({ key, group, isFile }) => {
- // Inside a single-biomarker group every marker carries the same label
- // and the same impact, so impact cannot order them and the line is the
- // only axis a reader can follow. Unlined markers sort last.
- if (isFile && key !== POOLED_FILE_KEY) {
- group.sort((a, b) => (a.line_start ?? Infinity) - (b.line_start ?? Infinity));
- }
- const total = group.reduce((s, f) => s + f.health_impact, 0);
- const worst = group.reduce((a, b) => (b.health_impact > a.health_impact ? b : a));
- // Claim the cap only when this group IS the category — otherwise the
- // ceiling belongs to markers outside the group and naming it here
- // misattributes it. Decided from the findings on screen rather than by
- // matching the server's subtotal, because a host may scope the two
- // differently (hosted excludes triaged findings from the breakdown but
- // not from this list) and a float comparison would then silently fail.
- const cat = biomarkerInfo(worst.biomarker_type).category;
- const ownsCategory =
- key !== POOLED_FILE_KEY &&
- findings.every(
- (f) =>
- biomarkerInfo(f.biomarker_type).category !== cat ||
- f.biomarker_type === worst.biomarker_type,
- );
- const atCap =
- isFile && ownsCategory && cappedCategories.has(cat)
- ? (cappedCategories.get(cat) ?? CATEGORY_CAP[cat] ?? null)
- : null;
- return { key, group, isFile, total, worst, atCap };
- })
- .sort((a, b) => b.total - a.total);
- })();
-
- // The one reason this file scores low, and it has to be one the reader can
- // act on. The server's lead is the highest-impact finding outright, which on
- // a churn-heavy file is a history marker — naming that as the leading cause
- // points someone at a commit log and calls it the thing to fix. So a history
- // lead is passed over for the strongest code-shape finding, and a file whose
- // whole deficit is history says that instead of naming a cause.
- const primaryLead = (() => {
- const codeShape = findings.filter((f) => !isHistoryBiomarker(f.biomarker_type));
- if (metric?.primary_biomarker && !isHistoryBiomarker(metric.primary_biomarker)) {
- return { biomarker: metric.primary_biomarker, reason: metric.primary_reason ?? null };
- }
- if (codeShape.length === 0) return null;
- const worst = codeShape.reduce((a, b) => (b.health_impact > a.health_impact ? b : a));
- return { biomarker: worst.biomarker_type, reason: worst.reason };
- })();
-
- // Only meaningful once the findings have loaded: an empty list before then is
- // "not known yet", not "nothing to fix".
- const historyOnly = primaryLead === null && findings.length > 0;
+/** A non-modal drawer stays open while the reader works the surface behind it. */
+const keepOpen = (event: Event) => event.preventDefault();
+
+/** Where the requested file stands against the data on hand. */
+function drawerView(props: HealthFileDrawerProps) {
+ const { filePath, metric, error } = props;
+ const shownPath = metric?.file_path ?? null;
+ const headerPath = filePath ?? shownPath;
+ // Previous data on screen under a new request: name the new file, dim the old.
+ const stale =
+ filePath != null && shownPath != null && filePath !== shownPath && error == null;
+ return { headerPath, stale };
+}
+export function HealthFileDrawer(props: HealthFileDrawerProps) {
+ const { open, onClose, loading, metric } = props;
+ const { headerPath, stale } = drawerView(props);
return (
<AdaptivePanel
open={open}
onOpenChange={(next) => {
if (!next) onClose();
}}
- eyebrow="File health"
- title={metric?.file_path ?? "Loading…"}
- widthClassName="md:max-w-[640px]"
+ // Non-modal: the map or list behind stays interactive, so clicking the
+ // next file swaps this content instead of fighting a focus trap.
+ // Escape and the close button still dismiss it.
+ modal={false}
+ onInteractOutside={keepOpen}
+ title={headerPath ? <FileTitle path={headerPath} /> : "Loading…"}
+ titleClassName="mt-0.5 flex min-w-0 flex-col gap-0.5"
+ widthClassName="md:max-w-[560px]"
>
- <div className="flex flex-col gap-6 px-4 py-4">
- {loading ? (
- <div className="text-sm text-[var(--color-text-tertiary)]">Loading…</div>
- ) : !metric ? (
- <p className="text-sm text-[var(--color-text-secondary)]">
- No metric for this file yet. It appears after the next index or sync.
- </p>
- ) : (
- <>
- {/* Lede: the score leads, and the leading cause is the sentence
- that makes it mean something. This used to be a small chip
- among ten identical bordered tiles, with the "why" in a
- separate box above them. */}
- <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:gap-6">
- <div className="flex shrink-0 flex-col gap-2 sm:w-[150px]">
- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Code health
- </p>
- {metric.score == null ? (
- // Nothing measured this file, so there is no number and no
- // band: the words the map's grey node carries instead.
- <p className="text-sm text-[var(--color-text-secondary)]">
- Not analysed. {HEALTH_UNSUPPORTED_LABEL}.
- </p>
- ) : (
- <ScoreLede score={metric.score} />
- )}
-
- {trend && trend.points.length >= 2 ? (
- <div className="mt-1 flex items-center gap-2">
- <Sparkline
- values={trend.points.map((p) => p.score)}
- domain={[0, 10]}
- width={92}
- height={24}
- stroke="var(--color-accent-primary)"
- />
- {trend.delta != null && trend.delta !== 0 ? (
- <span
- className={`text-xs font-semibold tabular-nums ${deltaColor(trend.delta)}`}
- >
- {formatDelta(trend.delta)}
- </span>
- ) : null}
- {trend.declining ? (
- <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-error)]">
- Declining
- </span>
- ) : null}
- </div>
- ) : null}
- </div>
-
- <div className="flex min-w-0 flex-col gap-3">
- {primaryLead ? (
- <div className="flex flex-col gap-1">
- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Leading cause
- </p>
- <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
- <strong className="font-semibold text-[var(--color-text-primary)]">
- {biomarkerLabel(primaryLead.biomarker)}.
- </strong>
- {primaryLead.reason ? ` ${primaryLead.reason}` : ""}
- </p>
- </div>
- ) : historyOnly ? (
- <div className="flex flex-col gap-1">
- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Leading cause
- </p>
- <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
- Nothing in this file&rsquo;s code is scored. Its deduction is all
- history, which no edit here will clear.
- </p>
- </div>
- ) : null}
-
- {/* Two actions, and only two: read the whole file's report,
- or hand what this drawer knows to an agent. The link was
- once duplicated, a tertiary line at the top and an
- accent-coloured one in the body, both to the same page. */}
- <div className="flex flex-wrap items-center gap-3">
- {(permalinkHref ?? fileViewHref) ? (
- <a
- href={permalinkHref ?? fileViewHref}
- className="inline-flex w-fit items-center gap-1.5 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
- >
- <ExternalLink className="h-3.5 w-3.5" />
- Open full page
- </a>
- ) : null}
- <AiPromptButton
- onClick={() => setPromptOpen(true)}
- label="AI prompt"
- />
- </div>
- </div>
- </div>
-
- {/* The other two pillars and the structural counters, as a
- hairline list. Ten bordered tiles made a 3.1 and a 14 read as
- the same kind of news. */}
- {lens === "performance" ? (
- <PerformanceCauses
- page={performance ?? null}
- loading={performanceLoading}
- onSelect={onOpportunitySelect}
- />
- ) : null}
-
- <MetricGrid metric={metric} />
-
- <FileSignalsPanel signals={signals} />
-
- <BugHistorySection signals={signals} />
-
- {/* Findings are this drawer's own list, and the performance lens
- already leads with the file's causes. */}
- <RelatedWork
- related={related}
- relatedWorkHref={relatedWorkHref}
- onNavigate={onNavigate}
- exclude={lens === "performance" ? ["findings", "performance"] : ["findings"]}
- />
-
- {/* Collapsed by default. This is the audit trail for a number
- the drawer already states at the top, beside a leading cause
- that names the biggest contributor in words. A reader who
- wants the per-category arithmetic can ask for it; one who
- does not should not scroll past it to reach the findings. */}
- {breakdown ? (
- <CollapsibleSection
- title="Why this score"
- hint={`−${breakdown.total_deduction.toFixed(2)} across ${
- breakdown.categories.length
- } ${breakdown.categories.length === 1 ? "category" : "categories"}`}
- >
- <ScoreBreakdown
- score={breakdown.score}
- totalDeduction={breakdown.total_deduction}
- categories={breakdown.categories}
- />
- </CollapsibleSection>
- ) : null}
-
- {findings.length > 0 ? (
- <section className="flex flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- All findings ({findings.length})
- </h3>
- <div className="flex flex-col">
- {findingSections.map((s) => (
- <FunctionFindingsGroup
- key={s.isFile ? `file:${s.key}` : `fn:${s.key}`}
- isFile={s.isFile}
- pooled={s.key === POOLED_FILE_KEY}
- functionName={s.isFile ? null : s.key}
- findings={s.group}
- total={s.total}
- worst={s.worst}
- atCap={s.atCap}
- // Single-marker groups have nothing to collapse; multi-
- // marker groups start collapsed so the drawer opens as
- // compact headers, since the leading-cause line above
- // already surfaces the top reason.
- defaultExpanded={s.group.length === 1}
- renderFinding={renderFinding}
- />
- ))}
- </div>
- </section>
- ) : null}
- </>
- )}
- </div>
-
- {/* Everything the drawer knows about this file, as one prompt. The
- modal renders through a portal, so it sits here for locality
- rather than for layout. */}
- <AiPromptModal
- open={promptOpen}
- onOpenChange={setPromptOpen}
- filePath={metric?.file_path ?? null}
- chatContext={fileChatContext(metric?.file_path)}
- title="AI prompt for this file"
- description="Every scored finding, category ceiling, open performance cause and change signal this drawer holds, written up so an agent can triage the file before it edits anything."
- getPrompt={
- metric
- ? (flavor) =>
- buildFileHealthAiPrompt({
- file: metric,
- findings: findings.map((f) => ({
- ...f,
- // Triage applied in this session but not yet refetched,
- // so a finding just marked resolved leaves the prompt.
- status: statusOverride[f.id] ?? f.status,
- details: f.details as Record<string, unknown> | null | undefined,
- })),
- categories: breakdown?.categories ?? [],
- signals: signals ?? null,
- performance: performance ?? null,
- trendDelta: trend?.delta ?? null,
- suggestions,
- flavor,
- ...(repoName ? { repoName } : {}),
- })
- : null
- }
- />
- </AdaptivePanel>
- );
-}
-
-/**
- * One collapsible group of findings that fire on the same function, or — for
- * markers with no function — on the same biomarker. The header names the
- * function plus its worst marker so a 7-marker oversized function reads as one
- * row, not seven — the P2 "looks padded" fix. A file-level group leads with the
- * biomarker instead, and carries a `capped` chip when the scorer is holding
- * that category at its ceiling. Single-finding groups render expanded.
- */
-/**
- * Which symbols this file's recent bug fixes landed in, behind a disclosure.
- *
- * Collapsed by default and silent without per-symbol data: the counts are a
- * "where do the bugs cluster" question, not something every reader of the
- * drawer needs answered. Two honesty rules show up in the copy. The heading
- * carries the last-fix age because a fix count without recency reads the same
- * at two weeks and two years. And the counts are labelled approximate, because
- * symbol spans are current-tree while each fix's line ranges are numbered on
- * its own parent commit, so a file that has moved since is matched on lines
- * that shifted.
- *
- * No commit is named here. File-level SZZ ran at 74.5% precision against the
- * frozen judgments, which is enough to count fixes and not enough to say which
- * commit caused one.
- */
-function BugHistorySection({ signals }: { signals: FileSignals | null | undefined }) {
- const counts = signals?.fix_symbol_counts;
- if (!counts || Object.keys(counts).length === 0) return null;
-
- const lastFix = formatRelativeTimeOrNull(signals?.last_fix_at ?? null, "");
- const entries = Object.entries(counts).sort((a, b) => b[1] - a[1]);
-
- return (
- <CollapsibleSection
- title="Bug history"
- hint={lastFix ? `last fix ${lastFix}` : "last fix unknown"}
- >
- <ul className="space-y-1">
- {entries.map(([symbolId, count]) => (
- <li
- key={symbolId}
- className="flex items-baseline gap-2 text-xs text-[var(--color-text-secondary)]"
- >
- <code className="font-mono text-[var(--color-text-primary)]">
- {symbolId.split("::").pop()}
- </code>
- <span className="ml-auto tabular-nums text-[var(--color-text-tertiary)]">
- {count} {count === 1 ? "fix" : "fixes"}
- </span>
- </li>
- ))}
- </ul>
- <p className="text-[10px] leading-tight text-[var(--color-text-tertiary)]">
- Approximate: fixes are matched to symbols by line range, and lines move.
- </p>
- </CollapsibleSection>
- );
-}
-
-function FunctionFindingsGroup({
- isFile,
- pooled,
- functionName,
- findings,
- total,
- worst,
- atCap,
- defaultExpanded,
- renderFinding,
-}: {
- isFile: boolean;
- /** The mixed bucket of one-off file-level markers, not a single biomarker. */
- pooled: boolean;
- functionName: string | null;
- findings: HealthDrawerFinding[];
- total: number;
- worst: HealthDrawerFinding;
- /** The enforced cap when this group's category is holding at it, else null. */
- atCap: number | null;
- defaultExpanded: boolean;
- renderFinding: (f: HealthDrawerFinding) => React.ReactNode;
-}) {
- const [expanded, setExpanded] = useState(defaultExpanded);
- const toggle = () => setExpanded((e) => !e);
- const worstLabel = biomarkerLabel(worst.biomarker_type);
- return (
- <div className="border-t border-[var(--color-border-default)]">
<div
- role="button"
- tabIndex={0}
- onClick={toggle}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- toggle();
- }
- }}
- aria-expanded={expanded}
- className="flex w-full cursor-pointer items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-[var(--color-bg-surface)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
- >
- {expanded ? (
- <ChevronDown className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />
- ) : (
- <ChevronRight className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />
- )}
- {isFile ? (
- <span className="min-w-0 truncate text-sm font-medium text-[var(--color-text-primary)]">
- {pooled ? (
- "File-level signals"
- ) : (
- <>
- {worstLabel}
- <span className="text-[var(--color-text-tertiary)]"> · file-level</span>
- </>
- )}
- </span>
- ) : (
- <span className="min-w-0 truncate text-sm font-medium text-[var(--color-text-primary)]">
- <span className="font-mono">{functionName}</span>
- <span className="text-[var(--color-text-tertiary)]"> · {worstLabel}</span>
- </span>
+ className={cn(
+ "flex flex-col gap-6 px-4 py-4 transition-opacity motion-reduce:transition-none",
+ stale && "pointer-events-none opacity-60",
)}
- <span className="ml-auto inline-flex shrink-0 items-center gap-2 text-xs tabular-nums">
- <span className="text-[var(--color-text-tertiary)]">
- {findings.length} {findings.length === 1 ? "marker" : "markers"}
- </span>
- <ImpactFigure impact={total} />
- {/* Why 34 markers cost half a point. Without this the count reads as
- the severity and the capped total looks like a bug. The
- explanation rides in the accessible name, not a `title`: a bare
- `title` on a span with its own text never reaches the accessible
- name, so it would be mouse-only. */}
- {atCap !== null ? (
- <span
- className="rounded-sm bg-[var(--color-bg-surface)] px-1 py-px text-[10px] font-normal text-[var(--color-text-tertiary)]"
- aria-label={`capped: held at its ${atCap.toFixed(2)}-point ceiling, so further markers of this kind add no deduction`}
- >
- capped
- </span>
- ) : null}
- </span>
+ 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>
- {expanded ? (
- <ul className="border-t border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
- {findings.map((f) => renderFinding(f))}
- </ul>
- ) : null}
- </div>
+ </AdaptivePanel>
);
}
-/** A structural counter that may genuinely be unmeasured — say so instead of
- * rendering a misleading 0. */
-function MeasuredNum({ v }: { v: number | null }) {
- if (v == null) {
+/** Error, loading, nothing yet, or the file. */
+function DrawerContent({
+ props,
+ headerPath,
+}: {
+ props: HealthFileDrawerProps;
+ headerPath: string | null;
+}) {
+ const { error, onRetry, loading, metric } = props;
+ if (error != null && (!metric || metric.file_path !== headerPath)) {
return (
- <span
- className="text-xs text-[var(--color-text-tertiary)]"
- title="Not measured — no metric row is available for this file on this snapshot."
- >
- not measured
- </span>
+ <ApiError
+ size="compact"
+ title="Couldn't load this file"
+ message={toFriendlyMessage(error)}
+ {...(onRetry ? { onRetry } : {})}
+ />
);
}
- return <span className="text-base font-semibold tabular-nums">{v}</span>;
+ if (!metric) {
+ return loading ? (
+ <DrawerSkeleton />
+ ) : (
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ No metric for this file yet. It appears after the next index or sync.
+ </p>
+ );
+ }
+ // Keyed by file, so triage overrides, an open prompt and every disclosure
+ // start fresh on the next file rather than carrying over.
+ return <DrawerBody key={metric.file_path} {...props} metric={metric} />;
}
-/**
- * The two co-pillars and the structural counters, as one hairline `<dl>`.
- *
- * Was ten bordered tiles in a 4-column grid that wrapped to 4/4/2 and gave a
- * pillar score, a cyclomatic count and a module name identical weight. Scores
- * carry their band colour; counters are plain, because a nesting depth of 3 is
- * not good or bad news on its own.
- */
-/** The score and its band, for a file that has one. */
-function ScoreLede({ score }: { score: number }) {
+/** The file name leads; the directory is the small machine fact under it. */
+function FileTitle({ path }: { path: string }) {
+ const cut = path.lastIndexOf("/");
+ const name = cut >= 0 ? path.slice(cut + 1) : path;
+ const dir = cut >= 0 ? path.slice(0, cut + 1) : "";
return (
<>
- <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
- <span
- className="text-[40px] font-semibold leading-none tracking-tight tabular-nums"
- style={{ color: healthBandColor(bandForScore(score)) }}
- >
- {formatScore(score)}
- </span>
- <span className="text-xs text-[var(--color-text-tertiary)]">out of 10</span>
- </div>
- <span
- className="w-fit rounded-full border px-2.5 py-0.5 text-[11px] font-medium"
- style={{
- color: healthBandColor(bandForScore(score)),
- borderColor: `color-mix(in srgb, ${healthBandColor(bandForScore(score))} 40%, transparent)`,
- background: `color-mix(in srgb, ${healthBandColor(bandForScore(score))} 9%, transparent)`,
- }}
- >
- {HEALTH_BAND_LABEL[bandForScore(score)]}
+ <span className="block break-words text-[18px] font-semibold leading-snug text-[var(--color-text-primary)]">
+ {name}
</span>
+ {dir ? (
+ <span className="block break-all font-mono text-xs leading-snug text-[var(--color-text-tertiary)]">
+ {dir}
+ </span>
+ ) : null}
</>
);
}
-function MetricGrid({ metric }: { metric: HealthDrawerMetric }) {
- const cells: { label: string; value: React.ReactNode }[] = [
- {
- label: "Maintainability",
- value: <PillarScore v={metric.maintainability_score ?? null} />,
- },
- { label: "Performance", value: <PillarScore v={metric.performance_score ?? null} /> },
- {
- // Stays "Coverage" while the tab is renamed to "Tests": this cell is the
- // measured percentage, and a "Tests" cell already sits four rows down
- // carrying the paired-file flag. Two cells named the same thing in one
- // grid is the vocabulary failure the rename exists to avoid.
- label: "Coverage",
- value: (
- <PlainValue>
- {metric.line_coverage_pct == null
- ? "not measured"
- : `${metric.line_coverage_pct.toFixed(0)}%`}
- </PlainValue>
- ),
- },
- { label: "Max CCN", value: <MeasuredNum v={metric.max_ccn} /> },
- { label: "Nesting", value: <MeasuredNum v={metric.max_nesting} /> },
- { label: "NLOC", value: <MeasuredNum v={metric.nloc} /> },
- {
- label: "Duplication",
- value: (
- <PlainValue>
- {metric.duplication_pct == null
- ? "not measured"
- : `${metric.duplication_pct.toFixed(0)}%`}
- </PlainValue>
- ),
- },
- {
- label: "Tests",
- value: <PlainValue>{metric.has_test_file ? "Paired" : "None"}</PlainValue>,
- },
- {
- label: "Module",
- value: (
- <span
- className="block truncate font-mono text-sm text-[var(--color-text-primary)]"
- title={metric.module ?? undefined}
- >
- {metric.module ?? "none"}
- </span>
- ),
- },
- ];
-
+/** Same shapes as the lede and the first rows, so the content lands without a jump. */
+function DrawerSkeleton() {
return (
- <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-3">
- {cells.map((c, i) => (
- <div
- key={c.label}
- className={[
- "min-w-0 px-3 py-2.5",
- "border-[var(--color-border-default)]",
- // Hairlines between cells only; the outer edges come from border-y
- // on the wrapper, so cells never double up on a boundary.
- i % 2 === 1 ? "border-l" : "",
- i >= 2 ? "border-t" : "",
- "sm:border-l sm:border-t-0",
- i % 3 === 0 ? "sm:border-l-0" : "",
- i >= 3 ? "sm:border-t" : "",
- ]
- .filter(Boolean)
- .join(" ")}
- >
- <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- {c.label}
- </dt>
- <dd className="mt-1">{c.value}</dd>
+ <SkeletonRegion className="flex flex-col gap-6" label="Loading file health">
+ <div className="flex flex-col gap-4 sm:flex-row sm:gap-6">
+ <Skeleton className="h-[72px] w-[150px]" />
+ <div className="flex flex-1 flex-col gap-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="mt-2 h-7 w-40" />
</div>
- ))}
- </dl>
- );
-}
-
-/** A 0–10 pillar score, band-coloured, or an honest "not measured". */
-function PillarScore({ v }: { v: number | null }) {
- if (v == null) {
- return <span className="text-sm text-[var(--color-text-tertiary)]">not measured</span>;
- }
- return (
- <span
- className="text-lg font-semibold tabular-nums"
- style={{ color: healthBandColor(bandForScore(v)) }}
- >
- {formatScore(v)}
- <span className="text-xs font-normal text-[var(--color-text-tertiary)]">/10</span>
- </span>
+ </div>
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ </SkeletonRegion>
);
}
-function PlainValue({ children }: { children: React.ReactNode }) {
- return (
- <span className="text-sm tabular-nums text-[var(--color-text-primary)]">{children}</span>
- );
-}
+function DrawerBody(props: HealthFileDrawerProps & { metric: HealthDrawerMetric }) {
+ const { metric, signals, lens } = props;
+ const [promptOpen, setPromptOpen] = useState(false);
+ const triage = useTriage(props.onFindingStatusChange);
+ const model = useDrawerModel(props, triage.overrides);
+
+ const suggestions = props.suggestions ?? {};
+ const ctx: RowContext = {
+ fileViewHrefFor: props.fileViewHrefFor,
+ savingId: triage.savingId,
+ onStatusChange: triage.setStatus,
+ overrides: triage.overrides,
+ detail: (f) => (
+ <FindingDetail
+ finding={f}
+ suggestion={suggestions[f.biomarker_type]}
+ onPartnerSelect={props.onPartnerSelect}
+ onPartnerHref={props.onPartnerHref}
+ />
+ ),
+ };
+ const { opportunity, refactoringOpportunityHref } = props;
+ const planTarget =
+ opportunity && refactoringOpportunityHref
+ ? refactoringOpportunityHref(opportunity.opportunity_id) || null
+ : null;
-/**
- * The file's open performance causes, when the reader arrived from that lens.
- *
- * Counts and causes, not a score: the performance pillar compresses into a
- * narrow band and a number from it says nothing about this file.
- *
- * A cause is titled by the shape the detector recognized and identified by
- * where it fires, because on one file that is what tells two of them apart:
- * this repository has files carrying thirty-six causes of a single marker, and
- * titling them by the marker alone produces thirty-six identical rows. The
- * whole section says plainly when the host never asked for the data, because
- * an empty list would read as a clear file.
- */
-function PerformanceCauses({
- page,
- loading,
- onSelect,
-}: {
- page: { items: PerformanceOpportunity[]; total: number } | null;
- loading: boolean;
- onSelect?: ((opportunityId: string) => void) | undefined;
-}) {
- const items = page?.items ?? [];
- const withPlan = items.filter((o) => o.plan_id).length;
return (
- <section className="flex flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Performance causes
- </h3>
- {loading ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">Loading causes…</p>
- ) : page === null ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- This view has no performance data wired up, so nothing is claimed about this
- file either way.
- </p>
- ) : items.length === 0 ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- No open cause names this file as the place to intervene. The detectors are
- high precision and low recall, so that is not a measurement that it is fast.
- </p>
- ) : (
- <>
- <p className="text-xs text-[var(--color-text-secondary)]">
- <span className="tabular-nums">{page.total.toLocaleString()}</span> open cause
- {page.total === 1 ? "" : "s"} name this file as the place to intervene
- {items.length < page.total ? (
- <>
- , <span className="tabular-nums">{items.length}</span> shown
- </>
- ) : null}
- . <span className="tabular-nums">{withPlan}</span> of those carry a stored plan.
- </p>
- <ul className="flex flex-col divide-y divide-[var(--color-border-default)]">
- {items.map((o) => (
- <CauseRow key={o.opportunity_id} opportunity={o} onSelect={onSelect} />
- ))}
- </ul>
- </>
- )}
- </section>
- );
-}
-
-/** Where a cause fires, from the evidence the queue already carries. */
-function causeLocation(o: PerformanceOpportunity): string | null {
- if (o.terminal_sink) return o.terminal_sink;
- if (o.intervention_symbol) return o.intervention_symbol;
- const first = o.evidence[0];
- if (!first) return null;
- const name = first.function_name ?? null;
- if (name && first.line_start != null) return `${name}:${first.line_start}`;
- if (name) return name;
- return first.line_start != null ? `line ${first.line_start}` : null;
-}
-
-function CauseRow({
- opportunity: o,
- onSelect,
-}: {
- opportunity: PerformanceOpportunity;
- onSelect?: ((opportunityId: string) => void) | undefined;
-}) {
- const location = causeLocation(o);
- const body = (
<>
- <span className="flex items-baseline gap-2">
- <span className="min-w-0 flex-1 text-xs font-medium text-[var(--color-text-primary)]">
- {biomarkerLabel(o.biomarker_type)}
- </span>
- <span className="shrink-0 font-mono text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
- {ACTIONABILITY_LABEL[o.actionability_state]}
- </span>
- </span>
- {location ? (
- <span className="truncate font-mono text-[10px] text-[var(--color-text-secondary)]">
- {location}
- </span>
+ <VerdictSection
+ metric={metric}
+ trend={props.trend}
+ model={model}
+ planTarget={planTarget}
+ fullPage={props.permalinkHref ?? props.fileViewHref}
+ onNavigate={props.onNavigate}
+ onPrompt={() => setPromptOpen(true)}
+ />
+ {lens === "performance" ? (
+ <PerformanceCauses
+ page={props.performance ?? null}
+ loading={props.performanceLoading ?? false}
+ onSelect={props.onOpportunitySelect}
+ />
) : null}
- <span className="text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
- {o.observations_total} observation{o.observations_total === 1 ? "" : "s"} ·{" "}
- {o.affected_files_total} file{o.affected_files_total === 1 ? "" : "s"} ·{" "}
- {o.plan_id ? "stored plan" : o.plan_reason}
- </span>
+ <WhatsWrong issues={model.topIssues} ctx={ctx} />
+ <VitalSigns metric={metric} signals={signals} />
+ <div className="flex flex-col">
+ <OtherIssues
+ rest={model.rest}
+ sections={model.sections}
+ leading={model.topIssues.length}
+ heldBack={props.heldBack}
+ heldBackTotal={model.heldBackTotal}
+ ctx={ctx}
+ />
+ <DetailsSection metric={metric} />
+ <HistorySection signals={signals} />
+ <DependenciesSection signals={signals} />
+ <ElsewhereSection
+ related={props.related}
+ relatedWorkHref={props.relatedWorkHref}
+ relatedError={props.relatedError}
+ onRelatedRetry={props.onRelatedRetry}
+ onNavigate={props.onNavigate}
+ exclude={model.relatedExclude}
+ tally={model.relatedTally}
+ />
+ <WhyScoreSection breakdown={props.breakdown} />
+ </div>
+ <FilePromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ props={props}
+ model={model}
+ overrides={triage.overrides}
+ />
</>
);
- return (
- <li>
- {onSelect ? (
- <button
- type="button"
- onClick={() => onSelect(o.opportunity_id)}
- className="flex w-full flex-col gap-0.5 px-1 py-2 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)]"
- >
- {body}
- </button>
- ) : (
- <div className="flex flex-col gap-0.5 px-1 py-2">{body}</div>
- )}
- </li>
- );
}
-
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 0b1498a0a..902fb007d 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -17,7 +17,6 @@ export * from "./sparkline";
export * from "./health-tabs";
export * from "./page-chrome";
export * from "./trend-chart";
-export * from "./trend-slope-chart";
export * from "./file-trend-chart";
export * from "./file-signals-panel";
export * from "./risk-coverage-scatter";
diff --git a/packages/ui/src/health/map/controls.tsx b/packages/ui/src/health/map/controls.tsx
new file mode 100644
index 000000000..b490cc942
--- /dev/null
+++ b/packages/ui/src/health/map/controls.tsx
@@ -0,0 +1,109 @@
+"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.
+ */
+
+import { MapLegendRows, MapLensSwitcher } from "./legend";
+import type { OverlaySpec } from "./lens";
+import type { CodeHealthOverlay } from "./types";
+
+const GLASS =
+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] shadow-sm backdrop-blur-sm";
+
+export function ZoomControls({
+ onZoomIn,
+ onZoomOut,
+ onFit,
+}: {
+ onZoomIn: () => void;
+ onZoomOut: () => void;
+ onFit: () => void;
+}) {
+ const buttons = [
+ { label: "Zoom in", text: "+", act: onZoomIn },
+ { label: "Zoom out", text: "−", act: onZoomOut },
+ { label: "Fit the whole field", text: "Fit", act: onFit },
+ ];
+ return (
+ <div role="group" aria-label="Zoom" className={`flex overflow-hidden text-xs ${GLASS}`}>
+ {buttons.map((b, i) => (
+ <button
+ key={b.label}
+ type="button"
+ aria-label={b.label}
+ title={b.label}
+ onClick={b.act}
+ className={`min-w-[28px] px-2 py-1 font-mono tabular-nums text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent-primary)] ${
+ i > 0 ? "border-l border-[var(--color-border-default)]" : ""
+ }`}
+ >
+ {b.text}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+/** 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,
+ spec,
+ lenses,
+ loading,
+ onOverlayChange,
+}: {
+ overlay: CodeHealthOverlay;
+ spec: OverlaySpec;
+ lenses: CodeHealthOverlay[];
+ loading: boolean;
+ onOverlayChange?: ((overlay: CodeHealthOverlay) => void) | undefined;
+}) {
+ return (
+ <>
+ {onOverlayChange ? (
+ <div className={`absolute left-3 top-3 p-1 ${GLASS}`}>
+ <MapLensSwitcher
+ overlay={overlay}
+ onOverlayChange={onOverlayChange}
+ lenses={lenses}
+ className="border-0"
+ />
+ </div>
+ ) : null}
+ <div
+ className={`absolute left-3 max-w-[220px] px-3 py-2 text-xs ${GLASS} ${
+ onOverlayChange ? "top-14" : "top-3"
+ }`}
+ >
+ <div className="mb-1.5 font-medium text-[var(--color-text-secondary)]">{spec.label}</div>
+ <MapLegendRows spec={spec} loading={loading} />
+ <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
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/packages/ui/src/health/map/hit-test.ts b/packages/ui/src/health/map/hit-test.ts
new file mode 100644
index 000000000..6b036d321
--- /dev/null
+++ b/packages/ui/src/health/map/hit-test.ts
@@ -0,0 +1,116 @@
+/**
+ * Which node is under a point, without walking every node.
+ *
+ * A uniform grid over the field, built once per layout: each node is listed
+ * in every cell its disc touches, so a query reads the few cells around the
+ * pointer instead of eight thousand discs. Cells are flat typed arrays (a
+ * compressed row list), which keeps the build one counting pass and one fill
+ * pass with no per-cell allocation.
+ */
+
+export interface HitNode {
+ x: number;
+ y: number;
+ r: number;
+}
+
+export interface HitGrid {
+ x0: number;
+ y0: number;
+ cell: number;
+ cols: number;
+ rows: number;
+ /** `start[c]..start[c + 1]` indexes `items` for cell `c`. */
+ start: Int32Array;
+ items: Int32Array;
+ xs: Float64Array;
+ ys: Float64Array;
+ rs: Float64Array;
+}
+
+/** Cells along the longer side, at most. Bounds memory on a sparse field. */
+const MAX_CELLS_PER_SIDE = 256;
+
+export function buildHitGrid(nodes: readonly HitNode[]): HitGrid {
+ const n = nodes.length;
+ const xs = new Float64Array(n);
+ const ys = new Float64Array(n);
+ const rs = new Float64Array(n);
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ let maxR = 0;
+ for (let i = 0; i < n; i++) {
+ const nd = nodes[i]!;
+ xs[i] = nd.x;
+ ys[i] = nd.y;
+ rs[i] = nd.r;
+ minX = Math.min(minX, nd.x - nd.r);
+ minY = Math.min(minY, nd.y - nd.r);
+ maxX = Math.max(maxX, nd.x + nd.r);
+ maxY = Math.max(maxY, nd.y + nd.r);
+ maxR = Math.max(maxR, nd.r);
+ }
+ if (n === 0) {
+ return { x0: 0, y0: 0, cell: 1, cols: 0, rows: 0, start: new Int32Array(1), items: new Int32Array(0), xs, ys, rs };
+ }
+ const w = Math.max(maxX - minX, 1e-9);
+ const h = Math.max(maxY - minY, 1e-9);
+ // About one node per cell on a dense field, never finer than a big node.
+ const cell = Math.max(Math.sqrt((w * h) / n), maxR, Math.max(w, h) / MAX_CELLS_PER_SIDE);
+ const cols = Math.max(1, Math.ceil(w / cell));
+ const rows = Math.max(1, Math.ceil(h / cell));
+ const counts = new Int32Array(cols * rows + 1);
+ const span = (i: number) => {
+ const c0 = Math.max(0, Math.floor((xs[i]! - rs[i]! - minX) / cell));
+ const c1 = Math.min(cols - 1, Math.floor((xs[i]! + rs[i]! - minX) / cell));
+ const r0 = Math.max(0, Math.floor((ys[i]! - rs[i]! - minY) / cell));
+ const r1 = Math.min(rows - 1, Math.floor((ys[i]! + rs[i]! - minY) / cell));
+ return [c0, c1, r0, r1] as const;
+ };
+ for (let i = 0; i < n; i++) {
+ const [c0, c1, r0, r1] = span(i);
+ for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) counts[r * cols + c + 1]!++;
+ }
+ const start = new Int32Array(cols * rows + 1);
+ for (let c = 0; c < cols * rows; c++) start[c + 1] = start[c]! + counts[c + 1]!;
+ const fill = start.slice(0, cols * rows);
+ const items = new Int32Array(start[cols * rows]!);
+ for (let i = 0; i < n; i++) {
+ const [c0, c1, r0, r1] = span(i);
+ for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) items[fill[r * cols + c]!++] = i;
+ }
+ return { x0: minX, y0: minY, cell, cols, rows, start, items, xs, ys, rs };
+}
+
+/**
+ * The node under `(x, y)`, or -1. `slop` widens every disc by that much, in
+ * the same units, so a one-pixel node stays hittable at a low zoom. When
+ * several qualify, the one the point sits deepest inside wins, and between
+ * near misses the one whose edge is closest.
+ */
+export function hitTest(grid: HitGrid, x: number, y: number, slop = 0): number {
+ if (grid.cols === 0) return -1;
+ const { x0, y0, cell, cols, rows, start, items, xs, ys, rs } = grid;
+ const c0 = Math.max(0, Math.floor((x - slop - x0) / cell));
+ const c1 = Math.min(cols - 1, Math.floor((x + slop - x0) / cell));
+ const r0 = Math.max(0, Math.floor((y - slop - y0) / cell));
+ const r1 = Math.min(rows - 1, Math.floor((y + slop - y0) / cell));
+ let best = -1;
+ let bestGap = Infinity;
+ for (let r = r0; r <= r1; r++) {
+ for (let c = c0; c <= c1; c++) {
+ const k = r * cols + c;
+ for (let j = start[k]!; j < start[k + 1]!; j++) {
+ const i = items[j]!;
+ const gap = Math.hypot(x - xs[i]!, y - ys[i]!) - rs[i]!;
+ if (gap <= slop && (gap < bestGap || (gap === bestGap && i < best))) {
+ best = i;
+ bestGap = gap;
+ }
+ }
+ }
+ }
+ return best;
+}
diff --git a/packages/ui/src/health/map/inspector.tsx b/packages/ui/src/health/map/inspector.tsx
index dc37979ab..8b5ddd879 100644
--- a/packages/ui/src/health/map/inspector.tsx
+++ b/packages/ui/src/health/map/inspector.tsx
@@ -1,29 +1,15 @@
"use client";
/**
- * The two things beside the canvas: what is selected, and how to reach the
- * rest of the field without a pointer.
+ * The ranked list beside the canvas: how to reach the field without a pointer.
*
- * The rail used to hold the repository's top findings permanently, which made
- * it a second findings list rather than an inspector: it never described the
- * object under the cursor, and it never changed when the lens did. An
- * inspector explains a selection, so it renders when there is one; the ranked
- * list is what fills the space otherwise, and it is also the field's keyboard
- * and screen-reader route into itself.
+ * It ranks what the active lens marks, so it changes when the lens does, and
+ * it is the field's keyboard and screen-reader route into itself.
*/
import { useMemo } from "react";
import { cn } from "../../lib/cn";
-import { scoreBadgeClass } from "../tokens";
-import {
- HEALTH_UNSUPPORTED_LABEL,
- NEUTRAL_FILL,
- PERFORMANCE_STATE_LABEL,
- performanceBurden,
- performanceFill,
- performanceSentence,
- scoreText,
-} from "./lens";
+import { performanceBurden, performanceSentence } from "./lens";
import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./types";
/** Rows the ranked list draws. Past this it is an inventory, not a lead. */
@@ -154,7 +140,7 @@ export function MapFieldList({
{f.file_path}
</span>
{overlay === "performance" ? (
- <span className="text-[11px] text-[var(--color-text-tertiary)]">
+ <span className="text-xs text-[var(--color-text-tertiary)]">
{performanceSentence(f)}
</span>
) : null}
@@ -163,7 +149,7 @@ export function MapFieldList({
);
})}
</ul>
- <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
<span className="tabular-nums">{rows.length}</span> of{" "}
<span className="tabular-nums">{ranked.length.toLocaleString()}</span>{" "}
{overlay === "performance" ? "files with an open cause" : "drawn files"} listed
@@ -172,139 +158,3 @@ export function MapFieldList({
</div>
);
}
-
-/**
- * The selected file, described by the active lens.
- *
- * Hover is pointer-bound decoding on the canvas; this opens for a click or a
- * keyboard selection and stays until it is dismissed, which is the difference
- * between reading a node and inspecting one.
- */
-export function MapInspector({
- file,
- overlay,
- onOpen,
- onClose,
-}: {
- file: CodeHealthMapFile;
- overlay: CodeHealthOverlay;
- onOpen: (path: string) => void;
- onClose: () => void;
-}) {
- const name = file.file_path.split("/").pop() ?? file.file_path;
- const burden = performanceBurden(file);
- return (
- <section
- aria-label={`Inspecting ${file.file_path}`}
- className="flex flex-col gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3"
- >
- <div className="flex items-center gap-2">
- {/* The lens decides what leads. Under performance the defect score is
- not the subject, and putting its coloured badge first told the
- reader the file was fine while the mark beside it said otherwise.
-
- The mark is the node as the canvas draws it, from the same
- function, so the selection and the field it was picked out of can
- never describe the file differently. */}
- <InspectorMark file={file} overlay={overlay} />
- <span className="min-w-0 flex-1 truncate text-sm font-medium text-[var(--color-text-primary)]">
- {name}
- </span>
- <button
- type="button"
- onClick={onClose}
- aria-label="Clear selection"
- className="shrink-0 rounded px-1.5 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- ✕
- </button>
- </div>
-
- <div className="truncate font-mono text-xs text-[var(--color-text-tertiary)]">
- {file.file_path}
- </div>
-
- {overlay === "performance" ? (
- <dl className="flex flex-col gap-1 border-t border-[var(--color-border-default)] pt-2 text-xs">
- <div className="flex items-baseline justify-between gap-3">
- <dt className="text-[var(--color-text-tertiary)]">
- Open {burden.unit}
- </dt>
- <dd className="font-mono text-base tabular-nums text-[var(--color-text-primary)]">
- {burden.count}
- </dd>
- </div>
- {file.performance_observations != null && burden.unit === "opportunities" ? (
- <div className="flex items-baseline justify-between gap-3">
- <dt className="text-[var(--color-text-tertiary)]">Observations behind them</dt>
- <dd className="font-mono tabular-nums text-[var(--color-text-primary)]">
- {file.performance_observations}
- </dd>
- </div>
- ) : null}
- <div className="flex items-baseline justify-between gap-3">
- <dt className="text-[var(--color-text-tertiary)]">State</dt>
- <dd className="text-right text-[var(--color-text-primary)]">
- {PERFORMANCE_STATE_LABEL[burden.state]}
- </dd>
- </div>
- </dl>
- ) : null}
-
- <div className="flex flex-wrap gap-x-3 gap-y-1 border-t border-[var(--color-border-default)] pt-2 text-xs text-[var(--color-text-secondary)]">
- {overlay === "performance" ? (
- // Still available, but as one supporting figure among several rather
- // than as the headline the lens is not about.
- <span className="tabular-nums">code health {scoreText(file)}</span>
- ) : file.score == null ? (
- <span>{HEALTH_UNSUPPORTED_LABEL}</span>
- ) : null}
- <span className="tabular-nums">{file.nloc.toLocaleString()} NLOC</span>
- {file.line_coverage_pct != null ? (
- <span className="tabular-nums">{Math.round(file.line_coverage_pct)}% coverage</span>
- ) : null}
- <span>{file.has_test_file ? "has tests" : "untested"}</span>
- </div>
-
- <button
- type="button"
- onClick={() => onOpen(file.file_path)}
- className="w-full rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- Open details
- </button>
- </section>
- );
-}
-
-/** The lead mark: the node as the field draws it, or the score pill. */
-function InspectorMark({
- file,
- overlay,
-}: {
- file: CodeHealthMapFile;
- overlay: CodeHealthOverlay;
-}) {
- // Under performance, or for a file with no score, the mark is the node as
- // the field draws it: a score pill would claim a figure the lens is not
- // about, or one nothing measured.
- if (overlay === "performance" || file.score == null) {
- return (
- <span
- aria-hidden
- className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full"
- style={{ backgroundColor: overlay === "performance" ? performanceFill(file) : NEUTRAL_FILL }}
- />
- );
- }
- return (
- <span
- className={cn(
- "inline-flex shrink-0 items-center justify-center rounded px-1.5 py-0.5 text-xs font-semibold tabular-nums",
- scoreBadgeClass(file.score),
- )}
- >
- {file.score.toFixed(1)}
- </span>
- );
-}
diff --git a/packages/ui/src/health/map/labels.tsx b/packages/ui/src/health/map/labels.tsx
new file mode 100644
index 000000000..5c9642d8d
--- /dev/null
+++ b/packages/ui/src/health/map/labels.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+/**
+ * Galaxy 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.
+ */
+
+import type { MutableRefObject } from "react";
+import type { Cam } from "./paint";
+import type { Galaxy } from "./types";
+
+/** 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. */
+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);
+
+interface Box {
+ x: number;
+ y: number;
+ w: 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;
+}
+
+function collides(box: Box, placed: Box[]): boolean {
+ return placed.some(
+ (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,
+ );
+}
+
+/** 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 };
+}
+
+/**
+ * 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.
+ */
+export function placeLabels(o: PlaceLabelsOptions): 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";
+ el.style.transform = `translate(${Math.round(box.x)}px, ${Math.round(box.y)}px)`;
+ }
+}
+
+export function GalaxyLabels({
+ galaxies,
+ refs,
+ focusIdx,
+ cursorIdx,
+ onToggle,
+}: {
+ 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;
+}) {
+ return (
+ <div className="pointer-events-none absolute inset-0">
+ {galaxies.map((g, i) => (
+ <button
+ key={g.module}
+ ref={(el) => {
+ refs.current[i] = el;
+ }}
+ 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)]" : ""}`}
+ style={{ visibility: "hidden" }}
+ >
+ {g.label}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/map/layout.ts b/packages/ui/src/health/map/layout.ts
index 66f597821..c5ee51cab 100644
--- a/packages/ui/src/health/map/layout.ts
+++ b/packages/ui/src/health/map/layout.ts
@@ -1,32 +1,72 @@
/**
- * Where every node sits, as one pure function of the rows and the canvas size.
+ * Where every node sits, as one pure function of the rows.
*
* 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.
+ * 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.
+ *
+ * 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.
*/
-import * as d3 from "d3-hierarchy";
-import type { CodeHealthMapFile, Galaxy, GalaxyAgg } from "./types";
+import { packEnclose, packSiblings } from "d3-hierarchy";
+import type { CodeHealthMapFile, FileNode, Galaxy, GalaxyAgg } from "./types";
-const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5)); // ~2.39996 rad
+/** 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 UNGROUPED = "(ungrouped)";
+const ROOT = "(root)";
+const OTHER = "Other modules";
+
+const byPath = (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[] {
- const byModule = new Map<string, CodeHealthMapFile[]>();
+ 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 = f.module ?? "(ungrouped)";
- const arr = byModule.get(key);
+ const key = keyOf(f);
+ const arr = byKey.get(key);
if (arr) arr.push(f);
- else byModule.set(key, [f]);
+ else byKey.set(key, [f]);
}
const out: GalaxyAgg[] = [];
- for (const [module, group] of byModule) {
- group.sort((a, b) => b.nloc - a.nloc);
+ for (const [module, group] of byKey) {
+ group.sort(byPath);
out.push({
module,
files: group,
@@ -35,69 +75,244 @@ export function groupByModule(files: CodeHealthMapFile[]): GalaxyAgg[] {
});
}
// Biggest galaxies first -> stable z-order (small ones paint on top).
- out.sort((a, b) => b.totalNloc - a.totalNloc);
+ out.sort((a, b) => b.totalNloc - a.totalNloc || (a.module < b.module ? -1 : 1));
return out;
}
-/** Stable, well-spread hash so a module maps to a consistent palette family. */
+/** 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("/");
+}
+
/**
- * Galaxy placement (d3-pack) plus hub-and-spoke file layout (phyllotaxis).
+ * How files group into galaxies: by module, or by sub-folder when the modules
+ * are too few to separate anything.
*
- * `S` is the square the field is packed into; the caller centres it in the
- * container. Returns an empty field for an empty input rather than throwing,
- * because a host renders before its data lands.
+ * 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 packGalaxies(files: CodeHealthMapFile[], S: number): Galaxy[] {
- if (S === 0 || files.length === 0) return [];
- const aggs = groupByModule(files);
- const root = d3
- .hierarchy<{ value?: number; agg?: GalaxyAgg; children?: unknown[] }>(
- { children: aggs.map((a) => ({ value: a.totalNloc, agg: a })) },
- (d) => d.children as { value?: number; agg?: GalaxyAgg }[] | undefined,
- )
- .sum((d) => d.value ?? 0);
- d3.pack<{ value?: number; agg?: GalaxyAgg }>().size([S, S]).padding(S * 0.012)(
- root as d3.HierarchyNode<{ value?: number; agg?: GalaxyAgg }>,
+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 galaxies: Galaxy[] = [];
- for (const leaf of root.leaves() as d3.HierarchyCircularNode<{ agg?: GalaxyAgg }>[]) {
- const agg = leaf.data.agg;
- if (!agg) continue;
- const R = leaf.r;
- const cx = leaf.x;
- const cy = leaf.y;
- const n = agg.files.length;
- const spread = R * 0.84;
- const maxNodeR = Math.max(2, R * 0.16);
- galaxies.push({
- module: agg.module,
+ 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 {
+ file: CodeHealthMapFile;
+ x: number;
+ y: number;
+ r: number;
+}
+
+/**
+ * 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.
+ */
+function packGalaxy(
+ files: CodeHealthMapFile[],
+ radius: (nloc: number) => number,
+ floorR: number,
+): { nodes: LocalNode[]; R: number } {
+ const dotPad = floorR * DOT_GAP;
+ const byDir = new Map<string, CodeHealthMapFile[]>();
+ for (const f of files) {
+ const d = dirOf(f.file_path);
+ const arr = byDir.get(d);
+ if (arr) arr.push(f);
+ else byDir.set(d, [f]);
+ }
+ 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) };
+ });
+ 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 nodes: LocalNode[] = [];
+ for (const c of placed) {
+ for (const d of c.dots) {
+ nodes.push({
+ file: d.file,
+ x: c.x - enc.x + (d.x - c.ex),
+ y: c.y - enc.y + (d.y - c.ey),
+ r: d.r - dotPad,
+ });
+ }
+ }
+ return { nodes, R: enc.r + floorR };
+}
+
+/**
+ * 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,
- fileCount: n,
- colorId: moduleColorId(agg.module),
- nodes: agg.files.map((file, i) => {
- const rr = spread * Math.sqrt((i + 0.55) / n);
- const ang = i * GOLDEN_ANGLE;
- const nodeR = Math.max(
- 1.2,
- Math.min(maxNodeR, maxNodeR * Math.sqrt(file.nloc / agg.maxNloc)),
- );
- return { file, x: cx + rr * Math.cos(ang), y: cy + rr * Math.sin(ang), r: nodeR };
- }),
- });
- }
- return galaxies;
+ 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 })),
+ }));
}
-/** Deterministic pseudo-random in [0,1) for the static starfield. */
-export function rand(i: number): number {
- const x = Math.sin(i * 127.1) * 43758.5453;
- return x - Math.floor(x);
+/** The camera that shows the whole world square in a `w` by `h` box. */
+export function fitCamera(w: number, h: number): { cx: number; cy: number; scale: number } {
+ return { cx: WORLD / 2, cy: WORLD / 2, scale: (Math.max(1, Math.min(w, h)) * 0.94) / WORLD };
}
diff --git a/packages/ui/src/health/map/legend.tsx b/packages/ui/src/health/map/legend.tsx
index 54e71fa95..6a35a8cad 100644
--- a/packages/ui/src/health/map/legend.tsx
+++ b/packages/ui/src/health/map/legend.tsx
@@ -15,13 +15,14 @@ import { OVERLAY_ORDER, OVERLAY_SPECS, type LegendRow, type OverlaySpec } from "
import type { CodeHealthOverlay } from "./types";
import { ActivityDot } from "../../ui/activity-dot";
-/** One key swatch: a disc in the row's fill. */
+/** 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 }) {
+ const run = row.fill.startsWith("linear-gradient");
return (
<span
aria-hidden
className="inline-block shrink-0 rounded-full"
- style={{ width: size, height: size, backgroundColor: row.fill }}
+ style={{ width: run ? size * 2.4 : size, height: size, background: row.fill }}
/>
);
}
@@ -60,7 +61,7 @@ export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: b
{spec.legend.map((row, i) => (
<Fragment key={row.label}>
{row.group && row.group !== spec.legend[i - 1]?.group ? (
- <span className="mt-1 font-mono text-[9px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] first:mt-0">
+ <span className="mt-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] first:mt-0">
{row.group}
</span>
) : null}
@@ -70,7 +71,7 @@ export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: b
</span>
</Fragment>
))}
- <span className="mt-1 font-mono text-[9px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <span className="mt-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Size
</span>
<SizeKey className="text-[var(--color-text-tertiary)]" />
@@ -158,7 +159,7 @@ export function MapLegend({
const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
return (
<div
- className={`flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[11px] text-[var(--color-text-tertiary)] ${className ?? ""}`}
+ className={`flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-[var(--color-text-tertiary)] ${className ?? ""}`}
>
{loading ? (
<span className="flex items-center gap-1.5">
@@ -169,7 +170,7 @@ export function MapLegend({
spec.legend.map((row, i) => (
<Fragment key={row.label}>
{row.group && row.group !== spec.legend[i - 1]?.group ? (
- <span className="ml-1 font-mono text-[9px] uppercase tracking-[0.12em] first:ml-0">
+ <span className="ml-1 font-mono text-[10px] uppercase tracking-[0.12em] first:ml-0">
{row.group}
</span>
) : null}
diff --git a/packages/ui/src/health/map/lens.ts b/packages/ui/src/health/map/lens.ts
index 5aa50e3e6..9e436cf4b 100644
--- a/packages/ui/src/health/map/lens.ts
+++ b/packages/ui/src/health/map/lens.ts
@@ -5,19 +5,12 @@
* cannot drift: both call the same spec.
*/
-import {
- HEALTH_BAND_LABEL,
- HEALTH_BAND_ORDER,
- HEALTH_BAND_RANGE_LABEL,
-} from "@repowise-dev/types/health";
-import { healthBandNodeFill, healthNodeFill } from "../tokens";
+import { HEALTH_BAND_LABEL, HEALTH_BAND_ORDER, HEALTH_BAND_RANGE_LABEL } from "@repowise-dev/types/health";
+import { NODE_HEALTHY_FILL, NODE_RAMP_STOP, healthBandMapFill, healthRampFill } from "../tokens";
import type { CodeHealthMapFile, CodeHealthOverlay, PerformanceActionability } from "./types";
-/** Worst-first legend rows, each naming its band and the range it covers. */
-const BAND_LEGEND = HEALTH_BAND_ORDER.map((band) => ({
- fill: healthBandNodeFill(band),
- label: `${HEALTH_BAND_LABEL[band]} · ${HEALTH_BAND_RANGE_LABEL[band]}`,
-}));
+/** The one quiet tone every file that needs nothing takes, under every lens. */
+export const QUIET_FILL = NODE_HEALTHY_FILL;
/**
* Neutral fill for nodes a lens has no signal for.
@@ -40,6 +33,12 @@ export interface LegendRow {
group?: string;
}
+/** Worst-first legend rows on the five canonical bands, as every score pill reads. */
+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 {
label: string;
@@ -49,28 +48,28 @@ export interface OverlaySpec {
legend: LegendRow[];
}
-/** Score band: the health ramp, quiet grey when the pillar is unscored. */
+/** Score: the map ramp, the neutral when the pillar is unscored. */
function scoreFill(score: number | null | undefined): string {
if (score == null) return NEUTRAL_FILL;
- return healthNodeFill(score);
+ return healthRampFill(score);
}
-/** Coverage band: green = well covered, red = uncovered, grey = no data. */
+/** Coverage band: quiet when well covered, the ramp's stops below that. */
function coverageFill(pct: number | null | undefined): string {
if (pct == null) return NEUTRAL_FILL;
- if (pct >= 80) return "var(--color-success)";
- if (pct >= 50) return "var(--color-caution)";
- if (pct >= 20) return "var(--color-warning)";
- return "var(--color-error)";
+ if (pct >= 80) return QUIET_FILL;
+ if (pct >= 50) return NODE_RAMP_STOP.warning;
+ if (pct >= 20) return NODE_RAMP_STOP.serious;
+ return NODE_RAMP_STOP.alert;
}
-/** Churn band: red = top-decile churn, green = quiet. */
+/** Churn band: quiet below the top 60%, the ramp's stops above it. */
function churnFill(pctile: number | null | undefined): string {
if (pctile == null) return NEUTRAL_FILL;
- if (pctile >= 90) return "var(--color-error)";
- if (pctile >= 70) return "var(--color-warning)";
- if (pctile >= 40) return "var(--color-caution)";
- return "var(--color-success)";
+ if (pctile >= 90) return NODE_RAMP_STOP.alert;
+ if (pctile >= 70) return NODE_RAMP_STOP.serious;
+ if (pctile >= 40) return NODE_RAMP_STOP.warning;
+ return QUIET_FILL;
}
/* ------------------------------------------------------------------ *
@@ -187,16 +186,16 @@ export function burdenBand(count: number): 0 | 1 | 2 | 3 {
}
/**
- * The three steps, borrowed from the health ramp.
+ * The three steps, borrowed from the map ramp's stops.
*
- * Same tokens the score pills and the health lens use, so a colour means the
- * same severity wherever it appears on this surface. The two greens are
- * deliberately absent: they are the bands that would claim a file is fine.
+ * The same values the health lens paints at 7, 5 and 2.5, so a colour means
+ * 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> = {
- 1: healthBandNodeFill("fair"),
- 2: healthBandNodeFill("needs_work"),
- 3: healthBandNodeFill("at_risk"),
+ 1: NODE_RAMP_STOP.warning,
+ 2: NODE_RAMP_STOP.serious,
+ 3: NODE_RAMP_STOP.alert,
};
export const PERFORMANCE_STATE_LABEL: Record<PerformanceNodeState, string> = {
@@ -250,10 +249,7 @@ export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
label: "Maintainability",
caption: "color = maintainability score · grey = not measured",
fill: (f) => scoreFill(f.maintainability_score),
- legend: [
- ...BAND_LEGEND,
- { fill: NEUTRAL_FILL, label: "not measured" },
- ],
+ legend: [...BAND_LEGEND, { fill: NEUTRAL_FILL, label: "not measured" }],
},
performance: {
label: "Performance",
@@ -271,10 +267,10 @@ export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
caption: "color = line coverage · grey = no coverage data",
fill: (f) => coverageFill(f.line_coverage_pct),
legend: [
- { fill: "var(--color-success)", label: "≥80%" },
- { fill: "var(--color-caution)", label: "50-80%" },
- { fill: "var(--color-warning)", label: "20-50%" },
- { fill: "var(--color-error)", label: "<20%" },
+ { 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" },
],
},
@@ -283,28 +279,28 @@ export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
caption: "color = 90-day churn percentile",
fill: (f) => churnFill(f.churn_percentile),
legend: [
- { fill: "var(--color-error)", label: "Top 10%" },
- { fill: "var(--color-warning)", label: "Top 30%" },
- { fill: "var(--color-caution)", label: "Top 60%" },
- { fill: "var(--color-success)", label: "Quiet" },
+ { 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 ? "var(--color-error)" : NEUTRAL_FILL),
+ fill: (f) => ((f.dead_code_lines ?? 0) > 0 ? NODE_RAMP_STOP.alert : NEUTRAL_FILL),
legend: [
- { fill: "var(--color-error)", label: "Has dead code" },
+ { 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 ? "var(--color-error)" : NEUTRAL_FILL),
+ fill: (f) => ((f.security_findings ?? 0) > 0 ? NODE_RAMP_STOP.alert : NEUTRAL_FILL),
legend: [
- { fill: "var(--color-error)", label: "Has findings" },
+ { fill: NODE_RAMP_STOP.alert, label: "Has findings" },
{ fill: NEUTRAL_FILL, label: "Clean" },
],
},
@@ -324,3 +320,16 @@ export const OVERLAY_ORDER: CodeHealthOverlay[] = [
"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/node-layer.tsx b/packages/ui/src/health/map/node-layer.tsx
deleted file mode 100644
index c21ffe298..000000000
--- a/packages/ui/src/health/map/node-layer.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-"use client";
-
-/**
- * The base field: one circle per file, and nothing else.
- *
- * Memoized and fed only stable props, so hover, selection and search - which
- * all re-render the facade - never reconcile these thousands of elements.
- * Everything that moves with the pointer lives in the overlay layer instead.
- *
- * There is deliberately no second mark layer here. A rare per-file annotation
- * was tried both ways, as a ring outside the node and as a core inside it, and
- * neither survived contact with the field: at this density an outline lands on
- * the neighbours and reads as a mark on the group, and a core in the one
- * colour with enough contrast to be seen is louder than the severity ramp it
- * is annotating. Anything that fine belongs in the words beside the map.
- */
-
-import { memo } from "react";
-import type { MouseEvent as ReactMouseEvent } from "react";
-import type { CodeHealthMapFile, Galaxy } from "./types";
-
-export interface NodeLayerProps {
- galaxies: Galaxy[];
- focusModuleKey: string | null;
- fill: (f: CodeHealthMapFile) => string;
- offX: number;
- offY: number;
- /**
- * Stroke in user units, pre-divided by the zoom scale so it lands on half a
- * device pixel at rest.
- *
- * The obvious spelling is `vectorEffect="non-scaling-stroke"`, which is what
- * this used. Chrome recomputes stroke geometry per element per frame for
- * that attribute, and these are thousands of elements inside the group whose
- * transform animates on every galaxy zoom. Dividing by the scale is free.
- * The trade is that during the transition the browser interpolates the
- * transform while this value is already at its destination, so strokes are
- * fractionally off mid-flight, which is invisible on a half-pixel line under
- * a moving field and correct the instant it settles.
- */
- strokeWidth: number;
- interactive: boolean;
- onSelect: (path: string) => void;
- /** The event comes along so the hover card can open at the pointer. */
- onHoverEnter: (f: CodeHealthMapFile, e: ReactMouseEvent) => void;
- onHoverLeave: (f: CodeHealthMapFile) => void;
-}
-
-export const FileNodes = memo(function FileNodes({
- galaxies,
- focusModuleKey,
- fill,
- offX,
- offY,
- strokeWidth,
- interactive,
- onSelect,
- onHoverEnter,
- onHoverLeave,
-}: NodeLayerProps) {
- return (
- <>
- {galaxies.map((g) => {
- const faded = focusModuleKey != null && g.module !== focusModuleKey;
- return (
- <g key={`nodes-${g.module}`}>
- {g.nodes.map((nd) => {
- const f = nd.file;
- return (
- /* No <title> child. It was thousands of extra DOM nodes driving
- a native tooltip that appears on its own delay, in the corner
- the pointer is in, restating what the hover card already
- shows the moment you touch a node - two tooltips racing.
- `data-path` costs no node and gives tests a stable handle. */
- <circle
- key={f.file_path}
- data-path={f.file_path}
- cx={nd.x + offX}
- cy={nd.y + offY}
- r={nd.r}
- fill={fill(f)}
- // One opacity for every lens. Opacity here means "this galaxy
- // is not the focused one" and nothing else; a lens that also
- // spent it on data left the reader unable to tell a quiet
- // file from a dimmed one.
- fillOpacity={faded ? 0.18 : 0.9}
- // The separating stroke is what makes this a field of files
- // rather than a wash. Every node keeps it, whatever it is
- // filled with.
- stroke="var(--color-bg-root)"
- strokeWidth={strokeWidth}
- className={interactive ? "cursor-pointer" : undefined}
- onMouseEnter={(e) => onHoverEnter(f, e)}
- onMouseLeave={() => onHoverLeave(f)}
- onClick={(e) => {
- e.stopPropagation();
- onSelect(f.file_path);
- }}
- />
- );
- })}
- </g>
- );
- })}
- </>
- );
-});
diff --git a/packages/ui/src/health/map/overlay.tsx b/packages/ui/src/health/map/overlay.tsx
index 0f5a01561..04331e2a7 100644
--- a/packages/ui/src/health/map/overlay.tsx
+++ b/packages/ui/src/health/map/overlay.tsx
@@ -1,112 +1,18 @@
"use client";
/**
- * Everything that follows the pointer, the keyboard, or the search box.
+ * The hover card, and the bound on how many search matches take a ring.
*
- * Kept off the base field on purpose. Hovering a node used to re-render the
- * whole node layer, and typing a search query used to re-render it once per
- * keystroke, because the query dimmed every non-matching circle. Both are now
- * bounded marks drawn on top: hover paints one circle, and search paints a
- * ring on the matches instead of touching the thousands that did not match.
+ * The rings themselves paint on the map's top canvas, above the field, so
+ * hover and typing repaint a few marks and never the thousands of nodes.
*/
import { performanceSentence, scoreText } from "./lens";
-import type { CodeHealthMapFile, CodeHealthOverlay, FileNode } from "./types";
+import type { CodeHealthMapFile, CodeHealthOverlay } from "./types";
/** Match rings drawn at once. Beyond this the field is the answer, not a mark. */
export const SEARCH_MARK_CAP = 250;
-/** The hovered and selected nodes only, drawn on top of the static field. */
-export function NodeHighlight({
- hovered,
- selectedPath,
- nodeIndex,
- offX,
- offY,
- fill,
-}: {
- hovered: CodeHealthMapFile | null;
- selectedPath: string | null;
- nodeIndex: Map<string, FileNode>;
- offX: number;
- offY: number;
- fill: (f: CodeHealthMapFile) => string;
-}) {
- const sel = selectedPath ? nodeIndex.get(selectedPath) : null;
- const hov = hovered ? nodeIndex.get(hovered.file_path) : null;
- return (
- <g className="pointer-events-none">
- {sel ? (
- <circle
- data-selected={sel.file.file_path}
- cx={sel.x + offX}
- cy={sel.y + offY}
- r={sel.r}
- fill={fill(sel.file)}
- fillOpacity={1}
- stroke="var(--color-accent-primary)"
- strokeWidth={2}
- vectorEffect="non-scaling-stroke"
- />
- ) : null}
- {hov && hov !== sel ? (
- <circle
- cx={hov.x + offX}
- cy={hov.y + offY}
- r={hov.r + 1.5}
- fill={fill(hov.file)}
- fillOpacity={1}
- stroke="var(--color-bg-root)"
- strokeWidth={0.5}
- vectorEffect="non-scaling-stroke"
- />
- ) : null}
- </g>
- );
-}
-
-/**
- * A ring on every node whose path matches the query, bounded.
- *
- * Marking the matches rather than dimming the rest is what keeps typing off
- * the base layer: the number of elements this draws tracks the answer, not the
- * repository, and the field underneath is untouched.
- */
-export function SearchMatches({
- paths,
- nodeIndex,
- offX,
- offY,
-}: {
- paths: string[];
- nodeIndex: Map<string, FileNode>;
- offX: number;
- offY: number;
-}) {
- if (paths.length === 0) return null;
- return (
- <g className="pointer-events-none">
- {paths.slice(0, SEARCH_MARK_CAP).map((path) => {
- const nd = nodeIndex.get(path);
- if (!nd) return null;
- return (
- <circle
- key={path}
- data-match={path}
- cx={nd.x + offX}
- cy={nd.y + offY}
- r={nd.r + 2.5}
- fill="none"
- stroke="var(--color-accent-primary)"
- strokeWidth={1.5}
- vectorEffect="non-scaling-stroke"
- />
- );
- })}
- </g>
- );
-}
-
/**
* Card box, for the edge flip.
*
@@ -168,11 +74,11 @@ export function HoverCard({
{dir}
</div>
) : null}
- <div className="break-all font-mono text-[11px] font-medium leading-snug text-[var(--color-text-primary)]">
+ <div className="break-all font-mono text-xs font-medium leading-snug text-[var(--color-text-primary)]">
{name}
</div>
{overlay === "performance" ? (
- <div className="mt-0.5 text-[11px] leading-tight text-[var(--color-text-secondary)]">
+ <div className="mt-0.5 text-xs leading-tight text-[var(--color-text-secondary)]">
{performanceSentence(file)}
</div>
) : null}
diff --git a/packages/ui/src/health/map/paint.ts b/packages/ui/src/health/map/paint.ts
new file mode 100644
index 000000000..9ae12c7f8
--- /dev/null
+++ b/packages/ui/src/health/map/paint.ts
@@ -0,0 +1,361 @@
+/**
+ * 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.
+ */
+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)"),
+ };
+}
+
+/** The laid-out field flattened for drawing: one index space for every node. */
+export interface FieldScene {
+ galaxies: Galaxy[];
+ nodes: FileNode[];
+ /** Node index -> galaxy index. */
+ galaxyOf: 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);
+ }
+ });
+ 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 };
+}
+
+/** One fill: the nodes that share a colour (or a colour pair, mid-tween). */
+export interface Batch {
+ 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.
+ */
+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 }>();
+ 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 g = groups.get(key);
+ if (g) g.list.push(i);
+ else groups.set(key, { list: [i], f, t, faded });
+ }
+ const out: Batch[] = [];
+ for (const g of groups.values()) {
+ out.push({
+ 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;
+}
+
+/** How much wider than its disc a node's glow reaches. */
+const GLOW_SCALE = 2.2;
+
+/**
+ * Build each batch's paths, with every radius floored at `floor` world units
+ * so a node never shrinks below a visible dot. Rebuilt only when the floor
+ * moves a zoom step, not per frame.
+ */
+export function attachPaths(batches: Batch[], scene: FieldScene, floor: number): void {
+ if (typeof Path2D === "undefined") return;
+ for (const b of batches) {
+ const path = new Path2D();
+ const glow = b.glowFrom || b.glowTo ? new Path2D() : null;
+ for (const i of b.nodes) {
+ const nd = scene.nodes[i]!;
+ const r = Math.max(nd.r, floor);
+ path.moveTo(nd.x + r, nd.y);
+ path.arc(nd.x, nd.y, r, 0, Math.PI * 2);
+ if (glow) {
+ glow.moveTo(nd.x + r * GLOW_SCALE, nd.y);
+ glow.arc(nd.x, nd.y, r * GLOW_SCALE, 0, Math.PI * 2);
+ }
+ }
+ b.path = path;
+ b.glow = glow;
+ }
+}
+
+export interface Cam {
+ cx: number;
+ cy: number;
+ scale: number;
+}
+
+export interface View {
+ w: number;
+ h: number;
+ dpr: number;
+}
+
+/** What one frame paints with: the field, 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;
+}
+
+/** 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;
+
+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];
+}
+
+/** Whether a disc of screen radius `r` at `(x, y)` misses the box. */
+function offscreen(view: View, x: number, y: number, r: number): boolean {
+ return x + r < 0 || y + r < 0 || x - r > view.w || y - r > view.h;
+}
+
+/** Reset to CSS-pixel space and clear. */
+function clear(ctx: CanvasRenderingContext2D, view: View): void {
+ ctx.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);
+ 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.
+ */
+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);
+ 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.stroke();
+ });
+}
+
+/** One batch at tween progress `t`: its glow, if it has one, then its discs. */
+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.fill(b.glow);
+ }
+ ctx.globalAlpha = alpha;
+ 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.
+ */
+export function drawField(
+ ctx: CanvasRenderingContext2D,
+ f: Frame,
+ batches: Batch[],
+ t: number,
+): void {
+ const { cam, view } = f;
+ clear(ctx, view);
+ drawGalaxies(ctx, f);
+ 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);
+ ctx.globalAlpha = 1;
+ ctx.setTransform(d, 0, 0, d, 0, 0);
+}
+
+export interface Marks {
+ selected: number;
+ hovered: number;
+ cursor: number;
+ matches: readonly number[];
+ /** 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. */
+function nodeOnScreen(f: Frame, i: number, floorPx: number): [number, number, number] | null {
+ const nd = f.scene.nodes[i];
+ if (!nd) 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)];
+}
+
+/**
+ * The top layer: rings in screen pixels, so a ring is the same weight at any
+ * zoom. Cheap enough to repaint on every hover change.
+ */
+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;
+ 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.stroke();
+ };
+ const solid = (i: number, grow: number) => {
+ const at = nodeOnScreen(f, i, marks.floorPx);
+ if (!at) return;
+ ctx.fillStyle = rgba(marks.fillOf(i));
+ ctx.beginPath();
+ ctx.arc(at[0], at[1], at[2] + grow, 0, Math.PI * 2);
+ ctx.fill();
+ };
+ const accent = rgba(f.palette.accent);
+ 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));
+ }
+ if (marks.selected >= 0) {
+ solid(marks.selected, 0);
+ ring(marks.selected, 3, 2, accent);
+ }
+ if (marks.cursor >= 0) ring(marks.cursor, 5.5, 2, accent, [3, 2]);
+ ctx.setLineDash([]);
+}
diff --git a/packages/ui/src/health/map/scope-note.tsx b/packages/ui/src/health/map/scope-note.tsx
new file mode 100644
index 000000000..ff8ee88fd
--- /dev/null
+++ b/packages/ui/src/health/map/scope-note.tsx
@@ -0,0 +1,164 @@
+"use client";
+
+/**
+ * What this field is, in one sentence, from the response that drew it, plus
+ * the few actions that change it.
+ *
+ * A count and the visual it describes have to come from one source, so this
+ * reads the server's own selection totals rather than the array length: a
+ * caption saying "3,808 files" over a two-thousand node field is a claim the
+ * reader has no way to check. The actions sit here because this is where the
+ * reader learns the field is partial.
+ */
+
+import type { ReactNode } from "react";
+import type { MapScope } from "./types";
+
+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";
+
+const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
+
+/** One clause of the sentence, after the separator. */
+function Part({ children }: { children: ReactNode }) {
+ return (
+ <>
+ {" · "}
+ {children}
+ </>
+ );
+}
+
+function Action({
+ pending,
+ onClick,
+ children,
+}: {
+ pending: boolean;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <button type="button" className={ACTION} disabled={pending} onClick={onClick}>
+ {children}
+ </button>
+ );
+}
+
+/** What the cap left out, in the units the server could count. */
+function omittedText(scope: MapScope): string {
+ const causes = scope.omitted.performanceFiles;
+ if (causes == null) return `${scope.omitted.files.toLocaleString()} not drawn`;
+ if (causes === 0) return "every file with an open cause is drawn";
+ return `${causes.toLocaleString()} ${plural(causes, "file", "files")} with open causes not drawn`;
+}
+
+function HeldToggle({
+ scope,
+ pending,
+ onChange,
+}: {
+ scope: MapScope;
+ pending: boolean;
+ onChange: (include: boolean) => void;
+}) {
+ const held = scope.held ?? 0;
+ if (held <= 0 && !scope.includeHeld) return null;
+ return (
+ <Part>
+ <Action pending={pending} onClick={() => onChange(!scope.includeHeld)}>
+ {scope.includeHeld
+ ? "Hide vendored and generated files"
+ : `Include ${held.toLocaleString()} vendored and generated ${plural(held, "file", "files")}`}
+ </Action>
+ </Part>
+ );
+}
+
+function SearchPart({
+ scope,
+ matches,
+ query,
+ capped,
+ pending,
+ onFindUndrawn,
+}: {
+ scope: MapScope;
+ matches: number;
+ query: string;
+ capped: boolean;
+ pending: boolean;
+ onFindUndrawn?: ((query: string) => void) | undefined;
+}) {
+ const pinned = scope.query && scope.query.text === query ? scope.query : null;
+ return (
+ <Part>
+ <span className="tabular-nums">{matches.toLocaleString()}</span>
+ {pinned
+ ? ` of ${pinned.matches.toLocaleString()} ${plural(pinned.matches, "match", "matches")} drawn`
+ : ` ${plural(matches, "match", "matches")} here`}
+ {onFindUndrawn && capped && !pinned ? (
+ <Part>
+ <Action pending={pending} onClick={() => onFindUndrawn(query)}>
+ Find matches outside the field
+ </Action>
+ </Part>
+ ) : null}
+ </Part>
+ );
+}
+
+export function MapScopeNote({
+ scope,
+ matches,
+ query,
+ drawMoreStep,
+ pending,
+ onDrawMore,
+ onIncludeHeldChange,
+ onFindUndrawn,
+}: {
+ scope: MapScope;
+ matches: number;
+ query: string;
+ drawMoreStep: number;
+ pending: boolean;
+ onDrawMore?: (() => void) | undefined;
+ onIncludeHeldChange?: ((include: boolean) => void) | undefined;
+ onFindUndrawn?: ((query: string) => void) | undefined;
+}) {
+ const capped = scope.shown < scope.eligible;
+ const more = Math.min(drawMoreStep, scope.eligible - scope.shown);
+ 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%]"
+ >
+ <span className="font-mono tabular-nums">
+ {scope.shown.toLocaleString()} of {scope.eligible.toLocaleString()}
+ </span>{" "}
+ files drawn
+ {capped ? <Part>{omittedText(scope)}</Part> : null}
+ {capped && onDrawMore && more > 0 ? (
+ <Part>
+ <Action pending={pending} onClick={onDrawMore}>
+ Draw {more.toLocaleString()} more
+ </Action>
+ </Part>
+ ) : null}
+ {onIncludeHeldChange ? (
+ <HeldToggle scope={scope} pending={pending} onChange={onIncludeHeldChange} />
+ ) : null}
+ {query ? (
+ <SearchPart
+ scope={scope}
+ matches={matches}
+ query={query}
+ capped={capped}
+ pending={pending}
+ onFindUndrawn={onFindUndrawn}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/map/types.ts b/packages/ui/src/health/map/types.ts
index f156eaeb2..3f37266e5 100644
--- a/packages/ui/src/health/map/types.ts
+++ b/packages/ui/src/health/map/types.ts
@@ -43,6 +43,8 @@ export interface CodeHealthMapFile {
dead_code_lines?: number | null;
/** Open security findings, drives the security lens. */
security_findings?: number | null;
+ /** Where the file's code comes from (production, test, vendored, ...). */
+ code_origin?: string | null;
}
// The wire vocabulary itself, so a new state cannot drift past the map.
@@ -77,7 +79,12 @@ export interface FileNode {
}
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;
@@ -111,4 +118,12 @@ export interface MapScope {
};
/** Paths the caller pinned that the index holds no drawable row for. */
missing?: string[];
+ /**
+ * Vendored and generated files held out of the field, and whether the host
+ * asked for them. Absent when the host does not hold them out.
+ */
+ held?: number;
+ includeHeld?: boolean;
+ /** The search the server pinned matches for, and how many it found. */
+ query?: { text: string; matches: number; shown: number };
}
diff --git a/packages/ui/src/health/map/use-field-canvas.ts b/packages/ui/src/health/map/use-field-canvas.ts
new file mode 100644
index 000000000..f31dfd522
--- /dev/null
+++ b/packages/ui/src/health/map/use-field-canvas.ts
@@ -0,0 +1,404 @@
+"use client";
+
+/**
+ * The map's two canvases and the loop that paints them.
+ *
+ * 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.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+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 { NEUTRAL_FILL } from "./lens";
+import { WORLD, fitCamera } from "./layout";
+import { placeLabels } from "./labels";
+import {
+ attachPaths,
+ createColourResolver,
+ drawField,
+ drawMarks,
+ groupBatches,
+ resolvePalette,
+ type Batch,
+ type Cam,
+ type FieldScene,
+ type Frame,
+ type Palette,
+ type Rgb,
+ type View,
+} from "./paint";
+
+/** Smallest radius a node is drawn at, so a zoomed-out file is still a dot. */
+export const MIN_NODE_PX = 0.9;
+/** Lens recolor, in ms. */
+const COLOUR_TWEEN_MS = 320;
+
+export function now(): number {
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
+}
+
+export interface Tween {
+ from: Cam;
+ to: Cam;
+ start: number;
+ dur: number;
+}
+
+/** What the frame loop paints, refreshed by the component on every render. */
+export interface FieldLive {
+ scene: FieldScene;
+ fills: string[];
+ focusIdx: number;
+ marked: number[];
+ selectedIdx: number;
+ cursorIdx: number;
+ hoverIdx: number;
+ minNodeR: number;
+ labelOrder: number[];
+}
+
+export interface Dirty {
+ base: boolean;
+ top: boolean;
+ labels: boolean;
+}
+
+/** The loop's whole mutable state. Other hooks move the camera through it. */
+export interface LoopState {
+ view: View;
+ cam: Cam;
+ /** The reader moved the camera, so a resize keeps their view. */
+ userMoved: boolean;
+ fly: Tween | null;
+ colour: { from: string[]; start: number } | null;
+ shownFills: string[] | null;
+ batches: Batch[];
+ stale: boolean;
+ /** The dot floor the current paths were built with, 0 for none. */
+ floor: number;
+ dirty: Dirty;
+ raf: number | null;
+ resolve: (css: string) => Rgb;
+ palette: Palette | null;
+}
+
+export type Invalidate = (what?: Partial<Dirty>) => void;
+
+export interface FieldCanvas {
+ loop: MutableRefObject<LoopState>;
+ invalidate: Invalidate;
+ /** The canvas has a size, so labels can be placed. */
+ ready: boolean;
+}
+
+const ALL: Dirty = { base: true, top: true, labels: true };
+
+function initialLoop(): LoopState {
+ return {
+ view: { w: 0, h: 0, dpr: 1 },
+ cam: { cx: WORLD / 2, cy: WORLD / 2, scale: 1 },
+ userMoved: false,
+ fly: null,
+ colour: null,
+ shownFills: null,
+ batches: [],
+ stale: true,
+ floor: 0,
+ dirty: { ...ALL },
+ raf: null,
+ resolve: () => [128, 128, 128],
+ palette: null,
+ };
+}
+
+/** Advance a camera flight. True when the camera moved this frame. */
+function stepFly(st: LoopState, t0: number): { moved: boolean; animating: boolean } {
+ const f = st.fly;
+ if (!f) return { moved: false, animating: false };
+ const p = f.dur <= 0 ? 1 : (t0 - f.start) / f.dur;
+ st.cam = p >= 1 ? f.to : interpolateCamera(f.from, f.to, p);
+ if (p >= 1) st.fly = null;
+ return { moved: true, animating: p < 1 };
+}
+
+/** Advance a lens recolor. `t` is its eased progress, 1 at rest. */
+function stepColour(st: LoopState, t0: number): { t: number; animating: boolean } {
+ if (!st.colour) return { t: 1, animating: false };
+ st.dirty.base = true;
+ const p = (t0 - st.colour.start) / COLOUR_TWEEN_MS;
+ if (p < 1) return { t: easeInOutCubic(p), animating: true };
+ st.colour = null;
+ st.stale = true;
+ return { t: 1, animating: false };
+}
+
+/**
+ * The dot floor this zoom needs, in world units, or 0 when no node is small
+ * enough to need one. A zoom step that moves the floor far enough rebuilds
+ * the paths; otherwise they are reused across every frame of a pan or zoom.
+ */
+function floorFor(st: LoopState, live: FieldLive): number {
+ const s = st.cam.scale;
+ const needed = live.minNodeR * s < MIN_NODE_PX * 1.5 ? MIN_NODE_PX / s : 0;
+ const built = st.floor;
+ const drift = built > 0 && needed > 0 ? needed / built : 1;
+ if ((needed > 0) !== (built > 0) || drift > 1.25 || drift < 0.8) st.stale = true;
+ return needed;
+}
+
+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,
+ );
+ attachPaths(st.batches, live.scene, floor);
+ st.floor = floor;
+ st.stale = false;
+ st.dirty.base = true;
+}
+
+interface Layers {
+ base: RefObject<HTMLCanvasElement | null>;
+ top: RefObject<HTMLCanvasElement | null>;
+ labels: MutableRefObject<(HTMLElement | null)[]>;
+}
+
+/** One frame: advance the tweens, rebuild what went stale, paint what changed. */
+function runFrame(st: LoopState, live: FieldLive, layers: Layers): boolean {
+ const t0 = now();
+ const flight = stepFly(st, t0);
+ const colour = stepColour(st, t0);
+ const floor = floorFor(st, live);
+ const base = layers.base.current?.getContext("2d") ?? null;
+ const top = layers.top.current?.getContext("2d") ?? null;
+ st.palette ??= resolvePalette(st.resolve);
+ if (st.stale && base) rebuild(st, live, floor);
+
+ const frame: Frame = {
+ scene: live.scene,
+ cam: st.cam,
+ view: st.view,
+ palette: st.palette,
+ focus: live.focusIdx,
+ };
+ 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,
+ });
+ }
+ st.dirty = { base: false, top: false, labels: false };
+ return flight.animating || colour.animating;
+}
+
+/** Size both canvases to `w` by `h` CSS px at the current pixel ratio. */
+function sizeCanvases(st: LoopState, layers: Layers, w: number, h: number): void {
+ const dpr = typeof window !== "undefined" ? Math.min(window.devicePixelRatio || 1, 3) : 1;
+ st.view = { w, h, dpr };
+ for (const c of [layers.base.current, layers.top.current]) {
+ if (!c) continue;
+ c.width = Math.max(1, Math.round(w * dpr));
+ c.height = Math.max(1, Math.round(h * dpr));
+ c.style.width = `${w}px`;
+ c.style.height = `${h}px`;
+ }
+ if (!st.userMoved) {
+ st.fly = null;
+ st.cam = fitCamera(w, h);
+ }
+}
+
+/**
+ * Track the container's box, coalesced to one resize per frame, and the
+ * screen's pixel ratio, which a ResizeObserver does not report: the query
+ * names the current ratio, so it is re-armed on every change.
+ */
+function useCanvasSize(
+ container: RefObject<HTMLElement | null>,
+ layers: Layers,
+ loop: MutableRefObject<LoopState>,
+ minHeight: number,
+ invalidate: Invalidate,
+ setReady: (ready: boolean) => void,
+): void {
+ useEffect(() => {
+ const node = container.current;
+ if (!node || typeof ResizeObserver === "undefined") return;
+ let pending: { width: number; height: number } | null = null;
+ let last = { width: 0, height: 0 };
+ let sizeRaf: number | null = null;
+ const apply = () => {
+ sizeRaf = null;
+ if (!pending) return;
+ last = pending;
+ pending = null;
+ const w = Math.round(last.width);
+ sizeCanvases(loop.current, layers, w, Math.round(Math.max(last.height, minHeight)));
+ setReady(w > 0);
+ invalidate();
+ };
+ const observer = new ResizeObserver((entries) => {
+ const first = entries[0];
+ if (!first) return;
+ pending = { width: first.contentRect.width, height: first.contentRect.height };
+ // The first size lands synchronously so the field never paints a blank
+ // frame at mount; later ones coalesce into one per animation frame.
+ if (loop.current.view.w === 0) apply();
+ else if (sizeRaf == null) sizeRaf = requestAnimationFrame(apply);
+ });
+ observer.observe(node);
+ let media: MediaQueryList | null = null;
+ const onRatio = () => {
+ pending = last;
+ apply();
+ watchRatio();
+ };
+ const watchRatio = () => {
+ media?.removeEventListener("change", onRatio);
+ if (typeof window === "undefined" || !window.matchMedia) return;
+ media = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`);
+ media.addEventListener("change", onRatio);
+ };
+ watchRatio();
+ return () => {
+ observer.disconnect();
+ media?.removeEventListener("change", onRatio);
+ if (sizeRaf != null) cancelAnimationFrame(sizeRaf);
+ };
+ }, [container, layers, loop, minHeight, invalidate, setReady]);
+}
+
+/** Each input names the one layer it changes. */
+function useRepaintTriggers(
+ container: RefObject<HTMLElement | null>,
+ loop: MutableRefObject<LoopState>,
+ live: FieldLive,
+ reducedMotion: boolean,
+ labelKey: unknown,
+ ready: boolean,
+ invalidate: Invalidate,
+): void {
+ const themeVersion = useThemeVersion();
+ const { scene, fills, focusIdx, marked, selectedIdx, cursorIdx, hoverIdx } = live;
+ useEffect(() => {
+ const st = loop.current;
+ st.resolve = createColourResolver(container.current);
+ st.palette = null;
+ st.stale = true;
+ invalidate();
+ }, [themeVersion, container, loop, invalidate]);
+
+ useEffect(() => {
+ // A new feed is a new field: no tween from the old one's 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]);
+
+ useEffect(() => {
+ const st = loop.current;
+ const previous = st.shownFills;
+ st.shownFills = fills;
+ if (previous && previous !== fills && previous.length === fills.length && !reducedMotion) {
+ st.colour = { from: previous, start: now() };
+ }
+ st.stale = true;
+ invalidate();
+ }, [fills, reducedMotion, loop, invalidate]);
+
+ useEffect(() => {
+ loop.current.stale = true;
+ invalidate();
+ }, [focusIdx, loop, invalidate]);
+
+ useEffect(() => {
+ invalidate({ top: true });
+ }, [marked, selectedIdx, cursorIdx, hoverIdx, invalidate]);
+
+ useEffect(() => {
+ invalidate({ labels: true });
+ }, [labelKey, ready, invalidate]);
+}
+
+export function useFieldCanvas(opts: {
+ container: RefObject<HTMLElement | null>;
+ base: RefObject<HTMLCanvasElement | null>;
+ top: RefObject<HTMLCanvasElement | null>;
+ labels: MutableRefObject<(HTMLElement | null)[]>;
+ minHeight: number;
+ live: FieldLive;
+ reducedMotion: boolean;
+ /** Changes whenever the labels need re-placing without a camera move. */
+ labelKey: unknown;
+}): FieldCanvas {
+ const { container, base, top, labels, minHeight, live, reducedMotion, labelKey } = opts;
+ const loop = useRef<LoopState>(initialLoop());
+ const liveRef = useRef(live);
+ liveRef.current = live;
+ const layers = useRef<Layers>({ base, top, labels }).current;
+ const [ready, setReady] = useState(false);
+
+ const frame = useCallback(() => {
+ const st = loop.current;
+ st.raf = null;
+ if (st.view.w === 0) return;
+ if (runFrame(st, liveRef.current, layers)) st.raf = requestAnimationFrame(frame);
+ }, [layers]);
+
+ const invalidate = useCallback<Invalidate>(
+ (what = ALL) => {
+ const st = loop.current;
+ if (what.base) st.dirty.base = true;
+ if (what.top) st.dirty.top = true;
+ if (what.labels) st.dirty.labels = true;
+ if (st.raf == null && typeof requestAnimationFrame !== "undefined") {
+ st.raf = requestAnimationFrame(frame);
+ }
+ },
+ [frame],
+ );
+
+ useEffect(
+ () => () => {
+ // Cleared as well as cancelled: a remount (StrictMode runs effects
+ // twice) must be able to schedule again.
+ const st = loop.current;
+ if (st.raf != null) cancelAnimationFrame(st.raf);
+ st.raf = null;
+ },
+ [],
+ );
+
+ useCanvasSize(container, layers, loop, minHeight, invalidate, setReady);
+ useRepaintTriggers(container, loop, live, reducedMotion, labelKey, ready, invalidate);
+ return { loop, invalidate, ready };
+}
diff --git a/packages/ui/src/health/map/use-field-model.ts b/packages/ui/src/health/map/use-field-model.ts
new file mode 100644
index 000000000..41d4e7aa1
--- /dev/null
+++ b/packages/ui/src/health/map/use-field-model.ts
@@ -0,0 +1,60 @@
+"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.
+ */
+
+import { useMemo } from "react";
+
+import { isLoudFill } from "../tokens";
+import { buildHitGrid } from "./hit-test";
+import { layoutField } from "./layout";
+import type { OverlaySpec } from "./lens";
+import { SEARCH_MARK_CAP } from "./overlay";
+import { buildScene } from "./paint";
+import type { CodeHealthMapFile } from "./types";
+
+export function useFieldModel(
+ files: CodeHealthMapFile[],
+ spec: OverlaySpec,
+ search: string | undefined,
+ highlightPaths: string[] | undefined,
+) {
+ const galaxies = useMemo(() => layoutField(files), [files]);
+ const scene = useMemo(() => buildScene(galaxies), [galaxies]);
+ 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 attention = useMemo(() => fills.filter(isLoudFill).length, [fills]);
+
+ const query = (search ?? "").trim().toLowerCase();
+ const matches = useMemo(() => {
+ if (query.length === 0) return [] as number[];
+ const out: number[] = [];
+ scene.nodes.forEach((n, i) => {
+ if (n.file.file_path.toLowerCase().includes(query)) out.push(i);
+ });
+ return out;
+ }, [query, scene]);
+ const marked = useMemo(() => {
+ const extra = (highlightPaths ?? [])
+ .map((p) => scene.index.get(p))
+ .filter((i): i is number => i !== undefined);
+ const all = extra.length ? [...new Set([...extra, ...matches])] : matches;
+ return all.slice(0, SEARCH_MARK_CAP);
+ }, [highlightPaths, matches, scene]);
+
+ return { galaxies, scene, grid, minNodeR, labelOrder, fills, attention, query, matches, marked };
+}
diff --git a/packages/ui/src/health/map/use-map-camera.ts b/packages/ui/src/health/map/use-map-camera.ts
new file mode 100644
index 000000000..07242d67b
--- /dev/null
+++ b/packages/ui/src/health/map/use-map-camera.ts
@@ -0,0 +1,110 @@
+"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.
+ */
+
+import { useCallback, useEffect, useRef } from "react";
+import type { MutableRefObject } from "react";
+
+import { frameRect, zoomAbout } from "../../zoom/camera";
+import { flyDuration } from "../../zoom/camera-anim";
+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;
+/** One step of the zoom buttons and keys. */
+export const ZOOM_STEP = 1.6;
+
+/** Keep the camera within zoom bounds and near the field. */
+export function clampCam(st: LoopState, c: Cam): Cam {
+ const fit = fitCamera(st.view.w, st.view.h);
+ const scale = Math.min(fit.scale * MAX_ZOOM, Math.max(fit.scale * MIN_ZOOM, c.scale));
+ const lo = -WORLD * 0.25;
+ const hi = WORLD * 1.25;
+ return { cx: Math.min(hi, Math.max(lo, c.cx)), cy: Math.min(hi, Math.max(lo, c.cy)), scale };
+}
+
+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;
+}
+
+export function useMapCamera(opts: {
+ loop: MutableRefObject<LoopState>;
+ invalidate: Invalidate;
+ reducedMotion: boolean;
+ galaxies: Galaxy[];
+ focusModule: string | null;
+ setFocusModule: (module: string | null) => void;
+}): MapCamera {
+ const { loop, invalidate, reducedMotion, galaxies, focusModule, setFocusModule } = opts;
+
+ /** Move the camera, flown unless the reader asked for no motion. */
+ const flyTo = useCallback(
+ (to: Cam, animate = true) => {
+ const st = loop.current;
+ const target = clampCam(st, to);
+ const from = st.cam;
+ st.fly = {
+ from,
+ to: target,
+ start: now(),
+ dur: animate && !reducedMotion ? flyDuration(from, target) : 0,
+ };
+ invalidate();
+ },
+ [loop, invalidate, reducedMotion],
+ );
+
+ const fitView = useCallback(() => {
+ const st = loop.current;
+ st.userMoved = false;
+ flyTo(fitCamera(st.view.w, st.view.h));
+ }, [loop, flyTo]);
+
+ const zoomBy = useCallback(
+ (factor: number) => {
+ const st = loop.current;
+ st.userMoved = true;
+ flyTo(zoomAbout(st.cam, st.view, st.view.w / 2, st.view.h / 2, factor));
+ },
+ [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]);
+
+ return { zoomBy, fitView, focusOn, fitAll };
+}
diff --git a/packages/ui/src/health/map/use-map-keyboard.ts b/packages/ui/src/health/map/use-map-keyboard.ts
new file mode 100644
index 000000000..d50342773
--- /dev/null
+++ b/packages/ui/src/health/map/use-map-keyboard.ts
@@ -0,0 +1,133 @@
+"use client";
+
+/**
+ * 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.
+ *
+ * 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.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from "react";
+
+import type { FileNode, Galaxy } from "./types";
+import { ZOOM_STEP, type MapCamera } from "./use-map-camera";
+
+export type KeyboardLevel = "module" | "file";
+
+/** 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;
+
+/** 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);
+ // 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 };
+}
+
+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;
+}
+
+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],
+ );
+
+ 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 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],
+ );
+
+ const escape = useRef({ focused: false, fileLevel: false });
+ escape.current = { focused: focusModule != null, fileLevel: kb.level === "file" };
+ const { setLevel } = kb;
+ 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;
+ e.stopPropagation();
+ e.preventDefault();
+ setLevel("module");
+ setFocusModule(null);
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [container, setLevel, setFocusModule]);
+
+ return onKeyDown;
+}
diff --git a/packages/ui/src/health/map/use-map-pointer.ts b/packages/ui/src/health/map/use-map-pointer.ts
new file mode 100644
index 000000000..d526957fb
--- /dev/null
+++ b/packages/ui/src/health/map/use-map-pointer.ts
@@ -0,0 +1,255 @@
+"use client";
+
+/**
+ * The pointer on the field: hover, click, drag to pan, pinch and wheel to zoom.
+ *
+ * Picking is a grid lookup, so it runs on every move. The hovered file is
+ * mirrored in a ref, so a move over the same node is that lookup and nothing
+ * else: React hears about hover only when it changes.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import type {
+ MouseEvent as ReactMouseEvent,
+ MutableRefObject,
+ PointerEvent as ReactPointerEvent,
+ RefObject,
+} from "react";
+
+import { panByScreen, screenToWorld, zoomAbout } from "../../zoom/camera";
+import { hitTest, type HitGrid } from "./hit-test";
+import type { FieldScene } from "./paint";
+import type { CodeHealthMapFile, Galaxy } from "./types";
+import { MIN_NODE_PX, type Invalidate, type LoopState } from "./use-field-canvas";
+import { clampCam } from "./use-map-camera";
+
+/** Pointer slop for picking a node, in px. */
+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;
+}
+
+interface Point {
+ x: number;
+ y: number;
+}
+
+interface Drag extends Point {
+ moved: boolean;
+ /** Distance between two fingers, 0 when not pinching. */
+ pinch: number;
+}
+
+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;
+ if (e.deltaMode === 2) return e.deltaY * pageHeight;
+ return e.deltaY;
+}
+
+/** Hover state, and a setter that only re-renders when the file changes. */
+export function useHover(onHoverFile: ((file: CodeHealthMapFile | null) => void) | undefined) {
+ const [hover, setHover] = useState<Hover | null>(null);
+ const hovered = useRef<CodeHealthMapFile | 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);
+ }, []);
+ return { hover, setHovered };
+}
+
+export function useMapPointer(opts: {
+ container: RefObject<HTMLElement | null>;
+ loop: MutableRefObject<LoopState>;
+ invalidate: Invalidate;
+ 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;
+}) {
+ const { container, loop, invalidate, scene, grid, minNodeR, galaxies, focusModule, focusOn, onSelect, 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.
+ const engaged = useRef(false);
+ const suppressClick = useRef(false);
+
+ const localPoint = useCallback(
+ (clientX: number, clientY: number): Point => {
+ const rect = container.current?.getBoundingClientRect();
+ return { x: clientX - (rect?.left ?? 0), y: clientY - (rect?.top ?? 0) };
+ },
+ [container],
+ );
+
+ const pick = useCallback(
+ (p: Point) => {
+ const { cam, view } = loop.current;
+ 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 };
+ },
+ [loop, grid, minNodeR],
+ );
+
+ /** Apply a camera the pointer produced and repaint everything. */
+ const moveCamera = useCallback(
+ (next: (st: LoopState) => LoopState["cam"]) => {
+ const st = loop.current;
+ st.cam = clampCam(st, next(st));
+ st.fly = null;
+ st.userMoved = true;
+ invalidate();
+ },
+ [loop, invalidate],
+ );
+
+ const onPointerDown = useCallback(
+ (e: ReactPointerEvent) => {
+ engaged.current = true;
+ const p = localPoint(e.clientX, e.clientY);
+ pointers.current.set(e.pointerId, p);
+ (e.currentTarget as Element).setPointerCapture?.(e.pointerId);
+ const pts = [...pointers.current.values()];
+ const pinch = pts.length === 2 ? distance(pts[0]!, pts[1]!) : 0;
+ drag.current = { ...p, moved: drag.current?.moved ?? false, pinch };
+ },
+ [localPoint],
+ );
+
+ const pinchTo = useCallback(
+ (d: Drag, a: Point, b: Point) => {
+ const dist = distance(a, b);
+ const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
+ moveCamera((st) => zoomAbout(st.cam, st.view, mid.x, mid.y, dist / d.pinch));
+ d.pinch = dist;
+ d.moved = true;
+ },
+ [moveCamera],
+ );
+
+ const panTo = useCallback(
+ (d: Drag, p: Point): boolean => {
+ const dx = p.x - d.x;
+ const dy = p.y - d.y;
+ if (!d.moved && Math.hypot(dx, dy) < DRAG_PX) return false;
+ d.moved = true;
+ d.x = p.x;
+ d.y = p.y;
+ moveCamera((st) => panByScreen(st.cam, dx, dy));
+ return true;
+ },
+ [moveCamera],
+ );
+
+ const onPointerMove = useCallback(
+ (e: ReactPointerEvent) => {
+ const d = drag.current;
+ if (!d || !pointers.current.has(e.pointerId)) return;
+ const p = localPoint(e.clientX, e.clientY);
+ pointers.current.set(e.pointerId, p);
+ const pts = [...pointers.current.values()];
+ if (pts.length === 2 && d.pinch > 0) pinchTo(d, pts[0]!, pts[1]!);
+ else if (!panTo(d, p)) return;
+ setHovered(null);
+ },
+ [localPoint, pinchTo, panTo, setHovered],
+ );
+
+ const onPointerUp = useCallback((e: ReactPointerEvent) => {
+ pointers.current.delete(e.pointerId);
+ const d = drag.current;
+ if (pointers.current.size === 0) {
+ suppressClick.current = d?.moved ?? false;
+ drag.current = null;
+ } else if (d) {
+ const rest = [...pointers.current.values()][0]!;
+ drag.current = { ...rest, moved: d.moved, pinch: 0 };
+ }
+ }, []);
+
+ 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);
+ },
+ [localPoint, pick, scene, setHovered],
+ );
+
+ const onMouseLeave = useCallback(() => {
+ engaged.current = false;
+ setHovered(null);
+ }, [setHovered]);
+
+ const onClick = useCallback(
+ (e: ReactMouseEvent) => {
+ if (suppressClick.current) {
+ suppressClick.current = false;
+ 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);
+ },
+ [localPoint, pick, onSelect, scene, galaxies, focusModule, focusOn],
+ );
+
+ // Wheel zooms once the reader is working in the map (or pinches a
+ // trackpad, which arrives as ctrl+wheel), so scrolling the page past the
+ // map never gets trapped by it. Bound natively: React's wheel listener is
+ // passive and cannot stop the page from scrolling.
+ useEffect(() => {
+ const node = container.current;
+ if (!node) return;
+ const onWheel = (e: WheelEvent) => {
+ if (!engaged.current && !e.ctrlKey && !e.metaKey) return;
+ e.preventDefault();
+ const rate = e.ctrlKey ? 0.01 : 0.0015;
+ const factor = Math.exp(-wheelPixels(e, loop.current.view.h) * rate);
+ const p = localPoint(e.clientX, e.clientY);
+ moveCamera((st) => zoomAbout(st.cam, st.view, p.x, p.y, factor));
+ };
+ node.addEventListener("wheel", onWheel, { passive: false });
+ return () => node.removeEventListener("wheel", onWheel);
+ }, [container, loop, localPoint, moveCamera]);
+
+ return { onPointerDown, onPointerMove, onPointerUp, onMouseMove, onMouseLeave, onClick };
+}
diff --git a/packages/ui/src/health/plain-language.ts b/packages/ui/src/health/plain-language.ts
new file mode 100644
index 000000000..a309eea5d
--- /dev/null
+++ b/packages/ui/src/health/plain-language.ts
@@ -0,0 +1,283 @@
+/**
+ * Findings in the words a developer uses, for the file drawer's first screen.
+ *
+ * The glossary names detectors ("Brain method", "Bumpy road"); those names are
+ * precise and they are jargon. A reader who has never seen Repowise needs what
+ * is wrong and why it matters, so each detector gets a plain title and a
+ * one-line consequence here, with its category as the fallback. The detector's
+ * own label stays one click away, in the expanded row.
+ */
+
+import { bandForScore, type HealthBand } from "@repowise-dev/types/health";
+import { biomarkerInfo, isHistoryBiomarker, type BiomarkerCategory } from "./biomarker-glossary";
+
+export interface PlainIssue {
+ /** What is wrong, as a short noun phrase. */
+ title: string;
+ /** Why it matters, in one line. */
+ why: string;
+}
+
+const BY_CATEGORY: Record<BiomarkerCategory, PlainIssue> = {
+ structural_complexity: {
+ title: "Hard-to-follow logic",
+ why: "Tangled control flow is easy to break when it changes.",
+ },
+ size_and_complexity: {
+ title: "Function is too big",
+ why: "Large functions are hard to read, review and test.",
+ },
+ duplication: {
+ title: "Duplicated code",
+ why: "A fix made in one copy is easy to miss in the others.",
+ },
+ test_coverage: {
+ title: "Untested code",
+ why: "Nothing would catch a mistake here.",
+ },
+ test_coverage_gradient: {
+ title: "Coverage drops off",
+ why: "Part of the file is tested and part is not.",
+ },
+ test_quality: {
+ title: "Weak test",
+ why: "The test runs the code but checks little of what it does.",
+ },
+ error_handling: {
+ title: "Errors caught too broadly",
+ why: "A broad catch can hide a real failure.",
+ },
+ performance: {
+ title: "Slow pattern",
+ why: "Work is repeated where it can get slow as data grows.",
+ },
+ organizational: {
+ title: "Risky change history",
+ why: "Measured from git history, not the code: no edit here clears it.",
+ },
+ sql: {
+ title: "Risky SQL",
+ why: "The query is hard to reason about or can touch more rows than meant.",
+ },
+};
+
+const BY_BIOMARKER: Record<string, PlainIssue> = {
+ brain_method: {
+ title: "Function does too much",
+ why: "Many decisions in one place make every change to it risky.",
+ },
+ nested_complexity: {
+ title: "Deeply nested logic",
+ why: "Each level of nesting is more context a reader has to hold.",
+ },
+ bumpy_road: {
+ title: "Several tangled blocks in one function",
+ why: "It reads as a few functions glued together.",
+ },
+ complex_conditional: {
+ title: "Complicated condition",
+ why: "A condition with many parts is easy to get wrong.",
+ },
+ low_cohesion: {
+ title: "Unrelated jobs in one place",
+ why: "Code that changes for different reasons ends up changing together.",
+ },
+ god_class: {
+ title: "Class does too much",
+ why: "One class owns too many responsibilities to change safely.",
+ },
+ complex_method: {
+ title: "Too many paths through one function",
+ why: "Every path is another case to test.",
+ },
+ large_method: {
+ title: "Very long function",
+ why: "Long functions are hard to read and review.",
+ },
+ primitive_obsession: {
+ title: "Too many parameters",
+ why: "Calls become positional and easy to mix up.",
+ },
+ untested_hotspot: {
+ title: "Changes often and is untested",
+ why: "Frequent edits with nothing to catch a mistake.",
+ },
+ prior_defect: {
+ title: "Fixed for bugs often",
+ why: "Files with past bug fixes tend to get more.",
+ },
+ churn_risk: {
+ title: "Changes very often",
+ why: "Heavy churn is a strong predictor of new bugs.",
+ },
+ change_entropy: {
+ title: "Scattered changes",
+ why: "Edits arrive from many unrelated pieces of work.",
+ },
+ co_change_scatter: {
+ title: "Edits ripple to other files",
+ why: "Changing this file usually means changing many others.",
+ },
+ knowledge_loss: {
+ title: "Its main authors have moved on",
+ why: "Fewer people know how it works.",
+ },
+ developer_congestion: {
+ title: "Many people edit it at once",
+ why: "Parallel edits collide and get merged wrongly.",
+ },
+ ownership_risk: {
+ title: "No clear owner",
+ why: "Nobody is clearly responsible for it.",
+ },
+};
+
+export function plainIssue(biomarker: string): PlainIssue {
+ return BY_BIOMARKER[biomarker] ?? BY_CATEGORY[biomarkerInfo(biomarker).category] ?? {
+ title: "Code health issue",
+ why: "This lowers the file's score.",
+ };
+}
+
+const COUNT_WORD = ["", "one", "two", "three"];
+
+/** The clause each kind of problem adds to the verdict, other than size and shape. */
+const FIXED_CLAUSE: Partial<Record<BiomarkerCategory, string>> = {
+ duplication: "it repeats code found elsewhere",
+ test_coverage: "parts of it are untested",
+ test_coverage_gradient: "parts of it are untested",
+ test_quality: "its tests check little",
+ error_handling: "it catches errors too broadly",
+ performance: "it has slow patterns",
+ sql: "it has risky SQL",
+ organizational: "its change history is risky",
+};
+
+/** Size and shape read as one kind of problem: how many functions, and whether
+ * "too long" is the whole of it. */
+function functionClause(functions: number, onlyLength: boolean): string {
+ const what = onlyLength ? "long" : "complex";
+ return functions > 1
+ ? `${COUNT_WORD[functions] ?? functions} functions are too ${what}`
+ : `one function is too ${what}`;
+}
+
+/** The clause one kind of problem contributes to the verdict sentence. */
+function clause(category: BiomarkerCategory, functions: number, onlyLength: boolean): string {
+ return FIXED_CLAUSE[category] ?? functionClause(functions, onlyLength);
+}
+
+export interface VerdictInput {
+ score: number | null;
+ /** The findings the drawer leads with, worst first. */
+ top: readonly { biomarker_type: string; function_name: string | null }[];
+ /** Whether a paired test file was found, when that is known. */
+ hasTestFile?: boolean | undefined;
+ /** Every scored finding is history, not code. */
+ historyOnly: boolean;
+ /** The findings were loaded. Without them the verdict makes no claim. */
+ findingsKnown?: boolean | undefined;
+ /** Open findings not leading: how many, their summed impact, and how much
+ * of that is change history. */
+ rest?: { count: number; impact: number; historyImpact: number } | undefined;
+}
+
+export interface Verdict {
+ /** The sentence, or null when the evidence on hand supports none. */
+ text: string | null;
+ /** The sentence is the all-clear, so there is nothing to hand an agent. */
+ healthy: boolean;
+}
+
+/** The verdict's opening words, on the shared bands so they agree with the mark. */
+const BAND_LEAD: Record<HealthBand, string> = {
+ excellent: "In good shape",
+ good: "In good shape",
+ fair: "Needs attention",
+ needs_work: "Needs work",
+ at_risk: "Hard to change safely",
+};
+
+const HISTORY_VERDICT =
+ "The code itself is not flagged. Its score comes from change history, which no edit here will clear.";
+
+/** Below this a summed impact is rounding, not a deduction. */
+const IMPACT_EPSILON = 0.005;
+
+/**
+ * One sentence that says how bad the file is and why, built from the
+ * findings on screen and nothing else.
+ *
+ * At most two reasons, worst first, because a sentence listing five is a
+ * list. A missing test file is added only when it was measured as missing and
+ * there is room, and it is phrased as "no test file was found", because
+ * absence of a paired file is not proof that nothing tests the code.
+ *
+ * The all-clear is said only when it is true: the findings are loaded, the
+ * open ones left take nothing off, and the band agrees. A low score with no
+ * open issue on hand (still loading, failed, or just triaged) gets no
+ * positive claim.
+ */
+export function fileVerdict(input: VerdictInput): Verdict {
+ if (input.historyOnly) return { text: HISTORY_VERDICT, healthy: false };
+ return input.top.length === 0 ? nothingLeadsVerdict(input) : reasonsVerdict(input);
+}
+
+/** Nothing leads: say only what the findings on hand support. */
+function nothingLeadsVerdict({
+ score,
+ findingsKnown = true,
+ rest = { count: 0, impact: 0, historyImpact: 0 },
+}: VerdictInput): Verdict {
+ if (!findingsKnown) return { text: null, healthy: false };
+ if (rest.impact > IMPACT_EPSILON) {
+ const allHistory = rest.historyImpact >= rest.impact - IMPACT_EPSILON;
+ return {
+ text: allHistory ? HISTORY_VERDICT : "Its score comes from the issues listed in this panel.",
+ healthy: false,
+ };
+ }
+ const band = score == null ? null : bandForScore(score);
+ if (band !== "excellent" && band !== "good") {
+ return { text: "No open issue on hand explains this score.", healthy: false };
+ }
+ return {
+ text: rest.count > 0 ? "Nothing here takes points off its score." : "Nothing needs fixing here.",
+ healthy: true,
+ };
+}
+
+/** The leading problems, grouped by kind in the order of the worst finding. */
+function kindsOf(top: VerdictInput["top"]) {
+ const kinds = new Map<BiomarkerCategory, { functions: Set<string>; biomarkers: Set<string> }>();
+ for (const f of top) {
+ if (isHistoryBiomarker(f.biomarker_type)) continue;
+ const raw = biomarkerInfo(f.biomarker_type).category;
+ // Size and shape read as one kind of problem to a reader.
+ const kind: BiomarkerCategory = raw === "size_and_complexity" ? "structural_complexity" : raw;
+ let entry = kinds.get(kind);
+ if (!entry) {
+ entry = { functions: new Set(), biomarkers: new Set() };
+ kinds.set(kind, entry);
+ }
+ entry.functions.add(f.function_name ?? "");
+ entry.biomarkers.add(f.biomarker_type);
+ }
+ return kinds;
+}
+
+/** "<band lead>: <at most two reasons>." */
+function reasonsVerdict({ score, top, hasTestFile }: VerdictInput): Verdict {
+ const lead = score == null ? "Worth a look" : BAND_LEAD[bandForScore(score)];
+ const kinds = kindsOf(top);
+ const parts = [...kinds.entries()]
+ .slice(0, 2)
+ .map(([kind, e]) =>
+ clause(kind, Math.max(1, e.functions.size), [...e.biomarkers].every((b) => b === "large_method")),
+ );
+ if (parts.length < 2 && hasTestFile === false && !kinds.has("test_coverage")) {
+ parts.push("no test file was found for it");
+ }
+ const text = parts.length === 0 ? `${lead}.` : `${lead}: ${parts.join(" and ")}.`;
+ return { text, healthy: false };
+}
diff --git a/packages/ui/src/health/related-work.tsx b/packages/ui/src/health/related-work.tsx
index 6c9c1e584..8c68416f6 100644
--- a/packages/ui/src/health/related-work.tsx
+++ b/packages/ui/src/health/related-work.tsx
@@ -12,7 +12,7 @@
* supplied no data, so an absent section is never read as "clean elsewhere".
*/
-import * as React from "react";
+import useSWR from "swr";
import type {
RelatedWorkFile,
@@ -40,41 +40,51 @@ export interface RelatedWorkSlotProps {
relatedWorkHref?: RelatedWorkHref | undefined;
/** Host navigation, for a surface that routes rather than follows an anchor. */
onNavigate?: ((href: string) => void) | undefined;
+ /** The lookup failed (`useRelatedWorkQuery`), so the drawer can say so and retry. */
+ relatedError?: unknown;
+ onRelatedRetry?: (() => void) | undefined;
+}
+
+/** The related-work lookup with its failure, for a surface that says so. */
+export interface RelatedWorkQuery {
+ data: RelatedWorkResponse | undefined;
+ error: unknown;
+ retry: () => void;
}
/**
- * Fetch what every lens holds for these files, once per set of paths.
+ * Fetch what every lens holds for these files, cached per fetcher and set of
+ * paths, so reopening a file a reader already looked at costs no request.
*
- * Same contract as `useFileOpportunity`: `undefined` while not asked, when
- * the host cannot ask, or when the lookup failed, so a caller never renders a
- * claim it has not established. Pass a stable `fetcher`.
+ * The fetcher's identity is part of the cache key: it closes over the repo,
+ * and two repos must never share an entry. Pass a stable `fetcher`.
*/
-export function useRelatedWork(
+export function useRelatedWorkQuery(
fetcher: ((filePaths: string[]) => Promise<RelatedWorkResponse>) | undefined,
filePaths: readonly (string | null | undefined)[],
-): RelatedWorkResponse | undefined {
- const [value, setValue] = React.useState<RelatedWorkResponse | undefined>(undefined);
+): RelatedWorkQuery {
// The one key: the paths in order. A new array with the same paths is the
// same request.
const key = filePaths.filter((p): p is string => Boolean(p)).join("\n");
+ const { data, error, mutate } = useSWR(
+ fetcher && key ? ["related-work", fetcher, key] : null,
+ () => fetcher!(key.split("\n")),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+ return { data, error, retry: () => void mutate() };
+}
- React.useEffect(() => {
- setValue(undefined);
- if (!fetcher || !key) return;
- let live = true;
- void fetcher(key.split("\n"))
- .then((result) => {
- if (live) setValue(result);
- })
- .catch(() => {
- if (live) setValue(undefined);
- });
- return () => {
- live = false;
- };
- }, [fetcher, key]);
-
- return value;
+/**
+ * {@link useRelatedWorkQuery} without the failure: `undefined` while not
+ * asked, when the host cannot ask, or when the lookup failed, so a caller
+ * never renders a claim it has not established.
+ */
+export function useRelatedWork(
+ fetcher: ((filePaths: string[]) => Promise<RelatedWorkResponse>) | undefined,
+ filePaths: readonly (string | null | undefined)[],
+): RelatedWorkResponse | undefined {
+ const { data, error } = useRelatedWorkQuery(fetcher, filePaths);
+ return error ? undefined : data;
}
/** Every lens, in the order the server lists them. */
@@ -144,6 +154,27 @@ export interface RelatedWorkProps extends RelatedWorkSlotProps {
exclude?: readonly RelatedLensName[] | undefined;
/** Heading level, so the section nests under the drawer's own headings. */
headingLevel?: "h3" | "h4" | undefined;
+ /** Drop the heading, for a host whose disclosure already names the section. */
+ hideHeading?: boolean | undefined;
+}
+
+/** Items the section would list, so a collapsed host can say how many. */
+export function relatedWorkCount(
+ related: RelatedWorkFile | null | undefined,
+ exclude: readonly RelatedLensName[] = [],
+): { items: number; lenses: number } {
+ let items = 0;
+ let lenses = 0;
+ for (const name of RELATED_LENSES) {
+ if (exclude.includes(name)) continue;
+ const lens = related?.lenses?.[name];
+ const n = lens?.items?.length ? (lens.total ?? lens.items.length) : 0;
+ if (n > 0) {
+ items += n;
+ lenses += 1;
+ }
+ }
+ return { items, lenses };
}
export function RelatedWork({
@@ -152,6 +183,7 @@ export function RelatedWork({
onNavigate,
exclude = [],
headingLevel = "h3",
+ hideHeading = false,
}: RelatedWorkProps) {
const lenses = RELATED_LENSES.filter((name) => !exclude.includes(name))
.map((name) => [name, related?.lenses?.[name]] as const)
@@ -163,16 +195,18 @@ export function RelatedWork({
const Heading = headingLevel;
return (
<section className="flex flex-col gap-2" aria-label="Elsewhere for this file">
- <Heading className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Elsewhere for this file
- </Heading>
+ {hideHeading ? null : (
+ <Heading className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Elsewhere for this file
+ </Heading>
+ )}
<div className="flex flex-col gap-3">
{lenses.map(([name, lens]) => {
const items = lens.items ?? [];
const total = lens.total ?? items.length;
return (
<div key={name} className="flex flex-col gap-1">
- <p className="text-[11px] font-medium text-[var(--color-text-secondary)]">
+ <p className="text-xs font-medium text-[var(--color-text-secondary)]">
{RELATED_LENS_LABEL[name]}{" "}
<span className="font-normal tabular-nums text-[var(--color-text-tertiary)]">
{items.length < total
@@ -232,7 +266,7 @@ function RelatedRow({
}
: (e) => e.stopPropagation()
}
- className="flex items-baseline gap-2 rounded text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)]"
+ className="flex items-baseline gap-2 rounded text-[var(--color-text-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)]"
>
{text}
</a>
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index de18e14bf..a14ce10c3 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -49,12 +49,16 @@ export interface ScoreBreakdownProps {
score: number;
totalDeduction: number;
categories: ScoreBreakdownCategory[];
+ /** List each category's findings under its bar. Default true; a surface
+ * that already lists the findings turns it off. */
+ showFindings?: boolean;
}
export function ScoreBreakdown({
score,
totalDeduction,
categories,
+ showFindings = true,
}: ScoreBreakdownProps) {
return (
<div className="space-y-3">
@@ -127,7 +131,7 @@ export function ScoreBreakdown({
}}
/>
</div>
- {c.findings.length > 0 && (
+ {showFindings && c.findings.length > 0 && (
<ul className="mt-2 space-y-1">
{c.findings.slice(0, 6).map((f) => (
<li
diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.ts
index 7ca645179..88870befa 100644
--- a/packages/ui/src/health/tokens.ts
+++ b/packages/ui/src/health/tokens.ts
@@ -156,6 +156,55 @@ export function healthNodeFill(score: number): string {
return HEALTH_BAND_NODE_FILL[bandForScore(score)];
}
+/**
+ * The map's fills: the five canonical bands, softened.
+ *
+ * The same bands every score pill on the page uses, so a dot and the pill
+ * beside it never disagree. Each band's node token is pulled a little toward
+ * the neutral, so a field of thousands reads as pigment rather than as light.
+ * Five fills also keep the canvas at five draw batches.
+ */
+function softened(token: string): string {
+ return `color-mix(in srgb, var(${token}) 82%, var(--color-node-neutral))`;
+}
+
+const NODE_BAND_FILL: Record<HealthBand, string> = {
+ excellent: softened("--color-node-excellent"),
+ good: softened("--color-node-good"),
+ fair: softened("--color-node-fair"),
+ needs_work: softened("--color-node-needs-work"),
+ at_risk: softened("--color-node-at-risk"),
+};
+
+/** The fill for a file that needs nothing under a banded lens. */
+export const NODE_HEALTHY_FILL = NODE_BAND_FILL.good;
+
+/** Three problem stops, for banded lenses (coverage, churn, performance). */
+export const NODE_RAMP_STOP = {
+ warning: NODE_BAND_FILL.fair,
+ serious: NODE_BAND_FILL.needs_work,
+ alert: NODE_BAND_FILL.at_risk,
+} as const;
+
+/** The map fill for a 1-10 score, on the canonical band. */
+export function healthRampFill(score: number): string {
+ return NODE_BAND_FILL[bandForScore(score)];
+}
+
+/** The map fill for a band, for keys. */
+export function healthBandMapFill(band: HealthBand): string {
+ return NODE_BAND_FILL[band];
+}
+
+/**
+ * Whether a map fill marks a file that needs attention, which is what earns a
+ * glow and a place in the "needs attention" count: the Needs work and At risk
+ * fills. Green, gold and the neutral stay quiet.
+ */
+export function isLoudFill(fill: string): boolean {
+ return fill === NODE_BAND_FILL.needs_work || fill === NODE_BAND_FILL.at_risk;
+}
+
export function healthBandColor(band: HealthBand): string {
return HEALTH_BAND_VAR[band];
}
diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsx
index abc08b240..7c35962cc 100644
--- a/packages/ui/src/health/trend-chart.tsx
+++ b/packages/ui/src/health/trend-chart.tsx
@@ -1,7 +1,13 @@
"use client";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { KeyboardEvent, PointerEvent, RefObject } from "react";
+import { HEALTHY_MIN, NEEDS_WORK_MIN, formatScore } from "@repowise-dev/types/health";
+
import { EmptyState } from "../shared/empty-state";
+import { seriesColor } from "../shared/series";
import { formatDate } from "../lib/format";
+import { deltaColor, formatDelta } from "./tokens";
export interface TrendSeriesPoint {
taken_at: string | null;
@@ -30,6 +36,43 @@ type LineKey =
| "worst_performer_score"
| "maintainability_average";
+interface Series {
+ key: LineKey;
+ label: string;
+ color: string;
+ dash?: string;
+}
+
+/**
+ * Identity, not verdict: health is the background bands' job, so a series at
+ * 3 is not drawn in green. Each series keeps its colour whatever else is
+ * shown. The three KPIs take the first three chart hues in order; the worst
+ * file stays in ink and is dashed, so it is told apart without colour.
+ */
+const LINES: Record<LineKey, Series> = {
+ maintainability_average: { key: "maintainability_average", label: "Maintainability", color: seriesColor(1) },
+ average_health: { key: "average_health", label: "Code health", color: seriesColor(0) },
+ hotspot_health: { key: "hotspot_health", label: "Hotspot", color: seriesColor(2) },
+ worst_performer_score: {
+ key: "worst_performer_score",
+ label: "Worst file",
+ color: "var(--color-text-tertiary)",
+ dash: "4 3",
+ },
+};
+
+/** The canonical three bands, top to bottom, as faint grounds behind the lines. */
+const BANDS = [
+ { label: "Healthy", from: 10, to: HEALTHY_MIN, fill: "var(--color-success)" },
+ { label: "Warning", from: HEALTHY_MIN, to: NEEDS_WORK_MIN, fill: "var(--color-warning)" },
+ { label: "Alert", from: NEEDS_WORK_MIN, to: 0, fill: "var(--color-error)" },
+] as const;
+
+// The right pad holds the band names, outside the lines they would collide with.
+const PAD = { l: 28, r: 56, t: 10, b: 24 };
+/** Until the container is measured (and in tests, which have no layout). */
+const FALLBACK_WIDTH = 720;
+
/**
* Index ranges over which *has* holds without a gap.
*
@@ -51,192 +94,584 @@ function runs<T>(items: T[], has: (item: T) => boolean): number[][] {
return out;
}
-export function TrendChart({ history, height = 220 }: TrendChartProps) {
- if (!history || history.length === 0) {
- return (
- <EmptyState
- size="compact"
- title="No snapshots yet"
- description="Each index update records one, and the trend appears from the second."
- />
- );
- }
+function value(p: TrendSeriesPoint, key: LineKey): number | null {
+ return p[key] ?? null;
+}
- const W = 720;
- const H = height;
- const padL = 36;
- const padR = 12;
- const padT = 12;
- const padB = 26;
- const plotW = W - padL - padR;
- const plotH = H - padT - padB;
-
- const xScale = (i: number) =>
- history.length === 1 ? padL + plotW / 2 : padL + (i / (history.length - 1)) * plotW;
- const yScale = (v: number) => padT + ((10 - v) / 10) * plotH;
-
- const path = (key: LineKey) => {
- const pts: [number, number][] = [];
- history.forEach((p, i) => {
- const v = p[key];
- if (v == null) return;
- pts.push([xScale(i), yScale(v as number)]);
- });
- return pts.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(" ");
- };
+/** Evenly spaced snapshot indices for the date axis, about one per 120px. */
+function tickIndices(n: number, plotW: number): number[] {
+ if (n <= 1) return [0];
+ const count = Math.max(2, Math.min(n, Math.floor(plotW / 120) + 1));
+ return [...new Set(Array.from({ length: count }, (_, k) => Math.round((k * (n - 1)) / (count - 1))))];
+}
- const hasMaintainability = history.some((p) => p.maintainability_average != null);
- // Maintainability leads wherever it was recorded. It is the series that
- // answers "is my code getting better", and the composite it sits beside
- // moves with git history too, so drawing the composite loudest emphasises
- // the number that misleads. Without a maintainability series the composite
- // is the only headline there is, and keeps the weight.
- const leadWidth = 2.4;
- const supportWidth = hasMaintainability ? 1.4 : 1.8;
+interface Geometry {
+ width: number;
+ height: number;
+ plotW: number;
+ x: (i: number) => number;
+ y: (v: number) => number;
+ paths: Record<LineKey, string>;
+ historyBands: string[];
+ ticks: { i: number; label: string }[];
+}
+
+/**
+ * The dated ticks, one per label: several snapshots a day would otherwise
+ * print the same date twice. The newest tick is the one kept.
+ */
+function dateTicks(history: TrendSeriesPoint[], indices: number[]): { i: number; label: string }[] {
+ const out: { i: number; label: string }[] = [];
+ for (const i of [...indices].reverse()) {
+ const at = history[i]?.taken_at;
+ if (!at) continue;
+ const label = formatDate(at);
+ if (out[0]?.label !== label) out.unshift({ i, label });
+ }
+ return out;
+}
+function geometry(history: TrendSeriesPoint[], width: number, height: number): Geometry {
+ const plotW = Math.max(1, width - PAD.l - PAD.r);
+ const plotH = Math.max(1, height - PAD.t - PAD.b);
+ const n = history.length;
+ const x = (i: number) => (n === 1 ? PAD.l + plotW / 2 : PAD.l + (i / (n - 1)) * plotW);
+ const y = (v: number) => PAD.t + ((10 - v) / 10) * plotH;
+ const path = (key: LineKey) =>
+ runs(history, (p) => value(p, key) != null)
+ .map((run) => run.map((i, j) => `${j === 0 ? "M" : "L"}${x(i)},${y(value(history[i]!, key)!)}`).join(" "))
+ .join(" ");
// The band between the score history does not touch and the score itself:
- // what git history costs, drawn where the lede says it in words. Only over
- // runs of snapshots that recorded the split.
+ // what git history costs, drawn where the readout says it in words.
const historyBands = runs(history, (p) => p.history_average != null).map((run) =>
[
- ...run.map((i) => {
+ ...run.map((i, j) => {
const p = history[i]!;
// Clamped: the two halves are means of deductions while the score is
// a mean of clamped scores, so on a repo with a floored file they can
// sum past 10 and the edge would leave the plot.
- return `${run[0] === i ? "M" : "L"}${xScale(i)},${yScale(
- Math.min(10, p.average_health + (p.history_average as number)),
- )}`;
+ return `${j === 0 ? "M" : "L"}${x(i)},${y(Math.min(10, p.average_health + p.history_average!))}`;
}),
- ...[...run].reverse().map((i) => `L${xScale(i)},${yScale(history[i]!.average_health)}`),
+ ...[...run].reverse().map((i) => `L${x(i)},${y(history[i]!.average_health)}`),
"Z",
].join(" "),
);
+ return {
+ width,
+ height,
+ plotW,
+ x,
+ y,
+ paths: {
+ average_health: path("average_health"),
+ hotspot_health: path("hotspot_health"),
+ worst_performer_score: path("worst_performer_score"),
+ maintainability_average: path("maintainability_average"),
+ },
+ historyBands,
+ ticks: dateTicks(history, tickIndices(n, plotW)),
+ };
+}
+const MICRO = { fontSize: 10, fill: "var(--color-text-tertiary)" } as const;
+
+/** The three health bands, named in the right margin. */
+function Bands({ g }: { g: Geometry }) {
+ return BANDS.map((b) => (
+ <g key={b.label}>
+ <rect x={PAD.l} width={g.plotW} y={g.y(b.from)} height={g.y(b.to) - g.y(b.from)} fill={b.fill} fillOpacity={0.06} />
+ <text x={PAD.l + g.plotW + 6} y={(g.y(b.from) + g.y(b.to)) / 2 + 3} textAnchor="start" {...MICRO}>
+ {b.label}
+ </text>
+ </g>
+ ));
+}
+
+/** The score gridlines and the date ticks. */
+function Axes({ g }: { g: Geometry }) {
return (
- // No card. The chart sits inside a section that already names it, so a
- // border here is a second frame around content that has one.
- <div className="flex flex-col">
- <div className="mb-2 flex items-center justify-between gap-4">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- KPI trend
- </h3>
- <div className="flex flex-wrap items-center gap-3 text-xs text-[var(--color-text-tertiary)]">
- {hasMaintainability && (
- <Legend dot="bg-[var(--color-accent-secondary)]" label="Maintainability" />
- )}
- <Legend dot="bg-[var(--color-success)]" label="Code health" />
- {historyBands.length > 0 && (
- <span className="inline-flex items-center gap-1">
- <span className="inline-block h-2 w-2 rounded-[1px] bg-current opacity-25" />
- History drag
- </span>
- )}
- <Legend dot="bg-[var(--color-warning)]" label="Hotspot" />
- <Legend dot="bg-[var(--color-error)]" label="Worst" />
- </div>
- </div>
- <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Health KPI trend">
- {/* Y grid */}
- {[0, 2, 4, 6, 8, 10].map((v) => (
- <g key={v}>
- <line x1={padL} x2={W - padR} y1={yScale(v)} y2={yScale(v)} stroke="currentColor" strokeOpacity={0.08} />
- <text x={padL - 6} y={yScale(v) + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>
- {v}
- </text>
- </g>
- ))}
- {/* Under the lines: the band is context for them, not a mark of its own.
- Its edges are stroked in the code-health colour because the band
- belongs to that line — it runs from the score up to where the score
- would sit with no history against it. Unstroked, it read as bounding
- whichever line happened to fall inside it. The lower edge lies on the
- code-health line itself, so only the upper one shows. */}
- {historyBands.map((d, i) => (
- <path
- key={i}
- d={d}
- fill="currentColor"
- fillOpacity={0.07}
- stroke="var(--color-success)"
- strokeOpacity={0.35}
- strokeWidth={1}
- strokeDasharray="2 3"
+ <>
+ {[0, 2, 4, 6, 8, 10].map((v) => (
+ <g key={v}>
+ <line x1={PAD.l} x2={PAD.l + g.plotW} y1={g.y(v)} y2={g.y(v)} stroke="currentColor" strokeOpacity={0.08} />
+ <text x={PAD.l - 6} y={g.y(v) + 3} textAnchor="end" {...MICRO}>
+ {v}
+ </text>
+ </g>
+ ))}
+ {g.ticks.map(({ i, label }, k) => (
+ <text
+ key={i}
+ x={g.x(i)}
+ y={g.height - 6}
+ textAnchor={k === 0 ? "start" : k === g.ticks.length - 1 ? "end" : "middle"}
+ {...MICRO}
+ >
+ {label}
+ </text>
+ ))}
+ </>
+ );
+}
+
+/**
+ * Under the lines: the band is context for the code-health line, so its upper
+ * edge takes that line's colour and dims with it.
+ */
+function HistoryDrag({ g, opacity }: { g: Geometry; opacity: number }) {
+ return g.historyBands.map((d, i) => (
+ <path
+ key={i}
+ d={d}
+ fill="currentColor"
+ fillOpacity={0.07}
+ stroke={LINES.average_health.color}
+ strokeOpacity={0.4 * opacity}
+ strokeWidth={1}
+ strokeDasharray="2 3"
+ />
+ ));
+}
+
+function Line({ g, history, s, lead }: { g: Geometry; history: TrendSeriesPoint[]; s: Series; lead: boolean }) {
+ return (
+ <>
+ <path
+ d={g.paths[s.key]}
+ stroke={s.color}
+ strokeWidth={lead ? 2.5 : 1.5}
+ strokeDasharray={s.dash}
+ fill="none"
+ strokeLinejoin="round"
+ />
+ {history.map((p, i) => {
+ const v = value(p, s.key);
+ return v == null ? null : <circle key={i} cx={g.x(i)} cy={g.y(v)} r={2} fill={s.color} />;
+ })}
+ </>
+ );
+}
+
+/** Bands, axes and lines: everything that does not move with the pointer. */
+const Plot = memo(function Plot({
+ g,
+ history,
+ series,
+ lead,
+ emphasis,
+}: {
+ g: Geometry;
+ history: TrendSeriesPoint[];
+ series: Series[];
+ lead: LineKey;
+ emphasis: LineKey | null;
+}) {
+ const opacity = (key: LineKey) => (emphasis && emphasis !== key ? 0.2 : 1);
+ // The lead last, so a support line never crosses it out.
+ const ordered = [...series].sort((a, b) => Number(a.key === lead) - Number(b.key === lead));
+ return (
+ <>
+ <Bands g={g} />
+ <Axes g={g} />
+ {series.some((s) => s.key === "average_health") && (
+ <HistoryDrag g={g} opacity={opacity("average_health")} />
+ )}
+ {ordered.map((s) => (
+ <g key={s.key} opacity={opacity(s.key)}>
+ <Line g={g} history={history} s={s} lead={s.key === lead} />
+ </g>
+ ))}
+ </>
+ );
+});
+
+type ReadoutRow = { series: Series; value: number; delta: number | null };
+
+/** One line of the readout per shown series, in the order the legend lists them. */
+function readoutRows(history: TrendSeriesPoint[], i: number, series: Series[]): ReadoutRow[] {
+ const p = history[i]!;
+ const prev = i > 0 ? history[i - 1]! : null;
+ return series.flatMap((s) => {
+ const v = value(p, s.key);
+ if (v == null) return [];
+ const before = prev ? value(prev, s.key) : null;
+ return [{ series: s, value: v, delta: before == null ? null : v - before }];
+ });
+}
+
+function historyWords(p: TrendSeriesPoint): string | null {
+ if (p.history_average == null) return null;
+ return `Change history takes ${p.history_average.toFixed(2)} points off code health.`;
+}
+
+/** The readout as one sentence, for the live region keyboard steps update. */
+function announce(history: TrendSeriesPoint[], i: number, series: Series[]): string {
+ const p = history[i]!;
+ const parts = readoutRows(history, i, series).map(
+ (r) => `${r.series.label} ${formatScore(r.value)}${r.delta == null ? "" : `, ${formatDelta(r.delta)}`}`,
+ );
+ const when = p.taken_at ? formatDate(p.taken_at) : "Undated snapshot";
+ return [`${when}, snapshot ${i + 1} of ${history.length}.`, `${parts.join("; ")}.`, historyWords(p)]
+ .filter(Boolean)
+ .join(" ");
+}
+
+/** The snapshot a key moves to from *from*, or `null` for a key that steps nowhere. */
+function keyStep(key: string, from: number, last: number): number | null {
+ if (key === "ArrowLeft") return Math.max(0, from - 1);
+ if (key === "ArrowRight") return Math.min(last, from + 1);
+ if (key === "Home") return 0;
+ if (key === "End") return last;
+ return null;
+}
+
+/** The container's width, so the chart is sized rather than scaled and 10px labels stay 10px. */
+function useChartSize(ref: RefObject<HTMLElement | null>): number {
+ const [width, setWidth] = useState(FALLBACK_WIDTH);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver((entries) => {
+ const w = Math.round(entries[0]?.contentRect.width ?? 0);
+ if (w > 0) setWidth(w);
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [ref]);
+ return width;
+}
+
+/** Which series the history carries, which are drawn, and the legend's toggle. */
+function useSeriesVisibility(history: TrendSeriesPoint[]) {
+ const [hidden, setHidden] = useState<ReadonlySet<LineKey>>(() => new Set());
+ const available = useMemo(() => {
+ const has = (key: LineKey) => history.some((p) => value(p, key) != null);
+ return (["maintainability_average", "average_health", "hotspot_health", "worst_performer_score"] as const)
+ .filter((key) => key === "average_health" || has(key))
+ .map((key) => LINES[key]);
+ }, [history]);
+ // A new history can drop the series left on, so an empty pick falls back to
+ // every series rather than drawing a blank plot.
+ const shown = useMemo(() => {
+ const picked = available.filter((s) => !hidden.has(s.key));
+ return picked.length > 0 ? picked : available;
+ }, [available, hidden]);
+ // Flipped from what is drawn, not from the stored set, so a fallback to
+ // every series cannot turn a click on one into hiding all the others.
+ const toggle = (key: LineKey) => {
+ const next = new Set(available.filter((s) => !shown.includes(s)).map((s) => s.key));
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ setHidden(next);
+ };
+ // Maintainability leads wherever it was recorded. It is the series that
+ // answers "is my code getting better", and the composite beside it moves
+ // with git history too, so drawing the composite loudest emphasises the
+ // number that misleads.
+ const lead: LineKey = available.some((s) => s.key === "maintainability_average")
+ ? "maintainability_average"
+ : "average_health";
+ return { available, shown, toggle, lead };
+}
+
+/**
+ * Pointer handlers that move the active snapshot, at most once a frame. A tap
+ * shows the readout, so a touch leaving the plot does not clear it.
+ */
+function usePointerSnapshot(
+ setActive: (update: (prev: number | null) => number | null) => void,
+ last: number,
+ plotW: number,
+) {
+ const frame = useRef<number | null>(null);
+ const pointerX = useRef(0);
+ useEffect(
+ () => () => {
+ if (frame.current != null) cancelAnimationFrame(frame.current);
+ },
+ [],
+ );
+ const nearest = (clientX: number, el: Element) => {
+ const t = last === 0 ? 0 : (clientX - el.getBoundingClientRect().left - PAD.l) / plotW;
+ return Math.max(0, Math.min(last, Math.round(t * last)));
+ };
+ const onPointerMove = (e: PointerEvent<SVGSVGElement>) => {
+ pointerX.current = e.clientX;
+ if (frame.current != null) return;
+ const el = e.currentTarget;
+ frame.current = requestAnimationFrame(() => {
+ frame.current = null;
+ const i = nearest(pointerX.current, el);
+ setActive((prev) => (prev === i ? prev : i));
+ });
+ };
+ const onPointerLeave = (e: PointerEvent<SVGSVGElement>) => {
+ if (e.pointerType === "touch") return;
+ if (frame.current != null) cancelAnimationFrame(frame.current);
+ frame.current = null;
+ setActive(() => null);
+ };
+ return { onPointerMove, onPointerDown: onPointerMove, onPointerLeave };
+}
+
+/** Clears the active snapshot on a press outside *ref*, while one is held. */
+function useClearOnPressAway(ref: RefObject<HTMLElement | null>, held: boolean, clear: () => void) {
+ useEffect(() => {
+ if (!held) return;
+ const away = (e: globalThis.PointerEvent) => {
+ if (!ref.current?.contains(e.target as Node)) clear();
+ };
+ document.addEventListener("pointerdown", away);
+ return () => document.removeEventListener("pointerdown", away);
+ }, [held, ref, clear]);
+}
+
+/**
+ * The snapshot under the pointer or the keyboard cursor, the handlers that
+ * move it, and the sentence keyboard steps announce.
+ */
+function useActiveSnapshot(
+ boxRef: RefObject<HTMLElement | null>,
+ history: TrendSeriesPoint[],
+ shown: Series[],
+ plotW: number,
+) {
+ const [active, setActive] = useState<number | null>(null);
+ const [spoken, setSpoken] = useState("");
+ const last = history.length - 1;
+ // A shorter history can leave the held index past its end.
+ const at = active != null && active <= last ? active : null;
+ const svg = usePointerSnapshot(setActive, last, plotW);
+ const clear = useCallback(() => setActive(null), []);
+ useClearOnPressAway(boxRef, active != null, clear);
+
+ const step = (i: number) => {
+ setActive(i);
+ setSpoken(announce(history, i, shown));
+ };
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
+ const to = keyStep(e.key, at ?? last, last);
+ if (to != null) {
+ e.preventDefault();
+ step(to);
+ } else if (e.key === "Escape") clear();
+ };
+ const box = { onKeyDown, onFocus: () => active == null && step(last), onBlur: clear };
+ return { at, spoken, svg, box };
+}
+
+function Swatch({ s, width, dim = false }: { s: Series; width: number; dim?: boolean }) {
+ return (
+ <svg width={width} height="6" aria-hidden className={dim ? "opacity-40" : ""}>
+ <line x1="0" x2={width} y1="3" y2="3" stroke={s.color} strokeWidth={2} strokeDasharray={s.dash} />
+ </svg>
+ );
+}
+
+function LegendButton({
+ s,
+ on,
+ locked,
+ onToggle,
+ onEmphasis,
+}: {
+ s: Series;
+ on: boolean;
+ locked: boolean;
+ onToggle: (key: LineKey) => void;
+ onEmphasis: (key: LineKey | null) => void;
+}) {
+ const emphasise = () => on && onEmphasis(s.key);
+ return (
+ <button
+ type="button"
+ aria-pressed={on}
+ disabled={locked}
+ title={locked ? "At least one series stays on the chart" : undefined}
+ onClick={() => onToggle(s.key)}
+ onPointerEnter={emphasise}
+ onPointerLeave={() => onEmphasis(null)}
+ onFocus={emphasise}
+ onBlur={() => onEmphasis(null)}
+ className={`inline-flex items-center gap-1.5 rounded px-1.5 py-1 transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)] disabled:cursor-default ${
+ on ? "text-[var(--color-text-secondary)]" : "text-[var(--color-text-tertiary)] line-through"
+ }`}
+ >
+ <Swatch s={s} width={14} dim={!on} />
+ {s.label}
+ </button>
+ );
+}
+
+function Legend({
+ available,
+ shown,
+ drag,
+ onToggle,
+ onEmphasis,
+}: {
+ available: Series[];
+ shown: Series[];
+ /** Whether the history-drag band is drawn, so its key is listed. */
+ drag: boolean;
+ onToggle: (key: LineKey) => void;
+ onEmphasis: (key: LineKey | null) => void;
+}) {
+ return (
+ <div className="flex flex-wrap items-center gap-1 text-xs" role="group" aria-label="Series">
+ {available.map((s) => {
+ const on = shown.includes(s);
+ // The last series shown cannot be hidden: an empty plot answers nothing.
+ return (
+ <LegendButton
+ key={s.key}
+ s={s}
+ on={on}
+ locked={on && shown.length === 1}
+ onToggle={onToggle}
+ onEmphasis={onEmphasis}
/>
- ))}
- <path
- d={path("average_health")}
- stroke="var(--color-success)"
- strokeWidth={supportWidth}
- fill="none"
- />
- <path
- d={path("hotspot_health")}
- stroke="var(--color-warning)"
- strokeWidth={supportWidth}
- fill="none"
+ );
+ })}
+ {drag && (
+ <span className="inline-flex items-center gap-1.5 px-1.5 text-[var(--color-text-tertiary)]">
+ <span className="inline-block h-2 w-3 rounded-[1px] bg-current opacity-25" aria-hidden />
+ History drag
+ </span>
+ )}
+ </div>
+ );
+}
+
+function Crosshair({ g, x, rows }: { g: Geometry; x: number; rows: ReadoutRow[] }) {
+ return (
+ <g pointerEvents="none">
+ <line x1={x} x2={x} y1={PAD.t} y2={g.height - PAD.b} stroke="var(--color-text-tertiary)" strokeWidth={1} />
+ {rows.map((r) => (
+ <circle
+ key={r.series.key}
+ cx={x}
+ cy={g.y(r.value)}
+ r={4}
+ fill={r.series.color}
+ stroke="var(--color-bg-root)"
+ strokeWidth={2}
/>
- <path d={path("worst_performer_score")} stroke="var(--color-error)" strokeWidth={1.4} fill="none" strokeDasharray="3 3" />
- {/* Last, so the lead series is never crossed out by a support line. */}
- {hasMaintainability && (
- <path
- d={path("maintainability_average")}
- stroke="var(--color-accent-secondary)"
- strokeWidth={leadWidth}
- fill="none"
- />
- )}
- {history.map((p, i) => (
- <g key={i}>
- <circle
- cx={xScale(i)}
- cy={yScale(p.average_health)}
- r={hasMaintainability ? 2 : 2.5}
- fill="var(--color-success)"
- />
- {p.hotspot_health != null ? (
- <circle
- cx={xScale(i)}
- cy={yScale(p.hotspot_health)}
- r={hasMaintainability ? 2 : 2.5}
- fill="var(--color-warning)"
- />
- ) : null}
- {p.worst_performer_score != null ? (
- <circle cx={xScale(i)} cy={yScale(p.worst_performer_score)} r={2} fill="var(--color-error)" />
- ) : null}
- {p.maintainability_average != null ? (
- <circle
- cx={xScale(i)}
- cy={yScale(p.maintainability_average)}
- r={3}
- fill="var(--color-accent-secondary)"
- />
- ) : null}
- </g>
+ ))}
+ </g>
+ );
+}
+
+function ReadoutLine({ r }: { r: ReadoutRow }) {
+ const tone = deltaColor(r.delta == null ? null : Number(r.delta.toFixed(2)));
+ return (
+ <div className="contents">
+ <dt className="inline-flex items-center gap-1.5 text-[var(--color-text-secondary)]">
+ <Swatch s={r.series} width={10} />
+ {r.series.label}
+ </dt>
+ <dd className="text-right font-mono tabular-nums text-[var(--color-text-primary)]">{formatScore(r.value)}</dd>
+ <dd className={`text-right font-mono tabular-nums ${tone}`}>{r.delta == null ? "" : formatDelta(r.delta)}</dd>
+ </div>
+ );
+}
+
+function Readout({
+ g,
+ x,
+ at,
+ history,
+ rows,
+}: {
+ g: Geometry;
+ x: number;
+ at: number;
+ history: TrendSeriesPoint[];
+ rows: ReadoutRow[];
+}) {
+ const point = history[at]!;
+ const width = Math.min(250, g.width - 8);
+ // Beside the crosshair on the roomier side, clamped inside the plot so a
+ // narrow screen never pushes it past an edge.
+ const left = Math.max(4, Math.min(g.width - width - 4, x > g.width / 2 ? x - 12 - width : x + 12));
+ const words = historyWords(point);
+ return (
+ <div
+ className="pointer-events-none absolute top-1 z-10 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-2.5 py-2 text-xs shadow-md"
+ style={{ width, left }}
+ >
+ <p className="mb-1 flex items-baseline justify-between gap-3 text-[var(--color-text-primary)]">
+ <span>{point.taken_at ? formatDate(point.taken_at) : "Undated snapshot"}</span>
+ <span className="font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {at + 1} of {history.length}
+ </span>
+ </p>
+ <dl className="grid grid-cols-[auto_auto_auto] items-center gap-x-3 gap-y-0.5">
+ {rows.map((r) => (
+ <ReadoutLine key={r.series.key} r={r} />
))}
- {history.length > 1 ? (
- <>
- <text x={padL} y={H - 8} fontSize={10} fill="currentColor" opacity={0.5}>
- {history[0]?.taken_at ? formatDate(history[0]!.taken_at!) : ""}
- </text>
- <text x={W - padR} y={H - 8} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>
- {history[history.length - 1]?.taken_at
- ? formatDate(history[history.length - 1]!.taken_at!)
- : ""}
- </text>
- </>
- ) : null}
- </svg>
+ </dl>
+ {words && <p className="mt-1 text-[var(--color-text-tertiary)]">{words}</p>}
</div>
);
}
-function Legend({ dot, label }: { dot: string; label: string }) {
+export function TrendChart({ history, height = 220 }: TrendChartProps) {
+ const boxRef = useRef<HTMLDivElement>(null);
+ const width = useChartSize(boxRef);
+ const [emphasis, setEmphasis] = useState<LineKey | null>(null);
+ const g = useMemo(() => geometry(history, width, height), [history, width, height]);
+ const { available, shown, toggle, lead } = useSeriesVisibility(history);
+ const { at, spoken, svg, box } = useActiveSnapshot(boxRef, history, shown, g.plotW);
+
+ if (!history || history.length === 0) {
+ return (
+ <EmptyState
+ size="compact"
+ title="No snapshots yet"
+ description="Each index update records one, and the trend appears from the second."
+ />
+ );
+ }
+
+ const rows = at == null ? [] : readoutRows(history, at, shown);
+ const x = at == null ? 0 : g.x(at);
+ const drag = g.historyBands.length > 0 && shown.some((s) => s.key === "average_health");
+
return (
- <span className="inline-flex items-center gap-1">
- <span className={`inline-block h-2 w-2 rounded-full ${dot}`} />
- {label}
- </span>
+ // No card. The chart sits inside a section that already names it, so a
+ // border here is a second frame around content that has one.
+ <div className="flex flex-col">
+ <div className="mb-2 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ KPI trend
+ </h3>
+ <Legend available={available} shown={shown} drag={drag} onToggle={toggle} onEmphasis={setEmphasis} />
+ </div>
+ <div
+ ref={boxRef}
+ tabIndex={0}
+ role="group"
+ aria-label="Health KPI trend. Arrow keys step through snapshots."
+ {...box}
+ className="relative rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-accent-primary)]"
+ >
+ <svg
+ width={g.width}
+ height={g.height}
+ viewBox={`0 0 ${g.width} ${g.height}`}
+ className="block max-w-full touch-pan-y"
+ aria-hidden
+ {...svg}
+ >
+ <Plot g={g} history={history} series={shown} lead={lead} emphasis={emphasis} />
+ {at != null && <Crosshair g={g} x={x} rows={rows} />}
+ </svg>
+ {at != null && <Readout g={g} x={x} at={at} history={history} rows={rows} />}
+ <p className="sr-only" aria-live="polite">
+ {spoken}
+ </p>
+ </div>
+ </div>
);
}
diff --git a/packages/ui/src/health/trend-slope-chart.tsx b/packages/ui/src/health/trend-slope-chart.tsx
deleted file mode 100644
index 84d76502c..000000000
--- a/packages/ui/src/health/trend-slope-chart.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-"use client";
-
-import { useMemo, useState } from "react";
-import { healthInk } from "./tokens";
-
-export interface TrendSlopePoint {
- file_path: string;
- before: number;
- after: number;
- delta: number;
-}
-
-export interface TrendSlopeChartProps {
- points: TrendSlopePoint[];
- height?: number;
- /** Cap the number of slopes drawn (largest |delta| first). */
- max?: number;
-}
-
-/**
- * Slope chart for "largest score changes" — each file is a line from its
- * before-score to its after-score across two snapshot columns. Declines drop,
- * improvements rise; colour follows the after-score health band. Replaces the
- * Before/After/Δ table (movement is read positionally, not parsed row by row).
- */
-export function TrendSlopeChart({ points, height = 320, max = 18 }: TrendSlopeChartProps) {
- const [hovered, setHovered] = useState<TrendSlopePoint | null>(null);
-
- const data = useMemo(
- () =>
- [...points]
- .sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta))
- .slice(0, max),
- [points, max],
- );
-
- if (data.length === 0) {
- return (
- <p className="text-sm text-[var(--color-text-secondary)]">
- No per-file score changes to plot yet.
- </p>
- );
- }
-
- const W = 640;
- const H = height;
- const padT = 16;
- const padB = 28;
- const xBefore = 140;
- const xAfter = W - 140;
- const plotH = H - padT - padB;
-
- // Fixed 0–10 health domain so the slope angle is meaningful across renders.
- const yScale = (score: number) => padT + ((10 - Math.max(0, Math.min(10, score))) / 10) * plotH;
-
- return (
- // No card: the section heading above already frames this.
- <div className="relative">
- <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Score change slope chart">
- {/* Axis columns */}
- <line x1={xBefore} y1={padT} x2={xBefore} y2={H - padB} stroke="currentColor" strokeOpacity={0.15} />
- <line x1={xAfter} y1={padT} x2={xAfter} y2={H - padB} stroke="currentColor" strokeOpacity={0.15} />
- <text x={xBefore} y={H - 8} fontSize={11} textAnchor="middle" fill="currentColor" opacity={0.6}>
- Before
- </text>
- <text x={xAfter} y={H - 8} fontSize={11} textAnchor="middle" fill="currentColor" opacity={0.6}>
- After
- </text>
-
- {data.map((p) => {
- const y1 = yScale(p.before);
- const y2 = yScale(p.after);
- const stroke = healthInk(p.after);
- const isHovered = hovered?.file_path === p.file_path;
- const name = p.file_path.split("/").pop() ?? p.file_path;
- return (
- <g
- key={p.file_path}
- onMouseEnter={() => setHovered(p)}
- onMouseLeave={() => setHovered(null)}
- className="cursor-default"
- >
- <line
- x1={xBefore}
- y1={y1}
- x2={xAfter}
- y2={y2}
- stroke={stroke}
- strokeWidth={isHovered ? 2.5 : 1.5}
- strokeOpacity={hovered && !isHovered ? 0.25 : 0.8}
- />
- <circle cx={xBefore} cy={y1} r={isHovered ? 4 : 3} fill={stroke} fillOpacity={0.9} />
- <circle cx={xAfter} cy={y2} r={isHovered ? 4 : 3} fill={stroke} fillOpacity={0.9} />
- <text x={xBefore - 8} y={y1 + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={isHovered ? 0.9 : 0.55}>
- {p.before.toFixed(1)}
- </text>
- <text x={xAfter + 8} y={y2 + 3} fontSize={10} textAnchor="start" fill="currentColor" opacity={isHovered ? 0.9 : 0.55}>
- {name}
- </text>
- </g>
- );
- })}
- </svg>
- {hovered ? (
- <div className="pointer-events-none absolute left-2 top-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md">
- <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>
- <span className="ml-2 tabular-nums text-[var(--color-text-tertiary)]">
- {hovered.before.toFixed(1)} → {hovered.after.toFixed(1)} ({hovered.delta >= 0 ? "+" : ""}
- {hovered.delta.toFixed(1)})
- </span>
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/packages/ui/src/health/trend-view.tsx b/packages/ui/src/health/trend-view.tsx
index bcdb69512..f30b65639 100644
--- a/packages/ui/src/health/trend-view.tsx
+++ b/packages/ui/src/health/trend-view.tsx
@@ -18,6 +18,7 @@
* double-fetched alongside anything else on the page.
*/
+import { useMemo, useState } from "react";
import { AlertTriangle, Info } from "lucide-react";
import type { HealthCounts, HealthTrendResponse } from "@repowise-dev/types/health";
import { formatScore } from "@repowise-dev/types/health";
@@ -29,15 +30,10 @@ import { toFriendlyMessage } from "../lib/errors";
import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { TrendChart } from "./trend-chart";
-import { TrendSlopeChart } from "./trend-slope-chart";
import { deltaColor, formatDelta, scoreTextColor } from "./tokens";
-/**
- * How many slopes the chart draws. Passed explicitly rather than left to
- * `TrendSlopeChart`'s default so the sentence above the chart and the chart
- * itself cannot report different numbers.
- */
-const SLOPE_MAX = 18;
+/** Rows each Movers group lists before "Show more". */
+const GROUP_MAX = 8;
/**
* Colour, lead phrase and icon per alert kind.
@@ -144,54 +140,246 @@ function TrendAlerts({ alerts }: { alerts: HealthTrendResponse["alerts"] }) {
);
}
-function slopeCaption(data: HealthTrendResponse) {
- const drawn = Math.min(SLOPE_MAX, data.file_deltas.length);
- // Without a server-sent total there is no way to know whether
- // the list arrived complete, so claim only what is drawn.
- // Saying "all N" off the response length would be a flat lie
- // against a backend that caps at N and does not report it.
- if (data.file_deltas_total == null) {
- return `Showing the ${drawn} largest ${drawn === 1 ? "change" : "changes"}.`;
- }
- const total = data.file_deltas_total;
- return drawn < total
- ? `Showing the ${drawn} largest of ${total} files that changed.`
- : `All ${total} ${total === 1 ? "file that changed" : "files that changed"}.`;
+type FileDelta = HealthTrendResponse["file_deltas"][number];
+
+/** A path as the name a reader scans for and the folder that places it. */
+function splitPath(path: string): { name: string; dir: string } {
+ const at = path.lastIndexOf("/");
+ return at < 0 ? { name: path, dir: "" } : { name: path.slice(at + 1), dir: path.slice(0, at) };
+}
+
+/**
+ * The line above the groups. The server's per-direction counts describe every
+ * file that moved; without them (the hosted backend sends none) the counts are
+ * of the rows that arrived, and the sentence says so.
+ */
+function moversSummary(
+ data: HealthTrendResponse,
+ worse: number,
+ improved: number,
+ net: number | null,
+): string {
+ const exact = data.file_deltas_worse != null && data.file_deltas_improved != null;
+ const counts = exact
+ ? `${data.file_deltas_worse} got worse · ${data.file_deltas_improved} improved`
+ : `Among the ${data.file_deltas.length} largest changes: ${worse} got worse · ${improved} improved`;
+ return net == null || Math.abs(net) < 0.005 ? counts : `${counts} · code health ${formatDelta(net)}`;
+}
+
+function MoverRow({
+ row,
+ scale,
+ onSelectFile,
+}: {
+ row: FileDelta;
+ scale: number;
+ onSelectFile?: ((path: string) => void) | undefined;
+}) {
+ const { name, dir } = splitPath(row.file_path);
+ const body = (
+ <>
+ <span className="flex min-w-0 items-baseline gap-2">
+ <span className="shrink-0 font-mono text-xs text-[var(--color-text-primary)]">{name}</span>
+ {dir && (
+ <span className="min-w-0 truncate font-mono text-xs text-[var(--color-text-tertiary)]" title={dir}>
+ {dir}
+ </span>
+ )}
+ </span>
+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">
+ {formatScore(row.before)} → {formatScore(row.after)}
+ </span>
+ {/* Length is the size of the move against the largest one listed. */}
+ <span className="hidden h-1.5 w-16 overflow-hidden rounded-full bg-[var(--color-bg-inset)] sm:block" aria-hidden>
+ <span
+ className={`block h-full rounded-full ${row.delta < 0 ? "bg-[var(--color-error)]" : "bg-[var(--color-success)]"}`}
+ style={{ width: `${Math.max(6, (Math.abs(row.delta) / scale) * 100)}%` }}
+ />
+ </span>
+ <span className={`w-12 text-right font-mono text-xs tabular-nums ${deltaColor(row.delta)}`}>
+ {formatDelta(row.delta)}
+ </span>
+ </>
+ );
+ const grid =
+ "grid w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-3 px-2 py-1.5 text-left sm:grid-cols-[minmax(0,1fr)_auto_auto_auto]";
+ return (
+ <li>
+ {onSelectFile ? (
+ <button
+ type="button"
+ onClick={() => onSelectFile(row.file_path)}
+ title={row.file_path}
+ className={`${grid} rounded transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]`}
+ >
+ {body}
+ </button>
+ ) : (
+ <div className={grid}>{body}</div>
+ )}
+ </li>
+ );
+}
+
+function MoverGroup({
+ title,
+ rows,
+ total,
+ scale,
+ onSelectFile,
+}: {
+ title: string;
+ rows: FileDelta[];
+ /** Every file that moved this way, when the server counted them. */
+ total: number | undefined;
+ scale: number;
+ onSelectFile?: ((path: string) => void) | undefined;
+}) {
+ const [open, setOpen] = useState(false);
+ if (rows.length === 0) return null;
+ const listed = open ? rows : rows.slice(0, GROUP_MAX);
+ const of = total ?? rows.length;
+ return (
+ <div className="flex flex-col gap-1">
+ <p className="flex items-baseline gap-2 px-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <span>{title}</span>
+ <span className="tabular-nums">{listed.length < of ? `${listed.length} of ${of}` : of}</span>
+ </p>
+ <ul className="flex flex-col">
+ {listed.map((r) => (
+ <MoverRow key={r.file_path} row={r} scale={scale} onSelectFile={onSelectFile} />
+ ))}
+ </ul>
+ {rows.length > GROUP_MAX && (
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="self-start rounded px-2 py-1 text-xs text-[var(--color-accent-primary)] hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]"
+ >
+ {open ? "Show fewer" : `Show ${rows.length - GROUP_MAX} more`}
+ </button>
+ )}
+ </div>
+ );
}
-function FileDeltasSection({
+/**
+ * The files that moved between the last two snapshots, as two ranked groups:
+ * what got worse first, since that is the work, then what improved. Each row
+ * names the file, places it by folder, and opens it when the host can.
+ *
+ * Ceiling: no cause per row. Snapshots keep one score per file, not the
+ * findings behind it, so why a file moved is not stored. Upgrade path: record
+ * each file's lead finding on the snapshot and compare the two.
+ */
+function MoversSection({
data,
singleSnapshot,
+ net,
+ onSelectFile,
}: {
data: HealthTrendResponse;
singleSnapshot: boolean;
+ net: number | null;
+ onSelectFile?: ((path: string) => void) | undefined;
}) {
+ const worse = data.file_deltas.filter((d) => d.delta < 0).sort((a, b) => a.delta - b.delta);
+ const improved = data.file_deltas.filter((d) => d.delta > 0).sort((a, b) => b.delta - a.delta);
+ const scale = Math.max(0.01, ...data.file_deltas.map((d) => Math.abs(d.delta)));
return (
- <section className="flex flex-col gap-2">
+ <section className="flex flex-col gap-3">
<h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Largest score changes since last index
+ Movers since last index
</h3>
{data.file_deltas.length === 0 ? (
- <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ <p className="max-w-[62ch] text-[15px] text-[var(--color-text-secondary)]">
{singleSnapshot
? "Per-file movement compares the last two snapshots, so it appears with the second one."
: "No file changed score between the last two snapshots."}
</p>
) : (
<>
- {/* Two caps sit between the response and the picture — the server
- slices its list, and the chart draws the largest few of what
- arrives. Naming the drawn count against the true total is the
- difference between "these are the changes" and "these are the
- biggest of N". */}
- <p className="text-xs text-[var(--color-text-tertiary)]">{slopeCaption(data)}</p>
- <TrendSlopeChart points={data.file_deltas} max={SLOPE_MAX} />
+ <p className="text-[15px] tabular-nums text-[var(--color-text-secondary)]">
+ {moversSummary(data, worse.length, improved.length, net)}
+ </p>
+ <div className="flex flex-col gap-4">
+ <MoverGroup
+ title="Got worse"
+ rows={worse}
+ total={data.file_deltas_worse}
+ scale={scale}
+ onSelectFile={onSelectFile}
+ />
+ <MoverGroup
+ title="Improved"
+ rows={improved}
+ total={data.file_deltas_improved}
+ scale={scale}
+ onSelectFile={onSelectFile}
+ />
+ </div>
</>
)}
</section>
);
}
+function trendStats(data: HealthTrendResponse, otherReading: boolean): RibbonStat[] {
+ // The response names the scope it used, which is what tells a null hotspot
+ // figure under a narrowed scope apart from one on the full scope.
+ const narrowed = data.scope === "production";
+ return [
+ codeHealthStat(data.summary, otherReading),
+ hotspotStat(data.summary, otherReading, narrowed),
+ { label: "Snapshots", value: String(data.snapshot_count), sub: "rolling window, 50 max" },
+ ];
+}
+
+function TrendBody({
+ data,
+ counts,
+ onSelectFile,
+}: {
+ data: HealthTrendResponse;
+ counts?: HealthCounts | undefined;
+ onSelectFile?: ((path: string) => void) | undefined;
+}) {
+ const singleSnapshot = data.snapshot_count <= 1;
+ // Snapshots recorded the full score, so there is no code-shape series to
+ // read. These two carry the same labels as the lede's figures, and showing
+ // the other reading of them here put two different numbers under one name on
+ // one screen — the exact confusion the single headline exists to end.
+ const otherReading = counts === "code_shape";
+ // Oldest first, and stable across renders so the chart's geometry is not
+ // rebuilt by a parent re-render that did not change the data.
+ const history = useMemo(() => [...data.history].reverse(), [data.history]);
+
+ return (
+ <div className="flex flex-col gap-6">
+ <StatRibbon stats={trendStats(data, otherReading)} />
+
+ <TrendAlerts alerts={data.alerts} />
+
+ {singleSnapshot ? (
+ <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ One snapshot so far. The trend lines appear once a second one lands, after the next
+ index update.
+ </p>
+ ) : (
+ <TrendChart history={history} />
+ )}
+
+ <MoversSection
+ data={data}
+ singleSnapshot={singleSnapshot}
+ // The code-health delta reads the full score, which the other reading
+ // does not show, so it stays off the line there.
+ net={otherReading ? null : data.summary.average_delta}
+ onSelectFile={onSelectFile}
+ />
+ </div>
+ );
+}
export function TrendView({
data,
@@ -199,6 +387,7 @@ export function TrendView({
error,
onRetry,
counts,
+ onSelectFile,
}: {
data: HealthTrendResponse | undefined;
isLoading: boolean;
@@ -206,6 +395,8 @@ export function TrendView({
onRetry?: (() => void) | undefined;
/** What the page's figures count, so this section cannot claim the other reading. */
counts?: HealthCounts;
+ /** Opens a file, from a Movers row. Rows are plain text without it. */
+ onSelectFile?: ((path: string) => void) | undefined;
}) {
if (isLoading) {
return (
@@ -234,44 +425,5 @@ export function TrendView({
/>
);
}
-
- const singleSnapshot = data.snapshot_count <= 1;
-
- // Snapshots recorded the full score, so there is no code-shape series to
- // read. These two carry the same labels as the lede's figures, and showing
- // the other reading of them here put two different numbers under one name on
- // one screen — the exact confusion the single headline exists to end.
- const otherReading = counts === "code_shape";
- // The response names the scope it used, which is what tells a null hotspot
- // figure under a narrowed scope apart from one on the full scope.
- const narrowed = data.scope === "production";
-
- const stats: RibbonStat[] = [
- codeHealthStat(data.summary, otherReading),
- hotspotStat(data.summary, otherReading, narrowed),
- {
- label: "Snapshots",
- value: String(data.snapshot_count),
- sub: "rolling window, 50 max",
- },
- ];
-
- return (
- <div className="flex flex-col gap-6">
- <StatRibbon stats={stats} />
-
- <TrendAlerts alerts={data.alerts} />
-
- {singleSnapshot ? (
- <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
- One snapshot so far. The trend lines appear once a second one lands, after the next
- index update.
- </p>
- ) : (
- <TrendChart history={[...data.history].reverse()} />
- )}
-
- <FileDeltasSection data={data} singleSnapshot={singleSnapshot} />
- </div>
- );
+ return <TrendBody data={data} counts={counts} onSelectFile={onSelectFile} />;
}
diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsx
index d72052e43..826102dc2 100644
--- a/packages/ui/src/health/triage-view.tsx
+++ b/packages/ui/src/health/triage-view.tsx
@@ -4,27 +4,26 @@
* Code Health's landing surface, on the section design language.
*
* The shape is: one lede that leads with the defect score and says in prose
- * what it means, then the galaxy map as the page's spine with its inspector
- * beside it, then the host's hotspot and trend sections. Grouping is hairlines
- * and vertical rhythm, not boxes.
+ * what it means, Fix first under it, then the galaxy map as the page's spine
+ * with its search and ranked list beside it, then the host's hotspot and trend
+ * sections. Grouping is hairlines and vertical rhythm, not boxes.
*
* The map's lens switcher and key live around the canvas rather than on it
* (`chrome="none"`), so the reader is not looking at the field through a stack
* of glass panels.
*
- * The rail is an inspector. It used to hold the repository's top findings
- * permanently, which made it a second findings list: it never described the
- * object under the cursor and it never changed when the lens did. It now shows
- * the selection when there is one and the field's ranked list otherwise, and
- * both follow the active lens. The findings queue lives on its own tab.
+ * Selection has one surface: the file drawer. It is non-modal, so the map stays
+ * live behind it and picking another node swaps the drawer in place. The rail
+ * used to carry an inspector card for the same file as well, which said less
+ * than the drawer beside it and offered an "open" that opened nothing new.
*
* Presentation + orchestration only: the host injects data, links, and the
* file-detail drawer through a {@link CodeHealthAdapter}, so web and hosted
* render the same view from different backends.
*/
-import { useMemo, useState } from "react";
-import type { ReactNode } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
+import type { CSSProperties, ReactNode } from "react";
import useSWR from "swr";
import { Search } from "lucide-react";
import type {
@@ -47,14 +46,15 @@ import {
type CodeHealthOverlay,
type MapScope,
} from "./code-health-map";
-import { MapFieldList, MapInspector } from "./map/inspector";
+import { MapFieldList } from "./map/inspector";
import type { CodeHealthAdapter } from "./code-health-adapter";
export type HealthPillar = "all" | "defect" | "maintainability" | "performance";
-/** Map height. The inspector is height-matched so the rail never outgrows the
- * field it is inspecting. */
+/** Map height. The rail is height-matched so it never outgrows the field it lists. */
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 {
@@ -72,6 +72,18 @@ export function scopeFromFeed(feed: HealthMapFeed): MapScope {
...(feed.selection.active_missing.length
? { missing: feed.selection.active_missing }
: {}),
+ ...(feed.omitted.held !== undefined
+ ? { held: feed.omitted.held, includeHeld: feed.selection.include_held ?? false }
+ : {}),
+ ...(feed.selection.query
+ ? {
+ query: {
+ text: feed.selection.query,
+ matches: feed.selection.query_matches ?? 0,
+ shown: feed.selection.query_shown ?? 0,
+ },
+ }
+ : {}),
};
}
@@ -89,6 +101,13 @@ export function TriageView({
hotspotsSlot,
trendSlot,
leadSlot,
+ onDrawMore,
+ drawMoreStep,
+ onIncludeHeldChange,
+ onFindUndrawn,
+ mapPending,
+ mapError,
+ onRetryMap,
}: {
adapter: CodeHealthAdapter;
/** Trend fetched once by the host. Consumed by `trendSlot`; accepted here so
@@ -120,10 +139,22 @@ export function TriageView({
hotspotsSlot?: ReactNode;
trendSlot?: ReactNode;
/**
- * Fix first, under the score. The score leads the page; the host renders
- * this collapsed so the headline keeps the first screen.
+ * Fix first, under the score. Mounted once, in the same place while the
+ * overview loads, fails or lands, so its open state and scope survive. It
+ * renders collapsed by default (`FixFirstList`), so the headline keeps the
+ * first screen.
*/
leadSlot?: ReactNode;
+ /** Map controls the host backs with a refetch: see {@link CodeHealthMap}. */
+ onDrawMore?: () => void;
+ drawMoreStep?: number;
+ onIncludeHeldChange?: (include: boolean) => void;
+ onFindUndrawn?: (query: string) => void;
+ /** A refetch of the field is in flight. */
+ mapPending?: boolean;
+ /** The field's request failed; the map shows it with a retry. */
+ mapError?: unknown;
+ onRetryMap?: () => void;
}) {
const { cacheKey } = adapter;
const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
@@ -134,156 +165,194 @@ export function TriageView({
const [localSelected, setLocalSelected] = useState<string | null>(null);
const selected = selectedPath !== undefined ? selectedPath : localSelected;
- const setSelected = (path: string | null) => {
- if (onSelectPath) onSelectPath(path);
+ // Stable across renders, so the memoized map layers do not reconcile on
+ // every selection just because the host handed in a fresh callback.
+ const onSelectRef = useRef(onSelectPath);
+ onSelectRef.current = onSelectPath;
+ const setSelected = useCallback((path: string | null) => {
+ const select = onSelectRef.current;
+ if (select) select(path);
else setLocalSelected(path);
- };
+ }, []);
+ 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]);
- const selectedFile = useMemo(
- () => (selected ? files?.find((f) => f.file_path === selected) ?? null : null),
+ // 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],
);
// CodeHealthMap's optional props, omitted rather than passed as `undefined`
- // (strict optional props in the shared lib).
- const mapExtra: {
- lenses?: CodeHealthOverlay[];
- overlayLoading?: boolean;
- scope?: MapScope;
- highlightPaths?: string[];
- } = {};
- if (lenses) mapExtra.lenses = lenses;
- if (overlayLoading !== undefined) mapExtra.overlayLoading = overlayLoading;
- if (scope) mapExtra.scope = scope;
- if (highlightPaths?.length) mapExtra.highlightPaths = highlightPaths;
+ // (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;
+ } = {};
+ if (lenses) extra.lenses = lenses;
+ if (overlayLoading !== undefined) extra.overlayLoading = overlayLoading;
+ if (scope) extra.scope = scope;
+ if (highlightPaths?.length) extra.highlightPaths = highlightPaths;
+ if (onDrawMore) extra.onDrawMore = onDrawMore;
+ if (drawMoreStep !== undefined) extra.drawMoreStep = drawMoreStep;
+ if (onIncludeHeldChange) extra.onIncludeHeldChange = onIncludeHeldChange;
+ if (onFindUndrawn) extra.onFindUndrawn = onFindUndrawn;
+ if (mapPending !== undefined) extra.pending = mapPending;
+ return extra;
+ }, [
+ lenses,
+ overlayLoading,
+ scope,
+ highlightPaths,
+ onDrawMore,
+ drawMoreStep,
+ onIncludeHeldChange,
+ onFindUndrawn,
+ mapPending,
+ ]);
- if (isLoading) {
- return (
- <div className="flex flex-col gap-6">
- {/* Shapes and widths match the real layout. A skeleton that does not
- causes a reflow when content lands, which reads as slower than
- showing nothing. */}
- <Skeleton className="h-12 w-40 rounded-lg" />
- <Skeleton className="h-20 w-full max-w-[54ch] rounded-lg" />
- <Skeleton className="h-[74px] w-full" />
- {/* Fix first has its own request, so it never waits on this one. */}
- {leadSlot}
- <Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />
- </div>
- );
- }
-
- if (error) {
- return (
- <div className="flex flex-col gap-6">
- {leadSlot}
- <ApiError
- title="Couldn't load health data"
- message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}
- onRetry={() => void mutate()}
- />
- </div>
- );
- }
+ // One node per region, so the children below keep their positions (and
+ // `leadSlot` its state) whichever way the overview request goes.
+ const lede = isLoading ? (
+ // Shapes and widths match the real layout. A skeleton that does not causes
+ // a reflow when content lands, which reads as slower than showing nothing.
+ <div className="flex flex-col gap-6">
+ <Skeleton className="h-12 w-40 rounded-lg" />
+ <Skeleton className="h-20 w-full max-w-[54ch] rounded-lg" />
+ <Skeleton className="h-[74px] w-full" />
+ </div>
+ ) : error ? (
+ <ApiError
+ title="Couldn't load health data"
+ message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}
+ onRetry={() => void mutate()}
+ />
+ ) : overview ? (
+ <CodeHealthLede
+ summary={overview.summary}
+ accuracy={overview.defect_accuracy ?? null}
+ distribution={overview.distribution ?? null}
+ pillar={overlay === "maintainability" ? "maintainability" : "health"}
+ />
+ ) : null;
- if (!overview) return null;
+ const loaded = !isLoading && !error && Boolean(overview);
return (
<div className="flex flex-col gap-6 sm:gap-8">
- <CodeHealthLede
- summary={overview.summary}
- accuracy={overview.defect_accuracy ?? null}
- distribution={overview.distribution ?? null}
- pillar={overlay === "maintainability" ? "maintainability" : "health"}
- />
+ {lede}
+ {/* Fix first has its own request, so it never waits on the overview. */}
{leadSlot}
- <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 ? (
- <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>
-
- {/* Inspector, height-matched to the map. 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-[772px]">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
- <input
- 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 focus:border-[var(--color-border-hover)] focus:outline-none"
- />
- </div>
-
- {selectedFile ? (
- <MapInspector
- file={selectedFile}
+ {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}
- onOpen={(p) => setSelected(p)}
- onClose={() => setSelected(null)}
+ onOverlayChange={onOverlayChange}
+ {...(lenses ? { lenses } : {})}
/>
- ) : selected ? (
- <p className="rounded-lg border border-dashed border-[var(--color-border-default)] p-3 text-xs text-[var(--color-text-tertiary)]">
- <span className="font-mono">{selected}</span> is not in the drawn field, so
- there is no node to inspect. Its details still open below.
- </p>
- ) : null}
-
- {files ? (
- <div className="min-h-0 flex-1 overflow-hidden border-t border-[var(--color-border-default)] pt-3">
- <MapFieldList
+ ) : 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}
- overlay={overlay}
+ search={mapQuery}
selectedPath={selected}
onSelectFile={setSelected}
- {...(scope ? { scope } : {})}
+ 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>
- ) : null}
- </aside>
- </div>
- </OverviewSection>
- {hotspotsSlot}
- {trendSlot}
+ {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>
+ ) : 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({
filePath: selected,
- onClose: () => setSelected(null),
+ onClose: closeDrawer,
lens: overlay,
})}
</div>
diff --git a/packages/ui/src/shared/adaptive-panel.tsx b/packages/ui/src/shared/adaptive-panel.tsx
index 002ff5ed1..861bacee2 100644
--- a/packages/ui/src/shared/adaptive-panel.tsx
+++ b/packages/ui/src/shared/adaptive-panel.tsx
@@ -21,6 +21,9 @@ export interface AdaptivePanelProps {
onOpenChange: (open: boolean) => void;
/** Accessible name for the panel; rendered in the header unless `hideHeader`. */
title: React.ReactNode;
+ /** Replaces the title's default mono 12px treatment, for a header that sets
+ * its own type (e.g. a file name over its directory). */
+ titleClassName?: string | undefined;
/** Small uppercase label rendered above the title (e.g. entity kind). */
eyebrow?: React.ReactNode | undefined;
children: React.ReactNode;
@@ -45,6 +48,7 @@ export function AdaptivePanel({
open,
onOpenChange,
title,
+ titleClassName,
eyebrow,
children,
widthClassName = "md:max-w-[520px]",
@@ -96,7 +100,16 @@ export function AdaptivePanel({
aria-describedby={undefined}
{...(onInteractOutside ? { onInteractOutside } : {})}
className={cn(
- "fixed z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-surface)] shadow-2xl",
+ // The page's own plane, so a drawer reads as part of the page it
+ // opens over; the hairline edge and shadow separate it.
+ // The page's plane, so the drawer reads as more of the page. Two
+ // planes are then too close to root to show inside it: dark inset
+ // wells (about 1.03:1 on root) and light elevated hovers (about
+ // 1.02:1). Inside the panel, wells take the overlay ground in dark
+ // and hovers take the translucent selection wash, which shows on
+ // root in both themes.
+ "dark:[--color-bg-inset:var(--color-bg-overlay)] [--color-bg-elevated:var(--color-bg-selected)]",
+ "fixed z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-root)] shadow-2xl",
"data-[state=open]:animate-in data-[state=closed]:animate-out",
// Mobile: bottom sheet.
"inset-x-0 bottom-0 rounded-t-2xl border-t border-[var(--color-border-default)]",
@@ -128,7 +141,12 @@ export function AdaptivePanel({
{eyebrow}
</p>
)}
- <DialogPrimitive.Title className="mt-0.5 break-all font-mono text-[12px] leading-snug text-[var(--color-text-primary)]">
+ <DialogPrimitive.Title
+ className={
+ titleClassName ??
+ "mt-0.5 break-all font-mono text-[12px] leading-snug text-[var(--color-text-primary)]"
+ }
+ >
{title}
</DialogPrimitive.Title>
</div>
diff --git a/packages/ui/src/shared/collapsible-section.tsx b/packages/ui/src/shared/collapsible-section.tsx
index 1f64f2d1a..3f790483b 100644
--- a/packages/ui/src/shared/collapsible-section.tsx
+++ b/packages/ui/src/shared/collapsible-section.tsx
@@ -1,6 +1,7 @@
"use client";
import * as React from "react";
+import { ChevronRight } from "lucide-react";
import { cn } from "../lib/cn";
export interface CollapsibleSectionProps {
@@ -10,12 +11,23 @@ export interface CollapsibleSectionProps {
defaultOpen?: boolean;
children?: React.ReactNode;
className?: string;
+ /**
+ * `hairline` (default) is a rule above a borderless toggle, the section
+ * look. `boxed` keeps the older bordered button for a surface that needs
+ * the toggle to read as a control on its own.
+ */
+ variant?: "hairline" | "boxed";
+ /** Tighter row and a 12px title, for a disclosure nested inside another. */
+ dense?: boolean;
}
/**
- * The progressive-disclosure idiom used across Code Health: a borderless
- * toggle button that reveals a demoted table/queue beneath. One home so the
+ * The progressive-disclosure idiom used across the product: a toggle that
+ * reveals a demoted table, queue or audit trail beneath. One home so the
* disclosure chrome restyles everywhere on a package bump.
+ *
+ * The body mounts only while open, so a closed section costs nothing to
+ * render and a drawer with six of them opens as fast as one with none.
*/
export function CollapsibleSection({
title,
@@ -23,30 +35,69 @@ export function CollapsibleSection({
defaultOpen = false,
children,
className,
+ variant = "hairline",
+ dense = false,
}: CollapsibleSectionProps) {
const [open, setOpen] = React.useState(defaultOpen);
const bodyId = React.useId();
+
+ if (variant === "boxed") {
+ return (
+ <section className={cn("space-y-3", className)}>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-controls={bodyId}
+ className="flex w-full items-center gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm 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)]"
+ >
+ <span aria-hidden="true" className="text-[var(--color-text-tertiary)]">
+ {open ? "▾" : "▸"}
+ </span>
+ {title}
+ {hint != null && (
+ <span className="ml-auto text-xs font-normal text-[var(--color-text-tertiary)]">
+ {hint}
+ </span>
+ )}
+ </button>
+ {open ? (
+ <div id={bodyId} className="space-y-3">
+ {children}
+ </div>
+ ) : null}
+ </section>
+ );
+ }
+
return (
- <section className={cn("space-y-3", className)}>
+ <section className={cn("border-t border-[var(--color-border-default)]", className)}>
<button
type="button"
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
aria-controls={bodyId}
- className="flex w-full items-center gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm 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)]"
+ className={cn(
+ "flex w-full min-w-0 items-center gap-2 rounded-sm text-left font-medium text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",
+ dense ? "py-2 text-xs" : "py-2.5 text-[15px]",
+ )}
>
- <span aria-hidden="true" className="text-[var(--color-text-tertiary)]">
- {open ? "▾" : "▸"}
- </span>
- {title}
+ <ChevronRight
+ aria-hidden="true"
+ className={cn(
+ "h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] transition-transform motion-reduce:transition-none",
+ open && "rotate-90",
+ )}
+ />
+ <span className="min-w-0 flex-1">{title}</span>
{hint != null && (
- <span className="ml-auto text-xs font-normal text-[var(--color-text-tertiary)]">
+ <span className="ml-auto inline-flex shrink-0 items-center gap-2 text-xs font-normal tabular-nums text-[var(--color-text-tertiary)]">
{hint}
</span>
)}
</button>
{open ? (
- <div id={bodyId} className="space-y-3">
+ <div id={bodyId} className={cn("flex flex-col gap-3", dense ? "pb-2" : "pb-4 pt-1")}>
{children}
</div>
) : null}
diff --git a/packages/vscode/webview/src/views/health/App.test.tsx b/packages/vscode/webview/src/views/health/App.test.tsx
index fd7e6b7b5..ad859849f 100644
--- a/packages/vscode/webview/src/views/health/App.test.tsx
+++ b/packages/vscode/webview/src/views/health/App.test.tsx
@@ -8,7 +8,7 @@ import type {
} from "@repowise-dev/types/health";
import { bandForScore } from "@repowise-dev/types/health";
import { OVERLAY_SPECS } from "@repowise-dev/ui/health/code-health-map";
-import { scoreTextColor } from "@repowise-dev/ui/health/tokens";
+import { healthRampFill, scoreTextColor } from "@repowise-dev/ui/health/tokens";
import type { WebviewHost } from "../../runtime/rpc";
import { App } from "./App";
@@ -202,12 +202,12 @@ describe("Health dashboard", () => {
//
// The two are no longer the same colour value, and must not be asserted to
// be. Inking text and filling a disc are different jobs, so the map paints
- // from the canvas ramp and the panel from the semantic one. What may never
- // differ is the band beneath both, which is what this pins: the map fills
- // the node token for this file's band, and the figure carries the ink that
- // the same band function gives the same score.
+ // from its continuous ramp and the panel from the semantic one. What may
+ // never differ is the score beneath both, which is what this pins: the map
+ // fills the ramp at this file's score, and the figure carries the ink that
+ // the band function gives the same score.
expect(bandForScore(file.score)).toBe("good");
- expect(OVERLAY_SPECS.health.fill(file)).toBe("var(--color-node-good)");
+ expect(OVERLAY_SPECS.health.fill(file)).toBe(healthRampFill(file.score));
expect(figure.className).toContain(scoreTextColor(file.score));
});
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
index 8d0a49e71..bcd2b45bf 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -24,8 +24,9 @@
* operate rather than a pile you read, so neither is numbered.
*/
+import dynamic from "next/dynamic";
import { useParams, useRouter, useSearchParams } from "next/navigation";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import {
Bug,
@@ -45,6 +46,7 @@ import { ReleaseNotice } from "@repowise-dev/ui/shared/release-notice";
import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
import { OverviewSection } from "@repowise-dev/ui/overview";
import { Button } from "@repowise-dev/ui/ui/button";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import {
Select,
SelectContent,
@@ -64,14 +66,7 @@ import {
import type { DocDriftResponse } from "@repowise-dev/types/doc-drift";
import { TriageTab } from "@/components/code-health/triage-tab";
import { HotspotsSection } from "@/components/code-health/hotspots-section";
-import { FindingsTab } from "@/components/code-health/findings-tab";
-import { PerformanceTab } from "@/components/code-health/performance-tab";
-import { CoverageTab } from "@/components/code-health/coverage-tab";
import { TrendSection } from "@/components/code-health/trend-tab";
-import { DeadCodeTab } from "@/components/risk/dead-code-tab";
-import { DocDriftTab } from "@/components/risk/doc-drift-tab";
-import { ImpactTab } from "@/components/risk/impact-tab";
-import { SecurityTab } from "@/components/risk/security-tab";
import { getDeadCodeSummary } from "@/lib/api/dead-code";
import { getDocDrift } from "@/lib/api/doc-drift";
import {
@@ -89,6 +84,39 @@ import {
} from "@/lib/api/code-health";
import { useTranslations } from "next-intl";
+// The tabs render one at a time behind `?tab=` and triage is the default, so
+// the others are split out: landing here downloads the triage chunk only.
+// ssr:false because they are interactive, data-fetching client views.
+const TabFallback = () => <Skeleton className="h-[60vh] w-full rounded-lg" />;
+const FindingsTab = dynamic(
+ () => import("@/components/code-health/findings-tab").then((m) => m.FindingsTab),
+ { ssr: false, loading: TabFallback },
+);
+const PerformanceTab = dynamic(
+ () => import("@/components/code-health/performance-tab").then((m) => m.PerformanceTab),
+ { ssr: false, loading: TabFallback },
+);
+const CoverageTab = dynamic(
+ () => import("@/components/code-health/coverage-tab").then((m) => m.CoverageTab),
+ { ssr: false, loading: TabFallback },
+);
+const DeadCodeTab = dynamic(
+ () => import("@/components/risk/dead-code-tab").then((m) => m.DeadCodeTab),
+ { ssr: false, loading: TabFallback },
+);
+const DocDriftTab = dynamic(
+ () => import("@/components/risk/doc-drift-tab").then((m) => m.DocDriftTab),
+ { ssr: false, loading: TabFallback },
+);
+const SecurityTab = dynamic(
+ () => import("@/components/risk/security-tab").then((m) => m.SecurityTab),
+ { ssr: false, loading: TabFallback },
+);
+const ImpactTab = dynamic(
+ () => import("@/components/risk/impact-tab").then((m) => m.ImpactTab),
+ { ssr: false, loading: TabFallback },
+);
+
const TABS = [
"triage",
"performance",
@@ -215,12 +243,16 @@ const COUNTS_LABEL_KEYS: Record<HealthCounts, string> = {
};
/**
- * Nodes the map draws. The server chooses which ones: the selected file first,
- * then every file carrying an open performance cause in rank order, then the
- * biggest files fill the rest. Ranking by size alone used to push tens of
- * files with open causes off the field entirely.
+ * 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
@@ -347,22 +379,56 @@ export default function CodeHealthPage() {
// 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
- // size ranking happened to include them.
+ // 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([...(selectedPath ? [selectedPath] : []), ...(highlightPaths ?? [])])],
- [selectedPath, highlightPaths],
+ () => [...new Set([...extraPins, ...(highlightPaths ?? [])])],
+ [extraPins, highlightPaths],
);
- const { data: mapFeed } = useSWR<HealthMapFeed>(
- `code-health-map:${repoId}${viewKey}:${activePaths.join(",")}`,
+ 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: MAP_CAP,
+ 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
@@ -588,6 +654,13 @@ export default function CodeHealthPage() {
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
@@ -600,6 +673,7 @@ export default function CodeHealthPage() {
error={trendError}
onRetry={() => void mutateTrend()}
counts={counts}
+ onSelectFile={setSelectedPath}
/>
</OverviewSection>
}
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index d2846a969..0d6cd99e4 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -43,6 +43,13 @@ export function TriageTab({
trendSlot,
scope,
counts,
+ onDrawMore,
+ drawMoreStep,
+ onIncludeHeldChange,
+ onFindUndrawn,
+ mapPending,
+ mapError,
+ onRetryMap,
}: {
repoId: string;
/** Trend fetched once at the page level. */
@@ -68,6 +75,14 @@ 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();
@@ -118,6 +133,13 @@ export function TriageTab({
hotspotsSlot={hotspotsSlot}
trendSlot={trendSlot}
leadSlot={<FixFirstSection repoId={id} />}
+ onDrawMore={onDrawMore}
+ drawMoreStep={drawMoreStep}
+ onIncludeHeldChange={onIncludeHeldChange}
+ onFindUndrawn={onFindUndrawn}
+ mapPending={mapPending}
+ mapError={mapError}
+ onRetryMap={onRetryMap}
/>
);
}
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 6cce00f8a..d6989ce48 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -4,7 +4,7 @@ import { useCallback, useMemo } from "react";
import useSWR from "swr";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
-import { HealthFileDrawer, useRelatedWork } from "@repowise-dev/ui/health";
+import { HealthFileDrawer, useRelatedWorkQuery } from "@repowise-dev/ui/health";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getPerformanceOpportunities,
@@ -39,7 +39,7 @@ export function HealthFileDrawerHost({
}) {
const t = useTranslations("health");
const router = useRouter();
- const { data, isLoading } = useFileBreakdown(repoId, filePath, counts);
+ const { data, error, isLoading, mutate } = useFileBreakdown(repoId, filePath, counts);
const prefix = `/repos/${repoId}`;
const filePageHref = filePath ? fileEntityPath(prefix, filePath) : undefined;
@@ -74,7 +74,8 @@ export function HealthFileDrawerHost({
(paths: string[]) => getRelatedWork(repoId, paths),
[repoId],
);
- const related = useRelatedWork(fetchRelated, [filePath]);
+ // Cached per path, so going back to a file already looked at is instant.
+ const related = useRelatedWorkQuery(fetchRelated, [filePath]);
const toRelated = useMemo(() => relatedWorkHref(repoId), [repoId]);
return (
@@ -82,11 +83,16 @@ export function HealthFileDrawerHost({
open={filePath !== null}
opportunity={opportunity}
refactoringOpportunityHref={(id) => refactoringOpportunityHref(repoId, id)}
- related={related?.files?.[0]}
+ related={related.data?.files?.[0]}
+ relatedError={related.error}
+ onRelatedRetry={related.retry}
relatedWorkHref={toRelated}
onNavigate={(href) => router.push(href)}
onClose={onClose}
+ filePath={filePath}
loading={isLoading}
+ error={error}
+ onRetry={() => void mutate()}
metric={data?.metric ?? null}
breakdown={
data?.breakdown
@@ -99,6 +105,7 @@ export function HealthFileDrawerHost({
}
findings={data?.findings ?? []}
suggestions={data?.suggestions ?? {}}
+ heldBack={data?.gated ?? null}
trend={data?.trend ?? null}
signals={data?.signals ?? null}
lens={lens}
@@ -126,6 +133,9 @@ export function HealthFileDrawerHost({
toast.error(t("findingStatusFailed"));
throw err;
}
+ // The score, leading cause and category totals all count open
+ // findings, so they re-read rather than describe the old status.
+ void mutate();
}}
/>
);
diff --git a/packages/web/src/components/health/use-file-breakdown.ts b/packages/web/src/components/health/use-file-breakdown.ts
index caa39021d..26f5ebb76 100644
--- a/packages/web/src/components/health/use-file-breakdown.ts
+++ b/packages/web/src/components/health/use-file-breakdown.ts
@@ -19,6 +19,8 @@ export function useFileBreakdown(
return useSWR<HealthFileBreakdownResponse>(
filePath ? `code-health-breakdown:${repoId}:${filePath}${suffix}` : null,
() => getHealthFileBreakdown(repoId, filePath!, counts),
- { revalidateOnFocus: false },
+ // The previous file stays on screen (dimmed by the drawer) while the next
+ // one loads, so moving between files never flashes an empty panel.
+ { revalidateOnFocus: false, keepPreviousData: true },
);
}
diff --git a/packages/web/src/lib/api/related-work.ts b/packages/web/src/lib/api/related-work.ts
index e07f78bce..f179a6f96 100644
--- a/packages/web/src/lib/api/related-work.ts
+++ b/packages/web/src/lib/api/related-work.ts
@@ -14,17 +14,20 @@ export { getRelatedWork } from "./code-health";
export function relatedWorkHref(repoId: string): RelatedWorkHref {
const prefix = `/repos/${repoId}`;
return (item, filePath) => {
+ // Code Health links carry the file, so the page they land on still has it
+ // open (the map's selection is `?file=`) and Back returns to it.
+ const file = encodeURIComponent(filePath);
switch (item.lens) {
case "refactoring":
return refactoringOpportunityHref(repoId, item.id);
case "performance":
- return `${prefix}/code-health?tab=performance&opportunity=${encodeURIComponent(item.id)}`;
+ return `${prefix}/code-health?tab=performance&opportunity=${encodeURIComponent(item.id)}&file=${file}`;
case "findings":
return `${fileEntityPath(prefix, filePath)}?tab=health`;
case "fix_first":
- return `${prefix}/code-health`;
+ return `${prefix}/code-health?file=${file}`;
case "dead_code":
- return `${prefix}/code-health?tab=dead-code`;
+ return `${prefix}/code-health?tab=dead-code&file=${file}`;
}
};
}
diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.js
index bb68da767..89e702c98 100644
--- a/plugins/claude-code/hooks/lens/lens.js
+++ b/plugins/claude-code/hooks/lens/lens.js
@@ -3281,7 +3281,9 @@ async function getHealthMap(repoId, opts = {}) {
cap: opts.cap,
active: opts.active?.length ? opts.active.join(",") : void 0,
scope: opts.scope,
- counts: opts.counts
+ counts: opts.counts,
+ include_held: opts.include_held || void 0,
+ q: opts.q?.trim() || void 0
});
}
diff --git a/tests/unit/server/test_health_map_feed.py b/tests/unit/server/test_health_map_feed.py
index 639f8d4a5..e049b47e7 100644
--- a/tests/unit/server/test_health_map_feed.py
+++ b/tests/unit/server/test_health_map_feed.py
@@ -15,10 +15,18 @@ from repowise.core.persistence import crud
from tests.unit.server.conftest import create_test_repo
-def _metric(path: str, nloc: int, module: str = "src") -> dict:
+def _metric(
+ path: str,
+ nloc: int,
+ module: str = "src",
+ *,
+ score: float | None = 7.0,
+ origin: str | None = None,
+) -> dict:
return {
"file_path": path,
- "score": 7.0,
+ "score": score,
+ "code_origin": origin,
"max_ccn": 3,
"max_nesting": 2,
"nloc": nloc,
@@ -84,9 +92,11 @@ async def test_a_small_file_with_a_cause_outranks_a_large_clean_one(app, client)
feed = await _feed(client, repo_id, cap=2)
drawn = [f["file_path"] for f in feed["files"]]
assert "src/tiny.py" in drawn
- assert feed["selection"]["basis"] == "active_then_performance_then_nloc"
+ assert feed["selection"]["basis"] == (
+ "active_then_module_floor_then_origin_tier_then_performance_then_debt"
+ )
assert feed["selection"]["performance_shown"] == 1
- # The remaining slot went to the size sample, in size order.
+ # The remaining slot went to the debt rank: equal scores, so the bigger file.
assert feed["selection"]["nloc_shown"] == 1
assert "src/big0.py" in drawn
@@ -124,6 +134,7 @@ async def test_nothing_is_omitted_once_the_cap_clears_the_repository(app, client
"performance_files": 0,
"opportunities": 0,
"observations": 0,
+ "held": 0,
}
@@ -224,6 +235,10 @@ async def test_the_cap_is_bounded(app, client):
assert (
await client.get(f"/api/repos/{repo_id}/health/map", params={"cap": 99999})
).status_code == 422
+ # A canvas holds eight thousand nodes, so the ceiling sits there.
+ assert (
+ await client.get(f"/api/repos/{repo_id}/health/map", params={"cap": 8000})
+ ).status_code == 200
async def test_a_cause_on_an_unsizeable_file_is_not_reported_as_capped_out(app, client):
@@ -252,3 +267,110 @@ async def test_a_cause_on_an_unsizeable_file_is_not_reported_as_capped_out(app,
# so it is absent from the field rather than absent from the product.
assert feed["performance"]["files_with_opportunities"] == 1
assert feed["performance"]["files_with_opportunities_eligible"] == 0
+
+
+async def _seed_rows(app, client: AsyncClient, metrics: list[dict]) -> str:
+ repo = await create_test_repo(client)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(session, repo["id"], metrics)
+ await session.commit()
+ return repo["id"]
+
+
+async def test_vendored_and_generated_files_are_held_out_and_counted(app, client):
+ repo_id = await _seed_rows(
+ app,
+ client,
+ [
+ _metric("src/app.py", 50, origin="production"),
+ _metric("vendor/lib.js", 9000, "vendor", origin="vendored"),
+ _metric("gen/api_pb2.py", 4000, "gen", origin="generated"),
+ ],
+ )
+ feed = await _feed(client, repo_id, cap=100)
+ assert [f["file_path"] for f in feed["files"]] == ["src/app.py"]
+ # Not drawn, not counted as capped out: held, and the response says so.
+ assert feed["eligible_total"] == 1
+ assert feed["omitted"]["files"] == 0
+ assert feed["omitted"]["held"] == 2
+
+ everything = await _feed(client, repo_id, cap=100, include_held="true")
+ assert everything["eligible_total"] == 3
+ assert everything["omitted"]["held"] == 0
+ assert everything["selection"]["include_held"] is True
+
+
+async def test_a_pinned_vendored_file_is_drawn_even_while_held(app, client):
+ repo_id = await _seed_rows(
+ app,
+ client,
+ [_metric("src/app.py", 50), _metric("vendor/lib.js", 90, "vendor", origin="vendored")],
+ )
+ feed = await _feed(client, repo_id, cap=100, active="vendor/lib.js")
+ assert "vendor/lib.js" in [f["file_path"] for f in feed["files"]]
+ assert feed["omitted"]["held"] == 0
+
+
+async def test_production_code_is_admitted_before_tests_and_examples(app, client):
+ repo_id = await _seed_rows(
+ app,
+ client,
+ [
+ _metric("docs/example.py", 900, "docs", score=1.0, origin="docs_example"),
+ _metric("tests/test_x.py", 800, "tests", score=1.0, origin="test"),
+ _metric("scripts/build.py", 700, "scripts", score=1.0, origin="tooling"),
+ _metric("src/a.py", 10, "src", origin="production"),
+ ],
+ )
+ # A cap no larger than the floor's share leaves nothing for a floor, so the
+ # tier order alone decides.
+ feed = await _feed(client, repo_id, cap=4)
+ assert [f["file_path"] for f in feed["files"]] == [
+ "src/a.py",
+ "scripts/build.py",
+ "tests/test_x.py",
+ "docs/example.py",
+ ]
+ assert feed["files"][0]["code_origin"] == "production"
+
+
+async def test_an_unhealthy_file_outranks_a_bigger_clean_one(app, client):
+ repo_id = await _seed_rows(
+ app,
+ client,
+ [
+ _metric("src/huge_clean.py", 5000, score=10.0),
+ _metric("src/small_sick.py", 40, score=2.0),
+ _metric("src/unscored.py", 9000, score=None),
+ ],
+ )
+ feed = await _feed(client, repo_id, cap=3)
+ # Debt first, the clean file next by size, and the file health could not
+ # score last in its tier whatever its size.
+ assert [f["file_path"] for f in feed["files"]] == [
+ "src/small_sick.py",
+ "src/huge_clean.py",
+ "src/unscored.py",
+ ]
+
+
+async def test_a_small_module_keeps_a_floor_against_a_big_one(app, client):
+ big = [_metric(f"core/f{i}.py", 1000, "core", score=2.0) for i in range(20)]
+ small = [_metric("cli/main.py", 10, "cli", score=9.5)]
+ repo_id = await _seed_rows(app, client, big + small)
+ feed = await _feed(client, repo_id, cap=10)
+ drawn = [f["file_path"] for f in feed["files"]]
+ # The debt rank alone would spend all ten slots on the unhealthy module.
+ assert "cli/main.py" in drawn
+ assert feed["selection"]["module_floor_shown"] == 2
+ assert feed["shown"] == 10
+
+
+async def test_a_query_pins_the_files_whose_path_contains_it(app, client):
+ rows = [_metric(f"src/f{i}.py", 1000 - i) for i in range(10)]
+ rows.append(_metric("src/needle_here.py", 1))
+ repo_id = await _seed_rows(app, client, rows)
+ feed = await _feed(client, repo_id, cap=2, q="NEEDLE")
+ 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
diff --git a/tests/unit/server/test_health_trend_route.py b/tests/unit/server/test_health_trend_route.py
index 69cf5ae85..a4a46c992 100644
--- a/tests/unit/server/test_health_trend_route.py
+++ b/tests/unit/server/test_health_trend_route.py
@@ -215,3 +215,92 @@ async def test_a_narrowed_trend_blanks_the_figures_it_never_recorded(
assert row["structure_average"] is None
assert row["history_average"] is None
assert row["maintainability_average"] is None
+
+
+async def test_each_direction_keeps_half_the_slice(client, session, tmp_path) -> None:
+ """The page lists "got worse" and "improved" apart. A plain top-N by size
+ let many larger regressions fill the whole slice and leave the improved
+ group empty beside a count saying it has rows."""
+ repo_id = await _repo(client, session, tmp_path)
+ before, after = {}, {}
+ for i in range(FILE_DELTA_LIMIT):
+ before[f"down{i:02d}.py"], after[f"down{i:02d}.py"] = 9.0, 5.0
+ for i in range(30):
+ before[f"up{i:02d}.py"], after[f"up{i:02d}.py"] = 5.0, 5.5
+ await _two_snapshots(session, repo_id, before, after)
+
+ body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()
+
+ deltas = body["file_deltas"]
+ half = FILE_DELTA_LIMIT // 2
+ assert len(deltas) == FILE_DELTA_LIMIT
+ assert sum(1 for d in deltas if d["delta"] > 0) == half
+ assert sum(1 for d in deltas if d["delta"] < 0) == FILE_DELTA_LIMIT - half
+ # Still largest first across the merged slice.
+ assert [abs(d["delta"]) for d in deltas] == sorted((abs(d["delta"]) for d in deltas), reverse=True)
+ assert body["file_deltas_worse"] == FILE_DELTA_LIMIT
+ assert body["file_deltas_improved"] == 30
+ assert body["file_deltas_total"] == FILE_DELTA_LIMIT + 30
+
+
+async def test_a_direction_with_few_rows_leaves_its_half_to_the_other(
+ client, session, tmp_path
+) -> None:
+ repo_id = await _repo(client, session, tmp_path)
+ before = {f"d{i:02d}.py": 9.0 for i in range(FILE_DELTA_LIMIT + 5)}
+ after = {p: 8.0 for p in before}
+ before["up.py"], after["up.py"] = 4.0, 4.1
+ await _two_snapshots(session, repo_id, before, after)
+
+ body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()
+
+ deltas = body["file_deltas"]
+ assert len(deltas) == FILE_DELTA_LIMIT
+ assert [d["file_path"] for d in deltas if d["delta"] > 0] == ["up.py"]
+ assert (body["file_deltas_worse"], body["file_deltas_improved"]) == (FILE_DELTA_LIMIT + 5, 1)
+
+
+async def test_the_list_defers_the_per_file_maps(session, client, tmp_path) -> None:
+ """``file_maps=False`` loads every row's scalars and none of the
+ repository-sized maps; the trend route then loads only the last two."""
+ from sqlalchemy import inspect
+
+ from repowise.core.persistence.crud import list_health_snapshots
+
+ repo_id = await _repo(client, session, tmp_path)
+ await _two_snapshots(session, repo_id, {"a.py": 8.0}, {"a.py": 7.0})
+ session.expunge_all()
+
+ rows = await list_health_snapshots(session, repo_id, file_maps=False)
+
+ assert [r.average_health for r in rows] == [5.0, 5.0]
+ for row in rows:
+ unloaded = inspect(row).unloaded
+ assert {"per_file_scores_json", "per_file_deductions_json"} <= unloaded
+
+
+async def test_a_narrowed_trend_still_lists_movement(client, session, tmp_path) -> None:
+ """The scoped projection reads the deferred map through its stored row."""
+ repo_id = await _repo(client, session, tmp_path)
+ base = datetime(2026, 1, 1, tzinfo=UTC)
+ for day, score in ((0, 8.0), (1, 6.0)):
+ await save_health_snapshot(
+ session,
+ repo_id,
+ hotspot_health=5.0,
+ average_health=5.0,
+ worst_performer_path=None,
+ worst_performer_score=None,
+ per_file_scores={"src/a.py": score, "src/b.py": 5.0},
+ production_average=score,
+ taken_at=base + timedelta(days=day),
+ )
+ await session.commit()
+ session.expunge_all()
+
+ body = (await client.get(f"/api/repos/{repo_id}/health/trend?scope=production")).json()
+
+ assert body["file_deltas"] == [
+ {"file_path": "src/a.py", "before": 8.0, "after": 6.0, "delta": -2.0}
+ ]
+ assert body["file_deltas_worse"] == 1
diff --git a/tests/unit/server/test_overview_limit_slice.py b/tests/unit/server/test_overview_limit_slice.py
new file mode 100644
index 000000000..8e65f3b44
--- /dev/null
+++ b/tests/unit/server/test_overview_limit_slice.py
@@ -0,0 +1,78 @@
+"""``/health/overview`` builds the full file row only for the files it lists.
+
+The distribution and the defect-accuracy stat read path, score and NLOC off
+every file, so they must not change with ``limit``; the listed rows must be the
+same rows, leads included, whatever the limit.
+"""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+_FILES = 30
+
+
+def _metric(i: int) -> dict:
+ return {
+ "file_path": f"src/f{i:02d}.py",
+ # One score sits a hair under a band edge: the distribution reads the
+ # score at the rounding the file row carries, so it lands Excellent.
+ "score": 8.4996 if i == 29 else float(i) / 3.0,
+ "max_ccn": 1,
+ "max_nesting": 1,
+ "nloc": 10 + i,
+ "has_test_file": False,
+ "module": "src",
+ }
+
+
+def _finding(i: int, kind: str, impact: float) -> dict:
+ return {
+ "file_path": f"src/f{i:02d}.py",
+ "biomarker_type": kind,
+ "severity": "medium",
+ "function_name": None,
+ "line_start": None,
+ "line_end": None,
+ "details": {"prior_defect_count": 2, "window_days": 90},
+ "health_impact": impact,
+ "reason": f"{kind} on {i}",
+ }
+
+
+async def test_listed_rows_and_repo_figures_do_not_move_with_the_limit(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ async with get_session(app.state.session_factory) as session:
+ await crud.save_health_metrics(session, repo["id"], [_metric(i) for i in range(_FILES)])
+ await crud.save_health_findings(
+ session,
+ repo["id"],
+ [_finding(i, "prior_defect", 0.3) for i in range(6)]
+ + [_finding(i, "low_cohesion", 0.4 + i / 10) for i in range(0, _FILES, 2)],
+ )
+
+ async def overview(limit: int) -> dict:
+ resp = await client.get(f"/api/repos/{repo['id']}/health/overview", params={"limit": limit})
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+ narrow, wide = await overview(3), await overview(200)
+
+ assert len(narrow["files"]) == 3
+ assert len(wide["files"]) == _FILES
+ assert narrow["files"] == wide["files"][:3]
+ # Leads still reach the listed rows.
+ assert any(row["primary_biomarker"] for row in narrow["files"])
+ assert narrow["distribution"] == wide["distribution"]
+ assert narrow["distribution"]["total_files"] == _FILES
+ assert narrow["distribution"]["bands"]["excellent"]["files"] >= 1
+ assert narrow["defect_accuracy"] == wide["defect_accuracy"]
+ assert narrow["defect_accuracy"] is not None