Skip to content
Myr

decision-sections.tsx

This file

Path

apps/web/src/features/inbox/decision-sections.tsx

447 lines · 11.7 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 1–447why, one step back
1import { Brand } from "@repo/brand";
2import type { Decision, Today } from "@repo/protocol/domain/decision";3import type { LandingView } from "@repo/protocol/domain/landing";4import { Array as Arr, Option, Order } from "effect";5import type { DateTime } from "effect";6import { AsyncResult } from "effect/reactivity";7import { ChevronDown } from "lucide-react";8import { useState } from "react";9import type { ReactNode } from "react";1011import { commitHref, shortSha } from "../code/paths.ts";12import { stuckAtFoot } from "../decision/choices.tsx";13import { DecisionCard } from "../decision/decision-card.tsx";14import type { DecideInput } from "../decision/decision-card.tsx";15import {16 consequenceOf,17 decisionHref,18 decisionKey,19 describeSubject,20 subjectKind,21 takenWords,22 tookEffect,23} from "../decision/subject.ts";24import { EmptyState } from "../shared/empty.tsx";25import { useListKeys } from "../shared/keys.tsx";26import { personPath } from "../shared/paths.ts";27import { MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";28import { distanceInWords, When } from "../shared/time.tsx";29import { expiringSoon, expiryOrder } from "./decisions.ts";3031const counted = (count: number) => (count === 0 ? "none" : String(count));3233export const budgetSentence = (budget: Today["budget"]) =>34 `Decisions: ${budget.used} taken, ${counted(Math.max(0, budget.total - budget.used))} left today. Finishes are counted apart: ${counted(budget.finishes)} taken.`;3536export const budgetShort = (budget: Today["budget"]) =>37 `${counted(Math.max(0, budget.total - budget.used))} left today`;3839interface Listed {40 readonly decision: Decision;41 readonly soon: boolean;42}4344const choiceOf = (decision: Decision) => decision.decided?.choice;4546const openState = (listed: Listed, now: DateTime.Utc) => ({47 mark: listed.soon ? ("waiting" as const) : ("notYet" as const),48 time: `default: ${listed.decision.default}`,49 word: distanceInWords(listed.decision.expiresAt, now),50});5152const OpenHere = ({53 decision,54 onToggle,55 open,56}: {57 readonly decision: Decision;58 readonly open: boolean;59 readonly onToggle: () => void;60}) => (61 <button62 aria-controls={`here-${decisionKey(decision).replace("/", "-")}`}63 aria-expanded={open}64 aria-label={`${open ? "Close" : "Decide"} here: ${describeSubject(decision.subject)}`}65 className="text-muted-foreground hover:text-foreground hover:bg-surface relative z-10 inline-flex size-11 shrink-0 items-center justify-center transition-colors duration-[120ms]"66 onClick={onToggle}67 type="button"68 >69 <ChevronDown70 aria-hidden="true"71 className={`size-5 transition-transform duration-[180ms] ${open ? "rotate-180" : ""}`}72 strokeWidth={1.75}73 />74 </button>75);7677interface RowsProps {78 readonly busy: boolean;79 readonly now: DateTime.Utc;80 readonly onDecide: (input: DecideInput) => void;81 readonly open: string | undefined;82 readonly onOpen: (key: string | undefined) => void;83 readonly selected: string | undefined;84 readonly stamped: ReadonlySet<string>;85}8687const DecisionRow = ({88 listed,89 props,90}: {91 readonly listed: Listed;92 readonly props: RowsProps;93}) => {94 const { decision } = listed;95 const key = decisionKey(decision);96 const choice = choiceOf(decision);97 const isOpen = props.open === key && choice === undefined;9899 const state =100 choice === undefined101 ? openState(listed, props.now)102 : {103 mark: tookEffect(decision, choice)104 ? ("landed" as const)105 : ("notNeeded" as const),106 stamp: props.stamped.has(key),107 word: takenWords[choice],108 };109110 return (111 <Row112 action={113 choice === undefined ? (114 <OpenHere115 decision={decision}116 onToggle={() => {117 props.onOpen(isOpen ? undefined : key);118 }}119 open={isOpen}120 />121 ) : undefined122 }123 data={{124 "data-decided": choice,125 "data-decision": decision.id,126 "data-project": decision.project,127 "data-soon": listed.soon,128 }}129 href={decisionHref(decision)}130 id={key}131 meta={132 choice === undefined ? (133 <MetaLine134 parts={[135 decision.project,136 subjectKind(decision.subject),137 <MetaCode key="id">{decision.id}</MetaCode>,138 ]}139 />140 ) : (141 consequenceOf(decision.subject, choice)142 )143 }144 selected={props.selected === key}145 state={state}146 strip={147 choice === undefined ? (148 <div149 className={`pr-2 ${isOpen ? "animate-in fade-in-0 slide-in-from-top-1 pb-1 duration-[180ms]" : "hidden"}`}150 id={`here-${key.replace("/", "-")}`}151 >152 <DecisionCard153 busy={props.busy}154 choices={stuckAtFoot}155 decision={decision}156 now={props.now}157 onDecide={props.onDecide}158 soon={listed.soon}159 />160 </div>161 ) : undefined162 }163 title={describeSubject(decision.subject)}164 />165 );166};167168const Section = ({169 children,170 count,171 name,172}: {173 readonly children: ReactNode;174 readonly name: string;175 readonly count?: string;176}) => (177 <RowGroup178 {...(count === undefined ? {} : { counts: count })}179 label={name}180 name={name}181 under="bar"182 >183 {children}184 </RowGroup>185);186187const plural = (count: number, one: string, many: string) =>188 `${count} ${count === 1 ? one : many}`;189190const DecisionSections = ({191 listed,192 props,193}: {194 readonly listed: readonly Listed[];195 readonly props: RowsProps;196}) => {197 const dueToday = listed.filter(({ soon }) => soon);198 const later = listed.filter(({ soon }) => !soon);199200 return (201 <>202 {dueToday.length === 0 ? null : (203 <Section204 count={plural(dueToday.length, "decision", "decisions")}205 name="Due today"206 >207 {dueToday.map((each) => (208 <DecisionRow209 key={decisionKey(each.decision)}210 listed={each}211 props={props}212 />213 ))}214 </Section>215 )}216 {later.length === 0 ? null : (217 <Section218 count={plural(later.length, "decision", "decisions")}219 name="Within your budget"220 >221 {later.map((each) => (222 <DecisionRow223 key={decisionKey(each.decision)}224 listed={each}225 props={props}226 />227 ))}228 </Section>229 )}230 </>231 );232};233234const Tomorrow = ({ overflow }: { readonly overflow: number }) =>235 overflow === 0 ? null : (236 <Section name="Waits for tomorrow">237 <li238 className="border-rule text-ui flex min-h-10 items-center border-b py-2"239 data-overflow={overflow}240 >241 {overflow} more {overflow === 1 ? "waits" : "wait"} for tomorrow; each242 expires to its default if nobody decides first.243 </li>244 </Section>245 );246247const Newcomers = ({248 newcomers,249}: {250 readonly newcomers: Today["newcomers"];251}) =>252 newcomers.length === 0 ? null : (253 <Section name="Newcomers to welcome">254 {newcomers.map((handle) => (255 <Row256 href={personPath(handle)}257 id={handle}258 key={handle}259 meta="made a first claim this week"260 size="one-line"261 title={handle}262 />263 ))}264 </Section>265 );266267const Unattended = ({268 landings,269 now,270}: {271 readonly landings: readonly LandingView[];272 readonly now: DateTime.Utc;273}) =>274 landings.length === 0 ? null : (275 <Section name="Landed without a decision">276 {landings.map((landing) => (277 <Row278 href={commitHref(landing.project, landing.sha)}279 id={landing.sha}280 key={`${landing.project}/${landing.sha}`}281 meta={282 <MetaLine283 parts={[284 landing.project,285 <MetaCode key="sha">{shortSha(landing.sha)}</MetaCode>,286 ]}287 />288 }289 state={{290 mark: "landed",291 time: <When at={landing.landedAt} now={now} />,292 word: "Landed",293 }}294 title={295 landing.ask === undefined296 ? `Landed by ${landing.author}`297 : `${landing.ask}, answered by ${landing.author}`298 }299 />300 ))}301 </Section>302 );303304const listedOf = (305 today: Today,306 taken: ReadonlyMap<string, Listed>307): readonly Listed[] => {308 const soon = expiringSoon(today);309310 const current = today.decisions.map((decision) => {311 const key = decisionKey(decision);312313 return taken.get(key) ?? { decision, soon: soon.has(key) };314 });315316 const gone = [...taken.values()].filter(317 ({ decision }) =>318 !today.decisions.some(319 (each) => decisionKey(each) === decisionKey(decision)320 )321 );322323 return Arr.sort(324 [...current, ...gone],325 Order.combine(326 Order.mapInput(Order.Boolean, ({ soon: due }: Listed) => !due),327 Order.mapInput(expiryOrder, ({ decision }: Listed) => decision)328 )329 );330};331332const withTaken = (333 kept: ReadonlyMap<string, Listed>,334 decision: Decision,335 soon: ReadonlySet<string>336): ReadonlyMap<string, Listed> => {337 const key = decisionKey(decision);338339 return new Map([340 ...kept,341 [key, { decision, soon: kept.get(key)?.soon ?? soon.has(key) }],342 ]);343};344345const takenNow = (346 decided: AsyncResult.AsyncResult<{ readonly decision: Decision }, unknown>347): Option.Option<Decision> =>348 Option.filter(349 Option.map(AsyncResult.value(decided), ({ decision }) => decision),350 ({ decided: record }) => record !== undefined351 );352353export type Decided = AsyncResult.AsyncResult<354 { readonly decision: Decision },355 unknown356>;357358/** The decisions waiting on the reader, each decided in its row; a choice taken stays in its row after the next read leaves it out. */359export const DecisionGroups = ({360 decided,361 now,362 onDecide,363 selected,364 today,365}: {366 readonly today: Today;367 readonly now: DateTime.Utc;368 readonly onDecide: (input: DecideInput) => void;369 readonly decided: Decided;370 readonly selected: string | undefined;371}) => {372 const [kept, setKept] = useState<ReadonlyMap<string, Listed>>(new Map());373 const [open, setOpen] = useState<string>();374 const soon = expiringSoon(today);375 const fresh = takenNow(decided);376377 if (378 Option.isSome(fresh) &&379 kept.get(decisionKey(fresh.value))?.decision.decided === undefined380 ) {381 setKept(withTaken(kept, fresh.value, soon));382 }383384 const taken = Option.match(fresh, {385 onNone: () => kept,386 onSome: (decision) => withTaken(kept, decision, soon),387 });388389 const listed = listedOf(today, taken);390 useListKeys(listed.map(({ decision }) => decisionKey(decision)));391392 const stamped = new Set(393 [...kept.keys()].filter((key) => {394 const decision = kept.get(key)?.decision;395 const choice = decision?.decided?.choice;396397 return (398 decision !== undefined &&399 choice !== undefined &&400 choice !== "decline" &&401 tookEffect(decision, choice)402 );403 })404 );405406 const props: RowsProps = {407 busy: decided.waiting,408 now,409 onDecide,410 onOpen: setOpen,411 open,412 selected,413 stamped,414 };415416 return (417 <>418 {listed.length === 0 ? (419 <Section name="Decisions waiting">420 <li className="pt-3">421 <EmptyState422 command={`${Brand.cli} today`}423 title="Nothing to decide today. Undecided decisions expire to their safe default."424 />425 </li>426 </Section>427 ) : (428 <DecisionSections listed={listed} props={props} />429 )}430 <Tomorrow overflow={today.overflow} />431 </>432 );433};434435/** What happened lately in the projects the reader decides for. */436export const RecentGroups = ({437 now,438 today,439}: {440 readonly now: DateTime.Utc;441 readonly today: Today;442}) => (443 <>444 <Newcomers newcomers={today.newcomers} />445 <Unattended landings={today.unattended} now={now} />446 </>447);