1/**2 * Drafts: the working copies an author keeps in one browser.3 *4 * A draft is a working copy with a name, an identity and the width its5 * author last gave the wide view. A workspace holds every draft and says6 * which one is open. Each draft has its own composition, selection and Undo7 * history; changing one never touches another.8 *9 * Removing a draft takes it out of the workspace whole and hands it back as10 * a removal, which can later return exactly that draft to whatever the11 * workspace has become. A workspace whose last draft was removed has no12 * drafts and none open; it is still a workspace, distinct from never having13 * had one.14 *15 * Nothing here reads or writes storage. These functions say what a16 * workspace is and how it changes; the caller decides when to save, and17 * what to do when another tab saved first.18 *19 * A workspace is all or nothing. One that cannot be read in full is not20 * read at all, and a change that would not fit is refused, so a caller is21 * never handed a workspace with a draft quietly left out. Every workspace22 * these functions return can be saved and read back unchanged.23 */24importtype { Composition } from"./composition.ts";25import { clampWidth, maximumWidth } from"./width-control.ts";26import { restoreWorkingCopy, typeWorkingCopy } from"./working-copy.ts";2728/**29 * How much a workspace may hold. `characters` bounds the workspace written30 * as JSON, counted as `localStorage` counts it: `JSON.stringify(…).length`.31 */32exportconstdraftLimits= {33drafts: 20,34name: 80,35characters: 2*1024*1024,36} asconst;3738/** The wide view's width in a draft that has not been resized. */39exportconstnewDraftWidth=600;4041constidentityLimit=64;4243exportinterfaceDraft {44/** Chosen by the caller, and never reused in a workspace. */45readonlyid:string;46/** As its author typed it: at most `draftLimits.name` characters, perhaps none. */47readonlyname:string;48readonlycopy:WorkingCopy;49/** The wide view's requested width, in pixels. A view setting, not authored. */50readonlywidth:number;51}5253exportinterfaceDraftWorkspace {54readonlyversion:1;55/**56 * The draft that is open: always one of `drafts`. It is `null` exactly57 * when there are no drafts.58 */59readonlyactiveId:string|null;60/** In the order they were made, with a restored draft back in its place. */61readonlydrafts:readonlyDraft[];62}6364/** A draft taken out of a workspace, and where it stood among the others. */65exportinterfaceDraftRemoval {66/** The draft as it was: identity, name, working copy and width. */67readonlydraft:Draft;68/** Its position in `drafts` when it was removed. */69readonlyindex:number;70}7172/** Why a workspace cannot be read, or a change to one cannot be made. */73exporttypeDraftProblem=74/** There would be more than `draftLimits.drafts`. */75|"too-many-drafts"76/** The workspace would need more than `draftLimits.characters`. */77|"too-large"78/** The name has more than `draftLimits.name` characters. */79|"name"80/** The draft's working copy is not one. */81|"composition"82/** No draft has that identity. */83|"unknown-draft"84/** The identity is empty, too long, or already another draft's. */85|"identity"86/** A removed draft is already back among the drafts. */87|"already-restored"88/** The width is not a number. */89|"width";9091/** Each problem in a sentence for an author. Saved drafts are never changed by a refusal. */92exportconstdraftProblems:Record<DraftProblem, string> = {93"too-many-drafts": `This browser keeps at most ${draftLimits.drafts} drafts, so a new one was not made. Your drafts are unchanged. A snapshot link keeps this composition without a draft.`,94"too-large":95"Your drafts would be too large to save in this browser, so this change was not saved. What was saved before is unchanged. A snapshot link keeps this composition without a draft.",96name: `A draft's name can have at most ${draftLimits.name} characters.`,97composition: "A draft can only hold a composition.",98"unknown-draft": "That draft is not among your drafts.",99identity: "A draft needs an identity of its own.",100"already-restored":101"That draft is already among your drafts, so it was not restored again.",102width: "A draft's width is a number of pixels.",103};104105/** What the limits mean when the change refused is restoring a removed draft. */106constrestoringProblems:Partial<Record<DraftProblem, string>> = {107"too-many-drafts": `This browser keeps at most ${draftLimits.drafts} drafts and already has that many, so the removed draft was not restored. Your drafts are unchanged.`,108"too-large":109"Restoring the removed draft would make your drafts too large to save in this browser, so it was not restored. Your drafts are unchanged.",110};111112/** Thrown when a change to a workspace is refused. Its message is for an author. */113exportclassDraftErrorextendsError {114readonlyproblem:DraftProblem;115constructor(problem:DraftProblem, message=draftProblems[problem]) {116super(message);117this.name="DraftError";118this.problem=problem;119 }120}121122/** A draft built afresh from its four fields, or why they do not make one. */123functiondraftFrom(124id:unknown,125name:unknown,126copy:unknown,127width:unknown,128):Draft|DraftProblem {129if (typeofid!=="string"||!id||id.length>identityLimit)130return"identity";131if (typeofname!=="string"||name.length>draftLimits.name) return"name";132constrestored=restoreWorkingCopy(copy);133if (!restored) return"composition";134if (typeofwidth!=="number"||!Number.isFinite(width)) return"width";135return {136id,137name,138copy: restored,139width: clampWidth(width, maximumWidth),140 };141}142143/** No drafts and none open, or one of the drafts open: nothing between. */144functionopensOneOf(145activeId:unknown,146drafts:readonlyDraft[],147):activeIdisstring|null {148returnactiveId===null149?drafts.length===0150:drafts.some((draft) =>draft.id===activeId);151}152153/** A workspace of `drafts` with one open, or why they do not make one. */154functionworkspaceFrom(155activeId:unknown,156drafts:readonlyDraft[],157):DraftWorkspace|DraftProblem {158if (drafts.length>draftLimits.drafts) return"too-many-drafts";159if (newSet(drafts.map((draft) =>draft.id)).size!==drafts.length)160return"identity";161if (!opensOneOf(activeId, drafts)) return"unknown-draft";162constworkspace:DraftWorkspace= { version: 1, activeId, drafts };163returnJSON.stringify(workspace).length>draftLimits.characters164?"too-large"165:workspace;166}167168functionmade<Textendsobject>(result:T|DraftProblem):T {169if (typeofresult==="string") thrownewDraftError(result);170returnresult;171}172173/**174 * Reads a saved workspace.175 *176 * The whole value must be a version 1 workspace within `draftLimits`: every177 * draft readable, identities distinct, and the open draft among them, or178 * no drafts and `activeId` null. Anything else, including another version,179 * is `undefined`, and whatever was stored should be left as it is.180 *181 * The result is built afresh from known fields. Within a draft, a working182 * copy is read as `restoreWorkingCopy` reads it.183 */184exportfunctionrestoreDraftWorkspace(185saved:unknown,186):DraftWorkspace|undefined {187if (!saved||typeofsaved!=="object") returnundefined;188constrecord=savedasRecord<string, unknown>;189if (190record.version!==1||191!Array.isArray(record.drafts) ||192record.drafts.length>draftLimits.drafts193 )194returnundefined;195constdrafts:Draft[] = [];196for (constentryofrecord.drafts) {197if (!entry||typeofentry!=="object") returnundefined;198const { id, name, copy, width } =entryasRecord<string, unknown>;199constdraft=draftFrom(id, name, copy, width);200if (typeofdraft==="string") returnundefined;201drafts.push(draft);202 }203constworkspace=workspaceFrom(record.activeId, drafts);204returntypeofworkspace==="string"?undefined:workspace;205}206207/**208 * Adds a draft of `tree` and opens it. The new draft has no history, its209 * whole composition selected, and the width `newDraftWidth`. Every draft210 * already in `workspace` is kept as it is: this is how a snapshot, or a211 * composition handed over from a lesson, becomes editable without212 * replacing anything. With no workspace, or one with no drafts, the draft213 * is the only one.214 *215 * Throws a `DraftError` when there are already `draftLimits.drafts`, when216 * `id` is taken or `name` too long, when `tree` is not a composition a217 * working copy accepts, or when the workspace would be too large.218 */219exportfunctioncreateDraft(220workspace:DraftWorkspace|undefined,221tree:Composition,222name:string,223id:string,224):DraftWorkspace {225constdraft=made(226draftFrom(227id,228name,229 { model: tree, chosen: ["0"], undo: [] },230newDraftWidth,231 ),232 );233returnmade(workspaceFrom(id, [...(workspace?.drafts?? []), draft]));234}235236/**237 * Replaces one draft's working copy and width, and its name when one is238 * given. Every other draft is the same object as before, and the open239 * draft stays open.240 *241 * Throws a `DraftError` when no draft has that `id`, when `copy` is not a242 * working copy or `name` is too long, or when the workspace would be too243 * large. A refused change leaves `workspace` valid, as it was.244 */245exportfunctionupdateDraft(246workspace:DraftWorkspace,247id:string,248copy:WorkingCopy,249width:number,250name?:string,251):DraftWorkspace {252constcurrent=workspace.drafts.find((draft) =>draft.id===id);253if (!current) thrownewDraftError("unknown-draft");254constnext=made(draftFrom(id, name??current.name, copy, width));255returnmade(256workspaceFrom(257workspace.activeId,258workspace.drafts.map((draft) => (draft===current?next:draft)),259 ),260 );261}262263/**264 * Opens another draft. No draft changes. Opening the draft that is already265 * open returns `workspace` itself.266 *267 * Throws a `DraftError` when no draft has that `id`.268 */269exportfunctionactivateDraft(270workspace:DraftWorkspace,271id:string,272):DraftWorkspace {273if (id===workspace.activeId) returnworkspace;274returnmade(workspaceFrom(id, workspace.drafts));275}276277/**278 * Takes the draft with that `id` out of `workspace` and returns it as a279 * removal. Every other draft is the same object as before, in the same280 * order.281 *282 * Removing a draft that is not open leaves the open draft open. Removing283 * the open draft opens the one that followed it, else the one before it.284 * Removing the last draft leaves a workspace with no drafts and none open;285 * no blank draft is made to take its place.286 *287 * Throws a `DraftError` when no draft has that `id`.288 */289exportfunctionremoveDraft(290workspace:DraftWorkspace,291id:string,292): { readonlyworkspace:DraftWorkspace; readonlyremoved:DraftRemoval } {293constindex=workspace.drafts.findIndex((draft) =>draft.id===id);294constdraft=workspace.drafts[index];295if (!draft) thrownewDraftError("unknown-draft");296constdrafts=workspace.drafts.filter((other) =>other!==draft);297constactiveId=298workspace.activeId===id299? ((drafts[index] ??drafts[index-1])?.id??null)300:workspace.activeId;301return {302workspace: made(workspaceFrom(activeId, drafts)),303removed: { draft, index },304 };305}306307/**308 * Reads a saved removal: a draft, read as a workspace reads one, and the309 * position it had. Anything else is `undefined`, including a draft too310 * large for any workspace to take back. The result is built afresh from311 * known fields.312 */313exportfunctionrestoreDraftRemoval(saved:unknown):DraftRemoval|undefined {314if (!saved||typeofsaved!=="object") returnundefined;315const { draft: entry, index } =savedasRecord<string, unknown>;316if (317!entry||318typeofentry!=="object"||319typeofindex!=="number"||320!Number.isInteger(index) ||321index<0||322index>=draftLimits.drafts323 )324returnundefined;325const { id, name, copy, width } =entryasRecord<string, unknown>;326constdraft=draftFrom(id, name, copy, width);327if (typeofdraft==="string") returnundefined;328returntypeofworkspaceFrom(draft.id, [draft]) ==="string"329?undefined330: { draft, index };331}332333/**334 * Puts a removed draft back and opens it: the same identity, name, working335 * copy with its selection and Undo history, and width. No other draft336 * changes, whatever has happened to them since the removal.337 *338 * It returns to the position it had, among whichever drafts are there now,339 * or to the end when there are now fewer. With no workspace, it is the only340 * draft.341 *342 * Throws a `DraftError` when a draft with that identity is already there,343 * when there are already `draftLimits.drafts`, or when the workspace would344 * be too large. A refusal changes nothing, so the removal can be tried345 * again later.346 */347exportfunctionrestoreRemovedDraft(348workspace:DraftWorkspace|undefined,349removed:DraftRemoval,350):DraftWorkspace {351const { id, name, copy, width } =removed.draft;352constdraft=made(draftFrom(id, name, copy, width));353constcurrent=workspace?.drafts?? [];354if (current.some((other) =>other.id===draft.id))355thrownewDraftError("already-restored");356constindex=Number.isInteger(removed.index)357?Math.min(Math.max(removed.index, 0), current.length)358:current.length;359constrestored=workspaceFrom(draft.id, [360...current.slice(0, index),361draft,362...current.slice(index),363 ]);364if (typeofrestored==="string")365thrownewDraftError(restored, restoringProblems[restored]);366returnrestored;367}