@widgetic/canvas 0.5.41 → 0.5.42

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 (85) hide show
  1. package/dist/canvas/autosaveScheduler.js +37 -89
  2. package/dist/canvas/boardFrame.js +1 -1
  3. package/dist/canvas/boardSurface.js +1 -1
  4. package/dist/canvas/canvasLogger.js +7 -19
  5. package/dist/canvas/chromeLayout.js +17 -18
  6. package/dist/canvas/eventScope.js +10 -14
  7. package/dist/canvas/host/CanvasHost.js +1286 -1536
  8. package/dist/canvas/host/CanvasHostApi.js +4 -19
  9. package/dist/canvas/host/browserServices.js +65 -116
  10. package/dist/canvas/host/conversion.js +82 -170
  11. package/dist/canvas/host/hostObject.js +7 -7
  12. package/dist/canvas/host/pageEvents.js +4 -4
  13. package/dist/canvas/host/screenRects.js +28 -31
  14. package/dist/canvas/host/strokeSnap.js +88 -143
  15. package/dist/canvas/openMarks.js +2 -2
  16. package/dist/canvas/outsideClickDeselect.js +6 -7
  17. package/dist/canvas/panZoomPosition.js +2 -2
  18. package/dist/canvas/preferredTextFont.js +13 -25
  19. package/dist/canvas/shapes/ShapeLibrary.js +138 -148
  20. package/dist/canvas/shapes/shapeImageStore.js +3 -3
  21. package/dist/canvas/shapes/strokeShapeSnap.js +188 -233
  22. package/dist/canvas/toolbarPosition.js +2 -2
  23. package/dist/canvas/ui/colorModel.js +21 -32
  24. package/dist/canvas/ui/colorPickerMessages.js +5 -5
  25. package/dist/canvas/ui/floatingCard.js +18 -18
  26. package/dist/canvas/ui/floatingLayer.js +5 -6
  27. package/dist/canvas/ui/keyHints.js +9 -11
  28. package/dist/canvas/ui/popoverSide.js +2 -3
  29. package/dist/canvas/ui/selectionTraits.js +34 -40
  30. package/dist/canvas/view/erasingMarks.js +7 -7
  31. package/dist/canvas/view/geometry.js +71 -90
  32. package/dist/components/preferenceStorage.js +2 -2
  33. package/dist/engine/EngineCore.js +696 -795
  34. package/dist/engine/codec/canvasDocument.js +183 -147
  35. package/dist/engine/codec/hostReadableKeys.js +1 -1
  36. package/dist/engine/core/arrange.js +26 -38
  37. package/dist/engine/core/arrow.js +76 -89
  38. package/dist/engine/core/arrowBinding.js +98 -116
  39. package/dist/engine/core/arrowBindingRecords.js +23 -38
  40. package/dist/engine/core/brush.js +67 -94
  41. package/dist/engine/core/defaults.js +90 -51
  42. package/dist/engine/core/freehand.js +147 -163
  43. package/dist/engine/core/geometry.js +47 -54
  44. package/dist/engine/core/history.js +33 -50
  45. package/dist/engine/core/hitTest.js +68 -81
  46. package/dist/engine/core/matrix.js +18 -20
  47. package/dist/engine/core/pathData.js +183 -210
  48. package/dist/engine/core/rotationReset.js +5 -6
  49. package/dist/engine/core/scene.js +129 -187
  50. package/dist/engine/core/scribble.js +59 -84
  51. package/dist/engine/core/shapePaths.js +12 -15
  52. package/dist/engine/core/shapeTools.js +72 -63
  53. package/dist/engine/core/snapping.js +65 -117
  54. package/dist/engine/core/style.js +31 -64
  55. package/dist/engine/core/transform.js +83 -94
  56. package/dist/engine/core/types.js +4 -4
  57. package/dist/engine/core/viewport.js +23 -36
  58. package/dist/engine/input/PointerController.js +467 -474
  59. package/dist/engine/input/arrowHandles.js +12 -12
  60. package/dist/engine/input/gestures.js +262 -308
  61. package/dist/engine/input/hoverCursor.js +1 -1
  62. package/dist/engine/input/keyboard.js +27 -30
  63. package/dist/engine/input/selectionHandles.js +45 -50
  64. package/dist/engine/input/types.js +1 -1
  65. package/dist/engine/render/rasterize.js +86 -158
  66. package/dist/engine/state.js +4 -15
  67. package/dist/engine/text/layoutText.js +43 -62
  68. package/dist/engine/text/textMetrics.js +8 -10
  69. package/dist/engine/widgets.js +101 -137
  70. package/dist/fonts/interFont.js +17 -68
  71. package/dist/fonts/workspaceFonts.js +32 -90
  72. package/dist/i18n/labels.js +4 -4
  73. package/dist/i18n/language.js +4 -4
  74. package/dist/i18n/messages.js +1 -1
  75. package/dist/i18n/shortcuts.js +14 -14
  76. package/dist/settings/workspaceToolSettings.js +32 -48
  77. package/dist/tools/components/catalog.js +64 -74
  78. package/dist/tools/components/grouping.js +6 -28
  79. package/dist/tools/definitions.js +5 -5
  80. package/dist/tools/executors.js +105 -141
  81. package/dist/tools/hostAdapter.js +11 -13
  82. package/dist/tools/sceneSummary.js +43 -57
  83. package/dist/tools/sketchIntent.js +13 -21
  84. package/dist/tools/types.js +1 -1
  85. package/package.json +1 -1
@@ -10,74 +10,6 @@
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
- var __assign = (this && this.__assign) || function () {
14
- __assign = Object.assign || function(t) {
15
- for (var s, i = 1, n = arguments.length; i < n; i++) {
16
- s = arguments[i];
17
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
18
- t[p] = s[p];
19
- }
20
- return t;
21
- };
22
- return __assign.apply(this, arguments);
23
- };
24
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
25
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
- return new (P || (P = Promise))(function (resolve, reject) {
27
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
- step((generator = generator.apply(thisArg, _arguments || [])).next());
31
- });
32
- };
33
- var __generator = (this && this.__generator) || function (thisArg, body) {
34
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
35
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
36
- function verb(n) { return function (v) { return step([n, v]); }; }
37
- function step(op) {
38
- if (f) throw new TypeError("Generator is already executing.");
39
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
40
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
41
- if (y = 0, t) op = [op[0] & 2, t.value];
42
- switch (op[0]) {
43
- case 0: case 1: t = op; break;
44
- case 4: _.label++; return { value: op[1], done: false };
45
- case 5: _.label++; y = op[1]; op = [0]; continue;
46
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
47
- default:
48
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
49
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
50
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
51
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
52
- if (t[2]) _.ops.pop();
53
- _.trys.pop(); continue;
54
- }
55
- op = body.call(thisArg, _);
56
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
57
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
58
- }
59
- };
60
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
61
- if (kind === "m") throw new TypeError("Private method is not writable");
62
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
63
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
64
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
65
- };
66
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
67
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
68
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
69
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
70
- };
71
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
72
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
73
- if (ar || !(i in from)) {
74
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
75
- ar[i] = from[i];
76
- }
77
- }
78
- return to.concat(ar || Array.prototype.slice.call(from));
79
- };
80
- var _ValueStore_value, _ValueStore_subscribers, _CanvasHost_instances, _CanvasHost_ui, _CanvasHost_scheduler, _CanvasHost_measureText, _CanvasHost_raster, _CanvasHost_root, _CanvasHost_board, _CanvasHost_resizeObserver, _CanvasHost_removeListeners, _CanvasHost_destroyed, _CanvasHost_loadDepth, _CanvasHost_longPress, _CanvasHost_touchWasLast, _CanvasHost_menuFinger, _CanvasHost_lastOverlayState, _CanvasHost_afterRenderQueued, _CanvasHost_resizingWidgetId, _CanvasHost_textLayouts, _CanvasHost_textLayoutsFontRevision, _CanvasHost_applyingAfterRender, _CanvasHost_unsubscribeEngine, _CanvasHost_lastAutosavedJson, _CanvasHost_pageIsLeaving, _CanvasHost_wasEditingText, _CanvasHost_keyboardReturnQueued, _CanvasHost_loadedWorkspaceSettings, _CanvasHost_scribbleFrame, _CanvasHost_scribbleClockLast, _CanvasHost_compactStylePatch, _CanvasHost_syncWorkspaceContext, _CanvasHost_dropToolsThePageHides, _CanvasHost_announceWidgetResize, _CanvasHost_updateUi, _CanvasHost_start, _CanvasHost_openEmptyHintGate, _CanvasHost_closeEmptyHintGate, _CanvasHost_syncEmptyHintGate, _CanvasHost_listen, _CanvasHost_measureBoard, _CanvasHost_frame, _CanvasHost_cssScale, _CanvasHost_pointerInput, _CanvasHost_startLongPress, _CanvasHost_cancelLongPress, _CanvasHost_fireLongPress, _CanvasHost_noteFingerLifted, _CanvasHost_onWheel, _CanvasHost_closeTransientUi, _CanvasHost_keyboardActions, _CanvasHost_keyboardHost, _CanvasHost_onKeyDown, _CanvasHost_onKeyUp, _CanvasHost_onWindowBlur, _CanvasHost_markClipboardAsOurs, _CanvasHost_onPaste, _CanvasHost_wireEngineHooks, _CanvasHost_safely, _CanvasHost_markDirty, _CanvasHost_onSelectionChange, _CanvasHost_onWidgetDuplicated, _CanvasHost_handleActivate, _CanvasHost_onEngineState, _CanvasHost_takeKeyboardBackSoon, _CanvasHost_startScribbleClock, _CanvasHost_onScribbleFrame, _CanvasHost_queueAfterRender, _CanvasHost_handleStrokeFinished, _CanvasHost_runAutosave, _CanvasHost_serializeCanvasText, _CanvasHost_resolveStoredImages, _CanvasHost_placeAtCenter, _CanvasHost_sketchToolBatchBase;
81
13
  import { createObjectId, createImageObject, createRectObject, TEXT_DEFAULTS } from '../../engine/core/defaults.js';
82
14
  import { boundsOfObjects, shapeBounds } from '../../engine/core/scene.js';
83
15
  import { buildDraggedShape } from '../../engine/core/shapeTools.js';
@@ -106,7 +38,7 @@ import { isShapeSnapOn, snapDrawnStroke } from './strokeSnap.js';
106
38
  import { createCanvasToolHostFromEngine, executeCanvasTool, summarizeScene } from '../../tools/index.js';
107
39
  import { isCanvasToolName } from '../../tools/definitions.js';
108
40
  /** What each prop is until the page sets it (the values the canvas this one replaces had, but for `panZoomPosition`). */
