From d8d4ce73924534324e53cae7899f0471cc6452dd Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 13:55:56 -0500 Subject: [PATCH 1/3] feat(changes): Changes view with the Only edits and Show in repo maps (#397) The fourth view, ?view=changes. A window bar picks the window, touched or net, the map and the color lens. Only edits packs the edited chunks by folder and file, with area by changed lines and a floor. Show in repo marks the chunks on the file map. The panel and the commit rail are stand-ins in slots.tsx. ?clmock=1 answers from sample.ts until the server has /api/change-lens. Co-Authored-By: Claude Fable 5.2 --- client/src/changelens/ChangeLensView.tsx | 336 ++++++++++++++ client/src/changelens/Legend.tsx | 64 +++ client/src/changelens/LensMap.tsx | 410 ++++++++++++++++++ client/src/changelens/WindowBar.tsx | 248 +++++++++++ client/src/changelens/api.ts | 74 ++++ client/src/changelens/changelens.test.ts | 163 +++++++ client/src/changelens/colors.ts | 90 ++++ client/src/changelens/labels.ts | 78 ++++ client/src/changelens/layout.ts | 310 +++++++++++++ client/src/changelens/sample.ts | 390 +++++++++++++++++ client/src/changelens/slots.tsx | 207 +++++++++ client/src/changelens/urlState.ts | 99 +++++ client/src/components/Treemap.tsx | 7 +- client/src/navigation/location.ts | 19 +- .../viz/treemap/components/TreemapHeader.tsx | 6 +- 15 files changed, 2496 insertions(+), 5 deletions(-) create mode 100644 client/src/changelens/ChangeLensView.tsx create mode 100644 client/src/changelens/Legend.tsx create mode 100644 client/src/changelens/LensMap.tsx create mode 100644 client/src/changelens/WindowBar.tsx create mode 100644 client/src/changelens/api.ts create mode 100644 client/src/changelens/changelens.test.ts create mode 100644 client/src/changelens/colors.ts create mode 100644 client/src/changelens/labels.ts create mode 100644 client/src/changelens/layout.ts create mode 100644 client/src/changelens/sample.ts create mode 100644 client/src/changelens/slots.tsx create mode 100644 client/src/changelens/urlState.ts diff --git a/client/src/changelens/ChangeLensView.tsx b/client/src/changelens/ChangeLensView.tsx new file mode 100644 index 00000000..779b5811 --- /dev/null +++ b/client/src/changelens/ChangeLensView.tsx @@ -0,0 +1,336 @@ +// The Changes view (`?view=changes`): which code a window of work touched. +// It owns the fetches and the URL state; the map and the panel pieces get +// everything through props. + +import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show, type JSX } from "solid-js"; +import { ArrowRight } from "lucide-solid"; +import { Button } from "../components/ui/Button"; +import { atFromTreePath, baseName, splitAt } from "../navigation/location"; +import { go, location } from "../navigation/store"; +import { ViewTools } from "../viz/viewToolbar"; +import { fetchChangeLens, fetchHunk, LensError, type LensQuery } from "./api"; +import { plural, timeLimits } from "./labels"; +import { inScope, type RepoNode } from "./layout"; +import Legend from "./Legend"; +import LensMap from "./LensMap"; +import { ChunkInspector, CommitRail, HunkDiff, ReviewBuckets } from "./slots"; +import type { ChangeLensPayload, LensChunk, LensHunkDiff } from "./types"; +import { lens, setLens } from "./urlState"; +import WindowBar from "./WindowBar"; + +/** Below this width the panel moves under the map. */ +const NARROW_PX = 900; + +interface ScanNode { + name: string; + path: string; + type: string; + children?: ScanNode[]; + metrics?: { loc?: number; file_count?: number }; +} + +/** The scan tree as folders and files with repo-relative paths, and each folder's file count. */ +function repoTree(data: ScanNode | null, root: string): { tree: RepoNode | null; fileCounts: Map } { + const fileCounts = new Map(); + const walk = (node: ScanNode): RepoNode | null => { + const path = atFromTreePath(node.path, root); + if (path === null) return null; + if (node.type === "file") return { name: node.name, path, loc: node.metrics?.loc ?? 0 }; + if (node.type !== "folder") return null; + const children = (node.children ?? []).map(walk).filter((c): c is RepoNode => c !== null && (!c.children || c.children.length > 0)); + const files = children.reduce((n, c) => n + (c.children ? (fileCounts.get(c.path) ?? 0) : 1), 0); + fileCounts.set(path, files); + return { name: node.name, path, loc: node.metrics?.loc ?? 0, children }; + }; + return { tree: data ? walk(data) : null, fileCounts }; +} + +function Message(props: { title: string; children?: JSX.Element; state: string }) { + return ( +
+
+
{props.title}
+ {props.children} +
+
+ ); +} + +export default function ChangeLensView(props: { + /** The scan tree (absolute paths); null before a scan is loaded. */ + data: ScanNode | null; + /** Absolute path of the scan root. */ + rootPath: string; + /** Open a file or scope in the code viewer. */ + onOpenAt: (at: string, line?: number) => void; +}) { + const query = createMemo( + () => { + const s = lens(); + return props.rootPath ? { path: props.rootPath, window: s.window, mode: s.mode, base: s.base, head: s.head, since: s.since, until: s.until } : null; + }, + null, + { equals: (a, b) => JSON.stringify(a) === JSON.stringify(b) } + ); + + const [payload, setPayload] = createSignal(null); + const [error, setError] = createSignal(null); + const [loading, setLoading] = createSignal(false); + let request = 0; + const load = () => { + const q = query(); + if (!q) return; + const id = ++request; + setLoading(true); + setError(null); + fetchChangeLens(q).then( + (result) => { + if (id !== request) return; + setPayload(result); + setLoading(false); + }, + (e: unknown) => { + if (id !== request) return; + setPayload(null); + setError(e instanceof LensError ? e : new LensError(0, e instanceof Error ? e.message : String(e))); + setLoading(false); + } + ); + }; + createEffect(on(query, load)); + + const scope = () => splitAt(location().at).file; + const scan = createMemo(() => repoTree(props.data, props.rootPath)); + const selected = createMemo(() => payload()?.chunks.find((c) => c.id === lens().chunk) ?? null); + const commit = createMemo(() => payload()?.commits.find((c) => c.sha === lens().commit) ?? null); + const inView = createMemo(() => payload()?.chunks.filter((c) => inScope(c.path, scope())).length ?? 0); + + // --- the open diff ---------------------------------------------------------------- + const [hunk, setHunk] = createSignal<{ chunk: string; commit?: string } | null>(null); + const [diff, setDiff] = createSignal(null); + const [diffError, setDiffError] = createSignal(); + const [diffLoading, setDiffLoading] = createSignal(false); + let diffRequest = 0; + createEffect( + on([hunk, query], ([h, q]) => { + const id = ++diffRequest; + setDiffError(undefined); + if (!h || !q) { + setDiff(null); + setDiffLoading(false); + return; + } + setDiffLoading(true); + fetchHunk(q, h.chunk, h.commit).then( + (result) => { + if (id !== diffRequest) return; + setDiff(result); + setDiffLoading(false); + }, + (e: unknown) => { + if (id !== diffRequest) return; + setDiff(null); + setDiffError(e instanceof Error ? e.message : String(e)); + setDiffLoading(false); + } + ); + }) + ); + const openHunk = (chunk: string, sha?: string) => { + setHunk({ chunk, commit: sha }); + if (lens().chunk !== chunk) setLens({ chunk }); + }; + /** From the map: the selected commit's step when that commit changed the chunk, else the whole window. */ + const openFromMap = (chunk: string) => openHunk(chunk, commit()?.chunkIds.includes(chunk) ? commit()!.sha : undefined); + // An open diff follows the selection, so the arrow keys step through diffs. + createEffect( + on( + () => lens().chunk, + (chunk) => { + const open = hunk(); + if (!open || open.chunk === chunk) return; + setHunk(chunk ? { chunk } : null); + }, + { defer: true } + ) + ); + + let rootRef: HTMLDivElement | undefined; + const [narrow, setNarrow] = createSignal(false); + onMount(() => { + if (!rootRef) return; + const observer = new ResizeObserver((entries) => setNarrow((entries[entries.length - 1]?.contentRect.width ?? 0) < NARROW_PX)); + observer.observe(rootRef); + onCleanup(() => observer.disconnect()); + }); + + const state = () => (error() ? (error()!.status === 409 ? "not-git" : "error") : !payload() ? "loading" : !payload()!.chunks.length ? "empty" : loading() ? "refreshing" : "ready"); + + /** Root › scope › the selected chunk's folders, file and name. Every folder and file zooms. */ + const crumbs = createMemo(() => { + const out: { label: string; at: string; inScope: boolean }[] = [{ label: baseName(props.rootPath) || "repo", at: "", inScope: true }]; + const chunk = selected(); + const path = chunk && inScope(chunk.path, scope()) ? chunk.path : scope(); + const parts = path ? path.split("/") : []; + parts.forEach((label, i) => { + const at = parts.slice(0, i + 1).join("/"); + out.push({ label, at, inScope: inScope(scope(), at) }); + }); + return out; + }); + + return ( +
+ + setLens(patch)} /> + + + {/* What the window resolved to. One fixed-height row at rest; notes wrap under it. */} +
+ {loading() ? "Reading the history of this window…" : " "}}> + {(p) => ( + <> + + {p().selection.base.label} + + {p().selection.head.label} + + + {plural(p().commits.filter((c) => c.date !== null).length, "commit")} + {p().selection.includesWorktree ? " + uncommitted edits" : ""} + + {(text) => {text()}} + + Times in {p().selection.timezone} + + {p().selection.mode === "touched" ? "Touched: every chunk a commit changed" : "Net: what differs from start to end"} + {(note) => {note}} + + )} + + + {loading() && payload() ? "Updating…" : ""} + +
+ + + +

{error()!.message}

+

Changes reads commits and the working tree, so it needs a repository. The Treemap, Graph and 2x2 views work without one.

+
+
+ + +

{error()!.message}

+ +
+
+ + + + + + {(note) =>

{note}

}
+

Pick another window in the toolbar: 7 days reaches further back, and Custom takes any two revisions.

+
+
+ + + {(p) => ( +
+
+ {/* The diff opens over the map and its legend; the commit rail under them stays in reach. */} +
+
+ + + {plural(p().summary.filesEdited, "file")} of {p().summary.filesTotal.toLocaleString("en-US")} · {plural(p().summary.chunks, "chunk")} · {p().summary.churnLines.toLocaleString("en-US")} lines churned / {p().summary.netLines.toLocaleString("en-US")} net + {p().summary.reverted ? ` · ${p().summary.reverted} reverted` : ""} + +
+
+ scan().fileCounts.get(folder) ?? null} + onSelect={(chunk, how) => setLens({ chunk }, how)} + onOpen={openFromMap} + onZoom={(at) => go({ at })} + /> + +
+ + No edits under {scope()} in this window.{" "} + + +
+
+
+ + +
+ setHunk(null)} /> +
+
+
+
+ setLens({ commit: sha })} highlightChunk={lens().chunk} /> +
+
+ +
+ )} +
+
+ ); +} diff --git a/client/src/changelens/Legend.tsx b/client/src/changelens/Legend.tsx new file mode 100644 index 00000000..95d947fc --- /dev/null +++ b/client/src/changelens/Legend.tsx @@ -0,0 +1,64 @@ +// One line under the map that says what every fill and mark means. + +import { For, Show } from "solid-js"; +import { formatMetricValue, metricDef, metricLabel } from "../utils/metricsStore"; +import { TREEMAP_GRADIENT } from "../viz/treemap/utils/colors"; +import { ADDED_FILL, DELETED_FILL, deltaGradient, deltaSpan, NOT_MEASURED_FILL, REVERTED_FILL, STATE_GLYPH, STATE_LABEL, type Lens, type TileState } from "./colors"; +import type { LensLayout } from "./urlState"; + +const STATES: { id: Exclude; fill: (lens: Lens) => string; outline?: string; hint: string }[] = [ + { id: "added", fill: (lens) => (lens.color === "delta" ? ADDED_FILL : "var(--plc-surface-muted)"), hint: "Not in the base. A delta lens has nothing to subtract from, so it gets its own fill." }, + { id: "deleted", fill: () => DELETED_FILL, hint: "Not in the head. Its lines are the base's." }, + { id: "moved", fill: () => "var(--plc-surface-muted)", outline: "1px dashed rgba(15, 23, 42, 0.65)", hint: "The same symbol in another file, or in a renamed file" }, + { id: "reverted", fill: () => REVERTED_FILL, outline: "1px dashed var(--plc-on-disabled)", hint: "Changed in the window, then put back: the base and the head are equal" }, + { id: "not-measured", fill: () => NOT_MEASURED_FILL, hint: "No analyzer measures this metric here. It is not a zero." }, +]; + +export default function Legend(props: { lens: Lens; layout: LensLayout }) { + const span = () => deltaSpan(props.lens.metric); + const domain = () => metricDef(props.lens.metric)?.color_domain ?? [0, 10, 50]; + const value = (n: number) => formatMetricValue(props.lens.metric, n); + return ( +
+ + + {metricLabel(props.lens.metric)} {props.lens.color === "delta" ? "delta" : "now"} + + + {value(domain()[0])} + + {value(domain()[2])}+ + + } + > + fell −{value(span())} + + + + + rose +{value(span())} + + + + {(s) => ( + + + {STATE_LABEL[s.id]} + + )} + + + {props.layout === "edits" ? "Area: changed lines · dots: commits that touched the chunk" : "Area: file LOC · bands: edited chunks at their lines"} + +
+ ); +} diff --git a/client/src/changelens/LensMap.tsx b/client/src/changelens/LensMap.tsx new file mode 100644 index 00000000..06b31277 --- /dev/null +++ b/client/src/changelens/LensMap.tsx @@ -0,0 +1,410 @@ +// The map of the Changes view, in both layouts. Tiles are positioned HTML +// boxes: the layout memo depends on the data, the size, the scope and the +// collapsed groups only, so a color change repaints fills and moves nothing. + +import { createMemo, createSignal, For, onCleanup, onMount, Show, type JSX } from "solid-js"; +import { ChevronDown, ChevronRight } from "lucide-solid"; +import type { Rect } from "../compare/treemapLayout"; +import { metricLabel } from "../utils/metricsStore"; +import { STATE_GLYPH, tileLook, type Lens, type TileLook } from "./colors"; +import { beforeAfter, folderLabel, matchNote, plural, signed, STATUS_LABEL } from "./labels"; +import { inScope, layoutEdits, layoutRepo, neighbour, repoTreeFromFiles, type ChunkTile, type GroupTile, type RepoFileTile, type RepoNode } from "./layout"; +import { WORKTREE, type ChangeLensPayload, type LensChunk, type LensCommit } from "./types"; +import type { LensLayout } from "./urlState"; + +const INK = "#0f172a"; + +const box = (r: Rect): JSX.CSSProperties => ({ + left: `${r.x0}px`, + top: `${r.y0}px`, + width: `${Math.max(0, r.x1 - r.x0)}px`, + height: `${Math.max(0, r.y1 - r.y0)}px`, +}); +const widthOf = (r: Rect) => r.x1 - r.x0; +const heightOf = (r: Rect) => r.y1 - r.y0; + +/** What a tile says under its name: the lens's before → after, or why there is none. */ +function valueText(chunk: LensChunk, lens: Lens, look: TileLook): string { + if (look.state === "deleted") return "deleted"; + if (look.state === "reverted") return "reverted"; + if (look.state === "not-measured") return "not measured"; + const pair = chunk.metrics[lens.metric]; + return beforeAfter(lens.metric, pair) ?? ""; +} + +interface Hover { + x: number; + y: number; + chunk?: LensChunk; + file?: RepoFileTile; +} + +export default function LensMap(props: { + payload: ChangeLensPayload; + layout: LensLayout; + /** The folder or file the map is zoomed to; "" is the repo. */ + scope: string; + lens: Lens; + selected: string | null; + commit: LensCommit | null; + /** The scan's file tree, repo-relative; null before a scan is loaded. */ + tree: RepoNode | null; + /** Files in a folder, from the scan; null when unknown. */ + filesIn: (folder: string) => number | null; + onSelect: (chunkId: string | null, how?: "push" | "step") => void; + /** Open the chunk's diff. */ + onOpen: (chunkId: string) => void; + onZoom: (path: string) => void; +}) { + let host: HTMLDivElement | undefined; + const [size, setSize] = createSignal({ width: 0, height: 0 }); + const [collapsed, setCollapsed] = createSignal>(new Set()); + const [hover, setHover] = createSignal(null); + + onMount(() => { + if (!host) return; + const observer = new ResizeObserver((entries) => { + const r = entries[entries.length - 1]?.contentRect; + if (r) setSize({ width: Math.floor(r.width), height: Math.floor(r.height) }); + }); + observer.observe(host); + onCleanup(() => observer.disconnect()); + }); + + const edits = createMemo(() => (props.layout === "edits" ? layoutEdits(props.payload.chunks, size(), props.scope, collapsed()) : null)); + const repo = createMemo(() => + props.layout === "repo" ? layoutRepo(props.tree ?? repoTreeFromFiles(props.payload.files), props.payload.files, props.payload.chunks, size(), props.scope) : null + ); + /** Every tile a chunk can be selected on, for the arrow keys. */ + const tiles = createMemo(() => edits()?.chunks ?? repo()?.files.flatMap((f) => f.bands) ?? []); + const inCommit = createMemo(() => (props.commit ? new Set(props.commit.chunkIds) : null)); + const dimmed = (id: string) => Boolean(inCommit() && !inCommit()!.has(id)); + + const toggle = (path: string) => + setCollapsed((prev) => { + const next = new Set(prev); + if (!next.delete(path)) next.add(path); + return next; + }); + + const groupStats = (group: GroupTile) => { + const files = props.payload.files.filter((f) => inScope(f.path, group.path)); + return { + added: files.reduce((n, f) => n + f.added, 0), + deleted: files.reduce((n, f) => n + f.deleted, 0), + label: group.kind === "folder" ? folderLabel({ edited: files.length, total: props.filesIn(group.path), classes: files.map((f) => f.fileClass) }) : "", + edited: files.length, + }; + }; + + const onKeyDown = (e: KeyboardEvent) => { + if (e.altKey || e.metaKey || e.ctrlKey) return; + const list = tiles(); + const current = list.find((t) => t.chunk.id === props.selected); + if (e.key === "Escape" && props.selected) { + e.preventDefault(); + props.onSelect(null); + } else if (e.key === "Enter" && current) { + e.preventDefault(); + props.onOpen(current.chunk.id); + } else if (e.key.startsWith("Arrow") && list.length) { + e.preventDefault(); + // With nothing selected, the first arrow lands on the largest tile. + const next = current ? neighbour(list, current, e.key) : [...list].sort((a, b) => widthOf(b.rect) * heightOf(b.rect) - widthOf(a.rect) * heightOf(a.rect))[0]; + if (next) props.onSelect(next.chunk.id, "step"); + } + }; + + const hoverChunk = (chunk: LensChunk) => (e: MouseEvent) => setHover({ x: e.clientX, y: e.clientY, chunk }); + + const ChunkBox = (p: { tile: ChunkTile; band?: boolean }) => { + const chunk = p.tile.chunk; + const look = createMemo(() => tileLook(chunk, props.lens)); + const w = widthOf(p.tile.rect); + const h = heightOf(p.tile.rect); + const selected = () => props.selected === chunk.id; + const muted = () => look().state === "reverted" || look().state === "deleted"; + return ( + + ); + }; + + const GroupBox = (p: { group: GroupTile; repo?: boolean }) => { + const g = p.group; + const stats = createMemo(() => groupStats(g)); + const holdsSelection = () => Boolean(props.selected && g.chunkIds.includes(props.selected)); + const isDim = () => g.collapsed && g.chunkIds.every(dimmed) && Boolean(inCommit()); + const Chevron = g.collapsed ? ChevronRight : ChevronDown; + const slash = g.kind === "folder" ? "/" : ""; + return ( +
g.collapsed && toggle(g.path)} + title={g.collapsed ? `Show the ${plural(g.chunkIds.length, "chunk")} in ${g.name}` : undefined} + > + 40 && heightOf(g.rect) > 15)}> +
+ + + + + {/* When room runs out the label goes first, then the counts; the name goes last. */} + 0}> + + {stats().label} + + + +{stats().added} −{stats().deleted} + + +
+
+ 40}> +
{plural(g.chunkIds.length, "chunk")}
+
+
+ ); + }; + + const FileBox = (p: { tile: RepoFileTile }) => { + const t = p.tile; + const w = widthOf(t.rect); + const h = heightOf(t.rect); + const edited = Boolean(t.file); + /** A click on an edited file steps through its chunks, so a thin band is never the only target. */ + const cycle = () => { + if (!t.bands.length) return; + const i = t.bands.findIndex((b) => b.chunk.id === props.selected); + props.onSelect(t.bands[(i + 1) % t.bands.length].chunk.id); + }; + return ( +
{ + if (!edited) return; + e.stopPropagation(); + cycle(); + }} + onMouseMove={(e) => setHover({ x: e.clientX, y: e.clientY, file: t })} + onMouseLeave={() => setHover(null)} + > + = 34 && h >= 15 && (!edited || t.bands.every((b) => b.rect.y0 - t.rect.y0 > 15))}> + + {t.name} + + +
+ ); + }; + + return ( +
+ + {(l) => ( + <> + {(group) => } + {(tile) => } + + )} + + + {(l) => ( + <> + {(group) => } + {(tile) => } + f.bands)}>{(tile) => } + + )} + + {(h) => } +
+ ); +} + +function MapTooltip(props: { hover: Hover; lens: Lens; payload: ChangeLensPayload }) { + const W = 320; + const style = (): JSX.CSSProperties => ({ + left: `${props.hover.x + W + 24 > window.innerWidth ? props.hover.x - W - 12 : props.hover.x + 14}px`, + top: `${props.hover.y + 190 > window.innerHeight ? props.hover.y - 170 : props.hover.y + 16}px`, + width: `${W}px`, + }); + return ( +
+ + {(chunk) => { + const look = () => tileLook(chunk(), props.lens); + const pair = () => chunk().metrics[props.lens.metric]; + const delta = () => (pair() && pair()!.before !== null && pair()!.after !== null ? pair()!.after! - pair()!.before! : null); + const last = () => chunk().touches[chunk().touches.length - 1]; + return ( + <> +
+ {chunk().name} + + +{chunk().added} −{chunk().deleted} + +
+
+ {chunk().path}:{chunk().startLine}–{chunk().endLine} +
+
+ Status + + {STATUS_LABEL[chunk().status]} + {(note) => · {note()}} + + + Touches + + {plural(chunk().touches.length, "commit")} + + {" · last "} + {last().sha === WORKTREE ? "uncommitted" : (props.payload.commits.find((c) => c.sha === last().sha)?.short ?? last().sha.slice(0, 7))} + + + + {metricLabel(props.lens.metric)} + Not measured{chunk().naReason ? `: ${chunk().naReason}` : look().state === "reverted" ? ": not in base or head" : " at this scope"}} + > + {(text) => ( + + {text()} + + ({signed(delta()!, Number.isInteger(delta()) ? 0 : 1)}) + + + )} + +
+ + ); + }} +
+ + {(file) => ( + <> +
{file().path}
+
+ {plural(file().loc, "line")} + {" · "} + + {(f) => ( + <> + {plural(f().chunkIds.length, "edited chunk")} +{f().added} −{f().deleted} + {f().outOfScope ? " · generated or vendored" : ""} + + )} + +
+ + )} +
+
+ ); +} diff --git a/client/src/changelens/WindowBar.tsx b/client/src/changelens/WindowBar.tsx new file mode 100644 index 00000000..499200c9 --- /dev/null +++ b/client/src/changelens/WindowBar.tsx @@ -0,0 +1,248 @@ +// The Changes view's controls, drawn in the view toolbar's slot: which window, +// touched or net, which map, and what the color means. + +import { createSignal, For, Show, type JSX } from "solid-js"; +import { Check, ChevronDown } from "lucide-solid"; +import Popover from "../components/Popover"; +import { Button } from "../components/ui/Button"; +import { OptionRow, PopoverPanel } from "../components/ui/PopoverPanel"; +import { segmentedKeyDown } from "../components/ui/segmentedKeys"; +import { TextInput } from "../components/ui/TextInput"; +import { metricDef, metricLabel } from "../utils/metricsStore"; +import type { LensMode, LensWindow } from "./types"; +import { DEFAULT_LENS, type ColorMode, type LensLayout, type LensState } from "./urlState"; + +interface Option { + id: T; + label: string; + title: string; +} + +function Segmented(props: { label: string; name: string; options: Option[]; value: T; onChange: (id: T) => void }) { + return ( +
segmentedKeyDown(e, props.options.map((o) => o.id), props.value, props.onChange)} + class="flex shrink-0 rounded-md border border-[var(--plc-border)] bg-[var(--plc-surface-muted)] p-0.5" + > + + {(o) => ( + + )} + +
+ ); +} + +const PRESETS: Option>[] = [ + { id: "branch", label: "This branch", title: "Every commit on this branch since it left the default branch" }, + { id: "24h", label: "24 hours", title: "Commits of the last 24 hours" }, + { id: "7d", label: "7 days", title: "Commits of the last 7 days" }, +]; +const WINDOW_IDS: LensWindow[] = ["branch", "24h", "7d", "custom"]; + +const MODES: Option[] = [ + { id: "touched", label: "Touched", title: "Every chunk a commit in the window changed, with work that was later put back" }, + { id: "net", label: "Net", title: "Only what differs between the start and the end of the window" }, +]; +const LAYOUTS: Option[] = [ + { id: "edits", label: "Only edits", title: "Pack the edited chunks together; area is changed lines" }, + { id: "repo", label: "In repo", title: "Show in repo: the whole file map, with edited chunks marked in their files" }, +]; +const COLORS: Option[] = [ + { id: "now", label: "Now", title: "Color by the value at the end of the window" }, + { id: "delta", label: "Delta", title: "Color by how much the value changed in the window" }, +]; + +/** ISO time ↔ the value of a `datetime-local` input, in the browser's zone. */ +const toLocalInput = (iso: string): string => { + const d = new Date(iso); + if (!iso || Number.isNaN(d.getTime())) return ""; + return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16); +}; +const fromLocalInput = (value: string): string => (value ? new Date(value).toISOString() : ""); + +function Field(props: { label: string; hint?: string; children: JSX.Element }) { + return ( + + ); +} + +/** The window presets, with Custom opening a small form for refs and times. */ +function WindowPicker(props: { state: LensState; onChange: (patch: Partial) => void }) { + const [open, setOpen] = createSignal(false); + const [draft, setDraft] = createSignal({ base: "", head: "", since: "", until: "" }); + const openCustom = () => { + const s = props.state; + setDraft({ base: s.base, head: s.head, since: toLocalInput(s.since), until: toLocalInput(s.until) }); + setOpen(true); + }; + const apply = () => { + const d = draft(); + setOpen(false); + props.onChange({ window: "custom", base: d.base.trim(), head: d.head.trim(), since: fromLocalInput(d.since), until: fromLocalInput(d.until), commit: null }); + }; + const pick = (id: LensWindow) => (id === "custom" ? openCustom() : props.onChange({ window: id, commit: null })); + const active = (id: LensWindow) => props.state.window === id; + const edit = (key: "base" | "head" | "since" | "until") => (e: InputEvent & { currentTarget: HTMLInputElement }) => setDraft({ ...draft(), [key]: e.currentTarget.value }); + + return ( +
{ + // Arrow keys step through the presets; Custom needs its form, so they stop before it. + if ((e.target as HTMLElement).closest("[data-lens-custom-form]")) return; + segmentedKeyDown(e, WINDOW_IDS, props.state.window, pick); + }} + class="flex shrink-0 rounded-md border border-[var(--plc-border)] bg-[var(--plc-surface-muted)] p-0.5" + > + + {(o) => ( + + )} + + ( + + )} + > + +
{ + e.preventDefault(); + apply(); + }} + onKeyDown={(e) => e.key === "Escape" && setOpen(false)} + > + + queueMicrotask(() => el.focus())} /> + + + + + + + + + + +
+ + +
+
+
+
+
+ ); +} + +/** Which metric drives the color. Only metrics with a before and after in this window. */ +function MetricMenu(props: { metricIds: string[]; selected: string; onSelect: (id: string) => void }) { + const [open, setOpen] = createSignal(false); + return ( + ( + + )} + > + + No metric has a value in this window.}> + {(id) => ( + { + setOpen(false); + props.onSelect(id); + }} + > + {props.selected === id && + + {metricLabel(id)} + {(text) => {text()}} + + + )} + + + + ); +} + +const Divider = () =>