@widgetic/canvas 0.5.38 → 0.5.39

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 (44) hide show
  1. package/README.md +5 -0
  2. package/dist/canvas/DomCanvas.svelte +26 -5
  3. package/dist/canvas/DomCanvas.svelte.d.ts +5 -0
  4. package/dist/canvas/autosaveScheduler.d.ts +10 -2
  5. package/dist/canvas/autosaveScheduler.js +31 -5
  6. package/dist/canvas/boardSurface.d.ts +5 -1
  7. package/dist/canvas/boardSurface.js +5 -1
  8. package/dist/canvas/chromeLayout.js +3 -1
  9. package/dist/canvas/host/CanvasHost.d.ts +32 -1
  10. package/dist/canvas/host/CanvasHost.js +124 -10
  11. package/dist/canvas/outsideClickDeselect.d.ts +5 -0
  12. package/dist/canvas/outsideClickDeselect.js +25 -0
  13. package/dist/canvas/preferredTextFont.d.ts +7 -1
  14. package/dist/canvas/preferredTextFont.js +26 -2
  15. package/dist/canvas/ui/CanvasHint.svelte +2 -2
  16. package/dist/canvas/ui/CanvasToolbar.svelte +1 -0
  17. package/dist/canvas/ui/ColorField.svelte +1 -0
  18. package/dist/canvas/ui/SelectionPanel.svelte +58 -23
  19. package/dist/canvas/ui/SelectorBar.svelte +5 -3
  20. package/dist/canvas/ui/sizeLabelVisibility.d.ts +13 -0
  21. package/dist/canvas/ui/sizeLabelVisibility.js +15 -0
  22. package/dist/canvas/view/SelectionOverlay.svelte +11 -1
  23. package/dist/components/CanvasBoardPlaceholder.svelte.d.ts +1 -1
  24. package/dist/engine/EngineCore.d.ts +19 -2
  25. package/dist/engine/EngineCore.js +51 -7
  26. package/dist/engine/core/defaults.d.ts +1 -1
  27. package/dist/engine/core/defaults.js +1 -1
  28. package/dist/engine/core/shapeTools.d.ts +16 -6
  29. package/dist/engine/core/shapeTools.js +8 -6
  30. package/dist/engine/input/gestures.js +3 -2
  31. package/dist/engine/text/layoutText.d.ts +1 -2
  32. package/dist/engine/text/layoutText.js +2 -4
  33. package/dist/engine/text/textMetrics.d.ts +19 -0
  34. package/dist/engine/text/textMetrics.js +24 -0
  35. package/dist/fonts/interFont.d.ts +5 -0
  36. package/dist/fonts/interFont.js +31 -0
  37. package/dist/fonts/workspaceFonts.d.ts +12 -0
  38. package/dist/fonts/workspaceFonts.js +51 -0
  39. package/dist/i18n/language.d.ts +3 -3
  40. package/dist/i18n/messages.d.ts +3 -0
  41. package/dist/i18n/messages.js +3 -0
  42. package/dist/settings/workspaceToolSettings.d.ts +45 -0
  43. package/dist/settings/workspaceToolSettings.js +90 -0
  44. package/package.json +3 -3
