@templatical/core 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { r as UseEditorReturn } from "../editor-BCujEIye.js";
1
+ import { r as UseEditorReturn } from "../editor-Bl4WsPU3.js";
2
2
  import { AiChatMessage, AiConfig, AuthConfig, AuthRequestOptions, Block, Collaborator, CommentResponse, CommentsProvider, CustomFont, ExportResult, FontsConfig, HealthCheckResult, McpOperationPayload, MergeTag, PlanConfig, PlanFeatures, RenderProvider, SavedBlock, SavedBlocksProvider, ScoringCategory, ScoringFinding, ScoringResult, SdkAuthConfig, Template, TemplateContent, TemplatePatch, TemplateVersionResponse, TemplatesProvider, TestEmailConfig, TestEmailProvider, UserConfig, VersionHistoryProvider, WebSocketServerConfig } from "@templatical/types";
3
3
  import { ComputedRef, Ref, ref } from "vue";
4
4
  import { Channel, PresenceChannel } from "pusher-js";
@@ -1,4 +1,4 @@
1
- import { Block, Template, TemplateContent, TemplateDefaults, TemplateSettings, TemplatesProvider, UiTheme, ViewportSize } from "@templatical/types";
1
+ import { Block, Template, TemplateContent, TemplateDefaults, TemplateSaveTrigger, TemplateSettings, TemplatesProvider, UiTheme, ViewportSize } from "@templatical/types";
2
2
  import { DeepReadonly, Ref } from "@vue/reactivity";
3
3
  //#region src/editor.d.ts
4
4
  interface EditorState {
@@ -88,12 +88,18 @@ interface UseEditorReturn {
88
88
  }) => Promise<Template>;
89
89
  /** Fetch a template and make it the editor's content. */
90
90
  load: (templateId: string) => Promise<Template>;
91
- /** Persist the loaded template's name + content as a patch. */
92
- save: () => Promise<Template>;
91
+ /**
92
+ * Persist the loaded template's name + content as a patch.
93
+ *
94
+ * `trigger` is passed through to `TemplatesOptions.onSaved`. It defaults to
95
+ * `"api"`, which is the honest answer for a direct call — the editor package
96
+ * passes the value matching whichever affordance fired.
97
+ */
98
+ save: (trigger?: TemplateSaveTrigger) => Promise<Template>;
93
99
  /** Whether a template has been created or loaded. */
94
100
  hasTemplate: () => boolean;
95
101
  }
96
102
  declare function useEditor(options: UseEditorOptions): UseEditorReturn;
97
103
  //#endregion
98
104
  export { useEditor as i, UseEditorOptions as n, UseEditorReturn as r, EditorState as t };
99
- //# sourceMappingURL=editor-BCujEIye.d.ts.map
105
+ //# sourceMappingURL=editor-Bl4WsPU3.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as useEditor, n as UseEditorOptions, r as UseEditorReturn, t as EditorState } from "./editor-BCujEIye.js";
2
- import { Block, BlockDefaults, BlockType, Comment, CommentAuthor, CommentEvent, CommentInput, CommentPatch, CommentsListParams, CommentsProvider, CustomBlock, CustomBlockDefinition, SavedBlock, SavedBlockPatch, SavedBlocksListParams, SavedBlocksProvider, Template, TemplateContent, TemplateSettings, TemplateVersion, VersionHistoryListParams, VersionHistoryProvider } from "@templatical/types";
1
+ import { i as useEditor, n as UseEditorOptions, r as UseEditorReturn, t as EditorState } from "./editor-Bl4WsPU3.js";
2
+ import { Block, BlockDefaults, BlockType, Comment, CommentAuthor, CommentInput, CommentPatch, CommentsListParams, CommentsProvider, CustomBlock, CustomBlockDefinition, SavedBlock, SavedBlockPatch, SavedBlocksListParams, SavedBlocksProvider, Template, TemplateContent, TemplateSettings, TemplateVersion, VersionHistoryListParams, VersionHistoryProvider } from "@templatical/types";
3
3
  import { ComputedRef, Ref } from "@vue/reactivity";
4
4
  import { ComputedRef as ComputedRef$1, Ref as Ref$1 } from "vue";
5
5
  //#region src/history.d.ts
@@ -312,8 +312,6 @@ interface UseCommentsOptions {
312
312
  * than no comment feature.
313
313
  */
314
314
  getUser: () => CommentAuthor | null;
315
- /** Fired for every change this composable applied, local or remote. */
316
- onComment?: (event: CommentEvent) => void;
317
315
  onError?: (error: Error) => void;
318
316
  }
319
317
  interface UseCommentsReturn {
package/dist/index.js CHANGED
@@ -1,6 +1,36 @@
1
1
  import { SdkError, createBlock, createDefaultTemplateContent, generateId, safeClone } from "@templatical/types";
2
2
  import { computed, reactive, readonly, ref, watch } from "@vue/reactivity";
3
3
  import { computed as computed$1, onScopeDispose, ref as ref$1, watch as watch$1 } from "vue";
4
+ //#region src/error-reporting.ts
5
+ /**
6
+ * Turn a thrown value into an `Error`.
7
+ *
8
+ * A `catch` clause's binding is `unknown` — a provider or a consumer's event
9
+ * handler can throw a string, an object, or anything else. `onError` callbacks
10
+ * across this package are typed to take an `Error`, so this is what makes that
11
+ * contract honest at the one place values actually cross it.
12
+ */
13
+ function wrapReportedError(error) {
14
+ return error instanceof Error ? error : new Error(String(error), { cause: error });
15
+ }
16
+ /**
17
+ * Run a consumer's event handler without letting it fail the operation it
18
+ * followed.
19
+ *
20
+ * A handler that throws must not turn a completed write into a rejected one —
21
+ * the caller has already succeeded by the time this runs. `onError` is taken
22
+ * as a parameter rather than read from a shared reporter, so every feature
23
+ * module keeps its own `options.onError` wiring and this stays reusable by
24
+ * any module with the same fire-and-forget event shape.
25
+ */
26
+ function notifyHandler(onError, run) {
27
+ try {
28
+ run();
29
+ } catch (error) {
30
+ onError?.(wrapReportedError(error));
31
+ }
32
+ }
33
+ //#endregion
4
34
  //#region src/editor.ts
5
35
  function getColumnCount(layout) {
6
36
  if (layout === "1") return 1;
@@ -189,6 +219,15 @@ function useEditor(options) {
189
219
  function refuse(action, reason) {
190
220
  throw new SdkError(`[Templatical] Templates: ${action} ${reason}`);
191
221
  }
222
+ /**
223
+ * Run a consumer's event handler without letting it fail the operation.
224
+ *
225
+ * A handler that throws must not turn a completed write into a rejected one —
226
+ * the UI would report a failure for something that landed.
227
+ */
228
+ function notify(run) {
229
+ notifyHandler(options.onError, run);
230
+ }
192
231
  function requireProvider(action) {
193
232
  const { templates } = options;
194
233
  if (!templates) refuse(action, "needs a templates provider. Pass one as `init({ templates })` to enable saving and loading.");
@@ -203,44 +242,50 @@ function useEditor(options) {
203
242
  touch();
204
243
  }
205
244
  async function create(input) {
206
- const { create: providerCreate } = requireProvider("create()");
245
+ const provider = requireProvider("create()");
246
+ const { create: providerCreate } = provider;
207
247
  if (typeof providerCreate !== "function") refuse("create()", "is disabled by the provider — its `create` is `false`.");
248
+ let created;
208
249
  state.isLoading = true;
209
250
  try {
210
251
  if (input?.content) state.content = input.content;
211
252
  const revisionAtRequest = revision;
212
- const template = await providerCreate(input?.name !== void 0 ? {
253
+ created = await providerCreate(input?.name !== void 0 ? {
213
254
  name: input.name,
214
255
  content: state.content
215
256
  } : { content: state.content });
216
- state.template = template;
257
+ state.template = created;
217
258
  if (revision === revisionAtRequest) state.isDirty = false;
218
- return template;
219
259
  } catch (error) {
220
260
  options.onError?.(error);
221
261
  throw error;
222
262
  } finally {
223
263
  state.isLoading = false;
224
264
  }
265
+ notify(() => provider.onCreated?.(created));
266
+ return created;
225
267
  }
226
268
  async function load(templateId) {
227
269
  const provider = requireProvider("load()");
270
+ let loaded;
228
271
  state.isLoading = true;
229
272
  try {
230
- const template = await provider.load(templateId);
231
- state.template = template;
232
- state.content = template.content;
273
+ loaded = await provider.load(templateId);
274
+ state.template = loaded;
275
+ state.content = loaded.content;
233
276
  state.isDirty = false;
234
- return template;
235
277
  } catch (error) {
236
278
  options.onError?.(error);
237
279
  throw error;
238
280
  } finally {
239
281
  state.isLoading = false;
240
282
  }
283
+ notify(() => provider.onLoaded?.(loaded));
284
+ return loaded;
241
285
  }
242
- async function save() {
243
- const { save: providerSave } = requireProvider("save()");
286
+ async function save(trigger = "api") {
287
+ const provider = requireProvider("save()");
288
+ const { save: providerSave } = provider;
244
289
  if (typeof providerSave !== "function") refuse("save()", "is disabled by the provider — its `save` is `false`.");
245
290
  const current = state.template;
246
291
  if (!current) refuse("save()", "has no template loaded. Call create() or load() first.");
@@ -248,25 +293,27 @@ function useEditor(options) {
248
293
  name: current.name,
249
294
  content: state.content
250
295
  } : { content: state.content };
296
+ let saved;
251
297
  state.isSaving = true;
252
298
  try {
253
299
  const revisionAtRequest = revision;
254
- const template = await providerSave(current.id, patch);
300
+ saved = await providerSave(current.id, patch);
255
301
  if (state.template?.id === current.id) {
256
302
  const localName = state.template.name;
257
303
  state.template = localName !== current.name ? {
258
- ...template,
304
+ ...saved,
259
305
  name: localName
260
- } : template;
306
+ } : saved;
261
307
  }
262
308
  if (revision === revisionAtRequest) state.isDirty = false;
263
- return template;
264
309
  } catch (error) {
265
310
  options.onError?.(error);
266
311
  throw error;
267
312
  } finally {
268
313
  state.isSaving = false;
269
314
  }
315
+ notify(() => provider.onSaved?.(saved, { trigger }));
316
+ return saved;
270
317
  }
271
318
  function hasTemplate() {
272
319
  return state.template?.id !== void 0;
@@ -662,6 +709,15 @@ function useSavedBlocks(options) {
662
709
  function refuse(action, reason) {
663
710
  throw new SdkError(`[Templatical] Saved blocks: ${action} is ${reason}. Check the capability before calling — the editor's own UI hides the action.`);
664
711
  }
712
+ /**
713
+ * Run a consumer's event handler without letting it fail the operation.
714
+ *
715
+ * A handler that throws must not turn a completed write into a rejected one —
716
+ * the UI would report a failure for a saved block that was created.
717
+ */
718
+ function notify(run) {
719
+ notifyHandler(options.onError, run);
720
+ }
665
721
  async function load(params) {
666
722
  isLoading.value = true;
667
723
  try {
@@ -686,6 +742,7 @@ function useSavedBlocks(options) {
686
742
  content
687
743
  });
688
744
  savedBlocks.value = [created, ...savedBlocks.value];
745
+ notify(() => provider.onCreated?.(created));
689
746
  return created;
690
747
  } catch (error) {
691
748
  options.onError?.(error);
@@ -700,6 +757,7 @@ function useSavedBlocks(options) {
700
757
  try {
701
758
  const updated = await providerUpdate(id, patch);
702
759
  savedBlocks.value = savedBlocks.value.map((b) => b.id === id ? updated : b);
760
+ notify(() => provider.onUpdated?.(updated));
703
761
  return updated;
704
762
  } catch (error) {
705
763
  options.onError?.(error);
@@ -709,11 +767,12 @@ function useSavedBlocks(options) {
709
767
  async function remove(id) {
710
768
  const { delete: providerDelete } = provider;
711
769
  if (typeof providerDelete !== "function") refuse("delete", "disabled by the provider");
712
- const local = savedBlocks.value.find((b) => b.id === id);
713
- if (local && local.canDelete === false) refuse("delete", `not permitted for entry "${id}"`);
770
+ const removed = savedBlocks.value.find((b) => b.id === id) ?? null;
771
+ if (removed && removed.canDelete === false) refuse("delete", `not permitted for entry "${id}"`);
714
772
  try {
715
773
  await providerDelete(id);
716
774
  savedBlocks.value = savedBlocks.value.filter((b) => b.id !== id);
775
+ if (removed) notify(() => provider.onDeleted?.(removed));
717
776
  } catch (error) {
718
777
  options.onError?.(error);
719
778
  throw error;
@@ -853,6 +912,15 @@ function useVersionHistory(options) {
853
912
  function refuse(action) {
854
913
  throw new SdkError(`[Templatical] Version history: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`);
855
914
  }
915
+ /**
916
+ * Run a consumer's event handler without letting it fail the operation.
917
+ *
918
+ * A handler that throws must not turn a completed write into a rejected one —
919
+ * the UI would report a failure for a version that was recorded or restored.
920
+ */
921
+ function notify(run) {
922
+ notifyHandler(options.onError, run);
923
+ }
856
924
  async function load(params) {
857
925
  const templateId = requireTemplateId("list");
858
926
  isLoading.value = true;
@@ -890,6 +958,7 @@ function useVersionHistory(options) {
890
958
  try {
891
959
  const created = await providerCreate(templateId, content, meta);
892
960
  versions.value = [created, ...versions.value];
961
+ notify(() => provider.onCreated?.(created));
893
962
  return created;
894
963
  } catch (error) {
895
964
  options.onError?.(error);
@@ -900,15 +969,18 @@ function useVersionHistory(options) {
900
969
  const { restore: providerRestore } = provider;
901
970
  if (typeof providerRestore !== "function") refuse("restore");
902
971
  const templateId = requireTemplateId("restore");
972
+ let restored;
903
973
  isRestoring.value = true;
904
974
  try {
905
- return await providerRestore(templateId, versionId);
975
+ restored = await providerRestore(templateId, versionId);
906
976
  } catch (error) {
907
977
  options.onError?.(error);
908
978
  throw error;
909
979
  } finally {
910
980
  isRestoring.value = false;
911
981
  }
982
+ notify(() => provider.onRestored?.(restored));
983
+ return restored;
912
984
  }
913
985
  return {
914
986
  nextCursor,
@@ -987,22 +1059,20 @@ function useComments(options) {
987
1059
  const user = getUser();
988
1060
  return user !== null && comment.author.id === user.id;
989
1061
  }
990
- function emit(type, comment) {
991
- options.onComment?.({
992
- type,
993
- comment
994
- });
995
- }
996
1062
  function report(error) {
997
- const wrapped = error instanceof Error ? error : new Error(String(error), { cause: error });
1063
+ const wrapped = wrapReportedError(error);
998
1064
  options.onError?.(wrapped);
999
1065
  throw wrapped;
1000
1066
  }
1001
1067
  /**
1002
- * Insert a comment, replacing an entry with the same id rather than duplicating
1003
- * it. `create` and a subscribe echo of that same create both land here, which is
1004
- * why a provider does not have to de-duplicate its own broadcasts.
1068
+ * Run a consumer's event handler without letting it fail the operation.
1069
+ *
1070
+ * A handler that throws must not turn a completed write into a rejected one —
1071
+ * the UI would report a failure for a comment that was created.
1005
1072
  */
1073
+ function notify(run) {
1074
+ notifyHandler(options.onError, run);
1075
+ }
1006
1076
  function replaceAt(list, index, next) {
1007
1077
  return [
1008
1078
  ...list.slice(0, index),
@@ -1010,28 +1080,60 @@ function useComments(options) {
1010
1080
  ...list.slice(index + 1)
1011
1081
  ];
1012
1082
  }
1083
+ /**
1084
+ * Key-order sensitive: identical fields serialized in a different order
1085
+ * compare unequal, so an echo whose transport frame orders keys
1086
+ * differently than the mutation response it echoes would not be
1087
+ * suppressed. Accepted rather than a defect — not worth a deep-equal
1088
+ * dependency for it.
1089
+ */
1090
+ function sameComment(a, b) {
1091
+ return a !== void 0 && JSON.stringify(a) === JSON.stringify(b);
1092
+ }
1093
+ /**
1094
+ * Insert a comment, replacing an entry with the same id rather than
1095
+ * duplicating it, and report whether the list actually changed.
1096
+ *
1097
+ * The **remote** apply paths (`applyRemoteCreate` / `applyRemoteUpdate`)
1098
+ * emit their event only when this returns `true`. A transport's own
1099
+ * broadcast can come back to the sender — `CommentsProvider.subscribe`'s
1100
+ * contract permits it — and emitting unconditionally fires the handler
1101
+ * twice for one comment. The comparison below runs against the **merged**
1102
+ * result, never the raw payload: the root branch keeps already-loaded
1103
+ * `replies` when an update payload carries none, so comparing the payload
1104
+ * directly would report a change for an echo that altered nothing.
1105
+ * Deleting the `sameComment` check as a redundant no-op reinstates the
1106
+ * double-fire.
1107
+ */
1013
1108
  function upsert(comment) {
1014
1109
  if (comment.parentId) {
1015
- comments.value = comments.value.map((thread) => {
1110
+ let changed = false;
1111
+ const next = comments.value.map((thread) => {
1016
1112
  if (thread.id !== comment.parentId) return thread;
1017
1113
  const replies = thread.replies ?? [];
1018
1114
  const at = replies.findIndex((reply) => reply.id === comment.id);
1115
+ if (at !== -1 && sameComment(replies[at], comment)) return thread;
1116
+ changed = true;
1019
1117
  return {
1020
1118
  ...thread,
1021
1119
  replies: at === -1 ? [...replies, comment] : replaceAt(replies, at, comment)
1022
1120
  };
1023
1121
  });
1024
- return;
1122
+ if (changed) comments.value = next;
1123
+ return changed;
1025
1124
  }
1026
1125
  const at = comments.value.findIndex((thread) => thread.id === comment.id);
1027
1126
  if (at === -1) {
1028
1127
  comments.value = [...comments.value, comment];
1029
- return;
1128
+ return true;
1030
1129
  }
1031
- comments.value = replaceAt(comments.value, at, {
1130
+ const next = {
1032
1131
  ...comment,
1033
1132
  replies: comment.replies ?? comments.value[at].replies
1034
- });
1133
+ };
1134
+ if (sameComment(comments.value[at], next)) return false;
1135
+ comments.value = replaceAt(comments.value, at, next);
1136
+ return true;
1035
1137
  }
1036
1138
  function drop(commentId, parentId) {
1037
1139
  const existing = find(commentId);
@@ -1063,7 +1165,7 @@ function useComments(options) {
1063
1165
  try {
1064
1166
  const created = await providerCreate(templateId, input);
1065
1167
  upsert(created);
1066
- emit("created", created);
1168
+ notify(() => provider.onCreated?.(created, { origin: "local" }));
1067
1169
  return created;
1068
1170
  } catch (error) {
1069
1171
  report(error);
@@ -1080,7 +1182,7 @@ function useComments(options) {
1080
1182
  try {
1081
1183
  const updated = await providerUpdate(templateId, commentId, patch);
1082
1184
  upsert(updated);
1083
- emit("updated", updated);
1185
+ notify(() => provider.onUpdated?.(updated, { origin: "local" }));
1084
1186
  return updated;
1085
1187
  } catch (error) {
1086
1188
  report(error);
@@ -1098,7 +1200,7 @@ function useComments(options) {
1098
1200
  try {
1099
1201
  await providerDelete(templateId, commentId);
1100
1202
  drop(commentId);
1101
- if (existing) emit("deleted", existing);
1203
+ if (existing) notify(() => provider.onDeleted?.(existing, { origin: "local" }));
1102
1204
  } catch (error) {
1103
1205
  report(error);
1104
1206
  } finally {
@@ -1114,7 +1216,7 @@ function useComments(options) {
1114
1216
  try {
1115
1217
  const updated = await providerSetResolved(templateId, commentId, resolved);
1116
1218
  upsert(updated);
1117
- emit(updated.resolvedAt ? "resolved" : "unresolved", updated);
1219
+ notify(() => (updated.resolvedAt ? provider.onResolved : provider.onUnresolved)?.(updated, { origin: "local" }));
1118
1220
  return updated;
1119
1221
  } catch (error) {
1120
1222
  report(error);
@@ -1123,16 +1225,15 @@ function useComments(options) {
1123
1225
  }
1124
1226
  }
1125
1227
  function applyRemoteCreate(comment) {
1126
- upsert(comment);
1127
- emit("created", comment);
1228
+ if (upsert(comment)) notify(() => provider.onCreated?.(comment, { origin: "remote" }));
1128
1229
  }
1129
1230
  function applyRemoteUpdate(comment) {
1130
- upsert(comment);
1131
- emit(comment.resolvedAt ? "resolved" : "updated", comment);
1231
+ if (!upsert(comment)) return;
1232
+ notify(() => (comment.resolvedAt ? provider.onResolved : provider.onUpdated)?.(comment, { origin: "remote" }));
1132
1233
  }
1133
1234
  function applyRemoteDelete(commentId, parentId) {
1134
1235
  const existing = drop(commentId, parentId);
1135
- if (existing) emit("deleted", existing);
1236
+ if (existing) notify(() => provider.onDeleted?.(existing, { origin: "remote" }));
1136
1237
  }
1137
1238
  return {
1138
1239
  comments,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["ref","computed","ref","computed","ref","computed"],"sources":["../src/editor.ts","../src/history.ts","../src/block-actions.ts","../src/auto-save.ts","../src/condition-preview.ts","../src/data-source-fetch.ts","../src/history-interceptor.ts","../src/saved-blocks.ts","../src/saved-blocks-local.ts","../src/version-history.ts","../src/comments.ts"],"sourcesContent":["import type {\n Block,\n ColumnLayout,\n Template,\n TemplateContent,\n TemplateDefaults,\n TemplatePatch,\n TemplateSettings,\n TemplatesProvider,\n UiTheme,\n ViewportSize,\n} from \"@templatical/types\";\nimport { createDefaultTemplateContent, SdkError } from \"@templatical/types\";\n\nfunction getColumnCount(layout: ColumnLayout): number {\n if (layout === \"1\") return 1;\n if (layout === \"3\") return 3;\n return 2;\n}\nimport {\n computed,\n reactive,\n readonly,\n type DeepReadonly,\n type Ref,\n} from \"@vue/reactivity\";\n\nexport interface EditorState {\n /**\n * The template currently being edited, as the store last returned it — `null`\n * until `create()` or `load()` resolves, and always `null` without a\n * {@link TemplatesProvider}.\n *\n * Carries identity and name only for practical purposes: its `content` is the\n * store's copy from the last round-trip, whereas `state.content` is what the\n * user is editing.\n */\n template: Template | null;\n content: TemplateContent;\n selectedBlockId: string | null;\n viewport: ViewportSize;\n darkMode: boolean;\n previewMode: boolean;\n isDirty: boolean;\n /** True for the duration of a `save()` call. */\n isSaving: boolean;\n /** True for the duration of a `create()` or `load()` call. */\n isLoading: boolean;\n uiTheme: UiTheme;\n}\n\nexport interface UseEditorOptions {\n content: TemplateContent;\n defaultFontFamily?: string;\n templateDefaults?: TemplateDefaults;\n lockedBlocks?: Ref<Map<string, unknown>>;\n /**\n * Storage backend for the template's save/load lifecycle. Omit it and\n * `create()` / `load()` / `save()` reject — the editor keeps working as a\n * purely local editing surface.\n */\n templates?: TemplatesProvider;\n /**\n * Called with any error a provider call rejects with, before the rejection is\n * re-thrown to the caller.\n */\n onError?: (error: Error) => void;\n}\n\nexport interface UseEditorReturn {\n state: DeepReadonly<EditorState>;\n content: Ref<TemplateContent>;\n selectedBlock: Ref<Block | null>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n selectBlock: (blockId: string | null) => void;\n setViewport: (viewport: ViewportSize) => void;\n setDarkMode: (darkMode: boolean) => void;\n setPreviewMode: (previewMode: boolean) => void;\n setUiTheme: (theme: UiTheme) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n updateSettings: (updates: Partial<TemplateSettings>) => void;\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n moveBlock: (\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex?: number,\n ) => void;\n isBlockLocked: (blockId: string) => boolean;\n markDirty: () => void;\n findBlockLocation: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n /**\n * Rename the loaded template locally and mark the editor dirty. The new name\n * reaches the store on the next `save()`, in the same patch as the content —\n * a rename is an ordinary unsaved change, not a side channel.\n *\n * This method only stages it. The editor's inline rename field commits by\n * calling `setName()` and then saving immediately, because a rename reads as a\n * discrete action rather than an edit to be batched — so in the editor the\n * \"next `save()`\" is usually the one it triggers itself. A headless caller\n * decides its own moment.\n *\n * No-op when no template is loaded: there is nothing to name.\n */\n setName: (name: string) => void;\n /**\n * Persist the current content as a new template. `input.content`, when given,\n * replaces the editor's content first — so `create({ content })` both loads\n * and stores in one step.\n */\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n /** Fetch a template and make it the editor's content. */\n load: (templateId: string) => Promise<Template>;\n /** Persist the loaded template's name + content as a patch. */\n save: () => Promise<Template>;\n /** Whether a template has been created or loaded. */\n hasTemplate: () => boolean;\n}\n\nexport function useEditor(options: UseEditorOptions): UseEditorReturn {\n const state = reactive<EditorState>({\n template: null,\n content:\n options.content ??\n createDefaultTemplateContent(\n options.defaultFontFamily,\n options.templateDefaults,\n ),\n selectedBlockId: null,\n viewport: \"desktop\",\n darkMode: false,\n previewMode: false,\n isDirty: false,\n isSaving: false,\n isLoading: false,\n uiTheme: \"auto\",\n });\n\n /**\n * Bumped by every content mutation. `save()` captures it before awaiting the\n * provider and only clears `isDirty` if it is unchanged afterwards, so an edit\n * made while a save is in flight is not reported as persisted — which would\n * also make autosave skip it, since that decides dirtiness at debounce time.\n */\n let revision = 0;\n\n function touch(): void {\n state.isDirty = true;\n revision++;\n }\n\n const content = computed({\n get: () => state.content,\n set: (value: TemplateContent) => {\n state.content = value;\n touch();\n },\n });\n\n const selectedBlock = computed(() => {\n if (!state.selectedBlockId) return null;\n return findBlockById(state.content.blocks, state.selectedBlockId);\n });\n\n function findBlockById(blocks: Block[], id: string): Block | null {\n for (const block of blocks) {\n if (block.id === id) return block;\n if (block.type === \"section\") {\n for (const column of block.children) {\n const found = findBlockById(column, id);\n if (found) return found;\n }\n }\n }\n return null;\n }\n\n function collectBlockIds(block: Block, ids: Set<string>): void {\n ids.add(block.id);\n if (block.type === \"section\") {\n for (const column of block.children) {\n for (const child of column) {\n collectBlockIds(child, ids);\n }\n }\n }\n }\n\n function findBlockParent(\n blocks: Block[],\n id: string,\n parent: {\n blocks: Block[];\n sectionId?: string;\n columnIndex?: number;\n } = { blocks },\n ): { blocks: Block[]; sectionId?: string; columnIndex?: number } | null {\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (block.id === id) return parent;\n if (block.type === \"section\") {\n for (let colIdx = 0; colIdx < block.children.length; colIdx++) {\n const result = findBlockParent(block.children[colIdx], id, {\n blocks: block.children[colIdx],\n sectionId: block.id,\n columnIndex: colIdx,\n });\n if (result) return result;\n }\n }\n }\n return null;\n }\n\n function isBlockLocked(blockId: string): boolean {\n return options.lockedBlocks?.value.has(blockId) ?? false;\n }\n\n function findBlockLocation(blockId: string): {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null {\n const parent = findBlockParent(state.content.blocks, blockId);\n if (!parent) return null;\n const index = parent.blocks.findIndex((b) => b.id === blockId);\n if (index === -1) return null;\n return {\n targetSectionId: parent.sectionId,\n columnIndex: parent.columnIndex,\n index,\n };\n }\n\n // TODO(collab): the lock checks in addBlock/moveBlock/removeBlock/updateBlock\n // are shallow — they only consider the directly-targeted block id. A section\n // can still be removed, moved, or have its `children` array rewritten while a\n // peer is editing one of its descendants, which silently disrupts that peer's\n // edit. Add a `hasLockedDescendant(blockId)` helper and gate section-level\n // operations on it (and on the parent of each affected child) so cascades\n // through the tree are also blocked.\n\n function setContent(newContent: TemplateContent, markDirty = true): void {\n state.content = newContent;\n if (markDirty) {\n touch();\n }\n }\n\n function selectBlock(blockId: string | null): void {\n if (blockId && isBlockLocked(blockId)) {\n return;\n }\n state.selectedBlockId = blockId;\n }\n\n function setViewport(viewport: ViewportSize): void {\n state.viewport = viewport;\n }\n\n function setDarkMode(darkMode: boolean): void {\n state.darkMode = darkMode;\n }\n\n function setUiTheme(theme: UiTheme): void {\n state.uiTheme = theme;\n }\n\n function setPreviewMode(previewMode: boolean): void {\n state.previewMode = previewMode;\n if (previewMode) {\n state.selectedBlockId = null;\n }\n }\n\n function updateBlock(blockId: string, updates: Partial<Block>): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n const block = findBlockById(state.content.blocks, blockId);\n if (block) {\n Object.assign(block, updates);\n touch();\n }\n }\n\n function updateSettings(updates: Partial<TemplateSettings>): void {\n state.content.settings = { ...state.content.settings, ...updates };\n touch();\n }\n\n function addBlock(\n block: Block,\n targetSectionId?: string,\n columnIndex = 0,\n index?: number,\n ): void {\n // Sections cannot be nested inside a column — MJML forbids `mj-section`\n // inside `mj-column`, so the renderer drops them on export (issue #292).\n // Reject the nest up front rather than lose the content silently later.\n if (targetSectionId && block.type === \"section\") {\n return;\n }\n if (targetSectionId) {\n if (isBlockLocked(targetSectionId)) {\n return;\n }\n const section = findBlockById(state.content.blocks, targetSectionId);\n if (section && section.type === \"section\") {\n if (columnIndex < 0 || columnIndex >= getColumnCount(section.columns)) {\n return;\n }\n section.children[columnIndex] = section.children[columnIndex] || [];\n const targetArray = section.children[columnIndex];\n if (index !== undefined && index < targetArray.length) {\n targetArray.splice(index, 0, block);\n } else {\n targetArray.push(block);\n }\n }\n } else {\n if (index !== undefined && index < state.content.blocks.length) {\n state.content.blocks.splice(index, 0, block);\n } else {\n state.content.blocks.push(block);\n }\n }\n touch();\n }\n\n function removeBlock(blockId: string): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n const parent = findBlockParent(state.content.blocks, blockId);\n if (parent) {\n const index = parent.blocks.findIndex((b) => b.id === blockId);\n if (index !== -1) {\n const [removed] = parent.blocks.splice(index, 1);\n if (state.selectedBlockId) {\n const removedIds = new Set<string>();\n collectBlockIds(removed, removedIds);\n if (removedIds.has(state.selectedBlockId)) {\n state.selectedBlockId = null;\n }\n }\n touch();\n }\n }\n }\n\n function moveBlock(\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex = 0,\n ): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n if (targetSectionId && isBlockLocked(targetSectionId)) {\n return;\n }\n\n const parent = findBlockParent(state.content.blocks, blockId);\n if (!parent) return;\n\n const oldIndex = parent.blocks.findIndex((b) => b.id === blockId);\n if (oldIndex === -1) return;\n\n // Sections cannot be nested inside a column (issue #292) — refuse to move\n // a section into a section column; MJML would drop it on export.\n if (targetSectionId && parent.blocks[oldIndex].type === \"section\") {\n return;\n }\n\n // Resolve target before mutating the source — otherwise an invalid\n // targetSectionId leaves the block spliced-out and unrecoverable.\n let targetArray: Block[];\n if (targetSectionId) {\n const section = findBlockById(state.content.blocks, targetSectionId);\n if (!section || section.type !== \"section\") return;\n if (columnIndex < 0 || columnIndex >= getColumnCount(section.columns)) {\n return;\n }\n section.children[columnIndex] = section.children[columnIndex] || [];\n targetArray = section.children[columnIndex];\n } else {\n targetArray = state.content.blocks;\n }\n\n const [block] = parent.blocks.splice(oldIndex, 1);\n targetArray.splice(newIndex, 0, block);\n\n touch();\n }\n\n function markDirty(): void {\n touch();\n }\n\n // -------------------------------------------------------------------------\n // Template lifecycle (over an optional TemplatesProvider)\n // -------------------------------------------------------------------------\n\n /**\n * A refused call throws rather than resolving, because a resolved promise\n * would read as \"saved\" to whoever awaited it.\n *\n * The message names the provider key the consumer set, not an internal\n * capability flag: `EditorCapabilities` is type-only and its injection key is\n * unexported, so neither a core nor an editor consumer can read one. Note the\n * editor hides its own save controls when `save` is withheld but has no\n * create affordance to hide at all, so `create()` is reachable by definition.\n */\n function refuse(action: string, reason: string): never {\n throw new SdkError(`[Templatical] Templates: ${action} ${reason}`);\n }\n\n function requireProvider(action: string): TemplatesProvider {\n const { templates } = options;\n if (!templates) {\n refuse(\n action,\n \"needs a templates provider. Pass one as `init({ templates })` to enable saving and loading.\",\n );\n }\n return templates;\n }\n\n function setName(name: string): void {\n if (!state.template) return;\n state.template = { ...state.template, name };\n touch();\n }\n\n async function create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template> {\n const provider = requireProvider(\"create()\");\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") {\n refuse(\n \"create()\",\n \"is disabled by the provider — its `create` is `false`.\",\n );\n }\n\n state.isLoading = true;\n try {\n if (input?.content) {\n state.content = input.content;\n }\n // Omit `name` entirely when unset rather than sending `undefined` — a\n // provider serialising the input to JSON would otherwise receive a key it\n // never asked for.\n const revisionAtRequest = revision;\n const template = await providerCreate(\n input?.name !== undefined\n ? { name: input.name, content: state.content }\n : { content: state.content },\n );\n state.template = template;\n if (revision === revisionAtRequest) {\n state.isDirty = false;\n }\n return template;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isLoading = false;\n }\n }\n\n async function load(templateId: string): Promise<Template> {\n const provider = requireProvider(\"load()\");\n\n state.isLoading = true;\n try {\n const template = await provider.load(templateId);\n state.template = template;\n state.content = template.content;\n state.isDirty = false;\n return template;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isLoading = false;\n }\n }\n\n async function save(): Promise<Template> {\n const provider = requireProvider(\"save()\");\n const { save: providerSave } = provider;\n if (typeof providerSave !== \"function\") {\n refuse(\"save()\", \"is disabled by the provider — its `save` is `false`.\");\n }\n const current = state.template;\n if (!current) {\n refuse(\n \"save()\",\n \"has no template loaded. Call create() or load() first.\",\n );\n }\n\n // The name rides the same patch as the content: a rename is an ordinary\n // unsaved change, so one round-trip persists both.\n const patch: TemplatePatch =\n current.name !== undefined\n ? { name: current.name, content: state.content }\n : { content: state.content };\n\n state.isSaving = true;\n try {\n const revisionAtRequest = revision;\n const template = await providerSave(current.id, patch);\n // Adopt the response only while it still describes what is open. A\n // `load()` that landed mid-flight has already replaced the template, so\n // the response is stale.\n if (state.template?.id === current.id) {\n // The patch was built before the await, so a rename that landed during\n // it is absent from the response. Taking the response's name verbatim\n // reverts what the user typed — and because the next save reads the\n // name back off `state.template`, it would then persist the stale one,\n // losing the rename outright rather than merely on screen.\n const localName = state.template.name;\n state.template =\n localName !== current.name\n ? { ...template, name: localName }\n : template;\n }\n // Deliberately conditional. An edit landing while the request was in\n // flight is not persisted by it, and clearing the flag would both claim it\n // was and make autosave — which checks dirtiness at debounce time — skip\n // the follow-up save.\n if (revision === revisionAtRequest) {\n state.isDirty = false;\n }\n return template;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isSaving = false;\n }\n }\n\n function hasTemplate(): boolean {\n return state.template?.id !== undefined;\n }\n\n return {\n state: readonly(state),\n content,\n selectedBlock,\n isBlockLocked,\n setContent,\n selectBlock,\n setViewport,\n setDarkMode,\n setUiTheme,\n setPreviewMode,\n updateBlock,\n updateSettings,\n addBlock,\n removeBlock,\n moveBlock,\n markDirty,\n findBlockLocation,\n setName,\n create,\n load,\n save,\n hasTemplate,\n };\n}\n","import { safeClone, type TemplateContent } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"@vue/reactivity\";\n\nexport interface UseHistoryOptions {\n content: Ref<TemplateContent>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n isRemoteOperation?: () => boolean;\n maxSize?: number;\n}\n\nexport interface UseHistoryReturn {\n canUndo: ComputedRef<boolean>;\n canRedo: ComputedRef<boolean>;\n isNavigating: Ref<boolean>;\n undo: () => void;\n redo: () => void;\n record: () => void;\n recordDebounced: (blockId: string) => void;\n clear: () => void;\n destroy: () => void;\n}\n\ninterface DebouncedSnapshot {\n blockId: string;\n timeoutId: ReturnType<typeof setTimeout>;\n}\n\nconst MAX_STACK_SIZE = 50;\nconst DEBOUNCE_MS = 300;\nconst NAVIGATE_IDLE_MS = 1500;\n\nexport function useHistory(options: UseHistoryOptions): UseHistoryReturn {\n const {\n content,\n setContent,\n isRemoteOperation,\n maxSize = MAX_STACK_SIZE,\n } = options;\n\n const undoStack = ref<TemplateContent[]>([]);\n const redoStack = ref<TemplateContent[]>([]);\n const isNavigating = ref(false);\n let navigatingTimeoutId: ReturnType<typeof setTimeout> | null = null;\n let pendingDebounce: DebouncedSnapshot | null = null;\n\n const canUndo = computed(() => undoStack.value.length > 0);\n const canRedo = computed(() => redoStack.value.length > 0);\n\n function cloneContent(): TemplateContent {\n // Cycle-safe deep clone (see `safeClone`). A naked JSON.stringify throws\n // `Converting circular structure to JSON` if a DOM element with a Sortable\n // expando back-ref ever sneaks into block data via a drag handler — which\n // would freeze the undo stack, since every subsequent mutation calls\n // `record()`. safeClone drops the back-ref instead of throwing.\n return safeClone(content.value);\n }\n\n function pushToUndoStack(snapshot: TemplateContent): void {\n undoStack.value.push(snapshot);\n if (undoStack.value.length > maxSize) {\n undoStack.value.splice(0, undoStack.value.length - maxSize);\n }\n }\n\n function flushPendingDebounce(): void {\n if (pendingDebounce) {\n clearTimeout(pendingDebounce.timeoutId);\n pendingDebounce = null;\n }\n }\n\n function record(): void {\n if (isRemoteOperation?.()) {\n return;\n }\n\n flushPendingDebounce();\n pushToUndoStack(cloneContent());\n redoStack.value = [];\n }\n\n function recordDebounced(blockId: string): void {\n if (isRemoteOperation?.()) {\n return;\n }\n\n if (pendingDebounce && pendingDebounce.blockId === blockId) {\n clearTimeout(pendingDebounce.timeoutId);\n pendingDebounce.timeoutId = setTimeout(() => {\n pendingDebounce = null;\n }, DEBOUNCE_MS);\n return;\n }\n\n flushPendingDebounce();\n\n pushToUndoStack(cloneContent());\n redoStack.value = [];\n\n pendingDebounce = {\n blockId,\n timeoutId: setTimeout(() => {\n pendingDebounce = null;\n }, DEBOUNCE_MS),\n };\n }\n\n function setNavigating(): void {\n isNavigating.value = true;\n if (navigatingTimeoutId) {\n clearTimeout(navigatingTimeoutId);\n }\n navigatingTimeoutId = setTimeout(() => {\n isNavigating.value = false;\n navigatingTimeoutId = null;\n }, NAVIGATE_IDLE_MS);\n }\n\n function undo(): void {\n if (undoStack.value.length === 0) {\n return;\n }\n\n flushPendingDebounce();\n\n const snapshot = undoStack.value.pop()!;\n redoStack.value.push(cloneContent());\n setContent(snapshot, true);\n setNavigating();\n }\n\n function redo(): void {\n if (redoStack.value.length === 0) {\n return;\n }\n\n flushPendingDebounce();\n\n const snapshot = redoStack.value.pop()!;\n undoStack.value.push(cloneContent());\n setContent(snapshot, true);\n setNavigating();\n }\n\n function clear(): void {\n undoStack.value = [];\n redoStack.value = [];\n flushPendingDebounce();\n }\n\n function destroy(): void {\n clear();\n if (navigatingTimeoutId) {\n clearTimeout(navigatingTimeoutId);\n navigatingTimeoutId = null;\n }\n }\n\n return {\n canUndo,\n canRedo,\n isNavigating,\n undo,\n redo,\n record,\n recordDebounced,\n clear,\n destroy,\n };\n}\n","import type { Block, BlockDefaults, BlockType } from \"@templatical/types\";\nimport { createBlock, generateId } from \"@templatical/types\";\n\nfunction regenerateNestedIds(block: Block): void {\n if (block.type === \"table\") {\n block.rows = block.rows.map((row) => ({\n ...row,\n id: generateId(),\n cells: row.cells.map((cell) => ({ ...cell, id: generateId() })),\n }));\n } else if (block.type === \"social\") {\n block.icons = block.icons.map((icon) => ({ ...icon, id: generateId() }));\n } else if (block.type === \"menu\") {\n block.items = block.items.map((item) => ({ ...item, id: generateId() }));\n }\n}\n\nexport interface UseBlockActionsOptions {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n selectBlock: (blockId: string | null) => void;\n /** Locate a block in the tree — used by `duplicateBlock` to insert the\n * clone right after the source instead of appending to the end. */\n findBlockLocation?: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n blockDefaults?: BlockDefaults;\n}\n\nexport interface UseBlockActionsReturn {\n createAndAddBlock: (\n type: BlockType,\n targetSectionId?: string,\n columnIndex?: number,\n ) => Block;\n duplicateBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n ) => Block;\n deleteBlock: (blockId: string) => void;\n updateBlockProperty: <K extends keyof Block>(\n blockId: string,\n key: K,\n value: Block[K],\n ) => void;\n}\n\nexport function useBlockActions(\n options: UseBlockActionsOptions,\n): UseBlockActionsReturn {\n const { addBlock, removeBlock, updateBlock, selectBlock, findBlockLocation } =\n options;\n\n function createAndAddBlock(\n type: BlockType,\n targetSectionId?: string,\n columnIndex?: number,\n ): Block {\n const block = createBlock(type, options.blockDefaults);\n addBlock(block, targetSectionId, columnIndex);\n selectBlock(block.id);\n return block;\n }\n\n function duplicateBlock(\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n ): Block {\n const cloned = JSON.parse(JSON.stringify(block)) as Block;\n cloned.id = generateId();\n regenerateNestedIds(cloned);\n\n if (cloned.type === \"section\") {\n cloned.children = cloned.children.map((column) =>\n column.map((child) => {\n const clonedChild = JSON.parse(JSON.stringify(child)) as Block;\n clonedChild.id = generateId();\n regenerateNestedIds(clonedChild);\n return clonedChild;\n }),\n );\n }\n\n // Insert directly after the source block. Explicit target args win;\n // otherwise, resolve the source's location and bump index by 1. Falls\n // back to appending at the end if location is unknown.\n if (targetSectionId !== undefined || columnIndex !== undefined) {\n addBlock(cloned, targetSectionId, columnIndex);\n } else {\n const sourceLocation = findBlockLocation?.(block.id) ?? null;\n if (sourceLocation) {\n addBlock(\n cloned,\n sourceLocation.targetSectionId,\n sourceLocation.columnIndex,\n sourceLocation.index + 1,\n );\n } else {\n addBlock(cloned, targetSectionId, columnIndex);\n }\n }\n selectBlock(cloned.id);\n return cloned;\n }\n\n function deleteBlock(blockId: string): void {\n removeBlock(blockId);\n }\n\n function updateBlockProperty<K extends keyof Block>(\n blockId: string,\n key: K,\n value: Block[K],\n ): void {\n updateBlock(blockId, { [key]: value } as Partial<Block>);\n }\n\n return {\n createAndAddBlock,\n duplicateBlock,\n deleteBlock,\n updateBlockProperty,\n };\n}\n","import type { TemplateContent } from \"@templatical/types\";\nimport { watch, type Ref } from \"@vue/reactivity\";\n\nexport interface UseAutoSaveOptions {\n content: Ref<TemplateContent>;\n isDirty: () => boolean;\n onChange: (content: TemplateContent) => void;\n debounce?: number;\n enabled?: boolean | (() => boolean);\n}\n\nexport interface UseAutoSaveReturn {\n flush: () => void;\n cancel: () => void;\n pause: () => void;\n resume: () => void;\n destroy: () => void;\n}\n\n/**\n * Trailing debounce, in ms, measured from the *last* content mutation.\n *\n * Typing is not debounced upstream — TipTap's `onUpdate` calls `updateBlock` per\n * keystroke — so this is the only thing between a keypress and a whole-document\n * write. 1000 was too eager: ordinary prose pauses for a second constantly\n * (word choice, re-reading, reaching for the mouse), so a single paragraph could\n * produce dozens of full-content saves. 2000 roughly halves that while still\n * landing well before a user wonders whether their work was kept.\n *\n * **The single default for both entry points.** Cloud imports this constant\n * rather than declaring its own — a second copy for one setting drifts silently,\n * since nothing links the two.\n */\nexport const DEFAULT_AUTO_SAVE_DEBOUNCE_MS = 2000;\n\nexport function useAutoSave(options: UseAutoSaveOptions): UseAutoSaveReturn {\n const {\n content,\n isDirty,\n onChange,\n debounce = DEFAULT_AUTO_SAVE_DEBOUNCE_MS,\n enabled = true,\n } = options;\n\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let paused = false;\n\n function isEnabled(): boolean {\n return typeof enabled === \"function\" ? enabled() : enabled;\n }\n\n function pause(): void {\n paused = true;\n cancel();\n }\n\n function resume(): void {\n paused = false;\n }\n\n function cancel(): void {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n }\n\n function flush(): void {\n cancel();\n if (isDirty()) {\n onChange(JSON.parse(JSON.stringify(content.value)));\n }\n }\n\n function scheduleOnChange(): void {\n if (!isEnabled() || paused) return;\n\n cancel();\n timeoutId = setTimeout(() => {\n timeoutId = null;\n if (isEnabled() && !paused && isDirty()) {\n onChange(JSON.parse(JSON.stringify(content.value)));\n }\n }, debounce);\n }\n\n // `watch` from `@vue/reactivity` has no scheduler, so this callback runs\n // *synchronously inside the mutation* — before the editor's trailing\n // `state.isDirty = true`, and `isDirty` sits outside the watched `content`\n // subtree so setting it never re-triggers. An `isDirty()` guard here would\n // therefore drop the first edit after every dirty-flag reset (issue #522).\n // Dirtiness is decided at debounce time instead, where the flag is settled;\n // `scheduleOnChange` still checks `enabled`/`paused` up front.\n const stopWatch = watch(\n content,\n () => {\n scheduleOnChange();\n },\n { deep: true },\n );\n\n function destroy(): void {\n stopWatch();\n cancel();\n }\n\n return {\n flush,\n cancel,\n pause,\n resume,\n destroy,\n };\n}\n","import { computed, reactive, type ComputedRef } from \"@vue/reactivity\";\n\nexport interface UseConditionPreviewReturn {\n isHidden: (blockId: string) => boolean;\n toggleBlock: (blockId: string) => void;\n reset: () => void;\n hasHiddenBlocks: ComputedRef<boolean>;\n}\n\n/**\n * The slice of an editor this needs — deliberately structural, so both the OSS\n * and the Cloud `useEditor` satisfy it without either having to grow toward the\n * other.\n */\nexport interface ConditionPreviewEditor {\n state: { readonly selectedBlockId: string | null };\n selectBlock: (blockId: string | null) => void;\n}\n\nexport function useConditionPreview(\n editor: ConditionPreviewEditor,\n): UseConditionPreviewReturn {\n const hiddenBlockIds = reactive(new Set<string>());\n\n const hasHiddenBlocks = computed(() => hiddenBlockIds.size > 0);\n\n function isHidden(blockId: string): boolean {\n return hiddenBlockIds.has(blockId);\n }\n\n function toggleBlock(blockId: string): void {\n if (hiddenBlockIds.has(blockId)) {\n hiddenBlockIds.delete(blockId);\n } else {\n hiddenBlockIds.add(blockId);\n\n if (editor.state.selectedBlockId === blockId) {\n editor.selectBlock(null);\n }\n }\n }\n\n function reset(): void {\n hiddenBlockIds.clear();\n }\n\n return {\n isHidden,\n toggleBlock,\n reset,\n hasHiddenBlocks,\n };\n}\n","import type { CustomBlock, CustomBlockDefinition } from \"@templatical/types\";\nimport type { ComputedRef, Ref } from \"@vue/reactivity\";\nimport { computed, ref } from \"@vue/reactivity\";\n\nexport function useDataSourceFetch(options: {\n definition: ComputedRef<CustomBlockDefinition | undefined>;\n block: ComputedRef<CustomBlock>;\n onUpdate: (fieldValues: Record<string, unknown>, fetched: boolean) => void;\n}): {\n isFetching: Ref<boolean>;\n fetchError: Ref<boolean>;\n fetch: () => Promise<void>;\n hasDataSource: ComputedRef<boolean>;\n needsFetch: ComputedRef<boolean>;\n} {\n const isFetching = ref(false);\n const fetchError = ref(false);\n\n const hasDataSource = computed(() => !!options.definition.value?.dataSource);\n\n const needsFetch = computed(\n () => hasDataSource.value && !options.block.value.dataSourceFetched,\n );\n\n async function fetch(): Promise<void> {\n const def = options.definition.value;\n if (!def?.dataSource) {\n return;\n }\n\n isFetching.value = true;\n fetchError.value = false;\n\n try {\n const result = await def.dataSource.onFetch({\n fieldValues: { ...options.block.value.fieldValues },\n blockId: options.block.value.id,\n });\n\n if (result == null) {\n return;\n }\n\n const merged = { ...options.block.value.fieldValues };\n for (const key of Object.keys(merged)) {\n if (key in result) {\n merged[key] = result[key];\n }\n }\n\n options.onUpdate(merged, true);\n } catch (error) {\n console.warn(\"[Templatical] Data source fetch error:\", error);\n fetchError.value = true;\n } finally {\n isFetching.value = false;\n }\n }\n\n return {\n isFetching,\n fetchError,\n fetch,\n hasDataSource,\n needsFetch,\n };\n}\n","import type { Block, TemplateSettings } from \"@templatical/types\";\nimport type { UseHistoryReturn } from \"./history\";\n\n/**\n * The mutable slice of an editor this wraps — structural, so the OSS and Cloud\n * `useEditor` returns both satisfy it without either having to grow toward the\n * other. Not `Readonly`: the whole point is to replace these members in place.\n */\nexport interface HistoryInterceptorEditor {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n moveBlock: (\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex?: number,\n ) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n updateSettings: (updates: Partial<TemplateSettings>) => void;\n isBlockLocked: (blockId: string) => boolean;\n}\n\n/**\n * Wraps editor mutation methods to record history snapshots before each\n * operation. Mutates the editor object in place.\n *\n * Must be applied **after** any collaboration broadcast wrapping so the\n * call chain is: history.record() → broadcast → original mutation.\n */\nexport function useHistoryInterceptor(\n editor: HistoryInterceptorEditor,\n history: UseHistoryReturn,\n): void {\n const originalAddBlock = editor.addBlock;\n const originalRemoveBlock = editor.removeBlock;\n const originalMoveBlock = editor.moveBlock;\n const originalUpdateBlock = editor.updateBlock;\n const originalUpdateSettings = editor.updateSettings;\n\n // Skip recording when the underlying op is a no-op (e.g., a peer-locked\n // block or section), otherwise the undo stack fills with snapshots that\n // are identical to current state and undo silently does nothing.\n editor.addBlock = (block, targetSectionId?, columnIndex?, index?) => {\n if (targetSectionId && editor.isBlockLocked(targetSectionId)) {\n return;\n }\n history.record();\n originalAddBlock(block, targetSectionId, columnIndex, index);\n };\n\n editor.removeBlock = (blockId) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n history.record();\n originalRemoveBlock(blockId);\n };\n\n editor.moveBlock = (blockId, newIndex, targetSectionId?, columnIndex?) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n if (targetSectionId && editor.isBlockLocked(targetSectionId)) {\n return;\n }\n history.record();\n originalMoveBlock(blockId, newIndex, targetSectionId, columnIndex);\n };\n\n editor.updateBlock = (blockId, updates) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n history.recordDebounced(blockId);\n originalUpdateBlock(blockId, updates);\n };\n\n editor.updateSettings = (updates) => {\n history.record();\n originalUpdateSettings(updates);\n };\n}\n","import type {\n Block,\n SavedBlock,\n SavedBlockPatch,\n SavedBlocksListParams,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"vue\";\n\nexport interface UseSavedBlocksOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ savedBlocks })`, or\n * by Cloud's own adapter — this composable is transport-agnostic and never\n * talks to a network itself.\n */\n provider: SavedBlocksProvider;\n onError?: (error: Error) => void;\n}\n\nexport interface UseSavedBlocksReturn {\n /** In-memory mirror of the provider's list, kept in sync after each call. */\n savedBlocks: Ref<SavedBlock[]>;\n isLoading: Ref<boolean>;\n /**\n * Distinct categories across the loaded entries, alphabetically sorted.\n *\n * Derived rather than stored: a category exists exactly as long as an entry\n * carries it. Sorting here is not a violation of \"the editor never re-sorts\"\n * — that rule protects the provider's ordering of *entries*, whereas these\n * are strings with no given order.\n */\n categories: ComputedRef<string[]>;\n /**\n * Whether the provider supplied each mutation at all — `false` on the\n * provider means the capability does not exist for this user, and the UI\n * hides the corresponding affordance entirely.\n *\n * Constant for the provider's lifetime, but exposed as computed refs so\n * consumers can bind them the same way as everything else here.\n */\n canCreate: ComputedRef<boolean>;\n canUpdate: ComputedRef<boolean>;\n canDelete: ComputedRef<boolean>;\n /**\n * Whether a *particular* entry may be edited / deleted: the capability must\n * exist AND the entry must not opt out via `canUpdate` / `canDelete`.\n *\n * Use these rather than reading the flags directly, so every surface asks the\n * question the same way and the \"absent means allowed\" default lives in one\n * place.\n */\n canUpdateBlock: (block: SavedBlock) => boolean;\n canDeleteBlock: (block: SavedBlock) => boolean;\n /**\n * Re-read from the provider. The editor always calls this bare and filters\n * in memory; `params` exists for headless callers that want the provider to\n * filter instead (see {@link SavedBlocksListParams}).\n */\n load: (params?: SavedBlocksListParams) => Promise<void>;\n /** Rejects with an {@link SdkError} when the provider disabled `create`. */\n create: (\n name: string,\n content: Block[],\n category?: string,\n ) => Promise<SavedBlock>;\n /** Rejects when `update` is disabled or the entry opts out of editing. */\n update: (id: string, patch: SavedBlockPatch) => Promise<SavedBlock>;\n /** Rejects when `delete` is disabled or the entry opts out of deletion. */\n remove: (id: string) => Promise<void>;\n}\n\n/**\n * Reactive state over a {@link SavedBlocksProvider}.\n *\n * Owns the list, the loading flag, and the local mutations that keep the list\n * consistent after each successful call, so a provider only has to implement\n * four promise-returning methods. Errors are reported through `onError` and\n * re-thrown, leaving the local list untouched on failure.\n */\nexport function useSavedBlocks(\n options: UseSavedBlocksOptions,\n): UseSavedBlocksReturn {\n const { provider } = options;\n\n const savedBlocks = ref<SavedBlock[]>([]);\n const isLoading = ref(false);\n\n const categories = computed(() => {\n const seen = new Set<string>();\n for (const block of savedBlocks.value) {\n const category = block.category?.trim();\n if (category) seen.add(category);\n }\n return [...seen].sort((a, b) => a.localeCompare(b));\n });\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canUpdate = computed(() => typeof provider.update === \"function\");\n const canDelete = computed(() => typeof provider.delete === \"function\");\n\n /** Absent flag means allowed — the flags exist only to forbid. */\n function canUpdateBlock(block: SavedBlock): boolean {\n return canUpdate.value && block.canUpdate !== false;\n }\n\n function canDeleteBlock(block: SavedBlock): boolean {\n return canDelete.value && block.canDelete !== false;\n }\n\n /**\n * The UI hides disabled actions, so reaching one of these means a programmatic\n * caller went around it. Fail loudly rather than silently no-op: a resolved\n * promise would read as \"saved\" to whoever awaited it.\n */\n function refuse(action: string, reason: string): never {\n throw new SdkError(\n `[Templatical] Saved blocks: ${action} is ${reason}. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n async function load(params?: SavedBlocksListParams): Promise<void> {\n isLoading.value = true;\n try {\n savedBlocks.value = await provider.list(params);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isLoading.value = false;\n }\n }\n\n async function create(\n name: string,\n content: Block[],\n category?: string,\n ): Promise<SavedBlock> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") {\n refuse(\"create\", \"disabled by the provider\");\n }\n try {\n // Omit the key entirely when unset, rather than sending `undefined` —\n // a provider serialising the input to JSON would otherwise be handed an\n // explicit null-ish field it never asked for.\n const created = await providerCreate(\n category ? { name, content, category } : { name, content },\n );\n savedBlocks.value = [created, ...savedBlocks.value];\n return created;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function update(\n id: string,\n patch: SavedBlockPatch,\n ): Promise<SavedBlock> {\n const { update: providerUpdate } = provider;\n if (typeof providerUpdate !== \"function\") {\n refuse(\"update\", \"disabled by the provider\");\n }\n // An id absent from the local list isn't refused — a headless caller may\n // legitimately patch something it never loaded. Only a loaded entry that\n // explicitly opted out is blocked.\n const local = savedBlocks.value.find((b) => b.id === id);\n if (local && local.canUpdate === false) {\n refuse(\"update\", `not permitted for entry \"${id}\"`);\n }\n try {\n const updated = await providerUpdate(id, patch);\n savedBlocks.value = savedBlocks.value.map((b) =>\n b.id === id ? updated : b,\n );\n return updated;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function remove(id: string): Promise<void> {\n const { delete: providerDelete } = provider;\n if (typeof providerDelete !== \"function\") {\n refuse(\"delete\", \"disabled by the provider\");\n }\n const local = savedBlocks.value.find((b) => b.id === id);\n if (local && local.canDelete === false) {\n refuse(\"delete\", `not permitted for entry \"${id}\"`);\n }\n try {\n await providerDelete(id);\n savedBlocks.value = savedBlocks.value.filter((b) => b.id !== id);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n return {\n savedBlocks,\n isLoading,\n categories,\n canCreate,\n canUpdate,\n canDelete,\n canUpdateBlock,\n canDeleteBlock,\n load,\n create,\n update,\n remove,\n };\n}\n","import type {\n SavedBlock,\n SavedBlockInput,\n SavedBlockPatch,\n SavedBlocksListParams,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { generateId } from \"@templatical/types\";\n\nexport interface LocalStorageSavedBlocksOptions {\n /**\n * `localStorage` key holding the serialized array.\n *\n * @default \"templatical:saved-blocks\"\n */\n key?: string;\n}\n\nconst DEFAULT_KEY = \"templatical:saved-blocks\";\n\n/**\n * Browser-local {@link SavedBlocksProvider} backed by `localStorage`.\n *\n * Opt-in: pass it explicitly as `init({ savedBlocks: createLocalStorageSavedBlocksProvider() })`.\n * The editor never falls back to it, so consumers without a provider keep the\n * feature — and its UI — entirely off.\n *\n * Intended for demos, prototypes, and single-device use. Entries live in one\n * browser profile only: they don't sync across devices or users, and clearing\n * site data removes them. Back saved blocks with your own API for anything\n * that needs to outlive a browser profile.\n */\nexport function createLocalStorageSavedBlocksProvider(\n options: LocalStorageSavedBlocksOptions = {},\n): SavedBlocksProvider {\n const storageKey = options.key ?? DEFAULT_KEY;\n\n function getStorage(): Storage {\n // Core targets a neutral platform, so `localStorage` isn't guaranteed —\n // fail with an actionable message rather than a bare ReferenceError.\n if (typeof localStorage === \"undefined\") {\n throw new Error(\n \"[Templatical] createLocalStorageSavedBlocksProvider requires a browser environment with localStorage. Supply your own SavedBlocksProvider for server-side or non-browser use.\",\n );\n }\n return localStorage;\n }\n\n function readAll(): SavedBlock[] {\n const raw = getStorage().getItem(storageKey);\n if (!raw) return [];\n try {\n const parsed: unknown = JSON.parse(raw);\n // Tolerate a corrupted or hand-edited value rather than breaking the\n // editor: treat anything that isn't an array as \"no saved blocks\".\n return Array.isArray(parsed) ? (parsed as SavedBlock[]) : [];\n } catch {\n return [];\n }\n }\n\n function writeAll(blocks: SavedBlock[]): void {\n getStorage().setItem(storageKey, JSON.stringify(blocks));\n }\n\n // Every method is `async` so a synchronous failure (a missing\n // `localStorage`, a quota error from `setItem`) surfaces as a rejected\n // promise rather than a sync throw — callers of a `Promise`-returning\n // contract must be able to rely on `.catch()`.\n return {\n // The editor calls this bare and filters in memory; the params are honored\n // for headless callers that would rather the provider did the work.\n async list(params?: SavedBlocksListParams): Promise<SavedBlock[]> {\n const all = readAll();\n const search = params?.search?.trim().toLowerCase();\n const category = params?.category?.trim();\n return all.filter((b) => {\n if (search && !b.name.toLowerCase().includes(search)) return false;\n if (category && b.category !== category) return false;\n return true;\n });\n },\n\n // All three mutations are enabled: a browser-local store has no notion of\n // permissions, so there is nothing to forbid.\n async create(input: SavedBlockInput): Promise<SavedBlock> {\n const now = new Date().toISOString();\n const created: SavedBlock = {\n id: generateId(),\n name: input.name,\n content: input.content,\n ...(input.category ? { category: input.category } : {}),\n createdAt: now,\n updatedAt: now,\n };\n // Newest-first, matching the order the composable applies locally after\n // a create — so a reload preserves what the user just saw.\n writeAll([created, ...readAll()]);\n return created;\n },\n\n async update(id: string, patch: SavedBlockPatch): Promise<SavedBlock> {\n const all = readAll();\n const index = all.findIndex((b) => b.id === id);\n // Mirrors a REST 404 so provider behavior is consistent across adapters.\n if (index === -1) {\n throw new Error(`[Templatical] Saved block not found: ${id}`);\n }\n const updated: SavedBlock = {\n ...all[index],\n ...patch,\n updatedAt: new Date().toISOString(),\n };\n const next = [...all];\n next[index] = updated;\n writeAll(next);\n return updated;\n },\n\n async delete(id: string): Promise<void> {\n const all = readAll();\n if (!all.some((b) => b.id === id)) {\n throw new Error(`[Templatical] Saved block not found: ${id}`);\n }\n writeAll(all.filter((b) => b.id !== id));\n },\n };\n}\n","import type {\n Template,\n TemplateContent,\n TemplateVersion,\n VersionHistoryListParams,\n VersionHistoryProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"vue\";\n\nexport interface UseVersionHistoryOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ versionHistory })`,\n * or by Cloud's own adapter — this composable is transport-agnostic and never\n * talks to a network itself.\n */\n provider: VersionHistoryProvider;\n /**\n * Which template's history this is. A getter rather than a value because a\n * session can outlive the template: `initCloud()` constructs the feature at\n * setup and only learns the id once `create()` / `load()` resolves.\n */\n getTemplateId: () => string | null;\n onError?: (error: Error) => void;\n}\n\nexport interface UseVersionHistoryReturn {\n /** The provider's list, in the provider's order. Never re-sorted. */\n versions: Ref<TemplateVersion[]>;\n isLoading: Ref<boolean>;\n isRestoring: Ref<boolean>;\n /**\n * Cursor for the page after the one currently held, or `undefined` when the\n * provider signalled there is no more. The editor loads one page and ignores\n * this; it is here so a headless caller can page without reaching past the\n * composable.\n */\n nextCursor: Ref<string | undefined>;\n /** Whether the provider supplied each mutation at all. */\n canCreate: ComputedRef<boolean>;\n canRestore: ComputedRef<boolean>;\n /** Re-read the list. The editor calls this bare; `params` is for headless callers. */\n load: (params?: VersionHistoryListParams) => Promise<void>;\n /**\n * The version's content **if it is already in hand** — the provider's\n * `content` hint, or a previous `get` this composable cached. `null` means a\n * round-trip is required.\n *\n * Callers that must not block (scrubbing through history swaps the canvas in\n * the same tick) check this first and only await {@link resolveContent} when\n * it comes back null.\n */\n peekContent: (version: TemplateVersion) => TemplateContent | null;\n /**\n * `version.content ?? await provider.get(...)`, cached per version id, so a\n * lazily-loaded version costs one round-trip on its first visit and nothing\n * afterwards.\n */\n resolveContent: (version: TemplateVersion) => Promise<TemplateContent>;\n /** Rejects with an {@link SdkError} when the provider disabled `create`. */\n create: (\n content: TemplateContent,\n meta?: { label?: string },\n ) => Promise<TemplateVersion>;\n /** Rejects with an {@link SdkError} when the provider disabled `restore`. */\n restore: (versionId: string) => Promise<Template>;\n}\n\n/**\n * Reactive state over a {@link VersionHistoryProvider}.\n *\n * Owns the list, the loading flags and the per-version content cache that keeps\n * scrubbing synchronous. Errors are reported through `onError` and re-thrown,\n * leaving the list untouched on failure.\n *\n * It deliberately does **not** create versions of its own accord. The editor\n * never records a version on a save — whoever implements `TemplatesProvider.save`\n * decides that, because they are the side that pays for the storage.\n */\nexport function useVersionHistory(\n options: UseVersionHistoryOptions,\n): UseVersionHistoryReturn {\n const { provider, getTemplateId } = options;\n\n const versions = ref<TemplateVersion[]>([]);\n const isLoading = ref(false);\n const nextCursor = ref<string | undefined>(undefined);\n const isRestoring = ref(false);\n\n /**\n * Content fetched through `get`, keyed by version id. A version that carried\n * a `content` hint never lands here — the hint is read straight off the entry,\n * so a provider that eager-loads pays no second copy.\n */\n const fetched = new Map<string, TemplateContent>();\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canRestore = computed(() => typeof provider.restore === \"function\");\n\n /**\n * The UI hides disabled actions and renders nothing before a template exists,\n * so reaching one of these means a programmatic caller went around it. Fail\n * loudly rather than silently no-op: a resolved promise reads as \"done\".\n */\n function requireTemplateId(action: string): string {\n const templateId = getTemplateId();\n if (!templateId) {\n throw new SdkError(\n `[Templatical] Version history: ${action} needs a template. Call create() or load() first.`,\n );\n }\n return templateId;\n }\n\n function refuse(action: string): never {\n throw new SdkError(\n `[Templatical] Version history: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n async function load(params?: VersionHistoryListParams): Promise<void> {\n const templateId = requireTemplateId(\"list\");\n isLoading.value = true;\n try {\n const page = await provider.list(templateId, params);\n versions.value = page.versions;\n nextCursor.value = page.nextCursor;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isLoading.value = false;\n }\n }\n\n function peekContent(version: TemplateVersion): TemplateContent | null {\n return version.content ?? fetched.get(version.id) ?? null;\n }\n\n async function resolveContent(\n version: TemplateVersion,\n ): Promise<TemplateContent> {\n const known = peekContent(version);\n if (known) return known;\n\n const templateId = requireTemplateId(\"get\");\n try {\n const content = await provider.get(templateId, version.id);\n fetched.set(version.id, content);\n return content;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function create(\n content: TemplateContent,\n meta?: { label?: string },\n ): Promise<TemplateVersion> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") refuse(\"create\");\n const templateId = requireTemplateId(\"create\");\n try {\n const created = await providerCreate(templateId, content, meta);\n versions.value = [created, ...versions.value];\n return created;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function restore(versionId: string): Promise<Template> {\n const { restore: providerRestore } = provider;\n if (typeof providerRestore !== \"function\") refuse(\"restore\");\n const templateId = requireTemplateId(\"restore\");\n isRestoring.value = true;\n try {\n return await providerRestore(templateId, versionId);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isRestoring.value = false;\n }\n }\n\n return {\n nextCursor,\n versions,\n isLoading,\n isRestoring,\n canCreate,\n canRestore,\n load,\n peekContent,\n resolveContent,\n create,\n restore,\n };\n}\n","import type {\n Comment,\n CommentAuthor,\n CommentChange,\n CommentEvent,\n CommentInput,\n CommentPatch,\n CommentsListParams,\n CommentsProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport {\n computed,\n onScopeDispose,\n ref,\n watch,\n type ComputedRef,\n type Ref,\n} from \"vue\";\n\nexport interface UseCommentsOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ comments })`, or by\n * Cloud's own adapter — this composable is transport-agnostic and never talks\n * to a network itself.\n */\n provider: CommentsProvider;\n /**\n * Which template's conversation this is. A getter rather than a value because a\n * session can outlive the template: `initCloud()` constructs the feature at\n * setup and only learns the id once `create()` / `load()` resolves.\n */\n getTemplateId: () => string | null;\n /**\n * Who is commenting, read at call time. `null` means the editor has no\n * identity, and every mutation refuses — an unattributable comment is worse\n * than no comment feature.\n */\n getUser: () => CommentAuthor | null;\n /** Fired for every change this composable applied, local or remote. */\n onComment?: (event: CommentEvent) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface UseCommentsReturn {\n /** Thread roots in the provider's order. Never re-sorted. */\n comments: Ref<Comment[]>;\n isLoading: Ref<boolean>;\n isSubmitting: Ref<boolean>;\n /** Whether the provider supplied each mutation at all. */\n canCreate: ComputedRef<boolean>;\n canUpdate: ComputedRef<boolean>;\n canDelete: ComputedRef<boolean>;\n canResolve: ComputedRef<boolean>;\n /** Roots plus replies. */\n totalCount: ComputedRef<number>;\n /** Unresolved roots — the badge on the trigger. */\n unresolvedCount: ComputedRef<number>;\n /** Comments per anchored block id, roots plus their replies. */\n commentCountByBlock: ComputedRef<Map<string, number>>;\n /** Re-read the list. The editor calls this bare; `params` is for headless callers. */\n load: (params?: CommentsListParams) => Promise<void>;\n /** Rejects with an {@link SdkError} when `create` is disabled or there is no user. */\n create: (input: CommentInput) => Promise<Comment>;\n /** Rejects with an {@link SdkError} when `update` is disabled or there is no user. */\n update: (commentId: string, patch: CommentPatch) => Promise<Comment>;\n /** Rejects with an {@link SdkError} when `delete` is disabled or there is no user. */\n remove: (commentId: string) => Promise<void>;\n /** Rejects with an {@link SdkError} when `setResolved` is disabled or there is no user. */\n setResolved: (commentId: string, resolved: boolean) => Promise<Comment>;\n /** Look one up by id, root or reply. `null` when it isn't loaded. */\n find: (commentId: string) => Comment | null;\n /** Whether this comment was written by the current user. */\n isOwn: (comment: Comment) => boolean;\n /**\n * Apply a change that arrived from {@link CommentsProvider.subscribe}. Public\n * so a consumer driving this headlessly can push their own transport into it.\n */\n applyRemoteCreate: (comment: Comment) => void;\n applyRemoteUpdate: (comment: Comment) => void;\n applyRemoteDelete: (commentId: string, parentId?: string | null) => void;\n}\n\n/**\n * Reactive state over a {@link CommentsProvider}.\n *\n * Owns the thread list, the loading flags, the local mutations that keep the list\n * consistent, and the derived counts the chrome renders. Errors are reported\n * through `onError` and **re-thrown**, leaving the list untouched on failure —\n * the same discipline as `useSavedBlocks` and `useVersionHistory`.\n *\n * Mutations **reject** when the provider withheld them rather than resolving to\n * `null`: a resolved promise reads as \"saved\" to whoever awaited it. Ask through\n * `canCreate` / `canUpdate` / `canDelete` / `canResolve` first — which is what the\n * editor's own UI does, hiding each action rather than disabling it.\n */\nexport function useComments(options: UseCommentsOptions): UseCommentsReturn {\n const { provider, getTemplateId, getUser } = options;\n\n const comments = ref<Comment[]>([]);\n const isLoading = ref(false);\n const isSubmitting = ref(false);\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canUpdate = computed(() => typeof provider.update === \"function\");\n const canDelete = computed(() => typeof provider.delete === \"function\");\n const canResolve = computed(() => typeof provider.setResolved === \"function\");\n\n const totalCount = computed(() =>\n comments.value.reduce(\n (sum, thread) => sum + 1 + (thread.replies?.length ?? 0),\n 0,\n ),\n );\n\n const unresolvedCount = computed(\n () => comments.value.filter((thread) => !thread.resolvedAt).length,\n );\n\n const commentCountByBlock = computed(() => {\n const map = new Map<string, number>();\n for (const thread of comments.value) {\n if (!thread.blockId) continue;\n map.set(\n thread.blockId,\n (map.get(thread.blockId) ?? 0) + 1 + (thread.replies?.length ?? 0),\n );\n }\n return map;\n });\n\n /**\n * The UI hides disabled actions and renders nothing before a template exists,\n * so reaching one of these means a programmatic caller went around it. Fail\n * loudly rather than silently no-op.\n */\n function requireTemplateId(action: string): string {\n const templateId = getTemplateId();\n if (!templateId) {\n throw new SdkError(\n `[Templatical] Comments: ${action} needs a template. Call create() or load() first.`,\n );\n }\n return templateId;\n }\n\n function requireUser(action: string): CommentAuthor {\n const user = getUser();\n if (!user) {\n throw new SdkError(\n `[Templatical] Comments: ${action} needs to know who is commenting. Pass init({ user: { id, name } }) — an unattributed comment is not written.`,\n );\n }\n return user;\n }\n\n function refuse(action: string): never {\n throw new SdkError(\n `[Templatical] Comments: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n function find(commentId: string): Comment | null {\n for (const thread of comments.value) {\n if (thread.id === commentId) return thread;\n for (const reply of thread.replies ?? []) {\n if (reply.id === commentId) return reply;\n }\n }\n return null;\n }\n\n function isOwn(comment: Comment): boolean {\n const user = getUser();\n return user !== null && comment.author.id === user.id;\n }\n\n function emit(type: CommentEvent[\"type\"], comment: Comment): void {\n options.onComment?.({ type, comment });\n }\n\n function report(error: unknown): never {\n const wrapped =\n error instanceof Error\n ? error\n : new Error(String(error), { cause: error });\n options.onError?.(wrapped);\n throw wrapped;\n }\n\n /**\n * Insert a comment, replacing an entry with the same id rather than duplicating\n * it. `create` and a subscribe echo of that same create both land here, which is\n * why a provider does not have to de-duplicate its own broadcasts.\n */\n function replaceAt<T>(list: T[], index: number, next: T): T[] {\n return [...list.slice(0, index), next, ...list.slice(index + 1)];\n }\n\n function upsert(comment: Comment): void {\n if (comment.parentId) {\n comments.value = comments.value.map((thread) => {\n if (thread.id !== comment.parentId) return thread;\n const replies = thread.replies ?? [];\n const at = replies.findIndex((reply) => reply.id === comment.id);\n return {\n ...thread,\n replies:\n at === -1 ? [...replies, comment] : replaceAt(replies, at, comment),\n };\n });\n return;\n }\n\n const at = comments.value.findIndex((thread) => thread.id === comment.id);\n if (at === -1) {\n comments.value = [...comments.value, comment];\n return;\n }\n // A root arriving again keeps the replies already loaded: the update payload\n // for a body edit carries none, and dropping them would empty the thread.\n comments.value = replaceAt(comments.value, at, {\n ...comment,\n replies: comment.replies ?? comments.value[at].replies,\n });\n }\n\n function drop(commentId: string, parentId?: string | null): Comment | null {\n const existing = find(commentId);\n // `parentId` from the caller wins so a delete can be applied without the\n // comment being loaded — the subscribe path, on a thread never opened.\n const parent = parentId ?? existing?.parentId ?? null;\n\n if (parent) {\n comments.value = comments.value.map((thread) =>\n thread.id === parent\n ? {\n ...thread,\n replies: (thread.replies ?? []).filter((r) => r.id !== commentId),\n }\n : thread,\n );\n } else {\n comments.value = comments.value.filter((c) => c.id !== commentId);\n }\n return existing;\n }\n\n async function load(params?: CommentsListParams): Promise<void> {\n const templateId = requireTemplateId(\"list\");\n isLoading.value = true;\n try {\n comments.value = await provider.list(templateId, params);\n } catch (error) {\n report(error);\n } finally {\n isLoading.value = false;\n }\n }\n\n async function create(input: CommentInput): Promise<Comment> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") refuse(\"create\");\n const templateId = requireTemplateId(\"create\");\n requireUser(\"create\");\n isSubmitting.value = true;\n try {\n const created = await providerCreate(templateId, input);\n upsert(created);\n emit(\"created\", created);\n return created;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function update(\n commentId: string,\n patch: CommentPatch,\n ): Promise<Comment> {\n const { update: providerUpdate } = provider;\n if (typeof providerUpdate !== \"function\") refuse(\"update\");\n const templateId = requireTemplateId(\"update\");\n requireUser(\"update\");\n isSubmitting.value = true;\n try {\n const updated = await providerUpdate(templateId, commentId, patch);\n upsert(updated);\n emit(\"updated\", updated);\n return updated;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function remove(commentId: string): Promise<void> {\n const { delete: providerDelete } = provider;\n if (typeof providerDelete !== \"function\") refuse(\"delete\");\n const templateId = requireTemplateId(\"delete\");\n requireUser(\"delete\");\n // Snapshotted before the request: the event carries what was deleted, and\n // there is nothing to read afterwards.\n const existing = find(commentId);\n isSubmitting.value = true;\n try {\n await providerDelete(templateId, commentId);\n drop(commentId);\n if (existing) emit(\"deleted\", existing);\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function setResolved(\n commentId: string,\n resolved: boolean,\n ): Promise<Comment> {\n const { setResolved: providerSetResolved } = provider;\n if (typeof providerSetResolved !== \"function\") refuse(\"setResolved\");\n const templateId = requireTemplateId(\"setResolved\");\n requireUser(\"setResolved\");\n isSubmitting.value = true;\n try {\n const updated = await providerSetResolved(\n templateId,\n commentId,\n resolved,\n );\n upsert(updated);\n // The stored result decides which event fires, not the requested state: a\n // store may refuse to reopen, and the consumer should hear what happened.\n emit(updated.resolvedAt ? \"resolved\" : \"unresolved\", updated);\n return updated;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n function applyRemoteCreate(comment: Comment): void {\n upsert(comment);\n emit(\"created\", comment);\n }\n\n function applyRemoteUpdate(comment: Comment): void {\n upsert(comment);\n emit(\n comment.resolvedAt\n ? \"resolved\"\n : // An unresolve and a body edit are both \"not resolved\"; only a payload\n // that used to be resolved is an unresolve, and the transport doesn't\n // say. `updated` is the honest answer for a plain change.\n \"updated\",\n comment,\n );\n }\n\n function applyRemoteDelete(\n commentId: string,\n parentId?: string | null,\n ): void {\n const existing = drop(commentId, parentId);\n if (existing) emit(\"deleted\", existing);\n }\n\n return {\n comments,\n isLoading,\n isSubmitting,\n canCreate,\n canUpdate,\n canDelete,\n canResolve,\n totalCount,\n unresolvedCount,\n commentCountByBlock,\n load,\n create,\n update,\n remove,\n setResolved,\n find,\n isOwn,\n applyRemoteCreate,\n applyRemoteUpdate,\n applyRemoteDelete,\n };\n}\n\nexport interface UseCommentListenerOptions {\n comments: UseCommentsReturn;\n provider: CommentsProvider;\n getTemplateId: () => string | null;\n}\n\n/**\n * Wire {@link CommentsProvider.subscribe} into the three `applyRemote*` paths.\n *\n * A no-op when the provider has no `subscribe` — realtime is optional, and\n * comments without it work exactly the same except that a colleague's comment\n * only appears on the next read. Nothing here knows about a transport: Cloud's\n * Pusher channel lives inside `createCloudCommentsProvider`, and an SSE or\n * long-poll implementation is the same three lines on the consumer's side.\n *\n * Re-subscribes when the template id changes, and unsubscribes on scope dispose —\n * so a session that loads a second template does not keep receiving the first\n * one's comments.\n */\nexport function useCommentListener(options: UseCommentListenerOptions): void {\n const { comments, provider, getTemplateId } = options;\n const { subscribe } = provider;\n if (typeof subscribe !== \"function\") return;\n\n let unsubscribe: (() => void) | null = null;\n\n function stop(): void {\n unsubscribe?.();\n unsubscribe = null;\n }\n\n watch(\n () => getTemplateId(),\n (templateId) => {\n stop();\n if (!templateId) return;\n unsubscribe = subscribe(templateId, (change: CommentChange) => {\n switch (change.type) {\n case \"created\":\n comments.applyRemoteCreate(change.comment);\n break;\n case \"updated\":\n comments.applyRemoteUpdate(change.comment);\n break;\n case \"deleted\":\n comments.applyRemoteDelete(change.commentId, change.parentId);\n break;\n }\n });\n },\n { immediate: true },\n );\n\n onScopeDispose(stop);\n}\n"],"mappings":";;;;AAcA,SAAS,eAAe,QAA8B;CACpD,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,OAAO;AACT;AAkHA,SAAgB,UAAU,SAA4C;CACpE,MAAM,QAAQ,SAAsB;EAClC,UAAU;EACV,SACE,QAAQ,WACR,6BACE,QAAQ,mBACR,QAAQ,gBACV;EACF,iBAAiB;EACjB,UAAU;EACV,UAAU;EACV,aAAa;EACb,SAAS;EACT,UAAU;EACV,WAAW;EACX,SAAS;CACX,CAAC;;;;;;;CAQD,IAAI,WAAW;CAEf,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ACA;CACF;AACF;;;;;;;;;;;;;;AAqBA,SAAgB,mBAAmB,SAA0C;CAC3E,MAAM,EAAE,UAAU,UAAU,kBAAkB;CAC9C,MAAM,EAAE,cAAc;CACtB,IAAI,OAAO,cAAc,YAAY;CAErC,IAAI,cAAmC;CAEvC,SAAS,OAAa;EACpB,cAAc;EACd,cAAc;CAChB;CAEA,cACQ,cAAc,IACnB,eAAe;EACd,KAAK;EACL,IAAI,CAAC,YAAY;EACjB,cAAc,UAAU,aAAa,WAA0B;GAC7D,QAAQ,OAAO,MAAf;IACE,KAAK;KACH,SAAS,kBAAkB,OAAO,OAAO;KACzC;IACF,KAAK;KACH,SAAS,kBAAkB,OAAO,OAAO;KACzC;IACF,KAAK,WACH,SAAS,kBAAkB,OAAO,WAAW,OAAO,QAAQ;GAEhE;EACF,CAAC;CACH,GACA,EAAE,WAAW,KAAK,CACpB;CAEA,eAAe,IAAI;AACrB"}
1
+ {"version":3,"file":"index.js","names":["ref","computed","ref","computed","ref","computed"],"sources":["../src/error-reporting.ts","../src/editor.ts","../src/history.ts","../src/block-actions.ts","../src/auto-save.ts","../src/condition-preview.ts","../src/data-source-fetch.ts","../src/history-interceptor.ts","../src/saved-blocks.ts","../src/saved-blocks-local.ts","../src/version-history.ts","../src/comments.ts"],"sourcesContent":["/**\n * Turn a thrown value into an `Error`.\n *\n * A `catch` clause's binding is `unknown` — a provider or a consumer's event\n * handler can throw a string, an object, or anything else. `onError` callbacks\n * across this package are typed to take an `Error`, so this is what makes that\n * contract honest at the one place values actually cross it.\n */\nexport function wrapReportedError(error: unknown): Error {\n return error instanceof Error\n ? error\n : new Error(String(error), { cause: error });\n}\n\n/**\n * Run a consumer's event handler without letting it fail the operation it\n * followed.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the caller has already succeeded by the time this runs. `onError` is taken\n * as a parameter rather than read from a shared reporter, so every feature\n * module keeps its own `options.onError` wiring and this stays reusable by\n * any module with the same fire-and-forget event shape.\n */\nexport function notifyHandler(\n onError: ((error: Error) => void) | undefined,\n run: () => void,\n): void {\n try {\n run();\n } catch (error) {\n onError?.(wrapReportedError(error));\n }\n}\n","import type {\n Block,\n ColumnLayout,\n Template,\n TemplateContent,\n TemplateDefaults,\n TemplatePatch,\n TemplateSaveTrigger,\n TemplateSettings,\n TemplatesProvider,\n UiTheme,\n ViewportSize,\n} from \"@templatical/types\";\nimport { createDefaultTemplateContent, SdkError } from \"@templatical/types\";\nimport { notifyHandler } from \"./error-reporting\";\n\nfunction getColumnCount(layout: ColumnLayout): number {\n if (layout === \"1\") return 1;\n if (layout === \"3\") return 3;\n return 2;\n}\nimport {\n computed,\n reactive,\n readonly,\n type DeepReadonly,\n type Ref,\n} from \"@vue/reactivity\";\n\nexport interface EditorState {\n /**\n * The template currently being edited, as the store last returned it — `null`\n * until `create()` or `load()` resolves, and always `null` without a\n * {@link TemplatesProvider}.\n *\n * Carries identity and name only for practical purposes: its `content` is the\n * store's copy from the last round-trip, whereas `state.content` is what the\n * user is editing.\n */\n template: Template | null;\n content: TemplateContent;\n selectedBlockId: string | null;\n viewport: ViewportSize;\n darkMode: boolean;\n previewMode: boolean;\n isDirty: boolean;\n /** True for the duration of a `save()` call. */\n isSaving: boolean;\n /** True for the duration of a `create()` or `load()` call. */\n isLoading: boolean;\n uiTheme: UiTheme;\n}\n\nexport interface UseEditorOptions {\n content: TemplateContent;\n defaultFontFamily?: string;\n templateDefaults?: TemplateDefaults;\n lockedBlocks?: Ref<Map<string, unknown>>;\n /**\n * Storage backend for the template's save/load lifecycle. Omit it and\n * `create()` / `load()` / `save()` reject — the editor keeps working as a\n * purely local editing surface.\n */\n templates?: TemplatesProvider;\n /**\n * Called with any error a provider call rejects with, before the rejection is\n * re-thrown to the caller.\n */\n onError?: (error: Error) => void;\n}\n\nexport interface UseEditorReturn {\n state: DeepReadonly<EditorState>;\n content: Ref<TemplateContent>;\n selectedBlock: Ref<Block | null>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n selectBlock: (blockId: string | null) => void;\n setViewport: (viewport: ViewportSize) => void;\n setDarkMode: (darkMode: boolean) => void;\n setPreviewMode: (previewMode: boolean) => void;\n setUiTheme: (theme: UiTheme) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n updateSettings: (updates: Partial<TemplateSettings>) => void;\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n moveBlock: (\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex?: number,\n ) => void;\n isBlockLocked: (blockId: string) => boolean;\n markDirty: () => void;\n findBlockLocation: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n /**\n * Rename the loaded template locally and mark the editor dirty. The new name\n * reaches the store on the next `save()`, in the same patch as the content —\n * a rename is an ordinary unsaved change, not a side channel.\n *\n * This method only stages it. The editor's inline rename field commits by\n * calling `setName()` and then saving immediately, because a rename reads as a\n * discrete action rather than an edit to be batched — so in the editor the\n * \"next `save()`\" is usually the one it triggers itself. A headless caller\n * decides its own moment.\n *\n * No-op when no template is loaded: there is nothing to name.\n */\n setName: (name: string) => void;\n /**\n * Persist the current content as a new template. `input.content`, when given,\n * replaces the editor's content first — so `create({ content })` both loads\n * and stores in one step.\n */\n create: (input?: {\n name?: string;\n content?: TemplateContent;\n }) => Promise<Template>;\n /** Fetch a template and make it the editor's content. */\n load: (templateId: string) => Promise<Template>;\n /**\n * Persist the loaded template's name + content as a patch.\n *\n * `trigger` is passed through to `TemplatesOptions.onSaved`. It defaults to\n * `\"api\"`, which is the honest answer for a direct call — the editor package\n * passes the value matching whichever affordance fired.\n */\n save: (trigger?: TemplateSaveTrigger) => Promise<Template>;\n /** Whether a template has been created or loaded. */\n hasTemplate: () => boolean;\n}\n\nexport function useEditor(options: UseEditorOptions): UseEditorReturn {\n const state = reactive<EditorState>({\n template: null,\n content:\n options.content ??\n createDefaultTemplateContent(\n options.defaultFontFamily,\n options.templateDefaults,\n ),\n selectedBlockId: null,\n viewport: \"desktop\",\n darkMode: false,\n previewMode: false,\n isDirty: false,\n isSaving: false,\n isLoading: false,\n uiTheme: \"auto\",\n });\n\n /**\n * Bumped by every content mutation. `save()` captures it before awaiting the\n * provider and only clears `isDirty` if it is unchanged afterwards, so an edit\n * made while a save is in flight is not reported as persisted — which would\n * also make autosave skip it, since that decides dirtiness at debounce time.\n */\n let revision = 0;\n\n function touch(): void {\n state.isDirty = true;\n revision++;\n }\n\n const content = computed({\n get: () => state.content,\n set: (value: TemplateContent) => {\n state.content = value;\n touch();\n },\n });\n\n const selectedBlock = computed(() => {\n if (!state.selectedBlockId) return null;\n return findBlockById(state.content.blocks, state.selectedBlockId);\n });\n\n function findBlockById(blocks: Block[], id: string): Block | null {\n for (const block of blocks) {\n if (block.id === id) return block;\n if (block.type === \"section\") {\n for (const column of block.children) {\n const found = findBlockById(column, id);\n if (found) return found;\n }\n }\n }\n return null;\n }\n\n function collectBlockIds(block: Block, ids: Set<string>): void {\n ids.add(block.id);\n if (block.type === \"section\") {\n for (const column of block.children) {\n for (const child of column) {\n collectBlockIds(child, ids);\n }\n }\n }\n }\n\n function findBlockParent(\n blocks: Block[],\n id: string,\n parent: {\n blocks: Block[];\n sectionId?: string;\n columnIndex?: number;\n } = { blocks },\n ): { blocks: Block[]; sectionId?: string; columnIndex?: number } | null {\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (block.id === id) return parent;\n if (block.type === \"section\") {\n for (let colIdx = 0; colIdx < block.children.length; colIdx++) {\n const result = findBlockParent(block.children[colIdx], id, {\n blocks: block.children[colIdx],\n sectionId: block.id,\n columnIndex: colIdx,\n });\n if (result) return result;\n }\n }\n }\n return null;\n }\n\n function isBlockLocked(blockId: string): boolean {\n return options.lockedBlocks?.value.has(blockId) ?? false;\n }\n\n function findBlockLocation(blockId: string): {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null {\n const parent = findBlockParent(state.content.blocks, blockId);\n if (!parent) return null;\n const index = parent.blocks.findIndex((b) => b.id === blockId);\n if (index === -1) return null;\n return {\n targetSectionId: parent.sectionId,\n columnIndex: parent.columnIndex,\n index,\n };\n }\n\n // TODO(collab): the lock checks in addBlock/moveBlock/removeBlock/updateBlock\n // are shallow — they only consider the directly-targeted block id. A section\n // can still be removed, moved, or have its `children` array rewritten while a\n // peer is editing one of its descendants, which silently disrupts that peer's\n // edit. Add a `hasLockedDescendant(blockId)` helper and gate section-level\n // operations on it (and on the parent of each affected child) so cascades\n // through the tree are also blocked.\n\n function setContent(newContent: TemplateContent, markDirty = true): void {\n state.content = newContent;\n if (markDirty) {\n touch();\n }\n }\n\n function selectBlock(blockId: string | null): void {\n if (blockId && isBlockLocked(blockId)) {\n return;\n }\n state.selectedBlockId = blockId;\n }\n\n function setViewport(viewport: ViewportSize): void {\n state.viewport = viewport;\n }\n\n function setDarkMode(darkMode: boolean): void {\n state.darkMode = darkMode;\n }\n\n function setUiTheme(theme: UiTheme): void {\n state.uiTheme = theme;\n }\n\n function setPreviewMode(previewMode: boolean): void {\n state.previewMode = previewMode;\n if (previewMode) {\n state.selectedBlockId = null;\n }\n }\n\n function updateBlock(blockId: string, updates: Partial<Block>): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n const block = findBlockById(state.content.blocks, blockId);\n if (block) {\n Object.assign(block, updates);\n touch();\n }\n }\n\n function updateSettings(updates: Partial<TemplateSettings>): void {\n state.content.settings = { ...state.content.settings, ...updates };\n touch();\n }\n\n function addBlock(\n block: Block,\n targetSectionId?: string,\n columnIndex = 0,\n index?: number,\n ): void {\n // Sections cannot be nested inside a column — MJML forbids `mj-section`\n // inside `mj-column`, so the renderer drops them on export (issue #292).\n // Reject the nest up front rather than lose the content silently later.\n if (targetSectionId && block.type === \"section\") {\n return;\n }\n if (targetSectionId) {\n if (isBlockLocked(targetSectionId)) {\n return;\n }\n const section = findBlockById(state.content.blocks, targetSectionId);\n if (section && section.type === \"section\") {\n if (columnIndex < 0 || columnIndex >= getColumnCount(section.columns)) {\n return;\n }\n section.children[columnIndex] = section.children[columnIndex] || [];\n const targetArray = section.children[columnIndex];\n if (index !== undefined && index < targetArray.length) {\n targetArray.splice(index, 0, block);\n } else {\n targetArray.push(block);\n }\n }\n } else {\n if (index !== undefined && index < state.content.blocks.length) {\n state.content.blocks.splice(index, 0, block);\n } else {\n state.content.blocks.push(block);\n }\n }\n touch();\n }\n\n function removeBlock(blockId: string): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n const parent = findBlockParent(state.content.blocks, blockId);\n if (parent) {\n const index = parent.blocks.findIndex((b) => b.id === blockId);\n if (index !== -1) {\n const [removed] = parent.blocks.splice(index, 1);\n if (state.selectedBlockId) {\n const removedIds = new Set<string>();\n collectBlockIds(removed, removedIds);\n if (removedIds.has(state.selectedBlockId)) {\n state.selectedBlockId = null;\n }\n }\n touch();\n }\n }\n }\n\n function moveBlock(\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex = 0,\n ): void {\n if (isBlockLocked(blockId)) {\n return;\n }\n if (targetSectionId && isBlockLocked(targetSectionId)) {\n return;\n }\n\n const parent = findBlockParent(state.content.blocks, blockId);\n if (!parent) return;\n\n const oldIndex = parent.blocks.findIndex((b) => b.id === blockId);\n if (oldIndex === -1) return;\n\n // Sections cannot be nested inside a column (issue #292) — refuse to move\n // a section into a section column; MJML would drop it on export.\n if (targetSectionId && parent.blocks[oldIndex].type === \"section\") {\n return;\n }\n\n // Resolve target before mutating the source — otherwise an invalid\n // targetSectionId leaves the block spliced-out and unrecoverable.\n let targetArray: Block[];\n if (targetSectionId) {\n const section = findBlockById(state.content.blocks, targetSectionId);\n if (!section || section.type !== \"section\") return;\n if (columnIndex < 0 || columnIndex >= getColumnCount(section.columns)) {\n return;\n }\n section.children[columnIndex] = section.children[columnIndex] || [];\n targetArray = section.children[columnIndex];\n } else {\n targetArray = state.content.blocks;\n }\n\n const [block] = parent.blocks.splice(oldIndex, 1);\n targetArray.splice(newIndex, 0, block);\n\n touch();\n }\n\n function markDirty(): void {\n touch();\n }\n\n // -------------------------------------------------------------------------\n // Template lifecycle (over an optional TemplatesProvider)\n // -------------------------------------------------------------------------\n\n /**\n * A refused call throws rather than resolving, because a resolved promise\n * would read as \"saved\" to whoever awaited it.\n *\n * The message names the provider key the consumer set, not an internal\n * capability flag: `EditorCapabilities` is type-only and its injection key is\n * unexported, so neither a core nor an editor consumer can read one. Note the\n * editor hides its own save controls when `save` is withheld but has no\n * create affordance to hide at all, so `create()` is reachable by definition.\n */\n function refuse(action: string, reason: string): never {\n throw new SdkError(`[Templatical] Templates: ${action} ${reason}`);\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for something that landed.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n function requireProvider(action: string): TemplatesProvider {\n const { templates } = options;\n if (!templates) {\n refuse(\n action,\n \"needs a templates provider. Pass one as `init({ templates })` to enable saving and loading.\",\n );\n }\n return templates;\n }\n\n function setName(name: string): void {\n if (!state.template) return;\n state.template = { ...state.template, name };\n touch();\n }\n\n async function create(input?: {\n name?: string;\n content?: TemplateContent;\n }): Promise<Template> {\n const provider = requireProvider(\"create()\");\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") {\n refuse(\n \"create()\",\n \"is disabled by the provider — its `create` is `false`.\",\n );\n }\n\n let created: Template;\n state.isLoading = true;\n try {\n if (input?.content) {\n state.content = input.content;\n }\n // Omit `name` entirely when unset rather than sending `undefined` — a\n // provider serialising the input to JSON would otherwise receive a key it\n // never asked for.\n const revisionAtRequest = revision;\n created = await providerCreate(\n input?.name !== undefined\n ? { name: input.name, content: state.content }\n : { content: state.content },\n );\n state.template = created;\n if (revision === revisionAtRequest) {\n state.isDirty = false;\n }\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isLoading = false;\n }\n // Below the `finally` on purpose: `isLoading` is cleared there, so a handler\n // must not observe the editor still loading. Unreachable on failure — the\n // catch rethrows.\n notify(() => provider.onCreated?.(created));\n return created;\n }\n\n async function load(templateId: string): Promise<Template> {\n const provider = requireProvider(\"load()\");\n\n let loaded: Template;\n state.isLoading = true;\n try {\n loaded = await provider.load(templateId);\n state.template = loaded;\n state.content = loaded.content;\n state.isDirty = false;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isLoading = false;\n }\n // Below the `finally` on purpose: `isLoading` is cleared there, so a handler\n // must not observe the editor still loading. Unreachable on failure — the\n // catch rethrows.\n notify(() => provider.onLoaded?.(loaded));\n return loaded;\n }\n\n async function save(trigger: TemplateSaveTrigger = \"api\"): Promise<Template> {\n const provider = requireProvider(\"save()\");\n const { save: providerSave } = provider;\n if (typeof providerSave !== \"function\") {\n refuse(\"save()\", \"is disabled by the provider — its `save` is `false`.\");\n }\n const current = state.template;\n if (!current) {\n refuse(\n \"save()\",\n \"has no template loaded. Call create() or load() first.\",\n );\n }\n\n // The name rides the same patch as the content: a rename is an ordinary\n // unsaved change, so one round-trip persists both.\n const patch: TemplatePatch =\n current.name !== undefined\n ? { name: current.name, content: state.content }\n : { content: state.content };\n\n let saved: Template;\n state.isSaving = true;\n try {\n const revisionAtRequest = revision;\n saved = await providerSave(current.id, patch);\n // Adopt the response only while it still describes what is open. A\n // `load()` that landed mid-flight has already replaced the template, so\n // the response is stale.\n if (state.template?.id === current.id) {\n // The patch was built before the await, so a rename that landed during\n // it is absent from the response. Taking the response's name verbatim\n // reverts what the user typed — and because the next save reads the\n // name back off `state.template`, it would then persist the stale one,\n // losing the rename outright rather than merely on screen.\n const localName = state.template.name;\n state.template =\n localName !== current.name ? { ...saved, name: localName } : saved;\n }\n // Deliberately conditional. An edit landing while the request was in\n // flight is not persisted by it, and clearing the flag would both claim it\n // was and make autosave — which checks dirtiness at debounce time — skip\n // the follow-up save.\n if (revision === revisionAtRequest) {\n state.isDirty = false;\n }\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n state.isSaving = false;\n }\n // Below the `finally` on purpose: `isSaving` is cleared there, and a handler\n // that navigates must observe a settled editor or the consumer's own dirty\n // guard blocks their navigation. Unreachable on failure — the catch rethrows.\n notify(() => provider.onSaved?.(saved, { trigger }));\n return saved;\n }\n\n function hasTemplate(): boolean {\n return state.template?.id !== undefined;\n }\n\n return {\n state: readonly(state),\n content,\n selectedBlock,\n isBlockLocked,\n setContent,\n selectBlock,\n setViewport,\n setDarkMode,\n setUiTheme,\n setPreviewMode,\n updateBlock,\n updateSettings,\n addBlock,\n removeBlock,\n moveBlock,\n markDirty,\n findBlockLocation,\n setName,\n create,\n load,\n save,\n hasTemplate,\n };\n}\n","import { safeClone, type TemplateContent } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"@vue/reactivity\";\n\nexport interface UseHistoryOptions {\n content: Ref<TemplateContent>;\n setContent: (content: TemplateContent, markDirty?: boolean) => void;\n isRemoteOperation?: () => boolean;\n maxSize?: number;\n}\n\nexport interface UseHistoryReturn {\n canUndo: ComputedRef<boolean>;\n canRedo: ComputedRef<boolean>;\n isNavigating: Ref<boolean>;\n undo: () => void;\n redo: () => void;\n record: () => void;\n recordDebounced: (blockId: string) => void;\n clear: () => void;\n destroy: () => void;\n}\n\ninterface DebouncedSnapshot {\n blockId: string;\n timeoutId: ReturnType<typeof setTimeout>;\n}\n\nconst MAX_STACK_SIZE = 50;\nconst DEBOUNCE_MS = 300;\nconst NAVIGATE_IDLE_MS = 1500;\n\nexport function useHistory(options: UseHistoryOptions): UseHistoryReturn {\n const {\n content,\n setContent,\n isRemoteOperation,\n maxSize = MAX_STACK_SIZE,\n } = options;\n\n const undoStack = ref<TemplateContent[]>([]);\n const redoStack = ref<TemplateContent[]>([]);\n const isNavigating = ref(false);\n let navigatingTimeoutId: ReturnType<typeof setTimeout> | null = null;\n let pendingDebounce: DebouncedSnapshot | null = null;\n\n const canUndo = computed(() => undoStack.value.length > 0);\n const canRedo = computed(() => redoStack.value.length > 0);\n\n function cloneContent(): TemplateContent {\n // Cycle-safe deep clone (see `safeClone`). A naked JSON.stringify throws\n // `Converting circular structure to JSON` if a DOM element with a Sortable\n // expando back-ref ever sneaks into block data via a drag handler — which\n // would freeze the undo stack, since every subsequent mutation calls\n // `record()`. safeClone drops the back-ref instead of throwing.\n return safeClone(content.value);\n }\n\n function pushToUndoStack(snapshot: TemplateContent): void {\n undoStack.value.push(snapshot);\n if (undoStack.value.length > maxSize) {\n undoStack.value.splice(0, undoStack.value.length - maxSize);\n }\n }\n\n function flushPendingDebounce(): void {\n if (pendingDebounce) {\n clearTimeout(pendingDebounce.timeoutId);\n pendingDebounce = null;\n }\n }\n\n function record(): void {\n if (isRemoteOperation?.()) {\n return;\n }\n\n flushPendingDebounce();\n pushToUndoStack(cloneContent());\n redoStack.value = [];\n }\n\n function recordDebounced(blockId: string): void {\n if (isRemoteOperation?.()) {\n return;\n }\n\n if (pendingDebounce && pendingDebounce.blockId === blockId) {\n clearTimeout(pendingDebounce.timeoutId);\n pendingDebounce.timeoutId = setTimeout(() => {\n pendingDebounce = null;\n }, DEBOUNCE_MS);\n return;\n }\n\n flushPendingDebounce();\n\n pushToUndoStack(cloneContent());\n redoStack.value = [];\n\n pendingDebounce = {\n blockId,\n timeoutId: setTimeout(() => {\n pendingDebounce = null;\n }, DEBOUNCE_MS),\n };\n }\n\n function setNavigating(): void {\n isNavigating.value = true;\n if (navigatingTimeoutId) {\n clearTimeout(navigatingTimeoutId);\n }\n navigatingTimeoutId = setTimeout(() => {\n isNavigating.value = false;\n navigatingTimeoutId = null;\n }, NAVIGATE_IDLE_MS);\n }\n\n function undo(): void {\n if (undoStack.value.length === 0) {\n return;\n }\n\n flushPendingDebounce();\n\n const snapshot = undoStack.value.pop()!;\n redoStack.value.push(cloneContent());\n setContent(snapshot, true);\n setNavigating();\n }\n\n function redo(): void {\n if (redoStack.value.length === 0) {\n return;\n }\n\n flushPendingDebounce();\n\n const snapshot = redoStack.value.pop()!;\n undoStack.value.push(cloneContent());\n setContent(snapshot, true);\n setNavigating();\n }\n\n function clear(): void {\n undoStack.value = [];\n redoStack.value = [];\n flushPendingDebounce();\n }\n\n function destroy(): void {\n clear();\n if (navigatingTimeoutId) {\n clearTimeout(navigatingTimeoutId);\n navigatingTimeoutId = null;\n }\n }\n\n return {\n canUndo,\n canRedo,\n isNavigating,\n undo,\n redo,\n record,\n recordDebounced,\n clear,\n destroy,\n };\n}\n","import type { Block, BlockDefaults, BlockType } from \"@templatical/types\";\nimport { createBlock, generateId } from \"@templatical/types\";\n\nfunction regenerateNestedIds(block: Block): void {\n if (block.type === \"table\") {\n block.rows = block.rows.map((row) => ({\n ...row,\n id: generateId(),\n cells: row.cells.map((cell) => ({ ...cell, id: generateId() })),\n }));\n } else if (block.type === \"social\") {\n block.icons = block.icons.map((icon) => ({ ...icon, id: generateId() }));\n } else if (block.type === \"menu\") {\n block.items = block.items.map((item) => ({ ...item, id: generateId() }));\n }\n}\n\nexport interface UseBlockActionsOptions {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n selectBlock: (blockId: string | null) => void;\n /** Locate a block in the tree — used by `duplicateBlock` to insert the\n * clone right after the source instead of appending to the end. */\n findBlockLocation?: (blockId: string) => {\n targetSectionId?: string;\n columnIndex?: number;\n index: number;\n } | null;\n blockDefaults?: BlockDefaults;\n}\n\nexport interface UseBlockActionsReturn {\n createAndAddBlock: (\n type: BlockType,\n targetSectionId?: string,\n columnIndex?: number,\n ) => Block;\n duplicateBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n ) => Block;\n deleteBlock: (blockId: string) => void;\n updateBlockProperty: <K extends keyof Block>(\n blockId: string,\n key: K,\n value: Block[K],\n ) => void;\n}\n\nexport function useBlockActions(\n options: UseBlockActionsOptions,\n): UseBlockActionsReturn {\n const { addBlock, removeBlock, updateBlock, selectBlock, findBlockLocation } =\n options;\n\n function createAndAddBlock(\n type: BlockType,\n targetSectionId?: string,\n columnIndex?: number,\n ): Block {\n const block = createBlock(type, options.blockDefaults);\n addBlock(block, targetSectionId, columnIndex);\n selectBlock(block.id);\n return block;\n }\n\n function duplicateBlock(\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n ): Block {\n const cloned = JSON.parse(JSON.stringify(block)) as Block;\n cloned.id = generateId();\n regenerateNestedIds(cloned);\n\n if (cloned.type === \"section\") {\n cloned.children = cloned.children.map((column) =>\n column.map((child) => {\n const clonedChild = JSON.parse(JSON.stringify(child)) as Block;\n clonedChild.id = generateId();\n regenerateNestedIds(clonedChild);\n return clonedChild;\n }),\n );\n }\n\n // Insert directly after the source block. Explicit target args win;\n // otherwise, resolve the source's location and bump index by 1. Falls\n // back to appending at the end if location is unknown.\n if (targetSectionId !== undefined || columnIndex !== undefined) {\n addBlock(cloned, targetSectionId, columnIndex);\n } else {\n const sourceLocation = findBlockLocation?.(block.id) ?? null;\n if (sourceLocation) {\n addBlock(\n cloned,\n sourceLocation.targetSectionId,\n sourceLocation.columnIndex,\n sourceLocation.index + 1,\n );\n } else {\n addBlock(cloned, targetSectionId, columnIndex);\n }\n }\n selectBlock(cloned.id);\n return cloned;\n }\n\n function deleteBlock(blockId: string): void {\n removeBlock(blockId);\n }\n\n function updateBlockProperty<K extends keyof Block>(\n blockId: string,\n key: K,\n value: Block[K],\n ): void {\n updateBlock(blockId, { [key]: value } as Partial<Block>);\n }\n\n return {\n createAndAddBlock,\n duplicateBlock,\n deleteBlock,\n updateBlockProperty,\n };\n}\n","import type { TemplateContent } from \"@templatical/types\";\nimport { watch, type Ref } from \"@vue/reactivity\";\n\nexport interface UseAutoSaveOptions {\n content: Ref<TemplateContent>;\n isDirty: () => boolean;\n onChange: (content: TemplateContent) => void;\n debounce?: number;\n enabled?: boolean | (() => boolean);\n}\n\nexport interface UseAutoSaveReturn {\n flush: () => void;\n cancel: () => void;\n pause: () => void;\n resume: () => void;\n destroy: () => void;\n}\n\n/**\n * Trailing debounce, in ms, measured from the *last* content mutation.\n *\n * Typing is not debounced upstream — TipTap's `onUpdate` calls `updateBlock` per\n * keystroke — so this is the only thing between a keypress and a whole-document\n * write. 1000 was too eager: ordinary prose pauses for a second constantly\n * (word choice, re-reading, reaching for the mouse), so a single paragraph could\n * produce dozens of full-content saves. 2000 roughly halves that while still\n * landing well before a user wonders whether their work was kept.\n *\n * **The single default for both entry points.** Cloud imports this constant\n * rather than declaring its own — a second copy for one setting drifts silently,\n * since nothing links the two.\n */\nexport const DEFAULT_AUTO_SAVE_DEBOUNCE_MS = 2000;\n\nexport function useAutoSave(options: UseAutoSaveOptions): UseAutoSaveReturn {\n const {\n content,\n isDirty,\n onChange,\n debounce = DEFAULT_AUTO_SAVE_DEBOUNCE_MS,\n enabled = true,\n } = options;\n\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let paused = false;\n\n function isEnabled(): boolean {\n return typeof enabled === \"function\" ? enabled() : enabled;\n }\n\n function pause(): void {\n paused = true;\n cancel();\n }\n\n function resume(): void {\n paused = false;\n }\n\n function cancel(): void {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n }\n\n function flush(): void {\n cancel();\n if (isDirty()) {\n onChange(JSON.parse(JSON.stringify(content.value)));\n }\n }\n\n function scheduleOnChange(): void {\n if (!isEnabled() || paused) return;\n\n cancel();\n timeoutId = setTimeout(() => {\n timeoutId = null;\n if (isEnabled() && !paused && isDirty()) {\n onChange(JSON.parse(JSON.stringify(content.value)));\n }\n }, debounce);\n }\n\n // `watch` from `@vue/reactivity` has no scheduler, so this callback runs\n // *synchronously inside the mutation* — before the editor's trailing\n // `state.isDirty = true`, and `isDirty` sits outside the watched `content`\n // subtree so setting it never re-triggers. An `isDirty()` guard here would\n // therefore drop the first edit after every dirty-flag reset (issue #522).\n // Dirtiness is decided at debounce time instead, where the flag is settled;\n // `scheduleOnChange` still checks `enabled`/`paused` up front.\n const stopWatch = watch(\n content,\n () => {\n scheduleOnChange();\n },\n { deep: true },\n );\n\n function destroy(): void {\n stopWatch();\n cancel();\n }\n\n return {\n flush,\n cancel,\n pause,\n resume,\n destroy,\n };\n}\n","import { computed, reactive, type ComputedRef } from \"@vue/reactivity\";\n\nexport interface UseConditionPreviewReturn {\n isHidden: (blockId: string) => boolean;\n toggleBlock: (blockId: string) => void;\n reset: () => void;\n hasHiddenBlocks: ComputedRef<boolean>;\n}\n\n/**\n * The slice of an editor this needs — deliberately structural, so both the OSS\n * and the Cloud `useEditor` satisfy it without either having to grow toward the\n * other.\n */\nexport interface ConditionPreviewEditor {\n state: { readonly selectedBlockId: string | null };\n selectBlock: (blockId: string | null) => void;\n}\n\nexport function useConditionPreview(\n editor: ConditionPreviewEditor,\n): UseConditionPreviewReturn {\n const hiddenBlockIds = reactive(new Set<string>());\n\n const hasHiddenBlocks = computed(() => hiddenBlockIds.size > 0);\n\n function isHidden(blockId: string): boolean {\n return hiddenBlockIds.has(blockId);\n }\n\n function toggleBlock(blockId: string): void {\n if (hiddenBlockIds.has(blockId)) {\n hiddenBlockIds.delete(blockId);\n } else {\n hiddenBlockIds.add(blockId);\n\n if (editor.state.selectedBlockId === blockId) {\n editor.selectBlock(null);\n }\n }\n }\n\n function reset(): void {\n hiddenBlockIds.clear();\n }\n\n return {\n isHidden,\n toggleBlock,\n reset,\n hasHiddenBlocks,\n };\n}\n","import type { CustomBlock, CustomBlockDefinition } from \"@templatical/types\";\nimport type { ComputedRef, Ref } from \"@vue/reactivity\";\nimport { computed, ref } from \"@vue/reactivity\";\n\nexport function useDataSourceFetch(options: {\n definition: ComputedRef<CustomBlockDefinition | undefined>;\n block: ComputedRef<CustomBlock>;\n onUpdate: (fieldValues: Record<string, unknown>, fetched: boolean) => void;\n}): {\n isFetching: Ref<boolean>;\n fetchError: Ref<boolean>;\n fetch: () => Promise<void>;\n hasDataSource: ComputedRef<boolean>;\n needsFetch: ComputedRef<boolean>;\n} {\n const isFetching = ref(false);\n const fetchError = ref(false);\n\n const hasDataSource = computed(() => !!options.definition.value?.dataSource);\n\n const needsFetch = computed(\n () => hasDataSource.value && !options.block.value.dataSourceFetched,\n );\n\n async function fetch(): Promise<void> {\n const def = options.definition.value;\n if (!def?.dataSource) {\n return;\n }\n\n isFetching.value = true;\n fetchError.value = false;\n\n try {\n const result = await def.dataSource.onFetch({\n fieldValues: { ...options.block.value.fieldValues },\n blockId: options.block.value.id,\n });\n\n if (result == null) {\n return;\n }\n\n const merged = { ...options.block.value.fieldValues };\n for (const key of Object.keys(merged)) {\n if (key in result) {\n merged[key] = result[key];\n }\n }\n\n options.onUpdate(merged, true);\n } catch (error) {\n console.warn(\"[Templatical] Data source fetch error:\", error);\n fetchError.value = true;\n } finally {\n isFetching.value = false;\n }\n }\n\n return {\n isFetching,\n fetchError,\n fetch,\n hasDataSource,\n needsFetch,\n };\n}\n","import type { Block, TemplateSettings } from \"@templatical/types\";\nimport type { UseHistoryReturn } from \"./history\";\n\n/**\n * The mutable slice of an editor this wraps — structural, so the OSS and Cloud\n * `useEditor` returns both satisfy it without either having to grow toward the\n * other. Not `Readonly`: the whole point is to replace these members in place.\n */\nexport interface HistoryInterceptorEditor {\n addBlock: (\n block: Block,\n targetSectionId?: string,\n columnIndex?: number,\n index?: number,\n ) => void;\n removeBlock: (blockId: string) => void;\n moveBlock: (\n blockId: string,\n newIndex: number,\n targetSectionId?: string,\n columnIndex?: number,\n ) => void;\n updateBlock: (blockId: string, updates: Partial<Block>) => void;\n updateSettings: (updates: Partial<TemplateSettings>) => void;\n isBlockLocked: (blockId: string) => boolean;\n}\n\n/**\n * Wraps editor mutation methods to record history snapshots before each\n * operation. Mutates the editor object in place.\n *\n * Must be applied **after** any collaboration broadcast wrapping so the\n * call chain is: history.record() → broadcast → original mutation.\n */\nexport function useHistoryInterceptor(\n editor: HistoryInterceptorEditor,\n history: UseHistoryReturn,\n): void {\n const originalAddBlock = editor.addBlock;\n const originalRemoveBlock = editor.removeBlock;\n const originalMoveBlock = editor.moveBlock;\n const originalUpdateBlock = editor.updateBlock;\n const originalUpdateSettings = editor.updateSettings;\n\n // Skip recording when the underlying op is a no-op (e.g., a peer-locked\n // block or section), otherwise the undo stack fills with snapshots that\n // are identical to current state and undo silently does nothing.\n editor.addBlock = (block, targetSectionId?, columnIndex?, index?) => {\n if (targetSectionId && editor.isBlockLocked(targetSectionId)) {\n return;\n }\n history.record();\n originalAddBlock(block, targetSectionId, columnIndex, index);\n };\n\n editor.removeBlock = (blockId) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n history.record();\n originalRemoveBlock(blockId);\n };\n\n editor.moveBlock = (blockId, newIndex, targetSectionId?, columnIndex?) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n if (targetSectionId && editor.isBlockLocked(targetSectionId)) {\n return;\n }\n history.record();\n originalMoveBlock(blockId, newIndex, targetSectionId, columnIndex);\n };\n\n editor.updateBlock = (blockId, updates) => {\n if (editor.isBlockLocked(blockId)) {\n return;\n }\n history.recordDebounced(blockId);\n originalUpdateBlock(blockId, updates);\n };\n\n editor.updateSettings = (updates) => {\n history.record();\n originalUpdateSettings(updates);\n };\n}\n","import type {\n Block,\n SavedBlock,\n SavedBlockPatch,\n SavedBlocksListParams,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"vue\";\nimport { notifyHandler } from \"./error-reporting\";\n\nexport interface UseSavedBlocksOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ savedBlocks })`, or\n * by Cloud's own adapter — this composable is transport-agnostic and never\n * talks to a network itself.\n */\n provider: SavedBlocksProvider;\n onError?: (error: Error) => void;\n}\n\nexport interface UseSavedBlocksReturn {\n /** In-memory mirror of the provider's list, kept in sync after each call. */\n savedBlocks: Ref<SavedBlock[]>;\n isLoading: Ref<boolean>;\n /**\n * Distinct categories across the loaded entries, alphabetically sorted.\n *\n * Derived rather than stored: a category exists exactly as long as an entry\n * carries it. Sorting here is not a violation of \"the editor never re-sorts\"\n * — that rule protects the provider's ordering of *entries*, whereas these\n * are strings with no given order.\n */\n categories: ComputedRef<string[]>;\n /**\n * Whether the provider supplied each mutation at all — `false` on the\n * provider means the capability does not exist for this user, and the UI\n * hides the corresponding affordance entirely.\n *\n * Constant for the provider's lifetime, but exposed as computed refs so\n * consumers can bind them the same way as everything else here.\n */\n canCreate: ComputedRef<boolean>;\n canUpdate: ComputedRef<boolean>;\n canDelete: ComputedRef<boolean>;\n /**\n * Whether a *particular* entry may be edited / deleted: the capability must\n * exist AND the entry must not opt out via `canUpdate` / `canDelete`.\n *\n * Use these rather than reading the flags directly, so every surface asks the\n * question the same way and the \"absent means allowed\" default lives in one\n * place.\n */\n canUpdateBlock: (block: SavedBlock) => boolean;\n canDeleteBlock: (block: SavedBlock) => boolean;\n /**\n * Re-read from the provider. The editor always calls this bare and filters\n * in memory; `params` exists for headless callers that want the provider to\n * filter instead (see {@link SavedBlocksListParams}).\n */\n load: (params?: SavedBlocksListParams) => Promise<void>;\n /** Rejects with an {@link SdkError} when the provider disabled `create`. */\n create: (\n name: string,\n content: Block[],\n category?: string,\n ) => Promise<SavedBlock>;\n /** Rejects when `update` is disabled or the entry opts out of editing. */\n update: (id: string, patch: SavedBlockPatch) => Promise<SavedBlock>;\n /** Rejects when `delete` is disabled or the entry opts out of deletion. */\n remove: (id: string) => Promise<void>;\n}\n\n/**\n * Reactive state over a {@link SavedBlocksProvider}.\n *\n * Owns the list, the loading flag, and the local mutations that keep the list\n * consistent after each successful call, so a provider only has to implement\n * four promise-returning methods. Errors are reported through `onError` and\n * re-thrown, leaving the local list untouched on failure.\n */\nexport function useSavedBlocks(\n options: UseSavedBlocksOptions,\n): UseSavedBlocksReturn {\n const { provider } = options;\n\n const savedBlocks = ref<SavedBlock[]>([]);\n const isLoading = ref(false);\n\n const categories = computed(() => {\n const seen = new Set<string>();\n for (const block of savedBlocks.value) {\n const category = block.category?.trim();\n if (category) seen.add(category);\n }\n return [...seen].sort((a, b) => a.localeCompare(b));\n });\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canUpdate = computed(() => typeof provider.update === \"function\");\n const canDelete = computed(() => typeof provider.delete === \"function\");\n\n /** Absent flag means allowed — the flags exist only to forbid. */\n function canUpdateBlock(block: SavedBlock): boolean {\n return canUpdate.value && block.canUpdate !== false;\n }\n\n function canDeleteBlock(block: SavedBlock): boolean {\n return canDelete.value && block.canDelete !== false;\n }\n\n /**\n * The UI hides disabled actions, so reaching one of these means a programmatic\n * caller went around it. Fail loudly rather than silently no-op: a resolved\n * promise would read as \"saved\" to whoever awaited it.\n */\n function refuse(action: string, reason: string): never {\n throw new SdkError(\n `[Templatical] Saved blocks: ${action} is ${reason}. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for a saved block that was created.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n async function load(params?: SavedBlocksListParams): Promise<void> {\n isLoading.value = true;\n try {\n savedBlocks.value = await provider.list(params);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isLoading.value = false;\n }\n }\n\n async function create(\n name: string,\n content: Block[],\n category?: string,\n ): Promise<SavedBlock> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") {\n refuse(\"create\", \"disabled by the provider\");\n }\n try {\n // Omit the key entirely when unset, rather than sending `undefined` —\n // a provider serialising the input to JSON would otherwise be handed an\n // explicit null-ish field it never asked for.\n const created = await providerCreate(\n category ? { name, content, category } : { name, content },\n );\n savedBlocks.value = [created, ...savedBlocks.value];\n notify(() => provider.onCreated?.(created));\n return created;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function update(\n id: string,\n patch: SavedBlockPatch,\n ): Promise<SavedBlock> {\n const { update: providerUpdate } = provider;\n if (typeof providerUpdate !== \"function\") {\n refuse(\"update\", \"disabled by the provider\");\n }\n // An id absent from the local list isn't refused — a headless caller may\n // legitimately patch something it never loaded. Only a loaded entry that\n // explicitly opted out is blocked.\n const local = savedBlocks.value.find((b) => b.id === id);\n if (local && local.canUpdate === false) {\n refuse(\"update\", `not permitted for entry \"${id}\"`);\n }\n try {\n const updated = await providerUpdate(id, patch);\n savedBlocks.value = savedBlocks.value.map((b) =>\n b.id === id ? updated : b,\n );\n notify(() => provider.onUpdated?.(updated));\n return updated;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function remove(id: string): Promise<void> {\n const { delete: providerDelete } = provider;\n if (typeof providerDelete !== \"function\") {\n refuse(\"delete\", \"disabled by the provider\");\n }\n // Captured before the delete resolves: `onDeleted` carries the removed\n // entry itself, and there is nothing left to read once the list is\n // filtered.\n const removed = savedBlocks.value.find((b) => b.id === id) ?? null;\n if (removed && removed.canDelete === false) {\n refuse(\"delete\", `not permitted for entry \"${id}\"`);\n }\n try {\n await providerDelete(id);\n savedBlocks.value = savedBlocks.value.filter((b) => b.id !== id);\n if (removed) {\n notify(() => provider.onDeleted?.(removed));\n }\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n return {\n savedBlocks,\n isLoading,\n categories,\n canCreate,\n canUpdate,\n canDelete,\n canUpdateBlock,\n canDeleteBlock,\n load,\n create,\n update,\n remove,\n };\n}\n","import type {\n SavedBlock,\n SavedBlockInput,\n SavedBlockPatch,\n SavedBlocksListParams,\n SavedBlocksProvider,\n} from \"@templatical/types\";\nimport { generateId } from \"@templatical/types\";\n\nexport interface LocalStorageSavedBlocksOptions {\n /**\n * `localStorage` key holding the serialized array.\n *\n * @default \"templatical:saved-blocks\"\n */\n key?: string;\n}\n\nconst DEFAULT_KEY = \"templatical:saved-blocks\";\n\n/**\n * Browser-local {@link SavedBlocksProvider} backed by `localStorage`.\n *\n * Opt-in: pass it explicitly as `init({ savedBlocks: createLocalStorageSavedBlocksProvider() })`.\n * The editor never falls back to it, so consumers without a provider keep the\n * feature — and its UI — entirely off.\n *\n * Intended for demos, prototypes, and single-device use. Entries live in one\n * browser profile only: they don't sync across devices or users, and clearing\n * site data removes them. Back saved blocks with your own API for anything\n * that needs to outlive a browser profile.\n */\nexport function createLocalStorageSavedBlocksProvider(\n options: LocalStorageSavedBlocksOptions = {},\n): SavedBlocksProvider {\n const storageKey = options.key ?? DEFAULT_KEY;\n\n function getStorage(): Storage {\n // Core targets a neutral platform, so `localStorage` isn't guaranteed —\n // fail with an actionable message rather than a bare ReferenceError.\n if (typeof localStorage === \"undefined\") {\n throw new Error(\n \"[Templatical] createLocalStorageSavedBlocksProvider requires a browser environment with localStorage. Supply your own SavedBlocksProvider for server-side or non-browser use.\",\n );\n }\n return localStorage;\n }\n\n function readAll(): SavedBlock[] {\n const raw = getStorage().getItem(storageKey);\n if (!raw) return [];\n try {\n const parsed: unknown = JSON.parse(raw);\n // Tolerate a corrupted or hand-edited value rather than breaking the\n // editor: treat anything that isn't an array as \"no saved blocks\".\n return Array.isArray(parsed) ? (parsed as SavedBlock[]) : [];\n } catch {\n return [];\n }\n }\n\n function writeAll(blocks: SavedBlock[]): void {\n getStorage().setItem(storageKey, JSON.stringify(blocks));\n }\n\n // Every method is `async` so a synchronous failure (a missing\n // `localStorage`, a quota error from `setItem`) surfaces as a rejected\n // promise rather than a sync throw — callers of a `Promise`-returning\n // contract must be able to rely on `.catch()`.\n return {\n // The editor calls this bare and filters in memory; the params are honored\n // for headless callers that would rather the provider did the work.\n async list(params?: SavedBlocksListParams): Promise<SavedBlock[]> {\n const all = readAll();\n const search = params?.search?.trim().toLowerCase();\n const category = params?.category?.trim();\n return all.filter((b) => {\n if (search && !b.name.toLowerCase().includes(search)) return false;\n if (category && b.category !== category) return false;\n return true;\n });\n },\n\n // All three mutations are enabled: a browser-local store has no notion of\n // permissions, so there is nothing to forbid.\n async create(input: SavedBlockInput): Promise<SavedBlock> {\n const now = new Date().toISOString();\n const created: SavedBlock = {\n id: generateId(),\n name: input.name,\n content: input.content,\n ...(input.category ? { category: input.category } : {}),\n createdAt: now,\n updatedAt: now,\n };\n // Newest-first, matching the order the composable applies locally after\n // a create — so a reload preserves what the user just saw.\n writeAll([created, ...readAll()]);\n return created;\n },\n\n async update(id: string, patch: SavedBlockPatch): Promise<SavedBlock> {\n const all = readAll();\n const index = all.findIndex((b) => b.id === id);\n // Mirrors a REST 404 so provider behavior is consistent across adapters.\n if (index === -1) {\n throw new Error(`[Templatical] Saved block not found: ${id}`);\n }\n const updated: SavedBlock = {\n ...all[index],\n ...patch,\n updatedAt: new Date().toISOString(),\n };\n const next = [...all];\n next[index] = updated;\n writeAll(next);\n return updated;\n },\n\n async delete(id: string): Promise<void> {\n const all = readAll();\n if (!all.some((b) => b.id === id)) {\n throw new Error(`[Templatical] Saved block not found: ${id}`);\n }\n writeAll(all.filter((b) => b.id !== id));\n },\n };\n}\n","import type {\n Template,\n TemplateContent,\n TemplateVersion,\n VersionHistoryListParams,\n VersionHistoryProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport { computed, ref, type ComputedRef, type Ref } from \"vue\";\nimport { notifyHandler } from \"./error-reporting\";\n\nexport interface UseVersionHistoryOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ versionHistory })`,\n * or by Cloud's own adapter — this composable is transport-agnostic and never\n * talks to a network itself.\n */\n provider: VersionHistoryProvider;\n /**\n * Which template's history this is. A getter rather than a value because a\n * session can outlive the template: `initCloud()` constructs the feature at\n * setup and only learns the id once `create()` / `load()` resolves.\n */\n getTemplateId: () => string | null;\n onError?: (error: Error) => void;\n}\n\nexport interface UseVersionHistoryReturn {\n /** The provider's list, in the provider's order. Never re-sorted. */\n versions: Ref<TemplateVersion[]>;\n isLoading: Ref<boolean>;\n isRestoring: Ref<boolean>;\n /**\n * Cursor for the page after the one currently held, or `undefined` when the\n * provider signalled there is no more. The editor loads one page and ignores\n * this; it is here so a headless caller can page without reaching past the\n * composable.\n */\n nextCursor: Ref<string | undefined>;\n /** Whether the provider supplied each mutation at all. */\n canCreate: ComputedRef<boolean>;\n canRestore: ComputedRef<boolean>;\n /** Re-read the list. The editor calls this bare; `params` is for headless callers. */\n load: (params?: VersionHistoryListParams) => Promise<void>;\n /**\n * The version's content **if it is already in hand** — the provider's\n * `content` hint, or a previous `get` this composable cached. `null` means a\n * round-trip is required.\n *\n * Callers that must not block (scrubbing through history swaps the canvas in\n * the same tick) check this first and only await {@link resolveContent} when\n * it comes back null.\n */\n peekContent: (version: TemplateVersion) => TemplateContent | null;\n /**\n * `version.content ?? await provider.get(...)`, cached per version id, so a\n * lazily-loaded version costs one round-trip on its first visit and nothing\n * afterwards.\n */\n resolveContent: (version: TemplateVersion) => Promise<TemplateContent>;\n /** Rejects with an {@link SdkError} when the provider disabled `create`. */\n create: (\n content: TemplateContent,\n meta?: { label?: string },\n ) => Promise<TemplateVersion>;\n /** Rejects with an {@link SdkError} when the provider disabled `restore`. */\n restore: (versionId: string) => Promise<Template>;\n}\n\n/**\n * Reactive state over a {@link VersionHistoryProvider}.\n *\n * Owns the list, the loading flags and the per-version content cache that keeps\n * scrubbing synchronous. Errors are reported through `onError` and re-thrown,\n * leaving the list untouched on failure.\n *\n * It deliberately does **not** create versions of its own accord. The editor\n * never records a version on a save — whoever implements `TemplatesProvider.save`\n * decides that, because they are the side that pays for the storage.\n */\nexport function useVersionHistory(\n options: UseVersionHistoryOptions,\n): UseVersionHistoryReturn {\n const { provider, getTemplateId } = options;\n\n const versions = ref<TemplateVersion[]>([]);\n const isLoading = ref(false);\n const nextCursor = ref<string | undefined>(undefined);\n const isRestoring = ref(false);\n\n /**\n * Content fetched through `get`, keyed by version id. A version that carried\n * a `content` hint never lands here — the hint is read straight off the entry,\n * so a provider that eager-loads pays no second copy.\n */\n const fetched = new Map<string, TemplateContent>();\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canRestore = computed(() => typeof provider.restore === \"function\");\n\n /**\n * The UI hides disabled actions and renders nothing before a template exists,\n * so reaching one of these means a programmatic caller went around it. Fail\n * loudly rather than silently no-op: a resolved promise reads as \"done\".\n */\n function requireTemplateId(action: string): string {\n const templateId = getTemplateId();\n if (!templateId) {\n throw new SdkError(\n `[Templatical] Version history: ${action} needs a template. Call create() or load() first.`,\n );\n }\n return templateId;\n }\n\n function refuse(action: string): never {\n throw new SdkError(\n `[Templatical] Version history: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for a version that was recorded or restored.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n async function load(params?: VersionHistoryListParams): Promise<void> {\n const templateId = requireTemplateId(\"list\");\n isLoading.value = true;\n try {\n const page = await provider.list(templateId, params);\n versions.value = page.versions;\n nextCursor.value = page.nextCursor;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isLoading.value = false;\n }\n }\n\n function peekContent(version: TemplateVersion): TemplateContent | null {\n return version.content ?? fetched.get(version.id) ?? null;\n }\n\n async function resolveContent(\n version: TemplateVersion,\n ): Promise<TemplateContent> {\n const known = peekContent(version);\n if (known) return known;\n\n const templateId = requireTemplateId(\"get\");\n try {\n const content = await provider.get(templateId, version.id);\n fetched.set(version.id, content);\n return content;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function create(\n content: TemplateContent,\n meta?: { label?: string },\n ): Promise<TemplateVersion> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") refuse(\"create\");\n const templateId = requireTemplateId(\"create\");\n try {\n const created = await providerCreate(templateId, content, meta);\n versions.value = [created, ...versions.value];\n notify(() => provider.onCreated?.(created));\n return created;\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n }\n }\n\n async function restore(versionId: string): Promise<Template> {\n const { restore: providerRestore } = provider;\n if (typeof providerRestore !== \"function\") refuse(\"restore\");\n const templateId = requireTemplateId(\"restore\");\n\n let restored: Template;\n isRestoring.value = true;\n try {\n restored = await providerRestore(templateId, versionId);\n } catch (error) {\n options.onError?.(error as Error);\n throw error;\n } finally {\n isRestoring.value = false;\n }\n // Below the `finally` on purpose: `isRestoring` is cleared there, so a\n // handler must not observe the composable still reporting itself\n // mid-restore. Unreachable on failure — the catch rethrows.\n notify(() => provider.onRestored?.(restored));\n return restored;\n }\n\n return {\n nextCursor,\n versions,\n isLoading,\n isRestoring,\n canCreate,\n canRestore,\n load,\n peekContent,\n resolveContent,\n create,\n restore,\n };\n}\n","import type {\n Comment,\n CommentAuthor,\n CommentChange,\n CommentInput,\n CommentPatch,\n CommentsListParams,\n CommentsProvider,\n} from \"@templatical/types\";\nimport { SdkError } from \"@templatical/types\";\nimport {\n computed,\n onScopeDispose,\n ref,\n watch,\n type ComputedRef,\n type Ref,\n} from \"vue\";\nimport { notifyHandler, wrapReportedError } from \"./error-reporting\";\n\nexport interface UseCommentsOptions {\n /**\n * Storage backend. Supplied by the consumer via `init({ comments })`, or by\n * Cloud's own adapter — this composable is transport-agnostic and never talks\n * to a network itself.\n */\n provider: CommentsProvider;\n /**\n * Which template's conversation this is. A getter rather than a value because a\n * session can outlive the template: `initCloud()` constructs the feature at\n * setup and only learns the id once `create()` / `load()` resolves.\n */\n getTemplateId: () => string | null;\n /**\n * Who is commenting, read at call time. `null` means the editor has no\n * identity, and every mutation refuses — an unattributable comment is worse\n * than no comment feature.\n */\n getUser: () => CommentAuthor | null;\n onError?: (error: Error) => void;\n}\n\nexport interface UseCommentsReturn {\n /** Thread roots in the provider's order. Never re-sorted. */\n comments: Ref<Comment[]>;\n isLoading: Ref<boolean>;\n isSubmitting: Ref<boolean>;\n /** Whether the provider supplied each mutation at all. */\n canCreate: ComputedRef<boolean>;\n canUpdate: ComputedRef<boolean>;\n canDelete: ComputedRef<boolean>;\n canResolve: ComputedRef<boolean>;\n /** Roots plus replies. */\n totalCount: ComputedRef<number>;\n /** Unresolved roots — the badge on the trigger. */\n unresolvedCount: ComputedRef<number>;\n /** Comments per anchored block id, roots plus their replies. */\n commentCountByBlock: ComputedRef<Map<string, number>>;\n /** Re-read the list. The editor calls this bare; `params` is for headless callers. */\n load: (params?: CommentsListParams) => Promise<void>;\n /** Rejects with an {@link SdkError} when `create` is disabled or there is no user. */\n create: (input: CommentInput) => Promise<Comment>;\n /** Rejects with an {@link SdkError} when `update` is disabled or there is no user. */\n update: (commentId: string, patch: CommentPatch) => Promise<Comment>;\n /** Rejects with an {@link SdkError} when `delete` is disabled or there is no user. */\n remove: (commentId: string) => Promise<void>;\n /** Rejects with an {@link SdkError} when `setResolved` is disabled or there is no user. */\n setResolved: (commentId: string, resolved: boolean) => Promise<Comment>;\n /** Look one up by id, root or reply. `null` when it isn't loaded. */\n find: (commentId: string) => Comment | null;\n /** Whether this comment was written by the current user. */\n isOwn: (comment: Comment) => boolean;\n /**\n * Apply a change that arrived from {@link CommentsProvider.subscribe}. Public\n * so a consumer driving this headlessly can push their own transport into it.\n */\n applyRemoteCreate: (comment: Comment) => void;\n applyRemoteUpdate: (comment: Comment) => void;\n applyRemoteDelete: (commentId: string, parentId?: string | null) => void;\n}\n\n/**\n * Reactive state over a {@link CommentsProvider}.\n *\n * Owns the thread list, the loading flags, the local mutations that keep the list\n * consistent, and the derived counts the chrome renders. Errors are reported\n * through `onError` and **re-thrown**, leaving the list untouched on failure —\n * the same discipline as `useSavedBlocks` and `useVersionHistory`.\n *\n * Mutations **reject** when the provider withheld them rather than resolving to\n * `null`: a resolved promise reads as \"saved\" to whoever awaited it. Ask through\n * `canCreate` / `canUpdate` / `canDelete` / `canResolve` first — which is what the\n * editor's own UI does, hiding each action rather than disabling it.\n */\nexport function useComments(options: UseCommentsOptions): UseCommentsReturn {\n const { provider, getTemplateId, getUser } = options;\n\n const comments = ref<Comment[]>([]);\n const isLoading = ref(false);\n const isSubmitting = ref(false);\n\n const canCreate = computed(() => typeof provider.create === \"function\");\n const canUpdate = computed(() => typeof provider.update === \"function\");\n const canDelete = computed(() => typeof provider.delete === \"function\");\n const canResolve = computed(() => typeof provider.setResolved === \"function\");\n\n const totalCount = computed(() =>\n comments.value.reduce(\n (sum, thread) => sum + 1 + (thread.replies?.length ?? 0),\n 0,\n ),\n );\n\n const unresolvedCount = computed(\n () => comments.value.filter((thread) => !thread.resolvedAt).length,\n );\n\n const commentCountByBlock = computed(() => {\n const map = new Map<string, number>();\n for (const thread of comments.value) {\n if (!thread.blockId) continue;\n map.set(\n thread.blockId,\n (map.get(thread.blockId) ?? 0) + 1 + (thread.replies?.length ?? 0),\n );\n }\n return map;\n });\n\n /**\n * The UI hides disabled actions and renders nothing before a template exists,\n * so reaching one of these means a programmatic caller went around it. Fail\n * loudly rather than silently no-op.\n */\n function requireTemplateId(action: string): string {\n const templateId = getTemplateId();\n if (!templateId) {\n throw new SdkError(\n `[Templatical] Comments: ${action} needs a template. Call create() or load() first.`,\n );\n }\n return templateId;\n }\n\n function requireUser(action: string): CommentAuthor {\n const user = getUser();\n if (!user) {\n throw new SdkError(\n `[Templatical] Comments: ${action} needs to know who is commenting. Pass init({ user: { id, name } }) — an unattributed comment is not written.`,\n );\n }\n return user;\n }\n\n function refuse(action: string): never {\n throw new SdkError(\n `[Templatical] Comments: ${action} is disabled by the provider. Check the capability before calling — the editor's own UI hides the action.`,\n );\n }\n\n function find(commentId: string): Comment | null {\n for (const thread of comments.value) {\n if (thread.id === commentId) return thread;\n for (const reply of thread.replies ?? []) {\n if (reply.id === commentId) return reply;\n }\n }\n return null;\n }\n\n function isOwn(comment: Comment): boolean {\n const user = getUser();\n return user !== null && comment.author.id === user.id;\n }\n\n function report(error: unknown): never {\n const wrapped = wrapReportedError(error);\n options.onError?.(wrapped);\n throw wrapped;\n }\n\n /**\n * Run a consumer's event handler without letting it fail the operation.\n *\n * A handler that throws must not turn a completed write into a rejected one —\n * the UI would report a failure for a comment that was created.\n */\n function notify(run: () => void): void {\n notifyHandler(options.onError, run);\n }\n\n function replaceAt<T>(list: T[], index: number, next: T): T[] {\n return [...list.slice(0, index), next, ...list.slice(index + 1)];\n }\n\n /**\n * Key-order sensitive: identical fields serialized in a different order\n * compare unequal, so an echo whose transport frame orders keys\n * differently than the mutation response it echoes would not be\n * suppressed. Accepted rather than a defect — not worth a deep-equal\n * dependency for it.\n */\n function sameComment(a: Comment | undefined, b: Comment): boolean {\n return a !== undefined && JSON.stringify(a) === JSON.stringify(b);\n }\n\n /**\n * Insert a comment, replacing an entry with the same id rather than\n * duplicating it, and report whether the list actually changed.\n *\n * The **remote** apply paths (`applyRemoteCreate` / `applyRemoteUpdate`)\n * emit their event only when this returns `true`. A transport's own\n * broadcast can come back to the sender — `CommentsProvider.subscribe`'s\n * contract permits it — and emitting unconditionally fires the handler\n * twice for one comment. The comparison below runs against the **merged**\n * result, never the raw payload: the root branch keeps already-loaded\n * `replies` when an update payload carries none, so comparing the payload\n * directly would report a change for an echo that altered nothing.\n * Deleting the `sameComment` check as a redundant no-op reinstates the\n * double-fire.\n */\n function upsert(comment: Comment): boolean {\n if (comment.parentId) {\n let changed = false;\n const next = comments.value.map((thread) => {\n if (thread.id !== comment.parentId) return thread;\n const replies = thread.replies ?? [];\n const at = replies.findIndex((reply) => reply.id === comment.id);\n if (at !== -1 && sameComment(replies[at], comment)) return thread;\n changed = true;\n return {\n ...thread,\n replies:\n at === -1 ? [...replies, comment] : replaceAt(replies, at, comment),\n };\n });\n // Assigned only when something actually changed: `.map()` always returns\n // a new array, and reassigning `comments.value` for a no-op echo would\n // still invalidate every computed reading it (`commentCountByBlock`\n // returns a new `Map` on each recompute) for nothing.\n if (changed) comments.value = next;\n return changed;\n }\n\n const at = comments.value.findIndex((thread) => thread.id === comment.id);\n if (at === -1) {\n comments.value = [...comments.value, comment];\n return true;\n }\n // A root arriving again keeps the replies already loaded: the update payload\n // for a body edit carries none, and dropping them would empty the thread.\n const next: Comment = {\n ...comment,\n replies: comment.replies ?? comments.value[at].replies,\n };\n if (sameComment(comments.value[at], next)) return false;\n comments.value = replaceAt(comments.value, at, next);\n return true;\n }\n\n function drop(commentId: string, parentId?: string | null): Comment | null {\n const existing = find(commentId);\n // `parentId` from the caller wins so a delete can be applied without the\n // comment being loaded — the subscribe path, on a thread never opened.\n const parent = parentId ?? existing?.parentId ?? null;\n\n if (parent) {\n comments.value = comments.value.map((thread) =>\n thread.id === parent\n ? {\n ...thread,\n replies: (thread.replies ?? []).filter((r) => r.id !== commentId),\n }\n : thread,\n );\n } else {\n comments.value = comments.value.filter((c) => c.id !== commentId);\n }\n return existing;\n }\n\n async function load(params?: CommentsListParams): Promise<void> {\n const templateId = requireTemplateId(\"list\");\n isLoading.value = true;\n try {\n comments.value = await provider.list(templateId, params);\n } catch (error) {\n report(error);\n } finally {\n isLoading.value = false;\n }\n }\n\n async function create(input: CommentInput): Promise<Comment> {\n const { create: providerCreate } = provider;\n if (typeof providerCreate !== \"function\") refuse(\"create\");\n const templateId = requireTemplateId(\"create\");\n requireUser(\"create\");\n isSubmitting.value = true;\n try {\n const created = await providerCreate(templateId, input);\n upsert(created);\n notify(() => provider.onCreated?.(created, { origin: \"local\" }));\n return created;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function update(\n commentId: string,\n patch: CommentPatch,\n ): Promise<Comment> {\n const { update: providerUpdate } = provider;\n if (typeof providerUpdate !== \"function\") refuse(\"update\");\n const templateId = requireTemplateId(\"update\");\n requireUser(\"update\");\n isSubmitting.value = true;\n try {\n const updated = await providerUpdate(templateId, commentId, patch);\n upsert(updated);\n notify(() => provider.onUpdated?.(updated, { origin: \"local\" }));\n return updated;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function remove(commentId: string): Promise<void> {\n const { delete: providerDelete } = provider;\n if (typeof providerDelete !== \"function\") refuse(\"delete\");\n const templateId = requireTemplateId(\"delete\");\n requireUser(\"delete\");\n // Snapshotted before the request: the event carries what was deleted, and\n // there is nothing to read afterwards.\n const existing = find(commentId);\n isSubmitting.value = true;\n try {\n await providerDelete(templateId, commentId);\n drop(commentId);\n if (existing) {\n notify(() => provider.onDeleted?.(existing, { origin: \"local\" }));\n }\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n async function setResolved(\n commentId: string,\n resolved: boolean,\n ): Promise<Comment> {\n const { setResolved: providerSetResolved } = provider;\n if (typeof providerSetResolved !== \"function\") refuse(\"setResolved\");\n const templateId = requireTemplateId(\"setResolved\");\n requireUser(\"setResolved\");\n isSubmitting.value = true;\n try {\n const updated = await providerSetResolved(\n templateId,\n commentId,\n resolved,\n );\n upsert(updated);\n // The stored result decides which event fires, not the requested state: a\n // store may refuse to reopen, and the consumer should hear what happened.\n notify(() =>\n (updated.resolvedAt ? provider.onResolved : provider.onUnresolved)?.(\n updated,\n { origin: \"local\" },\n ),\n );\n return updated;\n } catch (error) {\n report(error);\n } finally {\n isSubmitting.value = false;\n }\n }\n\n function applyRemoteCreate(comment: Comment): void {\n // A reply whose parent thread isn't loaded reports nothing: `upsert`\n // finds no matching thread to attach it to, so the list doesn't change.\n if (upsert(comment)) {\n notify(() => provider.onCreated?.(comment, { origin: \"remote\" }));\n }\n }\n\n function applyRemoteUpdate(comment: Comment): void {\n if (!upsert(comment)) return;\n notify(() =>\n (comment.resolvedAt\n ? provider.onResolved\n : // An unresolve and a body edit are both \"not resolved\"; only a payload\n // that used to be resolved is an unresolve, and the transport doesn't\n // say. `updated` is the honest answer for a plain change.\n provider.onUpdated)?.(comment, { origin: \"remote\" }),\n );\n }\n\n function applyRemoteDelete(\n commentId: string,\n parentId?: string | null,\n ): void {\n const existing = drop(commentId, parentId);\n if (existing) {\n notify(() => provider.onDeleted?.(existing, { origin: \"remote\" }));\n }\n }\n\n return {\n comments,\n isLoading,\n isSubmitting,\n canCreate,\n canUpdate,\n canDelete,\n canResolve,\n totalCount,\n unresolvedCount,\n commentCountByBlock,\n load,\n create,\n update,\n remove,\n setResolved,\n find,\n isOwn,\n applyRemoteCreate,\n applyRemoteUpdate,\n applyRemoteDelete,\n };\n}\n\nexport interface UseCommentListenerOptions {\n comments: UseCommentsReturn;\n provider: CommentsProvider;\n getTemplateId: () => string | null;\n}\n\n/**\n * Wire {@link CommentsProvider.subscribe} into the three `applyRemote*` paths.\n *\n * A no-op when the provider has no `subscribe` — realtime is optional, and\n * comments without it work exactly the same except that a colleague's comment\n * only appears on the next read. Nothing here knows about a transport: Cloud's\n * Pusher channel lives inside `createCloudCommentsProvider`, and an SSE or\n * long-poll implementation is the same three lines on the consumer's side.\n *\n * Re-subscribes when the template id changes, and unsubscribes on scope dispose —\n * so a session that loads a second template does not keep receiving the first\n * one's comments.\n */\nexport function useCommentListener(options: UseCommentListenerOptions): void {\n const { comments, provider, getTemplateId } = options;\n const { subscribe } = provider;\n if (typeof subscribe !== \"function\") return;\n\n let unsubscribe: (() => void) | null = null;\n\n function stop(): void {\n unsubscribe?.();\n unsubscribe = null;\n }\n\n watch(\n () => getTemplateId(),\n (templateId) => {\n stop();\n if (!templateId) return;\n unsubscribe = subscribe(templateId, (change: CommentChange) => {\n switch (change.type) {\n case \"created\":\n comments.applyRemoteCreate(change.comment);\n break;\n case \"updated\":\n comments.applyRemoteUpdate(change.comment);\n break;\n case \"deleted\":\n comments.applyRemoteDelete(change.commentId, change.parentId);\n break;\n }\n });\n },\n { immediate: true },\n );\n\n onScopeDispose(stop);\n}\n"],"mappings":";;;;;;;;;;;;AAQA,SAAgB,kBAAkB,OAAuB;CACvD,OAAO,iBAAiB,QACpB,QACA,IAAI,MAAM,OAAO,KAAK,GAAG,EAAE,OAAO,MAAM,CAAC;AAC/C;;;;;;;;;;;AAYA,SAAgB,cACd,SACA,KACM;CACN,IAAI;EACF,IAAI;CACN,SAAS,OAAO;EACd,UAAU,kBAAkB,KAAK,CAAC;CACpC;AACF;;;ACjBA,SAAS,eAAe,QAA8B;CACpD,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,WAAW,KAAK,OAAO;CAC3B,OAAO;AACT;AAwHA,SAAgB,UAAU,SAA4C;CACpE,MAAM,QAAQ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MAAM,WAAW,KAAK,WAAW,QAAQ;EACzC,IAAI,UACF,aAAa,SAAS,YAAY,UAAU,EAAE,QAAQ,SAAS,CAAC,CAAC;CAErE;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;;;;;;;;;;;AAqBA,SAAgB,mBAAmB,SAA0C;CAC3E,MAAM,EAAE,UAAU,UAAU,kBAAkB;CAC9C,MAAM,EAAE,cAAc;CACtB,IAAI,OAAO,cAAc,YAAY;CAErC,IAAI,cAAmC;CAEvC,SAAS,OAAa;EACpB,cAAc;EACd,cAAc;CAChB;CAEA,cACQ,cAAc,IACnB,eAAe;EACd,KAAK;EACL,IAAI,CAAC,YAAY;EACjB,cAAc,UAAU,aAAa,WAA0B;GAC7D,QAAQ,OAAO,MAAf;IACE,KAAK;KACH,SAAS,kBAAkB,OAAO,OAAO;KACzC;IACF,KAAK;KACH,SAAS,kBAAkB,OAAO,OAAO;KACzC;IACF,KAAK,WACH,SAAS,kBAAkB,OAAO,WAAW,OAAO,QAAQ;GAEhE;EACF,CAAC;CACH,GACA,EAAE,WAAW,KAAK,CACpB;CAEA,eAAe,IAAI;AACrB"}
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@templatical/core",
3
3
  "description": "Framework-agnostic editor logic for Templatical email editor",
4
- "version": "0.28.0",
4
+ "version": "0.29.0",
5
5
  "bugs": "https://github.com/templatical/sdk/issues",
6
6
  "dependencies": {
7
- "@vue/reactivity": "^3.5.41",
8
- "@templatical/types": "0.28.0"
7
+ "@templatical/types": "0.29.0",
8
+ "@vue/reactivity": "^3.5.41"
9
9
  },
10
10
  "devDependencies": {
11
11
  "pusher-js": "^8.6.0",