@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,78 @@
1
+ /**
2
+ * Which cards of the board `listWidgetShapeScreenRects()` gives to the page: the ones near what the person sees.
3
+ *
4
+ * The page lays a live widget (an iframe, a whole running widget) over every card it is given, and moves it again at every frame in
5
+ * which the board changed. The list used to hold every card of the board, so a board of a few dozen cards had a few dozen widgets
6
+ * running, nearly all of them far outside the screen, and each change of the view made the page work for all of them. Now a card is
7
+ * listed only while it is close to the view; the page lays a live widget over it when it gets near and lets it go when it is far,
8
+ * exactly as the board does for its own elements (`mountedScene.ts`).
9
+ *
10
+ * What it decides, in short:
11
+ *
12
+ * - A board with fewer cards than `NEAR_CARDS_MINIMUM` lists every one of them, as it always did: a few widgets are what the
13
+ * person asked for, and what a card is made of (a widget that is running, what was typed in it) is not thrown away for nothing.
14
+ * - Above that, a card is listed when its box touches the *near area*: the view, with a whole view of room on every side. That is
15
+ * a wide margin on purpose: a live widget takes time to load, so it should be ready before the card is on the screen.
16
+ * - A card that is listed already stays listed until it is out of the *keep area*: the view with two whole views of room on
17
+ * every side. A pan that goes out and comes back (the hand of a person does that all the time) must not have the page build the
18
+ * same widget twice, and a card at the edge of the near area must not come and go with every pixel of the pan.
19
+ * - The card that is selected, and the one the pointer is over, are always listed wherever they are: the person is working with
20
+ * them (the page draws its frame and its drag bar for them).
21
+ * - A board that has no size yet (nothing is known to be far) lists every card.
22
+ *
23
+ * Plain TypeScript with no Svelte file in it, so that Node can test it.
24
+ */
25
+ import { rectsIntersect } from '../../engine/core/geometry.js';
26
+ import { visibleWorldRect } from '../../engine/core/viewport.js';
27
+ /** A board with fewer cards than this lists every one of them. */
28
+ export const NEAR_CARDS_MINIMUM = 8;
29
+ /** How far past the view a card is listed, as a share of the view's width and height, on every side. */
30
+ export const NEAR_CARD_MARGIN_RATIO = 1;
31
+ /** How far past the view a card that is listed already stays listed, in the same measure. More than `NEAR_CARD_MARGIN_RATIO`. */
32
+ export const KEEP_CARD_MARGIN_RATIO = 2;
33
+ /** A view with `ratio` of its width and height added on every side. */
34
+ function viewWithMargin(view, ratio) {
35
+ const marginX = view.width * ratio;
36
+ const marginY = view.height * ratio;
37
+ return { x: view.x - marginX, y: view.y - marginY, width: view.width + marginX * 2, height: view.height + marginY * 2 };
38
+ }
39
+ /** A rectangle made of finite numbers, with some size: anything else says the board has no size (or no view) yet. */
40
+ function isUsableView(view) {
41
+ return Number.isFinite(view.x) && Number.isFinite(view.y) && Number.isFinite(view.width) && Number.isFinite(view.height) && view.width > 0 && view.height > 0;
42
+ }
43
+ export function createNearCards(options = {}) {
44
+ const minimumCards = options.minimumCards ?? NEAR_CARDS_MINIMUM;
45
+ const nearMarginRatio = options.nearMarginRatio ?? NEAR_CARD_MARGIN_RATIO;
46
+ const keepMarginRatio = Math.max(nearMarginRatio, options.keepMarginRatio ?? KEEP_CARD_MARGIN_RATIO);
47
+ /** The ids that were listed the last time: the cards that keep their place while they are inside the keep area. */
48
+ let listed = new Set();
49
+ function listEveryCard(cards) {
50
+ listed = new Set(cards.map((card) => card.widgetId));
51
+ return new Set(listed);
52
+ }
53
+ return {
54
+ choose(cards, viewport, viewSize) {
55
+ if (cards.length < minimumCards)
56
+ return listEveryCard(cards);
57
+ if (!Number.isFinite(viewport.zoom) || viewport.zoom <= 0)
58
+ return listEveryCard(cards);
59
+ const view = visibleWorldRect(viewport, viewSize);
60
+ if (!isUsableView(view))
61
+ return listEveryCard(cards);
62
+ const nearArea = viewWithMargin(view, nearMarginRatio);
63
+ const keepArea = viewWithMargin(view, keepMarginRatio);
64
+ const next = new Set();
65
+ for (const card of cards) {
66
+ if (card.always || rectsIntersect(nearArea, card.bounds) || (listed.has(card.widgetId) && rectsIntersect(keepArea, card.bounds))) {
67
+ next.add(card.widgetId);
68
+ }
69
+ }
70
+ listed = next;
71
+ return new Set(next);
72
+ },
73
+ reset() {
74
+ if (listed.size > 0)
75
+ listed = new Set();
76
+ }
77
+ };
78
+ }
@@ -1,10 +1,14 @@
1
1
  /**
2
- * The two events the canvas sends to its page, on `window`.
2
+ * The events the canvas sends to its page, on `window`.
3
3
  *
4
- * The widget creator listens to both, so their names and what they carry are part of the host contract:
4
+ * The widget creator listens to them, so their names and what they carry are part of the host contract:
5
5
  *
6
- * - `widgetic:canvas-select-tool` (no detail): the Select tool was chosen. The creator closes the element selector of every
7
- * widget when it hears it.
6
+ * - `widgetic:canvas-select-tool` (no detail): the Select tool was chosen. The creator used to close the element selector of
7
+ * every widget when it heard it; it now listens to `widgetic:canvas-tool` instead (the Select tool is what turns the
8
+ * selector on), and this one is kept for the pages that still read it.
9
+ * - `widgetic:canvas-tool` (`{ tool }`): the tool changed, and once when the board opens, so a page that starts listening
10
+ * before the board is up always hears the first tool. `tool` is the engine's own name for it (`select`, `draw`, `erase`,
11
+ * `text`, `arrow`, `pan`, `rect`, ...). The creator turns its element selector on while it is `select`.
8
12
  * - `widgetic:widget-shape-pointer-block` (`{ widgetId, active }`): a widget card is being stretched (`active: true`, with
9
13
  * the widget's id) or the stretch ended (`active: false`, `widgetId: null`). The creator lets the pointer through the live
10
14
  * widget laid over the card while the stretch lasts, so the iframe does not take the gesture.
@@ -12,13 +16,21 @@
12
16
  * Kept free of Svelte so that Node can test it. A page rendered on the server has no `window` and gets nothing.
13
17
  */