109
- export var DEFAULT_HOST_PROPS = Object.freeze({
41
+ export const DEFAULT_HOST_PROPS = Object.freeze({
110
42
  showContainerFrame: true,
111
43
  widgetSelectionLayerTarget: '',
112
44
  onObjectClick: null,
@@ -153,40 +85,31 @@ export var DEFAULT_HOST_PROPS = Object.freeze({
153
85
  workspaceFonts: Object.freeze([])
154
86
  });
155
87
  /** A store the way Svelte reads one (`$store` and `fromStore` both work on it). */
156
- var ValueStore = /** @class */ (function () {
157
- function ValueStore(initial) {
158
- _ValueStore_value.set(this, void 0);
159
- _ValueStore_subscribers.set(this, new Set());
160
- __classPrivateFieldSet(this, _ValueStore_value, initial, "f");
161
- }
162
- Object.defineProperty(ValueStore.prototype, "value", {
163
- get: function () {
164
- return __classPrivateFieldGet(this, _ValueStore_value, "f");
165
- },
166
- enumerable: false,
167
- configurable: true
168
- });
169
- ValueStore.prototype.set = function (next) {
170
- if (Object.is(next, __classPrivateFieldGet(this, _ValueStore_value, "f")))
171
- return;
172
- __classPrivateFieldSet(this, _ValueStore_value, next, "f");
173
- for (var _i = 0, _a = __spreadArray([], __classPrivateFieldGet(this, _ValueStore_subscribers, "f"), true); _i < _a.length; _i++) {
174
- var run = _a[_i];
88
+ class ValueStore {
89
+ #value;
90
+ #subscribers = new Set();
91
+ constructor(initial) {
92
+ this.#value = initial;
93
+ }
94
+ get value() {
95
+ return this.#value;
96
+ }
97
+ set(next) {
98
+ if (Object.is(next, this.#value))
99
+ return;
100
+ this.#value = next;
101
+ for (const run of [...this.#subscribers])
175
102
  run(next);
176
- }
177
- };
178
- ValueStore.prototype.subscribe = function (run) {
179
- var _this = this;
180
- __classPrivateFieldGet(this, _ValueStore_subscribers, "f").add(run);
181
- run(__classPrivateFieldGet(this, _ValueStore_value, "f"));
182
- return function () {
183
- __classPrivateFieldGet(_this, _ValueStore_subscribers, "f").delete(run);
103
+ }
104
+ subscribe(run) {
105
+ this.#subscribers.add(run);
106
+ run(this.#value);
107
+ return () => {
108
+ this.#subscribers.delete(run);
184
109
  };
185
- };
186
- return ValueStore;
187
- }());
188
- _ValueStore_value = new WeakMap(), _ValueStore_subscribers = new WeakMap();
189
- var INITIAL_UI_STATE = Object.freeze({
110
+ }
111
+ }
112
+ const INITIAL_UI_STATE = Object.freeze({
190
113
  loadPhase: 'initializing',
191
114
  loadStatus: null,
192
115
  saveState: 'saved',
@@ -200,38 +123,38 @@ var INITIAL_UI_STATE = Object.freeze({
200
123
  emptyHintGateOpen: false
201
124
  });
202
125
  /** Text put on the system clipboard by a copy on the board, so that a picture copied earlier does not win the next paste. */
203
- export var CLIPBOARD_MARKER = 'widgetic-canvas-selection';
126
+ export const CLIPBOARD_MARKER = 'widgetic-canvas-selection';
204
127
  /** The longest side a picture gets when it is put on the board (the picture itself keeps its size). */
205
- export var IMAGE_INSERT_MAX_SIDE = 480;
128
+ export const IMAGE_INSERT_MAX_SIDE = 480;
206
129
  /** The smallest side of a picture put on the board. */
207
- export var IMAGE_INSERT_MIN_SIDE = 24;
130
+ export const IMAGE_INSERT_MIN_SIDE = 24;
208
131
  /**
209
132
  * How long a finger rests on the board before the press is a long press (it opens the menu a right click opens), and how
210
133
  * far the finger may wander meanwhile, in board pixels. The host times it itself: a browser that sends a `contextmenu`
211
134
  * for a long press (Android) is not needed, and one that does not (an iPad) is served the same.
212
135
  */
213
- export var TOUCH_LONG_PRESS_DELAY_MS = 500;
214
- export var TOUCH_LONG_PRESS_SLOP = 8;
136
+ export const TOUCH_LONG_PRESS_DELAY_MS = 500;
137
+ export const TOUCH_LONG_PRESS_SLOP = 8;
215
138
  /** How long after the finger that opened the menu lifts its release is still told apart from a choice (see `isMenuHeldByItsFinger`). */
216
- export var TOUCH_MENU_RELEASE_GRACE_MS = 400;
139
+ export const TOUCH_MENU_RELEASE_GRACE_MS = 400;
217
140
  /** A picture's size on the board: its own size, or the biggest one that fits `IMAGE_INSERT_MAX_SIDE`. */
218
141
  export function fitImageSize(naturalWidth, naturalHeight) {
219
- var width = Math.max(1, naturalWidth || IMAGE_INSERT_MAX_SIDE);
220
- var height = Math.max(1, naturalHeight || IMAGE_INSERT_MAX_SIDE);
221
- var scale = Math.min(1, IMAGE_INSERT_MAX_SIDE / Math.max(width, height));
142
+ const width = Math.max(1, naturalWidth || IMAGE_INSERT_MAX_SIDE);
143
+ const height = Math.max(1, naturalHeight || IMAGE_INSERT_MAX_SIDE);
144
+ const scale = Math.min(1, IMAGE_INSERT_MAX_SIDE / Math.max(width, height));
222
145
  return {
223
146
  width: Math.max(IMAGE_INSERT_MIN_SIDE, Math.round(width * scale)),
224
147
  height: Math.max(IMAGE_INSERT_MIN_SIDE, Math.round(height * scale))
225
148
  };
226
149
  }
227
- var isEditableTarget = function (element) {
150
+ const isEditableTarget = (element) => {
228
151
  if (!element)
229
152
  return false;
230
- var tag = element.tagName;
153
+ const tag = element.tagName;
231
154
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || element.isContentEditable === true;
232
155
  };
233
156
  /** Elements that read the arrow keys (and Home, End, Page Up and Down) themselves: a slider, a tab list, a list box. */
234
- var ARROW_KEY_ROLES = new Set([
157
+ const ARROW_KEY_ROLES = new Set([
235
158
  'slider',
236
159
  'spinbutton',
237
160
  'scrollbar',
@@ -248,151 +171,155 @@ var ARROW_KEY_ROLES = new Set([
248
171
  'gridcell'
249
172
  ]);
250
173
  /** The keys such an element moves with. */
251
- var NAVIGATION_KEYS = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown']);
174
+ const NAVIGATION_KEYS = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown']);
252
175
  /** An element with the focus that moves with the arrow keys itself: the selection must not move under it. */
253
- var ownsNavigationKeys = function (element) {
254
- var _a;
255
- var role = (_a = element === null || element === void 0 ? void 0 : element.getAttribute) === null || _a === void 0 ? void 0 : _a.call(element, 'role');
176
+ const ownsNavigationKeys = (element) => {
177
+ const role = element?.getAttribute?.('role');
256
178
  return role !== null && role !== undefined && ARROW_KEY_ROLES.has(role);
257
179
  };
258
180
  /** A button, link or menu entry that has the focus: Space belongs to it, not to the pan. */
259
- var isActivatableTarget = function (element) {
181
+ const isActivatableTarget = (element) => {
260
182
  if (!element)
261
183
  return false;
262
- var tag = element.tagName;
184
+ const tag = element.tagName;
263
185
  if (tag === 'BUTTON' || tag === 'A' || tag === 'SUMMARY')
264
186
  return true;
265
- var role = element.getAttribute('role');
187
+ const role = element.getAttribute('role');
266
188
  return role === 'button' || role === 'menuitem' || role === 'menuitemcheckbox' || role === 'menuitemradio' || role === 'option' || role === 'switch' || role === 'checkbox' || role === 'tab';
267
189
  };
268
190
  /** The part of the page a paste is not meant for (the creator's own panels and lists). */
269
- var PASTE_EXCLUDED_SELECTOR = '.widget-details-floating-panel, .widgets-list-panel, [data-widget-details]';
191
+ const PASTE_EXCLUDED_SELECTOR = '.widget-details-floating-panel, .widgets-list-panel, [data-widget-details]';
270
192
  // ──────────────────────────────────────────────────────────── the host
271
- var CanvasHost = /** @class */ (function () {
272
- function CanvasHost(initialProps) {
273
- if (initialProps === void 0) { initialProps = {}; }
274
- var _this = this;
275
- _CanvasHost_instances.add(this);
276
- this.conversions = new ConversionRegistry();
277
- this.props = __assign({}, DEFAULT_HOST_PROPS);
278
- /** The words the host draws or says (the shell gives it the language of the page). */
279
- this.translate = function (key) { return key; };
280
- _CanvasHost_ui.set(this, new ValueStore(INITIAL_UI_STATE));
281
- _CanvasHost_scheduler.set(this, void 0);
282
- _CanvasHost_measureText.set(this, createBrowserMeasureText());
283
- _CanvasHost_raster.set(this, createBrowserRasterServices(__classPrivateFieldGet(this, _CanvasHost_measureText, "f")));
284
- _CanvasHost_root.set(this, null);
285
- _CanvasHost_board.set(this, null);
286
- _CanvasHost_resizeObserver.set(this, null);
287
- _CanvasHost_removeListeners.set(this, []);
288
- _CanvasHost_destroyed.set(this, false);
289
- _CanvasHost_loadDepth.set(this, 0);
290
- /** A finger that is resting on the board and may become a long press. */
291
- _CanvasHost_longPress.set(this, null);
292
- /** The last press was a finger's: a `contextmenu` that follows it is the browser's own long-press menu. */
293
- _CanvasHost_touchWasLast.set(this, false);
294
- /** The finger whose long press opened the menu, and when it lifted (null while it is still down). */
295
- _CanvasHost_menuFinger.set(this, null);
296
- _CanvasHost_lastOverlayState.set(this, null);
297
- _CanvasHost_afterRenderQueued.set(this, false);
298
- /** The widget whose card is being stretched, as the page was told (null: the page was told nothing, or that it ended). */
299
- _CanvasHost_resizingWidgetId.set(this, null);
300
- /** The lines of every text, kept for as long as the text object is the same record and the fonts are the same. */
301
- _CanvasHost_textLayouts.set(this, new WeakMap());
302
- _CanvasHost_textLayoutsFontRevision.set(this, -1);
303
- _CanvasHost_applyingAfterRender.set(this, false);
304
- _CanvasHost_unsubscribeEngine.set(this, null);
305
- /** The last payload handed to `onAutoSave`, so a timer that fires with no real change does not serialize again. */
306
- _CanvasHost_lastAutosavedJson.set(this, null);
307
- /** The browser said `pagehide` and the page has not come back (`pageshow`): the saves made now are the page's last ones. */
308
- _CanvasHost_pageIsLeaving.set(this, false);
309
- /** A text was being typed at the last change of the engine (its field is on the page). */
310
- _CanvasHost_wasEditingText.set(this, false);
311
- /** The board is about to take the keyboard back from a text field that left the page (asked for the next frame). */
312
- _CanvasHost_keyboardReturnQueued.set(this, false);
313
- _CanvasHost_loadedWorkspaceSettings.set(this, null);
314
- /** 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). */
315
- _CanvasHost_scribbleFrame.set(this, null);
316
- _CanvasHost_scribbleClockLast.set(this, null);
317
- _CanvasHost_sketchToolBatchBase.set(this, null);
318
- this.props = __assign(__assign({}, DEFAULT_HOST_PROPS), initialProps);
319
- this.engine = new EngineCore({ measureText: __classPrivateFieldGet(this, _CanvasHost_measureText, "f") });
193
+ export class CanvasHost {
194
+ engine;
195
+ controller;
196
+ conversions = new ConversionRegistry();
197
+ /** The engine's state as a store. */
198
+ engineStore;
199
+ /** The host's own state as a store. */
200
+ uiStore;
201
+ props = { ...DEFAULT_HOST_PROPS };
202
+ /** The words the host draws or says (the shell gives it the language of the page). */
203
+ translate = (key) => key;
204
+ #ui = new ValueStore(INITIAL_UI_STATE);
205
+ #scheduler;
206
+ #measureText = createBrowserMeasureText();
207
+ #raster = createBrowserRasterServices(this.#measureText);
208
+ #root = null;
209
+ #board = null;
210
+ #resizeObserver = null;
211
+ #removeListeners = [];
212
+ #destroyed = false;
213
+ #loadDepth = 0;
214
+ /** A finger that is resting on the board and may become a long press. */
215
+ #longPress = null;
216
+ /** The last press was a finger's: a `contextmenu` that follows it is the browser's own long-press menu. */
217
+ #touchWasLast = false;
218
+ /** The finger whose long press opened the menu, and when it lifted (null while it is still down). */
219
+ #menuFinger = null;
220
+ #lastOverlayState = null;
221
+ #afterRenderQueued = false;
222
+ /** The widget whose card is being stretched, as the page was told (null: the page was told nothing, or that it ended). */
223
+ #resizingWidgetId = null;
224
+ /** The lines of every text, kept for as long as the text object is the same record and the fonts are the same. */
225
+ #textLayouts = new WeakMap();
226
+ #textLayoutsFontRevision = -1;
227
+ #applyingAfterRender = false;
228
+ #unsubscribeEngine = null;
229
+ /** The last payload handed to `onAutoSave`, so a timer that fires with no real change does not serialize again. */
230
+ #lastAutosavedJson = null;
231
+ /** The browser said `pagehide` and the page has not come back (`pageshow`): the saves made now are the page's last ones. */
232
+ #pageIsLeaving = false;
233
+ /** A text was being typed at the last change of the engine (its field is on the page). */
234
+ #wasEditingText = false;
235
+ /** The board is about to take the keyboard back from a text field that left the page (asked for the next frame). */
236
+ #keyboardReturnQueued = false;
237
+ #loadedWorkspaceSettings = null;
238
+ /** 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). */
239
+ #scribbleFrame = null;
240
+ #scribbleClockLast = null;
241
+ constructor(initialProps = {}) {
242
+ this.props = { ...DEFAULT_HOST_PROPS, ...initialProps };
243
+ this.engine = new EngineCore({ measureText: this.#measureText });
320
244
  this.engine.wireframeMode = this.props.wireframeMode;
321
245
  // The font the person chose for their texts the last time: the first text of this board starts with it too (null where nothing is kept).
322
- var preferredTextFontFamily = readPreferredTextFontFamily();
246
+ const preferredTextFontFamily = readPreferredTextFontFamily();
323
247
  if (preferredTextFontFamily)
324
248
  this.engine.setPreferredTextFontFamily(preferredTextFontFamily);
325
249
  this.controller = new PointerController(this.engine, {
326
- snapEnabled: function () { return true; },
327
- onStrokeFinished: function (stroke, handLine) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_handleStrokeFinished).call(_this, stroke, handLine); },
328
- onGestureChange: function (kind) {
329
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { gestureKind: kind });
330
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_announceWidgetResize).call(_this, kind);
250
+ snapEnabled: () => true,
251
+ onStrokeFinished: (stroke, handLine) => this.#handleStrokeFinished(stroke, handLine),
252
+ onGestureChange: (kind) => {
253
+ this.#updateUi({ gestureKind: kind });
254
+ this.#announceWidgetResize(kind);
331
255
  },
332
- onActivate: function (id) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_handleActivate).call(_this, id); },
333
- plainCardChrome: function () { return !_this.props.advancedFeatures; }
256
+ onActivate: (id) => this.#handleActivate(id),
257
+ plainCardChrome: () => !this.props.advancedFeatures
334
258
  });
335
259
  this.engineStore = {
336
- subscribe: function (run) {
337
- run(_this.engine.state);
338
- return _this.engine.subscribe(run);
260
+ subscribe: (run) => {
261
+ run(this.engine.state);
262
+ return this.engine.subscribe(run);
339
263
  }
340
264
  };
341
- this.uiStore = __classPrivateFieldGet(this, _CanvasHost_ui, "f");
342
- __classPrivateFieldSet(this, _CanvasHost_scheduler, createAutosaveScheduler({
343
- getDelayMs: function () { return _this.props.autosaveDelayMs; },
344
- getMaxWaitMs: function () { return _this.props.autosaveMaxWaitMs; },
345
- isSuspended: function () { return _this.props.suspendAutosave; },
346
- save: function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_runAutosave).call(_this); },
347
- getRetryDelayMs: function (failuresInARow) { var _a; return (_a = _this.props.autosaveRetryDelaysMs[failuresInARow - 1]) !== null && _a !== void 0 ? _a : 0; },
348
- onSaveFailed: function (error) {
349
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { saveState: 'dirty' });
265
+ this.uiStore = this.#ui;
266
+ this.#scheduler = createAutosaveScheduler({
267
+ getDelayMs: () => this.props.autosaveDelayMs,
268
+ getMaxWaitMs: () => this.props.autosaveMaxWaitMs,
269
+ isSuspended: () => this.props.suspendAutosave,
270
+ save: () => this.#runAutosave(),
271
+ getRetryDelayMs: (failuresInARow) => this.props.autosaveRetryDelaysMs[failuresInARow - 1] ?? 0,
272
+ onSaveFailed: (error) => {
273
+ this.#updateUi({ saveState: 'dirty' });
350
274
  canvasWarn('Canvas: autosave failed, the changes stay unsaved and the save is tried again', error);
351
275
  }
352
- }), "f");
353
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_wireEngineHooks).call(this);
354
- __classPrivateFieldSet(this, _CanvasHost_unsubscribeEngine, this.engine.subscribe(function (state) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onEngineState).call(_this, state); }), "f");
276
+ });
277
+ this.#wireEngineHooks();
278
+ this.#unsubscribeEngine = this.engine.subscribe((state) => this.#onEngineState(state));
355
279
  setCanvasLogsEnabled(this.props.showLogs);
356
280
  }
357
281
  // ────────────────────────────────────────────────────── props and ui
358
282
  /** The page changed some props. */
359
- CanvasHost.prototype.setProps = function (patch) {
360
- var _this = this;
361
- var previous = this.props;
362
- this.props = __assign(__assign({}, previous), patch);
283
+ setProps(patch) {
284
+ const previous = this.props;
285
+ this.props = { ...previous, ...patch };
363
286
  if (this.props.showLogs !== previous.showLogs)
364
287
  setCanvasLogsEnabled(this.props.showLogs);
365
288
  if (this.props.wireframeMode !== previous.wireframeMode)
366
289
  this.engine.wireframeMode = this.props.wireframeMode;
367
290
  if (this.props.widgetNameRevision !== previous.widgetNameRevision || this.props.getWidgetName !== previous.getWidgetName) {
368
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { nameRevision: __classPrivateFieldGet(this, _CanvasHost_ui, "f").value.nameRevision + 1 });
291
+ this.#updateUi({ nameRevision: this.#ui.value.nameRevision + 1 });
369
292
  }
370
293
  if (this.props.onAfterRender && !previous.onAfterRender)
371
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_queueAfterRender).call(this);
294
+ this.#queueAfterRender();
372
295
  if (this.props.showDrawingTools !== previous.showDrawingTools)
373
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_dropToolsThePageHides).call(this);
296
+ this.#dropToolsThePageHides();
374
297
  if (this.props.isExternalDataLoading !== previous.isExternalDataLoading) {
375
- queueMicrotask(function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_syncEmptyHintGate).call(_this); });
298
+ queueMicrotask(() => this.#syncEmptyHintGate());
376
299
  }
377
300
  if (this.props.workspaceId !== previous.workspaceId ||
378
301
  this.props.userId !== previous.userId ||
379
302
  this.props.workspaceFonts !== previous.workspaceFonts) {
380
- void __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_syncWorkspaceContext).call(this);
303
+ void this.#syncWorkspaceContext();
381
304
  }
382
- };
305
+ }
306
+ #compactStylePatch(fields) {
307
+ const compact = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
308
+ return Object.keys(compact).length > 0 ? compact : undefined;
309
+ }
383
310
  /** Persists tool style changes for this workspace (called from the selection panel). */
384
- CanvasHost.prototype.persistWorkspaceStyle = function (patch) {
385
- var workspaceId = this.props.workspaceId;
311
+ persistWorkspaceStyle(patch) {
312
+ const workspaceId = this.props.workspaceId;
386
313
  if (!workspaceId)
387
314
  return;
388
- var textPatch = patch.fontFamily !== undefined ||
315
+ const textPatch = patch.fontFamily !== undefined ||
389
316
  patch.fontSize !== undefined ||
390
317
  patch.fontWeight !== undefined ||
391
318
  patch.fontStyle !== undefined ||
392
319
  patch.color !== undefined ||
393
320
  patch.align !== undefined ||
394
321
  patch.underline !== undefined
395
- ? __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_compactStylePatch).call(this, {
322
+ ? this.#compactStylePatch({
396
323
  fontFamily: patch.fontFamily,
397
324
  fontSize: patch.fontSize,
398
325
  fontWeight: patch.fontWeight,
@@ -402,13 +329,13 @@ var CanvasHost = /** @class */ (function () {
402
329
  underline: patch.underline
403
330
  })
404
331
  : undefined;
405
- var paintPatch = patch.fill !== undefined ||
332
+ const paintPatch = patch.fill !== undefined ||
406
333
  patch.stroke !== undefined ||
407
334
  patch.strokeWidth !== undefined ||
408
335
  patch.strokeStyle !== undefined ||
409
336
  patch.opacity !== undefined ||
410
337
  patch.roundness !== undefined
411
- ? __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_compactStylePatch).call(this, {
338
+ ? this.#compactStylePatch({
412
339
  fill: patch.fill,
413
340
  stroke: patch.stroke,
414
341
  strokeWidth: patch.strokeWidth,
@@ -419,145 +346,245 @@ var CanvasHost = /** @class */ (function () {
419
346
  : undefined;
420
347
  if (!textPatch && !paintPatch)
421
348
  return;
422
- saveWorkspaceToolSettingsDebounced({ workspaceId: workspaceId, userId: this.props.userId }, { text: textPatch, paint: paintPatch });
423
- };
349
+ saveWorkspaceToolSettingsDebounced({ workspaceId, userId: this.props.userId }, { text: textPatch, paint: paintPatch });
350
+ }
351
+ async #syncWorkspaceContext() {
352
+ await ensureInterFontLoaded();
353
+ const fonts = this.props.workspaceFonts ?? [];
354
+ setWorkspaceFontFamilies(fonts.map((font) => font.family));
355
+ await registerWorkspaceFonts(fonts);
356
+ this.engine.notifyFontsChanged();
357
+ const workspaceId = this.props.workspaceId;
358
+ if (!workspaceId)
359
+ return;
360
+ this.#loadedWorkspaceSettings = loadWorkspaceToolSettings({ workspaceId, userId: this.props.userId });
361
+ const textFamily = this.#loadedWorkspaceSettings?.text?.fontFamily;
362
+ if (textFamily) {
363
+ this.engine.setPreferredTextFontFamily(textFamily);
364
+ writePreferredTextFontFamily(textFamily);
365
+ }
366
+ else {
367
+ this.engine.setPreferredTextFontFamily(TEXT_DEFAULTS.fontFamily);
368
+ }
369
+ this.engine.setWorkspaceToolDefaults({
370
+ text: this.#loadedWorkspaceSettings?.text ?? null,
371
+ paint: this.#loadedWorkspaceSettings?.paint ?? null
372
+ });
373
+ }
374
+ /**
375
+ * A tool whose button the page hides must not stay armed: once the page takes the drawing tools off (after the first
376
+ * generation) the pencil, the eraser, the arrow and the text go, and the Select tool takes over. The letter keys are
377
+ * ignored for them as well (see `tools`). The shapes stay: they are not part of the drawing group.
378
+ */
379
+ #dropToolsThePageHides() {
380
+ if (this.props.showDrawingTools)
381
+ return;
382
+ const { tool } = this.engine.state;
383
+ const drawingGroup = ['draw', 'erase', 'arrow', 'text'];
384
+ if (drawingGroup.includes(tool))
385
+ this.engine.setTool('select');
386
+ }
387
+ /**
388
+ * A widget card is being stretched (or the stretch ended): the page is told, so it can let the pointer through the live
389
+ * widget laid over the card. Sent once at each end of the gesture.
390
+ */
391
+ #announceWidgetResize(kind) {
392
+ if (kind === 'resize') {
393
+ if (this.#resizingWidgetId !== null)
394
+ return;
395
+ const widgetId = selectedWidgetId(this.engine);
396
+ if (!widgetId)
397
+ return;
398
+ this.#resizingWidgetId = widgetId;
399
+ announceWidgetPointerBlock({ widgetId, active: true });
400
+ return;
401
+ }
402
+ if (this.#resizingWidgetId === null)
403
+ return;
404
+ this.#resizingWidgetId = null;
405
+ announceWidgetPointerBlock({ widgetId: null, active: false });
406
+ }
424
407
  /** The shell gives the host the words of the page's language. */
425
- CanvasHost.prototype.setTranslator = function (translate) {
408
+ setTranslator(translate) {
426
409
  if (translate === this.translate)
427
410
  return;
428
411
  this.translate = translate;
429
412
  // The names drawn on widget cards are made with these words: the views read them again.
430
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { nameRevision: __classPrivateFieldGet(this, _CanvasHost_ui, "f").value.nameRevision + 1 });
431
- };
432
- Object.defineProperty(CanvasHost.prototype, "ui", {
433
- get: function () {
434
- return __classPrivateFieldGet(this, _CanvasHost_ui, "f").value;
435
- },
436
- enumerable: false,
437
- configurable: true
438
- });
439
- CanvasHost.prototype.updateUi = function (patch) {
440
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, patch);
441
- };
442
- Object.defineProperty(CanvasHost.prototype, "isLoading", {
443
- /** True while the board is loading or the page says it is (the loader shows, input waits). */
444
- get: function () {
445
- return __classPrivateFieldGet(this, _CanvasHost_ui, "f").value.loadPhase !== 'ready' || this.props.isExternalDataLoading;
446
- },
447
- enumerable: false,
448
- configurable: true
449
- });
450
- Object.defineProperty(CanvasHost.prototype, "tools", {
451
- /** The tools the page lets people use: the drawing group is the page's to hide, the shapes are always there. */
452
- get: function () {
453
- return { drawing: this.props.showDrawingTools };
454
- },
455
- enumerable: false,
456
- configurable: true
457
- });
413
+ this.#updateUi({ nameRevision: this.#ui.value.nameRevision + 1 });
414
+ }
415
+ get ui() {
416
+ return this.#ui.value;
417
+ }
418
+ updateUi(patch) {
419
+ this.#updateUi(patch);
420
+ }
421
+ #updateUi(patch) {
422
+ if (this.#destroyed)
423
+ return;
424
+ const current = this.#ui.value;
425
+ for (const key of Object.keys(patch)) {
426
+ if (!Object.is(patch[key], current[key])) {
427
+ this.#ui.set({ ...current, ...patch });
428
+ return;
429
+ }
430
+ }
431
+ }
432
+ /** True while the board is loading or the page says it is (the loader shows, input waits). */
433
+ get isLoading() {
434
+ return this.#ui.value.loadPhase !== 'ready' || this.props.isExternalDataLoading;
435
+ }
436
+ /** The tools the page lets people use: the drawing group is the page's to hide, the shapes are always there. */
437
+ get tools() {
438
+ return { drawing: this.props.showDrawingTools };
439
+ }
458
440
  // ────────────────────────────────────────────────────── lifecycle
459
441
  /** The shell mounted: the board element exists and has a size. Starts listening and loads the data the page gave. */
460
- CanvasHost.prototype.attach = function (root, board) {
461
- var _this = this;
462
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
442
+ attach(root, board) {
443
+ if (this.#destroyed)
463
444
  return;
464
- __classPrivateFieldSet(this, _CanvasHost_root, root, "f");
465
- __classPrivateFieldSet(this, _CanvasHost_board, board, "f");
466
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_measureBoard).call(this);
445
+ this.#root = root;
446
+ this.#board = board;
447
+ this.#measureBoard();
467
448
  if (typeof ResizeObserver !== 'undefined') {
468
- __classPrivateFieldSet(this, _CanvasHost_resizeObserver, new ResizeObserver(function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_measureBoard).call(_this); }), "f");
469
- __classPrivateFieldGet(this, _CanvasHost_resizeObserver, "f").observe(board);
470
- }
471
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, window, 'keydown', function (event) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onKeyDown).call(_this, event); }, true);
472
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, window, 'keyup', function (event) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onKeyUp).call(_this, event); });
473
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, window, 'blur', function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onWindowBlur).call(_this); });
474
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, window, 'paste', function (event) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onPaste).call(_this, event); });
475
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, window, 'pagehide', function () {
449
+ this.#resizeObserver = new ResizeObserver(() => this.#measureBoard());
450
+ this.#resizeObserver.observe(board);
451
+ }
452
+ this.#listen(window, 'keydown', (event) => this.#onKeyDown(event), true);
453
+ this.#listen(window, 'keyup', (event) => this.#onKeyUp(event));
454
+ this.#listen(window, 'blur', () => this.#onWindowBlur());
455
+ this.#listen(window, 'paste', (event) => this.#onPaste(event));
456
+ this.#listen(window, 'pagehide', () => {
476
457
  flushWorkspaceToolSettingsPending();
477
458
  // Said before the flush, and kept until the page comes back: a save that waits behind another one (the buffer runs one
478
459
  // at a time) is made after this handler returns, and it too is a save of a page that is going away.
479
- __classPrivateFieldSet(_this, _CanvasHost_pageIsLeaving, true, "f");
480
- void __classPrivateFieldGet(_this, _CanvasHost_scheduler, "f").flush();
460
+ this.#pageIsLeaving = true;
461
+ void this.#scheduler.flush();
481
462
  });
482
463
  // A page that went into the browser's back-forward cache and is shown again is not leaving any more.
483
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, window, 'pageshow', function () {
484
- __classPrivateFieldSet(_this, _CanvasHost_pageIsLeaving, false, "f");
464
+ this.#listen(window, 'pageshow', () => {
465
+ this.#pageIsLeaving = false;
485
466
  });
486
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, document, 'pointerdown', function (event) {
487
- var pointer = event;
467
+ this.#listen(document, 'pointerdown', (event) => {
468
+ const pointer = event;
488
469
  if (pointer.button !== 0)
489
470
  return;
490
- if (_this.engine.state.selectedIds.length === 0)
471
+ if (this.engine.state.selectedIds.length === 0)
491
472
  return;
492
- if (isCanvasOwnedTarget(pointer, __classPrivateFieldGet(_this, _CanvasHost_root, "f")))
473
+ if (isCanvasOwnedTarget(pointer, this.#root))
493
474
  return;
494
- if (_this.engine.state.editingTextId !== null)
495
- _this.engine.endTextEdit();
496
- _this.engine.clearSelection();
475
+ if (this.engine.state.editingTextId !== null)
476
+ this.engine.endTextEdit();
477
+ this.engine.clearSelection();
497
478
  }, true);
498
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, document, 'visibilitychange', function () {
479
+ this.#listen(document, 'visibilitychange', () => {
499
480
  if (document.visibilityState === 'hidden')
500
- void __classPrivateFieldGet(_this, _CanvasHost_scheduler, "f").flush();
481
+ void this.#scheduler.flush();
501
482
  });
502
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, board, 'wheel', function (event) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onWheel).call(_this, event); }, false, { passive: false });
483
+ this.#listen(board, 'wheel', (event) => this.#onWheel(event), false, { passive: false });
503
484
  if (typeof document !== 'undefined' && document.fonts && typeof document.fonts.addEventListener === 'function') {
504
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_listen).call(this, document.fonts, 'loadingdone', function () { return _this.engine.notifyFontsChanged(); });
485
+ this.#listen(document.fonts, 'loadingdone', () => this.engine.notifyFontsChanged());
505
486
  }
