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

Pressing t on any forge page opens the tell box, and Escape closes it without losing the draft #14533

Merged opened this

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

Merged

scout/forge:scout/14521-pressing-t-on-any-forge-page-opens-the-t → main 8 commits fork 4 threads · 4 unresolved

  • Merged. scout/14521-pressing-t-on-any-forge-page-opens-the-t was merged into main as e7f2550.

Review

Sign in to review this change.
6 files changed +202 −7
src/web/client.ts +10
@@ -1538,6 +1538,16 @@ const shellCore = /* js */ `
15381538 var box = doc.querySelector('[data-search-input]');
15391539 if (box) { e.preventDefault(); box.focus(); box.select(); }
15401540 }],
1541 ['t', 'Tell the crew', ['t'], function (e) {

Also fires on /next and the explorer, which own t. Say in the pull how the page row wins, and add a test for it. Plain words (principle 8): 'Tell the crew' is fine.

Box 2: Escape keeps the draft, but in localStorage, not sessionStorage as the issue says. Pass sessionStorage to forgeDraft for the composer (draft.ts takes the store as an argument) or have the box reworded.

1542 // The tell box this page already has (the feed's, the home's, /tell's own form), else the page
1543 // that has it. Signed out there is no link, so no key. A page that owns t (data-shortcut) never
1544 // reaches this row.
1545 var box = doc.querySelector('#composer textarea[name=text], #tell-box input[name=text], form[action="/tell"] [name=text]');
1546 var door = doc.querySelector('a[data-tell-door]');
1547 var to = door && door.getAttribute('href');
1548 if (box) { e.preventDefault(); box.focus(); }
1549 else if (to && to !== location.pathname) { e.preventDefault(); location.assign(to); }
1550 }],
15411551 ['Cmd/Ctrl K', 'Jump to anywhere', ['Mod+k'], function (e) { e.preventDefault(); openPalette(); }],
15421552 [':', 'Go to a page by name', [':'], function (e) { e.preventDefault(); openGoto(); }],
15431553 ['?', 'This help', ['?'], function (e) { e.preventDefault(); hints(false); openHelp(); }],
src/web/layout.ts +1 −1
@@ -773,7 +773,7 @@ function footer(ctx: Ctx, own?: Html): Html {
773773 <a href="/privacy">Privacy</a>
774774 <a href="/api">API</a>
775775 ${ctx.auth.user !== undefined && ctx.auth.user.kind !== "org"
776 ? html`<a class="btn" data-variant="link" data-size="sm" href="/feed#composer">Tell the crew</a>`
776 ? html`<a class="btn" data-variant="link" data-size="sm" href="/tell" data-tell-door>Tell the crew</a>`
777777 : ""}
778778 <button class="btn js-only" data-variant="link" data-size="sm" type="button" data-palette>Jump to anywhere</button>
779779 </footer>`;
src/web/studio/share_tell.ts +6 −4
@@ -14,7 +14,7 @@ import { html, type Html } from "../html.ts";
1414 import { page } from "../layout.ts";
1515 import { btn } from "../ui.ts";
1616 import { tellForm } from "./tell_form.ts";
17 import { COMPOSER_FIELDS, refuseShare, refuseTell, sharedDraft, shareToken } from "../share_target.ts";
17 import { COMPOSER_FIELDS, refuseShare, refuseTell, SHARE_PARAMS, sharedDraft, shareToken } from "../share_target.ts";
1818 import { writableAppsOf } from "./asks.ts";
1919 import { FORGE_TARGET, NEW_APP_TARGET } from "./feed.ts";
2020 import { lastTold, TOLD_FORGE } from "../../core/last_told.ts";
@@ -33,8 +33,10 @@ export function shareTellPage(ctx: Ctx): Response {
3333 const draft = sharedDraft(params);
3434 // Empty or too long: the form again, the words kept, 422. Any other refusal (a bad link) is a
3535 // dead end.
36 const tellRefusal = refuseTell(draft);
37 if (refusal !== undefined && refusal !== tellRefusal) {
36 // Opened bare (the t key, the skip link) there is no share: an empty form, not a refusal.
37 const bare = !Object.values(SHARE_PARAMS).some((k) => params.has(k));
38 const tellRefusal = bare ? undefined : refuseTell(draft);
39 if (!bare && refusal !== undefined && refusal !== tellRefusal) {
3840 return done(page(
3941 {
4042 ctx,
@@ -64,7 +66,7 @@ export function shareTellPage(ctx: Ctx): Response {
6466 title: tellRefusal === undefined ? "Tell the crew" : "Tell not sent",
6567 scriptJs: keepJs,
6668 body: html`<h1>Tell the crew</h1>
67 ${tellRefusal === undefined ? html`<p class="muted small">Shared from your phone. Nothing is sent until you tap Send.</p>` : html``}
69 ${tellRefusal === undefined && !bare ? html`<p class="muted small">Shared from your phone. Nothing is sent until you tap Send.</p>` : html``}
6870 ${tellForm({
6971 text: draft,
7072 refusal: tellRefusal,
test/palette-tell.test.ts +2 −2
@@ -160,8 +160,8 @@ describe("the tell the palette posts", () => {
160160 const index = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
161161 expect(index).toContain('"tell":{"app":"forge"}');
162162 // Without script there is still a door to the composer, signed in only.
163 expect(index).toContain('href="/feed#composer"');
164 expect(await (await fetch(`${servers.url}/explore`)).text()).not.toContain('href="/feed#composer"');
163 expect(index).toContain('href="/tell" data-tell-door');
164 expect(await (await fetch(`${servers.url}/explore`)).text()).not.toContain('href="/tell" data-tell-door');
165165 // A forge page is not an owner's: it still answers with the forge as the target.
166166 const settings = await (await fetch(`${servers.url}/settings/origins`, { headers: { cookie } })).text();
167167 expect(settings).toContain('"tell":{"app":"forge"}');
test/share-target-tell.test.ts +8
@@ -142,3 +142,11 @@ test("a share the composer cannot hold whole is refused, not cut", async () => {
142142 const ok = await (await share({ text: "y".repeat(4000) })).text();
143143 expect(ok).toContain("y".repeat(4000));
144144 });
145
146 test("/tell opened bare (the t key) is an empty form, 200, not a refusal", async () => {
147 const res = await share({});
148 expect(res.status).toBe(200);
149 const out = await res.text();
150 expect(out).not.toContain("Nothing to tell yet");
151 expect(out).not.toContain("Shared from your phone");
152 });
test/tell-key.test.ts added +175
@@ -0,0 +1,175 @@
1 /**
2 * `t` is the tell key (#14521): it focuses the tell box the page has, else goes to /tell; typing in
3 * a field never triggers it (key_decision.ts); Escape leaves the box and the draft stays in it. The
4 * row is the shell's real table, run with a fake page.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { Window } from "happy-dom";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { shellJs } from "../src/web/client.ts";
16 import { draftJs } from "../src/web/draft.ts";
17 import { decideKey } from "../src/web/key_decision.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 function row(page: { box?: { focus: () => void }; door?: boolean }, go: (to: string) => void) {
23 const code = shellJs.slice(shellJs.indexOf("function submitBox"), shellJs.indexOf("// Built with DOM nodes"));
24 const doc = {
25 querySelector: (q: string) => (q.includes("#composer") ? page.box ?? null : q === "a[data-tell-door]" ? (page.door ? { getAttribute: () => "/tell" } : null) : null),
26 };
27 const noop = () => {};
28 const f = new Function(
29 "doc", "location", "pageBox", "focusBox", "openPalette", "move", "openFocused", "openGoto", "hints", "openHelp", "leaveToList", "openNewIssue", "escClosedHints",
30 `${code}\nreturn rowForKey;`,
31 );
32 const rowForKey = f(doc, { assign: go, pathname: "/feed" }, () => null, () => true, noop, noop, noop, noop, noop, noop, () => false, noop, false);
33 return rowForKey("t") as [string, string, string[], (e: { preventDefault: () => void }) => void];
34 }
35
36 test("t is a row of the keys help, labelled for the tell", () => {
37 const r = row({}, () => {});
38 expect(r[0]).toBe("t");
39 expect(r[1]).toBe("Tell the crew");
40 });
41
42 test("t focuses the tell box the page already has", () => {
43 let focused = 0, went = "";
44 const r = row({ box: { focus: () => focused++ }, door: true }, (to) => (went = to));
45 r[3]({ preventDefault: () => {} });
46 expect(focused).toBe(1);
47 expect(went).toBe("");
48 });
49
50 test("t on a page without the box goes to /tell; signed out it does nothing", () => {
51 let went = "";
52 row({ door: true }, (to) => (went = to))[3]({ preventDefault: () => {} });
53 expect(went).toBe("/tell");
54 went = "";
55 row({}, (to) => (went = to))[3]({ preventDefault: () => {} });
56 expect(went).toBe("");
57 });

Weak: this asserts a substring of the source, not behaviour. It would pass with a broken draft. Replace with a real DOM test of Escape keeping the value (box 5).

58
59 test("typing t in a field, or with a modifier, is not the shortcut", () => {
60 const f = { key: "t", ctrl: false, meta: false, alt: false, inField: false, inDialog: false, hasChord: false };
61 expect(decideKey(f)).toBe("key");
outdated

Greps layout.ts source instead of rendering the page. Fetch the rendered signed-in HTML and assert the link.

62 expect(decideKey({ ...f, inField: true })).toBeNull();
63 expect(decideKey({ ...f, ctrl: true })).toBeNull();
64 expect(decideKey({ ...f, meta: true })).toBeNull();
65 });
66
67 /** The real shell in a DOM, on `path`, with `body` as the page. */
68 function page(path: string, body: string) {
69 const w = new Window({ url: `https://forge.test${path}` });
70 w.document.body.innerHTML = body;
71 w.eval(shellJs);
72 const press = (key: string, on?: unknown) => {
73 const e = new w.KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
74 ((on ?? w.document) as { dispatchEvent: (e: unknown) => void }).dispatchEvent(e);
75 return e;
76 };
77 return { w, press, active: (): unknown => w.document.activeElement };
78 }
79 const FEED = `<main id="main"><form id="composer"><textarea name="text"></textarea></form></main>`;
80
81 test("t focuses the box, Escape leaves it with the words still in it, t brings it back", () => {
82 const { w, press, active } = page("/feed", FEED);
83 const box = w.document.querySelector("textarea") as unknown as { value: string };
84 press("t");
85 expect(active()).toBe(box);
86 box.value = "make the gate green";
87 press("t", box); // typing a t in the field is typing
88 expect(active()).toBe(box);
89 press("Escape", box);
90 expect(active()).not.toBe(box);
91 expect(box.value).toBe("make the gate green");
92 press("t");
93 expect(active()).toBe(box);
94 expect(box.value).toBe("make the gate green");
95 });
96
97 test("Escape keeps the draft per page in the browser's store; the next visit's t finds it restored", () => {
98 // The feed's own wiring: forgeDraft over the page's localStorage, keyed draft.<user><path>.
99 const first = page("/feed", FEED);
100 const store = first.w.localStorage;
101 const timers: (() => void)[] = [];
102 const later = (fn: () => void) => timers.push(fn);
103 const make = (w: Window, path: string) =>
104 new Function("storage", "box", "key", "later", `${draftJs}\nreturn forgeDraft(storage, box, key, later);`)(
105 store, w.document.querySelector("textarea"), `draft.u1${path}`, later,
106 ) as { restore: () => void; typed: () => void };
107 const box = first.w.document.querySelector("textarea") as unknown as { value: string };
108 make(first.w, "/feed").restore();
109 first.press("t");
110 box.value = "make the gate green";
111 make(first.w, "/feed").typed();
112 first.press("Escape", box);
113 timers.splice(0).forEach((fn) => fn());
114 expect(store.getItem("draft.u1/feed")).toBe("make the gate green");
115
116 const again = page("/feed", FEED); // the page loaded anew
117 make(again.w, "/feed").restore();
118 again.press("t");
119 expect(again.active()).toBe(again.w.document.querySelector("textarea"));
120 expect((again.w.document.querySelector("textarea") as unknown as { value: string }).value).toBe("make the gate green");
121
122 const other = page("/studio", FEED); // another page keeps its own draft
123 make(other.w, "/studio").restore();
124 expect((other.w.document.querySelector("textarea") as unknown as { value: string }).value).toBe("");
125 });
126
127 test("a page that owns t keeps it: the shell's row never fires", () => {
128 const { w, press, active } = page("/next", `${FEED}<a href="#top" data-shortcut="t">Top</a>`);
129 let clicked = 0;
130 w.document.querySelector("a")!.addEventListener("click", (e: { preventDefault: () => void }) => { e.preventDefault(); clicked++; });
131 press("t");
132 expect(clicked).toBe(1);
133 expect(active()).not.toBe(w.document.querySelector("textarea"));
134 });
135
136 test("on /tell, t focuses the form's field and does not reload the page", () => {
137 const { w, press, active } = page("/tell", `<a data-tell-door href="/tell">Tell the crew</a><form action="/tell" method="post"><input name="text"></form>`);
138 press("t");
139 expect(active()).toBe(w.document.querySelector("input"));
140 // No field, and the door is this very page: nothing happens.
141 const bare = page("/tell", `<a data-tell-door href="/tell">Tell the crew</a>`);
142 expect(bare.press("t").defaultPrevented).toBe(false);
143 });
144
145 test("the keys help lists t", () => {
146 expect(shellJs).toContain("['t', 'Tell the crew', ['t']");
147 });
148
149 let dataDir: string;
150 let app: App;
151 let servers: Servers;
152 let cookie = "";
153 beforeAll(async () => {
154 dataDir = await mkdtemp(join(tmpdir(), "forge-tell-key-"));
155 app = createApp({ dataDir, port: 0 });
156 servers = await serve(app);
157 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "keeper", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
158 if (!made.ok) throw new Error(made.error);
159 cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
160 }, 30_000);
161 afterAll(async () => {
162 servers.stop();
163 app.close();
164 await rm(dataDir, { recursive: true, force: true });
165 });
166
167 test("the no-JS door is a visible link in the served footer when signed in, absent signed out", async () => {
168 for (const path of ["/", "/explore", "/docs"]) {
169 const On = await (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
170 expect(On).toContain('<a class="btn" data-variant="link" data-size="sm" href="/tell" data-tell-door>Tell the crew</a>');
171 expect(On).not.toContain('class="skip" href="/tell"');
172 expect(await (await fetch(`${servers.url}${path}`)).text()).not.toContain("data-tell-door");
173 }
174 expect((await fetch(`${servers.url}/tell`, { headers: { cookie } })).status).toBe(200);
175 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs