Skip to content
Myr

row.tsx

This file

Path

apps/web/src/features/shared/row.tsx

408 lines · 11.7 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import type { AskListing } from "@repo/protocol/domain/ask";2import type { ClaimState } from "@repo/protocol/domain/claim";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { ProjectName } from "@repo/protocol/ids";5import type { DateTime } from "effect";6import type { ReactNode } from "react";7import { Fragment } from "react";89import type { AskProgress } from "./ask-progress.ts";10import { ClaimAction } from "./copy-action.tsx";11import { useListKeys } from "./keys.tsx";12import { AppLink } from "./link.tsx";13import { STATE_MARKS, StateMarkIcon } from "./marks.tsx";14import type { StateMark } from "./marks.tsx";15import { askPath } from "./paths.ts";16import { useSelection } from "./shell/selection.ts";17import type { SelectionParam } from "./shell/selection.ts";18import { When } from "./time.tsx";1920export interface RowState {21  readonly mark: StateMark;22  readonly word: string;23  readonly time?: ReactNode;24  readonly stamp?: boolean;25}2627export interface RowProps {28  readonly id: string;29  readonly href: string;30  /** A region of the page `href` opens, as a link's fragment. */31  readonly hash?: string | undefined;32  readonly search?: Readonly<Record<string, string>> | undefined;33  readonly title: string;34  readonly meta?: ReactNode;35  readonly state?: RowState | undefined;36  readonly action?: ReactNode;37  readonly strip?: ReactNode;38  readonly data?: Readonly<39    Record<`data-${string}`, string | boolean | undefined>40  >;41  readonly size?: "two-line" | "one-line";42  readonly selected?: boolean | undefined;43  readonly mono?: boolean;44}4546/**47 * Ink, the role's colour left to the mark, so a list of waiting asks is not an48 * olive stripe; a refusal keeps red and a landing green.49 */50export const wordTone = (mark: StateMark) => {51  if (mark === "refused" || mark === "retry") {52    return STATE_MARKS.refused.tone;53  }5455  return mark === "landed" ? STATE_MARKS.landed.tone : "text-foreground";56};5758export const MetaLine = ({59  parts,60}: {61  readonly parts: readonly (ReactNode | false | null | undefined)[];62}) => {63  const shown = parts.filter(64    (part) =>65      part !== undefined && part !== null && part !== false && part !== ""66  );6768  return shown.map((part, index) => (69    <Fragment key={index}>70      {index === 0 ? null : " · "}71      {part}72    </Fragment>73  ));74};7576export const MetaCode = ({ children }: { readonly children: ReactNode }) => (77  <code className="text-mono font-mono">{children}</code>78);7980export const territoryPart = (territory: string) =>81  territory === "." || territory === "" ? undefined : (82    <MetaCode>{territory}</MetaCode>83  );8485const LINK =86  "text-foreground no-underline outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-ring focus-visible:after:outline-solid";8788const StateEnd = ({89  state,90  stacked,91}: {92  readonly state: RowState | undefined;93  readonly stacked: boolean;94}) =>95  state === undefined ? null : (96    <div97      className={98        stacked99          ? "tablet:flex hidden w-40 shrink-0 flex-col items-end text-right leading-5"100          : "flex shrink-0 items-baseline gap-3"101      }102    >103      <span104        className={`text-ui font-medium ${stacked ? "leading-6" : ""} ${wordTone(state.mark)}`}105      >106        {state.word}107      </span>108      {state.time === undefined ? null : (109        <span className="text-label text-muted-foreground tabular-nums">110          {state.time}111        </span>112      )}113    </div>114  );115116export const Row = ({117  action,118  data,119  hash,120  href,121  id,122  meta,123  mono = false,124  search,125  selected = false,126  size = "two-line",127  state,128  strip,129  title,130}: RowProps) => {131  const weight = selected ? "font-semibold" : "font-medium";132  const face = mono ? "text-mono font-mono" : "";133134  const link = (135    <AppLink136      aria-current={selected ? "true" : undefined}137      className={LINK}138      data-list-key={id}139      data-said=""140      search={search}141      title={title}142      to={href}143      {...(hash === undefined ? {} : { hash })}144    >145      {title}146    </AppLink>147  );148149  const mark =150    state === undefined ? null : (151      <StateMarkIcon mark={state.mark} stamp={state.stamp === true} />152    );153154  // `isolate` keeps the row's raised controls inside the row, so a sticky155  // header passes over them.156  const rowClass = `group/row border-rule relative isolate -mx-2 border-b px-2 transition-colors duration-[120ms] ${157    selected ? "bg-surface hover:bg-surface-2" : "hover:bg-surface/50"158  }`;159160  return (161    <li className={rowClass} data-selected={selected} {...data}>162      {size === "one-line" ? (163        <div className="flex h-10 min-w-0 items-center gap-3">164          <span className="flex w-5 shrink-0 justify-center">{mark}</span>165          <p className={`text-ui min-w-0 flex-1 truncate ${weight} ${face}`}>166            {link}167            {meta === undefined ? null : (168              <span className="text-muted-foreground ml-2 font-sans font-normal">169                {meta}170              </span>171            )}172          </p>173          <StateEnd stacked={false} state={state} />174          {action}175        </div>176      ) : (177        <div className="flex min-h-16 min-w-0 items-start gap-3 py-2.5">178          <span className="flex h-6 w-5 shrink-0 items-center justify-center">179            {mark}180          </span>181          <div className="flex min-w-0 flex-1 flex-col">182            {/* Below a tablet the want, the one line that says what done183                means, may take two lines. */}184            <p185              className={`text-want tablet:line-clamp-1 line-clamp-2 break-words ${weight} ${face}`}186            >187              {link}188            </p>189            {meta === undefined && state === undefined ? null : (190              <p className="text-ui text-muted-foreground truncate leading-5">191                {state === undefined ? null : (192                  <span193                    className={`tablet:hidden font-medium ${wordTone(state.mark)}`}194                  >195                    {state.word}196                    {meta === undefined ? null : " · "}197                  </span>198                )}199                {meta}200              </p>201            )}202          </div>203          <StateEnd stacked state={state} />204          {action === undefined ? null : (205            <div className="flex h-11 shrink-0 items-center">{action}</div>206          )}207        </div>208      )}209      {strip === undefined ? null : (210        <div className={size === "one-line" ? "pb-2 pl-8" : "pb-2.5 pl-8"}>211          {strip}212        </div>213      )}214    </li>215  );216};217218// Under the top bar, or under it and a page's toolbar (styles.css's `--stick-*`).219const STICK = {220  bar: "top-(--stick-bar)",221  toolbar: "top-(--stick-toolbar)",222} as const;223224export const RowGroup = ({225  children,226  counts,227  facts,228  label,229  name,230  under = "toolbar",231}: {232  readonly name: ReactNode;233  readonly facts?: ReactNode;234  readonly counts?: string | undefined;235  readonly label?: string;236  readonly under?: keyof typeof STICK;237  readonly children: ReactNode;238}) => (239  <section aria-label={label} className="flex min-w-0 flex-col">240    <div241      className={`border-rule bg-background tablet:h-8 tablet:flex-nowrap tablet:py-0 sticky z-[5] -mx-2 flex min-h-8 min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5 border-b px-2 py-1 ${STICK[under]}`}242    >243      <h2 className="text-ui shrink-0 font-semibold [&_a]:no-underline [&_a:hover]:underline">244        {name}245      </h2>246      {facts === undefined ? null : (247        <div className="text-ui text-muted-foreground tablet:truncate flex min-w-0 items-center">248          {facts}249        </div>250      )}251      {counts === undefined ? null : (252        <p className="text-label text-muted-foreground ml-auto shrink-0 tabular-nums">253          {counts}254        </p>255      )}256    </div>257    <ul className="flex flex-col">{children}</ul>258  </section>259);260261export const RowList = ({262  children,263  label,264}: {265  readonly children: ReactNode;266  readonly label: string;267}) => (268  <ul269    aria-label={label}270    className="border-rule -mx-2 flex flex-col border-t px-2"271  >272    {children}273  </ul>274);275276export const useRowSelection = (277  ids: readonly string[],278  param: SelectionParam279) => {280  const { clear, selected } = useSelection(param);281  const { focused } = useListKeys(ids);282283  return { clear, focused, selected };284};285286export const outcomeState = (outcome: Outcome): RowState =>287  Outcome.match(outcome, {288    AwaitingDecision: (): RowState => ({ mark: "waiting", word: "Waiting" }),289    AwaitingFinish: (): RowState => ({ mark: "waiting", word: "Waiting" }),290    Checking: (): RowState => ({ mark: "checking", word: "Checking" }),291    Landed: (): RowState => ({ mark: "landed", word: "Landed" }),292    Refused: ({ refusals }): RowState => ({293      mark: refusals[0].retryable ? "retry" : "refused",294      word: "Refused",295    }),296    WaitingOnParent: (): RowState => ({ mark: "waiting", word: "Waiting" }),297  });298299export const CLAIM_STATES = {300  answered: { mark: "landed", word: "Answered" },301  lapsed: { mark: "notNeeded", word: "Lapsed" },302  live: { mark: "claimed", word: "Claimed" },303  released: { mark: "notNeeded", word: "Given up" },304  warned: { mark: "waiting", word: "Warned, no push lately" },305} as const satisfies Record<ClaimState, RowState>;306307const reserveWords = {308  newcomers: "Held for newcomers",309  people: "Held for people",310} as const;311312const askState = (313  listing: AskListing,314  takeable: boolean | undefined,315  progress: AskProgress | undefined316): RowState => {317  if (progress?.landed !== undefined) {318    return { mark: "landed", word: "Landed" };319  }320321  if (progress?.latest !== undefined) {322    return outcomeState(progress.latest);323  }324325  if (listing.claimed || progress?.claimant !== undefined) {326    return { mark: "claimed", word: "Claimed" };327  }328329  if (listing.blockedBy.length > 0) {330    return { mark: "waiting", word: "Waiting" };331  }332333  if (listing.reserve !== undefined) {334    return { mark: "open", word: reserveWords[listing.reserve] };335  }336337  return takeable === false338    ? { mark: "notYet", word: "Not open to you" }339    : { mark: "open", word: "Open to take" };340};341342const askTime = (progress: AskProgress | undefined) =>343  progress?.lastPush?.at ?? progress?.rounds.at(-1)?.at ?? progress?.opened;344345export const AskRow = ({346  listing,347  now,348  progress,349  project,350  selected,351  showProject = false,352  strip,353  takeable,354}: {355  readonly listing: AskListing;356  readonly project: ProjectName;357  readonly takeable?: boolean | undefined;358  readonly progress?: AskProgress | undefined;359  readonly selected?: boolean | undefined;360  readonly showProject?: boolean;361  readonly strip?: ReactNode;362  readonly now?: DateTime.Utc | undefined;363}) => {364  const at = askTime(progress);365  const standing = askState(listing, takeable, progress);366367  const state =368    at === undefined || now === undefined369      ? standing370      : { ...standing, time: <When at={at} now={now} /> };371372  const claimant = progress?.claimant;373  const rounds = progress?.rounds.length ?? 0;374  const open = state.mark === "open";375376  return (377    <Row378      action={379        open && takeable !== false ? (380          <ClaimAction ask={listing.ask} project={project} />381        ) : undefined382      }383      data={{384        "data-ask": listing.ask,385        "data-project": project,386        "data-takeable": takeable,387      }}388      href={askPath(project, listing.ask)}389      id={listing.ask}390      meta={391        <MetaLine392          parts={[393            showProject ? project : undefined,394            listing.kind,395            territoryPart(listing.territory),396            <MetaCode key="id">{listing.ask}</MetaCode>,397            claimant === undefined ? undefined : `claimed by ${claimant}`,398            rounds === 0 ? undefined : `round ${rounds}`,399          ]}400        />401      }402      selected={selected}403      state={state}404      strip={strip}405      title={listing.want}406    />407  );408};