status-line.tsx
This file
Path
apps/web/src/features/shared/status-line.tsx
605 lines · 15.7 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1/**2 * Waiting is never drawn in the refused role, and a refusal is named by its3 * tag, never paraphrased.4 */5import type { Ask } from "@repo/protocol/domain/ask";6import type { Choice, Decision } from "@repo/protocol/domain/decision";7import { Outcome } from "@repo/protocol/domain/outcome";8import type { StageName } from "@repo/protocol/domain/outcome";9import { DraftState } from "@repo/protocol/domain/proposal";10import type { Proposal } from "@repo/protocol/domain/proposal";11import type { Handle, ProjectName } from "@repo/protocol/ids";12import { headline } from "@repo/protocol/render";13import { DateTime, Match } from "effect";14import { Fragment } from "react";15import type { ReactNode } from "react";1617import { commitHref, shortSha } from "../code/paths.ts";18import { whoseMove } from "./ask-progress.ts";19import type { Family, Move } from "./ask-progress.ts";20import { CommandChip } from "./copy-action.tsx";21import { HandleLink } from "./handle.tsx";22import { AppLink } from "./link.tsx";23import { StateMarkIcon } from "./marks.tsx";24import type { StateMark } from "./marks.tsx";25import { askPath, decisionPath } from "./paths.ts";26import { distanceInWords } from "./time.tsx";2728export const stageNames = Match.type<StageName>().pipe(29 Match.when("parse", () => ({ label: "Parse", words: "parse" })),30 Match.when("shape", () => ({ label: "Shape", words: "shape" })),31 Match.when("merge", () => ({ label: "Merge", words: "merge" })),32 Match.when("cheap", () => ({ label: "Cheap", words: "cheap checks" })),33 Match.when("checks", () => ({ label: "Checks", words: "checks" })),34 Match.when("heldBack", () => ({35 label: "Held-back",36 words: "held-back checks",37 })),38 Match.when("human", () => ({ label: "Maintainer", words: "maintainer" })),39 Match.exhaustive40);4142/** What each stage runs, in a sentence. */43export const stageRuns = Match.type<StageName>().pipe(44 Match.when(45 "parse",46 () => "Who may push what: the branch, the pusher and their claim."47 ),48 Match.when(49 "shape",50 () => "What the change touches, read from its paths and added lines."51 ),52 Match.when("merge", () => "The answer merged onto the landed main."),53 Match.when(54 "cheap",55 () => "Counts on the merged tree: the project's ratchets."56 ),57 Match.when(58 "checks",59 () =>60 "The ask's check first, then every lane of the project, on the merged tree."61 ),62 Match.when(63 "heldBack",64 () => "Checks kept in a layer, one result per area and nothing more."65 ),66 Match.when(67 "human",68 () => "A maintainer's finish, when the ask's kind asks for one."69 ),70 Match.exhaustive71);7273export type StatusSubject =74 | {75 readonly kind: "answer";76 readonly outcome: Outcome;77 readonly claimant?: Handle | undefined;78 readonly stage?: StageName | undefined;79 readonly project?: ProjectName | undefined;80 }81 | {82 readonly kind: "ask";83 readonly ask: Ask;84 readonly takeable: boolean;85 readonly claimant?: Handle | undefined;86 readonly latest?: Outcome | undefined;87 readonly blockers?: Family | undefined;88 }89 | {90 readonly kind: "decision";91 readonly decision: Decision;92 readonly now: DateTime.Utc;93 readonly viewerDecides: boolean;94 }95 | { readonly kind: "proposal"; readonly proposal: Proposal };9697export type StatusTone =98 | "checking"99 | "ink"100 | "landed"101 | "muted"102 | "refused"103 | "waiting";104105const leadTone = {106 checking: "text-checking",107 ink: "text-foreground",108 landed: "text-landed",109 muted: "text-foreground",110 refused: "text-refused",111 waiting: "text-waiting",112} as const satisfies Record<StatusTone, string>;113114interface Reading {115 readonly mark: StateMark;116 readonly tone: StatusTone;117 readonly lead: string;118 readonly rest?: ReactNode;119 readonly after: readonly string[];120 readonly next?: string;121}122123const Code = ({ children }: { readonly children: ReactNode }) => (124 <code className="text-mono font-mono [overflow-wrap:anywhere]">125 {children}126 </code>127);128129const CodeLink = ({130 children,131 to,132}: {133 readonly children: ReactNode;134 readonly to: string | undefined;135}) =>136 to === undefined ? (137 <Code>{children}</Code>138 ) : (139 <AppLink140 className="decoration-rule text-mono font-mono underline hover:decoration-current"141 to={to}142 >143 {children}144 </AppLink>145 );146147const moveWords = (148 move: Move,149 {150 claimant,151 decider,152 }: {153 readonly claimant?: Handle | undefined;154 readonly decider?: Handle | undefined;155 }156): readonly string[] =>157 Match.value(move).pipe(158 Match.when("answerer", () => [159 claimant === undefined ? "the answerer's move" : `${claimant}'s move`,160 ]),161 Match.when("decider", () => [162 decider === undefined ? "a maintainer's move" : `${decider}'s move`,163 ]),164 Match.when("platform", () => ["the platform's move"]),165 Match.when("parent", () => ["that ask's move"]),166 Match.when("none", () => []),167 Match.exhaustive168 );169170const answerReading = ({171 claimant,172 outcome,173 project,174 stage,175}: {176 readonly claimant?: Handle | undefined;177 readonly outcome: Outcome;178 readonly project?: ProjectName | undefined;179 readonly stage?: StageName | undefined;180}): Reading => {181 const after = (decider?: Handle) =>182 moveWords(whoseMove(outcome, claimant), { claimant, decider });183184 return Outcome.match(outcome, {185 AwaitingDecision: ({ decision }): Reading => ({186 after: after(),187 lead: "Waiting",188 mark: "waiting",189 rest: (190 <>191 {" "}192 on decision{" "}193 <CodeLink194 to={195 project === undefined196 ? undefined197 : decisionPath(project, decision)198 }199 >200 {decision}201 </CodeLink>202 </>203 ),204 tone: "waiting",205 }),206 AwaitingFinish: ({ decider }): Reading => ({207 after: after(decider),208 lead: "Passed",209 mark: "waiting",210 rest: (211 <>212 , waiting for a maintainer's finish213 {decider === undefined ? null : (214 <>215 {" "}216 from <HandleLink handle={decider} />217 </>218 )}219 </>220 ),221 tone: "waiting",222 }),223 Checking: ({ stage: at }): Reading => ({224 after: after(),225 lead: "Checking",226 mark: "checking",227 rest: (228 <>229 {" at the "}230 <span data-term="">{stageNames(at).words}</span>231 {" stage"}232 </>233 ),234 tone: "checking",235 }),236 Landed: ({ sha }): Reading => ({237 after: [],238 lead: "Landed",239 mark: "landed",240 rest: (241 <>242 {" "}243 as{" "}244 <CodeLink245 to={project === undefined ? undefined : commitHref(project, sha)}246 >247 {shortSha(sha)}248 </CodeLink>249 </>250 ),251 tone: "landed",252 }),253 Refused: ({ refusals }): Reading => ({254 after: after(),255 lead: "Refused",256 mark: refusals[0].retryable ? "retry" : "refused",257 next: refusals[0].next,258 rest: (259 <>260 {stage === undefined ? (261 ": "262 ) : (263 <>264 {" at "}265 <span data-term="">{stageNames(stage).label}</span>266 {": "}267 </>268 )}269 <Code>{headline(refusals)}</Code>270 </>271 ),272 tone: "refused",273 }),274 WaitingOnParent: ({ ask }): Reading => ({275 after: after(),276 lead: "Passed",277 mark: "waiting",278 rest: (279 <>280 , waiting for{" "}281 <CodeLink282 to={project === undefined ? undefined : askPath(project, ask)}283 >284 {ask}285 </CodeLink>{" "}286 to land first287 </>288 ),289 tone: "waiting",290 }),291 });292};293294const heldFor = (ask: Ask): readonly string[] => {295 if (ask.reserve === "newcomers") {296 return [297 ask.mentor === undefined298 ? "held for newcomers"299 : `held for newcomers, mentored by ${ask.mentor}`,300 ];301 }302303 return ask.reserve === "people" ? ["held for people, not agents"] : [];304};305306const waitingReading = (ask: Ask, blockers: Family | undefined): Reading => {307 if (blockers !== undefined && blockers.total > 0) {308 const remaining = blockers.total - blockers.landed;309310 return remaining === 0311 ? {312 after: ["the platform's move"],313 lead: "Waiting",314 mark: "waiting",315 rest: ` to open: all ${blockers.total} children landed`,316 tone: "waiting",317 }318 : {319 after: ["the family's move"],320 lead: "Waiting",321 mark: "waiting",322 rest: ` for ${remaining} of ${blockers.total} ${323 blockers.total === 1 ? "child" : "children"324 } to land`,325 tone: "waiting",326 };327 }328329 return {330 after: ["the family's move"],331 lead: "Waiting",332 mark: "waiting",333 rest:334 ask.blockedBy.length === 0 && ask.parent !== undefined ? (335 <>336 {" "}337 for{" "}338 <CodeLink to={askPath(ask.project, ask.parent)}>339 {ask.parent}340 </CodeLink>{" "}341 to land first342 </>343 ) : (344 " for the asks it waits on to land"345 ),346 tone: "waiting",347 };348};349350const askReading = ({351 ask,352 blockers,353 claimant,354 latest,355 takeable,356}: Extract<StatusSubject, { readonly kind: "ask" }>): Reading => {357 if (latest !== undefined && Outcome.isAnyOf(["Landed"])(latest)) {358 return answerReading({ outcome: latest, project: ask.project });359 }360361 if (ask.state === "closed") {362 return { after: [], lead: "Closed", mark: "notNeeded", tone: "ink" };363 }364365 if (ask.state === "waitingOnParent") {366 return waitingReading(ask, blockers);367 }368369 if (latest !== undefined) {370 return answerReading({ claimant, outcome: latest, project: ask.project });371 }372373 if (ask.state === "claimed" || claimant !== undefined) {374 return {375 after: moveWords("answerer", { claimant }),376 lead: "Claimed",377 mark: "claimed",378 rest: (379 <>380 {claimant === undefined ? null : (381 <>382 {" "}383 by <HandleLink handle={claimant} />384 </>385 )}386 , no answer pushed yet387 </>388 ),389 tone: "ink",390 };391 }392393 return !takeable && ask.blockedBy.length > 0394 ? { after: [], lead: "Waiting", mark: "waiting", tone: "waiting" }395 : {396 after: heldFor(ask),397 lead: takeable ? "Open to take" : "Open",398 mark: "open",399 tone: "muted",400 };401};402403const chosen = {404 accept: { effect: true, word: "Accepted" },405 adopt: { effect: true, word: "Adopted" },406 decline: { effect: false, word: "Declined" },407 revert: { effect: true, word: "Reverted" },408} as const satisfies Record<409 Choice,410 { readonly effect: boolean; readonly word: string }411>;412413const deciderMove = (decision: Decision, viewerDecides: boolean) => {414 if (viewerDecides) {415 return "your move";416 }417418 const [only, ...others] = decision.deciders;419420 return others.length === 0 ? `${only}'s move` : "a maintainer's move";421};422423const decisionReading = ({424 decision,425 now,426 viewerDecides,427}: Extract<StatusSubject, { readonly kind: "decision" }>): Reading => {428 if (decision.decided !== undefined) {429 const { at, by, choice } = decision.decided;430 const { effect, word } = chosen[choice];431432 return {433 after: [distanceInWords(at, now)],434 lead: word,435 mark: effect ? "landed" : "notNeeded",436 rest: (437 <>438 {" "}439 by <HandleLink handle={by} />440 </>441 ),442 tone: effect ? "landed" : "ink",443 };444 }445446 const fallback = `default: ${decision.default}`;447448 if (DateTime.isLessThanOrEqualTo(decision.expiresAt, now)) {449 return {450 after: [`the default applies: ${decision.default}`],451 lead: "Expired",452 mark: "default",453 rest: ` ${distanceInWords(decision.expiresAt, now)}`,454 tone: "ink",455 };456 }457458 return {459 after: [fallback, deciderMove(decision, viewerDecides)],460 lead: "Expires",461 mark: "waiting",462 rest: ` ${distanceInWords(decision.expiresAt, now)}`,463 tone: "waiting",464 };465};466467const proposalReading = (proposal: Proposal): Reading => {468 if (proposal.state === "accepted") {469 return { after: [], lead: "Accepted", mark: "landed", tone: "landed" };470 }471472 if (proposal.state === "declined") {473 return { after: [], lead: "Declined", mark: "notNeeded", tone: "ink" };474 }475476 if (proposal.state === "expired") {477 return { after: [], lead: "Expired", mark: "notNeeded", tone: "ink" };478 }479480 const waiting: Reading = {481 after: ["a maintainer's move"],482 lead: "Waiting",483 mark: "waiting",484 rest: " for a maintainer to open it or decline it",485 tone: "waiting",486 };487488 return proposal.draft === undefined489 ? waiting490 : DraftState.match(proposal.draft, {491 Drafting: ({ round }): Reading => ({492 after: ["the platform's move"],493 lead: "Drafting",494 mark: "checking",495 rest: round > 1 ? `, round ${round}` : undefined,496 tone: "checking",497 }),498 Failed: ({ attempts, refusal }): Reading => ({499 after: [],500 lead: "The draft failed",501 mark: "failed",502 rest: (503 <>504 {" "}505 after {attempts} {attempts === 1 ? "attempt" : "attempts"}:{" "}506 <Code>{refusal}</Code>507 </>508 ),509 tone: "ink",510 }),511 Ready: (): Reading => ({512 after: ["a maintainer's move"],513 lead: "Ready",514 mark: "waiting",515 rest: ", waits for a maintainer",516 tone: "waiting",517 }),518 });519};520521export const readStatus: (subject: StatusSubject) => Reading =522 Match.type<StatusSubject>().pipe(523 Match.discriminator("kind")("answer", answerReading),524 Match.discriminator("kind")("ask", askReading),525 Match.discriminator("kind")("decision", decisionReading),526 Match.discriminator("kind")("proposal", ({ proposal }) =>527 proposalReading(proposal)528 ),529 Match.exhaustive530 );531532const SIZE = {533 body: { line: "text-want", mark: "mt-1" },534 title: { line: "text-title", mark: "mt-[0.3rem]" },535} as const;536537export interface StatusLineProps {538 readonly subject: StatusSubject;539 readonly command?: string | false;540 readonly compact?: boolean;541 readonly size?: keyof typeof SIZE;542 readonly stamp?: boolean;543}544545export const StatusLine = ({546 command,547 compact = false,548 size = "body",549 stamp = false,550 subject,551}: StatusLineProps) => {552 const reading = readStatus(subject);553 const next = command === false ? undefined : (command ?? reading.next);554555 if (compact) {556 return (557 <span558 className="text-ui inline-flex min-w-0 items-center gap-1.5"559 data-mark={reading.mark}560 data-tone={reading.tone}561 >562 <StateMarkIcon mark={reading.mark} stamp={stamp} />563 <strong className={`font-semibold ${leadTone[reading.tone]}`}>564 {reading.lead}565 </strong>566 </span>567 );568 }569570 return (571 <p572 className={`flex min-w-0 items-start gap-2 ${SIZE[size].line}`}573 data-mark={reading.mark}574 data-tone={reading.tone}575 >576 <StateMarkIcon577 className={SIZE[size].mark}578 mark={reading.mark}579 stamp={stamp}580 />581 <span className="min-w-0 [overflow-wrap:anywhere]">582 <strong className={`font-semibold ${leadTone[reading.tone]}`}>583 {reading.lead}584 </strong>585 {reading.rest}586 {reading.after.map((part) => (587 <Fragment key={part}>588 <span aria-hidden="true" className="text-muted-foreground">589 {" · "}590 </span>591 <span className="text-muted-foreground">{part}</span>592 </Fragment>593 ))}594 {next === undefined ? null : (595 <>596 <span aria-hidden="true" className="text-muted-foreground">597 {" · "}598 </span>599 <CommandChip command={next} />600 </>601 )}602 </span>603 </p>604 );605};