@widgetic/editor 4.1.18 → 4.1.20

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.
Files changed (94) hide show
  1. package/dist/components/WidgetPreview.svelte +77 -14
  2. package/dist/components/editors/CompositionEditorApp.svelte +71 -35
  3. package/dist/components/editors/CompositionEditorApp.svelte.d.ts +3 -1
  4. package/dist/components/editors/ContentTabBulkDrop.svelte +268 -0
  5. package/dist/components/editors/ContentTabBulkDrop.svelte.d.ts +37 -0
  6. package/dist/components/editors/EmbedAssistantPanel.svelte +303 -0
  7. package/dist/components/editors/EmbedAssistantPanel.svelte.d.ts +29 -0
  8. package/dist/components/editors/EmbedEditor.svelte +221 -15
  9. package/dist/components/editors/EmbedEditor.svelte.d.ts +31 -3
  10. package/dist/components/editors/PropsEditor.svelte +223 -30
  11. package/dist/components/editors/PropsEditor.svelte.d.ts +11 -0
  12. package/dist/components/editors/propsEditorContentStateFlatten.d.ts +12 -0
  13. package/dist/components/editors/propsEditorContentStateFlatten.js +40 -0
  14. package/dist/components/ic/BrowserInputController.svelte +184 -21
  15. package/dist/components/ic/BrowserInputController.svelte.d.ts +2 -0
  16. package/dist/components/ic/CheckboxInputController.svelte +11 -0
  17. package/dist/components/ic/ColorPickerInputController.svelte +2 -1
  18. package/dist/components/ic/DatePickerInputController.svelte +5 -3
  19. package/dist/components/ic/FontInputController.svelte +9 -4
  20. package/dist/components/ic/InputControllerHeader.svelte +4 -3
  21. package/dist/components/ic/KnowledgeDocumentsInputController.svelte +13 -0
  22. package/dist/components/ic/NumberControls.svelte +140 -17
  23. package/dist/components/ic/RadioGroupInputController.svelte +11 -0
  24. package/dist/components/ic/RangeCalendarInputController.svelte +38 -13
  25. package/dist/components/ic/TextAreaInputController.svelte +593 -321
  26. package/dist/components/ic/TextAreaPreviewInputController.svelte +46 -58
  27. package/dist/components/ic/VectorInputController.svelte +0 -1
  28. package/dist/components/ic/numberControlsValueArea.d.ts +29 -0
  29. package/dist/components/ic/numberControlsValueArea.js +51 -0
  30. package/dist/components/ic/optionGroupCardPointerDown.d.ts +9 -0
  31. package/dist/components/ic/optionGroupCardPointerDown.js +20 -0
  32. package/dist/components/ic/shared/EditorFileBrowserOverlay.svelte +48 -6
  33. package/dist/components/ic/shared/EditorFileBrowserOverlay.svelte.d.ts +4 -1
  34. package/dist/components/ic/shared/EditorSelectedFilePreviewOverlay.svelte +34 -0
  35. package/dist/components/ic/shared/EditorSelectedFilePreviewOverlay.svelte.d.ts +24 -0
  36. package/dist/components/ic/shared/fileBrowserOverlayEscape.d.ts +29 -0
  37. package/dist/components/ic/shared/fileBrowserOverlayEscape.js +21 -0
  38. package/dist/composition/compositionApi.d.ts +16 -0
  39. package/dist/composition/compositionApi.js +16 -1
  40. package/dist/composition/compositionEditorController.d.ts +46 -0
  41. package/dist/composition/compositionEditorController.js +277 -5
  42. package/dist/composition/compositionEditorSchemaCache.d.ts +35 -0
  43. package/dist/composition/compositionEditorSchemaCache.js +82 -0
  44. package/dist/contentBulkDrop/applyContentPlan.d.ts +18 -0
  45. package/dist/contentBulkDrop/applyContentPlan.js +55 -0
  46. package/dist/contentBulkDrop/bulkDropSummary.d.ts +4 -0
  47. package/dist/contentBulkDrop/bulkDropSummary.js +12 -0
  48. package/dist/contentBulkDrop/dragIntent.d.ts +7 -0
  49. package/dist/contentBulkDrop/dragIntent.js +24 -0
  50. package/dist/contentBulkDrop/filterDropFiles.d.ts +2 -0
  51. package/dist/contentBulkDrop/filterDropFiles.js +21 -0
  52. package/dist/contentBulkDrop/formatFileSize.d.ts +2 -0
  53. package/dist/contentBulkDrop/formatFileSize.js +13 -0
  54. package/dist/contentBulkDrop/types.d.ts +34 -0
  55. package/dist/contentBulkDrop/types.js +1 -0
  56. package/dist/contentBulkDrop/uploadQueue.d.ts +41 -0
  57. package/dist/contentBulkDrop/uploadQueue.js +114 -0
  58. package/dist/drafts/compositionDraft.d.ts +65 -0
  59. package/dist/drafts/compositionDraft.js +136 -0
  60. package/dist/drafts/compositionEditorViewState.d.ts +9 -0
  61. package/dist/drafts/compositionEditorViewState.js +33 -0
  62. package/dist/drafts/draftJournal.d.ts +59 -0
  63. package/dist/drafts/draftJournal.js +261 -0
  64. package/dist/embed/__fixtures__/gatewayGeneratedEmbedCodes.json +25 -0
  65. package/dist/embed/__fixtures__/generatedEmbedCodes.json +320 -0
  66. package/dist/embed/embedSchema.json +409 -0
  67. package/dist/embed/parseCompositionEmbedCode.d.ts +21 -0
  68. package/dist/embed/parseCompositionEmbedCode.js +379 -0
  69. package/dist/embedAssistant/embedAssistantEvents.d.ts +22 -0
  70. package/dist/embedAssistant/embedAssistantEvents.js +39 -0
  71. package/dist/embedAssistant/embedAssistantStream.d.ts +30 -0
  72. package/dist/embedAssistant/embedAssistantStream.js +125 -0
  73. package/dist/embedAssistant/highlightTiming.d.ts +1 -0
  74. package/dist/embedAssistant/highlightTiming.js +6 -0
  75. package/dist/embedAssistant/types.d.ts +27 -0
  76. package/dist/embedAssistant/types.js +1 -0
  77. package/dist/i18n/labels.js +8 -4
  78. package/dist/i18n/language.d.ts +38 -2
  79. package/dist/i18n/messages.d.ts +38 -1
  80. package/dist/i18n/messages.js +40 -1
  81. package/dist/i18n/translate.d.ts +1 -1
  82. package/dist/index.d.ts +3 -1
  83. package/dist/index.js +2 -0
  84. package/dist/utils/FontManager.d.ts +2 -0
  85. package/dist/utils/FontManager.js +16 -1
  86. package/dist/utils/isEditableEventTarget.d.ts +5 -0
  87. package/dist/utils/isEditableEventTarget.js +25 -0
  88. package/dist/utils/linkUrlValidation.d.ts +17 -0
  89. package/dist/utils/linkUrlValidation.js +120 -0
  90. package/dist/utils/mediaFileValue.d.ts +12 -0
  91. package/dist/utils/mediaFileValue.js +24 -0
  92. package/dist/utils/placeRichTextCaretAtDocumentEnd.d.ts +11 -0
  93. package/dist/utils/placeRichTextCaretAtDocumentEnd.js +26 -0
  94. package/package.json +7 -7
