Skip to content
Myr

answer-page.tsx

This file

Path

apps/web/src/features/answer/answer-page.tsx

755 lines · 20.7 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { Brand } from "@repo/brand";2import type {3  HeldBackResult,4  LaneOutcome,5  LaneResult,6  Verdict,7} from "@repo/protocol/domain/answer";8import type { Ask } from "@repo/protocol/domain/ask";9import type { LandingView } from "@repo/protocol/domain/landing";10import { Outcome } from "@repo/protocol/domain/outcome";11import type { AskId, CommitSha, Handle, ProjectName } from "@repo/protocol/ids";12import { ChecksFailed } from "@repo/protocol/refusal";13import type { DateTime } from "effect";14import { ArrowRight, ChevronDown, LockKeyhole } from "lucide-react";15import { useState } from "react";1617import { Region } from "../ask/fields.tsx";18import { commitHref, shortSha } from "../code/paths.ts";19import type { AskProgress, Round } from "../shared/ask-progress.ts";20import { CommandLine } from "../shared/command.tsx";21import { CompactCredit, CreditTrailers } from "../shared/credits.tsx";22import { EmptyState } from "../shared/empty.tsx";23import {24  ClaimFacts,25  CodeValue,26  FamilyFacts,27  ProvenanceFacts,28  shortValue,29  TerritoryFacts,30  verdictProvenance,31} from "../shared/facts.tsx";32import { AppLink } from "../shared/link.tsx";33import { StateMarkIcon } from "../shared/marks.tsx";34import type { StateMark } from "../shared/marks.tsx";35import { OutcomeView, StageStrip } from "../shared/outcome.tsx";36import { answerPath, askPath } from "../shared/paths.ts";37import { MetaCode, MetaLine, Row, RowList } from "../shared/row.tsx";38import type { Crumb } from "../shared/shell/sections.ts";39import { Workspace } from "../shared/shell/workspace.tsx";40import { readStatus, StatusLine } from "../shared/status-line.tsx";41import type { StatusSubject } from "../shared/status-line.tsx";42import { distanceInWords, When } from "../shared/time.tsx";43import {44  deleteChildOf,45  familyHead,46  holdsOf,47  roundOf,48  roundsAsTheyStand,49} from "./subject.ts";5051export const durationText = (millis: number) => {52  if (millis < 1000) {53    return `${millis} ms`;54  }5556  if (millis < 60_000) {57    return `${(millis / 1000).toFixed(1)} s`;58  }5960  const seconds = Math.round(millis / 1000);6162  return `${Math.floor(seconds / 60)} min ${seconds % 60} s`;63};6465const results = {66  blocked: { mark: "waiting", tone: "text-waiting", word: "blocked" },67  failed: { mark: "refused", tone: "text-refused", word: "failed" },68  flaked: { mark: "retry", tone: "text-waiting", word: "flaked" },69  loadError: { mark: "refused", tone: "text-refused", word: "load error" },70  passed: { mark: "passed", tone: "text-landed", word: "passed" },71} as const satisfies Record<72  LaneOutcome,73  { readonly mark: StateMark; readonly tone: string; readonly word: string }74>;7576export const answerCrumbs = (ask: Ask): readonly Crumb[] => [77  { label: ask.project, to: `/${ask.project}` },78  { label: "Asks", to: `/${ask.project}` },79  { label: ask.id, mono: true, to: askPath(ask.project, ask.id) },80  { label: "Answer" },81];8283const LaneLog = ({84  lane,85  project,86}: {87  readonly lane: LaneResult;88  readonly project: Ask["project"];89}) => {90  if (lane.logRef === undefined) {91    return null;92  }9394  return lane.logRef === ChecksFailed.withheld ? (95    <p className="text-ui text-muted-foreground">96      Its log was not kept: it held a write-only value.97    </p>98  ) : (99    <CommandLine100      command={`${Brand.cli} evidence ${lane.logRef} --project ${project}`}101    />102  );103};104105const LaneRow = ({106  lane,107  project,108}: {109  readonly lane: LaneResult;110  readonly project: Ask["project"];111}) => {112  const { mark, tone, word } = results[lane.result];113114  return (115    <li116      className="border-rule flex min-w-0 flex-col gap-2 border-b py-2.5"117      data-lane={lane.lane}118      data-result={lane.result}119    >120      <div className="text-ui flex min-w-0 items-baseline gap-3">121        <StateMarkIcon className="translate-y-[3px]" mark={mark} />122        <span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-0.5">123          <span className="text-mono text-foreground font-mono font-medium">124            {lane.lane}125          </span>126          <code className="text-mono text-muted-foreground min-w-0 font-mono [overflow-wrap:anywhere]">127            {lane.command}128          </code>129        </span>130        <span className={`shrink-0 font-medium ${tone}`}>{word}</span>131        <span className="text-label text-muted-foreground w-16 shrink-0 text-right tabular-nums">132          {durationText(lane.durationMs)}133        </span>134      </div>135      {lane.result === "passed" ? null : (136        <div className="pl-7">137          <LaneLog lane={lane} project={project} />138        </div>139      )}140    </li>141  );142};143144const passedLine = (lanes: readonly LaneResult[]) =>145  `${lanes.length} ${lanes.length === 1 ? "lane" : "lanes"} passed in ${durationText(146    lanes.reduce((total, { durationMs }) => total + durationMs, 0)147  )}`;148149export const Lanes = ({150  checking = false,151  lanes,152  project,153}: {154  readonly lanes: readonly LaneResult[];155  readonly project: Ask["project"];156  readonly checking?: boolean;157}) => {158  if (lanes.length === 0) {159    return (160      <EmptyState161        title={162          checking ? "No lane has run yet." : "No lane ran on this answer."163        }164      />165    );166  }167168  const open = lanes.filter(({ result }) => result !== "passed");169  const passed = lanes.filter(({ result }) => result === "passed");170171  return (172    <div className="flex min-w-0 flex-col">173      {open.length === 0 ? null : (174        <ul175          aria-label="Lanes that did not pass"176          className="border-rule border-t"177        >178          {open.map((lane) => (179            <LaneRow key={lane.lane} lane={lane} project={project} />180          ))}181        </ul>182      )}183      {passed.length === 0 ? null : (184        <details185          className={`group border-rule border-b ${open.length === 0 ? "border-t" : ""}`}186        >187          <summary className="text-ui hover:bg-surface/50 flex min-h-10 cursor-pointer list-none items-center gap-3 transition-colors duration-[120ms] [&::-webkit-details-marker]:hidden">188            <StateMarkIcon mark="passed" />189            <span className="min-w-0 flex-1">{passedLine(passed)}</span>190            <ChevronDown191              aria-hidden="true"192              className="text-muted-foreground size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"193              strokeWidth={1.75}194            />195          </summary>196          <ul aria-label="Lanes that passed" className="border-rule border-t">197            {passed.map((lane) => (198              <LaneRow key={lane.lane} lane={lane} project={project} />199            ))}200          </ul>201        </details>202      )}203    </div>204  );205};206207export const HeldBackBits = ({208  results: areas,209}: {210  readonly results: readonly HeldBackResult[];211}) => (212  <ul213    aria-label="Held-back checks by area"214    className="text-sealed text-mono leading-terminal flex flex-col gap-1 font-mono"215  >216    {areas.map(({ area, passed, suite, total }) => (217      <li218        className="flex items-start gap-2 [overflow-wrap:anywhere]"219        data-area={area}220        key={area}221      >222        <LockKeyhole223          aria-hidden="true"224          className="mt-1 size-3.5 shrink-0"225          strokeWidth={1.75}226        />227        <span className="min-w-0">228          {area} {passed}/{total} @{" "}229          <span title={suite}>{shortValue(suite)}</span>230        </span>231      </li>232    ))}233  </ul>234);235236const Sha = ({ sha }: { readonly sha: string }) => (237  <code className="text-mono font-mono" title={sha}>238    {shortSha(sha)}239  </code>240);241242const RoundsRegion = ({243  ask,244  current,245  now,246  project,247  rounds,248}: {249  readonly ask: AskId;250  readonly project: ProjectName;251  readonly rounds: readonly Round[];252  readonly current: CommitSha | undefined;253  readonly now: DateTime.Utc;254}) => {255  const read =256    current === undefined257      ? 0258      : rounds.findLastIndex(({ head }) => head === current) + 1;259260  return (261    <Region id="answer-rounds" title="Rounds">262      <RowList label="Rounds">263        {rounds264          .map((round, index) => ({ number: index + 1, round }))265          .toReversed()266          .map(({ number, round: { at, head, outcome } }) => {267            const { lead, mark } = readStatus({ kind: "answer", outcome });268269            return (270              <Row271                href={answerPath(project, ask)}272                id={`${head}:${number}`}273                key={`${head}:${number}`}274                meta={<CodeValue value={head} />}275                search={{ head }}276                selected={number === read}277                size="one-line"278                state={{ mark, time: <When at={at} now={now} />, word: lead }}279                title={`Round ${number} of ${rounds.length}`}280              />281            );282          })}283      </RowList>284    </Region>285  );286};287288const waitingSentence = (round: ReturnType<typeof roundOf>) =>289  round === undefined290    ? "Nothing for you to run."291    : `Nothing for you to run. Pushing again starts round ${round.of + 1}; this verdict stays as round ${round.number}.`;292293const NoAnswerYet = ({294  ask,295  now,296  states,297}: {298  readonly ask: Ask;299  readonly now: DateTime.Utc;300  readonly states: ReadonlyMap<AskId, AskProgress>;301}) => {302  const progress = states.get(ask.id);303304  const toAsk = (305    <AppLink306      className="decoration-rule underline hover:decoration-current"307      to={askPath(ask.project, ask.id)}308    >309      The ask310    </AppLink>311  );312313  const claimant = progress?.claimant;314  const pushed = progress?.lastPush;315316  if (claimant !== undefined || ask.state === "claimed") {317    const holder =318      claimant === undefined ? "Claimed" : `Claimed by ${claimant}`;319320    return (321      <EmptyState322        onward={toAsk}323        title={324          pushed === undefined325            ? `${holder}, no answer pushed yet.`326            : `${holder}; the answer pushed ${distanceInWords(pushed.at, now)} waits for the gate.`327        }328      />329    );330  }331332  const waiting = ask.blockedBy.filter(333    (blocker) => states.get(blocker)?.landed === undefined334  ).length;335336  if (ask.state === "open" && waiting > 0) {337    return (338      <EmptyState339        onward={toAsk}340        title={`Nobody has answered this ask yet; it waits for ${waiting} ${341          waiting === 1 ? "ask" : "asks"342        } to land first.`}343      />344    );345  }346347  if (ask.state === "open") {348    return (349      <EmptyState350        command={`${Brand.cli} claim ${ask.id} --project ${ask.project}`}351        title="Nobody has answered this ask yet."352      />353    );354  }355356  return (357    <EmptyState358      onward={toAsk}359      title="No answer to this ask has been checked yet."360    />361  );362};363364const Hero = ({365  ask,366  now,367  stamp,368  states,369  verdict,370}: {371  readonly ask: Ask;372  readonly now: DateTime.Utc;373  readonly stamp: boolean;374  readonly states: ReadonlyMap<AskId, AskProgress>;375  readonly verdict: Verdict | undefined;376}) => {377  const tag = verdict?.outcome._tag ?? "none";378  const [shown, setShown] = useState(tag);379  const [changed, setChanged] = useState(false);380381  if (shown !== tag) {382    setShown(tag);383    setChanged(true);384  }385386  const claimant = states.get(ask.id)?.claimant;387388  return (389    <section aria-label="Outcome" className="flex min-w-0 flex-col gap-3">390      <h2 className="sr-only">Outcome</h2>391      <div392        className={393          changed ? "animate-in fade-in-0 min-w-0 duration-150" : "min-w-0"394        }395        key={tag}396      >397        {verdict === undefined ? (398          <NoAnswerYet ask={ask} now={now} states={states} />399        ) : (400          <OutcomeView401            outcome={verdict.outcome}402            project={ask.project}403            size="title"404            stage={verdict.stage}405            stamp={stamp}406            {...(claimant === undefined ? {} : { claimant })}407          />408        )}409      </div>410    </section>411  );412};413414const Run = ({415  holds,416  landing,417  now,418  round,419  verdict,420}: {421  readonly holds: ReturnType<typeof holdsOf>;422  readonly landing: LandingView | undefined;423  readonly now: DateTime.Utc;424  readonly round: ReturnType<typeof roundOf>;425  readonly verdict: Verdict;426}) => (427  <>428    <Region id="answer-gate" title="Gate">429      <StageStrip430        holds={holds}431        outcome={verdict.outcome}432        stage={verdict.stage}433      />434      {Outcome.isAnyOf([435        "AwaitingDecision",436        "AwaitingFinish",437        "WaitingOnParent",438      ])(verdict.outcome) ? (439        <p className="text-body max-w-(--measure)" data-waiting="">440          {waitingSentence(round)}441        </p>442      ) : null}443      <p className="text-ui text-muted-foreground">444        Checked on the tree it would land as: <Sha sha={verdict.head} /> merged445        onto main at{" "}446        <AppLink447          className="decoration-rule underline hover:decoration-current"448          to={commitHref(verdict.project, verdict.base)}449        >450          <Sha sha={verdict.base} />451        </AppLink>452        .453      </p>454    </Region>455456    <Region id="answer-lanes" title="Lanes">457      <Lanes458        checking={Outcome.isAnyOf(["Checking"])(verdict.outcome)}459        lanes={verdict.lanes}460        project={verdict.project}461      />462    </Region>463464    {verdict.heldBack.length === 0 ? null : (465      <Region id="answer-held-back" title="Held back">466        <p className="text-ui text-muted-foreground max-w-(--measure)">467          Checks the answer could not see: how many passed in each area, and the468          root of the suite the project committed to before the claim.469        </p>470        <HeldBackBits results={verdict.heldBack} />471      </Region>472    )}473474    {landing === undefined ? null : (475      <Region id="answer-landing" title="Landing">476        {/* The landing told as a sentence before it is shown as a hash. */}477        <p className="text-title flex min-w-0 flex-wrap items-baseline gap-x-2 font-normal">478          <span className="flex items-center gap-2 font-semibold">479            <StateMarkIcon mark="landed" />480            <span className="text-landed">Landed</span>481          </span>482          <span className="min-w-0 [overflow-wrap:anywhere]">483            {/* The space is the sentence's; the gap only draws it. */}484            {" as "}485            <AppLink486              className="decoration-rule underline hover:decoration-current"487              to={commitHref(landing.project, landing.sha)}488            >489              <code490                className="font-mono text-[length:inherit]"491                title={landing.sha}492              >493                {shortSha(landing.sha)}494              </code>495            </AppLink>496            {landing.credits.length === 0 ? null : (497              <>498                {" · "}499                <CompactCredit credits={landing.credits} within />500              </>501            )}502            {" · "}503            <span className="text-muted-foreground">504              <When at={landing.landedAt} now={now} />505            </span>506          </span>507        </p>508        {/* More room above Credit's head than under it. */}509        <div className="mt-3">510          <CreditTrailers511            assisted={landing.assisted}512            credits={landing.credits}513            label="title"514            {...(landing.heldBackTrailer === undefined515              ? {}516              : { heldBack: landing.heldBackTrailer })}517          />518        </div>519        <div className="flex min-w-0 flex-col gap-1.5">520          <span className="text-label text-muted-foreground">521            In a clone of {landing.project}522          </span>523          <CommandLine command={`git show ${landing.sha}`} />524        </div>525        <AppLink526          className="text-ui flex items-center gap-1.5 self-start font-medium no-underline hover:underline"527          to={commitHref(landing.project, landing.sha)}528        >529          The landing commit530          <ArrowRight531            aria-hidden="true"532            className="size-4"533            strokeWidth={1.75}534          />535        </AppLink>536      </Region>537    )}538539    {/* The facts sit above the run, so the plumbing comes here, last. */}540    <div>541      <ProvenanceFacts entries={verdictProvenance(verdict, now)} />542    </div>543  </>544);545546export interface AnswerViewProps {547  readonly ask: Ask;548  readonly verdict: Verdict | undefined;549  readonly landing?: LandingView | undefined;550  readonly now: DateTime.Utc;551  readonly states?: ReadonlyMap<AskId, AskProgress>;552  readonly parent?: Ask | undefined;553  readonly head?: CommitSha | undefined;554  readonly stamp?: boolean;555  readonly viewer?: Handle | undefined;556}557558const NONE: ReadonlyMap<AskId, AskProgress> = new Map();559560const AnswerFacts = ({561  ask,562  now,563  parent,564  progress,565  states,566  verdict,567  viewer,568}: {569  readonly ask: Ask;570  readonly now: DateTime.Utc;571  readonly parent: Ask | undefined;572  readonly progress: AskProgress | undefined;573  readonly states: ReadonlyMap<AskId, AskProgress>;574  readonly verdict: Verdict | undefined;575  readonly viewer: Handle | undefined;576}) => {577  const family = familyHead(ask, parent);578  const finale = family === undefined ? undefined : deleteChildOf(family);579580  const landed =581    verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome);582583  return (584    <>585      {landed ? null : (586        <ClaimFacts587          now={now}588          {...(progress?.claimant === undefined589            ? {}590            : { claimant: progress.claimant })}591          {...(progress?.lastPush === undefined592            ? {}593            : { lastPush: progress.lastPush })}594          {...(viewer === undefined ? {} : { viewer })}595        />596      )}597      {family === undefined ? null : (598        <FamilyFacts599          current={ask.id}600          parent={family}601          project={ask.project}602          states={states}603          {...(finale === undefined ? {} : { finale })}604        />605      )}606      <TerritoryFacts ask={ask} />607    </>608  );609};610611const AnswerMeta = ({612  ask,613  head,614  now,615  rounds,616  verdict,617}: {618  readonly ask: Ask;619  readonly head: CommitSha | undefined;620  readonly now: DateTime.Utc;621  readonly rounds: AskProgress["rounds"];622  readonly verdict: Verdict | undefined;623}) => {624  const round =625    verdict === undefined ? undefined : roundOf(rounds, verdict.head);626627  return (628    <MetaLine629      parts={[630        <MetaCode key="ask">{ask.id}</MetaCode>,631        round === undefined632          ? undefined633          : `round ${round.number} of ${round.of}`,634        verdict === undefined ? undefined : (635          <span key="judged">636            judged <When at={verdict.at} now={now} />637          </span>638        ),639        head === undefined ? undefined : (640          <span key="earlier">641            an earlier answer;{" "}642            <AppLink643              className="decoration-rule underline hover:decoration-current"644              to={answerPath(ask.project, ask.id)}645            >646              the latest647            </AppLink>648          </span>649        ),650      ]}651    />652  );653};654655export const AnswerView = ({656  ask,657  head,658  landing,659  now,660  parent,661  stamp = false,662  states = NONE,663  verdict,664  viewer,665}: AnswerViewProps) => {666  const progress = states.get(ask.id);667  const rounds = roundsAsTheyStand(progress, verdict);668669  const subject: StatusSubject | undefined =670    verdict === undefined671      ? undefined672      : {673          claimant: progress?.claimant,674          kind: "answer",675          outcome: verdict.outcome,676          project: ask.project,677          stage: verdict.stage,678        };679680  return (681    <Workspace682      crumbs={answerCrumbs(ask)}683      facts={684        <AnswerFacts685          ask={ask}686          now={now}687          parent={parent}688          progress={progress}689          states={states}690          verdict={verdict}691          viewer={viewer}692        />693      }694      factsHeading="This answer"695      state={696        <StatusLine697          compact698          subject={699            subject ?? {700              ask,701              claimant: progress?.claimant,702              kind: "ask",703              takeable: ask.state === "open",704            }705          }706        />707      }708      status={709        <div className="flex min-w-0 flex-col gap-4">710          <div className="text-ui text-muted-foreground">711            <AnswerMeta712              ask={ask}713              head={head}714              now={now}715              rounds={progress?.rounds ?? []}716              verdict={verdict}717            />718          </div>719          <Hero720            ask={ask}721            now={now}722            stamp={723              stamp &&724              verdict !== undefined &&725              Outcome.isAnyOf(["Landed"])(verdict.outcome)726            }727            states={states}728            verdict={verdict}729          />730        </div>731      }732      said733      title={ask.brief.want}734    >735      {rounds.length > 1 ? (736        <RoundsRegion737          ask={ask.id}738          current={verdict?.head}739          now={now}740          project={ask.project}741          rounds={rounds}742        />743      ) : null}744      {verdict === undefined ? null : (745        <Run746          holds={holdsOf(verdict, landing, progress?.rounds ?? [])}747          landing={landing}748          now={now}749          round={roundOf(progress?.rounds ?? [], verdict.head)}750          verdict={verdict}751        />752      )}753    </Workspace>754  );755};