@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
@@ -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
+ }
@@ -13,7 +13,8 @@ export type { ToolbarPosition } from './toolbarPosition';
13
13
  export { PAN_ZOOM_POSITIONS, DEFAULT_PAN_ZOOM_POSITION } from './panZoomPosition';
14
14
  export type { PanZoomPosition } from './panZoomPosition';
15
15
  export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
16
+ export type { CanvasFlyOptions, CanvasMoveOptions } from './types';
16
17
  export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
17
18
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
18
- export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
19
+ export { setShapeImageStore, getShapeImageStore, SHAPE_IMAGE_STORE_OBJECT_URLS } from './shapes/shapeImageStore';
19
20
  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';
@@ -16,15 +16,58 @@
16
16
  * With no store installed nothing changes — shapes keep serializing inline, so
17
17
  * a consumer that has not wired one up is never left with blank shapes.
18
18
  */
19
+ /**
20
+ * What the canvas tells the store about a read, when it knows (see `ShapeImageStore.load`).
21
+ *
22
+ * `visible`: the picture is on screen right now, and the person is looking at its place: answer as soon as you can.
23
+ * `background`: the picture is of an object that is off the screen, asked for ahead of time: nobody is waiting for it, so a
24
+ * store that has a queue, a network or a limit of its own may serve it after the ones that are `visible`. It must still
25
+ * answer: a board that is panned to it expects its picture to be there, or on its way.
26
+ */
27
+ export interface ShapeImageLoadOptions {
28
+ priority?: 'visible' | 'background';
29
+ }
19
30
  export interface ShapeImageStore {
20
31
  /**
21
32
  * Persist the bytes for a reference. Called during serialization, so it must
22
33
  * return immediately — write in the background and swallow failures.
23
34
  */
24
35
  save(ref: string, dataUrl: string): void;
25
- /** Resolve a reference to a data URL or any URL an `Image` can load. */
26
- load(ref: string): Promise<string | null>;
36
+ /**
37
+ * Resolve a reference to a data URL or any URL an `Image` can load.
38
+ *
39
+ * An object URL (`blob:`) is a good answer for a picture that is big: the board holds a short address instead of megabytes of
40
+ * text, and the browser reads the bytes where it keeps them. The canvas never writes one into the saved text (it writes the
41
+ * reference, which the store resolves again at the next load), so the store may hand out one it will not be able to hand out
42
+ * again after a reload. What a `blob:` address cannot do is leave the page: a card whose screenshot is one is not answered by
43
+ * `getWidgetShapeDataUrl` (it needs bytes), so a store gives `blob:` addresses for the pictures of the person's own and
44
+ * bytes for the screenshots of widget cards, unless the page that asks for the bytes can read an object URL.
45
+ *
46
+ * The canvas asks for the pictures on screen first, a few at a time, and for the others after them; the second argument says
47
+ * which kind this one is. A store written before the argument existed ignores it, which is fine.
48
+ */
49
+ load(ref: string, options?: ShapeImageLoadOptions): Promise<string | null>;
50
+ /**
51
+ * Optional. A picture the person has just put on the board (dropped, pasted or chosen), as bytes (a data URL).
52
+ *
53
+ * The store may keep the bytes under `ref` (as `save` does) and answer with a short address, an object URL (`blob:`), for the
54
+ * board to hold instead of the text: the board then never holds the megabytes, and the picture is the store's from the first
55
+ * moment, so the saved text carries the reference only. Answer `null` to leave the picture as it is (a small one, a page that
56
+ * cannot show an object URL, a limit reached, nowhere to keep the bytes yet): the canvas then keeps the bytes inline, and the
57
+ * next save hands them to `save` as it always did. When this answers with an address the bytes MUST have been kept: the canvas
58
+ * will not offer them again. It must return at once and never throw (a throw is treated as `null`).
59
+ *
60
+ * A store written before this existed has no `adopt`, and nothing changes for it.
61
+ */
62
+ adopt?(ref: string, dataUrl: string): string | null;
27
63
  }