@@ -44,6 +44,14 @@ import type { Translate } from '@widgetic/design-system/i18n';
44
44
  import type { EditorMessageKey } from '../i18n/messages.js';
45
45
  import type { CompositionApi } from './compositionApi.js';
46
46
  import { type JsonRecord } from './compositionHelpers.js';
47
+ import { type CompositionEditorShellStore } from './compositionEditorSchemaCache.js';
48
+ import { type DraftJournal, type DraftJournalOptions } from '../drafts/draftJournal.js';
49
+ import { type CompositionDraftPayload } from '../drafts/compositionDraft.js';
50
+ /** Called when a local draft is applied on top of the server copy after load. */
51
+ export interface DraftRestoredInfo {
52
+ key: string;
53
+ savedAtMs: number;
54
+ }
47
55
  /** Time to wait after the last edit before saving by itself. */
48
56
  export declare const DEFAULT_AUTOSAVE_DELAY_MS = 2500;
49
57
  /** How long to wait before trying an autosave again after it failed for a reason that may pass: first, second, third time. */
@@ -210,6 +218,22 @@ export interface CompositionEditorOptions {
210
218
  * with the composition (the partner owns embed size elsewhere).
211
219
  */
212
220
  lockPreviewSize?: boolean;
221
+ /** Locale for schema-cache keys and shell restore (default `en`). */
222
+ locale?: string;
223
+ /** Cache owner id; falls back to `@widgetic/cache-layer` `getCacheOwner()`. */
224
+ cacheOwnerId?: string | null;
225
+ /**
226
+ * Where the schemas and values of the last load are kept, to be shown at once the next time this composition is
227
+ * opened (the answer of the network replaces them). Without it: the Dexie cache of the cache owner, and no cache
228
+ * at all while there is no owner. `null` turns the cache off.
229
+ */
230
+ shellStore?: CompositionEditorShellStore | null;
231
+ /** When a crash/refresh draft is applied after load (host may show a short toast). */
232
+ onDraftRestored?: (info: DraftRestoredInfo) => void;
233
+ /** When `null`, draft persistence is off. Default: journal backed by `localStorage` in the browser. */
234
+ draftJournal?: DraftJournal<CompositionDraftPayload> | null;
235
+ /** Options for the default journal when `draftJournal` is not passed. */
236
+ draftJournalOptions?: DraftJournalOptions;
213
237
  }
214
238
  /** What went wrong, from whatever was thrown. */
215
239
  export declare function describeFailure(error: unknown): EditorFailure;
@@ -255,6 +279,12 @@ export declare class CompositionEditorController {
255
279
  private loadPromise;
256
280
  private savePromise;
257
281
  private disposed;
282
+ private readonly draftJournal;
283
+ private readonly onDraftRestored?;
284
+ private draftBaseRevision;
285
+ private lastJournaledPayload;
286
+ private leaveFlushDisposer;
287
+ private leaveSaveIdempotencyKey;
258
288
  constructor(options: CompositionEditorOptions);
259
289
  /** The state now. It is never changed in place: a change makes a new object. */
260
290
  getState(): CompositionEditorState;
@@ -264,6 +294,17 @@ export declare class CompositionEditorController {
264
294
  onEvent(listener: (event: CompositionEditorEvent) => void): () => void;
265
295
  /** Loads the composition, its preview address and its schemas. Asking again while it loads waits for the same load. */
266
296
  load(): Promise<void>;
297
+ private cacheLocale;
298
+ /** The store the last load is kept in: the one the host passed, else the cache owner's Dexie cache (none without an owner). */
299
+ private shellStore;
300
+ /**
301
+ * Shows what the last load of this composition kept (its schemas and values) while the new load is on its way, so
302
+ * the editor is there at once instead of a loading state. For a first paint only: with schemas on the screen already
303
+ * (a reload after a conflict) the screen keeps what it has. And only while the network has not answered: its answer
304
+ * is the fresher one, however late the cache is read. Returns whether it painted.
305
+ */
306
+ private trySeedFromSchemaCache;
307
+ private persistSchemaCacheFromState;
267
308
  private runLoad;
268
309
  private failLoad;
269
310
  /**
@@ -368,6 +409,11 @@ export declare class CompositionEditorController {
368
409
  private clearAutosaveTimer;
369
410
  /** Stops everything: timers, requests on their way, and any answer that arrives later. Unsaved edits are lost; `flush()` first to keep them. */
370
411
  dispose(): void;
412
+ private journalDraftFromState;
413
+ private flushDraftJournalNow;
414
+ private tryKeepaliveSaveOnLeave;
415
+ private tryApplyDraftAfterLoad;
416
+ private noteDraftAfterSuccessfulSave;
371
417
  /** Makes the next state out of the changes, tells the watchers, and says when the unsaved flag turned over. */
372
418
  private patch;
373
419
  private emit;
@@ -42,6 +42,10 @@
42
42
  */
43
43
  import { translateEnglish } from '../i18n/translate.js';
44
44
  import { buildPropsEditorContentSchema, compositionContentVersion, compositionWidgetId, contentItemsToEditorValueMap, ensureSubtitleFontInDesignSchema, extractContentItemsFromCompositionRaw, extractContentValuesFromCompositionRaw, flattenContentItemsForPreview, flattenDesignValuesForPreview, getCompositionEmbedSettings, mergeContentItemsWithSchema, mergeMissingContentValues, normalizeContentSchemaFromApiResponse, normalizeDesignSchemaFromApiResponse, parseEmbedDimension, readContentVersion, seedMissingFontFaces } from './compositionHelpers.js';
45
+ import { createCompositionEditorShellStore } from './compositionEditorSchemaCache.js';
46
+ import { createDraftJournal } from '../drafts/draftJournal.js';
47
+ import { COMPOSITION_DRAFT_NAMESPACE, applyDraftRestoreRule, draftPayloadFromEditorState, payloadsEqual, serverBaseRevision } from '../drafts/compositionDraft.js';
48
+ const KEEPALIVE_SAVE_MAX_BYTES = 60 * 1024;
45
49
  /** Time to wait after the last edit before saving by itself. */
46
50
  export const DEFAULT_AUTOSAVE_DELAY_MS = 2500;
47
51
  /** How long to wait before trying an autosave again after it failed for a reason that may pass: first, second, third time. */
@@ -213,6 +217,12 @@ export class CompositionEditorController {
213
217
  loadPromise = null;
214
218
  savePromise = null;
215
219
  disposed = false;
220
+ draftJournal;
221
+ onDraftRestored;
222
+ draftBaseRevision = null;
223
+ lastJournaledPayload = null;
224
+ leaveFlushDisposer = null;
225
+ leaveSaveIdempotencyKey = null;
216
226
  constructor(options) {
217
227
  if (typeof options?.compositionId !== 'string' || options.compositionId.trim() === '') {
218
228
  throw new TypeError('CompositionEditorController needs a composition id');
@@ -229,6 +239,19 @@ export class CompositionEditorController {
229
239
  this.translate = options.translate ?? translateEnglish;
230
240
  this.autosaveDelayMs = options.autosaveDelayMs ?? DEFAULT_AUTOSAVE_DELAY_MS;
231
241
  this.autosaveRetryDelaysMs = options.autosaveRetryDelaysMs ?? DEFAULT_AUTOSAVE_RETRY_DELAYS_MS;
242
+ this.onDraftRestored = options.onDraftRestored;
243
+ if (options.draftJournal !== undefined) {
244
+ this.draftJournal = options.draftJournal;
245
+ }
246
+ else {
247
+ this.draftJournal = createDraftJournal(COMPOSITION_DRAFT_NAMESPACE, options.draftJournalOptions ?? {});
248
+ }
249
+ if (this.draftJournal) {
250
+ this.leaveFlushDisposer = this.draftJournal.installFlushOnLeave(() => {
251
+ this.flushDraftJournalNow();
252
+ this.tryKeepaliveSaveOnLeave();
253
+ });
254
+ }
232
255
  this.state = {
233
256
  phase: 'idle',
234
257
  compositionId: options.compositionId,
@@ -295,6 +318,97 @@ export class CompositionEditorController {
295
318
  this.loadPromise = running;
296
319
  return running;
297
320
  }
321
+ cacheLocale() {
322
+ return (this.options.locale ?? 'en').trim() || 'en';
323
+ }
324
+ /** The store the last load is kept in: the one the host passed, else the cache owner's Dexie cache (none without an owner). */
325
+ shellStore() {
326
+ if (this.options.shellStore !== undefined)
327
+ return this.options.shellStore;
328
+ return createCompositionEditorShellStore(this.options.cacheOwnerId);
329
+ }
330
+ /**
331
+ * Shows what the last load of this composition kept (its schemas and values) while the new load is on its way, so
332
+ * the editor is there at once instead of a loading state. For a first paint only: with schemas on the screen already
333
+ * (a reload after a conflict) the screen keeps what it has. And only while the network has not answered: its answer
334
+ * is the fresher one, however late the cache is read. Returns whether it painted.
335
+ */
336
+ async trySeedFromSchemaCache(hasNetworkAnswered) {
337
+ if (this.state.designSchema || this.state.contentSchema)
338
+ return false;
339
+ const store = this.shellStore();
340
+ if (!store)
341
+ return false;
342
+ try {
343
+ const cached = await store.read(this.options.compositionId, this.cacheLocale());
344
+ if (!cached || hasNetworkAnswered() || this.disposed)
345
+ return false;
346
+ const designSchema = cached.designSchema
347
+ ? ensureSubtitleFontInDesignSchema(normalizeDesignSchemaFromApiResponse(cached.designSchema), this.translate('editor.schema.subtitleFont'))
348
+ : null;
349
+ const contentSchema = cached.contentSchema
350
+ ? normalizeContentSchemaFromApiResponse(cached.contentSchema)
351
+ : null;
352
+ if (!designSchema && !contentSchema)
353
+ return false;
354
+ const contentItems = mergeContentItemsWithSchema(Array.isArray(cached.contentItems) ? cached.contentItems : [], schemaContentItems(contentSchema));
355
+ this.patch({
356
+ phase: 'ready',
357
+ name: cached.name,
358
+ widgetId: cached.widgetId || this.state.widgetId,
359
+ preview: cached.previewUrl
360
+ ? {
361
+ previewUrl: cached.previewUrl,
362
+ widgetId: cached.widgetId,
363
+ version: cached.widgetVersion ?? 0
364
+ }
365
+ : this.state.preview,
366
+ designSchema,
367
+ contentSchema,
368
+ designValues: seedMissingFontFaces(cached.designValues),
369
+ contentValues: mergeMissingContentValues(cached.contentValues, contentSchema),
370
+ contentItems,
371
+ schemasLoading: true,
372
+ schemasError: null,
373
+ loadError: null,
374
+ previewError: this.state.previewError
375
+ });
376
+ return true;
377
+ }
378
+ catch (error) {
379
+ this.logger.warn('[CompositionEditor] Warm-start cache seed failed (non-fatal):', error);
380
+ return false;
381
+ }
382
+ }
383
+ async persistSchemaCacheFromState() {
384
+ const store = this.shellStore();
385
+ if (!store)
386
+ return;
387
+ const { compositionId } = this.options;
388
+ const { designSchema, contentSchema, designValues, contentValues, contentItems, widgetId, name, preview } = this.state;
389
+ if (!designSchema && !contentSchema)
390
+ return;
391
+ const shell = {
392
+ compositionId,
393
+ widgetId,
394
+ widgetVersion: preview?.version ?? null,
395
+ locale: this.cacheLocale(),
396
+ designSchema,
397
+ contentSchema,
398
+ designValues: designValues,
399
+ contentValues: contentValues,
400
+ contentItems,
401
+ previewUrl: preview?.previewUrl ?? null,
402
+ name,
403
+ storedAtMs: Date.now()
404
+ };
405
+ try {
406
+ await store.write(shell);
407
+ }
408
+ catch (error) {
409
+ this.logger.warn('[CompositionEditor] Keeping the shell for the next open failed (non-fatal):', error);
410
+ }
411
+ }
298
412
  async runLoad() {
299
413
  const { api, compositionId } = this.options;
300
414
  const { signal } = this.abortController;
@@ -305,13 +419,21 @@ export class CompositionEditorController {
305
419
  schemasLoading: true,
306
420
  schemasError: null
307
421
  });
308
- // None of the four needs another's answer, so they travel together.
309
- const [compositionResult, previewResult, designResult, contentResult] = await Promise.allSettled([
422
+ // None of the four needs another's answer, so they travel together. They are on their way before the cache is
423
+ // read, so reading it never delays them.
424
+ const answers = Promise.allSettled([
310
425
  api.getComposition(compositionId, { signal }),
311
426
  api.getPreview(compositionId, { signal }),
312
427
  api.getDesignSchema(compositionId, { signal }),
313
428
  api.getContentSchema(compositionId, { signal })
314
429
  ]);
430
+ let networkAnswered = false;
431
+ void answers.then(() => {
432
+ networkAnswered = true;
433
+ });
434
+ // (Beside the requests: it paints the kept shell in place of the loading state, if it is read before they answer.)
435
+ void this.trySeedFromSchemaCache(() => networkAnswered);
436
+ const [compositionResult, previewResult, designResult, contentResult] = await answers;
315
437
  if (this.disposed)
316
438
  return;
317
439
  // What stops the load: no composition, or a refusal that makes every other answer worthless.
@@ -373,7 +495,6 @@ export class CompositionEditorController {
373
495
  phase: 'ready',
374
496
  name: String(composition.name || 'Untitled Composition'),
375
497
  widgetId,
376
- preview,
377
498
  previewError: previewFailure ? previewFailureMessage(previewFailure, this.translate) : null,
378
499
  designSchema: schemas.designSchema,
379
500
  contentSchema: schemas.contentSchema,
@@ -391,14 +512,38 @@ export class CompositionEditorController {
391
512
  saveError: null,
392
513
  // A fresh read is the latest version, so a refused save no longer has anything to ask.
393
514
  conflict: null,
394
- loadError: null
515
+ loadError: null,
516
+ preview
517
+ });
518
+ const serverPayload = draftPayloadFromEditorState({
519
+ designValues,
520
+ contentValues,
521
+ contentItems,
522
+ embedWidth,
523
+ embedHeight
395
524
  });
525
+ this.draftBaseRevision = serverBaseRevision(this.contentVersion, serverPayload);
526
+ this.tryApplyDraftAfterLoad(serverPayload);
396
527
  this.emit({ type: 'ready' });
397
528
  this.reportMissingSchemas(schemas);
529
+ void this.persistSchemaCacheFromState();
398
530
  }
399
531
  failLoad(failure) {
400
532
  this.logger.error('[CompositionEditor] The composition could not be loaded:', failure.code, failure.message);
401
- this.patch({ phase: 'failed', schemasLoading: false, loadError: failure });
533
+ this.patch({
534
+ phase: 'failed',
535
+ schemasLoading: false,
536
+ loadError: failure,
537
+ // A kept shell painted while requests were in flight must not stay on screen as if the load succeeded.
538
+ designSchema: null,
539
+ contentSchema: null,
540
+ designValues: {},
541
+ contentValues: {},
542
+ contentItems: [],
543
+ preview: null,
544
+ name: '',
545
+ widgetId: null
546
+ });
402
547
  this.emit({ type: 'error', during: 'load', failure, fatal: true });
403
548
  }
404
549
  /**
@@ -694,6 +839,7 @@ export class CompositionEditorController {
694
839
  this.embedRevision += 1;
695
840
  this.failedAutosaves = 0;
696
841
  this.patch({ dirty: true });
842
+ this.journalDraftFromState();
697
843
  this.scheduleAutosave(this.autosaveDelayMs);
698
844
  }
699
845
  hasUnsavedChanges() {
@@ -781,6 +927,10 @@ export class CompositionEditorController {
781
927
  dirty: this.hasUnsavedChanges()
782
928
  });
783
929
  this.emit({ type: 'saved', composition: updated, savedAt });
930
+ this.noteDraftAfterSuccessfulSave(savingRevision, savingContentRevision, savingEmbedRevision);
931
+ // What the next open shows first is what was saved last (not what was loaded), when nothing is left unsaved.
932
+ if (sendsContent && !this.hasUnsavedChanges())
933
+ void this.persistSchemaCacheFromState();
784
934
  // (Edits made while this save travelled are still unsaved: the autosave they started waits for its turn.)
785
935
  return true;
786
936
  }
@@ -917,11 +1067,133 @@ export class CompositionEditorController {
917
1067
  dispose() {
918
1068
  this.disposed = true;
919
1069
  this.clearAutosaveTimer();
1070
+ this.leaveFlushDisposer?.();
1071
+ this.leaveFlushDisposer = null;
920
1072
  this.abortController.abort();
921
1073
  this.stateListeners.clear();
922
1074
  this.eventListeners.clear();
923
1075
  }
924
1076
  // ---------------------------------------------------------------------------------------------
1077
+ // Draft journal (refresh / crash safety)
1078
+ // ---------------------------------------------------------------------------------------------
1079
+ journalDraftFromState() {
1080
+ if (!this.draftJournal || this.state.phase !== 'ready')
1081
+ return;
1082
+ const payload = draftPayloadFromEditorState(this.state);
1083
+ this.lastJournaledPayload = payload;
1084
+ this.draftJournal.write(this.options.compositionId, payload, this.draftBaseRevision);
1085
+ }
1086
+ flushDraftJournalNow() {
1087
+ if (!this.draftJournal || this.state.phase !== 'ready' || !this.hasUnsavedChanges())
1088
+ return;
1089
+ const payload = draftPayloadFromEditorState(this.state);
1090
+ this.draftJournal.flushNow(this.options.compositionId, payload, this.draftBaseRevision);
1091
+ }
1092
+ tryKeepaliveSaveOnLeave() {
1093
+ if (this.disposed ||
1094
+ !this.hasUnsavedChanges() ||
1095
+ this.state.conflict ||
1096
+ this.state.phase !== 'ready') {
1097
+ return;
1098
+ }
1099
+ const body = this.buildSaveBody();
1100
+ if (Object.keys(body).length === 0)
1101
+ return;
1102
+ let serialized = '';
1103
+ try {
1104
+ serialized = JSON.stringify(body);
1105
+ }
1106
+ catch {
1107
+ return;
1108
+ }
1109
+ if (serialized.length > KEEPALIVE_SAVE_MAX_BYTES)
1110
+ return;
1111
+ if (!this.leaveSaveIdempotencyKey) {
1112
+ this.leaveSaveIdempotencyKey =
1113
+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
1114
+ ? crypto.randomUUID()
1115
+ : `leave-${this.now()}`;
1116
+ }
1117
+ const sendsContent = body.content !== undefined;
1118
+ const ifMatchVersion = sendsContent && this.contentVersion !== null ? this.contentVersion : undefined;
1119
+ void this.options.api.saveComposition(this.options.compositionId, body, {
1120
+ keepalive: true,
1121
+ idempotencyKey: this.leaveSaveIdempotencyKey,
1122
+ ...(ifMatchVersion !== undefined ? { ifMatchVersion } : {})
1123
+ });
1124
+ }
1125
+ tryApplyDraftAfterLoad(serverPayload) {
1126
+ if (!this.draftJournal || this.disposed)
1127
+ return;
1128
+ const compositionId = this.options.compositionId;
1129
+ const entry = this.draftJournal.read(compositionId);
1130
+ const serverRevision = this.draftBaseRevision ?? serverBaseRevision(this.contentVersion, serverPayload);
1131
+ const result = applyDraftRestoreRule({
1132
+ entry,
1133
+ serverRevision,
1134
+ serverPayload,
1135
+ journal: this.draftJournal,
1136
+ compositionId,
1137
+ nowMs: this.now(),
1138
+ logger: {
1139
+ debug: (message, detail) => {
1140
+ if (typeof console !== 'undefined' && console.debug) {
1141
+ console.debug(message, detail ?? '');
1142
+ }
1143
+ }
1144
+ }
1145
+ });
1146
+ if (!result.applied || !entry)
1147
+ return;
1148
+ const payload = entry.payload;
1149
+ const embedChanged = payload.embedWidth !== serverPayload.embedWidth ||
1150
+ payload.embedHeight !== serverPayload.embedHeight;
1151
+ const desktop = this.state.deviceView === 'desktop';
1152
+ this.revision += 1;
1153
+ this.contentRevision += 1;
1154
+ if (embedChanged)
1155
+ this.embedRevision += 1;
1156
+ this.patch({
1157
+ designValues: seedMissingFontFaces(payload.designValues),
1158
+ contentValues: payload.contentValues,
1159
+ contentItems: mergeContentItemsWithSchema(Array.isArray(payload.contentItems) ? payload.contentItems : [], schemaContentItems(this.state.contentSchema)),
1160
+ embedWidth: payload.embedWidth,
1161
+ embedHeight: payload.embedHeight,
1162
+ ...(desktop
1163
+ ? { previewWidth: payload.embedWidth, previewHeight: payload.embedHeight }
1164
+ : {}),
1165
+ dirty: true
1166
+ });
1167
+ this.lastJournaledPayload = payload;
1168
+ this.journalDraftFromState();
1169
+ this.scheduleAutosave(this.autosaveDelayMs);
1170
+ for (const message of this.buildPreviewSnapshot())
1171
+ this.options.onPreviewMessage?.(message);
1172
+ this.onDraftRestored?.({
1173
+ key: compositionId,
1174
+ savedAtMs: result.savedAtMs ?? entry.savedAtMs
1175
+ });
1176
+ }
1177
+ noteDraftAfterSuccessfulSave(savingRevision, savingContentRevision, savingEmbedRevision) {
1178
+ if (!this.draftJournal)
1179
+ return;
1180
+ const currentPayload = draftPayloadFromEditorState(this.state);
1181
+ this.draftBaseRevision = serverBaseRevision(this.contentVersion, currentPayload);
1182
+ const savedEverything = this.revision === savingRevision &&
1183
+ this.contentRevision === savingContentRevision &&
1184
+ this.embedRevision === savingEmbedRevision;
1185
+ if (savedEverything) {
1186
+ const journaled = this.lastJournaledPayload;
1187
+ if (!journaled || payloadsEqual(journaled, currentPayload)) {
1188
+ this.draftJournal.clear(this.options.compositionId);
1189
+ this.lastJournaledPayload = null;
1190
+ }
1191
+ else {
1192
+ this.journalDraftFromState();
1193
+ }
1194
+ }
1195
+ }
1196
+ // ---------------------------------------------------------------------------------------------
925
1197
  // Internals
926
1198
  // ---------------------------------------------------------------------------------------------
927
1199
  /** Makes the next state out of the changes, tells the watchers, and says when the unsaved flag turned over. */
@@ -0,0 +1,35 @@
1
+ export interface CompositionEditorShellCache {
2
+ compositionId: string;
3
+ widgetId: string;
4
+ widgetVersion: number | null;
5
+ locale: string;
6
+ designSchema: unknown;
7
+ contentSchema: unknown;
8
+ designValues: Record<string, unknown>;
9
+ contentValues: Record<string, unknown>;
10
+ contentItems: unknown[];
11
+ previewUrl: string | null;
12
+ name: string;
13
+ storedAtMs: number;
14
+ }
15
+ /**
16
+ * Where the controller keeps the shell of its last load. The Dexie cache of the signed-in user by default
17
+ * (`createCompositionEditorShellStore`); a test, or a host with a store of its own, passes anything with these two.
18
+ */
19
+ export interface CompositionEditorShellStore {
20
+ read(compositionId: string, locale: string): Promise<CompositionEditorShellCache | null>;
21
+ write(shell: CompositionEditorShellCache): Promise<void>;
22
+ }
23
+ export declare function compositionEditorCacheScope(compositionId: string, locale: string): string;
24
+ export declare function resolveCompositionCacheOwner(explicitOwner?: string | null): string | null;
25
+ export declare function readCompositionEditorShellCache(options: {
26
+ ownerId: string;
27
+ compositionId: string;
28
+ locale: string;
29
+ }): Promise<CompositionEditorShellCache | null>;
30
+ export declare function writeCompositionEditorShellCache(ownerId: string, payload: CompositionEditorShellCache): Promise<void>;
31
+ /**
32
+ * The Dexie-backed store of one cache owner (`explicitOwnerId`, or the owner the host set in `@widgetic/cache-layer`).
33
+ * `null` while there is no owner (before login, or in a partner's page that never sets one): nothing is cached then.
34
+ */
35
+ export declare function createCompositionEditorShellStore(explicitOwnerId?: string | null): CompositionEditorShellStore | null;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Stale-first Dexie cache for what the composition editor needs on first paint (schemas + edited values shell).
3
+ * Successful loads only; no tokens. No-op when IndexedDB or cache owner is unavailable.
4
+ *
5
+ * The rows belong to the cache owner (the signed-in user), so `clearAllForOwner` at logout removes them with the rest.
6
+ */
7
+ import { getCacheOwner, readStaleFirst, writeStaleFirstCache } from '@widgetic/cache-layer';
8
+ const HOUR_MS = 60 * 60 * 1000;
9
+ const FRESH_TTL_MS = 5 * 60 * 1000;
10
+ const STALE_TTL_MS = 7 * 24 * HOUR_MS;
11
+ const CACHE_SCOPE_PREFIX = 'editor.compositionShell';
12
+ export function compositionEditorCacheScope(compositionId, locale) {
13
+ const language = (locale || 'en').trim() || 'en';
14
+ return `${CACHE_SCOPE_PREFIX}:${compositionId}:${language}`;
15
+ }
16
+ export function resolveCompositionCacheOwner(explicitOwner) {
17
+ const owner = explicitOwner ?? getCacheOwner();
18
+ if (!owner)
19
+ return null;
20
+ const trimmed = String(owner).trim();
21
+ return trimmed || null;
22
+ }
23
+ export async function readCompositionEditorShellCache(options) {
24
+ try {
25
+ const scope = compositionEditorCacheScope(options.compositionId, options.locale);
26
+ const result = await readStaleFirst({
27
+ ownerId: options.ownerId,
28
+ scope,
29
+ freshTtlMs: FRESH_TTL_MS,
30
+ staleTtlMs: STALE_TTL_MS,
31
+ extract: (metadata) => {
32
+ const payload = metadata;
33
+ if (!payload?.designSchema && !payload?.contentSchema)
34
+ return null;
35
+ return {
36
+ compositionId: String(payload.compositionId ?? options.compositionId),
37
+ widgetId: String(payload.widgetId ?? ''),
38
+ widgetVersion: typeof payload.widgetVersion === 'number' ? payload.widgetVersion : null,
39
+ locale: String(payload.locale ?? options.locale),
40
+ designSchema: payload.designSchema ?? null,
41
+ contentSchema: payload.contentSchema ?? null,
42
+ designValues: payload.designValues ?? {},
43
+ contentValues: payload.contentValues ?? {},
44
+ contentItems: Array.isArray(payload.contentItems) ? payload.contentItems : [],
45
+ previewUrl: typeof payload.previewUrl === 'string' ? payload.previewUrl : null,
46
+ name: typeof payload.name === 'string' ? payload.name : 'Untitled Composition',
47
+ storedAtMs: typeof payload.storedAtMs === 'number' ? payload.storedAtMs : Date.now()
48
+ };
49
+ }
50
+ });
51
+ return result?.data ?? null;
52
+ }
53
+ catch (error) {
54
+ console.warn('[CompositionEditor] Schema cache read failed (non-fatal):', error);
55
+ return null;
56
+ }
57
+ }
58
+ export async function writeCompositionEditorShellCache(ownerId, payload) {
59
+ try {
60
+ const scope = compositionEditorCacheScope(payload.compositionId, payload.locale);
61
+ await writeStaleFirstCache(ownerId, scope, {
62
+ ...payload,
63
+ storedAtMs: Date.now()
64
+ });
65
+ }
66
+ catch (error) {
67
+ console.warn('[CompositionEditor] Schema cache write failed (non-fatal):', error);
68
+ }
69
+ }
70
+ /**
71
+ * The Dexie-backed store of one cache owner (`explicitOwnerId`, or the owner the host set in `@widgetic/cache-layer`).
72
+ * `null` while there is no owner (before login, or in a partner's page that never sets one): nothing is cached then.
73
+ */
74
+ export function createCompositionEditorShellStore(explicitOwnerId) {
75
+ const ownerId = resolveCompositionCacheOwner(explicitOwnerId);
76
+ if (!ownerId)
77
+ return null;
78
+ return {
79
+ read: (compositionId, locale) => readCompositionEditorShellCache({ ownerId, compositionId, locale }),
80
+ write: (shell) => writeCompositionEditorShellCache(ownerId, shell)
81
+ };
82
+ }
@@ -0,0 +1,18 @@
1
+ import type { MediaLibraryFile } from '@widgetic/file-browser';
2
+ import type { ContentFromFilesPlan } from './types.js';
3
+ type ContentItem = {
4
+ id: string;
5
+ title: string;
6
+ orderNumber?: number;
7
+ properties: Array<Record<string, unknown>>;
8
+ };
9
+ export interface ApplyContentPlanResult {
10
+ contentItems: ContentItem[];
11
+ contentState: Record<string, unknown>;
12
+ newItemIds: string[];
13
+ }
14
+ /**
15
+ * Turns a gateway plan into new content items and flat editor state, as one batch (one save/draft write).
16
+ */
17
+ export declare function applyContentPlan(contentItems: ContentItem[], itemTemplate: ContentItem | null, plan: ContentFromFilesPlan, uploadedByMediaId: Map<string, MediaLibraryFile>): ApplyContentPlanResult | null;
18
+ export {};
@@ -0,0 +1,55 @@
1
+ function browserValueFromLibrary(file) {
2
+ return {
3
+ id: file.id,
4
+ file: file.name,
5
+ url: file.url,
6
+ thumbnail: file.thumbnail,
7
+ mimeType: file.mimeType
8
+ };
9
+ }
10
+ function cloneTemplateProperties(template) {
11
+ return template.properties.map((prop) => ({
12
+ ...prop,
13
+ value: ''
14
+ }));
15
+ }
16
+ function createItemFromTemplate(template, title) {
17
+ const uniqueId = `${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
18
+ return {
19
+ ...template,
20
+ id: uniqueId,
21
+ title,
22
+ properties: cloneTemplateProperties(template)
23
+ };
24
+ }
25
+ /**
26
+ * Turns a gateway plan into new content items and flat editor state, as one batch (one save/draft write).
27
+ */
28
+ export function applyContentPlan(contentItems, itemTemplate, plan, uploadedByMediaId) {
29
+ const template = contentItems.find((item) => Array.isArray(item.properties) && item.properties.length > 0) ??
30
+ itemTemplate;
31
+ if (!template || !Array.isArray(template.properties) || template.properties.length === 0) {
32
+ return null;
33
+ }
34
+ const nextItems = [...contentItems];
35
+ const contentState = {};
36
+ const newItemIds = [];
37
+ for (const planned of plan.items) {
38
+ const item = createItemFromTemplate(template, planned.label);
39
+ for (const assignment of planned.assignments) {
40
+ if (!assignment.mediaId)
41
+ continue;
42
+ const libraryFile = uploadedByMediaId.get(assignment.mediaId);
43
+ if (!libraryFile)
44
+ continue;
45
+ const value = browserValueFromLibrary(libraryFile);
46
+ const prop = item.properties.find((property) => (property.id ?? property.name) === assignment.fieldPath);
47
+ if (prop)
48
+ prop.value = value;
49
+ contentState[`${item.id}__${assignment.fieldPath}`] = value;
50
+ }
51
+ nextItems.push(item);
52
+ newItemIds.push(item.id);
53
+ }
54
+ return { contentItems: nextItems, contentState, newItemIds };
55
+ }
@@ -0,0 +1,4 @@
1
+ import type { Translate } from '@widgetic/design-system/i18n';
2
+ import type { EditorMessageKey } from '../i18n/messages.js';
3
+ export declare function formatBulkDropSummary(t: Translate<EditorMessageKey>, added: number, libraryOnly: number): string;
4
+ export declare function formatBulkUploadFailureMessage(t: Translate<EditorMessageKey>, failedCount: number): string;
@@ -0,0 +1,12 @@
1
+ export function formatBulkDropSummary(t, added, libraryOnly) {
2
+ if (libraryOnly <= 0) {
3
+ return t('editor.contentBulkDrop.summaryAddedOnly', { added: String(added) });
4
+ }
5
+ return t('editor.contentBulkDrop.summaryWithLibraryOnly', {
6
+ added: String(added),
7
+ libraryOnly: String(libraryOnly)
8
+ });
9
+ }
10
+ export function formatBulkUploadFailureMessage(t, failedCount) {
11
+ return t('editor.contentBulkDrop.uploadFailures', { n: String(failedCount) });
12
+ }
@@ -0,0 +1,7 @@
1
+ /** Whether a drag carries files (not plain text or a URL from the page). */
2
+ export declare function dragCarriesFiles(dataTransfer: DataTransfer | null | undefined): boolean;
3
+ export declare const CONTENT_FIELD_FILE_DROP_SELECTOR = "[data-content-field-file-drop]";
4
+ /** True when the event target is over a per-field file drop zone (browser / knowledge panel). */
5
+ export declare function isOverContentFieldFileDrop(target: EventTarget | null): boolean;
6
+ /** Bulk tab drop only when the drag carries files and is not aimed at a field-level drop target. */
7
+ export declare function shouldStartBulkContentDrop(event: DragEvent): boolean;