@widgetic/editor 4.1.11 → 4.1.12
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/components/WidgetPreview.svelte +1 -1
- package/dist/components/editors/CompositionEditorApp.svelte +229 -2
- package/dist/components/editors/CompositionEditorApp.svelte.d.ts +27 -2
- package/dist/components/editors/EditLeaseNotice.svelte +150 -0
- package/dist/components/editors/EditLeaseNotice.svelte.d.ts +25 -0
- package/dist/composition/compositionApi.d.ts +80 -1
- package/dist/composition/compositionApi.js +132 -7
- package/dist/composition/compositionEditorController.d.ts +106 -6
- package/dist/composition/compositionEditorController.js +211 -27
- package/dist/composition/compositionHelpers.d.ts +10 -0
- package/dist/composition/compositionHelpers.js +23 -0
- package/dist/composition/editLeaseController.d.ts +157 -0
- package/dist/composition/editLeaseController.js +441 -0
- package/dist/i18n/language.d.ts +28 -0
- package/dist/i18n/messages.d.ts +56 -0
- package/dist/i18n/messages.js +58 -0
- package/dist/i18n/translate.d.ts +1 -1
- package/dist/index.d.ts +3 -1
- package/package.json +1 -1
|
@@ -18,15 +18,30 @@
|
|
|
18
18
|
* (the session ended, the field is refused) is not.
|
|
19
19
|
* - The embed settings the composition already has (anything set by the site or by the partner's own backend)
|
|
20
20
|
* are sent back with the new size, never replaced by it.
|
|
21
|
+
* - A save sends only what the person changed here: the content when settings or items were edited, the embed
|
|
22
|
+
* settings when the preview was given a size. The name is never sent (this editor cannot rename, and the name it
|
|
23
|
+
* loaded may be out of date). A save that carried everything would put back, unseen, whatever a teammate changed
|
|
24
|
+
* in the parts this person did not touch (the page this was taken from did exactly that).
|
|
25
|
+
* - A save that carries content names the content version it was made from (`If-Match`). When a teammate saved the
|
|
26
|
+
* content since, the API refuses it and the editor does NOT send it again: it keeps every edit, stops autosaving,
|
|
27
|
+
* and asks the person to choose (`state.conflict`): keep their own version (`keepMyChanges`, saved on top of the
|
|
28
|
+
* version the API holds now, which is read again first, so a third person's save is refused too and never
|
|
29
|
+
* replaced unseen) or load the latest one (`loadLatestVersion`, which drops their edits). Nothing is chosen for
|
|
30
|
+
* them. The version is adopted from a save's answer only when that save carried the content: the answer to a save
|
|
31
|
+
* of the embed settings alone may hold a teammate's newer version that this editor never loaded.
|
|
21
32
|
* - The size that is saved is the one the user gave the preview (by dragging its corner or typing it in), and
|
|
22
33
|
* nothing else. Looking at the preview as on a phone changes how it is drawn, not what is saved, and the
|
|
23
34
|
* size a small box forces on the preview is not the user's choice, so it is never saved either (the page this
|
|
24
35
|
* was taken from saved both, so opening a composition in a small window, or trying the mobile view, changed
|
|
25
36
|
* the size of the widget embedded on a site).
|
|
37
|
+
* - A page that knows a teammate is editing the same composition (`EditLeaseController`) can block edits
|
|
38
|
+
* (`setEditsBlocked`): the props editor and the preview's resize then change nothing, however the call got there.
|
|
39
|
+
* Blocking is not locking: it never touches what was edited before it (that is saved as usual), and it never makes a
|
|
40
|
+
* save fail, so a teammate's presence can never cost a person their work.
|
|
26
41
|
* - After `dispose()` nothing more happens: no request goes out, and answers still on their way are ignored.
|
|
27
42
|
*/
|
|
28
43
|
import { translateEnglish } from '../i18n/translate.js';
|
|
29
|
-
import { buildPropsEditorContentSchema, compositionWidgetId, contentItemsToEditorValueMap, ensureSubtitleFontInDesignSchema, extractContentItemsFromCompositionRaw, extractContentValuesFromCompositionRaw, flattenContentItemsForPreview, flattenDesignValuesForPreview, getCompositionEmbedSettings, mergeContentItemsWithSchema, mergeMissingContentValues, normalizeContentSchemaFromApiResponse, normalizeDesignSchemaFromApiResponse, parseEmbedDimension, seedMissingFontFaces } from './compositionHelpers.js';
|
|
44
|
+
import { buildPropsEditorContentSchema, compositionContentVersion, compositionWidgetId, contentItemsToEditorValueMap, ensureSubtitleFontInDesignSchema, extractContentItemsFromCompositionRaw, extractContentValuesFromCompositionRaw, flattenContentItemsForPreview, flattenDesignValuesForPreview, getCompositionEmbedSettings, mergeContentItemsWithSchema, mergeMissingContentValues, normalizeContentSchemaFromApiResponse, normalizeDesignSchemaFromApiResponse, parseEmbedDimension, readContentVersion, seedMissingFontFaces } from './compositionHelpers.js';
|
|
30
45
|
/** Time to wait after the last edit before saving by itself. */
|
|
31
46
|
export const DEFAULT_AUTOSAVE_DELAY_MS = 2500;
|
|
32
47
|
/** How long to wait before trying an autosave again after it failed for a reason that may pass: first, second, third time. */
|
|
@@ -62,7 +77,9 @@ export function describeFailure(error) {
|
|
|
62
77
|
status: error.status,
|
|
63
78
|
retryable: error.retryable === true,
|
|
64
79
|
sessionEnded: error.sessionEnded === true,
|
|
65
|
-
correlationId: error.correlationId
|
|
80
|
+
correlationId: error.correlationId,
|
|
81
|
+
// (Only when the API said something: a failure without details keeps the shape it always had.)
|
|
82
|
+
...(isRecord(error.details) ? { details: error.details } : {})
|
|
66
83
|
};
|
|
67
84
|
}
|
|
68
85
|
return {
|
|
@@ -103,6 +120,37 @@ export function failureMessage(failure, doing, translate = translateEnglish) {
|
|
|
103
120
|
function refusesAccess(failure) {
|
|
104
121
|
return failure.sessionEnded || failure.status === 403;
|
|
105
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Whether a save was refused because somebody else saved the content after it was read (see
|
|
125
|
+
* `CompositionApiError.versionConflict`). Read from the code and the status the failure carries, not from the class,
|
|
126
|
+
* for the same reason `isCompositionApiError` is: a page can load a second copy of the client. A 409 of the API's
|
|
127
|
+
* idempotency layer ("that save is still being processed") is NOT one: it has a code of its own.
|
|
128
|
+
*/
|
|
129
|
+
function isVersionConflict(failure) {
|
|
130
|
+
return (failure.status === 412 ||
|
|
131
|
+
failure.code === 'CONTENT_VERSION_MISMATCH' ||
|
|
132
|
+
failure.code === 'CONTENT_WRITE_CONFLICT');
|
|
133
|
+
}
|
|
134
|
+
/** The text of a field of a refusal's details, or `null` when it is missing or not text. */
|
|
135
|
+
function detailText(details, key) {
|
|
136
|
+
const value = details?.[key];
|
|
137
|
+
return typeof value === 'string' && value.trim() !== '' ? value : null;
|
|
138
|
+
}
|
|
139
|
+
/** What the person is told about a refused save: the version the API holds now and, when it says, who saved it and when. */
|
|
140
|
+
function conflictFromFailure(failure) {
|
|
141
|
+
const details = failure.details;
|
|
142
|
+
const editedBy = details?.lastEditedBy;
|
|
143
|
+
const id = isRecord(editedBy) ? detailText(editedBy, 'id') : null;
|
|
144
|
+
const name = isRecord(editedBy) ? detailText(editedBy, 'name') : null;
|
|
145
|
+
return {
|
|
146
|
+
currentVersion: readContentVersion(details?.currentVersion),
|
|
147
|
+
lastEditedBy: id || name ? { ...(id ? { id } : {}), ...(name ? { name } : {}) } : null,
|
|
148
|
+
lastEditedAt: detailText(details, 'lastEditedAt'),
|
|
149
|
+
resolving: false,
|
|
150
|
+
resolveError: null,
|
|
151
|
+
correlationId: failure.correlationId
|
|
152
|
+
};
|
|
153
|
+
}
|
|
106
154
|
/** Why there is no preview, in words for a person. */
|
|
107
155
|
function previewFailureMessage(failure, translate) {
|
|
108
156
|
if (failure.status === 404)
|
|
@@ -145,6 +193,19 @@ export class CompositionEditorController {
|
|
|
145
193
|
failedAutosaves = 0;
|
|
146
194
|
/** The embed settings the composition has, sent back with the size on every save. */
|
|
147
195
|
storedEmbedSettings = {};
|
|
196
|
+
/**
|
|
197
|
+
* The content version the API held when this editor last read or wrote the content: what a save that carries
|
|
198
|
+
* content sends as `If-Match`. `null` when the API gave none (an API without versions): saves are then made
|
|
199
|
+
* without the check, as before.
|
|
200
|
+
*/
|
|
201
|
+
contentVersion = null;
|
|
202
|
+
/** Counts the edits of the content (settings and items), and of the size the composition is embedded at: a save sends the parts that changed. */
|
|
203
|
+
contentRevision = 0;
|
|
204
|
+
/** The content revision the last successful save took. */
|
|
205
|
+
savedContentRevision = 0;
|
|
206
|
+
embedRevision = 0;
|
|
207
|
+
/** The embed revision the last successful save took. */
|
|
208
|
+
savedEmbedRevision = 0;
|
|
148
209
|
autosaveTimer = null;
|
|
149
210
|
/** What `getPropsEditorContentSchema` and `getPropsEditorContentValues` last made, and from what. */
|
|
150
211
|
propsEditorSchemaCache = null;
|
|
@@ -190,6 +251,8 @@ export class CompositionEditorController {
|
|
|
190
251
|
dirty: false,
|
|
191
252
|
saving: false,
|
|
192
253
|
saveError: null,
|
|
254
|
+
conflict: null,
|
|
255
|
+
editsBlocked: false,
|
|
193
256
|
loadError: null,
|
|
194
257
|
lastSavedAt: null
|
|
195
258
|
};
|
|
@@ -298,8 +361,14 @@ export class CompositionEditorController {
|
|
|
298
361
|
this.storedEmbedSettings = getCompositionEmbedSettings(composition);
|
|
299
362
|
const embedWidth = parseEmbedDimension(this.storedEmbedSettings.width, DEFAULT_PREVIEW_WIDTH);
|
|
300
363
|
const embedHeight = parseEmbedDimension(this.storedEmbedSettings.height, DEFAULT_PREVIEW_HEIGHT);
|
|
364
|
+
// What a later save is checked against: the version of the content just read (`null` for an API without versions).
|
|
365
|
+
this.contentVersion = compositionContentVersion(composition);
|
|
301
366
|
this.revision = 0;
|
|
302
367
|
this.savedRevision = 0;
|
|
368
|
+
this.contentRevision = 0;
|
|
369
|
+
this.savedContentRevision = 0;
|
|
370
|
+
this.embedRevision = 0;
|
|
371
|
+
this.savedEmbedRevision = 0;
|
|
303
372
|
this.patch({
|
|
304
373
|
phase: 'ready',
|
|
305
374
|
name: String(composition.name || 'Untitled Composition'),
|
|
@@ -320,6 +389,8 @@ export class CompositionEditorController {
|
|
|
320
389
|
deviceView: 'desktop',
|
|
321
390
|
dirty: false,
|
|
322
391
|
saveError: null,
|
|
392
|
+
// A fresh read is the latest version, so a refused save no longer has anything to ask.
|
|
393
|
+
conflict: null,
|
|
323
394
|
loadError: null
|
|
324
395
|
});
|
|
325
396
|
this.emit({ type: 'ready' });
|
|
@@ -462,9 +533,23 @@ export class CompositionEditorController {
|
|
|
462
533
|
// ---------------------------------------------------------------------------------------------
|
|
463
534
|
// Editing
|
|
464
535
|
// ---------------------------------------------------------------------------------------------
|
|
536
|
+
/**
|
|
537
|
+
* Says whether new edits are taken. While blocked (a teammate is editing this composition, or the person chose to
|
|
538
|
+
* only look) `changeProperty`, `changeContentItems` and a resize of the preview are ignored, so nothing can be
|
|
539
|
+
* saved over the teammate's work by a path the screen forgot to close. Edits made before are kept and saved as
|
|
540
|
+
* usual, and the preview, the device buttons and `adoptEmbedSettings` work as before: none of them is an edit.
|
|
541
|
+
*/
|
|
542
|
+
setEditsBlocked(blocked) {
|
|
543
|
+
if (this.disposed || this.state.editsBlocked === blocked)
|
|
544
|
+
return;
|
|
545
|
+
this.logger.warn(blocked
|
|
546
|
+
? '[CompositionEditor] Edits are blocked: somebody else is editing, or the person chose to only look.'
|
|
547
|
+
: '[CompositionEditor] Edits are taken again.');
|
|
548
|
+
this.patch({ editsBlocked: blocked });
|
|
549
|
+
}
|
|
465
550
|
/** One property was changed in the props editor. */
|
|
466
551
|
changeProperty(change) {
|
|
467
|
-
if (this.disposed || this.state.phase !== 'ready')
|
|
552
|
+
if (this.disposed || this.state.phase !== 'ready' || this.state.editsBlocked)
|
|
468
553
|
return;
|
|
469
554
|
const { schema, propertyId, value, itemId } = change;
|
|
470
555
|
if (schema === 'design') {
|
|
@@ -485,11 +570,11 @@ export class CompositionEditorController {
|
|
|
485
570
|
this.logger.warn('[CompositionEditor] A change to an unknown kind of property was ignored:', schema);
|
|
486
571
|
return;
|
|
487
572
|
}
|
|
488
|
-
this.markEdited();
|
|
573
|
+
this.markEdited('content');
|
|
489
574
|
}
|
|
490
575
|
/** The content items (slides, rows, cards...) were changed in the props editor. */
|
|
491
576
|
changeContentItems(items) {
|
|
492
|
-
if (this.disposed || this.state.phase !== 'ready')
|
|
577
|
+
if (this.disposed || this.state.phase !== 'ready' || this.state.editsBlocked)
|
|
493
578
|
return;
|
|
494
579
|
const incoming = Array.isArray(items) ? items : [];
|
|
495
580
|
const contentItems = mergeContentItemsWithSchema(incoming, schemaContentItems(this.state.contentSchema));
|
|
@@ -498,7 +583,7 @@ export class CompositionEditorController {
|
|
|
498
583
|
type: 'widgetic:update',
|
|
499
584
|
contentItems: flattenContentItemsForPreview(contentItems)
|
|
500
585
|
});
|
|
501
|
-
this.markEdited();
|
|
586
|
+
this.markEdited('content');
|
|
502
587
|
}
|
|
503
588
|
/**
|
|
504
589
|
* The user gave the preview a size, by dragging its corner or typing it in. That is the size saved with the
|
|
@@ -515,7 +600,9 @@ export class CompositionEditorController {
|
|
|
515
600
|
// (The preview reports the size it was just given, too: that is not a new size.)
|
|
516
601
|
if (previewWidth === this.state.previewWidth && previewHeight === this.state.previewHeight)
|
|
517
602
|
return;
|
|
518
|
-
|
|
603
|
+
// While edits are blocked the preview can still be drawn at another size, but that size is not the person's
|
|
604
|
+
// choice for the composition, so it must not become one that a later save sends.
|
|
605
|
+
if (this.options.lockPreviewSize === true || this.state.editsBlocked) {
|
|
519
606
|
this.patch({
|
|
520
607
|
previewWidth,
|
|
521
608
|
previewHeight,
|
|
@@ -532,7 +619,7 @@ export class CompositionEditorController {
|
|
|
532
619
|
deviceView: 'desktop'
|
|
533
620
|
});
|
|
534
621
|
if (embedChanged)
|
|
535
|
-
this.markEdited();
|
|
622
|
+
this.markEdited('embed');
|
|
536
623
|
}
|
|
537
624
|
/**
|
|
538
625
|
* The mobile and desktop buttons: the preview is drawn at a phone's size, or back at the saved size. That is a
|
|
@@ -580,9 +667,10 @@ export class CompositionEditorController {
|
|
|
580
667
|
});
|
|
581
668
|
}
|
|
582
669
|
/**
|
|
583
|
-
* The page renamed the composition itself (a page can have its own title field), so the name this editor loaded
|
|
584
|
-
*
|
|
585
|
-
* the
|
|
670
|
+
* The page renamed the composition itself (a page can have its own title field), so the name this editor loaded is
|
|
671
|
+
* out of date. From now on `getState().name` is this one. (A save never sends the name: this editor cannot rename,
|
|
672
|
+
* and sending the one it loaded would undo a rename made elsewhere.) Nothing becomes unsaved: the page saved it
|
|
673
|
+
* already. Call it when no save of the editor is on its way (after `flush()`).
|
|
586
674
|
*/
|
|
587
675
|
adoptName(name) {
|
|
588
676
|
if (this.disposed || this.state.phase !== 'ready')
|
|
@@ -593,9 +681,17 @@ export class CompositionEditorController {
|
|
|
593
681
|
return;
|
|
594
682
|
this.patch({ name });
|
|
595
683
|
}
|
|
596
|
-
/**
|
|
597
|
-
|
|
684
|
+
/**
|
|
685
|
+
* An edit was made: there is something new to save, the wait for the next autosave starts again, and so does the count
|
|
686
|
+
* of failures. `part` says what it changed, because a save sends only what changed: the content (settings and items)
|
|
687
|
+
* or the size the composition is embedded at.
|
|
688
|
+
*/
|
|
689
|
+
markEdited(part) {
|
|
598
690
|
this.revision += 1;
|
|
691
|
+
if (part === 'content')
|
|
692
|
+
this.contentRevision += 1;
|
|
693
|
+
else
|
|
694
|
+
this.embedRevision += 1;
|
|
599
695
|
this.failedAutosaves = 0;
|
|
600
696
|
this.patch({ dirty: true });
|
|
601
697
|
this.scheduleAutosave(this.autosaveDelayMs);
|
|
@@ -613,6 +709,10 @@ export class CompositionEditorController {
|
|
|
613
709
|
save(reason = 'manual') {
|
|
614
710
|
if (this.disposed || this.state.phase !== 'ready')
|
|
615
711
|
return Promise.resolve(false);
|
|
712
|
+
// A save the API refused because a teammate saved first is not sent again until the person has chosen a version
|
|
713
|
+
// (`keepMyChanges` or `loadLatestVersion`): it would only be refused again, and autosave would keep asking.
|
|
714
|
+
if (this.state.conflict)
|
|
715
|
+
return Promise.resolve(false);
|
|
616
716
|
if (this.savePromise) {
|
|
617
717
|
// One save at a time: wait for the one on its way, then save what is new since, if it worked.
|
|
618
718
|
return this.savePromise.then((worked) => worked && this.hasUnsavedChanges() ? this.save(reason) : worked);
|
|
@@ -644,20 +744,36 @@ export class CompositionEditorController {
|
|
|
644
744
|
async runSave(reason) {
|
|
645
745
|
this.clearAutosaveTimer();
|
|
646
746
|
const savingRevision = this.revision;
|
|
747
|
+
const savingContentRevision = this.contentRevision;
|
|
748
|
+
const savingEmbedRevision = this.embedRevision;
|
|
647
749
|
this.patch({ saving: true, saveError: null });
|
|
648
750
|
try {
|
|
649
751
|
const body = this.buildSaveBody();
|
|
752
|
+
// A save that carries the content says which version of it the edits were made on, when that is known: the API
|
|
753
|
+
// then refuses it if a teammate saved the content since. (The API checks nothing for a save without content.)
|
|
754
|
+
const sendsContent = body.content !== undefined;
|
|
755
|
+
const ifMatchVersion = sendsContent && this.contentVersion !== null ? this.contentVersion : undefined;
|
|
650
756
|
const updated = await this.options.api.saveComposition(this.options.compositionId, body, {
|
|
651
|
-
signal: this.abortController.signal
|
|
757
|
+
signal: this.abortController.signal,
|
|
758
|
+
...(ifMatchVersion !== undefined ? { ifMatchVersion } : {})
|
|
652
759
|
});
|
|
653
760
|
if (this.disposed)
|
|
654
761
|
return false;
|
|
655
762
|
const savedAt = this.now();
|
|
656
763
|
this.savedRevision = savingRevision;
|
|
657
|
-
|
|
764
|
+
this.savedContentRevision = savingContentRevision;
|
|
765
|
+
this.savedEmbedRevision = savingEmbedRevision;
|
|
766
|
+
// The version the API holds for the content just written. A save without content wrote none, and its answer may
|
|
767
|
+
// hold a teammate's newer version that this editor never loaded: taking it would let the next save replace
|
|
768
|
+
// their work without being refused.
|
|
769
|
+
if (sendsContent)
|
|
770
|
+
this.contentVersion = compositionContentVersion(updated);
|
|
771
|
+
// What the API now holds for the embed settings, else what was just sent (or what was there before).
|
|
658
772
|
const settingsNow = getCompositionEmbedSettings(updated);
|
|
659
773
|
this.storedEmbedSettings =
|
|
660
|
-
Object.keys(settingsNow).length > 0
|
|
774
|
+
Object.keys(settingsNow).length > 0
|
|
775
|
+
? settingsNow
|
|
776
|
+
: (body.embedSettings ?? this.storedEmbedSettings);
|
|
661
777
|
this.patch({
|
|
662
778
|
saving: false,
|
|
663
779
|
saveError: null,
|
|
@@ -672,6 +788,15 @@ export class CompositionEditorController {
|
|
|
672
788
|
if (this.disposed)
|
|
673
789
|
return false;
|
|
674
790
|
const failure = describeFailure(error);
|
|
791
|
+
if (isVersionConflict(failure)) {
|
|
792
|
+
// Not a failure to retry and not a loss: a teammate saved the content after this editor loaded it. Every edit is
|
|
793
|
+
// kept; nothing more is sent until the person chooses which version stays.
|
|
794
|
+
const conflict = conflictFromFailure(failure);
|
|
795
|
+
this.logger.warn('[CompositionEditor] The save was refused: the composition was saved by somebody else after it was loaded. The edits are kept until the person chooses:', failure.code, conflict.currentVersion);
|
|
796
|
+
this.patch({ saving: false, saveError: null, conflict });
|
|
797
|
+
this.emit({ type: 'conflict', conflict });
|
|
798
|
+
return false;
|
|
799
|
+
}
|
|
675
800
|
this.logger.warn('[CompositionEditor] Saving failed:', failure.code, failure.message);
|
|
676
801
|
this.patch({ saving: false, saveError: failure });
|
|
677
802
|
this.emit({ type: 'error', during: 'save', failure, fatal: false });
|
|
@@ -680,23 +805,82 @@ export class CompositionEditorController {
|
|
|
680
805
|
return false;
|
|
681
806
|
}
|
|
682
807
|
}
|
|
683
|
-
/**
|
|
808
|
+
/**
|
|
809
|
+
* What a save sends: a copy, taken now so later edits cannot change it, of the parts that changed since the last save.
|
|
810
|
+
* The content when settings or items were edited; the embed settings (the ones the composition has, with the new size)
|
|
811
|
+
* when the preview was given a size. The name is never sent: this editor cannot rename, so the name it holds is the
|
|
812
|
+
* one it loaded, and sending it back would undo a rename a teammate made since.
|
|
813
|
+
*/
|
|
684
814
|
buildSaveBody() {
|
|
685
|
-
const {
|
|
686
|
-
const
|
|
687
|
-
if (
|
|
688
|
-
content
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
content
|
|
692
|
-
|
|
815
|
+
const { designValues, contentValues, contentItems, embedWidth, embedHeight } = this.state;
|
|
816
|
+
const body = {};
|
|
817
|
+
if (this.contentRevision !== this.savedContentRevision) {
|
|
818
|
+
const content = { design: designValues, content: contentValues };
|
|
819
|
+
if (contentItems.length > 0)
|
|
820
|
+
content.contentItems = contentItems;
|
|
821
|
+
body.content = content;
|
|
822
|
+
}
|
|
823
|
+
if (this.embedRevision !== this.savedEmbedRevision) {
|
|
824
|
+
body.embedSettings = {
|
|
693
825
|
...this.storedEmbedSettings,
|
|
694
826
|
width: String(embedWidth),
|
|
695
827
|
height: String(embedHeight)
|
|
696
|
-
}
|
|
697
|
-
}
|
|
828
|
+
};
|
|
829
|
+
}
|
|
698
830
|
return JSON.parse(JSON.stringify(body));
|
|
699
831
|
}
|
|
832
|
+
/**
|
|
833
|
+
* After a refused save, the person chose to keep their own version: their edits are saved on top of what the API
|
|
834
|
+
* holds now. The version to save on top of is read again rather than taken from the refusal, because minutes may
|
|
835
|
+
* have passed: if a third person saved meanwhile, this save is refused too and the person is asked again, never
|
|
836
|
+
* replaced unseen. Resolves `true` when nothing is left unsaved afterwards, `false` otherwise (the conflict stays
|
|
837
|
+
* when it could not even be read, with `resolveError` saying why).
|
|
838
|
+
*/
|
|
839
|
+
async keepMyChanges() {
|
|
840
|
+
const conflict = this.state.conflict;
|
|
841
|
+
if (this.disposed || this.state.phase !== 'ready' || !conflict || conflict.resolving)
|
|
842
|
+
return false;
|
|
843
|
+
this.patch({ conflict: { ...conflict, resolving: true, resolveError: null } });
|
|
844
|
+
try {
|
|
845
|
+
const latest = await this.options.api.getComposition(this.options.compositionId, {
|
|
846
|
+
signal: this.abortController.signal
|
|
847
|
+
});
|
|
848
|
+
if (this.disposed)
|
|
849
|
+
return false;
|
|
850
|
+
this.contentVersion = compositionContentVersion(latest);
|
|
851
|
+
// The base a new embed size is merged into: what the composition holds now.
|
|
852
|
+
const latestEmbedSettings = getCompositionEmbedSettings(latest);
|
|
853
|
+
if (Object.keys(latestEmbedSettings).length > 0)
|
|
854
|
+
this.storedEmbedSettings = latestEmbedSettings;
|
|
855
|
+
}
|
|
856
|
+
catch (error) {
|
|
857
|
+
if (this.disposed)
|
|
858
|
+
return false;
|
|
859
|
+
const failure = describeFailure(error);
|
|
860
|
+
this.logger.warn('[CompositionEditor] The latest version could not be read, so the edits were not saved:', failure.code, failure.message);
|
|
861
|
+
this.patch({ conflict: { ...(this.state.conflict ?? conflict), resolving: false, resolveError: failure } });
|
|
862
|
+
return false;
|
|
863
|
+
}
|
|
864
|
+
this.patch({ conflict: null });
|
|
865
|
+
this.emit({ type: 'conflictResolved', resolution: 'keepMine' });
|
|
866
|
+
return this.save('manual');
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* After a refused save, the person chose the latest version: the composition is read again and their edits are
|
|
870
|
+
* dropped. The preview is told the new values (its page may not reload, when the widget is the same).
|
|
871
|
+
*/
|
|
872
|
+
async loadLatestVersion() {
|
|
873
|
+
const conflict = this.state.conflict;
|
|
874
|
+
if (this.disposed || this.state.phase !== 'ready' || !conflict || conflict.resolving)
|
|
875
|
+
return;
|
|
876
|
+
this.patch({ conflict: { ...conflict, resolving: true, resolveError: null } });
|
|
877
|
+
await this.load();
|
|
878
|
+
// (A load that failed leaves the editor `failed`, with its own message and "Try again"; one that worked cleared the conflict.)
|
|
879
|
+
if (this.disposed || this.state.phase !== 'ready')
|
|
880
|
+
return;
|
|
881
|
+
this.syncPreview();
|
|
882
|
+
this.emit({ type: 'conflictResolved', resolution: 'loadLatest' });
|
|
883
|
+
}
|
|
700
884
|
// ---------------------------------------------------------------------------------------------
|
|
701
885
|
// Autosave timing
|
|
702
886
|
// ---------------------------------------------------------------------------------------------
|
|
@@ -70,5 +70,15 @@ export declare function buildPropsEditorContentSchema(schema: any, items: any[])
|
|
|
70
70
|
export declare function seedMissingFontFaces(design: JsonRecord): JsonRecord;
|
|
71
71
|
/** The embed settings a composition saved, or `{}` when it saved none. */
|
|
72
72
|
export declare function getCompositionEmbedSettings(composition: JsonRecord): JsonRecord;
|
|
73
|
+
/**
|
|
74
|
+
* A content version as a number: the count the API keeps of the changes made to a composition's content, which a save
|
|
75
|
+
* sends back as `If-Match` so that a save made on a copy somebody else has saved over since is refused. A whole number
|
|
76
|
+
* of zero or more, written as a number or as digits, is a version. Anything else (a missing field, an API that has no
|
|
77
|
+
* versions yet, a fraction, `NaN`, a number too big to count exactly) is `null`: the version is not known, and a save is
|
|
78
|
+
* then sent without the check, as it was before versions existed.
|
|
79
|
+
*/
|
|
80
|
+
export declare function readContentVersion(value: unknown): number | null;
|
|
81
|
+
/** The content version a composition record carries (`contentVersion`, or `content_version` in a raw row), or `null` when it carries none. */
|
|
82
|
+
export declare function compositionContentVersion(composition: JsonRecord | null | undefined): number | null;
|
|
73
83
|
/** A size saved as text or number ("800", 800, "800px") as a positive whole number; anything else is the fallback. */
|
|
74
84
|
export declare function parseEmbedDimension(value: unknown, fallback: number): number;
|
|
@@ -398,6 +398,29 @@ export function getCompositionEmbedSettings(composition) {
|
|
|
398
398
|
const settings = composition.embedSettings ?? composition.embed_settings;
|
|
399
399
|
return settings && typeof settings === 'object' ? settings : {};
|
|
400
400
|
}
|
|
401
|
+
/**
|
|
402
|
+
* A content version as a number: the count the API keeps of the changes made to a composition's content, which a save
|
|
403
|
+
* sends back as `If-Match` so that a save made on a copy somebody else has saved over since is refused. A whole number
|
|
404
|
+
* of zero or more, written as a number or as digits, is a version. Anything else (a missing field, an API that has no
|
|
405
|
+
* versions yet, a fraction, `NaN`, a number too big to count exactly) is `null`: the version is not known, and a save is
|
|
406
|
+
* then sent without the check, as it was before versions existed.
|
|
407
|
+
*/
|
|
408
|
+
export function readContentVersion(value) {
|
|
409
|
+
if (typeof value === 'number') {
|
|
410
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
411
|
+
}
|
|
412
|
+
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
|
413
|
+
const parsed = Number(value.trim());
|
|
414
|
+
return Number.isSafeInteger(parsed) ? parsed : null;
|
|
415
|
+
}
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
/** The content version a composition record carries (`contentVersion`, or `content_version` in a raw row), or `null` when it carries none. */
|
|
419
|
+
export function compositionContentVersion(composition) {
|
|
420
|
+
if (!composition)
|
|
421
|
+
return null;
|
|
422
|
+
return readContentVersion(composition.contentVersion ?? composition.content_version);
|
|
423
|
+
}
|
|
401
424
|
/** A size saved as text or number ("800", 800, "800px") as a positive whole number; anything else is the fallback. */
|
|
402
425
|
export function parseEmbedDimension(value, fallback) {
|
|
403
426
|
const parsed = parseInt(String(value ?? ''), 10);
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who is editing this composition right now, as one open editor lives it: the claim this tab keeps while it edits, and
|
|
3
|
+
* what it does when somebody else holds it. No user interface in it, and no dependency but the API's answers, so a test
|
|
4
|
+
* can drive it with a fake port and fake timers.
|
|
5
|
+
*
|
|
6
|
+
* It is presence, never a lock. The rules that keep it harmless:
|
|
7
|
+
*
|
|
8
|
+
* - Nothing here can make a save fail or take edits away. The only thing it does to the editor is ask it to stop
|
|
9
|
+
* taking NEW edits (`editsBlocked`) while a teammate holds the claim; everything edited before is still saved.
|
|
10
|
+
* - Every doubt means "edit freely". The API cannot tell, the network is down, the composition has no presence
|
|
11
|
+
* (a personal one), the person may not write to it, the answer is unreadable: the editor behaves as if this feature
|
|
12
|
+
* did not exist, and tries again later (or, when the API refused for good, never).
|
|
13
|
+
* - The person always decides. When somebody else holds the claim the person may take over (their claim replaces the
|
|
14
|
+
* other's at once), or look only. Nobody is ever locked out: a claim that is not renewed ends by itself, and a
|
|
15
|
+
* take-over is always one click away.
|
|
16
|
+
* - A claim belongs to a tab (`sessionId`), not to a person: the same person in two windows is two holders, and the
|
|
17
|
+
* second window is told so ("you are editing this in another window").
|
|
18
|
+
* - A claim is kept up only while the tab is on screen. A tab left in the background all day does not keep a
|
|
19
|
+
* teammate out: its claim runs out after the time the API gave, and when the person comes back the tab asks again,
|
|
20
|
+
* and says so if somebody else has begun editing meanwhile.
|
|
21
|
+
* - One request at a time. A renewal never overlaps another call; a choice the person makes cancels the call on its
|
|
22
|
+
* way, and the answer of a cancelled call is ignored.
|
|
23
|
+
* - A claim is given up as soon as the editor closes (`dispose`) or the page goes (`pagehide`), with a request that
|
|
24
|
+
* outlives the page, so a teammate does not wait for it to run out.
|
|
25
|
+
* - After `dispose()` nothing more happens: no request goes out, and answers still on their way are ignored.
|
|
26
|
+
*/
|
|
27
|
+
import { type EditLeaseAnswer, type EditLeaseHolder } from './compositionApi.js';
|
|
28
|
+
/** What the controller asks of the API, for one composition. The page builds it from its `CompositionApi`. */
|
|
29
|
+
export interface EditLeasePort {
|
|
30
|
+
acquire(sessionId: string, options?: {
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}): Promise<EditLeaseAnswer>;
|
|
33
|
+
takeOver(sessionId: string, options?: {
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
}): Promise<EditLeaseAnswer>;
|
|
36
|
+
peek(options?: {
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
}): Promise<EditLeaseAnswer>;
|
|
39
|
+
release(sessionId: string, options?: {
|
|
40
|
+
keepalive?: boolean;
|
|
41
|
+
}): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Where the tab is:
|
|
45
|
+
* - `off`: no presence (not started, none for this composition, refused for good, or the API cannot tell): edit freely;
|
|
46
|
+
* - `editing`: this tab holds the claim;
|
|
47
|
+
* - `blocked`: somebody else holds it and the person has not chosen yet (a card asks);
|
|
48
|
+
* - `readOnly`: the person chose to only look (a slim bar says who is editing, or that nobody is).
|
|
49
|
+
*/
|
|
50
|
+
export type PresencePhase = 'off' | 'editing' | 'blocked' | 'readOnly';
|
|
51
|
+
export interface PresenceState {
|
|
52
|
+
phase: PresencePhase;
|
|
53
|
+
/** Who holds the claim, in `blocked` and `readOnly` (`null` when the API gave nobody, or nobody holds it). */
|
|
54
|
+
holder: EditLeaseHolder | null;
|
|
55
|
+
/** `blocked` because the claim was taken from this tab (a teammate took over, or its claim ran out): not just arrived. */
|
|
56
|
+
lostIt: boolean;
|
|
57
|
+
/** In `readOnly`: the last look found nobody editing, so the person may start. */
|
|
58
|
+
nobodyIsEditing: boolean;
|
|
59
|
+
/** A choice of the person (take over, start editing) is on its way. */
|
|
60
|
+
working: boolean;
|
|
61
|
+
/** The last choice could not be carried out (the API could not be reached): the person may try again. */
|
|
62
|
+
actionFailed: boolean;
|
|
63
|
+
/** The editor should take no new edit: `blocked` or `readOnly`. */
|
|
64
|
+
editsBlocked: boolean;
|
|
65
|
+
}
|
|
66
|
+
/** What the controller needs from the page it lives in. The default is the browser's own. */
|
|
67
|
+
export interface PresenceEnvironment {
|
|
68
|
+
/** The tab is on screen. */
|
|
69
|
+
isVisible(): boolean;
|
|
70
|
+
/** Calls `callback` when the tab comes back to the screen, the network returns, or the page is restored from the cache. */
|
|
71
|
+
onWake(callback: () => void): () => void;
|
|
72
|
+
/** Calls `callback` when the page is about to go (closed, or navigated away from). */
|
|
73
|
+
onPageHide(callback: () => void): () => void;
|
|
74
|
+
}
|
|
75
|
+
export interface TimerFunctions {
|
|
76
|
+
setTimeout: (callback: () => void, milliseconds: number) => unknown;
|
|
77
|
+
clearTimeout: (handle: unknown) => void;
|
|
78
|
+
}
|
|
79
|
+
export interface EditLeaseControllerOptions {
|
|
80
|
+
port: EditLeasePort;
|
|
81
|
+
/** The id of this tab (8 to 64 letters, digits, dashes or underscores). Default: a random UUID. */
|
|
82
|
+
sessionId?: string;
|
|
83
|
+
/** How often to renew the claim until the API says otherwise, in milliseconds. Default: 20 seconds. */
|
|
84
|
+
heartbeatMs?: number;
|
|
85
|
+
timers?: TimerFunctions;
|
|
86
|
+
/** The clock, in milliseconds. Default: `Date.now`. */
|
|
87
|
+
now?: () => number;
|
|
88
|
+
environment?: PresenceEnvironment;
|
|
89
|
+
/** Writes the controller's own notes (a request refused as malformed, a listener that failed). Default: the console. */
|
|
90
|
+
logger?: Pick<Console, 'warn' | 'error'>;
|
|
91
|
+
}
|
|
92
|
+
/** How often to renew a claim when the API has not said (it says, with every answer). */
|
|
93
|
+
export declare const DEFAULT_HEARTBEAT_MS = 20000;
|
|
94
|
+
/** The browser's own environment; one that does nothing where there is no page (a server, a test). */
|
|
95
|
+
export declare function createBrowserPresenceEnvironment(): PresenceEnvironment;
|
|
96
|
+
/** The state of a tab with no presence: nothing is shown and nothing is blocked. What a page starts from, before the API has said. */
|
|
97
|
+
export declare const NO_PRESENCE: Readonly<PresenceState>;
|
|
98
|
+
export declare class EditLeaseController {
|
|
99
|
+
private state;
|
|
100
|
+
private readonly stateListeners;
|
|
101
|
+
private readonly port;
|
|
102
|
+
private readonly sessionId;
|
|
103
|
+
private readonly timers;
|
|
104
|
+
private readonly now;
|
|
105
|
+
private readonly environment;
|
|
106
|
+
private readonly logger;
|
|
107
|
+
private heartbeatMs;
|
|
108
|
+
private timerHandle;
|
|
109
|
+
private inFlight;
|
|
110
|
+
/** Which call is the current one: the answer of an older call is ignored. */
|
|
111
|
+
private generation;
|
|
112
|
+
private started;
|
|
113
|
+
/** The API refused for good (or said there is no presence): no more requests. */
|
|
114
|
+
private stopped;
|
|
115
|
+
private disposed;
|
|
116
|
+
/** This tab holds the claim as far as it knows, so it must give it up when it goes. */
|
|
117
|
+
private holding;
|
|
118
|
+
private failureStreak;
|
|
119
|
+
private lastAnswerAt;
|
|
120
|
+
private removeWakeListener;
|
|
121
|
+
private removeHideListener;
|
|
122
|
+
constructor(options: EditLeaseControllerOptions);
|
|
123
|
+
/** The state now. It is never changed in place: a change makes a new object. */
|
|
124
|
+
getState(): PresenceState;
|
|
125
|
+
/** Svelte store contract: calls `listener` with the state now, and again after every change. */
|
|
126
|
+
subscribe(listener: (state: PresenceState) => void): () => void;
|
|
127
|
+
/** The id of this tab, as the API knows it. */
|
|
128
|
+
get tabId(): string;
|
|
129
|
+
/** Asks to edit, and keeps asking while the tab is open. Asking again does nothing. */
|
|
130
|
+
start(): void;
|
|
131
|
+
/** The person chose to take the claim from whoever holds it. Only from `blocked` and `readOnly`. */
|
|
132
|
+
takeOver(): void;
|
|
133
|
+
/** The person chose to only look, for now. Only from `blocked`. */
|
|
134
|
+
openReadOnly(): void;
|
|
135
|
+
/** The person chose to begin editing after looking. Only from `readOnly`. */
|
|
136
|
+
startEditing(): void;
|
|
137
|
+
private canChoose;
|
|
138
|
+
/** Stops everything, gives the claim up, and ignores any answer still on its way. */
|
|
139
|
+
dispose(): void;
|
|
140
|
+
/** The renewal the timer asks for: only while the tab is on screen (a hidden tab's claim is left to run out). */
|
|
141
|
+
private beat;
|
|
142
|
+
/** The tab came back to the screen (or the network did): ask at once instead of waiting for the timer. */
|
|
143
|
+
private wake;
|
|
144
|
+
private call;
|
|
145
|
+
private send;
|
|
146
|
+
/** What an answer changes. `kind` and the phase tell which question it answers. */
|
|
147
|
+
private apply;
|
|
148
|
+
private fail;
|
|
149
|
+
/** The API said there is no presence here (or refused for good): edit freely, and stop asking. */
|
|
150
|
+
private stop;
|
|
151
|
+
private scheduleBeat;
|
|
152
|
+
private clearTimer;
|
|
153
|
+
/** Gives the claim up, if this tab holds it, with a request that outlives the page. Never throws, never waits. */
|
|
154
|
+
private releaseClaim;
|
|
155
|
+
/** Makes the next state out of the changes and tells the watchers, once, when something changed. */
|
|
156
|
+
private patch;
|
|
157
|
+
}
|