64
+ /**
65
+ * Whether this canvas knows what to do with an object URL (`blob:`) that a store gives for a reference: it keeps the address for as
66
+ * long as the page lives, and writes the reference in the saved text, never the address (see `externalizeBytes`). A page that
67
+ * wants to give object URLs asks for this first, so that a page updated before the canvas is does not get a saved board with
68
+ * addresses in it that no other page can read.
69
+ */
70
+ export declare const SHAPE_IMAGE_STORE_OBJECT_URLS = true;
28
71
  export declare function setShapeImageStore(store: ShapeImageStore | null): void;
29
72
  export declare function getShapeImageStore(): ShapeImageStore | null;
30
73
  /** Inline bytes — the thing that must not reach the canvas JSON. */
@@ -16,6 +16,13 @@
16
16
  * With no store installed nothing changes — shapes keep serializing inline, so
17
17
  * a consumer that has not wired one up is never left with blank shapes.
18
18
  */
19
+ /**
20
+ * Whether this canvas knows what to do with an object URL (`blob:`) that a store gives for a reference: it keeps the address for as
21
+ * long as the page lives, and writes the reference in the saved text, never the address (see `externalizeBytes`). A page that
22
+ * wants to give object URLs asks for this first, so that a page updated before the canvas is does not get a saved board with
23
+ * addresses in it that no other page can read.
24
+ */
25
+ export const SHAPE_IMAGE_STORE_OBJECT_URLS = true;
19
26
  let installedStore = null;
20
27
  export function setShapeImageStore(store) {
21
28
  installedStore = store;
@@ -4,8 +4,8 @@
4
4
  * The toolbar has always been at the bottom centre. A host that has something of its own there (Shopify's Sidekick sits in
5
5
  * the same spot, a partner may have a cookie bar or a chat bubble) names another anchor with the `toolbarPosition` option:
6
6
  * any of the eight places `chromeLayout.ts` describes (the top edge, the bottom edge, or the middle of the left or right
7
- * edge, where the toolbar stands upright). The selector bar that replaces the toolbar after the first generation stands in
8
- * the same place, so the two never jump around when one takes over from the other.
7
+ * edge, where the toolbar stands upright). The toolbar stays where it is for the life of the board: the selector's
8
+ * indicator is a card of its own at the top centre (below the toolbar when a host put the toolbar there).
9
9
  *
10
10
  * Kept free of Svelte and of the DOM so that Node can test it.
11
11
  */
@@ -4,8 +4,8 @@
4
4
  * The toolbar has always been at the bottom centre. A host that has something of its own there (Shopify's Sidekick sits in
5
5
  * the same spot, a partner may have a cookie bar or a chat bubble) names another anchor with the `toolbarPosition` option:
6
6
  * any of the eight places `chromeLayout.ts` describes (the top edge, the bottom edge, or the middle of the left or right
7
- * edge, where the toolbar stands upright). The selector bar that replaces the toolbar after the first generation stands in
8
- * the same place, so the two never jump around when one takes over from the other.
7
+ * edge, where the toolbar stands upright). The toolbar stays where it is for the life of the board: the selector's
8
+ * indicator is a card of its own at the top centre (below the toolbar when a host put the toolbar there).
9
9
  *
10
10
  * Kept free of Svelte and of the DOM so that Node can test it.
11
11
  */
@@ -3,6 +3,7 @@
3
3
  * Importable by both the canvas project and consuming apps (e.g. widget-creator).
4
4
  */
5
5
  import type { CanvasSnapShape, SnapRanking, StrokeMeasurements } from './shapes/strokeShapeSnap';
6
+ import type { ViewMoveOptions } from '../engine/EngineCore.js';
6
7
  /** Payload emitted when a frame is converted to a widget via onConvertToWidget callback. */
