@widgetic/canvas 0.5.45 → 0.5.46

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