506
- void ensureInterFontLoaded().then(function () {
507
- _this.engine.notifyFontsChanged();
508
- void __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_syncWorkspaceContext).call(_this);
487
+ void ensureInterFontLoaded().then(() => {
488
+ this.engine.notifyFontsChanged();
489
+ void this.#syncWorkspaceContext();
509
490
  });
510
- void __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_start).call(this);
511
- };
491
+ void this.#start();
492
+ }
493
+ async #start() {
494
+ // One turn of the event loop first: the page that mounted the shell assigns its reference to it (`bind:this`) in
495
+ // the same flush as this mount, and `onReady` is the moment the page starts to call the host's functions.
496
+ await Promise.resolve();
497
+ if (this.#destroyed)
498
+ return;
499
+ const initial = this.props.initialData;
500
+ this.#closeEmptyHintGate();
501
+ if (initial) {
502
+ try {
503
+ await this.loadCanvas(initial);
504
+ }
505
+ catch (error) {
506
+ console.error('Canvas: could not load the initial data', error);
507
+ }
508
+ }
509
+ if (this.#destroyed)
510
+ return;
511
+ // The first tool: the pencil, when the page shows the drawing tools (a board opens ready for a sketch), else Select.
512
+ this.engine.setTool(this.props.showDrawingTools ? 'draw' : 'select');
513
+ this.#updateUi({ loadPhase: 'ready' });
514
+ this.#queueAfterRender();
515
+ markCanvasOpenStep(CANVAS_OPEN_MARKS.READY);
516
+ try {
517
+ this.props.onReady?.();
518
+ }
519
+ catch (error) {
520
+ canvasWarn('Canvas: onReady failed', error);
521
+ }
522
+ queueMicrotask(() => queueMicrotask(() => this.#syncEmptyHintGate()));
523
+ }
524
+ #openEmptyHintGate() {
525
+ if (!this.#ui.value.emptyHintGateOpen)
526
+ this.#updateUi({ emptyHintGateOpen: true });
527
+ }
528
+ #closeEmptyHintGate() {
529
+ if (this.#ui.value.emptyHintGateOpen)
530
+ this.#updateUi({ emptyHintGateOpen: false });
531
+ }
532
+ /** Opens the empty-board hint gate only when the host and the page are done loading (see `emptyBoardHint.ts`). */
533
+ #syncEmptyHintGate() {
534
+ if (this.#destroyed)
535
+ return;
536
+ const waiting = this.#ui.value.loadPhase !== 'ready' ||
537
+ this.#loadDepth > 0 ||
538
+ this.engine.state.loading ||
539
+ this.props.isExternalDataLoading;
540
+ if (waiting) {
541
+ this.#closeEmptyHintGate();
542
+ return;
543
+ }
544
+ this.#openEmptyHintGate();
545
+ }
512
546
  /** The shell is going away: hands the page its last chance to keep the board, then lets go of everything. */
513
- CanvasHost.prototype.destroy = function () {
514
- var _a, _b, _c, _d;
515
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
547
+ destroy() {
548
+ if (this.#destroyed)
516
549
  return;
517
550
  try {
518
- (_b = (_a = this.props).onBeforeUnmount) === null || _b === void 0 ? void 0 : _b.call(_a, this.saveCanvas());
551
+ this.props.onBeforeUnmount?.(this.saveCanvas());
519
552
  }
520
553
  catch (error) {
521
554
  canvasWarn('Canvas: onBeforeUnmount failed', error);
522
555
  }
523
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_announceWidgetResize).call(this, null);
524
- __classPrivateFieldSet(this, _CanvasHost_destroyed, true, "f");
525
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cancelLongPress).call(this);
526
- if (__classPrivateFieldGet(this, _CanvasHost_scribbleFrame, "f") !== null && typeof cancelAnimationFrame === 'function')
527
- cancelAnimationFrame(__classPrivateFieldGet(this, _CanvasHost_scribbleFrame, "f"));
528
- __classPrivateFieldSet(this, _CanvasHost_scribbleFrame, null, "f");
529
- __classPrivateFieldSet(this, _CanvasHost_scribbleClockLast, null, "f");
530
- __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").dispose();
531
- for (var _i = 0, _e = __classPrivateFieldGet(this, _CanvasHost_removeListeners, "f"); _i < _e.length; _i++) {
532
- var remove = _e[_i];
556
+ this.#announceWidgetResize(null);
557
+ this.#destroyed = true;
558
+ this.#cancelLongPress();
559
+ if (this.#scribbleFrame !== null && typeof cancelAnimationFrame === 'function')
560
+ cancelAnimationFrame(this.#scribbleFrame);
561
+ this.#scribbleFrame = null;
562
+ this.#scribbleClockLast = null;
563
+ this.#scheduler.dispose();
564
+ for (const remove of this.#removeListeners)
533
565
  remove();
534
- }
535
- __classPrivateFieldSet(this, _CanvasHost_removeListeners, [], "f");
536
- (_c = __classPrivateFieldGet(this, _CanvasHost_resizeObserver, "f")) === null || _c === void 0 ? void 0 : _c.disconnect();
537
- __classPrivateFieldSet(this, _CanvasHost_resizeObserver, null, "f");
538
- (_d = __classPrivateFieldGet(this, _CanvasHost_unsubscribeEngine, "f")) === null || _d === void 0 ? void 0 : _d.call(this);
539
- __classPrivateFieldSet(this, _CanvasHost_unsubscribeEngine, null, "f");
566
+ this.#removeListeners = [];
567
+ this.#resizeObserver?.disconnect();
568
+ this.#resizeObserver = null;
569
+ this.#unsubscribeEngine?.();
570
+ this.#unsubscribeEngine = null;
540
571
  this.controller.dispose();
541
572
  this.engine.dispose();
542
573
  this.conversions.clear();
543
- __classPrivateFieldSet(this, _CanvasHost_root, null, "f");
544
- __classPrivateFieldSet(this, _CanvasHost_board, null, "f");
545
- };
546
- Object.defineProperty(CanvasHost.prototype, "boardElement", {
547
- /** The element the board's pointer events come from. */
548
- get: function () {
549
- return __classPrivateFieldGet(this, _CanvasHost_board, "f");
550
- },
551
- enumerable: false,
552
- configurable: true
553
- });
554
- Object.defineProperty(CanvasHost.prototype, "rootElement", {
555
- get: function () {
556
- return __classPrivateFieldGet(this, _CanvasHost_root, "f");
557
- },
558
- enumerable: false,
559
- configurable: true
560
- });
574
+ this.#root = null;
575
+ this.#board = null;
576
+ }
577
+ #listen(target, type, listener, capture = false, options = {}) {
578
+ target.addEventListener(type, listener, { capture, ...options });
579
+ this.#removeListeners.push(() => target.removeEventListener(type, listener, { capture }));
580
+ }
581
+ /** The element the board's pointer events come from. */
582
+ get boardElement() {
583
+ return this.#board;
584
+ }
585
+ get rootElement() {
586
+ return this.#root;
587
+ }
561
588
  /**
562
589
  * Gives the board the keyboard.
563
590
  *
@@ -565,251 +592,742 @@ var CanvasHost = /** @class */ (function () {
565
592
  * when the last thing the person did was a key, and a press on the board is not asking for a ring (the keyboard still
566
593
  * has the focus, and a Tab or an arrow shows it). Browsers that do not know the option ignore it.
567
594
  */
568
- CanvasHost.prototype.focusBoard = function (options) {
569
- var _a;
570
- if (options === void 0) { options = {}; }
595
+ focusBoard(options = {}) {
571
596
  try {
572
- var focusOptions = __assign({ preventScroll: true }, options);
573
- (_a = __classPrivateFieldGet(this, _CanvasHost_board, "f")) === null || _a === void 0 ? void 0 : _a.focus(focusOptions);
597
+ const focusOptions = { preventScroll: true, ...options };
598
+ this.#board?.focus(focusOptions);
574
599
  }
575
- catch (_b) {
600
+ catch {
576
601
  // A board that cannot take the focus keeps working.
577
602
  }
578
- };
579
- CanvasHost.prototype.handlePointerDown = function (event) {
580
- var _a;
581
- if (this.isLoading || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
603
+ }
604
+ // ────────────────────────────────────────────────────── the board element
605
+ #measureBoard() {
606
+ const board = this.#board;
607
+ if (!board)
608
+ return;
609
+ this.engine.setViewSize({ width: board.clientWidth, height: board.clientHeight }, this.props.keepCenterOnResize);
610
+ }
611
+ /** The board on the page (its rectangle and its layout size), for everything the page lays over it. */
612
+ #frame() {
613
+ const board = this.#board;
614
+ if (!board)
615
+ return null;
616
+ const rect = board.getBoundingClientRect();
617
+ return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, layoutWidth: board.clientWidth, layoutHeight: board.clientHeight };
618
+ }
619
+ /** How much the page scales the board (a partner that zooms its whole screen): rendered size over layout size. */
620
+ #cssScale() {
621
+ const frame = this.#frame();
622
+ if (!frame || !frame.layoutWidth || !frame.layoutHeight)
623
+ return { x: 1, y: 1 };
624
+ return { x: frame.width / frame.layoutWidth || 1, y: frame.height / frame.layoutHeight || 1 };
625
+ }
626
+ #pointerInput(event, kind) {
627
+ const frame = this.#frame();
628
+ if (!frame)
629
+ return null;
630
+ const scaleX = frame.width / (frame.layoutWidth || frame.width || 1) || 1;
631
+ const scaleY = frame.height / (frame.layoutHeight || frame.height || 1) || 1;
632
+ const toBoard = (clientX, clientY) => ({ x: (clientX - frame.left) / scaleX, y: (clientY - frame.top) / scaleY });
633
+ const point = toBoard(event.clientX, event.clientY);
634
+ const pointerEvent = event;
635
+ const type = kind ?? (pointerEvent.pointerType === 'pen' ? 'pen' : pointerEvent.pointerType === 'touch' ? 'touch' : 'mouse');
636
+ const pressureOf = (sample) => typeof sample.pressure === 'number' && Number.isFinite(sample.pressure) ? { pressure: sample.pressure } : {};
637
+ const coalesced = typeof pointerEvent.getCoalescedEvents === 'function'
638
+ ? pointerEvent.getCoalescedEvents().map((sample) => ({ ...toBoard(sample.clientX, sample.clientY), time: sample.timeStamp, ...pressureOf(sample) }))
639
+ : undefined;
640
+ return {
641
+ pointerId: pointerEvent.pointerId ?? 1,
642
+ pointerType: type,
643
+ x: point.x,
644
+ y: point.y,
645
+ button: event.button,
646
+ time: event.timeStamp,
647
+ shiftKey: event.shiftKey,
648
+ altKey: event.altKey,
649
+ metaKey: event.metaKey,
650
+ ctrlKey: event.ctrlKey,
651
+ ...pressureOf(pointerEvent),
652
+ ...(coalesced && coalesced.length > 1 ? { coalesced } : {})
653
+ };
654
+ }
655
+ handlePointerDown(event) {
656
+ if (this.isLoading || this.#destroyed)
582
657
  return;
583
- var input = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_pointerInput).call(this, event);
658
+ const input = this.#pointerInput(event);
584
659
  if (!input)
585
660
  return;
586
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_closeTransientUi).call(this);
661
+ this.#closeTransientUi();
587
662
  this.focusBoard({ focusVisible: false });
588
- __classPrivateFieldSet(this, _CanvasHost_touchWasLast, input.pointerType === 'touch', "f");
663
+ this.#touchWasLast = input.pointerType === 'touch';
589
664
  // A second finger is a pinch, never a long press.
590
665
  if (event.isPrimary === false)
591
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cancelLongPress).call(this);
592
- var captured = this.controller.pointerDown(input);
666
+ this.#cancelLongPress();
667
+ const captured = this.controller.pointerDown(input);
593
668
  if (captured) {
594
669
  event.preventDefault();
595
670
  try {
596
- (_a = __classPrivateFieldGet(this, _CanvasHost_board, "f")) === null || _a === void 0 ? void 0 : _a.setPointerCapture(event.pointerId);
671
+ this.#board?.setPointerCapture(event.pointerId);
597
672
  }
598
- catch (_b) {
673
+ catch {
599
674
  // A pointer that is already gone cannot be captured: the gesture ends with it.
600
675
  }
601
676
  }
602
677
  if (input.pointerType === 'touch' && event.isPrimary !== false)
603
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_startLongPress).call(this, input);
604
- };
678
+ this.#startLongPress(input);
679
+ }
680
+ // ────────────────────────────────────────────────────── a finger's long press
681
+ #startLongPress(input) {
682
+ this.#cancelLongPress();
683
+ // Only the select tool has a menu to open: with a pen, an eraser or a shape tool the finger is drawing.
684
+ if (this.engine.state.tool !== 'select' || this.engine.state.editingTextId)
685
+ return;
686
+ const timer = setTimeout(() => this.#fireLongPress(), TOUCH_LONG_PRESS_DELAY_MS);
687
+ this.#longPress = { timer, pointerId: input.pointerId, x: input.x, y: input.y };
688
+ }
689
+ #cancelLongPress() {
690
+ if (!this.#longPress)
691
+ return;
692
+ clearTimeout(this.#longPress.timer);
693
+ this.#longPress = null;
694
+ }
695
+ #fireLongPress() {
696
+ const pending = this.#longPress;
697
+ this.#longPress = null;
698
+ if (!pending || this.#destroyed || this.isLoading)
699
+ return;
700
+ // What the finger started (a pan, a move that has not moved yet, a marquee) ends here: the press became a menu.
701
+ this.controller.pointerCancel({ pointerId: pending.pointerId });
702
+ this.controller.prepareContextMenu({ x: pending.x, y: pending.y });
703
+ this.#menuFinger = { pointerId: pending.pointerId, liftedAt: null };
704
+ this.#updateUi({ contextMenu: { x: pending.x, y: pending.y, byTouch: true }, shapesMenuOpen: false, selectionPanelDismissed: true });
705
+ }
605
706
  /**
606
707
  * Is the menu still held by the finger that opened it? True while that finger is down, and for a moment after it lifts:
607
708
  * the browser sends the finger's `click` a moment after `pointerup`, to whatever is under it, and that is not a choice.
608
709
  * The menu asks before it acts on an item, so a long press never picks the entry that opened under the finger.
609
710
  */
610
- CanvasHost.prototype.isMenuHeldByItsFinger = function () {
611
- var finger = __classPrivateFieldGet(this, _CanvasHost_menuFinger, "f");
711
+ isMenuHeldByItsFinger() {
712
+ const finger = this.#menuFinger;
612
713
  if (!finger)
613
714
  return false;
614
715
  if (finger.liftedAt === null)
615
716
  return true;
616
717
  if (Date.now() - finger.liftedAt <= TOUCH_MENU_RELEASE_GRACE_MS)
617
718
  return true;
618
- __classPrivateFieldSet(this, _CanvasHost_menuFinger, null, "f");
719
+ this.#menuFinger = null;
619
720
  return false;
620
- };
621
- CanvasHost.prototype.handlePointerMove = function (event) {
622
- if (this.isLoading || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
721
+ }
722
+ #noteFingerLifted(pointerId) {
723
+ if (this.#menuFinger && this.#menuFinger.pointerId === pointerId && this.#menuFinger.liftedAt === null)
724
+ this.#menuFinger.liftedAt = Date.now();
725
+ }
726
+ handlePointerMove(event) {
727
+ if (this.isLoading || this.#destroyed)
623
728
  return;
624
- var input = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_pointerInput).call(this, event);
729
+ const input = this.#pointerInput(event);
625
730
  if (!input)
626
731
  return;
627
- var resting = __classPrivateFieldGet(this, _CanvasHost_longPress, "f");
732
+ const resting = this.#longPress;
628
733
  if (resting && resting.pointerId === input.pointerId && Math.hypot(input.x - resting.x, input.y - resting.y) > TOUCH_LONG_PRESS_SLOP) {
629
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cancelLongPress).call(this);
734
+ this.#cancelLongPress();
630
735
  }
631
736
  this.controller.pointerMove(input);
632
- };
633
- CanvasHost.prototype.handlePointerUp = function (event) {
634
- var _a;
635
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
737
+ }
738
+ handlePointerUp(event) {
739
+ if (this.#destroyed)
636
740
  return;
637
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cancelLongPress).call(this);
638
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_noteFingerLifted).call(this, event.pointerId);
639
- var input = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_pointerInput).call(this, event);
741
+ this.#cancelLongPress();
742
+ this.#noteFingerLifted(event.pointerId);
743
+ const input = this.#pointerInput(event);
640
744
  try {
641
- (_a = __classPrivateFieldGet(this, _CanvasHost_board, "f")) === null || _a === void 0 ? void 0 : _a.releasePointerCapture(event.pointerId);
745
+ this.#board?.releasePointerCapture(event.pointerId);
642
746
  }
643
- catch (_b) {
747
+ catch {
644
748
  // Nothing was captured.
645
749
  }
646
750
  if (input)
647
751
  this.controller.pointerUp(input);
648
- };
649
- CanvasHost.prototype.handlePointerCancel = function (event) {
650
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
752
+ }
753
+ handlePointerCancel(event) {
754
+ if (this.#destroyed)
651
755
  return;
652
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cancelLongPress).call(this);
653
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_noteFingerLifted).call(this, event.pointerId);
756
+ this.#cancelLongPress();
757
+ this.#noteFingerLifted(event.pointerId);
654
758
  this.controller.pointerCancel({ pointerId: event.pointerId });
655
- };
656
- CanvasHost.prototype.handlePointerLeave = function (event) {
759
+ }
760
+ handlePointerLeave(event) {
657
761
  if (event.pointerType === 'touch')
658
762
  return;
659
763
  this.controller.pointerLeave();
660
- };
661
- CanvasHost.prototype.handleContextMenu = function (event) {
662
- if (this.isLoading || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
764
+ }
765
+ #onWheel(event) {
766
+ if (this.isLoading || this.#destroyed)
767
+ return;
768
+ const base = this.#pointerInput(event, 'mouse');
769
+ if (!base)
770
+ return;
771
+ event.preventDefault();
772
+ const input = {
773
+ x: base.x,
774
+ y: base.y,
775
+ deltaX: event.deltaX,
776
+ deltaY: event.deltaY,
777
+ deltaMode: event.deltaMode,
778
+ shiftKey: event.shiftKey,
779
+ altKey: event.altKey,
780
+ metaKey: event.metaKey,
781
+ ctrlKey: event.ctrlKey
782
+ };
783
+ this.controller.wheel(input);
784
+ }
785
+ handleContextMenu(event) {
786
+ if (this.isLoading || this.#destroyed)
663
787
  return;
664
788
  event.preventDefault();
665
789
  // The browser's own menu for a long press (Android sends one) is kept from showing: the host's timer opens ours.
666
- var sentBy = event.pointerType;
667
- if (sentBy === 'touch' || (sentBy === undefined && __classPrivateFieldGet(this, _CanvasHost_touchWasLast, "f")))
790
+ const sentBy = event.pointerType;
791
+ if (sentBy === 'touch' || (sentBy === undefined && this.#touchWasLast))
668
792
  return;
669
- var input = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_pointerInput).call(this, event, 'mouse');
793
+ const input = this.#pointerInput(event, 'mouse');
670
794
  if (!input)
671
795
  return;
672
796
  this.focusBoard({ focusVisible: false });
673
- __classPrivateFieldSet(this, _CanvasHost_menuFinger, null, "f");
797
+ this.#menuFinger = null;
674
798
  this.controller.prepareContextMenu({ x: input.x, y: input.y });
675
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { contextMenu: { x: input.x, y: input.y }, shapesMenuOpen: false, selectionPanelDismissed: true });
676
- };
799
+ this.#updateUi({ contextMenu: { x: input.x, y: input.y }, shapesMenuOpen: false, selectionPanelDismissed: true });
800
+ }
677
801
  /** A picture is being dragged over the board: say that it can be dropped. */
678
- CanvasHost.prototype.handleDragOver = function (event) {
679
- var _a;
802
+ handleDragOver(event) {
680
803
  if (this.isLoading)
681
804
  return;
682
- var types = (_a = event.dataTransfer) === null || _a === void 0 ? void 0 : _a.types;
805
+ const types = event.dataTransfer?.types;
683
806
  if (!types || !Array.from(types).includes('Files'))
684
807
  return;
685
808
  event.preventDefault();
686
809
  if (event.dataTransfer)
687
810
  event.dataTransfer.dropEffect = 'copy';
688
- };
811
+ }
689
812
  /** Pictures were dropped on the board: they land where the pointer is. */
690
- CanvasHost.prototype.handleDrop = function (event) {
691
- var _a, _b;
813
+ handleDrop(event) {
692
814
  if (this.isLoading)
693
815
  return;
694
- var files = Array.from((_b = (_a = event.dataTransfer) === null || _a === void 0 ? void 0 : _a.files) !== null && _b !== void 0 ? _b : []).filter(function (file) { return file.type.startsWith('image/') || /\.svg$/i.test(file.name); });
816
+ const files = Array.from(event.dataTransfer?.files ?? []).filter((file) => file.type.startsWith('image/') || /\.svg$/i.test(file.name));
695
817
  if (files.length === 0)
696
818
  return;
697
819
  event.preventDefault();
698
- var input = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_pointerInput).call(this, event, 'mouse');
699
- var at = input ? this.engine.toWorld({ x: input.x, y: input.y }) : undefined;
820
+ const input = this.#pointerInput(event, 'mouse');
821
+ const at = input ? this.engine.toWorld({ x: input.x, y: input.y }) : undefined;
700
822
  void this.insertImageFiles(files, at);
701
- };
823
+ }
824
+ #closeTransientUi() {
825
+ const { contextMenu, shapesMenuOpen } = this.#ui.value;
826
+ this.#menuFinger = null;
827
+ if (contextMenu || shapesMenuOpen)
828
+ this.#updateUi({ contextMenu: null, shapesMenuOpen: false });
829
+ }
830
+ // ────────────────────────────────────────────────────── keyboard and clipboard
831
+ #keyboardActions() {
832
+ return {
833
+ chooseTool: (tool) => this.chooseShortcutTool(tool),
834
+ save: () => this.saveNow(),
835
+ toggleShortcuts: () => this.#updateUi({ shortcutsOpen: !this.#ui.value.shortcutsOpen }),
836
+ closePanels: () => {
837
+ const { contextMenu, shapesMenuOpen, shortcutsOpen } = this.#ui.value;
838
+ if (!contextMenu && !shapesMenuOpen && !shortcutsOpen)
839
+ return false;
840
+ this.#updateUi({ contextMenu: null, shapesMenuOpen: false, shortcutsOpen: false });
841
+ return true;
842
+ },
843
+ afterCopy: () => this.#markClipboardAsOurs(),
844
+ spacePanChanged: (held) => this.#updateUi({ spacePan: held })
845
+ };
846
+ }
847
+ #keyboardHost(origin) {
848
+ let hasTextSelection = false;
849
+ try {
850
+ hasTextSelection = (window.getSelection()?.toString().length ?? 0) > 0;
851
+ }
852
+ catch {
853
+ hasTextSelection = false;
854
+ }
855
+ return {
856
+ engine: this.engine,
857
+ controller: this.controller,
858
+ actions: this.#keyboardActions(),
859
+ tools: this.tools,
860
+ typingInField: isEditableTarget(origin),
861
+ hasTextSelection,
862
+ selectorHintOpen: this.props.showElementSelector && this.props.elementSelectorActive
863
+ };
864
+ }
865
+ #onKeyDown(event) {
866
+ if (this.#destroyed || !this.#root || this.isLoading)
867
+ return;
868
+ if (!eventIsForScope(event, this.#root))
869
+ return;
870
+ const origin = getEventOrigin(event);
871
+ // A key pressed inside an open menu or dialog is that menu's (its typeahead, its arrows), not a tool's letter.
872
+ if (origin?.closest?.('[role="menu"], [role="dialog"], [role="listbox"]'))
873
+ return;
874
+ // A focused slider, tab list or list box keeps its arrow keys: they move its value, and not the selection on the board.
875
+ if (NAVIGATION_KEYS.has(event.key) && ownsNavigationKeys(origin))
876
+ return;
877
+ // A focused button, link or menu entry keeps its Space (the pan has its own button, and the hand tool).
878
+ if (event.code === 'Space' && isActivatableTarget(origin))
879
+ return;
880
+ const input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey, repeat: event.repeat };
881
+ // Shift, Alt and the like change what a running gesture does without moving the pointer.
882
+ if (event.key === 'Shift' || event.key === 'Alt' || event.key === 'Control' || event.key === 'Meta') {
883
+ this.controller.modifiersChanged({ shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
884
+ return;
885
+ }
886
+ let handled = false;
887
+ try {
888
+ handled = routeKeyDown(input, this.#keyboardHost(origin));
889
+ }
890
+ catch (error) {
891
+ canvasWarn('Canvas: a key press failed', error);
892
+ }
893
+ if (handled) {
894
+ event.preventDefault();
895
+ event.stopPropagation();
896
+ }
897
+ }
898
+ #onKeyUp(event) {
899
+ if (this.#destroyed || !this.#root)
900
+ return;
901
+ if (event.key === 'Shift' || event.key === 'Alt' || event.key === 'Control' || event.key === 'Meta') {
902
+ this.controller.modifiersChanged({ shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
903
+ return;
904
+ }
905
+ if (!eventIsForScope(event, this.#root)) {
906
+ // A Space released outside the canvas still ends the pan.
907
+ if (event.code === 'Space')
908
+ this.controller.setSpaceHeld(false);
909
+ return;
910
+ }
911
+ const input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey };
912
+ if (routeKeyUp(input, this.#keyboardHost(getEventOrigin(event)))) {
913
+ event.preventDefault();
914
+ this.#updateUi({ spacePan: false });
915
+ }
916
+ }
917
+ #onWindowBlur() {
918
+ releaseHeldKeys(this.#keyboardHost(null));
919
+ }
920
+ /** Cmd+C on the board puts a marker on the system clipboard, so the next paste is the board's, not an older picture's. */
921
+ #markClipboardAsOurs() {
922
+ try {
923
+ const clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;
924
+ void clipboard?.writeText?.(CLIPBOARD_MARKER).catch(() => undefined);
925
+ }
926
+ catch {
927
+ // A browser that refuses leaves the older clipboard in place: the paste then prefers its picture.
928
+ }
929
+ }
930
+ #onPaste(event) {
931
+ if (this.#destroyed || !this.#root || this.isLoading)
932
+ return;
933
+ if (!eventIsForScope(event, this.#root))
934
+ return;
935
+ if (this.engine.state.editingTextId)
936
+ return;
937
+ const origin = getEventOrigin(event);
938
+ if (isEditableTarget(origin))
939
+ return;
940
+ if (origin?.closest?.(PASTE_EXCLUDED_SELECTOR))
941
+ return;
942
+ const items = Array.from(event.clipboardData?.items ?? []);
943
+ const picture = items.find((item) => item.type.startsWith('image/'));
944
+ const pasteInside = this.engine.hasClipboard() && event.clipboardData?.getData('text/plain') === CLIPBOARD_MARKER;
945
+ if (picture && !pasteInside) {
946
+ const blob = picture.getAsFile();
947
+ if (!blob)
948
+ return;
949
+ event.preventDefault();
950
+ const at = this.engine.lastPointerWorld ?? undefined;
951
+ void this.insertImageFiles([blob], at);
952
+ return;
953
+ }
954
+ if (this.engine.hasClipboard()) {
955
+ event.preventDefault();
956
+ this.engine.paste();
957
+ }
958
+ }
959
+ // ────────────────────────────────────────────────────── engine hooks
960
+ #wireEngineHooks() {
961
+ const hooks = {
962
+ onDirty: () => this.#markDirty(),
963
+ // Typing is a change too: the letters are saved with the next save, before the typing ends and makes its undo step.
964
+ onDraftChange: () => this.#markDirty(),
965
+ onCleared: () => this.#safely(() => this.props.onCanvasCleared?.(), 'onCanvasCleared'),
966
+ onSelectionChange: (ids) => this.#onSelectionChange(ids),
967
+ confirmWidgetDeletion: (widgetId) => {
968
+ const ask = this.props.onWidgetShapeDeleting;
969
+ return ask ? ask(widgetId) : true;
970
+ },
971
+ onWidgetDuplicated: (sourceWidgetId, clone) => this.#onWidgetDuplicated(sourceWidgetId, clone),
972
+ onError: (message, error) => canvasWarn(`Canvas: ${message}`, error)
973
+ };
974
+ this.engine.hooks = hooks;
975
+ }
976
+ #safely(run, name) {
977
+ try {
978
+ run();
979
+ }
980
+ catch (error) {
981
+ canvasWarn(`Canvas: ${name} failed`, error);
982
+ }
983
+ }
984
+ #markDirty() {
985
+ if (this.#destroyed)
986
+ return;
987
+ this.#updateUi({ saveState: 'dirty' });
988
+ this.#safely(() => this.props.onCanvasDirty?.(), 'onCanvasDirty');
989
+ this.#scheduler.markChanged();
990
+ }
991
+ #onSelectionChange(ids) {
992
+ if (ids.length === 0)
993
+ return;
994
+ const selected = this.engine.selectedObjects();
995
+ const onlyAWidget = selected.length === 1 && selected[0].type === 'widget';
996
+ if (!onlyAWidget)
997
+ this.#safely(() => this.props.onNonWidgetSelected?.(), 'onNonWidgetSelected');
998
+ }
999
+ #onWidgetDuplicated(sourceWidgetId, clone) {
1000
+ const notify = this.props.onWidgetShapeDuplicated;
1001
+ if (!notify)
1002
+ return;
1003
+ // The page gets a view of the card, under the names the old canvas kept (`_widgetId`, `_objectId`).
1004
+ const view = hostObjectById(this.engine, clone.id);
1005
+ this.#safely(() => notify(sourceWidgetId, view), 'onWidgetShapeDuplicated');
1006
+ }
1007
+ #handleActivate(id) {
1008
+ const object = this.engine.getObject(id);
1009
+ if (!object || object.type !== 'widget')
1010
+ return;
1011
+ const notify = this.props.onWidgetImageClick;
1012
+ if (notify && object.widgetId)
1013
+ this.#safely(() => notify(object.widgetId), 'onWidgetImageClick');
1014
+ }
1015
+ /** After every change of the engine: the page's overlays are told to move, once a frame, when something they follow moved. */
1016
+ #onEngineState(state) {
1017
+ // The eraser's trail lives on the frame clock: it starts with the trail and stops when the trail is gone.
1018
+ if (state.scribble !== null)
1019
+ this.#startScribbleClock();
1020
+ const isEditingText = state.editingTextId !== null;
1021
+ if (this.#wasEditingText && !isEditingText)
1022
+ this.#takeKeyboardBackSoon();
1023
+ this.#wasEditingText = isEditingText;
1024
+ const last = this.#lastOverlayState;
1025
+ if (!last ||
1026
+ last.scene !== state.scene ||
1027
+ last.viewport !== state.viewport ||
1028
+ last.viewSize !== state.viewSize ||
1029
+ last.widgets !== state.widgets ||
1030
+ last.pending !== state.pending ||
1031
+ last.hoverWidgetId !== state.hoverWidgetId ||
1032
+ last.selectedIds !== state.selectedIds ||
1033
+ last.overlayDragActive !== state.overlayDragActive) {
1034
+ if (last && last.selectedIds !== state.selectedIds) {
1035
+ if (state.selectedIds.length === 0) {
1036
+ // Leave dismissal as the user left it.
1037
+ }
1038
+ else {
1039
+ const selected = state.selectedIds
1040
+ .map((id) => state.scene.find((object) => object.id === id))
1041
+ .filter((object) => object !== undefined);
1042
+ const widgetOnly = selected.length === 1 && selected[0].type === 'widget';
1043
+ this.#updateUi({ selectionPanelDismissed: widgetOnly });
1044
+ }
1045
+ }
1046
+ this.#lastOverlayState = {
1047
+ scene: state.scene,
1048
+ viewport: state.viewport,
1049
+ viewSize: state.viewSize,
1050
+ widgets: state.widgets,
1051
+ pending: state.pending,
1052
+ hoverWidgetId: state.hoverWidgetId,
1053
+ selectedIds: state.selectedIds,
1054
+ overlayDragActive: state.overlayDragActive
1055
+ };
1056
+ this.#queueAfterRender();
1057
+ }
1058
+ }
1059
+ /**
1060
+ * A text that was being typed has ended, and its field has left the page, so the focus fell to nothing. In a shadow root
1061
+ * the shortcuts follow the focus (see `eventScope`): without this the next Ctrl+Z or letter key would be ignored until the
1062
+ * next click on the board. The board takes the keyboard back unless the focus went somewhere of its own (a field of the
1063
+ * creator, or of the partner's page), which `shouldTakeFocusBack` tells. Asked after the field is gone, on the next frame.
1064
+ */
1065
+ #takeKeyboardBackSoon() {
1066
+ if (this.#keyboardReturnQueued || typeof requestAnimationFrame !== 'function')
1067
+ return;
1068
+ this.#keyboardReturnQueued = true;
1069
+ requestAnimationFrame(() => {
1070
+ this.#keyboardReturnQueued = false;
1071
+ if (this.#destroyed || !this.#board)
1072
+ return;
1073
+ try {
1074
+ if (shouldTakeFocusBack(this.#board)) {
1075
+ this.focusBoard();
1076
+ canvasLog('Canvas: the board took the keyboard back after a text was typed');
1077
+ }
1078
+ }
1079
+ catch (error) {
1080
+ canvasWarn('Canvas: could not give the keyboard back to the board', error);
1081
+ }
1082
+ });
1083
+ }
1084
+ /** Asks for the next frame of the eraser's trail, unless one is asked for already. Nothing runs while there is no trail. */
1085
+ #startScribbleClock() {
1086
+ if (this.#scribbleFrame !== null || this.#destroyed || typeof requestAnimationFrame !== 'function')
1087
+ return;
1088
+ if (this.#scribbleClockLast === null)
1089
+ this.#scribbleClockLast = typeof performance !== 'undefined' ? performance.now() : 0;
1090
+ this.#scribbleFrame = requestAnimationFrame((time) => this.#onScribbleFrame(time));
1091
+ }
1092
+ #onScribbleFrame(time) {
1093
+ this.#scribbleFrame = null;
1094
+ if (this.#destroyed)
1095
+ return;
1096
+ const elapsedMs = Math.max(0, time - (this.#scribbleClockLast ?? time));
1097
+ this.#scribbleClockLast = time;
1098
+ let alive = false;
1099
+ try {
1100
+ alive = this.engine.stepScribble(elapsedMs);
1101
+ }
1102
+ catch (error) {
1103
+ canvasWarn('Canvas: the eraser trail could not be stepped', error);
1104
+ }
1105
+ if (!alive) {
1106
+ this.#scribbleClockLast = null;
1107
+ return;
1108
+ }
1109
+ this.#startScribbleClock();
1110
+ }
1111
+ /**
1112
+ * Tells the page that its overlays (the live widgets over the cards) must move. At most once a frame, and never from
1113
+ * inside its own answer: what the page changes while it moves them does not call it again in the same turn.
1114
+ */
1115
+ #queueAfterRender() {
1116
+ if (!this.props.onAfterRender || this.#afterRenderQueued || this.#applyingAfterRender || this.#destroyed)
1117
+ return;
1118
+ if (typeof requestAnimationFrame !== 'function')
1119
+ return;
1120
+ this.#afterRenderQueued = true;
1121
+ requestAnimationFrame(() => {
1122
+ this.#afterRenderQueued = false;
1123
+ const callback = this.props.onAfterRender;
1124
+ if (!callback || this.#applyingAfterRender || this.#destroyed)
1125
+ return;
1126
+ this.#applyingAfterRender = true;
1127
+ try {
1128
+ callback();
1129
+ }
1130
+ catch (error) {
1131
+ canvasWarn('Canvas: onAfterRender failed', error);
1132
+ }
1133
+ finally {
1134
+ this.#applyingAfterRender = false;
1135
+ }
1136
+ });
1137
+ }
1138
+ // ────────────────────────────────────────────────────── stroke snap
1139
+ #handleStrokeFinished(stroke, handLine) {
1140
+ // Off unless the page asked (shapeSnap) or the package's own flag is flipped.
1141
+ if (!isShapeSnapOn(this.props.shapeSnap))
1142
+ return;
1143
+ void snapDrawnStroke(this.engine, stroke, { recognize: this.props.onRecognizeStroke, log: (message, details) => canvasLog(message, details) }, handLine);
1144
+ }
1145
+ // ────────────────────────────────────────────────────── saving and loading
1146
+ #runAutosave() {
1147
+ const json = this.#serializeCanvasText();
1148
+ if (json === null) {
1149
+ // The board has nothing to give right now (it is loading): ask the buffer for another go a delay later.
1150
+ canvasLog('Canvas: autosave: the board cannot be serialized yet, trying again after the delay');
1151
+ this.#scheduler.markChanged();
1152
+ return undefined;
1153
+ }
1154
+ if (json === this.#lastAutosavedJson) {
1155
+ this.#updateUi({ saveState: 'saved' });
1156
+ return undefined;
1157
+ }
1158
+ canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
1159
+ this.#updateUi({ saveState: 'saving' });
1160
+ let outcome;
1161
+ try {
1162
+ outcome = this.props.onAutoSave?.(json, { leaving: this.#pageIsLeaving });
1163
+ }
1164
+ catch (error) {
1165
+ this.#updateUi({ saveState: 'dirty' });
1166
+ throw error;
1167
+ }
1168
+ const finish = (savedJson) => {
1169
+ this.#lastAutosavedJson = savedJson;
1170
+ this.#updateUi({ saveState: this.#scheduler.isDirty ? 'dirty' : 'saved' });
1171
+ };
1172
+ if (outcome && typeof outcome.then === 'function') {
1173
+ return outcome.then((value) => {
1174
+ finish(json);
1175
+ return value;
1176
+ }, (error) => {
1177
+ this.#updateUi({ saveState: 'dirty' });
1178
+ throw error;
1179
+ });
1180
+ }
1181
+ finish(json);
1182
+ return outcome;
1183
+ }
702
1184
  /** Saves whatever the buffer still holds, now. Resolves once the page's save is done. */
703
- CanvasHost.prototype.flushAutosave = function () {
704
- return __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").flush();
705
- };
1185
+ flushAutosave() {
1186
+ return this.#scheduler.flush();
1187
+ }
706
1188
  /** An immediate save (Cmd+S, the save button, the page's own flushes). */
707
- CanvasHost.prototype.saveNow = function () {
708
- var _this = this;
709
- var _a, _b;
1189
+ saveNow() {
710
1190
  // What the buffer was waiting to save is in this save.
711
- __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").cancel();
712
- var json = this.saveCanvas();
713
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { saveState: 'saving' });
714
- var outcome;
1191
+ this.#scheduler.cancel();
1192
+ const json = this.saveCanvas();
1193
+ this.#updateUi({ saveState: 'saving' });
1194
+ let outcome;
715
1195
  try {
716
- outcome = (_b = (_a = this.props).onAutoSave) === null || _b === void 0 ? void 0 : _b.call(_a, json, { leaving: __classPrivateFieldGet(this, _CanvasHost_pageIsLeaving, "f") });
1196
+ outcome = this.props.onAutoSave?.(json, { leaving: this.#pageIsLeaving });
717
1197
  }
718
1198
  catch (error) {
719
1199
  canvasWarn('Canvas: the save failed', error);
720
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { saveState: 'dirty' });
1200
+ this.#updateUi({ saveState: 'dirty' });
721
1201
  return;
722
1202
  }
723
- var finish = function () {
1203
+ const finish = () => {
724
1204
  if (json)
725
- __classPrivateFieldSet(_this, _CanvasHost_lastAutosavedJson, json, "f");
726
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { saveState: __classPrivateFieldGet(_this, _CanvasHost_scheduler, "f").isDirty ? 'dirty' : 'saved' });
1205
+ this.#lastAutosavedJson = json;
1206
+ this.#updateUi({ saveState: this.#scheduler.isDirty ? 'dirty' : 'saved' });
727
1207
  };
728
1208
  if (outcome && typeof outcome.then === 'function') {
729
- outcome.then(finish, function (error) {
1209
+ outcome.then(finish, (error) => {
730
1210
  canvasWarn('Canvas: the save failed', error);
731
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { saveState: 'dirty' });
1211
+ this.#updateUi({ saveState: 'dirty' });
732
1212
  });
733
1213
  }
734
1214
  else {
735
1215
  finish();
736
1216
  }
737
1217
  canvasLog('Canvas: manual save triggered');
738
- };
1218
+ }
1219
+ /** Serializes the board without writing to the console (autosave compares payloads here first). */
1220
+ #serializeCanvasText() {
1221
+ if (this.#destroyed)
1222
+ return null;
1223
+ if (this.#loadDepth > 0 || this.engine.state.loading) {
1224
+ canvasLog('Canvas: saveCanvas skipped (the board is loading)');
1225
+ return null;
1226
+ }
1227
+ try {
1228
+ return this.engine.serialize({ imageStore: getShapeImageStore() });
1229
+ }
1230
+ catch (error) {
1231
+ console.error('Canvas: saveCanvas failed', error);
1232
+ return null;
1233
+ }
1234
+ }
739
1235
  /** The board as the text the page keeps. Null while the board is loading. */
740
- CanvasHost.prototype.saveCanvas = function () {
741
- var text = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_serializeCanvasText).call(this);
1236
+ saveCanvas() {
1237
+ const text = this.#serializeCanvasText();
742
1238
  if (text !== null) {
743
1239
  canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
744
1240
  }
745
1241
  return text;
746
- };
1242
+ }
747
1243
  /**
748
1244
  * Shows saved data. Never throws: text the board cannot read (a canvas of the older engine, or something that is not
749
1245
  * a canvas) opens as an empty board, says so, and nothing is saved until the person changes something.
750
1246
  */
751
- CanvasHost.prototype.loadCanvas = function (jsonString) {
752
- return __awaiter(this, void 0, Promise, function () {
753
- var parsed, error_1;
754
- var _this = this;
755
- return __generator(this, function (_a) {
756
- switch (_a.label) {
757
- case 0:
758
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
759
- return [2 /*return*/];
760
- markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_START);
761
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_closeEmptyHintGate).call(this);
762
- __classPrivateFieldSet(this, _CanvasHost_loadDepth, __classPrivateFieldGet(this, _CanvasHost_loadDepth, "f") + 1, "f");
763
- this.engine.setLoading(true);
764
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { loadPhase: 'loading' });
765
- _a.label = 1;
766
- case 1:
767
- _a.trys.push([1, 3, 4, 5]);
768
- parsed = this.engine.loadDocument(jsonString);
769
- __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").cancel();
770
- __classPrivateFieldSet(this, _CanvasHost_lastAutosavedJson, null, "f");
771
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { loadStatus: parsed.status, saveState: 'saved' });
772
- if (parsed.status === 'unsupported' || parsed.status === 'invalid') {
773
- // Not gated by the page's log switch: a board that opens empty is something its owner has to be able to find out.
774
- console.warn("Canvas: this canvas could not be opened (".concat(parsed.status, "); showing an empty board, nothing is overwritten until it is changed"), parsed.warnings);
775
- }
776
- else if (parsed.warnings.length > 0) {
777
- canvasWarn('Canvas: some objects of the saved canvas could not be read', parsed.warnings);
778
- }
779
- return [4 /*yield*/, __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_resolveStoredImages).call(this)];
780
- case 2:
781
- _a.sent();
782
- return [3 /*break*/, 5];
783
- case 3:
784
- error_1 = _a.sent();
785
- console.error('Canvas: loadCanvas failed', error_1);
786
- return [3 /*break*/, 5];
787
- case 4:
788
- __classPrivateFieldSet(this, _CanvasHost_loadDepth, Math.max(0, __classPrivateFieldGet(this, _CanvasHost_loadDepth, "f") - 1), "f");
789
- if (__classPrivateFieldGet(this, _CanvasHost_loadDepth, "f") === 0)
790
- this.engine.setLoading(false);
791
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { loadPhase: 'ready' });
792
- queueMicrotask(function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_syncEmptyHintGate).call(_this); });
793
- markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_END);
794
- return [7 /*endfinally*/];
795
- case 5: return [2 /*return*/];
796
- }
797
- });
1247
+ async loadCanvas(jsonString) {
1248
+ if (this.#destroyed)
1249
+ return;
1250
+ markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_START);
1251
+ this.#closeEmptyHintGate();
1252
+ this.#loadDepth += 1;
1253
+ this.engine.setLoading(true);
1254
+ this.#updateUi({ loadPhase: 'loading' });
1255
+ try {
1256
+ const parsed = this.engine.loadDocument(jsonString);
1257
+ this.#scheduler.cancel();
1258
+ this.#lastAutosavedJson = null;
1259
+ this.#updateUi({ loadStatus: parsed.status, saveState: 'saved' });
1260
+ if (parsed.status === 'unsupported' || parsed.status === 'invalid') {
1261
+ // Not gated by the page's log switch: a board that opens empty is something its owner has to be able to find out.
1262
+ console.warn(`Canvas: this canvas could not be opened (${parsed.status}); showing an empty board, nothing is overwritten until it is changed`, parsed.warnings);
1263
+ }
1264
+ else if (parsed.warnings.length > 0) {
1265
+ canvasWarn('Canvas: some objects of the saved canvas could not be read', parsed.warnings);
1266
+ }
1267
+ await this.#resolveStoredImages();
1268
+ }
1269
+ catch (error) {
1270
+ console.error('Canvas: loadCanvas failed', error);
1271
+ }
1272
+ finally {
1273
+ this.#loadDepth = Math.max(0, this.#loadDepth - 1);
1274
+ if (this.#loadDepth === 0)
1275
+ this.engine.setLoading(false);
1276
+ this.#updateUi({ loadPhase: 'ready' });
1277
+ queueMicrotask(() => this.#syncEmptyHintGate());
1278
+ markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_END);
1279
+ }
1280
+ }
1281
+ /** Pictures the saved board only points at (by reference) are read from the page's store and put in without a history step. */
1282
+ async #resolveStoredImages() {
1283
+ const store = getShapeImageStore();
1284
+ if (!store)
1285
+ return;
1286
+ const scene = this.engine.state.scene;
1287
+ const missing = scene.filter((object) => (object.type === 'image' && !object.src && !!object.imageRef) || (object.type === 'widget' && !object.thumbnail && !!object.thumbnailRef));
1288
+ if (missing.length === 0)
1289
+ return;
1290
+ const found = new Map();
1291
+ await Promise.all(missing.map(async (object) => {
1292
+ const reference = object.type === 'image' ? object.imageRef : object.type === 'widget' ? object.thumbnailRef : null;
1293
+ if (!reference)
1294
+ return;
1295
+ try {
1296
+ const dataUrl = await store.load(reference);
1297
+ if (dataUrl)
1298
+ found.set(object.id, dataUrl);
1299
+ }
1300
+ catch (error) {
1301
+ canvasWarn('Canvas: a stored picture could not be read', reference, error);
1302
+ }
1303
+ }));
1304
+ if (found.size === 0 || this.#destroyed)
1305
+ return;
1306
+ // What was loaded since is left alone: only the objects that are still the ones that were missing a picture are filled in.
1307
+ const next = this.engine.state.scene.map((object) => {
1308
+ const dataUrl = found.get(object.id);
1309
+ if (!dataUrl)
1310
+ return object;
1311
+ if (object.type === 'image' && !object.src)
1312
+ return { ...object, src: dataUrl };
1313
+ if (object.type === 'widget' && !object.thumbnail)
1314
+ return { ...object, thumbnail: dataUrl };
1315
+ return object;
798
1316
  });
799
- };
1317
+ this.engine.applySilently(next);
1318
+ }
800
1319
  /** Empties the board (an undo step) and tells the page. */
801
- CanvasHost.prototype.onClearAllObjects = function () {
802
- __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").cancel();
1320
+ onClearAllObjects() {
1321
+ this.#scheduler.cancel();
803
1322
  this.engine.clearAll();
804
1323
  canvasLog('Clear all objects created');
805
- };
1324
+ }
806
1325
  // ────────────────────────────────────────────────────── tools
807
- CanvasHost.prototype.setTool = function (tool, options) {
808
- if (options === void 0) { options = {}; }
1326
+ setTool(tool, options = {}) {
809
1327
  this.engine.setTool(tool, options);
810
- };
1328
+ }
811
1329
  /** A letter of the keyboard chose a tool (or the menu did). */
812
- CanvasHost.prototype.chooseShortcutTool = function (tool) {
1330
+ chooseShortcutTool(tool) {
813
1331
  switch (tool) {
814
1332
  case 'select':
815
1333
  return this.onSelectSelectTool();
@@ -832,286 +1350,214 @@ var CanvasHost = /** @class */ (function () {
832
1350
  case 'image':
833
1351
  return this.onSelectImageTool();
834
1352
  }
835
- };
1353
+ }
836
1354
  /** The Select tool: the creator closes the element selector of its widgets when it hears of it. */
837
- CanvasHost.prototype.onSelectSelectTool = function () {
1355
+ onSelectSelectTool() {
838
1356
  this.engine.setTool('select');
839
1357
  announceSelectTool();
840
- };
841
- CanvasHost.prototype.onSelectDrawTool = function () {
1358
+ }
1359
+ onSelectDrawTool() {
842
1360
  this.engine.setTool('draw');
843
- };
844
- CanvasHost.prototype.onSelectEraseTool = function () {
1361
+ }
1362
+ onSelectEraseTool() {
845
1363
  this.engine.setTool('erase');
846
- };
847
- CanvasHost.prototype.onSelectTextTool = function () {
1364
+ }
1365
+ onSelectTextTool() {
848
1366
  this.engine.setTool('text');
849
- };
850
- CanvasHost.prototype.onSelectArrowTool = function () {
1367
+ }
1368
+ onSelectArrowTool() {
851
1369
  this.engine.setTool('arrow');
852
- };
853
- CanvasHost.prototype.onSelectPanTool = function () {
1370
+ }
1371
+ onSelectPanTool() {
854
1372
  this.engine.setTool('pan');
855
- };
1373
+ }
856
1374
  /** The names are the old ones: `circle` is the oval, `circle-true` the circle. */
857
- CanvasHost.prototype.onSelectShapeTool = function (shapeType) {
858
- var _a;
859
- var tool = { rect: 'rect', 'rounded-rect': 'rounded-rect', circle: 'ellipse', 'circle-true': 'circle', triangle: 'triangle', arrow: 'arrow' };
860
- this.engine.setTool((_a = tool[shapeType]) !== null && _a !== void 0 ? _a : 'rect');
861
- };
1375
+ onSelectShapeTool(shapeType) {
1376
+ const tool = { rect: 'rect', 'rounded-rect': 'rounded-rect', circle: 'ellipse', 'circle-true': 'circle', triangle: 'triangle', arrow: 'arrow' };
1377
+ this.engine.setTool(tool[shapeType] ?? 'rect');
1378
+ }
862
1379
  /** The second argument of the old call (the path of the shape) is still accepted, and not needed: the library knows the shape by its key. */
863
1380
  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- part of the signature pages call
864
- CanvasHost.prototype.onSelectLibraryShapeTool = function (shapeKey, _pathData) {
1381
+ onSelectLibraryShapeTool(shapeKey, _pathData) {
865
1382
  this.engine.setTool('library-shape', { libraryShapeKey: shapeKey });
866
- };
1383
+ }
867
1384
  /** The image tool opens the file chooser (it needs the click that called it, which is how the toolbar and the key call it). */
868
- CanvasHost.prototype.onSelectImageTool = function () {
1385
+ onSelectImageTool() {
869
1386
  void this.addImage();
870
- };
1387
+ }
871
1388
  /** There are no frames on this board: kept so a page that still calls it keeps working. */
872
- CanvasHost.prototype.onSelectFrameTool = function () {
1389
+ onSelectFrameTool() {
873
1390
  canvasLog('Canvas: the frame tool is gone, nothing was done');
874
- };
1391
+ }
875
1392
  /** There is no video on this board: kept so a page that still calls it keeps working. */
876
- CanvasHost.prototype.onSelectVideoTool = function () {
1393
+ onSelectVideoTool() {
877
1394
  canvasLog('Canvas: the video tool is gone, nothing was done');
878
- };
1395
+ }
879
1396
  // ────────────────────────────────────────────────────── view
880
- CanvasHost.prototype.zoomIn = function () {
1397
+ zoomIn() {
881
1398
  this.engine.zoomStep(1);
882
- };
883
- CanvasHost.prototype.zoomOut = function () {
1399
+ }
1400
+ zoomOut() {
884
1401
  this.engine.zoomStep(-1);
885
- };
886
- CanvasHost.prototype.zoomTo = function (percent) {
1402
+ }
1403
+ zoomTo(percent) {
887
1404
  if (!Number.isFinite(percent))
888
1405
  return;
889
1406
  this.engine.zoomTo(percent / 100);
890
- };
891
- CanvasHost.prototype.zoomReset = function () {
1407
+ }
1408
+ zoomReset() {
892
1409
  this.engine.zoomReset();
893
- };
894
- CanvasHost.prototype.zoomFit = function () {
1410
+ }
1411
+ zoomFit() {
895
1412
  this.engine.zoomToFit();
896
- };
1413
+ }
897
1414
  // ────────────────────────────────────────────────────── selection and arrangement
898
- CanvasHost.prototype.deselectAll = function () {
1415
+ deselectAll() {
899
1416
  this.engine.clearSelection();
900
- };
901
- CanvasHost.prototype.onSelectAllObjects = function () {
1417
+ }
1418
+ onSelectAllObjects() {
902
1419
  this.engine.selectAll();
903
- };
904
- CanvasHost.prototype.onDeselectAllObjects = function () {
1420
+ }
1421
+ onDeselectAllObjects() {
905
1422
  this.engine.clearSelection();
906
- };
1423
+ }
907
1424
  /** The same as the keys and the menu: copies the selection. Widget cards are made into new widgets by the page. */
908
- CanvasHost.prototype.duplicateSelectedObjects = function () {
1425
+ duplicateSelectedObjects() {
909
1426
  return this.engine.duplicateSelection();
910
- };
911
- CanvasHost.prototype.deleteSelectedObjects = function () {
1427
+ }
1428
+ deleteSelectedObjects() {
912
1429
  return this.engine.deleteSelection();
913
- };
1430
+ }
914
1431
  /** The same as the Copy key: remembers the selection for a paste and marks the system clipboard as the board's. */
915
- CanvasHost.prototype.copySelection = function () {
916
- var copied = this.engine.copySelection();
1432
+ copySelection() {
1433
+ const copied = this.engine.copySelection();
917
1434
  if (copied)
918
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_markClipboardAsOurs).call(this);
1435
+ this.#markClipboardAsOurs();
919
1436
  return copied;
920
- };
1437
+ }
921
1438
  /** The same as the Cut key. */
922
- CanvasHost.prototype.cutSelection = function () {
923
- var cut = this.engine.cutSelection();
1439
+ cutSelection() {
1440
+ const cut = this.engine.cutSelection();
924
1441
  if (cut)
925
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_markClipboardAsOurs).call(this);
1442
+ this.#markClipboardAsOurs();
926
1443
  return cut;
927
- };
1444
+ }
928
1445
  /**
929
1446
  * Paste from the menu, centred on a point of the board (in pixels of the board). A copy made on the board wins; without
930
1447
  * one, a picture on the system clipboard is put on the board when the browser lets the page read it.
931
1448
  */
932
- CanvasHost.prototype.pasteAt = function (boardPoint) {
933
- return __awaiter(this, void 0, Promise, function () {
934
- var world, items, _i, items_1, item, pictureType, picture, error_2;
935
- var _a, _b, _c;
936
- return __generator(this, function (_d) {
937
- switch (_d.label) {
938
- case 0:
939
- world = boardPoint ? this.engine.toWorld(boardPoint) : null;
940
- if (this.engine.hasClipboard()) {
941
- this.engine.paste(world);
942
- return [2 /*return*/];
943
- }
944
- _d.label = 1;
945
- case 1:
946
- _d.trys.push([1, 8, , 9]);
947
- return [4 /*yield*/, ((_b = (_a = navigator.clipboard) === null || _a === void 0 ? void 0 : _a.read) === null || _b === void 0 ? void 0 : _b.call(_a))];
948
- case 2:
949
- items = (_c = (_d.sent())) !== null && _c !== void 0 ? _c : [];
950
- _i = 0, items_1 = items;
951
- _d.label = 3;
952
- case 3:
953
- if (!(_i < items_1.length)) return [3 /*break*/, 7];
954
- item = items_1[_i];
955
- pictureType = item.types.find(function (type) { return type.startsWith('image/'); });
956
- if (!pictureType)
957
- return [3 /*break*/, 6];
958
- return [4 /*yield*/, item.getType(pictureType)];
959
- case 4:
960
- picture = _d.sent();
961
- return [4 /*yield*/, this.insertImageFiles([picture], world !== null && world !== void 0 ? world : undefined)];
962
- case 5:
963
- _d.sent();
964
- return [2 /*return*/];
965
- case 6:
966
- _i++;
967
- return [3 /*break*/, 3];
968
- case 7: return [3 /*break*/, 9];
969
- case 8:
970
- error_2 = _d.sent();
971
- canvasLog('Canvas: the system clipboard could not be read, nothing was pasted', error_2);
972
- return [3 /*break*/, 9];
973
- case 9: return [2 /*return*/];
974
- }
975
- });
976
- });
977
- };
1449
+ async pasteAt(boardPoint) {
1450
+ const world = boardPoint ? this.engine.toWorld(boardPoint) : null;
1451
+ if (this.engine.hasClipboard()) {
1452
+ this.engine.paste(world);
1453
+ return;
1454
+ }
1455
+ try {
1456
+ const items = (await navigator.clipboard?.read?.()) ?? [];
1457
+ for (const item of items) {
1458
+ const pictureType = item.types.find((type) => type.startsWith('image/'));
1459
+ if (!pictureType)
1460
+ continue;
1461
+ const picture = await item.getType(pictureType);
1462
+ await this.insertImageFiles([picture], world ?? undefined);
1463
+ return;
1464
+ }
1465
+ }
1466
+ catch (error) {
1467
+ canvasLog('Canvas: the system clipboard could not be read, nothing was pasted', error);
1468
+ }
1469
+ }
978
1470
  /** A colour for a new shape: a random hue, so that shapes drawn in a row can be told apart. */
979
- CanvasHost.prototype.shapeFillColor = function () {
980
- return "hsl(".concat(this.engine.services.random() * 360, ", 70%, 50%)");
981
- };
982
- CanvasHost.prototype.onGroupSelection = function () {
983
- var _a;
1471
+ shapeFillColor() {
1472
+ return `hsl(${this.engine.services.random() * 360}, 70%, 50%)`;
1473
+ }
1474
+ onGroupSelection() {
984
1475
  if (!this.engine.groupSelection())
985
1476
  return null;
986
- return (_a = this.engine.state.selectedIds[0]) !== null && _a !== void 0 ? _a : null;
987
- };
988
- CanvasHost.prototype.onUngroupSelection = function () {
1477
+ return this.engine.state.selectedIds[0] ?? null;
1478
+ }
1479
+ onUngroupSelection() {
989
1480
  this.engine.ungroupSelection();
990
- };
991
- CanvasHost.prototype.undo = function () {
992
- return __awaiter(this, void 0, Promise, function () {
993
- return __generator(this, function (_a) {
994
- this.engine.undo();
995
- return [2 /*return*/];
996
- });
997
- });
998
- };
999
- CanvasHost.prototype.redo = function () {
1000
- return __awaiter(this, void 0, Promise, function () {
1001
- return __generator(this, function (_a) {
1002
- this.engine.redo();
1003
- return [2 /*return*/];
1004
- });
1005
- });
1006
- };
1481
+ }
1482
+ async undo() {
1483
+ this.engine.undo();
1484
+ }
1485
+ async redo() {
1486
+ this.engine.redo();
1487
+ }
1007
1488
  /** What the page reads of the selection: a view of the one object, or of the several. */
1008
- CanvasHost.prototype.getSelectedObject = function () {
1489
+ getSelectedObject() {
1009
1490
  return selectedHostObject(this.engine);
1010
- };
1011
- CanvasHost.prototype.addRect = function () {
1012
- var _a;
1013
- return (_a = this.engine.addObjects([__classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_placeAtCenter).call(this, 'rect')], { select: true })[0]) !== null && _a !== void 0 ? _a : null;
1014
- };
1015
- CanvasHost.prototype.addCircle = function () {
1016
- var _a;
1017
- return (_a = this.engine.addObjects([__classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_placeAtCenter).call(this, 'circle')], { select: true })[0]) !== null && _a !== void 0 ? _a : null;
1018
- };
1019
- CanvasHost.prototype.addTriangle = function () {
1020
- var _a;
1021
- return (_a = this.engine.addObjects([__classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_placeAtCenter).call(this, 'triangle')], { select: true })[0]) !== null && _a !== void 0 ? _a : null;
1022
- };
1491
+ }
1492
+ // ────────────────────────────────────────────────────── adding things
1493
+ #placeAtCenter(kind) {
1494
+ const center = this.engine.visibleCenter();
1495
+ return buildDraggedShape({
1496
+ kind,
1497
+ start: center,
1498
+ end: center,
1499
+ constrain: false,
1500
+ dragged: false,
1501
+ wireframe: this.engine.wireframeMode,
1502
+ createId: this.engine.services.createId,
1503
+ random: this.engine.services.random,
1504
+ workspacePaint: this.engine.workspacePaintForNewShape(this.engine.wireframeMode)
1505
+ });
1506
+ }
1507
+ addRect() {
1508
+ return this.engine.addObjects([this.#placeAtCenter('rect')], { select: true })[0] ?? null;
1509
+ }
1510
+ addCircle() {
1511
+ return this.engine.addObjects([this.#placeAtCenter('circle')], { select: true })[0] ?? null;
1512
+ }
1513
+ addTriangle() {
1514
+ return this.engine.addObjects([this.#placeAtCenter('triangle')], { select: true })[0] ?? null;
1515
+ }
1023
1516
  /** A label in the middle of the view, ready to be typed in. */
1024
- CanvasHost.prototype.addText = function () {
1517
+ addText() {
1025
1518
  this.engine.setTool('select');
1026
1519
  return this.engine.createText(this.engine.visibleCenter());
1027
- };
1520
+ }
1028
1521
  /** There are no frames on this board: kept so a page that still calls it keeps working. */
1029
- CanvasHost.prototype.addFrame = function () {
1522
+ addFrame() {
1030
1523
  canvasLog('Canvas: frames are gone, nothing was added');
1031
1524
  return null;
1032
- };
1525
+ }
1033
1526
  /** Opens the file chooser and puts the pictures that are chosen on the board. */
1034
- CanvasHost.prototype.addImage = function () {
1035
- return __awaiter(this, void 0, Promise, function () {
1036
- var files;
1037
- return __generator(this, function (_a) {
1038
- switch (_a.label) {
1039
- case 0: return [4 /*yield*/, chooseImageFiles(__classPrivateFieldGet(this, _CanvasHost_root, "f"), { multiple: true })];
1040
- case 1:
1041
- files = _a.sent();
1042
- if (!(files.length > 0)) return [3 /*break*/, 3];
1043
- return [4 /*yield*/, this.insertImageFiles(files)];
1044
- case 2:
1045
- _a.sent();
1046
- _a.label = 3;
1047
- case 3: return [2 /*return*/];
1048
- }
1049
- });
1050
- });
1051
- };
1527
+ async addImage() {
1528
+ const files = await chooseImageFiles(this.#root, { multiple: true });
1529
+ if (files.length > 0)
1530
+ await this.insertImageFiles(files);
1531
+ }
1052
1532
  /** The SVG entry of the shapes menu: the same as `addImage`, but the chooser only offers vector files. */
1053
- CanvasHost.prototype.addSvg = function () {
1054
- return __awaiter(this, void 0, Promise, function () {
1055
- var files;
1056
- return __generator(this, function (_a) {
1057
- switch (_a.label) {
1058
- case 0: return [4 /*yield*/, chooseImageFiles(__classPrivateFieldGet(this, _CanvasHost_root, "f"), { multiple: true, accept: 'image/svg+xml,.svg' })];
1059
- case 1:
1060
- files = _a.sent();
1061
- if (!(files.length > 0)) return [3 /*break*/, 3];
1062
- return [4 /*yield*/, this.insertImageFiles(files)];
1063
- case 2:
1064
- _a.sent();
1065
- _a.label = 3;
1066
- case 3: return [2 /*return*/];
1067
- }
1068
- });
1069
- });
1070
- };
1533
+ async addSvg() {
1534
+ const files = await chooseImageFiles(this.#root, { multiple: true, accept: 'image/svg+xml,.svg' });
1535
+ if (files.length > 0)
1536
+ await this.insertImageFiles(files);
1537
+ }
1071
1538
  /** Reads picture files and puts them on the board, side by side from `at` (the middle of the view by default), as one step. */
1072
- CanvasHost.prototype.insertImageFiles = function (files, at) {
1073
- return __awaiter(this, void 0, Promise, function () {
1074
- var loaded, _i, files_1, file, _a, _b, error_3;
1075
- return __generator(this, function (_c) {
1076
- switch (_c.label) {
1077
- case 0:
1078
- loaded = [];
1079
- _i = 0, files_1 = files;
1080
- _c.label = 1;
1081
- case 1:
1082
- if (!(_i < files_1.length)) return [3 /*break*/, 6];
1083
- file = files_1[_i];
1084
- _c.label = 2;
1085
- case 2:
1086
- _c.trys.push([2, 4, , 5]);
1087
- _b = (_a = loaded).push;
1088
- return [4 /*yield*/, readImageFile(file, file.name || 'pasted-image.png')];
1089
- case 3:
1090
- _b.apply(_a, [_c.sent()]);
1091
- return [3 /*break*/, 5];
1092
- case 4:
1093
- error_3 = _c.sent();
1094
- canvasWarn('Canvas: a picture could not be read', error_3);
1095
- return [3 /*break*/, 5];
1096
- case 5:
1097
- _i++;
1098
- return [3 /*break*/, 1];
1099
- case 6: return [2 /*return*/, this.insertLoadedImages(loaded, at)];
1100
- }
1101
- });
1102
- });
1103
- };
1104
- CanvasHost.prototype.insertLoadedImages = function (pictures, at) {
1105
- var _this = this;
1106
- if (pictures.length === 0 || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1539
+ async insertImageFiles(files, at) {
1540
+ const loaded = [];
1541
+ for (const file of files) {
1542
+ try {
1543
+ loaded.push(await readImageFile(file, file.name || 'pasted-image.png'));
1544
+ }
1545
+ catch (error) {
1546
+ canvasWarn('Canvas: a picture could not be read', error);
1547
+ }
1548
+ }
1549
+ return this.insertLoadedImages(loaded, at);
1550
+ }
1551
+ insertLoadedImages(pictures, at) {
1552
+ if (pictures.length === 0 || this.#destroyed)
1107
1553
  return [];
1108
- var center = at !== null && at !== void 0 ? at : this.engine.visibleCenter();
1109
- var objects = pictures.map(function (picture, position) {
1110
- var size = fitImageSize(picture.width, picture.height);
1554
+ const center = at ?? this.engine.visibleCenter();
1555
+ const objects = pictures.map((picture, position) => {
1556
+ const size = fitImageSize(picture.width, picture.height);
1111
1557
  // Several pictures are laid out in a cascade, so each one can still be seen.
1112
- var shift = position * 24;
1558
+ const shift = position * 24;
1113
1559
  return createImageObject({
1114
- id: _this.engine.services.createId('img'),
1560
+ id: this.engine.services.createId('img'),
1115
1561
  x: center.x - size.width / 2 + shift,
1116
1562
  y: center.y - size.height / 2 + shift,
1117
1563
  width: size.width,
@@ -1123,179 +1569,141 @@ var CanvasHost = /** @class */ (function () {
1123
1569
  });
1124
1570
  });
1125
1571
  this.engine.setTool('select');
1126
- var ids = this.engine.addObjects(objects, { select: true });
1572
+ const ids = this.engine.addObjects(objects, { select: true });
1127
1573
  canvasLog('Canvas: pictures put on the board', ids.length);
1128
1574
  return ids;
1129
- };
1575
+ }
1130
1576
  // ────────────────────────────────────────────────────── capture and conversion
1131
1577
  /** A PNG of everything on the board, cropped to it; an empty string for an empty board. */
1132
- CanvasHost.prototype.captureCanvasSketch = function () {
1133
- return __awaiter(this, void 0, Promise, function () {
1134
- var shapes, error_4;
1135
- return __generator(this, function (_a) {
1136
- switch (_a.label) {
1137
- case 0:
1138
- shapes = this.engine.state.scene.filter(function (object) { return object.type !== 'group'; });
1139
- if (shapes.length === 0)
1140
- return [2 /*return*/, ''];
1141
- _a.label = 1;
1142
- case 1:
1143
- _a.trys.push([1, 3, , 4]);
1144
- return [4 /*yield*/, renderShapesToDataUrl(shapes, __classPrivateFieldGet(this, _CanvasHost_raster, "f"), {
1145
- scale: 2,
1146
- background: '#ffffff',
1147
- widgetFallbackName: this.translate('canvas.draw.widgetName')
1148
- })];
1149
- case 2: return [2 /*return*/, _a.sent()];
1150
- case 3:
1151
- error_4 = _a.sent();
1152
- console.warn('Canvas: could not capture the sketch', error_4);
1153
- return [2 /*return*/, ''];
1154
- case 4: return [2 /*return*/];
1155
- }
1578
+ async captureCanvasSketch() {
1579
+ const shapes = this.engine.state.scene.filter((object) => object.type !== 'group');
1580
+ if (shapes.length === 0)
1581
+ return '';
1582
+ try {
1583
+ return await renderShapesToDataUrl(shapes, this.#raster, {
1584
+ scale: 2,
1585
+ background: '#ffffff',
1586
+ widgetFallbackName: this.translate('canvas.draw.widgetName')
1156
1587
  });
1157
- });
1158
- };
1588
+ }
1589
+ catch (error) {
1590
+ console.warn('Canvas: could not capture the sketch', error);
1591
+ return '';
1592
+ }
1593
+ }
1159
1594
  /** The selection panel's "capture": hands the page a screenshot of the selection. */
1160
- CanvasHost.prototype.captureSelection = function () {
1161
- return __awaiter(this, void 0, Promise, function () {
1162
- var notify, payload, error_5;
1163
- return __generator(this, function (_a) {
1164
- switch (_a.label) {
1165
- case 0:
1166
- notify = this.props.onObjectClick;
1167
- if (!notify)
1168
- return [2 /*return*/];
1169
- _a.label = 1;
1170
- case 1:
1171
- _a.trys.push([1, 3, , 4]);
1172
- return [4 /*yield*/, buildCapturePayload({
1173
- engine: this.engine,
1174
- raster: __classPrivateFieldGet(this, _CanvasHost_raster, "f"),
1175
- widgetFallbackName: this.translate('canvas.draw.widgetName')
1176
- })];
1177
- case 2:
1178
- payload = _a.sent();
1179
- if (!payload) {
1180
- canvasWarn('Canvas: nothing is selected to capture');
1181
- return [2 /*return*/];
1182
- }
1183
- notify(payload);
1184
- return [3 /*break*/, 4];
1185
- case 3:
1186
- error_5 = _a.sent();
1187
- console.error('Canvas: captureSelection failed', error_5);
1188
- return [3 /*break*/, 4];
1189
- case 4: return [2 /*return*/];
1190
- }
1595
+ async captureSelection() {
1596
+ const notify = this.props.onObjectClick;
1597
+ if (!notify)
1598
+ return;
1599
+ try {
1600
+ const payload = await buildCapturePayload({
1601
+ engine: this.engine,
1602
+ raster: this.#raster,
1603
+ widgetFallbackName: this.translate('canvas.draw.widgetName')
1191
1604
  });
1192
- });
1193
- };
1605
+ if (!payload) {
1606
+ canvasWarn('Canvas: nothing is selected to capture');
1607
+ return;
1608
+ }
1609
+ notify(payload);
1610
+ }
1611
+ catch (error) {
1612
+ console.error('Canvas: captureSelection failed', error);
1613
+ }
1614
+ }
1194
1615
  // ────────────────────────────────────────────────────── widget cards
1195
1616
  /** The whole board becomes one card of the widget. Resolves to the id of the card. */
1196
- CanvasHost.prototype.absorbCanvasSketchIntoWidget = function (widgetId, screenshotDataUrl) {
1197
- return __awaiter(this, void 0, Promise, function () {
1198
- return __generator(this, function (_a) {
1199
- if (!widgetId)
1200
- return [2 /*return*/, null];
1201
- try {
1202
- return [2 /*return*/, absorbSketchIntoWidget(this.engine, widgetId, screenshotDataUrl)];
1203
- }
1204
- catch (error) {
1205
- console.error('Canvas: absorbCanvasSketchIntoWidget failed', error);
1206
- return [2 /*return*/, null];
1207
- }
1208
- return [2 /*return*/];
1209
- });
1210
- });
1211
- };
1617
+ async absorbCanvasSketchIntoWidget(widgetId, screenshotDataUrl) {
1618
+ if (!widgetId)
1619
+ return null;
1620
+ try {
1621
+ return absorbSketchIntoWidget(this.engine, widgetId, screenshotDataUrl);
1622
+ }
1623
+ catch (error) {
1624
+ console.error('Canvas: absorbCanvasSketchIntoWidget failed', error);
1625
+ return null;
1626
+ }
1627
+ }
1212
1628
  /** Gives a card (or any object, which becomes one) the widget it stands for. */
1213
- CanvasHost.prototype.linkObjectToWidget = function (target, widgetId, widgetName) {
1214
- var _a;
1215
- var id = typeof target === 'string' ? target : ((_a = target === null || target === void 0 ? void 0 : target._objectId) !== null && _a !== void 0 ? _a : target === null || target === void 0 ? void 0 : target.id);
1629
+ linkObjectToWidget(target, widgetId, widgetName) {
1630
+ const id = typeof target === 'string' ? target : (target?._objectId ?? target?.id);
1216
1631
  if (!id || !widgetId)
1217
1632
  return;
1218
1633
  if (!this.engine.linkObjectToWidget(id, widgetId, widgetName))
1219
- canvasWarn('Canvas: could not link the object to the widget', { id: id, widgetId: widgetId });
1220
- };
1634
+ canvasWarn('Canvas: could not link the object to the widget', { id, widgetId });
1635
+ }
1221
1636
  /** Gives the card with that id its widget (the page learned the id of the widget it made). */
1222
- CanvasHost.prototype.linkFrameToWidget = function (objectId, widgetId) {
1223
- var object = this.engine.getObject(objectId);
1637
+ linkFrameToWidget(objectId, widgetId) {
1638
+ const object = this.engine.getObject(objectId);
1224
1639
  if (!object || object.type !== 'widget') {
1225
- canvasLog('Canvas: linkFrameToWidget found no card', { objectId: objectId, widgetId: widgetId });
1640
+ canvasLog('Canvas: linkFrameToWidget found no card', { objectId, widgetId });
1226
1641
  return;
1227
1642
  }
1228
1643
  this.engine.linkObjectToWidget(objectId, widgetId);
1229
- };
1644
+ }
1230
1645
  /** Marks the selected cards as being copied: a loader shows over them until the page links them. */
1231
- CanvasHost.prototype.markSelectedAsDuplicating = function () {
1232
- for (var _i = 0, _a = this.engine.selectedObjects(); _i < _a.length; _i++) {
1233
- var object = _a[_i];
1646
+ markSelectedAsDuplicating() {
1647
+ for (const object of this.engine.selectedObjects()) {
1234
1648
  if (object.type === 'widget')
1235
1649
  this.engine.setPending(object.id, 'duplicating');
1236
1650
  }
1237
- };
1651
+ }
1238
1652
  /** Replaces an object, or the selection a conversion remembered under that id, by a card of the widget. */
1239
- CanvasHost.prototype.replaceObjectWithWidgetImage = function (objectId, widgetId, screenshotDataUrl) {
1240
- return __awaiter(this, void 0, Promise, function () {
1241
- return __generator(this, function (_a) {
1242
- try {
1243
- return [2 /*return*/, replaceObjectWithWidgetCard(this.engine, this.conversions, objectId, widgetId, screenshotDataUrl)];
1244
- }
1245
- catch (error) {
1246
- console.error('Canvas: replaceObjectWithWidgetImage failed', error);
1247
- return [2 /*return*/, null];
1248
- }
1249
- return [2 /*return*/];
1250
- });
1251
- });
1252
- };
1253
- CanvasHost.prototype.updateWidgetImage = function (widgetId, newScreenshotDataUrl) {
1653
+ async replaceObjectWithWidgetImage(objectId, widgetId, screenshotDataUrl) {
1654
+ try {
1655
+ return replaceObjectWithWidgetCard(this.engine, this.conversions, objectId, widgetId, screenshotDataUrl);
1656
+ }
1657
+ catch (error) {
1658
+ console.error('Canvas: replaceObjectWithWidgetImage failed', error);
1659
+ return null;
1660
+ }
1661
+ }
1662
+ updateWidgetImage(widgetId, newScreenshotDataUrl) {
1254
1663
  if (!updateWidgetThumbnail(this.engine, widgetId, newScreenshotDataUrl)) {
1255
1664
  canvasWarn('Canvas: updateWidgetImage found no card for', widgetId);
1256
1665
  }
1257
- };
1258
- CanvasHost.prototype.selectWidgetShape = function (widgetId) {
1666
+ }
1667
+ selectWidgetShape(widgetId) {
1259
1668
  return selectWidgetCard(this.engine, widgetId);
1260
- };
1261
- CanvasHost.prototype.selectWidgetShapeById = function (widgetId) {
1669
+ }
1670
+ selectWidgetShapeById(widgetId) {
1262
1671
  return selectWidgetCard(this.engine, widgetId);
1263
- };
1264
- CanvasHost.prototype.getSelectedWidgetShapeId = function () {
1672
+ }
1673
+ getSelectedWidgetShapeId() {
1265
1674
  return selectedWidgetId(this.engine);
1266
- };
1267
- CanvasHost.prototype.getHoveredWidgetShapeId = function () {
1675
+ }
1676
+ getHoveredWidgetShapeId() {
1268
1677
  return this.engine.state.hoverWidgetId;
1269
- };
1678
+ }
1270
1679
  /** The cards a live widget can be drawn over, with where each is on the page. */
1271
- CanvasHost.prototype.listWidgetShapeScreenRects = function () {
1272
- var frame = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_frame).call(this);
1680
+ listWidgetShapeScreenRects() {
1681
+ const frame = this.#frame();
1273
1682
  if (!frame)
1274
1683
  return [];
1275
- var state = this.engine.state;
1276
- var results = [];
1277
- for (var _i = 0, _a = state.scene; _i < _a.length; _i++) {
1278
- var object = _a[_i];
1684
+ const state = this.engine.state;
1685
+ const results = [];
1686
+ for (const object of state.scene) {
1279
1687
  if (object.type !== 'widget' || !object.widgetId)
1280
1688
  continue;
1281
1689
  if (state.pending[object.id])
1282
1690
  continue;
1283
- var runtime = this.engine.widgetRuntime(object.widgetId);
1691
+ const runtime = this.engine.widgetRuntime(object.widgetId);
1284
1692
  if (runtime.orphaned)
1285
1693
  continue;
1286
- var geometry = widgetPreviewGeometry(object, state.viewport, frame);
1694
+ const geometry = widgetPreviewGeometry(object, state.viewport, frame);
1287
1695
  if (!geometry || !geometry.matrix.every(Number.isFinite) || geometry.width < 4 || geometry.height < 4)
1288
1696
  continue;
1289
- results.push(__assign({ widgetId: object.widgetId, hovered: object.widgetId === state.hoverWidgetId }, geometry));
1697
+ results.push({ widgetId: object.widgetId, hovered: object.widgetId === state.hoverWidgetId, ...geometry });
1290
1698
  }
1291
1699
  return results;
1292
- };
1700
+ }
1293
1701
  /** Where the card of a widget is on the page, with the board it is on. */
1294
- CanvasHost.prototype.getWidgetShapeScreenRect = function (widgetId) {
1295
- var frame = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_frame).call(this);
1702
+ getWidgetShapeScreenRect(widgetId) {
1703
+ const frame = this.#frame();
1296
1704
  if (!frame || !widgetId)
1297
1705
  return null;
1298
- var card = findWidgetCard(this.engine, widgetId);
1706
+ const card = findWidgetCard(this.engine, widgetId);
1299
1707
  if (!card) {
1300
1708
  // Draft convert shapes exist before the widget card is registered — expected on embedded create.
1301
1709
  if (!widgetId.startsWith('draft_convert_')) {
@@ -1304,827 +1712,169 @@ var CanvasHost = /** @class */ (function () {
1304
1712
  return null;
1305
1713
  }
1306
1714
  return screenRectOfBounds(shapeBounds(card), this.engine.state.viewport, frame);
1307
- };
1715
+ }
1308
1716
  /** Where any object is on the page: the id of an object, of a group, or of a selection a conversion remembered. */
1309
- CanvasHost.prototype.getObjectScreenRect = function (objectId) {
1310
- var _a, _b;
1311
- var frame = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_frame).call(this);
1717
+ getObjectScreenRect(objectId) {
1718
+ const frame = this.#frame();
1312
1719
  if (!frame || !objectId)
1313
1720
  return null;
1314
- var bounds = null;
1721
+ let bounds = null;
1315
1722
  if (this.engine.getObject(objectId))
1316
1723
  bounds = boundsOfObjects(this.engine.state.scene, [objectId]);
1317
1724
  else
1318
- bounds = (_b = (_a = this.conversions.peek(objectId)) === null || _a === void 0 ? void 0 : _a.bounds) !== null && _b !== void 0 ? _b : null;
1725
+ bounds = this.conversions.peek(objectId)?.bounds ?? null;
1319
1726
  if (!bounds) {
1320
1727
  canvasLog('Canvas: getObjectScreenRect found no object for', objectId);
1321
1728
  return null;
1322
1729
  }
1323
1730
  return screenRectOfBounds(bounds, this.engine.state.viewport, frame);
1324
- };
1731
+ }
1325
1732
  /**
1326
1733
  * The picture of a card as a data address, or null. A card shows its last screenshot; the answer is that one when it
1327
1734
  * is inline (the page asks for it at a moment it cannot wait, so the board does not draw anything new here).
1328
1735
  */
1329
- CanvasHost.prototype.getWidgetShapeDataUrl = function (widgetId) {
1330
- var _a;
1331
- var card = findWidgetCard(this.engine, widgetId);
1332
- var thumbnail = (_a = card === null || card === void 0 ? void 0 : card.thumbnail) !== null && _a !== void 0 ? _a : null;
1736
+ getWidgetShapeDataUrl(widgetId) {
1737
+ const card = findWidgetCard(this.engine, widgetId);
1738
+ const thumbnail = card?.thumbnail ?? null;
1333
1739
  return thumbnail && thumbnail.startsWith('data:image/') ? thumbnail : null;
1334
- };
1740
+ }
1335
1741
  /** Hides the screenshot of a card while a live widget covers it (so it does not show through the padding). */
1336
- CanvasHost.prototype.setWidgetShapeLivePreviewHiddenImage = function (widgetId, hidden) {
1742
+ setWidgetShapeLivePreviewHiddenImage(widgetId, hidden) {
1337
1743
  if (!widgetId)
1338
1744
  return;
1339
1745
  this.engine.setWidgetRuntime(widgetId, { hiddenImage: !!hidden });
1340
- };
1746
+ }
1341
1747
  /** Puts a card for a widget in the middle of the view (rows of up to four for a batch). */
1342
- CanvasHost.prototype.addWidgetShape = function (widgetId, widgetName, gridIndex, totalCount, previewImageUrl) {
1343
- if (gridIndex === void 0) { gridIndex = 0; }
1344
- if (totalCount === void 0) { totalCount = 1; }
1748
+ addWidgetShape(widgetId, widgetName, gridIndex = 0, totalCount = 1, previewImageUrl) {
1345
1749
  if (!widgetId)
1346
1750
  return null;
1347
- return addWidgetCard(this.engine, widgetId, { name: widgetName !== null && widgetName !== void 0 ? widgetName : null, gridIndex: gridIndex, totalCount: totalCount, previewImage: previewImageUrl !== null && previewImageUrl !== void 0 ? previewImageUrl : null });
1348
- };
1349
- CanvasHost.prototype.getLinkedWidgetIds = function () {
1751
+ return addWidgetCard(this.engine, widgetId, { name: widgetName ?? null, gridIndex, totalCount, previewImage: previewImageUrl ?? null });
1752
+ }
1753
+ getLinkedWidgetIds() {
1350
1754
  return linkedWidgetIds(this.engine);
1351
- };
1352
- CanvasHost.prototype.keepOnlyWidgetShape = function (widgetId) {
1755
+ }
1756
+ keepOnlyWidgetShape(widgetId) {
1353
1757
  return keepOnlyWidgetCard(this.engine, widgetId);
1354
- };
1758
+ }
1355
1759
  /** Takes everything but the card of one widget off the board. Returns how many objects went. */
1356
- CanvasHost.prototype.removeSketchObjectsKeepingWidget = function (widgetId) {
1760
+ removeSketchObjectsKeepingWidget(widgetId) {
1357
1761
  return removeSketchObjectsKeeping(this.engine, widgetId);
1358
- };
1359
- CanvasHost.prototype.hydrateWidgetShapeMetadata = function (widgetsById) {
1762
+ }
1763
+ hydrateWidgetShapeMetadata(widgetsById) {
1360
1764
  return hydrateWidgetMetadata(this.engine, widgetsById);
1361
- };
1362
- CanvasHost.prototype.markOrphanedWidgetShapes = function (validWidgetIds) {
1765
+ }
1766
+ markOrphanedWidgetShapes(validWidgetIds) {
1363
1767
  return markOrphanedWidgetCards(this.engine, validWidgetIds);
1364
- };
1365
- CanvasHost.prototype.setPrimaryWidgetShape = function (widgetId) {
1768
+ }
1769
+ setPrimaryWidgetShape(widgetId) {
1366
1770
  return setPrimaryWidgetCard(this.engine, widgetId);
1367
- };
1771
+ }
1368
1772
  /** The selection chrome's "set as primary": marks the card, then tells the page so it can keep it. */
1369
- CanvasHost.prototype.handleSetPrimaryFromPanel = function (widgetId) {
1370
- var _this = this;
1773
+ handleSetPrimaryFromPanel(widgetId) {
1371
1774
  this.setPrimaryWidgetShape(widgetId);
1372
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_safely).call(this, function () { var _a, _b; return (_b = (_a = _this.props).onSetPrimaryWidget) === null || _b === void 0 ? void 0 : _b.call(_a, widgetId); }, 'onSetPrimaryWidget');
1373
- };
1374
- CanvasHost.prototype.getPrimaryWidgetId = function () {
1775
+ this.#safely(() => this.props.onSetPrimaryWidget?.(widgetId), 'onSetPrimaryWidget');
1776
+ }
1777
+ getPrimaryWidgetId() {
1375
1778
  return primaryWidgetId(this.engine);
1376
- };
1779
+ }
1377
1780
  /** A live widget covers the card: its own bar moves it, so the body does not. */
1378
- CanvasHost.prototype.setWidgetShapeBodyDragAllowed = function (widgetId, allowed) {
1781
+ setWidgetShapeBodyDragAllowed(widgetId, allowed) {
1379
1782
  if (!widgetId)
1380
1783
  return;
1381
1784
  this.engine.setWidgetRuntime(widgetId, { bodyDragAllowed: !!allowed });
1382
- };
1785
+ }
1383
1786
  /** The page's bar drags a card by a distance in page pixels (the zoom, and a board the page scales, are accounted for). */
1384
- CanvasHost.prototype.translateWidgetShapeByScreen = function (widgetId, dxScreen, dyScreen) {
1787
+ translateWidgetShapeByScreen(widgetId, dxScreen, dyScreen) {
1385
1788
  if (!widgetId)
1386
1789
  return false;
1387
- var scale = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cssScale).call(this);
1790
+ const scale = this.#cssScale();
1388
1791
  return moveWidgetCardByScreen(this.engine, widgetId, dxScreen / scale.x, dyScreen / scale.y);
1389
- };
1792
+ }
1390
1793
  /** The page's bar let go: the move is one step and the board is marked as changed. */
1391
1794
  /** The id the old call carries (the creator still passes it) is not needed: only one card is carried at a time, and the engine knows which. */
1392
1795
  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- part of the signature pages call
1393
- CanvasHost.prototype.commitWidgetShapeTranslate = function (_widgetId) {
1796
+ commitWidgetShapeTranslate(_widgetId) {
1394
1797
  commitWidgetCardMove(this.engine);
1395
- };
1396
- CanvasHost.prototype.setWidgetShapeOverlayDragActive = function (active) {
1798
+ }
1799
+ setWidgetShapeOverlayDragActive(active) {
1397
1800
  this.engine.setOverlayDragActive(!!active);
1398
- };
1801
+ }
1399
1802
  // ────────────────────────────────────────────────────── helpers for the shell
1400
1803
  /**
1401
1804
  * The lines a text is drawn on. The board draws exactly these (never letting the browser wrap), and the sketch handed to
1402
1805
  * the AI is drawn from the same lines, so what is on the screen is what is sent. Kept per record: a text that did not
1403
1806
  * change is not laid out again on the next frame, and all of them are when the fonts finished loading.
1404
1807
  */
1405
- CanvasHost.prototype.textLayoutOf = function (text) {
1406
- var fontRevision = this.engine.state.fontRevision;
1407
- if (fontRevision !== __classPrivateFieldGet(this, _CanvasHost_textLayoutsFontRevision, "f")) {
1408
- __classPrivateFieldSet(this, _CanvasHost_textLayouts, new WeakMap(), "f");
1409
- __classPrivateFieldSet(this, _CanvasHost_textLayoutsFontRevision, fontRevision, "f");
1808
+ textLayoutOf(text) {
1809
+ const fontRevision = this.engine.state.fontRevision;
1810
+ if (fontRevision !== this.#textLayoutsFontRevision) {
1811
+ this.#textLayouts = new WeakMap();
1812
+ this.#textLayoutsFontRevision = fontRevision;
1410
1813
  }
1411
- var layout = __classPrivateFieldGet(this, _CanvasHost_textLayouts, "f").get(text);
1814
+ let layout = this.#textLayouts.get(text);
1412
1815
  if (!layout) {
1413
- layout = layoutTextObject(text, __classPrivateFieldGet(this, _CanvasHost_measureText, "f"));
1414
- __classPrivateFieldGet(this, _CanvasHost_textLayouts, "f").set(text, layout);
1816
+ layout = layoutTextObject(text, this.#measureText);
1817
+ this.#textLayouts.set(text, layout);
1415
1818
  }
1416
1819
  return layout;
1417
- };
1820
+ }
1418
1821
  /** The name drawn on a card: what the page calls the widget, what the card was saved with, or the generic word. */
1419
- CanvasHost.prototype.widgetLabel = function (card) {
1420
- var _a, _b;
1421
- var fromPage = (_b = (_a = this.props).getWidgetName) === null || _b === void 0 ? void 0 : _b.call(_a, card.widgetId);
1822
+ widgetLabel(card) {
1823
+ const fromPage = this.props.getWidgetName?.(card.widgetId);
1422
1824
  return fromPage || card.widgetName || this.translate('canvas.draw.widgetName');
1423
- };
1825
+ }
1424
1826
  /** Whether the widget behind a card is gone (the card is kept, with a label that says so). */
1425
- CanvasHost.prototype.isCardOrphaned = function (card) {
1827
+ isCardOrphaned(card) {
1426
1828
  if (this.engine.widgetRuntime(card.widgetId).orphaned)
1427
1829
  return true;
1428
- var known = this.props.isWidgetKnown;
1830
+ const known = this.props.isWidgetKnown;
1429
1831
  return known ? !known(card.widgetId) : false;
1430
- };
1832
+ }
1431
1833
  /** A new id for something the shell makes. */
1432
- CanvasHost.prototype.createId = function (prefix) {
1433
- if (prefix === void 0) { prefix = 'obj'; }
1834
+ createId(prefix = 'obj') {
1434
1835
  return createObjectId(prefix);
1435
- };
1836
+ }
1436
1837
  /** A plain rectangle in the middle of the view (used by the stress page). */
1437
- CanvasHost.prototype.makeRect = function (fields) {
1438
- if (fields === void 0) { fields = {}; }
1439
- var center = this.engine.visibleCenter();
1440
- var rect = createRectObject(__assign({ id: this.engine.services.createId('obj'), x: center.x - 50, y: center.y - 50, width: 100, height: 100 }, fields));
1838
+ makeRect(fields = {}) {
1839
+ const center = this.engine.visibleCenter();
1840
+ const rect = createRectObject({ id: this.engine.services.createId('obj'), x: center.x - 50, y: center.y - 50, width: 100, height: 100, ...fields });
1441
1841
  return this.engine.addObjects([rect])[0];
1442
- };
1842
+ }
1443
1843
  /** Scene summary for the sketch assistant (ids, labels, bounding boxes). */
1444
- CanvasHost.prototype.getSketchSceneSummary = function () {
1445
- var host = createCanvasToolHostFromEngine({
1844
+ getSketchSceneSummary() {
1845
+ const host = createCanvasToolHostFromEngine({
1446
1846
  engine: this.engine,
1447
1847
  bounds: { width: this.engine.state.viewSize.width || 1200, height: this.engine.state.viewSize.height || 800 }
1448
1848
  });
1449
1849
  return summarizeScene(host.getScene(), host.bounds);
1450
- };
1451
- CanvasHost.prototype.beginSketchToolBatch = function () {
1452
- if (__classPrivateFieldGet(this, _CanvasHost_sketchToolBatchBase, "f") === null) {
1850
+ }
1851
+ #sketchToolBatchBase = null;
1852
+ beginSketchToolBatch() {
1853
+ if (this.#sketchToolBatchBase === null) {
1453
1854
  // One undo step for the whole sketch turn: the tools run `transient` and `endSketchToolBatch` pushes one step.
1454
1855
  // The author's own undo history stays as it is (an assistant turn must never make earlier edits un-undoable).
1455
- __classPrivateFieldSet(this, _CanvasHost_sketchToolBatchBase, this.engine.state.scene, "f");
1856
+ this.#sketchToolBatchBase = this.engine.state.scene;
1456
1857
  }
1457
- };
1458
- CanvasHost.prototype.endSketchToolBatch = function () {
1459
- if (__classPrivateFieldGet(this, _CanvasHost_sketchToolBatchBase, "f") === null)
1858
+ }
1859
+ endSketchToolBatch() {
1860
+ if (this.#sketchToolBatchBase === null)
1460
1861
  return;
1461
- var finalScene = this.engine.state.scene;
1462
- if (finalScene !== __classPrivateFieldGet(this, _CanvasHost_sketchToolBatchBase, "f")) {
1862
+ const finalScene = this.engine.state.scene;
1863
+ if (finalScene !== this.#sketchToolBatchBase) {
1463
1864
  this.engine.applyScene(finalScene, 'push');
1464
1865
  }
1465
- __classPrivateFieldSet(this, _CanvasHost_sketchToolBatchBase, null, "f");
1466
- };
1866
+ this.#sketchToolBatchBase = null;
1867
+ }
1467
1868
  /** Run one allow-listed sketch tool (batched into one undo step when a batch is open). */
1468
- CanvasHost.prototype.executeSketchTool = function (name, args) {
1869
+ executeSketchTool(name, args) {
1469
1870
  if (!isCanvasToolName(name)) {
1470
- return { ok: false, error: "Unknown tool ".concat(name), code: 'invalid_args' };
1871
+ return { ok: false, error: `Unknown tool ${name}`, code: 'invalid_args' };
1471
1872
  }
1472
- var host = createCanvasToolHostFromEngine({
1873
+ const host = createCanvasToolHostFromEngine({
1473
1874
  engine: this.engine,
1474
1875
  bounds: { width: this.engine.state.viewSize.width || 1200, height: this.engine.state.viewSize.height || 800 },
1475
- commitMode: __classPrivateFieldGet(this, _CanvasHost_sketchToolBatchBase, "f") ? 'transient' : 'push'
1876
+ commitMode: this.#sketchToolBatchBase ? 'transient' : 'push'
1476
1877
  });
1477
1878
  return executeCanvasTool(host, name, args);
1478
- };
1479
- return CanvasHost;
1480
- }());
1481
- export { CanvasHost };
1482
- _CanvasHost_ui = new WeakMap(), _CanvasHost_scheduler = new WeakMap(), _CanvasHost_measureText = new WeakMap(), _CanvasHost_raster = new WeakMap(), _CanvasHost_root = new WeakMap(), _CanvasHost_board = new WeakMap(), _CanvasHost_resizeObserver = new WeakMap(), _CanvasHost_removeListeners = new WeakMap(), _CanvasHost_destroyed = new WeakMap(), _CanvasHost_loadDepth = new WeakMap(), _CanvasHost_longPress = new WeakMap(), _CanvasHost_touchWasLast = new WeakMap(), _CanvasHost_menuFinger = new WeakMap(), _CanvasHost_lastOverlayState = new WeakMap(), _CanvasHost_afterRenderQueued = new WeakMap(), _CanvasHost_resizingWidgetId = new WeakMap(), _CanvasHost_textLayouts = new WeakMap(), _CanvasHost_textLayoutsFontRevision = new WeakMap(), _CanvasHost_applyingAfterRender = new WeakMap(), _CanvasHost_unsubscribeEngine = new WeakMap(), _CanvasHost_lastAutosavedJson = new WeakMap(), _CanvasHost_pageIsLeaving = new WeakMap(), _CanvasHost_wasEditingText = new WeakMap(), _CanvasHost_keyboardReturnQueued = new WeakMap(), _CanvasHost_loadedWorkspaceSettings = new WeakMap(), _CanvasHost_scribbleFrame = new WeakMap(), _CanvasHost_scribbleClockLast = new WeakMap(), _CanvasHost_sketchToolBatchBase = new WeakMap(), _CanvasHost_instances = new WeakSet(), _CanvasHost_compactStylePatch = function _CanvasHost_compactStylePatch(fields) {
1483
- var compact = Object.fromEntries(Object.entries(fields).filter(function (_a) {
1484
- var value = _a[1];
1485
- return value !== undefined;
1486
- }));
1487
- return Object.keys(compact).length > 0 ? compact : undefined;
1488
- }, _CanvasHost_syncWorkspaceContext = function _CanvasHost_syncWorkspaceContext() {
1489
- return __awaiter(this, void 0, void 0, function () {
1490
- var fonts, workspaceId, textFamily;
1491
- var _a, _b, _c, _d, _e, _f, _g;
1492
- return __generator(this, function (_h) {
1493
- switch (_h.label) {
1494
- case 0: return [4 /*yield*/, ensureInterFontLoaded()];
1495
- case 1:
1496
- _h.sent();
1497
- fonts = (_a = this.props.workspaceFonts) !== null && _a !== void 0 ? _a : [];
1498
- setWorkspaceFontFamilies(fonts.map(function (font) { return font.family; }));
1499
- return [4 /*yield*/, registerWorkspaceFonts(fonts)];
1500
- case 2:
1501
- _h.sent();
1502
- this.engine.notifyFontsChanged();
1503
- workspaceId = this.props.workspaceId;
1504
- if (!workspaceId)
1505
- return [2 /*return*/];
1506
- __classPrivateFieldSet(this, _CanvasHost_loadedWorkspaceSettings, loadWorkspaceToolSettings({ workspaceId: workspaceId, userId: this.props.userId }), "f");
1507
- textFamily = (_c = (_b = __classPrivateFieldGet(this, _CanvasHost_loadedWorkspaceSettings, "f")) === null || _b === void 0 ? void 0 : _b.text) === null || _c === void 0 ? void 0 : _c.fontFamily;
1508
- if (textFamily) {
1509
- this.engine.setPreferredTextFontFamily(textFamily);
1510
- writePreferredTextFontFamily(textFamily);
1511
- }
1512
- else {
1513
- this.engine.setPreferredTextFontFamily(TEXT_DEFAULTS.fontFamily);
1514
- }
1515
- this.engine.setWorkspaceToolDefaults({
1516
- text: (_e = (_d = __classPrivateFieldGet(this, _CanvasHost_loadedWorkspaceSettings, "f")) === null || _d === void 0 ? void 0 : _d.text) !== null && _e !== void 0 ? _e : null,
1517
- paint: (_g = (_f = __classPrivateFieldGet(this, _CanvasHost_loadedWorkspaceSettings, "f")) === null || _f === void 0 ? void 0 : _f.paint) !== null && _g !== void 0 ? _g : null
1518
- });
1519
- return [2 /*return*/];
1520
- }
1521
- });
1522
- });
1523
- }, _CanvasHost_dropToolsThePageHides = function _CanvasHost_dropToolsThePageHides() {
1524
- if (this.props.showDrawingTools)
1525
- return;
1526
- var tool = this.engine.state.tool;
1527
- var drawingGroup = ['draw', 'erase', 'arrow', 'text'];
1528
- if (drawingGroup.includes(tool))
1529
- this.engine.setTool('select');
1530
- }, _CanvasHost_announceWidgetResize = function _CanvasHost_announceWidgetResize(kind) {
1531
- if (kind === 'resize') {
1532
- if (__classPrivateFieldGet(this, _CanvasHost_resizingWidgetId, "f") !== null)
1533
- return;
1534
- var widgetId = selectedWidgetId(this.engine);
1535
- if (!widgetId)
1536
- return;
1537
- __classPrivateFieldSet(this, _CanvasHost_resizingWidgetId, widgetId, "f");
1538
- announceWidgetPointerBlock({ widgetId: widgetId, active: true });
1539
- return;
1540
- }
1541
- if (__classPrivateFieldGet(this, _CanvasHost_resizingWidgetId, "f") === null)
1542
- return;
1543
- __classPrivateFieldSet(this, _CanvasHost_resizingWidgetId, null, "f");
1544
- announceWidgetPointerBlock({ widgetId: null, active: false });
1545
- }, _CanvasHost_updateUi = function _CanvasHost_updateUi(patch) {
1546
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1547
- return;
1548
- var current = __classPrivateFieldGet(this, _CanvasHost_ui, "f").value;
1549
- for (var _i = 0, _a = Object.keys(patch); _i < _a.length; _i++) {
1550
- var key = _a[_i];
1551
- if (!Object.is(patch[key], current[key])) {
1552
- __classPrivateFieldGet(this, _CanvasHost_ui, "f").set(__assign(__assign({}, current), patch));
1553
- return;
1554
- }
1555
- }
1556
- }, _CanvasHost_start = function _CanvasHost_start() {
1557
- return __awaiter(this, void 0, void 0, function () {
1558
- var initial, error_6;
1559
- var _this = this;
1560
- var _a, _b;
1561
- return __generator(this, function (_c) {
1562
- switch (_c.label) {
1563
- case 0:
1564
- // One turn of the event loop first: the page that mounted the shell assigns its reference to it (`bind:this`) in
1565
- // the same flush as this mount, and `onReady` is the moment the page starts to call the host's functions.
1566
- return [4 /*yield*/, Promise.resolve()];
1567
- case 1:
1568
- // One turn of the event loop first: the page that mounted the shell assigns its reference to it (`bind:this`) in
1569
- // the same flush as this mount, and `onReady` is the moment the page starts to call the host's functions.
1570
- _c.sent();
1571
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1572
- return [2 /*return*/];
1573
- initial = this.props.initialData;
1574
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_closeEmptyHintGate).call(this);
1575
- if (!initial) return [3 /*break*/, 5];
1576
- _c.label = 2;
1577
- case 2:
1578
- _c.trys.push([2, 4, , 5]);
1579
- return [4 /*yield*/, this.loadCanvas(initial)];
1580
- case 3:
1581
- _c.sent();
1582
- return [3 /*break*/, 5];
1583
- case 4:
1584
- error_6 = _c.sent();
1585
- console.error('Canvas: could not load the initial data', error_6);
1586
- return [3 /*break*/, 5];
1587
- case 5:
1588
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1589
- return [2 /*return*/];
1590
- // The first tool: the pencil, when the page shows the drawing tools (a board opens ready for a sketch), else Select.
1591
- this.engine.setTool(this.props.showDrawingTools ? 'draw' : 'select');
1592
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { loadPhase: 'ready' });
1593
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_queueAfterRender).call(this);
1594
- markCanvasOpenStep(CANVAS_OPEN_MARKS.READY);
1595
- try {
1596
- (_b = (_a = this.props).onReady) === null || _b === void 0 ? void 0 : _b.call(_a);
1597
- }
1598
- catch (error) {
1599
- canvasWarn('Canvas: onReady failed', error);
1600
- }
1601
- queueMicrotask(function () { return queueMicrotask(function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_syncEmptyHintGate).call(_this); }); });
1602
- return [2 /*return*/];
1603
- }
1604
- });
1605
- });
1606
- }, _CanvasHost_openEmptyHintGate = function _CanvasHost_openEmptyHintGate() {
1607
- if (!__classPrivateFieldGet(this, _CanvasHost_ui, "f").value.emptyHintGateOpen)
1608
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { emptyHintGateOpen: true });
1609
- }, _CanvasHost_closeEmptyHintGate = function _CanvasHost_closeEmptyHintGate() {
1610
- if (__classPrivateFieldGet(this, _CanvasHost_ui, "f").value.emptyHintGateOpen)
1611
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { emptyHintGateOpen: false });
1612
- }, _CanvasHost_syncEmptyHintGate = function _CanvasHost_syncEmptyHintGate() {
1613
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1614
- return;
1615
- var waiting = __classPrivateFieldGet(this, _CanvasHost_ui, "f").value.loadPhase !== 'ready' ||
1616
- __classPrivateFieldGet(this, _CanvasHost_loadDepth, "f") > 0 ||
1617
- this.engine.state.loading ||
1618
- this.props.isExternalDataLoading;
1619
- if (waiting) {
1620
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_closeEmptyHintGate).call(this);
1621
- return;
1622
- }
1623
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_openEmptyHintGate).call(this);
1624
- }, _CanvasHost_listen = function _CanvasHost_listen(target, type, listener, capture, options) {
1625
- if (capture === void 0) { capture = false; }
1626
- if (options === void 0) { options = {}; }
1627
- target.addEventListener(type, listener, __assign({ capture: capture }, options));
1628
- __classPrivateFieldGet(this, _CanvasHost_removeListeners, "f").push(function () { return target.removeEventListener(type, listener, { capture: capture }); });
1629
- }, _CanvasHost_measureBoard = function _CanvasHost_measureBoard() {
1630
- var board = __classPrivateFieldGet(this, _CanvasHost_board, "f");
1631
- if (!board)
1632
- return;
1633
- this.engine.setViewSize({ width: board.clientWidth, height: board.clientHeight }, this.props.keepCenterOnResize);
1634
- }, _CanvasHost_frame = function _CanvasHost_frame() {
1635
- var board = __classPrivateFieldGet(this, _CanvasHost_board, "f");
1636
- if (!board)
1637
- return null;
1638
- var rect = board.getBoundingClientRect();
1639
- return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, layoutWidth: board.clientWidth, layoutHeight: board.clientHeight };
1640
- }, _CanvasHost_cssScale = function _CanvasHost_cssScale() {
1641
- var frame = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_frame).call(this);
1642
- if (!frame || !frame.layoutWidth || !frame.layoutHeight)
1643
- return { x: 1, y: 1 };
1644
- return { x: frame.width / frame.layoutWidth || 1, y: frame.height / frame.layoutHeight || 1 };
1645
- }, _CanvasHost_pointerInput = function _CanvasHost_pointerInput(event, kind) {
1646
- var _a;
1647
- var frame = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_frame).call(this);
1648
- if (!frame)
1649
- return null;
1650
- var scaleX = frame.width / (frame.layoutWidth || frame.width || 1) || 1;
1651
- var scaleY = frame.height / (frame.layoutHeight || frame.height || 1) || 1;
1652
- var toBoard = function (clientX, clientY) { return ({ x: (clientX - frame.left) / scaleX, y: (clientY - frame.top) / scaleY }); };
1653
- var point = toBoard(event.clientX, event.clientY);
1654
- var pointerEvent = event;
1655
- var type = kind !== null && kind !== void 0 ? kind : (pointerEvent.pointerType === 'pen' ? 'pen' : pointerEvent.pointerType === 'touch' ? 'touch' : 'mouse');
1656
- var pressureOf = function (sample) {
1657
- return typeof sample.pressure === 'number' && Number.isFinite(sample.pressure) ? { pressure: sample.pressure } : {};
1658
- };
1659
- var coalesced = typeof pointerEvent.getCoalescedEvents === 'function'
1660
- ? pointerEvent.getCoalescedEvents().map(function (sample) { return (__assign(__assign(__assign({}, toBoard(sample.clientX, sample.clientY)), { time: sample.timeStamp }), pressureOf(sample))); })
1661
- : undefined;
1662
- return __assign(__assign({ pointerId: (_a = pointerEvent.pointerId) !== null && _a !== void 0 ? _a : 1, pointerType: type, x: point.x, y: point.y, button: event.button, time: event.timeStamp, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey }, pressureOf(pointerEvent)), (coalesced && coalesced.length > 1 ? { coalesced: coalesced } : {}));
1663
- }, _CanvasHost_startLongPress = function _CanvasHost_startLongPress(input) {
1664
- var _this = this;
1665
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_cancelLongPress).call(this);
1666
- // Only the select tool has a menu to open: with a pen, an eraser or a shape tool the finger is drawing.
1667
- if (this.engine.state.tool !== 'select' || this.engine.state.editingTextId)
1668
- return;
1669
- var timer = setTimeout(function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_fireLongPress).call(_this); }, TOUCH_LONG_PRESS_DELAY_MS);
1670
- __classPrivateFieldSet(this, _CanvasHost_longPress, { timer: timer, pointerId: input.pointerId, x: input.x, y: input.y }, "f");
1671
- }, _CanvasHost_cancelLongPress = function _CanvasHost_cancelLongPress() {
1672
- if (!__classPrivateFieldGet(this, _CanvasHost_longPress, "f"))
1673
- return;
1674
- clearTimeout(__classPrivateFieldGet(this, _CanvasHost_longPress, "f").timer);
1675
- __classPrivateFieldSet(this, _CanvasHost_longPress, null, "f");
1676
- }, _CanvasHost_fireLongPress = function _CanvasHost_fireLongPress() {
1677
- var pending = __classPrivateFieldGet(this, _CanvasHost_longPress, "f");
1678
- __classPrivateFieldSet(this, _CanvasHost_longPress, null, "f");
1679
- if (!pending || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f") || this.isLoading)
1680
- return;
1681
- // What the finger started (a pan, a move that has not moved yet, a marquee) ends here: the press became a menu.
1682
- this.controller.pointerCancel({ pointerId: pending.pointerId });
1683
- this.controller.prepareContextMenu({ x: pending.x, y: pending.y });
1684
- __classPrivateFieldSet(this, _CanvasHost_menuFinger, { pointerId: pending.pointerId, liftedAt: null }, "f");
1685
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { contextMenu: { x: pending.x, y: pending.y, byTouch: true }, shapesMenuOpen: false, selectionPanelDismissed: true });
1686
- }, _CanvasHost_noteFingerLifted = function _CanvasHost_noteFingerLifted(pointerId) {
1687
- if (__classPrivateFieldGet(this, _CanvasHost_menuFinger, "f") && __classPrivateFieldGet(this, _CanvasHost_menuFinger, "f").pointerId === pointerId && __classPrivateFieldGet(this, _CanvasHost_menuFinger, "f").liftedAt === null)
1688
- __classPrivateFieldGet(this, _CanvasHost_menuFinger, "f").liftedAt = Date.now();
1689
- }, _CanvasHost_onWheel = function _CanvasHost_onWheel(event) {
1690
- if (this.isLoading || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1691
- return;
1692
- var base = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_pointerInput).call(this, event, 'mouse');
1693
- if (!base)
1694
- return;
1695
- event.preventDefault();
1696
- var input = {
1697
- x: base.x,
1698
- y: base.y,
1699
- deltaX: event.deltaX,
1700
- deltaY: event.deltaY,
1701
- deltaMode: event.deltaMode,
1702
- shiftKey: event.shiftKey,
1703
- altKey: event.altKey,
1704
- metaKey: event.metaKey,
1705
- ctrlKey: event.ctrlKey
1706
- };
1707
- this.controller.wheel(input);
1708
- }, _CanvasHost_closeTransientUi = function _CanvasHost_closeTransientUi() {
1709
- var _a = __classPrivateFieldGet(this, _CanvasHost_ui, "f").value, contextMenu = _a.contextMenu, shapesMenuOpen = _a.shapesMenuOpen;
1710
- __classPrivateFieldSet(this, _CanvasHost_menuFinger, null, "f");
1711
- if (contextMenu || shapesMenuOpen)
1712
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { contextMenu: null, shapesMenuOpen: false });
1713
- }, _CanvasHost_keyboardActions = function _CanvasHost_keyboardActions() {
1714
- var _this = this;
1715
- return {
1716
- chooseTool: function (tool) { return _this.chooseShortcutTool(tool); },
1717
- save: function () { return _this.saveNow(); },
1718
- toggleShortcuts: function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { shortcutsOpen: !__classPrivateFieldGet(_this, _CanvasHost_ui, "f").value.shortcutsOpen }); },
1719
- closePanels: function () {
1720
- var _a = __classPrivateFieldGet(_this, _CanvasHost_ui, "f").value, contextMenu = _a.contextMenu, shapesMenuOpen = _a.shapesMenuOpen, shortcutsOpen = _a.shortcutsOpen;
1721
- if (!contextMenu && !shapesMenuOpen && !shortcutsOpen)
1722
- return false;
1723
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { contextMenu: null, shapesMenuOpen: false, shortcutsOpen: false });
1724
- return true;
1725
- },
1726
- afterCopy: function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_markClipboardAsOurs).call(_this); },
1727
- spacePanChanged: function (held) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { spacePan: held }); }
1728
- };
1729
- }, _CanvasHost_keyboardHost = function _CanvasHost_keyboardHost(origin) {
1730
- var _a, _b;
1731
- var hasTextSelection = false;
1732
- try {
1733
- hasTextSelection = ((_b = (_a = window.getSelection()) === null || _a === void 0 ? void 0 : _a.toString().length) !== null && _b !== void 0 ? _b : 0) > 0;
1734
1879
  }
1735
- catch (_c) {
1736
- hasTextSelection = false;
1737
- }
1738
- return {
1739
- engine: this.engine,
1740
- controller: this.controller,
1741
- actions: __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_keyboardActions).call(this),
1742
- tools: this.tools,
1743
- typingInField: isEditableTarget(origin),
1744
- hasTextSelection: hasTextSelection,
1745
- selectorHintOpen: this.props.showElementSelector && this.props.elementSelectorActive
1746
- };
1747
- }, _CanvasHost_onKeyDown = function _CanvasHost_onKeyDown(event) {
1748
- var _a;
1749
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f") || !__classPrivateFieldGet(this, _CanvasHost_root, "f") || this.isLoading)
1750
- return;
1751
- if (!eventIsForScope(event, __classPrivateFieldGet(this, _CanvasHost_root, "f")))
1752
- return;
1753
- var origin = getEventOrigin(event);
1754
- // A key pressed inside an open menu or dialog is that menu's (its typeahead, its arrows), not a tool's letter.
1755
- if ((_a = origin === null || origin === void 0 ? void 0 : origin.closest) === null || _a === void 0 ? void 0 : _a.call(origin, '[role="menu"], [role="dialog"], [role="listbox"]'))
1756
- return;
1757
- // A focused slider, tab list or list box keeps its arrow keys: they move its value, and not the selection on the board.
1758
- if (NAVIGATION_KEYS.has(event.key) && ownsNavigationKeys(origin))
1759
- return;
1760
- // A focused button, link or menu entry keeps its Space (the pan has its own button, and the hand tool).
1761
- if (event.code === 'Space' && isActivatableTarget(origin))
1762
- return;
1763
- var input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey, repeat: event.repeat };
1764
- // Shift, Alt and the like change what a running gesture does without moving the pointer.
1765
- if (event.key === 'Shift' || event.key === 'Alt' || event.key === 'Control' || event.key === 'Meta') {
1766
- this.controller.modifiersChanged({ shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
1767
- return;
1768
- }
1769
- var handled = false;
1770
- try {
1771
- handled = routeKeyDown(input, __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_keyboardHost).call(this, origin));
1772
- }
1773
- catch (error) {
1774
- canvasWarn('Canvas: a key press failed', error);
1775
- }
1776
- if (handled) {
1777
- event.preventDefault();
1778
- event.stopPropagation();
1779
- }
1780
- }, _CanvasHost_onKeyUp = function _CanvasHost_onKeyUp(event) {
1781
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f") || !__classPrivateFieldGet(this, _CanvasHost_root, "f"))
1782
- return;
1783
- if (event.key === 'Shift' || event.key === 'Alt' || event.key === 'Control' || event.key === 'Meta') {
1784
- this.controller.modifiersChanged({ shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
1785
- return;
1786
- }
1787
- if (!eventIsForScope(event, __classPrivateFieldGet(this, _CanvasHost_root, "f"))) {
1788
- // A Space released outside the canvas still ends the pan.
1789
- if (event.code === 'Space')
1790
- this.controller.setSpaceHeld(false);
1791
- return;
1792
- }
1793
- var input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey };
1794
- if (routeKeyUp(input, __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_keyboardHost).call(this, getEventOrigin(event)))) {
1795
- event.preventDefault();
1796
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { spacePan: false });
1797
- }
1798
- }, _CanvasHost_onWindowBlur = function _CanvasHost_onWindowBlur() {
1799
- releaseHeldKeys(__classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_keyboardHost).call(this, null));
1800
- }, _CanvasHost_markClipboardAsOurs = function _CanvasHost_markClipboardAsOurs() {
1801
- var _a;
1802
- try {
1803
- var clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;
1804
- void ((_a = clipboard === null || clipboard === void 0 ? void 0 : clipboard.writeText) === null || _a === void 0 ? void 0 : _a.call(clipboard, CLIPBOARD_MARKER).catch(function () { return undefined; }));
1805
- }
1806
- catch (_b) {
1807
- // A browser that refuses leaves the older clipboard in place: the paste then prefers its picture.
1808
- }
1809
- }, _CanvasHost_onPaste = function _CanvasHost_onPaste(event) {
1810
- var _a, _b, _c, _d, _e;
1811
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f") || !__classPrivateFieldGet(this, _CanvasHost_root, "f") || this.isLoading)
1812
- return;
1813
- if (!eventIsForScope(event, __classPrivateFieldGet(this, _CanvasHost_root, "f")))
1814
- return;
1815
- if (this.engine.state.editingTextId)
1816
- return;
1817
- var origin = getEventOrigin(event);
1818
- if (isEditableTarget(origin))
1819
- return;
1820
- if ((_a = origin === null || origin === void 0 ? void 0 : origin.closest) === null || _a === void 0 ? void 0 : _a.call(origin, PASTE_EXCLUDED_SELECTOR))
1821
- return;
1822
- var items = Array.from((_c = (_b = event.clipboardData) === null || _b === void 0 ? void 0 : _b.items) !== null && _c !== void 0 ? _c : []);
1823
- var picture = items.find(function (item) { return item.type.startsWith('image/'); });
1824
- var pasteInside = this.engine.hasClipboard() && ((_d = event.clipboardData) === null || _d === void 0 ? void 0 : _d.getData('text/plain')) === CLIPBOARD_MARKER;
1825
- if (picture && !pasteInside) {
1826
- var blob = picture.getAsFile();
1827
- if (!blob)
1828
- return;
1829
- event.preventDefault();
1830
- var at = (_e = this.engine.lastPointerWorld) !== null && _e !== void 0 ? _e : undefined;
1831
- void this.insertImageFiles([blob], at);
1832
- return;
1833
- }
1834
- if (this.engine.hasClipboard()) {
1835
- event.preventDefault();
1836
- this.engine.paste();
1837
- }
1838
- }, _CanvasHost_wireEngineHooks = function _CanvasHost_wireEngineHooks() {
1839
- var _this = this;
1840
- var hooks = {
1841
- onDirty: function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_markDirty).call(_this); },
1842
- // Typing is a change too: the letters are saved with the next save, before the typing ends and makes its undo step.
1843
- onDraftChange: function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_markDirty).call(_this); },
1844
- onCleared: function () { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_safely).call(_this, function () { var _a, _b; return (_b = (_a = _this.props).onCanvasCleared) === null || _b === void 0 ? void 0 : _b.call(_a); }, 'onCanvasCleared'); },
1845
- onSelectionChange: function (ids) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onSelectionChange).call(_this, ids); },
1846
- confirmWidgetDeletion: function (widgetId) {
1847
- var ask = _this.props.onWidgetShapeDeleting;
1848
- return ask ? ask(widgetId) : true;
1849
- },
1850
- onWidgetDuplicated: function (sourceWidgetId, clone) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onWidgetDuplicated).call(_this, sourceWidgetId, clone); },
1851
- onError: function (message, error) { return canvasWarn("Canvas: ".concat(message), error); }
1852
- };
1853
- this.engine.hooks = hooks;
1854
- }, _CanvasHost_safely = function _CanvasHost_safely(run, name) {
1855
- try {
1856
- run();
1857
- }
1858
- catch (error) {
1859
- canvasWarn("Canvas: ".concat(name, " failed"), error);
1860
- }
1861
- }, _CanvasHost_markDirty = function _CanvasHost_markDirty() {
1862
- var _this = this;
1863
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1864
- return;
1865
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { saveState: 'dirty' });
1866
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_safely).call(this, function () { var _a, _b; return (_b = (_a = _this.props).onCanvasDirty) === null || _b === void 0 ? void 0 : _b.call(_a); }, 'onCanvasDirty');
1867
- __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").markChanged();
1868
- }, _CanvasHost_onSelectionChange = function _CanvasHost_onSelectionChange(ids) {
1869
- var _this = this;
1870
- if (ids.length === 0)
1871
- return;
1872
- var selected = this.engine.selectedObjects();
1873
- var onlyAWidget = selected.length === 1 && selected[0].type === 'widget';
1874
- if (!onlyAWidget)
1875
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_safely).call(this, function () { var _a, _b; return (_b = (_a = _this.props).onNonWidgetSelected) === null || _b === void 0 ? void 0 : _b.call(_a); }, 'onNonWidgetSelected');
1876
- }, _CanvasHost_onWidgetDuplicated = function _CanvasHost_onWidgetDuplicated(sourceWidgetId, clone) {
1877
- var notify = this.props.onWidgetShapeDuplicated;
1878
- if (!notify)
1879
- return;
1880
- // The page gets a view of the card, under the names the old canvas kept (`_widgetId`, `_objectId`).
1881
- var view = hostObjectById(this.engine, clone.id);
1882
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_safely).call(this, function () { return notify(sourceWidgetId, view); }, 'onWidgetShapeDuplicated');
1883
- }, _CanvasHost_handleActivate = function _CanvasHost_handleActivate(id) {
1884
- var object = this.engine.getObject(id);
1885
- if (!object || object.type !== 'widget')
1886
- return;
1887
- var notify = this.props.onWidgetImageClick;
1888
- if (notify && object.widgetId)
1889
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_safely).call(this, function () { return notify(object.widgetId); }, 'onWidgetImageClick');
1890
- }, _CanvasHost_onEngineState = function _CanvasHost_onEngineState(state) {
1891
- // The eraser's trail lives on the frame clock: it starts with the trail and stops when the trail is gone.
1892
- if (state.scribble !== null)
1893
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_startScribbleClock).call(this);
1894
- var isEditingText = state.editingTextId !== null;
1895
- if (__classPrivateFieldGet(this, _CanvasHost_wasEditingText, "f") && !isEditingText)
1896
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_takeKeyboardBackSoon).call(this);
1897
- __classPrivateFieldSet(this, _CanvasHost_wasEditingText, isEditingText, "f");
1898
- var last = __classPrivateFieldGet(this, _CanvasHost_lastOverlayState, "f");
1899
- if (!last ||
1900
- last.scene !== state.scene ||
1901
- last.viewport !== state.viewport ||
1902
- last.viewSize !== state.viewSize ||
1903
- last.widgets !== state.widgets ||
1904
- last.pending !== state.pending ||
1905
- last.hoverWidgetId !== state.hoverWidgetId ||
1906
- last.selectedIds !== state.selectedIds ||
1907
- last.overlayDragActive !== state.overlayDragActive) {
1908
- if (last && last.selectedIds !== state.selectedIds) {
1909
- if (state.selectedIds.length === 0) {
1910
- // Leave dismissal as the user left it.
1911
- }
1912
- else {
1913
- var selected = state.selectedIds
1914
- .map(function (id) { return state.scene.find(function (object) { return object.id === id; }); })
1915
- .filter(function (object) { return object !== undefined; });
1916
- var widgetOnly = selected.length === 1 && selected[0].type === 'widget';
1917
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { selectionPanelDismissed: widgetOnly });
1918
- }
1919
- }
1920
- __classPrivateFieldSet(this, _CanvasHost_lastOverlayState, {
1921
- scene: state.scene,
1922
- viewport: state.viewport,
1923
- viewSize: state.viewSize,
1924
- widgets: state.widgets,
1925
- pending: state.pending,
1926
- hoverWidgetId: state.hoverWidgetId,
1927
- selectedIds: state.selectedIds,
1928
- overlayDragActive: state.overlayDragActive
1929
- }, "f");
1930
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_queueAfterRender).call(this);
1931
- }
1932
- }, _CanvasHost_takeKeyboardBackSoon = function _CanvasHost_takeKeyboardBackSoon() {
1933
- var _this = this;
1934
- if (__classPrivateFieldGet(this, _CanvasHost_keyboardReturnQueued, "f") || typeof requestAnimationFrame !== 'function')
1935
- return;
1936
- __classPrivateFieldSet(this, _CanvasHost_keyboardReturnQueued, true, "f");
1937
- requestAnimationFrame(function () {
1938
- __classPrivateFieldSet(_this, _CanvasHost_keyboardReturnQueued, false, "f");
1939
- if (__classPrivateFieldGet(_this, _CanvasHost_destroyed, "f") || !__classPrivateFieldGet(_this, _CanvasHost_board, "f"))
1940
- return;
1941
- try {
1942
- if (shouldTakeFocusBack(__classPrivateFieldGet(_this, _CanvasHost_board, "f"))) {
1943
- _this.focusBoard();
1944
- canvasLog('Canvas: the board took the keyboard back after a text was typed');
1945
- }
1946
- }
1947
- catch (error) {
1948
- canvasWarn('Canvas: could not give the keyboard back to the board', error);
1949
- }
1950
- });
1951
- }, _CanvasHost_startScribbleClock = function _CanvasHost_startScribbleClock() {
1952
- var _this = this;
1953
- if (__classPrivateFieldGet(this, _CanvasHost_scribbleFrame, "f") !== null || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f") || typeof requestAnimationFrame !== 'function')
1954
- return;
1955
- if (__classPrivateFieldGet(this, _CanvasHost_scribbleClockLast, "f") === null)
1956
- __classPrivateFieldSet(this, _CanvasHost_scribbleClockLast, typeof performance !== 'undefined' ? performance.now() : 0, "f");
1957
- __classPrivateFieldSet(this, _CanvasHost_scribbleFrame, requestAnimationFrame(function (time) { return __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_onScribbleFrame).call(_this, time); }), "f");
1958
- }, _CanvasHost_onScribbleFrame = function _CanvasHost_onScribbleFrame(time) {
1959
- var _a;
1960
- __classPrivateFieldSet(this, _CanvasHost_scribbleFrame, null, "f");
1961
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1962
- return;
1963
- var elapsedMs = Math.max(0, time - ((_a = __classPrivateFieldGet(this, _CanvasHost_scribbleClockLast, "f")) !== null && _a !== void 0 ? _a : time));
1964
- __classPrivateFieldSet(this, _CanvasHost_scribbleClockLast, time, "f");
1965
- var alive = false;
1966
- try {
1967
- alive = this.engine.stepScribble(elapsedMs);
1968
- }
1969
- catch (error) {
1970
- canvasWarn('Canvas: the eraser trail could not be stepped', error);
1971
- }
1972
- if (!alive) {
1973
- __classPrivateFieldSet(this, _CanvasHost_scribbleClockLast, null, "f");
1974
- return;
1975
- }
1976
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_startScribbleClock).call(this);
1977
- }, _CanvasHost_queueAfterRender = function _CanvasHost_queueAfterRender() {
1978
- var _this = this;
1979
- if (!this.props.onAfterRender || __classPrivateFieldGet(this, _CanvasHost_afterRenderQueued, "f") || __classPrivateFieldGet(this, _CanvasHost_applyingAfterRender, "f") || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
1980
- return;
1981
- if (typeof requestAnimationFrame !== 'function')
1982
- return;
1983
- __classPrivateFieldSet(this, _CanvasHost_afterRenderQueued, true, "f");
1984
- requestAnimationFrame(function () {
1985
- __classPrivateFieldSet(_this, _CanvasHost_afterRenderQueued, false, "f");
1986
- var callback = _this.props.onAfterRender;
1987
- if (!callback || __classPrivateFieldGet(_this, _CanvasHost_applyingAfterRender, "f") || __classPrivateFieldGet(_this, _CanvasHost_destroyed, "f"))
1988
- return;
1989
- __classPrivateFieldSet(_this, _CanvasHost_applyingAfterRender, true, "f");
1990
- try {
1991
- callback();
1992
- }
1993
- catch (error) {
1994
- canvasWarn('Canvas: onAfterRender failed', error);
1995
- }
1996
- finally {
1997
- __classPrivateFieldSet(_this, _CanvasHost_applyingAfterRender, false, "f");
1998
- }
1999
- });
2000
- }, _CanvasHost_handleStrokeFinished = function _CanvasHost_handleStrokeFinished(stroke, handLine) {
2001
- // Off unless the page asked (shapeSnap) or the package's own flag is flipped.
2002
- if (!isShapeSnapOn(this.props.shapeSnap))
2003
- return;
2004
- void snapDrawnStroke(this.engine, stroke, { recognize: this.props.onRecognizeStroke, log: function (message, details) { return canvasLog(message, details); } }, handLine);
2005
- }, _CanvasHost_runAutosave = function _CanvasHost_runAutosave() {
2006
- var _this = this;
2007
- var _a, _b;
2008
- var json = __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_serializeCanvasText).call(this);
2009
- if (json === null) {
2010
- // The board has nothing to give right now (it is loading): ask the buffer for another go a delay later.
2011
- canvasLog('Canvas: autosave: the board cannot be serialized yet, trying again after the delay');
2012
- __classPrivateFieldGet(this, _CanvasHost_scheduler, "f").markChanged();
2013
- return undefined;
2014
- }
2015
- if (json === __classPrivateFieldGet(this, _CanvasHost_lastAutosavedJson, "f")) {
2016
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { saveState: 'saved' });
2017
- return undefined;
2018
- }
2019
- canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
2020
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { saveState: 'saving' });
2021
- var outcome;
2022
- try {
2023
- outcome = (_b = (_a = this.props).onAutoSave) === null || _b === void 0 ? void 0 : _b.call(_a, json, { leaving: __classPrivateFieldGet(this, _CanvasHost_pageIsLeaving, "f") });
2024
- }
2025
- catch (error) {
2026
- __classPrivateFieldGet(this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(this, { saveState: 'dirty' });
2027
- throw error;
2028
- }
2029
- var finish = function (savedJson) {
2030
- __classPrivateFieldSet(_this, _CanvasHost_lastAutosavedJson, savedJson, "f");
2031
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { saveState: __classPrivateFieldGet(_this, _CanvasHost_scheduler, "f").isDirty ? 'dirty' : 'saved' });
2032
- };
2033
- if (outcome && typeof outcome.then === 'function') {
2034
- return outcome.then(function (value) {
2035
- finish(json);
2036
- return value;
2037
- }, function (error) {
2038
- __classPrivateFieldGet(_this, _CanvasHost_instances, "m", _CanvasHost_updateUi).call(_this, { saveState: 'dirty' });
2039
- throw error;
2040
- });
2041
- }
2042
- finish(json);
2043
- return outcome;
2044
- }, _CanvasHost_serializeCanvasText = function _CanvasHost_serializeCanvasText() {
2045
- if (__classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
2046
- return null;
2047
- if (__classPrivateFieldGet(this, _CanvasHost_loadDepth, "f") > 0 || this.engine.state.loading) {
2048
- canvasLog('Canvas: saveCanvas skipped (the board is loading)');
2049
- return null;
2050
- }
2051
- try {
2052
- return this.engine.serialize({ imageStore: getShapeImageStore() });
2053
- }
2054
- catch (error) {
2055
- console.error('Canvas: saveCanvas failed', error);
2056
- return null;
2057
- }
2058
- }, _CanvasHost_resolveStoredImages = function _CanvasHost_resolveStoredImages() {
2059
- return __awaiter(this, void 0, void 0, function () {
2060
- var store, scene, missing, found, next;
2061
- var _this = this;
2062
- return __generator(this, function (_a) {
2063
- switch (_a.label) {
2064
- case 0:
2065
- store = getShapeImageStore();
2066
- if (!store)
2067
- return [2 /*return*/];
2068
- scene = this.engine.state.scene;
2069
- missing = scene.filter(function (object) { return (object.type === 'image' && !object.src && !!object.imageRef) || (object.type === 'widget' && !object.thumbnail && !!object.thumbnailRef); });
2070
- if (missing.length === 0)
2071
- return [2 /*return*/];
2072
- found = new Map();
2073
- return [4 /*yield*/, Promise.all(missing.map(function (object) { return __awaiter(_this, void 0, void 0, function () {
2074
- var reference, dataUrl, error_7;
2075
- return __generator(this, function (_a) {
2076
- switch (_a.label) {
2077
- case 0:
2078
- reference = object.type === 'image' ? object.imageRef : object.type === 'widget' ? object.thumbnailRef : null;
2079
- if (!reference)
2080
- return [2 /*return*/];
2081
- _a.label = 1;
2082
- case 1:
2083
- _a.trys.push([1, 3, , 4]);
2084
- return [4 /*yield*/, store.load(reference)];
2085
- case 2:
2086
- dataUrl = _a.sent();
2087
- if (dataUrl)
2088
- found.set(object.id, dataUrl);
2089
- return [3 /*break*/, 4];
2090
- case 3:
2091
- error_7 = _a.sent();
2092
- canvasWarn('Canvas: a stored picture could not be read', reference, error_7);
2093
- return [3 /*break*/, 4];
2094
- case 4: return [2 /*return*/];
2095
- }
2096
- });
2097
- }); }))];
2098
- case 1:
2099
- _a.sent();
2100
- if (found.size === 0 || __classPrivateFieldGet(this, _CanvasHost_destroyed, "f"))
2101
- return [2 /*return*/];
2102
- next = this.engine.state.scene.map(function (object) {
2103
- var dataUrl = found.get(object.id);
2104
- if (!dataUrl)
2105
- return object;
2106
- if (object.type === 'image' && !object.src)
2107
- return __assign(__assign({}, object), { src: dataUrl });
2108
- if (object.type === 'widget' && !object.thumbnail)
2109
- return __assign(__assign({}, object), { thumbnail: dataUrl });
2110
- return object;
2111
- });
2112
- this.engine.applySilently(next);
2113
- return [2 /*return*/];
2114
- }
2115
- });
2116
- });
2117
- }, _CanvasHost_placeAtCenter = function _CanvasHost_placeAtCenter(kind) {
2118
- var center = this.engine.visibleCenter();
2119
- return buildDraggedShape({
2120
- kind: kind,
2121
- start: center,
2122
- end: center,
2123
- constrain: false,
2124
- dragged: false,
2125
- wireframe: this.engine.wireframeMode,
2126
- createId: this.engine.services.createId,
2127
- random: this.engine.services.random,
2128
- workspacePaint: this.engine.workspacePaintForNewShape(this.engine.wireframeMode)
2129
- });
2130
- };
1880
+ }