@widgetic/canvas 0.5.40 → 0.5.41

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