Public: anyone can read this; the crew can change it.
The file editor never mangles or loses work: own line endings, a stale save refused, drafts survive reload (#16420) #16424
Check · Review · Land · Live done — Landed and live in production.
fix/editor-integrity → main 0 commits 4 threads · 4 unresolved
11 files
changed +800
−23
docs/features/edit-keeps-your-work.md added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | --- | |
| 2 | topic: Files in the browser | |
| 3 | row: The editor never loses or mangles your work | |
| 4 | --- | |
| 5 | ||
| 6 | # The editor never loses or mangles your work (#16420) | |
| 7 | ||
| 8 | Three promises when you edit a file in the browser (`/<owner>/<repo>/edit/<branch>/<path>`) or in the terminal's workspace (`e`, then `ctrl+s`): | |
| 9 | ||
| 10 | - **Your file keeps its line endings.** A browser sends a text box's line breaks as CRLF whatever the file had. The editor notes the file's own endings when it opens (`eol`, by what most lines end in) and the save writes your text in them, so a one-line edit changes one line (`asTyped`, `src/web/pages/edit.ts`). The terminal's editor keeps the bytes it read. | |
| 11 | - **A save never replaces a newer change unseen.** The editor remembers which version of the file it opened. If someone changed it on that branch since, the save is refused: "notes.md changed on main since you opened it. Nothing was saved; your text is kept." The same check and the same sentence in both editors (`fileAt` and `EditFile.was` in `src/actions/contents.ts`, `changedSinceWords` in `src/actions/edit_words.ts`). | |
| 12 | - On the web, the refusal links **See what changed** (the file's history on the branch) and offers **Replace their change with mine** beside a box, "I have seen their change, and mine should replace it". The button writes only with the box ticked, and only over the version you were shown; if a third change lands meanwhile, it refuses again. Plain **Commit change** keeps refusing. Their change stays in the history either way. | |
| 13 | - In the terminal (`src/tui/screens/workspace.ts`, its commit box `src/tui/screens/commit.ts`), the commit box says the sentence and nothing is written; your buffer is untouched. The terminal has no Replace: to keep yours over theirs, paste your text into the web editor and use its Replace. | |
| 14 | - A new file is refused the same way when a file of that name appeared meanwhile. | |
| 15 | - **A reload does not lose what you typed.** What you have typed and not committed is kept in this browser, per file, and comes back with one line: "Restored what you typed here before (time), not yet committed." with **Discard it**. It is dropped once the commit lands. Storage that is blocked or private keeps nothing and changes nothing else. It lives only in this browser (`editorJs`, `src/web/client.ts`). | |
| 16 | ||
| 17 | Proof: `test/web-editor-integrity.test.ts` (endings, two tabs, Replace and its box, drafts), `test/tui-editor.test.ts` (the terminal's refusal). |
scripts/doorless-allow.json −1
| @@ -25,7 +25,6 @@ | ||
| 25 | 25 | "src/web/pages/crew-settings.ts", |
| 26 | 26 | "src/web/pages/danger.ts", |
| 27 | 27 | "src/web/pages/dep_chain.ts", |
| 28 | "src/web/pages/edit.ts", | |
| 29 | 28 | "src/web/pages/everyday.ts", |
| 30 | 29 | "src/web/pages/explorer.ts", |
| 31 | 30 | "src/web/pages/family_tree_js.ts", |
src/actions/contents.ts +45 −1
| @@ -19,8 +19,10 @@ import { canAdmin, type Repo } from "../core/repos.ts"; | ||
| 19 | 19 | import { trackPullHead, type Pull } from "../core/pulls.ts"; |
| 20 | 20 | import { commitIdentity } from "../core/commit_identity.ts"; |
| 21 | 21 | import type { User } from "../core/users.ts"; |
| 22 | import { isSafeTreePath } from "../git/guard.ts"; | |
| 22 | import { isSafeRef, isSafeTreePath } from "../git/guard.ts"; | |
| 23 | 23 | import { repoDir } from "../git/repos.ts"; |
| 24 | import { resolveOid } from "../git/merge.ts"; | |
| 25 | import { blobOidAt } from "../git/read.ts"; | |
| 24 | 26 | import { |
| 25 | 27 | commitFiles, |
| 26 | 28 | type CommitFilesError, |
| @@ -45,6 +47,12 @@ export interface EditFile { | ||
| 45 | 47 | readonly path: string; |
| 46 | 48 | /** The file's new contents, or `null` to delete it. */ |
| 47 | 49 | readonly content: string | Uint8Array | null; |
| 50 | /** | |
| 51 | * The blob the writer saw at the base when they began (`null`: no file there). Given, the edit | |
| 52 | * is refused `changed_since` when the file is not that now, so a save never silently replaces | |
| 53 | * a change made after it was opened. Absent: not asked. | |
| 54 | */ | |
| 55 | readonly was?: string | null; | |
| 48 | 56 | } |
| 49 | 57 | |
| 50 | 58 | export interface EditFilesInput { |
| @@ -79,6 +87,11 @@ export type EditFilesError = | ||
| 79 | 87 | | { kind: "protected_branch"; branch: string } |
| 80 | 88 | /** The same path named twice in one edit — which content was meant? */ |
| 81 | 89 | | { kind: "duplicate_path"; path: string } |
| 90 | /** | |
| 91 | * `path` on `branch` is not the blob the writer opened (`EditFile.was`): someone changed it | |
| 92 | * since. `now` is what is there (null: gone), so the writer can look and save over it knowingly. | |
| 93 | */ | |
| 94 | | { kind: "changed_since"; path: string; branch: string; now: string | null } | |
| 82 | 95 | /** |
| 83 | 96 | * The branch could not be made; `reason` is the branch action's own code. |
| 84 | 97 | * (Not `error`: an adapter that spreads this object next to its own |
| @@ -103,6 +116,18 @@ const sizeOf = (content: string | Uint8Array): number => | ||
| 103 | 116 | ? Buffer.byteLength(content, "utf8") |
| 104 | 117 | : content.length; |
| 105 | 118 | |
| 119 | /** | |
| 120 | * What `path` is at `ref` now: the commit the ref names and the file's blob there (`null`: no | |
| 121 | * such file), or undefined when the ref names no commit. An editor keeps the blob it opened as | |
| 122 | * `EditFile.was`, and `editFiles` reads it again here before a save (both doors, one check). | |
| 123 | */ | |
| 124 | export async function fileAt(app: App, repo: Repo, ref: string, path: string): Promise<{ readonly tip: string; readonly blob: string | null } | undefined> { | |
| 125 | if (!isSafeRef(ref) || !isSafeTreePath(path)) return undefined; | |
| 126 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 127 | const tip = (await resolveOid(dir, `refs/heads/${ref}`)) ?? (await resolveOid(dir, ref)); | |
| 128 | return tip === undefined ? undefined : { tip, blob: (await blobOidAt(dir, tip, path)) ?? null }; | |
| 129 | } | |
| 130 | ||
| 106 | 131 | /** |
| 107 | 132 | * Write files to a branch, optionally onto a fresh branch, optionally |
| 108 | 133 | * proposing them back. Every check that can be made up front is made up |
| @@ -167,6 +192,24 @@ export async function editFiles( | ||
| 167 | 192 | return err({ kind: "protected_branch", branch }); |
| 168 | 193 | } |
| 169 | 194 | |
| 195 | // A file the writer saw at some blob is still that blob, or the edit is refused before anything | |
| 196 | // is made; committing in place, the commit is then held to the tip that was read, so a change | |
| 197 | // that lands between this reading and the write refuses too (`branch_moved`). | |
| 198 | let expectTip: string | undefined; | |
| 199 | const watched = input.files.filter((f) => f.was !== undefined); | |
| 200 | const from = fresh !== "" ? base : branch; | |
| 201 | let readAt: string | undefined; | |
| 202 | for (const file of watched) { | |
| 203 | const now = await fileAt(app, repo, from, file.path); | |
| 204 | // A ref that names no commit yet (an empty repository) has nothing to compare. | |
| 205 | if (now === undefined) break; | |
| 206 | if (now.blob !== file.was) return err({ kind: "changed_since", path: file.path, branch: from, now: now.blob }); | |
| 207 | // Every file is read at one tip: a branch that moved between two readings is read again. | |
| 208 | if (readAt !== undefined && now.tip !== readAt) return err({ kind: "branch_moved" }); | |
| 209 | readAt = now.tip; | |
| 210 | if (fresh === "") expectTip = now.tip; | |
| 211 | } | |
| 212 | ||
| 170 | 213 | if (fresh !== "") { |
| 171 | 214 | const created = await createBranch(app, writer.value, repo, { |
| 172 | 215 | name: fresh, |
| @@ -192,6 +235,7 @@ export async function editFiles( | ||
| 192 | 235 | ...(branch !== base ? { startPoint: base } : {}), |
| 193 | 236 | message: input.message?.trim() || "Update files", |
| 194 | 237 | files: input.files, |
| 238 | ...(expectTip === undefined ? {} : { expectTip }), | |
| 195 | 239 | author: commitIdentity(app.config, writer.value), |
| 196 | 240 | ...(send === undefined |
| 197 | 241 | ? {} |
src/actions/edit_words.ts +10
| @@ -3,6 +3,14 @@ | ||
| 3 | 3 | * so `POST …/contents` and any other door that writes a file say the same |
| 4 | 4 | * thing for the same failure. |
| 5 | 5 | */ |
| 6 | /** | |
| 7 | * A save refused because the file changed after it was read (`changed_since`): the one sentence the | |
| 8 | * web editor and the terminal's both say. Nothing typed is lost on either. | |
| 9 | */ | |
| 10 | export function changedSinceWords(path: string, branch: string, gone: boolean): string { | |
| 11 | return `${path} ${gone ? "was removed from" : "changed on"} ${branch} since you opened it. Nothing was saved; your text is kept.`; | |
| 12 | } | |
| 13 | ||
| 6 | 14 | export function editMessage(kind: string): string { |
| 7 | 15 | switch (kind) { |
| 8 | 16 | case "storage_limit": |
| @@ -15,6 +23,8 @@ export function editMessage(kind: string): string { | ||
| 15 | 23 | return "the edit is larger than one commit may carry; push it instead"; |
| 16 | 24 | case "branch_moved": |
| 17 | 25 | return "the branch moved while this edit was being written; re-read and retry"; |
| 26 | case "changed_since": | |
| 27 | return "the file changed since it was read; read it again, then write over it knowingly"; | |
| 18 | 28 | case "land_refused": |
| 19 | 29 | return "the origin refused this commit; nothing was changed here either"; |
| 20 | 30 | case "pull_failed": |
src/git/read.ts +18
| @@ -412,6 +412,24 @@ export async function blobForRender( | ||
| 412 | 412 | return classify(body.value, size, named.value.trim()); |
| 413 | 413 | } |
| 414 | 414 | |
| 415 | /** | |
| 416 | * The blob `path` names at `rev` (a commit), or undefined when there is none there: what an | |
| 417 | * editor opened, compared with what is there now before a save replaces it. The pooled reader | |
| 418 | * answers it with no process; a reader that died falls back to one `rev-parse`. | |
| 419 | */ | |
| 420 | export async function blobOidAt(dir: string, rev: string, path: string): Promise<string | undefined> { | |
| 421 | const spec = `${rev}:${path}`; | |
| 422 | assertBatchSafe(spec); | |
| 423 | try { | |
| 424 | const stat = await readerFor(dir).stat(spec); | |
| 425 | return stat.ok && stat.value.type === "blob" ? stat.value.oid : undefined; | |
| 426 | } catch { | |
| 427 | closeReader(dir); | |
| 428 | const named = await runGit(["rev-parse", "--verify", "--quiet", `${spec}^{blob}`], { cwd: dir }); | |
| 429 | return named.ok && named.value.trim() !== "" ? named.value.trim() : undefined; | |
| 430 | } | |
| 431 | } | |
| 432 | ||
| 415 | 433 | /** |
| 416 | 434 | * `undefined` means "the pool could not answer" — never "the blob is not |
| 417 | 435 | * there". A miss the reader is sure about comes back as a real verdict, so |
src/tui/screens/commit.ts +13 −11
| @@ -23,12 +23,13 @@ | ||
| 23 | 23 | |
| 24 | 24 | import type { Repo } from "../../core/repos.ts"; |
| 25 | 25 | import type { EditFilesError } from "../../actions/contents.ts"; |
| 26 | import { changedSinceWords } from "../../actions/edit_words.ts"; | |
| 26 | 27 | import type { Result } from "../../kernel/result.ts"; |
| 27 | 28 | import type { Ctx, Screen } from "../app/app.ts"; |
| 28 | 29 | import { binding } from "../app/keys.ts"; |
| 29 | 30 | import { G } from "../term/screen.ts"; |
| 30 | 31 | import { style, BOLD } from "../term/style.ts"; |
| 31 | import { truncate } from "../term/width.ts"; | |
| 32 | import { truncate, wrap } from "../term/width.ts"; | |
| 32 | 33 | import { center, fill, len, split } from "../ui/layout.ts"; |
| 33 | 34 | import { card, input, type CursorPos, type Tone } from "../ui/widgets.ts"; |
| 34 | 35 | import { Textarea } from "../ui/textarea.ts"; |
| @@ -128,6 +129,8 @@ export function editErrorText(error: EditFilesError): string { | ||
| 128 | 129 | return `too many files (${error.count})`; |
| 129 | 130 | case "duplicate_path": |
| 130 | 131 | return `${error.path} is named twice in this edit`; |
| 132 | case "changed_since": | |
| 133 | return changedSinceWords(error.path, error.branch, error.now === null); | |
| 131 | 134 | case "path_conflict": |
| 132 | 135 | return `${error.path} collides with a file or directory already there`; |
| 133 | 136 | case "branch_failed": |
| @@ -274,10 +277,13 @@ export function commitScreen( | ||
| 274 | 277 | // empty rows under its last line reads as a card that lost something. |
| 275 | 278 | const fileRows = all.length === 0 ? 0 : 1 + Math.min(all.length, 6); |
| 276 | 279 | const tailRows = proposing ? 5 : onNewBranch ? 5 : 3; |
| 280 | // The error is wrapped, up to three lines, so a sentence that says what to do is read whole. | |
| 281 | const width = Math.min(66, area.w - 4); | |
| 282 | const errorRows = error === "" ? 1 : Math.min(3, wrap(error, Math.max(8, width - 4)).length); | |
| 277 | 283 | const r = center( |
| 278 | 284 | area, |
| 279 | Math.min(66, area.w - 4), | |
| 280 | Math.min(2 + 2 + 4 + fileRows + tailRows + 1, area.h), | |
| 285 | width, | |
| 286 | Math.min(2 + 2 + 4 + fileRows + tailRows + errorRows, area.h), | |
| 281 | 287 | ); |
| 282 | 288 | const inner = card(s, r, c, { |
| 283 | 289 | title: o.title, |
| @@ -415,14 +421,10 @@ export function commitScreen( | ||
| 415 | 421 | c.accent, |
| 416 | 422 | ); |
| 417 | 423 | } |
| 418 | if (error !== "" && y < rest!.y + rest!.h) | |
| 419 | s.text( | |
| 420 | rest!.x, | |
| 421 | y, | |
| 422 | truncate(error, rest!.w), | |
| 423 | style(c.danger, c.card), | |
| 424 | right, | |
| 425 | ); | |
| 424 | if (error !== "") | |
| 425 | for (const [i, said] of wrap(error, Math.max(8, rest!.w)).slice(0, 3).entries()) | |
| 426 | if (y + i < rest!.y + rest!.h) | |
| 427 | s.text(rest!.x, y + i, truncate(said, rest!.w), style(c.danger, c.card), right); | |
| 426 | 428 | ctx.setCursor(caret); |
| 427 | 429 | }, |
| 428 | 430 | paste(text) { |
src/tui/screens/workspace.ts +18 −3
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | * default, and on a mirror they ask the origin first. |
| 35 | 35 | */ |
| 36 | 36 | |
| 37 | import { editFiles } from "../../actions/contents.ts"; | |
| 37 | import { editFiles, fileAt } from "../../actions/contents.ts"; | |
| 38 | 38 | import { proposeEdit, proposeEditText } from "../../actions/propose_edit.ts"; |
| 39 | 39 | import { schemaRefusal } from "../../web/render/json-schema.ts"; |
| 40 | 40 | import { err, ok } from "../../kernel/result.ts"; |
| @@ -924,6 +924,8 @@ class Tab { | ||
| 924 | 924 | mode: TabMode = "view"; |
| 925 | 925 | /** A file that does not exist at this ref yet. */ |
| 926 | 926 | creating = false; |
| 927 | /** The blob the buffer was read from (`null`: none), or undefined where nothing is compared. */ | |
| 928 | opened: string | null | undefined = undefined; | |
| 927 | 929 | find: FindMode = "off"; |
| 928 | 930 | needle = ""; |
| 929 | 931 | replacement = ""; |
| @@ -1280,6 +1282,11 @@ interface CacheEntry { | ||
| 1280 | 1282 | readonly sheet: Table | null; |
| 1281 | 1283 | readonly db: Uint8Array | null; |
| 1282 | 1284 | readonly big?: { readonly prefix: Uint8Array; readonly size: number }; |
| 1285 | /** | |
| 1286 | * The blob read (`null`: none there), sent back as `EditFile.was` so a save over a newer change | |
| 1287 | * refuses. | |
| 1288 | */ | |
| 1289 | readonly opened?: string | null; | |
| 1283 | 1290 | } |
| 1284 | 1291 | |
| 1285 | 1292 | // ---- what a workspace remembers between visits ---- |
| @@ -1552,6 +1559,8 @@ export function workspaceScreen( | ||
| 1552 | 1559 | if (entry === undefined) { |
| 1553 | 1560 | t.loading = true; |
| 1554 | 1561 | ctx.invalidate(); |
| 1562 | // Read before the bytes: a change landing in between makes a save refuse, never overwrite. | |
| 1563 | const opened = repo === undefined ? undefined : (await fileAt(f.app, repo, ref, t.path))?.blob; | |
| 1555 | 1564 | const read = await src.blob(ref, t.path, { prefix: true }); |
| 1556 | 1565 | if (stale(mine)) return; |
| 1557 | 1566 | let note = ""; |
| @@ -1653,7 +1662,7 @@ export function workspaceScreen( | ||
| 1653 | 1662 | } |
| 1654 | 1663 | // A too-large file says its reason in the note; the line above the source is for the rest. |
| 1655 | 1664 | const why = read.ok && read.value.kind !== "too_large" ? (plainReason(t.path, read.value) ?? "") : ""; |
| 1656 | entry = { note, noteTitle, noteDetail, cut, why, raw, picture, sheet, db, ...(big === undefined ? {} : { big }) }; | |
| 1665 | entry = { note, noteTitle, noteDetail, cut, why, raw, picture, sheet, db, ...(big === undefined ? {} : { big }), ...(opened === undefined ? {} : { opened }) }; | |
| 1657 | 1666 | remember(key, entry); |
| 1658 | 1667 | } |
| 1659 | 1668 | if (stale(mine)) return; |
| @@ -1662,6 +1671,7 @@ export function workspaceScreen( | ||
| 1662 | 1671 | t.noteTitle = entry.noteTitle; |
| 1663 | 1672 | t.noteDetail = entry.noteDetail; |
| 1664 | 1673 | t.raw = entry.raw; |
| 1674 | t.opened = entry.opened; | |
| 1665 | 1675 | t.cut = entry.cut ?? ""; |
| 1666 | 1676 | t.why = entry.why ?? ""; |
| 1667 | 1677 | if (t.cut !== "") ctx.toast(t.cut, "attn"); |
| @@ -1881,7 +1891,12 @@ export function workspaceScreen( | ||
| 1881 | 1891 | ? {} |
| 1882 | 1892 | : { newBranch: plan.newBranch }), |
| 1883 | 1893 | message: plan.message, |
| 1884 | files: payload(plan.paths), | |
| 1894 | // Each file carries the blob it was read from: a newer change refuses the save. | |
| 1895 | files: payload(plan.paths).map((file) => { | |
| 1896 | const tab = tabs.find((t) => t.path === file.path); | |
| 1897 | const was = tab?.creating === true ? null : tab?.opened; | |
| 1898 | return was === undefined ? file : { ...file, was }; | |
| 1899 | }), | |
| 1885 | 1900 | ...(plan.pull === undefined ? {} : { openPull: plan.pull }), |
| 1886 | 1901 | }); |
| 1887 | 1902 | if (!made.ok) return err(editErrorText(made.error)); |
src/web/client.ts +77
| @@ -1231,6 +1231,83 @@ export const editorJs = /* js */ ` | ||
| 1231 | 1231 | r.addEventListener('change', syncTarget); |
| 1232 | 1232 | }); |
| 1233 | 1233 | syncTarget(); |
| 1234 | ||
| 1235 | // ---- the unsent draft ---- | |
| 1236 | // What is typed and not yet committed is kept in this browser, per file, so a reload, a crash | |
| 1237 | // or a closed tab does not lose it. Restored with one line that says so; dropped once it has | |
| 1238 | // landed (the file is no longer the blob it was opened at) or when discarded. Storage that is | |
| 1239 | // full, blocked or private only means no draft is kept: the editor works the same. | |
| 1240 | var openedInput = form && form.querySelector('input[name=opened]'); | |
| 1241 | var refInput = form && form.querySelector('input[name=ref]'); | |
| 1242 | var fixedPath = form && form.querySelector('input[type=hidden][name=path]'); | |
| 1243 | var draftKey = 'forge:draft:' + (form ? form.getAttribute('action') : '') + ':' + | |
| 1244 | (refInput ? refInput.value : '') + ':' + (fixedPath ? fixedPath.value : 'new:' + window.location.pathname); | |
| 1245 | var initial = area.value; | |
| 1246 | function readDraft() { | |
| 1247 | try { var v = JSON.parse(window.localStorage.getItem(draftKey) || 'null'); return v && typeof v.text === 'string' ? v : null; } | |
| 1248 | catch (_) { return null; } | |
| 1249 | } | |
| 1250 | function writeDraft(v) { | |
| 1251 | try { if (v === null) window.localStorage.removeItem(draftKey); else window.localStorage.setItem(draftKey, JSON.stringify(v)); } | |
| 1252 | catch (_) {} | |
| 1253 | } | |
| 1254 | var kept = readDraft(); | |
| 1255 | var opened = openedInput ? openedInput.value : ''; | |
| 1256 | if (kept && form && form.getAttribute('data-sent') === '1') { | |
| 1257 | // A refused save came back holding every word just sent: that text is the draft now. | |
| 1258 | kept = null; | |
| 1259 | } else if (kept && (kept.text === area.value || (kept.sent && kept.opened !== opened))) { | |
| 1260 | // Nothing unsaved, or it was sent and the file has moved on from where it was opened: it landed. | |
| 1261 | writeDraft(null); | |
| 1262 | kept = null; | |
| 1263 | } | |
| 1264 | if (kept) { | |
| 1265 | area.value = kept.text; | |
| 1266 | // Opened at another blob: kept, so a save refuses and shows the change made since. | |
| 1267 | if (openedInput && typeof kept.opened === 'string') openedInput.value = kept.opened; | |
| 1268 | area.dispatchEvent(new Event('input', { bubbles: true })); | |
| 1269 | var note = doc.createElement('p'); | |
| 1270 | note.className = 'muted small'; | |
| 1271 | note.id = 'editor-restored'; | |
| 1272 | note.setAttribute('role', 'status'); | |
| 1273 | var when = new Date(kept.at || Date.now()); | |
| 1274 | note.appendChild(doc.createTextNode('Restored what you typed here before (' + | |
| 1275 | when.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + '), not yet committed. ')); | |
| 1276 | var drop = doc.createElement('button'); | |
| 1277 | drop.type = 'button'; | |
| 1278 | drop.className = 'btn'; | |
| 1279 | drop.setAttribute('data-size', 'sm'); | |
| 1280 | drop.setAttribute('data-variant', 'ghost'); | |
| 1281 | drop.textContent = 'Discard it'; | |
| 1282 | drop.addEventListener('click', function () { | |
| 1283 | writeDraft(null); | |
| 1284 | area.value = initial; | |
| 1285 | if (openedInput) openedInput.value = opened; | |
| 1286 | area.dispatchEvent(new Event('input', { bubbles: true })); | |
| 1287 | note.remove(); | |
| 1288 | }); | |
| 1289 | note.appendChild(drop); | |
| 1290 | // Above the file's box, not inside it between its head and its text. | |
| 1291 | var head = doc.querySelector('.editor-head') || wrap; | |
| 1292 | if (head && head.parentNode) head.parentNode.insertBefore(note, head); | |
| 1293 | } | |
| 1294 | var saveTimer = 0; | |
| 1295 | function keep() { | |
| 1296 | window.clearTimeout(saveTimer); | |
| 1297 | saveTimer = window.setTimeout(function () { | |
| 1298 | if (area.value === initial) { writeDraft(null); return; } | |
| 1299 | writeDraft({ text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now() }); | |
| 1300 | }, 250); | |
| 1301 | } | |
| 1302 | area.addEventListener('input', keep); | |
| 1303 | if (form) form.addEventListener('submit', function () { | |
| 1304 | window.clearTimeout(saveTimer); | |
| 1305 | writeDraft({ text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now(), sent: true }); | |
| 1306 | }); | |
| 1307 | // A tab put away or closed keeps the last keystrokes too, not only those before the pause. | |
| 1308 | window.addEventListener('pagehide', function () { | |
| 1309 | if (area.value !== initial && !(readDraft() || {}).sent) writeDraft({ text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now() }); | |
| 1310 | }); | |
| 1234 | 1311 | })(); |
| 1235 | 1312 | `; |
| 1236 | 1313 |
src/web/pages/edit.ts +113 −7
| @@ -19,12 +19,13 @@ | ||
| 19 | 19 | |
| 20 | 20 | import { binaryRefusal } from "../render/opens_with.ts"; |
| 21 | 21 | import { fileKind, NO_BYTES } from "../render/kinds.ts"; |
| 22 | import { editFiles, MAX_FILE_BYTES } from "../../actions/contents.ts"; | |
| 22 | import { editFiles, fileAt, MAX_FILE_BYTES } from "../../actions/contents.ts"; | |
| 23 | 23 | import { editMesh, type MeshForm } from "../../actions/mesh_edit.ts"; |
| 24 | 24 | import { sizeText } from "../render/mesh.ts"; |
| 25 | 25 | import { shiftSubtitles } from "../../actions/subtitle_shift.ts"; |
| 26 | 26 | import { contribute } from "../../actions/contribute.ts"; |
| 27 | 27 | import { NO_WRITE_ACCESS } from "../../actions/pull_words.ts"; |
| 28 | import { changedSinceWords } from "../../actions/edit_words.ts"; | |
| 28 | 29 | import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts"; |
| 29 | 30 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| 30 | 31 | import { isSafeRef, isSafeTreePath } from "../../git/guard.ts"; |
| @@ -76,8 +77,48 @@ export interface Draft { | ||
| 76 | 77 | * allowed, branch moved) and is the page's flash. |
| 77 | 78 | */ |
| 78 | 79 | errorOn?: "path" | "message" | "branch"; |
| 80 | /** One link after a form-level error: where to see what the refusal is about. */ | |
| 81 | errorLink?: { href: string; label: string }; | |
| 82 | /** | |
| 83 | * The blob this editor opened (`""`: a new file, none there), sent back so a save refuses when | |
| 84 | * the file changed since. Absent where it is not asked (a contribution lands on a fork). | |
| 85 | */ | |
| 86 | opened?: string; | |
| 87 | /** The file's own line endings: a save keeps them, whatever the browser sends (`asTyped`). */ | |
| 88 | eol?: Eol; | |
| 89 | /** | |
| 90 | * After a `changed_since` refusal: the blob there now (`""`: the file is gone). Offered on its | |
| 91 | * own button, "Replace their change with mine"; plain Commit still sends `opened` and keeps | |
| 92 | * refusing, so nobody's change is replaced by a habit. | |
| 93 | */ | |
| 94 | replaceWith?: string; | |
| 79 | 95 | } |
| 80 | 96 | |
| 97 | /** How a file ends its lines. */ | |
| 98 | export type Eol = "lf" | "crlf"; | |
| 99 | ||
| 100 | /** | |
| 101 | * A file's line endings, by what most of its lines end in: an editor saves in the same. A file | |
| 102 | * with no line break, or more bare LF than CRLF, is `lf`. | |
| 103 | */ | |
| 104 | export function eolOf(content: string): Eol { | |
| 105 | const crlf = content.split("\r\n").length - 1; | |
| 106 | const lf = content.split("\n").length - 1 - crlf; | |
| 107 | return crlf > lf ? "crlf" : "lf"; | |
| 108 | } | |
| 109 | ||
| 110 | /** | |
| 111 | * What the person typed, in the file's own endings. A form sends a textarea's line breaks as | |
| 112 | * CRLF whatever the file had (the HTML form encoding), so without this a one-line edit of an LF | |
| 113 | * file rewrote every line. | |
| 114 | */ | |
| 115 | export function asTyped(content: string, eol: Eol): string { | |
| 116 | const lf = content.replace(/\r\n/g, "\n"); | |
| 117 | return eol === "crlf" ? lf.replace(/\n/g, "\r\n") : lf; | |
| 118 | } | |
| 119 | ||
| 120 | const eolField = (form: Form): Eol => (formValue(form, "eol") === "crlf" ? "crlf" : "lf"); | |
| 121 | ||
| 81 | 122 | /** |
| 82 | 123 | * Where the live-highlighted editor gives up and hands you a plain textarea. |
| 83 | 124 | * |
| @@ -119,6 +160,9 @@ export function suggestBranch(username: string, path: string): string { | ||
| 119 | 160 | return `${username}/edit-${leaf === "" ? "file" : leaf}`; |
| 120 | 161 | } |
| 121 | 162 | |
| 163 | /** Replace pressed without the box ticked: nothing replaced, nothing typed lost. */ | |
| 164 | export const REPLACE_ASKS = "Nothing was saved; tick the box to replace their change with yours."; | |
| 165 | ||
| 122 | 166 | /** The words for a refused edit. Every branch of the union gets one. */ |
| 123 | 167 | export function editErrorText(error: unknown): string { |
| 124 | 168 | if (typeof error === "string") { |
| @@ -157,6 +201,10 @@ export function editErrorText(error: unknown): string { | ||
| 157 | 201 | : `That branch could not be created: ${e.message}`; |
| 158 | 202 | case "branch_moved": |
| 159 | 203 | return "The branch moved while you were editing. Open it again and reapply your change."; |
| 204 | case "changed_since": { | |
| 205 | const c = error as { path: string; branch: string; now: string | null }; | |
| 206 | return changedSinceWords(c.path, c.branch, c.now === null); | |
| 207 | } | |
| 160 | 208 | case "land_refused": |
| 161 | 209 | return e.message ?? "The origin refused this change."; |
| 162 | 210 | case "pull_failed": |
| @@ -188,8 +236,11 @@ function editorForm( | ||
| 188 | 236 | method="post" |
| 189 | 237 | action="${draft.propose?.action ?? `${base}/edit`}" |
| 190 | 238 | class="editor-form" |
| 239 | ${draft.error === undefined ? null : raw('data-sent="1"')} | |
| 191 | 240 | > |
| 192 | 241 | <input type="hidden" name="ref" value="${draft.ref}" /> |
| 242 | <input type="hidden" name="eol" value="${draft.eol ?? "lf"}" /> | |
| 243 | ${draft.opened === undefined ? null : html`<input type="hidden" name="opened" value="${draft.opened}" />`} | |
| 193 | 244 | ${draft.creating |
| 194 | 245 | ? raw('<input type="hidden" name="creating" value="1" />') |
| 195 | 246 | : html`<input type="hidden" name="path" value="${draft.path}" />`} |
| @@ -324,6 +375,12 @@ ${draft.content}</textarea | ||
| 324 | 375 | ${draft.propose !== undefined |
| 325 | 376 | ? proposeBlock(draft, draft.propose, suggestion) |
| 326 | 377 | : landingBlock(draft, suggestion)} |
| 378 | ${draft.replaceWith === undefined | |
Non-blocking, principle 3: this checkbox repeats what the labelled Replace button already says. Keep one guard. |
||
| 379 | ? null | |
| 380 | : html`<label class="check"> | |
| 381 | <input type="checkbox" name="confirm" value="replace" /> | |
| 382 | <span>I have seen their change, and mine should replace it</span> | |
| 383 | </label>`} | |
| 327 | 384 | <div class="form-actions"> |
| 328 | 385 | ${btn( |
| 329 | 386 | draft.propose !== undefined |
| @@ -333,6 +390,9 @@ ${draft.content}</textarea | ||
| 333 | 390 | : "Commit change", |
| 334 | 391 | { variant: "primary" }, |
| 335 | 392 | )} |
| 393 | ${draft.replaceWith === undefined | |
| 394 | ? null | |
| 395 | : btn("Replace their change with mine", { type: "submit", name: "replace", value: draft.replaceWith, variant: "secondary" })} | |
| 336 | 396 | ${btn("Cancel", { |
| 337 | 397 | href: draft.creating |
| 338 | 398 | ? `${base}/tree/${encoded}` |
| @@ -528,7 +588,7 @@ export async function editorPage( | ||
| 528 | 588 | return page({ |
| 529 | 589 | ctx, |
| 530 | 590 | ...(formLevel !== undefined |
| 531 | ? { flash: { tone: "danger" as const, message: formLevel } } | |
| 591 | ? { flash: { tone: "danger" as const, message: formLevel, ...(draft.errorLink === undefined ? {} : { link: draft.errorLink }) } } | |
| 532 | 592 | : {}), |
| 533 | 593 | title: `${draft.creating ? "New file" : draft.path} · ${scope.facts.name}`, |
| 534 | 594 | crumbs: scope.crumbs, |
| @@ -635,11 +695,13 @@ export async function editPage(ctx: Ctx): Promise<Response> { | ||
| 635 | 695 | ); |
| 636 | 696 | } |
| 637 | 697 | const content = new TextDecoder().decode(blob.value.body); |
| 698 | const opened = await openedBlob(ctx, scope, ref, path); | |
| 638 | 699 | const draft = await timePhaseAsync(ctx.request, "refs", () => |
| 639 | 700 | blankDraft(ctx, scope, ref, { |
| 640 | 701 | path, |
| 641 | 702 | content, |
| 642 | 703 | creating: false, |
| 704 | ...(opened === undefined ? {} : { opened }), | |
| 643 | 705 | }), |
| 644 | 706 | ); |
| 645 | 707 | return await timePhaseAsync(ctx.request, "render", () => |
| @@ -647,6 +709,16 @@ export async function editPage(ctx: Ctx): Promise<Response> { | ||
| 647 | 709 | ); |
| 648 | 710 | } |
| 649 | 711 | |
| 712 | /** | |
| 713 | * The blob `path` is at `ref` in this forge's own repository (`""`: no file there), or undefined | |
| 714 | * where the editor writes elsewhere (a contribution) and nothing is compared. | |
| 715 | */ | |
| 716 | async function openedBlob(ctx: Ctx, scope: RepoScope, ref: string, path: string): Promise<string | undefined> { | |
| 717 | const repo = scope.repo; | |
| 718 | if (repo === undefined || scope.propose !== undefined) return undefined; | |
| 719 | return (await fileAt(ctx.app, repo, ref, path))?.blob ?? ""; | |
| 720 | } | |
| 721 | ||
| 650 | 722 | /** |
| 651 | 723 | * A fresh draft for this repository, this ref and this file — with the |
| 652 | 724 | * propose/commit decision already made, so every page and every refusal |
| @@ -656,7 +728,7 @@ export async function blankDraft( | ||
| 656 | 728 | ctx: Ctx, |
| 657 | 729 | scope: RepoScope, |
| 658 | 730 | ref: string, |
| 659 | o: { path: string; content: string; creating: boolean }, | |
| 731 | o: { path: string; content: string; creating: boolean; opened?: string }, | |
| 660 | 732 | ): Promise<Draft> { |
| 661 | 733 | const propose = scope.propose; |
| 662 | 734 | // A contribution always branches: there is nothing here to commit onto. |
| @@ -678,6 +750,9 @@ export async function blankDraft( | ||
| 678 | 750 | pullBody: "", |
| 679 | 751 | creating: o.creating, |
| 680 | 752 | mustBranch, |
| 753 | eol: eolOf(o.content), | |
| 754 | // A new file was opened at nothing: one that appears meanwhile is not overwritten unseen. | |
| 755 | ...(propose !== undefined ? {} : o.opened !== undefined ? { opened: o.opened } : o.creating ? { opened: "" } : {}), | |
| 681 | 756 | ...(propose === undefined ? {} : { propose }), |
| 682 | 757 | }; |
| 683 | 758 | } |
| @@ -736,7 +811,8 @@ function proposeDraft(form: Form, propose: ProposeTarget): Draft { | ||
| 736 | 811 | return { |
| 737 | 812 | ref: formValue(form, "ref"), |
| 738 | 813 | path: formValue(form, "path").trim().replace(/^\/+/, ""), |
| 739 | content: formValue(form, "content"), | |
| 814 | content: asTyped(formValue(form, "content"), eolField(form)), | |
| 815 | eol: eolField(form), | |
| 740 | 816 | subject: formValue(form, "message").trim(), |
| 741 | 817 | body: formValue(form, "description").trim(), |
| 742 | 818 | target: "new", |
| @@ -952,7 +1028,16 @@ export async function editSubmit(ctx: Ctx): Promise<Response> { | ||
| 952 | 1028 | |
| 953 | 1029 | const ref = formValue(form, "ref"); |
| 954 | 1030 | const path = formValue(form, "path").trim().replace(/^\/+/, ""); |
| 955 | const content = formValue(form, "content"); | |
| 1031 | const eol = eolField(form); | |
| 1032 | const content = asTyped(formValue(form, "content"), eol); | |
| 1033 | // Sent by every editor this forge renders; a form without it (an older page) is not compared. | |
| 1034 | const opened = form.has("opened") ? formValue(form, "opened") : undefined; | |
| 1035 | // The deliberate way past a newer change: the blob the person saw it replaced with, on its own | |
| 1036 | // button. Plain Commit sends only `opened`. | |
| 1037 | const replace = form.has("replace") ? formValue(form, "replace") : undefined; | |
| 1038 | // Replacing someone's change asks first: the box beside the button, ticked (`confirm`). | |
| 1039 | const replacing = replace !== undefined && formValue(form, "confirm") === "replace"; | |
| 1040 | const was = replacing ? replace : opened; | |
| 956 | 1041 | const subject = formValue(form, "message").trim(); |
| 957 | 1042 | const description = formValue(form, "description").trim(); |
| 958 | 1043 | const target = formValue(form, "target") === "new" ? "new" : "current"; |
| @@ -976,6 +1061,8 @@ export async function editSubmit(ctx: Ctx): Promise<Response> { | ||
| 976 | 1061 | pullBody, |
| 977 | 1062 | creating, |
| 978 | 1063 | mustBranch, |
| 1064 | eol, | |
| 1065 | ...(opened === undefined ? {} : { opened }), | |
| 979 | 1066 | }; |
| 980 | 1067 | const refuse = ( |
| 981 | 1068 | message: string, |
| @@ -991,13 +1078,20 @@ export async function editSubmit(ctx: Ctx): Promise<Response> { | ||
| 991 | 1078 | if (path === "" || !isSafeTreePath(path)) |
| 992 | 1079 | return refuse("Give the file a path this repository can hold.", "path"); |
| 993 | 1080 | if (subject === "") return refuse("A commit needs a message.", "message"); |
| 1081 | if (replace !== undefined && !replacing) | |
| 1082 | return editorPage(ctx, scope, { | |
| 1083 | ...draft, | |
| 1084 | replaceWith: replace, | |
| 1085 | error: REPLACE_ASKS, | |
| 1086 | errorLink: { href: `${scope.base}/commits?ref=${encodeURIComponent(ref)}&path=${encodeURIComponent(path)}`, label: "See what changed" }, | |
| 1087 | }); | |
| 994 | 1088 | |
| 995 | 1089 | const message = description === "" ? subject : `${subject}\n\n${description}`; |
| 996 | 1090 | const written = await editFiles(ctx.app, ctx.auth.user, repo, { |
| 997 | 1091 | branch: ref, |
| 998 | 1092 | base: ref, |
| 999 | 1093 | message, |
| 1000 | files: [{ path, content }], | |
| 1094 | files: [{ path, content, ...(was === undefined ? {} : { was: was === "" ? null : was }) }], | |
| 1001 | 1095 | ...(target === "new" ? { newBranch: branch } : {}), |
| 1002 | 1096 | ...(pull |
| 1003 | 1097 | ? { |
| @@ -1008,7 +1102,19 @@ export async function editSubmit(ctx: Ctx): Promise<Response> { | ||
| 1008 | 1102 | } |
| 1009 | 1103 | : {}), |
| 1010 | 1104 | }); |
| 1011 | if (!written.ok) return refuse(editErrorText(written.error)); | |
| 1105 | if (!written.ok) { | |
| 1106 | const e = written.error; | |
| 1107 | // Changed since it was opened: the person's text stays in the editor and they are shown the | |
| 1108 | // other change. Commit keeps refusing; only "Replace their change with mine" writes over it. | |
| 1109 | if (typeof e === "object" && e.kind === "changed_since") | |
| 1110 | return editorPage(ctx, scope, { | |
| 1111 | ...draft, | |
| 1112 | replaceWith: e.now ?? "", | |
| 1113 | error: editErrorText(e), | |
| 1114 | errorLink: { href: `${scope.base}/commits?ref=${encodeURIComponent(e.branch)}&path=${encodeURIComponent(e.path)}`, label: "See what changed" }, | |
| 1115 | }); | |
| 1116 | return refuse(editErrorText(e)); | |
| 1117 | } | |
| 1012 | 1118 | |
| 1013 | 1119 | const landed = written.value; |
| 1014 | 1120 | if (landed.pull !== undefined) { |
test/tui-editor.test.ts +37
| @@ -335,6 +335,43 @@ describe("editing a file in the terminal workspace", () => { | ||
| 335 | 335 | } |
| 336 | 336 | }); |
| 337 | 337 | |
| 338 | test("a save over a change made since the file was read is refused in the web's words, the buffer kept", async () => { | |
| 339 | const h = boot(); | |
| 340 | try { | |
| 341 | await h.settle(); | |
| 342 | await openEditorOn(h, "README"); | |
| 343 | expect(h.text()).toContain("# Workshop"); | |
| 344 | await h.press("end"); | |
| 345 | await h.type(" from the terminal"); | |
| 346 | // Someone else changes the file on main while it is open here. | |
| 347 | await commitToBranch(forge, alice, getRepo(forge.db, "alice", "workshop")!, { | |
| 348 | message: "meanwhile", | |
| 349 | files: [{ path: "README.md", content: "# Workshop, renamed elsewhere\n" }], | |
| 350 | }); | |
| 351 | await h.press("ctrl+s"); | |
| 352 | await h.settle(); | |
| 353 | expect(h.text()).toContain("Commit README.md"); | |
| 354 | await h.press("ctrl+s"); | |
| 355 | await h.until("since you opened it"); | |
| 356 | // The commit box wraps it; the words are the web editor's (`changedSinceWords`). | |
| 357 | expect(h.text().replace(/[\s│]+/g, " ")).toContain("README.md changed on main since you opened it. Nothing was saved; your text is kept."); | |
| 358 | // Nothing was written anywhere, and the other change stands. | |
| 359 | const dir = join(forge.reposRoot, "alice", "workshop.git"); | |
| 360 | const onMain = await blobForRender(dir, "main", "README.md", 1 << 20); | |
| 361 | if (onMain.kind === "text") expect(text(onMain.body)).toBe("# Workshop, renamed elsewhere\n"); | |
| 362 | const branch = await blobForRender(dir, "alice/edit-readme-md", "README.md", 1 << 20); | |
| 363 | expect(branch.kind).toBe("missing"); | |
| 364 | // The typed words are still in the buffer. | |
| 365 | await h.press("escape"); | |
| 366 | await h.settle(); | |
| 367 | expect(h.text()).toContain("from the terminal"); | |
| 368 | } finally { | |
| 369 | h.stop(); | |
| 370 | // The other tests read the seeded README: put it back. | |
| 371 | await commitToBranch(forge, alice, getRepo(forge.db, "alice", "workshop")!, { message: "restore", files: [{ path: "README.md", content: "# Workshop\n" }] }); | |
| 372 | } | |
| 373 | }); | |
| 374 | ||
| 338 | 375 | /** |
| 339 | 376 | * `esc` is not "throw it away" any more, because the buffer is not a screen |
| 340 | 377 | * any more: it stops typing and goes back to reading the same tab, edits |
test/web-editor-integrity.test.ts added +452
| @@ -0,0 +1,452 @@ | ||
| 1 | /** | |
| 2 | * The in-browser editor keeps what it is given (#16420): a save keeps the file's own line endings | |
| 3 | * (a form sends a textarea's breaks as CRLF), a save over a change made since the file was opened | |
| 4 | * is refused in one sentence with the other change linked and the typed text kept, and what is | |
| 5 | * typed and not committed survives a reload in this browser's storage. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { getRepo } from "../src/core/repos.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { localSource } from "../src/view/local.ts"; | |
| 18 | import { editorJs } from "../src/web/client.ts"; | |
| 19 | import { asTyped, eolOf } from "../src/web/pages/edit.ts"; | |
| 20 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | ||
| 23 | quietLogs(); | |
| 24 | ||
| 25 | let dataDir: string; | |
| 26 | let app: App; | |
| 27 | let servers: Servers; | |
| 28 | let cookie = ""; | |
| 29 | ||
| 30 | const fileAt = async (path: string): Promise<string | undefined> => { | |
| 31 | const repo = getRepo(app.db, "alice", "lamp")!; | |
| 32 | const blob = await localSource(app, repo, undefined).blob("main", path); | |
| 33 | if (!blob.ok || blob.value.kind !== "text") return undefined; | |
| 34 | return new TextDecoder().decode(blob.value.body); | |
| 35 | }; | |
| 36 | ||
| 37 | /** The editor page's hidden fields, as a browser would send them back. */ | |
| 38 | const opened = async ( | |
| 39 | path: string, | |
| 40 | ): Promise<{ opened: string; eol: string }> => { | |
| 41 | const page = await ( | |
| 42 | await fetch(`${servers.url}/alice/lamp/edit/main/${path}`, { | |
| 43 | headers: { cookie }, | |
| 44 | }) | |
| 45 | ).text(); | |
| 46 | return { | |
| 47 | opened: /name="opened" value="([^"]*)"/.exec(page)?.[1] ?? "missing", | |
| 48 | eol: /name="eol" value="([^"]*)"/.exec(page)?.[1] ?? "missing", | |
| 49 | }; | |
| 50 | }; | |
| 51 | ||
| 52 | const save = (fields: Record<string, string>) => | |
| 53 | fetch(`${servers.url}/alice/lamp/edit`, { | |
| 54 | method: "POST", | |
| 55 | headers: { cookie, origin: new URL(servers.url).origin }, | |
| 56 | body: new URLSearchParams({ | |
| 57 | ref: "main", | |
| 58 | message: "Edit", | |
| 59 | description: "", | |
| 60 | target: "current", | |
| 61 | branch: "", | |
| 62 | ...fields, | |
| 63 | }), | |
| 64 | redirect: "manual", | |
| 65 | }); | |
| 66 | ||
| 67 | beforeAll(async () => { | |
| 68 | dataDir = await mkdtemp(join(tmpdir(), "forge-editor-integrity-")); | |
| 69 | app = createApp({ dataDir, port: 0 }); | |
| 70 | servers = await serve(app); | |
| 71 | const a = await seedAdmin(app, { | |
| 72 | username: "alice", | |
| 73 | email: "[email protected]", | |
| 74 | password: "a-long-editor-passphrase", | |
| 75 | }); | |
| 76 | if (!a.ok) throw new Error("admin"); | |
| 77 | cookie = `forge_session=${createSession(app.db, a.value.id).token}`; | |
| 78 | const made = await createRepo(app, a.value, { | |
| 79 | name: "lamp", | |
| 80 | visibility: "public", | |
| 81 | }); | |
| 82 | if (!made.ok) throw new Error("repo"); | |
| 83 | await commitToBranch(app, a.value, made.value, { | |
| 84 | message: "first", | |
| 85 | files: [ | |
| 86 | { path: "README.md", content: "# lamp\none\ntwo\nthree\n" }, | |
| 87 | { path: "win.txt", content: "a\r\nb\r\nc\r\n" }, | |
| 88 | { path: "notes.md", content: "first line\n" }, | |
| 89 | ], | |
| 90 | }); | |
| 91 | }); | |
| 92 | ||
| 93 | afterAll(async () => { | |
| 94 | servers.stop(); | |
| 95 | app.close(); | |
| 96 | await rm(dataDir, { recursive: true, force: true }); | |
| 97 | }); | |
| 98 | ||
| 99 | describe("a save keeps the file's own line endings", () => { | |
| 100 | test("a one-line edit of an LF file, sent with the CRLF a form sends, changes one line", async () => { | |
| 101 | const { opened: was, eol } = await opened("README.md"); | |
| 102 | expect(eol).toBe("lf"); | |
| 103 | const res = await save({ | |
| 104 | path: "README.md", | |
| 105 | opened: was, | |
| 106 | eol, | |
| 107 | content: "# lamp\r\none\r\nTWO\r\nthree\r\n", | |
| 108 | }); | |
| 109 | expect(res.status).toBe(303); | |
| 110 | expect(await fileAt("README.md")).toBe("# lamp\none\nTWO\nthree\n"); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a CRLF file stays CRLF, whether the browser sent CRLF or LF", async () => { | |
| 114 | const first = await opened("win.txt"); | |
| 115 | expect(first.eol).toBe("crlf"); | |
| 116 | expect( | |
| 117 | ( | |
| 118 | await save({ | |
| 119 | path: "win.txt", | |
| 120 | opened: first.opened, | |
| 121 | eol: first.eol, | |
| 122 | content: "a\r\nB\r\nc\r\n", | |
| 123 | }) | |
| 124 | ).status, | |
| 125 | ).toBe(303); | |
| 126 | expect(await fileAt("win.txt")).toBe("a\r\nB\r\nc\r\n"); | |
| 127 | const second = await opened("win.txt"); | |
| 128 | expect( | |
| 129 | ( | |
| 130 | await save({ | |
| 131 | path: "win.txt", | |
| 132 | opened: second.opened, | |
| 133 | eol: second.eol, | |
| 134 | content: "a\nB\nC\n", | |
| 135 | }) | |
| 136 | ).status, | |
| 137 | ).toBe(303); | |
| 138 | expect(await fileAt("win.txt")).toBe("a\r\nB\r\nC\r\n"); | |
| 139 | }); | |
| 140 | ||
| 141 | test("a file's endings are what most of its lines end in", () => { | |
| 142 | expect(eolOf("x")).toBe("lf"); | |
| 143 | expect(eolOf("a\r\nb\r\nc\n")).toBe("crlf"); | |
| 144 | expect(eolOf("a\nb\nc\r\n")).toBe("lf"); | |
| 145 | expect(asTyped("a\r\nb\n", "lf")).toBe("a\nb\n"); | |
| 146 | expect(asTyped("a\r\nb\n", "crlf")).toBe("a\r\nb\r\n"); | |
| 147 | }); | |
| 148 | }); | |
| 149 | ||
| 150 | describe("a save over a change made since the file was opened", () => { | |
| 151 | test("two tabs: the later save is refused in one sentence, keeps its text, links the other change, then saves knowingly", async () => { | |
| 152 | const tabA = await opened("notes.md"); | |
| 153 | const tabB = await opened("notes.md"); | |
| 154 | expect(tabA.opened).toMatch(/^[0-9a-f]{40}$/); | |
| 155 | expect( | |
| 156 | ( | |
| 157 | await save({ | |
| 158 | path: "notes.md", | |
| 159 | opened: tabA.opened, | |
| 160 | eol: "lf", | |
| 161 | content: "from tab A\n", | |
| 162 | }) | |
| 163 | ).status, | |
| 164 | ).toBe(303); | |
| 165 | ||
| 166 | const refused = await save({ | |
| 167 | path: "notes.md", | |
| 168 | opened: tabB.opened, | |
| 169 | eol: "lf", | |
| 170 | content: "from tab B\n", | |
| 171 | }); | |
| 172 | expect(refused.status).toBe(200); | |
| 173 | const page = await refused.text(); | |
| 174 | expect(page).toContain( | |
| 175 | "notes.md changed on main since you opened it. Nothing was saved; your text is kept.", | |
| 176 | ); | |
| 177 | expect(page).toContain("See what changed"); | |
| 178 | expect(page).toContain("/alice/lamp/commits?ref=main&path=notes.md"); | |
| 179 | // Every typed word is still in the editor. | |
| 180 | expect(page).toContain("from tab B"); | |
| 181 | expect(await fileAt("notes.md")).toBe("from tab A\n"); | |
| 182 | ||
| 183 | // Plain Commit, sent again from the refused page, still refuses: nobody's change goes by habit. | |
| 184 | expect(page).toContain(`name="opened" value="${tabB.opened}"`); | |
| 185 | const again = await save({ path: "notes.md", opened: tabB.opened, eol: "lf", content: "from tab B\n" }); | |
| 186 | expect(again.status).toBe(200); | |
| 187 | expect(await again.text()).toContain("from tab B"); | |
| 188 | expect(await fileAt("notes.md")).toBe("from tab A\n"); | |
| 189 | ||
| 190 | // The button that says what it does sends the blob that is there now, and replaces it. | |
| 191 | const now = /name="replace"\s+value="([0-9a-f]{40})"/.exec(page)?.[1] ?? ""; | |
| 192 | expect(page).toContain("Replace their change with mine"); | |
| 193 | expect(page).toContain('name="confirm" value="replace"'); | |
| 194 | // Replace without the box ticked asks instead: nothing replaced, the text kept. | |
| 195 | const unasked = await save({ path: "notes.md", opened: tabB.opened, replace: now, eol: "lf", content: "from tab B\n" }); | |
| 196 | expect(unasked.status).toBe(200); | |
| 197 | const asked = await unasked.text(); | |
| 198 | expect(asked).toContain("tick the box to replace their change with yours"); | |
| 199 | expect(asked).toContain("from tab B"); | |
| 200 | expect(await fileAt("notes.md")).toBe("from tab A\n"); | |
| 201 | expect(now).not.toBe(tabB.opened); | |
| 202 | expect((await save({ path: "notes.md", opened: tabB.opened, replace: now, confirm: "replace", eol: "lf", content: "from tab B\n" })).status).toBe(303); | |
| 203 | expect(await fileAt("notes.md")).toBe("from tab B\n"); | |
| 204 | }); | |
| 205 | ||
| 206 | test("Replace with a blob that is no longer there refuses too: a third change is not replaced unseen", async () => { | |
| 207 | const seen = await opened("notes.md"); | |
| 208 | expect((await save({ path: "notes.md", opened: seen.opened, eol: "lf", content: "third\n" })).status).toBe(303); | |
| 209 | const stale = await save({ path: "notes.md", opened: seen.opened, replace: seen.opened, confirm: "replace", eol: "lf", content: "mine\n" }); | |
| 210 | expect(stale.status).toBe(200); | |
| 211 | expect(await stale.text()).toContain("mine"); | |
| 212 | expect(await fileAt("notes.md")).toBe("third\n"); | |
| 213 | }); | |
| 214 | ||
| 215 | test("a new file is not written over one that appeared meanwhile", async () => { | |
| 216 | const res = await save({ | |
| 217 | path: "notes.md", | |
| 218 | creating: "1", | |
| 219 | opened: "", | |
| 220 | eol: "lf", | |
| 221 | content: "a stranger's notes\n", | |
| 222 | }); | |
| 223 | expect(res.status).toBe(200); | |
| 224 | expect(await res.text()).toContain("changed on main since you opened it"); | |
| 225 | expect(await fileAt("notes.md")).toBe("third\n"); | |
| 226 | }); | |
| 227 | }); | |
| 228 | ||
| 229 | /** | |
| 230 | * Just enough of a page for the editor script's draft: one form, one textarea, real storage rules. | |
| 231 | */ | |
| 232 | function editorDom(o: { | |
| 233 | value: string; | |
| 234 | opened: string; | |
| 235 | sent?: boolean; | |
| 236 | storage: Map<string, string> | "blocked"; | |
| 237 | }) { | |
| 238 | type Listener = (e: { type: string }) => void; | |
| 239 | class El { | |
| 240 | listeners = new Map<string, Listener[]>(); | |
| 241 | attrs = new Map<string, string>(); | |
| 242 | kids: El[] = []; | |
| 243 | value = ""; | |
| 244 | text = ""; | |
| 245 | parentNode: El | null = null; | |
| 246 | id = ""; | |
| 247 | className = ""; | |
| 248 | type = ""; | |
| 249 | childElementCount = 0; | |
| 250 | addEventListener(t: string, f: Listener) { | |
| 251 | this.listeners.set(t, [...(this.listeners.get(t) ?? []), f]); | |
| 252 | } | |
| 253 | dispatchEvent(e: { type: string }) { | |
| 254 | for (const f of this.listeners.get(e.type) ?? []) f(e); | |
| 255 | return true; | |
| 256 | } | |
| 257 | getAttribute(n: string) { | |
| 258 | return this.attrs.get(n) ?? null; | |
| 259 | } | |
| 260 | setAttribute(n: string, v: string) { | |
| 261 | this.attrs.set(n, v); | |
| 262 | } | |
| 263 | removeAttribute(n: string) { | |
| 264 | this.attrs.delete(n); | |
| 265 | } | |
| 266 | appendChild(c: El | { t: string }) { | |
| 267 | if (c instanceof El) this.kids.push(c); | |
| 268 | else this.text += c.t; | |
| 269 | return c; | |
| 270 | } | |
| 271 | insertBefore(c: El) { | |
| 272 | c.parentNode = this; | |
| 273 | this.kids.unshift(c); | |
| 274 | return c; | |
| 275 | } | |
| 276 | remove() { | |
| 277 | if (this.parentNode) | |
| 278 | this.parentNode.kids = this.parentNode.kids.filter((k) => k !== this); | |
| 279 | } | |
| 280 | set textContent(v: string) { | |
| 281 | this.text = v; | |
| 282 | } | |
| 283 | get textContent() { | |
| 284 | return this.text + this.kids.map((k) => k.textContent).join(""); | |
| 285 | } | |
| 286 | } | |
| 287 | const form = new El(); | |
| 288 | form.attrs.set("action", "/alice/lamp/edit"); | |
| 289 | if (o.sent) form.attrs.set("data-sent", "1"); | |
| 290 | const fields: Record<string, El> = {}; | |
| 291 | for (const [name, value] of [ | |
| 292 | ["opened", o.opened], | |
| 293 | ["ref", "main"], | |
| 294 | ["path", "notes.md"], | |
| 295 | ] as const) { | |
| 296 | const input = new El(); | |
| 297 | input.value = value; | |
| 298 | fields[name] = input; | |
| 299 | } | |
| 300 | ( | |
| 301 | form as unknown as { querySelector: (s: string) => El | null } | |
| 302 | ).querySelector = (s: string) => | |
| 303 | s.includes("opened") | |
| 304 | ? fields["opened"]! | |
| 305 | : s.includes("name=ref") | |
| 306 | ? fields["ref"]! | |
| 307 | : s.includes("name=path") | |
| 308 | ? fields["path"]! | |
| 309 | : null; | |
| 310 | const area = new El(); | |
| 311 | area.value = o.value; | |
| 312 | (area as unknown as { form: El }).form = form; | |
| 313 | const holder = new El(); | |
| 314 | const wrap = new El(); | |
| 315 | wrap.parentNode = holder; | |
| 316 | const doc = { | |
| 317 | readyState: "complete", | |
| 318 | activeElement: null, | |
| 319 | querySelector: (s: string) => (s === "textarea.editor" ? area : null), | |
| 320 | querySelectorAll: () => [], | |
| 321 | getElementById: (id: string) => (id === "editor-write" ? wrap : null), | |
| 322 | addEventListener: () => {}, | |
| 323 | createElement: () => new El(), | |
| 324 | createDocumentFragment: () => new El(), | |
| 325 | createTextNode: (t: string) => ({ t }), | |
| 326 | }; | |
| 327 | const timers: (() => void)[] = []; | |
| 328 | const winListeners = new Map<string, () => void>(); | |
| 329 | const localStorage = { | |
| 330 | getItem: (k: string) => { | |
| 331 | if (o.storage === "blocked") throw new Error("SecurityError"); | |
| 332 | return o.storage.get(k) ?? null; | |
| 333 | }, | |
| 334 | setItem: (k: string, v: string) => { | |
| 335 | if (o.storage === "blocked") throw new Error("SecurityError"); | |
| 336 | o.storage.set(k, v); | |
| 337 | }, | |
| 338 | removeItem: (k: string) => { | |
| 339 | if (o.storage === "blocked") throw new Error("SecurityError"); | |
| 340 | o.storage.delete(k); | |
| 341 | }, | |
| 342 | }; | |
| 343 | const win = { | |
| 344 | localStorage, | |
| 345 | location: { pathname: "/alice/lamp/edit/main/notes.md" }, | |
| 346 | setTimeout: (f: () => void) => timers.push(f), | |
| 347 | clearTimeout: () => {}, | |
| 348 | requestAnimationFrame: () => 0, | |
| 349 | cancelAnimationFrame: () => {}, | |
| 350 | addEventListener: (t: string, f: () => void) => winListeners.set(t, f), | |
| 351 | }; | |
| 352 | new Function("document", "window", "Event", editorJs)( | |
| 353 | doc, | |
| 354 | win, | |
| 355 | class { | |
| 356 | constructor(public type: string) {} | |
| 357 | }, | |
| 358 | ); | |
| 359 | return { | |
| 360 | area, | |
| 361 | form, | |
| 362 | opened: fields["opened"]!, | |
| 363 | note: () => holder.kids.find((k) => k.id === "editor-restored"), | |
| 364 | type: (text: string) => { | |
| 365 | area.value = text; | |
| 366 | area.dispatchEvent({ type: "input" }); | |
| 367 | for (const f of timers.splice(0)) f(); | |
| 368 | }, | |
| 369 | submit: () => form.dispatchEvent({ type: "submit" }), | |
| 370 | hide: () => winListeners.get("pagehide")?.(), | |
| 371 | }; | |
| 372 | } | |
| 373 | ||
| 374 | describe("an unsent edit survives a reload", () => { | |
| 375 | test("typed, reloaded: the text and the blob it was opened at come back, with one line that says so", () => { | |
| 376 | const storage = new Map<string, string>(); | |
| 377 | const before = editorDom({ | |
| 378 | value: "server text\n", | |
| 379 | opened: "a".repeat(40), | |
| 380 | storage, | |
| 381 | }); | |
| 382 | before.type("my unsent words\n"); | |
| 383 | const after = editorDom({ | |
| 384 | value: "server text\n", | |
| 385 | opened: "a".repeat(40), | |
| 386 | storage, | |
| 387 | }); | |
| 388 | expect(after.area.value).toBe("my unsent words\n"); | |
| 389 | expect(after.note()?.textContent).toContain( | |
| 390 | "Restored what you typed here before", | |
| 391 | ); | |
| 392 | expect(after.note()?.textContent).toContain("Discard it"); | |
| 393 | }); | |
| 394 | ||
| 395 | test("opened since at another blob: the draft keeps the blob it was typed against, so a save refuses", () => { | |
| 396 | const storage = new Map<string, string>(); | |
| 397 | editorDom({ value: "server text\n", opened: "a".repeat(40), storage }).type( | |
| 398 | "mine\n", | |
| 399 | ); | |
| 400 | const later = editorDom({ | |
| 401 | value: "someone else's\n", | |
| 402 | opened: "b".repeat(40), | |
| 403 | storage, | |
| 404 | }); | |
| 405 | expect(later.area.value).toBe("mine\n"); | |
| 406 | expect(later.opened.value).toBe("a".repeat(40)); | |
| 407 | }); | |
| 408 | ||
| 409 | test("committed: the next editor of the file starts clean", () => { | |
| 410 | const storage = new Map<string, string>(); | |
| 411 | const tab = editorDom({ | |
| 412 | value: "server text\n", | |
| 413 | opened: "a".repeat(40), | |
| 414 | storage, | |
| 415 | }); | |
| 416 | tab.type("landed words\n"); | |
| 417 | tab.submit(); | |
| 418 | const after = editorDom({ | |
| 419 | value: "landed words\n", | |
| 420 | opened: "c".repeat(40), | |
| 421 | storage, | |
| 422 | }); | |
| 423 | expect(after.note()).toBeUndefined(); | |
| 424 | expect(storage.size).toBe(0); | |
| 425 | }); | |
| 426 | ||
| 427 | test("a refused save's page already holds the words: nothing older is put over them", () => { | |
| 428 | const storage = new Map<string, string>(); | |
| 429 | editorDom({ value: "server\n", opened: "a".repeat(40), storage }).type( | |
| 430 | "older draft\n", | |
| 431 | ); | |
| 432 | const refused = editorDom({ | |
| 433 | value: "the words just sent\n", | |
| 434 | opened: "b".repeat(40), | |
| 435 | sent: true, | |
| 436 | storage, | |
| 437 | }); | |
| 438 | expect(refused.area.value).toBe("the words just sent\n"); | |
| 439 | expect(refused.note()).toBeUndefined(); | |
| 440 | }); | |
| 441 | ||
| 442 | test("storage that is blocked keeps no draft and breaks nothing", () => { | |
| 443 | const tab = editorDom({ | |
| 444 | value: "server\n", | |
| 445 | opened: "a".repeat(40), | |
| 446 | storage: "blocked", | |
| 447 | }); | |
| 448 | tab.type("typed\n"); | |
| 449 | tab.hide(); | |
| 450 | expect(tab.area.value).toBe("typed\n"); | |
| 451 | }); | |
| 452 | }); |
new above
offline
Principles 1 and 8: two long sentences telling the person three steps. One plain sentence is enough; the checkbox and button label carry the rest.