Skip to content
Myr

front-page.tsx

This file

Path

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

447 lines · 13.1 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { Brand } from "@repo/brand";2import { Reserve } from "@repo/protocol/domain/ask";3import type { Ask } from "@repo/protocol/domain/ask";4import type { ProjectEvent } from "@repo/protocol/domain/event";5import type {6  FrontPageEntry,7  ProjectListing,8} from "@repo/protocol/domain/front-page";9import type { AskId, KindName, ProjectName } from "@repo/protocol/ids";10import type { DateTime } from "effect";11import { useId, useMemo } from "react";12import type { ReactNode } from "react";1314import { postureLabel } from "../project/posture-label.ts";15import { askStates } from "../shared/ask-progress.ts";16import type { AskProgress } from "../shared/ask-progress.ts";17import { EmptyState } from "../shared/empty.tsx";18import { FamilyStrip } from "../shared/family.tsx";19import { AppLink } from "../shared/link.tsx";20import { projectPath } from "../shared/paths.ts";21import { PostureBadge } from "../shared/posture.tsx";22import { AskRow, RowGroup, useRowSelection } from "../shared/row.tsx";23import { Workspace } from "../shared/shell/workspace.tsx";24import { plural } from "./facts.tsx";25import { arrange } from "./families.ts";26import type { Arranged } from "./families.ts";27import { compact, countWith, filterEntries, frontPath } from "./filter.ts";28import type { FrontFilter, FrontFilterInput } from "./filter.ts";29import { EXPLAINER } from "./head.ts";30import { HOW_TO_TITLE, HowToTake, useHowTo } from "./how-to.tsx";3132export const frontCount = (shown: readonly FrontPageEntry[]) =>33  `${plural(shown.length, "open ask", "open asks")}, ${34    shown.filter(({ takeable }) => takeable).length35  } open to take`;3637export interface FrontPageProps {38  readonly entries: readonly FrontPageEntry[];39  readonly filter: FrontFilter;40  readonly now: DateTime.Utc;41  readonly parents: readonly Ask[];42  readonly events: ReadonlyMap<ProjectName, readonly ProjectEvent[]>;43  readonly stampsOf?: (project: ProjectName) => ReadonlySet<AskId>;44  readonly projects: readonly ProjectListing[] | undefined;45}4647const byProject = (shown: readonly FrontPageEntry[]) => {48  const groups = new Map<ProjectName, FrontPageEntry[]>();4950  for (const entry of shown) {51    groups.set(entry.project, [...(groups.get(entry.project) ?? []), entry]);52  }5354  return [...groups];55};5657const OPTION =58  "text-ui text-muted-foreground hover:bg-surface/50 hover:text-foreground aria-[current=page]:bg-surface aria-[current=page]:text-foreground flex min-h-8 min-w-0 items-center justify-between gap-3 px-2 no-underline transition-colors duration-[120ms] focus-visible:outline-offset-[-2px] aria-[current=page]:font-semibold";5960const FilterOption = ({61  count,62  current,63  label,64  search,65}: {66  readonly count: number;67  readonly current: boolean;68  readonly label: string;69  readonly search: FrontFilterInput;70}) => (71  <li className="min-w-0">72    <AppLink73      activeOptions={{ exact: true, includeSearch: true }}74      aria-current={current ? "page" : undefined}75      className={OPTION}76      to={frontPath(search)}77    >78      <span className="min-w-0 truncate">{label}</span>79      <span className="text-label text-muted-foreground shrink-0 font-normal tabular-nums">80        {count}81      </span>82    </AppLink>83  </li>84);8586const Facet = ({87  children,88  label,89}: {90  readonly children: ReactNode;91  readonly label: string;92}) => {93  const heading = useId();9495  return (96    <div className="flex min-w-0 flex-col gap-1">97      <h2 className="text-ui px-2 font-semibold" id={heading}>98        {label}99      </h2>100      <ul aria-labelledby={heading} className="flex min-w-0 flex-col">101        {children}102      </ul>103    </div>104  );105};106107const kindsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>108  [109    ...new Set([110      ...entries.map(({ ask }) => ask.kind),111      ...(filter.kind === undefined ? [] : [filter.kind]),112    ]),113  ].toSorted();114115const projectsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>116  [117    ...new Set([118      ...entries.map(({ project }) => project),119      ...(filter.project === undefined ? [] : [filter.project]),120    ]),121  ].toSorted();122123const reserveWords = {124  newcomers: "Held for newcomers",125  people: "Held for people",126} as const satisfies Record<Reserve, string>;127128const LINK = "decoration-rule underline hover:decoration-current";129130/**131 * The board's left column: links, so every filter is an address and works132 * with no script. Each option keeps the other filters as they are.133 */134const Filters = ({135  entries,136  filter,137  onRestore,138}: {139  readonly entries: readonly FrontPageEntry[];140  readonly filter: FrontFilter;141  readonly onRestore: (() => void) | undefined;142}) => {143  const held = Reserve.literals.filter(144    (reserved) =>145      entries.some(({ ask }) => ask.reserve === reserved) ||146      filter.reserved === reserved147  );148149  const filtered = Object.keys(compact(filter)).length > 0;150151  return (152    <nav153      aria-label="Filter the asks"154      className="columns:sticky columns:top-[calc(var(--top-bar)+1.5rem)] columns:max-h-[calc(100dvh-var(--top-bar)-3rem)] columns:overflow-y-auto tablet:grid-cols-3 columns:flex columns:flex-col columns:self-start -mx-2 grid min-w-0 gap-6"155    >156      <Facet label="Kind">157        <FilterOption158          count={countWith(entries, filter, { kind: undefined })}159          current={filter.kind === undefined}160          label="All"161          search={{ ...filter, kind: undefined }}162        />163        {kindsOf(entries, filter).map((kind: KindName) => (164          <FilterOption165            count={countWith(entries, filter, { kind })}166            current={filter.kind === kind}167            key={kind}168            label={kind}169            search={{ ...filter, kind }}170          />171        ))}172      </Facet>173      <Facet label="State">174        <FilterOption175          count={countWith(entries, filter, {176            reserved: undefined,177            take: undefined,178          })}179          current={filter.take === undefined && filter.reserved === undefined}180          label="Any"181          search={{ ...filter, reserved: undefined, take: undefined }}182        />183        <FilterOption184          count={countWith(entries, filter, {185            reserved: undefined,186            take: "open",187          })}188          current={filter.take === "open"}189          label="Open to take"190          search={{ ...filter, reserved: undefined, take: "open" }}191        />192        {held.map((reserved) => (193          <FilterOption194            count={countWith(entries, filter, { reserved, take: undefined })}195            current={filter.reserved === reserved}196            key={reserved}197            label={reserveWords[reserved]}198            search={{ ...filter, reserved, take: undefined }}199          />200        ))}201      </Facet>202      <Facet label="Project">203        <FilterOption204          count={countWith(entries, filter, { project: undefined })}205          current={filter.project === undefined}206          label="Every project"207          search={{ ...filter, project: undefined }}208        />209        {projectsOf(entries, filter).map((project) => (210          <FilterOption211            count={countWith(entries, filter, { project })}212            current={filter.project === project}213            key={project}214            label={project}215            search={{ ...filter, project }}216          />217        ))}218      </Facet>219      {filtered || onRestore !== undefined ? (220        <div className="text-ui flex flex-col items-start gap-2 px-2">221          {filtered ? (222            <AppLink className={LINK} to={frontPath({})}>223              Reset filters224            </AppLink>225          ) : null}226          {onRestore === undefined ? null : (227            <button228              className={`text-muted-foreground hover:text-foreground ${LINK}`}229              onClick={onRestore}230              type="button"231            >232              {HOW_TO_TITLE}233            </button>234          )}235        </div>236      ) : null}237    </nav>238  );239};240241const NoAsks = ({242  projects,243}: {244  readonly projects: readonly ProjectListing[] | undefined;245}) =>246  projects?.length === 0 ? (247    <EmptyState248      command={`${Brand.cli} init`}249      title="No open asks, and no project yet. Run init in a repo to bring it here."250    />251  ) : (252    <EmptyState253      command={`${Brand.cli} ask open <ask> --files <files>`}254      title="No open asks on any project. A maintainer opens one from an ask file."255    />256  );257258interface Group {259  readonly project: ProjectName;260  readonly entries: readonly FrontPageEntry[];261  readonly items: readonly Arranged[];262  readonly states: ReadonlyMap<AskId, AskProgress>;263}264265const rowIds = (groups: readonly Group[]) =>266  groups.flatMap(({ items }) =>267    items.map((item) =>268      item.kind === "ask" ? item.listing.ask : item.parent.ask269    )270  );271272const ProjectGroup = ({273  group,274  listing,275  now,276  parents,277  selected,278  stamps,279}: {280  readonly group: Group;281  readonly listing: ProjectListing | undefined;282  readonly now: DateTime.Utc;283  readonly parents: readonly Ask[];284  readonly selected: string | undefined;285  readonly stamps: ReadonlySet<AskId>;286}) => {287  const { entries, items, project, states } = group;288  const takeable = new Map(entries.map((entry) => [entry.ask.ask, entry]));289290  const row = (listingOf: FrontPageEntry["ask"], strip?: ReactNode) => (291    <AskRow292      key={listingOf.ask}293      listing={listingOf}294      now={now}295      progress={states.get(listingOf.ask)}296      project={project}297      selected={selected === listingOf.ask}298      strip={strip}299      takeable={takeable.get(listingOf.ask)?.takeable}300    />301  );302303  return (304    <RowGroup305      counts={`${entries.length} open · ${306        entries.filter((entry) => entry.takeable).length307      } to take`}308      facts={309        listing === undefined ? undefined : (310          <PostureBadge311            label={postureLabel(listing.posture)}312            posture={listing.posture}313          />314        )315      }316      label={project}317      name={<AppLink to={projectPath(project)}>{project}</AppLink>}318      under="bar"319    >320      {items.flatMap((item) => {321        if (item.kind === "ask") {322          return [row(item.listing)];323        }324325        const parent = parents.find(326          (ask) => ask.project === project && ask.id === item.parent.ask327        );328329        if (parent === undefined) {330          return [331            row(item.parent),332            ...item.members.map((member) => row(member)),333          ];334        }335336        return [337          row(338            item.parent,339            <FamilyStrip340              expanded={false}341              finale={item.finale}342              parent={parent}343              project={project}344              stamps={stamps}345              states={states}346              wants={347                new Map(item.members.map((member) => [member.ask, member.want]))348              }349            />350          ),351        ];352      })}353    </RowGroup>354  );355};356357export const FrontPageView = ({358  entries,359  events,360  filter,361  now,362  parents,363  projects,364  stampsOf,365}: FrontPageProps) => {366  const shown = filterEntries(entries, filter);367  const { dismiss, dismissed, restore } = useHowTo();368369  const states = useMemo(370    () =>371      new Map(372        [...events].map(373          ([project, read]) => [project, askStates(read)] as const374        )375      ),376    [events]377  );378379  const groups: readonly Group[] = byProject(shown).map(380    ([project, grouped]) => ({381      entries: grouped,382      items: arrange(grouped.map(({ ask }) => ask)),383      project,384      states: states.get(project) ?? new Map(),385    })386  );387388  const { selected } = useRowSelection(rowIds(groups), "ask");389390  return (391    <Workspace392      count={frontCount(shown)}393      crumbs={[{ label: "Asks" }]}394      status={395        <p className="text-want text-muted-foreground max-w-(--measure)">396          {EXPLAINER}397        </p>398      }399      title="Open asks"400      variant="board"401    >402      {entries.length === 0 ? (403        <NoAsks projects={projects} />404      ) : (405        <>406          {dismissed ? null : <HowToTake onDismiss={dismiss} />}407          <div408            className="columns:grid columns:grid-cols-[var(--column-filters)_minmax(0,1fr)] flex flex-col gap-8"409            data-board=""410          >411            <Filters412              entries={entries}413              filter={filter}414              onRestore={dismissed ? restore : undefined}415            />416            <div className="flex min-w-0 flex-col gap-6" data-board-list="">417              {shown.length === 0 ? (418                <EmptyState419                  onward={420                    <AppLink className={LINK} to={frontPath({})}>421                      Show every open ask422                    </AppLink>423                  }424                  title="No open asks match this filter."425                />426              ) : (427                groups.map((group) => (428                  <ProjectGroup429                    group={group}430                    key={group.project}431                    listing={projects?.find(432                      ({ project }) => project === group.project433                    )}434                    now={now}435                    parents={parents}436                    selected={selected}437                    stamps={stampsOf?.(group.project) ?? new Set()}438                  />439                ))440              )}441            </div>442          </div>443        </>444      )}445    </Workspace>446  );447};