pi-better-show 0.4.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,353 @@
1
+ import { isMap, isScalar, isSeq, LineCounter, type Node, parseDocument, type Scalar } from "yaml";
2
+ import { locate } from "./parse.ts";
3
+ import type { BlockKind } from "./types.ts";
4
+
5
+ /**
6
+ * Finds what is wrong with the blocks of a Markdown file, so the agent that wrote it can fix them: a block that does
7
+ * not parse (the page shows its source), and the slips that parse without an error and lose data (a value cut at a
8
+ * ` #`, a key no block reads). Each problem carries the line of the Markdown file.
9
+ */
10
+
11
+ export interface BlockProblem {
12
+ kind: BlockKind;
13
+ /** 1-based line of the Markdown file. */
14
+ line: number;
15
+ /** Where in the block, as the author reads it: `form question "o5" choice 1 label`. */
16
+ path: string;
17
+ message: string;
18
+ /** `error`: the block cannot be drawn. `warning`: it is drawn, but part of what was written is lost. */
19
+ severity: "error" | "warning";
20
+ }
21
+
22
+ export interface CheckOptions {
23
+ /** Checks a Mermaid source and returns what is wrong with it; core carries no Mermaid parser, a host passes one. */
24
+ mermaid?: (source: string) => string | undefined;
25
+ }
26
+
27
+ interface Shape {
28
+ /** The keys the block reads at this level. */
29
+ keys?: readonly string[];
30
+ /** Keys that hold a list of items, with the shape of an item. */
31
+ lists?: Record<string, ListShape>;
32
+ /** Keys that hold a mapping. */
33
+ maps?: Record<string, Shape>;
34
+ /** The list a document that is a bare YAML list stands for. */
35
+ bare?: string;
36
+ }
37
+ interface ListShape {
38
+ noun: string;
39
+ item?: Shape;
40
+ /** Item keys that name an item, first found wins. */
41
+ names?: readonly string[];
42
+ }
43
+
44
+ const items = (noun: string, keys: readonly string[], names?: readonly string[]): ListShape => ({
45
+ noun,
46
+ item: { keys },
47
+ ...(names ? { names } : {}),
48
+ });
49
+
50
+ /** What each YAML kind reads, level by level; it mirrors the converters in blocks.ts and blocks-new.ts. */
51
+ const SHAPES: Record<string, Shape> = {
52
+ cards: { keys: ["cards"], bare: "cards", lists: { cards: items("card", ["title", "tone", "body"]) } },
53
+ options: {
54
+ keys: ["options"],
55
+ bare: "options",
56
+ lists: { options: items("option", ["title", "recommended", "body", "pros", "cons"]) },
57
+ },
58
+ form: {
59
+ keys: ["title", "submit", "questions"],
60
+ bare: "questions",
61
+ lists: {
62
+ questions: {
63
+ noun: "question",
64
+ names: ["name", "label"],
65
+ item: {
66
+ keys: ["name", "label", "type", "hint", "required", "other", "choices"],
67
+ lists: { choices: items("choice", ["value", "label", "note", "recommended"]) },
68
+ },
69
+ },
70
+ },
71
+ },
72
+ review: {
73
+ keys: ["title", "submit", "pick", "columns", "items"],
74
+ bare: "items",
75
+ lists: { items: items("item", ["name", "label", "image", "page", "height", "body"], ["name", "label"]) },
76
+ },
77
+ suggest: { keys: ["items"], bare: "items", lists: { items: items("suggestion", ["label", "text"]) } },
78
+ checklist: {
79
+ keys: ["title", "submit", "items"],
80
+ bare: "items",
81
+ lists: { items: items("item", ["name", "label", "checked", "note"], ["name", "label"]) },
82
+ },
83
+ table: {
84
+ keys: ["columns", "rows", "sort", "filter"],
85
+ lists: { columns: items("column", ["name", "label", "type", "align"], ["name", "label"]), rows: { noun: "row" } },
86
+ maps: { sort: { keys: ["column", "by", "direction", "dir"] } },
87
+ },
88
+ steps: { keys: ["items"], bare: "items", lists: { items: items("step", ["title", "status", "when", "body"]) } },
89
+ stats: {
90
+ keys: ["items"],
91
+ bare: "items",
92
+ lists: { items: items("stat", ["label", "value", "delta", "tone", "note"]) },
93
+ },
94
+ };
95
+
96
+ /** Keys whose value is an enum, flag or number: a ` #` after one is a plain comment, not lost text. */
97
+ const NON_TEXT_KEYS = new Set([
98
+ "status",
99
+ "type",
100
+ "align",
101
+ "direction",
102
+ "dir",
103
+ "checked",
104
+ "required",
105
+ "filter",
106
+ "height",
107
+ "columns",
108
+ "tone",
109
+ ]);
110
+
111
+ const QUOTE_HINT = 'quote any value that holds " #" or ": " (and commas inside {…})';
112
+
113
+ const short = (text: string, max = 40): string => (text.length > max ? `${text.slice(0, max)}…` : text);
114
+
115
+ /** Edit distance, to offer the known key a misspelling was probably meant for. */
116
+ function distance(a: string, b: string): number {
117
+ let row = Array.from({ length: b.length + 1 }, (_, index) => index);
118
+ for (let i = 1; i <= a.length; i++) {
119
+ const next = [i];
120
+ for (let j = 1; j <= b.length; j++) {
121
+ next[j] = Math.min(
122
+ (next[j - 1] as number) + 1,
123
+ (row[j] as number) + 1,
124
+ (row[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1),
125
+ );
126
+ }
127
+ row = next;
128
+ }
129
+ return row[b.length] as number;
130
+ }
131
+
132
+ const nearest = (key: string, known: readonly string[]): string | undefined => {
133
+ const lower = key.toLowerCase();
134
+ return known.find((name) => name.toLowerCase() === lower || distance(lower, name.toLowerCase()) <= 2);
135
+ };
136
+
137
+ const quoteYaml = (text: string): string => `'${text.replace(/'/g, "''")}'`;
138
+
139
+ interface Context {
140
+ kind: BlockKind;
141
+ /** The file line of the block's opening fence: a source line n is file line `fence + n`. */
142
+ fence: number;
143
+ source: string;
144
+ lines: LineCounter;
145
+ out: BlockProblem[];
146
+ }
147
+
148
+ const lineOf = (context: Context, offset: number): number => context.fence + context.lines.linePos(offset).line;
149
+
150
+ function report(context: Context, offset: number, path: string, message: string): void {
151
+ context.out.push({ kind: context.kind, line: lineOf(context, offset), path, message, severity: "warning" });
152
+ }
153
+
154
+ /** A plain value that a ` #` on its line cut short: YAML reads the rest as a comment, so that text is lost. */
155
+ function checkComment(context: Context, node: Scalar, path: string): void {
156
+ if (node.type !== "PLAIN" || node.comment === undefined || node.comment === null || !node.range) return;
157
+ const [start, end] = node.range;
158
+ const rest = context.source.slice(
159
+ end,
160
+ context.source.indexOf("\n", end) < 0 ? undefined : context.source.indexOf("\n", end),
161
+ );
162
+ if (!/^[ \t]*#/.test(rest)) return;
163
+ const kept = context.source.slice(start, end);
164
+ const whole = `${kept}${rest}`.trimEnd();
165
+ const read = kept === "" ? "no value" : `the value ${JSON.stringify(kept)}`;
166
+ report(
167
+ context,
168
+ end,
169
+ path,
170
+ `a plain value ends at " #": ${JSON.stringify(rest.trim())} is read as a YAML comment and dropped, leaving ${read}; if it is text, quote the whole value: ${quoteYaml(whole)}`,
171
+ );
172
+ }
173
+
174
+ function checkKeys(context: Context, node: Node, shape: Shape | undefined, owner: string): void {
175
+ if (!isMap(node)) return;
176
+ for (const pair of node.items) {
177
+ const key = isScalar(pair.key) ? String(pair.key.value) : undefined;
178
+ const keyAt = isScalar(pair.key) && pair.key.range ? pair.key.range[0] : (node.range?.[0] ?? 0);
179
+ if (key !== undefined && shape?.keys && !shape.keys.includes(key)) {
180
+ const near = nearest(key, shape.keys);
181
+ report(
182
+ context,
183
+ keyAt,
184
+ owner,
185
+ `unknown key ${JSON.stringify(key)} is ignored${near ? ` (did you mean ${JSON.stringify(near)}?)` : ""}; this level reads: ${shape.keys.join(", ")}`,
186
+ );
187
+ }
188
+ walk(context, pair.value as Node | null, key === undefined ? undefined : shape, owner, key);
189
+ }
190
+ }
191
+
192
+ function itemName(item: Node | unknown, names: readonly string[] | undefined): string | undefined {
193
+ if (!isMap(item) || !names) return undefined;
194
+ for (const name of names) {
195
+ const found = item.items.find((pair) => isScalar(pair.key) && pair.key.value === name);
196
+ if (found && isScalar(found.value) && found.value.value !== null && found.value.value !== "")
197
+ return short(String(found.value.value), 30);
198
+ }
199
+ return undefined;
200
+ }
201
+
202
+ /** Walks a value, checking keys against `shape` (the owner's) and plain values for a cut-off comment. */
203
+ function walk(context: Context, node: Node | null, shape: Shape | undefined, owner: string, key: string | undefined) {
204
+ const path = key === undefined ? owner : `${owner} ${key}`;
205
+ const list = key === undefined ? undefined : shape?.lists?.[key];
206
+ if (isSeq(node)) {
207
+ for (const [index, item] of node.items.entries()) {
208
+ const name = itemName(item, list?.names);
209
+ const here = list
210
+ ? `${owner} ${list.noun} ${name === undefined ? index + 1 : JSON.stringify(name)}`
211
+ : `${path} ${index + 1}`;
212
+ walk(context, item as Node | null, list?.item, here, undefined);
213
+ }
214
+ } else if (isMap(node)) {
215
+ checkKeys(context, node, key === undefined ? shape : shape?.maps?.[key], path);
216
+ } else if (isScalar(node)) {
217
+ if (key !== undefined && NON_TEXT_KEYS.has(key)) return;
218
+ checkComment(context, node, path);
219
+ }
220
+ }
221
+
222
+ /** The YAML kinds, whose body is parsed as a document. */
223
+ const isYamlKind = (kind: BlockKind): boolean => kind in SHAPES;
224
+
225
+ function checkBody(context: Context): void {
226
+ const doc = parseDocument(context.source, { lineCounter: context.lines });
227
+ if (doc.errors.length > 0) return;
228
+ const shape = SHAPES[context.kind] as Shape;
229
+ const root = doc.contents;
230
+ const name = context.kind;
231
+ if (isSeq(root)) {
232
+ if (shape.bare === undefined) return;
233
+ const list = shape.lists?.[shape.bare];
234
+ for (const [index, item] of root.items.entries()) {
235
+ const label = itemName(item, list?.names);
236
+ const here = `${name} ${list?.noun ?? "item"} ${label === undefined ? index + 1 : JSON.stringify(label)}`;
237
+ walk(context, item as Node | null, list?.item, here, undefined);
238
+ }
239
+ } else if (isMap(root)) {
240
+ checkKeys(context, root, shape, name);
241
+ }
242
+ }
243
+
244
+ /** An invalid YAML block: YAML's own error points past a broken flow collection, so look back for the line that opened it. */
245
+ function yamlError(context: Context, error: string): { line: number; message: string; hint: string } | undefined {
246
+ const doc = parseDocument(context.source, { lineCounter: new LineCounter() });
247
+ const first = doc.errors[0];
248
+ if (!first) return undefined;
249
+ const lines = context.source.split("\n");
250
+ let at = first.linePos?.[0].line ?? 1;
251
+ const message = first.message
252
+ .split("\n")[0]
253
+ ?.replace(/ at line \d+, column \d+:?$/, "")
254
+ .replace(/:$/, "");
255
+ if (first.message.startsWith("Flow ")) {
256
+ const hit = (text: string): boolean => /[{[][^}\]]*\s#/.test(text);
257
+ for (let n = at; n >= Math.max(1, at - 50); n--) {
258
+ if (hit(lines[n - 1] ?? "")) {
259
+ at = n;
260
+ return { line: at, message: message ?? error, hint: QUOTE_HINT };
261
+ }
262
+ }
263
+ at = Math.max(1, at - 1);
264
+ return { line: at, message: message ?? error, hint: QUOTE_HINT };
265
+ }
266
+ const hint =
267
+ first.code === "MISSING_CHAR" ? "close the quote" : 'check the indentation, and quote text holding ": " or " #"';
268
+ return { line: at, message: message ?? error, hint };
269
+ }
270
+
271
+ /** A tree or mindmap error that names its source line. */
272
+ function sourceLine(context: Context, error: string): number | undefined {
273
+ const numbered = /^line (\d+): /.exec(error);
274
+ if (numbered) return Number(numbered[1]);
275
+ const listed = /^not a list item: (.*)$/.exec(error);
276
+ if (listed) {
277
+ const at = context.source.split("\n").findIndex((line) => line.trim() === (listed[1] as string));
278
+ return at < 0 ? undefined : at + 1;
279
+ }
280
+ return undefined;
281
+ }
282
+
283
+ /**
284
+ * The problems of every block in `markdown`, in document order. `error` problems are blocks that cannot be drawn
285
+ * (the page shows their source); `warning` problems are blocks that draw but lose part of what was written: a plain
286
+ * value cut at ` #`, a key the block does not read, a fence that never closes, a diagram `options.mermaid` refuses.
287
+ */
288
+ export function checkBlocks(markdown: string, options: CheckOptions = {}): BlockProblem[] {
289
+ const out: BlockProblem[] = [];
290
+ for (const { segment, line, closed, source } of locate(markdown)) {
291
+ if (segment.type === "markdown") continue;
292
+ const kind = segment.kind;
293
+ const context: Context = { kind, fence: line, source, lines: new LineCounter(), out };
294
+ if (segment.type === "invalid") {
295
+ let at = line;
296
+ let message = segment.error;
297
+ let hint = "";
298
+ if (isYamlKind(kind)) {
299
+ const found = yamlError(context, segment.error);
300
+ if (found) {
301
+ at = line + found.line;
302
+ message = found.message;
303
+ hint = found.hint;
304
+ }
305
+ } else {
306
+ const inner = sourceLine(context, segment.error);
307
+ if (inner !== undefined) {
308
+ at = line + inner;
309
+ message = segment.error.replace(/^line \d+: /, "");
310
+ }
311
+ }
312
+ out.push({
313
+ kind,
314
+ line: at,
315
+ path: kind,
316
+ message: `the ${kind} block is invalid and is shown as source: ${message}${hint ? `; ${hint}` : ""}`,
317
+ severity: "error",
318
+ });
319
+ } else if (isYamlKind(kind)) {
320
+ checkBody(context);
321
+ } else if (kind === "mermaid" && options.mermaid) {
322
+ const problem = options.mermaid(source);
323
+ if (problem !== undefined) {
324
+ out.push({
325
+ kind,
326
+ line: line + 1,
327
+ path: kind,
328
+ message: `the diagram will not draw: ${problem}`,
329
+ severity: "error",
330
+ });
331
+ }
332
+ }
333
+ if (!closed) {
334
+ out.push({
335
+ kind,
336
+ line,
337
+ path: kind,
338
+ message: `the ${kind} fence is never closed, so the block runs to the end of the file; add a closing fence`,
339
+ severity: "warning",
340
+ });
341
+ }
342
+ }
343
+ return out.sort((a, b) => a.line - b.line);
344
+ }
345
+
346
+ /** The problems as the lines an agent reads: `Block problems in notes.md:` then one `- line N path: message` each. */
347
+ export function formatProblems(name: string, problems: readonly BlockProblem[]): string {
348
+ const lines = problems.map(
349
+ (problem) =>
350
+ `- line ${problem.line} ${problem.path}${problem.severity === "warning" ? " (warning)" : ""}: ${problem.message}`,
351
+ );
352
+ return [`Block problems in ${name}:`, ...lines].join("\n");
353
+ }
package/src/core/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { encodeAnswer } from "./answer.ts";
2
- export { reviewItemName } from "./blocks.ts";
2
+ export { NOTE_FIELD, reviewItemName } from "./blocks.ts";
3
+ export { type BlockProblem, type CheckOptions, checkBlocks, formatProblems } from "./check.ts";
3
4
  export { inline, inlinePlain } from "./inline.ts";
4
5
  export { parse } from "./parse.ts";
5
6
  export { toText } from "./text.ts";
package/src/core/parse.ts CHANGED
@@ -96,21 +96,40 @@ function trimBlankEdges(lines: string[]): string {
96
96
  return lines.slice(start, end).join("\n");
97
97
  }
98
98
 
99
+ /** A segment with the 1-based line of the document where it starts (a block's opening fence); `closed` is false for a fence that never closes. */
100
+ export interface Located {
101
+ segment: Segment;
102
+ line: number;
103
+ closed: boolean;
104
+ /** A fenced block's text between its fences, as converted; empty for prose and alerts. */
105
+ source: string;
106
+ }
107
+
99
108
  /**
100
109
  * Splits a document into its prose and its blocks, in order. A block is a fenced code block whose first
101
110
  * word names a block kind (`form`, `table`, ...), or a GitHub alert; other code, and prose, stay Markdown.
102
111
  * A block whose body does not fit its schema becomes an `invalid` segment that keeps its source and the reason.
103
112
  */
104
113
  export function parse(markdown: string): Segment[] {
114
+ return locate(markdown).map((located) => located.segment);
115
+ }
116
+
117
+ /** `parse` with where each segment starts; `checkBlocks` reports problems by these lines. */
118
+ export function locate(markdown: string): Located[] {
105
119
  const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
106
- const segments: Segment[] = [];
120
+ const segments: Located[] = [];
107
121
  let prose: string[] = [];
122
+ let proseLine = 1;
108
123
  let index = 0;
109
124
  const flush = () => {
110
125
  const text = trimBlankEdges(prose);
111
- if (text !== "") segments.push({ type: "markdown", text });
126
+ if (text !== "") segments.push({ segment: { type: "markdown", text }, line: proseLine, closed: true, source: "" });
112
127
  prose = [];
113
128
  };
129
+ const addProse = (from: number, added: string[]) => {
130
+ if (prose.length === 0) proseLine = from + 1;
131
+ prose.push(...added);
132
+ };
114
133
 
115
134
  let i = 0;
116
135
  while (i < lines.length) {
@@ -124,6 +143,7 @@ export function parse(markdown: string): Segment[] {
124
143
  body.push((lines[end] as string).replace(new RegExp(`^ {0,${indent.length}}`), ""));
125
144
  end++;
126
145
  }
146
+ const closed = end < lines.length;
127
147
  const stop = Math.min(end + 1, lines.length);
128
148
  const kind = (info.trim().split(/\s+/)[0] as string).toLowerCase();
129
149
  if (fenceKinds.has(kind)) {
@@ -135,9 +155,9 @@ export function parse(markdown: string): Segment[] {
135
155
  lines.slice(i, stop).join("\n"),
136
156
  );
137
157
  if (segment.type === "block") index++;
138
- segments.push(segment);
158
+ segments.push({ segment, line: i + 1, closed, source: body.join("\n") });
139
159
  } else {
140
- prose.push(...lines.slice(i, stop));
160
+ addProse(i, lines.slice(i, stop));
141
161
  }
142
162
  i = stop;
143
163
  continue;
@@ -150,15 +170,20 @@ export function parse(markdown: string): Segment[] {
150
170
  const data = alertOf(run);
151
171
  if (data) {
152
172
  flush();
153
- segments.push({ type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ });
173
+ segments.push({
174
+ segment: { type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ },
175
+ line: i + 1,
176
+ closed: true,
177
+ source: "",
178
+ });
154
179
  } else {
155
- prose.push(...run);
180
+ addProse(i, run);
156
181
  }
157
182
  i = end;
158
183
  continue;
159
184
  }
160
185
 
161
- prose.push(line);
186
+ addProse(i, [line]);
162
187
  i++;
163
188
  }
164
189
  flush();
package/src/core/text.ts CHANGED
@@ -46,26 +46,30 @@ interface Replies {
46
46
  /** Followed by the pick sentence, when the review has one. */
47
47
  review: string;
48
48
  pick: (label: string | undefined) => string;
49
+ /** Closes a review reply, which has no fixed sentence of its own. */
50
+ welcome: string;
49
51
  suggest: string;
50
52
  checklist: string;
51
53
  }
52
54
 
53
55
  const REPLIES: Record<TextLang, Replies> = {
54
56
  en: {
55
- options: "Reply with a number.",
56
- form: (example) => `Reply in text, one line per question, like ${example}.`,
57
+ options: "Reply with a number. Other comments are welcome.",
58
+ form: (example) => `Reply in text, one line per question, like ${example}. Other comments are welcome.`,
57
59
  review: "Reply with a comment for each item, naming the item.",
58
60
  pick: (label) => ` Say which one you pick${label === undefined ? "" : ` (${label})`}.`,
61
+ welcome: " Other comments are welcome.",
59
62
  suggest: "You can reply: ",
60
- checklist: "Reply with the items you tick or leave unticked, naming each.",
63
+ checklist: "Reply with the items you tick or leave unticked, naming each. Other comments are welcome.",
61
64
  },
62
65
  "zh-TW": {
63
- options: "請回覆編號。",
64
- form: (example) => `請用文字回覆,每題一行,例如 ${example}。`,
66
+ options: "請回覆編號。也歡迎補充其他意見。",
67
+ form: (example) => `請用文字回覆,每題一行,例如 ${example}。也歡迎補充其他意見。`,
65
68
  review: "請逐項回覆意見,並寫明是哪一項。",
66
69
  pick: (label) => `請說明你選哪一項${label === undefined ? "" : `(${label})`}。`,
70
+ welcome: "也歡迎補充其他意見。",
67
71
  suggest: "可以回覆:",
68
- checklist: "請回覆你勾選或不勾選的項目,逐項寫明。",
72
+ checklist: "請回覆你勾選或不勾選的項目,逐項寫明。也歡迎補充其他意見。",
69
73
  },
70
74
  };
71
75
 
@@ -152,7 +156,7 @@ function review(dialect: Dialect, data: ReviewData): string {
152
156
  ]);
153
157
  const pick = data.pick === undefined ? "" : dialect.say.pick(data.pick === true ? undefined : data.pick);
154
158
  const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
155
- return [...title, ...lines, "", `${dialect.say.review}${pick}`].join("\n");
159
+ return [...title, ...lines, "", `${dialect.say.review}${pick}${dialect.say.welcome}`].join("\n");
156
160
  }
157
161
 
158
162
  function mindmap(dialect: Dialect, data: MindmapData): string {
@@ -1,4 +1,4 @@
1
- import { optionName, reviewItemName } from "./blocks.ts";
1
+ import { NOTE_FIELD, optionName, reviewItemName } from "./blocks.ts";
2
2
  import type { Answer, AnswerKind, BlockSegment, FormData, QuestionData } from "./types.ts";
3
3
 
4
4
  /** `reason` says what is wrong, for a host's refusal. */
@@ -116,10 +116,22 @@ function problem(block: BlockSegment, answer: Answer): string | undefined {
116
116
  }
117
117
  }
118
118
 
119
+ /** A form question or checklist item named like the reserved note field could not be told from the comments box. */
120
+ function reservedName(block: BlockSegment): string | undefined {
121
+ const clash =
122
+ block.kind === "form"
123
+ ? block.data.questions.some((question) => question.name === NOTE_FIELD)
124
+ : block.kind === "checklist"
125
+ ? block.data.items.some((item) => item.name === NOTE_FIELD)
126
+ : false;
127
+ return clash ? `the name ${quoted(NOTE_FIELD)} is reserved for other comments` : undefined;
128
+ }
129
+
119
130
  /**
120
131
  * Whether an untrusted `answer` fits `block`: its kind is the block's, every field names a question, choice, or item
121
- * of the block, several values appear only for a `multi` form question, required questions are answered, and there
122
- * are at most 64 fields of 1,024 characters each.
132
+ * of the block, several values appear only for a `multi` form question, required questions are answered, one optional
133
+ * `pi-note` field (the "Other comments" box) is accepted on every kind, and there are at most 64 fields of 1,024
134
+ * characters each.
123
135
  */
124
136
  export function validateAnswer(block: BlockSegment, answer: Answer): Validation {
125
137
  // The answer comes from outside: check its shape before reading it.
@@ -135,9 +147,14 @@ export function validateAnswer(block: BlockSegment, answer: Answer): Validation
135
147
  const expected = KINDS[block.kind];
136
148
  if (expected === undefined) return fail(`a ${block.kind} block takes no answer`);
137
149
  if (answer.kind !== expected) return fail(`answer kind ${quoted(answer.kind)} does not fit a ${block.kind} block`);
138
- if (answer.fields.length > MAX_FIELDS) return fail(`more than ${MAX_FIELDS} fields`);
150
+ if (answer.fields.filter(([name]) => name !== NOTE_FIELD).length > MAX_FIELDS)
151
+ return fail(`more than ${MAX_FIELDS} fields`);
139
152
  if (answer.fields.some(([name, value]) => name.length > MAX_LENGTH || value.length > MAX_LENGTH))
140
153
  return fail(`a field is longer than ${MAX_LENGTH} characters`);
141
- const found = problem(block, answer);
154
+ const notes = answer.fields.filter(([name]) => name === NOTE_FIELD);
155
+ if (notes.length > 1) return fail("several other comments");
156
+ const reserved = reservedName(block);
157
+ if (reserved) return fail(reserved);
158
+ const found = problem(block, { ...answer, fields: answer.fields.filter(([name]) => name !== NOTE_FIELD) });
142
159
  return found === undefined ? PASS : fail(found);
143
160
  }
@@ -1,8 +1,8 @@
1
- import { optionName } from "../core/blocks.ts";
1
+ import { NOTE_FIELD, optionName } from "../core/blocks.ts";
2
2
  import { inlinePlain } from "../core/inline.ts";
3
3
  import type { ChecklistData, OptionData, OptionsData, SuggestData } from "../core/types.ts";
4
4
  import { define, PbsElement } from "./base.ts";
5
- import { controlCss, fieldOf, sendingForm, sentBadge, submitRow } from "./controls.ts";
5
+ import { controlCss, fieldOf, noteBox, noteField, sendingForm, sentBadge, submitRow } from "./controls.ts";
6
6
  import { h, inlineNodes, prose, uid } from "./dom.ts";
7
7
 
8
8
  /** The elements that answer with a pick or ticks: options, suggest, checklist. */
@@ -15,9 +15,11 @@ import { h, inlineNodes, prose, uid } from "./dom.ts";
15
15
  export class PbsOptions extends PbsElement<OptionsData> {
16
16
  static override css = controlCss;
17
17
  #sent: number | undefined;
18
+ #note = "";
18
19
 
19
20
  protected override reset(): void {
20
21
  this.#sent = undefined;
22
+ this.#note = "";
21
23
  }
22
24
  protected override settled(): void {
23
25
  this.#sent = undefined;
@@ -28,11 +30,12 @@ export class PbsOptions extends PbsElement<OptionsData> {
28
30
  const selected =
29
31
  this.#sent ?? (picked === undefined ? undefined : data.options.findIndex((o, i) => optionName(o, i) === picked));
30
32
  const locked = this.answered !== undefined || this.#sent !== undefined;
33
+ const sentNote = fieldOf(this.answered, NOTE_FIELD) ?? (this.#sent === undefined ? "" : this.#note.trim());
31
34
  const pick = (index: number) => {
32
35
  if (locked) return;
33
36
  const ok = this.answer({
34
37
  kind: "pick",
35
- fields: [["picked", optionName(data.options[index] as OptionData, index)]],
38
+ fields: [["picked", optionName(data.options[index] as OptionData, index)], ...noteField(this.#note)],
36
39
  });
37
40
  if (!ok) return;
38
41
  this.#sent = index;
@@ -40,6 +43,15 @@ export class PbsOptions extends PbsElement<OptionsData> {
40
43
  this.focusIn("[data-selected] button");
41
44
  };
42
45
  return [
46
+ ...(locked
47
+ ? sentNote
48
+ ? [h("p", { part: "sent-note", class: "status" }, `${this.t("otherComments")}: ${sentNote}`)]
49
+ : []
50
+ : [
51
+ noteBox(this.t("otherComments"), this.#note, (text) => {
52
+ this.#note = text;
53
+ }),
54
+ ]),
43
55
  h(
44
56
  "div",
45
57
  { part: "grid", class: "grid", role: "list", "aria-label": this.t("options") },
@@ -153,9 +165,11 @@ export class PbsSuggest extends PbsElement<SuggestData> {
153
165
  export class PbsChecklist extends PbsElement<ChecklistData> {
154
166
  static override css = controlCss;
155
167
  #checked: boolean[] | undefined;
168
+ #note = "";
156
169
 
157
170
  protected override reset(): void {
158
171
  this.#checked = undefined;
172
+ this.#note = "";
159
173
  }
160
174
 
161
175
  protected view(data: ChecklistData): Node {
@@ -203,6 +217,7 @@ export class PbsChecklist extends PbsElement<ChecklistData> {
203
217
  },
204
218
  rows,
205
219
  );
220
+ const sentNote = fieldOf(locked, NOTE_FIELD);
206
221
  if (locked) {
207
222
  return h(
208
223
  "section",
@@ -210,6 +225,7 @@ export class PbsChecklist extends PbsElement<ChecklistData> {
210
225
  h("div", { class: "sent-head" }, title, sentBadge(this.t("submitted"))),
211
226
  group,
212
227
  progress,
228
+ sentNote && h("p", { part: "sent-note", class: "status" }, `${this.t("otherComments")}: ${sentNote}`),
213
229
  );
214
230
  }
215
231
  const { row, status } = submitRow(data.submit ? inlinePlain(data.submit) : this.t("send"));
@@ -218,10 +234,21 @@ export class PbsChecklist extends PbsElement<ChecklistData> {
218
234
  item.name,
219
235
  checked[index] ? "checked" : "unchecked",
220
236
  ]);
237
+ fields.push(...noteField(this.#note));
221
238
  if (this.answer({ kind: "checklist", ...(data.title ? { title: inlinePlain(data.title) } : {}), fields }))
222
239
  status.textContent = this.t("sent");
223
240
  };
224
- return sendingForm(send, { part: "checklist", class: "panel form-panel" }, title, group, progress, row);
241
+ return sendingForm(
242
+ send,
243
+ { part: "checklist", class: "panel form-panel" },
244
+ title,
245
+ group,
246
+ progress,
247
+ noteBox(this.t("otherComments"), this.#note, (text) => {
248
+ this.#note = text;
249
+ }),
250
+ row,
251
+ );
225
252
  }
226
253
  }
227
254
 
@@ -1,3 +1,4 @@
1
+ import { NOTE_FIELD } from "../core/blocks.ts";
1
2
  import type { AnsweredFields } from "./base.ts";
2
3
  import { type Child, h } from "./dom.ts";
3
4
 
@@ -48,6 +49,8 @@ fieldset.question { border: 0; min-width: 0; display: flex; flex-direction: colu
48
49
  .question .req { color: var(--_risk); }
49
50
  .question .hint { color: var(--_muted); font-size: 0.9em; }
50
51
  .question[aria-invalid="true"] .label { color: var(--_risk); }
52
+ .note-field { display: flex; flex-direction: column; gap: 0.3rem; }
53
+ .note-field .label { font-weight: 600; }
51
54
  .sent-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
52
55
  `;
53
56
 
@@ -58,6 +61,22 @@ export function submitRow(label: string): { row: HTMLElement; button: HTMLButton
58
61
  return { row: h("div", { part: "actions", class: "row" }, button, status), button, status };
59
62
  }
60
63
 
64
+ /** The fixed "Other comments" box above a submit button: its text is sent as the reserved `note` field when not blank. */
65
+ export function noteBox(label: string, value: string, onInput: (text: string) => void): HTMLElement {
66
+ const box = h("textarea", {
67
+ part: "note",
68
+ class: "note-box",
69
+ maxlength: 1024,
70
+ rows: 2,
71
+ value,
72
+ });
73
+ box.addEventListener("input", () => onInput(box.value));
74
+ return h("label", { part: "note-field", class: "note-field" }, h("span", { class: "label" }, label), box);
75
+ }
76
+
77
+ /** The reserved field for a note, or nothing when blank. */
78
+ export const noteField = (text: string): [string, string][] => (text.trim() ? [[NOTE_FIELD, text.trim()]] : []);
79
+
61
80
  /** A form wrapper that submits through `onSend`, from the button, Enter in a one-line box, or Ctrl/Cmd+Enter anywhere inside. */
62
81
  export function sendingForm(onSend: () => void, props: Record<string, string>, ...children: Child[]): HTMLFormElement {
63
82
  const form = h("form", { novalidate: true, ...props }, ...children);