diff-view.tsx
This file
Path
apps/web/src/features/code/diff-view.tsx
384 lines · 12.6 KiB · TypeScript
Last changed by
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
History of this fileTake it
Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 1why, one step back1/**Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 2–8why, one step back2 * A set of changed files drawn by Pierre's `CodeView`: one scroller that3 * draws only the files in view, each file's header sticky at its top4 * (with a hairline only while it is stuck), unchanged runs folded into5 * "N unmodified lines" bars, changed words marked inside changed lines,6 * and highlighting done in the worker pool (`pool.tsx`). It sits in a7 * `DiffPane`, over the server's `PlainDiff` (the same hunks, the same8 * measures), which it replaces in place.Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 9why, one step back9 *Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 10–21why, one step back10 * Unified diffs mark each line `+` or `-`, so a change reads without11 * colour; split diffs mark the side with a bar. Each header has a chevron12 * that folds the file; an added or deleted file past 80 lines starts13 * folded. Lines can be selected, and the selection is kept in the address14 * (`#diff-<path>:L4-L7`); an address naming a file (the tree, `J`/`K`)15 * scrolls to its header.16 *17 * What a page adds, so the finish and waiver pages draw with it unedited:18 * `annotations` (a row under a line, on one side), and per file a header19 * slot (`slots[].header`, a "Mark read" button) and a status (`read`20 * marks the header with a check, `refused` with the refused cross).21 *Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 22–23why, one step back22 * Only the browser loads this module (`client-code.tsx`).23 */Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 24–26why, one step back24import type { CodeViewItem, DiffLineAnnotation } from "@pierre/diffs";25import { CodeView } from "@pierre/diffs/react";26import type { CodeViewHandle, CodeViewReactOptions } from "@pierre/diffs/react";Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 27why, one step back27import type { ChangedFile } from "@repo/protocol/domain/code";Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
line 28why, one step back28import { useLocation, useRouter } from "@tanstack/react-router";Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
line 29why, one step back29import { Effect, Option, Predicate } from "effect";Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 30–32why, one step back30import { Check, ChevronDown, OctagonX } from "lucide-react";31import { useEffect, useMemo, useRef, useState } from "react";32import type { ReactNode } from "react";Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 33why, one step back33Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 34–37why, one step back34import { drawnFiles, emptyDiffOf } from "./diff-model.ts";35import type { DrawnFile } from "./diff-model.ts";36import { PANE_SCROLLER } from "./diff-pane.tsx";37import { diffLinesHash, parseDiffHash } from "./line-hash.ts";Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 38–40why, one step back38import { diffOptionsFor, diffsOptions, registerCodeTheme } from "./pierre.ts";39import { CodePool, poolReady, workerPool } from "./pool.tsx";40import { SERVER_FILES } from "./prerender.ts";Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 41why, one step back41Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e
lines 42–43why, one step back42registerCodeTheme();43Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 44–50why, one step back44/** A row a page draws under one line of one file's diff, on one side. */45export interface DiffAnnotation {46 readonly path: string;47 readonly line: number;48 readonly side: "additions" | "deletions";49 readonly render: () => ReactNode;50}Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 51why, one step back51Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 52–58why, one step back52/** What a page adds to one file's header: a control, and the file's status. */53export interface DiffFileSlot {54 readonly path: string;55 readonly header?: ReactNode;56 readonly status?: "read" | "refused";57}58Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 59–61why, one step back59export interface DiffCodeProps {60 readonly files: readonly ChangedFile[];61 readonly split: boolean;Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 62–67why, one step back62 readonly annotations?: readonly DiffAnnotation[];63 readonly slots?: readonly DiffFileSlot[];64 /** The files folded now; each file's own default when absent. */65 readonly folded?: ReadonlySet<string> | undefined;66 /** A header's fold was pressed. */67 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;Merge build/1224-decider-pagesoscabrielbefore adoptiond22b7a2
lines 68–72why, one step back68 /**69 * The files already parsed, in the order to draw them: a decision's diff70 * comes as a patch, with no whole texts to parse `files` from.71 */72 readonly drawn?: readonly DrawnFile[] | undefined;Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 73–74why, one step back73}74Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 75–85why, one step back75/**76 * The header's hairline, only while it is stuck at the top (where the77 * browser can tell); a plain one where it cannot. Each header also carries78 * a hairline above it, parting one file from the next.79 */80const HEADER_CSS = `81[data-diffs-header] { box-shadow: inset 0 1px var(--rule); container-type: scroll-state; }82[data-diffs-header]::after { content: ""; position: absolute; inset-inline: 0; bottom: 0; height: 1px; background: transparent; }83@container scroll-state(stuck: top) { [data-diffs-header]::after { background: var(--rule); } }84@supports not (container-type: scroll-state) { [data-diffs-header]::after { background: var(--rule); } }85`;Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 86why, one step back86Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
line 87why, one step back87const NO_ANNOTATIONS: readonly DiffAnnotation[] = [];Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 88why, one step back88Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 89–164why, one step back89const NO_SLOTS: readonly DiffFileSlot[] = [];9091/**92 * An item's version: it changes whenever what the item draws does (folded93 * or not, the lines its annotations sit on), so `CodeView` draws it again.94 */95const versionOf = (96 folded: boolean,97 annotations: readonly DiffLineAnnotation<DiffAnnotation>[]98) => {99 let hash = folded ? 1 : 0;100101 for (const { lineNumber, side } of annotations) {102 hash =103 (hash * 31 + lineNumber * 2 + (side === "additions" ? 1 : 0)) %104 2_147_483_647;105 }106107 return hash * 2 + annotations.length;108};109110/** One file as `CodeView` holds it; a binary or unsent file as a header with no lines. */111const itemOf = (112 drawn: DrawnFile,113 folded: boolean,114 annotations: readonly DiffAnnotation[]115): CodeViewItem<DiffAnnotation> => {116 const mine = annotations.flatMap((annotation) =>117 annotation.path === drawn.file.path118 ? [119 {120 lineNumber: annotation.line,121 metadata: annotation,122 side: annotation.side,123 } satisfies DiffLineAnnotation<DiffAnnotation>,124 ]125 : []126 );127128 return {129 annotations: mine,130 collapsed: folded,131 fileDiff: Option.getOrElse(drawn.diff, () => emptyDiffOf(drawn.file)),132 id: drawn.file.path,133 type: "diff",134 version: versionOf(folded, mine),135 };136};137138/** The address's fragment, handed up as it changes; only inside a router. */139const HashFollower = ({140 onHash,141}: {142 readonly onHash: (hash: string) => void;143}) => {144 const hash = useLocation({ select: (location) => location.hash });145146 useEffect(() => {147 onHash(hash);148 }, [hash, onHash]);149150 return null;151};152153/** Scroll the pane into place, then the file's header to its top. */154const reveal = (155 handle: CodeViewHandle<DiffAnnotation, undefined> | null,156 container: HTMLElement | null,157 path: string158) => {159 container?.closest("[data-diff-pane]")?.scrollIntoView({ block: "start" });160 handle?.scrollTo({ align: "start", id: path, type: "item" });161};162163export const DiffCode = ({164 annotations = NO_ANNOTATIONS,Merge build/1224-decider-pagesoscabrielbefore adoptiond22b7a2
line 165why, one step back165 drawn: parsed,Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 166–175why, one step back166 files,167 folded,168 onFold,169 slots = NO_SLOTS,170 split,171}: DiffCodeProps) => {172 const handle = useRef<CodeViewHandle<DiffAnnotation, undefined>>(null);173 const container = useRef<HTMLDivElement>(null);174 const [hash, setHash] = useState("");175Merge build/1224-decider-pagesoscabrielbefore adoptiond22b7a2
line 176why, one step back176 const drawn = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 177–184why, one step back177178 const items = useMemo(179 () =>180 drawn.map((file) =>181 itemOf(182 file,183 folded === undefined ? file.folded : folded.has(file.file.path),184 annotationsMerge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 185why, one step back185 )Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 186–243why, one step back186 ),187 [annotations, drawn, folded]188 );189190 const byPath = useMemo(191 () =>192 new Map<string, DrawnFile>(drawn.map((file) => [file.file.path, file])),193 [drawn]194 );195196 const slotOf = (path: string) => slots.find((slot) => slot.path === path);197198 // The folds as they are now, read when the address moves: a fold the199 // reader makes later must neither unfold the named file again nor200 // scroll back to it.201 const folds = useRef({ folded, onFold });202203 useEffect(() => {204 folds.current = { folded, onFold };205 });206207 // An address naming a file scrolls to it, and its lines are selected.208 useEffect(() => {209 const named = parseDiffHash(hash);210211 if (Option.isNone(named) || !byPath.has(named.value.path)) {212 return;213 }214215 const { lines, path } = named.value;216217 if (folds.current.folded?.has(path) === true) {218 folds.current.onFold?.(path, false);219 }220221 reveal(handle.current, container.current, path);222223 if (Option.isSome(lines)) {224 handle.current?.setSelectedLines({225 id: path,226 range: {227 end: lines.value.end,228 side: lines.value.side,229 start: lines.value.start,230 },231 });232 handle.current?.scrollTo({233 align: "center",234 id: path,235 lineNumber: lines.value.start,236 side: lines.value.side,237 type: "line",238 });239 }240 }, [byPath, hash]);241242 const options = useMemo(243 (): CodeViewReactOptions<DiffAnnotation, undefined> => ({Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
line 244why, one step back244 ...diffOptionsFor(split),Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 245–246why, one step back245 layout: { gap: 0, paddingBottom: 16, paddingTop: 0 },246 stickyHeaders: true,Finish the Control room: every page passes axe and a keyboard walk in both schemesoscabrielbefore adoption3fd50a5
line 247why, one step back247 unsafeCSS: `${diffsOptions.unsafeCSS}\n${HEADER_CSS}`,Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 248–350why, one step back248 }),249 [split]250 );251252 // A view drawn with no router around it (its own test) follows no address.253 const router = useRouter({ warn: false });254255 return (256 <CodePool>257 {Predicate.isNotNullish(router) ? (258 <HashFollower onHash={setHash} />259 ) : null}260 <div className="contents" data-diff="pierre">261 <CodeView<DiffAnnotation>262 className={PANE_SCROLLER}263 containerRef={container}264 items={items}265 onSelectedLinesChange={(selection) => {266 const url = `${globalThis.location.pathname}${globalThis.location.search}`;267268 globalThis.history.replaceState(269 globalThis.history.state,270 "",271 selection === null272 ? url273 : `${url}#${diffLinesHash({274 end: Math.max(selection.range.start, selection.range.end),275 path: selection.id,276 side: selection.range.side ?? "additions",277 start: Math.min(selection.range.start, selection.range.end),278 })}`279 );280 }}281 options={options}282 ref={handle}283 renderAnnotation={(annotation) => annotation.metadata?.render()}284 renderHeaderMetadata={(item) => {285 const file = byPath.get(item.id);286 const slot = slotOf(item.id);287288 return (289 // Pierre prints the counts itself; what it cannot say is here.290 <span className="flex items-center gap-3 font-sans">291 {file === undefined || Option.isSome(file.diff) ? null : (292 <span className="text-muted-foreground">293 {file.file.binary ? "binary" : "not shown"}294 </span>295 )}296 {slot?.header}297 </span>298 );299 }}300 renderHeaderPrefix={(item) => {301 const closed = item.collapsed === true;302303 return (304 <button305 aria-expanded={!closed}306 aria-label={`${closed ? "Unfold" : "Fold"} ${item.id}`}307 className="text-muted-foreground hover:text-foreground -ml-1 flex size-6 items-center justify-center"308 onClick={() => {309 onFold?.(item.id, !closed);310 }}311 type="button"312 >313 <ChevronDown314 aria-hidden="true"315 className={`size-4 transition-transform duration-150 ${closed ? "-rotate-90" : ""}`}316 strokeWidth={1.75}317 />318 </button>319 );320 }}321 renderHeaderFilenameSuffix={(item) => {322 const status = slotOf(item.id)?.status;323324 if (status === "refused") {325 return (326 <span className="text-refused flex items-center gap-1 font-sans">327 <OctagonX328 aria-hidden="true"329 className="size-3.5"330 strokeWidth={1.75}331 />332 <span className="sr-only">refused here</span>333 </span>334 );335 }336337 return status === "read" ? (338 <span className="text-muted-foreground flex items-center gap-1 font-sans">339 <Check340 aria-hidden="true"341 className="size-3.5"342 strokeWidth={1.75}343 />344 <span className="sr-only">read</span>345 </span>346 ) : null;347 }}348 />349 </div>350 </CodePool>Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 351–352why, one step back351 );352};Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 353–381why, one step back353354/**355 * Ready to draw the first files of a diff highlighted at once: the pool356 * up, and the files a reader sees first (those the server may have sent357 * highlighted) highlighted in it, keyed as `DiffCode` draws them. The rest358 * are highlighted as they scroll into view. Settles either way.359 */360export const prepareDiffs = ({361 drawn,362 files,363}: Pick<DiffCodeProps, "drawn" | "files">) =>364 Effect.tryPromise(() => poolReady()).pipe(365 Effect.andThen(366 Effect.forEach(367 (drawn ?? drawnFiles(files))368 .filter((file) => !file.folded)369 .flatMap((file) => Option.toArray(file.diff))370 .slice(0, SERVER_FILES),371 (diff) =>372 "Worker" in globalThis373 ? Effect.tryPromise(() =>374 workerPool().primeDiffHighlightCache(diff)375 )376 : Effect.void,377 { concurrency: "unbounded", discard: true }378 )379 ),380 Effect.ignore381 );Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 382–384why, one step back382383// `React.lazy` takes a module's default export.384export default DiffCode;