14
18
  export declare const CANVAS_SELECT_TOOL_EVENT = "widgetic:canvas-select-tool";
19
+ export declare const CANVAS_TOOL_EVENT = "widgetic:canvas-tool";
15
20
  export declare const WIDGET_POINTER_BLOCK_EVENT = "widgetic:widget-shape-pointer-block";
16
21
  export interface WidgetPointerBlockDetail {
17
22
  /** The widget whose card is being stretched, or null when the stretch ended. */
18
23
  widgetId: string | null;
19
24
  active: boolean;
20
25
  }
26
+ /** What `widgetic:canvas-tool` carries. */
27
+ export interface CanvasToolDetail {
28
+ /** The tool that is chosen now: the engine's name for it (`select`, `draw`, `erase`, `text`, `arrow`, `pan`, ...). */
29
+ tool: string;
30
+ }
21
31
  /** The Select tool was chosen. */
22
32
  export declare function announceSelectTool(): void;
33
+ /** The tool changed (or the board opened with this tool). */
34
+ export declare function announceCanvasTool(tool: string): void;
23
35
  /** A widget card is being stretched, or no longer is. */
24
36
  export declare function announceWidgetPointerBlock(detail: WidgetPointerBlockDetail): void;
@@ -1,10 +1,14 @@
1
1
  /**
2
- * The two events the canvas sends to its page, on `window`.
2
+ * The events the canvas sends to its page, on `window`.
3
3
  *
4
- * The widget creator listens to both, so their names and what they carry are part of the host contract:
4
+ * The widget creator listens to them, so their names and what they carry are part of the host contract:
5
5
  *
6
- * - `widgetic:canvas-select-tool` (no detail): the Select tool was chosen. The creator closes the element selector of every
7
- * widget when it hears it.
6
+ * - `widgetic:canvas-select-tool` (no detail): the Select tool was chosen. The creator used to close the element selector of
7
+ * every widget when it heard it; it now listens to `widgetic:canvas-tool` instead (the Select tool is what turns the
8
+ * selector on), and this one is kept for the pages that still read it.
9
+ * - `widgetic:canvas-tool` (`{ tool }`): the tool changed, and once when the board opens, so a page that starts listening
10
+ * before the board is up always hears the first tool. `tool` is the engine's own name for it (`select`, `draw`, `erase`,
11
+ * `text`, `arrow`, `pan`, `rect`, ...). The creator turns its element selector on while it is `select`.
8
12
  * - `widgetic:widget-shape-pointer-block` (`{ widgetId, active }`): a widget card is being stretched (`active: true`, with
9
13
  * the widget's id) or the stretch ended (`active: false`, `widgetId: null`). The creator lets the pointer through the live
10
14
  * widget laid over the card while the stretch lasts, so the iframe does not take the gesture.
@@ -13,6 +17,7 @@
13
17
  */
14
18
  import { canvasWarn } from '../canvasLogger.js';
15
19
  export const CANVAS_SELECT_TOOL_EVENT = 'widgetic:canvas-select-tool';
20
+ export const CANVAS_TOOL_EVENT = 'widgetic:canvas-tool';
16
21
  export const WIDGET_POINTER_BLOCK_EVENT = 'widgetic:widget-shape-pointer-block';
17
22
  function dispatchOnWindow(name, detail) {
18
23
  if (typeof window === 'undefined' || typeof CustomEvent === 'undefined')
@@ -29,6 +34,10 @@ function dispatchOnWindow(name, detail) {
29
34
  export function announceSelectTool() {
30
35
  dispatchOnWindow(CANVAS_SELECT_TOOL_EVENT);
31
36
  }
37
+ /** The tool changed (or the board opened with this tool). */
38
+ export function announceCanvasTool(tool) {
39
+ dispatchOnWindow(CANVAS_TOOL_EVENT, { tool: String(tool) });
40
+ }
32
41
  /** A widget card is being stretched, or no longer is. */
33
42
  export function announceWidgetPointerBlock(detail) {
34
43
  dispatchOnWindow(WIDGET_POINTER_BLOCK_EVENT, { widgetId: detail.widgetId === null ? null : String(detail.widgetId), active: detail.active });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What the board has already given to the page's picture store, so that a save gives the store only what it has not got yet.
3
+ *
4
+ * Saving writes the whole board, and the writer hands the store the bytes of every picture that is still held inline, on every
5
+ * save. The bytes stay in the board in memory (only the saved text leaves them out), so a board with a few photos on it wrote
6
+ * the same megabytes again after every small change: a page whose store keeps them on disk did a structured clone of each of
7
+ * them, on the main thread, for bytes that had not changed.
8
+ *
9
+ * The store is given a picture once for a set of bytes. A save that comes with the same bytes again is not passed on.
10
+ *
11
+ * - Only what the store accepted is remembered. A `save` that throws is not: the writer keeps those bytes in the text, and the
12
+ * next save offers them again.
13
+ * - The first save that is complete forgets whatever it did not see, so a picture that left the board is offered again if an
14
+ * undo brings it back (the store may have dropped it meanwhile).
15
+ * - A store that was replaced by another has none of it: everything is offered again.
16
+ * - What is compared is the bytes, not the reference: a picture that was replaced under the same reference (a new screenshot of
17
+ * a widget) is given again.
18
+ */
19
+ import type { ImageBytesSink } from '../../engine/codec/canvasDocument.js';
20
+ import type { ShapeImageStore } from '../shapes/shapeImageStore.js';
21
+ export interface PictureSaveMemory {
22
+ /**
23
+ * The place for the writer to put bytes during one save, or null when there is no store (the bytes then stay in the text).
24
+ * Call `finishSave` when the save is over.
25
+ */
26
+ startSave(store: ShapeImageStore | null): ImageBytesSink | null;
27
+ /**
28
+ * Ends the save that began last. `completed` is false when the save failed half way: what it handed over is kept, and nothing
29
+ * is forgotten, since the part it did not get to says nothing about the pictures it did not see.
30
+ */
31
+ finishSave(completed: boolean): void;
32
+ }
33
+ export declare function createPictureSaveMemory(): PictureSaveMemory;
@@ -0,0 +1,42 @@
1
+ export function createPictureSaveMemory() {
2
+ /** The store the memory is about. */
3
+ let rememberedFor = null;
4
+ /** Reference → the bytes the store accepted for it. */
5
+ let remembered = new Map();
6
+ /** What the save that is on its way has handed over or found already handed over, by reference; null between saves. */
7
+ let thisSave = null;
8
+ return {
9
+ startSave(store) {
10
+ if (!store) {
11
+ thisSave = null;
12
+ return null;
13
+ }
14
+ if (store !== rememberedFor) {
15
+ rememberedFor = store;
16
+ remembered = new Map();
17
+ }
18
+ const seenInThisSave = new Map();
19
+ thisSave = seenInThisSave;
20
+ return {
21
+ save(reference, dataUrl) {
22
+ // A throw from the store is the writer's to deal with, and nothing is noted for it.
23
+ if (remembered.get(reference) !== dataUrl)
24
+ store.save(reference, dataUrl);
25
+ seenInThisSave.set(reference, dataUrl);
26
+ }
27
+ };
28
+ },
29
+ finishSave(completed) {
30
+ const seenInThisSave = thisSave;
31
+ thisSave = null;
32
+ if (!seenInThisSave)
33
+ return;
34
+ if (completed) {
35
+ remembered = seenInThisSave;
36
+ return;
37
+ }
38
+ for (const [reference, dataUrl] of seenInThisSave)
39
+ remembered.set(reference, dataUrl);
40
+ }
41
+ };
42
+ }
@@ -47,6 +47,11 @@ export interface WidgetScreenRect extends WidgetPreviewGeometry {
47
47
  widgetId: string;
48
48
  hovered: boolean;
49
49
  }
50
+ /** What `listWidgetShapeScreenRects()` can be asked (see `nearCards.ts` for which cards it lists when it is not asked for all). */
51
+ export interface ListWidgetScreenRectsOptions {
52
+ /** Every card of the board, near the view or not: what the list held before it was limited to the cards near the view. */
53
+ all?: boolean;
54
+ }
50
55
  /** A point of the world on the page. */
51
56
  export declare function worldPointToPage(viewport: Viewport, frame: BoardFrame, x: number, y: number): {
52
57
  x: number;
@@ -0,0 +1,88 @@
1
+ import type { Scene } from '../../engine/core/scene.js';
2
+ import type { ObjectId, Rect } from '../../engine/core/types.js';
3
+ import type { ShapeImageStore } from '../shapes/shapeImageStore.js';
4
+ /** How many pictures are asked of the store at the same time. */
5
+ export declare const PICTURE_LOAD_CONCURRENCY = 6;
6
+ /** How long the pictures that came in are kept before they are put on the board together (so that a burst is one change, not forty). */
7
+ export declare const PICTURE_APPLY_DELAY_MS = 40;
8
+ /**
9
+ * How long the pictures that are not on screen wait for the ones that are, at most. They wait for them to come in, so that the
10
+ * store and the network are the on-screen pictures' alone; one that hangs must not hold back the rest of the board for ever.
11
+ */
12
+ export declare const PICTURE_BACKGROUND_GRACE_MS = 3000;
13
+ /** An object that points at a picture and does not hold its bytes yet. */
14
+ export interface MissingPicture {
15
+ objectId: ObjectId;
16
+ /** What the page's store knows the picture by. */
17
+ reference: string;
18
+ /** Where the object paints, in the world (what decides whether it is on screen). */
19
+ bounds: Rect;
20
+ }
21
+ /** A picture that the store gave back, with the reference it was asked for (the object may have been given another since). */
22
+ export interface LoadedPicture {
23
+ reference: string;
24
+ dataUrl: string;
25
+ }
26
+ /** The objects of a scene that point at a picture and do not hold its bytes, in the order of the scene. */
27
+ export declare function picturesStillMissing(scene: Scene): MissingPicture[];
28
+ /**
29
+ * A scene with the pictures that came in put into the objects that were waiting for exactly that picture. An object that holds a
30
+ * picture by now (the person put another one there), or points at another reference, or is gone, is left as it is. The very same
31
+ * scene when nothing changed.
32
+ */
33
+ export declare function fillPictures(scene: Scene, loaded: ReadonlyMap<ObjectId, LoadedPicture>): Scene;
34
+ /**
35
+ * Waits for a promise for at most `milliseconds`. True when it finished in time, false when the time ran out first (the promise is
36
+ * not stopped: whatever it was doing goes on). A promise that fails counts as finished: the caller only wanted to know that it is over.
37
+ */
38
+ export declare function waitUpTo(promise: Promise<unknown>, milliseconds: number): Promise<boolean>;
39
+ /** A rectangle made of finite numbers with some size: anything else says the board has no size (or no view) yet. */
40
+ export declare function isUsableView(view: Rect | null | undefined): view is Rect;
41
+ /** How many of the pictures are of objects that touch the view. All of them when the view is not known: nothing is known to be far. */
42
+ export declare function countPicturesInView(missing: readonly MissingPicture[], view: Rect | null | undefined): number;
43
+ /**
44
+ * The pictures still to be asked for, handing out the one to ask next: the ones of objects that touch the view first, the nearest
45
+ * to the middle of the view first among those and among the others. The order is made again when the view has moved by a quarter
46
+ * of itself or changed its size by a quarter (not at every pan frame, and not at every picture), and it is the scene's own order
47
+ * when the view is not known.
48
+ */
49
+ export declare class PictureQueue {
50
+ #private;
51
+ constructor(missing: readonly MissingPicture[]);
52
+ /** How many are still to be asked for. */
53
+ get length(): number;
54
+ /** The picture to ask for next, or undefined when none is left. */
55
+ take(view: Rect | null | undefined): MissingPicture | undefined;
56
+ /** Puts back a picture that was taken and not asked for after all: it is the next one to be handed out (it was the best). */
57
+ giveBack(picture: MissingPicture): void;
58
+ }
59
+ /** What `startLoadingPictures` needs to know about the board and the page. */
60
+ export interface PictureLoadPlan {
61
+ missing: readonly MissingPicture[];
62
+ store: ShapeImageStore;
63
+ /** The rectangle of the world that is on screen right now, or null when that is not known. */
64
+ currentView(): Rect | null;
65
+ /** Puts pictures that came in on the board. Called with a batch, never with an empty one. */
66
+ apply(loaded: ReadonlyMap<ObjectId, LoadedPicture>): void;
67
+ /** True once the board is gone or was replaced by another one: nothing more is asked, and nothing that came is put on the board. */
68
+ isCancelled(): boolean;
69
+ /** Says what went wrong with one picture (the others go on). */
70
+ warn(message: string, ...details: unknown[]): void;
71
+ concurrency?: number;
72
+ applyDelayMs?: number;
73
+ backgroundGraceMs?: number;
74
+ }
75
+ export interface PictureLoad {
76
+ /**
77
+ * Resolves when no picture of an object that is on screen is left to be asked for or to be answered (found or not), and the ones
78
+ * that were found are on the board: the pictures the board waits for before it opens. At once when none is on screen.
79
+ */
80
+ firstScreenful: Promise<void>;
81
+ /** Resolves when every picture has been answered (or the board was replaced), and the ones that were found are on the board. */
82
+ everything: Promise<void>;
83
+ }
84
+ /**
85
+ * Asks the store for the missing pictures, a few at a time and in the order of `PictureQueue`, and puts what comes in on the board
86
+ * in small batches. Never throws: a picture the store cannot give is a warning, and the others go on.
87
+ */
88
+ export declare function startLoadingPictures(plan: PictureLoadPlan): PictureLoad;
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Reading the pictures that a saved board only points at, when the board is opened.
3
+ *
4
+ * A saved board does not hold the bytes of its pictures (an image, the screenshot of a widget card): it holds a reference, and
5
+ * the page's store (`ShapeImageStore`) turns the reference into the picture. The host used to ask the store for every
6
+ * reference at once and to keep the board shut until the last answer came, so a board of a thousand cards opened as slowly as
7
+ * its slowest picture, and the pictures that were on screen waited for the ones that were not. Now:
8
+ *
9
+ * - the pictures that are on screen are asked for first, the nearest to the middle of the view first, and the board opens as
10
+ * soon as those are in (`firstScreenful`);
11
+ * - the others are asked for after them, in the background, the nearest to the view first, and that order follows the view
12
+ * when it moves (a pan during the load puts the pictures of the place it went to in front); they are not asked for while a
13
+ * picture on screen is still on its way, so that those have the store and the network to themselves (for a few seconds at
14
+ * most: one that hangs must not hold the rest back);
15
+ * - only a few are asked for at a time (`PICTURE_LOAD_CONCURRENCY`), so that the pictures that matter do not share the store
16
+ * and the network with a thousand that do not;
17
+ * - what comes in is put on the board in small batches: not one by one, and not all at the end.
18
+ *
19
+ * Plain TypeScript over the engine's records, so that Node can test it.
20
+ */
21
+ import { rectsIntersect } from '../../engine/core/geometry.js';
22
+ import { shapeVisualBounds } from '../../engine/core/scene.js';
23
+ /** How many pictures are asked of the store at the same time. */
24
+ export const PICTURE_LOAD_CONCURRENCY = 6;
25
+ /** How long the pictures that came in are kept before they are put on the board together (so that a burst is one change, not forty). */
26
+ export const PICTURE_APPLY_DELAY_MS = 40;
27
+ /**
28
+ * How long the pictures that are not on screen wait for the ones that are, at most. They wait for them to come in, so that the
29
+ * store and the network are the on-screen pictures' alone; one that hangs must not hold back the rest of the board for ever.
30
+ */
31
+ export const PICTURE_BACKGROUND_GRACE_MS = 3000;
32
+ /** The objects of a scene that point at a picture and do not hold its bytes, in the order of the scene. */
33
+ export function picturesStillMissing(scene) {
34
+ const missing = [];
35
+ for (const object of scene) {
36
+ if (object.type === 'image' && !object.src && object.imageRef) {
37
+ missing.push({ objectId: object.id, reference: object.imageRef, bounds: shapeVisualBounds(object) });
38
+ }
39
+ else if (object.type === 'widget' && !object.thumbnail && object.thumbnailRef) {
40
+ missing.push({ objectId: object.id, reference: object.thumbnailRef, bounds: shapeVisualBounds(object) });
41
+ }
42
+ }
43
+ return missing;
44
+ }
45
+ /**
46
+ * A scene with the pictures that came in put into the objects that were waiting for exactly that picture. An object that holds a
47
+ * picture by now (the person put another one there), or points at another reference, or is gone, is left as it is. The very same
48
+ * scene when nothing changed.
49
+ */
50
+ export function fillPictures(scene, loaded) {
51
+ if (loaded.size === 0)
52
+ return scene;
53
+ let changed = false;
54
+ const filled = scene.map((object) => {
55
+ const picture = loaded.get(object.id);
56
+ if (!picture)
57
+ return object;
58
+ if (object.type === 'image' && !object.src && object.imageRef === picture.reference) {
59
+ changed = true;
60
+ return { ...object, src: picture.dataUrl };
61
+ }
62
+ if (object.type === 'widget' && !object.thumbnail && object.thumbnailRef === picture.reference) {
63
+ changed = true;
64
+ return { ...object, thumbnail: picture.dataUrl };
65
+ }
66
+ return object;
67
+ });
68
+ return changed ? filled : scene;
69
+ }
70
+ /**
71
+ * Waits for a promise for at most `milliseconds`. True when it finished in time, false when the time ran out first (the promise is
72
+ * not stopped: whatever it was doing goes on). A promise that fails counts as finished: the caller only wanted to know that it is over.
73
+ */
74
+ export async function waitUpTo(promise, milliseconds) {
75
+ let timeRanOut = () => undefined;
76
+ const timeUp = new Promise((resolve) => {
77
+ timeRanOut = () => resolve(false);
78
+ });
79
+ const timer = setTimeout(() => timeRanOut(), milliseconds);
80
+ try {
81
+ return await Promise.race([promise.then(() => true, () => true), timeUp]);
82
+ }
83
+ finally {
84
+ clearTimeout(timer);
85
+ }
86
+ }
87
+ /** A rectangle made of finite numbers with some size: anything else says the board has no size (or no view) yet. */
88
+ export function isUsableView(view) {
89
+ return !!view && Number.isFinite(view.x) && Number.isFinite(view.y) && Number.isFinite(view.width) && Number.isFinite(view.height) && view.width > 0 && view.height > 0;
90
+ }
91
+ /** How many of the pictures are of objects that touch the view. All of them when the view is not known: nothing is known to be far. */
92
+ export function countPicturesInView(missing, view) {
93
+ if (!isUsableView(view))
94
+ return missing.length;
95
+ let count = 0;
96
+ for (const picture of missing) {
97
+ if (rectsIntersect(view, picture.bounds))
98
+ count += 1;
99
+ }
100
+ return count;
101
+ }
102
+ /**
103
+ * The pictures still to be asked for, handing out the one to ask next: the ones of objects that touch the view first, the nearest
104
+ * to the middle of the view first among those and among the others. The order is made again when the view has moved by a quarter
105
+ * of itself or changed its size by a quarter (not at every pan frame, and not at every picture), and it is the scene's own order
106
+ * when the view is not known.
107
+ */
108
+ export class PictureQueue {
109
+ // Kept with the best one last, so that handing it out is a `pop`.
110
+ #waiting;
111
+ // Where each picture was in the scene: what breaks a tie, and what a picture that is given back keeps.
112
+ #positions = new Map();
113
+ #orderedFor = null;
114
+ constructor(missing) {
115
+ this.#waiting = missing.map((picture, position) => ({ picture, position })).reverse();
116
+ for (const { picture, position } of this.#waiting)
117
+ this.#positions.set(picture, position);
118
+ }
119
+ /** How many are still to be asked for. */
120
+ get length() {
121
+ return this.#waiting.length;
122
+ }
123
+ /** The picture to ask for next, or undefined when none is left. */
124
+ take(view) {
125
+ if (isUsableView(view) && this.#needsOrderingFor(view))
126
+ this.#orderFor(view);
127
+ return this.#waiting.pop()?.picture;
128
+ }
129
+ /** Puts back a picture that was taken and not asked for after all: it is the next one to be handed out (it was the best). */
130
+ giveBack(picture) {
131
+ this.#waiting.push({ picture, position: this.#positions.get(picture) ?? 0 });
132
+ }
133
+ #needsOrderingFor(view) {
134
+ const last = this.#orderedFor;
135
+ if (last === null)
136
+ return true;
137
+ return (Math.abs(view.x - last.x) > last.width * 0.25 ||
138
+ Math.abs(view.y - last.y) > last.height * 0.25 ||
139
+ view.width > last.width * 1.25 ||
140
+ view.width < last.width * 0.8);
141
+ }
142
+ #orderFor(view) {
143
+ this.#orderedFor = view;
144
+ const middleX = view.x + view.width / 2;
145
+ const middleY = view.y + view.height / 2;
146
+ // Squared distances stay far below this, so adding it puts every picture that is off the view after every one that is on it.
147
+ const OFF_THE_VIEW = 1e18;
148
+ const ranked = this.#waiting.map((entry) => {
149
+ const bounds = entry.picture.bounds;
150
+ const offsetX = bounds.x + bounds.width / 2 - middleX;
151
+ const offsetY = bounds.y + bounds.height / 2 - middleY;
152
+ return { entry, rank: (rectsIntersect(view, bounds) ? 0 : OFF_THE_VIEW) + offsetX * offsetX + offsetY * offsetY };
153
+ });
154
+ // The worst first and, among equals, the one that was later in the scene first: the last one is the best, and the earliest of equals.
155
+ ranked.sort((first, second) => second.rank - first.rank || second.entry.position - first.entry.position);
156
+ this.#waiting = ranked.map((item) => item.entry);
157
+ }
158
+ }
159
+ /**
160
+ * Asks the store for the missing pictures, a few at a time and in the order of `PictureQueue`, and puts what comes in on the board
161
+ * in small batches. Never throws: a picture the store cannot give is a warning, and the others go on.
162
+ */
163
+ export function startLoadingPictures(plan) {
164
+ const concurrency = Math.max(1, plan.concurrency ?? PICTURE_LOAD_CONCURRENCY);
165
+ const applyDelayMs = plan.applyDelayMs ?? PICTURE_APPLY_DELAY_MS;
166
+ const backgroundGraceMs = plan.backgroundGraceMs ?? PICTURE_BACKGROUND_GRACE_MS;
167
+ const queue = new PictureQueue(plan.missing);
168
+ const arrived = new Map();
169
+ const requests = new Map();
170
+ const failedReferences = new Set();
171
+ let applyTimer = null;
172
+ let boardOpened = false;
173
+ let finishFirstScreenful = () => undefined;
174
+ const firstScreenful = new Promise((resolve) => {
175
+ finishFirstScreenful = resolve;
176
+ });
177
+ // The pictures of objects that are on screen and are being asked for right now, and the workers that hold back a picture of an
178
+ // object that is not on screen until those are answered (or until `letBackgroundStart`).
179
+ let onScreenInFlight = 0;
180
+ let backgroundMayStart = false;
181
+ let workersHeldBack = [];
182
+ let graceTimer = null;
183
+ function letBackgroundStart() {
184
+ backgroundMayStart = true;
185
+ const held = workersHeldBack;
186
+ workersHeldBack = [];
187
+ for (const release of held)
188
+ release();
189
+ }
190
+ function putArrivedOnTheBoard() {
191
+ if (applyTimer !== null) {
192
+ clearTimeout(applyTimer);
193
+ applyTimer = null;
194
+ }
195
+ if (arrived.size === 0)
196
+ return;
197
+ const batch = new Map(arrived);
198
+ arrived.clear();
199
+ if (plan.isCancelled())
200
+ return;
201
+ try {
202
+ plan.apply(batch);
203
+ }
204
+ catch (error) {
205
+ plan.warn('Canvas: pictures that came in could not be put on the board', error);
206
+ }
207
+ }
208
+ /** The pictures of the objects that are on screen are all in: what they gave is on the board, the board opens, the rest is asked for. */
209
+ function openTheBoard() {
210
+ if (boardOpened)
211
+ return;
212
+ boardOpened = true;
213
+ putArrivedOnTheBoard();
214
+ finishFirstScreenful();
215
+ letBackgroundStart();
216
+ }
217
+ async function work() {
218
+ for (;;) {
219
+ if (plan.isCancelled())
220
+ return;
221
+ const view = plan.currentView();
222
+ const picture = queue.take(view);
223
+ if (!picture)
224
+ return;
225
+ const onScreen = !isUsableView(view) || rectsIntersect(view, picture.bounds);
226
+ if (!onScreen) {
227
+ // The queue hands out the pictures of objects that are on screen first, so this one coming up means none of them is left to
228
+ // be asked for. When none is on its way either, they are all in: the board opens. Otherwise the ones on their way have the
229
+ // store and the network to themselves until they are answered (or the grace is over: one that hangs must not hold the rest
230
+ // of the board back for ever).
231
+ if (onScreenInFlight === 0) {
232
+ openTheBoard();
233
+ }
234
+ else if (!backgroundMayStart) {
235
+ queue.giveBack(picture);
236
+ graceTimer ??= setTimeout(letBackgroundStart, backgroundGraceMs);
237
+ await new Promise((resolve) => workersHeldBack.push(resolve));
238
+ continue;
239
+ }
240
+ }
241
+ else {
242
+ onScreenInFlight += 1;
243
+ }
244
+ try {
245
+ // One question per reference: a picture that several objects point at is read once and given to each of them.
246
+ let request = requests.get(picture.reference);
247
+ if (!request) {
248
+ request = plan.store.load(picture.reference, { priority: onScreen ? 'visible' : 'background' });
249
+ requests.set(picture.reference, request);
250
+ }
251
+ const dataUrl = await request;
252
+ if (dataUrl) {
253
+ arrived.set(picture.objectId, { reference: picture.reference, dataUrl });
254
+ if (applyTimer === null)
255
+ applyTimer = setTimeout(putArrivedOnTheBoard, applyDelayMs);
256
+ }
257
+ }
258
+ catch (error) {
259
+ // Said once for a reference, not once for each object that points at it.
260
+ if (!failedReferences.has(picture.reference)) {
261
+ failedReferences.add(picture.reference);
262
+ plan.warn('Canvas: a stored picture could not be read', picture.reference, error);
263
+ }
264
+ }
265
+ finally {
266
+ if (onScreen) {
267
+ onScreenInFlight -= 1;
268
+ // Workers are held back only by a picture that is not on screen, so there is none on screen left to be asked for.
269
+ if (onScreenInFlight === 0 && workersHeldBack.length > 0)
270
+ openTheBoard();
271
+ }
272
+ }
273
+ }
274
+ }
275
+ const workerCount = Math.min(concurrency, plan.missing.length);
276
+ const everything = Promise.all(Array.from({ length: workerCount }, () => work()))
277
+ // Nothing above throws, but a board that is opened must never be left waiting for a promise that fails.
278
+ .catch((error) => plan.warn('Canvas: reading the stored pictures stopped early', error))
279
+ .then(() => {
280
+ if (graceTimer !== null)
281
+ clearTimeout(graceTimer);
282
+ // What is still waiting for its batch goes on the board now, and nothing is left to wait for: everything is answered (or the
283
+ // board was replaced, or there was nothing to read).
284
+ putArrivedOnTheBoard();
285
+ openTheBoard();
286
+ });
287
+ return { firstScreenful, everything };
288
+ }
@@ -15,5 +15,5 @@ export type { PanZoomPosition } from './panZoomPosition';
15
15
  export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
16
16
  export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
17
17
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
18
- export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
18
+ export { setShapeImageStore, getShapeImageStore, SHAPE_IMAGE_STORE_OBJECT_URLS } from './shapes/shapeImageStore';
19
19
  export type { ShapeImageStore } from './shapes/shapeImageStore';
@@ -13,4 +13,4 @@ export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './toolbarPosition';
13
13
  export { PAN_ZOOM_POSITIONS, DEFAULT_PAN_ZOOM_POSITION } from './panZoomPosition';
14
14
  export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
15
15
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
16
- export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
16
+ export { setShapeImageStore, getShapeImageStore, SHAPE_IMAGE_STORE_OBJECT_URLS } from './shapes/shapeImageStore';