@templatical/core 0.30.0 → 0.32.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.
- package/dist/cloud/index.d.ts +30 -30
- package/dist/index.d.ts +22 -14
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/cloud/index.d.ts
CHANGED
|
@@ -20,8 +20,8 @@ import { Channel, PresenceChannel } from "pusher-js";
|
|
|
20
20
|
* `404` is treated as fatal deliberately: a refresh URL that does not exist is a
|
|
21
21
|
* misconfiguration, and retrying a typo forever is worse than saying so.
|
|
22
22
|
*/
|
|
23
|
-
declare function isFatalAuthError(error: unknown): boolean;
|
|
24
|
-
declare class AuthManager {
|
|
23
|
+
export declare function isFatalAuthError(error: unknown): boolean;
|
|
24
|
+
export declare class AuthManager {
|
|
25
25
|
private static readonly DEFAULT_BASE_URL;
|
|
26
26
|
private accessToken;
|
|
27
27
|
private expiresAt;
|
|
@@ -51,10 +51,10 @@ declare class AuthManager {
|
|
|
51
51
|
private performRefresh;
|
|
52
52
|
authenticatedFetch(url: string, options?: RequestInit): Promise<Response>;
|
|
53
53
|
}
|
|
54
|
-
declare function createSdkAuthManager(config: SdkAuthConfig, onError?: (error: Error) => void): AuthManager;
|
|
54
|
+
export declare function createSdkAuthManager(config: SdkAuthConfig, onError?: (error: Error) => void): AuthManager;
|
|
55
55
|
//#endregion
|
|
56
56
|
//#region src/cloud/api.d.ts
|
|
57
|
-
declare class ApiClient {
|
|
57
|
+
export declare class ApiClient {
|
|
58
58
|
private readonly authManager;
|
|
59
59
|
constructor(authManager: AuthManager);
|
|
60
60
|
private get projectId();
|
|
@@ -131,8 +131,8 @@ declare class ApiClient {
|
|
|
131
131
|
}
|
|
132
132
|
//#endregion
|
|
133
133
|
//#region src/cloud/url-builder.d.ts
|
|
134
|
-
declare function buildUrl(template: string, params: Record<string, string>): string;
|
|
135
|
-
declare const API_ROUTES: {
|
|
134
|
+
export declare function buildUrl(template: string, params: Record<string, string>): string;
|
|
135
|
+
export declare const API_ROUTES: {
|
|
136
136
|
readonly health: "/api/v1/health";
|
|
137
137
|
readonly "projects.config": "/api/v1/projects/{project}/tenants/{tenant}/config";
|
|
138
138
|
readonly "broadcasting.auth": "/api/v1/projects/{project}/tenants/{tenant}/broadcasting/auth";
|
|
@@ -184,7 +184,7 @@ interface WebSocketConfig {
|
|
|
184
184
|
port: number;
|
|
185
185
|
appKey: string;
|
|
186
186
|
}
|
|
187
|
-
declare function resolveWebSocketConfig(serverConfig: WebSocketServerConfig): WebSocketConfig;
|
|
187
|
+
export declare function resolveWebSocketConfig(serverConfig: WebSocketServerConfig): WebSocketConfig;
|
|
188
188
|
interface PresenceMember {
|
|
189
189
|
id: string;
|
|
190
190
|
name: string;
|
|
@@ -195,7 +195,7 @@ interface WebSocketClientOptions {
|
|
|
195
195
|
config: WebSocketConfig;
|
|
196
196
|
onError?: (error: Error) => void;
|
|
197
197
|
}
|
|
198
|
-
declare class WebSocketClient {
|
|
198
|
+
export declare class WebSocketClient {
|
|
199
199
|
private pusher;
|
|
200
200
|
private readonly authManager;
|
|
201
201
|
private readonly config;
|
|
@@ -211,7 +211,7 @@ declare class WebSocketClient {
|
|
|
211
211
|
}
|
|
212
212
|
//#endregion
|
|
213
213
|
//#region src/cloud/mcp-operation-handler.d.ts
|
|
214
|
-
declare function handleOperation(editor: UseEditorReturn, payload: McpOperationPayload): void;
|
|
214
|
+
export declare function handleOperation(editor: UseEditorReturn, payload: McpOperationPayload): void;
|
|
215
215
|
//#endregion
|
|
216
216
|
//#region src/cloud/ai-chat.d.ts
|
|
217
217
|
interface UseAiChatOptions {
|
|
@@ -236,7 +236,7 @@ interface UseAiChatReturn {
|
|
|
236
236
|
loadSuggestions: (currentContent: TemplateContent, mergeTags: MergeTag[]) => Promise<void>;
|
|
237
237
|
clearChat: () => void;
|
|
238
238
|
}
|
|
239
|
-
declare function useAiChat(options: UseAiChatOptions): UseAiChatReturn;
|
|
239
|
+
export declare function useAiChat(options: UseAiChatOptions): UseAiChatReturn;
|
|
240
240
|
//#endregion
|
|
241
241
|
//#region src/cloud/ai-rewrite.d.ts
|
|
242
242
|
interface UseAiRewriteOptions {
|
|
@@ -255,14 +255,14 @@ interface UseAiRewriteReturn {
|
|
|
255
255
|
redo: () => string | null;
|
|
256
256
|
reset: () => void;
|
|
257
257
|
}
|
|
258
|
-
declare function useAiRewrite(options: UseAiRewriteOptions): UseAiRewriteReturn;
|
|
258
|
+
export declare function useAiRewrite(options: UseAiRewriteOptions): UseAiRewriteReturn;
|
|
259
259
|
//#endregion
|
|
260
260
|
//#region src/cloud/ai-config.d.ts
|
|
261
261
|
interface UseAiConfigReturn {
|
|
262
262
|
isFeatureEnabled: (feature: keyof AiConfig) => boolean;
|
|
263
263
|
hasAnyMenuFeature: ComputedRef<boolean>;
|
|
264
264
|
}
|
|
265
|
-
declare function useAiConfig(config?: AiConfig | false): UseAiConfigReturn;
|
|
265
|
+
export declare function useAiConfig(config?: AiConfig | false): UseAiConfigReturn;
|
|
266
266
|
//#endregion
|
|
267
267
|
//#region src/cloud/template-scoring.d.ts
|
|
268
268
|
interface UseTemplateScoringOptions {
|
|
@@ -281,7 +281,7 @@ interface UseTemplateScoringReturn {
|
|
|
281
281
|
removeFinding: (category: ScoringCategory, findingId: string) => void;
|
|
282
282
|
reset: () => void;
|
|
283
283
|
}
|
|
284
|
-
declare function useTemplateScoring(options: UseTemplateScoringOptions): UseTemplateScoringReturn;
|
|
284
|
+
export declare function useTemplateScoring(options: UseTemplateScoringOptions): UseTemplateScoringReturn;
|
|
285
285
|
//#endregion
|
|
286
286
|
//#region src/cloud/design-reference.d.ts
|
|
287
287
|
interface UseDesignReferenceOptions {
|
|
@@ -301,7 +301,7 @@ interface DesignReferenceInput {
|
|
|
301
301
|
imageUpload?: File;
|
|
302
302
|
pdfUpload?: File;
|
|
303
303
|
}
|
|
304
|
-
declare function useDesignReference(options: UseDesignReferenceOptions): UseDesignReferenceReturn;
|
|
304
|
+
export declare function useDesignReference(options: UseDesignReferenceOptions): UseDesignReferenceReturn;
|
|
305
305
|
//#endregion
|
|
306
306
|
//#region src/cloud/comments-provider.d.ts
|
|
307
307
|
/**
|
|
@@ -355,7 +355,7 @@ interface CreateCloudCommentsProviderOptions {
|
|
|
355
355
|
* is nonetheless echo-safe (`upsert` replaces by id), so a backend without that
|
|
356
356
|
* header is fine too.
|
|
357
357
|
*/
|
|
358
|
-
declare function createCloudCommentsProvider(options: CreateCloudCommentsProviderOptions): CommentsProvider;
|
|
358
|
+
export declare function createCloudCommentsProvider(options: CreateCloudCommentsProviderOptions): CommentsProvider;
|
|
359
359
|
//#endregion
|
|
360
360
|
//#region src/cloud/collaboration.d.ts
|
|
361
361
|
interface UseCollaborationOptions {
|
|
@@ -378,7 +378,7 @@ interface UseCollaborationReturn {
|
|
|
378
378
|
collaborators: Ref<Collaborator[]>;
|
|
379
379
|
lockedBlocks: Ref<Map<string, Collaborator>>;
|
|
380
380
|
}
|
|
381
|
-
declare function useCollaboration(options: UseCollaborationOptions): UseCollaborationReturn & {
|
|
381
|
+
export declare function useCollaboration(options: UseCollaborationOptions): UseCollaborationReturn & {
|
|
382
382
|
_broadcastOperation: (payload: McpOperationPayload) => void;
|
|
383
383
|
_isProcessingRemoteOperation: () => boolean;
|
|
384
384
|
};
|
|
@@ -394,7 +394,7 @@ interface BroadcastTarget {
|
|
|
394
394
|
* Must be applied **before** the history interceptor so the call chain is:
|
|
395
395
|
* history.record() → broadcast + original mutation.
|
|
396
396
|
*/
|
|
397
|
-
declare function useCollaborationBroadcast(editor: Pick<UseEditorReturn, "addBlock" | "updateBlock" | "removeBlock" | "moveBlock" | "updateSettings" | "setContent">, collaboration: BroadcastTarget): void;
|
|
397
|
+
export declare function useCollaborationBroadcast(editor: Pick<UseEditorReturn, "addBlock" | "updateBlock" | "removeBlock" | "moveBlock" | "updateSettings" | "setContent">, collaboration: BroadcastTarget): void;
|
|
398
398
|
//#endregion
|
|
399
399
|
//#region src/cloud/web-socket.d.ts
|
|
400
400
|
interface UseWebSocketOptions {
|
|
@@ -408,7 +408,7 @@ interface UseWebSocketReturn {
|
|
|
408
408
|
disconnect: () => void;
|
|
409
409
|
getSocketId: () => string | null;
|
|
410
410
|
}
|
|
411
|
-
declare function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn;
|
|
411
|
+
export declare function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn;
|
|
412
412
|
//#endregion
|
|
413
413
|
//#region src/cloud/saved-blocks-provider.d.ts
|
|
414
414
|
/**
|
|
@@ -431,7 +431,7 @@ declare function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn;
|
|
|
431
431
|
* `updatedAt`. Until it does, those fields simply arrive absent, which degrades
|
|
432
432
|
* to "no timestamp label, every action allowed" rather than breaking.
|
|
433
433
|
*/
|
|
434
|
-
declare function createCloudSavedBlocksProvider(authManager: AuthManager): SavedBlocksProvider;
|
|
434
|
+
export declare function createCloudSavedBlocksProvider(authManager: AuthManager): SavedBlocksProvider;
|
|
435
435
|
//#endregion
|
|
436
436
|
//#region src/cloud/templates-provider.d.ts
|
|
437
437
|
/**
|
|
@@ -460,7 +460,7 @@ declare function createCloudSavedBlocksProvider(authManager: AuthManager): Saved
|
|
|
460
460
|
* rewrite, scoring and the server-side export, so an id Cloud never issued would
|
|
461
461
|
* degrade all six silently.
|
|
462
462
|
*/
|
|
463
|
-
declare function createCloudTemplatesProvider(authManager: AuthManager): TemplatesProvider;
|
|
463
|
+
export declare function createCloudTemplatesProvider(authManager: AuthManager): TemplatesProvider;
|
|
464
464
|
//#endregion
|
|
465
465
|
//#region src/cloud/render-provider.d.ts
|
|
466
466
|
interface CreateCloudRenderProviderOptions {
|
|
@@ -499,7 +499,7 @@ interface CreateCloudRenderProviderOptions {
|
|
|
499
499
|
* pipeline calls here, so there is no MJML the editor would hand back for
|
|
500
500
|
* compiling.
|
|
501
501
|
*/
|
|
502
|
-
declare function createCloudRenderProvider(options: CreateCloudRenderProviderOptions): RenderProvider;
|
|
502
|
+
export declare function createCloudRenderProvider(options: CreateCloudRenderProviderOptions): RenderProvider;
|
|
503
503
|
//#endregion
|
|
504
504
|
//#region src/cloud/version-history-provider.d.ts
|
|
505
505
|
/**
|
|
@@ -515,7 +515,7 @@ declare function createCloudRenderProvider(options: CreateCloudRenderProviderOpt
|
|
|
515
515
|
* decision on whoever implements `save` — the side that knows the storage cost.
|
|
516
516
|
* `create` here is for a version a person asked for.
|
|
517
517
|
*/
|
|
518
|
-
declare function createCloudVersionHistoryProvider(authManager: AuthManager): VersionHistoryProvider;
|
|
518
|
+
export declare function createCloudVersionHistoryProvider(authManager: AuthManager): VersionHistoryProvider;
|
|
519
519
|
//#endregion
|
|
520
520
|
//#region src/cloud/test-email.d.ts
|
|
521
521
|
/**
|
|
@@ -544,7 +544,7 @@ interface UseTestEmailReturn {
|
|
|
544
544
|
/** The signature accompanying {@link allowedEmails}, or `null` when disabled. */
|
|
545
545
|
getSignature: () => string | null;
|
|
546
546
|
}
|
|
547
|
-
declare function useTestEmail(options: UseTestEmailOptions): UseTestEmailReturn;
|
|
547
|
+
export declare function useTestEmail(options: UseTestEmailOptions): UseTestEmailReturn;
|
|
548
548
|
//#endregion
|
|
549
549
|
//#region src/cloud/test-email-provider.d.ts
|
|
550
550
|
interface CreateCloudTestEmailProviderOptions {
|
|
@@ -578,7 +578,7 @@ interface CreateCloudTestEmailProviderOptions {
|
|
|
578
578
|
* - **It never sets `includeMjml`.** Cloud renders server-side, so the editor
|
|
579
579
|
* should not spend a render pass producing MJML nobody reads.
|
|
580
580
|
*/
|
|
581
|
-
declare function createCloudTestEmailProvider(options: CreateCloudTestEmailProviderOptions): TestEmailProvider;
|
|
581
|
+
export declare function createCloudTestEmailProvider(options: CreateCloudTestEmailProviderOptions): TestEmailProvider;
|
|
582
582
|
//#endregion
|
|
583
583
|
//#region src/cloud/export.d.ts
|
|
584
584
|
/** The fonts half of an export request, as Cloud's endpoint expects it. */
|
|
@@ -599,7 +599,7 @@ interface UseExportReturn {
|
|
|
599
599
|
* Unconditional: gating fonts by entitlement meters no resource Cloud buys, and
|
|
600
600
|
* would only make the paid tier render fewer fonts than the free editor.
|
|
601
601
|
*/
|
|
602
|
-
declare function resolveExportFonts(fonts: FontsConfig | undefined): ExportFontsPayload;
|
|
602
|
+
export declare function resolveExportFonts(fonts: FontsConfig | undefined): ExportFontsPayload;
|
|
603
603
|
/**
|
|
604
604
|
* Cloud's server-side export endpoint, as a plain API wrapper.
|
|
605
605
|
*
|
|
@@ -607,7 +607,7 @@ declare function resolveExportFonts(fonts: FontsConfig | undefined): ExportFonts
|
|
|
607
607
|
* canvas may have moved on — see `createCloudRenderProvider`, which is where that
|
|
608
608
|
* policy lives.
|
|
609
609
|
*/
|
|
610
|
-
declare function useExport(options: UseExportOptions): UseExportReturn;
|
|
610
|
+
export declare function useExport(options: UseExportOptions): UseExportReturn;
|
|
611
611
|
//#endregion
|
|
612
612
|
//#region src/cloud/plan-config.d.ts
|
|
613
613
|
interface UsePlanConfigOptions {
|
|
@@ -621,14 +621,14 @@ interface UsePlanConfigReturn {
|
|
|
621
621
|
features: ComputedRef<PlanFeatures | null>;
|
|
622
622
|
fetchConfig: () => Promise<void>;
|
|
623
623
|
}
|
|
624
|
-
declare function usePlanConfig(options: UsePlanConfigOptions): UsePlanConfigReturn;
|
|
624
|
+
export declare function usePlanConfig(options: UsePlanConfigOptions): UsePlanConfigReturn;
|
|
625
625
|
//#endregion
|
|
626
626
|
//#region src/cloud/health-check.d.ts
|
|
627
627
|
interface HealthCheckOptions {
|
|
628
628
|
authManager?: AuthManager;
|
|
629
629
|
baseUrl?: string;
|
|
630
630
|
}
|
|
631
|
-
declare function performHealthCheck(options?: HealthCheckOptions): Promise<HealthCheckResult>;
|
|
631
|
+
export declare function performHealthCheck(options?: HealthCheckOptions): Promise<HealthCheckResult>;
|
|
632
632
|
//#endregion
|
|
633
633
|
//#region src/cloud/mcp-listener.d.ts
|
|
634
634
|
interface UseMcpListenerOptions {
|
|
@@ -636,7 +636,7 @@ interface UseMcpListenerOptions {
|
|
|
636
636
|
channel: Ref<PresenceChannel | null>;
|
|
637
637
|
onOperation?: (payload: McpOperationPayload) => void;
|
|
638
638
|
}
|
|
639
|
-
declare function useMcpListener(options: UseMcpListenerOptions): void;
|
|
639
|
+
export declare function useMcpListener(options: UseMcpListenerOptions): void;
|
|
640
640
|
//#endregion
|
|
641
|
-
export {
|
|
641
|
+
export type { AuthConfig, AuthRequestOptions, CreateCloudCommentsProviderOptions, CreateCloudRenderProviderOptions, CreateCloudTestEmailProviderOptions, DesignReferenceInput, ExportFontsPayload, PresenceMember, RealtimeChannel, SdkAuthConfig, TestEmailConfig, UseAiChatOptions, UseAiChatReturn, UseAiConfigReturn, UseAiRewriteOptions, UseAiRewriteReturn, UseCollaborationOptions, UseCollaborationReturn, UseDesignReferenceOptions, UseDesignReferenceReturn, UseExportOptions, UseExportReturn, UseMcpListenerOptions, UsePlanConfigOptions, UsePlanConfigReturn, UseTemplateScoringOptions, UseTemplateScoringReturn, UseTestEmailOptions, UseTestEmailReturn, UseWebSocketOptions, UseWebSocketReturn, UserConfig, WebSocketClientOptions, WebSocketConfig };
|
|
642
642
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ interface UseHistoryReturn {
|
|
|
20
20
|
clear: () => void;
|
|
21
21
|
destroy: () => void;
|
|
22
22
|
}
|
|
23
|
-
declare function useHistory(options: UseHistoryOptions): UseHistoryReturn;
|
|
23
|
+
export declare function useHistory(options: UseHistoryOptions): UseHistoryReturn;
|
|
24
24
|
//#endregion
|
|
25
25
|
//#region src/block-actions.d.ts
|
|
26
26
|
interface UseBlockActionsOptions {
|
|
@@ -35,7 +35,15 @@ interface UseBlockActionsOptions {
|
|
|
35
35
|
columnIndex?: number;
|
|
36
36
|
index: number;
|
|
37
37
|
} | null;
|
|
38
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Defaults merged onto every block `createAndAddBlock` creates.
|
|
40
|
+
*
|
|
41
|
+
* A **getter** is re-read on each insert; a plain object is captured once.
|
|
42
|
+
* The editor passes a getter because half of these defaults track the
|
|
43
|
+
* template's own `settings.locale`, which the author can change mid-session
|
|
44
|
+
* — a snapshot would pin every later insert to the value at mount.
|
|
45
|
+
*/
|
|
46
|
+
blockDefaults?: BlockDefaults | (() => BlockDefaults);
|
|
39
47
|
}
|
|
40
48
|
interface UseBlockActionsReturn {
|
|
41
49
|
createAndAddBlock: (type: BlockType, targetSectionId?: string, columnIndex?: number) => Block;
|
|
@@ -43,7 +51,7 @@ interface UseBlockActionsReturn {
|
|
|
43
51
|
deleteBlock: (blockId: string) => void;
|
|
44
52
|
updateBlockProperty: <K extends keyof Block>(blockId: string, key: K, value: Block[K]) => void;
|
|
45
53
|
}
|
|
46
|
-
declare function useBlockActions(options: UseBlockActionsOptions): UseBlockActionsReturn;
|
|
54
|
+
export declare function useBlockActions(options: UseBlockActionsOptions): UseBlockActionsReturn;
|
|
47
55
|
//#endregion
|
|
48
56
|
//#region src/auto-save.d.ts
|
|
49
57
|
interface UseAutoSaveOptions {
|
|
@@ -74,8 +82,8 @@ interface UseAutoSaveReturn {
|
|
|
74
82
|
* rather than declaring its own — a second copy for one setting drifts silently,
|
|
75
83
|
* since nothing links the two.
|
|
76
84
|
*/
|
|
77
|
-
declare const DEFAULT_AUTO_SAVE_DEBOUNCE_MS = 2000;
|
|
78
|
-
declare function useAutoSave(options: UseAutoSaveOptions): UseAutoSaveReturn;
|
|
85
|
+
export declare const DEFAULT_AUTO_SAVE_DEBOUNCE_MS = 2000;
|
|
86
|
+
export declare function useAutoSave(options: UseAutoSaveOptions): UseAutoSaveReturn;
|
|
79
87
|
//#endregion
|
|
80
88
|
//#region src/condition-preview.d.ts
|
|
81
89
|
interface UseConditionPreviewReturn {
|
|
@@ -95,10 +103,10 @@ interface ConditionPreviewEditor {
|
|
|
95
103
|
};
|
|
96
104
|
selectBlock: (blockId: string | null) => void;
|
|
97
105
|
}
|
|
98
|
-
declare function useConditionPreview(editor: ConditionPreviewEditor): UseConditionPreviewReturn;
|
|
106
|
+
export declare function useConditionPreview(editor: ConditionPreviewEditor): UseConditionPreviewReturn;
|
|
99
107
|
//#endregion
|
|
100
108
|
//#region src/data-source-fetch.d.ts
|
|
101
|
-
declare function useDataSourceFetch(options: {
|
|
109
|
+
export declare function useDataSourceFetch(options: {
|
|
102
110
|
definition: ComputedRef<CustomBlockDefinition | undefined>;
|
|
103
111
|
block: ComputedRef<CustomBlock>;
|
|
104
112
|
onUpdate: (fieldValues: Record<string, unknown>, fetched: boolean) => void;
|
|
@@ -131,7 +139,7 @@ interface HistoryInterceptorEditor {
|
|
|
131
139
|
* Must be applied **after** any collaboration broadcast wrapping so the
|
|
132
140
|
* call chain is: history.record() → broadcast → original mutation.
|
|
133
141
|
*/
|
|
134
|
-
declare function useHistoryInterceptor(editor: HistoryInterceptorEditor, history: UseHistoryReturn): void;
|
|
142
|
+
export declare function useHistoryInterceptor(editor: HistoryInterceptorEditor, history: UseHistoryReturn): void;
|
|
135
143
|
//#endregion
|
|
136
144
|
//#region src/saved-blocks.d.ts
|
|
137
145
|
interface UseSavedBlocksOptions {
|
|
@@ -198,7 +206,7 @@ interface UseSavedBlocksReturn {
|
|
|
198
206
|
* four promise-returning methods. Errors are reported through `onError` and
|
|
199
207
|
* re-thrown, leaving the local list untouched on failure.
|
|
200
208
|
*/
|
|
201
|
-
declare function useSavedBlocks(options: UseSavedBlocksOptions): UseSavedBlocksReturn;
|
|
209
|
+
export declare function useSavedBlocks(options: UseSavedBlocksOptions): UseSavedBlocksReturn;
|
|
202
210
|
//#endregion
|
|
203
211
|
//#region src/saved-blocks-local.d.ts
|
|
204
212
|
interface LocalStorageSavedBlocksOptions {
|
|
@@ -221,7 +229,7 @@ interface LocalStorageSavedBlocksOptions {
|
|
|
221
229
|
* site data removes them. Back saved blocks with your own API for anything
|
|
222
230
|
* that needs to outlive a browser profile.
|
|
223
231
|
*/
|
|
224
|
-
declare function createLocalStorageSavedBlocksProvider(options?: LocalStorageSavedBlocksOptions): SavedBlocksProvider;
|
|
232
|
+
export declare function createLocalStorageSavedBlocksProvider(options?: LocalStorageSavedBlocksOptions): SavedBlocksProvider;
|
|
225
233
|
//#endregion
|
|
226
234
|
//#region src/version-history.d.ts
|
|
227
235
|
interface UseVersionHistoryOptions {
|
|
@@ -290,7 +298,7 @@ interface UseVersionHistoryReturn {
|
|
|
290
298
|
* never records a version on a save — whoever implements `TemplatesProvider.save`
|
|
291
299
|
* decides that, because they are the side that pays for the storage.
|
|
292
300
|
*/
|
|
293
|
-
declare function useVersionHistory(options: UseVersionHistoryOptions): UseVersionHistoryReturn;
|
|
301
|
+
export declare function useVersionHistory(options: UseVersionHistoryOptions): UseVersionHistoryReturn;
|
|
294
302
|
//#endregion
|
|
295
303
|
//#region src/comments.d.ts
|
|
296
304
|
interface UseCommentsOptions {
|
|
@@ -365,7 +373,7 @@ interface UseCommentsReturn {
|
|
|
365
373
|
* `canCreate` / `canUpdate` / `canDelete` / `canResolve` first — which is what the
|
|
366
374
|
* editor's own UI does, hiding each action rather than disabling it.
|
|
367
375
|
*/
|
|
368
|
-
declare function useComments(options: UseCommentsOptions): UseCommentsReturn;
|
|
376
|
+
export declare function useComments(options: UseCommentsOptions): UseCommentsReturn;
|
|
369
377
|
interface UseCommentListenerOptions {
|
|
370
378
|
comments: UseCommentsReturn;
|
|
371
379
|
provider: CommentsProvider;
|
|
@@ -384,7 +392,7 @@ interface UseCommentListenerOptions {
|
|
|
384
392
|
* so a session that loads a second template does not keep receiving the first
|
|
385
393
|
* one's comments.
|
|
386
394
|
*/
|
|
387
|
-
declare function useCommentListener(options: UseCommentListenerOptions): void;
|
|
395
|
+
export declare function useCommentListener(options: UseCommentListenerOptions): void;
|
|
388
396
|
//#endregion
|
|
389
|
-
export {
|
|
397
|
+
export { type EditorState, type LocalStorageSavedBlocksOptions, type UseAutoSaveOptions, type UseAutoSaveReturn, type UseBlockActionsOptions, type UseBlockActionsReturn, type UseCommentListenerOptions, type UseCommentsOptions, type UseCommentsReturn, type UseConditionPreviewReturn, type UseEditorOptions, type UseEditorReturn, type UseHistoryOptions, type UseHistoryReturn, type UseSavedBlocksOptions, type UseSavedBlocksReturn, type UseVersionHistoryOptions, type UseVersionHistoryReturn, useEditor };
|
|
390
398
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -466,7 +466,8 @@ function regenerateNestedIds(block) {
|
|
|
466
466
|
function useBlockActions(options) {
|
|
467
467
|
const { addBlock, removeBlock, updateBlock, selectBlock, findBlockLocation } = options;
|
|
468
468
|
function createAndAddBlock(type, targetSectionId, columnIndex) {
|
|
469
|
-
const
|
|
469
|
+
const defaults = typeof options.blockDefaults === "function" ? options.blockDefaults() : options.blockDefaults;
|
|
470
|
+
const block = createBlock(type, defaults);
|
|
470
471
|
addBlock(block, targetSectionId, columnIndex);
|
|
471
472
|
selectBlock(block.id);
|
|
472
473
|
return block;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;CA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AAS,UAAA,GAAa,SAAS,EAAE,QAAQ,SAAS,CAAC,CACzD;CACF;CAEA,SAAS,kBACP,WACA,UACM;EACN,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"}
|
|
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 /**\n * Defaults merged onto every block `createAndAddBlock` creates.\n *\n * A **getter** is re-read on each insert; a plain object is captured once.\n * The editor passes a getter because half of these defaults track the\n * template's own `settings.locale`, which the author can change mid-session\n * — a snapshot would pin every later insert to the value at mount.\n */\n blockDefaults?: 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 defaults =\n typeof options.blockDefaults === \"function\"\n ? options.blockDefaults()\n : options.blockDefaults;\n const block = createBlock(type, defaults);\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,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,SAAS,QAAc;EACrB,MAAM,UAAU;EAChB;CACF;CAEA,MAAM,UAAU,SAAS;EACvB,WAAW,MAAM;EACjB,MAAM,UAA2B;GAC/B,MAAM,UAAU;GAChB,MAAM;EACR;CACF,CAAC;CAED,MAAM,gBAAgB,eAAe;EACnC,IAAI,CAAC,MAAM,iBAAiB,OAAO;EACnC,OAAO,cAAc,MAAM,QAAQ,QAAQ,MAAM,eAAe;CAClE,CAAC;CAED,SAAS,cAAc,QAAiB,IAA0B;EAChE,KAAK,MAAM,SAAS,QAAQ;GAC1B,IAAI,MAAM,OAAO,IAAI,OAAO;GAC5B,IAAI,MAAM,SAAS,WACjB,KAAK,MAAM,UAAU,MAAM,UAAU;IACnC,MAAM,QAAQ,cAAc,QAAQ,EAAE;IACtC,IAAI,O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kB,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,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@templatical/core",
|
|
3
3
|
"description": "Framework-agnostic editor logic for Templatical email editor",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.32.0",
|
|
5
5
|
"bugs": "https://github.com/templatical/sdk/issues",
|
|
6
6
|
"dependencies": {
|
|
7
|
-
"@templatical/types": "0.
|
|
7
|
+
"@templatical/types": "0.32.0",
|
|
8
8
|
"@vue/reactivity": "^3.5.42"
|
|
9
9
|
},
|
|
10
10
|
"devDependencies": {
|
|
11
11
|
"pusher-js": "^8.6.0",
|
|
12
12
|
"typescript": "^6.0.3",
|
|
13
|
-
"vitest": "^
|
|
13
|
+
"vitest": "^5.0.0",
|
|
14
14
|
"vue": "^3.5.42"
|
|
15
15
|
},
|
|
16
16
|
"exports": {
|