documentation/components/source/draft-storage.ts

1import {
2  activateDraft,
3  createDraft,
4  draftLimits,
5  restoreDraftWorkspace,
6  removeDraft,
7  restoreDraftRemoval,
8  restoreRemovedDraft,
9  updateDraft,
10  type Draft,
11  type DraftWorkspace,
12  type DraftRemoval,
13} from "./drafts.ts";
14import type { Composition } from "./composition.ts";
15
16export const draftStorageKey = "axiomatic-drafts:v1";
17export const draftRemovalKey = "axiomatic-last-removal:v1";
18export class DraftConflict extends Error {}
19export class DraftRemovalReplacement extends Error {}
20
21export interface RemovalStorage {
22  read(): string | null;
23  write(value: string | null): void;
24}
25const browserRemoval: RemovalStorage = {
26  read: () => sessionStorage.getItem(draftRemovalKey),
27  write: (value) => {
28    if (value === null) sessionStorage.removeItem(draftRemovalKey);
29    else sessionStorage.setItem(draftRemovalKey, value);
30  },
31};
32
33export interface DraftStorageEnvironment {
34  read(): string | null;
35  write(value: string): void;
36  exclusive<T>(action: () => T): Promise<T>;
37}
38const browserStorage: DraftStorageEnvironment = {
39  read: () => localStorage.getItem(draftStorageKey),
40  write: (value) => localStorage.setItem(draftStorageKey, value),
41  exclusive: (action) => {
42    if (!navigator.locks)
43      return Promise.reject(
44        new Error(
45          "Saving drafts needs HTTPS or localhost in a modern browser.",
46        ),
47      );
48    return navigator.locks.request(draftStorageKey, action);
49  },
50};
51
52/** Native locks serialize the read/check/write across tabs. Comparing the
53 * saved draft with our base prevents a stale editor from overwriting it. */
54export class DraftStorage {
55  private readonly environment: DraftStorageEnvironment;
56  private readonly removal: RemovalStorage;
57  constructor(
58    environment: DraftStorageEnvironment = browserStorage,
59    removal: RemovalStorage = browserRemoval,
60  ) {
61    this.environment = environment;
62    this.removal = removal;
63  }
64  read(): DraftWorkspace | undefined {
65    const raw = this.environment.read();
66    if (raw === null) return undefined;
67    if (raw.length > draftLimits.characters)
68      throw new Error("Stored drafts are too large to open.");
69    const value = restoreDraftWorkspace(JSON.parse(raw));
70    if (!value)
71      throw new Error(
72        "Stored drafts could not be read. They have been left unchanged.",
73      );
74    return value;
75  }
76
77  private write(value: DraftWorkspace): DraftWorkspace {
78    const restored = restoreDraftWorkspace(value);
79    if (!restored)
80      throw new Error(
81        "These drafts are too large to save. Your previous saved work is unchanged.",
82      );
83    this.environment.write(JSON.stringify(restored));
84    return restored;
85  }
86
87  private locked<T>(action: () => T): Promise<T> {
88    return this.environment.exclusive(action);
89  }
90
91  create(
92    tree: Composition,
93    name: string,
94    state?: Pick<Draft, "copy" | "width">,
95  ): Promise<DraftWorkspace> {
96    return this.locked(() => {
97      const workspace = this.read();
98      const names = new Set(workspace?.drafts.map((draft) => draft.name));
99      const stem = (name.trim() || "Untitled composition").slice(0, 72);
100      let unique = stem;
101      for (let index = 2; names.has(unique); index++)
102        unique = `${stem} (${index})`;
103      const id = crypto.randomUUID();
104      let next = createDraft(workspace, tree, unique, id);
105      if (state) next = updateDraft(next, id, state.copy, state.width, unique);
106      return this.write(next);
107    });
108  }
109
110  save(draft: Draft, base: Draft | undefined): Promise<DraftWorkspace> {
111    return this.locked(() => {
112      const workspace = this.read();
113      const current = workspace?.drafts.find((item) => item.id === draft.id);
114      if (
115        !workspace ||
116        !base ||
117        JSON.stringify(current) !== JSON.stringify(base)
118      )
119        throw new DraftConflict(
120          current
121            ? "This draft changed in another tab. Your edits here are still available."
122            : "This draft was removed in another tab. Your edits here are still available to save as a new draft.",
123        );
124      return this.write(
125        updateDraft(workspace, draft.id, draft.copy, draft.width, draft.name),
126      );
127    });
128  }
129
130  activate(id: string): Promise<DraftWorkspace> {
131    return this.locked(() => {
132      const workspace = this.read();
133      if (!workspace)
134        throw new Error("This saved draft is no longer available.");
135      return this.write(activateDraft(workspace, id));
136    });
137  }
138
139  lastRemoval(): DraftRemoval | undefined {
140    const raw = this.removal.read();
141    if (raw === null) return undefined;
142    if (raw.length > draftLimits.characters)
143      throw new Error("The removed draft could not be read.");
144    const value: unknown = JSON.parse(raw);
145    const restored =
146      value &&
147      typeof value === "object" &&
148      "version" in value &&
149      value.version === 1
150        ? restoreDraftRemoval(value)
151        : undefined;
152    if (!restored) throw new Error("The removed draft could not be read.");
153    // A successful restoration is durable even if clearing its receipt failed.
154    let workspace: DraftWorkspace | undefined;
155    try {
156      workspace = this.read();
157    } catch {
158      // The receipt is readable even if durable storage is not. Restoration
159      // still refuses to replace unreadable work inside the locked transaction.
160    }
161    if (workspace?.drafts.some((draft) => draft.id === restored.draft.id))
162      return undefined;
163    return restored;
164  }
165
166  remove(base: Draft, replaceBlockedRemoval = false): Promise<DraftWorkspace> {
167    return this.locked(() => {
168      const workspace = this.read();
169      const current = workspace?.drafts.find((draft) => draft.id === base.id);
170      if (!workspace || JSON.stringify(current) !== JSON.stringify(base))
171        throw new DraftConflict(
172          current
173            ? "This draft changed in another tab. Your draft has not been removed."
174            : "This draft was already removed in another tab. Your work here is still available.",
175        );
176      const result = removeDraft(workspace, base.id);
177      let previousRemoval: DraftRemoval | undefined;
178      try {
179        previousRemoval = this.lastRemoval();
180      } catch {
181        if (!replaceBlockedRemoval)
182          throw new DraftRemovalReplacement(
183            `The previous Undo removal entry cannot be read. Removing “${base.name || "Untitled composition"}” will replace it.`,
184          );
185      }
186      if (previousRemoval && !replaceBlockedRemoval) {
187        try {
188          restoreRemovedDraft(workspace, previousRemoval);
189        } catch {
190          throw new DraftRemovalReplacement(
191            `“${previousRemoval.draft.name || "Untitled composition"}” cannot currently be restored. Removing “${base.name || "Untitled composition"}” will replace its Undo removal entry.`,
192          );
193        }
194      }
195      const previous = this.removal.read();
196      // Save the recovery copy before deleting anything durable. A refusal
197      // leaves both the workspace and the previous removal unchanged.
198      this.removal.write(JSON.stringify({ version: 1, ...result.removed }));
199      try {
200        return this.write(result.workspace);
201      } catch (error) {
202        try {
203          this.removal.write(previous);
204        } catch (rollbackError) {
205          throw new AggregateError(
206            [error, rollbackError],
207            "The draft was not removed. Storage also refused to recover the previous Undo removal entry.",
208          );
209        }
210        throw error;
211      }
212    });
213  }
214
215  undoRemoval(): Promise<DraftWorkspace> {
216    return this.locked(() => {
217      const removed = this.lastRemoval();
218      if (!removed)
219        throw new Error("There is no removed draft to restore in this tab.");
220      const workspace = this.write(restoreRemovedDraft(this.read(), removed));
221      try {
222        this.removal.write(null);
223      } catch {
224        // The saved draft is authoritative; lastRemoval ignores its old receipt.
225      }
226      return workspace;
227    });
228  }
229}