@widgetic/canvas 0.5.42 → 0.5.44

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 (69) hide show
  1. package/README.md +1 -0
  2. package/dist/canvas/DomCanvas.svelte +53 -20
  3. package/dist/canvas/DomCanvas.svelte.d.ts +19 -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 +66 -6
  7. package/dist/canvas/host/CanvasHost.js +316 -91
  8. package/dist/canvas/host/CanvasHostApi.d.ts +2 -2
  9. package/dist/canvas/host/CanvasHostApi.js +5 -1
  10. package/dist/canvas/host/nearCards.d.ts +33 -0
  11. package/dist/canvas/host/nearCards.js +78 -0
  12. package/dist/canvas/host/pageEvents.d.ts +16 -4
  13. package/dist/canvas/host/pageEvents.js +13 -4
  14. package/dist/canvas/host/pictureSaves.d.ts +33 -0
  15. package/dist/canvas/host/pictureSaves.js +42 -0
  16. package/dist/canvas/host/screenRects.d.ts +5 -0
  17. package/dist/canvas/host/storedPictures.d.ts +88 -0
  18. package/dist/canvas/host/storedPictures.js +288 -0
  19. package/dist/canvas/index.d.ts +2 -1
  20. package/dist/canvas/index.js +1 -1
  21. package/dist/canvas/shapes/shapeImageStore.d.ts +45 -2
  22. package/dist/canvas/shapes/shapeImageStore.js +7 -0
  23. package/dist/canvas/toolbarPosition.d.ts +2 -2
  24. package/dist/canvas/toolbarPosition.js +2 -2
  25. package/dist/canvas/types.d.ts +17 -0
  26. package/dist/canvas/ui/ColorField.svelte +7 -2
  27. package/dist/canvas/ui/SelectionPanel.svelte +56 -31
  28. package/dist/canvas/ui/SelectionPanel.svelte.d.ts +7 -0
  29. package/dist/canvas/ui/SelectorIndicator.svelte +81 -0
  30. package/dist/canvas/ui/SelectorIndicator.svelte.d.ts +11 -0
  31. package/dist/canvas/ui/ToolButton.svelte +11 -3
  32. package/dist/canvas/ui/floatingCard.d.ts +2 -2
  33. package/dist/canvas/ui/floatingCard.js +2 -2
  34. package/dist/canvas/ui/floatingLayer.d.ts +13 -2
  35. package/dist/canvas/ui/floatingLayer.js +14 -2
  36. package/dist/canvas/view/CanvasStage.svelte +101 -67
  37. package/dist/canvas/view/LeftToRightScope.svelte +21 -0
  38. package/dist/canvas/view/LeftToRightScope.svelte.d.ts +7 -0
  39. package/dist/canvas/view/ObjectView.svelte +15 -10
  40. package/dist/canvas/view/ObjectView.svelte.d.ts +1 -1
  41. package/dist/canvas/view/liftedScene.d.ts +31 -0
  42. package/dist/canvas/view/liftedScene.js +146 -0
  43. package/dist/canvas/view/mountedScene.d.ts +71 -0
  44. package/dist/canvas/view/mountedScene.js +363 -0
  45. package/dist/engine/EngineCore.d.ts +89 -1
  46. package/dist/engine/EngineCore.js +158 -4
  47. package/dist/engine/codec/canvasDocument.d.ts +5 -0
  48. package/dist/engine/codec/canvasDocument.js +31 -4
  49. package/dist/engine/core/cameraMove.d.ts +67 -0
  50. package/dist/engine/core/cameraMove.js +154 -0
  51. package/dist/engine/core/history.d.ts +6 -0
  52. package/dist/engine/core/history.js +16 -0
  53. package/dist/engine/core/scene.d.ts +10 -0
  54. package/dist/engine/core/scene.js +24 -0
  55. package/dist/engine/core/types.d.ts +8 -2
  56. package/dist/engine/input/PointerController.js +12 -0
  57. package/dist/engine/input/gestures.js +4 -2
  58. package/dist/engine/state.d.ts +20 -0
  59. package/dist/engine/state.js +1 -0
  60. package/dist/fonts/interFont.d.ts +10 -1
  61. package/dist/fonts/interFont.js +36 -13
  62. package/dist/i18n/language.d.ts +3 -3
  63. package/dist/i18n/messages.d.ts +8 -1
  64. package/dist/i18n/messages.js +9 -1
  65. package/dist/index.d.ts +2 -2
  66. package/dist/index.js +1 -1
  67. package/package.json +1 -1
  68. package/dist/canvas/ui/SelectorBar.svelte +0 -84
  69. package/dist/canvas/ui/SelectorBar.svelte.d.ts +0 -12
