tests/drafts.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4  Stack,
5  Shelf,
6  Switcher,
7  type Composition,
8} from "../documentation/components/source/composition.ts";
9import {
10  activateDraft,
11  createDraft,
12  DraftError,
13  draftLimits,
14  newDraftWidth,
15  removeDraft,
16  restoreDraftRemoval,
17  restoreDraftWorkspace,
18  restoreRemovedDraft,
19  updateDraft,
20  type Draft,
21  type DraftProblem,
22  type DraftRemoval,
23  type DraftWorkspace,
24} from "../documentation/components/source/drafts.ts";
25import {
26  decodeSnapshot,
27  encodeSnapshot,
28} from "../documentation/components/source/snapshot.ts";
29import {
30  addText,
31  commitEdit,
32  editText,
33  removeMember,
34  undoEdit,
35  type WorkingCopy,
36} from "../documentation/components/source/working-copy.ts";
37
38const stored = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
39const text = (value: string): Composition => ({ kind: "Text", text: value });
40const heading = (value: string): Composition => ({
41  kind: "Heading",
42  text: value,
43});
44const notice = Stack(
45  heading("Repair café"),
46  Switcher(text("Saturday"), text("10 am–1 pm")),
47  Shelf(),
48  Stack(text("only member")),
49);
50const list = Stack(text("milk"), text("eggs"));
51
52function draft(workspace: DraftWorkspace, id: string): Draft {
53  const found = workspace.drafts.find((item) => item.id === id);
54  if (!found) throw new Error(`No draft ${id}`);
55  return found;
56}
57function problem(action: () => unknown): DraftProblem | "no error" {
58  try {
59    action();
60  } catch (error) {
61    assert.ok(error instanceof DraftError, String(error));
62    assert.ok(error.message.length > 20, "it says what happened");
63    return error.problem;
64  }
65  return "no error";
66}
67/** A working copy after two edits, with a selection and two steps to undo. */
68function edited(tree: Composition): WorkingCopy {
69  let copy: WorkingCopy = { model: tree, chosen: ["0"], undo: [] };
70  const added = addText(copy.model, { parent: "0", index: 0 }, "Added");
71  copy = commitEdit(copy, added.tree, added.chosen);
72  return commitEdit(copy, editText(copy.model, "0.0", "Reworded"), ["0.0"]);
73}
74/** A workspace of `count` drafts named and identified by number. */
75function workspaceOf(count: number): DraftWorkspace {
76  let workspace: DraftWorkspace | undefined;
77  for (let index = 0; index < count; index++)
78    workspace = createDraft(workspace, list, `Draft ${index}`, `id-${index}`);
79  return workspace!;
80}
81
82test("the first draft holds the composition, ready to edit, with nothing to undo", () => {
83  const workspace = createDraft(undefined, notice, "Café notice", "a");
84  assert.deepEqual(workspace, {
85    version: 1,
86    activeId: "a",
87    drafts: [
88      {
89        id: "a",
90        name: "Café notice",
91        copy: { model: notice, chosen: ["0"], undo: [] },
92        width: newDraftWidth,
93      },
94    ],
95  });
96  assert.equal(undoEdit(draft(workspace, "a").copy), undefined);
97  // An empty composition and an unnamed draft are both drafts.
98  const blank = createDraft(undefined, Stack(), "", "b");
99  assert.deepEqual(draft(blank, "b").copy.model, Stack());
100  assert.equal(draft(blank, "b").name, "");
101});
102
103test("a new draft joins the others and opens, and none of them changes", () => {
104  const one = createDraft(undefined, notice, "Café notice", "a");
105  const before = stored(one);
106  const two = createDraft(one, list, "Shopping", "b");
107  assert.deepEqual(
108    two.drafts.map((item) => item.id),
109    ["a", "b"],
110    "in the order they were made",
111  );
112  assert.equal(two.activeId, "b");
113  assert.equal(draft(two, "a"), draft(one, "a"), "the same draft, untouched");
114  assert.deepEqual(
115    stored(one),
116    before,
117    "the earlier workspace is not rewritten",
118  );
119  assert.equal(one.activeId, "a");
120});
121
122test("saving one draft replaces its copy, width and name and nothing else", () => {
123  const start = createDraft(
124    createDraft(undefined, notice, "Café notice", "a"),
125    list,
126    "Shopping",
127    "b",
128  );
129  const copy = edited(notice);
130  const saved = updateDraft(start, "a", copy, 412.4);
131  assert.deepEqual(draft(saved, "a"), {
132    id: "a",
133    name: "Café notice",
134    copy,
135    width: 412,
136  });
137  assert.equal(
138    draft(saved, "b"),
139    draft(start, "b"),
140    "the other draft is untouched",
141  );
142  assert.equal(saved.activeId, "b", "saving does not open a draft");
143  assert.deepEqual(
144    draft(start, "a").copy.undo,
145    [],
146    "the earlier workspace stands",
147  );
148
149  const renamed = updateDraft(saved, "a", copy, 412, "Saturday café");
150  assert.equal(draft(renamed, "a").name, "Saturday café");
151  assert.deepEqual(draft(renamed, "a").copy, copy);
152  // A name is kept as typed, including nothing at all and spaces mid-word.
153  for (const name of ["", " ", "Café ", "  two  words  ", "修理カフェ 🛠️"])
154    assert.equal(
155      draft(updateDraft(saved, "a", copy, 412, name), "a").name,
156      name,
157    );
158  // A width outside what the wide view can show is brought within it.
159  assert.equal(draft(updateDraft(saved, "a", copy, 5), "a").width, 160);
160  assert.equal(draft(updateDraft(saved, "a", copy, 5000), "a").width, 720);
161});
162
163test("each draft keeps its own composition, selection and Undo", () => {
164  let workspace = createDraft(
165    createDraft(undefined, notice, "Café notice", "a"),
166    list,
167    "Shopping",
168    "b",
169  );
170  workspace = updateDraft(workspace, "a", edited(notice), 600);
171  const removed = removeMember(list, "0.1");
172  workspace = updateDraft(
173    workspace,
174    "b",
175    commitEdit(draft(workspace, "b").copy, removed.tree, removed.chosen),
176    600,
177  );
178  workspace = activateDraft(workspace, "a");
179
180  const reopened = restoreDraftWorkspace(stored(workspace))!;
181  const a = draft(reopened, "a").copy;
182  const b = draft(reopened, "b").copy;
183  assert.deepEqual(a.chosen, ["0.0"]);
184  assert.deepEqual(b.chosen, ["0.0"]);
185  assert.equal(a.undo.length, 2);
186  assert.equal(b.undo.length, 1);
187  // Undoing in one leaves the other where it was.
188  assert.deepEqual(undoEdit(b)!.model, list);
189  assert.deepEqual(undoEdit(b)!.chosen, ["0"]);
190  assert.deepEqual(undoEdit(undoEdit(a)!)!.model, notice);
191  assert.deepEqual(b.model, Stack(text("milk")));
192  // Empty and one-member groups are still groups after saving.
193  assert.deepEqual("children" in a.model && a.model.children.slice(3), [
194    Shelf(),
195    Stack(text("only member")),
196  ]);
197});
198
199test("opening a draft changes which is open and nothing else", () => {
200  const workspace = workspaceOf(3);
201  const opened = activateDraft(workspace, "id-0");
202  assert.equal(opened.activeId, "id-0");
203  assert.equal(opened.drafts, workspace.drafts, "no draft was touched");
204  assert.equal(workspace.activeId, "id-2");
205  assert.equal(activateDraft(opened, "id-0"), opened, "already open");
206  assert.equal(
207    problem(() => activateDraft(workspace, "id-9")),
208    "unknown-draft",
209  );
210  assert.equal(
211    problem(() => updateDraft(workspace, "id-9", edited(list), 600)),
212    "unknown-draft",
213  );
214});
215
216test("a saved workspace reads back exactly, and writes the same text again", () => {
217  let workspace = workspaceOf(3);
218  workspace = updateDraft(workspace, "id-1", edited(notice), 348, "Café");
219  workspace = activateDraft(workspace, "id-1");
220  const text1 = JSON.stringify(workspace);
221  const reopened = restoreDraftWorkspace(JSON.parse(text1) as unknown)!;
222  assert.deepEqual(reopened, workspace);
223  // A saved draft can be compared with a later reading of it as text.
224  assert.equal(JSON.stringify(reopened), text1);
225  assert.equal(
226    JSON.stringify(restoreDraftWorkspace(reopened)),
227    text1,
228    "reading what was read changes nothing",
229  );
230});
231
232test("reading keeps known fields, and settles what a draft's view and selection can be", () => {
233  const saved = {
234    version: 1,
235    activeId: "a",
236    theme: "dark",
237    drafts: [
238      {
239        id: "a",
240        name: "Café",
241        width: 9000,
242        pinned: true,
243        copy: {
244          model: {
245            kind: "Stack",
246            children: [{ kind: "Text", text: "a", id: 4 }],
247          },
248          chosen: ["0.7"],
249          undo: [
250            { model: { kind: "Grid" } },
251            { model: Stack(), chosen: ["0"] },
252          ],
253          redo: [],
254        },
255      },
256    ],
257  };
258  assert.deepEqual(restoreDraftWorkspace(stored(saved)), {
259    version: 1,
260    activeId: "a",
261    drafts: [
262      {
263        id: "a",
264        name: "Café",
265        copy: {
266          model: Stack(text("a")),
267          chosen: [],
268          undo: [{ model: Stack(), chosen: ["0"] }],
269        },
270        width: 720,
271      },
272    ],
273  });
274});
275
276test("a workspace that cannot be read in full is not read at all", () => {
277  const good = stored(workspaceOf(2)) as {
278    version: unknown;
279    activeId: unknown;
280    drafts: Record<string, unknown>[];
281  };
282  const withDraft = (change: Record<string, unknown>) => ({
283    ...good,
284    drafts: [good.drafts[0], { ...good.drafts[1], ...change }],
285  });
286  assert.ok(restoreDraftWorkspace(good));
287  for (const [saved, why] of [
288    [null, "nothing saved"],
289    ["{}", "a string"],
290    [[good], "an array"],
291    [{ ...good, version: undefined }, "no version"],
292    [{ ...good, version: 0 }, "an earlier version"],
293    [{ ...good, version: 2 }, "a later version"],
294    [{ ...good, version: "1" }, "a version that is not a number"],
295    [{ ...good, drafts: undefined }, "no drafts"],
296    [
297      { ...good, drafts: { 0: good.drafts[0], length: 1 } },
298      "drafts not a list",
299    ],
300    [{ ...good, drafts: [] }, "a draft open with no drafts"],
301    [{ version: 1, drafts: [] }, "no drafts, and no word on which is open"],
302    [{ ...good, activeId: undefined }, "no open draft"],
303    [{ ...good, activeId: null }, "drafts with none open"],
304    [{ ...good, activeId: "id-9" }, "an open draft that is not there"],
305    [{ ...good, activeId: 0 }, "an open draft named by position"],
306    [
307      { ...good, drafts: [good.drafts[0], good.drafts[0]] },
308      "one identity twice",
309    ],
310    [{ ...good, drafts: [good.drafts[0], null] }, "a missing draft"],
311    [{ ...good, drafts: [good.drafts[0], "id-1"] }, "a draft that is not one"],
312    [withDraft({ id: "" }), "an empty identity"],
313    [withDraft({ id: 7 }), "an identity that is not text"],
314    [withDraft({ id: "x".repeat(65) }), "an overlong identity"],
315    [withDraft({ name: undefined }), "no name"],
316    [withDraft({ name: 7 }), "a name that is not text"],
317    [withDraft({ name: "n".repeat(draftLimits.name + 1) }), "an overlong name"],
318    [withDraft({ width: undefined }), "no width"],
319    [withDraft({ width: "600" }), "a width that is not a number"],
320    [withDraft({ width: null }), "a width JSON could not write"],
321    [withDraft({ copy: undefined }), "no working copy"],
322    [
323      withDraft({ copy: { model: text("a") } }),
324      "content as a whole composition",
325    ],
326    [
327      withDraft({ copy: { model: { kind: "Grid", children: [] } } }),
328      "an unknown kind",
329    ],
330    [
331      withDraft({ copy: Stack() }),
332      "a composition where a working copy belongs",
333    ],
334    [
335      {
336        ...good,
337        drafts: Array.from({ length: draftLimits.drafts + 1 }, (_, index) => ({
338          ...good.drafts[0],
339          id: `many-${index}`,
340        })),
341        activeId: "many-0",
342      },
343      "more drafts than are kept",
344    ],
345    [
346      withDraft({
347        copy: { model: Stack(text("a".repeat(draftLimits.characters))) },
348      }),
349      "more than can be saved",
350    ],
351    // The lesson's own saved working copy is not a workspace.
352    [{ model: Stack(), chosen: [], undo: [], width: 600 }, "a working copy"],
353  ] as const)
354    assert.equal(restoreDraftWorkspace(saved), undefined, why);
355});
356
357test("a twenty-first draft is refused, and the twenty stay as they were", () => {
358  const full = workspaceOf(draftLimits.drafts);
359  assert.equal(full.drafts.length, 20);
360  const before = JSON.stringify(full);
361  assert.equal(
362    problem(() => createDraft(full, notice, "One more", "extra")),
363    "too-many-drafts",
364  );
365  assert.equal(JSON.stringify(full), before);
366  assert.deepEqual(restoreDraftWorkspace(stored(full)), full);
367  // Existing drafts can still be saved and opened.
368  assert.equal(
369    draft(updateDraft(full, "id-3", edited(notice), 600), "id-3").copy.undo
370      .length,
371    2,
372  );
373  assert.equal(activateDraft(full, "id-0").activeId, "id-0");
374});
375
376test("a workspace is saved within its size or not changed", () => {
377  const start = workspaceOf(2);
378  const holding = (wording: number): WorkingCopy => ({
379    model: Stack(text("a".repeat(wording))),
380    chosen: [],
381    undo: [],
382  });
383  const fixed = JSON.stringify(
384    updateDraft(start, "id-0", holding(0), 600),
385  ).length;
386  const room = draftLimits.characters - fixed;
387
388  const exact = updateDraft(start, "id-0", holding(room), 600);
389  assert.equal(JSON.stringify(exact).length, draftLimits.characters);
390  assert.deepEqual(restoreDraftWorkspace(stored(exact)), exact);
391
392  assert.equal(
393    problem(() => updateDraft(start, "id-0", holding(room + 1), 600)),
394    "too-large",
395  );
396  // The full workspace takes no further draft, and still opens and saves smaller.
397  assert.equal(
398    problem(() => createDraft(exact, list, "", "c")),
399    "too-large",
400  );
401  assert.equal(activateDraft(exact, "id-0").activeId, "id-0");
402  assert.ok(updateDraft(exact, "id-0", holding(room - 10), 600));
403  // History counts toward the size: it is saved too.
404  const once = commitEdit(
405    holding(room >> 1),
406    Stack(text("b".repeat(room >> 1))),
407    [],
408  );
409  assert.equal(
410    problem(() => updateDraft(start, "id-0", once, 600)),
411    "too-large",
412  );
413  assert.deepEqual(restoreDraftWorkspace(stored(start)), start, "as it was");
414});
415
416test("a draft needs a bounded name, its own identity and a real composition", () => {
417  const start = createDraft(undefined, list, "Shopping", "a");
418  const longest = "n".repeat(draftLimits.name);
419  assert.equal(
420    draft(createDraft(start, list, longest, "b"), "b").name,
421    longest,
422  );
423  for (const [action, expected] of [
424    [() => createDraft(start, list, `${longest}n`, "b"), "name"],
425    [() => updateDraft(start, "a", edited(list), 600, `${longest}n`), "name"],
426    [() => createDraft(start, list, "Again", "a"), "identity"],
427    [() => createDraft(start, list, "Nameless", ""), "identity"],
428    [() => createDraft(undefined, list, "Long", "x".repeat(65)), "identity"],
429    [() => createDraft(start, text("a"), "Content", "b"), "composition"],
430    [
431      () =>
432        createDraft(
433          start,
434          { kind: "Grid", children: [] } as unknown as Composition,
435          "Grid",
436          "b",
437        ),
438      "composition",
439    ],
440    [
441      () =>
442        updateDraft(
443          start,
444          "a",
445          { model: text("a"), chosen: [], undo: [] },
446          600,
447        ),
448      "composition",
449    ],
450    [() => updateDraft(start, "a", edited(list), Number.NaN), "width"],
451    [
452      () => updateDraft(start, "a", edited(list), Number.POSITIVE_INFINITY),
453      "width",
454    ],
455  ] as const)
456    assert.equal(problem(action), expected);
457  assert.deepEqual(restoreDraftWorkspace(stored(start)), start, "as it was");
458});
459
460test("editing a snapshot makes a new draft, and neither the snapshot nor any draft changes", () => {
461  const link = encodeSnapshot(notice);
462  let workspace = createDraft(undefined, list, "Shopping", "mine");
463  workspace = updateDraft(workspace, "mine", edited(list), 480);
464  const mine = draft(workspace, "mine");
465
466  workspace = createDraft(
467    workspace,
468    decodeSnapshot(link),
469    "Snapshot copy",
470    "copy",
471  );
472  assert.equal(workspace.activeId, "copy");
473  assert.equal(draft(workspace, "mine"), mine, "work in progress is untouched");
474  assert.deepEqual(draft(workspace, "copy").copy, {
475    model: notice,
476    chosen: ["0"],
477    undo: [],
478  });
479
480  // Edit the copy; the link still opens what it always held.
481  const removed = removeMember(draft(workspace, "copy").copy.model, "0.1");
482  workspace = updateDraft(
483    workspace,
484    "copy",
485    commitEdit(draft(workspace, "copy").copy, removed.tree, removed.chosen),
486    600,
487  );
488  assert.notDeepEqual(draft(workspace, "copy").copy.model, notice);
489  assert.deepEqual(decodeSnapshot(link), notice);
490  assert.equal(encodeSnapshot(notice), link);
491  // The same link opened again is a second draft, not a replacement.
492  workspace = createDraft(
493    workspace,
494    decodeSnapshot(link),
495    "Snapshot copy",
496    "copy-2",
497  );
498  assert.deepEqual(
499    workspace.drafts.map((item) => item.id),
500    ["mine", "copy", "copy-2"],
501  );
502  assert.equal(draft(workspace, "mine"), mine);
503  // A link written from a draft leaves its width, selection and history behind.
504  assert.equal(
505    encodeSnapshot(draft(workspace, "mine").copy.model),
506    encodeSnapshot(Stack(text("Reworded"), text("milk"), text("eggs"))),
507  );
508});
509
510/** Frozen all the way down, so any attempt to change it throws. */
511function frozen<T>(value: T): T {
512  if (value && typeof value === "object" && !Object.isFrozen(value)) {
513    Object.freeze(value);
514    for (const member of Object.values(value)) frozen(member);
515  }
516  return value;
517}
518const ids = (workspace: DraftWorkspace) =>
519  workspace.drafts.map((item) => item.id);
520/** A removal after its trip through the tab's storage. */
521function kept(removed: DraftRemoval): DraftRemoval {
522  const read = restoreDraftRemoval(stored(removed));
523  if (!read) throw new Error("Expected a removal");
524  return read;
525}
526
527test("removing a draft takes out exactly that draft and says where it stood", () => {
528  const start = frozen(activateDraft(workspaceOf(4), "id-0"));
529  const { workspace, removed } = removeDraft(start, "id-2");
530  assert.deepEqual(ids(workspace), ["id-0", "id-1", "id-3"]);
531  assert.equal(workspace.activeId, "id-0", "the open draft stays open");
532  for (const id of ids(workspace))
533    assert.equal(draft(workspace, id), draft(start, id), "untouched");
534  assert.equal(removed.draft, draft(start, "id-2"), "the draft itself");
535  assert.equal(removed.index, 2);
536  assert.deepEqual(ids(start), ["id-0", "id-1", "id-2", "id-3"], "as it was");
537  assert.deepEqual(restoreDraftWorkspace(stored(workspace)), workspace);
538  assert.equal(
539    problem(() => removeDraft(start, "id-9")),
540    "unknown-draft",
541  );
542  assert.equal(
543    problem(() => removeDraft(workspace, "id-2")),
544    "unknown-draft",
545    "it cannot be removed twice",
546  );
547});
548
549test("removing the open draft opens the next one, or the one before the end", () => {
550  const start = workspaceOf(3);
551  const open = (id: string) =>
552    removeDraft(activateDraft(start, id), id).workspace.activeId;
553  assert.equal(open("id-0"), "id-1", "the draft that followed it");
554  assert.equal(open("id-1"), "id-2");
555  assert.equal(open("id-2"), "id-1", "at the end, the draft before it");
556});
557
558test("removing the last draft leaves a workspace with no drafts and none open", () => {
559  const only = createDraft(undefined, notice, "Café notice", "a");
560  const { workspace: empty, removed } = removeDraft(frozen(only), "a");
561  assert.deepEqual(empty, { version: 1, activeId: null, drafts: [] });
562  // It is saved and read as what it is; no blank draft stands in for it.
563  assert.equal(
564    JSON.stringify(empty),
565    '{"version":1,"activeId":null,"drafts":[]}',
566  );
567  assert.deepEqual(restoreDraftWorkspace(stored(empty)), empty);
568
569  for (const action of [
570    () => removeDraft(empty, "a"),
571    () => activateDraft(empty, "a"),
572    () => updateDraft(empty, "a", edited(list), 600),
573  ])
574    assert.equal(problem(action), "unknown-draft");
575
576  // A new draft and the removed one each start it again.
577  const fresh = createDraft(empty, list, "Shopping", "b");
578  assert.deepEqual(ids(fresh), ["b"]);
579  assert.equal(fresh.activeId, "b");
580  assert.deepEqual(restoreRemovedDraft(empty, kept(removed)), only);
581  assert.deepEqual(
582    restoreRemovedDraft(undefined, removed),
583    only,
584    "even when nothing is stored any more",
585  );
586});
587
588test("work saved before drafts could be removed still reads as it was", () => {
589  const before =
590    '{"version":1,"activeId":"b","drafts":[' +
591    '{"id":"a","name":"Café","copy":{"model":{"kind":"Stack","children":[{"kind":"Heading","text":"Repair café"},{"kind":"Switcher","children":[]}]},"chosen":["0.1"],"undo":[{"model":{"kind":"Stack","children":[]},"chosen":["0"]}]},"width":412},' +
592    '{"id":"b","name":"","copy":{"model":{"kind":"Stack","children":[]},"chosen":["0"],"undo":[]},"width":600}]}';
593  const read = restoreDraftWorkspace(JSON.parse(before) as unknown);
594  assert.equal(JSON.stringify(read), before);
595});
596
597test("undoing a removal returns the whole draft, exactly, and opens it", () => {
598  let start = workspaceOf(3);
599  const copy = edited(notice);
600  start = updateDraft(start, "id-1", copy, 412, " Saturday café ");
601  start = activateDraft(start, "id-2");
602  const original = draft(start, "id-1");
603
604  const { workspace: reduced, removed } = removeDraft(start, "id-1");
605  // Both sides are saved, as they are between a removal and its Undo.
606  const reopened = restoreDraftWorkspace(stored(reduced))!;
607  const restored = restoreRemovedDraft(frozen(reopened), frozen(kept(removed)));
608
609  assert.deepEqual(draft(restored, "id-1"), original);
610  assert.deepEqual(draft(restored, "id-1"), {
611    id: "id-1",
612    name: " Saturday café ",
613    copy,
614    width: 412,
615  });
616  assert.deepEqual(draft(restored, "id-1").copy.chosen, ["0.0"]);
617  assert.equal(draft(restored, "id-1").copy.undo.length, 2);
618  assert.deepEqual(ids(restored), ["id-0", "id-1", "id-2"], "in its old place");
619  assert.equal(restored.activeId, "id-1", "the restored draft is opened");
620  assert.deepEqual({ ...restored, activeId: "id-2" }, start);
621  for (const id of ["id-0", "id-2"])
622    assert.equal(draft(restored, id), draft(reopened, id), "untouched");
623  assert.deepEqual(restoreDraftWorkspace(stored(restored)), restored);
624});
625
626test("undoing a removal leaves every later change to the other drafts in place", () => {
627  const start = workspaceOf(4);
628  const { workspace: reduced, removed } = removeDraft(start, "id-1");
629
630  // Since the removal: one draft edited and renamed, one made, one opened.
631  let later = updateDraft(reduced, "id-0", edited(notice), 348, "Reworked");
632  later = createDraft(later, list, "Made since", "new");
633  later = activateDraft(later, "id-3");
634  const restored = restoreRemovedDraft(later, removed);
635  assert.deepEqual(ids(restored), ["id-0", "id-1", "id-2", "id-3", "new"]);
636  for (const id of ids(later))
637    assert.equal(draft(restored, id), draft(later, id), "kept as it is now");
638  assert.equal(draft(restored, "id-0").name, "Reworked");
639  assert.deepEqual(draft(restored, "id-1"), removed.draft);
640
641  // Its old neighbors may be gone. It takes its old position among the
642  // drafts there now, or the end when there are fewer than that.
643  const fewer = removeDraft(removeDraft(reduced, "id-0").workspace, "id-2");
644  assert.deepEqual(ids(fewer.workspace), ["id-3"]);
645  assert.deepEqual(ids(restoreRemovedDraft(fewer.workspace, removed)), [
646    "id-3",
647    "id-1",
648  ]);
649  const last = removeDraft(start, "id-3");
650  const shorter = removeDraft(last.workspace, "id-0").workspace;
651  assert.deepEqual(ids(restoreRemovedDraft(shorter, last.removed)), [
652    "id-1",
653    "id-2",
654    "id-3",
655  ]);
656});
657
658test("a removal is restored once, and never over a draft with its identity", () => {
659  const start = workspaceOf(3);
660  const { workspace: reduced, removed } = removeDraft(start, "id-1");
661  const restored = restoreRemovedDraft(reduced, removed);
662  const before = JSON.stringify(restored);
663  assert.equal(
664    problem(() => restoreRemovedDraft(frozen(restored), frozen(removed))),
665    "already-restored",
666  );
667  assert.equal(JSON.stringify(restored), before);
668
669  // A draft that has since taken the identity is kept; the removal is refused.
670  const taken = updateDraft(
671    createDraft(reduced, list, "Mine now", "id-1"),
672    "id-1",
673    edited(list),
674    500,
675  );
676  assert.equal(
677    problem(() => restoreRemovedDraft(taken, removed)),
678    "already-restored",
679  );
680  assert.equal(draft(taken, "id-1").name, "Mine now");
681  assert.equal(draft(taken, "id-1").copy.undo.length, 2);
682  // The removal itself is unchanged, and still restores where it can.
683  assert.deepEqual(ids(restoreRemovedDraft(reduced, removed)), ids(start));
684});
685
686test("removing makes room, and a removal with no room is refused whole", () => {
687  // Twenty drafts: a new one needs a removal first.
688  const full = workspaceOf(draftLimits.drafts);
689  assert.equal(
690    problem(() => createDraft(full, list, "One more", "extra")),
691    "too-many-drafts",
692  );
693  const { workspace: nineteen, removed } = removeDraft(full, "id-7");
694  const refilled = createDraft(nineteen, list, "One more", "extra");
695  assert.equal(refilled.drafts.length, draftLimits.drafts);
696  const before = JSON.stringify(refilled);
697  try {
698    restoreRemovedDraft(refilled, removed);
699    assert.fail("restored past the limit");
700  } catch (error) {
701    assert.ok(error instanceof DraftError);
702    assert.equal(error.problem, "too-many-drafts");
703    assert.match(error.message, /not restored/);
704  }
705  assert.equal(JSON.stringify(refilled), before, "no draft was pushed out");
706  assert.deepEqual(ids(restoreRemovedDraft(nineteen, removed)), ids(full));
707
708  // A workspace at its size limit: the same, counted in characters.
709  const holding = (wording: number): WorkingCopy => ({
710    model: Stack(text("a".repeat(wording))),
711    chosen: [],
712    undo: [],
713  });
714  const two = workspaceOf(2);
715  const room =
716    draftLimits.characters -
717    JSON.stringify(updateDraft(two, "id-0", holding(0), 600)).length;
718  const exact = updateDraft(two, "id-0", holding(room), 600);
719  assert.equal(
720    problem(() => createDraft(exact, list, "", "c")),
721    "too-large",
722  );
723  const large = removeDraft(exact, "id-0");
724  assert.ok(createDraft(large.workspace, list, "", "c"), "there is room now");
725
726  const grown = updateDraft(large.workspace, "id-1", edited(list), 600);
727  const grownBefore = JSON.stringify(grown);
728  try {
729    restoreRemovedDraft(grown, large.removed);
730    assert.fail("restored past the limit");
731  } catch (error) {
732    assert.ok(error instanceof DraftError);
733    assert.equal(error.problem, "too-large");
734    assert.match(error.message, /not restored/);
735  }
736  assert.equal(JSON.stringify(grown), grownBefore);
737  const back = restoreRemovedDraft(large.workspace, kept(large.removed));
738  assert.equal(JSON.stringify(back).length, draftLimits.characters);
739  assert.deepEqual(draft(back, "id-0"), draft(exact, "id-0"));
740});
741
742test("a saved removal reads back exactly, and anything else is not one", () => {
743  const start = updateDraft(
744    workspaceOf(3),
745    "id-1",
746    edited(notice),
747    412,
748    "Café",
749  );
750  const { removed } = removeDraft(start, "id-1");
751  const text1 = JSON.stringify(removed);
752  assert.deepEqual(restoreDraftRemoval(JSON.parse(text1) as unknown), removed);
753  assert.equal(JSON.stringify(restoreDraftRemoval(JSON.parse(text1))), text1);
754  // Only the draft and its position are kept, read as a workspace reads them.
755  assert.deepEqual(
756    restoreDraftRemoval({
757      version: 1,
758      removedAt: "2026-11-20",
759      index: 0,
760      draft: {
761        id: "a",
762        name: "",
763        width: 9000,
764        pinned: true,
765        copy: { model: Stack(text("a")), chosen: ["0.7"], redo: [] },
766      },
767    }),
768    {
769      draft: {
770        id: "a",
771        name: "",
772        copy: { model: Stack(text("a")), chosen: [], undo: [] },
773        width: 720,
774      },
775      index: 0,
776    },
777  );
778
779  const good = stored(removed) as {
780    draft: Record<string, unknown>;
781    index: number;
782  };
783  const withDraft = (change: Record<string, unknown>) => ({
784    ...good,
785    draft: { ...good.draft, ...change },
786  });
787  for (const [saved, why] of [
788    [null, "nothing saved"],
789    ["{}", "a string"],
790    [[good], "an array"],
791    [good.draft, "a draft with no position"],
792    [{ index: 1 }, "a position with no draft"],
793    [{ ...good, draft: null }, "a missing draft"],
794    [{ ...good, draft: "id-1" }, "an identity where a draft belongs"],
795    [{ ...good, index: -1 }, "a position before the start"],
796    [{ ...good, index: 1.5 }, "a position between drafts"],
797    [
798      { ...good, index: draftLimits.drafts },
799      "a position no draft can have had",
800    ],
801    [{ ...good, index: "1" }, "a position that is not a number"],
802    [{ ...good, index: null }, "a position JSON could not write"],
803    [withDraft({ id: "" }), "an empty identity"],
804    [withDraft({ name: "n".repeat(draftLimits.name + 1) }), "an overlong name"],
805    [withDraft({ width: "412" }), "a width that is not a number"],
806    [withDraft({ copy: undefined }), "no working copy"],
807    [
808      withDraft({ copy: { model: text("a") } }),
809      "content as a whole composition",
810    ],
811    [
812      withDraft({ copy: { model: { kind: "Grid", children: [] } } }),
813      "an unknown kind",
814    ],
815    [
816      withDraft({
817        copy: { model: Stack(text("a".repeat(draftLimits.characters))) },
818      }),
819      "a draft no workspace could take back",
820    ],
821    // A workspace is not a removal, nor is a working copy.
822    [stored(start), "a workspace"],
823    [stored(removed.draft.copy), "a working copy"],
824  ] as const)
825    assert.equal(restoreDraftRemoval(saved), undefined, why);
826});