@widgetic/creator 0.4.40 → 0.4.41

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.
@@ -256,6 +256,7 @@
256
256
  publishTargetOf
257
257
  } from './host/hostControls.js';
258
258
  import { createSerialQueue } from './utils/serialQueue.js';
259
+ import { createHeldAutosave } from './utils/heldAutosave.js';
259
260
  import { widgetsToRestore } from './utils/widgetsToRestore.js';
260
261
 
261
262
  function resolveCreatorWorkflowStep(
@@ -615,10 +616,15 @@
615
616
  * it (the saves already on their way are waited for too). A page that is about to take the person away from the creator
616
617
  * (its Back arrow) calls this first. Never rejects: a save that fails stays unsaved on the canvas, and the copy kept in the
617
618
  * browser is not lost (see `handleCanvasAutoSave`).
619
+ *
620
+ * A change made in the first seconds after a canvas has loaded is held back by `handleCanvasAutoSave`, and the canvas's
621
+ * own flush resolves with it still held: it is waited out and sent here (at most a few seconds, the length of that hold),
622
+ * so "saved" is true when this resolves.
618
623
  */
619
624
  export async function flush(): Promise<void> {
620
625
  try {
621
626
  await canvasRef?.flushAutosave?.();
627
+ await heldCooldownAutosave.sendNow();
622
628
  await canvasSaveQueue.whenIdle();
623
629
  } catch (error) {
624
630
  console.warn('[CreatorApp] Host flush failed:', error);
@@ -7718,11 +7724,7 @@
7718
7724
  * it later would write one canvas's shapes into another.
7719
7725
  */
7720
7726
  function discardPendingCooldownAutosave(): void {
7721
- if (cooldownAutosaveTimer) {
7722
- clearTimeout(cooldownAutosaveTimer);
7723
- cooldownAutosaveTimer = null;
7724
- }
7725
- pendingCooldownAutosaveJson = null;
7727
+ heldCooldownAutosave.discard();
7726
7728
  }
7727
7729
 
7728
7730
  function relinkSelectedWidgetShape(): void {
@@ -17839,14 +17841,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17839
17841
  let lastResolvedAutosaveSequence = 0;
17840
17842
  /** The requests that write the canvas to the API, one at a time and in the order they were made (see `handleCanvasAutoSave`). */
17841
17843
  const canvasSaveQueue = createSerialQueue();
17844
+ /** How long after a canvas load we still defer (not drop) autosaves. */
17845
+ const CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS = 3000;
17846
+ /**
17847
+ * The longest `flush()` waits for a canvas that has only just loaded to be quiet. A load's cooldown is 3 s and a restore of
17848
+ * the widget's shapes can start another just after, so twice that is a hold that really is over.
17849
+ */
17850
+ const CANVAS_COOLDOWN_FLUSH_MAX_WAIT_MS = 6000;
17842
17851
  /**
17843
17852
  * Trailing save deferred while `isLoadCooldownActive` is set.
17844
- * See {@link handleCanvasAutoSave}: dropping cooldown saves lost user edits.
17853
+ * See {@link handleCanvasAutoSave}: dropping cooldown saves lost user edits. `flush()` waits for it and sends it; a save
17854
+ * that goes through, or a switch of canvas, drops it (`utils/heldAutosave.ts`).
17845
17855
  */
17846
- let pendingCooldownAutosaveJson: string | null = null;
17847
- let cooldownAutosaveTimer: ReturnType<typeof setTimeout> | null = null;
17848
- /** How long after a canvas load we still defer (not drop) autosaves. */
17849
- const CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS = 3000;
17856
+ const heldCooldownAutosave = createHeldAutosave({
17857
+ isHolding: () => isLoadCooldownActive,
17858
+ send: (json) => handleCanvasAutoSave(json),
17859
+ delayMs: CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS,
17860
+ maxWaitMs: CANVAS_COOLDOWN_FLUSH_MAX_WAIT_MS
17861
+ });
17850
17862
 
17851
17863
  async function handleCanvasAutoSave(
17852
17864
  json: string | null,
@@ -17876,14 +17888,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17876
17888
  // overwrite freshly painted state, but a real move/resize a moment later is
17877
17889
  // persisted rather than silently discarded.
17878
17890
  if (!force && isLoadCooldownActive && !isUnmountSave) {
17879
- pendingCooldownAutosaveJson = json;
17880
- if (cooldownAutosaveTimer) clearTimeout(cooldownAutosaveTimer);
17881
- cooldownAutosaveTimer = setTimeout(() => {
17882
- cooldownAutosaveTimer = null;
17883
- const deferred = pendingCooldownAutosaveJson;
17884
- pendingCooldownAutosaveJson = null;
17885
- if (deferred) void handleCanvasAutoSave(deferred);
17886
- }, CANVAS_COOLDOWN_AUTOSAVE_DELAY_MS);
17891
+ heldCooldownAutosave.hold(json);
17887
17892
  return;
17888
17893
  }
17889
17894
 
@@ -17928,6 +17933,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17928
17933
  // console.log('[CanvasDebug] Allowing save: last object deleted by user (1→0)');
17929
17934
  }
17930
17935
 
17936
+ // This save goes through, so the one held back from the load's cooldown is older than it: sent after it, three seconds
17937
+ // on, it would write the older canvas over the newer one and ask the server twice for one run of changes.
17938
+ heldCooldownAutosave.discard();
17939
+
17931
17940
  lastSavedCanvasObjectCount = objectCount;
17932
17941
  try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
17933
17942
  emitCreatorSaveState(false);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The save that a canvas holds back for a few seconds after it has loaded.
3
+ *
4
+ * Opening a canvas draws its shapes one by one, and every one of them fires an event that looks like a change made by the person.
5
+ * For a few seconds after a load the creator therefore does not send a save at once (`isLoadCooldownActive` in `CreatorApp.svelte`):
6
+ * dropping it would lose a real edit made in those seconds, so it keeps the newest one and sends it when the canvas is quiet again.
7
+ * This module is that keeper. It was a timer and a variable in the component, and it had two faults that a person only meets when
8
+ * they change something in the first seconds:
9
+ *
10
+ * - **A save that goes through did not make the held one stale.** The held one was sent three seconds later all the same: a second
11
+ * request for one run of changes, and an older snapshot written after a newer one. {@link HeldAutosave.discard} is what a save
12
+ * that goes through calls, so the held one is forgotten.
13
+ * - **A page that asked for a save now waited for nothing.** `flush()` resolves when the canvas's own save has resolved, and a save
14
+ * that is held resolves at once: the page was told "saved" with the canvas still on the shelf. {@link HeldAutosave.sendNow} waits
15
+ * for the hold to end (a snapshot taken in the middle of a load can be half a canvas), sends the held save and resolves when the
16
+ * save is done.
17
+ *
18
+ * Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
19
+ */
20
+ /** The clock the keeper reads and sets timers with. Tests pass one they move by hand. */
21
+ export interface HeldAutosaveClock {
22
+ /** Milliseconds, from any fixed point. */
23
+ now(): number;
24
+ /** Calls `callback` once, `delayMs` from now. Returns what {@link clearTimer} needs to take it back. */
25
+ setTimer(callback: () => void, delayMs: number): unknown;
26
+ clearTimer(handle: unknown): void;
27
+ }
28
+ export interface HeldAutosaveOptions {
29
+ /** True while saves are held back (a canvas has just loaded). Read whenever it matters. */
30
+ isHolding: () => boolean;
31
+ /**
32
+ * Makes the save of the canvas (the component's `handleCanvasAutoSave`). Called while the hold is still on, it holds the
33
+ * save again, which is how a hold that lasts longer than the timer keeps the save until it is over.
34
+ */
35
+ send: (json: string) => Promise<unknown> | void;
36
+ /** How long the held save waits, after the last one handed over, before it is sent by itself. */
37
+ delayMs: number;
38
+ /** The longest {@link HeldAutosave.sendNow} waits for the hold to end. A hold that lasts longer leaves the save to its timer. */
39
+ maxWaitMs: number;
40
+ /** Told what went wrong or was left undone. Defaults to `console.warn`. */
41
+ warn?: (message: string, error?: unknown) => void;
42
+ /** Defaults to the real one. */
43
+ clock?: HeldAutosaveClock;
44
+ }
45
+ export interface HeldAutosave {
46
+ /**
47
+ * A save came while saves are held back. Keeps it in place of the one held (the canvas is saved whole, so the newest holds the
48
+ * changes of the older) and starts the wait again.
49
+ */
50
+ hold(json: string): void;
51
+ /**
52
+ * Forgets the held save: a newer one is going out, or the canvas it belongs to is not the one on the screen any more. A save
53
+ * that is already on its way is left alone.
54
+ */
55
+ discard(): void;
56
+ /**
57
+ * Sends the held save once the hold is over, and resolves when that save is done (when the one the timer already sent is done,
58
+ * if the timer was first). Resolves at once when nothing is held and nothing is on its way. Never rejects. A hold that outlasts
59
+ * `maxWaitMs` resolves it with the save still held: its timer sends it.
60
+ */
61
+ sendNow(): Promise<void>;
62
+ /** Whether a save is held. */
63
+ readonly isHeld: boolean;
64
+ }
65
+ export declare function createHeldAutosave(options: HeldAutosaveOptions): HeldAutosave;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The save that a canvas holds back for a few seconds after it has loaded.
3
+ *
4
+ * Opening a canvas draws its shapes one by one, and every one of them fires an event that looks like a change made by the person.
5
+ * For a few seconds after a load the creator therefore does not send a save at once (`isLoadCooldownActive` in `CreatorApp.svelte`):
6
+ * dropping it would lose a real edit made in those seconds, so it keeps the newest one and sends it when the canvas is quiet again.
7
+ * This module is that keeper. It was a timer and a variable in the component, and it had two faults that a person only meets when
8
+ * they change something in the first seconds:
9
+ *
10
+ * - **A save that goes through did not make the held one stale.** The held one was sent three seconds later all the same: a second
11
+ * request for one run of changes, and an older snapshot written after a newer one. {@link HeldAutosave.discard} is what a save
12
+ * that goes through calls, so the held one is forgotten.
13
+ * - **A page that asked for a save now waited for nothing.** `flush()` resolves when the canvas's own save has resolved, and a save
14
+ * that is held resolves at once: the page was told "saved" with the canvas still on the shelf. {@link HeldAutosave.sendNow} waits
15
+ * for the hold to end (a snapshot taken in the middle of a load can be half a canvas), sends the held save and resolves when the
16
+ * save is done.
17
+ *
18
+ * Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
19
+ */
20
+ /** How often {@link HeldAutosave.sendNow} looks again at whether the hold is over. */
21
+ const POLL_INTERVAL_MS = 50;
22
+ const realClock = {
23
+ now: () => Date.now(),
24
+ setTimer: (callback, delayMs) => setTimeout(callback, delayMs),
25
+ clearTimer: (handle) => clearTimeout(handle)
26
+ };
27
+ export function createHeldAutosave(options) {
28
+ const clock = options.clock ?? realClock;
29
+ const warn = options.warn ??
30
+ ((message, error) => {
31
+ if (error === undefined)
32
+ console.warn(message);
33
+ else
34
+ console.warn(message, error);
35
+ });
36
+ /** The newest save handed over while the hold was on, if no newer one has gone out since. */
37
+ let heldJson = null;
38
+ let timerHandle = null;
39
+ /** The save this keeper sent and that is not done yet. It never rejects. */
40
+ let sending = null;
41
+ function stopTimer() {
42
+ if (timerHandle === null)
43
+ return;
44
+ clock.clearTimer(timerHandle);
45
+ timerHandle = null;
46
+ }
47
+ /** Sends what is held, now, whatever the hold. Resolves when that save is done; with nothing held, when the one on its way is. */
48
+ function sendHeld() {
49
+ stopTimer();
50
+ const json = heldJson;
51
+ heldJson = null;
52
+ if (json === null)
53
+ return sending ?? Promise.resolve();
54
+ let outcome;
55
+ try {
56
+ outcome = Promise.resolve(options.send(json));
57
+ }
58
+ catch (error) {
59
+ warn('[heldAutosave] the held save failed', error);
60
+ return Promise.resolve();
61
+ }
62
+ const running = outcome
63
+ .then(() => undefined, (error) => warn('[heldAutosave] the held save failed', error))
64
+ .then(() => {
65
+ if (sending === running)
66
+ sending = null;
67
+ });
68
+ sending = running;
69
+ return running;
70
+ }
71
+ function hold(json) {
72
+ heldJson = json;
73
+ stopTimer();
74
+ timerHandle = clock.setTimer(() => {
75
+ timerHandle = null;
76
+ void sendHeld();
77
+ }, options.delayMs);
78
+ }
79
+ function discard() {
80
+ stopTimer();
81
+ heldJson = null;
82
+ }
83
+ async function sendNow() {
84
+ const startedAt = clock.now();
85
+ // The hold is waited out: the events a canvas fires while it loads look like changes, and a save taken in the middle of
86
+ // them can be half a canvas written over the whole one.
87
+ while (heldJson !== null && options.isHolding()) {
88
+ if (clock.now() - startedAt >= options.maxWaitMs) {
89
+ warn('[heldAutosave] the canvas is still loading: the save it holds goes out when the hold is over');
90
+ return;
91
+ }
92
+ await new Promise((resolve) => {
93
+ clock.setTimer(resolve, POLL_INTERVAL_MS);
94
+ });
95
+ }
96
+ if (heldJson !== null) {
97
+ await sendHeld();
98
+ }
99
+ else if (sending) {
100
+ await sending;
101
+ }
102
+ }
103
+ return {
104
+ hold,
105
+ discard,
106
+ sendNow,
107
+ get isHeld() {
108
+ return heldJson !== null;
109
+ }
110
+ };
111
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/creator",
3
- "version": "0.4.40",
3
+ "version": "0.4.41",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "peerDependencies": {