@@ -28,12 +28,16 @@ import { flushWorkspaceToolSettingsPending, loadWorkspaceToolSettings, saveWorks
28
28
  import { canvasLog, canvasWarn, setCanvasLogsEnabled } from '../canvasLogger.js';
29
29
  import { CANVAS_OPEN_MARKS, markCanvasOpenStep } from '../openMarks.js';
30
30
  import { eventIsForScope, getEventOrigin, shouldTakeFocusBack } from '../eventScope.js';
31
- import { getShapeImageStore } from '../shapes/shapeImageStore.js';
31
+ import { getShapeImageStore, shapeImageRef } from '../shapes/shapeImageStore.js';
32
32
  import { chooseImageFiles, createBrowserMeasureText, createBrowserRasterServices, readImageFile } from './browserServices.js';
33
33
  import { buildCapturePayload } from './conversion.js';
34
- import { announceSelectTool, announceWidgetPointerBlock } from './pageEvents.js';
34
+ import { announceCanvasTool, announceSelectTool, announceWidgetPointerBlock } from './pageEvents.js';
35
35
  import { hostObjectById, selectedHostObject } from './hostObject.js';
36
36
  import { screenRectOfBounds, widgetPreviewGeometry } from './screenRects.js';
37
+ import { NEAR_CARDS_MINIMUM, createNearCards } from './nearCards.js';
38
+ import { createPictureSaveMemory } from './pictureSaves.js';
39
+ // `countPicturesInView` is only used by the log of `#resolveStoredImages` that is commented out.
40
+ import { /* countPicturesInView, */ fillPictures, picturesStillMissing, startLoadingPictures, waitUpTo } from './storedPictures.js';
37
41
  import { isShapeSnapOn, snapDrawnStroke } from './strokeSnap.js';
38
42
  import { createCanvasToolHostFromEngine, executeCanvasTool, summarizeScene } from '../../tools/index.js';
39
43
  import { isCanvasToolName } from '../../tools/definitions.js';
@@ -50,6 +54,7 @@ export const DEFAULT_HOST_PROPS = Object.freeze({
50
54
  showDrawingTools: true,
51
55
  elementSelectorActive: false,
52
56
  onToggleElementSelector: null,
57
+ onDismissElementSelectorHint: null,
53
58
  selectorGuide: null,
54
59
  showZoomPanel: true,
55
60
  mediaBtsOnBar: true,
@@ -82,7 +87,8 @@ export const DEFAULT_HOST_PROPS = Object.freeze({
82
87
  keepCenterOnResize: false,
83
88
  workspaceId: null,
84
89
  userId: null,
85
- workspaceFonts: Object.freeze([])
90
+ workspaceFonts: Object.freeze([]),
91
+ interFontSources: Object.freeze([])
86
92
  });
87
93
  /** A store the way Svelte reads one (`$store` and `fromStore` both work on it). */
88
94
  class ValueStore {
@@ -137,6 +143,12 @@ export const TOUCH_LONG_PRESS_DELAY_MS = 500;
137
143
  export const TOUCH_LONG_PRESS_SLOP = 8;
138
144
  /** How long after the finger that opened the menu lifts its release is still told apart from a choice (see `isMenuHeldByItsFinger`). */
139
145
  export const TOUCH_MENU_RELEASE_GRACE_MS = 400;
146
+ /**
147
+ * How long the host waits for the pictures it was told to wait for (the ones on screen when a board is opened, or all of them
148
+ * when a capture needs them) before it goes on without them. A page whose store never answers must not keep the board shut for
149
+ * good; the pictures that come later still go on the board.
150
+ */
151
+ export const PICTURE_PATIENCE_MS = 15000;
140
152
  /** A picture's size on the board: its own size, or the biggest one that fits `IMAGE_INSERT_MAX_SIDE`. */
141
153
  export function fitImageSize(naturalWidth, naturalHeight) {
142
154
  const width = Math.max(1, naturalWidth || IMAGE_INSERT_MAX_SIDE);
@@ -153,6 +165,8 @@ const isEditableTarget = (element) => {
153
165
  const tag = element.tagName;
154
166
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || element.isContentEditable === true;
155
167
  };
168
+ /** Whether two lists hold the same entries in the same order (a page may pass a new array with the same content each time). */
169
+ const hasSameEntries = (first, second) => first.length === second.length && first.every((entry, index) => entry === second[index]);
156
170
  /** Elements that read the arrow keys (and Home, End, Page Up and Down) themselves: a slider, a tab list, a list box. */
157
171
  const ARROW_KEY_ROLES = new Set([
158
172
  'slider',
@@ -211,6 +225,12 @@ export class CanvasHost {
211
225
  #removeListeners = [];
212
226
  #destroyed = false;
213
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();
214
234
  /** A finger that is resting on the board and may become a long press. */
215
235
  #longPress = null;
216
236
  /** The last press was a finger's: a `contextmenu` that follows it is the browser's own long-press menu. */
@@ -219,6 +239,11 @@ export class CanvasHost {
219
239
  #menuFinger = null;
220
240
  #lastOverlayState = null;
221
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;
222
247
  /** The widget whose card is being stretched, as the page was told (null: the page was told nothing, or that it ended). */
223
248
  #resizingWidgetId = null;
224
249
  /** The lines of every text, kept for as long as the text object is the same record and the fonts are the same. */
@@ -238,6 +263,10 @@ export class CanvasHost {
238
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). */
239
264
  #scribbleFrame = null;
240
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;
241
270
  constructor(initialProps = {}) {
242
271
  this.props = { ...DEFAULT_HOST_PROPS, ...initialProps };
243
272
  this.engine = new EngineCore({ measureText: this.#measureText });
@@ -302,6 +331,13 @@ export class CanvasHost {
302
331
  this.props.workspaceFonts !== previous.workspaceFonts) {
303
332
  void this.#syncWorkspaceContext();
304
333
  }
334
+ // A page that passes its Inter files late (or another list) is read by what is in the list, not by the array it came in.
335
+ if (!hasSameEntries(this.props.interFontSources, previous.interFontSources)) {
336
+ void ensureInterFontLoaded(this.props.interFontSources).then(() => {
337
+ if (!this.#destroyed)
338
+ this.engine.notifyFontsChanged();
339
+ });
340
+ }
305
341
  }
306
342
  #compactStylePatch(fields) {
307
343
  const compact = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
@@ -349,7 +385,7 @@ export class CanvasHost {
349
385
  saveWorkspaceToolSettingsDebounced({ workspaceId, userId: this.props.userId }, { text: textPatch, paint: paintPatch });
350
386
  }
351
387
  async #syncWorkspaceContext() {
352
- await ensureInterFontLoaded();
388
+ await ensureInterFontLoaded(this.props.interFontSources);
353
389
  const fonts = this.props.workspaceFonts ?? [];
354
390
  setWorkspaceFontFamilies(fonts.map((font) => font.family));
355
391
  await registerWorkspaceFonts(fonts);
@@ -484,7 +520,7 @@ export class CanvasHost {
484
520
  if (typeof document !== 'undefined' && document.fonts && typeof document.fonts.addEventListener === 'function') {
485
521
  this.#listen(document.fonts, 'loadingdone', () => this.engine.notifyFontsChanged());
486
522
  }
487
- void ensureInterFontLoaded().then(() => {
523
+ void ensureInterFontLoaded(this.props.interFontSources).then(() => {
488
524
  this.engine.notifyFontsChanged();
489
525
  void this.#syncWorkspaceContext();
490
526
  });
@@ -510,6 +546,9 @@ export class CanvasHost {
510
546
  return;
511
547
  // The first tool: the pencil, when the page shows the drawing tools (a board opens ready for a sketch), else Select.
512
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);
513
552
  this.#updateUi({ loadPhase: 'ready' });
514
553
  this.#queueAfterRender();
515
554
  markCanvasOpenStep(CANVAS_OPEN_MARKS.READY);
@@ -859,7 +898,8 @@ export class CanvasHost {
859
898
  tools: this.tools,
860
899
  typingInField: isEditableTarget(origin),
861
900
  hasTextSelection,
862
- selectorHintOpen: this.props.showElementSelector && this.props.elementSelectorActive
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
863
903
  };
864
904
  }
865
905
  #onKeyDown(event) {
@@ -1004,6 +1044,17 @@ export class CanvasHost {
1004
1044
  const view = hostObjectById(this.engine, clone.id);
1005
1045
  this.#safely(() => notify(sourceWidgetId, view), 'onWidgetShapeDuplicated');
1006
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
+ }
1007
1058
  #handleActivate(id) {
1008
1059
  const object = this.engine.getObject(id);
1009
1060
  if (!object || object.type !== 'widget')
@@ -1014,6 +1065,7 @@ export class CanvasHost {
1014
1065
  }
1015
1066
  /** After every change of the engine: the page's overlays are told to move, once a frame, when something they follow moved. */
1016
1067
  #onEngineState(state) {
1068
+ this.#announceToolIfChanged(state.tool);
1017
1069
  // The eraser's trail lives on the frame clock: it starts with the trail and stops when the trail is gone.
1018
1070
  if (state.scribble !== null)
1019
1071
  this.#startScribbleClock();
@@ -1031,17 +1083,12 @@ export class CanvasHost {
1031
1083
  last.hoverWidgetId !== state.hoverWidgetId ||
1032
1084
  last.selectedIds !== state.selectedIds ||
1033
1085
  last.overlayDragActive !== state.overlayDragActive) {
1034
- if (last && last.selectedIds !== state.selectedIds) {
1035
- if (state.selectedIds.length === 0) {
1036
- // Leave dismissal as the user left it.
1037
- }
1038
- else {
1039
- const selected = state.selectedIds
1040
- .map((id) => state.scene.find((object) => object.id === id))
1041
- .filter((object) => object !== undefined);
1042
- const widgetOnly = selected.length === 1 && selected[0].type === 'widget';
1043
- this.#updateUi({ selectionPanelDismissed: widgetOnly });
1044
- }
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 });
1045
1092
  }
1046
1093
  this.#lastOverlayState = {
1047
1094
  scene: state.scene,
@@ -1073,7 +1120,7 @@ export class CanvasHost {
1073
1120
  try {
1074
1121
  if (shouldTakeFocusBack(this.#board)) {
1075
1122
  this.focusBoard();
1076
- canvasLog('Canvas: the board took the keyboard back after a text was typed');
1123
+ // canvasLog('Canvas: the board took the keyboard back after a text was typed');
1077
1124
  }
1078
1125
  }
1079
1126
  catch (error) {
@@ -1147,7 +1194,7 @@ export class CanvasHost {
1147
1194
  const json = this.#serializeCanvasText();
1148
1195
  if (json === null) {
1149
1196
  // The board has nothing to give right now (it is loading): ask the buffer for another go a delay later.
1150
- canvasLog('Canvas: autosave: the board cannot be serialized yet, trying again after the delay');
1197
+ // canvasLog('Canvas: autosave: the board cannot be serialized yet, trying again after the delay');
1151
1198
  this.#scheduler.markChanged();
1152
1199
  return undefined;
1153
1200
  }
@@ -1155,7 +1202,7 @@ export class CanvasHost {
1155
1202
  this.#updateUi({ saveState: 'saved' });
1156
1203
  return undefined;
1157
1204
  }
1158
- canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
1205
+ // canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
1159
1206
  this.#updateUi({ saveState: 'saving' });
1160
1207
  let outcome;
1161
1208
  try {
@@ -1214,30 +1261,48 @@ export class CanvasHost {
1214
1261
  else {
1215
1262
  finish();
1216
1263
  }
1217
- canvasLog('Canvas: manual save triggered');
1264
+ // canvasLog('Canvas: manual save triggered');
1218
1265
  }
1219
1266
  /** Serializes the board without writing to the console (autosave compares payloads here first). */
1220
1267
  #serializeCanvasText() {
1221
1268
  if (this.#destroyed)
1222
1269
  return null;
1223
1270
  if (this.#loadDepth > 0 || this.engine.state.loading) {
1224
- canvasLog('Canvas: saveCanvas skipped (the board is loading)');
1271
+ // canvasLog('Canvas: saveCanvas skipped (the board is loading)');
1225
1272
  return null;
1226
1273
  }
1274
+ let refusedPictures = 0;
1275
+ let firstRefusal = null;
1276
+ let completed = false;
1227
1277
  try {
1228
- return this.engine.serialize({ imageStore: getShapeImageStore() });
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;
1229
1291
  }
1230
1292
  catch (error) {
1231
1293
  console.error('Canvas: saveCanvas failed', error);
1232
1294
  return null;
1233
1295
  }
1296
+ finally {
1297
+ this.#pictureSaves.finishSave(completed);
1298
+ }
1234
1299
  }
1235
1300
  /** The board as the text the page keeps. Null while the board is loading. */
1236
1301
  saveCanvas() {
1237
1302
  const text = this.#serializeCanvasText();
1238
- if (text !== null) {
1239
- canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
1240
- }
1303
+ // if (text !== null) {
1304
+ // canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
1305
+ // }
1241
1306
  return text;
1242
1307
  }
1243
1308
  /**
@@ -1249,6 +1314,9 @@ export class CanvasHost {
1249
1314
  return;
1250
1315
  markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_START);
1251
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;
1252
1320
  this.#loadDepth += 1;
1253
1321
  this.engine.setLoading(true);
1254
1322
  this.#updateUi({ loadPhase: 'loading' });
@@ -1264,7 +1332,7 @@ export class CanvasHost {
1264
1332
  else if (parsed.warnings.length > 0) {
1265
1333
  canvasWarn('Canvas: some objects of the saved canvas could not be read', parsed.warnings);
1266
1334
  }
1267
- await this.#resolveStoredImages();
1335
+ await this.#resolveStoredImages(generation);
1268
1336
  }
1269
1337
  catch (error) {
1270
1338
  console.error('Canvas: loadCanvas failed', error);
@@ -1278,49 +1346,69 @@ export class CanvasHost {
1278
1346
  markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_END);
1279
1347
  }
1280
1348
  }
1281
- /** Pictures the saved board only points at (by reference) are read from the page's store and put in without a history step. */
1282
- async #resolveStoredImages() {
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) {
1283
1357
  const store = getShapeImageStore();
1284
1358
  if (!store)
1285
1359
  return;
1286
- const scene = this.engine.state.scene;
1287
- const missing = scene.filter((object) => (object.type === 'image' && !object.src && !!object.imageRef) || (object.type === 'widget' && !object.thumbnail && !!object.thumbnailRef));
1360
+ const missing = picturesStillMissing(this.engine.state.scene);
1288
1361
  if (missing.length === 0)
1289
1362
  return;
1290
- const found = new Map();
1291
- await Promise.all(missing.map(async (object) => {
1292
- const reference = object.type === 'image' ? object.imageRef : object.type === 'widget' ? object.thumbnailRef : null;
1293
- if (!reference)
1294
- return;
1295
- try {
1296
- const dataUrl = await store.load(reference);
1297
- if (dataUrl)
1298
- found.set(object.id, dataUrl);
1299
- }
1300
- catch (error) {
1301
- canvasWarn('Canvas: a stored picture could not be read', reference, error);
1302
- }
1303
- }));
1304
- if (found.size === 0 || this.#destroyed)
1305
- return;
1306
- // What was loaded since is left alone: only the objects that are still the ones that were missing a picture are filled in.
1307
- const next = this.engine.state.scene.map((object) => {
1308
- const dataUrl = found.get(object.id);
1309
- if (!dataUrl)
1310
- return object;
1311
- if (object.type === 'image' && !object.src)
1312
- return { ...object, src: dataUrl };
1313
- if (object.type === 'widget' && !object.thumbnail)
1314
- return { ...object, thumbnail: dataUrl };
1315
- return object;
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;
1316
1375
  });
1317
- this.engine.applySilently(next);
1376
+ this.#picturesInBackground = inBackground;
1377
+ if (await waitUpTo(load.firstScreenful, PICTURE_PATIENCE_MS)) {
1378
+ // canvasLog('Canvas: the pictures on screen are in, the board opens; the others go on in the background');
1379
+ }
1380
+ else {
1381
+ canvasWarn('Canvas: the pictures on screen are slow to arrive, so the board opens without waiting for them');
1382
+ }
1383
+ }
1384
+ /**
1385
+ * Puts pictures that came in on the board, with no history step, and in every step of the history too (a picture that came
1386
+ * after the person had begun to work must not be taken away again by an undo). What the board holds now is left alone: only
1387
+ * an object that is still waiting for exactly that picture is filled in.
1388
+ */
1389
+ #putPicturesOnTheBoard(loaded) {
1390
+ if (this.#destroyed)
1391
+ return;
1392
+ this.engine.repairLoaded((scene) => fillPictures(scene, loaded));
1393
+ }
1394
+ /**
1395
+ * Resolves when every picture of the board has been asked for and put on it (at once when none is on its way): what draws the
1396
+ * whole board, a capture for instance, waits for it. It gives up after `PICTURE_PATIENCE_MS`, so a store that never answers cannot
1397
+ * hold anything for good; what was missing is then left out, as a picture the store could not give.
1398
+ */
1399
+ async whenPicturesLoaded() {
1400
+ const inBackground = this.#picturesInBackground;
1401
+ if (!inBackground)
1402
+ return;
1403
+ if (!(await waitUpTo(inBackground, PICTURE_PATIENCE_MS))) {
1404
+ canvasWarn('Canvas: some pictures are slow to arrive, so what needed them goes on without them');
1405
+ }
1318
1406
  }
1319
1407
  /** Empties the board (an undo step) and tells the page. */
1320
1408
  onClearAllObjects() {
1321
1409
  this.#scheduler.cancel();
1322
1410
  this.engine.clearAll();
1323
- canvasLog('Clear all objects created');
1411
+ // canvasLog('Clear all objects created');
1324
1412
  }
1325
1413
  // ────────────────────────────────────────────────────── tools
1326
1414
  setTool(tool, options = {}) {
@@ -1351,7 +1439,10 @@ export class CanvasHost {
1351
1439
  return this.onSelectImageTool();
1352
1440
  }
1353
1441
  }
1354
- /** The Select tool: the creator closes the element selector of its widgets when it hears of it. */
1442
+ /**
1443
+ * The Select tool. The page hears `widgetic:canvas-tool` for it (the creator's element selector is on while this tool is
1444
+ * chosen), and the older `widgetic:canvas-select-tool`, which a page that was written before the selector followed the tool still reads.
1445
+ */
1355
1446
  onSelectSelectTool() {
1356
1447
  this.engine.setTool('select');
1357
1448
  announceSelectTool();
@@ -1387,11 +1478,11 @@ export class CanvasHost {
1387
1478
  }
1388
1479
  /** There are no frames on this board: kept so a page that still calls it keeps working. */
1389
1480
  onSelectFrameTool() {
1390
- canvasLog('Canvas: the frame tool is gone, nothing was done');
1481
+ // canvasLog('Canvas: the frame tool is gone, nothing was done');
1391
1482
  }
1392
1483
  /** There is no video on this board: kept so a page that still calls it keeps working. */
1393
1484
  onSelectVideoTool() {
1394
- canvasLog('Canvas: the video tool is gone, nothing was done');
1485
+ // canvasLog('Canvas: the video tool is gone, nothing was done');
1395
1486
  }
1396
1487
  // ────────────────────────────────────────────────────── view
1397
1488
  zoomIn() {
@@ -1411,6 +1502,66 @@ export class CanvasHost {
1411
1502
  zoomFit() {
1412
1503
  this.engine.zoomToFit();
1413
1504
  }
1505
+ /**
1506
+ * Eases the view to some objects (objects of the board, groups included; ids that are not on the board are left out): the
1507
+ * position and the zoom move together and arrive together, with the middle of the objects in the middle of the board. The
1508
+ * objects fill the board unless `zoomPercent` or `keepZoom` says otherwise. False when none of the ids is on the board.
1509
+ * A press on the board, a scroll or a pinch takes the view back at once.
1510
+ */
1511
+ flyToObjects(objectIds, options = {}) {
1512
+ try {
1513
+ if (!Array.isArray(objectIds)) {
1514
+ canvasWarn('Canvas: flyToObjects needs a list of object ids; the view was not moved', objectIds);
1515
+ return false;
1516
+ }
1517
+ const idsOnBoard = objectIds.filter((objectId) => typeof objectId === 'string' && !!this.engine.getObject(objectId));
1518
+ if (idsOnBoard.length === 0) {
1519
+ canvasLog('Canvas: flyToObjects found none of the objects on the board; the view was not moved', objectIds);
1520
+ return false;
1521
+ }
1522
+ const { zoomPercent, keepZoom, ...moveOptions } = options;
1523
+ // 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 });
1526
+ }
1527
+ catch (error) {
1528
+ canvasWarn('Canvas: flyToObjects failed', error);
1529
+ return false;
1530
+ }
1531
+ }
1532
+ /**
1533
+ * 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
+ * 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
+ * view is there already.
1536
+ */
1537
+ flyToPoint(point, options = {}) {
1538
+ try {
1539
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
1540
+ canvasWarn('Canvas: flyToPoint needs a point with an x and a y that are numbers; the view was not moved', point);
1541
+ return false;
1542
+ }
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);
1546
+ }
1547
+ catch (error) {
1548
+ canvasWarn('Canvas: flyToPoint failed', error);
1549
+ return false;
1550
+ }
1551
+ }
1552
+ /**
1553
+ * 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
+ * the empty board does. Position and zoom move together. An empty board goes back to where a new board starts.
1555
+ */
1556
+ flyToContent(options = {}) {
1557
+ try {
1558
+ return this.engine.flyToContent(options);
1559
+ }
1560
+ catch (error) {
1561
+ canvasWarn('Canvas: flyToContent failed', error);
1562
+ return false;
1563
+ }
1564
+ }
1414
1565
  // ────────────────────────────────────────────────────── selection and arrangement
1415
1566
  deselectAll() {
1416
1567
  this.engine.clearSelection();
@@ -1463,8 +1614,8 @@ export class CanvasHost {
1463
1614
  return;
1464
1615
  }
1465
1616
  }
1466
- catch (error) {
1467
- canvasLog('Canvas: the system clipboard could not be read, nothing was pasted', error);
1617
+ catch {
1618
+ // canvasLog('Canvas: the system clipboard could not be read, nothing was pasted', error); // (needs `catch (error)` to be turned back on)
1468
1619
  }
1469
1620
  }
1470
1621
  /** A colour for a new shape: a random hue, so that shapes drawn in a row can be told apart. */
@@ -1520,7 +1671,7 @@ export class CanvasHost {
1520
1671
  }
1521
1672
  /** There are no frames on this board: kept so a page that still calls it keeps working. */
1522
1673
  addFrame() {
1523
- canvasLog('Canvas: frames are gone, nothing was added');
1674
+ // canvasLog('Canvas: frames are gone, nothing was added');
1524
1675
  return null;
1525
1676
  }
1526
1677
  /** Opens the file chooser and puts the pictures that are chosen on the board. */
@@ -1556,13 +1707,17 @@ export class CanvasHost {
1556
1707
  const size = fitImageSize(picture.width, picture.height);
1557
1708
  // Several pictures are laid out in a cascade, so each one can still be seen.
1558
1709
  const shift = position * 24;
1710
+ const id = this.engine.services.createId('img');
1711
+ // 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);
1559
1713
  return createImageObject({
1560
- id: this.engine.services.createId('img'),
1714
+ id,
1561
1715
  x: center.x - size.width / 2 + shift,
1562
1716
  y: center.y - size.height / 2 + shift,
1563
1717
  width: size.width,
1564
1718
  height: size.height,
1565
- src: picture.src,
1719
+ src: adopted.src,
1720
+ imageRef: adopted.imageRef,
1566
1721
  fileName: picture.fileName || null,
1567
1722
  naturalWidth: picture.width,
1568
1723
  naturalHeight: picture.height
@@ -1570,12 +1725,38 @@ export class CanvasHost {
1570
1725
  });
1571
1726
  this.engine.setTool('select');
1572
1727
  const ids = this.engine.addObjects(objects, { select: true });
1573
- canvasLog('Canvas: pictures put on the board', ids.length);
1728
+ // canvasLog('Canvas: pictures put on the board', ids.length);
1574
1729
  return ids;
1575
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
+ }
1576
1755
  // ────────────────────────────────────────────────────── capture and conversion
1577
1756
  /** A PNG of everything on the board, cropped to it; an empty string for an empty board. */
1578
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();
1579
1760
  const shapes = this.engine.state.scene.filter((object) => object.type !== 'group');
1580
1761
  if (shapes.length === 0)
1581
1762
  return '';
@@ -1597,6 +1778,8 @@ export class CanvasHost {
1597
1778
  if (!notify)
1598
1779
  return;
1599
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();
1600
1783
  const payload = await buildCapturePayload({
1601
1784
  engine: this.engine,
1602
1785
  raster: this.#raster,
@@ -1637,7 +1820,7 @@ export class CanvasHost {
1637
1820
  linkFrameToWidget(objectId, widgetId) {
1638
1821
  const object = this.engine.getObject(objectId);
1639
1822
  if (!object || object.type !== 'widget') {
1640
- canvasLog('Canvas: linkFrameToWidget found no card', { objectId, widgetId });
1823
+ // canvasLog('Canvas: linkFrameToWidget found no card', { objectId, widgetId });
1641
1824
  return;
1642
1825
  }
1643
1826
  this.engine.linkObjectToWidget(objectId, widgetId);
@@ -1676,27 +1859,69 @@ export class CanvasHost {
1676
1859
  getHoveredWidgetShapeId() {
1677
1860
  return this.engine.state.hoverWidgetId;
1678
1861
  }
1679
- /** The cards a live widget can be drawn over, with where each is on the page. */
1680
- listWidgetShapeScreenRects() {
1862
+ /**
1863
+ * The cards a live widget can be drawn over, with where each is on the page.
1864
+ *
1865
+ * On a board of many cards (`NEAR_CARDS_MINIMUM` or more) only the cards near the view are listed, the selected one and the one
1866
+ * under the pointer wherever they are (see `nearCards.ts`): a page that lays a live widget over each card it is given then runs
1867
+ * the widgets that are near, and lets the others go until the view comes back to them. `{ all: true }` lists every card, as
1868
+ * the list did before. `getWidgetShapeScreenRect(widgetId)` answers for any card, near or not.
1869
+ */
1870
+ listWidgetShapeScreenRects(options = {}) {
1681
1871
  const frame = this.#frame();
1682
1872
  if (!frame)
1683
1873
  return [];
1684
- const state = this.engine.state;
1685
- const results = [];
1686
- for (const object of state.scene) {
1687
- if (object.type !== 'widget' || !object.widgetId)
1688
- continue;
1689
- if (state.pending[object.id])
1690
- continue;
1691
- const runtime = this.engine.widgetRuntime(object.widgetId);
1692
- if (runtime.orphaned)
1693
- continue;
1694
- const geometry = widgetPreviewGeometry(object, state.viewport, frame);
1695
- if (!geometry || !geometry.matrix.every(Number.isFinite) || geometry.width < 4 || geometry.height < 4)
1696
- continue;
1697
- results.push({ widgetId: object.widgetId, hovered: object.widgetId === state.hoverWidgetId, ...geometry });
1698
- }
1699
- return results;
1874
+ try {
1875
+ const state = this.engine.state;
1876
+ // 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) {
1880
+ if (object.type !== 'widget' || !object.widgetId)
1881
+ continue;
1882
+ if (state.pending[object.id])
1883
+ continue;
1884
+ const runtime = this.engine.widgetRuntime(object.widgetId);
1885
+ if (runtime.orphaned)
1886
+ continue;
1887
+ // 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);
1889
+ listable.push({
1890
+ card: object,
1891
+ candidate: { widgetId: object.widgetId, bounds: shapeBounds(object), always: selectedIds.has(object.id) || object.widgetId === state.hoverWidgetId }
1892
+ });
1893
+ }
1894
+ if (listable.length === 0) {
1895
+ this.#nearCards.reset();
1896
+ return [];
1897
+ }
1898
+ // `all` lists every card and forgets which ones were listed: the next answer that is not for all starts from what is near.
1899
+ 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) {
1904
+ if (chosen && !chosen.has(card.widgetId))
1905
+ continue;
1906
+ const geometry = widgetPreviewGeometry(card, state.viewport, frame);
1907
+ if (!geometry || !geometry.matrix.every(Number.isFinite) || geometry.width < 4 || geometry.height < 4)
1908
+ continue;
1909
+ results.push({ widgetId: card.widgetId, hovered: card.widgetId === state.hoverWidgetId, ...geometry });
1910
+ }
1911
+ // 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;
1915
+ if (listable.length >= NEAR_CARDS_MINIMUM)
1916
+ canvasLog('Canvas: cards given to the page', { listed: results.length, of: listable.length });
1917
+ }
1918
+ return results;
1919
+ }
1920
+ catch (error) {
1921
+ // A list that cannot be made must not take the page's frame down with it: it gets no cards, and asks again at the next frame.
1922
+ canvasWarn('Canvas: listWidgetShapeScreenRects failed', error);
1923
+ return [];
1924
+ }
1700
1925
  }
1701
1926
  /** Where the card of a widget is on the page, with the board it is on. */
1702
1927
  getWidgetShapeScreenRect(widgetId) {
@@ -1706,9 +1931,9 @@ export class CanvasHost {
1706
1931
  const card = findWidgetCard(this.engine, widgetId);
1707
1932
  if (!card) {
1708
1933
  // Draft convert shapes exist before the widget card is registered — expected on embedded create.
1709
- if (!widgetId.startsWith('draft_convert_')) {
1710
- canvasLog('Canvas: getWidgetShapeScreenRect found no card for', widgetId);
1711
- }
1934
+ // if (!widgetId.startsWith('draft_convert_')) {
1935
+ // canvasLog('Canvas: getWidgetShapeScreenRect found no card for', widgetId);
1936
+ // }
1712
1937
  return null;
1713
1938
  }
1714
1939
  return screenRectOfBounds(shapeBounds(card), this.engine.state.viewport, frame);
@@ -1724,7 +1949,7 @@ export class CanvasHost {
1724
1949
  else
1725
1950
  bounds = this.conversions.peek(objectId)?.bounds ?? null;
1726
1951
  if (!bounds) {
1727
- canvasLog('Canvas: getObjectScreenRect found no object for', objectId);
1952
+ // canvasLog('Canvas: getObjectScreenRect found no object for', objectId);
1728
1953
  return null;
1729
1954
  }
1730
1955
  return screenRectOfBounds(bounds, this.engine.state.viewport, frame);