7
8
  export interface WidgetConversionPayload {
8
9
  frameName: string;
@@ -77,3 +78,19 @@ export interface StrokeRecognitionResult {
77
78
  }
78
79
  /** The recognizer a host supplies to enable stroke snapping. */
79
80
  export type StrokeRecognizer = (request: StrokeRecognitionRequest) => Promise<StrokeRecognitionResult | null>;
81
+ /**
82
+ * How a move of the view goes (`flyToPoint`, `flyToObjects`, `flyToContent`): a page can set how long it takes, the shape of the
83
+ * motion (`easing`), whether the position and the zoom ease together or the view flies (`path`: `'ease'`, the default, or `'fly'`),
84
+ * and be told when it is over (and whether the view arrived or the person took it first).
85
+ */
86
+ export type CanvasMoveOptions = ViewMoveOptions;
87
+ /** What `flyToPoint` and `flyToObjects` take besides how the move goes: the zoom to arrive at. */
88
+ export interface CanvasFlyOptions extends CanvasMoveOptions {
89
+ /**
90
+ * The zoom to arrive at, in percent as `zoomTo` takes it (100 is 100%). Left out: `flyToObjects` fits the objects to the board
91
+ * (never past 200%) and `flyToPoint` keeps the zoom the board has.
92
+ */
93
+ zoomPercent?: number;
94
+ /** Keeps the zoom the board has and only moves to the place (`flyToObjects` would otherwise fit the objects to the board). Wins over `zoomPercent`. */
95
+ keepZoom?: boolean;
96
+ }
@@ -104,10 +104,15 @@
104
104
  data-canvas-color-picker-trigger
105
105
  aria-label="{label}: {fieldText}"
106
106
  title={$t('canvas.panel.pickColor')}
107
- class="flex h-9 w-[185px] min-h-9 items-center justify-between gap-2 rounded-lg bg-accent py-0 ps-3 pe-2 text-body text-foreground transition-colors duration-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:ring-2 data-[state=open]:ring-ring"
107
+ class="group/color-field flex h-9 w-[185px] min-h-9 items-center justify-between gap-2 rounded-lg bg-accent py-0 ps-3 pe-2 text-body text-foreground transition-colors duration-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:ring-2 data-[state=open]:ring-ring"
108
108
  >
109
109
  <span class="truncate tabular-nums">{fieldText}</span>
110
- <span class="size-5 shrink-0 rounded-md border border-border" style:background={swatchBackground}></span>
110
+ <!-- The press cue is the swatch shrinking a little, never the field: a field is a component, and only a real button or a
111
+ small icon inside a component shrinks when it is pressed. A person who asks for less motion gets no shrink. -->
112
+ <span
113
+ class="size-5 shrink-0 rounded-md border border-border transition-transform duration-fast ease-out group-active/color-field:scale-90 motion-reduce:transition-none motion-reduce:group-active/color-field:scale-100"
114
+ style:background={swatchBackground}
115
+ ></span>
111
116
  </button>
112
117
  {/snippet}
113
118
  </Popover.Trigger>
@@ -11,14 +11,16 @@
11
11
  is still being dragged is one step of the history, taken when it ends.
12
12
 
13
13
  A selection shows a settings control at the corner; it opens the panel, and the close button collapses it again without
14
- changing when the selection changes. It stands
14
+ changing when the selection changes. Nothing opens the panel by itself, not a selection and not a text: it is closed by
15
+ default, it stays as the person left it while the selection moves from one object to another, and it goes back to the
16
+ settings control when nothing is selected any more (the host does that, see `#onEngineState`). It stands
15
17
  in the top corner at the end of the line, and keeps clear of the cards the page put there: below the ones on the top
16
18
  edge, and beside an upright one on the right edge (see `PanelClearance`).
17
19
  -->
18
20
  <script lang="ts">
19
21
  import { onDestroy } from 'svelte';
20
22
  import type { Attachment } from 'svelte/attachments';
21
- import { IconButton, NumberStepper, Select, Slider } from '@widgetic/design-system/components';
23
+ import { IconButton, NumberControls, Select, Slider } from '@widgetic/design-system/components';
22
24
  import type { StylePatch } from '../../engine/core/style.js';
23
25
  import type { EngineState } from '../../engine/state.js';
24
26
  import { useCanvasLanguage } from '../../i18n/language.js';
@@ -53,9 +55,16 @@
53
55
  canOpenDetails: boolean;
54
56
  /** What the panel keeps clear of: the cards that stand on the top edge, and an upright one on the right edge. */
55
57
  clearance: PanelClearance;
58
+ /**
59
+ * A selected widget card (one whose widget is there) has no settings: no settings control at the corner and no panel.
60
+ * Its name, its id and its preview belong to the page's own chrome. A card whose widget is gone is left out of this: the
61
+ * panel's rule for a lone card (`shouldOfferSelectionPanelForTraits`) applies to it, and the card itself says so and
62
+ * offers the way to take it off the board.
63
+ */
64
+ widgetCardHasNoSettings?: boolean;
56
65
  }
57
66
 
58
- let { host, state, ui, wireframeMode, canCapture, canConvert, canRename, canRefresh, canOpenDetails, clearance }: Props = $props();
67
+ let { host, state, ui, wireframeMode, canCapture, canConvert, canRename, canRefresh, canOpenDetails, clearance, widgetCardHasNoSettings = false }: Props = $props();
59
68
 
60
69
  const { t } = useCanvasLanguage();
61
70
  const floatingLayer = useFloatingLayer();
@@ -118,15 +127,22 @@
118
127
  * Gives the thumb of a design-system slider the name of its row. The slider draws its thumb itself and takes no name for
119
128
  * it, so a screen reader would say "slider" and nothing more (the group around it is not the thumb's name). The thumb is
120
129
  * found by its role, and again if the slider draws it anew.
130
+ *
131
+ * The slider also writes the attributes of its thumb again after the thumb is drawn, and that takes the name away (found with the
132
+ * accessibility check: the thumbs were named for an instant, and then said "slider" and nothing more). So the name is put back
133
+ * when the thumb loses it, not only when it appears. A thumb that already has the name is not written to: a write that changes
134
+ * nothing is a change to the observer, and the observer would then go round and round.
121
135
  */
122
136
  function nameSliderThumb(name: string): Attachment<HTMLElement> {
123
137
  return (row) => {
124
138
  const applyName = (): void => {
125
- for (const thumb of row.querySelectorAll('[role="slider"]')) thumb.setAttribute('aria-label', name);
139
+ for (const thumb of row.querySelectorAll('[role="slider"]')) {
140
+ if (thumb.getAttribute('aria-label') !== name) thumb.setAttribute('aria-label', name);
141
+ }
126
142
  };
127
143
  applyName();
128
144
  const observer = new MutationObserver(applyName);
129
- observer.observe(row, { childList: true, subtree: true });
145
+ observer.observe(row, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-label'] });
130
146
  return () => observer.disconnect();
131
147
  };
132
148
  }
@@ -152,8 +168,15 @@
152
168
  const strokeWidthValue = $derived(traitNumber(traits.strokeWidth, 0));
153
169
  const fontSizeValue = $derived(traits.text ? traitNumber(traits.text.fontSize, 16) : 16);
154
170
 
171
+ // The widget on the board is not edited here: a selected card whose widget is there has no settings control and no panel.
172
+ const selectionIsAWidgetWithoutSettings = $derived(
173
+ widgetCardHasNoSettings && traits.widgetCard !== null && !host.isCardOrphaned(traits.widgetCard)
174
+ );
175
+ // A lone widget card does not open the sketch settings panel on any board (`shouldOfferSelectionPanelForTraits`); on the
176
+ // simple board it does not even when the page can capture (`selectionIsAWidgetWithoutSettings`).
155
177
  const showPanel = $derived(
156
- (shouldOfferSelectionPanelForTraits(traits) && hasSelection) || (canCapture && !canConvert),
178
+ !selectionIsAWidgetWithoutSettings &&
179
+ ((shouldOfferSelectionPanelForTraits(traits) && hasSelection) || (canCapture && !canConvert))
157
180
  );
158
181
  const showFillColor = $derived(showFillColorRow(traits, wireframeMode));
159
182
  const showStrokeColor = $derived(showStrokeColorRow(traits, wireframeMode));
@@ -211,19 +234,20 @@
211
234
  {#if traits.strokeWidth.kind !== 'none'}
212
235
  <div class="flex h-9 w-full items-start" data-canvas-panel-row="strokeWidth">
213
236
  <span class="flex h-9 min-w-0 flex-1 items-center gap-1 text-body">{$t('canvas.panel.strokeWidth')}</span>
214
- <!-- The design system's number stepper (IC Number): the value can be typed or stepped, and the group names the two buttons after the row. -->
215
- <NumberStepper
216
- class="w-[185px]"
217
- label={$t('canvas.panel.strokeWidth')}
218
- decreaseLabel={$t('canvas.panel.decrease')}
219
- increaseLabel={$t('canvas.panel.increase')}
220
- value={traits.strokeWidth.kind === 'same' ? Number(strokeWidthValue.toFixed(1)) : null}
221
- fallbackValue={strokeWidthValue}
222
- min={0}
223
- max={200}
224
- step={1}
225
- onChange={(next) => changeStyle({ strokeWidth: next })}
226
- />
237
+ <!-- The design system's number control (IC Number), the one the editor draws: the value can be typed or stepped, and the group names the two buttons after the row. -->
238
+ <div class="w-[185px] shrink-0">
239
+ <NumberControls
240
+ label={$t('canvas.panel.strokeWidth')}
241
+ decreaseLabel={$t('canvas.panel.decrease')}
242
+ increaseLabel={$t('canvas.panel.increase')}
243
+ value={traits.strokeWidth.kind === 'same' ? Number(strokeWidthValue.toFixed(1)) : null}
244
+ fallbackValue={strokeWidthValue}
245
+ min={0}
246
+ max={200}
247
+ step={1}
248
+ onChange={(next) => changeStyle({ strokeWidth: next })}
249
+ />
250
+ </div>
227
251
  </div>
228
252
  {/if}
229
253
 
@@ -293,18 +317,19 @@
293
317
 
294
318
  <div class="flex h-9 w-full items-start">
295
319
  <span class="flex h-9 min-w-0 flex-1 items-center gap-1 text-body">{$t('canvas.panel.fontSize')}</span>
296
- <NumberStepper
297
- class="w-[185px]"
298
- label={$t('canvas.panel.fontSize')}
299
- decreaseLabel={$t('canvas.panel.decrease')}
300
- increaseLabel={$t('canvas.panel.increase')}
301
- value={typeof fontSizeDisplay === 'number' ? fontSizeDisplay : null}
302
- fallbackValue={fontSizeValue}
303
- min={8}
304
- max={200}
305
- step={1}
306
- onChange={(next) => changeStyle({ fontSize: next })}
307
- />
320
+ <div class="w-[185px] shrink-0">
321
+ <NumberControls
322
+ label={$t('canvas.panel.fontSize')}
323
+ decreaseLabel={$t('canvas.panel.decrease')}
324
+ increaseLabel={$t('canvas.panel.increase')}
325
+ value={typeof fontSizeDisplay === 'number' ? fontSizeDisplay : null}
326
+ fallbackValue={fontSizeValue}
327
+ min={8}
328
+ max={200}
329
+ step={1}
330
+ onChange={(next) => changeStyle({ fontSize: next })}
331
+ />
332
+ </div>
308
333
  </div>
309
334
 
310
335
  <div class="flex items-center justify-between gap-1" role="group" aria-label={$t('canvas.control.textStyle')}>
@@ -14,6 +14,13 @@ interface Props {
14
14
  canOpenDetails: boolean;
15
15
  /** What the panel keeps clear of: the cards that stand on the top edge, and an upright one on the right edge. */
16
16
  clearance: PanelClearance;
17
+ /**
18
+ * A selected widget card (one whose widget is there) has no settings: no settings control at the corner and no panel.
19
+ * Its name, its id and its preview belong to the page's own chrome. A card whose widget is gone is left out of this: the
20
+ * panel's rule for a lone card (`shouldOfferSelectionPanelForTraits`) applies to it, and the card itself says so and
21
+ * offers the way to take it off the board.
22
+ */
23
+ widgetCardHasNoSettings?: boolean;
17
24
  }
18
25
  declare const SelectionPanel: import("svelte").Component<Props, {}, "">;
19
26
  type SelectionPanel = ReturnType<typeof SelectionPanel>;