Skip to content
Myr

Add /home: a signed-in reader's claims, decisions waiting and asks to take

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parent 9000f4e · Browse files · 6 files+565 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+565 added−8 removed

  • tests:+132 added−0 removed
  • other:+433 added−8 removed

6 files+565 added−8 removed

modified:apps/web/src/features/docs/head.ts+1 added-2 removed
added:apps/web/src/features/home/home-page.tsx+310 added
1/**2 * A signed-in reader's own page: their claims, each with where its answer3 * stands; the decisions waiting for them when they decide somewhere; the4 * open asks they may take; and the way to their record. No score and no5 * count of credit (DESIGN.md). Signed out, it says what the page is and how6 * to sign in. A view: what the server read, and the instant, in; markup out.7 */8import { Brand } from "@repo/brand";9import type { AnswerView } from "@repo/protocol/domain/answer";10import type { ClaimState, ClaimView } from "@repo/protocol/domain/claim";11import type { Today } from "@repo/protocol/domain/decision";12import type { FrontPageEntry } from "@repo/protocol/domain/front-page";13import { Outcome } from "@repo/protocol/domain/outcome";14import type { Handle } from "@repo/protocol/ids";15import { Array as Arr, DateTime } from "effect";1617import { signInHref } from "../auth/session-slot.tsx";18import {19 decisionHref,20 describeSubject,21 subjectKind,22} from "../decision/subject.ts";23import { CommandLine } from "../shared/command.tsx";24import { EmptyState } from "../shared/empty.tsx";25import { AppLink } from "../shared/link.tsx";26import {27 answerPath,28 ASKS_PATH,29 askPath,30 HOME_PATH,31 personPath,32} from "../shared/paths.ts";33import { UnreachableNotice } from "../shared/pending.tsx";34import { AskRow, MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";35import type { RowState } from "../shared/row.tsx";36import { Workspace } from "../shared/shell/workspace.tsx";37import { When } from "../shared/time.tsx";38import { orderDecisions } from "../today/read.ts";39import { HomeRead } from "./read.ts";4041/** What the page is, said to a reader who is not signed in. */42const WHAT_HOME_IS =43 "Home is your own page: the asks you hold and where each answer stands, the decisions waiting for you, and the asks you may take next.";4445/** The decisions the page lists; the rest are on Today. */46const DECISIONS_SHOWN = 5;4748const LINK =49 "decoration-rule hover:decoration-foreground font-medium underline underline-offset-4";5051/** A claim still running: its holder's to push to. */52const running = (claim: ClaimView) =>53 claim.state === "live" || claim.state === "warned";5455/** An answer's latest outcome as a row's state. */56const outcomeState = (answer: AnswerView): RowState =>57 Outcome.match(answer.outcome, {58 AwaitingDecision: (): RowState => ({ mark: "waiting", word: "Waiting" }),59 AwaitingFinish: (): RowState => ({ mark: "waiting", word: "Waiting" }),60 Checking: (): RowState => ({ mark: "checking", word: "Checking" }),61 Landed: (): RowState => ({ mark: "landed", word: "Landed" }),62 Refused: (): RowState => ({ mark: "refused", word: "Refused" }),63 WaitingOnParent: (): RowState => ({ mark: "waiting", word: "Waiting" }),64 });6566/** A claim with no answer yet, as a row's state. */67const CLAIM_STATES = {68 answered: { mark: "passed", word: "Answered" },69 lapsed: { mark: "notNeeded", word: "Lapsed" },70 live: { mark: "claimed", word: "Claimed" },71 released: { mark: "notNeeded", word: "Released" },72 warned: { mark: "waiting", word: "Push soon" },73} as const satisfies Record<ClaimState, RowState>;7475/**76 * Each claim's latest answer. An answer names its ask but not its project,77 * so it is matched only where one claim of the reader's holds that ask.78 */79const latestAnswers = (80 claims: readonly ClaimView[],81 answers: readonly AnswerView[]82): ReadonlyMap<ClaimView, AnswerView> => {83 const byAsk = Arr.groupBy(claims, ({ ask }) => ask);8485 return new Map(86 claims.flatMap((claim) => {87 if ((byAsk[claim.ask]?.length ?? 0) !== 1) {88 return [];89 }9091 const [latest] = answers92 .filter(({ ask }) => ask === claim.ask)93 .toSorted(94 (a, b) => DateTime.toEpochMillis(b.at) - DateTime.toEpochMillis(a.at)95 );9697 return latest === undefined ? [] : [[claim, latest] as const];98 })99 );100};101102/** Running claims first, then the newest. */103const claimOrder = (a: ClaimView, b: ClaimView) =>104 Number(running(b)) - Number(running(a)) ||105 DateTime.toEpochMillis(b.openedAt) - DateTime.toEpochMillis(a.openedAt);106107const ClaimRows = ({108 answers,109 claims,110 now,111}: {112 readonly answers: readonly AnswerView[];113 readonly claims: readonly ClaimView[];114 readonly now: DateTime.Utc;115}) => {116 const latest = latestAnswers(claims, answers);117118 return (119 <RowGroup120 counts={`${claims.filter(running).length} running`}121 label="Your claims"122 name="Your claims"123 under="bar"124 >125 {claims.toSorted(claimOrder).map((claim) => {126 const answer = latest.get(claim);127128 return (129 <Row130 data={{131 "data-claim": claim.ask,132 "data-project": claim.project,133 "data-state": claim.state,134 }}135 href={136 answer === undefined137 ? askPath(claim.project, claim.ask)138 : answerPath(claim.project, claim.ask)139 }140 id={`${claim.project}/${claim.ask}`}141 key={`${claim.project}/${claim.ask}`}142 meta={143 <MetaLine144 parts={[145 claim.project,146 <MetaCode key="fork">{claim.fork}</MetaCode>,147 running(claim) ? (148 <span key="lapses">149 lapses <When at={claim.lapsesAt} now={now} />150 </span>151 ) : undefined,152 ]}153 />154 }155 mono156 state={157 answer === undefined158 ? CLAIM_STATES[claim.state]159 : outcomeState(answer)160 }161 title={claim.ask}162 />163 );164 })}165 </RowGroup>166 );167};168169const DecisionRows = ({ today }: { readonly today: Today }) => {170 const waiting = today.decisions.length + today.overflow;171172 return (173 <RowGroup174 counts={`${waiting} waiting`}175 label="Decisions waiting"176 name={<AppLink to="/today">Decisions waiting</AppLink>}177 under="bar"178 >179 {orderDecisions(today)180 .slice(0, DECISIONS_SHOWN)181 .map((decision) => (182 <Row183 data={{184 "data-decision": decision.id,185 "data-project": decision.project,186 }}187 href={decisionHref(decision)}188 id={`${decision.project}/${decision.id}`}189 key={`${decision.project}/${decision.id}`}190 meta={191 <MetaLine192 parts={[193 decision.project,194 subjectKind(decision.subject),195 <MetaCode key="id">{decision.id}</MetaCode>,196 ]}197 />198 }199 state={{ mark: "now", word: "Yours to decide" }}200 title={describeSubject(decision.subject)}201 />202 ))}203 </RowGroup>204 );205};206207const AskRows = ({ asks }: { readonly asks: readonly FrontPageEntry[] }) => (208 <RowGroup209 label="Asks you may take"210 name={<AppLink to={ASKS_PATH}>Asks you may take</AppLink>}211 under="bar"212 >213 {asks.map(({ ask, project }) => (214 <AskRow215 key={`${project}/${ask.ask}`}216 listing={ask}217 project={project}218 showProject219 takeable220 />221 ))}222 </RowGroup>223);224225/** The way to the reader's record. */226const Record = ({ handle }: { readonly handle: Handle }) => (227 <>228 Signed in as {handle}.{" "}229 <AppLink className={LINK} to={personPath(handle)}>230 Your record231 </AppLink>232 </>233);234235const Signed = ({236 read,237 now,238}: {239 readonly read: typeof HomeRead.cases.Read.Type;240 readonly now: DateTime.Utc;241}) => (242 <Workspace243 crumbs={[{ label: "Home" }]}244 meta={<Record handle={read.handle} />}245 title="Home"246 variant="list"247 >248 <div className="flex flex-col gap-8">249 {read.claims.length === 0 ? (250 <EmptyState251 command={`${Brand.cli} front`}252 onward={253 <AppLink className={LINK} to={ASKS_PATH}>254 The open asks255 </AppLink>256 }257 title="You hold no claim. Find an ask to take, then claim it."258 />259 ) : (260 <ClaimRows answers={read.answers} claims={read.claims} now={now} />261 )}262 {read.today === undefined ? null : <DecisionRows today={read.today} />}263 {read.asks.length === 0 ? (264 <EmptyState265 onward={266 <AppLink className={LINK} to={ASKS_PATH}>267 Every open ask268 </AppLink>269 }270 title="No open ask is yours to take right now."271 />272 ) : (273 <AskRows asks={read.asks} />274 )}275 </div>276 </Workspace>277);278279/** Signed out: what the page is, the way in, and the command. */280const SignedOut = () => (281 <Workspace crumbs={[{ label: "Home" }]} title="Home">282 <div className="flex max-w-[70ch] flex-col items-start gap-3">283 <p className="text-body">{WHAT_HOME_IS}</p>284 <p className="text-ui">285 <a className={LINK} href={signInHref(HOME_PATH)}>286 Sign in287 </a>{" "}288 to see yours, or read it from a terminal:289 </p>290 <CommandLine command={`${Brand.cli} status`} />291 </div>292 </Workspace>293);294295export const HomeView = ({296 now,297 read,298}: {299 readonly now: DateTime.Utc;300 readonly read: HomeRead;301}) =>302 HomeRead.match(read, {303 Read: (signed) => <Signed now={now} read={signed} />,304 SignedOut: () => <SignedOut />,305 Unreachable: () => (306 <Workspace crumbs={[{ label: "Home" }]} title="Home">307 <UnreachableNotice />308 </Workspace>309 ),310 });
added:apps/web/src/features/home/read.ts+92 added
1/**2 * What `/home` reads, in a module with no view of its own: a route's loader3 * runs before its page's view loads.4 *5 * - `HomeRead`: the reader's claims and answers (`status`), their Today when6 * they decide somewhere, the open asks they may take (`frontPage`, read7 * as them), or why there is none of it.8 * - `readHome`: that read, made with whatever `Client` the caller gives9 * (the server's, carrying the reader's own session).10 */11import { Client } from "@repo/protocol/contracts";12import { AnswerView } from "@repo/protocol/domain/answer";13import { ClaimView } from "@repo/protocol/domain/claim";14import { Today } from "@repo/protocol/domain/decision";15import { FrontPageEntry } from "@repo/protocol/domain/front-page";16import { Handle } from "@repo/protocol/ids";17import { Unauthenticated } from "@repo/protocol/principal";18import { Cause, DateTime, Effect, Exit, Option, Schema } from "effect";1920/** The asks the page lists: the first few the reader may take; the rest are at `/asks`. */21const ASKS_SHOWN = 8;2223/** What the page read for its reader: their work, or why there is none. */24export const HomeRead = Schema.TaggedUnion({25 Read: {26 answers: Schema.Array(AnswerView),27 asks: Schema.Array(FrontPageEntry),28 claims: Schema.Array(ClaimView),29 handle: Handle,30 /** Absent for a reader who decides nowhere, or whose Today did not come. */31 today: Schema.optionalKey(Today),32 },33 SignedOut: {},34 Unreachable: {},35});3637export type HomeRead = typeof HomeRead.Type;3839/** What the loader sends: the read, and the instant it was made. */40export const HomePageData = Schema.Struct({41 now: Schema.DateTimeUtcFromString,42 read: HomeRead,43});4445export type HomePageData = typeof HomePageData.Type;4647const isUnauthenticated = Schema.is(Unauthenticated);4849/** A failed `status`, as the page says it: signed out, or the platform did not answer. */50const readOfCause = (cause: Cause.Cause<unknown>): HomeRead =>51 Option.exists(Cause.findErrorOption(cause), isUnauthenticated)52 ? HomeRead.cases.SignedOut.make({})53 : HomeRead.cases.Unreachable.make({});5455/** The reader's home, or why there is none, encoded for the page. */56export const readHome = Effect.gen(function* () {57 const client = yield* Client;5859 const [status, today, front] = yield* Effect.all(60 [61 Effect.exit(client.status({})),62 // A reader who decides nowhere has no Today: the block is left out.63 Effect.option(client.today({})),64 Effect.option(client.frontPage({})),65 ],66 { concurrency: "unbounded" }67 );6869 const read = Exit.match(status, {70 onFailure: readOfCause,71 onSuccess: ({ answers, claims, handle }) =>72 HomeRead.cases.Read.make({73 answers,74 asks: Option.match(front, {75 onNone: () => [],76 onSome: ({ entries }) =>77 entries.filter(({ takeable }) => takeable).slice(0, ASKS_SHOWN),78 }),79 claims,80 handle,81 ...Option.match(today, {82 onNone: () => ({}),83 onSome: (decisions) => ({ today: decisions }),84 }),85 }),86 });8788 return yield* Schema.encodeEffect(HomePageData)({89 now: yield* DateTime.now,90 read,91 });92});
modified:apps/web/src/routes/home.tsx+30 added-6 removed
modified:apps/web/test/edge-cache.test.ts+1 added
457 unmodified lines
458 );459460 expect(reading.toSorted()).toStrictEqual([461 "../src/routes/$project/decisions/$decision.tsx",462 "../src/routes/home.tsx",463 "../src/routes/today.tsx",464 ]);465466 for (const path of reading) {
24 unmodified lines
added:apps/web/test/home.test.tsx+131 added
1/**2 * `/home`, a signed-in reader's own page, read on the server with their3 * session from the dev world and its fixtures: their claims with where each4 * answer stands, the decisions waiting when they decide somewhere, the asks5 * they may take, and their record. Signed out, it says what the page is6 * and how to sign in. A page about its reader, kept by no cache.7 */8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Client, Contracts } from "@repo/protocol/contracts";11import { Handle } from "@repo/protocol/ids";12import { Effect, Layer, Schema } from "effect";13import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";14import { RpcClient, RpcSerialization } from "effect/rpc";1516import { devServer } from "../src/dev/server.ts";17import { devToken } from "../src/dev/sessions.ts";18import { HomeView } from "../src/features/home/home-page.tsx";19import { HomePageData, readHome } from "../src/features/home/read.ts";20import { homeHeaders, Route } from "../src/routes/home.tsx";21import { renderAt } from "./render.tsx";2223/** A `Client` of a fresh dev world with its fixtures, signed in as `handle` (or as nobody). */24const fixturesClient = (handle?: string) =>25 Layer.unwrap(26 Effect.gen(function* () {27 const { dispose, handler } = devServer({ fixtures: "on" });2829 yield* Effect.addFinalizer(() => Effect.promise(dispose));3031 return Layer.effect(Client)(RpcClient.make(Contracts)).pipe(32 Layer.provide(33 RpcClient.layerProtocolHttp({34 transformClient: HttpClient.mapRequest((request) =>35 handle === undefined36 ? request37 : HttpClientRequest.bearerToken(38 request,39 devToken(Handle.make(handle))40 )41 ),42 url: "http://localhost/rpc",43 })44 ),45 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),46 Layer.provide(47 Layer.succeed(FetchHttpClient.Fetch, (input, init) =>48 handler(new Request(input, init))49 )50 )51 );52 })53 );5455/** The page as the route renders it from what `readHome` sent. */56const pageFrom = (encoded: typeof HomePageData.Encoded) =>57 Effect.gen(function* () {58 const data = yield* Schema.decodeEffect(HomePageData)(encoded);5960 return yield* renderAt(61 "/home",62 <HomeView now={data.now} read={data.read} />63 );64 });6566const textIn = (markup: string) =>67 markup68 .replaceAll(/<[^>]+>/gu, " ")69 .replaceAll("&#x27;", "'")70 .replaceAll(/\s+/gu, " ")71 .trim();7273/** The sections' names, in order. */74const sectionsOf = (markup: string) =>75 [...markup.matchAll(/<section\b[^>]*aria-label="(?<name>[^"]+)"/gu)].map(76 (found) => found.groups?.name77 );7879describe("home, read on the server with the reader's session", () => {80 it.live(81 "gives a contributor their claims, the asks they may take and their record, and no decisions",82 () =>83 Effect.gen(function* () {84 const markup = yield* pageFrom(yield* readHome);8586 expect(sectionsOf(markup)).toStrictEqual([87 "Your claims",88 "Asks you may take",89 ]);90 expect(markup).toMatch(/data-claim="[^"]+"[^>]*data-project="vellum"/u);91 expect(markup).toContain('href="/people/bram"');92 expect(markup).toContain('href="/asks"');93 }).pipe(Effect.provide(fixturesClient("bram")), Effect.scoped),94 60_00095 );9697 it.live(98 "gives a decider the decisions waiting for them, each linking its page, and Today",99 () =>100 Effect.gen(function* () {101 const markup = yield* pageFrom(yield* readHome);102103 expect(sectionsOf(markup)).toContain("Decisions waiting");104 expect(markup).toMatch(/href="\/[a-z-]+\/decisions\/[^"]+"/u);105 expect(markup).toContain('href="/today"');106 }).pipe(Effect.provide(fixturesClient("ines-v")), Effect.scoped),107 60_000108 );109110 it.live(111 "signed out, says what the page is, how to sign in and come back, and the command",112 () =>113 Effect.gen(function* () {114 const markup = yield* pageFrom(yield* readHome);115116 expect(textIn(markup)).toContain(`${Brand.cli} status`);117 expect(markup).toContain(118 `href="/auth/signin?return=${encodeURIComponent("/home")}"`119 );120 expect(sectionsOf(markup)).toStrictEqual([]);121 }).pipe(Effect.provide(fixturesClient()), Effect.scoped),122 60_000123 );124125 it("is kept by no cache: its response is private and never stored", () => {126 expect(Route.options.headers).toBe(homeHeaders);127 expect(homeHeaders()).toStrictEqual({128 "Cache-Control": "private, no-store",129 });130 });131});