1import { test } from"node:test";2importassertfrom"node:assert/strict";3import {4Stack,5Shelf,6Switcher,7typeComposition,8} from"../documentation/components/source/composition.ts";9import {10activateDraft,11createDraft,12DraftError,13draftLimits,14newDraftWidth,15removeDraft,16restoreDraftRemoval,17restoreDraftWorkspace,18restoreRemovedDraft,19updateDraft,20typeDraft,21typeDraftProblem,22typeDraftRemoval,23typeDraftWorkspace,24} from"../documentation/components/source/drafts.ts";25import {26decodeSnapshot,27encodeSnapshot,28} from"../documentation/components/source/snapshot.ts";29import {30addText,31commitEdit,32editText,33removeMember,34undoEdit,35typeWorkingCopy,36} from"../documentation/components/source/working-copy.ts";3738conststored= (value:unknown):unknown=>JSON.parse(JSON.stringify(value));39consttext= (value:string):Composition=> ({ kind: "Text", text: value });40constheading= (value:string):Composition=> ({41kind: "Heading",42text: value,43});44constnotice=Stack(45heading("Repair café"),46Switcher(text("Saturday"), text("10 am–1 pm")),47Shelf(),48Stack(text("only member")),49);50constlist=Stack(text("milk"), text("eggs"));5152functiondraft(workspace:DraftWorkspace, id:string):Draft {53constfound=workspace.drafts.find((item) =>item.id===id);54if (!found) thrownewError(`No draft ${id}`);55returnfound;56}57functionproblem(action: () =>unknown):DraftProblem|"no error" {58try {59action();60 } catch (error) {61assert.ok(errorinstanceofDraftError, String(error));62assert.ok(error.message.length>20, "it says what happened");63returnerror.problem;64 }65return"no error";66}67/** A working copy after two edits, with a selection and two steps to undo. */68functionedited(tree:Composition):WorkingCopy {69letcopy:WorkingCopy= { model: tree, chosen: ["0"], undo: [] };70constadded=addText(copy.model, { parent: "0", index: 0 }, "Added");71copy=commitEdit(copy, added.tree, added.chosen);72returncommitEdit(copy, editText(copy.model, "0.0", "Reworded"), ["0.0"]);73}74/** A workspace of `count` drafts named and identified by number. */75functionworkspaceOf(count:number):DraftWorkspace {76letworkspace:DraftWorkspace|undefined;77for (letindex=0; index<count; index++)78workspace=createDraft(workspace, list, `Draft ${index}`, `id-${index}`);79returnworkspace!;80}8182test("the first draft holds the composition, ready to edit, with nothing to undo", () => {83constworkspace=createDraft(undefined, notice, "Café notice", "a");84assert.deepEqual(workspace, {85version: 1,86activeId: "a",87drafts: [88 {89id: "a",90name: "Café notice",91copy: { model: notice, chosen: ["0"], undo: [] },92width: newDraftWidth,93 },94 ],95 });96assert.equal(undoEdit(draft(workspace, "a").copy), undefined);97// An empty composition and an unnamed draft are both drafts.98constblank=createDraft(undefined, Stack(), "", "b");99assert.deepEqual(draft(blank, "b").copy.model, Stack());100assert.equal(draft(blank, "b").name, "");101});102103test("a new draft joins the others and opens, and none of them changes", () => {104constone=createDraft(undefined, notice, "Café notice", "a");105constbefore=stored(one);106consttwo=createDraft(one, list, "Shopping", "b");107assert.deepEqual(108two.drafts.map((item) =>item.id),109 ["a", "b"],110"in the order they were made",111 );112assert.equal(two.activeId, "b");113assert.equal(draft(two, "a"), draft(one, "a"), "the same draft, untouched");114assert.deepEqual(115stored(one),116before,117"the earlier workspace is not rewritten",118 );119assert.equal(one.activeId, "a");120});121122test("saving one draft replaces its copy, width and name and nothing else", () => {123conststart=createDraft(124createDraft(undefined, notice, "Café notice", "a"),125list,126"Shopping",127"b",128 );129constcopy=edited(notice);130constsaved=updateDraft(start, "a", copy, 412.4);131assert.deepEqual(draft(saved, "a"), {132id: "a",133name: "Café notice",134copy,135width: 412,136 });137assert.equal(138draft(saved, "b"),139draft(start, "b"),140"the other draft is untouched",141 );142assert.equal(saved.activeId, "b", "saving does not open a draft");143assert.deepEqual(144draft(start, "a").copy.undo,145 [],146"the earlier workspace stands",147 );148149constrenamed=updateDraft(saved, "a", copy, 412, "Saturday café");150assert.equal(draft(renamed, "a").name, "Saturday café");151assert.deepEqual(draft(renamed, "a").copy, copy);152// A name is kept as typed, including nothing at all and spaces mid-word.153for (constnameof ["", " ", "Café ", " two words ", "修理カフェ 🛠️"])154assert.equal(155draft(updateDraft(saved, "a", copy, 412, name), "a").name,156name,157 );158// A width outside what the wide view can show is brought within it.159assert.equal(draft(updateDraft(saved, "a", copy, 5), "a").width, 160);160assert.equal(draft(updateDraft(saved, "a", copy, 5000), "a").width, 720);161});162163test("each draft keeps its own composition, selection and Undo", () => {164letworkspace=createDraft(165createDraft(undefined, notice, "Café notice", "a"),166list,167"Shopping",168"b",169 );170workspace=updateDraft(workspace, "a", edited(notice), 600);171constremoved=removeMember(list, "0.1");172workspace=updateDraft(173workspace,174"b",175commitEdit(draft(workspace, "b").copy, removed.tree, removed.chosen),176600,177 );178workspace=activateDraft(workspace, "a");179180constreopened=restoreDraftWorkspace(stored(workspace))!;181consta=draft(reopened, "a").copy;182constb=draft(reopened, "b").copy;183assert.deepEqual(a.chosen, ["0.0"]);184assert.deepEqual(b.chosen, ["0.0"]);185assert.equal(a.undo.length, 2);186assert.equal(b.undo.length, 1);187// Undoing in one leaves the other where it was.188assert.deepEqual(undoEdit(b)!.model, list);189assert.deepEqual(undoEdit(b)!.chosen, ["0"]);190assert.deepEqual(undoEdit(undoEdit(a)!)!.model, notice);191assert.deepEqual(b.model, Stack(text("milk")));192// Empty and one-member groups are still groups after saving.193assert.deepEqual("children"ina.model&&a.model.children.slice(3), [194Shelf(),195Stack(text("only member")),196 ]);197});198199test("opening a draft changes which is open and nothing else", () => {200constworkspace=workspaceOf(3);201constopened=activateDraft(workspace, "id-0");202assert.equal(opened.activeId, "id-0");203assert.equal(opened.drafts, workspace.drafts, "no draft was touched");204assert.equal(workspace.activeId, "id-2");205assert.equal(activateDraft(opened, "id-0"), opened, "already open");206assert.equal(207problem(() =>activateDraft(workspace, "id-9")),208"unknown-draft",209 );210assert.equal(211problem(() =>updateDraft(workspace, "id-9", edited(list), 600)),212"unknown-draft",213 );214});215216test("a saved workspace reads back exactly, and writes the same text again", () => {217letworkspace=workspaceOf(3);218workspace=updateDraft(workspace, "id-1", edited(notice), 348, "Café");219workspace=activateDraft(workspace, "id-1");220consttext1=JSON.stringify(workspace);221constreopened=restoreDraftWorkspace(JSON.parse(text1) asunknown)!;222assert.deepEqual(reopened, workspace);223// A saved draft can be compared with a later reading of it as text.224assert.equal(JSON.stringify(reopened), text1);225assert.equal(226JSON.stringify(restoreDraftWorkspace(reopened)),227text1,228"reading what was read changes nothing",229 );230});231232test("reading keeps known fields, and settles what a draft's view and selection can be", () => {233constsaved= {234version: 1,235activeId: "a",236theme: "dark",237drafts: [238 {239id: "a",240name: "Café",241width: 9000,242pinned: true,243copy: {244model: {245kind: "Stack",246children: [{ kind: "Text", text: "a", id: 4 }],247 },248chosen: ["0.7"],249undo: [250 { model: { kind: "Grid" } },251 { model: Stack(), chosen: ["0"] },252 ],253redo: [],254 },255 },256 ],257 };258assert.deepEqual(restoreDraftWorkspace(stored(saved)), {259version: 1,260activeId: "a",261drafts: [262 {263id: "a",264name: "Café",265copy: {266model: Stack(text("a")),267chosen: [],268undo: [{ model: Stack(), chosen: ["0"] }],269 },270width: 720,271 },272 ],273 });274});275276test("a workspace that cannot be read in full is not read at all", () => {277constgood=stored(workspaceOf(2)) as {278version:unknown;279activeId:unknown;280drafts:Record<string, unknown>[];281 };282constwithDraft= (change:Record<string, unknown>) => ({283...good,284drafts: [good.drafts[0], { ...good.drafts[1], ...change }],285 });286assert.ok(restoreDraftWorkspace(good));287for (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 [323withDraft({ copy: { model: text("a") } }),324"content as a whole composition",325 ],326 [327withDraft({ copy: { model: { kind: "Grid", children: [] } } }),328"an unknown kind",329 ],330 [331withDraft({ copy: Stack() }),332"a composition where a working copy belongs",333 ],334 [335 {336...good,337drafts: Array.from({ length: draftLimits.drafts+1 }, (_, index) => ({338...good.drafts[0],339id: `many-${index}`,340 })),341activeId: "many-0",342 },343"more drafts than are kept",344 ],345 [346withDraft({347copy: { 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 ] asconst)354assert.equal(restoreDraftWorkspace(saved), undefined, why);355});356357test("a twenty-first draft is refused, and the twenty stay as they were", () => {358constfull=workspaceOf(draftLimits.drafts);359assert.equal(full.drafts.length, 20);360constbefore=JSON.stringify(full);361assert.equal(362problem(() =>createDraft(full, notice, "One more", "extra")),363"too-many-drafts",364 );365assert.equal(JSON.stringify(full), before);366assert.deepEqual(restoreDraftWorkspace(stored(full)), full);367// Existing drafts can still be saved and opened.368assert.equal(369draft(updateDraft(full, "id-3", edited(notice), 600), "id-3").copy.undo370 .length,3712,372 );373assert.equal(activateDraft(full, "id-0").activeId, "id-0");374});375376test("a workspace is saved within its size or not changed", () => {377conststart=workspaceOf(2);378constholding= (wording:number):WorkingCopy=> ({379model: Stack(text("a".repeat(wording))),380chosen: [],381undo: [],382 });383constfixed=JSON.stringify(384updateDraft(start, "id-0", holding(0), 600),385 ).length;386constroom=draftLimits.characters-fixed;387388constexact=updateDraft(start, "id-0", holding(room), 600);389assert.equal(JSON.stringify(exact).length, draftLimits.characters);390assert.deepEqual(restoreDraftWorkspace(stored(exact)), exact);391392assert.equal(393problem(() =>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.397assert.equal(398problem(() =>createDraft(exact, list, "", "c")),399"too-large",400 );401assert.equal(activateDraft(exact, "id-0").activeId, "id-0");402assert.ok(updateDraft(exact, "id-0", holding(room-10), 600));403// History counts toward the size: it is saved too.404constonce=commitEdit(405holding(room>>1),406Stack(text("b".repeat(room>>1))),407 [],408 );409assert.equal(410problem(() =>updateDraft(start, "id-0", once, 600)),411"too-large",412 );413assert.deepEqual(restoreDraftWorkspace(stored(start)), start, "as it was");414});415416test("a draft needs a bounded name, its own identity and a real composition", () => {417conststart=createDraft(undefined, list, "Shopping", "a");418constlongest="n".repeat(draftLimits.name);419assert.equal(420draft(createDraft(start, list, longest, "b"), "b").name,421longest,422 );423for (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 () =>432createDraft(433start,434 { kind: "Grid", children: [] } asunknownasComposition,435"Grid",436"b",437 ),438"composition",439 ],440 [441 () =>442updateDraft(443start,444"a",445 { model: text("a"), chosen: [], undo: [] },446600,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 ] asconst)456assert.equal(problem(action), expected);457assert.deepEqual(restoreDraftWorkspace(stored(start)), start, "as it was");458});459460test("editing a snapshot makes a new draft, and neither the snapshot nor any draft changes", () => {461constlink=encodeSnapshot(notice);462letworkspace=createDraft(undefined, list, "Shopping", "mine");463workspace=updateDraft(workspace, "mine", edited(list), 480);464constmine=draft(workspace, "mine");465466workspace=createDraft(467workspace,468decodeSnapshot(link),469"Snapshot copy",470"copy",471 );472assert.equal(workspace.activeId, "copy");473assert.equal(draft(workspace, "mine"), mine, "work in progress is untouched");474assert.deepEqual(draft(workspace, "copy").copy, {475model: notice,476chosen: ["0"],477undo: [],478 });479480// Edit the copy; the link still opens what it always held.481constremoved=removeMember(draft(workspace, "copy").copy.model, "0.1");482workspace=updateDraft(483workspace,484"copy",485commitEdit(draft(workspace, "copy").copy, removed.tree, removed.chosen),486600,487 );488assert.notDeepEqual(draft(workspace, "copy").copy.model, notice);489assert.deepEqual(decodeSnapshot(link), notice);490assert.equal(encodeSnapshot(notice), link);491// The same link opened again is a second draft, not a replacement.492workspace=createDraft(493workspace,494decodeSnapshot(link),495"Snapshot copy",496"copy-2",497 );498assert.deepEqual(499workspace.drafts.map((item) =>item.id),500 ["mine", "copy", "copy-2"],501 );502assert.equal(draft(workspace, "mine"), mine);503// A link written from a draft leaves its width, selection and history behind.504assert.equal(505encodeSnapshot(draft(workspace, "mine").copy.model),506encodeSnapshot(Stack(text("Reworded"), text("milk"), text("eggs"))),507 );508});509510/** Frozen all the way down, so any attempt to change it throws. */511functionfrozen<T>(value:T):T {512if (value&&typeofvalue==="object"&&!Object.isFrozen(value)) {513Object.freeze(value);514for (constmemberofObject.values(value)) frozen(member);515 }516returnvalue;517}518constids= (workspace:DraftWorkspace) =>519workspace.drafts.map((item) =>item.id);520/** A removal after its trip through the tab's storage. */521functionkept(removed:DraftRemoval):DraftRemoval {522constread=restoreDraftRemoval(stored(removed));523if (!read) thrownewError("Expected a removal");524returnread;525}526527test("removing a draft takes out exactly that draft and says where it stood", () => {528conststart=frozen(activateDraft(workspaceOf(4), "id-0"));529const { workspace, removed } =removeDraft(start, "id-2");530assert.deepEqual(ids(workspace), ["id-0", "id-1", "id-3"]);531assert.equal(workspace.activeId, "id-0", "the open draft stays open");532for (constidofids(workspace))533assert.equal(draft(workspace, id), draft(start, id), "untouched");534assert.equal(removed.draft, draft(start, "id-2"), "the draft itself");535assert.equal(removed.index, 2);536assert.deepEqual(ids(start), ["id-0", "id-1", "id-2", "id-3"], "as it was");537assert.deepEqual(restoreDraftWorkspace(stored(workspace)), workspace);538assert.equal(539problem(() =>removeDraft(start, "id-9")),540"unknown-draft",541 );542assert.equal(543problem(() =>removeDraft(workspace, "id-2")),544"unknown-draft",545"it cannot be removed twice",546 );547});548549test("removing the open draft opens the next one, or the one before the end", () => {550conststart=workspaceOf(3);551constopen= (id:string) =>552removeDraft(activateDraft(start, id), id).workspace.activeId;553assert.equal(open("id-0"), "id-1", "the draft that followed it");554assert.equal(open("id-1"), "id-2");555assert.equal(open("id-2"), "id-1", "at the end, the draft before it");556});557558test("removing the last draft leaves a workspace with no drafts and none open", () => {559constonly=createDraft(undefined, notice, "Café notice", "a");560const { workspace: empty, removed } =removeDraft(frozen(only), "a");561assert.deepEqual(empty, { version: 1, activeId: null, drafts: [] });562// It is saved and read as what it is; no blank draft stands in for it.563assert.equal(564JSON.stringify(empty),565'{"version":1,"activeId":null,"drafts":[]}',566 );567assert.deepEqual(restoreDraftWorkspace(stored(empty)), empty);568569for (constactionof [570 () =>removeDraft(empty, "a"),571 () =>activateDraft(empty, "a"),572 () =>updateDraft(empty, "a", edited(list), 600),573 ])574assert.equal(problem(action), "unknown-draft");575576// A new draft and the removed one each start it again.577constfresh=createDraft(empty, list, "Shopping", "b");578assert.deepEqual(ids(fresh), ["b"]);579assert.equal(fresh.activeId, "b");580assert.deepEqual(restoreRemovedDraft(empty, kept(removed)), only);581assert.deepEqual(582restoreRemovedDraft(undefined, removed),583only,584"even when nothing is stored any more",585 );586});587588test("work saved before drafts could be removed still reads as it was", () => {589constbefore=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}]}';593constread=restoreDraftWorkspace(JSON.parse(before) asunknown);594assert.equal(JSON.stringify(read), before);595});596597test("undoing a removal returns the whole draft, exactly, and opens it", () => {598letstart=workspaceOf(3);599constcopy=edited(notice);600start=updateDraft(start, "id-1", copy, 412, " Saturday café ");601start=activateDraft(start, "id-2");602constoriginal=draft(start, "id-1");603604const { workspace: reduced, removed } =removeDraft(start, "id-1");605// Both sides are saved, as they are between a removal and its Undo.606constreopened=restoreDraftWorkspace(stored(reduced))!;607constrestored=restoreRemovedDraft(frozen(reopened), frozen(kept(removed)));608609assert.deepEqual(draft(restored, "id-1"), original);610assert.deepEqual(draft(restored, "id-1"), {611id: "id-1",612name: " Saturday café ",613copy,614width: 412,615 });616assert.deepEqual(draft(restored, "id-1").copy.chosen, ["0.0"]);617assert.equal(draft(restored, "id-1").copy.undo.length, 2);618assert.deepEqual(ids(restored), ["id-0", "id-1", "id-2"], "in its old place");619assert.equal(restored.activeId, "id-1", "the restored draft is opened");620assert.deepEqual({ ...restored, activeId: "id-2" }, start);621for (constidof ["id-0", "id-2"])622assert.equal(draft(restored, id), draft(reopened, id), "untouched");623assert.deepEqual(restoreDraftWorkspace(stored(restored)), restored);624});625626test("undoing a removal leaves every later change to the other drafts in place", () => {627conststart=workspaceOf(4);628const { workspace: reduced, removed } =removeDraft(start, "id-1");629630// Since the removal: one draft edited and renamed, one made, one opened.631letlater=updateDraft(reduced, "id-0", edited(notice), 348, "Reworked");632later=createDraft(later, list, "Made since", "new");633later=activateDraft(later, "id-3");634constrestored=restoreRemovedDraft(later, removed);635assert.deepEqual(ids(restored), ["id-0", "id-1", "id-2", "id-3", "new"]);636for (constidofids(later))637assert.equal(draft(restored, id), draft(later, id), "kept as it is now");638assert.equal(draft(restored, "id-0").name, "Reworked");639assert.deepEqual(draft(restored, "id-1"), removed.draft);640641// Its old neighbors may be gone. It takes its old position among the642// drafts there now, or the end when there are fewer than that.643constfewer=removeDraft(removeDraft(reduced, "id-0").workspace, "id-2");644assert.deepEqual(ids(fewer.workspace), ["id-3"]);645assert.deepEqual(ids(restoreRemovedDraft(fewer.workspace, removed)), [646"id-3",647"id-1",648 ]);649constlast=removeDraft(start, "id-3");650constshorter=removeDraft(last.workspace, "id-0").workspace;651assert.deepEqual(ids(restoreRemovedDraft(shorter, last.removed)), [652"id-1",653"id-2",654"id-3",655 ]);656});657658test("a removal is restored once, and never over a draft with its identity", () => {659conststart=workspaceOf(3);660const { workspace: reduced, removed } =removeDraft(start, "id-1");661constrestored=restoreRemovedDraft(reduced, removed);662constbefore=JSON.stringify(restored);663assert.equal(664problem(() =>restoreRemovedDraft(frozen(restored), frozen(removed))),665"already-restored",666 );667assert.equal(JSON.stringify(restored), before);668669// A draft that has since taken the identity is kept; the removal is refused.670consttaken=updateDraft(671createDraft(reduced, list, "Mine now", "id-1"),672"id-1",673edited(list),674500,675 );676assert.equal(677problem(() =>restoreRemovedDraft(taken, removed)),678"already-restored",679 );680assert.equal(draft(taken, "id-1").name, "Mine now");681assert.equal(draft(taken, "id-1").copy.undo.length, 2);682// The removal itself is unchanged, and still restores where it can.683assert.deepEqual(ids(restoreRemovedDraft(reduced, removed)), ids(start));684});685686test("removing makes room, and a removal with no room is refused whole", () => {687// Twenty drafts: a new one needs a removal first.688constfull=workspaceOf(draftLimits.drafts);689assert.equal(690problem(() =>createDraft(full, list, "One more", "extra")),691"too-many-drafts",692 );693const { workspace: nineteen, removed } =removeDraft(full, "id-7");694constrefilled=createDraft(nineteen, list, "One more", "extra");695assert.equal(refilled.drafts.length, draftLimits.drafts);696constbefore=JSON.stringify(refilled);697try {698restoreRemovedDraft(refilled, removed);699assert.fail("restored past the limit");700 } catch (error) {701assert.ok(errorinstanceofDraftError);702assert.equal(error.problem, "too-many-drafts");703assert.match(error.message,/not restored/);704 }705assert.equal(JSON.stringify(refilled), before, "no draft was pushed out");706assert.deepEqual(ids(restoreRemovedDraft(nineteen, removed)), ids(full));707708// A workspace at its size limit: the same, counted in characters.709constholding= (wording:number):WorkingCopy=> ({710model: Stack(text("a".repeat(wording))),711chosen: [],712undo: [],713 });714consttwo=workspaceOf(2);715constroom=716draftLimits.characters-717JSON.stringify(updateDraft(two, "id-0", holding(0), 600)).length;718constexact=updateDraft(two, "id-0", holding(room), 600);719assert.equal(720problem(() =>createDraft(exact, list, "", "c")),721"too-large",722 );723constlarge=removeDraft(exact, "id-0");724assert.ok(createDraft(large.workspace, list, "", "c"), "there is room now");725726constgrown=updateDraft(large.workspace, "id-1", edited(list), 600);727constgrownBefore=JSON.stringify(grown);728try {729restoreRemovedDraft(grown, large.removed);730assert.fail("restored past the limit");731 } catch (error) {732assert.ok(errorinstanceofDraftError);733assert.equal(error.problem, "too-large");734assert.match(error.message,/not restored/);735 }736assert.equal(JSON.stringify(grown), grownBefore);737constback=restoreRemovedDraft(large.workspace, kept(large.removed));738assert.equal(JSON.stringify(back).length, draftLimits.characters);739assert.deepEqual(draft(back, "id-0"), draft(exact, "id-0"));740});741742test("a saved removal reads back exactly, and anything else is not one", () => {743conststart=updateDraft(744workspaceOf(3),745"id-1",746edited(notice),747412,748"Café",749 );750const { removed } =removeDraft(start, "id-1");751consttext1=JSON.stringify(removed);752assert.deepEqual(restoreDraftRemoval(JSON.parse(text1) asunknown), removed);753assert.equal(JSON.stringify(restoreDraftRemoval(JSON.parse(text1))), text1);754// Only the draft and its position are kept, read as a workspace reads them.755assert.deepEqual(756restoreDraftRemoval({757version: 1,758removedAt: "2026-11-20",759index: 0,760draft: {761id: "a",762name: "",763width: 9000,764pinned: true,765copy: { model: Stack(text("a")), chosen: ["0.7"], redo: [] },766 },767 }),768 {769draft: {770id: "a",771name: "",772copy: { model: Stack(text("a")), chosen: [], undo: [] },773width: 720,774 },775index: 0,776 },777 );778779constgood=stored(removed) as {780draft:Record<string, unknown>;781index:number;782 };783constwithDraft= (change:Record<string, unknown>) => ({784...good,785draft: { ...good.draft, ...change },786 });787for (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 [808withDraft({ copy: { model: text("a") } }),809"content as a whole composition",810 ],811 [812withDraft({ copy: { model: { kind: "Grid", children: [] } } }),813"an unknown kind",814 ],815 [816withDraft({817copy: { 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 ] asconst)825assert.equal(restoreDraftRemoval(saved), undefined, why);826});