Public: anyone can read this; the crew can change it.

A Find box on the clock narrows it to the deals whose address, client or party name matches what the agent types, and works without JavaScript #43

Merged opened this

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

Merged

mason/deal-clock:mason/38-a-find-box-on-the-clock-narrows-it-to-th → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/38-a-find-box-on-the-clock-narrows-it-to-th was merged into main as d71b956.

Review

Sign in to review this change.
10 files changed +249 −10
README.md +7
@@ -22,6 +22,13 @@ address, who owes it and how urgent it is; tap a row to open its sheet. It
2222 reads well on a phone, with no sideways scrolling. In the terminal, press w
2323 for the same list; over MCP, an agent asks for the `this_week` tool.
2424
25 To find a deal, type part of its address, or of a buyer's, seller's or other
26 party's name, phone or email, into **Find a deal** above the clock and press
27 Find (try `harbor`). The clock, This week and today's reminders narrow to the
28 deals that match, with no JavaScript needed; **Clear** brings them all back.
29 In the terminal, press / and type the same, then enter; the dates, week and
30 reminders views narrow to it, and / then enter alone clears it.
31
2532 Signed out, `/` shows what deal-clock does, three short points, a still picture of the clock drawn from a made-up deal, and one **Sign in** button; no real deal is read.
2633
2734 1. **Look at the clock.** You see four lanes: 77 Harbor View Dr, Unit 4B
docs/design/areas/find.md added +5
@@ -0,0 +1,5 @@
1 # Find
2
3 New class on the clock:
4
5 - `.find` — the Find a deal form above the clock: a label, one search field, a Find button and, once something is typed, a Clear link.
src/find.test.ts added +39
@@ -0,0 +1,39 @@
1 import { expect, test } from "bun:test";
2 import type { DealView } from "./deals.ts";
3 import { find, query } from "./find.ts";
4
5 const deal = (id: number, address: string, parties: [string, string][]): DealView =>
6 ({
7 id,
8 address,
9 parties: parties.map(([name, contact], i) => ({ id: i, deal_id: id, role: "buyer", name, contact })),
10 }) as unknown as DealView;
11
12 const deals = [
13 deal(1, "77 Harbor View Dr", [["Maya Chen", "[email protected]"]]),
14 deal(2, "9 Elm Street", [["Omar Reyes", "555-0142"]]),
15 ];
16 const ids = (q: string) => find(deals, q).map((d) => d.id);
17
18 test("finds by address, party name and contact, ignoring case and padding", () => {
19 expect(ids("harbor")).toEqual([1]);
20 expect(ids(" ELM ")).toEqual([2]);
21 expect(ids("chen")).toEqual([1]);
22 expect(ids("MAYA@EXAMPLE")).toEqual([1]);
23 expect(ids("0142")).toEqual([2]);
24 });
25
26 test("an empty query keeps every deal; no match keeps none", () => {
27 expect(ids("")).toEqual([1, 2]);
28 expect(ids(" ")).toEqual([1, 2]);
29 expect(ids("zzz")).toEqual([]);
30 });
31
32 test("query trims, and refuses long text and control characters", () => {
33 expect(query(null)).toBe("");
34 expect(query(" elm ")).toBe("elm");
35 expect(query("a".repeat(100))).toHaveLength(100);
36 expect(query("a".repeat(101))).toBeUndefined();
37 expect(query("a\u0000b")).toBeUndefined();
38 expect(query("a\nb")).toBeUndefined();
39 });
src/find.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * Finding a deal: which deals match what the agent typed. Plain deals in,
3 * plain deals out; the clock narrows itself with it.
4 */
5
6 import type { DealView } from "./deals.ts";
7
8 export const FIND_MAX = 100;
9
10 /** The text a deal is found by: address, every party (buyer and seller included)'s name and contact. */
11 const haystack = (deal: DealView): string =>
12 [deal.address, ...deal.parties.flatMap((p) => [p.name, p.contact])]
13 .join("\n")
14 .toLowerCase();
15
16 /** `q` as a query: trimmed, within bounds, no control characters — or undefined. */
17 export function query(value: string | null): string | undefined {
18 if (value === null) return "";
19 const q = value.trim();
20 if (q.length > FIND_MAX || /[\p{Cc}]/u.test(q)) return undefined;
21 return q;
22 }
23
24 /** The deals that contain `q`, case-insensitively; an empty `q` keeps them all. */
25 export function find(deals: readonly DealView[], q: string): DealView[] {
26 const needle = q.trim().toLowerCase();
27 return needle === "" ? [...deals] : deals.filter((deal) => haystack(deal).includes(needle));
28 }
src/pages/clock.ts +19 −5
@@ -17,6 +17,7 @@ import { layout } from "./layout.ts";
1717 import { mayRestore } from "../actions.ts";
1818 import { badge, draftItem, owedBy, sheet, sheetId, URGENCY_LABEL } from "./sheet.ts";
1919 import { canChange } from "../deals.ts";
20 import { find } from "../find.ts";
2021
2122 /** The days the clock shows: a week behind today (further, if something open is older), to a few days past the last closing. */
2223 export function span(deals: readonly DealView[], on: string): { start: string; days: number } {
@@ -116,10 +117,13 @@ export function clock(input: {
116117 deals: readonly DealView[];
117118 on: string;
118119 notice?: string | undefined;
120 q?: string | undefined;
119121 }): string {
120122 const { who, on, notice } = input;
121 const deals = input.deals.filter((deal) => !deal.closed);
122 const closed = input.deals
123 const q = input.q ?? "";
124 const found = find(input.deals, q);
125 const deals = found.filter((deal) => !deal.closed);
126 const closed = found
123127 .filter((deal) => deal.closed)
124128 .sort((a, b) => b.closing.localeCompare(a.closing) || b.id - a.id);
125129 const open = deals.flatMap((deal) => deal.deadlines.filter((d) => d.done_at === null));
@@ -131,10 +135,15 @@ export function clock(input: {
131135 .filter((r) => pending(r, on))
132136 .map((r) => ({ r, may: canChange(who, deal) })),
133137 );
138 const none = q !== "" && found.length === 0;
134139 const toSend = today.filter(({ r }) => unsent(r)).length;
140 const nothing =
141 q !== ""
outdated

This is a nested ternary with a new branch, and its indentation does not match the existing chain. Compute the no-match message in its own const, or reorder the chain so the new case reads cleanly.

142 ? `<p class="empty">No deal matches “${escape(q)}”. <a href="/">Clear</a></p>`
143 : `<p class="empty">No deals yet. <a href="/deals/new">Open the first one</a>.</p>`;
135144 const timeline =
136145 deals.length === 0 && closed.length === 0
137 ? `<p class="empty">No deals yet. <a href="/deals/new">Open the first one</a>.</p>`
146 ? nothing
138147 : deals.length === 0
139148 ? `<p class="empty">Every deal is closed.</p>`
140149 : `<div class="clock-scroll" tabindex="0" role="region" aria-label="Timeline of every deal's dates">
@@ -170,6 +179,11 @@ export function clock(input: {
170179 </div>
171180 ${who.role === "anon" ? "" : `<a class="button" href="/deals/new">New deal</a>`}
172181 </section>
182 <form class="find" method="get" action="/" role="search">
183 <label for="find-q">Find a deal</label>
184 <input id="find-q" class="input" type="search" name="q" value="${escape(q)}" maxlength="100" placeholder="Address, client or party" autocomplete="off">
185 <button class="button button-quiet">Find</button>${q === "" ? "" : ` <a href="/">Clear</a>`}
186 </form>
173187 <section id="clock" class="card clock" data-live="deal.changed">
174188 ${timeline}
175189 <ul class="legend" aria-label="Legend">
@@ -182,7 +196,7 @@ export function clock(input: {
182196 ${closedCard}
183197 ${restoreCard}
184198 ${deals.length === 0 ? "" : weekCard(deals, on)}
185 <section id="today" class="card" data-live="deal.changed">
199 ${none ? "" : `<section id="today" class="card" data-live="deal.changed">
186200 <h2>Reminders for today <span class="muted">· ${toSend === 0 ? "all sent" : `${toSend} to send`}</span></h2>
187201 ${
188202 today.length === 0
@@ -190,6 +204,6 @@ export function clock(input: {
190204 : `<ul class="drafts">${today.map(({ r, may }) => draftItem(r, on, may, "/", true)).join("")}</ul>`
191205 }
192206 <p class="muted small">Each date reminds its parties three days before and the morning of, and the one who owes a date is asked for an update the morning after it slips. Sending is simulated: the draft is shown and marked sent.</p>
193 </section>`;
207 </section>`}`;
194208 return layout({ body, who, path: "/", notice });
195209 }
src/routes.ts +15 −1
@@ -59,6 +59,7 @@ import {
5959 } from "./deals.ts";
6060 import { calendar } from "./ics.ts";
6161 import { rpc } from "./mcp.ts";
62 import { FIND_MAX, query } from "./find.ts";
6263 import { clock } from "./pages/clock.ts";
6364 import { dealPage, newDealPage } from "./pages/deal.ts";
6465 import { refusedPage } from "./pages/refused.ts";
@@ -328,7 +329,20 @@ export const routes: readonly Route[] = [
328329 200,
329330 clear,
330331 );
331 return html(clock({ who: c.who, deals: deals.value, on: today(), notice }), 200, clear);
332 const q = query(c.url.searchParams.get("q"));
333 if (q === undefined)
334 return html(
335 refusedPage({
336 who: c.who,
337 path: "/",
338 heading: "The clock",
339 error: "invalid",
340 message: `Find takes up to ${FIND_MAX} characters, with no control characters.`,
341 }),
342 400,
343 clear,
344 );
345 return html(clock({ who: c.who, deals: deals.value, on: today(), notice, q }), 200, clear);
332346 },
333347 },
334348 {
src/server.test.ts +58
@@ -925,3 +925,61 @@ test("This week over MCP lists the same dates, for a signed-in account only; a d
925925 await call("mark_done", { id: late.deadline.id }, week);
926926 expect(await card()).not.toContain(`popovertarget="sheet-${late.deadline.id}"`);
927927 });
928
929 test("the clock's Find box narrows the clock, echoes escaped, and refuses bad input", async () => {
930 const get = (q: string) => fetch(base + "/?q=" + encodeURIComponent(q), { headers: alice });
931 const all = await (await get("")).text();
932 expect(all).toContain('<form class="find" method="get"');
933 expect(all).toContain("Find a deal");
934 const harbor = await (await get("harbor view")).text();
935 expect(harbor).toContain("77 Harbor View Dr");
936 expect(harbor.match(/class="lane"/g)).toHaveLength(1);
937 expect(harbor).toContain('value="harbor view"');
938 const none = await (await get('zz"><i>')).text();
939 expect(none).toContain("No deal matches “zz&quot;&gt;&lt;i&gt;”");
940 expect(none).toContain('<a href="/">Clear</a>');
941 expect(none).not.toContain("<i>");
942 const long = await get("a".repeat(101));
943 expect(long.status).toBe(400);
944 const refused = await long.text();
945 expect(refused).toContain("Find takes up to 100 characters");
946 expect(refused).not.toContain("Error");
947 expect((await get("a\u0001")).status).toBe(400);
948 });
949
950 test("a Find narrows This week, today's reminders and the Closed card, and a miss hides the reminders", async () => {
951 // Its own account: the write allowance is shared by every test file in one run.
952 const finder = as("u-find", "fiona");
953 const call = (name: string, args: unknown) =>
954 rpc({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name, arguments: args } }, finder);
955 const created = await api("/api/deals", { method: "POST", ...jsonBody({ ...NEW_DEAL, address: "3 Finder Row" }) }, finder);
956 expect(created.status).toBe(201);
957 const made = await created.json();
958 const closing = made.deadlines.find((d: any) => d.kind === "closing");
959 expect((await call("mark_done", { id: closing.id })).result.isError).toBeFalsy();
960 const section = (page: string, id: string) => {
961 const from = page.indexOf(`id="${id}"`);
962 return from < 0 ? "" : page.slice(from, page.indexOf("</section>", from));
963 };
964 const get = async (q: string) => (await api("/?q=" + encodeURIComponent(q), {}, finder)).text();
965
966 const everything = await get("");
967 expect(section(everything, "week")).toContain("1418 Alder Lane");
968 expect(section(everything, "today")).toContain("Alder");
969 expect(section(everything, "closed")).toContain("3 Finder Row");
970
971 const harbor = await get("harbor");
972 expect(section(harbor, "week")).toContain("77 Harbor View Dr");
973 expect(section(harbor, "week")).not.toContain("1418 Alder Lane");
974 expect(section(harbor, "today")).not.toContain("Alder");
975 expect(section(harbor, "closed")).toBe("");
976
977 const finder_ = await get("finder row");
978 expect(section(finder_, "closed")).toContain("3 Finder Row");
979 expect(section(finder_, "week")).toBe("");
980
981 const miss = await get("nobody");
982 expect(miss).toContain("No deal matches “nobody”");
983 expect(section(miss, "today")).toBe("");
984 expect(section(miss, "week")).toBe("");
985 });
src/terminal.test.ts +43
@@ -389,3 +389,46 @@ test("R then yes puts the sample deals back, leaving a person's deal alone", ()
389389 expect(harbor().deadlines.every((d) => d.done_at === null)).toBe(true);
390390 expect(getDeal(db, alice, { id }).ok).toBe(true);
391391 });
392
393 test("/ finds a deal and narrows dates, week and reminders to it; / then enter clears it", () => {
394 const other = createDeal(db, alice, {
395 address: "9 Oak Ln",
396 buyer: "Zed Zimmer",
397 seller: "Yan Yates",
398 contractDate: today(),
399 closingDate: addDays(today(), 45),
400 });
401 if (!other.ok) throw new Error(other.message);
402 for (const dealId of [id, other.value.id]) {
403 const added = addDeadline(db, alice, { dealId, label: "Find check", due: addDays(today(), 1), owes: "buyer" });
404 if (!added.ok) throw new Error(added.message);
405 }
406 const t = terminal(db, alice, context);
407 const shown = (key: string) => {
408 t.press(key);
409 return lines(t).join("\n");
410 };
411 expect(shown("d")).toContain("Find check — 9 Oak Ln");
412 press(t, "/", "zimmer\r");
413 const dates = lines(t).join("\n");
414 expect(dates).toContain("Finding “zimmer”");
415 expect(dates).toContain("Find check — 9 Oak Ln");
416 expect(dates).not.toContain("12 Elm St");
417 const week = shown("w");
418 expect(week).toContain("Find check — 9 Oak Ln");
419 expect(week).not.toContain("12 Elm St");
420 const reminders = shown("r");
421 expect(reminders).toContain("9 Oak Ln");
422 expect(reminders).not.toContain("12 Elm St");
423 // No match says so; typing stops at 100 characters.
424 press(t, "/", "nobody here\r");
425 expect(lines(t).join("\n")).toContain("No deal matches “nobody here”");
426 press(t, "/", "a".repeat(150), "\r");
427 expect(lines(t).join("\n")).toContain(`Finding “${"a".repeat(100)}” —`);
428 press(t, "/", "\r");
429 expect(lines(t).join("\n")).toContain("Showing every deal.");
430 const all = shown("d");
431 expect(all).toContain("12 Elm St");
432 expect(all).toContain("9 Oak Ln");
433 expect(all).not.toContain("Finding");
434 });
src/terminal.ts +24 −4
@@ -12,7 +12,8 @@
1212 * On a date (dates or deal view): x marks it done, u reopens it, m moves it
1313 * (a new date, then the reason). o or enter opens its deal; n opens a new
1414 * deal (address, buyer, seller, contract and closing dates); d, r and b move
15 * between views; esc cancels a prompt; q leaves.
15 * between views; esc cancels a prompt; q leaves. / finds a deal by address or
16 * party and narrows dates, week and reminders to it; / then enter clears it.
1617 */
1718
1819 import type { Database } from "bun:sqlite";
@@ -44,6 +45,7 @@ import {
4445 type DealView,
4546 type DeadlineView,
4647 } from "./deals.ts";
48 import { find, FIND_MAX, query } from "./find.ts";
4749 import { mayRestore, restoreSamples } from "./actions.ts";
4850 import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
4951 import { drafts, MOMENT_LABEL, pending, unsent, type Agent, type Draft } from "./reminders.ts";
@@ -94,11 +96,13 @@ export function terminal(
9496 const edits = new Map<string, { subject: string; body: string }>();
9597 let prompt: Prompt | undefined;
9698 let said = "";
99 /** What `/` narrowed the deals to; empty is all of them. */
100 let found = "";
97101 let done = false;
98102
99103 const deals = (): DealView[] => {
100104 const listed = listDeals(db, me);
101 return listed.ok ? listed.value : [];
105 return listed.ok ? find(listed.value, found) : [];
102106 };
103107 const openDeal = (): DealView | undefined => {
104108 if (dealId === undefined) return undefined;
@@ -362,6 +366,20 @@ export function terminal(
362366 view = "reminders";
363367 cursor = 0;
364368 reading = undefined;
369 } else if (key === "/" && (view === "dates" || view === "week" || view === "reminders")) {
370 prompt = {
371 steps: [`Find a deal (address, client or party; enter alone clears${found === "" ? "" : `; now “${found}”`})`],
372 answers: [],
373 text: "",
374 max: FIND_MAX,
375 finish: ([text]) => {
376 const q = query(text ?? "");
377 if (q === undefined) return `Find takes up to ${FIND_MAX} characters, with no control characters.`;
378 found = q;
379 cursor = 0;
380 return q === "" ? "Showing every deal." : deals().length === 0 ? `No deal matches “${q}”. / then enter clears it.` : `Showing deals that match “${q}”.`;
381 },
382 };
365383 } else if (key === "R" && (view === "dates" || view === "week")) {
366384 const may = mayRestore(me);
367385 if (!may.ok) said = may.message;
@@ -425,6 +443,8 @@ export function terminal(
425443 `${spoken(day)} · ${all.length} deals · ${view === "dates" ? bold("[d] dates") : "[d] dates"} · ${view === "week" ? bold("[w] this week") : "[w] this week"} · ${view === "reminders" ? bold("[r] reminders today") : "[r] reminders today"}`,
426444 "",
427445 ];
446 if (found !== "" && (view === "dates" || view === "week" || view === "reminders"))
447 lines.splice(3, 0, dim(`Finding “${found}” — / changes it, / then enter clears it`));
428448 if (view === "dates") {
429449 const rows = dateRows();
430450 const listed = listDeals(db, me);
@@ -505,14 +525,14 @@ export function terminal(
505525 if (said !== "") lines.push(...said.split("\n"));
506526 const keys =
507527 view === "reminders"
508 ? "j/k move · enter read · e edit · s send · n don't send · u undo · d dates · q quit"
528 ? "j/k move · enter read · e edit · s send · n don't send · u undo · / find · d dates · q quit"
509529 : view === "messages"
510530 ? "j/k move · enter read · b back to the deal · d dates · q quit"
511531 : view === "timeline"
512532 ? "b back to the deal · d dates · q quit"
513533 : view === "deal"
514534 ? "j/k move · t client timeline · s messages · x done · u reopen · m move · a add date · p add party · e edit party · X remove date/party · D remove deal · b back · q quit"
515 : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · q quit`;
535 : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · q quit`;
516536 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
517537 }
518538 return lines;
static/app.css +11
@@ -842,6 +842,17 @@ textarea.input {
842842 margin-bottom: var(--space-2);
843843 }
844844
845 .find {
outdated

The .find rule was inserted between the comment "On paper: only the client timeline changes..." and its @media print block. That leaves the comment describing the wrong rule. Move .find above that comment.

846 display: flex;
847 flex-wrap: wrap;
848 align-items: center;
849 gap: var(--space-2);
850 margin-bottom: var(--space-4);
851 }
852 .find label {
853 font-weight: 600;
854 }
855
845856 /* On paper: only the client timeline changes — black on white, no tools, no row split. */
846857 @media print {
847858 .timeline-page {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs