@widgetic/canvas 0.5.34 → 0.5.35
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/canvas/Canvas.svelte +99 -35
- package/dist/canvas/Canvas.svelte.d.ts +6 -1
- package/dist/canvas/autosaveScheduler.d.ts +58 -0
- package/dist/canvas/autosaveScheduler.js +157 -0
- package/dist/canvas/index.d.ts +2 -0
- package/dist/canvas/index.js +2 -0
- package/dist/canvas/toolbarPosition.d.ts +24 -0
- package/dist/canvas/toolbarPosition.js +37 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/package.json +1 -1
|
@@ -52,6 +52,8 @@
|
|
|
52
52
|
shouldTakeFocusBack
|
|
53
53
|
} from './eventScope';
|
|
54
54
|
import { installTextareaInShadowRoot } from './shadowRootText';
|
|
55
|
+
import { createAutosaveScheduler } from './autosaveScheduler';
|
|
56
|
+
import { toolbarPositionClasses, type ToolbarPosition } from './toolbarPosition';
|
|
55
57
|
import type { WidgetConversionPayload, StrokeRecognizer } from './types';
|
|
56
58
|
import { provideCanvasLanguage } from '../i18n/language.js';
|
|
57
59
|
import { makeShapeWords, setShapeWords, shapeWordsOf } from '../i18n/shapeWords.js';
|
|
@@ -183,6 +185,12 @@
|
|
|
183
185
|
// PanZoom Panel position: TL (top-left), TC (top-center), TR (top-right), BL, BC, BR
|
|
184
186
|
export let panZoomPosition: 'TL' | 'TC' | 'TR' | 'BL' | 'BC' | 'BR' = 'TC';
|
|
185
187
|
|
|
188
|
+
// Where the drawing toolbar stands along the bottom edge: BL (bottom-left), BC (bottom-center, the default) or BR.
|
|
189
|
+
// The selector bar that replaces the toolbar after the first generation stands in the same place. A host that has
|
|
190
|
+
// something of its own at the bottom centre of the page (Shopify's Sidekick) names the corner it wants. Anything
|
|
191
|
+
// that is not one of the three is the bottom centre.
|
|
192
|
+
export let toolbarPosition: ToolbarPosition = 'BC';
|
|
193
|
+
|
|
186
194
|
// Wireframe mode: hides color pickers in PropsPanel and enforces wireframe defaults
|
|
187
195
|
// (white fill, dark stroke) on all newly created objects
|
|
188
196
|
export let wireframeMode: boolean = true;
|
|
@@ -229,9 +237,12 @@
|
|
|
229
237
|
// destroys this component before the auto-save timer fires.
|
|
230
238
|
export let onBeforeUnmount: ((json: string | null) => void) | null = null;
|
|
231
239
|
|
|
232
|
-
// Callback fired
|
|
233
|
-
// Receives the serialized canvas JSON so the host doesn't need to call saveCanvas().
|
|
234
|
-
|
|
240
|
+
// Callback fired once the changes have been quiet for autosaveDelayMs (see the autosave buffer below), and when the
|
|
241
|
+
// host or the page asks to flush. Receives the serialized canvas JSON so the host doesn't need to call saveCanvas().
|
|
242
|
+
// May return a promise: while it is pending no second autosave starts, and what changes meanwhile goes out in one
|
|
243
|
+
// save after it, so a slow server is never flooded. A promise that rejects counts as a failed save (the changes stay
|
|
244
|
+
// unsaved until the next change or flush).
|
|
245
|
+
export let onAutoSave: ((json: string | null) => void | Promise<unknown>) | null = null;
|
|
235
246
|
|
|
236
247
|
// Delay in ms for the internal auto-save debounce.
|
|
237
248
|
// Controls how long Canvas waits after the last content modification before emitting onAutoSave.
|
|
@@ -239,8 +250,13 @@
|
|
|
239
250
|
// Lower = more frequent saves, higher = less API pressure. Default: 3000ms.
|
|
240
251
|
export let autosaveDelayMs: number = 3000;
|
|
241
252
|
|
|
253
|
+
// The longest a change waits before it is saved, however busy the person stays (a long stretch of drawing never
|
|
254
|
+
// leaves a quiet delay). A crash then costs at most this long. 0 means no limit. Default: 10000ms.
|
|
255
|
+
export let autosaveMaxWaitMs: number = 10000;
|
|
256
|
+
|
|
242
257
|
// While set, a due autosave waits another delay instead of serializing.
|
|
243
258
|
// Serializing during code generation blocks the page thread for the whole save.
|
|
259
|
+
// (Flushing, when the page is hidden or the editor closes, saves whatever the hold.)
|
|
244
260
|
export let suspendAutosave: boolean = false;
|
|
245
261
|
|
|
246
262
|
// Show a save button in the bottom-right corner of the canvas.
|
|
@@ -6378,8 +6394,8 @@
|
|
|
6378
6394
|
const unmountJson = saveCanvas();
|
|
6379
6395
|
onBeforeUnmount?.(unmountJson);
|
|
6380
6396
|
|
|
6381
|
-
//
|
|
6382
|
-
|
|
6397
|
+
// Stop the autosave buffer (the host was just given the final save above) and the history debounce timer
|
|
6398
|
+
autosaveScheduler.dispose();
|
|
6383
6399
|
if (_historyDebounceTimer) { clearTimeout(_historyDebounceTimer); _historyDebounceTimer = null; }
|
|
6384
6400
|
|
|
6385
6401
|
detachCanvasPointerHandlers();
|
|
@@ -10218,9 +10234,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
10218
10234
|
* Push the current canvas state onto the history stack.
|
|
10219
10235
|
* Call this AFTER each discrete user action that mutates objects.
|
|
10220
10236
|
* Is a no-op when called during a history restore (isRestoringHistory = true).
|
|
10221
|
-
* Also marks the canvas as dirty and
|
|
10237
|
+
* Also marks the canvas as dirty and tells the autosave buffer a change was made.
|
|
10222
10238
|
*/
|
|
10223
|
-
let _autoSaveTimer: ReturnType<typeof setTimeout> | null = null;
|
|
10224
10239
|
function takeHistorySnapshot(silent: boolean = false) {
|
|
10225
10240
|
if (isRestoringHistory || isCapturingHistory || !canvas) return;
|
|
10226
10241
|
const snapshot = captureHistorySnapshot();
|
|
@@ -10238,43 +10253,92 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
10238
10253
|
// Silent snapshots (e.g. initial empty canvas) only record history — no dirty flag or autosave
|
|
10239
10254
|
if (silent) return;
|
|
10240
10255
|
|
|
10241
|
-
// Mark dirty and
|
|
10256
|
+
// Mark dirty and tell the autosave buffer
|
|
10242
10257
|
_hasUnsavedChanges = true;
|
|
10243
10258
|
onCanvasDirty?.();
|
|
10244
|
-
|
|
10259
|
+
autosaveScheduler.markChanged();
|
|
10260
|
+
}
|
|
10261
|
+
|
|
10262
|
+
// ── Autosave buffer ──────────────────────────────────────────────────────
|
|
10263
|
+
// Every change goes through the scheduler, which is the buffer between the person editing and the server:
|
|
10264
|
+
// - a save starts after autosaveDelayMs of quiet (a trailing debounce, so a drag is one save, not fifty);
|
|
10265
|
+
// - a person who never pauses still gets a save every autosaveMaxWaitMs;
|
|
10266
|
+
// - a save waits while suspendAutosave is set (a code generation is running), however long that takes;
|
|
10267
|
+
// - one save at a time: while onAutoSave's promise is pending, what changes goes out in one save after it;
|
|
10268
|
+
// - flushAutosave() (and the page being hidden or closed) saves whatever is unsaved at once.
|
|
10269
|
+
const autosaveScheduler = createAutosaveScheduler({
|
|
10270
|
+
getDelayMs: () => autosaveDelayMs,
|
|
10271
|
+
getMaxWaitMs: () => autosaveMaxWaitMs,
|
|
10272
|
+
isSuspended: () => {
|
|
10273
|
+
if (suspendAutosave && import.meta.env.DEV) {
|
|
10274
|
+
fetch('http://localhost:3000/health?probe=autosave&status=deferred').catch(() => {});
|
|
10275
|
+
}
|
|
10276
|
+
return suspendAutosave;
|
|
10277
|
+
},
|
|
10278
|
+
save: runAutosave,
|
|
10279
|
+
onSaveFailed: (error) => {
|
|
10280
|
+
// The host's save failed: what it was meant to keep is unsaved again, and the next change or flush tries again.
|
|
10281
|
+
_hasUnsavedChanges = true;
|
|
10282
|
+
canvasWarn('Canvas: autosave failed, the changes stay unsaved until the next change', error);
|
|
10283
|
+
}
|
|
10284
|
+
});
|
|
10285
|
+
|
|
10286
|
+
/** One autosave: serializes the board and hands it to the host. Returns the host's promise, so the buffer keeps one save at a time. */
|
|
10287
|
+
function runAutosave(): void | Promise<unknown> {
|
|
10288
|
+
const json = saveCanvas();
|
|
10289
|
+
if (json === null) {
|
|
10290
|
+
// The board has nothing to give right now (it is still loading): nothing was saved, so ask the buffer for
|
|
10291
|
+
// another go a delay later rather than telling the host there is nothing.
|
|
10292
|
+
canvasLog('Canvas: autosave — the board cannot be serialized yet, trying again after the delay');
|
|
10293
|
+
autosaveScheduler.markChanged();
|
|
10294
|
+
return;
|
|
10295
|
+
}
|
|
10296
|
+
if (import.meta.env.DEV) {
|
|
10297
|
+
fetch('http://localhost:3000/health?probe=autosave&status=run').catch(() => {});
|
|
10298
|
+
}
|
|
10299
|
+
_hasUnsavedChanges = false;
|
|
10300
|
+
return onAutoSave?.(json);
|
|
10245
10301
|
}
|
|
10246
10302
|
|
|
10247
|
-
/**
|
|
10248
|
-
|
|
10249
|
-
|
|
10250
|
-
|
|
10251
|
-
|
|
10252
|
-
|
|
10253
|
-
|
|
10254
|
-
|
|
10255
|
-
}
|
|
10256
|
-
scheduleAutoSave();
|
|
10257
|
-
return;
|
|
10258
|
-
}
|
|
10259
|
-
if (import.meta.env.DEV) {
|
|
10260
|
-
fetch('http://localhost:3000/health?probe=autosave&status=run').catch(() => {});
|
|
10261
|
-
}
|
|
10262
|
-
const json = saveCanvas();
|
|
10263
|
-
onAutoSave?.(json);
|
|
10264
|
-
_hasUnsavedChanges = false;
|
|
10265
|
-
}, autosaveDelayMs);
|
|
10303
|
+
/**
|
|
10304
|
+
* Saves whatever the buffer still holds, now, whatever the delay and the hold. Resolves once the host's save is
|
|
10305
|
+
* done (after the one that was already on its way, so two never overlap). A host calls it before it leaves the
|
|
10306
|
+
* editor (a Back button, Publish) so that the last seconds of work are not lost to the delay; nothing is saved
|
|
10307
|
+
* when nothing changed.
|
|
10308
|
+
*/
|
|
10309
|
+
export function flushAutosave(): Promise<void> {
|
|
10310
|
+
return autosaveScheduler.flush();
|
|
10266
10311
|
}
|
|
10267
10312
|
|
|
10268
10313
|
/** Force an immediate save (used by Cmd+S, the save button, and host post-replace flushes). */
|
|
10269
10314
|
export function saveNow() {
|
|
10270
|
-
|
|
10271
|
-
|
|
10315
|
+
// What the buffer was waiting to save is in this save.
|
|
10316
|
+
autosaveScheduler.cancel();
|
|
10272
10317
|
const json = saveCanvas();
|
|
10273
10318
|
onAutoSave?.(json);
|
|
10274
10319
|
_hasUnsavedChanges = false;
|
|
10275
10320
|
canvasLog('Canvas: manual save triggered');
|
|
10276
10321
|
}
|
|
10277
10322
|
|
|
10323
|
+
// The page goes away (the tab is closed or reloaded, the browser is put in the background, a phone is locked): save
|
|
10324
|
+
// what is unsaved now instead of after the delay. The hold of suspendAutosave does not apply, a save is better than
|
|
10325
|
+
// losing the last stretch of work. The host's own save is started here; whether the browser lets it finish is the
|
|
10326
|
+
// browser's call, which is why a host keeps its own local copy too.
|
|
10327
|
+
onMount(() => {
|
|
10328
|
+
function flushWhenPageIsLeft() {
|
|
10329
|
+
void autosaveScheduler.flush();
|
|
10330
|
+
}
|
|
10331
|
+
function flushWhenPageIsHidden() {
|
|
10332
|
+
if (document.visibilityState === 'hidden') flushWhenPageIsLeft();
|
|
10333
|
+
}
|
|
10334
|
+
window.addEventListener('pagehide', flushWhenPageIsLeft);
|
|
10335
|
+
document.addEventListener('visibilitychange', flushWhenPageIsHidden);
|
|
10336
|
+
return () => {
|
|
10337
|
+
window.removeEventListener('pagehide', flushWhenPageIsLeft);
|
|
10338
|
+
document.removeEventListener('visibilitychange', flushWhenPageIsHidden);
|
|
10339
|
+
};
|
|
10340
|
+
});
|
|
10341
|
+
|
|
10278
10342
|
// Debounced version of takeHistorySnapshot — used in continuous slider handlers
|
|
10279
10343
|
// (stroke width, roundness, etc.) to avoid serializing the canvas on every input event.
|
|
10280
10344
|
// Fires once 500 ms after the last call, capturing the final slider value.
|
|
@@ -10363,7 +10427,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
10363
10427
|
await restoreHistorySnapshot(historyStack[historyIndex]);
|
|
10364
10428
|
_hasUnsavedChanges = true;
|
|
10365
10429
|
onCanvasDirty?.();
|
|
10366
|
-
|
|
10430
|
+
autosaveScheduler.markChanged();
|
|
10367
10431
|
}
|
|
10368
10432
|
|
|
10369
10433
|
/** Redo the previously undone action. No-op if at the newest state. */
|
|
@@ -10374,7 +10438,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
10374
10438
|
await restoreHistorySnapshot(historyStack[historyIndex]);
|
|
10375
10439
|
_hasUnsavedChanges = true;
|
|
10376
10440
|
onCanvasDirty?.();
|
|
10377
|
-
|
|
10441
|
+
autosaveScheduler.markChanged();
|
|
10378
10442
|
}
|
|
10379
10443
|
|
|
10380
10444
|
/** Serialize the current canvas state to a JSON string */
|
|
@@ -10596,7 +10660,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
10596
10660
|
}
|
|
10597
10661
|
|
|
10598
10662
|
// Cancel any pending autosave from previous operations (e.g. loadCanvas)
|
|
10599
|
-
|
|
10663
|
+
autosaveScheduler.cancel();
|
|
10600
10664
|
|
|
10601
10665
|
// clear the entire canvas
|
|
10602
10666
|
canvas.clear();
|
|
@@ -13044,7 +13108,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
13044
13108
|
|
|
13045
13109
|
<!-- Drawing toolbar. After the first generation the host hides it and the selector bar below takes this spot. -->
|
|
13046
13110
|
{#if showDrawingTools}
|
|
13047
|
-
<CanvasToolbar class="
|
|
13111
|
+
<CanvasToolbar class="{toolbarPositionClasses(toolbarPosition)} max-w-[calc(100%-1rem)] {isCanvasLoading ? 'pointer-events-none opacity-60 transition-opacity duration-200' : 'transition-opacity duration-200'}"
|
|
13048
13112
|
{activeTool}
|
|
13049
13113
|
{onSelectSelectTool}
|
|
13050
13114
|
{onSelectEraseTool}
|
|
@@ -13086,7 +13150,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
|
|
|
13086
13150
|
/>
|
|
13087
13151
|
{/if}
|
|
13088
13152
|
{#if !showDrawingTools && showElementSelector}
|
|
13089
|
-
<div class="widget-selector-bar
|
|
13153
|
+
<div class="widget-selector-bar {toolbarPositionClasses(toolbarPosition)} z-20 flex h-12 w-max flex-nowrap items-center justify-center gap-1.5 whitespace-nowrap rounded-full border border-neutral-200 bg-white px-4 shadow-md">
|
|
13090
13154
|
<button
|
|
13091
13155
|
class="selector-bt flex items-center justify-center rounded-lg focus:outline-none focus-visible:outline-none {elementSelectorActive ? 'selector-bt-open h-7 w-7 bg-[#314F2F]' : 'h-9 w-9 bg-transparent text-neutral-700'}"
|
|
13092
13156
|
onclick={() => onToggleElementSelector?.()}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Canvas } from 'fabric';
|
|
2
|
+
import { type ToolbarPosition } from './toolbarPosition';
|
|
2
3
|
import type { WidgetConversionPayload, StrokeRecognizer } from './types';
|
|
3
4
|
interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {
|
|
4
5
|
new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & {
|
|
@@ -34,6 +35,7 @@ declare const Canvas: $$__sveltets_2_IsomorphicComponent<{
|
|
|
34
35
|
metadata: Record<string, any>;
|
|
35
36
|
}) => void) | null;
|
|
36
37
|
panZoomPosition?: "TL" | "TC" | "TR" | "BL" | "BC" | "BR";
|
|
38
|
+
toolbarPosition?: ToolbarPosition;
|
|
37
39
|
wireframeMode?: boolean;
|
|
38
40
|
advancedFeatures?: boolean;
|
|
39
41
|
/** The element selector on the toolbar. The host owns whether it is on. */ showElementSelector?: boolean;
|
|
@@ -55,8 +57,9 @@ declare const Canvas: $$__sveltets_2_IsomorphicComponent<{
|
|
|
55
57
|
onReady?: (() => void) | null;
|
|
56
58
|
isExternalDataLoading?: boolean;
|
|
57
59
|
onBeforeUnmount?: ((json: string | null) => void) | null;
|
|
58
|
-
onAutoSave?: ((json: string | null) => void) | null;
|
|
60
|
+
onAutoSave?: ((json: string | null) => void | Promise<unknown>) | null;
|
|
59
61
|
autosaveDelayMs?: number;
|
|
62
|
+
autosaveMaxWaitMs?: number;
|
|
60
63
|
suspendAutosave?: boolean;
|
|
61
64
|
showSaveButton?: boolean;
|
|
62
65
|
onCanvasDirty?: (() => void) | null;
|
|
@@ -165,6 +168,7 @@ declare const Canvas: $$__sveltets_2_IsomorphicComponent<{
|
|
|
165
168
|
onUngroupSelection?: () => void;
|
|
166
169
|
onSelectAllObjects?: () => void;
|
|
167
170
|
onDeselectAllObjects?: () => void;
|
|
171
|
+
flushAutosave?: () => Promise<void>;
|
|
168
172
|
saveNow?: () => void;
|
|
169
173
|
undo?: () => Promise<void>;
|
|
170
174
|
redo?: () => Promise<void>;
|
|
@@ -264,6 +268,7 @@ declare const Canvas: $$__sveltets_2_IsomorphicComponent<{
|
|
|
264
268
|
onUngroupSelection: () => void;
|
|
265
269
|
onSelectAllObjects: () => void;
|
|
266
270
|
onDeselectAllObjects: () => void;
|
|
271
|
+
flushAutosave: () => Promise<void>;
|
|
267
272
|
saveNow: () => void;
|
|
268
273
|
undo: () => Promise<void>;
|
|
269
274
|
redo: () => Promise<void>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The buffer between a person who edits the board and the server that keeps it.
|
|
3
|
+
*
|
|
4
|
+
* A save is not made at every change: a drag, a run of nudges or a long stretch of drawing would send the whole board
|
|
5
|
+
* to the server fifty times. The scheduler keeps the rule in one place:
|
|
6
|
+
*
|
|
7
|
+
* - a save starts after a **quiet delay** since the last change (a trailing debounce), so a burst is one save;
|
|
8
|
+
* - a person who never pauses still gets a save every **longest wait**, so a crash costs seconds, not minutes;
|
|
9
|
+
* - a save is **held back** while the host asks for it (a code generation makes the page thread busy), for as long as
|
|
10
|
+
* the host asks, however long that is;
|
|
11
|
+
* - **one save at a time**: when a save is still on its way at the moment the next one is due, the next waits for it
|
|
12
|
+
* and everything that changed meanwhile goes out in a single save after it. A slow server is never flooded;
|
|
13
|
+
* - **flush** sends whatever is unsaved at once, whatever the delay and the hold, for the moments a page is about to
|
|
14
|
+
* go (the tab goes to the background, the page is hidden, the editor closes);
|
|
15
|
+
* - a save that fails leaves the changes unsaved and says so, and **does not try again by itself**: the next change, or
|
|
16
|
+
* the next flush, is the retry. A server that is down is not hammered.
|
|
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 scheduler reads and sets timers with. Tests pass one they move by hand. */
|
|
21
|
+
export interface AutosaveClock {
|
|
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 AutosaveSchedulerOptions {
|
|
29
|
+
/** The quiet time after the last change before a save starts, in milliseconds. Read at every change. */
|
|
30
|
+
getDelayMs: () => number;
|
|
31
|
+
/** The longest a change waits before a save starts, however busy the person stays. 0 means no limit. Read at every change. */
|
|
32
|
+
getMaxWaitMs: () => number;
|
|
33
|
+
/**
|
|
34
|
+
* Makes the save. It may return a promise: while that is pending, no second save starts. A save that throws or
|
|
35
|
+
* rejects counts as failed. A save that finds it has nothing to save yet (the board is still loading) calls
|
|
36
|
+
* {@link AutosaveScheduler.markChanged} again to ask for another go a delay later.
|
|
37
|
+
*/
|
|
38
|
+
save: () => void | Promise<unknown>;
|
|
39
|
+
/** True while the host wants saves to wait. A save that falls due then looks again a delay later. */
|
|
40
|
+
isSuspended?: () => boolean;
|
|
41
|
+
/** Told when a save failed. The changes stay unsaved. */
|
|
42
|
+
onSaveFailed?: (error: unknown) => void;
|
|
43
|
+
/** Defaults to the real one. */
|
|
44
|
+
clock?: AutosaveClock;
|
|
45
|
+
}
|
|
46
|
+
export interface AutosaveScheduler {
|
|
47
|
+
/** Something changed that is not saved: starts (or restarts) the quiet delay. */
|
|
48
|
+
markChanged(): void;
|
|
49
|
+
/** Saves whatever is unsaved now, after a save that is on its way, whatever the delay and the hold. Resolves once it is done. Never rejects. */
|
|
50
|
+
flush(): Promise<void>;
|
|
51
|
+
/** Forgets what is unsaved, and the time it has waited: the board was just loaded, so what is on it is what is saved. A save on its way is left alone. */
|
|
52
|
+
cancel(): void;
|
|
53
|
+
/** Stops for good: nothing is saved afterwards. */
|
|
54
|
+
dispose(): void;
|
|
55
|
+
/** Whether something changed that no save has taken yet. */
|
|
56
|
+
readonly isDirty: boolean;
|
|
57
|
+
}
|
|
58
|
+
export declare function createAutosaveScheduler(options: AutosaveSchedulerOptions): AutosaveScheduler;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The buffer between a person who edits the board and the server that keeps it.
|
|
3
|
+
*
|
|
4
|
+
* A save is not made at every change: a drag, a run of nudges or a long stretch of drawing would send the whole board
|
|
5
|
+
* to the server fifty times. The scheduler keeps the rule in one place:
|
|
6
|
+
*
|
|
7
|
+
* - a save starts after a **quiet delay** since the last change (a trailing debounce), so a burst is one save;
|
|
8
|
+
* - a person who never pauses still gets a save every **longest wait**, so a crash costs seconds, not minutes;
|
|
9
|
+
* - a save is **held back** while the host asks for it (a code generation makes the page thread busy), for as long as
|
|
10
|
+
* the host asks, however long that is;
|
|
11
|
+
* - **one save at a time**: when a save is still on its way at the moment the next one is due, the next waits for it
|
|
12
|
+
* and everything that changed meanwhile goes out in a single save after it. A slow server is never flooded;
|
|
13
|
+
* - **flush** sends whatever is unsaved at once, whatever the delay and the hold, for the moments a page is about to
|
|
14
|
+
* go (the tab goes to the background, the page is hidden, the editor closes);
|
|
15
|
+
* - a save that fails leaves the changes unsaved and says so, and **does not try again by itself**: the next change, or
|
|
16
|
+
* the next flush, is the retry. A server that is down is not hammered.
|
|
17
|
+
*
|
|
18
|
+
* Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
|
|
19
|
+
*/
|
|
20
|
+
/** The shortest time a save that is held back waits before the host is asked again, so that a delay of 0 does not spin. */
|
|
21
|
+
const SHORTEST_RECHECK_DELAY_MS = 250;
|
|
22
|
+
const realClock = {
|
|
23
|
+
now: () => Date.now(),
|
|
24
|
+
setTimer: (callback, delayMs) => setTimeout(callback, delayMs),
|
|
25
|
+
clearTimer: (handle) => clearTimeout(handle)
|
|
26
|
+
};
|
|
27
|
+
/** A number a host passed as a duration: anything that is not a finite number of at least 0 is 0. */
|
|
28
|
+
function toDurationMs(value) {
|
|
29
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
30
|
+
}
|
|
31
|
+
function isPromiseLike(value) {
|
|
32
|
+
return !!value && typeof value.then === 'function';
|
|
33
|
+
}
|
|
34
|
+
export function createAutosaveScheduler(options) {
|
|
35
|
+
const clock = options.clock ?? realClock;
|
|
36
|
+
/** Something changed that no save has taken yet. */
|
|
37
|
+
let dirty = false;
|
|
38
|
+
/** When the first change that no save has taken yet was made: where the longest wait is counted from. */
|
|
39
|
+
let firstChangeAt = null;
|
|
40
|
+
let timerHandle = null;
|
|
41
|
+
/** The save that is on its way, if there is one. It never rejects. */
|
|
42
|
+
let saveOnItsWay = null;
|
|
43
|
+
/** The next save fell due while another was on its way: it starts as soon as that one is done. */
|
|
44
|
+
let dueWhileSaving = false;
|
|
45
|
+
let disposed = false;
|
|
46
|
+
function stopTimer() {
|
|
47
|
+
if (timerHandle === null)
|
|
48
|
+
return;
|
|
49
|
+
clock.clearTimer(timerHandle);
|
|
50
|
+
timerHandle = null;
|
|
51
|
+
}
|
|
52
|
+
function startTimer(waitMs) {
|
|
53
|
+
stopTimer();
|
|
54
|
+
timerHandle = clock.setTimer(onTimerFired, Math.max(0, waitMs));
|
|
55
|
+
}
|
|
56
|
+
function onTimerFired() {
|
|
57
|
+
timerHandle = null;
|
|
58
|
+
if (disposed)
|
|
59
|
+
return;
|
|
60
|
+
if (saveOnItsWay) {
|
|
61
|
+
// One save at a time: this one starts when the one on its way is done.
|
|
62
|
+
dueWhileSaving = true;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
saveUnlessHeldBack();
|
|
66
|
+
}
|
|
67
|
+
/** Starts the save, or, when the host holds saves back, looks again a delay later. */
|
|
68
|
+
function saveUnlessHeldBack() {
|
|
69
|
+
if (options.isSuspended?.()) {
|
|
70
|
+
startTimer(Math.max(toDurationMs(options.getDelayMs()), SHORTEST_RECHECK_DELAY_MS));
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
void startSave();
|
|
74
|
+
}
|
|
75
|
+
function noteFailure(error) {
|
|
76
|
+
// What the failed save was meant to keep is not kept: it is unsaved again, and the next change or flush tries again.
|
|
77
|
+
dirty = true;
|
|
78
|
+
try {
|
|
79
|
+
options.onSaveFailed?.(error);
|
|
80
|
+
}
|
|
81
|
+
catch (reportError) {
|
|
82
|
+
console.warn('[autosave] onSaveFailed threw', reportError);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Takes everything unsaved into a save, now. The promise it returns never rejects and settles when the save is done. */
|
|
86
|
+
function startSave() {
|
|
87
|
+
stopTimer();
|
|
88
|
+
// What is unsaved goes into this save. Anything that changes from here on (a save that asks for another go, a change
|
|
89
|
+
// made while the save is on its way) is unsaved again, and is the next save's.
|
|
90
|
+
dirty = false;
|
|
91
|
+
firstChangeAt = null;
|
|
92
|
+
let outcome;
|
|
93
|
+
try {
|
|
94
|
+
outcome = options.save();
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
noteFailure(error);
|
|
98
|
+
return Promise.resolve();
|
|
99
|
+
}
|
|
100
|
+
if (!isPromiseLike(outcome))
|
|
101
|
+
return Promise.resolve();
|
|
102
|
+
const running = Promise.resolve(outcome)
|
|
103
|
+
.then(() => undefined, (error) => noteFailure(error))
|
|
104
|
+
.then(() => {
|
|
105
|
+
if (saveOnItsWay === running)
|
|
106
|
+
saveOnItsWay = null;
|
|
107
|
+
if (disposed)
|
|
108
|
+
return;
|
|
109
|
+
if (dueWhileSaving && dirty) {
|
|
110
|
+
dueWhileSaving = false;
|
|
111
|
+
saveUnlessHeldBack();
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
saveOnItsWay = running;
|
|
115
|
+
return running;
|
|
116
|
+
}
|
|
117
|
+
function markChanged() {
|
|
118
|
+
if (disposed)
|
|
119
|
+
return;
|
|
120
|
+
const now = clock.now();
|
|
121
|
+
dirty = true;
|
|
122
|
+
if (firstChangeAt === null)
|
|
123
|
+
firstChangeAt = now;
|
|
124
|
+
const quietUntil = now + toDurationMs(options.getDelayMs());
|
|
125
|
+
const longestWait = toDurationMs(options.getMaxWaitMs());
|
|
126
|
+
const dueAt = longestWait > 0 ? Math.min(quietUntil, firstChangeAt + longestWait) : quietUntil;
|
|
127
|
+
startTimer(dueAt - now);
|
|
128
|
+
}
|
|
129
|
+
async function flush() {
|
|
130
|
+
// A save on its way finishes first, so that two never overlap.
|
|
131
|
+
while (saveOnItsWay)
|
|
132
|
+
await saveOnItsWay;
|
|
133
|
+
// Nothing changed since the last save (or the last failure left nothing unsaved): there is nothing to send.
|
|
134
|
+
if (disposed || !dirty)
|
|
135
|
+
return;
|
|
136
|
+
await startSave();
|
|
137
|
+
}
|
|
138
|
+
function cancel() {
|
|
139
|
+
stopTimer();
|
|
140
|
+
dirty = false;
|
|
141
|
+
firstChangeAt = null;
|
|
142
|
+
dueWhileSaving = false;
|
|
143
|
+
}
|
|
144
|
+
function dispose() {
|
|
145
|
+
cancel();
|
|
146
|
+
disposed = true;
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
markChanged,
|
|
150
|
+
flush,
|
|
151
|
+
cancel,
|
|
152
|
+
dispose,
|
|
153
|
+
get isDirty() {
|
|
154
|
+
return dirty;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
package/dist/canvas/index.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export { default as ContextMenu } from './ContextMenu.svelte';
|
|
|
10
10
|
export { default as PanZoomPanel } from './PanZoomPanel.svelte';
|
|
11
11
|
export { default as PropsPanel } from './props-panel/PropsPanel.svelte';
|
|
12
12
|
export type { WidgetConversionPayload } from './types';
|
|
13
|
+
export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './toolbarPosition';
|
|
14
|
+
export type { ToolbarPosition } from './toolbarPosition';
|
|
13
15
|
export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
|
|
14
16
|
export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
|
|
15
17
|
export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
|
package/dist/canvas/index.js
CHANGED
|
@@ -9,6 +9,8 @@ export { default as CanvasToolbar } from './CanvasToolbar.svelte';
|
|
|
9
9
|
export { default as ContextMenu } from './ContextMenu.svelte';
|
|
10
10
|
export { default as PanZoomPanel } from './PanZoomPanel.svelte';
|
|
11
11
|
export { default as PropsPanel } from './props-panel/PropsPanel.svelte';
|
|
12
|
+
// Where the drawing toolbar stands along the bottom edge of the board (the `toolbarPosition` option of <Canvas>)
|
|
13
|
+
export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './toolbarPosition';
|
|
12
14
|
export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
|
|
13
15
|
export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
|
|
14
16
|
export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the drawing toolbar stands along the bottom edge of the board.
|
|
3
|
+
*
|
|
4
|
+
* The toolbar has always been at the bottom centre. A host that has something of its own there (Shopify's Sidekick
|
|
5
|
+
* sits in the same spot, a partner may have a cookie bar or a chat bubble) names the corner it wants with the
|
|
6
|
+
* `toolbarPosition` option instead. The selector bar that replaces the toolbar after the first generation stands in the
|
|
7
|
+
* same place, so the two never jump around when one takes over from the other.
|
|
8
|
+
*
|
|
9
|
+
* Kept free of Svelte and of the DOM so that Node can test it.
|
|
10
|
+
*/
|
|
11
|
+
/** The places the toolbar can stand: the bottom left, the bottom centre and the bottom right of the board. */
|
|
12
|
+
export declare const TOOLBAR_POSITIONS: readonly ["BL", "BC", "BR"];
|
|
13
|
+
/** One of {@link TOOLBAR_POSITIONS}. */
|
|
14
|
+
export type ToolbarPosition = (typeof TOOLBAR_POSITIONS)[number];
|
|
15
|
+
/** Where the toolbar stands when the host says nothing: the bottom centre, as it always did. */
|
|
16
|
+
export declare const DEFAULT_TOOLBAR_POSITION: ToolbarPosition;
|
|
17
|
+
/**
|
|
18
|
+
* The position to use for what a host passed. Anything that is not one of the three (a corner at the top, a word in
|
|
19
|
+
* lower case, nothing at all) is the default, so that a mistake in the host's option never takes the toolbar off the
|
|
20
|
+
* board.
|
|
21
|
+
*/
|
|
22
|
+
export declare function normalizeToolbarPosition(value: unknown): ToolbarPosition;
|
|
23
|
+
/** The classes that put the toolbar (or the selector bar) where the host asked, on the line it has always been on. */
|
|
24
|
+
export declare function toolbarPositionClasses(value: unknown): string;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the drawing toolbar stands along the bottom edge of the board.
|
|
3
|
+
*
|
|
4
|
+
* The toolbar has always been at the bottom centre. A host that has something of its own there (Shopify's Sidekick
|
|
5
|
+
* sits in the same spot, a partner may have a cookie bar or a chat bubble) names the corner it wants with the
|
|
6
|
+
* `toolbarPosition` option instead. The selector bar that replaces the toolbar after the first generation stands in the
|
|
7
|
+
* same place, so the two never jump around when one takes over from the other.
|
|
8
|
+
*
|
|
9
|
+
* Kept free of Svelte and of the DOM so that Node can test it.
|
|
10
|
+
*/
|
|
11
|
+
/** The places the toolbar can stand: the bottom left, the bottom centre and the bottom right of the board. */
|
|
12
|
+
export const TOOLBAR_POSITIONS = ['BL', 'BC', 'BR'];
|
|
13
|
+
/** Where the toolbar stands when the host says nothing: the bottom centre, as it always did. */
|
|
14
|
+
export const DEFAULT_TOOLBAR_POSITION = 'BC';
|
|
15
|
+
/**
|
|
16
|
+
* The classes that put the toolbar in place. Written out in full, so that the stylesheet of a page that installs the
|
|
17
|
+
* canvas picks every one of them up when it reads this file.
|
|
18
|
+
*/
|
|
19
|
+
const TOOLBAR_POSITION_CLASSES = {
|
|
20
|
+
// rtl-ok: the page names a corner of the screen, as it is drawn
|
|
21
|
+
BL: 'absolute bottom-1 left-2',
|
|
22
|
+
BC: 'absolute bottom-1 left-1/2 -translate-x-1/2',
|
|
23
|
+
// rtl-ok: the page names a corner of the screen, as it is drawn
|
|
24
|
+
BR: 'absolute bottom-1 right-2'
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The position to use for what a host passed. Anything that is not one of the three (a corner at the top, a word in
|
|
28
|
+
* lower case, nothing at all) is the default, so that a mistake in the host's option never takes the toolbar off the
|
|
29
|
+
* board.
|
|
30
|
+
*/
|
|
31
|
+
export function normalizeToolbarPosition(value) {
|
|
32
|
+
return TOOLBAR_POSITIONS.includes(value) ? value : DEFAULT_TOOLBAR_POSITION;
|
|
33
|
+
}
|
|
34
|
+
/** The classes that put the toolbar (or the selector bar) where the host asked, on the line it has always been on. */
|
|
35
|
+
export function toolbarPositionClasses(value) {
|
|
36
|
+
return TOOLBAR_POSITION_CLASSES[normalizeToolbarPosition(value)];
|
|
37
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
*/
|
|
9
9
|
export { Canvas, CanvasToolbar, ContextMenu, PanZoomPanel, PropsPanel } from './canvas';
|
|
10
10
|
export type { WidgetConversionPayload, StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './canvas';
|
|
11
|
+
export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './canvas';
|
|
12
|
+
export type { ToolbarPosition } from './canvas';
|
|
11
13
|
export { setShapeImageStore, getShapeImageStore } from './canvas';
|
|
12
14
|
export type { ShapeImageStore } from './canvas';
|
|
13
15
|
export { Tooltip, ColorIC, FontSelectorIC, SliderUnitIC, TextAlignIC, TextStyleIC } from './components';
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
*/
|
|
9
9
|
// Canvas (heavy — dynamic import recommended)
|
|
10
10
|
export { Canvas, CanvasToolbar, ContextMenu, PanZoomPanel, PropsPanel } from './canvas';
|
|
11
|
+
// Where the drawing toolbar stands along the bottom edge of the board (the `toolbarPosition` option of <Canvas>)
|
|
12
|
+
export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './canvas';
|
|
11
13
|
// Widget thumbnails live outside the canvas JSON when the host installs a store
|
|
12
14
|
export { setShapeImageStore, getShapeImageStore } from './canvas';
|
|
13
15
|
// Lightweight components (safe for static import)
|