@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
@@ -10,6 +10,7 @@
10
10
  * end, so one gesture is one undo step. The pointer controller drives them; everything else (the menus, the
11
11
  * keyboard, the host's own calls) uses the commands below, each of which is one step.
12
12
  */
13
+ import type { CameraPathShape } from './core/cameraMove.js';
13
14
  import type { ParsedCanvas, SerializeOptions } from './codec/canvasDocument.js';
14
15
  import type { AlignMode, DistributeAxis } from './core/arrange.js';
15
16
  import type { ArrowHandleId } from './core/arrow.js';
@@ -40,6 +41,50 @@ export interface EngineServices {
40
41
  random?: () => number;
41
42
  /** Schedules an animation frame; returns a function that cancels it (tests pass a manual clock). */
42
43
  requestAnimationFrame?: (callback: (time: number) => void) => () => void;
44
+ /**
45
+ * Whether the person asked their system for less motion (the browser's `prefers-reduced-motion` in the app, `false` in
46
+ * tests unless a test says otherwise). A move of the view (`flyTo` and the other `flyTo…` calls) then puts the view
47
+ * in its place at once instead of easing it there.
48
+ */
49
+ prefersReducedMotion?: () => boolean;
50
+ }
51
+ /** A place to look at: the point of the world that goes to the middle of the board element, and the zoom to arrive at. */
52
+ export interface ViewTarget {
53
+ center: Point;
54
+ /** The zoom to arrive at (1 is 100%). Left out: the zoom stays what it is. */
55
+ zoom?: number;
56
+ }
57
+ /** How a move of the view goes (`flyTo` and the other `flyTo…` calls). */
58
+ export interface ViewMoveOptions {
59
+ /** How long the move takes, in milliseconds. Left out: worked out from how far the view goes, and always under a second. */
60
+ duration?: number;
61
+ /**
62
+ * The shape of the move: how much of the way is done (0 to 1) when this much of the time has passed (0 to 1), for the
63
+ * position and the zoom together. Left out: slow start, quick middle, slow end.
64
+ */
65
+ easing?: (progress: number) => number;
66
+ /**
67
+ * The way the view travels. `'ease'` (the default): the position and the zoom ease together, on the one `easing`, and arrive at
68
+ * the same moment; the zoom never goes beyond its two ends. `'fly'`: the path of van Wijk and Nuij, which for a long way zooms out
69
+ * on the way and in again at the end so the person keeps sight of where the view goes (it suits a jump across a big board); the
70
+ * zoom then changes at another rate than the position. Any other value is taken for `'ease'`. The time of the move does not depend
71
+ * on it.
72
+ */
73
+ path?: CameraPathShape;
74
+ /**
75
+ * Called once when the move is over, with `true` when the view arrived at the place and `false` when somebody else took the
76
+ * view first (the person pressed on the board, scrolled or pinched it; another move or a new board started). Also called, with
77
+ * `true`, when there was nothing to move because the view was there already.
78
+ */
79
+ onEnd?: (arrived: boolean) => void;
80
+ }
81
+ /** A move of the view to some objects. */
82
+ export interface ViewObjectsMoveOptions extends ViewMoveOptions {
83
+ /**
84
+ * The zoom to arrive at: a number (1 is 100%), `'fit'` (the objects fill the board with room around them, never past 200%,
85
+ * as "zoom to selection" does) or `'keep'` (the zoom the board has). Left out: `'fit'`.
86
+ */
87
+ zoom?: number | 'fit' | 'keep';
43
88
  }
44
89
  /** What the engine tells the host shell. Every hook is optional and read at the moment it is needed. */
45
90
  export interface EngineHooks {
@@ -128,13 +173,27 @@ export declare class EngineCore {
128
173
  * of what was loaded (a name filled in), not an edit.
129
174
  */
130
175
  applySilently(next: Scene): void;
176
+ /**
177
+ * 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
178
+ * its history, with no undo step and without telling the host that the board changed: a repair of what was loaded, not an edit.
179
+ * `repair` must give back the very same scene when it has nothing to change.
180
+ *
181
+ * Not `applySilently`, which is for what is done before the person can do anything: it makes the board the current step, and
182
+ * 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
183
+ * 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
184
+ * could not take it back; and the steps before this one would still be without the picture, so an undo would take it away.
185
+ */
186
+ repairLoaded(repair: (scene: Scene) => Scene): void;
131
187
  /** 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
188
  commit(): boolean;
133
189
  /** Throws away what a gesture did and goes back to the last step (Escape in the middle of a drag). */
134
190
  revertToCommitted(): void;
135
191
  undo(): boolean;
136
192
  redo(): boolean;
137
- /** Adds objects on top of the board in one step. Returns their ids. */
193
+ /**
194
+ * 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).
195
+ * Returns their ids.
196
+ */
138
197
  addObjects(objects: readonly SceneObject[], options?: {
139
198
  select?: boolean;
140
199
  }): ObjectId[];
@@ -192,6 +251,7 @@ export declare class EngineCore {
192
251
  force?: boolean;
193
252
  }): void;
194
253
  setStickyTool(sticky: boolean): void;
254
+ /** Puts the view where it is asked at once. A move of the view that was on its way (see `flyTo`) is over: the view is the person's. */
195
255
  setViewport(viewport: Viewport): void;
196
256
  panBy(deltaX: number, deltaY: number): void;
197
257
  /** Zooms and keeps the world point under `screenPoint` where it is. */
@@ -206,6 +266,34 @@ export declare class EngineCore {
206
266
  zoomToFit(): void;
207
267
  /** Shows the selection, or everything when nothing is selected. */
208
268
  zoomToSelection(): void;
269
+ /** Whether the view is on its way to a place (a move started by `flyTo` or one of the other `flyTo…` calls has not ended). */
270
+ get isViewMoving(): boolean;
271
+ /**
272
+ * Eases the view to a place: the point that ends in the middle of the board and the zoom change together, on one progress,
273
+ * so the move is a single motion and not a pan followed by a zoom, and both arrive at the same moment. With `options.path` set
274
+ * to `'fly'` a long way zooms out on the way and in again at the end instead (see `core/cameraMove.ts`). The view ends exactly
275
+ * on the place, and the size of the board is read at every frame, so a board that is resized on the way still ends with the
276
+ * place in its middle.
277
+ *
278
+ * Any other change of the view ends the move where the view is: a press on the board, a scroll, a pinch, `setViewport` or a new
279
+ * board, so the person is never fought for the view. With "reduce motion" on in the system, the view goes there at once.
280
+ *
281
+ * Returns whether the view moved (or jumped); false when it is there already or the place is not a place.
282
+ */
283
+ flyTo(target: ViewTarget, options?: ViewMoveOptions): boolean;
284
+ /**
285
+ * Eases the view to some objects (groups count as one, as in a selection): the middle of the objects goes to the middle of the
286
+ * board while the zoom changes to what `options.zoom` asks (the objects fill the board unless it says otherwise).
287
+ * False when none of the ids is an object of the board.
288
+ */
289
+ flyToObjects(ids: readonly ObjectId[], options?: ViewObjectsMoveOptions): boolean;
290
+ /**
291
+ * Eases the view back to 100% with the middle of everything that is drawn in the middle of the board (a double click on the
292
+ * empty board does this). An empty board goes back to where a new board starts.
293
+ */
294
+ flyToContent(options?: ViewMoveOptions): boolean;
295
+ /** Ends a move of the view where it is (the view keeps the place it had reached) and tells its `onEnd` that it did not arrive. */
296
+ cancelViewportMove(): void;
209
297
  /** The rectangle of the world that is on screen. */
210
298
  visibleRect(): Rect;
211
299
  /** The point of the world at a point of the board element. */
@@ -12,12 +12,13 @@
12
12
  */
13
13
  import { parseCanvasDocument, serializeCanvasDocument } from './codec/canvasDocument.js';
14
14
  import { rotationAfterResetProgress, rotationResetProgress } from './core/rotationReset.js';
15
+ import { cameraOfViewport, createCameraPath, easeInOutCubic, viewportOfCamera, viewportsMatch } from './core/cameraMove.js';
15
16
  import { alignObjects, distributeObjects } from './core/arrange.js';
16
17
  import { reconcileArrowBindings } from './core/arrowBinding.js';
17
18
  import { createImageObject, createObjectId, createRectObject, createTextObject, createWidgetObject, TEXT_DEFAULTS } from './core/defaults.js';
18
19
  import { HistoryStack } from './core/history.js';
19
20
  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';
21
+ import { addObjectsBehindWidgetCards, boardVisualBounds, boundsOfObjects, duplicateObjects, groupObjects, indexScene, leafShapesOf, normalizeScene, normalizeSelection, removeObjects as removeFromScene, reorderObjects, replaceObject, sameIds, translateObjects, ungroupObjects, withDescendantIds } from './core/scene.js';
21
22
  import { applyStylePatch } from './core/style.js';
22
23
  import { Scribble } from './core/scribble.js';
23
24
  import { selectionFrameOf } from './core/transform.js';
@@ -59,6 +60,8 @@ export class EngineCore {
59
60
  services;
60
61
  #state = createInitialState();
61
62
  #rotationResetCancel = null;
63
+ /** Stops the move of the view that is on its way (see `flyTo`); null when the view is not moving by itself. */
64
+ #viewportMoveCancel = null;
62
65
  #listeners = new Set();
63
66
  #history;
64
67
  #clipboard = null;
@@ -79,6 +82,8 @@ export class EngineCore {
79
82
  measureText: services.measureText ?? createFixedAdvanceMeasure(),
80
83
  now: services.now ?? (() => Date.now()),
81
84
  random: services.random ?? Math.random,
85
+ prefersReducedMotion: services.prefersReducedMotion ??
86
+ (() => typeof globalThis.matchMedia === 'function' && globalThis.matchMedia('(prefers-reduced-motion: reduce)').matches),
82
87
  requestAnimationFrame: services.requestAnimationFrame ??
83
88
  ((callback) => {
84
89
  if (typeof globalThis.requestAnimationFrame === 'function') {
@@ -105,6 +110,7 @@ export class EngineCore {
105
110
  /** Lets go of every listener and hook (the board was removed from the page). */
106
111
  dispose() {
107
112
  this.cancelRotationReset();
113
+ this.cancelViewportMove();
108
114
  this.#listeners.clear();
109
115
  this.hooks = {};
110
116
  this.#textSession = null;
@@ -189,6 +195,8 @@ export class EngineCore {
189
195
  // ──────────────────────────────────────────────────────── loading and saving
190
196
  /** Shows a canvas that was read from saved data. History starts again from it, and it is not "changed". */
191
197
  load(parsed, options = {}) {
198
+ // A new board has its own view: a move that was on its way to a place of the old board is over.
199
+ this.cancelViewportMove();
192
200
  this.#textSession = null;
193
201
  // The texts are laid out first: an arrow tied to one rests on the box its letters make.
194
202
  const scene = reconcileArrowBindings(this.#fitTexts(parsed.scene));
@@ -317,6 +325,28 @@ export class EngineCore {
317
325
  // What the board holds now (the arrows tied to shapes drawn again), not the scene that was asked for.
318
326
  this.#history.replaceCurrent(this.#state.scene);
319
327
  }
328
+ /**
329
+ * 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
330
+ * its history, with no undo step and without telling the host that the board changed: a repair of what was loaded, not an edit.
331
+ * `repair` must give back the very same scene when it has nothing to change.
332
+ *
333
+ * Not `applySilently`, which is for what is done before the person can do anything: it makes the board the current step, and
334
+ * 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
335
+ * 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
336
+ * could not take it back; and the steps before this one would still be without the picture, so an undo would take it away.
337
+ */
338
+ repairLoaded(repair) {
339
+ // At rest the board is the current step itself; during a gesture it is not.
340
+ const atRest = this.#history.current === this.#state.scene;
341
+ this.#history.mapAll(repair);
342
+ const next = atRest ? this.#history.current : repair(this.#state.scene);
343
+ if (next === this.#state.scene)
344
+ return;
345
+ this.applyScene(next, 'transient');
346
+ // What the board holds now (the arrows tied to shapes drawn again), so that the board stays the very same list as its step.
347
+ if (atRest)
348
+ this.#history.replaceCurrent(this.#state.scene);
349
+ }
320
350
  /** 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
351
  commit() {
322
352
  this.#nudgeMergeUntil = 0;
@@ -356,12 +386,15 @@ export class EngineCore {
356
386
  this.#set({ canUndo: this.#history.canUndo, canRedo: this.#history.canRedo, overlay: EMPTY_OVERLAY });
357
387
  this.hooks.onDirty?.();
358
388
  }
359
- /** Adds objects on top of the board in one step. Returns their ids. */
389
+ /**
390
+ * 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).
391
+ * Returns their ids.
392
+ */
360
393
  addObjects(objects, options = {}) {
361
394
  if (objects.length === 0)
362
395
  return [];
363
396
  const fitted = objects.map((object) => this.#fitText(object));
364
- this.applyScene([...this.#state.scene, ...fitted], 'push');
397
+ this.applyScene(addObjectsBehindWidgetCards(this.#state.scene, fitted), 'push');
365
398
  const ids = fitted.map((object) => object.id);
366
399
  if (options.select)
367
400
  this.select(ids);
@@ -597,7 +630,13 @@ export class EngineCore {
597
630
  this.#set({ stickyTool: sticky });
598
631
  }
599
632
  // ──────────────────────────────────────────────────────── viewport
633
+ /** Puts the view where it is asked at once. A move of the view that was on its way (see `flyTo`) is over: the view is the person's. */
600
634
  setViewport(viewport) {
635
+ this.cancelViewportMove();
636
+ this.#writeViewport(viewport);
637
+ }
638
+ /** Writes the view without ending a move in progress: the one way the move itself puts the view where the frame says. */
639
+ #writeViewport(viewport) {
601
640
  const next = sanitizeViewport(viewport);
602
641
  const current = this.#state.viewport;
603
642
  if (next.x === current.x && next.y === current.y && next.zoom === current.zoom)
@@ -649,6 +688,120 @@ export class EngineCore {
649
688
  }
650
689
  this.setViewport(fitViewportToRect(bounds, this.#state.viewSize, VIEW_FIT_PADDING, 2));
651
690
  }
691
+ // ──────────────────────────────────────────────────────── moving the view with an ease
692
+ /** Whether the view is on its way to a place (a move started by `flyTo` or one of the other `flyTo…` calls has not ended). */
693
+ get isViewMoving() {
694
+ return this.#viewportMoveCancel !== null;
695
+ }
696
+ /**
697
+ * Eases the view to a place: the point that ends in the middle of the board and the zoom change together, on one progress,
698
+ * so the move is a single motion and not a pan followed by a zoom, and both arrive at the same moment. With `options.path` set
699
+ * to `'fly'` a long way zooms out on the way and in again at the end instead (see `core/cameraMove.ts`). The view ends exactly
700
+ * on the place, and the size of the board is read at every frame, so a board that is resized on the way still ends with the
701
+ * place in its middle.
702
+ *
703
+ * Any other change of the view ends the move where the view is: a press on the board, a scroll, a pinch, `setViewport` or a new
704
+ * board, so the person is never fought for the view. With "reduce motion" on in the system, the view goes there at once.
705
+ *
706
+ * Returns whether the view moved (or jumped); false when it is there already or the place is not a place.
707
+ */
708
+ flyTo(target, options = {}) {
709
+ // A move on its way is over: this one starts from where the view is now.
710
+ this.cancelViewportMove();
711
+ const viewSize = this.#state.viewSize;
712
+ const startView = cameraOfViewport(this.#state.viewport, viewSize);
713
+ const endView = {
714
+ center: { x: target.center.x, y: target.center.y },
715
+ zoom: clampZoom(target.zoom ?? startView.zoom)
716
+ };
717
+ // A board that is not on the page yet has no middle to put a place in, and a place that is not a point is the caller's mistake:
718
+ // the view stays as it is.
719
+ if (!(viewSize.width > 0) || !(viewSize.height > 0) || !Number.isFinite(endView.center.x) || !Number.isFinite(endView.center.y)) {
720
+ this.#callHook(() => options.onEnd?.(false), 'view move end callback');
721
+ return false;
722
+ }
723
+ const endViewport = viewportOfCamera(endView, viewSize);
724
+ if (viewportsMatch(endViewport, this.#state.viewport)) {
725
+ // Nothing to move, and nothing to wait for.
726
+ this.#callHook(() => options.onEnd?.(true), 'view move end callback');
727
+ return false;
728
+ }
729
+ const path = createCameraPath(startView, endView, viewSize, options.path);
730
+ const duration = options.duration ?? path?.duration ?? 0;
731
+ if (!path || !(duration > 0) || this.services.prefersReducedMotion()) {
732
+ // No time to move in, or a person who asked their system for no motion: the view is in its place at once.
733
+ this.#writeViewport(endViewport);
734
+ this.#callHook(() => options.onEnd?.(true), 'view move end callback');
735
+ return true;
736
+ }
737
+ const easing = options.easing ?? easeInOutCubic;
738
+ const startedAt = this.services.now();
739
+ let cancelFrame = null;
740
+ let over = false;
741
+ const finish = (arrived) => {
742
+ if (over)
743
+ return;
744
+ over = true;
745
+ cancelFrame?.();
746
+ if (this.#viewportMoveCancel === stopMove)
747
+ this.#viewportMoveCancel = null;
748
+ this.#callHook(() => options.onEnd?.(arrived), 'view move end callback');
749
+ };
750
+ const stopMove = () => finish(false);
751
+ const advance = () => {
752
+ if (over)
753
+ return;
754
+ const timeProgress = Math.min(1, Math.max(0, (this.services.now() - startedAt) / duration));
755
+ const arrived = timeProgress >= 1;
756
+ // The board is measured now, not when the move began, and the last frame is the place itself, not a step close to it.
757
+ const view = arrived ? endView : path.at(easing(timeProgress));
758
+ this.#writeViewport(viewportOfCamera(view, this.#state.viewSize));
759
+ // What listens to the view may have taken it in the meantime (a call to `setViewport` from a listener ends the move).
760
+ if (over)
761
+ return;
762
+ if (arrived) {
763
+ finish(true);
764
+ return;
765
+ }
766
+ cancelFrame = this.services.requestAnimationFrame(advance);
767
+ };
768
+ this.#viewportMoveCancel = stopMove;
769
+ cancelFrame = this.services.requestAnimationFrame(advance);
770
+ return true;
771
+ }
772
+ /**
773
+ * Eases the view to some objects (groups count as one, as in a selection): the middle of the objects goes to the middle of the
774
+ * board while the zoom changes to what `options.zoom` asks (the objects fill the board unless it says otherwise).
775
+ * False when none of the ids is an object of the board.
776
+ */
777
+ flyToObjects(ids, options = {}) {
778
+ const { zoom = 'fit', ...moveOptions } = options;
779
+ const bounds = boundsOfObjects(this.#state.scene, ids);
780
+ if (!bounds)
781
+ return false;
782
+ const center = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
783
+ const targetZoom = zoom === 'keep' ? undefined : zoom === 'fit' ? fitViewportToRect(bounds, this.#state.viewSize, VIEW_FIT_PADDING, 2).zoom : zoom;
784
+ return this.flyTo({ center, zoom: targetZoom }, moveOptions);
785
+ }
786
+ /**
787
+ * Eases the view back to 100% with the middle of everything that is drawn in the middle of the board (a double click on the
788
+ * empty board does this). An empty board goes back to where a new board starts.
789
+ */
790
+ flyToContent(options = {}) {
791
+ const bounds = boardVisualBounds(this.#state.scene);
792
+ const center = bounds
793
+ ? { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 }
794
+ : cameraOfViewport(INITIAL_VIEWPORT, this.#state.viewSize).center;
795
+ return this.flyTo({ center, zoom: 1 }, options);
796
+ }
797
+ /** Ends a move of the view where it is (the view keeps the place it had reached) and tells its `onEnd` that it did not arrive. */
798
+ cancelViewportMove() {
799
+ const stopMove = this.#viewportMoveCancel;
800
+ if (!stopMove)
801
+ return;
802
+ this.#viewportMoveCancel = null;
803
+ stopMove();
804
+ }
652
805
  /** The rectangle of the world that is on screen. */
653
806
  visibleRect() {
654
807
  return visibleWorldRect(this.#state.viewport, this.#state.viewSize);
@@ -733,7 +886,8 @@ export class EngineCore {
733
886
  });
734
887
  const text = this.#fitText(base);
735
888
  const sceneBefore = this.#state.scene;
736
- this.applyScene([...sceneBefore, text], 'transient');
889
+ // A text typed after a widget stands goes behind it, like every other drawing.
890
+ this.applyScene(addObjectsBehindWidgetCards(sceneBefore, [text]), 'transient');
737
891
  this.#textSession = { id: text.id, isNew: true, sceneBefore, typed: false };
738
892
  this.#set({ editingTextId: text.id, selectedIds: [text.id], enteredGroupId: null });
739
893
  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]) {
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Moving the view the way a camera moves: from where it looks now to a place it is asked to look at, with the position and the
3
+ * zoom changing together, on one eased progress, and ending exactly on the place.
4
+ *
5
+ * A view is what the board looks at (`CameraView`): the point of the world in the middle of the board element, and the zoom (1 is
6
+ * 100%). The viewport the engine keeps (`x`, `y`, `zoom`) is worked out from it for the size of the board at that moment, so a board
7
+ * that is resized on the way still ends with the place in its middle.
8
+ *
9
+ * There are two shapes of path between two views (`CameraPathShape`):
10
+ *
11
+ * - `'ease'`, the default: the position and the zoom ease together. The centre goes in a straight line and the zoom changes by the
12
+ * same factor at every step, both on the one eased progress, so they start, speed up, slow down and arrive at the same moment, and
13
+ * the zoom never goes beyond its two ends. This is what "ease the position and the zoom at the same time" asks for.
14
+ * - `'fly'`: the path of van Wijk and Nuij, "Smooth and efficient zooming and panning" (2003), the one d3's `interpolateZoom` draws.
15
+ * A view that only zooms moves like a plain zoom; a view that has to go far zooms out on the way and in again at the end, so what
16
+ * the person looks at does not rush past. The position and the zoom still ride on one progress, but not at the same rate (the view
17
+ * zooms out while it pans and in as it arrives), so it is not the plain ease above.
18
+ *
19
+ * Both last as long as the length of the van Wijk path says, so a move takes the same time whichever shape it has.
20
+ *
21
+ * Nothing here knows the clock or the page: the engine asks for the view at a progress, and a test asks for the same.
22
+ */
23
+ import type { Point, Size, Viewport } from './types.js';
24
+ /**
25
+ * The way a move goes between two views: `'ease'` (the default) changes the position and the zoom together at the same rate, and
26
+ * `'fly'` is the path of van Wijk and Nuij, which zooms out on the way when the move is long. Any other value is taken for `'ease'`.
27
+ */
28
+ export type CameraPathShape = 'ease' | 'fly';
29
+ /** What the board looks at: the point of the world in the middle of the board element, and the zoom. */
30
+ export interface CameraView {
31
+ center: Point;
32
+ /** The scale of the world on screen (1 is 100%). */
33
+ zoom: number;
34
+ }
35
+ /** The path of a move between two views. */
36
+ export interface CameraPath {
37
+ /** How far the view travels, in the units of the path: a plain zoom of about four times is 1, and a longer way is more. */
38
+ length: number;
39
+ /** How long the move should last, in milliseconds, worked out from its length (never under the shortest or over the longest). */
40
+ duration: number;
41
+ /** The view `progress` of the way along the path: 0 is the start, 1 is exactly the end. */
42
+ at(progress: number): CameraView;
43
+ }
44
+ /** The shape a move has when nobody chose one: the position and the zoom ease together. */
45
+ export declare const DEFAULT_CAMERA_PATH_SHAPE: CameraPathShape;
46
+ /** The shortest a move lasts when nobody gave its length, in milliseconds: a shorter one is too quick for the eye to follow. */
47
+ export declare const CAMERA_MOVE_MIN_DURATION_MS = 380;
48
+ /** The longest a move lasts when nobody gave its length, in milliseconds: a long way across the board still takes under a second. */
49
+ export declare const CAMERA_MOVE_MAX_DURATION_MS = 1000;
50
+ /** The time for each unit of the length of a path, in milliseconds. */
51
+ export declare const CAMERA_MOVE_MS_PER_UNIT = 800;
52
+ /** The view that a viewport shows in a board element of `viewSize`. */
53
+ export declare function cameraOfViewport(viewport: Viewport, viewSize: Size): CameraView;
54
+ /** The viewport that shows `camera` in a board element of `viewSize`. */
55
+ export declare function viewportOfCamera(camera: CameraView, viewSize: Size): Viewport;
56
+ /** Whether two viewports look the same to a person: less than half a pixel apart, with a zoom that differs by less than 0.01%. */
57
+ export declare function viewportsMatch(first: Viewport, second: Viewport): boolean;
58
+ /** Slow start, quick middle, slow end: the way a person expects a camera to move. `progress` and the answer are between 0 and 1. */
59
+ export declare function easeInOutCubic(progress: number): number;
60
+ /**
61
+ * The path from one view to another, or `null` when there is no path to draw: the board has no size yet, or one of the views is not
62
+ * a view (a centre that is not a point, a zoom that is not above 0). The caller then puts the view in place at once.
63
+ *
64
+ * `shape` is how the view goes (see `CameraPathShape`): by default the position and the zoom ease together, and `'fly'` takes the
65
+ * path of van Wijk and Nuij. How long the move lasts comes from the length of that path whichever shape is asked for.
66
+ */
67
+ export declare function createCameraPath(from: CameraView, to: CameraView, viewSize: Size, shape?: CameraPathShape): CameraPath | null;