plain-diff.tsx
This file
Path
apps/web/src/features/code/plain-diff.tsx
351 lines · 11.4 KiB · TypeScript
Last changed by
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
History of this fileTake it
Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 1–8why, one step back1/**2 * A commit's diff as plain text: what the server sends, and what a reader3 * sees until the browser has drawn the highlighted diff over it. It holds4 * the hunks the drawing holds (`diff-model.ts` parses both texts with the5 * drawing's own parser) and takes Pierre's measures: a 44 px file header,6 * 13 px code on 20 px lines, line numbers in a gutter of at least three7 * figures with two before and one after, a sign in the first of two8 * leading columns, unchanged runs as 32 px "N unmodified lines" bars. SoMerge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 9–11why, one step back9 * the highlighting arrives in place and nothing moves. The first files the10 * server highlights (`prerenderedPaths`, ADR 0027) are its drawing instead11 * of plain lines, under the same header.Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 12–28why, one step back12 *13 * Each file is a disclosure whose summary is its header: folded, only the14 * header shows (an added or deleted file past 80 lines starts folded).15 * Additions and deletions take the diff's own tints, never the landed or16 * refused colour; a unified diff marks each line `+` or `-`, a split one17 * marks the side with a bar.18 */19import type { ChangedFile } from "@repo/protocol/domain/code";20import { Option } from "effect";21import { ChevronDown, SquareDot, SquareMinus, SquarePlus } from "lucide-react";22import type { LucideIcon } from "lucide-react";23import { useMemo } from "react";24import type { ReactNode } from "react";2526import { drawnFiles, splitRows, unifiedRows } from "./diff-model.ts";27import type { DrawnFile, PlainRow, SplitRow } from "./diff-model.ts";28import { diffAnchor } from "./paths.ts";Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 29–30why, one step back29import { diffDrawing } from "./prerender.ts";30import { ServerCode } from "./server-code.tsx";Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 31–193why, one step back3132/** One numbered line: its text, and which side it is on. */33type Line = Extract<PlainRow, { readonly number: number }>;3435/** A line's ground and its number's colour, by what it is. */36const TONES = {37 addition: {38 line: "bg-diff-add-bg",39 number: "bg-diff-add-bg text-diff-add-sign",40 },41 context: { line: "", number: "text-muted-foreground" },42 deletion: {43 line: "bg-diff-del-bg",44 number: "bg-diff-del-bg text-diff-del-sign",45 },46} as const satisfies Record<47 Line["kind"],48 { readonly line: string; readonly number: string }49>;5051/** Each line's sign in a unified diff, the mark that reads without colour. */52const SIGNS = { addition: "+", context: " ", deletion: "-" } as const;5354/** Pierre's gutter: at least three figures, two before them and one after, then a 2 px gap. */55const GUTTER =56 "border-background min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums select-none";5758/** An unchanged run between hunks: a 32 px bar saying how many lines it skips. */59const Separator = ({60 lines,61 span,62}: {63 readonly lines: number;64 readonly span: number;65}) => (66 <div67 className="bg-surface text-muted-foreground my-2 flex h-8 items-center px-[2ch] font-sans first:mt-0 last:mb-0"68 data-separator="line-info"69 style={{ gridColumn: `span ${span} / span ${span}` }}70 >71 {lines} unmodified {lines === 1 ? "line" : "lines"}72 </div>73);7475/** One line of a unified diff: its number, then its sign and text. */76const UnifiedLine = ({ line }: { readonly line: Line }) => (77 <>78 <span className={`${GUTTER} ${TONES[line.kind].number}`}>79 {line.number}80 </span>81 <span82 className={`pr-[1ch] whitespace-pre ${TONES[line.kind].line}`}83 data-line={line.number}84 data-line-type={line.kind}85 >86 <span aria-hidden="true" className="inline-block w-[2ch] select-none">87 {SIGNS[line.kind]}88 </span>89 {line.text}90 </span>91 </>92);9394/** One side of a split diff's row: its number with the side's bar, then its text; empty when the side has none. */95const SplitSide = ({ line }: { readonly line: Line | undefined }) =>96 line === undefined ? (97 <>98 <span className={`${GUTTER} bg-surface`} />99 <span className="bg-surface" />100 </>101 ) : (102 <>103 <span104 className={`${GUTTER} relative ${TONES[line.kind].number} ${105 line.kind === "context"106 ? ""107 : `before:absolute before:inset-y-0 before:left-0 before:w-1 ${108 line.kind === "addition"109 ? "before:bg-diff-add-sign"110 : "before:bg-[repeating-linear-gradient(0deg,var(--diff-del-sign)_0_2px,transparent_2px_4px)]"111 }`112 }`}113 >114 {line.number}115 </span>116 <span117 className={`pr-[1ch] pl-[1ch] whitespace-pre ${TONES[line.kind].line}`}118 data-line={line.number}119 data-line-type={line.kind}120 >121 {line.text}122 </span>123 </>124 );125126/** A file's lines, unified: one grid of gutter and code, scrolling sideways in itself. */127const UnifiedBody = ({ rows }: { readonly rows: readonly PlainRow[] }) => (128 <div className="overflow-x-auto pb-2">129 <code className="grid min-w-full grid-cols-[min-content_1fr]">130 {rows.map((row, index) =>131 row.kind === "separator" ? (132 <Separator key={`s${index}`} lines={row.lines} span={2} />133 ) : (134 <UnifiedLine key={`${row.kind}${row.number}:${index}`} line={row} />135 )136 )}137 </code>138 </div>139);140141/** A file's lines, split: old on the left, new on the right, row beside row. */142const SplitBody = ({ rows }: { readonly rows: readonly SplitRow[] }) => (143 <div className="overflow-x-auto pb-2">144 <code className="grid min-w-full grid-cols-[min-content_1fr_min-content_1fr]">145 {rows.map((row, index) =>146 row.kind === "separator" ? (147 <Separator key={`s${index}`} lines={row.lines} span={4} />148 ) : (149 <span className="contents" key={`p${index}`}>150 <SplitSide line={row.left} />151 <SplitSide line={row.right} />152 </span>153 )154 )}155 </code>156 </div>157);158159/** What a file changed, in counts: `+n −m`, each in its tint, with words for a screen reader. */160export const ChangeCounts = ({161 additions,162 deletions,163 header = false,164}: {165 readonly additions: number;166 readonly deletions: number;167 /** As a diff's file header prints them: a hyphen, and no count of nothing. */168 readonly header?: boolean;169}) => (170 <span className="text-mono flex shrink-0 items-center gap-[1ch] font-mono tabular-nums">171 {header && additions === 0 ? null : (172 <span className="text-diff-add-sign">173 +{additions}174 <span className="sr-only"> added</span>175 </span>176 )}177 {header && deletions === 0 ? null : (178 <span className="text-diff-del-sign">179 {header ? "-" : "−"}180 {deletions}181 <span className="sr-only"> removed</span>182 </span>183 )}184 </span>185);186187/** Why a file has no lines to show: binary, or its text not sent. */188const Unshown = ({ file }: { readonly file: ChangedFile }) => (189 <p className="text-ui text-muted-foreground px-4 pb-3 font-sans">190 {file.binary ? "A binary file" : "Its text is not shown"}, {file.status}.191 </p>192);193Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 194–198why, one step back194/**195 * A file's lines, unified or split; why it has none when it has none. A196 * file the server highlighted (unified, `prerenderedPaths`) is its drawing,197 * and the plain lines only where the document did not bring it.198 */Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 199–200why, one step back199const FileBody = ({200 file,Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
line 201why, one step back201 prerendered,Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 202–204why, one step back202 split,203}: {204 readonly file: DrawnFile;Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
line 205why, one step back205 readonly prerendered: boolean;Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 206–213why, one step back206 readonly split: boolean;207}) => {208 const diff = Option.getOrUndefined(file.diff);209210 if (diff === undefined) {211 return <Unshown file={file.file} />;212 }213Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 214–223why, one step back214 if (split) {215 return <SplitBody rows={splitRows(diff)} />;216 }217218 const plain = <UnifiedBody rows={unifiedRows(diff)} />;219220 return prerendered ? (221 <div className="min-w-0" data-code="prerendered">222 <ServerCode drawing={() => diffDrawing(file)} plain={plain} />223 </div>Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
line 224why, one step back224 ) : (Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
line 225why, one step back225 plainMerge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 226–291why, one step back226 );227};228229/** Each kind of change as the drawing's header marks it, in the diff's tints. */230const CHANGE_MARKS = {231 added: { icon: SquarePlus, tone: "text-diff-add-sign" },232 deleted: { icon: SquareMinus, tone: "text-diff-del-sign" },233 modified: { icon: SquareDot, tone: "text-muted-foreground" },234} as const satisfies Record<235 ChangedFile["status"],236 { readonly icon: LucideIcon; readonly tone: string }237>;238239/**240 * A file's header as the drawing draws it: the fold's chevron, the mark of241 * its change (with its word for a screen reader), its path, then its242 * counts and anything the page adds.243 */244export const FileHeaderLine = ({245 end,246 file,247}: {248 readonly file: DrawnFile;249 /** Anything a page puts at the header's end (a "Mark read" button). */250 readonly end?: ReactNode;251}) => {252 const { icon: Icon, tone } = CHANGE_MARKS[file.file.status];253254 return (255 <>256 <ChevronDown257 aria-hidden="true"258 className="text-muted-foreground size-4 shrink-0 -rotate-90 transition-transform duration-150 group-open/file:rotate-0"259 strokeWidth={1.75}260 />261 <Icon262 aria-hidden="true"263 className={`size-4 shrink-0 ${tone}`}264 strokeWidth={1.75}265 />266 <span className="sr-only">{file.file.status}:</span>267 <span className="min-w-0 flex-1 truncate" title={file.file.path}>268 {file.file.path}269 </span>270 {Option.isNone(file.diff) ? (271 <span className="text-muted-foreground shrink-0">272 {file.file.binary ? "binary" : "not shown"}273 </span>274 ) : (275 <ChangeCounts {...file.counts} header />276 )}277 {end}278 </>279 );280};281282export interface PlainDiffProps {283 readonly files: readonly ChangedFile[];284 /** Old and new side by side; unified when absent. */285 readonly split?: boolean;286 /** The files folded now; each file's own default (`folded`) when absent. */287 readonly folded?: ReadonlySet<string> | undefined;288 /** A header's fold was pressed. */289 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;290 /** `files` already parsed (`drawnFiles`), so a page parses each once. */291 readonly drawn?: readonly DrawnFile[] | undefined;Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 292–293why, one step back292 /** The paths the server sends highlighted (`prerenderedPaths`); none when absent. */293 readonly prerendered?: ReadonlySet<string> | undefined;Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 294–305why, one step back294}295296/**297 * The diff of `files`, plain, in the order a tree lists them. Server298 * markup: one `section[data-file]` per file, its header sticky at the top299 * of the pane that scrolls it.300 */301export const PlainDiff = ({302 drawn: parsed,303 files,304 folded,305 onFold,Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
line 306why, one step back306 prerendered,Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 307–339why, one step back307 split = false,308}: PlainDiffProps) => {309 const drawnList = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);310311 return (312 <div className="text-mono leading-code font-mono" data-diff="plain">313 {drawnList.map((drawn) => {314 const { file } = drawn;315316 const closed =317 folded === undefined ? drawn.folded : folded.has(file.path);318319 return (320 <section321 aria-label={file.path}322 data-file={file.path}323 data-folded={closed}324 id={diffAnchor(file.path)}325 key={file.path}326 >327 <details328 className="group/file"329 onToggle={(event) => {330 onFold?.(file.path, !event.currentTarget.open);331 }}332 open={!closed}333 >334 <summary335 className="border-rule bg-background text-mono hover:bg-surface sticky top-0 z-[1] flex h-11 cursor-pointer list-none items-center gap-2 border-y px-4 font-sans [&::-webkit-details-marker]:hidden"336 data-diffs-header=""337 >338 <FileHeaderLine file={drawn} />339 </summary>Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 340–344why, one step back340 <FileBody341 file={drawn}342 prerendered={prerendered?.has(file.path) === true}343 split={split}344 />Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 345–351why, one step back345 </details>346 </section>347 );348 })}349 </div>350 );351};