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

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/deal-clock:mason/54-the-clock-answers-in-under-50-ms-the-fir → main 3 commits fork

  • Merged. mason/54-the-clock-answers-in-under-50-ms-the-fir was merged into main as c84eebf.

Review

Sign in to review this change.
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
5050 for each party, grouped as three days before, the morning of, and an
5151 Overdue follow-up to the buyer, because the date passed without being marked
5252 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.
5456 3. **Read and edit a reminder.** In the sheet, tap a party's reminder. You
5557 see the words it would send, in a subject field and a message field,
5658 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
5961 "Reminder sent (simulated)." and the reminder now shows "Sent" with
6062 today's date and your edited words, not the original draft. Under the
6163 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.
6367 Decided against a message? Beside Send, **Don't send** asks why (up to 200
6468 characters). The reminder stops counting as "to send" and reads "Not sent:
6569 <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
3838 `decline_reminder` and `undo_decline_reminder`; in the terminal, `n` then the
3939 reason on the reminders list, and `u` to undo. Each is an update of the deal.
4040
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
4146 `GET /deals/:id/timeline` is a deal's printable client timeline: its dates in
4247 order, who owes each, and Done, Upcoming or Overdue in words, with no forms,
4348 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.
129134 | `src/server.ts` | boot: open the database, serve |
130135 | `src/tty.ts`, `src/terminal.ts` | the terminal: the pty, and the keys and screen over the same actions |
131136 | `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 |
133138
134139 ## What every app stands on
135140
src/cache.test.ts +8 −4
@@ -56,6 +56,7 @@ beforeAll(async () => {
5656 /** Every surface that shows the deal, read as `who`. */
5757 const surfaces = async (who: Record<string, string>) => ({
5858 clock: (await get("/", who)).body,
59 sheets: (await get(`/deals/${deal.id}/sheets`, who)).body,
5960 page: (await get(`/deals/${deal.id}`, who)).body,
6061 list: (await get("/api/deals", who)).body,
6162 });
@@ -67,14 +68,14 @@ test("a change shows on the next request of the clock, the deal page and the lis
6768
6869 expect((await post(`/deadlines/${closing.id}/move`, { due: "2027-04-20", reason: "Lender needs a week", to: "/" })).status).toBe(303);
6970 const moved = await surfaces(owner);
70 expect(moved.clock).toContain("Lender needs a week");
71 expect(moved.sheets).toContain("Lender needs a week");
7172 expect(moved.page).toContain("Lender needs a week");
7273 expect(moved.list).toContain("2027-04-20");
7374 expect(moved.list).not.toBe(before.list);
7475
7576 expect((await post("/deals/" + deal.id + "/parties", { role: "lender", name: "Lena Lender", contact: "[email protected]" })).status).toBe(303);
7677 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");
7879 expect(before.page).not.toContain("Lena Lender");
7980
8081 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
8283 expect(closed.list).not.toBe(added.list);
8384 expect(isClosed(closed.list)).toBe(true);
8485 expect(closed.clock).not.toBe(added.clock);
86 expect(closed.sheets).not.toBe(added.sheets);
8587 expect(closed.page).not.toBe(added.page);
8688
8789 expect((await post(`/deadlines/${closing.id}/done`, { done: "0", to: "/" })).status).toBe(303);
@@ -91,24 +93,26 @@ expect(isClosed(closed.list)).toBe(true);
9193 test("a stranger is never handed the clock or sheets drawn for a signed-in user, nor the reverse", async () => {
9294 // The owner asks first, so what is remembered was drawn for someone who may change the deal.
9395 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"`);
9597 expect(mine.page).toContain("[email protected]");
9698
9799 // The table lets any signed-in user change a deal, so another user is drawn the same controls.
98100 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"`);
100102 expect(theirs.page).toContain("[email protected]");
101103
102104 // A stranger sees the welcome, not a signed-in clock someone else rendered.
103105 const stranger = await get("/", anon);
104106 expect(stranger.body).not.toContain("Memo Mews");
105107 expect(stranger.body).not.toContain(`action="/deadlines/`);
108 expect((await get(`/deals/${deal.id}/sheets`, anon)).status).toBe(401);
106109 expect((await get(`/deals/${deal.id}`, anon)).body).not.toContain("[email protected]");
107110 expect((await get("/api/deals", anon)).status).toBe(401);
108111
109112 // Signed in as each of them again: what the stranger was shown left nothing behind.
110113 expect((await surfaces(admin)).page).toContain("[email protected]");
111114 expect((await surfaces(owner)).clock).toBe(mine.clock);
115 expect((await surfaces(owner)).sheets).toBe(mine.sheets);
112116 });
113117
114118 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 {
1717 return d.toISOString().slice(0, 10) === value;
1818 }
1919
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 };
2131 const fromMs = (ms: number): string => new Date(ms).toISOString().slice(0, 10);
2232
2333 /** `date` moved by `days` calendar days (negative goes back). */
src/pages/clock.ts +20 −15
@@ -1,7 +1,7 @@
11 /**
22 * The first screen: every deal as a lane, left to right by time, today as a
33 * 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
55 * clock, the reminders that go out today.
66 */
77
@@ -15,8 +15,7 @@ import type { Who } from "../who.ts";
1515 import { thisWeek } from "../week.ts";
1616 import { layout } from "./layout.ts";
1717 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";
2019 import { find } from "../find.ts";
2120 import { memoizer, print } from "../memo.ts";
2221
@@ -47,7 +46,13 @@ function rows(deal: DealView, start: string): { row: number; x: number; i: numbe
4746
4847 const at = (days: number): string => `calc(${days} * var(--size-day))`;
4948
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 {
5156 const placed = rows(deal, start);
5257 const height = Math.max(1, ...placed.map((p) => p.row + 1));
5358 const markers = placed
@@ -55,7 +60,7 @@ function lane(deal: DealView, start: string, on: string): string {
5560 const d = deal.deadlines[i]!;
5661 const u = urgency(d.due, on, d.done_at !== null);
5762 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>`;
5964 })
6065 .join("");
6166 return `<li class="lane">
@@ -84,6 +89,8 @@ export function axis(start: string, days: number, on: string): string {
8489 const dayHeading = (due: string, on: string): string =>
8590 due < on ? "Overdue" : due === on ? "Today" : spoken(due);
8691
92 const weekRows = memoizer<string>(3000);
93
8794 /** Open dates due within the week, under day headings; each row opens its sheet. */
8895 function weekCard(deals: readonly DealView[], on: string): string {
8996 const items = thisWeek(deals, on);
@@ -101,9 +108,9 @@ function weekCard(deals: readonly DealView[], on: string): string {
101108 .map(
102109 (g) => `<h3 class="week-day">${escape(g.heading)}</h3>
103110 <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 )
107114 .join("")}</ul>`,
108115 )
109116 .join("");
@@ -116,14 +123,13 @@ function weekCard(deals: readonly DealView[], on: string): string {
116123 const remembered = memoizer<{ count: number; toSend: number; html: string }>(400);
117124
118125 /** 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)}`, () => {
122128 const these = drafts(deal, agent).filter((r) => pending(r, on));
123129 return {
124130 count: these.length,
125131 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(""),
127133 };
128134 });
129135 }
@@ -163,7 +169,7 @@ function render(input: {
163169 const overdue = open.filter((d) => urgency(d.due, on, false) === "overdue").length;
164170 const soon = open.filter((d) => urgency(d.due, on, false) === "soon").length;
165171 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));
167173 const todayCount = today.reduce((n, t) => n + t.count, 0);
168174 const none = q !== "" && found.length === 0;
169175 const toSend = today.reduce((n, t) => n + t.toSend, 0);
@@ -181,8 +187,7 @@ function render(input: {
181187 <div class="axis" aria-hidden="true">${axis(start, days, on)}</div>
182188 <ol class="lanes">${deals.map((deal) => lane(deal, start, on)).join("")}</ol>
183189 </div>
184 </div>
185 ${deals.map((deal) => dealSheets(deal, who, on, "/")).join("")}`;
190 </div>`;
186191 const closedCard =
187192 closed.length === 0
188193 ? ""
src/pages/layout.ts +1 −1
@@ -64,7 +64,7 @@ export function layout(input: {
6464 <meta name="twitter:description" content="${escape(description)}">
6565 <link rel="stylesheet" href="${tokensHref}">
6666 <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>`}
6868 <body${bodyClass === undefined ? "" : ` class="${escape(bodyClass)}"`}>
6969 <div class="page">
7070 <header class="head">
src/pages/sheet.ts +27 −7
@@ -17,6 +17,15 @@ import { owner } from "../week.ts";
1717
1818 export const sheetId = (d: DeadlineView): string => `sheet-${d.id}`;
1919
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
2029 export const URGENCY_LABEL: Readonly<Record<Urgency, string>> = {
2130 done: "Done",
2231 overdue: "Overdue",
@@ -77,11 +86,8 @@ const undoForm = (draft: Draft, to: string): string =>
7786 <button class="button button-quiet">Undo: make it a draft again</button>
7887 </form>`;
7988
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 {
8591 const state =
8692 draft.sent_at !== null
8793 ? `<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
9298 : draft.on === on
9399 ? `<span class="state" data-today>Goes out today</span>`
94100 : `<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 {
96109 const inside =
97110 draft.sent_at !== null
98111 ? draftText(draft)
@@ -101,9 +114,16 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string, wi
101114 : may
102115 ? `${sendForm(draft, to)}${declineForm(draft, to)}`
103116 : 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>`;
105118 }
106119
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
107127 export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string): string {
108128 const id = sheetId(d);
109129 const may = canChange(who, deal);
src/routes.ts +11
@@ -64,6 +64,7 @@ import { book, calendar } from "./ics.ts";
6464 import { rpc } from "./mcp.ts";
6565 import { FIND_REFUSAL, find, query } from "./find.ts";
6666 import { clock } from "./pages/clock.ts";
67 import { dealSheets } from "./pages/sheet.ts";
6768 import { dealPage, newDealPage } from "./pages/deal.ts";
6869 import { refusedPage } from "./pages/refused.ts";
6970 import { people } from "./people.ts";
@@ -437,6 +438,16 @@ export const routes: readonly Route[] = [
437438 return html(dealPage({ who: c.who, deal: found.value, on: today(), notice }), 200, clear);
438439 },
439440 },
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 },
440451 {
441452 method: "GET",
442453 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 () => {
7777 expect(signed).toContain("<h1>The clock</h1>");
7878 expect(signed).toContain("/__forge/signout");
7979 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=");
8182 });
8283
8384 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
731732 const deal = deals[deals.length - 1]!;
732733 const deadline = deal.deadlines.find((x) => x.done_at === null && !deal.sent.some((s) => s.deadline_id === x.id))!;
733734 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();
735737 expect(before).toContain('name="subject" value="');
736738 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();
738740 expect(guest).not.toContain('name="subject"');
739741 const form = new FormData();
740742 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: "/" }))
741743 form.set(k, v);
742744 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();
744746 expect(after).toContain("Sent &lt;u&gt;words&lt;/u&gt;");
745747 expect(after).toContain("Sent &lt;script&gt;x&lt;/script&gt; body");
746748 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
953955 expect(week).toContain("Closing");
954956 expect(week).toContain("1418 Alder Lane");
955957 expect(week).toContain('data-live="deal.changed"');
956 expect(week).toContain("popovertarget=");
958 expect(week).toContain("data-sheet=");
957959 });
958960
959961 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
971973 const page = await (await api("/", {}, week)).text();
972974 return page.slice(page.indexOf('id="week"'), page.indexOf('id="today"'));
973975 };
974 expect(await card()).toContain(`popovertarget="sheet-${late.deadline.id}"`);
976 expect(await card()).toContain(`data-sheet="sheet-${late.deadline.id}"`);
975977 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}"`);
977979 });
978980
979981 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>();
101101 function gzipped(body: Uint8Array): Uint8Array {
102102 let zipped = compressed.get(body);
103103 if (zipped === undefined) {
104 zipped = Bun.gzipSync(body);
104 zipped = Bun.gzipSync(body, { level: 1 });
105105 compressed.set(body, zipped);
106106 }
107107 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
116116 expect(await warm(path())).toBeLessThan(BUDGET_MS);
117117 });
118118
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);
127133 });
static/app.css +24
@@ -867,6 +867,30 @@ a.week-row {
867867 font-weight: 600;
868868 }
869869
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(--space-4) 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(--space-1) var(--space-3);
888 min-height: var(--size-tap);
889 padding: var(--space-1) 0;
890 color: inherit;
891 text-decoration: none;
892 }
893
870894 /* On paper: only the client timeline changes — black on white, no tools, no row split. */
871895 @media print {
872896 .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 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs