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

Editor: a restored draft keeps its message, Replace waits for its tick, a reader is told to fork (#16454) #16456

Merged opened this

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

Merged

fix/editor-ui-663 → main 0 commits 2 threads · 2 unresolved

  • Merged. fix/editor-ui-663 was merged into main as dd05bf3.

Review

Sign in to review this change.
7 files changed +117 −20
docs/features/edit-keeps-your-work.md +5 −2
@@ -5,7 +5,7 @@ row: The editor never loses or mangles your work
55
66 # The editor never loses or mangles your work (#16420)
77
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`):
8 What holds when you edit a file in the browser (`/<owner>/<repo>/edit/<branch>/<path>`) or in the terminal's workspace (`e`, then `ctrl+s`):
99
1010 - **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.
1111 - **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`).
@@ -13,5 +13,8 @@ Three promises when you edit a file in the browser (`/<owner>/<repo>/edit/<branc
1313 - 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.
1414 - A new file is refused the same way when a file of that name appeared meanwhile.
1515 - **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 - A restored draft brings back the commit message and description too. Typed against an earlier version of the file, it says so in the note, and Commit shows what changed first (the refusal above, once, with the text and message kept) (#16454).
17 - **Replace waits for its tick.** **Replace their change with mine** stays disabled until its box is ticked; with scripts off it stays enabled, and the server asks for the tick all the same (#16454).
18 - **A reader who may not write is shown the way to propose.** A reader (a contributor, say) opening the editor is told "You can't change owner/repo directly; fork it to propose a change", with the fork beside it (`cannotChangeWords`, `src/actions/edit_words.ts`); the terminal's workspace says the same for a signed-in reader (`src/tui/screens/workspace.ts`). Someone who cannot read still gets the 404 a stranger gets (#16454).
1619
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).
20 Proof: `test/web-editor-integrity.test.ts` (endings, two tabs, Replace and its box, drafts; "a restored draft brings its commit message back, and says when it was typed against an earlier version", "Replace their change with mine waits for its tick"), `test/web-editor.test.ts` ("a reader who may not write is told how to propose, with the fork, never an editor"), `test/tui-editor.test.ts` (the terminal's refusal).
src/actions/edit_words.ts +7
@@ -39,3 +39,10 @@ export function editMessage(kind: string): string {
3939 return "this edit could not be applied";
4040 }
4141 }
42
43 /**
44 * A person who may read a repository and not change it, asking to: the way they propose instead
45 * (#16454). The web editor says it with the fork action beside it; the terminal says it too.
46 */
47 export const cannotChangeWords = (name: string): string =>
48 `You can't change ${name} directly; fork it to propose a change.`;
src/tui/screens/workspace.ts +4 −1
@@ -34,6 +34,7 @@
3434 * default, and on a mirror they ask the origin first.
3535 */
3636
37 import { cannotChangeWords } from "../../actions/edit_words.ts";
3738 import { editFiles, fileAt } from "../../actions/contents.ts";
3839 import { proposeEdit, proposeEditText } from "../../actions/propose_edit.ts";
3940 import { schemaRefusal } from "../../web/render/json-schema.ts";
@@ -1480,7 +1481,9 @@ export function workspaceScreen(
14801481 ctx.toast(
14811482 repo === undefined
14821483 ? "this browse is read-only — W to edit the workbench copy"
1483 : "you cannot write to this repository",
1484 : f.user === undefined
1485 ? "you cannot write to this repository"
1486 : cannotChangeWords(`${repo.ownerName}/${repo.name}`),
14841487 "attn",
14851488 );
14861489 };
src/web/client.ts +33 −5
@@ -1253,6 +1253,17 @@ export const editorJs = /* js */ `
12531253 }
12541254 var kept = readDraft();
12551255 var opened = openedInput ? openedInput.value : '';
1256 var messageInput = form && form.querySelector('input[name=message]');
1257 var bodyInput = form && form.querySelector('textarea[name=description]');
1258 // What a draft holds: the text, the commit message and description beside it, and the blob the
1259 // text was typed against.
1260 function snapshot(sent) {
1261 var v = { text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now() };
1262 if (messageInput && messageInput.value !== '') v.message = messageInput.value;
1263 if (bodyInput && bodyInput.value !== '') v.description = bodyInput.value;
1264 if (sent) v.sent = true;
1265 return v;
1266 }
12561267 if (kept && form && form.getAttribute('data-sent') === '1') {
12571268 // A refused save came back holding every word just sent: that text is the draft now.
12581269 kept = null;
@@ -1263,7 +1274,10 @@ export const editorJs = /* js */ `
12631274 }
12641275 if (kept) {
12651276 area.value = kept.text;
1266 // Opened at another blob: kept, so a save refuses and shows the change made since.
1277 if (messageInput && typeof kept.message === 'string' && messageInput.value === '') messageInput.value = kept.message;
1278 if (bodyInput && typeof kept.description === 'string' && bodyInput.value === '') bodyInput.value = kept.description;
1279 // Opened at another blob: kept, so the save refuses once and shows the change made since.
1280 var older = typeof kept.opened === 'string' && kept.opened !== opened;
12671281 if (openedInput && typeof kept.opened === 'string') openedInput.value = kept.opened;
12681282 area.dispatchEvent(new Event('input', { bubbles: true }));
12691283 var note = doc.createElement('p');
@@ -1272,7 +1286,8 @@ export const editorJs = /* js */ `
12721286 note.setAttribute('role', 'status');
12731287 var when = new Date(kept.at || Date.now());
12741288 note.appendChild(doc.createTextNode('Restored what you typed here before (' +
1275 when.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + '), not yet committed. '));
1289 when.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + '), not yet committed' +
1290 (older ? ', typed against an earlier version of the file: Commit shows what changed first. ' : '. ')));
12761291 var drop = doc.createElement('button');
12771292 drop.type = 'button';
12781293 drop.className = 'btn';
@@ -1296,18 +1311,31 @@ export const editorJs = /* js */ `
12961311 window.clearTimeout(saveTimer);
12971312 saveTimer = window.setTimeout(function () {
12981313 if (area.value === initial) { writeDraft(null); return; }
1299 writeDraft({ text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now() });
1314 writeDraft(snapshot(false));
13001315 }, 250);
13011316 }
13021317 area.addEventListener('input', keep);
1318 if (messageInput) messageInput.addEventListener('input', keep);
1319 if (bodyInput) bodyInput.addEventListener('input', keep);
13031320 if (form) form.addEventListener('submit', function () {
13041321 window.clearTimeout(saveTimer);
1305 writeDraft({ text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now(), sent: true });
1322 writeDraft(snapshot(true));
13061323 });
13071324 // A tab put away or closed keeps the last keystrokes too, not only those before the pause.
13081325 window.addEventListener('pagehide', function () {
1309 if (area.value !== initial && !(readDraft() || {}).sent) writeDraft({ text: area.value, opened: openedInput ? openedInput.value : '', at: Date.now() });
1326 if (area.value !== initial && !(readDraft() || {}).sent) writeDraft(snapshot(false));
13101327 });
1328
1329 // ---- replacing a newer change ----
1330 // The button waits for its tick, so it is never offered as if it were ready (the server asks for
1331 // the tick all the same).
1332 var tick = form && form.querySelector('input[name=confirm][value=replace]');
1333 var replaceButton = form && form.querySelector('button[name=replace]');
1334 if (tick && replaceButton) {
1335 var syncReplace = function () { replaceButton.disabled = !tick.checked; };
1336 tick.addEventListener('change', syncReplace);
1337 syncReplace();
1338 }
13111339 })();
13121340 `;
13131341
src/web/pages/edit.ts +21 −5
@@ -25,7 +25,8 @@ import { sizeText } from "../render/mesh.ts";
2525 import { shiftSubtitles } from "../../actions/subtitle_shift.ts";
2626 import { contribute } from "../../actions/contribute.ts";
2727 import { NO_WRITE_ACCESS } from "../../actions/pull_words.ts";
28 import { changedSinceWords } from "../../actions/edit_words.ts";
28 import { cannotChangeWords, changedSinceWords } from "../../actions/edit_words.ts";
29 import { FORK_AND_SEND } from "../studio/contribute_steps.ts";
2930 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
3031 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
3132 import { isSafeRef, isSafeTreePath } from "../../git/guard.ts";
@@ -633,21 +634,36 @@ const isMarkdownPath = (path: string): boolean =>
633634 path === "" || fileKind(path, NO_BYTES) === "markdown";
634635
635636 /**
636 * The repository and the situation an edit route needs, or the refusal. A
637 * reader who cannot write gets the same 404 a stranger gets — the editor is
638 * not a place to learn that a repository exists but is not yours.
637 * The repository and the situation an edit route needs, or the refusal. Someone who cannot read
638 * gets the same 404 a stranger gets; a reader who cannot write is told so, with the fork that is
639 * how they propose a change (`cannotChangePage`, #16454).
639640 */
640641 function editContext(ctx: Ctx): { scope: RepoScope; ref: string } | Response {
641642 const repo = loadRepo(ctx);
642643 if (!repo) return notFoundPage(ctx);
643644 if (!ctx.auth.user) return signInFirst(ctx);
644645 const scope = localScope(ctx, repo);
645 if (!scope.caps.write) return notFoundPage(ctx);
646 // A reader may not change it; a fork is how they propose. Someone who cannot read never got here.

The doc comment above editContext ("gets the same 404 a stranger gets") is now false. Update it to say a reader gets the fork page, and only someone who cannot read gets the 404.

647 if (!scope.caps.write) return cannotChangePage(ctx, scope, repo);
646648 const ref = ctx.params.ref ?? "";
647649 if (!isSafeRef(ref)) return notFoundPage(ctx);
648650 return { scope, ref };
649651 }
650652
653 /** The editor's answer to a reader: they can't change it here, and the fork that proposes. */
654 function cannotChangePage(ctx: Ctx, scope: RepoScope, repo: Repo): Response {
655 const name = `${repo.ownerName}/${repo.name}`;
656 return page({
657 ctx,
658 title: `Propose a change · ${name}`,
659 crumbs: scope.crumbs,
660 palette: scope.palette,
661 body: html`${pageHead(html`${icon("fork")}Propose a change`, { sub: html`to <span class="mono">${name}</span>` })}
662 <p>${cannotChangeWords(name)}</p>
663 <p>${btn(FORK_AND_SEND, { href: `/${repo.ownerName}/${repo.name}/make-it-yours`, variant: "primary", icon: "fork" })}</p>`,
664 });
665 }
666
651667 /**
652668 * Whether committing straight onto this ref is even on offer. A tag is not a
653669 * branch, and a protected default takes commits from repo admins only — the
test/web-editor-integrity.test.ts +41 −5
@@ -233,6 +233,8 @@ function editorDom(o: {
233233 value: string;
234234 opened: string;
235235 sent?: boolean;
236 message?: string;
237 replace?: boolean;
236238 storage: Map<string, string> | "blocked";
237239 }) {
238240 type Listener = (e: { type: string }) => void;
@@ -292,6 +294,9 @@ function editorDom(o: {
292294 ["opened", o.opened],
293295 ["ref", "main"],
294296 ["path", "notes.md"],
297 ["message", o.message ?? ""],
298 ["confirm", ""],
299 ["replace", ""],
295300 ] as const) {
296301 const input = new El();
297302 input.value = value;
@@ -302,11 +307,17 @@ function editorDom(o: {
302307 ).querySelector = (s: string) =>
303308 s.includes("opened")
304309 ? fields["opened"]!
305 : s.includes("name=ref")
306 ? fields["ref"]!
307 : s.includes("name=path")
308 ? fields["path"]!
309 : null;
310 : s.includes("name=message")
311 ? fields["message"]!
312 : s.includes("name=confirm")
313 ? (o.replace ? fields["confirm"]! : null)
314 : s.includes("name=replace")
315 ? (o.replace ? fields["replace"]! : null)
316 : s.includes("name=ref")
317 ? fields["ref"]!
318 : s.includes("name=path")
319 ? fields["path"]!
320 : null;
310321 const area = new El();
311322 area.value = o.value;
312323 (area as unknown as { form: El }).form = form;
@@ -360,6 +371,9 @@ function editorDom(o: {
360371 area,
361372 form,
362373 opened: fields["opened"]!,
374 message: fields["message"]!,
375 tick: fields["confirm"]!,
376 replace: fields["replace"]!,
363377 note: () => holder.kids.find((k) => k.id === "editor-restored"),
364378 type: (text: string) => {
365379 area.value = text;
@@ -450,3 +464,25 @@ describe("an unsent edit survives a reload", () => {
450464 expect(tab.area.value).toBe("typed\n");
451465 });
452466 });
467
468 describe("a restored draft and the Replace tick", () => {
469 test("a restored draft brings its commit message back, and says when it was typed against an earlier version", () => {
outdated

"the editor after the 0.7.663 check" names a moment, not a concept. Rename it for what it proves, and remove the stray blank line above it.

470 const storage = new Map<string, string>();
471 const tab = editorDom({ value: "server\n", opened: "a".repeat(40), storage });
472 tab.message.value = "Fix the pattern";
473 tab.type("typed\n");
474 const back = editorDom({ value: "newer\n", opened: "b".repeat(40), storage });
475 expect(back.area.value).toBe("typed\n");
476 expect(back.message.value).toBe("Fix the pattern");
477 expect(back.opened.value).toBe("a".repeat(40));
478 expect(back.note()?.textContent).toContain("typed against an earlier version of the file");
479 });
480
481 test("Replace their change with mine waits for its tick", () => {
482 const tab = editorDom({ value: "x\n", opened: "a".repeat(40), replace: true, sent: true, storage: new Map() });
483 expect((tab.replace as unknown as { disabled: boolean }).disabled).toBe(true);
484 (tab.tick as unknown as { checked: boolean }).checked = true;
485 tab.tick.dispatchEvent({ type: "change" });
486 expect((tab.replace as unknown as { disabled: boolean }).disabled).toBe(false);
487 });
488 });
test/web-editor.test.ts +6 −2
@@ -193,9 +193,13 @@ describe("editing files on the web", () => {
193193 }
194194 });
195195
196 test("a stranger cannot even open the editor", async () => {
196 test("a reader who may not write is told how to propose, with the fork, never an editor", async () => {
197197 const res = await get("/alice/beacon/edit/main/src/lamp.ts", kim);
198 expect(res.status).toBe(404);
198 expect(res.status).toBe(200);
199 const page = await res.text();
200 expect(page).toContain("You can&#39;t change alice/beacon directly; fork it to propose a change.");
201 expect(page).toContain("/alice/beacon/make-it-yours");
202 expect(page).not.toContain("<textarea");
199203 });
200204
201205 test("an anonymous visitor is sent to sign in, not shown a form", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs