@widgetic/canvas 0.5.41 → 0.5.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +1 -0
  2. package/dist/canvas/DomCanvas.svelte +49 -20
  3. package/dist/canvas/DomCanvas.svelte.d.ts +13 -7
  4. package/dist/canvas/autosaveScheduler.js +37 -89
  5. package/dist/canvas/boardFrame.js +1 -1
  6. package/dist/canvas/boardSurface.js +1 -1
  7. package/dist/canvas/canvasLogger.js +7 -19
  8. package/dist/canvas/chromeLayout.d.ts +14 -3
  9. package/dist/canvas/chromeLayout.js +30 -20
  10. package/dist/canvas/eventScope.js +10 -14
  11. package/dist/canvas/host/CanvasHost.d.ts +47 -5
  12. package/dist/canvas/host/CanvasHost.js +1481 -1566
  13. package/dist/canvas/host/CanvasHostApi.js +4 -19
  14. package/dist/canvas/host/browserServices.js +65 -116
  15. package/dist/canvas/host/conversion.js +82 -170
  16. package/dist/canvas/host/hostObject.js +7 -7
  17. package/dist/canvas/host/nearCards.d.ts +33 -0
  18. package/dist/canvas/host/nearCards.js +78 -0
  19. package/dist/canvas/host/pageEvents.d.ts +16 -4
  20. package/dist/canvas/host/pageEvents.js +17 -8
  21. package/dist/canvas/host/pictureSaves.d.ts +33 -0
  22. package/dist/canvas/host/pictureSaves.js +42 -0
  23. package/dist/canvas/host/screenRects.d.ts +5 -0
  24. package/dist/canvas/host/screenRects.js +28 -31
  25. package/dist/canvas/host/storedPictures.d.ts +88 -0
  26. package/dist/canvas/host/storedPictures.js +288 -0
  27. package/dist/canvas/host/strokeSnap.js +88 -143
  28. package/dist/canvas/index.d.ts +1 -1
  29. package/dist/canvas/index.js +1 -1
  30. package/dist/canvas/openMarks.js +2 -2
  31. package/dist/canvas/outsideClickDeselect.js +6 -7
  32. package/dist/canvas/panZoomPosition.js +2 -2
  33. package/dist/canvas/preferredTextFont.js +13 -25
  34. package/dist/canvas/shapes/ShapeLibrary.js +138 -148
  35. package/dist/canvas/shapes/shapeImageStore.d.ts +45 -2
  36. package/dist/canvas/shapes/shapeImageStore.js +10 -3
  37. package/dist/canvas/shapes/strokeShapeSnap.js +188 -233
  38. package/dist/canvas/toolbarPosition.d.ts +2 -2
  39. package/dist/canvas/toolbarPosition.js +4 -4
  40. package/dist/canvas/ui/SelectionPanel.svelte +28 -5
  41. package/dist/canvas/ui/SelectionPanel.svelte.d.ts +7 -0
  42. package/dist/canvas/ui/SelectorIndicator.svelte +81 -0
  43. package/dist/canvas/ui/SelectorIndicator.svelte.d.ts +11 -0
  44. package/dist/canvas/ui/ToolButton.svelte +8 -2
  45. package/dist/canvas/ui/colorModel.js +21 -32
  46. package/dist/canvas/ui/colorPickerMessages.js +5 -5
  47. package/dist/canvas/ui/floatingCard.d.ts +2 -2
  48. package/dist/canvas/ui/floatingCard.js +20 -20
  49. package/dist/canvas/ui/floatingLayer.d.ts +13 -2
  50. package/dist/canvas/ui/floatingLayer.js +18 -7
  51. package/dist/canvas/ui/keyHints.js +9 -11
  52. package/dist/canvas/ui/popoverSide.js +2 -3
  53. package/dist/canvas/ui/selectionTraits.js +34 -40
  54. package/dist/canvas/view/CanvasStage.svelte +101 -67
  55. package/dist/canvas/view/LeftToRightScope.svelte +21 -0
  56. package/dist/canvas/view/LeftToRightScope.svelte.d.ts +7 -0
  57. package/dist/canvas/view/ObjectView.svelte +15 -10
  58. package/dist/canvas/view/ObjectView.svelte.d.ts +1 -1
  59. package/dist/canvas/view/erasingMarks.js +7 -7
  60. package/dist/canvas/view/geometry.js +71 -90
  61. package/dist/canvas/view/liftedScene.d.ts +31 -0
  62. package/dist/canvas/view/liftedScene.js +146 -0
  63. package/dist/canvas/view/mountedScene.d.ts +71 -0
  64. package/dist/canvas/view/mountedScene.js +363 -0
  65. package/dist/components/preferenceStorage.js +2 -2
  66. package/dist/engine/EngineCore.d.ts +15 -1
  67. package/dist/engine/EngineCore.js +724 -797
  68. package/dist/engine/codec/canvasDocument.d.ts +5 -0
  69. package/dist/engine/codec/canvasDocument.js +212 -149
  70. package/dist/engine/codec/hostReadableKeys.js +1 -1
  71. package/dist/engine/core/arrange.js +26 -38
  72. package/dist/engine/core/arrow.js +76 -89
  73. package/dist/engine/core/arrowBinding.js +98 -116
  74. package/dist/engine/core/arrowBindingRecords.js +23 -38
  75. package/dist/engine/core/brush.js +67 -94
  76. package/dist/engine/core/defaults.js +90 -51
  77. package/dist/engine/core/freehand.js +147 -163
  78. package/dist/engine/core/geometry.js +47 -54
  79. package/dist/engine/core/history.d.ts +6 -0
  80. package/dist/engine/core/history.js +49 -50
  81. package/dist/engine/core/hitTest.js +68 -81
  82. package/dist/engine/core/matrix.js +18 -20
  83. package/dist/engine/core/pathData.js +183 -210
  84. package/dist/engine/core/rotationReset.js +5 -6
  85. package/dist/engine/core/scene.d.ts +10 -0
  86. package/dist/engine/core/scene.js +153 -187
  87. package/dist/engine/core/scribble.js +59 -84
  88. package/dist/engine/core/shapePaths.js +12 -15
  89. package/dist/engine/core/shapeTools.js +72 -63
  90. package/dist/engine/core/snapping.js +65 -117
  91. package/dist/engine/core/style.js +31 -64
  92. package/dist/engine/core/transform.js +83 -94
  93. package/dist/engine/core/types.d.ts +8 -2
  94. package/dist/engine/core/types.js +4 -4
  95. package/dist/engine/core/viewport.js +23 -36
  96. package/dist/engine/input/PointerController.js +467 -474
  97. package/dist/engine/input/arrowHandles.js +12 -12
  98. package/dist/engine/input/gestures.js +265 -309
  99. package/dist/engine/input/hoverCursor.js +1 -1
  100. package/dist/engine/input/keyboard.js +27 -30
  101. package/dist/engine/input/selectionHandles.js +45 -50
  102. package/dist/engine/input/types.js +1 -1
  103. package/dist/engine/render/rasterize.js +86 -158
  104. package/dist/engine/state.d.ts +20 -0
  105. package/dist/engine/state.js +5 -15
  106. package/dist/engine/text/layoutText.js +43 -62
  107. package/dist/engine/text/textMetrics.js +8 -10
  108. package/dist/engine/widgets.js +101 -137
  109. package/dist/fonts/interFont.d.ts +10 -1
  110. package/dist/fonts/interFont.js +47 -75
  111. package/dist/fonts/workspaceFonts.js +32 -90
  112. package/dist/i18n/labels.js +4 -4
  113. package/dist/i18n/language.d.ts +3 -3
  114. package/dist/i18n/language.js +4 -4
  115. package/dist/i18n/messages.d.ts +8 -1
  116. package/dist/i18n/messages.js +10 -2
  117. package/dist/i18n/shortcuts.js +14 -14
  118. package/dist/index.d.ts +1 -1
  119. package/dist/index.js +1 -1
  120. package/dist/settings/workspaceToolSettings.js +32 -48
  121. package/dist/tools/components/catalog.js +64 -74
  122. package/dist/tools/components/grouping.js +6 -28
  123. package/dist/tools/definitions.js +5 -5
  124. package/dist/tools/executors.js +105 -141
  125. package/dist/tools/hostAdapter.js +11 -13
  126. package/dist/tools/sceneSummary.js +43 -57
  127. package/dist/tools/sketchIntent.js +13 -21
  128. package/dist/tools/types.js +1 -1
  129. package/package.json +1 -1
  130. package/dist/canvas/ui/SelectorBar.svelte +0 -84
  131. package/dist/canvas/ui/SelectorBar.svelte.d.ts +0 -12
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Reading the pictures that a saved board only points at, when the board is opened.
3
+ *
4
+ * A saved board does not hold the bytes of its pictures (an image, the screenshot of a widget card): it holds a reference, and
5
+ * the page's store (`ShapeImageStore`) turns the reference into the picture. The host used to ask the store for every
6
+ * reference at once and to keep the board shut until the last answer came, so a board of a thousand cards opened as slowly as
7
+ * its slowest picture, and the pictures that were on screen waited for the ones that were not. Now:
8
+ *
9
+ * - the pictures that are on screen are asked for first, the nearest to the middle of the view first, and the board opens as
10
+ * soon as those are in (`firstScreenful`);
11
+ * - the others are asked for after them, in the background, the nearest to the view first, and that order follows the view
12
+ * when it moves (a pan during the load puts the pictures of the place it went to in front); they are not asked for while a
13
+ * picture on screen is still on its way, so that those have the store and the network to themselves (for a few seconds at
14
+ * most: one that hangs must not hold the rest back);
15
+ * - only a few are asked for at a time (`PICTURE_LOAD_CONCURRENCY`), so that the pictures that matter do not share the store
16
+ * and the network with a thousand that do not;
17
+ * - what comes in is put on the board in small batches: not one by one, and not all at the end.
18
+ *
19
+ * Plain TypeScript over the engine's records, so that Node can test it.
20
+ */
21
+ import { rectsIntersect } from '../../engine/core/geometry.js';
22
+ import { shapeVisualBounds } from '../../engine/core/scene.js';
23
+ /** How many pictures are asked of the store at the same time. */
24
+ export const PICTURE_LOAD_CONCURRENCY = 6;
25
+ /** How long the pictures that came in are kept before they are put on the board together (so that a burst is one change, not forty). */
26
+ export const PICTURE_APPLY_DELAY_MS = 40;
27
+ /**
28
+ * How long the pictures that are not on screen wait for the ones that are, at most. They wait for them to come in, so that the
29
+ * store and the network are the on-screen pictures' alone; one that hangs must not hold back the rest of the board for ever.
30
+ */
31
+ export const PICTURE_BACKGROUND_GRACE_MS = 3000;
32
+ /** The objects of a scene that point at a picture and do not hold its bytes, in the order of the scene. */
33
+ export function picturesStillMissing(scene) {
34
+ const missing = [];
35
+ for (const object of scene) {
36
+ if (object.type === 'image' && !object.src && object.imageRef) {
37
+ missing.push({ objectId: object.id, reference: object.imageRef, bounds: shapeVisualBounds(object) });
38
+ }
39
+ else if (object.type === 'widget' && !object.thumbnail && object.thumbnailRef) {
40
+ missing.push({ objectId: object.id, reference: object.thumbnailRef, bounds: shapeVisualBounds(object) });
41
+ }
42
+ }
43
+ return missing;
44
+ }
45
+ /**
46
+ * A scene with the pictures that came in put into the objects that were waiting for exactly that picture. An object that holds a
47
+ * picture by now (the person put another one there), or points at another reference, or is gone, is left as it is. The very same
48
+ * scene when nothing changed.
49
+ */
50
+ export function fillPictures(scene, loaded) {
51
+ if (loaded.size === 0)
52
+ return scene;
53
+ let changed = false;
54
+ const filled = scene.map((object) => {
55
+ const picture = loaded.get(object.id);
56
+ if (!picture)
57
+ return object;
58
+ if (object.type === 'image' && !object.src && object.imageRef === picture.reference) {
59
+ changed = true;
60
+ return { ...object, src: picture.dataUrl };
61
+ }
62
+ if (object.type === 'widget' && !object.thumbnail && object.thumbnailRef === picture.reference) {
63
+ changed = true;
64
+ return { ...object, thumbnail: picture.dataUrl };
65
+ }
66
+ return object;
67
+ });
68
+ return changed ? filled : scene;
69
+ }
70
+ /**
71
+ * Waits for a promise for at most `milliseconds`. True when it finished in time, false when the time ran out first (the promise is
72
+ * not stopped: whatever it was doing goes on). A promise that fails counts as finished: the caller only wanted to know that it is over.
73
+ */
74
+ export async function waitUpTo(promise, milliseconds) {
75
+ let timeRanOut = () => undefined;
76
+ const timeUp = new Promise((resolve) => {
77
+ timeRanOut = () => resolve(false);
78
+ });
79
+ const timer = setTimeout(() => timeRanOut(), milliseconds);
80
+ try {
81
+ return await Promise.race([promise.then(() => true, () => true), timeUp]);
82
+ }
83
+ finally {
84
+ clearTimeout(timer);
85
+ }
86
+ }
87
+ /** A rectangle made of finite numbers with some size: anything else says the board has no size (or no view) yet. */
88
+ export function isUsableView(view) {
89
+ return !!view && Number.isFinite(view.x) && Number.isFinite(view.y) && Number.isFinite(view.width) && Number.isFinite(view.height) && view.width > 0 && view.height > 0;
90
+ }
91
+ /** How many of the pictures are of objects that touch the view. All of them when the view is not known: nothing is known to be far. */
92
+ export function countPicturesInView(missing, view) {
93
+ if (!isUsableView(view))
94
+ return missing.length;
95
+ let count = 0;
96
+ for (const picture of missing) {
97
+ if (rectsIntersect(view, picture.bounds))
98
+ count += 1;
99
+ }
100
+ return count;
101
+ }
102
+ /**
103
+ * The pictures still to be asked for, handing out the one to ask next: the ones of objects that touch the view first, the nearest
104
+ * to the middle of the view first among those and among the others. The order is made again when the view has moved by a quarter
105
+ * of itself or changed its size by a quarter (not at every pan frame, and not at every picture), and it is the scene's own order
106
+ * when the view is not known.
107
+ */
108
+ export class PictureQueue {
109
+ // Kept with the best one last, so that handing it out is a `pop`.
110
+ #waiting;
111
+ // Where each picture was in the scene: what breaks a tie, and what a picture that is given back keeps.
112
+ #positions = new Map();
113
+ #orderedFor = null;
114
+ constructor(missing) {
115
+ this.#waiting = missing.map((picture, position) => ({ picture, position })).reverse();
116
+ for (const { picture, position } of this.#waiting)
117
+ this.#positions.set(picture, position);
118
+ }
119
+ /** How many are still to be asked for. */
120
+ get length() {
121
+ return this.#waiting.length;
122
+ }
123
+ /** The picture to ask for next, or undefined when none is left. */
124
+ take(view) {
125
+ if (isUsableView(view) && this.#needsOrderingFor(view))
126
+ this.#orderFor(view);
127
+ return this.#waiting.pop()?.picture;
128
+ }
129
+ /** Puts back a picture that was taken and not asked for after all: it is the next one to be handed out (it was the best). */
130
+ giveBack(picture) {
131
+ this.#waiting.push({ picture, position: this.#positions.get(picture) ?? 0 });
132
+ }
133
+ #needsOrderingFor(view) {
134
+ const last = this.#orderedFor;
135
+ if (last === null)
136
+ return true;
137
+ return (Math.abs(view.x - last.x) > last.width * 0.25 ||
138
+ Math.abs(view.y - last.y) > last.height * 0.25 ||
139
+ view.width > last.width * 1.25 ||
140
+ view.width < last.width * 0.8);
141
+ }
142
+ #orderFor(view) {
143
+ this.#orderedFor = view;
144
+ const middleX = view.x + view.width / 2;
145
+ const middleY = view.y + view.height / 2;
146
+ // Squared distances stay far below this, so adding it puts every picture that is off the view after every one that is on it.
147
+ const OFF_THE_VIEW = 1e18;
148
+ const ranked = this.#waiting.map((entry) => {
149
+ const bounds = entry.picture.bounds;
150
+ const offsetX = bounds.x + bounds.width / 2 - middleX;
151
+ const offsetY = bounds.y + bounds.height / 2 - middleY;
152
+ return { entry, rank: (rectsIntersect(view, bounds) ? 0 : OFF_THE_VIEW) + offsetX * offsetX + offsetY * offsetY };
153
+ });
154
+ // The worst first and, among equals, the one that was later in the scene first: the last one is the best, and the earliest of equals.
155
+ ranked.sort((first, second) => second.rank - first.rank || second.entry.position - first.entry.position);
156
+ this.#waiting = ranked.map((item) => item.entry);
157
+ }
158
+ }
159
+ /**
160
+ * Asks the store for the missing pictures, a few at a time and in the order of `PictureQueue`, and puts what comes in on the board
161
+ * in small batches. Never throws: a picture the store cannot give is a warning, and the others go on.
162
+ */
163
+ export function startLoadingPictures(plan) {
164
+ const concurrency = Math.max(1, plan.concurrency ?? PICTURE_LOAD_CONCURRENCY);
165
+ const applyDelayMs = plan.applyDelayMs ?? PICTURE_APPLY_DELAY_MS;
166
+ const backgroundGraceMs = plan.backgroundGraceMs ?? PICTURE_BACKGROUND_GRACE_MS;
167
+ const queue = new PictureQueue(plan.missing);
168
+ const arrived = new Map();
169
+ const requests = new Map();
170
+ const failedReferences = new Set();
171
+ let applyTimer = null;
172
+ let boardOpened = false;
173
+ let finishFirstScreenful = () => undefined;
174
+ const firstScreenful = new Promise((resolve) => {
175
+ finishFirstScreenful = resolve;
176
+ });
177
+ // The pictures of objects that are on screen and are being asked for right now, and the workers that hold back a picture of an
178
+ // object that is not on screen until those are answered (or until `letBackgroundStart`).
179
+ let onScreenInFlight = 0;
180
+ let backgroundMayStart = false;
181
+ let workersHeldBack = [];
182
+ let graceTimer = null;
183
+ function letBackgroundStart() {
184
+ backgroundMayStart = true;
185
+ const held = workersHeldBack;
186
+ workersHeldBack = [];
187
+ for (const release of held)
188
+ release();
189
+ }
190
+ function putArrivedOnTheBoard() {
191
+ if (applyTimer !== null) {
192
+ clearTimeout(applyTimer);
193
+ applyTimer = null;
194
+ }
195
+ if (arrived.size === 0)
196
+ return;
197
+ const batch = new Map(arrived);
198
+ arrived.clear();
199
+ if (plan.isCancelled())
200
+ return;
201
+ try {
202
+ plan.apply(batch);
203
+ }
204
+ catch (error) {
205
+ plan.warn('Canvas: pictures that came in could not be put on the board', error);
206
+ }
207
+ }
208
+ /** The pictures of the objects that are on screen are all in: what they gave is on the board, the board opens, the rest is asked for. */
209
+ function openTheBoard() {
210
+ if (boardOpened)
211
+ return;
212
+ boardOpened = true;
213
+ putArrivedOnTheBoard();
214
+ finishFirstScreenful();
215
+ letBackgroundStart();
216
+ }
217
+ async function work() {
218
+ for (;;) {
219
+ if (plan.isCancelled())
220
+ return;
221
+ const view = plan.currentView();
222
+ const picture = queue.take(view);
223
+ if (!picture)
224
+ return;
225
+ const onScreen = !isUsableView(view) || rectsIntersect(view, picture.bounds);
226
+ if (!onScreen) {
227
+ // The queue hands out the pictures of objects that are on screen first, so this one coming up means none of them is left to
228
+ // be asked for. When none is on its way either, they are all in: the board opens. Otherwise the ones on their way have the
229
+ // store and the network to themselves until they are answered (or the grace is over: one that hangs must not hold the rest
230
+ // of the board back for ever).
231
+ if (onScreenInFlight === 0) {
232
+ openTheBoard();
233
+ }
234
+ else if (!backgroundMayStart) {
235
+ queue.giveBack(picture);
236
+ graceTimer ??= setTimeout(letBackgroundStart, backgroundGraceMs);
237
+ await new Promise((resolve) => workersHeldBack.push(resolve));
238
+ continue;
239
+ }
240
+ }
241
+ else {
242
+ onScreenInFlight += 1;
243
+ }
244
+ try {
245
+ // One question per reference: a picture that several objects point at is read once and given to each of them.
246
+ let request = requests.get(picture.reference);
247
+ if (!request) {
248
+ request = plan.store.load(picture.reference, { priority: onScreen ? 'visible' : 'background' });
249
+ requests.set(picture.reference, request);
250
+ }
251
+ const dataUrl = await request;
252
+ if (dataUrl) {
253
+ arrived.set(picture.objectId, { reference: picture.reference, dataUrl });
254
+ if (applyTimer === null)
255
+ applyTimer = setTimeout(putArrivedOnTheBoard, applyDelayMs);
256
+ }
257
+ }
258
+ catch (error) {
259
+ // Said once for a reference, not once for each object that points at it.
260
+ if (!failedReferences.has(picture.reference)) {
261
+ failedReferences.add(picture.reference);
262
+ plan.warn('Canvas: a stored picture could not be read', picture.reference, error);
263
+ }
264
+ }
265
+ finally {
266
+ if (onScreen) {
267
+ onScreenInFlight -= 1;
268
+ // Workers are held back only by a picture that is not on screen, so there is none on screen left to be asked for.
269
+ if (onScreenInFlight === 0 && workersHeldBack.length > 0)
270
+ openTheBoard();
271
+ }
272
+ }
273
+ }
274
+ }
275
+ const workerCount = Math.min(concurrency, plan.missing.length);
276
+ const everything = Promise.all(Array.from({ length: workerCount }, () => work()))
277
+ // Nothing above throws, but a board that is opened must never be left waiting for a promise that fails.
278
+ .catch((error) => plan.warn('Canvas: reading the stored pictures stopped early', error))
279
+ .then(() => {
280
+ if (graceTimer !== null)
281
+ clearTimeout(graceTimer);
282
+ // What is still waiting for its batch goes on the board now, and nothing is left to wait for: everything is answered (or the
283
+ // board was replaced, or there was nothing to read).
284
+ putArrivedOnTheBoard();
285
+ openTheBoard();
286
+ });
287
+ return { firstScreenful, everything };
288
+ }
@@ -10,53 +10,6 @@
10
10
  *
11
11
  * The functions are plain TypeScript over the engine's records, so they run (and are tested) in Node.
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
13
  import { brushCentreline, isBrushStroke } from '../../engine/core/brush.js';
61
14
  import { outlineBounds } from '../../engine/core/hitTest.js';
62
15
  import { parsePathData } from '../../engine/core/pathData.js';
@@ -70,8 +23,7 @@ import { CANVAS_SHAPE_SNAP_ENABLED, CANVAS_SNAP_SHAPE_LABELS, confidentSnapShape
70
23
  * (`CANVAS_SHAPE_SNAP_ENABLED`, false as shipped) turns it on for every page when it is flipped, which is the one
71
24
  * line to roll the behaviour out or back. The flag is a parameter so a test can hold both of its values.
72
25
  */
73
- export function isShapeSnapOn(pageAsked, packageFlag) {
74
- if (packageFlag === void 0) { packageFlag = CANVAS_SHAPE_SNAP_ENABLED; }
26
+ export function isShapeSnapOn(pageAsked, packageFlag = CANVAS_SHAPE_SNAP_ENABLED) {
75
27
  return packageFlag === true || pageAsked === true;
76
28
  }
77
29
  /**
@@ -82,71 +34,67 @@ export function isShapeSnapOn(pageAsked, packageFlag) {
82
34
  */
83
35
  export function strokeMeasurementPoints(stroke, handLine) {
84
36
  if (handLine && handLine.length >= 2)
85
- return handLine.map(function (point) { return ({ x: point.x - stroke.x, y: point.y - stroke.y }); });
37
+ return handLine.map((point) => ({ x: point.x - stroke.x, y: point.y - stroke.y }));
86
38
  if (isBrushStroke(stroke))
87
39
  return brushCentreline(stroke);
88
40
  return flattenPathCommands(parsePathData(stroke.d));
89
41
  }
90
42
  /** What the geometry says about a stroke: its measurements, or null when it is too small or too plain to measure. */
91
43
  export function measureDrawnStroke(stroke, handLine) {
92
- var points = strokeMeasurementPoints(stroke, handLine);
44
+ const points = strokeMeasurementPoints(stroke, handLine);
93
45
  if (points.length < 2)
94
46
  return null;
95
- var measurements = measureStroke(points);
47
+ const measurements = measureStroke(points);
96
48
  if (!measurements)
97
49
  return null;
98
- return { points: points, measurements: measurements };
50
+ return { points, measurements };
99
51
  }
100
52
  /**
101
53
  * Decides whether a stroke is a clean shape. Resolves to null for "leave it as drawn".
102
54
  * Deliberately never rejects.
103
55
  */
104
- export function decideStrokeSnap(stroke, context, handLine) {
105
- return __awaiter(this, void 0, Promise, function () {
106
- var measured, points, measurements, rankings, candidates, decisive, strokeImage, answer, named_1, error_1;
107
- var _a, _b, _c, _d, _e, _f;
108
- return __generator(this, function (_g) {
109
- switch (_g.label) {
110
- case 0:
111
- _g.trys.push([0, 2, , 3]);
112
- measured = measureDrawnStroke(stroke, handLine);
113
- if (!measured)
114
- return [2 /*return*/, null];
115
- points = measured.points, measurements = measured.measurements;
116
- rankings = rankSnapShapes(measurements);
117
- if (rankings.length === 0)
118
- return [2 /*return*/, null];
119
- candidates = rankings.map(function (ranking) { return (__assign(__assign({}, ranking), { label: CANVAS_SNAP_SHAPE_LABELS[ranking.shape] })); });
120
- decisive = confidentSnapShape(rankings);
121
- if (decisive)
122
- return [2 /*return*/, { shape: decisive.shape, source: 'geometry', axisTilt: measurements.axisTilt }];
123
- if (!context.recognize) {
124
- (_a = context.log) === null || _a === void 0 ? void 0 : _a.call(context, 'Shape snap: ambiguous and no recognizer configured, leaving the stroke as drawn', {
125
- candidates: candidates.map(function (candidate) { return candidate.shape; })
126
- });
127
- return [2 /*return*/, null];
128
- }
129
- strokeImage = renderStrokeSnapImage(points);
130
- return [4 /*yield*/, context.recognize(__assign({ measurements: measurements, candidates: candidates, best: (_b = candidates[0]) !== null && _b !== void 0 ? _b : null }, (strokeImage ? { image: strokeImage } : {})))];
131
- case 1:
132
- answer = _g.sent();
133
- named_1 = (_c = answer === null || answer === void 0 ? void 0 : answer.shape) !== null && _c !== void 0 ? _c : null;
134
- if (!named_1 || !candidates.some(function (candidate) { return candidate.shape === named_1; })) {
135
- (_d = context.log) === null || _d === void 0 ? void 0 : _d.call(context, 'Shape snap: the recognizer declined or named a shape the geometry ruled out', {
136
- shape: named_1,
137
- reason: (_e = answer === null || answer === void 0 ? void 0 : answer.reason) !== null && _e !== void 0 ? _e : 'no_answer'
138
- });
139
- return [2 /*return*/, null];
140
- }
141
- return [2 /*return*/, { shape: named_1, source: 'recognizer', axisTilt: measurements.axisTilt }];
142
- case 2:
143
- error_1 = _g.sent();
144
- (_f = context.log) === null || _f === void 0 ? void 0 : _f.call(context, 'Shape snap: failed, leaving the stroke as drawn', error_1);
145
- return [2 /*return*/, null];
146
- case 3: return [2 /*return*/];
147
- }
56
+ export async function decideStrokeSnap(stroke, context, handLine) {
57
+ try {
58
+ const measured = measureDrawnStroke(stroke, handLine);
59
+ if (!measured)
60
+ return null;
61
+ const { points, measurements } = measured;
62
+ // Only shapes the measurements cannot rule out are ever considered, and the same list is the only roster
63
+ // the host may choose from.
64
+ const rankings = rankSnapShapes(measurements);
65
+ if (rankings.length === 0)
66
+ return null;
67
+ const candidates = rankings.map((ranking) => ({ ...ranking, label: CANVAS_SNAP_SHAPE_LABELS[ranking.shape] }));
68
+ const decisive = confidentSnapShape(rankings);
69
+ if (decisive)
70
+ return { shape: decisive.shape, source: 'geometry', axisTilt: measurements.axisTilt };
71
+ if (!context.recognize) {
72
+ context.log?.('Shape snap: ambiguous and no recognizer configured, leaving the stroke as drawn', {
73
+ candidates: candidates.map((candidate) => candidate.shape)
74
+ });
75
+ return null;
76
+ }
77
+ const strokeImage = renderStrokeSnapImage(points);
78
+ const answer = await context.recognize({
79
+ measurements,
80
+ candidates,
81
+ best: candidates[0] ?? null,
82
+ ...(strokeImage ? { image: strokeImage } : {})
148
83
  });
149
- });
84
+ const named = answer?.shape ?? null;
85
+ if (!named || !candidates.some((candidate) => candidate.shape === named)) {
86
+ context.log?.('Shape snap: the recognizer declined or named a shape the geometry ruled out', {
87
+ shape: named,
88
+ reason: answer?.reason ?? 'no_answer'
89
+ });
90
+ return null;
91
+ }
92
+ return { shape: named, source: 'recognizer', axisTilt: measurements.axisTilt };
93
+ }
94
+ catch (error) {
95
+ context.log?.('Shape snap: failed, leaving the stroke as drawn', error);
96
+ return null;
97
+ }
150
98
  }
151
99
  /**
152
100
  * The clean shape for a stroke: the same place and size (where the hand went, when it is known, else the box of the
@@ -154,67 +102,64 @@ export function decideStrokeSnap(stroke, context, handLine) {
154
102
  * The circle and the two library shapes stay square. Null when the shape cannot be built.
155
103
  */
156
104
  export function buildSnappedShape(stroke, shape, services, handLine) {
157
- var _a;
158
- var box = (_a = (handLine && handLine.length >= 2 ? outlineBounds(handLine) : null)) !== null && _a !== void 0 ? _a : shapeBounds(stroke);
159
- var placement = planSnapPlacement(shape, { left: box.x, top: box.y, width: box.width, height: box.height });
160
- var area = placement.bounds;
161
- var start = { x: area.left, y: area.top };
162
- var end = { x: area.left + area.width, y: area.top + area.height };
163
- var id = services.createId('obj');
164
- var replacement = null;
105
+ const box = (handLine && handLine.length >= 2 ? outlineBounds(handLine) : null) ?? shapeBounds(stroke);
106
+ const placement = planSnapPlacement(shape, { left: box.x, top: box.y, width: box.width, height: box.height });
107
+ const area = placement.bounds;
108
+ const start = { x: area.left, y: area.top };
109
+ const end = { x: area.left + area.width, y: area.top + area.height };
110
+ const id = services.createId('obj');
111
+ let replacement = null;
165
112
  if (shape === 'diamond' || shape === 'hexagon') {
166
- replacement = buildLibraryShape({ id: id, x: area.left, y: area.top, width: area.width, height: area.height, key: shape });
113
+ replacement = buildLibraryShape({ id, x: area.left, y: area.top, width: area.width, height: area.height, key: shape });
167
114
  }
168
115
  else {
169
- var kind = shape === 'oval' ? 'ellipse' : shape;
116
+ const kind = shape === 'oval' ? 'ellipse' : shape;
170
117
  replacement = buildDraggedShape({
171
- kind: kind,
172
- start: start,
173
- end: end,
118
+ kind,
119
+ start,
120
+ end,
174
121
  constrain: false,
175
122
  dragged: true,
176
123
  wireframe: true,
177
- createId: function () { return id; },
124
+ createId: () => id,
178
125
  random: services.random
179
126
  });
180
127
  }
181
128
  if (!replacement)
182
129
  return null;
183
- return __assign(__assign({}, replacement), { parentId: stroke.parentId, opacity: stroke.opacity, fill: 'transparent', fillOpacity: 0,
130
+ return {
131
+ ...replacement,
132
+ parentId: stroke.parentId,
133
+ opacity: stroke.opacity,
134
+ fill: 'transparent',
135
+ fillOpacity: 0,
184
136
  // A brush stroke keeps its colour in the fill of its outline: the clean shape draws it as a line.
185
- stroke: lineColorOf(stroke), strokeWidth: stroke.strokeWidth, strokeStyle: stroke.strokeStyle });
137
+ stroke: lineColorOf(stroke),
138
+ strokeWidth: stroke.strokeWidth,
139
+ strokeStyle: stroke.strokeStyle
140
+ };
186
141
  }
187
142
  /**
188
143
  * Decides and, when the answer is a shape, replaces the stroke on the board in one undo step. Resolves to the
189
144
  * decision that was applied, or null when the stroke stays.
190
145
  */
191
- export function snapDrawnStroke(engine, stroke, context, handLine) {
192
- return __awaiter(this, void 0, Promise, function () {
193
- var decision, replacement;
194
- var _a, _b;
195
- return __generator(this, function (_c) {
196
- switch (_c.label) {
197
- case 0: return [4 /*yield*/, decideStrokeSnap(stroke, context, handLine)];
198
- case 1:
199
- decision = _c.sent();
200
- if (!decision)
201
- return [2 /*return*/, null];
202
- // While the host was thinking the person may have moved, restyled or erased the stroke: then it is theirs.
203
- if (engine.getObject(stroke.id) !== stroke)
204
- return [2 /*return*/, null];
205
- replacement = buildSnappedShape(stroke, decision.shape, engine.services, handLine);
206
- if (!replacement)
207
- return [2 /*return*/, null];
208
- try {
209
- engine.applyScene(replaceObject(engine.state.scene, stroke.id, replacement), 'push');
210
- }
211
- catch (error) {
212
- (_a = context.log) === null || _a === void 0 ? void 0 : _a.call(context, 'Shape snap: could not put the clean shape on the board', error);
213
- return [2 /*return*/, null];
214
- }
215
- (_b = context.log) === null || _b === void 0 ? void 0 : _b.call(context, 'Shape snap: stroke replaced with the clean shape', __assign(__assign({}, decision), { id: replacement.id }));
216
- return [2 /*return*/, decision];
217
- }
218
- });
219
- });
146
+ export async function snapDrawnStroke(engine, stroke, context, handLine) {
147
+ const decision = await decideStrokeSnap(stroke, context, handLine);
148
+ if (!decision)
149
+ return null;
150
+ // While the host was thinking the person may have moved, restyled or erased the stroke: then it is theirs.
151
+ if (engine.getObject(stroke.id) !== stroke)
152
+ return null;
153
+ const replacement = buildSnappedShape(stroke, decision.shape, engine.services, handLine);
154
+ if (!replacement)
155
+ return null;
156
+ try {
157
+ engine.applyScene(replaceObject(engine.state.scene, stroke.id, replacement), 'push');
158
+ }
159
+ catch (error) {
160
+ context.log?.('Shape snap: could not put the clean shape on the board', error);
161
+ return null;
162
+ }
163
+ context.log?.('Shape snap: stroke replaced with the clean shape', { ...decision, id: replacement.id });
164
+ return decision;
220
165
  }
@@ -15,5 +15,5 @@ export type { PanZoomPosition } from './panZoomPosition';
15
15
  export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
16
16
  export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
17
17
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
18
- export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
18
+ export { setShapeImageStore, getShapeImageStore, SHAPE_IMAGE_STORE_OBJECT_URLS } from './shapes/shapeImageStore';
19
19
  export type { ShapeImageStore } from './shapes/shapeImageStore';
@@ -13,4 +13,4 @@ export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './toolbarPosition';
13
13
  export { PAN_ZOOM_POSITIONS, DEFAULT_PAN_ZOOM_POSITION } from './panZoomPosition';
14
14
  export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
15
15
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
16
- export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
16
+ export { setShapeImageStore, getShapeImageStore, SHAPE_IMAGE_STORE_OBJECT_URLS } from './shapes/shapeImageStore';
@@ -5,7 +5,7 @@
5
5
  * Nothing reads them but a person with the panel open, so a page that has no User Timing API (or a browser that refuses a
6
6
  * mark) loses nothing.
7
7
  */
8
- export var CANVAS_OPEN_MARKS = {
8
+ export const CANVAS_OPEN_MARKS = {
9
9
  /** The board is in place with the data the page gave it, a moment before `onReady` is called. */
10
10
  READY: 'canvas:ready',
11
11
  /** `loadCanvas` began reading a saved canvas. */
@@ -20,7 +20,7 @@ export function markCanvasOpenStep(stepName) {
20
20
  return;
21
21
  performance.mark(stepName);
22
22
  }
23
- catch (_a) {
23
+ catch {
24
24
  // Marks are diagnostics only.
25
25
  }
26
26
  }
@@ -1,25 +1,24 @@
1
1
  /**
2
2
  * Document-level outside press: deselect when the press is outside the canvas root and its portaled UI (item B18).
3
3
  */
4
- export var CANVAS_UI_ATTRIBUTE = 'data-canvas-ui';
4
+ export const CANVAS_UI_ATTRIBUTE = 'data-canvas-ui';
5
5
  export function isCanvasOwnedTarget(event, canvasRoot) {
6
6
  if (!canvasRoot)
7
7
  return false;
8
- var path = typeof event.composedPath === 'function' ? event.composedPath() : [];
8
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
9
9
  if (path.length > 0) {
10
- for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
11
- var node = path_1[_i];
10
+ for (const node of path) {
12
11
  if (!(node instanceof Node))
13
12
  continue;
14
13
  if (node === canvasRoot || canvasRoot.contains(node))
15
14
  return true;
16
- if (node instanceof Element && node.closest("[".concat(CANVAS_UI_ATTRIBUTE, "]")))
15
+ if (node instanceof Element && node.closest(`[${CANVAS_UI_ATTRIBUTE}]`))
17
16
  return true;
18
17
  }
19
18
  return false;
20
19
  }
21
- var target = event.target;
22
- if (target instanceof Node && (canvasRoot.contains(target) || (target instanceof Element && target.closest("[".concat(CANVAS_UI_ATTRIBUTE, "]"))))) {
20
+ const target = event.target;
21
+ if (target instanceof Node && (canvasRoot.contains(target) || (target instanceof Element && target.closest(`[${CANVAS_UI_ATTRIBUTE}]`)))) {
23
22
  return true;
24
23
  }
25
24
  return false;