@widgetic/canvas 0.5.42 → 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 (62) 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/chromeLayout.d.ts +14 -3
  5. package/dist/canvas/chromeLayout.js +14 -3
  6. package/dist/canvas/host/CanvasHost.d.ts +47 -5
  7. package/dist/canvas/host/CanvasHost.js +256 -91
  8. package/dist/canvas/host/nearCards.d.ts +33 -0
  9. package/dist/canvas/host/nearCards.js +78 -0
  10. package/dist/canvas/host/pageEvents.d.ts +16 -4
  11. package/dist/canvas/host/pageEvents.js +13 -4
  12. package/dist/canvas/host/pictureSaves.d.ts +33 -0
  13. package/dist/canvas/host/pictureSaves.js +42 -0
  14. package/dist/canvas/host/screenRects.d.ts +5 -0
  15. package/dist/canvas/host/storedPictures.d.ts +88 -0
  16. package/dist/canvas/host/storedPictures.js +288 -0
  17. package/dist/canvas/index.d.ts +1 -1
  18. package/dist/canvas/index.js +1 -1
  19. package/dist/canvas/shapes/shapeImageStore.d.ts +45 -2
  20. package/dist/canvas/shapes/shapeImageStore.js +7 -0
  21. package/dist/canvas/toolbarPosition.d.ts +2 -2
  22. package/dist/canvas/toolbarPosition.js +2 -2
  23. package/dist/canvas/ui/SelectionPanel.svelte +28 -5
  24. package/dist/canvas/ui/SelectionPanel.svelte.d.ts +7 -0
  25. package/dist/canvas/ui/SelectorIndicator.svelte +81 -0
  26. package/dist/canvas/ui/SelectorIndicator.svelte.d.ts +11 -0
  27. package/dist/canvas/ui/ToolButton.svelte +8 -2
  28. package/dist/canvas/ui/floatingCard.d.ts +2 -2
  29. package/dist/canvas/ui/floatingCard.js +2 -2
  30. package/dist/canvas/ui/floatingLayer.d.ts +13 -2
  31. package/dist/canvas/ui/floatingLayer.js +14 -2
  32. package/dist/canvas/view/CanvasStage.svelte +101 -67
  33. package/dist/canvas/view/LeftToRightScope.svelte +21 -0
  34. package/dist/canvas/view/LeftToRightScope.svelte.d.ts +7 -0
  35. package/dist/canvas/view/ObjectView.svelte +15 -10
  36. package/dist/canvas/view/ObjectView.svelte.d.ts +1 -1
  37. package/dist/canvas/view/liftedScene.d.ts +31 -0
  38. package/dist/canvas/view/liftedScene.js +146 -0
  39. package/dist/canvas/view/mountedScene.d.ts +71 -0
  40. package/dist/canvas/view/mountedScene.js +363 -0
  41. package/dist/engine/EngineCore.d.ts +15 -1
  42. package/dist/engine/EngineCore.js +30 -4
  43. package/dist/engine/codec/canvasDocument.d.ts +5 -0
  44. package/dist/engine/codec/canvasDocument.js +31 -4
  45. package/dist/engine/core/history.d.ts +6 -0
  46. package/dist/engine/core/history.js +16 -0
  47. package/dist/engine/core/scene.d.ts +10 -0
  48. package/dist/engine/core/scene.js +24 -0
  49. package/dist/engine/core/types.d.ts +8 -2
  50. package/dist/engine/input/gestures.js +4 -2
  51. package/dist/engine/state.d.ts +20 -0
  52. package/dist/engine/state.js +1 -0
  53. package/dist/fonts/interFont.d.ts +10 -1
  54. package/dist/fonts/interFont.js +36 -13
  55. package/dist/i18n/language.d.ts +3 -3
  56. package/dist/i18n/messages.d.ts +8 -1
  57. package/dist/i18n/messages.js +9 -1
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.js +1 -1
  60. package/package.json +1 -1
  61. package/dist/canvas/ui/SelectorBar.svelte +0 -84
  62. package/dist/canvas/ui/SelectorBar.svelte.d.ts +0 -12
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Which objects of the board have an element: the ones near what the person sees.
3
+ *
4
+ * Every object of the board used to be an element of the world layer, seen or not, and the work of the browser grew with
5
+ * the number of them (with 3000 objects, the page spent its time on elements that were far outside the screen). Now an
6
+ * object has an element only while it is close to the view; the rest is only a record in the engine's scene, which costs
7
+ * nothing to the browser. What the person does with those records does not need an element (the pointer is found by the
8
+ * engine's own hit test, a selection is drawn from the records), so a far object appears the moment it is near, and the
9
+ * person never meets one that is missing: the margin below is the room an object has to be made in.
10
+ *
11
+ * It is a store of its own, and not something `CanvasStage` derives from the engine's state, for the reason that
12
+ * `erasingMarks.ts` gives: the state is a new object at every frame of a pan, a zoom or a drag, and the board must only be
13
+ * told when the list of objects with an element is a different one.
14
+ *
15
+ * What it decides, in short:
16
+ *
17
+ * - A board of fewer objects than `CULLING_MINIMUM_OBJECTS` keeps an element for every one of them, as it always did: on a
18
+ * small board there is nothing to save, and nothing that could go wrong.
19
+ * - Above that, an object has an element when the rectangle it paints (its box turned, with its stroke, see
20
+ * `shapeVisualBounds`) touches the *near area*: the view, with half a view of room on every side.
21
+ * - An object that has its element already keeps it a while longer: until it is out of the *keep area*, which is the view with
22
+ * a whole view of room on every side. A pan that goes out and comes back (the hand of a person on a tablet does that all the
23
+ * time) must not have the browser build the same objects twice. The keep area is for a view that pans or zooms out. A view
24
+ * that zooms in has no use for what it left behind (the person looks at a few objects of a big board now, which is what this
25
+ * is all for), so it lets go at once of everything that is not near it.
26
+ * - The near area is not worked out again at every frame. It is kept while the view stays within `REFRESH_DISTANCE_RATIO`
27
+ * of a view of where it was when the area was made (and has not zoomed in by more than `ZOOM_IN_REFRESH_RATIO`), so
28
+ * most frames of a pan cost nothing but that check, and the objects are made in steps instead of one by one.
29
+ * - A text that is being typed in always has its element, wherever the person scrolls to: its field is the element.
30
+ * - When many objects are wanted at once (the board was just opened, the view jumped to the whole board, an undo brought
31
+ * back a thousand shapes) they are not all made in the same frame: the ones the person can see come first, the nearest
32
+ * to the middle of the view first among them, then the ones of the margin. How many a frame takes follows how the frames
33
+ * are going: it starts at `MOUNT_BATCH_SIZE`, shrinks by half when a frame came late (the last batch was too much for this
34
+ * device) and grows a little when frames come on time, so that a fast desktop is done in a few frames and a slow tablet
35
+ * keeps drawing at its pace. Objects that are out of the keep area lose their element at once, which is cheap.
36
+ * - The order of the list is the paint order of the scene, and a group, which draws nothing, is not in it.
37
+ *
38
+ * Plain TypeScript with no Svelte file in it, so that Node can test it.
39
+ */
40
+ import { writable } from 'svelte/store';
41
+ import { rectsIntersect } from '../../engine/core/geometry.js';
42
+ import { shapeVisualBounds } from '../../engine/core/scene.js';
43
+ import { isBoxedObject } from '../../engine/core/types.js';
44
+ import { visibleWorldRect } from '../../engine/core/viewport.js';
45
+ /** A board with fewer objects than this keeps an element for every one of them. */
46
+ export const CULLING_MINIMUM_OBJECTS = 150;
47
+ /** How far past the view an object is given an element, as a share of the view's width and height, on every side. */
48
+ export const NEAR_MARGIN_RATIO = 0.5;
49
+ /**
50
+ * How far past the view an object that has an element keeps it, in the same measure. More than `NEAR_MARGIN_RATIO`: an object
51
+ * is not made at the edge of the near area and taken away the moment the view has moved a little, which would have a pan that
52
+ * goes out and back build the same objects twice (a few hundred of them, when the whole board is in view). The most that can have
53
+ * an element is what is in this area, which is nine views. It is not used by a view that has just zoomed in, nor by the first
54
+ * area of a board (see `nearAreaAround`).
55
+ */
56
+ export const KEEP_MARGIN_RATIO = 1;
57
+ /**
58
+ * How far the view may go past where it was when the near area was made, as a share of the view, before the area is made again.
59
+ * What is left of the margin at that moment is the room that a quick pan has before it reaches an object without an element.
60
+ */
61
+ export const REFRESH_DISTANCE_RATIO = 0.15;
62
+ /** The area is made again once the view has zoomed in by this factor: the objects that are not near the view now lose their element at once. */
63
+ export const ZOOM_IN_REFRESH_RATIO = 1.5;
64
+ /** How many objects that had no element get one in the first frame, when many are wanted at once (what follows adapts, see below). */
65
+ export const MOUNT_BATCH_SIZE = 30;
66
+ /** The batch never gets smaller than this, so that a very slow device (or a frame that is slow for another reason, a zoom with a thousand objects in view) still gets somewhere... */
67
+ export const MIN_MOUNT_BATCH_SIZE = 16;
68
+ /** ...and never larger than this, however quick the frames are: one frame must stay a frame's work. */
69
+ export const MAX_MOUNT_BATCH_SIZE = 120;
70
+ /** What the batch grows by after a frame that came on time. */
71
+ export const MOUNT_BATCH_GROWTH = 8;
72
+ /** A frame that comes later than this after the one before it (a frame at 60 Hz is 16.7 ms) says the last batch was too much. */
73
+ export const SLOW_FRAME_MS = 24;
74
+ /** A frame that comes sooner than this after the one before it says the last batch left room. */
75
+ export const QUICK_FRAME_MS = 20;
76
+ /** Frames further apart than this were not being drawn (a hidden tab): they say nothing of how much a batch costs. */
77
+ export const PAUSED_FRAME_MS = 500;
78
+ /** The list before anything was handed over (and the list of an empty board): one shared list. */
79
+ export const NOTHING_MOUNTED = Object.freeze([]);
80
+ /**
81
+ * The rectangle an object paints, in the world: its box turned, with the stroke or the brush's overflow, never negative in size.
82
+ *
83
+ * It is not remembered for the record. A record is measured in about a tenth of a microsecond, and a `WeakMap` that is handed every
84
+ * new record of a drag (all of them, when the whole selection moves) costs ten times that at every frame: measured, a drag of the
85
+ * whole of a board of 1,000 objects spent most of this module's time on the map and not on the measuring.
86
+ */
87
+ function paintedBoundsOf(shape) {
88
+ const measured = shapeVisualBounds(shape);
89
+ if (measured.width >= 0 && measured.height >= 0)
90
+ return measured;
91
+ // A box that was written with a negative size is the same box from the other corner.
92
+ return {
93
+ x: measured.width < 0 ? measured.x + measured.width : measured.x,
94
+ y: measured.height < 0 ? measured.y + measured.height : measured.y,
95
+ width: Math.abs(measured.width),
96
+ height: Math.abs(measured.height)
97
+ };
98
+ }
99
+ /** A view with `ratio` of its width and height added on every side. */
100
+ function viewWithMargin(view, ratio) {
101
+ const marginX = view.width * ratio;
102
+ const marginY = view.height * ratio;
103
+ return { x: view.x - marginX, y: view.y - marginY, width: view.width + marginX * 2, height: view.height + marginY * 2 };
104
+ }
105
+ /**
106
+ * The near area around a view (`NEAR_MARGIN_RATIO` on every side), and the keep area that goes with it.
107
+ *
108
+ * The keep area is wider (`KEEP_MARGIN_RATIO`) only for a view that comes after another one (`previous`) and has not zoomed in by
109
+ * more than `ZOOM_IN_REFRESH_RATIO` since: it panned, or zoomed out, and what it made stays until it is far. A view that has
110
+ * zoomed in, or the first view of a board (nothing was made around a view before it, or everything was, which a board that has no
111
+ * size yet does), has the keep area of the near area: what is not near it loses its element at once.
112
+ */
113
+ function nearAreaAround(view, zoom, previous) {
114
+ const keepsWhatItHas = previous !== null && zoom <= previous.zoom * ZOOM_IN_REFRESH_RATIO;
115
+ return {
116
+ view,
117
+ zoom,
118
+ area: viewWithMargin(view, NEAR_MARGIN_RATIO),
119
+ keepArea: viewWithMargin(view, keepsWhatItHas ? KEEP_MARGIN_RATIO : NEAR_MARGIN_RATIO)
120
+ };
121
+ }
122
+ /** Whether the near area still serves a view: the view is where it was, give or take the slack, and has not zoomed in far. */
123
+ function isStillNear(near, view, zoom) {
124
+ if (zoom > near.zoom * ZOOM_IN_REFRESH_RATIO)
125
+ return false;
126
+ const slackX = near.view.width * REFRESH_DISTANCE_RATIO;
127
+ const slackY = near.view.height * REFRESH_DISTANCE_RATIO;
128
+ return (view.x >= near.view.x - slackX &&
129
+ view.y >= near.view.y - slackY &&
130
+ view.x + view.width <= near.view.x + near.view.width + slackX &&
131
+ view.y + view.height <= near.view.y + near.view.height + slackY);
132
+ }
133
+ /** A rectangle made of finite numbers, with some size: anything else says the board has no size (or no view) yet. */
134
+ function isUsableView(view) {
135
+ return Number.isFinite(view.x) && Number.isFinite(view.y) && Number.isFinite(view.width) && Number.isFinite(view.height) && view.width > 0 && view.height > 0;
136
+ }
137
+ /** Whether two lists hold the very same records in the same order (the very same list is the quick case). */
138
+ function sameRecords(first, second) {
139
+ if (first === second)
140
+ return true;
141
+ if (first.length !== second.length)
142
+ return false;
143
+ for (let position = 0; position < first.length; position += 1) {
144
+ if (first[position] !== second[position])
145
+ return false;
146
+ }
147
+ return true;
148
+ }
149
+ /** Whether two lists are of the very same objects (by id) in the same order, whatever their records are: a drag changes records and not objects. */
150
+ function sameObjects(first, second) {
151
+ if (first.length !== second.length)
152
+ return false;
153
+ for (let position = 0; position < first.length; position += 1) {
154
+ if (first[position].id !== second[position].id)
155
+ return false;
156
+ }
157
+ return true;
158
+ }
159
+ /**
160
+ * The ids of the `count` objects to make first: the ones that touch the view before the others, and the nearest to the middle of the
161
+ * view first in each of the two kinds.
162
+ */
163
+ function nearestIdsFirst(candidates, view, count) {
164
+ const middleX = view.x + view.width / 2;
165
+ const middleY = view.y + view.height / 2;
166
+ // Squared distances stay far below this, so adding it puts every object that is out of the view after every one that is in it.
167
+ const OUT_OF_VIEW = 1e18;
168
+ const ranked = candidates.map((object) => {
169
+ const bounds = paintedBoundsOf(object);
170
+ const offsetX = bounds.x + bounds.width / 2 - middleX;
171
+ const offsetY = bounds.y + bounds.height / 2 - middleY;
172
+ return { id: object.id, rank: (rectsIntersect(view, bounds) ? 0 : OUT_OF_VIEW) + offsetX * offsetX + offsetY * offsetY };
173
+ });
174
+ ranked.sort((first, second) => first.rank - second.rank);
175
+ return new Set(ranked.slice(0, count).map((entry) => entry.id));
176
+ }
177
+ /** The frame the page gives, or null where there is none (a server render). */
178
+ function pageFrameScheduler() {
179
+ if (typeof requestAnimationFrame !== 'function' || typeof cancelAnimationFrame !== 'function')
180
+ return null;
181
+ return (callback) => {
182
+ const handle = requestAnimationFrame((frameTime) => callback(frameTime));
183
+ return () => cancelAnimationFrame(handle);
184
+ };
185
+ }
186
+ export function createMountedScene(options = {}) {
187
+ const minimumObjects = options.minimumObjects ?? CULLING_MINIMUM_OBJECTS;
188
+ const scheduleFrame = options.scheduleFrame ?? pageFrameScheduler();
189
+ // A batch size that was given stays; otherwise it follows the frames (see `adaptBatchSizeTo`).
190
+ const batchSizeFollowsFrames = options.batchSize === undefined;
191
+ // With no frame to wait for, there is no later to leave the rest of the objects to.
192
+ let batchSize = scheduleFrame === null ? Infinity : Math.max(1, options.batchSize ?? MOUNT_BATCH_SIZE);
193
+ // The time of the frame in which the last batch was made: the next frame says how long that batch took to show.
194
+ let lastBatchFrameTime = null;
195
+ const { subscribe, set } = writable(NOTHING_MOUNTED);
196
+ /** The list the subscribers have. */
197
+ let published = NOTHING_MOUNTED;
198
+ // The ids of the published list, made when someone asks and kept for as long as the list is of the same objects (see `publish`).
199
+ let idsOfPublishedFor = null;
200
+ let idsOfPublished = new Set();
201
+ let near = null;
202
+ let latestInput = null;
203
+ let latestView = null;
204
+ // What the last work was made from: the same again is no news.
205
+ let workedScene = null;
206
+ let workedEditingTextId = null;
207
+ let workedNear = null;
208
+ let cancelFrame = null;
209
+ let destroyed = false;
210
+ // Once the work has failed, the board is drawn whole from then on (and the failure is said once).
211
+ let failed = false;
212
+ function idsOfPublishedList() {
213
+ if (idsOfPublishedFor !== published) {
214
+ idsOfPublished = new Set(published.map((object) => object.id));
215
+ idsOfPublishedFor = published;
216
+ }
217
+ return idsOfPublished;
218
+ }
219
+ function publish(next) {
220
+ // A store tells its subscribers of every `set` of an object, equal or not: the same records again is no news.
221
+ if (sameRecords(next, published))
222
+ return;
223
+ // A drag hands over other records for the same objects, at every frame: the ids that were gathered for the list that was
224
+ // published are the ids of this one too, and gathering them again (a set of every id) would cost a good part of the frame.
225
+ if (idsOfPublishedFor === published && sameObjects(next, published))
226
+ idsOfPublishedFor = next;
227
+ published = next;
228
+ set(next);
229
+ }
230
+ function stopWaitingForFrame() {
231
+ cancelFrame?.();
232
+ cancelFrame = null;
233
+ }
234
+ /**
235
+ * Learns from the frames how many objects a frame can take. The frame that comes after a batch is late when the batch was too
236
+ * much (the page could not draw it in time), so the next batch is half of it; frames on time let the batch grow by a few.
237
+ * A frame time that is not known, or a pause between frames (a hidden tab), teaches nothing.
238
+ */
239
+ function adaptBatchSizeTo(frameTime) {
240
+ if (!batchSizeFollowsFrames || batchSize === Infinity)
241
+ return;
242
+ if (typeof frameTime !== 'number' || !Number.isFinite(frameTime)) {
243
+ lastBatchFrameTime = null;
244
+ return;
245
+ }
246
+ const previous = lastBatchFrameTime;
247
+ lastBatchFrameTime = frameTime;
248
+ if (previous === null)
249
+ return;
250
+ const interval = frameTime - previous;
251
+ if (interval > PAUSED_FRAME_MS || interval < 0)
252
+ return;
253
+ if (interval > SLOW_FRAME_MS)
254
+ batchSize = Math.max(MIN_MOUNT_BATCH_SIZE, Math.floor(batchSize / 2));
255
+ else if (interval < QUICK_FRAME_MS)
256
+ batchSize = Math.min(MAX_MOUNT_BATCH_SIZE, batchSize + MOUNT_BATCH_GROWTH);
257
+ }
258
+ /** Every object has its element: the board is small, or nothing is known of the view, or the work failed. */
259
+ function publishWholeScene(scene) {
260
+ stopWaitingForFrame();
261
+ near = null;
262
+ workedScene = null;
263
+ workedNear = null;
264
+ publish(scene);
265
+ }
266
+ function giveUpCulling(error, scene) {
267
+ if (!failed) {
268
+ failed = true;
269
+ console.warn('Canvas: the board could not tell which objects are near the view, so every object is drawn', error);
270
+ }
271
+ publishWholeScene(scene);
272
+ }
273
+ /** Works out the list from the records and the near area, and makes what is wanted in the frames that follow when it is a lot. */
274
+ function mountNearObjects(input, nearArea, view) {
275
+ const { scene, editingTextId } = input;
276
+ // The objects that have an element now: the ones that keep it while they are inside the keep area.
277
+ const alreadyMade = idsOfPublishedList();
278
+ const wanted = [];
279
+ // How many of the wanted ones have no element yet: counted on the way, so that a pass in which nothing is missing (the frames of
280
+ // a drag) makes no list of them.
281
+ let missingCount = 0;
282
+ for (const object of scene) {
283
+ // A group draws nothing: its members are objects of their own.
284
+ if (!isBoxedObject(object))
285
+ continue;
286
+ const hasElementAlready = alreadyMade.has(object.id);
287
+ if (object.id !== editingTextId) {
288
+ const painted = paintedBoundsOf(object);
289
+ // An object is given an element inside the near area, and keeps it (it is not made again later) inside the keep area.
290
+ const keepsItsElement = hasElementAlready && rectsIntersect(nearArea.keepArea, painted);
291
+ if (!keepsItsElement && !rectsIntersect(nearArea.area, painted))
292
+ continue;
293
+ }
294
+ wanted.push(object);
295
+ if (!hasElementAlready)
296
+ missingCount += 1;
297
+ }
298
+ let next = wanted;
299
+ let moreToMake = false;
300
+ if (batchSize !== Infinity && missingCount > batchSize) {
301
+ const missing = wanted.filter((object) => !alreadyMade.has(object.id));
302
+ const makeNow = nearestIdsFirst(missing, view, batchSize);
303
+ next = wanted.filter((object) => alreadyMade.has(object.id) || makeNow.has(object.id));
304
+ moreToMake = true;
305
+ }
306
+ workedScene = scene;
307
+ workedEditingTextId = editingTextId;
308
+ workedNear = nearArea;
309
+ publish(next);
310
+ if (!moreToMake) {
311
+ stopWaitingForFrame();
312
+ // The next burst starts from a fresh reading of the frames.
313
+ lastBatchFrameTime = null;
314
+ return;
315
+ }
316
+ if (cancelFrame !== null || scheduleFrame === null)
317
+ return;
318
+ cancelFrame = scheduleFrame((frameTime) => {
319
+ cancelFrame = null;
320
+ if (destroyed || latestInput === null || near === null || latestView === null)
321
+ return;
322
+ adaptBatchSizeTo(frameTime);
323
+ try {
324
+ mountNearObjects(latestInput, near, latestView);
325
+ }
326
+ catch (error) {
327
+ giveUpCulling(error, latestInput.scene);
328
+ }
329
+ });
330
+ }
331
+ return {
332
+ subscribe,
333
+ take(input) {
334
+ if (destroyed)
335
+ return;
336
+ latestInput = input;
337
+ try {
338
+ if (failed || input.scene.length < minimumObjects) {
339
+ publishWholeScene(input.scene);
340
+ return;
341
+ }
342
+ const view = visibleWorldRect(input.viewport, input.viewSize);
343
+ if (!isUsableView(view) || !Number.isFinite(input.viewport.zoom) || input.viewport.zoom <= 0) {
344
+ publishWholeScene(input.scene);
345
+ return;
346
+ }
347
+ latestView = view;
348
+ if (near === null || !isStillNear(near, view, input.viewport.zoom))
349
+ near = nearAreaAround(view, input.viewport.zoom, near);
350
+ if (input.scene === workedScene && input.editingTextId === workedEditingTextId && near === workedNear)
351
+ return;
352
+ mountNearObjects(input, near, view);
353
+ }
354
+ catch (error) {
355
+ giveUpCulling(error, input.scene);
356
+ }
357
+ },
358
+ destroy() {
359
+ destroyed = true;
360
+ stopWaitingForFrame();
361
+ }
362
+ };
363
+ }
@@ -128,13 +128,27 @@ export declare class EngineCore {
128
128
  * of what was loaded (a name filled in), not an edit.
129
129
  */
130
130
  applySilently(next: Scene): void;
131
+ /**
132
+ * Fills in what was loaded late (a picture that arrived after the board was opened and used) in the board and in every step of
133
+ * its history, with no undo step and without telling the host that the board changed: a repair of what was loaded, not an edit.
134
+ * `repair` must give back the very same scene when it has nothing to change.
135
+ *
136
+ * Not `applySilently`, which is for what is done before the person can do anything: it makes the board the current step, and
137
+ * that is wrong twice over for a repair that comes in the middle of the person's work. A gesture that is under way has a scene
138
+ * of its own (the board is then not any step), and it would be written into the step the gesture started from, so that Escape
139
+ * could not take it back; and the steps before this one would still be without the picture, so an undo would take it away.
140
+ */
141
+ repairLoaded(repair: (scene: Scene) => Scene): void;
131
142
  /** Records the scene as it is now as one undo step (the end of a gesture). False when nothing changed since the last step. */
132
143
  commit(): boolean;
133
144
  /** Throws away what a gesture did and goes back to the last step (Escape in the middle of a drag). */
134
145
  revertToCommitted(): void;
135
146
  undo(): boolean;
136
147
  redo(): boolean;
137
- /** Adds objects on top of the board in one step. Returns their ids. */
148
+ /**
149
+ * Adds objects on top of the board in one step, except that a drawing goes under the widget cards (a card is added on top).
150
+ * Returns their ids.
151
+ */
138
152
  addObjects(objects: readonly SceneObject[], options?: {
139
153
  select?: boolean;
140
154
  }): ObjectId[];
@@ -17,7 +17,7 @@ import { reconcileArrowBindings } from './core/arrowBinding.js';
17
17
  import { createImageObject, createObjectId, createRectObject, createTextObject, createWidgetObject, TEXT_DEFAULTS } from './core/defaults.js';
18
18
  import { HistoryStack } from './core/history.js';
19
19
  import { hitTestPoint, hitTestRect, hitTestStack } from './core/hitTest.js';
20
- import { boardVisualBounds, boundsOfObjects, duplicateObjects, groupObjects, indexScene, leafShapesOf, normalizeScene, normalizeSelection, removeObjects as removeFromScene, reorderObjects, replaceObject, sameIds, translateObjects, ungroupObjects, withDescendantIds } from './core/scene.js';
20
+ import { addObjectsBehindWidgetCards, boardVisualBounds, boundsOfObjects, duplicateObjects, groupObjects, indexScene, leafShapesOf, normalizeScene, normalizeSelection, removeObjects as removeFromScene, reorderObjects, replaceObject, sameIds, translateObjects, ungroupObjects, withDescendantIds } from './core/scene.js';
21
21
  import { applyStylePatch } from './core/style.js';
22
22
  import { Scribble } from './core/scribble.js';
23
23
  import { selectionFrameOf } from './core/transform.js';
@@ -317,6 +317,28 @@ export class EngineCore {
317
317
  // What the board holds now (the arrows tied to shapes drawn again), not the scene that was asked for.
318
318
  this.#history.replaceCurrent(this.#state.scene);
319
319
  }
320
+ /**
321
+ * Fills in what was loaded late (a picture that arrived after the board was opened and used) in the board and in every step of
322
+ * its history, with no undo step and without telling the host that the board changed: a repair of what was loaded, not an edit.
323
+ * `repair` must give back the very same scene when it has nothing to change.
324
+ *
325
+ * Not `applySilently`, which is for what is done before the person can do anything: it makes the board the current step, and
326
+ * that is wrong twice over for a repair that comes in the middle of the person's work. A gesture that is under way has a scene
327
+ * of its own (the board is then not any step), and it would be written into the step the gesture started from, so that Escape
328
+ * could not take it back; and the steps before this one would still be without the picture, so an undo would take it away.
329
+ */
330
+ repairLoaded(repair) {
331
+ // At rest the board is the current step itself; during a gesture it is not.
332
+ const atRest = this.#history.current === this.#state.scene;
333
+ this.#history.mapAll(repair);
334
+ const next = atRest ? this.#history.current : repair(this.#state.scene);
335
+ if (next === this.#state.scene)
336
+ return;
337
+ this.applyScene(next, 'transient');
338
+ // What the board holds now (the arrows tied to shapes drawn again), so that the board stays the very same list as its step.
339
+ if (atRest)
340
+ this.#history.replaceCurrent(this.#state.scene);
341
+ }
320
342
  /** Records the scene as it is now as one undo step (the end of a gesture). False when nothing changed since the last step. */
321
343
  commit() {
322
344
  this.#nudgeMergeUntil = 0;
@@ -356,12 +378,15 @@ export class EngineCore {
356
378
  this.#set({ canUndo: this.#history.canUndo, canRedo: this.#history.canRedo, overlay: EMPTY_OVERLAY });
357
379
  this.hooks.onDirty?.();
358
380
  }
359
- /** Adds objects on top of the board in one step. Returns their ids. */
381
+ /**
382
+ * Adds objects on top of the board in one step, except that a drawing goes under the widget cards (a card is added on top).
383
+ * Returns their ids.
384
+ */
360
385
  addObjects(objects, options = {}) {
361
386
  if (objects.length === 0)
362
387
  return [];
363
388
  const fitted = objects.map((object) => this.#fitText(object));
364
- this.applyScene([...this.#state.scene, ...fitted], 'push');
389
+ this.applyScene(addObjectsBehindWidgetCards(this.#state.scene, fitted), 'push');
365
390
  const ids = fitted.map((object) => object.id);
366
391
  if (options.select)
367
392
  this.select(ids);
@@ -733,7 +758,8 @@ export class EngineCore {
733
758
  });
734
759
  const text = this.#fitText(base);
735
760
  const sceneBefore = this.#state.scene;
736
- this.applyScene([...sceneBefore, text], 'transient');
761
+ // A text typed after a widget stands goes behind it, like every other drawing.
762
+ this.applyScene(addObjectsBehindWidgetCards(sceneBefore, [text]), 'transient');
737
763
  this.#textSession = { id: text.id, isNew: true, sceneBefore, typed: false };
738
764
  this.#set({ editingTextId: text.id, selectedIds: [text.id], enteredGroupId: null });
739
765
  return text.id;
@@ -42,6 +42,11 @@ export interface SerializeOptions {
42
42
  now?: Date;
43
43
  /** When given, inline image bytes go here and only a reference is written. */
44
44
  imageStore?: ImageBytesSink | null;
45
+ /**
46
+ * Called for a picture whose bytes the store refused (its `save` threw): they stay in the text instead. The engine writes
47
+ * nothing to the console, so the host decides how to report it (once per save, not once per picture).
48
+ */
49
+ onImageStoreRefused?: (ref: string, error: unknown) => void;
45
50
  }
46
51
  /** The document for a board, as a plain object (the form `serializeCanvasDocument` writes). */
47
52
  export declare function createCanvasDocument(scene: readonly SceneObject[], viewport: Viewport, options?: SerializeOptions): CanvasDocument;
@@ -58,14 +58,41 @@ const KEYS_BY_TYPE = {
58
58
  widget: [...BOX_KEYS, 'widgetId', 'widgetName', 'isPrimary', 'thumbnail', 'thumbnailRef'],
59
59
  group: []
60
60
  };
61
+ /**
62
+ * Whether an address only lives as long as the page that made it (an object URL, `blob:`). A store may answer a reference with
63
+ * one instead of bytes, so that the picture is not a string megabytes long in the board and in every `<img>` that shows it.
64
+ */
65
+ function isPageLocalAddress(address) {
66
+ return address.startsWith('blob:');
67
+ }
61
68
  /** The reference and the (possibly inline) bytes of a picture, with the bytes moved to the store when there is one. */
62
- function externalizeBytes(inline, existingRef, makeRef, store) {
69
+ function externalizeBytes(inline, existingRef, makeRef, options) {
70
+ const store = options.imageStore;
71
+ // An object URL the store gave for a reference is not bytes, and it must never reach the text: the next page cannot read it, and
72
+ // a board that holds an address is not asked to read the picture again, so the card would stay blank. The picture is the
73
+ // store's already, under the reference it was given for: only the reference is written. With no store, or with no reference to
74
+ // say where the picture is, there is nothing to point at, and the address is left as it always was.
75
+ if (store && existingRef && inline && isPageLocalAddress(inline))
76
+ return { value: null, ref: existingRef };
63
77
  if (!store || !inline || !inline.startsWith('data:'))
64
78
  return { value: inline, ref: existingRef };
65
79
  const ref = existingRef ?? makeRef();
66
80
  if (!ref)
67
81
  return { value: inline, ref: existingRef };
68
- store.save(ref, inline);
82
+ try {
83
+ store.save(ref, inline);
84
+ }
85
+ catch (error) {
86
+ // A store that refuses (it has nowhere to keep the bytes yet) must not take the whole save down with it, and must not
87
+ // cost a picture: the bytes stay in the text, as if there were no store, and are offered again at the next save.
88
+ try {
89
+ options.onImageStoreRefused?.(ref, error);
90
+ }
91
+ catch {
92
+ // The report is a courtesy; a report that fails changes nothing about the save.
93
+ }
94
+ return { value: inline, ref: existingRef };
95
+ }
69
96
  return { value: null, ref };
70
97
  }
71
98
  /** A tie of an arrow's end as it is saved: the shape it holds to (`target`) and, for a point of the outline, where on the shape's box. */
@@ -79,11 +106,11 @@ function serializeObject(object, options) {
79
106
  const source = object;
80
107
  let overrides = {};
81
108
  if (object.type === 'widget') {
82
- const thumbnail = externalizeBytes(object.thumbnail, object.thumbnailRef, () => `widget:${object.widgetId}`, options.imageStore);
109
+ const thumbnail = externalizeBytes(object.thumbnail, object.thumbnailRef, () => `widget:${object.widgetId}`, options);
83
110
  overrides = { thumbnail: thumbnail.value, thumbnailRef: thumbnail.ref };
84
111
  }
85
112
  else if (object.type === 'image') {
86
- const image = externalizeBytes(object.src, object.imageRef, () => `shape:${object.id}`, options.imageStore);
113
+ const image = externalizeBytes(object.src, object.imageRef, () => `shape:${object.id}`, options);
87
114
  overrides = { src: image.value, imageRef: image.ref };
88
115
  }
89
116
  for (const key of KEYS_BY_TYPE[object.type]) {
@@ -34,6 +34,12 @@ export declare class HistoryStack<State> {
34
34
  redo(): State | null;
35
35
  /** Replaces the current step without adding one (for a change that must not be undone on its own). */
36
36
  replaceCurrent(state: State): void;
37
+ /**
38
+ * Rewrites every step, the past and the future of the cursor too, with no step added (a repair that all of them must have, as
39
+ * a picture that arrived late: going back to a step from before it came must not take it away). A step that the rewrite
40
+ * leaves as it is keeps its identity, and a state that is held by two steps is rewritten once.
41
+ */
42
+ mapAll(rewrite: (state: State) => State): void;
37
43
  /** Forgets everything and starts again from this state (a canvas was loaded). */
38
44
  reset(state: State): void;
39
45
  }
@@ -61,6 +61,22 @@ export class HistoryStack {
61
61
  replaceCurrent(state) {
62
62
  this.entries[this.cursor] = state;
63
63
  }
64
+ /**
65
+ * Rewrites every step, the past and the future of the cursor too, with no step added (a repair that all of them must have, as
66
+ * a picture that arrived late: going back to a step from before it came must not take it away). A step that the rewrite
67
+ * leaves as it is keeps its identity, and a state that is held by two steps is rewritten once.
68
+ */
69
+ mapAll(rewrite) {
70
+ const rewritten = new Map();
71
+ this.entries = this.entries.map((entry) => {
72
+ let result = rewritten.get(entry);
73
+ if (result === undefined) {
74
+ result = rewrite(entry);
75
+ rewritten.set(entry, result);
76
+ }
77
+ return result;
78
+ });
79
+ }
64
80
  /** Forgets everything and starts again from this state (a canvas was loaded). */
65
81
  reset(state) {
66
82
  this.entries = [state];
@@ -49,6 +49,16 @@ export declare function flattenSceneTree(roots: readonly SceneNode[]): SceneObje
49
49
  /** Repairs a list of records into a valid scene: unique ids, groups before their members, no empty groups. */
50
50
  export declare function normalizeScene(scene: Scene): SceneObject[];
51
51
  export declare function addObjects(scene: Scene, objects: readonly SceneObject[]): SceneObject[];
52
+ /**
53
+ * Where something the person draws goes: on top of everything, except that it stays under the widget cards. The page lays
54
+ * the live widget over its card, so whatever is drawn after a widget stands has to go behind it, as the card does, and
55
+ * never hide it (and the sketch the widget was built from is not taken for the widget's content).
56
+ *
57
+ * The new objects go under the lowest card, or under the group that holds it. A card, and an object that is a member of
58
+ * a group already, keep the place the caller gave them (the end of the list), so adding a card, or a copy of a group,
59
+ * works as it always did. With no card on the board this is `addObjects`.
60
+ */
61
+ export declare function addObjectsBehindWidgetCards(scene: Scene, objects: readonly SceneObject[]): SceneObject[];
52
62
  /** Removes the objects and everything below them, then any group left with no members. */
53
63
  export declare function removeObjects(scene: Scene, ids: Iterable<ObjectId>): Scene;
54
64
  /** Changes one object. Returns the same scene when the object is missing or the patch changes nothing. */
@@ -238,6 +238,30 @@ function findSiblingList(roots, id) {
238
238
  export function addObjects(scene, objects) {
239
239
  return objects.length === 0 ? [...scene] : [...scene, ...objects];
240
240
  }
241
+ /**
242
+ * Where something the person draws goes: on top of everything, except that it stays under the widget cards. The page lays
243
+ * the live widget over its card, so whatever is drawn after a widget stands has to go behind it, as the card does, and
244
+ * never hide it (and the sketch the widget was built from is not taken for the widget's content).
245
+ *
246
+ * The new objects go under the lowest card, or under the group that holds it. A card, and an object that is a member of
247
+ * a group already, keep the place the caller gave them (the end of the list), so adding a card, or a copy of a group,
248
+ * works as it always did. With no card on the board this is `addObjects`.
249
+ */
250
+ export function addObjectsBehindWidgetCards(scene, objects) {
251
+ if (objects.length === 0)
252
+ return [...scene];
253
+ if (objects.some((object) => object.type === 'widget' || object.parentId !== null))
254
+ return [...scene, ...objects];
255
+ const lowestCard = scene.find((object) => object.type === 'widget');
256
+ if (!lowestCard)
257
+ return [...scene, ...objects];
258
+ // A group comes before its members in the list: the objects go before the group that holds the card, not between its members.
259
+ const unitId = topLevelAncestorId(indexScene(scene), lowestCard.id);
260
+ const at = scene.findIndex((object) => object.id === unitId);
261
+ if (at < 0)
262
+ return [...scene, ...objects];
263
+ return [...scene.slice(0, at), ...objects, ...scene.slice(at)];
264
+ }
241
265
  /** Removes the objects and everything below them, then any group left with no members. */
242
266
  export function removeObjects(scene, ids) {
243
267
  const doomed = withDescendantIds(scene, ids);
@@ -196,7 +196,10 @@ export interface TextObject extends ObjectBase, BoxProps {
196
196
  }
197
197
  export interface ImageObject extends ObjectBase, BoxProps {
198
198
  type: 'image';
199
- /** A `data:` or `http(s)` address, or null while the image is only a placeholder. */
199
+ /**
200
+ * A `data:` or `http(s)` address, or an object URL (`blob:`) the host's image store gave for `imageRef`, or null while the
201
+ * image is only a placeholder. An object URL is never written into the saved text: its `imageRef` is.
202
+ */
200
203
  src: string | null;
201
204
  /** The reference under which the host's image store keeps the bytes, when they are not inline. */
202
205
  imageRef: string | null;
@@ -215,7 +218,10 @@ export interface WidgetObject extends ObjectBase, BoxProps {
215
218
  widgetName: string | null;
216
219
  /** The widget the board is about (the host draws a mark around it in the advanced mode). */
217
220
  isPrimary: boolean;
218
- /** The last screenshot of the widget: inline bytes or an address. */
221
+ /**
222
+ * The last screenshot of the widget: inline bytes or an address (an object URL, `blob:`, is one the store gave for
223
+ * `thumbnailRef`: it is never written into the saved text, and `getWidgetShapeDataUrl` answers `null` for it).
224
+ */
219
225
  thumbnail: string | null;
220
226
  /** The reference under which the host's image store keeps the screenshot. */
221
227
  thumbnailRef: string | null;
@@ -122,8 +122,10 @@ export function createMoveGesture(context, start, unitIds, options = {}) {
122
122
  }
123
123
  carried ??= movingShapeIds(startScene, [...moving]);
124
124
  engine.applyScene(translateShapes(startScene, carried, deltaX, deltaY), 'transient');
125
- // The handles step aside while the selection is carried: what is carried is all that is to be seen.
126
- engine.setOverlay({ guides, dragging: 'move' });
125
+ // The handles step aside while the selection is carried: what is carried is all that is to be seen. The board is also told
126
+ // what is carried, from which records and how far (`CarriedShapes`), so that it can draw a big selection as one layer and
127
+ // not as a new record for every shape at every step; the records written above are the same, and the engine reads only them.
128
+ engine.setOverlay({ guides, dragging: 'move', carry: { startRecords: engine.sceneIndex(startScene), shapeIds: carried, deltaX, deltaY } });
127
129
  };
128
130
  return {
129
131
  kind: 'move',