Public: anyone can read this; the crew can change it.
The clock answers in under 50 ms the first time after an edit, by loading date sheets on demand #59
Check · Review · Land · Live done — Landed and live in production.
mason/deal-clock:mason/54-the-clock-answers-in-under-50-ms-the-fir → main 3 commits fork
14 files
changed +289
−47
README.md +6 −2
| @@ -50,7 +50,9 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture | ||
| 50 | 50 | for each party, grouped as three days before, the morning of, and an |
| 51 | 51 | Overdue follow-up to the buyer, because the date passed without being marked |
| 52 | 52 | done (it waits under Reminders for today until you send or decline it). It |
| 53 | also has two buttons: Mark done, and Move this date. | |
| 53 | also has two buttons: Mark done, and Move this date. The clock itself | |
| 54 | stays small: a deal's sheets are fetched the first time you tap one of its | |
| 55 | dates, a blink later. | |
| 54 | 56 | 3. **Read and edit a reminder.** In the sheet, tap a party's reminder. You |
| 55 | 57 | see the words it would send, in a subject field and a message field, |
| 56 | 58 | already filled in. Change the message; the subject can run to 150 |
| @@ -59,7 +61,9 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture | ||
| 59 | 61 | "Reminder sent (simulated)." and the reminder now shows "Sent" with |
| 60 | 62 | today's date and your edited words, not the original draft. Under the |
| 61 | 63 | clock, the heading "Reminders for today" counts what is left ("14 to send" |
| 62 | becomes "13 to send"; when nothing is left it reads "all sent"). | |
| 64 | becomes "13 to send"; when nothing is left it reads "all sent"). Each row | |
| 65 | there opens the sheet of the date it is for, where the reminder is edited, | |
| 66 | sent or declined. | |
| 63 | 67 | Decided against a message? Beside Send, **Don't send** asks why (up to 200 |
| 64 | 68 | characters). The reminder stops counting as "to send" and reads "Not sent: |
| 65 | 69 | <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again. |
docs/TECHNICAL.md +6 −1
| @@ -38,6 +38,11 @@ sent until undone. Over the API: `POST /api/deals/:id/reminders/decline` and | ||
| 38 | 38 | `decline_reminder` and `undo_decline_reminder`; in the terminal, `n` then the |
| 39 | 39 | reason on the reminders list, and `u` to undo. Each is an update of the deal. |
| 40 | 40 | |
| 41 | `GET /deals/:id/sheets` is an HTML fragment: every date's sheet for one deal. The clock carries | |
| 42 | no sheets (they were most of its size); `sheets.js` fetches a deal's the first time one of its dates is tapped, | |
| 43 | and without script the date is a link to `/deals/:id#sheet-N`; the deal page has its sheets inline, | |
| 44 | and `.sheet:target` shows the one the link names. | |
| 45 | ||
| 41 | 46 | `GET /deals/:id/timeline` is a deal's printable client timeline: its dates in |
| 42 | 47 | order, who owes each, and Done, Upcoming or Overdue in words, with no forms, |
| 43 | 48 | contacts or script (`src/pages/timeline.ts`, rows from `src/timeline.ts`). It |
| @@ -129,7 +134,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it. | ||
| 129 | 134 | | `src/server.ts` | boot: open the database, serve | |
| 130 | 135 | | `src/tty.ts`, `src/terminal.ts` | the terminal: the pty, and the keys and screen over the same actions | |
| 131 | 136 | | `src/env.ts` | what the forge told this process | |
| 132 | | `static/app.css`, `static/live.js` | the look in the tokens' words, and the clock that stays current | | |
| 137 | | `static/app.css`, `static/live.js`, `static/sheets.js` | the look in the tokens' words, the clock that stays current, and a date's sheet fetched when tapped | | |
| 133 | 138 | |
| 134 | 139 | ## What every app stands on |
| 135 | 140 |
src/cache.test.ts +8 −4
| @@ -56,6 +56,7 @@ beforeAll(async () => { | ||
| 56 | 56 | /** Every surface that shows the deal, read as `who`. */ |
| 57 | 57 | const surfaces = async (who: Record<string, string>) => ({ |
| 58 | 58 | clock: (await get("/", who)).body, |
| 59 | sheets: (await get(`/deals/${deal.id}/sheets`, who)).body, | |
| 59 | 60 | page: (await get(`/deals/${deal.id}`, who)).body, |
| 60 | 61 | list: (await get("/api/deals", who)).body, |
| 61 | 62 | }); |
| @@ -67,14 +68,14 @@ test("a change shows on the next request of the clock, the deal page and the lis | ||
| 67 | 68 | |
| 68 | 69 | expect((await post(`/deadlines/${closing.id}/move`, { due: "2027-04-20", reason: "Lender needs a week", to: "/" })).status).toBe(303); |
| 69 | 70 | const moved = await surfaces(owner); |
| 70 | expect(moved.clock).toContain("Lender needs a week"); | |
| 71 | expect(moved.sheets).toContain("Lender needs a week"); | |
| 71 | 72 | expect(moved.page).toContain("Lender needs a week"); |
| 72 | 73 | expect(moved.list).toContain("2027-04-20"); |
| 73 | 74 | expect(moved.list).not.toBe(before.list); |
| 74 | 75 | |
| 75 | 76 | expect((await post("/deals/" + deal.id + "/parties", { role: "lender", name: "Lena Lender", contact: "[email protected]" })).status).toBe(303); |
| 76 | 77 | const added = await surfaces(owner); |
| 77 | for (const text of Object.values(added)) expect(text).toContain("Lena Lender"); | |
| 78 | for (const text of [added.sheets, added.page, added.list]) expect(text).toContain("Lena Lender"); | |
| 78 | 79 | expect(before.page).not.toContain("Lena Lender"); |
| 79 | 80 | |
| 80 | 81 | expect((await post(`/deadlines/${closing.id}/done`, { to: "/" })).status).toBe(303); |
| @@ -82,6 +83,7 @@ test("a change shows on the next request of the clock, the deal page and the lis | ||
| 82 | 83 | expect(closed.list).not.toBe(added.list); |
| 83 | 84 | expect(isClosed(closed.list)).toBe(true); |
| 84 | 85 | expect(closed.clock).not.toBe(added.clock); |
| 86 | expect(closed.sheets).not.toBe(added.sheets); | |
| 85 | 87 | expect(closed.page).not.toBe(added.page); |
| 86 | 88 | |
| 87 | 89 | expect((await post(`/deadlines/${closing.id}/done`, { done: "0", to: "/" })).status).toBe(303); |
| @@ -91,24 +93,26 @@ expect(isClosed(closed.list)).toBe(true); | ||
| 91 | 93 | test("a stranger is never handed the clock or sheets drawn for a signed-in user, nor the reverse", async () => { |
| 92 | 94 | // The owner asks first, so what is remembered was drawn for someone who may change the deal. |
| 93 | 95 | const mine = await surfaces(owner); |
| 94 | expect(mine.clock).toContain(`action="/deadlines/${closing.id}/move"`); | |
| 96 | expect(mine.sheets).toContain(`action="/deadlines/${closing.id}/move"`); | |
| 95 | 97 | expect(mine.page).toContain("[email protected]"); |
| 96 | 98 | |
| 97 | 99 | // The table lets any signed-in user change a deal, so another user is drawn the same controls. |
| 98 | 100 | const theirs = await surfaces(other); |
| 99 | expect(theirs.clock).toContain(`action="/deadlines/${closing.id}/move"`); | |
| 101 | expect(theirs.sheets).toContain(`action="/deadlines/${closing.id}/move"`); | |
| 100 | 102 | expect(theirs.page).toContain("[email protected]"); |
| 101 | 103 | |
| 102 | 104 | // A stranger sees the welcome, not a signed-in clock someone else rendered. |
| 103 | 105 | const stranger = await get("/", anon); |
| 104 | 106 | expect(stranger.body).not.toContain("Memo Mews"); |
| 105 | 107 | expect(stranger.body).not.toContain(`action="/deadlines/`); |
| 108 | expect((await get(`/deals/${deal.id}/sheets`, anon)).status).toBe(401); | |
| 106 | 109 | expect((await get(`/deals/${deal.id}`, anon)).body).not.toContain("[email protected]"); |
| 107 | 110 | expect((await get("/api/deals", anon)).status).toBe(401); |
| 108 | 111 | |
| 109 | 112 | // Signed in as each of them again: what the stranger was shown left nothing behind. |
| 110 | 113 | expect((await surfaces(admin)).page).toContain("[email protected]"); |
| 111 | 114 | expect((await surfaces(owner)).clock).toBe(mine.clock); |
| 115 | expect((await surfaces(owner)).sheets).toBe(mine.sheets); | |
| 112 | 116 | }); |
| 113 | 117 | |
| 114 | 118 | test("the memoizer makes a value once per key and drops the oldest past its limit", () => { |
src/dates.ts +11 −1
| @@ -17,7 +17,17 @@ export function isDate(value: unknown): value is string { | ||
| 17 | 17 | return d.toISOString().slice(0, 10) === value; |
| 18 | 18 | } |
| 19 | 19 | |
| 20 | const toMs = (date: string): number => Date.parse(`${date}T00:00:00Z`); | |
| 20 | // A book repeats a few hundred dates over thousands of rows: parse each once. | |
| 21 | const parsed = new Map<string, number>(); | |
| 22 | const toMs = (date: string): number => { | |
| 23 | let ms = parsed.get(date); | |
| 24 | if (ms === undefined) { | |
| 25 | ms = Date.parse(`${date}T00:00:00Z`); | |
| 26 | if (parsed.size >= 5000) parsed.clear(); | |
| 27 | parsed.set(date, ms); | |
| 28 | } | |
| 29 | return ms; | |
| 30 | }; | |
| 21 | 31 | const fromMs = (ms: number): string => new Date(ms).toISOString().slice(0, 10); |
| 22 | 32 | |
| 23 | 33 | /** `date` moved by `days` calendar days (negative goes back). */ |
src/pages/clock.ts +20 −15
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The first screen: every deal as a lane, left to right by time, today as a |
| 3 | 3 | * line down the middle of it all, and each date a marker coloured by how |
| 4 | * urgent it is. Tapping a marker opens its sheet (`sheet.ts`). Below the | |
| 4 | * urgent it is. Tapping a marker opens its sheet (`sheet.ts`), fetched on demand. Below the | |
| 5 | 5 | * clock, the reminders that go out today. |
| 6 | 6 | */ |
| 7 | 7 | |
| @@ -15,8 +15,7 @@ import type { Who } from "../who.ts"; | ||
| 15 | 15 | import { thisWeek } from "../week.ts"; |
| 16 | 16 | import { layout } from "./layout.ts"; |
| 17 | 17 | import { mayRestore } from "../actions.ts"; |
| 18 | import { badge, dealSheets, draftItem, owedBy, sheetId, URGENCY_LABEL } from "./sheet.ts"; | |
| 19 | import { canChange } from "../deals.ts"; | |
| 18 | import { badge, draftLink, opens, owedBy, URGENCY_LABEL } from "./sheet.ts"; | |
| 20 | 19 | import { find } from "../find.ts"; |
| 21 | 20 | import { memoizer, print } from "../memo.ts"; |
| 22 | 21 | |
| @@ -47,7 +46,13 @@ function rows(deal: DealView, start: string): { row: number; x: number; i: numbe | ||
| 47 | 46 | |
| 48 | 47 | const at = (days: number): string => `calc(${days} * var(--size-day))`; |
| 49 | 48 | |
| 50 | function lane(deal: DealView, start: string, on: string): string { | |
| 49 | const lanes = memoizer<string>(1000); | |
| 50 | ||
| 51 | /** One deal's lane, rendered once while the deal and the days shown stand. */ | |
| 52 | const lane = (deal: DealView, start: string, on: string): string => | |
| 53 | lanes(`${start}|${on}|${print(deal)}`, () => drawLane(deal, start, on)); | |
| 54 | ||
| 55 | function drawLane(deal: DealView, start: string, on: string): string { | |
| 51 | 56 | const placed = rows(deal, start); |
| 52 | 57 | const height = Math.max(1, ...placed.map((p) => p.row + 1)); |
| 53 | 58 | const markers = placed |
| @@ -55,7 +60,7 @@ function lane(deal: DealView, start: string, on: string): string { | ||
| 55 | 60 | const d = deal.deadlines[i]!; |
| 56 | 61 | const u = urgency(d.due, on, d.done_at !== null); |
| 57 | 62 | const tag = d.kind === "custom" ? d.label.split(" ")[0]! : KIND[d.kind].tag; |
| 58 | return `<button class="marker" data-u="${u}" popovertarget="${sheetId(d)}" style="left:${at(x)};top:calc(${row} * 3rem)" aria-label="${escape(`${d.label}, ${spoken(d.due)} — ${URGENCY_LABEL[u]}`)}"><span class="dot"></span>${escape(tag)}</button>`; | |
| 63 | return `<a class="marker" data-u="${u}" ${opens(deal, d)} style="left:${at(x)};top:calc(${row} * 3rem)" aria-label="${escape(`${d.label}, ${spoken(d.due)} — ${URGENCY_LABEL[u]}`)}"><span class="dot"></span>${escape(tag)}</a>`; | |
| 59 | 64 | }) |
| 60 | 65 | .join(""); |
| 61 | 66 | return `<li class="lane"> |
| @@ -84,6 +89,8 @@ export function axis(start: string, days: number, on: string): string { | ||
| 84 | 89 | const dayHeading = (due: string, on: string): string => |
| 85 | 90 | due < on ? "Overdue" : due === on ? "Today" : spoken(due); |
| 86 | 91 | |
| 92 | const weekRows = memoizer<string>(3000); | |
| 93 | ||
| 87 | 94 | /** Open dates due within the week, under day headings; each row opens its sheet. */ |
| 88 | 95 | function weekCard(deals: readonly DealView[], on: string): string { |
| 89 | 96 | const items = thisWeek(deals, on); |
| @@ -101,9 +108,9 @@ function weekCard(deals: readonly DealView[], on: string): string { | ||
| 101 | 108 | .map( |
| 102 | 109 | (g) => `<h3 class="week-day">${escape(g.heading)}</h3> |
| 103 | 110 | <ul class="week-list">${g.items |
| 104 | .map(({ deal, deadline: d }) => { | |
| 105 | return `<li><button class="week-row" popovertarget="${sheetId(d)}"><span class="week-what"><b>${escape(d.label)}</b><small class="muted">${escape(deal.address)} · ${owedBy(deal, d)}</small></span>${badge(d, on)}</button></li>`; | |
| 106 | }) | |
| 111 | .map(({ deal, deadline: d }) => | |
| 112 | weekRows(`${on}|${print(deal)}|${d.id}`, () => `<li><a class="week-row" ${opens(deal, d)}><span class="week-what"><b>${escape(d.label)}</b><small class="muted">${escape(deal.address)} · ${owedBy(deal, d)}</small></span>${badge(d, on)}</a></li>`), | |
| 113 | ) | |
| 107 | 114 | .join("")}</ul>`, |
| 108 | 115 | ) |
| 109 | 116 | .join(""); |
| @@ -116,14 +123,13 @@ function weekCard(deals: readonly DealView[], on: string): string { | ||
| 116 | 123 | const remembered = memoizer<{ count: number; toSend: number; html: string }>(400); |
| 117 | 124 | |
| 118 | 125 | /** One deal's reminders that go out today, as list items: counted, and rendered once while the deal stands. */ |
| 119 | function reminderRows(deal: DealView, who: Who, on: string): { count: number; toSend: number; html: string } { | |
| 120 | const may = canChange(who, deal); | |
| 121 | return remembered(`${may}|${on}|${print(deal)}`, () => { | |
| 126 | function reminderRows(deal: DealView, on: string): { count: number; toSend: number; html: string } { | |
| 127 | return remembered(`${on}|${print(deal)}`, () => { | |
| 122 | 128 | const these = drafts(deal, agent).filter((r) => pending(r, on)); |
| 123 | 129 | return { |
| 124 | 130 | count: these.length, |
| 125 | 131 | toSend: these.filter(unsent).length, |
| 126 | html: these.map((r) => draftItem(r, on, may, "/", true)).join(""), | |
| 132 | html: these.map((r) => draftLink(r, on)).join(""), | |
| 127 | 133 | }; |
| 128 | 134 | }); |
| 129 | 135 | } |
| @@ -163,7 +169,7 @@ function render(input: { | ||
| 163 | 169 | const overdue = open.filter((d) => urgency(d.due, on, false) === "overdue").length; |
| 164 | 170 | const soon = open.filter((d) => urgency(d.due, on, false) === "soon").length; |
| 165 | 171 | const { start, days } = span(deals, on); |
| 166 | const today = deals.map((deal) => reminderRows(deal, who, on)); | |
| 172 | const today = deals.map((deal) => reminderRows(deal, on)); | |
| 167 | 173 | const todayCount = today.reduce((n, t) => n + t.count, 0); |
| 168 | 174 | const none = q !== "" && found.length === 0; |
| 169 | 175 | const toSend = today.reduce((n, t) => n + t.toSend, 0); |
| @@ -181,8 +187,7 @@ function render(input: { | ||
| 181 | 187 | <div class="axis" aria-hidden="true">${axis(start, days, on)}</div> |
| 182 | 188 | <ol class="lanes">${deals.map((deal) => lane(deal, start, on)).join("")}</ol> |
| 183 | 189 | </div> |
| 184 | </div> | |
| 185 | ${deals.map((deal) => dealSheets(deal, who, on, "/")).join("")}`; | |
| 190 | </div>`; | |
| 186 | 191 | const closedCard = |
| 187 | 192 | closed.length === 0 |
| 188 | 193 | ? "" |
src/pages/layout.ts +1 −1
| @@ -64,7 +64,7 @@ export function layout(input: { | ||
| 64 | 64 | <meta name="twitter:description" content="${escape(description)}"> |
| 65 | 65 | <link rel="stylesheet" href="${tokensHref}"> |
| 66 | 66 | <link rel="stylesheet" href="${asset("app.css")}"> |
| 67 | ${plain || input.live === false ? "" : `<script type="module" src="${asset("live.js")}"></script>`} | |
| 67 | ${plain || input.live === false ? "" : `<script type="module" src="${asset("live.js")}"></script><script type="module" src="${asset("sheets.js")}"></script>`} | |
| 68 | 68 | <body${bodyClass === undefined ? "" : ` class="${escape(bodyClass)}"`}> |
| 69 | 69 | <div class="page"> |
| 70 | 70 | <header class="head"> |
src/pages/sheet.ts +27 −7
| @@ -17,6 +17,15 @@ import { owner } from "../week.ts"; | ||
| 17 | 17 | |
| 18 | 18 | export const sheetId = (d: DeadlineView): string => `sheet-${d.id}`; |
| 19 | 19 | |
| 20 | /** | |
| 21 | * What makes a date on the clock open its sheet. The clock does not carry | |
| 22 | * sheets: the link goes to the deal page (where `:target` shows the sheet it | |
| 23 | * names), and `sheets.js` fetches the deal's sheets (`/deals/:id/sheets`) the | |
| 24 | * first time one is asked for. | |
| 25 | */ | |
| 26 | export const opens = (deal: DealView, d: DeadlineView): string => | |
| 27 | `href="/deals/${deal.id}#${sheetId(d)}" data-sheet="${sheetId(d)}" data-sheets="/deals/${deal.id}/sheets"`; | |
| 28 | ||
| 20 | 29 | export const URGENCY_LABEL: Readonly<Record<Urgency, string>> = { |
| 21 | 30 | done: "Done", |
| 22 | 31 | overdue: "Overdue", |
| @@ -77,11 +86,8 @@ const undoForm = (draft: Draft, to: string): string => | ||
| 77 | 86 | <button class="button button-quiet">Undo: make it a draft again</button> |
| 78 | 87 | </form>`; |
| 79 | 88 | |
| 80 | /** | |
| 81 | * One reminder: who, when, and its words. Opened, an unsent draft is a form | |
| 82 | * the agent may edit before *Send*; a sent one shows the words that went out. | |
| 83 | */ | |
| 84 | export function draftItem(draft: Draft, on: string, may: boolean, to: string, withDeal = false): string { | |
| 89 | /** A reminder's one line: who, what it is for, and where it stands. */ | |
| 90 | function draftLine(draft: Draft, on: string, withDeal: boolean): string { | |
| 85 | 91 | const state = |
| 86 | 92 | draft.sent_at !== null |
| 87 | 93 | ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>` |
| @@ -92,7 +98,14 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string, wi | ||
| 92 | 98 | : draft.on === on |
| 93 | 99 | ? `<span class="state" data-today>Goes out today</span>` |
| 94 | 100 | : `<span class="state">Goes out ${escape(short(draft.on))}</span>`; |
| 95 | const who = `<span><b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${withDeal ? ` · ${escape(draft.label)}, ${escape(draft.address)}` : ""}</span></span>${state}`; | |
| 101 | return `<span><b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${withDeal ? ` · ${escape(draft.label)}, ${escape(draft.address)}` : ""}</span></span>${state}`; | |
| 102 | } | |
| 103 | ||
| 104 | /** | |
| 105 | * One reminder: who, when, and its words. Opened, an unsent draft is a form | |
| 106 | * the agent may edit before *Send*; a sent one shows the words that went out. | |
| 107 | */ | |
| 108 | export function draftItem(draft: Draft, on: string, may: boolean, to: string): string { | |
| 96 | 109 | const inside = |
| 97 | 110 | draft.sent_at !== null |
| 98 | 111 | ? draftText(draft) |
| @@ -101,9 +114,16 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string, wi | ||
| 101 | 114 | : may |
| 102 | 115 | ? `${sendForm(draft, to)}${declineForm(draft, to)}` |
| 103 | 116 | : draftText(draft); |
| 104 | return `<li class="draft"><details><summary>${who}</summary>${inside}</details></li>`; | |
| 117 | return `<li class="draft"><details><summary>${draftLine(draft, on, false)}</summary>${inside}</details></li>`; | |
| 105 | 118 | } |
| 106 | 119 | |
| 120 | /** | |
| 121 | * A reminder on the clock: its line, opening the sheet of the date it is | |
| 122 | * for, where the draft is edited and sent. The clock carries no forms. | |
| 123 | */ | |
| 124 | export const draftLink = (draft: Draft, on: string): string => | |
| 125 | `<li class="draft"><a class="draft-open" href="/deals/${draft.deal_id}#sheet-${draft.deadline_id}" data-sheet="sheet-${draft.deadline_id}" data-sheets="/deals/${draft.deal_id}/sheets">${draftLine(draft, on, true)}</a></li>`; | |
| 126 | ||
| 107 | 127 | export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string): string { |
| 108 | 128 | const id = sheetId(d); |
| 109 | 129 | const may = canChange(who, deal); |
src/routes.ts +11
| @@ -64,6 +64,7 @@ import { book, calendar } from "./ics.ts"; | ||
| 64 | 64 | import { rpc } from "./mcp.ts"; |
| 65 | 65 | import { FIND_REFUSAL, find, query } from "./find.ts"; |
| 66 | 66 | import { clock } from "./pages/clock.ts"; |
| 67 | import { dealSheets } from "./pages/sheet.ts"; | |
| 67 | 68 | import { dealPage, newDealPage } from "./pages/deal.ts"; |
| 68 | 69 | import { refusedPage } from "./pages/refused.ts"; |
| 69 | 70 | import { people } from "./people.ts"; |
| @@ -437,6 +438,16 @@ export const routes: readonly Route[] = [ | ||
| 437 | 438 | return html(dealPage({ who: c.who, deal: found.value, on: today(), notice }), 200, clear); |
| 438 | 439 | }, |
| 439 | 440 | }, |
| 441 | { | |
| 442 | method: "GET", | |
| 443 | path: "/deals/:id/sheets", | |
| 444 | // A fragment: every sheet of one deal, fetched by `sheets.js` when the clock asks for one. | |
| 445 | handle: (c) => { | |
| 446 | const found = getDeal(c.db, c.who, { id: Number(c.params.id) }); | |
| 447 | if (!found.ok) return text(found.message, STATUS[found.error]); | |
| 448 | return html(dealSheets(found.value, c.who, today(), "/")); | |
| 449 | }, | |
| 450 | }, | |
| 440 | 451 | { |
| 441 | 452 | method: "GET", |
| 442 | 453 | path: "/deals/:id/timeline", |
src/server.test.ts +9 −7
| @@ -77,7 +77,8 @@ test("the clock knows who you are and offers the right door", async () => { | ||
| 77 | 77 | expect(signed).toContain("<h1>The clock</h1>"); |
| 78 | 78 | expect(signed).toContain("/__forge/signout"); |
| 79 | 79 | expect(signed).toContain('href="/deals/new"'); |
| 80 | expect(signed).toContain('action="/deadlines/'); | |
| 80 | expect(signed).toContain('data-sheets="/deals/'); | |
| 81 | expect(signed).not.toContain("popover id="); | |
| 81 | 82 | }); |
| 82 | 83 | |
| 83 | 84 | test("a form post opens a deal as the person; a guest is sent to sign in", async () => { |
| @@ -731,16 +732,17 @@ test("the page offers an unsent draft as an edit form, and shows a sent one as i | ||
| 731 | 732 | const deal = deals[deals.length - 1]!; |
| 732 | 733 | const deadline = deal.deadlines.find((x) => x.done_at === null && !deal.sent.some((s) => s.deadline_id === x.id))!; |
| 733 | 734 | const party = deal.parties.find((p) => p.role === deadline.owes)!; |
| 734 | const before = await (await api("/", {}, editor)).text(); | |
| 735 | const sheets = async () => (await api(`/deals/${deal.id}/sheets`, {}, editor)).text(); | |
| 736 | const before = await sheets(); | |
| 735 | 737 | expect(before).toContain('name="subject" value="'); |
| 736 | 738 | expect(before).toContain('<textarea class="input" name="body"'); |
| 737 | const guest = await (await fetch(base + "/")).text(); | |
| 739 | const guest = await (await fetch(base + `/deals/${deal.id}/sheets`)).text(); | |
| 738 | 740 | expect(guest).not.toContain('name="subject"'); |
| 739 | 741 | const form = new FormData(); |
| 740 | 742 | for (const [k, v] of Object.entries({ deadline: String(deadline.id), party: String(party.id), moment: "before", subject: "Sent <u>words</u>", body: "Sent <script>x</script> body", to: "/" })) |
| 741 | 743 | form.set(k, v); |
| 742 | 744 | expect((await api("/reminders", { method: "POST", body: form, redirect: "manual" }, editor)).status).toBe(303); |
| 743 | const after = await (await api("/", {}, editor)).text(); | |
| 745 | const after = await sheets(); | |
| 744 | 746 | expect(after).toContain("Sent <u>words</u>"); |
| 745 | 747 | expect(after).toContain("Sent <script>x</script> body"); |
| 746 | 748 | expect(after).not.toContain("<script>x</script>"); |
| @@ -953,7 +955,7 @@ test("This week lists the sample's overdue inspection and this week's closing, a | ||
| 953 | 955 | expect(week).toContain("Closing"); |
| 954 | 956 | expect(week).toContain("1418 Alder Lane"); |
| 955 | 957 | expect(week).toContain('data-live="deal.changed"'); |
| 956 | expect(week).toContain("popovertarget="); | |
| 958 | expect(week).toContain("data-sheet="); | |
| 957 | 959 | }); |
| 958 | 960 | |
| 959 | 961 | test("This week over MCP lists the same dates, for a signed-in account only; a date marked done drops off the card", async () => { |
| @@ -971,9 +973,9 @@ test("This week over MCP lists the same dates, for a signed-in account only; a d | ||
| 971 | 973 | const page = await (await api("/", {}, week)).text(); |
| 972 | 974 | return page.slice(page.indexOf('id="week"'), page.indexOf('id="today"')); |
| 973 | 975 | }; |
| 974 | expect(await card()).toContain(`popovertarget="sheet-${late.deadline.id}"`); | |
| 976 | expect(await card()).toContain(`data-sheet="sheet-${late.deadline.id}"`); | |
| 975 | 977 | await call("mark_done", { id: late.deadline.id }, week); |
| 976 | expect(await card()).not.toContain(`popovertarget="sheet-${late.deadline.id}"`); | |
| 978 | expect(await card()).not.toContain(`data-sheet="sheet-${late.deadline.id}"`); | |
| 977 | 979 | }); |
| 978 | 980 | |
| 979 | 981 | test("the clock's Find box narrows the clock, echoes escaped, and refuses bad input", async () => { |
src/server.ts +1 −1
| @@ -101,7 +101,7 @@ const compressed = new WeakMap<Uint8Array, Uint8Array>(); | ||
| 101 | 101 | function gzipped(body: Uint8Array): Uint8Array { |
| 102 | 102 | let zipped = compressed.get(body); |
| 103 | 103 | if (zipped === undefined) { |
| 104 | zipped = Bun.gzipSync(body); | |
| 104 | zipped = Bun.gzipSync(body, { level: 1 }); | |
| 105 | 105 | compressed.set(body, zipped); |
| 106 | 106 | } |
| 107 | 107 | return zipped; |
src/sheets.test.ts added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | /** The clock opens a date's sheet on demand: its links, its script, its fragment. */ | |
| 2 | import { afterAll, beforeEach, expect, test } from "bun:test"; | |
| 3 | import { mkdtempSync } from "node:fs"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { forgetRationing } from "./security.ts"; | |
| 7 | import { serve } from "./server.ts"; | |
| 8 | import { sign } from "./who.ts"; | |
| 9 | ||
| 10 | const KEY = "a-key-only-the-forge-holds"; | |
| 11 | const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-sheets-")), identityKey: KEY }); | |
| 12 | const base = `http://${server.hostname}:${server.port}`; | |
| 13 | afterAll(() => server.stop(true)); | |
| 14 | beforeEach(forgetRationing); | |
| 15 | ||
| 16 | const identity = `u1|alice|user|${Date.now() + 600_000}`; | |
| 17 | const alice = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 18 | const clockPage = async (): Promise<string> => (await fetch(base + "/", { headers: alice })).text(); | |
| 19 | ||
| 20 | test("a reminder row on the clock links to its date's sheet and carries no form", async () => { | |
| 21 | const page = await clockPage(); | |
| 22 | const today = page.slice(page.indexOf('id="today"')); | |
| 23 | const rows = [...today.matchAll(/<li class="draft"><a class="draft-open" href="\/deals\/(\d+)#sheet-(\d+)" data-sheet="sheet-\2" data-sheets="\/deals\/\1\/sheets">/g)]; | |
| 24 | expect(rows.length).toBeGreaterThan(0); | |
| 25 | expect(today).not.toContain("<details>"); | |
| 26 | expect(today).not.toContain('action="/reminders'); | |
| 27 | expect(today).not.toContain("<textarea"); | |
| 28 | // The sheet the row names is in the fragment the script fetches, with the draft's form. | |
| 29 | const [, deal, sheet] = rows[0]!; | |
| 30 | const fragment = await (await fetch(`${base}/deals/${deal}/sheets`, { headers: alice })).text(); | |
| 31 | expect(fragment).toContain(`id="sheet-${sheet}"`); | |
| 32 | }); | |
| 33 | ||
| 34 | test("signed-in pages load sheets.js; a plain or live=false page does not; the asset is served", async () => { | |
| 35 | const page = await clockPage(); | |
| 36 | const src = /src="(\/static\/sheets\.js\?v=[0-9a-f]{8})"/.exec(page)?.[1]; | |
| 37 | expect(src).toBeDefined(); | |
| 38 | const script = await fetch(base + src!); | |
| 39 | expect(script.status).toBe(200); | |
| 40 | expect(script.headers.get("cache-control")).toContain("immutable"); | |
| 41 | expect(await script.text()).toContain("showPopover"); | |
| 42 | const { layout } = await import("./pages/layout.ts"); | |
| 43 | const who = { role: "user", id: "u1", name: "alice" } as const; | |
| 44 | expect(layout({ body: "", who, path: "/" })).toContain("sheets.js"); | |
| 45 | expect(layout({ body: "", who, path: "/", live: false })).not.toContain("sheets.js"); | |
| 46 | expect(layout({ body: "", who, path: "/", plain: true })).not.toContain("sheets.js"); | |
| 47 | }); | |
| 48 | ||
| 49 | test("sheets.js fetches a deal once, opens the sheet asked for, drops closed sheets on a change, and falls back to the link", async () => { | |
| 50 | const real = { document: (globalThis as any).document, fetch: globalThis.fetch, location: (globalThis as any).location }; | |
| 51 | const listeners: Record<string, (event: any) => unknown> = {}; | |
| 52 | const holders: any[] = []; | |
| 53 | const opened: string[] = []; | |
| 54 | const fetched: string[] = []; | |
| 55 | let failing = false; | |
| 56 | const sheets = new Map<string, { showPopover(): void }>(); | |
| 57 | (globalThis as any).document = { | |
| 58 | addEventListener: (type: string, fn: (event: any) => unknown) => (listeners[type] = fn), | |
| 59 | createElement: () => { | |
| 60 | const holder: any = { | |
| 61 | dataset: {}, | |
| 62 | remove() { | |
| 63 | holders.splice(holders.indexOf(holder), 1); | |
| 64 | }, | |
| 65 | querySelector: () => (holder.open ? {} : null), | |
| 66 | set innerHTML(_html: string) { | |
| 67 | sheets.set("sheet-7", { showPopover: () => opened.push("sheet-7") }); | |
| 68 | }, | |
| 69 | }; | |
| 70 | return holder; | |
| 71 | }, | |
| 72 | body: { append: (holder: any) => holders.push(holder) }, | |
| 73 | getElementById: (id: string) => sheets.get(id) ?? null, | |
| 74 | querySelectorAll: () => [...holders], | |
| 75 | }; | |
| 76 | (globalThis as any).fetch = async (url: string) => { | |
| 77 | fetched.push(url); | |
| 78 | return { ok: !failing, status: failing ? 500 : 200, text: async () => "<div popover id=sheet-7></div>" }; | |
| 79 | }; | |
| 80 | (globalThis as any).location = { href: "" }; | |
| 81 | await import("./../static/sheets.js"); | |
| 82 | const link = { href: "/deals/3#sheet-7", dataset: { sheet: "sheet-7", sheets: "/deals/3/sheets" } }; | |
| 83 | const tap = async () => { | |
| 84 | let prevented = false; | |
| 85 | await listeners.click!({ target: { closest: () => link }, defaultPrevented: false, preventDefault: () => (prevented = true) }); | |
| 86 | return prevented; | |
| 87 | }; | |
| 88 | ||
| 89 | expect(await tap()).toBe(true); | |
| 90 | expect(await tap()).toBe(true); | |
| 91 | expect(fetched).toEqual(["/deals/3/sheets"]); // once, however many taps | |
| 92 | expect(opened).toEqual(["sheet-7", "sheet-7"]); | |
| 93 | ||
| 94 | holders[0].open = true; // a sheet someone is reading survives a change | |
| 95 | listeners["live:deal.changed"]!({}); | |
| 96 | expect(holders).toHaveLength(1); | |
| 97 | holders[0].open = false; | |
| 98 | listeners["live:deal.changed"]!({}); | |
| 99 | expect(holders).toHaveLength(0); | |
| 100 | await tap(); | |
| 101 | expect(fetched).toHaveLength(2); // stale, so asked for again | |
| 102 | ||
| 103 | failing = true; | |
| 104 | listeners["live:deal.changed"]!({}); | |
| 105 | await tap(); | |
| 106 | expect((globalThis as any).location.href).toBe("/deals/3#sheet-7"); | |
| 107 | Object.assign(globalThis, real); | |
| 108 | }); |
src/speed.test.ts +14 −8
| @@ -116,12 +116,18 @@ test.each(routes)("%s answers in under 50 ms with 200 deals", async (_name, path | ||
| 116 | 116 | expect(await warm(path())).toBeLessThan(BUDGET_MS); |
| 117 | 117 | }); |
| 118 | 118 | |
| 119 | // The clock carries every deal's sheets inline, some 9 MB with 200 deals, and | |
| 120 | // after an edit that page is rebuilt, encoded and compressed whole. Cutting | |
| 121 | // that is a change to what the page shows, so its budget after an edit is | |
| 122 | // larger, and a regression past it still fails. | |
| 123 | const COLD_CLOCK_MS = 400; | |
| 124 | ||
| 125 | test.each(routes)("%s answers within budget the first time after a deal changes", async (name, path) => { | |
| 126 | expect(await cold(path())).toBeLessThan(name === "the clock" ? COLD_CLOCK_MS : BUDGET_MS); | |
| 119 | // The clock carries no sheets, so it is rebuilt small after an edit; a | |
| 120 | // deal's sheets are fetched when one is opened. | |
| 121 | test.each(routes)("%s answers within budget the first time after a deal changes", async (_name, path) => { | |
| 122 | expect(await cold(path())).toBeLessThan(BUDGET_MS); | |
| 123 | }); | |
| 124 | ||
| 125 | test("the clock does not carry sheets; a deal's sheets come on demand", async () => { | |
| 126 | const clock = await (await fetch(base + "/", { headers })).text(); | |
| 127 | expect(clock).not.toContain("popover id="); | |
| 128 | expect(clock).toContain(`data-sheets="/deals/${firstId}/sheets"`); | |
| 129 | const sheets = await fetch(`${base}/deals/${firstId}/sheets`, { headers }); | |
| 130 | expect(sheets.status).toBe(200); | |
| 131 | expect(await sheets.text()).toContain('popover id="sheet-'); | |
| 132 | expect((await fetch(`${base}/deals/999999/sheets`, { headers })).status).toBe(404); | |
| 127 | 133 | }); |
static/app.css +24
| @@ -867,6 +867,30 @@ a.week-row { | ||
| 867 | 867 | font-weight: 600; |
| 868 | 868 | } |
| 869 | 869 | |
| 870 | /* A date on the clock is a link to its sheet; the script opens the sheet in place. */ | |
| 871 | a.marker { | |
| 872 | color: inherit; | |
| 873 | text-decoration: none; | |
| 874 | } | |
| 875 | /* Without script a date's link lands here: the sheet it names shows in the page. */ | |
| 876 | .sheet:target:not(:popover-open) { | |
| 877 | display: block; | |
| 878 | position: static; | |
| 879 | margin: var() auto; | |
| 880 | } | |
| 881 | .draft-open { | |
| 882 | display: flex; | |
| 883 | flex: 1; | |
| 884 | flex-wrap: wrap; | |
| 885 | justify-content: space-between; | |
| 886 | align-items: center; | |
| 887 | gap: var() var(); | |
| 888 | min-height: var(); | |
| 889 | padding: var() 0; | |
| 890 | color: inherit; | |
| 891 | text-decoration: none; | |
| 892 | } | |
| 893 | ||
| 870 | 894 | /* On paper: only the client timeline changes — black on white, no tools, no row split. */ |
| 871 | 895 | @media print { |
| 872 | 896 | .timeline-page { |
static/sheets.js added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | // The clock carries no sheets: a date is a link to its deal page, and the | |
| 2 | // first tap fetches that deal's sheets and opens the one asked for. Without | |
| 3 | // this file the link goes to the deal page, which shows the sheet it names. | |
| 4 | ||
| 5 | const asked = new Map(); | |
| 6 | ||
| 7 | /** The deal's sheets, in the page; fetched once until something changes. */ | |
| 8 | function load(url) { | |
| 9 | if (!asked.has(url)) | |
| 10 | asked.set( | |
| 11 | url, | |
| 12 | fetch(url, { headers: { accept: "text/html" } }).then(async (response) => { | |
| 13 | if (!response.ok) throw new Error(String(response.status)); | |
| 14 | const holder = document.createElement("div"); | |
| 15 | holder.dataset.sheetsFrom = url; | |
| 16 | holder.innerHTML = await response.text(); | |
| 17 | document.body.append(holder); | |
| 18 | }), | |
| 19 | ); | |
| 20 | return asked.get(url); | |
| 21 | } | |
| 22 | ||
| 23 | document.addEventListener("click", async (event) => { | |
| 24 | const link = event.target.closest?.("a[data-sheet]"); | |
| 25 | if (!link || event.defaultPrevented || event.metaKey || event.ctrlKey) return; | |
| 26 | event.preventDefault(); | |
| 27 | try { | |
| 28 | await load(link.dataset.sheets); | |
| 29 | document.getElementById(link.dataset.sheet)?.showPopover(); | |
| 30 | } catch { | |
| 31 | asked.delete(link.dataset.sheets); | |
| 32 | location.href = link.href; | |
| 33 | } | |
| 34 | }); | |
| 35 | ||
| 36 | // A change makes what was fetched stale: drop the closed sheets, ask again next time. | |
| 37 | document.addEventListener("live:deal.changed", () => { | |
| 38 | for (const holder of document.querySelectorAll("[data-sheets-from]")) { | |
| 39 | if (holder.querySelector(":popover-open")) continue; | |
| 40 | asked.delete(holder.dataset.sheetsFrom); | |
| 41 | holder.remove(); | |
| 42 | } | |
| 43 | }); |
new above
offline