Public: anyone can read this; the crew can change it.
Config files open as a form in the terminal too: JSON, YAML and TOML values edited field by field #16679
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/8934-config-files-open-as-a-form-in-the-termi → main 0 commits fork 1 thread · 1 unresolved
10 files
changed +695
−24
docs/features/config-form.md +16 −2
| @@ -149,8 +149,22 @@ file, then `c`: | ||
| 149 | 149 | against its schema (`schemaRefusal`, found the same three ways). A file |
| 150 | 150 | that breaks it is refused in the dialog, naming the field and the schema, |
| 151 | 151 | and nothing is written. |
| 152 | - There is no form screen in the terminal yet, for JSON, YAML or TOML: values | |
| 153 | are edited as text. #8934 adds one. | |
| 152 | ||
| 153 | ## In the terminal | |
| 154 | ||
| 155 | `Z` in the workspace, on a file `isFormConfig` accepts, opens it as a form | |
| 156 | (`src/tui/screens/configform.ts`, #8934), the other door to `src/web/pages/config.ts`. The rows are the web form's | |
| 157 | fields: the same document, the same `findSchema` and `validate`, the same | |
| 158 | `applyOp` for cards. `enter` or `e` edits a value (an enum is a picker, | |
| 159 | `space` toggles a boolean), `a` adds a card to the array the cursor is in, | |
| 160 | `x` removes the card, `n` adds a key, `s` saves. Saving goes through | |
| 161 | `settleConfig` (`web/render/config-save.ts`, shared with the web), so YAML | |
| 162 | and TOML keep their comments, only the touched lines change, and the | |
| 163 | read-back check holds; "Nothing changed, so there is nothing to save." is | |
| 164 | the web's sentence. A writer then gets the commit dialog (`editFiles`, with | |
| 165 | the blob the form read as `was`); a reader gets **Propose a change** | |
| 166 | (`proposeEdit`). A mirror of an origin is not offered the form; edit it as | |
| 167 | text. Tests: `test/tui-config-form.test.ts`, `test/tui-propose-edit.test.ts`. | |
| 154 | 168 | |
| 155 | 169 | ## Try it |
| 156 | 170 |
scripts/doorless-allow.json −1
src/tui/screens/config_rows.ts added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | /** | |
| 2 | * A config file's document as the rows of a terminal form: plain data in | |
| 3 | * (`Json` and the schema `findSchema` found), plain rows out. The same | |
| 4 | * pointers name the same fields as the web form's (`render/config-form.ts`), | |
| 5 | * and the same `applyOp` adds and removes its cards. | |
| 6 | */ | |
| 7 | ||
| 8 | import { pointer, type Json } from "../../web/render/json-doc.ts"; | |
| 9 | import { schemaAt, type FoundSchema } from "../../web/render/json-schema.ts"; | |
| 10 | ||
| 11 | export interface FormRow { | |
| 12 | /** The value's JSON pointer, the web form's field name. */ | |
| 13 | readonly at: string; | |
| 14 | readonly depth: number; | |
| 15 | readonly label: string; | |
| 16 | readonly kind: Json["t"]; | |
| 17 | /** The value as typed: a scalar's text, a card's size. */ | |
| 18 | readonly text: string; | |
| 19 | /** What an enum allows, as JSON texts, when the schema lists them. */ | |
| 20 | readonly choices?: readonly string[]; | |
| 21 | readonly help?: string; | |
| 22 | readonly required: boolean; | |
| 23 | /** The nearest array this row is in or is, the one `a` adds a card to. */ | |
| 24 | readonly array?: string; | |
| 25 | /** The array card this row is in or is: what `x` removes. */ | |
| 26 | readonly item?: string; | |
| 27 | /** The nearest object, where `n` names a new key. */ | |
| 28 | readonly object: string; | |
| 29 | } | |
| 30 | ||
| 31 | const scalarText = (v: Json): string => | |
| 32 | v.t === "string" || v.t === "number" ? v.v : v.t === "boolean" ? String(v.v) : v.t === "null" ? "null" : ""; | |
| 33 | ||
| 34 | export function formRows(doc: Json, found: FoundSchema | undefined): FormRow[] { | |
| 35 | const rows: FormRow[] = []; | |
| 36 | const walk = ( | |
| 37 | v: Json, | |
| 38 | p: string, | |
| 39 | depth: number, | |
| 40 | label: string, | |
| 41 | near: { array?: string; item?: string; object: string }, | |
| 42 | required: boolean, | |
| 43 | ): void => { | |
| 44 | const s = schemaAt(found, p); | |
| 45 | const choices = Array.isArray(s?.enum) && s.enum.length > 0 ? s.enum.map((e) => JSON.stringify(e)) : undefined; | |
| 46 | const base = { | |
| 47 | at: p, | |
| 48 | depth, | |
| 49 | label, | |
| 50 | kind: v.t, | |
| 51 | required, | |
| 52 | ...(typeof s?.description === "string" && s.description !== "" ? { help: s.description } : {}), | |
| 53 | ...(choices === undefined || v.t === "array" || v.t === "object" ? {} : { choices }), | |
| 54 | ...(near.array === undefined ? {} : { array: near.array }), | |
| 55 | ...(near.item === undefined ? {} : { item: near.item }), | |
| 56 | object: near.object, | |
| 57 | }; | |
| 58 | if (v.t === "object") { | |
| 59 | if (p !== "") rows.push({ ...base, text: `${v.entries.length} keys` }); | |
| 60 | const need = Array.isArray(s?.required) ? s.required : []; | |
| 61 | for (const [k, x] of v.entries) | |
| 62 | walk(x, pointer(p, k), p === "" ? depth : depth + 1, k, { ...near, object: p }, need.includes(k)); | |
| 63 | } else if (v.t === "array") { | |
| 64 | rows.push({ ...base, array: p, text: `${v.items.length} cards`, object: near.object }); | |
| 65 | v.items.forEach((x, i) => { | |
| 66 | const at = pointer(p, i); | |
| 67 | walk(x, at, depth + 1, `[${i}]`, { array: p, item: at, object: near.object }, false); | |
| 68 | }); | |
| 69 | } else rows.push({ ...base, text: scalarText(v) }); | |
| 70 | }; | |
| 71 | walk(doc, "", 0, "", { object: "" }, false); | |
| 72 | return rows; | |
| 73 | } |
src/tui/screens/configform.ts added +302
| @@ -0,0 +1,302 @@ | ||
| 1 | /** | |
| 2 | * A JSON, YAML or TOML file as a form in the terminal (#8934): the web's | |
| 3 | * form (`web/pages/config.ts`, #7336 and #7337) on the other door. Fields | |
| 4 | * come from the same `formRows` over `configFields`' document and the same | |
| 5 | * `findSchema`; cards are added and removed by the same `applyOp`; a save is | |
| 6 | * settled by `settleConfig`, so YAML and TOML keep their comments, only the | |
| 7 | * lines touched change, and the read-back check holds. A writer commits | |
| 8 | * (`editFiles`, through the commit dialog); anyone else proposes | |
| 9 | * (`proposeEdit`), refused in the web's words. The workspace opens it with | |
| 10 | * `Z` on a file `isFormConfig` accepts. | |
| 11 | * | |
| 12 | * j/k move · enter or e edit the value · space toggles a boolean · | |
| 13 | * a adds a card · x removes it · n adds a key · s saves · esc leaves. | |
| 14 | */ | |
| 15 | ||
| 16 | import { editFiles, fileAt } from "../../actions/contents.ts"; | |
| 17 | import { proposeEdit, proposeEditText } from "../../actions/propose_edit.ts"; | |
| 18 | import type { Repo } from "../../core/repos.ts"; | |
| 19 | import { err, ok } from "../../kernel/result.ts"; | |
| 20 | import { MAX_FIELDS, applyOp, countFields, opValue } from "../../web/render/config-form.ts"; | |
| 21 | import { isFormConfig, languageOf, parseConfig } from "../../web/render/config-format.ts"; | |
| 22 | import { MAX_FORM_BYTES, NOTHING_CHANGED, settleConfig } from "../../web/render/config-save.ts"; | |
| 23 | import { fromPlain, getAt, updateAt, type Json } from "../../web/render/json-doc.ts"; | |
| 24 | import { findSchema, isJsonNumber, validate, type FoundSchema } from "../../web/render/json-schema.ts"; | |
| 25 | import type { RepoSource } from "../../view/source.ts"; | |
| 26 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 27 | import { binding } from "../app/keys.ts"; | |
| 28 | import { style } from "../term/style.ts"; | |
| 29 | import { wrap } from "../term/width.ts"; | |
| 30 | import { fill, len, split } from "../ui/layout.ts"; | |
| 31 | import type { Session } from "../session.ts"; | |
| 32 | import { commitScreen, editErrorText, suggestBranch } from "./commit.ts"; | |
| 33 | import { ListState, drawList, pickerScreen, promptScreen, runAsync, slug, type ListRow } from "./common.ts"; | |
| 34 | import { formRows, type FormRow } from "./config_rows.ts"; | |
| 35 | ||
| 36 | export interface ConfigFormOptions { | |
| 37 | readonly src: RepoSource; | |
| 38 | readonly repo: Repo; | |
| 39 | readonly ref: string; | |
| 40 | readonly path: string; | |
| 41 | /** Whether this person proposes (a pull on their fork) rather than commits. */ | |
| 42 | readonly proposing: boolean; | |
| 43 | /** Told once a save landed, so the workspace reads the file again. */ | |
| 44 | readonly saved?: (branch: string) => void; | |
| 45 | } | |
| 46 | ||
| 47 | /** Whether the form can open this file: the same rule as the web's link. */ | |
| 48 | export const hasConfigForm = (path: string): boolean => isFormConfig(path); | |
| 49 | ||
| 50 | export function configFormScreen(f: Session, ctx: Ctx, o: ConfigFormOptions): Screen { | |
| 51 | const state = new ListState(); | |
| 52 | let current = ""; | |
| 53 | let original: Json | undefined; | |
| 54 | let doc: Json | undefined; | |
| 55 | let was: string | null = null; | |
| 56 | let found: FoundSchema | undefined; | |
| 57 | let note = "Reading the file."; | |
| 58 | ||
| 59 | const read = async (p: string): Promise<string | undefined> => { | |
| 60 | const blob = await o.src.blob(o.ref, p); | |
| 61 | return blob.ok && blob.value.kind === "text" ? new TextDecoder().decode(blob.value.body) : undefined; | |
| 62 | }; | |
| 63 | ||
| 64 | const load = async (): Promise<void> => { | |
| 65 | const blob = await o.src.blob(o.ref, o.path); | |
| 66 | if (!blob.ok || blob.value.kind !== "text" || blob.value.size > MAX_FORM_BYTES) { | |
| 67 | note = "This file is too large to edit as a form. Edit it as text, or with git."; | |
| 68 | ctx.invalidate(); | |
| 69 | return; | |
| 70 | } | |
| 71 | current = new TextDecoder().decode(blob.value.body); | |
| 72 | const parsed = parseConfig(o.path, current); | |
| 73 | if (!parsed.ok) { | |
| 74 | const e = parsed.error; | |
| 75 | note = `Not valid ${languageOf(o.path)}: ${e.message} at line ${e.line}, column ${e.column}. Fix it in the source first.`; | |
| 76 | ctx.invalidate(); | |
| 77 | return; | |
| 78 | } | |
| 79 | if (countFields(parsed.value) > MAX_FIELDS) { | |
| 80 | note = `This file has more than ${MAX_FIELDS.toLocaleString()} values, too many for a form. Edit it as text.`; | |
| 81 | ctx.invalidate(); | |
| 82 | return; | |
| 83 | } | |
| 84 | original = doc = parsed.value; | |
| 85 | was = (await fileAt(f.app, o.repo, o.ref, o.path))?.blob ?? null; | |
| 86 | found = await findSchema(o.path, parsed.value, read); | |
| 87 | note = ""; | |
| 88 | ctx.invalidate(); | |
| 89 | }; | |
| 90 | runAsync(ctx, load); | |
| 91 | ||
| 92 | const rows = (): FormRow[] => (doc === undefined ? [] : formRows(doc, found)); | |
| 93 | const errors = (): Map<string, string> => (doc === undefined ? new Map() : validate(doc, found)); | |
| 94 | const change = (next: Json, say = ""): void => { | |
| 95 | doc = next; | |
| 96 | note = say; | |
| 97 | state.clamp(rows().length); | |
| 98 | ctx.invalidate(); | |
| 99 | }; | |
| 100 | const set = (at: string, v: Json): void => change(updateAt(doc!, at, () => v)); | |
| 101 | ||
| 102 | const typed = (row: FormRow, text: string): string | undefined => { | |
| 103 | if (row.kind === "number") { | |
| 104 | if (!isJsonNumber(text.trim())) return "Must be a number."; | |
| 105 | set(row.at, { t: "number", v: text.trim() }); | |
| 106 | } else set(row.at, { t: "string", v: text }); | |
| 107 | return undefined; | |
| 108 | }; | |
| 109 | ||
| 110 | const edit = (row: FormRow | undefined): void => { | |
| 111 | if (row === undefined || doc === undefined) return; | |
| 112 | if (row.kind === "object" || row.kind === "array") return; | |
| 113 | if (row.choices !== undefined) { | |
| 114 | ctx.push( | |
| 115 | pickerScreen(ctx, screen, { | |
| 116 | title: row.label, | |
| 117 | items: row.choices.map((c) => ({ id: c, label: c })), | |
| 118 | onPick: ([chosen]) => { | |
| 119 | if (chosen !== undefined) set(row.at, fromPlain(JSON.parse(chosen))); | |
| 120 | }, | |
| 121 | }), | |
| 122 | ); | |
| 123 | return; | |
| 124 | } | |
| 125 | if (row.kind === "boolean") { | |
| 126 | set(row.at, { t: "boolean", v: row.text !== "true" }); | |
| 127 | return; | |
| 128 | } | |
| 129 | ctx.push( | |
| 130 | promptScreen(ctx, screen, { | |
| 131 | title: row.label, | |
| 132 | label: row.help ?? (row.kind === "number" ? "a number" : "the value"), | |
| 133 | value: row.kind === "null" ? "" : row.text, | |
| 134 | onSubmit: (text) => typed(row, text), | |
| 135 | }), | |
| 136 | ); | |
| 137 | }; | |
| 138 | ||
| 139 | const add = (row: FormRow | undefined): void => { | |
| 140 | if (doc === undefined) return; | |
| 141 | if (row?.array === undefined) { | |
| 142 | note = "a adds a card to a list: move to a row inside one."; | |
| 143 | ctx.invalidate(); | |
| 144 | return; | |
| 145 | } | |
| 146 | change(applyOp(doc, opValue("add", row.array), found)); | |
| 147 | }; | |
| 148 | const remove = (row: FormRow | undefined): void => { | |
| 149 | if (doc === undefined) return; | |
| 150 | if (row?.item === undefined) { | |
| 151 | note = "x removes a card from a list: move to a row inside one."; | |
| 152 | ctx.invalidate(); | |
| 153 | return; | |
| 154 | } | |
| 155 | change(applyOp(doc, opValue("remove", row.item), found)); | |
| 156 | }; | |
| 157 | const newKey = (row: FormRow | undefined): void => { | |
| 158 | if (row === undefined || doc === undefined) return; | |
| 159 | const at = row.kind === "object" ? row.at : row.object; | |
| 160 | const here = getAt(doc, at); | |
| 161 | if (here?.t !== "object") return; | |
| 162 | ctx.push( | |
| 163 | promptScreen(ctx, screen, { | |
| 164 | title: "Add a key", | |
| 165 | label: "the key's name", | |
| 166 | onSubmit: (name) => { | |
| 167 | if (name === "") return "A key needs a name."; | |
| 168 | if (here.entries.some(([k]) => k === name)) return `${name} is already there.`; | |
| 169 | change(applyOp(doc!, opValue("key", at, name), found)); | |
| 170 | return undefined; | |
| 171 | }, | |
| 172 | }), | |
| 173 | ); | |
| 174 | }; | |
| 175 | ||
| 176 | const save = (): void => { | |
| 177 | if (doc === undefined || original === undefined) return; | |
| 178 | const bad = errors(); | |
| 179 | if (bad.size > 0) { | |
| 180 | note = bad.size === 1 ? "One field needs a fix." : `${bad.size} fields need a fix.`; | |
| 181 | ctx.invalidate(); | |
| 182 | return; | |
| 183 | } | |
| 184 | const settled = settleConfig(o.path, current, original, doc); | |
| 185 | if (settled.kind === "same") { | |
| 186 | note = NOTHING_CHANGED; | |
| 187 | ctx.invalidate(); | |
| 188 | return; | |
| 189 | } | |
| 190 | if (settled.kind === "refused") { | |
| 191 | note = settled.message; | |
| 192 | ctx.invalidate(); | |
| 193 | return; | |
| 194 | } | |
| 195 | const after = settled.after; | |
| 196 | const subject = `Update ${o.path}`; | |
| 197 | const fullName = `${o.repo.ownerName}/${o.repo.name}`; | |
| 198 | const finished = (branch: string): void => { | |
| 199 | o.saved?.(branch); | |
| 200 | ctx.pop(); | |
| 201 | }; | |
| 202 | ctx.push( | |
| 203 | commitScreen(f, ctx, screen, { | |
| 204 | repo: o.repo, | |
| 205 | where: fullName, | |
| 206 | branch: o.ref, | |
| 207 | title: o.proposing ? "Propose a change" : `Commit ${o.path}`, | |
| 208 | subject, | |
| 209 | files: [{ path: o.path, kind: "edit" }], | |
| 210 | defaultBranchName: suggestBranch(f, "edit", slug(o.path)), | |
| 211 | ...(o.proposing ? { mode: "propose" as const, upstream: { fullName, base: o.ref } } : {}), | |
| 212 | commit: async (plan) => { | |
| 213 | if (o.proposing) { | |
| 214 | const sent = await proposeEdit(f.app, f.user, o.repo, { | |
| 215 | base: o.ref, | |
| 216 | files: [{ path: o.path, content: after }], | |
| 217 | message: plan.message, | |
| 218 | title: plan.pull?.title ?? subject, | |
| 219 | ...(plan.pull?.body === undefined ? {} : { body: plan.pull.body }), | |
| 220 | ...(plan.newBranch === undefined ? {} : { branch: plan.newBranch }), | |
| 221 | }); | |
| 222 | if (!sent.ok) return err(proposeEditText(sent.error)); | |
| 223 | return ok({ | |
| 224 | message: `opened pull #${sent.value.pull.number} on ${fullName} from ${sent.value.head.ownerName}/${sent.value.head.name}`, | |
| 225 | then: () => finished(sent.value.branch), | |
| 226 | }); | |
| 227 | } | |
| 228 | const made = await editFiles(f.app, f.user, o.repo, { | |
| 229 | branch: o.ref, | |
| 230 | base: o.ref, | |
| 231 | ...(plan.newBranch === undefined ? {} : { newBranch: plan.newBranch }), | |
| 232 | message: plan.message, | |
| 233 | files: [{ path: o.path, content: after, was }], | |
| 234 | ...(plan.pull === undefined ? {} : { openPull: plan.pull }), | |
| 235 | }); | |
| 236 | if (!made.ok) return err(editErrorText(made.error)); | |
| 237 | const result = made.value; | |
| 238 | return ok({ | |
| 239 | message: | |
| 240 | result.pull === undefined | |
| 241 | ? `committed to ${result.branch}` | |
| 242 | : `committed to ${result.branch} · pull #${result.pull.number} opened`, | |
| 243 | then: () => finished(result.branch), | |
| 244 | }); | |
| 245 | }, | |
| 246 | }), | |
| 247 | ); | |
| 248 | }; | |
| 249 | ||
| 250 | const lines = (): ListRow[] => { | |
| 251 | const bad = errors(); | |
| 252 | return rows().map((r) => { | |
| 253 | const error = bad.get(r.at); | |
| 254 | return { | |
| 255 | title: `${" ".repeat(r.depth)}${r.label === "" ? "(value)" : r.label}${r.required ? " *" : ""}`, | |
| 256 | meta: r.kind === "object" || r.kind === "array" ? r.text : r.kind === "string" ? JSON.stringify(r.text) : r.text, | |
| 257 | ...(error === undefined ? {} : { below: [error] }), | |
| 258 | }; | |
| 259 | }); | |
| 260 | }; | |
| 261 | ||
| 262 | const screen: Screen = { | |
| 263 | title: o.path, | |
| 264 | get keys() { | |
| 265 | return [ | |
| 266 | binding(["enter", "e"], "edit the value"), | |
| 267 | binding(["space"], "toggle"), | |
| 268 | binding(["a", "x", "n"], "add a card, remove it, add a key"), | |
| 269 | binding(["s"], o.proposing ? "review and propose" : "review and commit"), | |
| 270 | binding(["j", "k"], "move cursor"), | |
| 271 | ]; | |
| 272 | }, | |
| 273 | render(area, s) { | |
| 274 | const c = ctx.theme.c; | |
| 275 | const row = rows()[state.index]; | |
| 276 | const text = | |
| 277 | note !== "" | |
| 278 | ? note | |
| 279 | : (row?.help ?? `${o.path} on ${o.ref} in ${o.repo.ownerName}/${o.repo.name}${found === undefined ? " · fields from the values" : ` · fields from ${found.from}`}`); | |
| 280 | const said = wrap(text, Math.max(1, area.w)).slice(0, 3); | |
| 281 | const [head, list] = split(area, "v", [len(said.length), fill(1)]); | |
| 282 | said.forEach((line, i) => s.text(head!.x, head!.y + i, line, style(c.mutedFg, c.bg), head!.x + head!.w)); | |
| 283 | drawList(s, list!, c, state, lines()); | |
| 284 | }, | |
| 285 | key(e) { | |
| 286 | const list = rows(); | |
| 287 | if (state.key(e, list.length)) return true; | |
| 288 | if (e.ctrl || e.alt) return false; | |
| 289 | const row = list[state.index]; | |
| 290 | if (e.key === "enter" || e.key === "e") edit(row); | |
| 291 | else if (e.key === "space") { | |
| 292 | if (row?.kind === "boolean") edit(row); | |
| 293 | } else if (e.key === "a") add(row); | |
| 294 | else if (e.key === "x") remove(row); | |
| 295 | else if (e.key === "n") newKey(row); | |
| 296 | else if (e.key === "s") save(); | |
| 297 | else return false; | |
| 298 | return true; | |
| 299 | }, | |
| 300 | }; | |
| 301 | return screen; | |
| 302 | } |
src/tui/screens/workspace.ts +33
| @@ -38,6 +38,7 @@ import { cannotChangeWords } from "../../actions/edit_words.ts"; | ||
| 38 | 38 | import { editFiles, fileAt } from "../../actions/contents.ts"; |
| 39 | 39 | import { proposeEdit, proposeEditText } from "../../actions/propose_edit.ts"; |
| 40 | 40 | import { schemaRefusal } from "../../web/render/json-schema.ts"; |
| 41 | import { configFormScreen, hasConfigForm } from "./configform.ts"; | |
| 41 | 42 | import { err, ok } from "../../kernel/result.ts"; |
| 42 | 43 | import { createBranchSaying } from "../../actions/branches.ts"; |
| 43 | 44 | import { NAME_THE_BRANCH } from "../../actions/branch_words.ts"; |
| @@ -2397,6 +2398,7 @@ export function workspaceScreen( | ||
| 2397 | 2398 | ...(t?.db == null ? [] : [binding([">", "<", "}", "{"], "next / previous 100 rows, next / previous table")]), |
| 2398 | 2399 | binding(["tab"], "focus explorer"), |
| 2399 | 2400 | binding(["e"], "edit", { disabled: !editable() }), |
| 2401 | ...(t !== undefined && hasConfigForm(t.path) ? [binding(["Z"], "edit as a form", { disabled: !editable() })] : []), | |
| 2400 | 2402 | binding( |
| 2401 | 2403 | ["v"], |
| 2402 | 2404 | t?.image !== null && t !== undefined |
| @@ -2992,6 +2994,10 @@ export function workspaceScreen( | ||
| 2992 | 2994 | runAsync(ctx, reload); |
| 2993 | 2995 | return true; |
| 2994 | 2996 | } |
| 2997 | if (plain && e.key === "Z" && t !== undefined && hasConfigForm(t.path)) { | |
| 2998 | openForm(t.path); | |
| 2999 | return true; | |
| 3000 | } | |
| 2995 | 3001 | if (plain && e.key === "E") { |
| 2996 | 3002 | openExternal(); |
| 2997 | 3003 | return true; |
| @@ -3103,6 +3109,33 @@ export function workspaceScreen( | ||
| 3103 | 3109 | ctx.replace(workspaceScreen(f, ctx, local(f, next))); |
| 3104 | 3110 | } |
| 3105 | 3111 | |
| 3112 | /** `Z`: a JSON, YAML or TOML file as a form (#8934), saved by commit or proposal. */ | |
| 3113 | function openForm(path: string): void { | |
| 3114 | const t = tab(); | |
| 3115 | if (repo === undefined || !(writable() || forkable())) { | |
| 3116 | if (proposal() !== undefined) ctx.toast("this mirrors an origin: edit the file as text to propose it", "attn"); | |
| 3117 | else readOnlyToast(); | |
| 3118 | return; | |
| 3119 | } | |
| 3120 | if (t !== undefined && t.modified) { | |
| 3121 | ctx.toast("save or discard your edits to this file first: the form reads what the branch holds", "attn"); | |
| 3122 | return; | |
| 3123 | } | |
| 3124 | ctx.push( | |
| 3125 | configFormScreen(f, ctx, { | |
| 3126 | src, | |
| 3127 | repo, | |
| 3128 | ref: ref === "" ? repo.defaultBranch : ref, | |
| 3129 | path, | |
| 3130 | proposing: !writable(), | |
| 3131 | saved: (branch) => { | |
| 3132 | if (writable()) ref = branch; | |
| 3133 | runAsync(ctx, reload); | |
| 3134 | }, | |
| 3135 | }), | |
| 3136 | ); | |
| 3137 | } | |
| 3138 | ||
| 3106 | 3139 | /** `E`: hand the file to the operator's own editor and commit what comes back. */ |
| 3107 | 3140 | function openExternal(): void { |
| 3108 | 3141 | if (!hasExternalEditor()) { |
src/web/pages/config.ts +8 −19
| @@ -32,17 +32,16 @@ import { loadRepo, notFoundPage, pageHead, signInFirst } from "../chrome.ts"; | ||
| 32 | 32 | import { field as formValue, readForm, type Form } from "../form.ts"; |
| 33 | 33 | import { html, when, type Html } from "../html.ts"; |
| 34 | 34 | import { flashTo, page } from "../layout.ts"; |
| 35 | import { isFormConfig, languageOf, parseConfig, writeConfig } from "../render/config-format.ts"; | |
| 35 | import { isFormConfig, languageOf, parseConfig } from "../render/config-format.ts"; | |
| 36 | import { MAX_FORM_BYTES, NOTHING_CHANGED, settleConfig } from "../render/config-save.ts"; | |
| 36 | 37 | import { applyOp, configFields, countFields, MAX_FIELDS, readValues } from "../render/config-form.ts"; |
| 37 | import { lineDiff, parseJson, sameDoc, stringify, type Json } from "../render/json-doc.ts"; | |
| 38 | import { lineDiff, parseJson, stringify, type Json } from "../render/json-doc.ts"; | |
| 38 | 39 | import { findSchema, validate, type FoundSchema } from "../render/json-schema.ts"; |
| 39 | 40 | import { localScope, type RepoScope } from "../scope.ts"; |
| 40 | 41 | import { btn, field, icon } from "../ui.ts"; |
| 41 | 42 | import { editErrorText } from "./edit.ts"; |
| 42 | 43 | import { refSetFrom } from "./refs.ts"; |
| 43 | 44 | |
| 44 | /** Bigger than this, the form is no help; the source editor is. */ | |
| 45 | export const MAX_FORM_BYTES = 256 * 1024; | |
| 46 | 45 | /** A schema file larger than this is not read. */ |
| 47 | 46 | const MAX_SCHEMA_BYTES = 256 * 1024; |
| 48 | 47 | |
| @@ -296,21 +295,11 @@ export async function configSubmit(ctx: Ctx): Promise<Response> { | ||
| 296 | 295 | flash: { tone: "danger", message: `${path} changed on ${ref} since you opened it. Check your values, then review again.` }, |
| 297 | 296 | }); |
| 298 | 297 | } |
| 299 | if (sameDoc(original.value, read.doc)) | |
| 300 | return formPage(ctx, scope, { ...state, flash: { tone: "success", message: "Nothing changed, so there is nothing to save." } }); | |
| 301 | ||
| 302 | const written = writeConfig(path, current, original.value, read.doc); | |
| 303 | // What is written must read back as exactly the form's document. | |
| 304 | const check = written.ok ? parseConfig(path, written.text) : undefined; | |
| 305 | if (!written.ok || check === undefined || !check.ok || !sameDoc(check.value, read.doc)) | |
| 306 | return formPage(ctx, scope, { | |
| 307 | ...state, | |
| 308 | flash: { | |
| 309 | tone: "danger", | |
| 310 | message: written.ok ? "That change could not be written back safely. Edit the file as text." : written.message, | |
| 311 | }, | |
| 312 | }); | |
| 313 | const after = written.text; | |
| 298 | const settled = settleConfig(path, current, original.value, read.doc); | |
| 299 | if (settled.kind === "same") | |
| 300 | return formPage(ctx, scope, { ...state, flash: { tone: "success", message: NOTHING_CHANGED } }); | |
| 301 | if (settled.kind === "refused") return formPage(ctx, scope, { ...state, flash: { tone: "danger", message: settled.message } }); | |
| 302 | const after = settled.after; | |
| 314 | 303 | if (step !== "save") return reviewPage(ctx, scope, state, { before: current, after }); |
| 315 | 304 | |
| 316 | 305 | const subject = formValue(form, "message").trim(); |
src/web/render/config-save.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | /** | |
| 2 | * What a config form's save writes, settled once for the web form and the | |
| 3 | * terminal's: the document unchanged writes nothing, a change is written in | |
| 4 | * the file's own shape, and what is written must read back as exactly the | |
| 5 | * document the form held. The words are the doors' shared words. | |
| 6 | */ | |
| 7 | ||
| 8 | import { parseConfig, writeConfig } from "./config-format.ts"; | |
| 9 | import { sameDoc, type Json } from "./json-doc.ts"; | |
| 10 | ||
| 11 | /** Bigger than this, the form is no help; the source editor is. */ | |
| 12 | export const MAX_FORM_BYTES = 256 * 1024; | |
| 13 | export const NOTHING_CHANGED = "Nothing changed, so there is nothing to save."; | |
| 14 | export const NOT_WRITTEN_BACK = "That change could not be written back safely. Edit the file as text."; | |
| 15 | ||
| 16 | export type Settled = | |
| 17 | | { readonly kind: "same" } | |
| 18 | | { readonly kind: "text"; readonly after: string } | |
| 19 | | { readonly kind: "refused"; readonly message: string }; | |
| 20 | ||
| 21 | export function settleConfig(path: string, current: string, original: Json, doc: Json): Settled { | |
| 22 | if (sameDoc(original, doc)) return { kind: "same" }; | |
| 23 | const written = writeConfig(path, current, original, doc); | |
| 24 | if (!written.ok) return { kind: "refused", message: written.message }; | |
| 25 | const check = parseConfig(path, written.text); | |
| 26 | if (!check.ok || !sameDoc(check.value, doc)) return { kind: "refused", message: NOT_WRITTEN_BACK }; | |
| 27 | return { kind: "text", after: written.text }; | |
| 28 | } |
test/config-form.test.ts +2 −1
| @@ -26,7 +26,8 @@ import { localSource } from "../src/view/local.ts"; | ||
| 26 | 26 | import { applyOp, configFields, opValue, readValues } from "../src/web/render/config-form.ts"; |
| 27 | 27 | import { detectStyle, parseJson, sameDoc, stringify, type Json } from "../src/web/render/json-doc.ts"; |
| 28 | 28 | import { findSchema, globMatches, validate } from "../src/web/render/json-schema.ts"; |
| 29 | import { digestOf, MAX_FORM_BYTES } from "../src/web/pages/config.ts"; | |
| 29 | import { digestOf } from "../src/web/pages/config.ts"; | |
| 30 | import { MAX_FORM_BYTES } from "../src/web/render/config-save.ts"; | |
| 30 | 31 | import { seedAdmin } from "./helpers/admin.ts"; |
| 31 | 32 | import { signUpProven } from "./helpers/verified.ts"; |
| 32 | 33 | import { gitClientEnv } from "./helpers/git-client.ts"; |
test/tui-config-form.test.ts added +191
| @@ -0,0 +1,191 @@ | ||
| 1 | /** | |
| 2 | * A config file as a form in the terminal (#8934): a JSON, a YAML and a TOML | |
| 3 | * edit, each changing only the line it touched, and the card and refusal | |
| 4 | * paths that share the web form's code. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 10 | import type { App as Forge } from "../src/app.ts"; | |
| 11 | import type { Repo } from "../src/core/repos.ts"; | |
| 12 | import type { User } from "../src/core/users.ts"; | |
| 13 | import { listBranches } from "../src/git/branches.ts"; | |
| 14 | import { blobForRender } from "../src/git/read.ts"; | |
| 15 | import { formRows } from "../src/tui/screens/config_rows.ts"; | |
| 16 | import { parseJson } from "../src/web/render/json-doc.ts"; | |
| 17 | import type { TuiIdentity } from "../src/tui/session.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | import { workspaceFixture, type Fixture } from "./helpers/tui-workspace.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const FILES = { | |
| 24 | "app.json": '{\n "name": "lighthouse",\n "port": 8080,\n "debug": false\n}\n', | |
| 25 | "app.yml": "# the lamp\nname: lighthouse # keep this\nport: 8080\ndebug: false\ntags:\n - a\n", | |
| 26 | "live.json": '{\n "name": "lighthouse",\n "port": 8080,\n "debug": false\n}\n', | |
| 27 | "app.toml": '# the lamp\nname = "lighthouse" # keep this\nport = 8080\ndebug = false\n', | |
| 28 | }; | |
| 29 | ||
| 30 | const lines = (s: string): string[] => s.split("\n"); | |
| 31 | ||
| 32 | describe("a config file as a terminal form", () => { | |
| 33 | let fx: Fixture; | |
| 34 | let forge: Forge; | |
| 35 | let alice: User; | |
| 36 | let repo: Repo; | |
| 37 | let dir: string; | |
| 38 | ||
| 39 | const asAlice = (): TuiIdentity => ({ sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }); | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | fx = await workspaceFixture(); | |
| 43 | ({ forge, alice } = fx); | |
| 44 | const made = await createRepo(forge, alice, { name: "beacon", visibility: "public" }); | |
| 45 | if (!made.ok) throw new Error("repo failed"); | |
| 46 | repo = made.value; | |
| 47 | dir = join(forge.reposRoot, "alice", "beacon.git"); | |
| 48 | await commitToBranch(forge, alice, repo, { | |
| 49 | message: "seed", | |
| 50 | files: [{ path: "README.md", content: "# Beacon\n" }, ...Object.entries(FILES).map(([path, content]) => ({ path, content }))], | |
| 51 | }); | |
| 52 | }); | |
| 53 | afterAll(() => fx.close()); | |
| 54 | ||
| 55 | const branchNames = async (): Promise<string[]> => { | |
| 56 | const listed = await listBranches(dir, repo.defaultBranch); | |
| 57 | return listed.ok ? listed.value.branches.map((b) => b.name) : []; | |
| 58 | }; | |
| 59 | ||
| 60 | const textAt = async (ref: string, path: string): Promise<string> => { | |
| 61 | const b = await blobForRender(dir, ref, path, 1 << 20); | |
| 62 | if (b.kind !== "text") throw new Error(`${path} is not text on ${ref}`); | |
| 63 | return new TextDecoder().decode(b.body); | |
| 64 | }; | |
| 65 | ||
| 66 | /** Open `file` as a form, run `edit`, save to a new branch; the branch's text. */ | |
| 67 | async function saved(file: keyof typeof FILES, edit: (h: ReturnType<Fixture["boot"]>) => Promise<void>): Promise<string> { | |
| 68 | const before = new Set(await branchNames()); | |
| 69 | const h = fx.boot(asAlice()); | |
| 70 | try { | |
| 71 | await h.settle(); | |
| 72 | await fx.open(h, "beacon"); | |
| 73 | await fx.openFile(h, file); | |
| 74 | await h.press("Z"); | |
| 75 | expect(h.text()).toContain(file); | |
| 76 | await edit(h); | |
| 77 | await h.press("s"); | |
| 78 | await h.settle(); | |
| 79 | await h.press("ctrl+s"); | |
| 80 | await h.until("committed to"); | |
| 81 | } finally { | |
| 82 | h.stop(); | |
| 83 | } | |
| 84 | const made = (await branchNames()).filter((n) => !before.has(n)); | |
| 85 | expect(made).toHaveLength(1); | |
| 86 | return textAt(made[0]!, file); | |
| 87 | } | |
| 88 | ||
| 89 | test("a JSON number is typed in, and one line changes", async () => { | |
| 90 | const after = await saved("app.json", async (h) => { | |
| 91 | await h.press("j", "enter"); // name, then port | |
| 92 | await h.press("backspace", "backspace", "backspace", "backspace"); | |
| 93 | await h.type("9090"); | |
| 94 | await h.press("enter"); | |
| 95 | }); | |
| 96 | const was = lines(FILES["app.json"]); | |
| 97 | const now = lines(after); | |
| 98 | expect(now).toHaveLength(was.length); | |
| 99 | expect(now.filter((l, i) => l !== was[i])).toEqual([' "port": 9090,']); | |
| 100 | }); | |
| 101 | ||
| 102 | test("a YAML boolean toggles, and its comments stay", async () => { | |
| 103 | const after = await saved("app.yml", async (h) => { | |
| 104 | await h.press("j", "j", "space"); // debug | |
| 105 | }); | |
| 106 | const was = lines(FILES["app.yml"]); | |
| 107 | const now = lines(after); | |
| 108 | expect(now.filter((l, i) => l !== was[i])).toEqual(["debug: true"]); | |
| 109 | expect(after).toContain("# the lamp"); | |
| 110 | expect(after).toContain("# keep this"); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a TOML string is edited, and its comments stay", async () => { | |
| 114 | const after = await saved("app.toml", async (h) => { | |
| 115 | await h.press("enter"); // name | |
| 116 | await h.type("!"); | |
| 117 | await h.press("enter"); | |
| 118 | }); | |
| 119 | const was = lines(FILES["app.toml"]); | |
| 120 | const now = lines(after); | |
| 121 | expect(now.filter((l, i) => l !== was[i])).toHaveLength(1); | |
| 122 | expect(after).toContain('name = "lighthouse!"'); | |
| 123 | expect(after).toContain("# keep this"); | |
| 124 | }); | |
| 125 | ||
| 126 | test("a save from the terminal is announced as a push to the new branch, as a web viewer's stream hears it", async () => { | |
| 127 | const heard: { repoId: string; actorId: string | null; refs: string[] }[] = []; | |
| 128 | const off = forge.bus.subscribe((e) => { | |
| 129 | if (e.kind !== "push" || e.repoId !== repo.id) return; | |
| 130 | const updates = (e.payload as { updates: { ref: string }[] }).updates; | |
| 131 | heard.push({ repoId: e.repoId, actorId: e.actorId, refs: updates.map((u) => u.ref) }); | |
| 132 | }); | |
| 133 | let after = ""; | |
| 134 | try { | |
| 135 | after = await saved("live.json", async (h) => { | |
| 136 | await h.press("j", "j", "space"); // debug | |
| 137 | }); | |
| 138 | } finally { | |
| 139 | off(); | |
| 140 | } | |
| 141 | expect(after).toContain('"debug": true'); | |
| 142 | expect(heard).toHaveLength(1); | |
| 143 | expect(heard[0]!.actorId).toBe(alice.id); | |
| 144 | expect(heard[0]!.refs).toHaveLength(1); | |
| 145 | expect(heard[0]!.refs[0]!).toMatch(/^refs\/heads\/.+/); | |
| 146 | expect(await branchNames()).toContain(heard[0]!.refs[0]!.slice("refs/heads/".length)); | |
| 147 | }, 20_000); | |
| 148 | ||
| 149 | test("a and x outside a card say so", async () => { | |
| 150 | const h = fx.boot(asAlice()); | |
| 151 | try { | |
| 152 | await h.settle(); | |
| 153 | await fx.open(h, "beacon"); | |
| 154 | await fx.openFile(h, "app.yml"); | |
| 155 | await h.press("Z"); | |
| 156 | await h.press("a"); | |
| 157 | expect(h.text()).toContain("a adds a card to a list"); | |
| 158 | await h.press("x"); | |
| 159 | expect(h.text()).toContain("x removes a card from a list"); | |
| 160 | } finally { | |
| 161 | h.stop(); | |
| 162 | } | |
| 163 | }); | |
| 164 | ||
| 165 | test("a card is added and removed, and a save with no change says so", async () => { | |
| 166 | const h = fx.boot(asAlice()); | |
| 167 | try { | |
| 168 | await h.settle(); | |
| 169 | await fx.open(h, "beacon"); | |
| 170 | await fx.openFile(h, "app.yml"); | |
| 171 | await h.press("Z"); | |
| 172 | expect(h.text()).toContain("1 cards"); | |
| 173 | await h.press("j", "j", "j", "a"); | |
| 174 | expect(h.text()).toContain("2 cards"); | |
| 175 | await h.press("j", "j", "x"); | |
| 176 | expect(h.text()).toContain("1 cards"); | |
| 177 | await h.press("s"); | |
| 178 | expect(h.text()).toContain("Nothing changed, so there is nothing to save."); | |
| 179 | } finally { | |
| 180 | h.stop(); | |
| 181 | } | |
| 182 | }); | |
| 183 | ||
| 184 | test("rows carry the web form's pointers and the schema's help", () => { | |
| 185 | const parsed = parseJson('{"a":{"b":[1,2]},"c":true}'); | |
| 186 | if (!parsed.ok) throw new Error("bad json"); | |
| 187 | const rows = formRows(parsed.value, undefined); | |
| 188 | expect(rows.map((r) => r.at)).toEqual(["/a", "/a/b", "/a/b/0", "/a/b/1", "/c"]); | |
| 189 | expect(rows[2]).toMatchObject({ item: "/a/b/0", array: "/a/b", object: "/a" }); | |
| 190 | }); | |
| 191 | }); |
test/tui-propose-edit.test.ts +42 −1
| @@ -69,7 +69,7 @@ describe("proposing and checking from the terminal", () => { | ||
| 69 | 69 | async function openBeacon(h: Harness): Promise<void> { |
| 70 | 70 | await h.settle(); |
| 71 | 71 | await h.press("/"); |
| 72 | await h.type("beacon"); | |
| 72 | await h.type("alice/beacon"); | |
| 73 | 73 | await h.press("enter"); |
| 74 | 74 | await h.press("enter"); |
| 75 | 75 | await h.until("alice/beacon"); |
| @@ -154,4 +154,45 @@ describe("proposing and checking from the terminal", () => { | ||
| 154 | 154 | h.stop(); |
| 155 | 155 | } |
| 156 | 156 | }); |
| 157 | ||
| 158 | test("the form refuses a value that breaks the schema, in the web's words, and writes nothing", async () => { | |
| 159 | const h = boot(as(alice)); | |
| 160 | try { | |
| 161 | await openBeacon(h); | |
| 162 | await openFile(h, "limitsjson"); | |
| 163 | await h.press("Z"); | |
| 164 | await h.press("enter"); | |
| 165 | await h.type("00"); | |
| 166 | await h.press("enter"); | |
| 167 | expect(h.text()).toContain("Must be at most"); | |
| 168 | await h.press("s"); | |
| 169 | expect(h.text()).toContain("One field needs a fix."); | |
| 170 | expect(await fileAt("alice", "main", "limits.json")).toBe(LIMITS); | |
| 171 | } finally { | |
| 172 | h.stop(); | |
| 173 | } | |
| 174 | }); | |
| 175 | ||
| 176 | test("a reader proposes from the form: one line on their fork's branch, and a pull", async () => { | |
| 177 | const h = boot(as(kim)); | |
| 178 | try { | |
| 179 | await openBeacon(h); | |
| 180 | await openFile(h, "limitsjson"); | |
| 181 | await h.press("Z"); | |
| 182 | await h.press("enter", "backspace"); | |
| 183 | await h.type("7"); | |
| 184 | await h.press("enter"); | |
| 185 | await h.press("s"); | |
| 186 | await h.until("Propose a change"); | |
| 187 | await h.press("ctrl+s"); | |
| 188 | await h.until("opened pull #"); | |
| 189 | const beacon = getRepo(forge.db, "alice", "beacon")!; | |
| 190 | const pull = listPulls(forge.db, beacon.id, { state: "open" }).find((p) => p.headRepoId === getRepo(forge.db, "kim", "beacon")!.id); | |
| 191 | expect(pull).toBeDefined(); | |
| 192 | expect(await fileAt("kim", pull!.headBranch, "limits.json")).toBe('{\n "max": 7\n}\n'); | |
| 193 | expect(await fileAt("alice", "main", "limits.json")).toBe(LIMITS); | |
| 194 | } finally { | |
| 195 | h.stop(); | |
| 196 | } | |
| 197 | }); | |
| 157 | 198 | }); |
new above
offline
Add a test that a terminal save is seen live by a web viewer of the file and the branch (box 4). Nothing here would fail if the terminal stopped publishing.