@widgetic/canvas 0.5.41 → 0.5.43

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