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

Every POST form re-renders with its values kept and the failing field marked and named #16684

Merged opened this

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

Merged

scout/forge:scout/14024-every-post-form-re-renders-with-its-valu → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/14024-every-post-form-re-renders-with-its-valu was merged into main as 9d636b5.

Review

Sign in to review this change.
2 files changed +55 −15
src/web/pages/captain.ts +40 −15
@@ -15,7 +15,7 @@ import { costLine, dayCost } from "../../crew/captain_cost.ts";
1515 import type { Ctx } from "../../http/context.ts";
1616 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1717 import { forbiddenPage, notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts";
18 import { field, readForm } from "../form.ts";
18 import { field, kept, readForm, refused, type Refused } from "../form.ts";
1919 import { html, type Html } from "../html.ts";
2020 import { flashTo, page } from "../layout.ts";
2121 import { btn, field as uiField, row, rowList } from "../ui.ts";
@@ -23,6 +23,19 @@ import { accountSections } from "./origins.ts";
2323
2424 const BACK = "/settings/captain";
2525
26 /** The field each way a watch is refused is beside; the rest sit on the first. */
27 const WATCH_FIELD: Readonly<Record<keyof typeof WATCH_WORDS, string>> = {
28 not_owner: "brief",
29 bad_brief: "brief",
30 bad_kind: "kind",
31 bad_target: "target",
32 bad_done: "target",
33 bad_cap: "cap",
34 bad_every: "cap",
35 too_many: "brief",
36 from_watch: "brief",
37 };
38
2639 function requireOwner(ctx: Ctx): Response | undefined {
2740 if (!ctx.auth.user) return signInFirst(ctx);
2841 if (!ctx.auth.user.isAdmin || ctx.auth.user.kind !== "user") return notFoundPage(ctx);
@@ -31,7 +44,14 @@ function requireOwner(ctx: Ctx): Response | undefined {
3144
3245 const when = (iso: string | null): string => (iso === null ? "not yet" : iso.slice(0, 16).replace("T", " ") + " UTC");
3346
34 function view(ctx: Ctx, error?: string, status = 200): Response {
47 /** A refused post and which form on the page it came from, so only that form keeps its words. */
48 interface Refusal {
49 at: string;
50 refused: Refused;
51 }
52
53 function view(ctx: Ctx, error?: string, status = 200, refusal?: Refusal): Response {
54 const of = (at: string): Refused | undefined => (refusal?.at === at ? refusal.refused : undefined);
3555 const user = ctx.auth.user!;
3656 const memory = rulesOf(ctx.app.db, user.id);
3757 const routines = listRoutines(ctx.app.db, user.id);
@@ -46,13 +66,13 @@ function view(ctx: Ctx, error?: string, status = 200): Response {
4666 <ul class="list">${memory.map((m) => html`<li class="row">
4767 <form method="post" action="${BACK}" class="row-main">
4868 <input type="hidden" name="id" value="${m.id}">
49 ${uiField({ label: "Rule", name: "text", value: m.text, maxlength: MEMORY_TEXT_MAX, id: `m-${m.id}` })}
69 ${uiField(kept(of(`edit:${m.id}`), { label: "Rule", name: "text", value: m.text, maxlength: MEMORY_TEXT_MAX, id: `m-${m.id}` }))}
5070 <div class="form-actions">${btn("Save", { name: "do", value: "edit" })}${btn("Delete", { name: "do", value: "delete" })}</div>
5171 </form>
5272 </li>`)}</ul>
5373 <form method="post" action="${BACK}">
5474 <input type="hidden" name="do" value="add">
55 ${uiField({ label: "Remember", name: "text", maxlength: MEMORY_TEXT_MAX, placeholder: "Never merge on a Friday without asking.", id: "m-new" })}
75 ${uiField(kept(of("add"), { label: "Remember", name: "text", maxlength: MEMORY_TEXT_MAX, placeholder: "Never merge on a Friday without asking.", id: "m-new" }))}
5676 <div class="form-actions">${btn("Add", { variant: "primary" })}</div>
5777 </form>
5878 </section>
@@ -61,9 +81,9 @@ function view(ctx: Ctx, error?: string, status = 200): Response {
6181 <ul class="list">${routines.map((r) => html`<li class="row">
6282 <form method="post" action="${BACK}" class="row-main">
6383 <input type="hidden" name="kind" value="${r.kind}">
64 ${uiField({ label: ROUTINE_NAMES[r.kind], name: "enabled", type: "checkbox", value: "1", checked: r.enabled, id: `on-${r.kind}` })}
65 ${uiField({ label: "Every (minutes)", name: "every", type: "number", value: String(r.everyMin), min: EVERY_MIN, max: EVERY_MAX, id: `ev-${r.kind}` })}
66 ${uiField({ label: "Daily at hour (UTC)", name: "hour", type: "number", value: r.atHour === null ? "" : String(r.atHour), min: 0, max: 23, id: `hr-${r.kind}` })}
84 ${uiField(kept(of(`routine:${r.kind}`), { label: ROUTINE_NAMES[r.kind], name: "enabled", type: "checkbox", value: "1", checked: r.enabled, id: `on-${r.kind}` }))}
85 ${uiField(kept(of(`routine:${r.kind}`), { label: "Every (minutes)", name: "every", type: "number", value: String(r.everyMin), min: EVERY_MIN, max: EVERY_MAX, id: `ev-${r.kind}` }))}
86 ${uiField(kept(of(`routine:${r.kind}`), { label: "Daily at hour (UTC)", name: "hour", type: "number", value: r.atHour === null ? "" : String(r.atHour), min: 0, max: 23, id: `hr-${r.kind}` }))}
6787 <span class="muted small">Last posted: ${when(r.lastAt)}${r.conversationId === null ? "" : html` · <a href="/talk/${r.conversationId}">thread</a>`}</span>
6888 <div class="form-actions">${btn("Save", { variant: "primary", name: "do", value: "routine" })}${btn("Post now", { name: "do", value: "run" })}</div>
6989 </form>
@@ -88,11 +108,10 @@ function view(ctx: Ctx, error?: string, status = 200): Response {
88108 }))}
89109 <form method="post" action="${BACK}">
90110 <input type="hidden" name="do" value="watch_add">
91 ${uiField({ label: "Brief", name: "brief", maxlength: WATCH_BRIEF_MAX, placeholder: "Merge it once green and tell me.", id: "w-brief" })}
92 <label for="w-kind">Waits for</label>
93 <select name="kind" id="w-kind">${WATCH_KINDS.map((k) => html`<option value="${k}">${KIND_WORDS[k].says(`(${KIND_WORDS[k].target})`)}</option>`)}</select>
94 ${uiField({ label: "Target", name: "target", placeholder: "trevato/forge#16532", id: "w-target" })}
95 ${uiField({ label: "Spend cap ($)", name: "cap", type: "number", value: String(CAP_DEFAULT), min: 0.5, max: CAP_MAX, step: "0.5", id: "w-cap" })}
111 ${uiField(kept(of("watch_add"), { label: "Brief", name: "brief", maxlength: WATCH_BRIEF_MAX, placeholder: "Merge it once green and tell me.", id: "w-brief" }))}
112 ${uiField(kept(of("watch_add"), { label: "Waits for", name: "kind", type: "select", id: "w-kind", options: WATCH_KINDS.map((k) => ({ value: k, label: KIND_WORDS[k].says(`(${KIND_WORDS[k].target})`) })) }))}
113 ${uiField(kept(of("watch_add"), { label: "Target", name: "target", placeholder: "trevato/forge#16532", id: "w-target" }))}
114 ${uiField(kept(of("watch_add"), { label: "Spend cap ($)", name: "cap", type: "number", value: String(CAP_DEFAULT), min: 0.5, max: CAP_MAX, step: "0.5", id: "w-cap" }))}
96115 <div class="form-actions">${btn("Watch", { variant: "primary" })}</div>
97116 </form>
98117 </section>`;
@@ -128,7 +147,8 @@ export async function captainAct(ctx: Ctx): Promise<Response> {
128147 const db = ctx.app.db;
129148 if (what === "add" || what === "edit") {
130149 const saved = what === "add" ? addMemory(db, user.id, field(form, "text")) : editMemory(db, user.id, field(form, "id"), field(form, "text"));
131 return saved.ok ? flashTo(ctx, BACK, { message: what === "add" ? "Remembered." : "Saved." }) : view(ctx, MEMORY_WORDS[saved.error], 422);
150 if (saved.ok) return flashTo(ctx, BACK, { message: what === "add" ? "Remembered." : "Saved." });
151 return view(ctx, undefined, 422, { at: what === "add" ? "add" : `edit:${field(form, "id")}`, refused: refused(form, { text: MEMORY_WORDS[saved.error] }) });
132152 }
133153 if (what === "delete") {
134154 const gone = removeMemory(db, user.id, field(form, "id"));
@@ -136,7 +156,8 @@ export async function captainAct(ctx: Ctx): Promise<Response> {
136156 }
137157 if (what === "watch_add") {
138158 const made = createWatch(db, user, { brief: field(form, "brief"), kind: field(form, "kind"), target: field(form, "target"), capUsd: Number(field(form, "cap") || CAP_DEFAULT) });
139 return made.ok ? flashTo(ctx, BACK, { message: "Watching." }) : view(ctx, WATCH_WORDS[made.error], 422);
159 if (made.ok) return flashTo(ctx, BACK, { message: "Watching." });
160 return view(ctx, undefined, 422, { at: "watch_add", refused: refused(form, { [WATCH_FIELD[made.error]]: WATCH_WORDS[made.error] }) });
140161 }
141162 if (what === "watch_pause" || what === "watch_end" || what === "watch_delete") {
142163 const wid = field(form, "id");
@@ -156,7 +177,11 @@ export async function captainAct(ctx: Ctx): Promise<Response> {
156177 }
157178 const hour = field(form, "hour").trim();
158179 const saved = setRoutine(db, user.id, kind, { enabled: field(form, "enabled") === "1", everyMin: Number(field(form, "every")), atHour: hour === "" ? null : Number(hour) });
159 if (!saved.ok) return view(ctx, { not_a_routine: "That is not a routine.", bad_every: `Every must be ${EVERY_MIN} to ${EVERY_MAX} minutes.`, bad_hour: "The hour is 0 to 23." }[saved.error], 422);
180 if (!saved.ok) {
181 const words = { not_a_routine: "That is not a routine.", bad_every: `Every must be ${EVERY_MIN} to ${EVERY_MAX} minutes.`, bad_hour: "The hour is 0 to 23." };
182 const where = saved.error === "bad_hour" ? "hour" : "every";

A not_a_routine refusal gets pinned on every, a field the person did not get wrong. Send that one to the banner (view(ctx, words.not_a_routine, 422)) and keep the field mark for bad_every and bad_hour. This is principle 8, plain words, and non-blocking.

183 return view(ctx, undefined, 422, { at: `routine:${kind}`, refused: refused(form, { [where]: words[saved.error] }) });
184 }
160185 return flashTo(ctx, BACK, { message: `${ROUTINE_NAMES[saved.value.kind]} saved.` });
161186 }
162187 return view(ctx, "Nothing to do.", 422);
test/talk-captain.test.ts +15
@@ -236,6 +236,21 @@ describe("Settings › Captain", () => {
236236 expect((await post(other, { do: "add", text: "mine" })).status).toBe(403);
237237 });
238238
239 test("a refused form answers 422 with its words kept and the failing field named", async () => {
240 const text = async (res: Response) => (res.status === 422 ? await res.text() : `status ${res.status}`);
241 const watch = await text(await post(owner, { do: "watch_add", brief: "Tell me <b>when</b>", kind: "pull_landed", target: "nowhere/at-all#1", cap: "2" }));
242 expect(watch).toContain("Tell me &lt;b&gt;when&lt;/b&gt;");
243 expect(watch).toContain('id="w-target-err"');
244 expect(watch).toContain("That is not something you can read here");
245 const add = await text(await post(owner, { do: "add", text: "" }));
246 expect(add).toContain("Say what to remember.");
247 expect(add).toMatch(/id="m-new-err"/);
248 const every = await text(await post(owner, { do: "routine", kind: "checkin", enabled: "1", every: "3", hour: "7" }));
249 expect(every).toContain('value="3"');
250 expect(every).toContain('value="7"');
251 expect(every).toMatch(/id="ev-checkin-err"/);
252 });

The test covers three refusals. Add the edit-rule case, where the edit:<id> form keeps its text while the other rule keeps its stored text, plus bad_hour and the spend cap. These are non-blocking.

253
239254 test("a post from another origin changes nothing", async () => {
240255 const before = listMemory(app.db, owner.id).length;
241256 const res = await post(owner, { do: "add", text: "forged" }, "https://evil.example");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs