documentation/components/source/playground-page.ts

1import styles from "./playground-page.css";
2import primitiveStyles from "./primitives.css";
3import { Stack, declaration, type Composition } from "./composition.ts";
4import { AxiomaticPlayground, type PlaygroundState } from "./playground.ts";
5import { mountComposition, type MountedComposition } from "./primitives.ts";
6import { decodeSnapshot, encodeSnapshot } from "./snapshot.ts";
7import {
8  type Draft,
9  type DraftWorkspace,
10  type DraftRemoval,
11} from "./drafts.ts";
12import {
13  DraftConflict,
14  DraftRemovalReplacement,
15  DraftStorage,
16  draftStorageKey,
17} from "./draft-storage.ts";
18import { playgroundURL } from "./playground-link.ts";
19import { startWorkingCopy } from "./working-copy.ts";
20
21const message = (error: unknown) =>
22  error instanceof Error ? error.message : "The action could not be completed.";
23const markup = `
24<section class="editor-view" hidden>
25  <div class="workspace-tools">
26    <div class="draft-heading"><label class="draft-title"><span class="sr-only">Draft name</span><input maxlength="80" autocomplete="off" placeholder="Untitled composition"></label><p class="save-status" role="status" aria-live="polite"></p></div>
27    <label class="draft-picker">Your drafts<select aria-label="Your drafts"></select></label>
28    <div class="actions"><button class="new-draft">New draft</button><button class="share">Copy snapshot link</button><button class="remove-draft">Remove draft</button></div>
29  </div>
30  <div class="removal" hidden><p class="removal-note" role="status"></p><button class="undo-removal">Undo removal</button></div>
31  <p class="removal-error" role="alert" hidden></p>
32  <div class="replace-removal" hidden><div class="actions"><button class="confirm-removal">Remove and replace Undo</button><button class="cancel-removal">Keep drafts as they are</button></div></div>
33  <div class="recovery" hidden><p class="problem" role="alert"></p><div class="actions"><button class="retry">Retry save</button><button class="fork">Save mine as a new draft</button><button class="reload-draft">Load saved draft</button></div></div>
34  <div class="link-result" hidden><p class="link-message" role="status"></p><label><span class="sr-only">Snapshot link</span><input class="snapshot-link" readonly></label><p class="local-note"></p></div>
35  <div class="editor-host"></div>
36  <p class="empty-workspace" hidden>No drafts here yet. Create a new draft, or undo your last removal.</p>
37  <p class="privacy">Drafts are saved in this browser. A snapshot link contains a fixed copy of its composition; anyone with the link can open it.</p>
38</section>
39<section class="snapshot-view" hidden>
40  <h1>Composition snapshot</h1>
41  <p class="snapshot-note">A fixed copy, adapting to the space on this page. Editing a copy keeps the snapshot and your existing drafts intact.</p>
42  <div class="actions"><button class="edit-copy">Edit a copy</button><button class="return-drafts">Return to my drafts</button></div>
43  <p class="snapshot-error" role="alert" hidden></p>
44  <div class="snapshot-surface"></div>
45  <details class="snapshot-source"><summary>See the composition</summary><pre></pre></details>
46</section>`;
47
48/** Owns documents and persistence. The editor continues to own tree edits;
49 * the snapshot uses the same bare runtime in one native, fluid slot. */
50class AxiomaticWorkspace extends HTMLElement {
51  readonly root = this.attachShadow({ mode: "open" });
52  private readonly storage = new DraftStorage();
53  private workspace: DraftWorkspace | undefined;
54  private active: Draft | undefined;
55  private base: Draft | undefined;
56  private editor: AxiomaticPlayground | undefined;
57  private pending: Draft | undefined;
58  private saving: Promise<void> | undefined;
59  private blocked = false;
60  private transitioning = false;
61  private routeRevision = 0;
62  private editorRevision = 0;
63  private snapshot: Composition | undefined;
64  private mounted: MountedComposition | undefined;
65  private removed: DraftRemoval | undefined;
66  private removalChange: Promise<void> | undefined;
67  private abort = new AbortController();
68
69  connectedCallback() {
70    this.root.innerHTML = `<style>${styles}${primitiveStyles}</style>${markup}`;
71    const on = (
72      selector: string,
73      event: string,
74      callback: () => void | Promise<void>,
75    ) =>
76      this.get(selector).addEventListener(
77        event,
78        () => {
79          void callback();
80        },
81        { signal: this.abort.signal },
82      );
83    on(".new-draft", "click", () =>
84      this.newDraft(Stack(), "Untitled composition"),
85    );
86    on(".remove-draft", "click", () => this.changeRemoval(false));
87    on(".undo-removal", "click", () => this.changeRemoval(true));
88    on(".confirm-removal", "click", () => this.changeRemoval(false, true));
89    on(".cancel-removal", "click", () => {
90      this.removalError();
91      this.get(".remove-draft").focus();
92    });
93    on(".draft-picker select", "change", () =>
94      this.chooseDraft(
95        this.get<HTMLSelectElement>(".draft-picker select").value,
96      ),
97    );
98    on(".draft-title input", "input", () => {
99      if (!this.active || this.editor?.isMoving) return;
100      this.active = {
101        ...this.active,
102        name: this.get<HTMLInputElement>(".draft-title input").value,
103      };
104      this.queue(this.active);
105    });
106    on(".share", "click", () => this.share());
107    on(".retry", "click", async () => {
108      if (!this.base && this.active) {
109        await this.retryUnsaved();
110        return;
111      }
112      this.blocked = false;
113      this.get(".recovery").hidden = true;
114      if (this.active) this.queue(this.active);
115      await this.flush();
116    });
117    on(
118      ".fork",
119      "click",
120      () =>
121        this.active &&
122        this.newDraft(
123          this.active.copy.model,
124          `${this.active.name || "Untitled"} copy`,
125          true,
126          this.routeRevision,
127          this.active,
128        ),
129    );
130    on(".reload-draft", "click", () => this.loadSaved());
131    on(
132      ".edit-copy",
133      "click",
134      () =>
135        this.snapshot && this.newDraft(this.snapshot, "Snapshot copy", true),
136    );
137    on(".return-drafts", "click", () => this.returnToDrafts());
138    window.addEventListener(
139      "hashchange",
140      () => {
141        void this.route();
142      },
143      { signal: this.abort.signal },
144    );
145    window.addEventListener(
146      "storage",
147      (event) => {
148        if (event.key === draftStorageKey) this.observeStorage();
149      },
150      { signal: this.abort.signal },
151    );
152    window.addEventListener(
153      "beforeunload",
154      (event) => {
155        if (this.pending || this.saving || this.blocked) {
156          event.preventDefault();
157          event.returnValue = "";
158        }
159      },
160      { signal: this.abort.signal },
161    );
162    void this.route();
163  }
164
165  disconnectedCallback() {
166    this.abort.abort();
167    this.mounted?.dispose();
168  }
169  private get<T extends HTMLElement = HTMLElement>(selector: string): T {
170    const element = this.root.querySelector<T>(selector);
171    if (!element) throw new Error(`Missing workspace control ${selector}`);
172    return element;
173  }
174  private status(value: string) {
175    this.get(".save-status").textContent = value;
176  }
177  private controls() {
178    const moving = !!this.editor?.isMoving;
179    if (this.editor) this.editor.inert = this.transitioning;
180    this.get<HTMLSelectElement>(".draft-picker select").disabled =
181      moving ||
182      this.blocked ||
183      !!this.saving ||
184      this.transitioning ||
185      !this.workspace?.drafts.length;
186    this.get<HTMLButtonElement>(".new-draft").disabled =
187      moving || this.blocked || !!this.saving || this.transitioning;
188    this.get<HTMLInputElement>(".draft-title input").disabled =
189      moving || !this.active || this.transitioning;
190    this.get<HTMLButtonElement>(".share").disabled =
191      moving || !this.active || this.transitioning;
192    this.get<HTMLButtonElement>(".remove-draft").disabled =
193      !this.base ||
194      moving ||
195      this.blocked ||
196      !!this.saving ||
197      this.transitioning;
198    this.get<HTMLButtonElement>(".undo-removal").disabled =
199      !this.removed ||
200      moving ||
201      this.blocked ||
202      !!this.saving ||
203      this.transitioning;
204    this.get<HTMLButtonElement>(".confirm-removal").disabled =
205      !this.base ||
206      moving ||
207      this.blocked ||
208      !!this.saving ||
209      this.transitioning;
210    this.get<HTMLButtonElement>(".edit-copy").disabled =
211      !this.snapshot || this.blocked || this.transitioning;
212    this.get<HTMLButtonElement>(".return-drafts").disabled = this.transitioning;
213  }
214  private problem(error: unknown) {
215    this.blocked = true;
216    this.status("Not saved — your edits are still here.");
217    this.get(".problem").textContent = message(error);
218    this.get(".recovery").hidden = false;
219    this.get<HTMLButtonElement>(".reload-draft").disabled = !this.base;
220    this.get(".reload-draft").textContent =
221      this.base &&
222      !this.workspace?.drafts.some((draft) => draft.id === this.base!.id)
223        ? "Close removed draft"
224        : "Load saved draft";
225    this.get(".retry").hidden = error instanceof DraftConflict;
226    this.controls();
227  }
228
229  private list() {
230    const select = this.get<HTMLSelectElement>(".draft-picker select");
231    const drafts = [...(this.workspace?.drafts ?? [])];
232    if (this.active && !drafts.some((draft) => draft.id === this.active!.id))
233      drafts.push(this.active);
234    select.replaceChildren(
235      ...drafts.map((draft) => {
236        const option = document.createElement("option");
237        option.value = draft.id;
238        option.textContent = draft.name || "Untitled composition";
239        return option;
240      }),
241    );
242    if (!this.active && drafts.length) {
243      const placeholder = document.createElement("option");
244      placeholder.value = "";
245      placeholder.textContent = "Choose a draft";
246      placeholder.disabled = true;
247      select.prepend(placeholder);
248    }
249    select.value = this.active?.id ?? "";
250  }
251
252  private open(draft: Draft, persisted = true) {
253    this.editorRevision++;
254    this.removalError();
255    this.active = draft;
256    this.base = persisted ? draft : undefined;
257    this.pending = undefined;
258    this.blocked = false;
259    this.get(".recovery").hidden = true;
260    this.get(".link-result").hidden = true;
261    this.get(".empty-workspace").hidden = true;
262    this.get<HTMLInputElement>(".draft-title input").value = draft.name;
263    this.list();
264    let mounting = true;
265    const editor = document.createElement(
266      "axiomatic-playground",
267    ) as AxiomaticPlayground;
268    editor.setAttribute("standalone", "");
269    editor.initialState = { copy: draft.copy, width: draft.width };
270    editor.addEventListener("composition-change", (event) => {
271      if (mounting || this.editor !== editor || !this.active) return;
272      const state = (event as CustomEvent<PlaygroundState>).detail;
273      this.active = { ...this.active, copy: state.copy, width: state.width };
274      this.queue(this.active);
275    });
276    editor.addEventListener("composition-interaction", () => this.controls());
277    this.editor = editor;
278    this.get(".editor-host").replaceChildren(editor);
279    mounting = false;
280    this.get(".editor-view").hidden = false;
281    this.get(".snapshot-view").hidden = true;
282    this.mounted?.dispose();
283    this.mounted = undefined;
284    this.status(
285      persisted
286        ? "Saved in this browser"
287        : "Not saved — your edits are still here.",
288    );
289    this.controls();
290  }
291
292  private emptyWorkspace() {
293    this.editorRevision++;
294    this.removalError();
295    this.editor = undefined;
296    this.active = undefined;
297    this.base = undefined;
298    this.pending = undefined;
299    this.blocked = false;
300    this.get(".editor-host").replaceChildren();
301    this.get<HTMLInputElement>(".draft-title input").value = "";
302    this.get(".recovery").hidden = true;
303    this.get(".link-result").hidden = true;
304    this.get(".empty-workspace").hidden = false;
305    this.get(".editor-view").hidden = false;
306    this.get(".snapshot-view").hidden = true;
307    this.mounted?.dispose();
308    this.mounted = undefined;
309    this.list();
310    this.status("No saved drafts");
311    history.replaceState(null, "", location.pathname);
312    this.controls();
313  }
314
315  private removalError(error?: unknown) {
316    this.get(".removal-error").hidden = !error;
317    this.get(".removal-error").textContent = error ? message(error) : "";
318    this.get(".replace-removal").hidden = !(
319      error instanceof DraftRemovalReplacement
320    );
321  }
322
323  private refreshRemoval() {
324    try {
325      this.removed = this.storage.lastRemoval();
326      this.get(".removal").hidden = !this.removed;
327      this.get(".removal-note").textContent = this.removed
328        ? `Removed “${this.removed.draft.name || "Untitled composition"}”. Undo removal is available in this tab until you remove another draft or close the tab.`
329        : "";
330      this.get(".empty-workspace").textContent =
331        this.workspace?.drafts.length && !this.editor
332          ? "Choose a draft above to continue working."
333          : this.removed
334            ? "No saved drafts. Create a new draft, or undo your last removal."
335            : "No saved drafts. Create a new draft to begin.";
336    } catch (error) {
337      this.removed = undefined;
338      this.get(".removal").hidden = true;
339      if (this.get(".removal-error").hidden) this.removalError(error);
340    }
341    this.controls();
342  }
343
344  private openWorkspace(workspace: DraftWorkspace) {
345    this.workspace = workspace;
346    const draft = workspace.drafts.find(
347      (item) => item.id === workspace.activeId,
348    );
349    if (draft) {
350      this.open(draft);
351      history.replaceState(null, "", `#draft=${draft.id}`);
352    } else this.emptyWorkspace();
353    this.refreshRemoval();
354  }
355
356  private changeRemoval(
357    restore: boolean,
358    replaceBlockedRemoval = false,
359  ): Promise<void> | undefined {
360    if (
361      this.removalChange ||
362      this.blocked ||
363      this.transitioning ||
364      this.editor?.isMoving ||
365      (restore ? !this.removed : !this.base)
366    )
367      return;
368    const operation = this.performRemoval(restore, replaceBlockedRemoval);
369    this.removalChange = operation;
370    void operation.finally(() => {
371      this.removalChange = undefined;
372    });
373    return operation;
374  }
375
376  private async performRemoval(
377    restore: boolean,
378    replaceBlockedRemoval: boolean,
379  ) {
380    const revision = this.routeRevision;
381    this.transitioning = true;
382    this.controls();
383    this.removalError();
384    let completed = false;
385    let failed = false;
386    try {
387      await this.flush();
388      if (this.blocked || revision !== this.routeRevision) return;
389      const workspace = restore
390        ? await this.storage.undoRemoval()
391        : await this.storage.remove(this.base!, replaceBlockedRemoval);
392      // Navigation waits for this transaction, then reads the resulting state.
393      // It owns the view and focus if the author navigated in the meantime.
394      if (revision !== this.routeRevision) {
395        this.workspace = workspace;
396        this.editorRevision++;
397        this.editor = undefined;
398        this.active = undefined;
399        this.base = undefined;
400        this.pending = undefined;
401        this.blocked = false;
402        this.get(".editor-host").replaceChildren();
403        return;
404      }
405      this.openWorkspace(workspace);
406      if (restore) this.status("Draft restored. Saved in this browser.");
407      completed = true;
408    } catch (error) {
409      if (revision !== this.routeRevision) return;
410      failed = true;
411      if (!(error instanceof DraftConflict)) this.removalError(error);
412      this.observeStorage();
413      this.refreshRemoval();
414    } finally {
415      this.transitioning = false;
416      this.controls();
417      if (completed && revision === this.routeRevision)
418        this.get(restore ? ".draft-title input" : ".undo-removal").focus();
419      else if (failed && revision === this.routeRevision)
420        this.get(
421          !this.get(".replace-removal").hidden
422            ? ".cancel-removal"
423            : this.blocked
424              ? ".fork"
425              : restore
426                ? ".undo-removal"
427                : ".remove-draft",
428        ).focus();
429    }
430  }
431
432  private queue(draft: Draft) {
433    if (JSON.stringify(draft) === JSON.stringify(this.base) && !this.pending)
434      return;
435    this.pending = draft;
436    if (this.blocked || this.saving) return;
437    this.status("Saving…");
438    this.saving = this.drain().finally(() => {
439      this.saving = undefined;
440      this.controls();
441      if (!this.blocked) this.observeStorage();
442      if (this.pending && !this.blocked) this.queue(this.pending);
443    });
444    this.controls();
445  }
446  private async drain() {
447    const revision = this.editorRevision;
448    while (this.pending && !this.blocked) {
449      const draft = this.pending;
450      this.pending = undefined;
451      try {
452        const workspace = await this.storage.save(draft, this.base);
453        if (revision !== this.editorRevision) return;
454        this.workspace = workspace;
455        this.base = workspace.drafts.find((item) => item.id === draft.id);
456        this.list();
457        if (!this.pending) this.status("Saved in this browser");
458      } catch (error) {
459        if (revision !== this.editorRevision) return;
460        this.pending ??= draft;
461        this.problem(error);
462      }
463    }
464  }
465  private async flush() {
466    this.editor?.finishEditing();
467    await this.saving;
468  }
469
470  private async retryUnsaved() {
471    if (!this.active || this.transitioning) return;
472    const draft = this.active;
473    this.transitioning = true;
474    this.controls();
475    try {
476      this.workspace = await this.storage.create(
477        draft.copy.model,
478        draft.name,
479        draft,
480      );
481      const saved = this.workspace.drafts.find(
482        (item) => item.id === this.workspace!.activeId,
483      )!;
484      this.open(saved);
485      history.replaceState(null, "", `#draft=${saved.id}`);
486    } catch (error) {
487      this.problem(error);
488    } finally {
489      this.transitioning = false;
490      this.controls();
491    }
492  }
493
494  private async newDraft(
495    tree: Composition,
496    name: string,
497    recovery = false,
498    revision = this.routeRevision,
499    state?: Pick<Draft, "copy" | "width">,
500  ) {
501    if (this.blocked && this.editor && tree !== this.active?.copy.model) {
502      this.showSnapshot(
503        tree,
504        "Your current draft has unsaved changes. Return to your drafts to save them before editing this copy.",
505      );
506      return;
507    }
508    if (
509      this.transitioning ||
510      this.editor?.isMoving ||
511      (this.blocked && !recovery)
512    )
513      return;
514    this.transitioning = true;
515    this.controls();
516    try {
517      await this.flush();
518      if (revision !== this.routeRevision || (this.blocked && !recovery))
519        return;
520      if (this.blocked && this.editor && tree !== this.active?.copy.model) {
521        this.showSnapshot(
522          tree,
523          "Your current draft has unsaved changes. Return to your drafts to save them before editing this copy.",
524        );
525        return;
526      }
527      const created = await this.storage.create(tree, name.slice(0, 80), state);
528      if (revision !== this.routeRevision) return;
529      this.workspace = created;
530      const draft = this.workspace.drafts.find(
531        (item) => item.id === this.workspace!.activeId,
532      )!;
533      this.open(draft);
534      history.replaceState(null, "", `#draft=${draft.id}`);
535      this.get<HTMLInputElement>(".draft-title input").focus();
536    } catch (error) {
537      if (revision !== this.routeRevision) return;
538      // Keep imported work visible and its fragment recoverable if persistence fails.
539      if (!this.editor || (recovery && !this.blocked))
540        this.open(
541          {
542            id: crypto.randomUUID(),
543            name,
544            copy: { ...startWorkingCopy(tree), chosen: ["0"] },
545            width: 600,
546          },
547          false,
548        );
549      this.problem(error);
550    } finally {
551      this.transitioning = false;
552      this.controls();
553    }
554  }
555  private async chooseDraft(id: string, discard = false) {
556    if (this.transitioning || this.editor?.isMoving) return;
557    const revision = this.routeRevision;
558    this.transitioning = true;
559    this.controls();
560    try {
561      if (discard) await this.saving;
562      else {
563        await this.flush();
564        if (this.blocked) return;
565      }
566      if (revision !== this.routeRevision) return;
567      const workspace = await this.storage.activate(id);
568      if (revision !== this.routeRevision) return;
569      this.workspace = workspace;
570      const draft = workspace.drafts.find((item) => item.id === id)!;
571      this.open(draft);
572      history.replaceState(null, "", `#draft=${id}`);
573    } catch (error) {
574      this.problem(error);
575    } finally {
576      this.transitioning = false;
577      this.controls();
578    }
579  }
580
581  private async loadSaved() {
582    if (!this.base || this.transitioning || this.editor?.isMoving) return;
583    const revision = this.routeRevision;
584    const base = this.base;
585    try {
586      await this.saving;
587      if (revision !== this.routeRevision) return;
588      const workspace = this.storage.read();
589      if (workspace?.drafts.some((draft) => draft.id === base.id)) {
590        await this.chooseDraft(base.id, true);
591      } else {
592        this.openWorkspace(
593          workspace ?? { version: 1, activeId: null, drafts: [] },
594        );
595        this.get(this.active ? ".draft-title input" : ".new-draft").focus();
596      }
597    } catch (error) {
598      this.problem(error);
599    }
600  }
601
602  private observeStorage() {
603    try {
604      const workspace = this.storage.read();
605      this.workspace = workspace;
606      if (this.base && !this.saving) {
607        const current = workspace?.drafts.find(
608          (draft) => draft.id === this.base!.id,
609        );
610        if (JSON.stringify(current) !== JSON.stringify(this.base)) {
611          this.problem(
612            new DraftConflict(
613              current
614                ? "This draft changed in another tab. Keep your edits as a new draft, or load the saved version."
615                : "This draft was removed in another tab. Save your work as a new draft, or close this editor to return to saved drafts.",
616            ),
617          );
618          return;
619        }
620      }
621      this.workspace = workspace;
622      this.list();
623      if (
624        !this.editor &&
625        !this.get(".editor-view").hidden &&
626        workspace?.drafts.length
627      ) {
628        this.status("Choose a saved draft, or create a new one.");
629      }
630      this.refreshRemoval();
631    } catch (error) {
632      if (this.editor) this.problem(error);
633    }
634  }
635
636  private async route() {
637    const revision = ++this.routeRevision;
638    const hash = location.hash.slice(1);
639    await this.removalChange;
640    if (revision !== this.routeRevision) return;
641    this.removalError();
642    this.refreshRemoval();
643    this.editor?.prepareToLeave();
644    await this.flush();
645    if (revision !== this.routeRevision) return;
646    if (hash.startsWith("snapshot=") || hash.startsWith("edit=")) {
647      try {
648        const tree = decodeSnapshot(hash.slice(hash.indexOf("=") + 1));
649        if (hash.startsWith("edit="))
650          await this.newDraft(tree, "From the guide", true, revision);
651        else this.showSnapshot(tree);
652      } catch (error) {
653        this.showSnapshot(undefined, message(error));
654      }
655      return;
656    }
657    if (this.editor && !hash.startsWith("draft=")) {
658      this.observeStorage();
659      if (this.active && this.base)
660        history.replaceState(null, "", `#draft=${this.active.id}`);
661      this.get(".editor-view").hidden = false;
662      this.get(".snapshot-view").hidden = true;
663      this.mounted?.dispose();
664      this.mounted = undefined;
665      return;
666    }
667    if (this.editor && this.blocked) {
668      this.get(".editor-view").hidden = false;
669      this.get(".snapshot-view").hidden = true;
670      return;
671    }
672    try {
673      this.workspace = this.storage.read();
674      const id = hash.startsWith("draft=")
675        ? hash.slice(6)
676        : this.workspace?.activeId;
677      const draft = this.workspace?.drafts.find((item) => item.id === id);
678      if (draft) {
679        this.open(draft);
680        history.replaceState(null, "", `#draft=${draft.id}`);
681      } else if (this.workspace?.drafts.length)
682        this.openWorkspace(this.workspace);
683      else if (this.workspace) this.emptyWorkspace();
684      else await this.newDraft(Stack(), "Untitled composition");
685    } catch (error) {
686      this.open(
687        {
688          id: crypto.randomUUID(),
689          name: "Untitled composition",
690          copy: { ...startWorkingCopy(Stack()), chosen: ["0"] },
691          width: 600,
692        },
693        false,
694      );
695      this.problem(error);
696    }
697  }
698  private showSnapshot(tree: Composition | undefined, error?: string) {
699    this.snapshot = tree;
700    this.get(".editor-view").hidden = true;
701    this.get(".snapshot-view").hidden = false;
702    this.get(".snapshot-error").hidden = !error;
703    this.get(".snapshot-error").textContent = error ?? "";
704    this.get<HTMLButtonElement>(".edit-copy").disabled = !tree || this.blocked;
705    this.get(".snapshot-source").hidden = !tree;
706    this.get(".snapshot-surface").hidden = !tree;
707    this.mounted?.dispose();
708    this.mounted = undefined;
709    this.get(".snapshot-surface").replaceChildren();
710    if (tree) {
711      this.mounted = mountComposition(this.get(".snapshot-surface"), tree);
712      this.get(".snapshot-source pre").textContent = declaration(tree)
713        .map((line) => line.tokens.map((token) => token.text).join(""))
714        .join("\n");
715    }
716  }
717  private async returnToDrafts() {
718    history.replaceState(null, "", location.pathname);
719    await this.route();
720  }
721  private async share() {
722    if (!this.editor || this.editor.isMoving) return;
723    const state = this.editor.finishEditing();
724    if (!state) return;
725    try {
726      const link = playgroundURL(
727        "snapshot",
728        encodeSnapshot(state.copy.model),
729      ).href;
730      const field = this.get<HTMLInputElement>(".snapshot-link");
731      field.value = link;
732      field.parentElement!.hidden = false;
733      this.get(".link-result").hidden = false;
734      this.get(".local-note").textContent = [
735        "localhost",
736        "127.0.0.1",
737        "[::1]",
738      ].includes(location.hostname)
739        ? "This link works on this computer while the local server is running. Sharing across devices will be available after hosting."
740        : "This is a fixed copy. Later edits to your draft leave this link unchanged.";
741      try {
742        await navigator.clipboard.writeText(link);
743        this.get(".link-message").textContent = "Snapshot link copied.";
744      } catch {
745        this.get(".link-message").textContent =
746          "Copy this link to share the snapshot.";
747        field.focus();
748        field.select();
749      }
750    } catch (error) {
751      this.get(".link-result").hidden = false;
752      this.get(".link-message").textContent = message(error);
753      this.get<HTMLInputElement>(".snapshot-link").value = "";
754      this.get<HTMLInputElement>(".snapshot-link").parentElement!.hidden = true;
755      this.get(".local-note").textContent = "";
756    }
757  }
758}
759if (!customElements.get("axiomatic-workspace"))
760  customElements.define("axiomatic-workspace", AxiomaticWorkspace);