@widgetic/canvas 0.5.44 → 0.5.45

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