Skip to content
Myr

commit-view.tsx

This file

Path

apps/web/src/features/code/commit-view.tsx

466 lines · 15.0 KiB · TypeScript

Last changed by

Finish the Control room: every page passes axe and a keyboard walk in both schemesoscabrielbefore adoption3fd50a5

History of this file

Take it

1/**2 * One commit, read as a landing first and a diff second. The head: the3 * subject, the landing's status line ("Landed as 9b1c3e5 · answered4 * format-ordinal", the SHA and the ask linked), the body as prose, and5 * git's own metadata on one muted line. The inspector holds the typed6 * facts: this landing's state, its credit (the trailers, once), the diff's7 * stats split by path, and its provenance. Then the diff, file by file, in8 * a pane of its own: the server's plain text (`PlainDiff`), which the9 * browser's drawing (`drawing`, from `client-code.tsx`) replaces in place.10 *11 * A commit the platform did not land came in with the history the project12 * adopted, and says so; its trailers are listed as written, linking no one.13 */14import type {15  CommitDiff,16  CommitView as Commit,17} from "@repo/protocol/domain/code";18import type { ProjectName } from "@repo/protocol/ids";19import { Option } from "effect";20import type { DateTime } from "effect";21import { Columns2, FoldVertical, Rows3, UnfoldVertical } from "lucide-react";22import { useMemo } from "react";23import type { ReactNode } from "react";2425import { Button } from "@/components/ui/button";2627import { CreditFacts, FactBlock, ProvenanceFacts } from "../shared/facts.tsx";28import type { ProvenanceEntry } from "../shared/facts.tsx";29import { HandleLink } from "../shared/handle.tsx";30import { AppLink } from "../shared/link.tsx";31import { StateMarkIcon } from "../shared/marks.tsx";32import { answerPath, askPath } from "../shared/paths.ts";33import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";34import { When } from "../shared/time.tsx";35import { askOf } from "../why/rows.ts";36import { drawnFiles, statsOf } from "./diff-model.ts";37import type { DiffStats, DrawnFile } from "./diff-model.ts";38import { DiffPane, PANE_SCROLLER } from "./diff-pane.tsx";39import { commitHref, shortSha, treeHref } from "./paths.ts";40import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";4142const LINK = "decoration-rule underline hover:decoration-current";4344/** A trailer line: `Key: value`, the key one word of letters and dashes. */45const TRAILER = /^[A-Za-z][\w-]*:\s/u;4647/**48 * The body without its trailers, which the Credit block shows: git's49 * trailer block is the last paragraph when every line of it is a50 * `Key: value`.51 */52export const bodyWithoutTrailers = (commit: Commit) => {53  const paragraphs = commit.body.trim().split(/\n\s*\n/u);54  const last = paragraphs.at(-1) ?? "";5556  const trailers =57    commit.trailers.length > 0 &&58    last.split("\n").every((line) => TRAILER.test(line.trim()));5960  return (trailers ? paragraphs.slice(0, -1) : paragraphs).join("\n\n").trim();61};6263/** Where the commit stands, in one line: landed as its SHA, and the ask it answered or opened. */64export const LandingStatus = ({65  commit,66  project,67}: {68  readonly commit: Commit;69  readonly project: ProjectName;70}) => {71  const { landing } = commit;7273  if (landing === undefined) {74    return (75      <p className="text-want text-muted-foreground flex items-start gap-2">76        <StateMarkIcon className="mt-1" mark="notNeeded" />77        <span>78          Before adoption: this commit came in with the history the project79          adopted, so no landing records it.80        </span>81      </p>82    );83  }8485  const linked = Option.getOrUndefined(askOf(landing));8687  return (88    <p className="text-want flex items-start gap-2" data-outcome="Landed">89      <StateMarkIcon className="mt-1" mark="landed" />90      <span className="min-w-0 [overflow-wrap:anywhere]">91        <strong className="text-landed font-semibold">Landed</strong> as{" "}92        <AppLink93          className={`text-mono font-mono ${LINK}`}94          to={commitHref(project, commit.sha)}95        >96          {shortSha(commit.sha)}97        </AppLink>98        {linked === undefined ? null : (99          <>100            <span aria-hidden="true" className="text-muted-foreground">101              {" · "}102            </span>103            {linked.kind === "opened" ? "opened " : "answered "}104            <AppLink105              className={`text-mono font-mono ${LINK}`}106              to={askPath(project, linked.ask)}107            >108              {linked.ask}109            </AppLink>110          </>111        )}112      </span>113    </p>114  );115};116117/** Git's own metadata, on one line: who wrote it, who committed it, its parents. */118const GitLine = ({119  commit,120  now,121  project,122}: {123  readonly commit: Commit;124  readonly now: DateTime.Utc;125  readonly project: ProjectName;126}) => (127  <span className="[overflow-wrap:anywhere]">128    authored by {commit.author.name} <When at={commit.author.at} now={now} />129    {" · "}130    committed by{" "}131    {commit.landing === undefined ? commit.committer.name : "the platform"}132    {" · "}133    {commit.parents.length === 0 ? (134      "the first commit"135    ) : (136      <>137        {commit.parents.length === 1 ? "parent" : "parents"}{" "}138        {commit.parents.map((parent, index) => (139          <span key={parent}>140            {index === 0 ? null : ", "}141            <AppLink142              className={`text-mono font-mono ${LINK}`}143              to={commitHref(project, parent)}144            >145              {shortSha(parent)}146            </AppLink>147          </span>148        ))}149      </>150    )}151    {" · "}152    <AppLink className={LINK} to={treeHref(project, commit.sha)}>153      Browse files154    </AppLink>155  </span>156);157158const PART_WORDS = {159  other: "other",160  territory: "territory",161  tests: "tests",162} as const;163164/** The diff in numbers: files, lines added and removed, then split by path. */165export const DiffStatsFacts = ({ stats }: { readonly stats: DiffStats }) => (166  <FactBlock label="Diff stats">167    <p168      className="text-ui flex flex-wrap items-center gap-x-3 gap-y-1"169      data-stats=""170    >171      <span>172        {stats.files} {stats.files === 1 ? "file" : "files"}173      </span>174      <ChangeCounts additions={stats.additions} deletions={stats.deletions} />175    </p>176    {stats.parts.length === 0 ? null : (177      <ul className="text-ui flex flex-col gap-1">178        {stats.parts.map((part) => (179          <li180            className="flex items-center justify-between gap-3"181            data-part={part.label}182            key={part.label}183          >184            <span className="text-muted-foreground">185              {PART_WORDS[part.label]}186              <span className="sr-only">:</span>187            </span>188            <ChangeCounts189              additions={part.additions}190              deletions={part.deletions}191            />192          </li>193        ))}194      </ul>195    )}196  </FactBlock>197);198199/** The trailers of a commit the platform did not land, as written, linking no one. */200const WrittenTrailers = ({ commit }: { readonly commit: Commit }) =>201  commit.trailers.length === 0 ? null : (202    <FactBlock label="Trailers">203      <ul className="text-mono leading-terminal flex flex-col gap-1 font-mono">204        {commit.trailers.map(({ key, value }) => (205          <li className="[overflow-wrap:anywhere]" key={`${key}:${value}`}>206            <span className="text-muted-foreground">{key}:</span> {value}207          </li>208        ))}209      </ul>210    </FactBlock>211  );212213/** A landing's credit from the record; a commit the platform did not land, its trailers as written. */214const LandingCredit = ({ commit }: { readonly commit: Commit }) =>215  commit.landing === undefined ? (216    <WrittenTrailers commit={commit} />217  ) : (218    <CreditFacts219      assisted={commit.landing.assisted}220      credits={commit.landing.credits}221      heldBack={commit.landing.heldBackTrailer}222    />223  );224225/** Where the commit comes from: its id, its tree, its people and parents, and the landing's request. */226const provenanceOf = (commit: Commit): readonly ProvenanceEntry[] => [227  { label: "Commit", value: commit.sha },228  { label: "Tree", value: commit.tree },229  { label: "Author", value: `${commit.author.name} <${commit.author.email}>` },230  {231    label: "Committer",232    value: `${commit.committer.name} <${commit.committer.email}>`,233  },234  ...commit.parents.map((parent, index) => ({235    label: commit.parents.length === 1 ? "Parent" : `Parent ${index + 1}`,236    value: parent,237  })),238  ...(commit.landing?.verdict === undefined239    ? []240    : [{ label: "Patch id", value: commit.landing.verdict.patchId }]),241  ...(commit.landing?.requestId === undefined242    ? []243    : [{ label: "Request-Id", value: commit.landing.requestId }]),244];245246/** The inspector's facts for a commit. */247const CommitFacts = ({248  commit,249  project,250  stats,251}: {252  readonly commit: Commit;253  readonly project: ProjectName;254  readonly stats: DiffStats;255}) => {256  const linked =257    commit.landing === undefined258      ? undefined259      : Option.getOrUndefined(askOf(commit.landing));260261  return (262    <>263      <FactBlock label="State">264        <LandingStatus commit={commit} project={project} />265        {commit.landing === undefined ? null : (266          <p className="text-ui text-muted-foreground">267            By <HandleLink handle={commit.landing.author} />268            {linked === undefined || linked.kind === "opened" ? null : (269              <>270                {" · "}271                <AppLink className={LINK} to={answerPath(project, linked.ask)}>272                  the answer and its checks273                </AppLink>274              </>275            )}276          </p>277        )}278      </FactBlock>279      <LandingCredit commit={commit} />280      <DiffStatsFacts stats={stats} />281      <ProvenanceFacts entries={provenanceOf(commit)} />282    </>283  );284};285286/** A segmented pair of buttons, the pressed one in ink. */287const SEGMENT =288  "text-ui hover:bg-surface aria-pressed:bg-foreground aria-pressed:text-background aria-pressed:hover:bg-foreground flex h-7 cursor-pointer items-center gap-1.5 px-2.5 font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:size-3.5";289290/** The diff's toolbar: unified or split, fold or unfold every file, and the counts. */291export const DiffToolbar = ({292  allFolded,293  files,294  onFoldAll,295  onSplit,296  split,297  stats,298}: {299  readonly split: boolean;300  readonly onSplit?: ((split: boolean) => void) | undefined;301  /** Whether every file is folded now. */302  readonly allFolded: boolean;303  readonly onFoldAll?: ((folded: boolean) => void) | undefined;304  readonly stats: DiffStats;305  /** The Files button, below the shell's width. */306  readonly files?: ReactNode;307}) => (308  <>309    {files === undefined ? null : (310      <div className="shell:hidden flex shrink-0">{files}</div>311    )}312    <fieldset className="border-input diffsplit:flex m-0 hidden min-w-0 border p-0">313      <legend className="sr-only">Diff layout</legend>314      <button315        aria-pressed={!split}316        className={SEGMENT}317        onClick={() => onSplit?.(false)}318        type="button"319      >320        <Rows3 aria-hidden="true" strokeWidth={1.75} />321        Unified322      </button>323      <button324        aria-pressed={split}325        className={SEGMENT}326        onClick={() => onSplit?.(true)}327        type="button"328      >329        <Columns2 aria-hidden="true" strokeWidth={1.75} />330        Split331      </button>332    </fieldset>333    <span className="text-muted-foreground">334      <Button onClick={() => onFoldAll?.(!allFolded)} size="sm" variant="ghost">335        {allFolded ? (336          <UnfoldVertical aria-hidden="true" strokeWidth={1.75} />337        ) : (338          <FoldVertical aria-hidden="true" strokeWidth={1.75} />339        )}340        {allFolded ? "Unfold all" : "Collapse all"}341      </Button>342    </span>343    <p className="text-ui text-muted-foreground ml-auto flex items-center gap-3 tabular-nums">344      <span>345        {stats.files} {stats.files === 1 ? "file" : "files"}346        <span className="tablet:inline hidden"> changed</span>347      </span>348      <ChangeCounts additions={stats.additions} deletions={stats.deletions} />349    </p>350  </>351);352353export interface CommitViewProps {354  readonly diff: CommitDiff;355  readonly now: DateTime.Utc;356  readonly project: ProjectName;357  /** The ask's territory, when the commit landed an answer: the stats split by it. */358  readonly territory?: readonly string[] | undefined;359  /** Old and new side by side. */360  readonly split?: boolean;361  readonly onSplit?: ((split: boolean) => void) | undefined;362  /** The files folded now; each file's default when absent. */363  readonly folded?: ReadonlySet<string> | undefined;364  readonly onFold?: ((path: string, folded: boolean) => void) | undefined;365  readonly onFoldAll?: ((folded: boolean) => void) | undefined;366  /** The browser's drawing of the diff, holding `PlainDiff` as its fallback. */367  readonly drawing?: ReactNode;368  /** The Files button, below the shell's width. */369  readonly files?: ReactNode;370  /** The diff's files already parsed (`drawnFiles`), so a page parses each once. */371  readonly drawn?: readonly DrawnFile[] | undefined;372}373374export const CommitView = ({375  diff,376  drawing,377  drawn: parsed,378  files: filesButton,379  folded,380  now,381  onFold,382  onFoldAll,383  onSplit,384  project,385  split = false,386  territory,387}: CommitViewProps) => {388  const { commit, files, truncated } = diff;389  const body = bodyWithoutTrailers(commit);390  const drawn = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);391  const stats = useMemo(() => statsOf(drawn, territory), [drawn, territory]);392393  const allFolded = drawn.every((file) =>394    folded === undefined ? file.folded : folded.has(file.file.path)395  );396397  return (398    <Workspace399      facts={<CommitFacts commit={commit} project={project} stats={stats} />}400      factsHeading={401        commit.landing === undefined ? "This commit" : "This landing"402      }403      meta={<GitLine commit={commit} now={now} project={project} />}404      state={405        commit.landing === undefined ? undefined : (406          <span className="flex items-center gap-1.5">407            <StateMarkIcon mark="landed" />408            <strong className="text-landed font-semibold">Landed</strong>409          </span>410        )411      }412      status={413        <div className="flex flex-col gap-4">414          <LandingStatus commit={commit} project={project} />415          {body === "" ? null : (416            <p417              className="text-body max-w-[70ch] [overflow-wrap:anywhere] whitespace-pre-wrap"418              data-body=""419              data-said=""420            >421              {body}422            </p>423          )}424        </div>425      }426      title={427        commit.subject === ""428          ? `Commit ${shortSha(commit.sha)}`429          : commit.subject430      }431      toolbar={432        <DiffToolbar433          allFolded={allFolded}434          files={filesButton}435          onFoldAll={onFoldAll}436          onSplit={onSplit}437          split={split}438          stats={stats}439        />440      }441      variant="code"442    >443      {truncated ? (444        <div className={`${GUTTER} ${MEASURE}`}>445          <p className="border-rule text-ui border border-dashed px-4 py-3">446            This commit is too large to show whole: its files are listed by447            path, without their changes.448          </p>449        </div>450      ) : null}451      <DiffPane>452        {drawing ?? (453          <div className={PANE_SCROLLER}>454            <PlainDiff455              drawn={drawn}456              files={files}457              folded={folded}458              onFold={onFold}459              split={split}460            />461          </div>462        )}463      </DiffPane>464    </Workspace>465  );466};