package/README.md CHANGED
@@ -191,6 +191,11 @@ that shape when the geometry is confident (a stroke it cannot decide is handed t
191
191
  The package constant `CANVAS_SHAPE_SNAP_ENABLED` stays `false`: it is the one line that turns the snap on for every page, or
192
192
  back off.
193
193
 
194
+ **Keep the drawing centred when the board is resized (off by default).** A page that lets its person drag the edges of the
195
+ board passes `keepCenterOnResize={true}` on `<Canvas>`: when the board grows or shrinks, the pan moves by half of the change
196
+ in size, so the drawing that was in the middle stays in the middle (the zoom does not change). Without it the top-left corner
197
+ of the board stays where it was, as before.
198
+
194
199
  [`__docs/dom-canvas.md`](./__docs/dom-canvas.md) explains the parts, the host contract, the document, the tools and the
195
200
  tests. The engine this one replaced is gone from the package, with no fallback to it: no dependency, no reader for its saved
196
201
  files, and no document about it. Its specs and progress log are only in the git history (`git show d824044:__specs/<file>`).
@@ -25,6 +25,7 @@
25
25
  import { onlyCardIsSelected } from '../engine/widgets.js';
26
26
  import { provideCanvasLanguage } from '../i18n/language.js';
27
27
  import { BOARD_FRAME_CLASSES } from './boardFrame.js';
28
+ import { BOARD_SURFACE_COLOR } from './boardSurface.js';
28
29
  import { CanvasHost, DEFAULT_HOST_PROPS } from './host/CanvasHost.js';
29
30
  import type { CanvasHostProps, SelectorGuide } from './host/CanvasHost.js';
30
31
  import { forwardToHost } from './host/CanvasHostApi.js';
@@ -113,8 +114,8 @@
113
114
  // Callback fired once the changes have been quiet for autosaveDelayMs, and when the host or the page asks to flush.
114
115
  // Receives the serialized canvas JSON so the host doesn't need to call saveCanvas().
115
116
  // May return a promise: while it is pending no second autosave starts, and what changes meanwhile goes out in one
116
- // save after it, so a slow server is never flooded. A promise that rejects counts as a failed save (the changes stay
117
- // unsaved until the next change or flush).
117
+ // save after it, so a slow server is never flooded. A promise that rejects counts as a failed save: the changes stay
118
+ // unsaved, and the canvas asks again after the waits of autosaveRetryDelaysMs (a change or a flush asks too).
118
119
  export let onAutoSave: CanvasHostProps['onAutoSave'] = DEFAULT_HOST_PROPS.onAutoSave;
119
120
 
120
121
  // Delay in ms for the internal auto-save debounce: how long the canvas waits after the last change before onAutoSave.
@@ -124,6 +125,11 @@
124
125
  // The longest a change waits before it is saved, however busy the person stays. 0 means no limit. Default: 10000ms.
125
126
  export let autosaveMaxWaitMs: CanvasHostProps['autosaveMaxWaitMs'] = DEFAULT_HOST_PROPS.autosaveMaxWaitMs;
126
127
 
128
+ // After onAutoSave fails, the waits (ms) before each new try: the first after the first failure, the second after the
129
+ // second in a row, and so on. When they are used up the trying stops until the next change or flush. An empty list
130
+ // means no retry by itself. Default: 5, 10, 20, 40 and 60 seconds.
131
+ export let autosaveRetryDelaysMs: CanvasHostProps['autosaveRetryDelaysMs'] = DEFAULT_HOST_PROPS.autosaveRetryDelaysMs;
132
+
127
133
  // While set, a due autosave waits another delay instead of serializing.
128
134
  // (Flushing, when the page is hidden or the editor closes, saves whatever the hold.)
129
135
  export let suspendAutosave: CanvasHostProps['suspendAutosave'] = DEFAULT_HOST_PROPS.suspendAutosave;
@@ -184,6 +190,15 @@
184
190
  * becomes that shape. Off unless a page passes true: the package's own flag turns it on for every page.
185
191
  */
186
192
  export let shapeSnap: CanvasHostProps['shapeSnap'] = DEFAULT_HOST_PROPS.shapeSnap;
193
+ /** The drawing stays centred when the board is resized (a page that lets its person drag the edges). Off unless a page passes true. */
194
+ export let keepCenterOnResize: CanvasHostProps['keepCenterOnResize'] = DEFAULT_HOST_PROPS.keepCenterOnResize;
195
+
196
+ /** Workspace id for persisted tool settings (B16). */
197
+ export let workspaceId: CanvasHostProps['workspaceId'] = DEFAULT_HOST_PROPS.workspaceId;
198
+ /** Optional user id when the host distinguishes users inside one workspace embed. */
199
+ export let userId: CanvasHostProps['userId'] = DEFAULT_HOST_PROPS.userId;
200
+ /** Brand-kit fonts for this workspace (B15). */
201
+ export let workspaceFonts: CanvasHostProps['workspaceFonts'] = DEFAULT_HOST_PROPS.workspaceFonts;
187
202
 
188
203
  /**
189
204
  * The language of the canvas: `locale` ("de", "pt-BR") picks the plural rules, the number format and the language
@@ -232,6 +247,7 @@
232
247
  onAutoSave,
233
248
  autosaveDelayMs,
234
249
  autosaveMaxWaitMs,
250
+ autosaveRetryDelaysMs,
235
251
  suspendAutosave,
236
252
  showSaveButton,
237
253
  onCanvasDirty,
@@ -249,7 +265,11 @@
249
265
  widgetNameRevision,
250
266
  isWidgetKnown,
251
267
  showLogs,
252
- shapeSnap
268
+ shapeSnap,
269
+ keepCenterOnResize,
270
+ workspaceId,
271
+ userId,
272
+ workspaceFonts
253
273
  };
254
274
  $: host.setProps(hostProps);
255
275
 
@@ -382,8 +402,9 @@
382
402
  <Tooltip.Provider delayDuration={400} skipDelayDuration={200}>
383
403
  <div
384
404
  bind:this={rootElement}
385
- class="{className ? className + ' ' : ''}canvas-container @container relative isolate h-full w-full overflow-visible bg-muted text-foreground outline-hidden {showContainerFrame ? BOARD_FRAME_CLASSES : ''}"
405
+ class="{className ? className + ' ' : ''}canvas-container @container relative isolate h-full w-full overflow-visible text-foreground outline-hidden {showContainerFrame ? BOARD_FRAME_CLASSES : ''}"
386
406
  {style}
407
+ style:background-color={BOARD_SURFACE_COLOR}
387
408
  data-canvas-root
388
409
  >
389
410
  <!-- The board: the pointer surface, with the objects, the selection, the text field and the loader. -->
@@ -444,6 +465,6 @@
444
465
  {/if}
445
466
 
446
467
  <!-- Where every menu, popover and tooltip is drawn: a layer without a size that is its own containing block. -->
447
- <div bind:this={floatingLayerElement} class={FLOATING_LAYER_CLASSES} data-canvas-floating-layer></div>
468
+ <div bind:this={floatingLayerElement} class={FLOATING_LAYER_CLASSES} data-canvas-floating-layer data-canvas-ui></div>
448
469
  </div>
449
470
  </Tooltip.Provider>
@@ -40,6 +40,7 @@ declare const DomCanvas: $$__sveltets_2_IsomorphicComponent<{
40
40
  onAutoSave?: CanvasHostProps["onAutoSave"];
41
41
  autosaveDelayMs?: CanvasHostProps["autosaveDelayMs"];
42
42
  autosaveMaxWaitMs?: CanvasHostProps["autosaveMaxWaitMs"];
43
+ autosaveRetryDelaysMs?: CanvasHostProps["autosaveRetryDelaysMs"];
43
44
  suspendAutosave?: CanvasHostProps["suspendAutosave"];
44
45
  showSaveButton?: CanvasHostProps["showSaveButton"];
45
46
  onCanvasDirty?: CanvasHostProps["onCanvasDirty"];
@@ -61,6 +62,10 @@ declare const DomCanvas: $$__sveltets_2_IsomorphicComponent<{
61
62
  * Whether a freehand stroke that is a clean shape (a circle, an oval, a rectangle, a triangle, a diamond, a hexagon)
62
63
  * becomes that shape. Off unless a page passes true: the package's own flag turns it on for every page.
63
64
  */ shapeSnap?: CanvasHostProps["shapeSnap"];
65
+ /** The drawing stays centred when the board is resized (a page that lets its person drag the edges). Off unless a page passes true. */ keepCenterOnResize?: CanvasHostProps["keepCenterOnResize"];
66
+ /** Workspace id for persisted tool settings (B16). */ workspaceId?: CanvasHostProps["workspaceId"];
67
+ /** Optional user id when the host distinguishes users inside one workspace embed. */ userId?: CanvasHostProps["userId"];
68
+ /** Brand-kit fonts for this workspace (B15). */ workspaceFonts?: CanvasHostProps["workspaceFonts"];
64
69
  /**
65
70
  * The language of the canvas: `locale` ("de", "pt-BR") picks the plural rules, the number format and the language
66
71
  * the page's own words are in; `messages` are the page's own words, keyed like CANVAS_MESSAGES (a key left out
@@ -12,8 +12,10 @@
12
12
  * and everything that changed meanwhile goes out in a single save after it. A slow server is never flooded;
13
13
  * - **flush** sends whatever is unsaved at once, whatever the delay and the hold, for the moments a page is about to
14
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.
15
+ * - a save that fails leaves the changes unsaved and says so. It tries again only when the host gave it a **retry
16
+ * schedule** (`getRetryDelayMs`): a wait that grows with every failure in a row, and an end to the trying, so a
17
+ * server that is down is asked a handful of times and not hammered. With no schedule, the next change or the next
18
+ * flush is the retry. A change made after a failure starts its own quiet delay, which is the retry too.
17
19
  *
18
20
  * Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
19
21
  */
@@ -40,6 +42,12 @@ export interface AutosaveSchedulerOptions {
40
42
  isSuspended?: () => boolean;
41
43
  /** Told when a save failed. The changes stay unsaved. */
42
44
  onSaveFailed?: (error: unknown) => void;
45
+ /**
46
+ * How long to wait before trying again after a failed save, in milliseconds, given how many saves in a row have failed
47
+ * (1 after the first). A value of 0 (or less, or not a number) ends the trying: the next change or flush is the retry.
48
+ * Left out, a failed save is not tried again by itself. Read at every failure.
49
+ */
50
+ getRetryDelayMs?: (failuresInARow: number) => number;
43
51
  /** Defaults to the real one. */
44
52
  clock?: AutosaveClock;
45
53
  }
@@ -12,8 +12,10 @@
12
12
  * and everything that changed meanwhile goes out in a single save after it. A slow server is never flooded;
13
13
  * - **flush** sends whatever is unsaved at once, whatever the delay and the hold, for the moments a page is about to
14
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.
15
+ * - a save that fails leaves the changes unsaved and says so. It tries again only when the host gave it a **retry
16
+ * schedule** (`getRetryDelayMs`): a wait that grows with every failure in a row, and an end to the trying, so a
17
+ * server that is down is asked a handful of times and not hammered. With no schedule, the next change or the next
18
+ * flush is the retry. A change made after a failure starts its own quiet delay, which is the retry too.
17
19
  *
18
20
  * Kept free of Svelte and of the DOM (the clock can be replaced) so that Node can test it.
19
21
  */
@@ -42,6 +44,8 @@ export function createAutosaveScheduler(options) {
42
44
  let saveOnItsWay = null;
43
45
  /** The next save fell due while another was on its way: it starts as soon as that one is done. */
44
46
  let dueWhileSaving = false;
47
+ /** How many saves in a row have failed. A save that goes through, or a board that was just loaded, makes it 0. */
48
+ let failuresInARow = 0;
45
49
  let disposed = false;
46
50
  function stopTimer() {
47
51
  if (timerHandle === null)
@@ -72,15 +76,32 @@ export function createAutosaveScheduler(options) {
72
76
  }
73
77
  void startSave();
74
78
  }
79
+ /** Sets a timer for the next try after a failure, when the host's schedule has one left. A timer that is already running is left alone: a change made since has its own. */
80
+ function scheduleRetry() {
81
+ if (disposed || timerHandle !== null || !options.getRetryDelayMs)
82
+ return;
83
+ let waitMs = 0;
84
+ try {
85
+ waitMs = toDurationMs(options.getRetryDelayMs(failuresInARow));
86
+ }
87
+ catch (scheduleError) {
88
+ console.warn('[autosave] getRetryDelayMs threw', scheduleError);
89
+ }
90
+ if (waitMs > 0)
91
+ startTimer(waitMs);
92
+ }
75
93
  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.
94
+ // What the failed save was meant to keep is not kept: it is unsaved again, and the retry (or the next change or
95
+ // flush) tries again.
77
96
  dirty = true;
97
+ failuresInARow += 1;
78
98
  try {
79
99
  options.onSaveFailed?.(error);
80
100
  }
81
101
  catch (reportError) {
82
102
  console.warn('[autosave] onSaveFailed threw', reportError);
83
103
  }
104
+ scheduleRetry();
84
105
  }
85
106
  /** Takes everything unsaved into a save, now. The promise it returns never rejects and settles when the save is done. */
86
107
  function startSave() {
@@ -97,10 +118,14 @@ export function createAutosaveScheduler(options) {
97
118
  noteFailure(error);
98
119
  return Promise.resolve();
99
120
  }
100
- if (!isPromiseLike(outcome))
121
+ if (!isPromiseLike(outcome)) {
122
+ failuresInARow = 0;
101
123
  return Promise.resolve();
124
+ }
102
125
  const running = Promise.resolve(outcome)
103
- .then(() => undefined, (error) => noteFailure(error))
126
+ .then(() => {
127
+ failuresInARow = 0;
128
+ }, (error) => noteFailure(error))
104
129
  .then(() => {
105
130
  if (saveOnItsWay === running)
106
131
  saveOnItsWay = null;
@@ -140,6 +165,7 @@ export function createAutosaveScheduler(options) {
140
165
  dirty = false;
141
166
  firstChangeAt = null;
142
167
  dueWhileSaving = false;
168
+ failuresInARow = 0;
143
169
  }
144
170
  function dispose() {
145
171
  cancel();
@@ -5,5 +5,9 @@
5
5
  * The fallback is the token's value in the light theme, for a page that does not load the design system's styles. One
6
6
  * constant, read by the board and by the placeholder a page shows while the canvas is still downloading, so the swap
7
7
  * from one to the other cannot change colour.
8
+ *
9
+ * A page that wants another colour sets `--canvas-surface` on an element around the board (the home page's sketch card is
10
+ * white in the design, while the full canvas stays `muted`). Nothing else changes: the variable is not set anywhere else, so
11
+ * the board, the creator and the embeds keep the token.
8
12
  */
9
- export declare const BOARD_SURFACE_COLOR = "var(--muted, #f5f5f5)";
13
+ export declare const BOARD_SURFACE_COLOR = "var(--canvas-surface, var(--muted, #f5f5f5))";
@@ -5,5 +5,9 @@
5
5
  * The fallback is the token's value in the light theme, for a page that does not load the design system's styles. One
6
6
  * constant, read by the board and by the placeholder a page shows while the canvas is still downloading, so the swap
7
7
  * from one to the other cannot change colour.
8
+ *
9
+ * A page that wants another colour sets `--canvas-surface` on an element around the board (the home page's sketch card is
10
+ * white in the design, while the full canvas stays `muted`). Nothing else changes: the variable is not set anywhere else, so
11
+ * the board, the creator and the embeds keep the token.
8
12
  */
9
- export const BOARD_SURFACE_COLOR = 'var(--muted, #f5f5f5)';
13
+ export const BOARD_SURFACE_COLOR = 'var(--canvas-surface, var(--muted, #f5f5f5))';
@@ -111,11 +111,13 @@ export function zoomVisibilityClasses(toolbarAnchor, zoomAnchor) {
111
111
  return ZOOM_CONTROL_VISIBLE_FROM.centredBesideCornerToolbar;
112
112
  return ZOOM_CONTROL_VISIBLE_FROM.oppositeCorners;
113
113
  }
114
+ const TOP_PANEL_CONFLICT_ANCHORS = new Set(['TC', 'TR']);
114
115
  /** What the panel keeps clear of, for the slots that are drawn. */
115
116
  export function panelClearanceFor(slots) {
116
117
  const rightEdgeSlot = slots.find((slot) => slot.anchor === 'CR');
117
118
  return {
118
- belowTopCards: slots.some((slot) => isTopAnchor(slot.anchor)),
119
+ // Top-left chrome (e.g. zoom on the creator big page) does not overlap the top-right selection panel.
120
+ belowTopCards: slots.some((slot) => TOP_PANEL_CONFLICT_ANCHORS.has(slot.anchor)),
119
121
  besideSideCard: rightEdgeSlot ? (rightEdgeSlot.cards.includes('toolbar') ? 'toolbar' : 'zoom') : null
120
122
  };
121
123
  }
@@ -19,6 +19,8 @@ import type { TextLayout } from '../../engine/text/layoutText.js';
19
19
  import type { EngineState, ToolId } from '../../engine/state.js';
20
20
  import { ConversionRegistry } from '../../engine/widgets.js';
21
21
  import type { WidgetMetadata } from '../../engine/widgets.js';
22
+ import { type WorkspaceCanvasFont } from '../../fonts/workspaceFonts.js';
23
+ import type { StylePatch } from '../../engine/core/style.js';
22
24
  import type { PanZoomPosition } from '../panZoomPosition.js';
23
25
  import type { ToolbarPosition } from '../toolbarPosition.js';
24
26
  import type { Translate as CatalogTranslate } from '@widgetic/design-system/i18n';
@@ -37,6 +39,18 @@ export interface SelectorGuide {
37
39
  esc: string;
38
40
  done: string;
39
41
  }
42
+ /**
43
+ * What the canvas tells the page about a save, as the second argument of `onAutoSave`.
44
+ */
45
+ export interface AutosaveContext {
46
+ /**
47
+ * The page is going away (the browser sent `pagehide`: the tab closes, a reload, a navigation to another site). Nothing that
48
+ * waits survives that, so a page that sends the save to a server should send it as a request that outlives the page
49
+ * (`fetch` with `keepalive: true`), at once, and not behind a queue. It is false for every other save, and false again if the
50
+ * page comes back from the browser's back-forward cache (`pageshow`).
51
+ */
52
+ leaving: boolean;
53
+ }
40
54
  /**
41
55
  * Every prop of the canvas that the host reads. `class`, `style`, `locale` and `messages` belong to the shell (they
42
56
  * are about the element and the words), the rest are here. Each is read when it is needed, never copied.
@@ -60,9 +74,15 @@ export interface CanvasHostProps {
60
74
  onReady: (() => void) | null;
61
75
  isExternalDataLoading: boolean;
62
76
  onBeforeUnmount: ((json: string | null) => void) | null;
63
- onAutoSave: ((json: string | null) => void | Promise<unknown>) | null;
77
+ onAutoSave: ((json: string | null, context: AutosaveContext) => void | Promise<unknown>) | null;
64
78
  autosaveDelayMs: number;
65
79
  autosaveMaxWaitMs: number;
80
+ /**
81
+ * After `onAutoSave` fails (it throws or its promise rejects), how long to wait before each new try, in milliseconds:
82
+ * the first entry after the first failure, the second after the second one in a row, and so on. When the list is used
83
+ * up, the trying stops until the next change or flush. An empty list means a failed save is not tried again by itself.
84
+ */
85
+ autosaveRetryDelaysMs: readonly number[];
66
86
  suspendAutosave: boolean;
67
87
  showSaveButton: boolean;
68
88
  onCanvasDirty: (() => void) | null;
@@ -82,6 +102,15 @@ export interface CanvasHostProps {
82
102
  showLogs: boolean;
83
103
  /** Whether a freehand stroke that is a clean shape becomes that shape. Off unless the page passes true. */
84
104
  shapeSnap: boolean;
105
+ /**
106
+ * Whether the drawing stays centred when the board is resized (the pan moves by half of the change in size), for a page
107
+ * that lets its person drag the edges of the board. Off unless the page passes true: the top-left corner stays put then.
108
+ */
109
+ keepCenterOnResize: boolean;
110
+ /** Workspace id for per-workspace tool settings (localStorage by default). */
111
+ workspaceId: string | null;
112
+ userId: string | null;
113
+ workspaceFonts: readonly WorkspaceCanvasFont[];
85
114
  }
86
115
  /** What each prop is until the page sets it (the values the canvas this one replaces had, but for `panZoomPosition`). */
87
116
  export declare const DEFAULT_HOST_PROPS: Readonly<CanvasHostProps>;
@@ -156,6 +185,8 @@ export declare class CanvasHost {
156
185
  constructor(initialProps?: Partial<CanvasHostProps>);
157
186
  /** The page changed some props. */
158
187
  setProps(patch: Partial<CanvasHostProps>): void;
188
+ /** Persists tool style changes for this workspace (called from the selection panel). */
189
+ persistWorkspaceStyle(patch: StylePatch): void;
159
190
  /** The shell gives the host the words of the page's language. */
160
191
  setTranslator(translate: Translate): void;
161
192
  get ui(): HostUiState;
@@ -10,7 +10,7 @@
10
10
  * the shell calls `attach` from `onMount` and `destroy` from `onDestroy`. The engine's state and the host's own UI state
11
11
  * are offered as stores (`engineStore`, `uiStore`), so legacy and runes components read them the same way.
12
12
  */
13
- import { createObjectId, createImageObject, createRectObject } from '../../engine/core/defaults.js';
13
+ import { createObjectId, createImageObject, createRectObject, TEXT_DEFAULTS } from '../../engine/core/defaults.js';
14
14
  import { boundsOfObjects, shapeBounds } from '../../engine/core/scene.js';
15
15
  import { buildDraggedShape } from '../../engine/core/shapeTools.js';
16
16
  import { EngineCore } from '../../engine/EngineCore.js';
@@ -20,7 +20,11 @@ import { renderShapesToDataUrl } from '../../engine/render/rasterize.js';
20
20
  import { layoutTextObject } from '../../engine/text/layoutText.js';
21
21
  import { ConversionRegistry, absorbSketchIntoWidget, addWidgetCard, commitWidgetCardMove, findWidgetCard, hydrateWidgetMetadata, keepOnlyWidgetCard, linkedWidgetIds, markOrphanedWidgetCards, moveWidgetCardByScreen, primaryWidgetId, removeSketchObjectsKeeping, replaceObjectWithWidgetCard, selectWidgetCard, selectedWidgetId, setPrimaryWidgetCard, updateWidgetThumbnail } from '../../engine/widgets.js';
22
22
  import { createAutosaveScheduler } from '../autosaveScheduler.js';
23
- import { readPreferredTextFontFamily } from '../preferredTextFont.js';
23
+ import { readPreferredTextFontFamily, setWorkspaceFontFamilies, writePreferredTextFontFamily } from '../preferredTextFont.js';
24
+ import { ensureInterFontLoaded } from '../../fonts/interFont.js';
25
+ import { registerWorkspaceFonts } from '../../fonts/workspaceFonts.js';
26
+ import { isCanvasOwnedTarget } from '../outsideClickDeselect.js';
27
+ import { flushWorkspaceToolSettingsPending, loadWorkspaceToolSettings, saveWorkspaceToolSettingsDebounced } from '../../settings/workspaceToolSettings.js';
24
28
  import { canvasLog, canvasWarn, setCanvasLogsEnabled } from '../canvasLogger.js';
25
29
  import { CANVAS_OPEN_MARKS, markCanvasOpenStep } from '../openMarks.js';
26
30
  import { eventIsForScope, getEventOrigin, shouldTakeFocusBack } from '../eventScope.js';
@@ -54,6 +58,7 @@ export const DEFAULT_HOST_PROPS = Object.freeze({
54
58
  onAutoSave: null,
55
59
  autosaveDelayMs: 3000,
56
60
  autosaveMaxWaitMs: 10000,
61
+ autosaveRetryDelaysMs: Object.freeze([5000, 10000, 20000, 40000, 60000]),
57
62
  suspendAutosave: false,
58
63
  showSaveButton: false,
59
64
  onCanvasDirty: null,
@@ -71,7 +76,11 @@ export const DEFAULT_HOST_PROPS = Object.freeze({
71
76
  widgetNameRevision: 0,
72
77
  isWidgetKnown: null,
73
78
  showLogs: false,
74
- shapeSnap: false
79
+ shapeSnap: false,
80
+ keepCenterOnResize: false,
81
+ workspaceId: null,
82
+ userId: null,
83
+ workspaceFonts: Object.freeze([])
75
84
  });
76
85
  /** A store the way Svelte reads one (`$store` and `fromStore` both work on it). */
77
86
  class ValueStore {
@@ -217,10 +226,13 @@ export class CanvasHost {
217
226
  #unsubscribeEngine = null;
218
227
  /** The last payload handed to `onAutoSave`, so a timer that fires with no real change does not serialize again. */
219
228
  #lastAutosavedJson = null;
229
+ /** The browser said `pagehide` and the page has not come back (`pageshow`): the saves made now are the page's last ones. */
230
+ #pageIsLeaving = false;
220
231
  /** A text was being typed at the last change of the engine (its field is on the page). */
221
232
  #wasEditingText = false;
222
233
  /** The board is about to take the keyboard back from a text field that left the page (asked for the next frame). */
223
234
  #keyboardReturnQueued = false;
235
+ #loadedWorkspaceSettings = null;
224
236
  /** The animation frame that steps the eraser's trail (null: none asked for), and when the trail was last stepped (null: the clock is idle). */
225
237
  #scribbleFrame = null;
226
238
  #scribbleClockLast = null;
@@ -254,9 +266,10 @@ export class CanvasHost {
254
266
  getMaxWaitMs: () => this.props.autosaveMaxWaitMs,
255
267
  isSuspended: () => this.props.suspendAutosave,
256
268
  save: () => this.#runAutosave(),
269
+ getRetryDelayMs: (failuresInARow) => this.props.autosaveRetryDelaysMs[failuresInARow - 1] ?? 0,
257
270
  onSaveFailed: (error) => {
258
271
  this.#updateUi({ saveState: 'dirty' });
259
- canvasWarn('Canvas: autosave failed, the changes stay unsaved until the next change', error);
272
+ canvasWarn('Canvas: autosave failed, the changes stay unsaved and the save is tried again', error);
260
273
  }
261
274
  });
262
275
  this.#wireEngineHooks();
@@ -282,6 +295,79 @@ export class CanvasHost {
282
295
  if (this.props.isExternalDataLoading !== previous.isExternalDataLoading) {
283
296
  queueMicrotask(() => this.#syncEmptyHintGate());
284
297
  }
298
+ if (this.props.workspaceId !== previous.workspaceId ||
299
+ this.props.userId !== previous.userId ||
300
+ this.props.workspaceFonts !== previous.workspaceFonts) {
301
+ void this.#syncWorkspaceContext();
302
+ }
303
+ }
304
+ #compactStylePatch(fields) {
305
+ const compact = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
306
+ return Object.keys(compact).length > 0 ? compact : undefined;
307
+ }
308
+ /** Persists tool style changes for this workspace (called from the selection panel). */
309
+ persistWorkspaceStyle(patch) {
310
+ const workspaceId = this.props.workspaceId;
311
+ if (!workspaceId)
312
+ return;
313
+ const textPatch = patch.fontFamily !== undefined ||
314
+ patch.fontSize !== undefined ||
315
+ patch.fontWeight !== undefined ||
316
+ patch.fontStyle !== undefined ||
317
+ patch.color !== undefined ||
318
+ patch.align !== undefined ||
319
+ patch.underline !== undefined
320
+ ? this.#compactStylePatch({
321
+ fontFamily: patch.fontFamily,
322
+ fontSize: patch.fontSize,
323
+ fontWeight: patch.fontWeight,
324
+ fontStyle: patch.fontStyle,
325
+ color: patch.color,
326
+ align: patch.align,
327
+ underline: patch.underline
328
+ })
329
+ : undefined;
330
+ const paintPatch = patch.fill !== undefined ||
331
+ patch.stroke !== undefined ||
332
+ patch.strokeWidth !== undefined ||
333
+ patch.strokeStyle !== undefined ||
334
+ patch.opacity !== undefined ||
335
+ patch.roundness !== undefined
336
+ ? this.#compactStylePatch({
337
+ fill: patch.fill,
338
+ stroke: patch.stroke,
339
+ strokeWidth: patch.strokeWidth,
340
+ strokeStyle: patch.strokeStyle,
341
+ opacity: patch.opacity,
342
+ roundness: patch.roundness
343
+ })
344
+ : undefined;
345
+ if (!textPatch && !paintPatch)
346
+ return;
347
+ saveWorkspaceToolSettingsDebounced({ workspaceId, userId: this.props.userId }, { text: textPatch, paint: paintPatch });
348
+ }
349
+ async #syncWorkspaceContext() {
350
+ await ensureInterFontLoaded();
351
+ const fonts = this.props.workspaceFonts ?? [];
352
+ setWorkspaceFontFamilies(fonts.map((font) => font.family));
353
+ await registerWorkspaceFonts(fonts);
354
+ this.engine.notifyFontsChanged();
355
+ const workspaceId = this.props.workspaceId;
356
+ if (!workspaceId)
357
+ return;
358
+ this.#loadedWorkspaceSettings = loadWorkspaceToolSettings({ workspaceId, userId: this.props.userId });
359
+ const textFamily = this.#loadedWorkspaceSettings?.text?.fontFamily;
360
+ if (textFamily) {
361
+ this.engine.setPreferredTextFontFamily(textFamily);
362
+ writePreferredTextFontFamily(textFamily);
363
+ }
364
+ else {
365
+ this.engine.setPreferredTextFontFamily(TEXT_DEFAULTS.fontFamily);
366
+ }
367
+ this.engine.setWorkspaceToolDefaults({
368
+ text: this.#loadedWorkspaceSettings?.text ?? null,
369
+ paint: this.#loadedWorkspaceSettings?.paint ?? null
370
+ });
285
371
  }
286
372
  /**
287
373
  * A tool whose button the page hides must not stay armed: once the page takes the drawing tools off (after the first
@@ -365,7 +451,29 @@ export class CanvasHost {
365
451
  this.#listen(window, 'keyup', (event) => this.#onKeyUp(event));
366
452
  this.#listen(window, 'blur', () => this.#onWindowBlur());
367
453
  this.#listen(window, 'paste', (event) => this.#onPaste(event));
368
- this.#listen(window, 'pagehide', () => void this.#scheduler.flush());
454
+ this.#listen(window, 'pagehide', () => {
455
+ flushWorkspaceToolSettingsPending();
456
+ // Said before the flush, and kept until the page comes back: a save that waits behind another one (the buffer runs one
457
+ // at a time) is made after this handler returns, and it too is a save of a page that is going away.
458
+ this.#pageIsLeaving = true;
459
+ void this.#scheduler.flush();
460
+ });
461
+ // A page that went into the browser's back-forward cache and is shown again is not leaving any more.
462
+ this.#listen(window, 'pageshow', () => {
463
+ this.#pageIsLeaving = false;
464
+ });
465
+ this.#listen(document, 'pointerdown', (event) => {
466
+ const pointer = event;
467
+ if (pointer.button !== 0)
468
+ return;
469
+ if (this.engine.state.selectedIds.length === 0)
470
+ return;
471
+ if (isCanvasOwnedTarget(pointer, this.#root))
472
+ return;
473
+ if (this.engine.state.editingTextId !== null)
474
+ this.engine.endTextEdit();
475
+ this.engine.clearSelection();
476
+ }, true);
369
477
  this.#listen(document, 'visibilitychange', () => {
370
478
  if (document.visibilityState === 'hidden')
371
479
  void this.#scheduler.flush();
@@ -374,7 +482,10 @@ export class CanvasHost {
374
482
  if (typeof document !== 'undefined' && document.fonts && typeof document.fonts.addEventListener === 'function') {
375
483
  this.#listen(document.fonts, 'loadingdone', () => this.engine.notifyFontsChanged());
376
484
  }
377
- this.engine.notifyFontsChanged();
485
+ void ensureInterFontLoaded().then(() => {
486
+ this.engine.notifyFontsChanged();
487
+ void this.#syncWorkspaceContext();
488
+ });
378
489
  void this.#start();
379
490
  }
380
491
  async #start() {
@@ -493,7 +604,7 @@ export class CanvasHost {
493
604
  const board = this.#board;
494
605
  if (!board)
495
606
  return;
496
- this.engine.setViewSize({ width: board.clientWidth, height: board.clientHeight });
607
+ this.engine.setViewSize({ width: board.clientWidth, height: board.clientHeight }, this.props.keepCenterOnResize);
497
608
  }
498
609
  /** The board on the page (its rectangle and its layout size), for everything the page lays over it. */
499
610
  #frame() {
@@ -847,6 +958,8 @@ export class CanvasHost {
847
958
  #wireEngineHooks() {
848
959
  const hooks = {
849
960
  onDirty: () => this.#markDirty(),
961
+ // Typing is a change too: the letters are saved with the next save, before the typing ends and makes its undo step.
962
+ onDraftChange: () => this.#markDirty(),
850
963
  onCleared: () => this.#safely(() => this.props.onCanvasCleared?.(), 'onCanvasCleared'),
851
964
  onSelectionChange: (ids) => this.#onSelectionChange(ids),
852
965
  confirmWidgetDeletion: (widgetId) => {
@@ -1032,7 +1145,7 @@ export class CanvasHost {
1032
1145
  this.#updateUi({ saveState: 'saving' });
1033
1146
  let outcome;
1034
1147
  try {
1035
- outcome = this.props.onAutoSave?.(json);
1148
+ outcome = this.props.onAutoSave?.(json, { leaving: this.#pageIsLeaving });
1036
1149
  }
1037
1150
  catch (error) {
1038
1151
  this.#updateUi({ saveState: 'dirty' });
@@ -1066,7 +1179,7 @@ export class CanvasHost {
1066
1179
  this.#updateUi({ saveState: 'saving' });
1067
1180
  let outcome;
1068
1181
  try {
1069
- outcome = this.props.onAutoSave?.(json);
1182
+ outcome = this.props.onAutoSave?.(json, { leaving: this.#pageIsLeaving });
1070
1183
  }
1071
1184
  catch (error) {
1072
1185
  canvasWarn('Canvas: the save failed', error);
@@ -1373,7 +1486,8 @@ export class CanvasHost {
1373
1486
  dragged: false,
1374
1487
  wireframe: this.engine.wireframeMode,
1375
1488
  createId: this.engine.services.createId,
1376
- random: this.engine.services.random
1489
+ random: this.engine.services.random,
1490
+ workspacePaint: this.engine.workspacePaintForNewShape(this.engine.wireframeMode)
1377
1491
  });
1378
1492
  }
1379
1493
  addRect() {
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Document-level outside press: deselect when the press is outside the canvas root and its portaled UI (item B18).
3
+ */
4
+ export declare const CANVAS_UI_ATTRIBUTE = "data-canvas-ui";
5
+ export declare function isCanvasOwnedTarget(event: Event, canvasRoot: HTMLElement | null): boolean;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Document-level outside press: deselect when the press is outside the canvas root and its portaled UI (item B18).
3
+ */
4
+ export const CANVAS_UI_ATTRIBUTE = 'data-canvas-ui';
5
+ export function isCanvasOwnedTarget(event, canvasRoot) {
6
+ if (!canvasRoot)
7
+ return false;
8
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
9
+ if (path.length > 0) {
10
+ for (const node of path) {
11
+ if (!(node instanceof Node))
12
+ continue;
13
+ if (node === canvasRoot || canvasRoot.contains(node))
14
+ return true;
15
+ if (node instanceof Element && node.closest(`[${CANVAS_UI_ATTRIBUTE}]`))
16
+ return true;
17
+ }
18
+ return false;
19
+ }
20
+ const target = event.target;
21
+ if (target instanceof Node && (canvasRoot.contains(target) || (target instanceof Element && target.closest(`[${CANVAS_UI_ATTRIBUTE}]`)))) {
22
+ return true;
23
+ }
24
+ return false;
25
+ }
@@ -3,7 +3,13 @@
3
3
  * store a partner page installed with `setCanvasPreferenceStorage`), so that the next text they place starts with it.
4
4
  */
5
5
  /** The font families the selection panel offers for a text, in the order of its list. */
6
- export declare const TEXT_FONT_FAMILIES: readonly ["Arial", "Helvetica", "Times New Roman", "Georgia", "Verdana", "Comic Sans MS", "Courier New", "Impact"];
6
+ export declare const TEXT_FONT_FAMILIES: readonly ["Inter", "Comic Sans MS", "Arial", "Helvetica", "Times New Roman", "Georgia", "Verdana", "Courier New", "Impact"];
7
+ export declare function setWorkspaceFontFamilies(families: readonly string[]): void;
8
+ export declare function fontFamiliesForPicker(): string[];
9
+ /** Inter + Comic Sans for the picker’s “Default fonts” group. */
10
+ export declare const PRIMARY_CANVAS_FONT_FAMILIES: readonly ["Inter", "Comic Sans MS"];
11
+ export declare function builtInFontFamiliesForPicker(): string[];
12
+ export declare function workspaceFontFamiliesForPicker(): string[];
7
13
  /** The key the choice is kept under. */
8
14
  export declare const PREFERRED_TEXT_FONT_STORAGE_KEY = "widgetic-canvas:preferred-text-font";
9
15
  /** The font family kept from an earlier choice, or null when none was made (or the store refuses, or the name is no longer offered). */