Skip to content
Myr

commit-view.tsx

This file

Path

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

459 lines · 13.6 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import type {2  CommitDiff,3  CommitView as Commit,4} from "@repo/protocol/domain/code";5import type { ProjectName } from "@repo/protocol/ids";6import { Option } from "effect";7import type { DateTime } from "effect";8import { Columns2, FoldVertical, Rows3, UnfoldVertical } from "lucide-react";9import { useMemo } from "react";10import type { ReactNode } from "react";1112import { Button } from "@/components/ui/button";1314import { CreditFacts, FactBlock, ProvenanceFacts } from "../shared/facts.tsx";15import type { ProvenanceEntry } from "../shared/facts.tsx";16import { HandleLink } from "../shared/handle.tsx";17import { AppLink } from "../shared/link.tsx";18import { StateMarkIcon } from "../shared/marks.tsx";19import { answerPath, askPath } from "../shared/paths.ts";20import { GUTTER } from "../shared/shell/gutter.ts";21import { MEASURE, Workspace } from "../shared/shell/workspace.tsx";22import { When } from "../shared/time.tsx";23import { askOf } from "../why/rows.ts";24import { drawnFiles, statsOf } from "./diff-model.ts";25import type { DiffStats, DrawnFile } from "./diff-model.ts";26import { DiffPane, PANE_SCROLLER } from "./diff-pane.tsx";27import { commitHref, shortSha, treeHref } from "./paths.ts";28import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";29import { pinnedRev } from "./rev.ts";3031const LINK = "decoration-rule underline hover:decoration-current";3233const TRAILER = /^[A-Za-z][\w-]*:\s/u;3435/**36 * Git's trailer block is the last paragraph when every line of it is a `Key:37 * value`.38 */39export const bodyWithoutTrailers = (commit: Commit) => {40  const paragraphs = commit.body.trim().split(/\n\s*\n/u);41  const last = paragraphs.at(-1) ?? "";4243  const trailers =44    commit.trailers.length > 0 &&45    last.split("\n").every((line) => TRAILER.test(line.trim()));4647  return (trailers ? paragraphs.slice(0, -1) : paragraphs).join("\n\n").trim();48};4950export const LandingStatus = ({51  commit,52  project,53}: {54  readonly commit: Commit;55  readonly project: ProjectName;56}) => {57  const { landing } = commit;5859  if (landing === undefined) {60    return (61      <p className="text-want text-muted-foreground flex items-start gap-2">62        <StateMarkIcon className="mt-1" mark="notNeeded" />63        <span>64          Before adoption: this commit came in with the history the project65          adopted, so no landing records it.66        </span>67      </p>68    );69  }7071  const linked = Option.getOrUndefined(askOf(landing));7273  return (74    <p className="text-want flex items-start gap-2" data-outcome="Landed">75      <StateMarkIcon className="mt-1" mark="landed" />76      <span className="min-w-0 [overflow-wrap:anywhere]">77        <strong className="text-landed font-semibold">Landed</strong> as{" "}78        <AppLink79          className={`text-mono font-mono ${LINK}`}80          to={commitHref(project, commit.sha)}81        >82          {shortSha(commit.sha)}83        </AppLink>84        {linked === undefined ? null : (85          <>86            <span aria-hidden="true" className="text-muted-foreground">87              {" · "}88            </span>89            {linked.kind === "opened" ? "opened " : "answered "}90            <AppLink91              className={`text-mono font-mono ${LINK}`}92              to={askPath(project, linked.ask)}93            >94              {linked.ask}95            </AppLink>96          </>97        )}98      </span>99    </p>100  );101};102103const GitLine = ({104  at,105  commit,106  now,107  project,108  stats,109}: {110  readonly at: string;111  readonly commit: Commit;112  readonly now: DateTime.Utc;113  readonly project: ProjectName;114  readonly stats: DiffStats;115}) => (116  <span className="[overflow-wrap:anywhere]">117    authored by {commit.author.name} <When at={commit.author.at} now={now} />118    {" · "}119    committed by{" "}120    {commit.landing === undefined ? commit.committer.name : "the platform"}121    {" · "}122    {commit.parents.length === 0 ? (123      "the first commit"124    ) : (125      <>126        {commit.parents.length === 1 ? "parent" : "parents"}{" "}127        {commit.parents.map((parent, index) => (128          <span key={parent}>129            {index === 0 ? null : ", "}130            <AppLink131              className={`text-mono font-mono ${LINK}`}132              to={commitHref(project, pinnedRev(at, parent))}133            >134              {shortSha(parent)}135            </AppLink>136          </span>137        ))}138      </>139    )}140    {" · "}141    <AppLink className={LINK} to={treeHref(project, pinnedRev(at, commit.sha))}>142      Browse files143    </AppLink>144    {" · "}145    <a146      className="inline-flex items-baseline gap-[1ch] no-underline hover:underline"147      href="#diff"148    >149      <span className="tabular-nums">150        {stats.files} {stats.files === 1 ? "file" : "files"}151      </span>152      <span aria-hidden="true">·</span>153      <ChangeCounts additions={stats.additions} deletions={stats.deletions} />154    </a>155  </span>156);157158const PART_WORDS = {159  other: "other",160  territory: "territory",161  tests: "tests",162} as const;163164export const DiffStatsFacts = ({ stats }: { readonly stats: DiffStats }) => (165  <FactBlock label="Diff stats">166    <p167      className="text-ui flex flex-wrap items-center gap-x-3 gap-y-1"168      data-stats=""169    >170      <span>171        {stats.files} {stats.files === 1 ? "file" : "files"}172      </span>173      <ChangeCounts additions={stats.additions} deletions={stats.deletions} />174    </p>175    {stats.parts.length === 0 ? null : (176      <ul className="text-ui flex flex-col gap-1">177        {stats.parts.map((part) => (178          <li179            className="flex items-center justify-between gap-3"180            data-part={part.label}181            key={part.label}182          >183            <span className="text-muted-foreground">184              {PART_WORDS[part.label]}185              <span className="sr-only">:</span>186            </span>187            <ChangeCounts188              additions={part.additions}189              deletions={part.deletions}190            />191          </li>192        ))}193      </ul>194    )}195  </FactBlock>196);197198const WrittenTrailers = ({ commit }: { readonly commit: Commit }) =>199  commit.trailers.length === 0 ? null : (200    <FactBlock label="Trailers">201      <ul className="text-mono leading-terminal flex flex-col gap-1 font-mono">202        {commit.trailers.map(({ key, value }) => (203          <li className="[overflow-wrap:anywhere]" key={`${key}:${value}`}>204            <span className="text-muted-foreground">{key}:</span> {value}205          </li>206        ))}207      </ul>208    </FactBlock>209  );210211const LandingCredit = ({ commit }: { readonly commit: Commit }) =>212  commit.landing === undefined ? (213    <WrittenTrailers commit={commit} />214  ) : (215    <CreditFacts216      assisted={commit.landing.assisted}217      credits={commit.landing.credits}218      heldBack={commit.landing.heldBackTrailer}219    />220  );221222const provenanceOf = (commit: Commit): readonly ProvenanceEntry[] => [223  { label: "Commit", value: commit.sha },224  { label: "Tree", value: commit.tree },225  { label: "Author", value: `${commit.author.name} <${commit.author.email}>` },226  {227    label: "Committer",228    value: `${commit.committer.name} <${commit.committer.email}>`,229  },230  ...commit.parents.map((parent, index) => ({231    label: commit.parents.length === 1 ? "Parent" : `Parent ${index + 1}`,232    value: parent,233  })),234  ...(commit.landing?.verdict === undefined235    ? []236    : [{ label: "Patch id", value: commit.landing.verdict.patchId }]),237  ...(commit.landing?.requestId === undefined238    ? []239    : [{ label: "Request-Id", value: commit.landing.requestId }]),240];241242const CommitFacts = ({243  commit,244  project,245  stats,246}: {247  readonly commit: Commit;248  readonly project: ProjectName;249  readonly stats: DiffStats;250}) => {251  const linked =252    commit.landing === undefined253      ? undefined254      : Option.getOrUndefined(askOf(commit.landing));255256  return (257    <>258      <FactBlock label="State">259        <LandingStatus commit={commit} project={project} />260        {commit.landing === undefined ? null : (261          <p className="text-ui text-muted-foreground">262            By <HandleLink handle={commit.landing.author} />263            {linked === undefined || linked.kind === "opened" ? null : (264              <>265                {" · "}266                <AppLink className={LINK} to={answerPath(project, linked.ask)}>267                  the answer and its checks268                </AppLink>269              </>270            )}271          </p>272        )}273      </FactBlock>274      <LandingCredit commit={commit} />275      <DiffStatsFacts stats={stats} />276      <ProvenanceFacts entries={provenanceOf(commit)} />277    </>278  );279};280281const SEGMENT =282  "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";283284export const DiffToolbar = ({285  allFolded,286  files,287  onFoldAll,288  onSplit,289  split,290  stats,291}: {292  readonly split: boolean;293  readonly onSplit?: ((split: boolean) => void) | undefined;294  readonly allFolded: boolean;295  readonly onFoldAll?: ((folded: boolean) => void) | undefined;296  readonly stats: DiffStats;297  readonly files?: ReactNode;298}) => (299  <>300    {files === undefined ? null : (301      <div className="columns:hidden flex shrink-0">{files}</div>302    )}303    <fieldset className="border-input diffsplit:flex m-0 hidden min-w-0 border p-0">304      <legend className="sr-only">Diff layout</legend>305      <button306        aria-pressed={!split}307        className={SEGMENT}308        onClick={() => onSplit?.(false)}309        type="button"310      >311        <Rows3 aria-hidden="true" strokeWidth={1.75} />312        Unified313      </button>314      <button315        aria-pressed={split}316        className={SEGMENT}317        onClick={() => onSplit?.(true)}318        type="button"319      >320        <Columns2 aria-hidden="true" strokeWidth={1.75} />321        Split322      </button>323    </fieldset>324    <span className="text-muted-foreground">325      <Button onClick={() => onFoldAll?.(!allFolded)} size="sm" variant="ghost">326        {allFolded ? (327          <UnfoldVertical aria-hidden="true" strokeWidth={1.75} />328        ) : (329          <FoldVertical aria-hidden="true" strokeWidth={1.75} />330        )}331        {allFolded ? "Unfold all" : "Collapse all"}332      </Button>333    </span>334    <p className="text-ui text-muted-foreground ml-auto flex items-center gap-3 tabular-nums">335      <span>336        {stats.files} {stats.files === 1 ? "file" : "files"}337        <span className="tablet:inline hidden"> changed</span>338      </span>339      <ChangeCounts additions={stats.additions} deletions={stats.deletions} />340    </p>341  </>342);343344export interface CommitViewProps {345  /** The fork the commit was read in (`@<handle>/<ask>`); its links stay inside it. */346  readonly at?: string | undefined;347  readonly diff: CommitDiff;348  readonly now: DateTime.Utc;349  readonly project: ProjectName;350  readonly territory?: readonly string[] | undefined;351  readonly split?: boolean;352  readonly onSplit?: ((split: boolean) => void) | undefined;353  readonly folded?: ReadonlySet<string> | undefined;354  readonly onFold?: ((path: string, folded: boolean) => void) | undefined;355  readonly onFoldAll?: ((folded: boolean) => void) | undefined;356  readonly drawing?: ReactNode;357  readonly drawn?: readonly DrawnFile[] | undefined;358}359360export const CommitView = ({361  at = "main",362  diff,363  drawing,364  drawn: parsed,365  folded,366  now,367  onFold,368  onFoldAll,369  onSplit,370  project,371  split = false,372  territory,373}: CommitViewProps) => {374  const { commit, files, truncated } = diff;375  const body = bodyWithoutTrailers(commit);376  const drawn = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);377  const stats = useMemo(() => statsOf(drawn, territory), [drawn, territory]);378379  const allFolded = drawn.every((file) =>380    folded === undefined ? file.folded : folded.has(file.file.path)381  );382383  return (384    <Workspace385      facts={<CommitFacts commit={commit} project={project} stats={stats} />}386      factsHeading={387        commit.landing === undefined ? "This commit" : "This landing"388      }389      meta={390        <GitLine391          at={at}392          commit={commit}393          now={now}394          project={project}395          stats={stats}396        />397      }398      state={399        commit.landing === undefined ? undefined : (400          <span className="flex items-center gap-1.5">401            <StateMarkIcon mark="landed" />402            <strong className="text-landed font-semibold">Landed</strong>403          </span>404        )405      }406      status={407        <div className="flex flex-col gap-4">408          <LandingStatus commit={commit} project={project} />409          {body === "" ? null : (410            <p411              className="text-body max-w-(--measure) [overflow-wrap:anywhere] whitespace-pre-wrap"412              data-body=""413              data-said=""414            >415              {body}416            </p>417          )}418        </div>419      }420      title={421        commit.subject === ""422          ? `Commit ${shortSha(commit.sha)}`423          : commit.subject424      }425      toolbar={426        <DiffToolbar427          allFolded={allFolded}428          onFoldAll={onFoldAll}429          onSplit={onSplit}430          split={split}431          stats={stats}432        />433      }434      variant="code"435    >436      {truncated ? (437        <div className={`${GUTTER} ${MEASURE}`}>438          <p className="border-rule text-ui border border-dashed px-4 py-3">439            This commit is too large to show whole: its files are listed by440            path, without their changes.441          </p>442        </div>443      ) : null}444      <DiffPane id="diff">445        {drawing ?? (446          <div className={PANE_SCROLLER}>447            <PlainDiff448              drawn={drawn}449              files={files}450              folded={folded}451              onFold={onFold}452              split={split}453            />454          </div>455        )}456      </DiffPane>457    </Workspace>458  );459};