@widgetic/canvas 0.5.45 → 0.5.47

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