documentation/components/source/drafts.ts

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 its
5 * author last gave the wide view. A workspace holds every draft and says
6 * which one is open. Each draft has its own composition, selection and Undo
7 * history; changing one never touches another.
8 *
9 * Removing a draft takes it out of the workspace whole and hands it back as
10 * a removal, which can later return exactly that draft to whatever the
11 * workspace has become. A workspace whose last draft was removed has no
12 * drafts and none open; it is still a workspace, distinct from never having
13 * had one.
14 *
15 * Nothing here reads or writes storage. These functions say what a
16 * workspace is and how it changes; the caller decides when to save, and
17 * what to do when another tab saved first.
18 *
19 * A workspace is all or nothing. One that cannot be read in full is not
20 * read at all, and a change that would not fit is refused, so a caller is
21 * never handed a workspace with a draft quietly left out. Every workspace
22 * these functions return can be saved and read back unchanged.
23 */
24import type { Composition } from "./composition.ts";
25import { clampWidth, maximumWidth } from "./width-control.ts";
26import { restoreWorkingCopy, type WorkingCopy } from "./working-copy.ts";
27
28/**
29 * How much a workspace may hold. `characters` bounds the workspace written
30 * as JSON, counted as `localStorage` counts it: `JSON.stringify(…).length`.
31 */
32export const draftLimits = {
33  drafts: 20,
34  name: 80,
35  characters: 2 * 1024 * 1024,
36} as const;
37
38/** The wide view's width in a draft that has not been resized. */
39export const newDraftWidth = 600;
40
41const identityLimit = 64;
42
43export interface Draft {
44  /** Chosen by the caller, and never reused in a workspace. */
45  readonly id: string;
46  /** As its author typed it: at most `draftLimits.name` characters, perhaps none. */
47  readonly name: string;
48  readonly copy: WorkingCopy;
49  /** The wide view's requested width, in pixels. A view setting, not authored. */
50  readonly width: number;
51}
52
53export interface DraftWorkspace {
54  readonly version: 1;
55  /**
56   * The draft that is open: always one of `drafts`. It is `null` exactly
57   * when there are no drafts.
58   */
59  readonly activeId: string | null;
60  /** In the order they were made, with a restored draft back in its place. */
61  readonly drafts: readonly Draft[];
62}
63
64/** A draft taken out of a workspace, and where it stood among the others. */
65export interface DraftRemoval {
66  /** The draft as it was: identity, name, working copy and width. */
67  readonly draft: Draft;
68  /** Its position in `drafts` when it was removed. */
69  readonly index: number;
70}
71
72/** Why a workspace cannot be read, or a change to one cannot be made. */
73export type DraftProblem =
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";
90
91/** Each problem in a sentence for an author. Saved drafts are never changed by a refusal. */
92export const draftProblems: 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.",
96  name: `A draft's name can have at most ${draftLimits.name} characters.`,
97  composition: "A draft can only hold a composition.",
98  "unknown-draft": "That draft is not among your drafts.",
99  identity: "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.",
102  width: "A draft's width is a number of pixels.",
103};
104
105/** What the limits mean when the change refused is restoring a removed draft. */
106const restoringProblems: 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};
111
112/** Thrown when a change to a workspace is refused. Its message is for an author. */
113export class DraftError extends Error {
114  readonly problem: DraftProblem;
115  constructor(problem: DraftProblem, message = draftProblems[problem]) {
116    super(message);
117    this.name = "DraftError";
118    this.problem = problem;
119  }
120}
121
122/** A draft built afresh from its four fields, or why they do not make one. */
123function draftFrom(
124  id: unknown,
125  name: unknown,
126  copy: unknown,
127  width: unknown,
128): Draft | DraftProblem {
129  if (typeof id !== "string" || !id || id.length > identityLimit)
130    return "identity";
131  if (typeof name !== "string" || name.length > draftLimits.name) return "name";
132  const restored = restoreWorkingCopy(copy);
133  if (!restored) return "composition";
134  if (typeof width !== "number" || !Number.isFinite(width)) return "width";
135  return {
136    id,
137    name,
138    copy: restored,
139    width: clampWidth(width, maximumWidth),
140  };
141}
142
143/** No drafts and none open, or one of the drafts open: nothing between. */
144function opensOneOf(
145  activeId: unknown,
146  drafts: readonly Draft[],
147): activeId is string | null {
148  return activeId === null
149    ? drafts.length === 0
150    : drafts.some((draft) => draft.id === activeId);
151}
152
153/** A workspace of `drafts` with one open, or why they do not make one. */
154function workspaceFrom(
155  activeId: unknown,
156  drafts: readonly Draft[],
157): DraftWorkspace | DraftProblem {
158  if (drafts.length > draftLimits.drafts) return "too-many-drafts";
159  if (new Set(drafts.map((draft) => draft.id)).size !== drafts.length)
160    return "identity";
161  if (!opensOneOf(activeId, drafts)) return "unknown-draft";
162  const workspace: DraftWorkspace = { version: 1, activeId, drafts };
163  return JSON.stringify(workspace).length > draftLimits.characters
164    ? "too-large"
165    : workspace;
166}
167
168function made<T extends object>(result: T | DraftProblem): T {
169  if (typeof result === "string") throw new DraftError(result);
170  return result;
171}
172
173/**
174 * Reads a saved workspace.
175 *
176 * The whole value must be a version 1 workspace within `draftLimits`: every
177 * draft readable, identities distinct, and the open draft among them, or
178 * 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 working
182 * copy is read as `restoreWorkingCopy` reads it.
183 */
184export function restoreDraftWorkspace(
185  saved: unknown,
186): DraftWorkspace | undefined {
187  if (!saved || typeof saved !== "object") return undefined;
188  const record = saved as Record<string, unknown>;
189  if (
190    record.version !== 1 ||
191    !Array.isArray(record.drafts) ||
192    record.drafts.length > draftLimits.drafts
193  )
194    return undefined;
195  const drafts: Draft[] = [];
196  for (const entry of record.drafts) {
197    if (!entry || typeof entry !== "object") return undefined;
198    const { id, name, copy, width } = entry as Record<string, unknown>;
199    const draft = draftFrom(id, name, copy, width);
200    if (typeof draft === "string") return undefined;
201    drafts.push(draft);
202  }
203  const workspace = workspaceFrom(record.activeId, drafts);
204  return typeof workspace === "string" ? undefined : workspace;
205}
206
207/**
208 * Adds a draft of `tree` and opens it. The new draft has no history, its
209 * whole composition selected, and the width `newDraftWidth`. Every draft
210 * already in `workspace` is kept as it is: this is how a snapshot, or a
211 * composition handed over from a lesson, becomes editable without
212 * replacing anything. With no workspace, or one with no drafts, the draft
213 * is the only one.
214 *
215 * Throws a `DraftError` when there are already `draftLimits.drafts`, when
216 * `id` is taken or `name` too long, when `tree` is not a composition a
217 * working copy accepts, or when the workspace would be too large.
218 */
219export function createDraft(
220  workspace: DraftWorkspace | undefined,
221  tree: Composition,
222  name: string,
223  id: string,
224): DraftWorkspace {
225  const draft = made(
226    draftFrom(
227      id,
228      name,
229      { model: tree, chosen: ["0"], undo: [] },
230      newDraftWidth,
231    ),
232  );
233  return made(workspaceFrom(id, [...(workspace?.drafts ?? []), draft]));
234}
235
236/**
237 * Replaces one draft's working copy and width, and its name when one is
238 * given. Every other draft is the same object as before, and the open
239 * draft stays open.
240 *
241 * Throws a `DraftError` when no draft has that `id`, when `copy` is not a
242 * working copy or `name` is too long, or when the workspace would be too
243 * large. A refused change leaves `workspace` valid, as it was.
244 */
245export function updateDraft(
246  workspace: DraftWorkspace,
247  id: string,
248  copy: WorkingCopy,
249  width: number,
250  name?: string,
251): DraftWorkspace {
252  const current = workspace.drafts.find((draft) => draft.id === id);
253  if (!current) throw new DraftError("unknown-draft");
254  const next = made(draftFrom(id, name ?? current.name, copy, width));
255  return made(
256    workspaceFrom(
257      workspace.activeId,
258      workspace.drafts.map((draft) => (draft === current ? next : draft)),
259    ),
260  );
261}
262
263/**
264 * Opens another draft. No draft changes. Opening the draft that is already
265 * open returns `workspace` itself.
266 *
267 * Throws a `DraftError` when no draft has that `id`.
268 */
269export function activateDraft(
270  workspace: DraftWorkspace,
271  id: string,
272): DraftWorkspace {
273  if (id === workspace.activeId) return workspace;
274  return made(workspaceFrom(id, workspace.drafts));
275}
276
277/**
278 * Takes the draft with that `id` out of `workspace` and returns it as a
279 * removal. Every other draft is the same object as before, in the same
280 * order.
281 *
282 * Removing a draft that is not open leaves the open draft open. Removing
283 * 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 */
289export function removeDraft(
290  workspace: DraftWorkspace,
291  id: string,
292): { readonly workspace: DraftWorkspace; readonly removed: DraftRemoval } {
293  const index = workspace.drafts.findIndex((draft) => draft.id === id);
294  const draft = workspace.drafts[index];
295  if (!draft) throw new DraftError("unknown-draft");
296  const drafts = workspace.drafts.filter((other) => other !== draft);
297  const activeId =
298    workspace.activeId === id
299      ? ((drafts[index] ?? drafts[index - 1])?.id ?? null)
300      : workspace.activeId;
301  return {
302    workspace: made(workspaceFrom(activeId, drafts)),
303    removed: { draft, index },
304  };
305}
306
307/**
308 * Reads a saved removal: a draft, read as a workspace reads one, and the
309 * position it had. Anything else is `undefined`, including a draft too
310 * large for any workspace to take back. The result is built afresh from
311 * known fields.
312 */
313export function restoreDraftRemoval(saved: unknown): DraftRemoval | undefined {
314  if (!saved || typeof saved !== "object") return undefined;
315  const { draft: entry, index } = saved as Record<string, unknown>;
316  if (
317    !entry ||
318    typeof entry !== "object" ||
319    typeof index !== "number" ||
320    !Number.isInteger(index) ||
321    index < 0 ||
322    index >= draftLimits.drafts
323  )
324    return undefined;
325  const { id, name, copy, width } = entry as Record<string, unknown>;
326  const draft = draftFrom(id, name, copy, width);
327  if (typeof draft === "string") return undefined;
328  return typeof workspaceFrom(draft.id, [draft]) === "string"
329    ? undefined
330    : { draft, index };
331}
332
333/**
334 * Puts a removed draft back and opens it: the same identity, name, working
335 * copy with its selection and Undo history, and width. No other draft
336 * 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 only
340 * 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 would
344 * be too large. A refusal changes nothing, so the removal can be tried
345 * again later.
346 */
347export function restoreRemovedDraft(
348  workspace: DraftWorkspace | undefined,
349  removed: DraftRemoval,
350): DraftWorkspace {
351  const { id, name, copy, width } = removed.draft;
352  const draft = made(draftFrom(id, name, copy, width));
353  const current = workspace?.drafts ?? [];
354  if (current.some((other) => other.id === draft.id))
355    throw new DraftError("already-restored");
356  const index = Number.isInteger(removed.index)
357    ? Math.min(Math.max(removed.index, 0), current.length)
358    : current.length;
359  const restored = workspaceFrom(draft.id, [
360    ...current.slice(0, index),
361    draft,
362    ...current.slice(index),
363  ]);
364  if (typeof restored === "string")
365    throw new DraftError(restored, restoringProblems[restored]);
366  return restored;
367}