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

Comment forms (issues, pulls) keep the typed text and name the failing field on refusal #14006

Merged opened this

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

Merged

scout/forge:scout/14004-comment-forms-issues-pulls-keep-the-type → main 8 commits fork 3 threads · 3 unresolved

  • Merged. scout/14004-comment-forms-issues-pulls-keep-the-type was merged into main as 4765a95.

Review

Sign in to review this change.
8 files changed +260 −23
docs/features/README.md +1
@@ -36,6 +36,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
3636 - [Feed fold](feed-fold.md)
3737 - [Filter the feed by one app](feed-app-filter.md)
3838 - [Questions on an issue](question.md)
39 - [A refused comment keeps its words](comment-refused.md)
3940 - [A feed post has a permalink](feed-permalink.md)
4041 - [A run post opens its log](feed-run-log.md)
4142 - [Feed likes: the ledger](feed-like-ledger.md)
docs/features/comment-refused.md added +10
@@ -0,0 +1,10 @@
1 # A refused comment keeps its words
2
3 On an issue or a pull page, a comment that is refused (blank, or not posted) draws the page again with status 422:
4 what you typed stays in the box, "Ask as a question" stays ticked, and the message sits on the field.
5 Refusals from the origin, from the feed and from review lines still return by flash.
6
7 In the terminal nothing changes and nothing is lost: when a comment is not posted, `src/tui/screens/issue.ts`
8 toasts the reason and leaves the composer open with its text.
9
10 Try it: open an issue, post a blank comment, see the box kept and marked.
src/web/form.ts +21
@@ -91,6 +91,27 @@ export function refused(form: Form, errors: Record<string, string>): Refused {
9191 return { form, errors };
9292 }
9393
94 /**
95 * A refusal a page draws in place: a POST handler that has no page of its own
96 * stashes it against the request, then calls the GET page, whose form reads it
97 * back with `refusedHere`. Keyed by the request, so nothing outlives it.
98 */
99 const here = new WeakMap<Request, Refused>();
100
101 export function refuseHere(ctx: Ctx, r: Refused): void {
102 here.set(ctx.request, r);
103 }
104
105 export function refusedHere(ctx: Ctx): Refused | undefined {
106 return here.get(ctx.request);
107 }
108
109 /** A page drawn after a refusal answers 422, its body untouched. */
110 export async function asRefusal(page: Response | Promise<Response>): Promise<Response> {
111 const res = await page;
112 return res.status === 200 ? new Response(res.body, { status: 422, headers: res.headers }) : res;
113 }
114
94115 /** Fields whose value is never sent back to the browser. */
95116 const SECRET_NAME = /^(.*[_-])?(pass(word)?|secret|token|credential|api_?key|otp|pin)$/i;
96117 /** The camelCase spelling of the same words: `newPassword`, `apiKey`. */
src/web/pages/issues.ts +19 −5
@@ -31,10 +31,11 @@ import {
3131 signInFirst,
3232 signInHref,
3333 } from "../chrome.ts";
34 import { field, readForm } from "../form.ts";
34 import { asRefusal, field, readForm, refused, refuseHere } from "../form.ts";
3535 import { html, raw, type Html } from "../html.ts";
3636 import { flashTo, page, redirect } from "../layout.ts";
3737 import { flashKeeping } from "../flash.ts";
38 import { tellPage } from "../studio/tell.ts";
3839 import { cleanFrom, repoOfPath, withFromLine } from "../issue_from.ts";
3940 import { btn, empty, field as formField, listCard, row } from "../ui.ts";
4041 import {
@@ -364,11 +365,22 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
364365 const dest = `${repoBase(found.repo)}/issues/${found.issue.number}`;
365366 const refusedTo = back?.refusedTo ?? dest;
366367 const body = field(form, "body");
368 // From the thread's own page the refusal is drawn in place: the words typed
369 // stay in the box and the message sits beside it. A reply from the feed or
370 // the board has no such box here, so it goes back with its flash. The issue
371 // page is drawn by `tellPage`: it is the one renderer of an issue thread.
outdated

inPlace is back?.refusedTo === undefined and every use also tests back === undefined, so the variable is redundant and confusing. Use one condition, e.g. const inPlace = back === undefined. Also issue pages are drawn with tellPage from studio/tell.ts; name why, or use the issue page's own renderer.

372 const inPlace = back === undefined;
373 const refuse = (why: string): Promise<Response> => {
374 refuseHere(ctx, refused(form, { body: why }));
375 return asRefusal(tellPage(ctx));
376 };
367377 if (body.trim() === "")
368 return flashTo(ctx, refusedTo, {
369 tone: "danger",
370 message: COMMENT_EMPTY,
371 });
378 return inPlace
379 ? refuse(COMMENT_EMPTY)
380 : flashTo(ctx, refusedTo, {
381 tone: "danger",
382 message: COMMENT_EMPTY,
383 });
372384 const added = await addCommentThrough(
373385 ctx.app,
374386 ctx.auth.user,
@@ -376,6 +388,8 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
376388 found.issue,
377389 body,
378390 );
391 if (!added.ok && inPlace && !originError(added.error))
392 return refuse(COMMENT_NOT_POSTED);
379393 if (!added.ok)
380394 return flashTo(
381395 ctx,
src/web/pages/pull.ts +14 −6
@@ -93,7 +93,7 @@ import {
9393 type DiffViewOptions,
9494 type ThreadView,
9595 } from "../diff-view.ts";
96 import { field, readForm } from "../form.ts";
96 import { asRefusal, field, readForm, refused, refuseHere } from "../form.ts";
9797 import { teamHoldRefusal, waitingOnTeams } from "../../core/teams_words.ts";
9898 import { teamsHolding, teamVerdicts, type TeamVerdict } from "../../core/issue_teams.ts";
9999 import { html, raw, when, type Html } from "../html.ts";
@@ -135,6 +135,7 @@ import {
135135 changeHead,
136136 changeTabs,
137137 pullContext,
138 pullPage,
138139 wallCard,
139140 } from "../studio/change.ts";
140141
@@ -1258,11 +1259,16 @@ export async function pullCommentSubmit(ctx: Ctx): Promise<Response> {
12581259 // A reply from the feed returns there: a fixed word, never a URL from the form.
12591260 const fromFeed = field(form, "back") === "feed";
12601261 const bodyText = field(form, "body");
1262 // From the pull's own page the refusal is drawn in place, the typed words
1263 // kept and the message beside the box; from the feed it returns by flash.
1264 const refuse = (why: string): Promise<Response> => {
1265 refuseHere(ctx, refused(form, { body: why }));
1266 return asRefusal(pullPage(ctx));
1267 };
12611268 if (bodyText.trim() === "")
1262 return flashTo(ctx, fromFeed ? "/feed" : dest, {
1263 tone: "danger",
1264 message: COMMENT_EMPTY,
1265 });
1269 return fromFeed
1270 ? flashTo(ctx, "/feed", { tone: "danger", message: COMMENT_EMPTY })
1271 : refuse(COMMENT_EMPTY);
12661272 const added = await addCommentThrough(
12671273 ctx.app,
12681274 ctx.auth.user,
@@ -1270,8 +1276,10 @@ export async function pullCommentSubmit(ctx: Ctx): Promise<Response> {
12701276 found.pull,
12711277 bodyText,
12721278 );
1279 if (!added.ok && !fromFeed && !originError(added.error))
1280 return refuse(COMMENT_NOT_POSTED);
12731281 if (!added.ok)
1274 return flashTo(ctx, fromFeed ? "/feed" : dest, {
1282 return flashTo(ctx, "/feed", {
12751283 tone: "danger",
12761284 message: originError(added.error) ?? COMMENT_NOT_POSTED,
12771285 });
src/web/pages/thread.ts +27 −10
@@ -63,7 +63,7 @@ import {
6363 } from "../../core/users.ts";
6464 import type { Ctx } from "../../http/context.ts";
6565 import { commentCard } from "../comments.ts";
66 import { backTo, field, readForm } from "../form.ts";
66 import { backTo, field, kept, readForm, refusedHere } from "../form.ts";
6767 import { html, raw, when, type Html } from "../html.ts";
6868 import { planCard } from "./plan_card.ts";
6969 import { NOT_CHANGED } from "../edit_words.ts";
@@ -71,6 +71,7 @@ import { flashOrJson, flashTo } from "../layout.ts";
7171 import {
7272 btn,
7373 card,
74 field as formField,
7475 icon,
7576 labelChip,
7677 time,
@@ -621,6 +622,11 @@ export interface ComposerOptions {
621622 question?: boolean;
622623 }
623624
625 /** Whether a refused submit had "Ask as a question" ticked, so the box comes back ticked. */
626 function questionKept(ctx: Ctx): boolean {
627 return refusedHere(ctx)?.form.get("question") === "open";
628 }
629
624630 /** The comment box. Close and reopen are their own form, not an `intent`
625631 * rider on this one — one endpoint, one verb.
626632 *
@@ -696,18 +702,29 @@ export function composer(ctx: Ctx, o: ComposerOptions): Html {
696702 data-box="${tell ? "Tell the crew" : "Write a comment"}"
697703 data-submit-key
698704 >
699 <label class="sr-only" for="comment-body"
700 >${tell ? "Tell the crew" : "Comment"}</label
701 >
705 ${tell
706 ? html`<label class="sr-only" for="comment-body">Tell the crew</label>
702707 <textarea
703708 class="input"
704709 id="comment-body"
705 name="${tell ? "text" : "body"}"
706 rows="${String(tell ? (tell.rows ?? 4) : 4)}"
707 ${tell ? raw('maxlength="2000"') : raw("data-grow")}
708 placeholder="${tell ? "Tell the crew what should change" : "Leave a comment"}"
710 name="text"
711 rows="${String(tell.rows ?? 4)}"
outdated

Principle 3 / accessibility: the old textarea carried data-grow (auto-grow); kept(...) drops it. Restore it through the field, otherwise every comment box on a 360px phone becomes a fixed 4-row scroller. Also the tell branch now duplicates the textarea markup; keep one textarea and vary only the attributes.

712 maxlength="2000"
713 placeholder="Tell the crew what should change"
709714 required
710 >${tell?.text ?? ""}</textarea>
715 >${tell.text ?? ""}</textarea>`
716 : formField(
717 kept(refusedHere(ctx), {
718 label: "Comment",
719 labelHidden: true,
720 name: "body",
721 id: "comment-body",
722 type: "textarea",
723 rows: 4,
724 placeholder: "Leave a comment",
725 required: true,
726 }),
727 )}
711728 ${tell?.from
712729 ? html`<input type="hidden" name="from" value="${tell.from}" />`
713730 : null}
@@ -738,7 +755,7 @@ export function composer(ctx: Ctx, o: ComposerOptions): Html {
738755 <span class="spacer"></span>
739756 ${o.question && !tell
740757 ? html`<label class="muted small"
741 ><input type="checkbox" name="question" value="open" /> Ask as a question</label
758 ><input type="checkbox" name="question" value="open" ${questionKept(ctx) ? raw("checked") : null} /> Ask as a question</label
742759 >`
743760 : null}
744761 ${reasons} ${closeButton}
test/comment-forms-refused.test.ts added +165
@@ -0,0 +1,165 @@
1 /**

Add cases for: question checkbox stays checked after refusal; a non-empty body that fails to post (COMMENT_NOT_POSTED) draws in place; origin refusal still 303s with the flash; the feed back=feed reply still flashes. The 65,600-char test depends on an unstated limit; import the constant instead.

2 * A refused comment on an issue or a pull draws the thread page again, 422:
3 * the typed words stay in the box (escaped) and the message sits on that field.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createIssue, MAX_BODY } from "../src/core/issues.ts";
13 import { createOrigin, linkRepoToOrigin } from "../src/core/origins.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { COMMENT_EMPTY, COMMENT_NOT_POSTED } from "../src/actions/comment_words.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 let dataDir: string;
23 let app: App;
24 let servers: Servers;
25 let token = "";
26 let pullNumber = 0;
27 let issueNumber = 0;
28 let bobToken = "";
29 let mirrorIssue = 0;
30
31 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
32 if (!r.ok) throw new Error(JSON.stringify(r.error));
33 return r.value;
34 };
35
36 const post = (path: string, fields: Record<string, string>, as = token, repo = "sq") =>
37 fetch(`${servers.url}/alice/${repo}/${path}/comments`, {
38 method: "POST",
39 redirect: "manual",
40 headers: { authorization: `Bearer ${as}`, "content-type": "application/x-www-form-urlencoded" },
41 body: new URLSearchParams(fields),
42 });
43
44 beforeAll(async () => {
45 dataDir = await mkdtemp(join(tmpdir(), "forge-comment-refused-"));
46 app = createApp({ dataDir, port: 0 });
47 servers = await serve(app);
48 const alice = ok(
49 await createUser(app.db, {
50 origin: "seed",
51 trusted: true,
52 username: "alice",
53 email: "[email protected]",
54 password: "a-good-passphrase",
55 adminIfFirst: true,
56 }),
57 );
58 const repo = ok(await createRepo(app, alice, { name: "sq", visibility: "public" }));
59 ok(await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# sq\n" }] }));
60 ok(
61 await commitToBranch(app, alice, repo, {
62 branch: "topic",
63 base: "main",
64 message: "Topic",
65 files: [{ path: "README.md", content: "# sq\nmore\n" }],
66 }),
67 );
68 pullNumber = ok(await openPull(app, alice, repo, { title: "Topic", body: "", baseBranch: "main", headBranch: "topic" })).number;
69 issueNumber = ok(createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: "A bug", body: "" })).number;
70 token = createToken(app.db, alice.id, "rw", "rw").token;
71 const bob = ok(
72 await createUser(app.db, {
73 origin: "seed",
74 trusted: true,
75 username: "bob",
76 email: "[email protected]",
77 password: "a-good-passphrase",
78 }),
79 );
80 bobToken = createToken(app.db, bob.id, "rw", "rw").token;
81 const mirror = ok(await createRepo(app, alice, { name: "mir", visibility: "public" }));
82 mirrorIssue = ok(createIssue(app.db, { repoId: mirror.id, authorId: alice.id, title: "Up there", body: "" })).number;
83 const origin = createOrigin(app.db, dataDir, {
84 userId: alice.id,
85 kind: "github",
86 apiUrl: "https://api.github.invalid",
87 webUrl: "https://github.invalid",
88 login: "alice",
89 token: "not-a-real-token",
90 });
91 if (!origin.ok) throw new Error(origin.error);
92 linkRepoToOrigin(app.db, mirror.id, {
93 originId: origin.value.id,
94 fullName: "alice/mir",
95 remoteId: "2",
96 htmlUrl: "https://github.invalid/alice/mir",
97 });
98 });
99
100 afterAll(async () => {
101 await servers.stop();
102 app.db.close();
103 await rm(dataDir, { recursive: true, force: true });
104 });
105
106 for (const kind of ["issues", "pulls"] as const) {
107 test(`${kind}: a blank comment is refused in place, the field marked`, async () => {
108 const res = await post(`${kind}/${kind === "issues" ? issueNumber : pullNumber}`, { body: " " });
109 expect(res.status).toBe(422);
110 const page = await res.text();
111 expect(page).toContain('id="comment-body"');
112 expect(page).toContain('aria-invalid="true"');
113 expect(page).toContain(COMMENT_EMPTY);
114 });
115 }
116
117 for (const kind of ["issues", "pulls"] as const) {
118 test(`${kind}: a refused comment keeps what was typed, escaped`, async () => {
119 const typed = `<script>alert(1)</script> ${"x".repeat(MAX_BODY + 1)}`;
120 const res = await post(`${kind}/${kind === "issues" ? issueNumber : pullNumber}`, { body: typed });
121 expect(res.status).toBe(422);
122 const page = await res.text();
123 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt; xxxx");
124 expect(page).not.toContain("<script>alert(1)");
125 expect(page).toContain('aria-invalid="true"');
126 });
127 }
128
129 test("the comment box still grows with its text", async () => {
130 const page = await (await post(`issues/${issueNumber}`, { body: " " })).text();
131 expect(page).toMatch(/<textarea[^>]*id="comment-body"[^>]*data-grow/);
132 });
133
134 test("a refused question comment comes back with the checkbox still ticked", async () => {
135 const res = await post(`issues/${issueNumber}`, { body: "x".repeat(MAX_BODY + 1), question: "open" });
136 expect(res.status).toBe(422);
137 expect(await res.text()).toMatch(/name="question" value="open"\s+checked/);
138 const plain = await (await post(`issues/${issueNumber}`, { body: " " })).text();
139 expect(plain).toMatch(/name="question" value="open"/);
140 expect(plain).not.toMatch(/name="question" value="open"\s+checked/);
141 });
142
143 for (const kind of ["issues", "pulls"] as const) {
144 test(`${kind}: a comment that fails to post is drawn in place with its words`, async () => {
145 const res = await post(`${kind}/${kind === "issues" ? issueNumber : pullNumber}`, { body: "y".repeat(MAX_BODY + 1) });
146 expect(res.status).toBe(422);
147 expect(await res.text()).toContain(COMMENT_NOT_POSTED);
148 });
149 }
150
151 test("an origin refusal still redirects with its flash, not an in-place page", async () => {
152 const res = await post(`issues/${mirrorIssue}`, { body: "hello" }, bobToken, "mir");
153 expect(res.status).toBe(303);
154 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe(`/alice/mir/issues/${mirrorIssue}`);
155 expect(decodeURIComponent(res.headers.getSetCookie().join(";"))).toContain("Only the person who connected this origin");
156 });
157
158 for (const kind of ["issues", "pulls"] as const) {
159 test(`${kind}: a blank reply from the feed still redirects to /feed with a flash`, async () => {
160 const res = await post(`${kind}/${kind === "issues" ? issueNumber : pullNumber}`, { body: " ", back: "feed" });
161 expect(res.status).toBe(303);
162 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
163 expect(decodeURIComponent(res.headers.getSetCookie().join(";"))).toContain(COMMENT_EMPTY);
164 });
165 }
test/feed-reply.test.ts +3 −2
@@ -212,9 +212,10 @@ test("an empty reply on an issue returns to the feed with a danger flash", async
212212 expect(flashOf(res).tone).toBe("danger");
213213 });
214214
215 test("an empty comment from the issue page stays on it", async () => {
215 test("an empty comment from the issue page is drawn again in place, the field marked", async () => {
216216 const res = await post(`/alice/open/issues/${publicIssue}/comments`, aliceCookie, { body: " " });
217 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe(`/alice/open/issues/${publicIssue}`);
217 expect(res.status).toBe(422);
218 expect(await res.text()).toContain('aria-invalid="true"');
218219 });
219220
220221 test("a signed-out visitor to the feed sees no Reply form", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs