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(dead-code): rebuild the findings table on the shared table primitive (#992)

Raghav Chamadiya323a6afd46f8
diff --git a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx
index 6bd0c330b..2c857f99d 100644
--- a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx
+++ b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import { SWRConfig } from "swr";
import type { ReactElement } from "react";
import { DeadCodeView } from "../../src/dead-code/dead-code-view.js";
@@ -29,6 +29,22 @@ vi.mock("sonner", () => ({
},
}));
+/**
+ * The findings table stacks into a mobile card list beside the real table and
+ * lets CSS pick one; jsdom applies no CSS, so a row control matches in both.
+ * These scope row queries to the table.
+ */
+const rowButton = (name: string) =>
+ within(screen.getByRole("table")).getByRole("button", { name });
+const queryRowButton = (name: string) => {
+ const table = screen.queryByRole("table");
+ return table ? within(table).queryByRole("button", { name }) : null;
+};
+const findRowButton = async (name: string) => {
+ await screen.findByRole("table");
+ return rowButton(name);
+};
+
const SUMMARY: DeadCodeSummary = {
total_findings: 3,
confidence_summary: { high: 2, medium: 1, low: 0 },
@@ -196,7 +212,7 @@ describe("DeadCodeView", () => {
renderView(<DeadCodeView adapter={adapter} />);
// No safe pile above it, so the section leads the page already open.
- fireEvent.click(await screen.findByRole("button", { name: "Resolve src/old/legacy.ts" }));
+ fireEvent.click(await findRowButton("Resolve src/old/legacy.ts"));
fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));
// Emptying the list locally must not swap in the "No dead code found"
@@ -204,7 +220,7 @@ describe("DeadCodeView", () => {
// section that remounted collapsed.
await waitFor(() =>
expect(
- screen.queryByRole("button", { name: "Resolve src/old/legacy.ts" }),
+ queryRowButton("Resolve src/old/legacy.ts"),
).not.toBeInTheDocument(),
);
expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();
@@ -213,7 +229,7 @@ describe("DeadCodeView", () => {
await undo.onClick();
await waitFor(() =>
- expect(screen.getByRole("button", { name: "Resolve src/old/legacy.ts" })).toBeInTheDocument(),
+ expect(rowButton("Resolve src/old/legacy.ts")).toBeInTheDocument(),
);
});
@@ -289,13 +305,13 @@ describe("DeadCodeView", () => {
// Open the drill-down table (collapsed by default).
fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));
- fireEvent.click(await screen.findByRole("button", { name: "Resolve src/old/legacy.ts" }));
+ fireEvent.click(await findRowButton("Resolve src/old/legacy.ts"));
fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));
// Optimistically gone from the table.
await waitFor(() =>
expect(
- screen.queryByRole("button", { name: "Resolve src/old/legacy.ts" }),
+ queryRowButton("Resolve src/old/legacy.ts"),
).not.toBeInTheDocument(),
);
@@ -304,7 +320,7 @@ describe("DeadCodeView", () => {
await undo.onClick();
await waitFor(() =>
- expect(screen.getByRole("button", { name: "Resolve src/old/legacy.ts" })).toBeInTheDocument(),
+ expect(rowButton("Resolve src/old/legacy.ts")).toBeInTheDocument(),
);
});
});
diff --git a/packages/ui/__tests__/dead-code/findings-table.test.tsx b/packages/ui/__tests__/dead-code/findings-table.test.tsx
index d96a3351e..fee51a6b2 100644
--- a/packages/ui/__tests__/dead-code/findings-table.test.tsx
+++ b/packages/ui/__tests__/dead-code/findings-table.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import { FindingsTable } from "../../src/dead-code/findings-table.js";
import type { DeadCodeFinding } from "@repowise-dev/types/dead-code";
@@ -53,6 +53,15 @@ function renderTable(findings: DeadCodeFinding[], props: Record<string, unknown>
);
}
+/**
+ * `stacked="sm"` renders the table and the mobile card list side by side and
+ * lets CSS pick one. jsdom applies no CSS, so both are present and every row
+ * control matches twice; scope row-level queries to the table.
+ */
+function inTable() {
+ return within(screen.getByRole("table"));
+}
+
beforeEach(() => {
toastError.mockClear();
noopPatch.mockClear();
@@ -174,6 +183,67 @@ describe("FindingsTable selection", () => {
});
});
+describe("FindingsTable sort and search", () => {
+ /** File paths in render order, read off the real table (not the card list). */
+ function paths() {
+ return inTable()
+ .getAllByRole("row")
+ .slice(1)
+ .map((r) => r.querySelector("a,span[title]")?.getAttribute("title"))
+ .filter(Boolean);
+ }
+
+ it("defaults to the server's confidence-first order", () => {
+ renderTable([
+ finding({ id: "a", file_path: "src/a.ts", confidence: 0.5 }),
+ finding({ id: "b", file_path: "src/b.ts", confidence: 0.9 }),
+ ]);
+
+ expect(paths()).toEqual(["src/b.ts", "src/a.ts"]);
+ });
+
+ it("sorts by a column and flips direction on a second click", () => {
+ renderTable([
+ finding({ id: "a", file_path: "src/a.ts", lines: 5 }),
+ finding({ id: "b", file_path: "src/b.ts", lines: 90 }),
+ ]);
+
+ const header = inTable().getByRole("button", { name: /Lines/ });
+ fireEvent.click(header);
+ expect(paths()).toEqual(["src/b.ts", "src/a.ts"]);
+
+ fireEvent.click(header);
+ expect(paths()).toEqual(["src/a.ts", "src/b.ts"]);
+ });
+
+ it("searches across path, symbol, owner and reason", () => {
+ renderTable([
+ finding({ id: "a", file_path: "src/keep.ts", reason: "No importers" }),
+ finding({ id: "b", file_path: "src/other.ts", reason: "Only self-references" }),
+ ]);
+
+ fireEvent.change(screen.getByLabelText("Search findings"), {
+ target: { value: "self-ref" },
+ });
+
+ expect(paths()).toEqual(["src/other.ts"]);
+ });
+
+ it("offers a way back when the filters have emptied the table", () => {
+ renderTable([finding({ id: "a", file_path: "src/a.ts" })]);
+
+ fireEvent.change(screen.getByLabelText("Search findings"), {
+ target: { value: "nothing matches this" },
+ });
+ expect(screen.queryByRole("table")).not.toBeInTheDocument();
+
+ // Without this the user is left staring at an empty state with no hint
+ // that their own filter, not the repository, is why.
+ fireEvent.click(screen.getByRole("button", { name: "Reset filters" }));
+ expect(paths()).toEqual(["src/a.ts"]);
+ });
+});
+
describe("FindingsTable row affordances", () => {
it("links the file path and opens the row through the host router", () => {
const onNavigate = vi.fn();
@@ -182,10 +252,10 @@ describe("FindingsTable row affordances", () => {
onNavigate,
});
- const link = screen.getByRole("link", { name: "src/a.ts" });
+ const link = inTable().getByRole("link", { name: "src/a.ts" });
expect(link).toHaveAttribute("href", "/repos/repo-1/files/src/a.ts");
- fireEvent.click(screen.getByRole("row", { name: /src\/a\.ts/ }));
+ fireEvent.click(inTable().getByRole("row", { name: /src\/a\.ts/ }));
expect(onNavigate).toHaveBeenCalledWith("/repos/repo-1/files/src/a.ts");
// A plain click on the name routes through the host too, rather than
@@ -199,7 +269,7 @@ describe("FindingsTable row affordances", () => {
const onNavigate = vi.fn();
renderTable([finding({ id: "a" })], { fileHref: (p: string) => `/f/${p}`, onNavigate });
- fireEvent.click(screen.getByLabelText("Select finding src/a.ts"));
+ fireEvent.click(inTable().getByLabelText("Select finding src/a.ts"));
expect(onNavigate).not.toHaveBeenCalled();
});
@@ -207,14 +277,14 @@ describe("FindingsTable row affordances", () => {
it("shows the detector's reason, which previously only the AI prompt saw", () => {
renderTable([finding({ id: "a", reason: "No importers in the dependency graph" })]);
- expect(screen.getByText("No importers in the dependency graph")).toBeInTheDocument();
+ expect(inTable().getByText("No importers in the dependency graph")).toBeInTheDocument();
});
it("offers an AI prompt per row and for the current selection", () => {
const onGeneratePrompt = vi.fn();
renderTable([finding({ id: "a" }), finding({ id: "b" })], { onGeneratePrompt });
- fireEvent.click(screen.getByRole("button", { name: "AI cleanup prompt for src/a.ts" }));
+ fireEvent.click(inTable().getByRole("button", { name: "AI cleanup prompt for src/a.ts" }));
expect(onGeneratePrompt).toHaveBeenCalledWith(["a"]);
fireEvent.click(screen.getByLabelText("Select all findings"));
@@ -226,7 +296,7 @@ describe("FindingsTable row affordances", () => {
const { unmount } = renderTable([finding({ id: "a" })], {
graphHref: (p: string) => `/repos/repo-1/architecture?node=${encodeURIComponent(p)}`,
});
- expect(screen.getByRole("link", { name: "Graph" })).toHaveAttribute(
+ expect(inTable().getByRole("link", { name: "Graph" })).toHaveAttribute(
"href",
"/repos/repo-1/architecture?node=src%2Fa.ts",
);
@@ -260,7 +330,7 @@ describe("FindingsTable row actions", () => {
});
renderTable([finding({ id: "a" })], { onPatch });
- fireEvent.click(screen.getByRole("button", { name: "Resolve src/a.ts" }));
+ fireEvent.click(inTable().getByRole("button", { name: "Resolve src/a.ts" }));
fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));
await waitFor(() => expect(toastError).toHaveBeenCalled());
diff --git a/packages/ui/__tests__/shared/virtualized-table.test.tsx b/packages/ui/__tests__/shared/virtualized-table.test.tsx
index 77731c65c..aba3c9648 100644
--- a/packages/ui/__tests__/shared/virtualized-table.test.tsx
+++ b/packages/ui/__tests__/shared/virtualized-table.test.tsx
@@ -68,4 +68,16 @@ describe("useVirtualRows", () => {
// Windowed: far fewer rows rendered than the full 500.
expect(result.current.virtualRows.length).toBeLessThan(500);
});
+
+ it("gives the spacer the full list height while no window has been measured", () => {
+ // jsdom reports a zero-height viewport, which is also the state of any real
+ // scroll container on first paint. A zero spacer there is a deadlock: no
+ // rows means no height, and no height means the virtualizer never computes
+ // a range, so the container stays empty forever.
+ const { result } = renderHook(() =>
+ useVirtualRows({ count: 500, estimateSize: 40, threshold: 60 }),
+ );
+ expect(result.current.virtualRows).toHaveLength(0);
+ expect(result.current.paddingBottom).toBe(500 * 40);
+ });
});
diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsx
new file mode 100644
index 000000000..118c7791c
--- /dev/null
+++ b/packages/ui/src/dead-code/finding-cells.tsx
@@ -0,0 +1,248 @@
+"use client";
+
+import { useState, type MouseEvent } from "react";
+import { GitBranch } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "../ui/button";
+import { Badge } from "../ui/badge";
+import { ConfirmDialog } from "../ui/confirm-dialog";
+import { RowActions } from "../shared/row-actions";
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { formatConfidence } from "../lib/format";
+import { toFriendlyMessage } from "../lib/errors";
+import { cn } from "../lib/cn";
+import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";
+
+/**
+ * The cell renderers behind the findings table's columns. They live apart from
+ * `findings-table.tsx` because the actions cell owns per-row state (a pending
+ * patch and its confirm dialog) that a plain `render(row)` closure cannot hold.
+ */
+
+const STATUS_LABELS: Record<
+ string,
+ { title: string; description: string; confirmLabel: string; destructive: boolean }
+> = {
+ resolved: {
+ title: "Resolve finding?",
+ description: "Mark this finding as resolved. You can undo from the toast.",
+ confirmLabel: "Resolve",
+ destructive: false,
+ },
+ acknowledged: {
+ title: "Acknowledge finding?",
+ description: "Mark this finding as acknowledged.",
+ confirmLabel: "Acknowledge",
+ destructive: false,
+ },
+ false_positive: {
+ title: "Mark as false positive?",
+ // Deliberately does not promise exclusion from future analyses: a
+ // re-analysis re-inserts every detected finding under a fresh id, so the
+ // marking does not carry across passes. Upgrade path is a stable finding
+ // identity server-side, then this copy can make the stronger promise.
+ description: "This finding will be hidden from the list. You can undo from the toast.",
+ confirmLabel: "Mark FP",
+ destructive: true,
+ },
+};
+
+export interface FindingIdentityProps {
+ finding: DeadCodeFinding;
+ /** Href for the file detail page; makes the path a link. */
+ href?: string | undefined;
+ /** Client-side navigation, so a plain click does not trigger a full page load. */
+ onNavigate?: ((href: string) => void) | undefined;
+}
+
+/**
+ * File path (linked when the host can route), symbol name, and the detector's
+ * reason. The reason was already being fed to the AI prompt builder, so the
+ * model saw the justification and the human did not.
+ */
+export function FindingIdentity({ finding, href, onNavigate }: FindingIdentityProps) {
+ const onLinkClick = (e: MouseEvent<HTMLAnchorElement>) => {
+ e.stopPropagation();
+ if (!href || !onNavigate) return;
+ // Modified and non-primary clicks keep the browser's own behavior, so
+ // "open in new tab" and middle-click still work off the real href.
+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
+ e.preventDefault();
+ onNavigate(href);
+ };
+
+ return (
+ <div className="min-w-0">
+ {href ? (
+ <a
+ href={href}
+ onClick={onLinkClick}
+ className="block truncate font-mono text-xs text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ title={finding.file_path}
+ >
+ {finding.file_path}
+ </a>
+ ) : (
+ <span
+ className="block truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={finding.file_path}
+ >
+ {finding.file_path}
+ </span>
+ )}
+ {finding.symbol_name && (
+ <span
+ className="block truncate font-mono text-xs text-[var(--color-text-tertiary)]"
+ title={finding.symbol_name}
+ >
+ {finding.symbol_name}
+ </span>
+ )}
+ {finding.reason && (
+ <span
+ className="mt-0.5 block truncate text-2xs text-[var(--color-text-tertiary)]"
+ title={finding.reason}
+ >
+ {finding.reason}
+ </span>
+ )}
+ </div>
+ );
+}
+
+/** Confidence, coloured on the shared tier boundaries. */
+export function FindingConfidence({ finding }: { finding: DeadCodeFinding }) {
+ return (
+ <span
+ className={cn(
+ "font-medium tabular-nums text-xs",
+ finding.confidence >= 0.8
+ ? "text-[var(--color-error)]"
+ : finding.confidence >= 0.6
+ ? "text-[var(--color-warning)]"
+ : "text-[var(--color-text-secondary)]",
+ )}
+ >
+ {formatConfidence(finding.confidence)}
+ </span>
+ );
+}
+
+/** "Candidate" vs "Review", with the risk factors behind the tooltip. */
+export function FindingSafety({ finding }: { finding: DeadCodeFinding }) {
+ if (finding.safe_to_delete) return <Badge variant="fresh">Candidate</Badge>;
+ return (
+ <Badge
+ variant="default"
+ title={
+ finding.risk_factors && finding.risk_factors.length > 0
+ ? `Runtime-load risk (${finding.risk_factors.join(", ")}) - verify it isn't loaded outside static imports before deleting`
+ : "Lower confidence - verify before deleting"
+ }
+ >
+ Review
+ </Badge>
+ );
+}
+
+export interface FindingRowActionsProps {
+ finding: DeadCodeFinding;
+ /** Injected mutation - returns the updated finding (host owns the API + toasts). */
+ onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;
+ /** Href for the dependency graph focused on this file; omit to hide the action. */
+ graphHref?: ((path: string) => string) | undefined;
+ /** When set, the row offers an AI cleanup prompt scoped to this finding. */
+ onGeneratePrompt?: ((id: string) => void) | undefined;
+}
+
+/** Per-row status actions: resolve, acknowledge, or mark false positive. */
+export function FindingRowActions({
+ finding,
+ onPatch,
+ graphHref,
+ onGeneratePrompt,
+}: FindingRowActionsProps) {
+ const [pending, setPending] = useState(false);
+ const [confirmStatus, setConfirmStatus] = useState<string | null>(null);
+
+ const applyPatch = async (status: string) => {
+ setPending(true);
+ try {
+ await onPatch(finding.id, { status: status as DeadCodeStatus });
+ setConfirmStatus(null);
+ } catch (err) {
+ // Without this the rejection escapes to the console and the dialog sits
+ // open with no explanation of why nothing happened.
+ toast.error(`Couldn't update finding: ${toFriendlyMessage(err)}`);
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const confirmConfig = confirmStatus ? STATUS_LABELS[confirmStatus] : null;
+
+ return (
+ <span onClick={(e) => e.stopPropagation()}>
+ <span className="flex flex-wrap items-center justify-end gap-1">
+ {onGeneratePrompt && (
+ <AiPromptButton
+ variant="icon"
+ label={`AI cleanup prompt for ${finding.file_path}`}
+ onClick={() => onGeneratePrompt(finding.id)}
+ />
+ )}
+ {graphHref && (
+ <RowActions
+ actions={[{ icon: GitBranch, label: "Graph", href: graphHref(finding.file_path) }]}
+ />
+ )}
+ {finding.status === "open" && (
+ <>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={pending}
+ onClick={() => setConfirmStatus("resolved")}
+ className="h-6 px-2 text-xs text-[var(--color-success)] hover:text-[var(--color-success)]"
+ aria-label={`Resolve ${finding.file_path}`}
+ >
+ Resolve
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={pending}
+ onClick={() => setConfirmStatus("acknowledged")}
+ className="h-6 px-2 text-xs"
+ aria-label={`Acknowledge ${finding.file_path}`}
+ >
+ Ack
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={pending}
+ onClick={() => setConfirmStatus("false_positive")}
+ className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"
+ aria-label={`Mark ${finding.file_path} as false positive`}
+ >
+ FP
+ </Button>
+ </>
+ )}
+ </span>
+ {confirmConfig && (
+ <ConfirmDialog
+ open={confirmStatus !== null}
+ onOpenChange={(o) => !o && setConfirmStatus(null)}
+ title={confirmConfig.title}
+ description={confirmConfig.description}
+ confirmLabel={confirmConfig.confirmLabel}
+ destructive={confirmConfig.destructive}
+ loading={pending}
+ onConfirm={() => applyPatch(confirmStatus!)}
+ />
+ )}
+ </span>
+ );
+}
diff --git a/packages/ui/src/dead-code/finding-row.tsx b/packages/ui/src/dead-code/finding-row.tsx
deleted file mode 100644
index 935df8cd2..000000000
--- a/packages/ui/src/dead-code/finding-row.tsx
+++ /dev/null
@@ -1,266 +0,0 @@
-"use client";
-
-import { useState, type MouseEvent } from "react";
-import { GitBranch } from "lucide-react";
-import { toast } from "sonner";
-import { Button } from "../ui/button";
-import { Badge } from "../ui/badge";
-import { ConfirmDialog } from "../ui/confirm-dialog";
-import { RowActions } from "../shared/row-actions";
-import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";
-import { AiPromptButton } from "../health/ai-prompt-button";
-import { formatConfidence } from "../lib/format";
-import { toFriendlyMessage } from "../lib/errors";
-import { cn } from "../lib/cn";
-import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";
-
-const STATUS_LABELS: Record<
- string,
- { title: string; description: string; confirmLabel: string; destructive: boolean }
-> = {
- resolved: {
- title: "Resolve finding?",
- description: "Mark this finding as resolved. You can undo from the toast.",
- confirmLabel: "Resolve",
- destructive: false,
- },
- acknowledged: {
- title: "Acknowledge finding?",
- description: "Mark this finding as acknowledged.",
- confirmLabel: "Acknowledge",
- destructive: false,
- },
- false_positive: {
- title: "Mark as false positive?",
- // Deliberately does not promise exclusion from future analyses: a
- // re-analysis re-inserts every detected finding under a fresh id, so the
- // marking does not carry across passes. Upgrade path is a stable finding
- // identity server-side, then this copy can make the stronger promise.
- description: "This finding will be hidden from the list. You can undo from the toast.",
- confirmLabel: "Mark FP",
- destructive: true,
- },
-};
-
-export interface FindingRowProps {
- finding: DeadCodeFinding;
- selected: boolean;
- onToggle: (id: string) => void;
- /** Injected mutation — returns the updated finding (host owns the API + toasts). */
- onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;
- /** Href for the file detail page; the path becomes a link and the row opens it. */
- fileHref?: ((path: string) => string) | undefined;
- /** Client-side navigation for a row click (falls back to the anchor alone). */
- onNavigate?: ((href: string) => void) | undefined;
- /** Href for the dependency graph focused on this file; omit to hide the action. */
- graphHref?: ((path: string) => string) | undefined;
- /** When set, the row offers an AI cleanup prompt scoped to this finding. */
- onGeneratePrompt?: ((id: string) => void) | undefined;
-}
-
-/**
- * Pure dead-code findings row: presentation + row-level status actions. The host
- * injects the patch mutation so this component carries no data/transport deps.
- */
-export function FindingRow({
- finding,
- selected,
- onToggle,
- onPatch,
- fileHref,
- onNavigate,
- graphHref,
- onGeneratePrompt,
-}: FindingRowProps) {
- const [pending, setPending] = useState(false);
- const [confirmStatus, setConfirmStatus] = useState<string | null>(null);
-
- const applyPatch = async (status: string) => {
- setPending(true);
- try {
- await onPatch(finding.id, { status: status as DeadCodeStatus });
- setConfirmStatus(null);
- } catch (err) {
- // Without this the rejection escapes to the console and the dialog sits
- // open with no explanation of why nothing happened.
- toast.error(`Couldn't update finding: ${toFriendlyMessage(err)}`);
- } finally {
- setPending(false);
- }
- };
-
- const requestPatch = (status: string) => setConfirmStatus(status);
- const confirmConfig = confirmStatus ? STATUS_LABELS[confirmStatus] : null;
-
- const href = fileHref?.(finding.file_path);
- // Row click navigates only when the host can route; the anchor still carries
- // a real href so middle-click and "open in new tab" keep working.
- const openFile = href && onNavigate ? () => onNavigate(href) : undefined;
-
- // Hand a plain left click on the file name to the host router too, so it does
- // not fall through to a full page load while the row around it routes
- // client-side. Modified and non-primary clicks keep the browser's behavior.
- const onLinkClick = (e: MouseEvent<HTMLAnchorElement>) => {
- e.stopPropagation();
- if (!openFile) return;
- if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
- e.preventDefault();
- openFile();
- };
-
- return (
- <tr
- className={cn(
- "border-b border-[var(--color-table-divider)] transition-colors last:border-0",
- selected ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]",
- openFile && CLICKABLE_ROW_CLS,
- )}
- {...(openFile ? clickableRowProps(openFile) : {})}
- >
- <td className="px-4 py-2.5" onClick={(e) => e.stopPropagation()}>
- <input
- type="checkbox"
- checked={selected}
- onChange={() => onToggle(finding.id)}
- aria-label={`Select finding ${finding.file_path}`}
- className="rounded border-[var(--color-border-default)]"
- />
- </td>
- <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[200px] max-w-[480px]">
- {href ? (
- <a
- href={href}
- onClick={onLinkClick}
- className="truncate block hover:text-[var(--color-accent-primary)] hover:underline"
- title={finding.file_path}
- >
- {finding.file_path}
- </a>
- ) : (
- <span className="truncate block" title={finding.file_path}>
- {finding.file_path}
- </span>
- )}
- {finding.symbol_name && (
- <span className="block truncate text-[var(--color-text-tertiary)]" title={finding.symbol_name}>
- {finding.symbol_name}
- </span>
- )}
- {/* The detector's justification. It was already being fed to the AI
- prompt builder, so the model saw the reasoning and the human did not. */}
- {finding.reason && (
- <span
- className="mt-0.5 block truncate font-sans text-[11px] text-[var(--color-text-tertiary)]"
- title={finding.reason}
- >
- {finding.reason}
- </span>
- )}
- </td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums">
- <span
- className={cn(
- "font-medium",
- finding.confidence >= 0.8
- ? "text-[var(--color-error)]"
- : finding.confidence >= 0.6
- ? "text-[var(--color-warning)]"
- : "text-[var(--color-text-secondary)]",
- )}
- >
- {formatConfidence(finding.confidence)}
- </span>
- </td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">
- {finding.primary_owner ?? "—"}
- </td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums hidden md:table-cell">
- {finding.lines}
- </td>
- <td className="px-4 py-2.5 hidden sm:table-cell">
- {finding.safe_to_delete ? (
- <Badge variant="fresh">Candidate</Badge>
- ) : (
- <Badge
- variant="default"
- title={
- finding.risk_factors && finding.risk_factors.length > 0
- ? `Runtime-load risk (${finding.risk_factors.join(", ")}) — verify it isn't loaded outside static imports before deleting`
- : "Lower confidence — verify before deleting"
- }
- >
- Review
- </Badge>
- )}
- </td>
- <td className="px-4 py-2.5" onClick={(e) => e.stopPropagation()}>
- <div className="flex items-center gap-1 flex-wrap justify-end">
- {onGeneratePrompt && (
- <AiPromptButton
- variant="icon"
- label={`AI cleanup prompt for ${finding.file_path}`}
- onClick={() => onGeneratePrompt(finding.id)}
- />
- )}
- {graphHref && (
- <RowActions
- actions={[
- {
- icon: GitBranch,
- label: "Graph",
- href: graphHref(finding.file_path),
- },
- ]}
- />
- )}
- {finding.status === "open" && (
- <div className="flex items-center gap-1 flex-wrap justify-end">
- <Button
- size="sm"
- variant="ghost"
- disabled={pending}
- onClick={() => requestPatch("resolved")}
- className="h-6 px-2 text-xs text-[var(--color-success)] hover:text-[var(--color-success)]"
- aria-label={`Resolve ${finding.file_path}`}
- >
- Resolve
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={pending}
- onClick={() => requestPatch("acknowledged")}
- className="h-6 px-2 text-xs"
- aria-label={`Acknowledge ${finding.file_path}`}
- >
- Ack
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={pending}
- onClick={() => requestPatch("false_positive")}
- className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"
- aria-label={`Mark ${finding.file_path} as false positive`}
- >
- FP
- </Button>
- </div>
- )}
- </div>
- </td>
- {confirmConfig && (
- <ConfirmDialog
- open={confirmStatus !== null}
- onOpenChange={(o) => !o && setConfirmStatus(null)}
- title={confirmConfig.title}
- description={confirmConfig.description}
- confirmLabel={confirmConfig.confirmLabel}
- destructive={confirmConfig.destructive}
- loading={pending}
- onConfirm={() => applyPatch(confirmStatus!)}
- />
- )}
- </tr>
- );
-}
diff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsx
index 9cf3eaeb6..e44863c5e 100644
--- a/packages/ui/src/dead-code/findings-table.tsx
+++ b/packages/ui/src/dead-code/findings-table.tsx
@@ -1,17 +1,25 @@
"use client";
import { useMemo, useState } from "react";
+import { Search } from "lucide-react";
import { toast } from "sonner";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "../ui/tabs";
import { Button } from "../ui/button";
+import { Input } from "../ui/input";
import { Slider } from "../ui/slider";
import { Switch } from "../ui/switch";
import { TableSkeleton } from "../shared/loading-skeletons";
import { ConfirmDialog } from "../ui/confirm-dialog";
import { EmptyState } from "../shared/empty-state";
+import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
import { toFriendlyMessage } from "../lib/errors";
import { AiPromptButton } from "../health/ai-prompt-button";
-import { FindingRow } from "./finding-row";
+import {
+ FindingIdentity,
+ FindingConfidence,
+ FindingSafety,
+ FindingRowActions,
+} from "./finding-cells";
import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";
/**
@@ -40,6 +48,22 @@ function labelForKind(kind: string): string {
.join(" ");
}
+type SortKey = "path" | "confidence" | "owner" | "lines";
+
+/** Sort value per column; strings compare with localeCompare, numbers subtract. */
+function sortValue(f: DeadCodeFinding, key: SortKey): string | number {
+ switch (key) {
+ case "path":
+ return `${f.file_path} ${f.symbol_name ?? ""}`;
+ case "owner":
+ return f.primary_owner ?? "";
+ case "lines":
+ return f.lines;
+ case "confidence":
+ return f.confidence;
+ }
+}
+
export interface FindingsTableProps {
/** Full open-findings slice; the table filters by kind / confidence / safety client-side. */
findings: DeadCodeFinding[];
@@ -59,10 +83,16 @@ export interface FindingsTableProps {
}
/**
- * Canonical interactive dead-code table: kind tabs, a confidence slider (the
- * single confidence control for the spine), cleanup-ready filter, bulk resolve,
- * and per-row status actions. Pure presentation — the host injects the data
- * slice and the patch/bulk mutations, so this propagates via the package.
+ * Canonical interactive dead-code table: kind tabs, a search box, sortable
+ * columns, a confidence slider (the single confidence control for the spine),
+ * cleanup-ready filter, bulk resolve, and per-row status actions.
+ *
+ * Built on the shared `ResponsiveTable` so it collapses to stacked cards on
+ * small screens and windows its rows — the fetch is capped at 500, which is
+ * well past the point where rendering every `<tr>` costs a visible frame.
+ *
+ * Pure presentation — the host injects the data slice and the patch/bulk
+ * mutations, so this propagates via the package.
*/
export function FindingsTable({
findings,
@@ -77,6 +107,9 @@ export function FindingsTable({
const [activeTab, setActiveTab] = useState<string | null>(null);
const [minConfidence, setMinConfidence] = useState(0.4);
const [safeOnly, setSafeOnly] = useState(false);
+ const [query, setQuery] = useState("");
+ const [sortKey, setSortKey] = useState<SortKey>("confidence");
+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [selected, setSelected] = useState<Set<string>>(new Set());
const [bulkPending, setBulkPending] = useState(false);
const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false);
@@ -92,24 +125,58 @@ export function FindingsTable({
}, [findings]);
const byKind = useMemo(() => {
+ const needle = query.trim().toLowerCase();
const buckets: Record<string, DeadCodeFinding[]> = {};
for (const t of tabs) buckets[t.value] = [];
for (const f of findings) {
if (f.confidence < minConfidence) continue;
if (safeOnly && !f.safe_to_delete) continue;
+ if (
+ needle &&
+ !f.file_path.toLowerCase().includes(needle) &&
+ !(f.symbol_name ?? "").toLowerCase().includes(needle) &&
+ !(f.primary_owner ?? "").toLowerCase().includes(needle) &&
+ !(f.reason ?? "").toLowerCase().includes(needle)
+ ) {
+ continue;
+ }
buckets[f.kind]?.push(f);
}
return buckets;
- }, [findings, tabs, minConfidence, safeOnly]);
+ }, [findings, tabs, minConfidence, safeOnly, query]);
// The active tab can disappear when the slice changes (a refetch, a resolved
// last row); fall back to the first tab rather than rendering nothing.
const effectiveTab =
activeTab && tabs.some((t) => t.value === activeTab) ? activeTab : (tabs[0]?.value ?? null);
- const current = useMemo(
- () => (effectiveTab ? (byKind[effectiveTab] ?? []) : []),
- [byKind, effectiveTab],
- );
+
+ // Rows arrived in server order (confidence desc) with no way to reorder them.
+ // The default keeps that order so the rewrite does not silently reshuffle
+ // anyone's table; every column can now take over.
+ const current = useMemo(() => {
+ const rows = effectiveTab ? (byKind[effectiveTab] ?? []) : [];
+ const dir = sortOrder === "asc" ? 1 : -1;
+ // Copy before sorting: never mutate the caller's findings array in place.
+ return [...rows].sort((a, b) => {
+ const av = sortValue(a, sortKey);
+ const bv = sortValue(b, sortKey);
+ const cmp =
+ typeof av === "string" && typeof bv === "string" ? av.localeCompare(bv) : Number(av) - Number(bv);
+ // Ties would otherwise fall back to bucket order, which shifts as filters
+ // change; the id is stable and unique.
+ return cmp !== 0 ? cmp * dir : a.id.localeCompare(b.id);
+ });
+ }, [byKind, effectiveTab, sortKey, sortOrder]);
+
+ const toggleSort = (key: string) => {
+ if (key === sortKey) {
+ setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
+ return;
+ }
+ setSortKey(key as SortKey);
+ // Paths read best A→Z; every metric reads best biggest-first.
+ setSortOrder(key === "path" || key === "owner" ? "asc" : "desc");
+ };
// Selection is scoped to what is on screen. Without this, raising the
// confidence slider after selecting rows would resolve findings the user can
@@ -135,6 +202,14 @@ export function FindingsTable({
setSelected(allVisibleSelected ? new Set() : new Set(current.map((f) => f.id)));
};
+ const resetFilters = () => {
+ setMinConfidence(0.4);
+ setSafeOnly(false);
+ setQuery("");
+ };
+
+ const filtersActive = minConfidence > 0.4 || safeOnly || query.trim() !== "";
+
const resolveSelected = async () => {
if (!onBulkResolve) return;
setBulkPending(true);
@@ -152,10 +227,152 @@ export function FindingsTable({
}
};
+ const columns = useMemo<ResponsiveColumn<DeadCodeFinding>[]>(() => {
+ const checkbox = (f: DeadCodeFinding) => (
+ <span onClick={(e) => e.stopPropagation()}>
+ <input
+ type="checkbox"
+ checked={selected.has(f.id)}
+ onChange={() => toggleSelect(f.id)}
+ aria-label={`Select finding ${f.file_path}`}
+ className="rounded border-[var(--color-border-default)]"
+ />
+ </span>
+ );
+
+ return [
+ {
+ key: "select",
+ header: (
+ <span onClick={(e) => e.stopPropagation()}>
+ <input
+ type="checkbox"
+ checked={allVisibleSelected}
+ onChange={toggleSelectAll}
+ aria-label="Select all findings"
+ className="rounded border-[var(--color-border-default)]"
+ />
+ </span>
+ ),
+ headerClassName: "w-8",
+ // Stacked cards give the first visible column to the card title, so the
+ // checkbox rides along with the identity cell there instead.
+ hideInCard: true,
+ render: checkbox,
+ },
+ {
+ key: "path",
+ header: "File / Symbol",
+ sortable: true,
+ cellClassName: "min-w-[200px] max-w-[480px]",
+ render: (f) => (
+ <FindingIdentity
+ finding={f}
+ href={fileHref?.(f.file_path)}
+ onNavigate={onNavigate}
+ />
+ ),
+ mobileRender: (f) => (
+ <span className="flex items-start gap-2">
+ {checkbox(f)}
+ <FindingIdentity
+ finding={f}
+ href={fileHref?.(f.file_path)}
+ onNavigate={onNavigate}
+ />
+ </span>
+ ),
+ },
+ {
+ key: "confidence",
+ header: "Confidence",
+ mobileLabel: "Confidence",
+ sortable: true,
+ headerClassName: "w-24",
+ render: (f) => <FindingConfidence finding={f} />,
+ },
+ {
+ key: "owner",
+ header: "Owner",
+ sortable: true,
+ priority: 2,
+ render: (f) => (
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {f.primary_owner ?? "—"}
+ </span>
+ ),
+ },
+ {
+ key: "lines",
+ header: "Lines",
+ sortable: true,
+ priority: 2,
+ align: "right",
+ headerClassName: "w-16",
+ render: (f) => (
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{f.lines}</span>
+ ),
+ },
+ {
+ key: "safety",
+ header: "Safety",
+ mobileLabel: "Safety",
+ // The badge's tooltip is the only place risk_factors surface, so keep
+ // it on tablet widths where the old markup showed it.
+ priority: 2,
+ headerClassName: "w-20",
+ render: (f) => <FindingSafety finding={f} />,
+ },
+ {
+ key: "actions",
+ header: <span className="sr-only">Actions</span>,
+ mobileLabel: "Actions",
+ headerClassName: "w-36",
+ align: "right",
+ render: (f) => (
+ <FindingRowActions
+ finding={f}
+ onPatch={onPatch}
+ graphHref={graphHref}
+ {...(onGeneratePrompt
+ ? { onGeneratePrompt: (id: string) => onGeneratePrompt([id]) }
+ : {})}
+ />
+ ),
+ },
+ ];
+ // `selected` and `allVisibleSelected` drive the checkbox state; the rest are
+ // the injected callbacks.
+ }, [
+ selected,
+ allVisibleSelected,
+ fileHref,
+ onNavigate,
+ graphHref,
+ onGeneratePrompt,
+ onPatch,
+ current,
+ ]);
+
+ const openFile =
+ fileHref && onNavigate
+ ? (f: DeadCodeFinding) => onNavigate(fileHref(f.file_path))
+ : undefined;
+
return (
<div className="space-y-4">
{/* Controls — the confidence slider is the only confidence axis. */}
<div className="flex flex-wrap items-center gap-4">
+ <div className="relative">
+ <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search path, symbol, owner, reason…"
+ aria-label="Search findings"
+ className="h-8 w-full pl-8 text-xs sm:w-72"
+ />
+ </div>
<div className="flex items-center gap-2">
<label htmlFor="min-confidence" className="text-xs text-[var(--color-text-secondary)]">
Min confidence: {Math.round(minConfidence * 100)}%
@@ -171,7 +388,7 @@ export function FindingsTable({
className="w-28"
/>
</div>
- <label className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] cursor-pointer select-none">
+ <label className="flex cursor-pointer select-none items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
<Switch checked={safeOnly} onCheckedChange={setSafeOnly} />
Cleanup-ready only
</label>
@@ -213,98 +430,65 @@ export function FindingsTable({
description="No open dead-code findings for this repository."
/>
) : (
- <Tabs
- // Non-null in this branch: tabs is non-empty, so effectiveTab resolved.
- value={effectiveTab ?? ""}
- onValueChange={(v) => {
- setActiveTab(v);
- // Selection is per-kind; clearing on tab change keeps "Resolve N
- // selected" and the select-all checkbox scoped to the visible rows.
- setSelected(new Set());
- }}
- >
- <TabsList>
- {tabs.map((t) => (
- <TabsTrigger key={t.value} value={t.value}>
- {t.label}
- {(byKind[t.value]?.length ?? 0) > 0 && (
- <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">
- {byKind[t.value]?.length}
- </span>
- )}
- </TabsTrigger>
- ))}
- </TabsList>
+ <Tabs
+ // Non-null in this branch: tabs is non-empty, so effectiveTab resolved.
+ value={effectiveTab ?? ""}
+ onValueChange={(v) => {
+ setActiveTab(v);
+ // Selection is per-kind; clearing on tab change keeps "Resolve N
+ // selected" and the select-all checkbox scoped to the visible rows.
+ setSelected(new Set());
+ }}
+ >
+ <TabsList>
+ {tabs.map((t) => (
+ <TabsTrigger key={t.value} value={t.value}>
+ {t.label}
+ {(byKind[t.value]?.length ?? 0) > 0 && (
+ <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">
+ {byKind[t.value]?.length}
+ </span>
+ )}
+ </TabsTrigger>
+ ))}
+ </TabsList>
- {/* One content panel for the active tab only. Rendering a panel per tab
- and filling each with the *active* tab's rows happened to work
- because Radix unmounts inactive content, which is a trap waiting on
- whoever adds forceMount. */}
- <TabsContent value={effectiveTab ?? ""}>
- {current.length === 0 ? (
- <EmptyState
- title="No findings"
- description="No open findings for this category with current filters."
- />
- ) : (
- <div className="border border-[var(--color-border-default)] overflow-x-auto overflow-hidden mt-2">
- <table className="w-full text-sm">
- <caption className="sr-only">Dead code findings</caption>
- <thead className="sticky top-0 z-10 bg-[var(--color-bg-surface)]">
- <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
- <th scope="col" className="px-4 py-2.5 w-8">
- <input
- type="checkbox"
- checked={allVisibleSelected}
- onChange={toggleSelectAll}
- aria-label="Select all findings"
- className="rounded border-[var(--color-border-default)]"
- />
- </th>
- <th scope="col" className="px-4 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- File / Symbol
- </th>
- <th scope="col" className="px-4 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24">
- Confidence
- </th>
- <th scope="col" className="px-4 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">
- Owner
- </th>
- <th scope="col" className="px-4 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-16 hidden md:table-cell">
- Lines
- </th>
- <th scope="col" className="px-4 py-2.5 w-20 hidden sm:table-cell">
- <span className="sr-only">Safety</span>
- </th>
- {/* No status column: the fetch only ever asks for open
- findings, so the badge could only ever say "open". */}
- <th scope="col" className="px-4 py-2.5 w-36">
- <span className="sr-only">Actions</span>
- </th>
- </tr>
- </thead>
- <tbody>
- {current.map((f) => (
- <FindingRow
- key={f.id}
- finding={f}
- selected={selected.has(f.id)}
- onToggle={toggleSelect}
- onPatch={onPatch}
- fileHref={fileHref}
- onNavigate={onNavigate}
- graphHref={graphHref}
- {...(onGeneratePrompt
- ? { onGeneratePrompt: (id: string) => onGeneratePrompt([id]) }
- : {})}
- />
- ))}
- </tbody>
- </table>
- </div>
- )}
- </TabsContent>
- </Tabs>
+ {/* One content panel for the active tab only. Rendering a panel per tab
+ and filling each with the *active* tab's rows happened to work
+ because Radix unmounts inactive content, which is a trap waiting on
+ whoever adds forceMount. */}
+ <TabsContent value={effectiveTab ?? ""} className="mt-2">
+ <ResponsiveTable<DeadCodeFinding>
+ columns={columns}
+ rows={current}
+ rowKey={(f) => f.id}
+ caption="Dead code findings"
+ stacked="sm"
+ sortField={sortKey}
+ sortOrder={sortOrder}
+ onSort={toggleSort}
+ virtualize={{ estimateRowHeight: 56, estimateCardHeight: 96 }}
+ // The hover class the primitive applies is a different Tailwind
+ // variant, so it survives the merge and would blank the selected
+ // tint the moment the pointer lands on a selected row.
+ rowClassName={(f) =>
+ selected.has(f.id)
+ ? "bg-[var(--color-accent-muted)] hover:bg-[var(--color-accent-muted)]"
+ : undefined
+ }
+ {...(openFile ? { onRowClick: openFile } : {})}
+ empty={
+ <EmptyState
+ title="No findings"
+ description="No open findings for this category with current filters."
+ {...(filtersActive
+ ? { action: { label: "Reset filters", onClick: resetFilters } }
+ : {})}
+ />
+ }
+ />
+ </TabsContent>
+ </Tabs>
)}
</div>
);
diff --git a/packages/ui/src/dead-code/index.ts b/packages/ui/src/dead-code/index.ts
index 61c0f0dcd..d6c3ea974 100644
--- a/packages/ui/src/dead-code/index.ts
+++ b/packages/ui/src/dead-code/index.ts
@@ -3,6 +3,6 @@ export * from "./safe-to-delete-pile";
export * from "./owner-leaderboard";
export * from "./findings-breakdown-grid";
export * from "./findings-table";
-export * from "./finding-row";
+export * from "./finding-cells";
export * from "./dead-code-adapter";
export * from "./dead-code-view";
diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.ts
index a7811abf2..259df918a 100644
--- a/packages/ui/src/shared/index.ts
+++ b/packages/ui/src/shared/index.ts
@@ -11,6 +11,7 @@ export {
CLICKABLE_ROW_CLS,
type ResponsiveColumn,
type ResponsiveTableProps,
+ type ResponsiveTableVirtualization,
type ColumnPriority,
} from "./responsive-table";
export {
diff --git a/packages/ui/src/shared/responsive-table/index.ts b/packages/ui/src/shared/responsive-table/index.ts
index 3000fa4cd..81f331f19 100644
--- a/packages/ui/src/shared/responsive-table/index.ts
+++ b/packages/ui/src/shared/responsive-table/index.ts
@@ -4,5 +4,6 @@ export {
CLICKABLE_ROW_CLS,
type ResponsiveColumn,
type ResponsiveTableProps,
+ type ResponsiveTableVirtualization,
type ColumnPriority,
} from "./responsive-table";
diff --git a/packages/ui/src/shared/responsive-table/responsive-table.tsx b/packages/ui/src/shared/responsive-table/responsive-table.tsx
index 011e82083..ad01bc974 100644
--- a/packages/ui/src/shared/responsive-table/responsive-table.tsx
+++ b/packages/ui/src/shared/responsive-table/responsive-table.tsx
@@ -3,6 +3,7 @@
import * as React from "react";
import { ArrowDown, ArrowUp } from "lucide-react";
import { cn } from "../../lib/cn";
+import { useVirtualRows } from "../virtualized-table/use-virtual-rows";
/**
* ResponsiveTable — shared table primitive with a column-priority API.
@@ -18,6 +19,11 @@ import { cn } from "../../lib/cn";
* renders as the card title and the remaining columns render as label/value
* rows (via `mobileRender` when provided, else `render`).
*
+ * With `virtualize`, both the row body and the stacked card list are windowed
+ * through {@link useVirtualRows}. Stacked mode keeps both trees in the DOM (CSS
+ * picks one), so a long list has to window both or it only pays half the saving.
+ * Below the hook's threshold nothing is windowed and the markup is unchanged.
+ *
* Purely presentational: rows in, callbacks out. No routing, no data fetching.
*/
@@ -41,12 +47,28 @@ export interface ResponsiveColumn<T> {
hideInCard?: boolean | undefined;
}
+/** Windowing knobs; presence of the object is what turns virtualization on. */
+export interface ResponsiveTableVirtualization {
+ /** Estimated `<tr>` height in px. Default 44. */
+ estimateRowHeight?: number | undefined;
+ /** Estimated stacked-card height in px. Default 76 (title + one meta line). */
+ estimateCardHeight?: number | undefined;
+ /** Below this many rows, render everything. Default 60 (the hook's own). */
+ threshold?: number | undefined;
+ /** Max height of the scroll viewport. Default 600. */
+ maxHeight?: number | string | undefined;
+}
+
export interface ResponsiveTableProps<T> {
columns: ResponsiveColumn<T>[];
rows: T[];
rowKey: (row: T) => string;
onRowClick?: ((row: T) => void) | undefined;
selectedKey?: string | null | undefined;
+ /** Extra per-row classes — e.g. a multi-select highlight `selectedKey` can't express. */
+ rowClassName?: ((row: T) => string | undefined) | undefined;
+ /** Window the rows (and the stacked cards) instead of rendering all of them. */
+ virtualize?: ResponsiveTableVirtualization | undefined;
sortField?: string | undefined;
sortOrder?: "asc" | "desc" | undefined;
onSort?: ((key: string) => void) | undefined;
@@ -103,12 +125,24 @@ export function clickableRowProps<E extends HTMLElement>(activate: () => void) {
export const CLICKABLE_ROW_CLS =
"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent-primary)]";
+const NOOP_MEASURE = () => {};
+
+/** The window of rows to render plus the spacer heights standing in for the rest. */
+interface Window<T> {
+ items: { row: T; index: number }[];
+ paddingTop: number;
+ paddingBottom: number;
+ measure: (el: HTMLElement | null) => void;
+}
+
export function ResponsiveTable<T>({
columns,
rows,
rowKey,
onRowClick,
selectedKey,
+ rowClassName,
+ virtualize,
sortField,
sortOrder = "desc",
onSort,
@@ -118,12 +152,61 @@ export function ResponsiveTable<T>({
className,
bare,
}: ResponsiveTableProps<T>) {
+ // Hooks run unconditionally, so `count: 0` (not an early return) is how the
+ // non-virtualized path opts out.
+ const count = virtualize ? rows.length : 0;
+ const shared = {
+ ...(virtualize?.threshold !== undefined ? { threshold: virtualize.threshold } : {}),
+ };
+ const rowWindow = useVirtualRows<HTMLDivElement>({
+ count,
+ estimateSize: virtualize?.estimateRowHeight ?? 44,
+ ...shared,
+ });
+ const cardWindow = useVirtualRows<HTMLDivElement>({
+ count,
+ estimateSize: virtualize?.estimateCardHeight ?? 76,
+ ...shared,
+ });
+
+ const windowFor = (w: typeof rowWindow): Window<T> =>
+ virtualize
+ ? {
+ items: w.virtualRows.flatMap((vr) => {
+ const row = rows[vr.index];
+ return row === undefined ? [] : [{ row, index: vr.index }];
+ }),
+ paddingTop: w.paddingTop,
+ paddingBottom: w.paddingBottom,
+ measure: w.measureElement,
+ }
+ : {
+ items: rows.map((row, index) => ({ row, index })),
+ paddingTop: 0,
+ paddingBottom: 0,
+ // Module-level, not a fresh closure: a new ref identity per render
+ // makes React detach and re-attach every row's ref on every render,
+ // and most consumers never virtualize.
+ measure: NOOP_MEASURE,
+ };
+
if (rows.length === 0 && empty) {
return <>{empty}</>;
}
+ const maxHeight = virtualize?.maxHeight ?? 600;
+ const tableWindow = windowFor(rowWindow);
+ const cardsWindow = windowFor(cardWindow);
+
const table = (
- <div className={cn("overflow-x-auto", stacked && STACKED_TABLE_CLS[stacked])}>
+ <div
+ ref={virtualize ? rowWindow.scrollRef : undefined}
+ className={cn(
+ virtualize ? "overflow-auto" : "overflow-x-auto",
+ stacked && STACKED_TABLE_CLS[stacked],
+ )}
+ style={virtualize ? { maxHeight } : undefined}
+ >
<table className="w-full text-sm">
{caption ? <caption className="sr-only">{caption}</caption> : null}
<thead className="bg-[var(--color-bg-surface)] text-[var(--color-text-tertiary)] text-2xs uppercase tracking-wider sticky top-0 z-10 border-b border-[var(--color-border-default)]">
@@ -145,6 +228,7 @@ export function ResponsiveTable<T>({
return (
<th
key={c.key}
+ scope="col"
className={cn(
"px-3 py-2.5 font-medium whitespace-nowrap",
alignCls(c.align),
@@ -172,16 +256,24 @@ export function ResponsiveTable<T>({
</tr>
</thead>
<tbody>
- {rows.map((row) => {
+ {tableWindow.paddingTop > 0 && (
+ <tr aria-hidden>
+ <td style={{ height: tableWindow.paddingTop, padding: 0, border: 0 }} />
+ </tr>
+ )}
+ {tableWindow.items.map(({ row, index }) => {
const key = rowKey(row);
const isSelected = selectedKey != null && selectedKey === key;
return (
<tr
key={key}
+ ref={tableWindow.measure}
+ data-index={index}
className={cn(
"border-t border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)]",
isSelected && "bg-[var(--color-accent-muted)]/30",
onRowClick && CLICKABLE_ROW_CLS,
+ rowClassName?.(row),
)}
{...(onRowClick ? clickableRowProps(() => onRowClick(row)) : {})}
>
@@ -201,49 +293,67 @@ export function ResponsiveTable<T>({
</tr>
);
})}
+ {tableWindow.paddingBottom > 0 && (
+ <tr aria-hidden>
+ <td style={{ height: tableWindow.paddingBottom, padding: 0, border: 0 }} />
+ </tr>
+ )}
</tbody>
</table>
</div>
);
const cards = stacked ? (
- <ul className={cn("divide-y divide-[var(--color-table-divider)]", STACKED_CARDS_CLS[stacked])}>
- {rows.map((row) => {
- const key = rowKey(row);
- const isSelected = selectedKey != null && selectedKey === key;
- const [titleCol, ...rest] = columns.filter((c) => !c.hideInCard);
- if (!titleCol) return null;
- return (
- <li
- key={key}
- className={cn(
- "px-3 py-2.5",
- isSelected && "bg-[var(--color-accent-muted)]/30",
- onRowClick && cn("hover:bg-[var(--color-bg-elevated)]", CLICKABLE_ROW_CLS),
- )}
- {...(onRowClick ? clickableRowProps(() => onRowClick(row)) : {})}
- >
- <div className="text-sm text-[var(--color-text-primary)]">
- {(titleCol.mobileRender ?? titleCol.render)(row)}
- </div>
- <dl className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1">
- {rest.map((c) => {
- const value = (c.mobileRender ?? c.render)(row);
- if (value == null || value === "") return null;
- return (
- <div key={c.key} className="flex items-baseline gap-1.5 text-xs">
- <dt className="text-[var(--color-text-tertiary)]">
- {c.mobileLabel ?? (typeof c.header === "string" ? c.header : c.key)}
- </dt>
- <dd className="text-[var(--color-text-secondary)] tabular-nums">{value}</dd>
- </div>
- );
- })}
- </dl>
- </li>
- );
- })}
- </ul>
+ <div
+ ref={virtualize ? cardWindow.scrollRef : undefined}
+ className={cn(virtualize && "overflow-auto", STACKED_CARDS_CLS[stacked])}
+ style={virtualize ? { maxHeight } : undefined}
+ >
+ {cardsWindow.paddingTop > 0 && <div style={{ height: cardsWindow.paddingTop }} aria-hidden />}
+ <ul className="divide-y divide-[var(--color-table-divider)]">
+ {cardsWindow.items.map(({ row, index }) => {
+ const key = rowKey(row);
+ const isSelected = selectedKey != null && selectedKey === key;
+ const [titleCol, ...rest] = columns.filter((c) => !c.hideInCard);
+ if (!titleCol) return null;
+ return (
+ <li
+ key={key}
+ ref={cardsWindow.measure}
+ data-index={index}
+ className={cn(
+ "px-3 py-2.5",
+ isSelected && "bg-[var(--color-accent-muted)]/30",
+ onRowClick && cn("hover:bg-[var(--color-bg-elevated)]", CLICKABLE_ROW_CLS),
+ rowClassName?.(row),
+ )}
+ {...(onRowClick ? clickableRowProps(() => onRowClick(row)) : {})}
+ >
+ <div className="text-sm text-[var(--color-text-primary)]">
+ {(titleCol.mobileRender ?? titleCol.render)(row)}
+ </div>
+ <dl className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1">
+ {rest.map((c) => {
+ const value = (c.mobileRender ?? c.render)(row);
+ if (value == null || value === "") return null;
+ return (
+ <div key={c.key} className="flex items-baseline gap-1.5 text-xs">
+ <dt className="text-[var(--color-text-tertiary)]">
+ {c.mobileLabel ?? (typeof c.header === "string" ? c.header : c.key)}
+ </dt>
+ <dd className="text-[var(--color-text-secondary)] tabular-nums">{value}</dd>
+ </div>
+ );
+ })}
+ </dl>
+ </li>
+ );
+ })}
+ </ul>
+ {cardsWindow.paddingBottom > 0 && (
+ <div style={{ height: cardsWindow.paddingBottom }} aria-hidden />
+ )}
+ </div>
) : null;
return (
diff --git a/packages/ui/src/shared/virtualized-table/use-virtual-rows.ts b/packages/ui/src/shared/virtualized-table/use-virtual-rows.ts
index 4a9a05503..c3f12a37f 100644
--- a/packages/ui/src/shared/virtualized-table/use-virtual-rows.ts
+++ b/packages/ui/src/shared/virtualized-table/use-virtual-rows.ts
@@ -107,7 +107,12 @@ export function useVirtualRows<E extends HTMLElement = HTMLDivElement>({
const first = items[0];
const last = items[items.length - 1];
const paddingTop = first ? first.start : 0;
- const paddingBottom = last ? totalSize - last.end : 0;
+ // With no window yet (first paint, before the container is measured) the whole
+ // list is still "below", so the spacer has to carry the full height. Returning
+ // 0 here deadlocks any scroll container whose only content is these rows: no
+ // rows means no height, and a zero-height viewport makes the virtualizer
+ // refuse to compute a range, so no rows ever appear.
+ const paddingBottom = last ? totalSize - last.end : totalSize;
return {
scrollRef,