@widgetic/canvas 0.5.44 → 0.5.46

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 (107) hide show
  1. package/README.md +1 -1
  2. package/dist/canvas/DomCanvas.svelte +52 -3
  3. package/dist/canvas/DomCanvas.svelte.d.ts +59 -34
  4. package/dist/canvas/host/CanvasHost.d.ts +74 -3
  5. package/dist/canvas/host/CanvasHost.js +278 -16
  6. package/dist/canvas/host/CanvasHostApi.d.ts +2 -2
  7. package/dist/canvas/host/CanvasHostApi.js +9 -1
  8. package/dist/canvas/host/boardFiles.d.ts +90 -0
  9. package/dist/canvas/host/boardFiles.js +139 -0
  10. package/dist/canvas/host/browserServices.d.ts +17 -0
  11. package/dist/canvas/host/browserServices.js +58 -0
  12. package/dist/canvas/index.d.ts +2 -1
  13. package/dist/canvas/types.d.ts +7 -1
  14. package/dist/canvas/ui/CanvasContextMenu.svelte +7 -0
  15. package/dist/canvas/ui/CanvasToolbar.svelte +4 -1
  16. package/dist/canvas/ui/CanvasToolbar.svelte.d.ts +2 -0
  17. package/dist/canvas/ui/SelectionPanel.svelte +78 -17
  18. package/dist/canvas/ui/ShapesMenu.svelte +65 -31
  19. package/dist/canvas/ui/ShapesMenu.svelte.d.ts +2 -0
  20. package/dist/canvas/ui/ShortcutTooltip.svelte +64 -0
  21. package/dist/canvas/ui/ShortcutTooltip.svelte.d.ts +24 -0
  22. package/dist/canvas/ui/ToolButton.svelte +34 -55
  23. package/dist/canvas/ui/ToolButton.svelte.d.ts +4 -1
  24. package/dist/canvas/ui/floatingCard.d.ts +26 -4
  25. package/dist/canvas/ui/floatingCard.js +26 -4
  26. package/dist/canvas/ui/icons.d.ts +1 -1
  27. package/dist/canvas/ui/icons.js +1 -1
  28. package/dist/canvas/ui/selectionTraits.d.ts +12 -0
  29. package/dist/canvas/ui/selectionTraits.js +26 -1
  30. package/dist/canvas/ui/sizeLabelVisibility.d.ts +4 -2
  31. package/dist/canvas/ui/sizeLabelVisibility.js +5 -5
  32. package/dist/canvas/view/CanvasStage.svelte +7 -2
  33. package/dist/canvas/view/CanvasStage.svelte.d.ts +2 -0
  34. package/dist/canvas/view/SelectionOverlay.svelte +17 -10
  35. package/dist/canvas/view/WidgetChromeLayer.svelte +15 -3
  36. package/dist/canvas/view/geometry.d.ts +1 -1
  37. package/dist/canvas/view/geometry.js +1 -1
  38. package/dist/components/CanvasBoardPlaceholder.svelte +68 -10
  39. package/dist/components/CanvasBoardPlaceholder.svelte.d.ts +10 -2
  40. package/dist/components/CanvasBoardPoster.svelte +206 -0
  41. package/dist/components/CanvasBoardPoster.svelte.d.ts +17 -0
  42. package/dist/components/CanvasToolbarPlaceholder.svelte +129 -0
  43. package/dist/components/CanvasToolbarPlaceholder.svelte.d.ts +15 -0
  44. package/dist/components/boardLoaderDelay.d.ts +39 -0
  45. package/dist/components/boardLoaderDelay.js +71 -0
  46. package/dist/components/index.d.ts +7 -0
  47. package/dist/components/index.js +8 -0
  48. package/dist/engine/EngineCore.d.ts +46 -4
  49. package/dist/engine/EngineCore.js +85 -16
  50. package/dist/engine/codec/canvasDocument.d.ts +7 -0
  51. package/dist/engine/codec/canvasDocument.js +25 -2
  52. package/dist/engine/core/arrow.d.ts +18 -8
  53. package/dist/engine/core/arrow.js +24 -12
  54. package/dist/engine/core/arrowBinding.d.ts +1 -1
  55. package/dist/engine/core/arrowBinding.js +10 -3
  56. package/dist/engine/core/arrowBindingRecords.d.ts +9 -3
  57. package/dist/engine/core/arrowBindingRecords.js +10 -6
  58. package/dist/engine/core/brush.d.ts +8 -0
  59. package/dist/engine/core/brush.js +10 -2
  60. package/dist/engine/core/cameraMove.d.ts +6 -0
  61. package/dist/engine/core/cameraMove.js +6 -0
  62. package/dist/engine/core/defaults.js +2 -0
  63. package/dist/engine/core/scene.d.ts +22 -0
  64. package/dist/engine/core/scene.js +86 -1
  65. package/dist/engine/core/style.d.ts +10 -0
  66. package/dist/engine/core/style.js +19 -3
  67. package/dist/engine/core/transform.d.ts +6 -0
  68. package/dist/engine/core/transform.js +9 -0
  69. package/dist/engine/core/types.d.ts +7 -0
  70. package/dist/engine/input/PointerController.d.ts +15 -1
  71. package/dist/engine/input/PointerController.js +70 -12
  72. package/dist/engine/input/gestures.d.ts +3 -1
  73. package/dist/engine/input/gestures.js +41 -10
  74. package/dist/engine/input/keyboard.d.ts +22 -3
  75. package/dist/engine/input/keyboard.js +100 -5
  76. package/dist/engine/input/types.d.ts +7 -0
  77. package/dist/engine/state.d.ts +18 -0
  78. package/dist/engine/state.js +10 -0
  79. package/dist/fonts/workspaceFonts.d.ts +6 -0
  80. package/dist/fonts/workspaceFonts.js +44 -29
  81. package/dist/i18n/language.d.ts +3 -3
  82. package/dist/i18n/messages.d.ts +6 -0
  83. package/dist/i18n/messages.js +6 -0
  84. package/dist/i18n/shortcuts.d.ts +6 -4
  85. package/dist/i18n/shortcuts.js +16 -12
  86. package/dist/index.d.ts +2 -1
  87. package/dist/poster/boardPlacement.d.ts +80 -0
  88. package/dist/poster/boardPlacement.js +138 -0
  89. package/dist/poster/boardPoster.d.ts +80 -0
  90. package/dist/poster/boardPoster.js +226 -0
  91. package/dist/poster/paintBoardPoster.d.ts +49 -0
  92. package/dist/poster/paintBoardPoster.js +89 -0
  93. package/dist/poster/posterPictures.d.ts +32 -0
  94. package/dist/poster/posterPictures.js +122 -0
  95. package/dist/settings/rememberedTool.d.ts +50 -0
  96. package/dist/settings/rememberedTool.js +68 -0
  97. package/dist/settings/workspaceToolSettings.d.ts +14 -0
  98. package/dist/settings/workspaceToolSettings.js +21 -10
  99. package/dist/tools/definitions.js +26 -4
  100. package/dist/tools/executors.js +81 -5
  101. package/dist/tools/hostAdapter.d.ts +5 -1
  102. package/dist/tools/hostAdapter.js +2 -0
  103. package/dist/tools/styleArguments.d.ts +35 -0
  104. package/dist/tools/styleArguments.js +91 -0
  105. package/dist/tools/types.d.ts +26 -1
  106. package/dist/tools/types.js +1 -0
  107. package/package.json +2 -2
@@ -14,22 +14,25 @@ import { createObjectId, createImageObject, createRectObject, TEXT_DEFAULTS } fr
14
14
  import { boundsOfObjects, shapeBounds } from '../../engine/core/scene.js';
15
15
  import { buildDraggedShape } from '../../engine/core/shapeTools.js';
16
16
  import { EngineCore } from '../../engine/EngineCore.js';
17
- import { releaseHeldKeys, routeKeyDown, routeKeyUp } from '../../engine/input/keyboard.js';
17
+ import { releaseHeldKeys, routeKeyDown, routeKeyUp, shapeShortcutOf } from '../../engine/input/keyboard.js';
18
18
  import { PointerController } from '../../engine/input/PointerController.js';
19
19
  import { renderShapesToDataUrl } from '../../engine/render/rasterize.js';
20
20
  import { layoutTextObject } from '../../engine/text/layoutText.js';
21
+ import { DEFAULT_PEN_STYLE } from '../../engine/state.js';
21
22
  import { ConversionRegistry, absorbSketchIntoWidget, addWidgetCard, commitWidgetCardMove, findWidgetCard, hydrateWidgetMetadata, keepOnlyWidgetCard, linkedWidgetIds, markOrphanedWidgetCards, moveWidgetCardByScreen, primaryWidgetId, removeSketchObjectsKeeping, replaceObjectWithWidgetCard, selectWidgetCard, selectedWidgetId, setPrimaryWidgetCard, updateWidgetThumbnail } from '../../engine/widgets.js';
22
23
  import { createAutosaveScheduler } from '../autosaveScheduler.js';
23
- import { readPreferredTextFontFamily, setWorkspaceFontFamilies, writePreferredTextFontFamily } from '../preferredTextFont.js';
24
+ import { fontFamiliesForPicker, readPreferredTextFontFamily, setWorkspaceFontFamilies, writePreferredTextFontFamily } from '../preferredTextFont.js';
24
25
  import { ensureInterFontLoaded } from '../../fonts/interFont.js';
25
26
  import { registerWorkspaceFonts } from '../../fonts/workspaceFonts.js';
26
27
  import { isCanvasOwnedTarget } from '../outsideClickDeselect.js';
27
28
  import { flushWorkspaceToolSettingsPending, loadWorkspaceToolSettings, saveWorkspaceToolSettingsDebounced } from '../../settings/workspaceToolSettings.js';
29
+ import { isDrawingGroupTool, readRememberedToolId, toolTheBoardOpensWith, toolToRemember } from '../../settings/rememberedTool.js';
28
30
  import { canvasLog, canvasWarn, setCanvasLogsEnabled } from '../canvasLogger.js';
29
31
  import { CANVAS_OPEN_MARKS, markCanvasOpenStep } from '../openMarks.js';
30
32
  import { eventIsForScope, getEventOrigin, shouldTakeFocusBack } from '../eventScope.js';
31
33
  import { getShapeImageStore, shapeImageRef } from '../shapes/shapeImageStore.js';
32
- import { chooseImageFiles, createBrowserMeasureText, createBrowserRasterServices, readImageFile } from './browserServices.js';
34
+ import { BOARD_FILE_KINDS, applyLibraryFile, normalizeLibraryFiles } from './boardFiles.js';
35
+ import { chooseImageFiles, createBrowserMeasureText, createBrowserRasterServices, readImageFile, readLibraryPicture } from './browserServices.js';
33
36
  import { buildCapturePayload } from './conversion.js';
34
37
  import { announceCanvasTool, announceSelectTool, announceWidgetPointerBlock } from './pageEvents.js';
35
38
  import { hostObjectById, selectedHostObject } from './hostObject.js';
@@ -74,6 +77,7 @@ export const DEFAULT_HOST_PROPS = Object.freeze({
74
77
  onRecognizeStroke: null,
75
78
  onNonWidgetSelected: null,
76
79
  onWidgetShapeDuplicated: null,
80
+ allowWidgetDuplication: true,
77
81
  onWidgetShapeDeleting: null,
78
82
  onWidgetRename: null,
79
83
  onRefreshScreenshot: null,
@@ -88,7 +92,10 @@ export const DEFAULT_HOST_PROPS = Object.freeze({
88
92
  workspaceId: null,
89
93
  userId: null,
90
94
  workspaceFonts: Object.freeze([]),
91
- interFontSources: Object.freeze([])
95
+ interFontSources: Object.freeze([]),
96
+ showFileBrowser: false,
97
+ pickFiles: null,
98
+ sketchAssets: Object.freeze([])
92
99
  });
93
100
  /** A store the way Svelte reads one (`$store` and `fromStore` both work on it). */
94
101
  class ValueStore {
@@ -260,6 +267,10 @@ export class CanvasHost {
260
267
  /** The board is about to take the keyboard back from a text field that left the page (asked for the next frame). */
261
268
  #keyboardReturnQueued = false;
262
269
  #loadedWorkspaceSettings = null;
270
+ /** The workspace and the person whose pen was last taken from the storage (null: none yet), so that the pen is read once for each. */
271
+ #penScopeApplied = null;
272
+ /** The tool at the last change of the engine (null: none yet), to tell the moment the Draw tool is left from any other change. */
273
+ #toolAtLastEngineState = null;
263
274
  /** The animation frame that steps the eraser's trail (null: none asked for), and when the trail was last stepped (null: the clock is idle). */
264
275
  #scribbleFrame = null;
265
276
  #scribbleClockLast = null;
@@ -267,9 +278,15 @@ export class CanvasHost {
267
278
  #announcedTool = null;
268
279
  /** The board has opened with its first tool: until then the page is told nothing about the tool (the engine's own starting tool is not a choice). */
269
280
  #toolAnnouncementsOpen = false;
281
+ /** The tool last kept for this workspace (null: none yet), so a tool that is the same as the one that is kept writes nothing. */
282
+ #rememberedToolId = null;
283
+ /** The tool at the last look of the memory above (null: no look yet): every change of the engine passes by it, and only a change of the tool is a choice. */
284
+ #toolSeenForMemory = null;
285
+ /** The host itself is changing the tool (it took a tool its page hides off the board): that is not the person's choice, and is not kept. */
286
+ #toolChangeIsNotAChoice = false;
270
287
  constructor(initialProps = {}) {
271
288
  this.props = { ...DEFAULT_HOST_PROPS, ...initialProps };
272
- this.engine = new EngineCore({ measureText: this.#measureText });
289
+ this.engine = new EngineCore({ measureText: this.#measureText, log: (message, details) => canvasLog(message, details) });
273
290
  this.engine.wireframeMode = this.props.wireframeMode;
274
291
  // The font the person chose for their texts the last time: the first text of this board starts with it too (null where nothing is kept).
275
292
  const preferredTextFontFamily = readPreferredTextFontFamily();
@@ -384,6 +401,35 @@ export class CanvasHost {
384
401
  return;
385
402
  saveWorkspaceToolSettingsDebounced({ workspaceId, userId: this.props.userId }, { text: textPatch, paint: paintPatch });
386
403
  }
404
+ /**
405
+ * Sets the pen, the line the Draw tool draws next (its colour, its width, how much of the board shows through it), and keeps it
406
+ * for this workspace, so the pen is the same when the page is opened again. The settings panel calls it while the Draw tool is
407
+ * chosen and nothing is selected, which is how the pen is set before a line is drawn. The pen is not on the board: nothing that
408
+ * is drawn already changes, and no step of the history is taken.
409
+ *
410
+ * `final` is false while a slider or a colour picker is still being dragged: the pen changes (the next line is drawn with it)
411
+ * and is kept, but the console has one line for the whole drag, written when it ends (`final`, with no patch for the pen).
412
+ */
413
+ changePenStyle(patch, options = {}) {
414
+ try {
415
+ const changed = this.engine.setPenStyle(patch);
416
+ const pen = this.engine.state.penStyle;
417
+ if (changed)
418
+ this.#persistPenStyle(pen);
419
+ if (options.final !== false)
420
+ canvasLog('Canvas: the pen is set', { color: pen.color, width: pen.width, opacity: pen.opacity });
421
+ }
422
+ catch (error) {
423
+ canvasWarn('Canvas: the pen could not be set', error);
424
+ }
425
+ }
426
+ /** Keeps the pen for this workspace and this person (a write after a short delay, so a drag of a slider writes once). Without a workspace nothing is kept. */
427
+ #persistPenStyle(pen) {
428
+ const workspaceId = this.props.workspaceId;
429
+ if (!workspaceId)
430
+ return;
431
+ saveWorkspaceToolSettingsDebounced({ workspaceId, userId: this.props.userId }, { pen: { color: pen.color, width: pen.width, opacity: pen.opacity } });
432
+ }
387
433
  async #syncWorkspaceContext() {
388
434
  await ensureInterFontLoaded(this.props.interFontSources);
389
435
  const fonts = this.props.workspaceFonts ?? [];
@@ -406,6 +452,17 @@ export class CanvasHost {
406
452
  text: this.#loadedWorkspaceSettings?.text ?? null,
407
453
  paint: this.#loadedWorkspaceSettings?.paint ?? null
408
454
  });
455
+ // The pen of this workspace and this person: the one that was kept, or the standard pen where none was. Set once for each
456
+ // workspace and person: a page that passes its fonts again later (another list) does not take the pen back to what the storage
457
+ // holds, which may be a moment behind what the person has just set.
458
+ const penScope = `${workspaceId}\u0000${this.props.userId ?? ''}`;
459
+ if (penScope !== this.#penScopeApplied) {
460
+ this.#penScopeApplied = penScope;
461
+ // What the storage holds is checked key by key by `setPenStyle`: a key that is no value stays what the standard pen has.
462
+ this.engine.setPenStyle(DEFAULT_PEN_STYLE);
463
+ if (this.#loadedWorkspaceSettings?.pen)
464
+ this.engine.setPenStyle(this.#loadedWorkspaceSettings.pen);
465
+ }
409
466
  }
410
467
  /**
411
468
  * A tool whose button the page hides must not stay armed: once the page takes the drawing tools off (after the first
@@ -416,9 +473,16 @@ export class CanvasHost {
416
473
  if (this.props.showDrawingTools)
417
474
  return;
418
475
  const { tool } = this.engine.state;
419
- const drawingGroup = ['draw', 'erase', 'arrow', 'text'];
420
- if (drawingGroup.includes(tool))
476
+ if (!isDrawingGroupTool(tool))
477
+ return;
478
+ // Select takes over because the page took the button off, which is not the person's choice: the tool that was kept stays kept.
479
+ this.#toolChangeIsNotAChoice = true;
480
+ try {
421
481
  this.engine.setTool('select');
482
+ }
483
+ finally {
484
+ this.#toolChangeIsNotAChoice = false;
485
+ }
422
486
  }
423
487
  /**
424
488
  * A widget card is being stretched (or the stretch ended): the page is told, so it can let the pointer through the live
@@ -544,8 +608,15 @@ export class CanvasHost {
544
608
  }
545
609
  if (this.#destroyed)
546
610
  return;
547
- // The first tool: the pencil, when the page shows the drawing tools (a board opens ready for a sketch), else Select.
548
- this.engine.setTool(this.props.showDrawingTools ? 'draw' : 'select');
611
+ // The first tool: the one the person had last in this workspace (so a refresh does not take them back to the pencil), when the page
612
+ // has a button for it; else the pencil, when the page shows the drawing tools (a board opens ready for a sketch), else Select.
613
+ // `CanvasToolbarPlaceholder` is drawn by the same rule (`rememberedTool.ts`), so the tool that is lit does not change at the hand-over.
614
+ const keptToolId = readRememberedToolId({ workspaceId: this.props.workspaceId, userId: this.props.userId });
615
+ this.#rememberedToolId = keptToolId;
616
+ this.engine.setTool(toolTheBoardOpensWith({ rememberedToolId: keptToolId, showDrawingTools: this.props.showDrawingTools }));
617
+ // The tool the board opens with is not a choice: from here on only a change of the tool is looked at (the engine says nothing when
618
+ // the first tool is the one it started with).
619
+ this.#toolSeenForMemory = this.engine.state.tool;
549
620
  // The page hears the first tool even when it is the one the engine started with (nothing changed, so nothing was sent).
550
621
  this.#toolAnnouncementsOpen = true;
551
622
  this.#announceToolIfChanged(this.engine.state.tool);
@@ -698,12 +769,19 @@ export class CanvasHost {
698
769
  if (!input)
699
770
  return;
700
771
  this.#closeTransientUi();
701
- this.focusBoard({ focusVisible: false });
772
+ // A press that ends a text being typed lets the controller end it, which tells the empty placeholder of the Text tool from a
773
+ // text that was typed. The field keeps the focus until then: taking the focus first would end the edit through the blur of the
774
+ // field, before the controller sees it, and the Text tool would be left by a press that is meant to place the text.
775
+ const wasTypingText = this.engine.state.editingTextId !== null;
776
+ if (!wasTypingText)
777
+ this.focusBoard({ focusVisible: false });
702
778
  this.#touchWasLast = input.pointerType === 'touch';
703
779
  // A second finger is a pinch, never a long press.
704
780
  if (event.isPrimary === false)
705
781
  this.#cancelLongPress();
706
782
  const captured = this.controller.pointerDown(input);
783
+ if (wasTypingText)
784
+ this.focusBoard({ focusVisible: false });
707
785
  if (captured) {
708
786
  event.preventDefault();
709
787
  try {
@@ -880,9 +958,39 @@ export class CanvasHost {
880
958
  return true;
881
959
  },
882
960
  afterCopy: () => this.#markClipboardAsOurs(),
883
- spacePanChanged: (held) => this.#updateUi({ spacePan: held })
961
+ spacePanChanged: (held) => this.#updateUi({ spacePan: held }),
962
+ // One line for the press of G and one for its release (the repeats of a held key are not told).
963
+ guidesSuppressedChanged: (held) => canvasLog(held ? 'Canvas: the alignment guides are off while G is held' : 'Canvas: the alignment guides are back, G was let go'),
964
+ // One line for a press: the board left the key alone because something is being drawn or dragged.
965
+ keyIgnoredDuringGesture: (key, gesture) => canvasLog('Canvas: a key was ignored while something is being drawn or dragged', { key, gesture })
884
966
  };
885
967
  }
968
+ /**
969
+ * A shape's letter pressed while the Shapes menu is open: that shape is chosen and the menu stays open, so the mark moves to the
970
+ * tile of the shape as the person looks at the menu (the board's own keys are not answered inside a menu, and the menu itself
971
+ * would only take the letter for its typeahead). True when the key was taken.
972
+ */
973
+ #chooseShapeWhileShapesMenuOpen(event) {
974
+ try {
975
+ const shape = shapeShortcutOf({ key: event.key, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
976
+ if (!shape)
977
+ return false;
978
+ // The letter is the Shapes menu's now: neither the menu's typeahead nor the page may act on it as well.
979
+ event.preventDefault();
980
+ event.stopPropagation();
981
+ // A held key repeats and makes the one choice only; and a shape is not chosen from under a gesture (none runs while a menu is open, but a
982
+ // touch can still be down on the board).
983
+ if (event.repeat || this.controller.gestureKind)
984
+ return true;
985
+ this.chooseShortcutTool(shape);
986
+ canvasLog('Canvas: the Shapes menu followed the key of a shape', { key: event.key, shape });
987
+ return true;
988
+ }
989
+ catch (error) {
990
+ canvasWarn('Canvas: the key of a shape could not be followed in the Shapes menu', error);
991
+ return false;
992
+ }
993
+ }
886
994
  #keyboardHost(origin) {
887
995
  let hasTextSelection = false;
888
996
  try {
@@ -907,6 +1015,9 @@ export class CanvasHost {
907
1015
  return;
908
1016
  if (!eventIsForScope(event, this.#root))
909
1017
  return;
1018
+ // The open Shapes menu follows the letter of a shape (the one exception to the line below): the tool changes and the menu stays.
1019
+ if (this.#ui.value.shapesMenuOpen && this.#chooseShapeWhileShapesMenuOpen(event))
1020
+ return;
910
1021
  const origin = getEventOrigin(event);
911
1022
  // A key pressed inside an open menu or dialog is that menu's (its typeahead, its arrows), not a tool's letter.
912
1023
  if (origin?.closest?.('[role="menu"], [role="dialog"], [role="listbox"]'))
@@ -943,15 +1054,19 @@ export class CanvasHost {
943
1054
  return;
944
1055
  }
945
1056
  if (!eventIsForScope(event, this.#root)) {
946
- // A Space released outside the canvas still ends the pan.
1057
+ // A Space released outside the canvas still ends the pan, and a G released outside it lets the guides come back.
947
1058
  if (event.code === 'Space')
948
1059
  this.controller.setSpaceHeld(false);
1060
+ if (event.code === 'KeyG')
1061
+ this.controller.setGuidesSuppressed(false);
949
1062
  return;
950
1063
  }
951
1064
  const input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey };
952
1065
  if (routeKeyUp(input, this.#keyboardHost(getEventOrigin(event)))) {
953
1066
  event.preventDefault();
954
- this.#updateUi({ spacePan: false });
1067
+ // Only the release of Space ends the grid of the pan: letting go of G must not hide it while Space is still held.
1068
+ if (event.code === 'Space')
1069
+ this.#updateUi({ spacePan: false });
955
1070
  }
956
1071
  }
957
1072
  #onWindowBlur() {
@@ -1002,12 +1117,13 @@ export class CanvasHost {
1002
1117
  onDirty: () => this.#markDirty(),
1003
1118
  // Typing is a change too: the letters are saved with the next save, before the typing ends and makes its undo step.
1004
1119
  onDraftChange: () => this.#markDirty(),
1005
- onCleared: () => this.#safely(() => this.props.onCanvasCleared?.(), 'onCanvasCleared'),
1120
+ onCleared: (cause) => this.#safely(() => this.props.onCanvasCleared?.(cause), 'onCanvasCleared'),
1006
1121
  onSelectionChange: (ids) => this.#onSelectionChange(ids),
1007
1122
  confirmWidgetDeletion: (widgetId) => {
1008
1123
  const ask = this.props.onWidgetShapeDeleting;
1009
1124
  return ask ? ask(widgetId) : true;
1010
1125
  },
1126
+ canDuplicateWidget: () => this.props.allowWidgetDuplication,
1011
1127
  onWidgetDuplicated: (sourceWidgetId, clone) => this.#onWidgetDuplicated(sourceWidgetId, clone),
1012
1128
  onError: (message, error) => canvasWarn(`Canvas: ${message}`, error)
1013
1129
  };
@@ -1055,6 +1171,34 @@ export class CanvasHost {
1055
1171
  this.#announcedTool = tool;
1056
1172
  announceCanvasTool(tool);
1057
1173
  }
1174
+ /**
1175
+ * Keeps the tool that is chosen on the toolbar for this workspace and person, so a board opened again (a refresh) starts with it
1176
+ * and not with the pencil (see `rememberedTool.ts`). It follows the engine, so a tool that ends itself (a shape that was drawn, a text
1177
+ * that was placed: back to Select) is kept as it ends: that is the tool the person sees when they leave. The tool the board opened with
1178
+ * is not a new choice, and neither is the tool the host takes off a board whose page hides it. The write waits for a pause and is
1179
+ * made when the page is left (`pagehide`). Without a workspace nothing is kept, as for the pen.
1180
+ */
1181
+ #rememberToolIfChosen(tool) {
1182
+ // Every change of the engine passes here (a viewport, a selection, an object): only a change of the tool is looked at.
1183
+ if (tool === this.#toolSeenForMemory)
1184
+ return;
1185
+ this.#toolSeenForMemory = tool;
1186
+ if (this.#destroyed || !this.#toolAnnouncementsOpen || this.#toolChangeIsNotAChoice)
1187
+ return;
1188
+ const toolToKeep = toolToRemember(tool);
1189
+ if (!toolToKeep || toolToKeep === this.#rememberedToolId)
1190
+ return;
1191
+ const workspaceId = this.props.workspaceId;
1192
+ if (!workspaceId)
1193
+ return;
1194
+ this.#rememberedToolId = toolToKeep;
1195
+ try {
1196
+ saveWorkspaceToolSettingsDebounced({ workspaceId, userId: this.props.userId }, { tool: { id: toolToKeep } });
1197
+ }
1198
+ catch (error) {
1199
+ canvasWarn('Canvas: the tool could not be kept for the next time', error);
1200
+ }
1201
+ }
1058
1202
  #handleActivate(id) {
1059
1203
  const object = this.engine.getObject(id);
1060
1204
  if (!object || object.type !== 'widget')
@@ -1066,6 +1210,14 @@ export class CanvasHost {
1066
1210
  /** After every change of the engine: the page's overlays are told to move, once a frame, when something they follow moved. */
1067
1211
  #onEngineState(state) {
1068
1212
  this.#announceToolIfChanged(state.tool);
1213
+ this.#rememberToolIfChosen(state.tool);
1214
+ // The panel of the pen (the Draw tool, nothing selected) goes back to the settings control when the Draw tool is left, however it
1215
+ // was left (a letter, the toolbar, Escape), so whatever is picked up next (a line to edit, a shape) starts with the panel closed,
1216
+ // as every selection does. A change of tool that also empties the selection collapses the panel through the rule below as well.
1217
+ if (this.#toolAtLastEngineState === 'draw' && state.tool !== 'draw' && !this.#ui.value.selectionPanelDismissed) {
1218
+ this.#updateUi({ selectionPanelDismissed: true });
1219
+ }
1220
+ this.#toolAtLastEngineState = state.tool;
1069
1221
  // The eraser's trail lives on the frame clock: it starts with the trail and stops when the trail is gone.
1070
1222
  if (state.scribble !== null)
1071
1223
  this.#startScribbleClock();
@@ -1453,8 +1605,22 @@ export class CanvasHost {
1453
1605
  onSelectEraseTool() {
1454
1606
  this.engine.setTool('erase');
1455
1607
  }
1608
+ /**
1609
+ * The Text tool. The text is on the board the moment the tool is chosen: an empty text, shown as the placeholder prompt, in the
1610
+ * middle of the view and ready to be typed in (its field has the focus, so the letters go straight into it). Escape takes it away
1611
+ * and the tool with it; a press elsewhere on the board, while nothing is typed, places the text there instead (a drag gives it a
1612
+ * width); a press on a text that is already there edits that one.
1613
+ */
1456
1614
  onSelectTextTool() {
1457
1615
  this.engine.setTool('text');
1616
+ try {
1617
+ const placeholderId = this.engine.createText(this.engine.visibleCenter(), { placeholder: true });
1618
+ canvasLog('Canvas: the Text tool put its placeholder on the board', { placeholderId });
1619
+ }
1620
+ catch (error) {
1621
+ // The tool stays chosen: a click on the board still places a text, as it always did.
1622
+ canvasWarn('Canvas: the Text tool could not put its placeholder on the board', error);
1623
+ }
1458
1624
  }
1459
1625
  onSelectArrowTool() {
1460
1626
  this.engine.setTool('arrow');
@@ -1686,6 +1852,94 @@ export class CanvasHost {
1686
1852
  if (files.length > 0)
1687
1853
  await this.insertImageFiles(files);
1688
1854
  }
1855
+ /** Whether the File Browser is open now (so a second press of its menu entry does not open a second one). */
1856
+ #fileBrowserOpen = false;
1857
+ /**
1858
+ * The Files entry of the Shapes menu: asks the page's File Browser (`pickFiles`) for pictures and vector files of the person's
1859
+ * library, in the workspace they are in, and puts the chosen ones on the board as one step. Nothing happens when the page did not
1860
+ * turn the entry on (`showFileBrowser`) or gave no picker, when the browser is open already, or when the person closes it without
1861
+ * choosing. The picker's answer comes from the page, so it is checked before anything is read (see `normalizeLibraryFiles`).
1862
+ */
1863
+ async openFileBrowser() {
1864
+ const picker = this.props.pickFiles;
1865
+ if (!this.props.showFileBrowser || typeof picker !== 'function') {
1866
+ canvasWarn('Canvas: the file browser is not available, the page has to pass showFileBrowser and pickFiles');
1867
+ return;
1868
+ }
1869
+ if (this.#fileBrowserOpen || this.#destroyed)
1870
+ return;
1871
+ this.#fileBrowserOpen = true;
1872
+ try {
1873
+ const answer = await picker({ kinds: BOARD_FILE_KINDS, multiple: true });
1874
+ const files = normalizeLibraryFiles(answer);
1875
+ if (files.length > 0 && !this.#destroyed)
1876
+ await this.insertPickedFiles(files);
1877
+ }
1878
+ catch (error) {
1879
+ // A picker that fails (the page's dialog could not open, the network is down) must not break the board.
1880
+ canvasWarn('Canvas: the file browser could not give its files', error);
1881
+ }
1882
+ finally {
1883
+ this.#fileBrowserOpen = false;
1884
+ }
1885
+ }
1886
+ /**
1887
+ * Puts files of the person's library on the board, side by side from `at` (the middle of the view by default), as one step. Each
1888
+ * picture remembers the library file it is (`libraryFileId`, `libraryFileUrl`), so the page knows it is in the library already. A
1889
+ * file that cannot be shown is left out (and said in the console).
1890
+ */
1891
+ async insertPickedFiles(files, at) {
1892
+ const library = normalizeLibraryFiles(files);
1893
+ if (library.length === 0)
1894
+ return [];
1895
+ const loaded = await Promise.all(library.map((file) => readLibraryPicture(file)));
1896
+ return this.insertLoadedImages(loaded.filter((picture) => picture !== null), at);
1897
+ }
1898
+ /**
1899
+ * The pictures that are on the board and where each one comes from: what the page needs to put the ones its library does not have
1900
+ * into it (see `setPictureLibraryFile`). Waits for the pictures that are still on their way from the page's store.
1901
+ */
1902
+ async getBoardPictures() {
1903
+ await this.whenPicturesLoaded();
1904
+ return this.getLoadedBoardPictures();
1905
+ }
1906
+ /**
1907
+ * The same list as `getBoardPictures`, at once and without waiting: the pictures that are on the board now. A picture whose bytes
1908
+ * are still on their way from the page's store has `src: null` for the moment. It is for the moment the board is about to change
1909
+ * (the sketch becoming the widget's card) and the page has no time to wait, only to take note of what is there: it keeps each
1910
+ * picture's `src` and puts the ones its library lacks into it afterwards, when the pictures are no longer on the board.
1911
+ */
1912
+ getLoadedBoardPictures() {
1913
+ const pictures = [];
1914
+ for (const object of this.engine.state.scene) {
1915
+ if (object.type !== 'image')
1916
+ continue;
1917
+ pictures.push({
1918
+ objectId: object.id,
1919
+ fileName: object.fileName,
1920
+ src: object.src,
1921
+ libraryFileId: object.libraryFileId,
1922
+ libraryFileUrl: object.libraryFileUrl,
1923
+ naturalWidth: object.naturalWidth,
1924
+ naturalHeight: object.naturalHeight
1925
+ });
1926
+ }
1927
+ return pictures;
1928
+ }
1929
+ /**
1930
+ * Remembers that the page's library has the picture of an object now (the page put it there). The picture itself, the history and
1931
+ * the selection are left as they are; the board is saved with the new ids. True when something was written.
1932
+ */
1933
+ setPictureLibraryFile(objectId, file) {
1934
+ if (this.#destroyed)
1935
+ return false;
1936
+ const before = this.engine.state.scene;
1937
+ this.engine.repairLoaded((scene) => applyLibraryFile(scene, objectId, file));
1938
+ const written = this.engine.state.scene !== before;
1939
+ if (written)
1940
+ this.#markDirty();
1941
+ return written;
1942
+ }
1689
1943
  /** Reads picture files and puts them on the board, side by side from `at` (the middle of the view by default), as one step. */
1690
1944
  async insertImageFiles(files, at) {
1691
1945
  const loaded = [];
@@ -1709,7 +1963,8 @@ export class CanvasHost {
1709
1963
  const shift = position * 24;
1710
1964
  const id = this.engine.services.createId('img');
1711
1965
  // The page's store may keep the bytes now and give a short address for the board to hold (see `ShapeImageStore.adopt`).
1712
- const adopted = this.#adoptPicture(id, picture.src);
1966
+ // A picture that is only an address (a library file the page would not hand over the bytes of) has no bytes to keep.
1967
+ const adopted = picture.src.startsWith('data:') ? this.#adoptPicture(id, picture.src) : { src: picture.src, imageRef: null };
1713
1968
  return createImageObject({
1714
1969
  id,
1715
1970
  x: center.x - size.width / 2 + shift,
@@ -1719,6 +1974,9 @@ export class CanvasHost {
1719
1974
  src: adopted.src,
1720
1975
  imageRef: adopted.imageRef,
1721
1976
  fileName: picture.fileName || null,
1977
+ // A picture that came from the person's library remembers it, so it is never put there a second time.
1978
+ libraryFileId: picture.libraryFileId ?? null,
1979
+ libraryFileUrl: picture.libraryFileUrl ?? null,
1722
1980
  naturalWidth: picture.width,
1723
1981
  naturalHeight: picture.height
1724
1982
  });
@@ -2098,7 +2356,11 @@ export class CanvasHost {
2098
2356
  const host = createCanvasToolHostFromEngine({
2099
2357
  engine: this.engine,
2100
2358
  bounds: { width: this.engine.state.viewSize.width || 1200, height: this.engine.state.viewSize.height || 800 },
2101
- commitMode: this.#sketchToolBatchBase ? 'transient' : 'push'
2359
+ commitMode: this.#sketchToolBatchBase ? 'transient' : 'push',
2360
+ // What the assistant may use besides shapes: the pictures the page named (the brand kit's icons, the person's library files)
2361
+ // and the fonts the canvas has (the built-in ones and the brand kit's, the same list the font picker shows).
2362
+ assets: this.props.sketchAssets,
2363
+ fontFamilies: fontFamiliesForPicker()
2102
2364
  });
2103
2365
  return executeCanvasTool(host, name, args);
2104
2366
  }
@@ -17,9 +17,9 @@ export declare const CANVAS_CONTRACT_FUNCTION_NAMES: readonly ["shapeFillColor",
17
17
  * (feat/shopify-feedback-canvas) adds the same one, so it keeps the name and the answer (how many objects went): removes
18
18
  * the sketch objects around one widget card and keeps the card.
19
19
  */
20
- export declare const CANVAS_ADDED_FUNCTION_NAMES: readonly ["removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch", "flyToObjects", "flyToPoint", "flyToContent"];
20
+ export declare const CANVAS_ADDED_FUNCTION_NAMES: readonly ["removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch", "flyToObjects", "flyToPoint", "flyToContent", "openFileBrowser", "insertPickedFiles", "getBoardPictures", "getLoadedBoardPictures", "setPictureLibraryFile"];
21
21
  /** Every function the shell exports. */
22
- export declare const CANVAS_EXPORTED_FUNCTION_NAMES: readonly ["shapeFillColor", "captureCanvasSketch", "absorbCanvasSketchIntoWidget", "deselectAll", "duplicateSelectedObjects", "deleteSelectedObjects", "markSelectedAsDuplicating", "linkObjectToWidget", "linkFrameToWidget", "replaceObjectWithWidgetImage", "updateWidgetImage", "selectWidgetShape", "listWidgetShapeScreenRects", "getWidgetShapeScreenRect", "getObjectScreenRect", "getWidgetShapeDataUrl", "setWidgetShapeLivePreviewHiddenImage", "addWidgetShape", "getLinkedWidgetIds", "keepOnlyWidgetShape", "hydrateWidgetShapeMetadata", "markOrphanedWidgetShapes", "onSelectSelectTool", "onSelectLibraryShapeTool", "onSelectEraseTool", "onSelectDrawTool", "onSelectTextTool", "onSelectArrowTool", "onSelectShapeTool", "onSelectFrameTool", "setPrimaryWidgetShape", "getPrimaryWidgetId", "setWidgetShapeBodyDragAllowed", "translateWidgetShapeByScreen", "commitWidgetShapeTranslate", "setWidgetShapeOverlayDragActive", "selectWidgetShapeById", "getSelectedWidgetShapeId", "getSelectedObject", "getHoveredWidgetShapeId", "onSelectImageTool", "onSelectVideoTool", "onSelectPanTool", "zoomIn", "zoomOut", "zoomTo", "zoomReset", "zoomFit", "onGroupSelection", "onUngroupSelection", "onSelectAllObjects", "onDeselectAllObjects", "flushAutosave", "saveNow", "undo", "redo", "saveCanvas", "loadCanvas", "onClearAllObjects", "addText", "addTriangle", "addRect", "addCircle", "addFrame", "addImage", "removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch", "flyToObjects", "flyToPoint", "flyToContent"];
22
+ export declare const CANVAS_EXPORTED_FUNCTION_NAMES: readonly ["shapeFillColor", "captureCanvasSketch", "absorbCanvasSketchIntoWidget", "deselectAll", "duplicateSelectedObjects", "deleteSelectedObjects", "markSelectedAsDuplicating", "linkObjectToWidget", "linkFrameToWidget", "replaceObjectWithWidgetImage", "updateWidgetImage", "selectWidgetShape", "listWidgetShapeScreenRects", "getWidgetShapeScreenRect", "getObjectScreenRect", "getWidgetShapeDataUrl", "setWidgetShapeLivePreviewHiddenImage", "addWidgetShape", "getLinkedWidgetIds", "keepOnlyWidgetShape", "hydrateWidgetShapeMetadata", "markOrphanedWidgetShapes", "onSelectSelectTool", "onSelectLibraryShapeTool", "onSelectEraseTool", "onSelectDrawTool", "onSelectTextTool", "onSelectArrowTool", "onSelectShapeTool", "onSelectFrameTool", "setPrimaryWidgetShape", "getPrimaryWidgetId", "setWidgetShapeBodyDragAllowed", "translateWidgetShapeByScreen", "commitWidgetShapeTranslate", "setWidgetShapeOverlayDragActive", "selectWidgetShapeById", "getSelectedWidgetShapeId", "getSelectedObject", "getHoveredWidgetShapeId", "onSelectImageTool", "onSelectVideoTool", "onSelectPanTool", "zoomIn", "zoomOut", "zoomTo", "zoomReset", "zoomFit", "onGroupSelection", "onUngroupSelection", "onSelectAllObjects", "onDeselectAllObjects", "flushAutosave", "saveNow", "undo", "redo", "saveCanvas", "loadCanvas", "onClearAllObjects", "addText", "addTriangle", "addRect", "addCircle", "addFrame", "addImage", "removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch", "flyToObjects", "flyToPoint", "flyToContent", "openFileBrowser", "insertPickedFiles", "getBoardPictures", "getLoadedBoardPictures", "setPictureLibraryFile"];
23
23
  export type CanvasExportedFunctionName = (typeof CANVAS_EXPORTED_FUNCTION_NAMES)[number];
24
24
  /** What a page gets from `bind:this` besides the component's props: the host's own type of each function. */
25
25
  export type CanvasHostApi = Pick<CanvasHost, CanvasExportedFunctionName>;
@@ -91,7 +91,15 @@ export const CANVAS_ADDED_FUNCTION_NAMES = [
91
91
  // The camera: the view eases to a place (position and zoom together). A page jumps from one object to another, or to a point.
92
92
  'flyToObjects',
93
93
  'flyToPoint',
94
- 'flyToContent'
94
+ 'flyToContent',
95
+ // The person's file library on the board: the Files entry of the Shapes menu, and the calls a page uses to put the pictures that
96
+ // are only on the board into its library (`getLoadedBoardPictures` is the same list as `getBoardPictures`, without waiting: for the
97
+ // moment the board is about to change).
98
+ 'openFileBrowser',
99
+ 'insertPickedFiles',
100
+ 'getBoardPictures',
101
+ 'getLoadedBoardPictures',
102
+ 'setPictureLibraryFile'
95
103
  ];
96
104
  /** Every function the shell exports. */
97
105
  export const CANVAS_EXPORTED_FUNCTION_NAMES = [...CANVAS_CONTRACT_FUNCTION_NAMES, ...CANVAS_ADDED_FUNCTION_NAMES];
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The files of the person's library (the File Browser of their workspace) as the board sees them.
3
+ *
4
+ * The board never shows a File Browser itself: the page that embeds it owns the browser, the workspace and the partner's media
5
+ * library, and gives the board a picker (`pickFiles`). This module is what is said at that door in both directions:
6
+ *
7
+ * - what the board asks for (`BoardFilePickRequest`: pictures and vector files, one or several), and what comes back (`BoardLibraryFile`s,
8
+ * which are checked here because they come from the page, and a partner's page is not ours);
9
+ * - what the board says about the pictures it holds (`BoardPicture`), so the page can put the ones the library does not have yet into it.
10
+ *
11
+ * Deleting something from the board never reaches the library: no function here deletes anything, and the board has no callback
12
+ * that does.
13
+ *
14
+ * Plain TypeScript: runs in Node.
15
+ */
16
+ import type { Scene } from '../../engine/core/scene.js';
17
+ import type { ObjectId } from '../../engine/core/types.js';
18
+ /** The kinds of file the board can put down: pictures (png, jpg, gif, webp, avif…) and vector files (svg). */
19
+ export type BoardFileKind = 'image' | 'svg';
20
+ /** The kinds the board asks the picker for, in the order the File Browser lists them. */
21
+ export declare const BOARD_FILE_KINDS: readonly BoardFileKind[];
22
+ /** What the board asks the page's picker for. */
23
+ export interface BoardFilePickRequest {
24
+ /** The kinds of file the board can use (the picker should list nothing else). */
25
+ kinds: readonly BoardFileKind[];
26
+ /** Whether the person may choose several files at once. */
27
+ multiple: boolean;
28
+ }
29
+ /** A file of the library, as the page's picker reports it (and as a sketch assistant is told about it). */
30
+ export interface BoardLibraryFile {
31
+ /** The library's own id for the file. Null when the library has none (a partner's list without ids). */
32
+ id: string | null;
33
+ name: string;
34
+ /** Where the browser can load it: an http(s) address or a path of the page. */
35
+ url: string;
36
+ /** `image/png`, `image/svg+xml`… when the library knows it. */
37
+ mimeType: string | null;
38
+ }
39
+ /**
40
+ * The page's File Browser. It opens the browser in a dialog (in select state, filtered to `request.kinds`) and answers with the files the
41
+ * person chose, or with nothing when they closed it. It may be asynchronous. The answer is never trusted: see `normalizeLibraryFiles`.
42
+ */
43
+ export type BoardFilePicker = (request: BoardFilePickRequest) => Promise<readonly BoardLibraryFile[] | null | undefined> | readonly BoardLibraryFile[] | null | undefined;
44
+ /** A picture that is on the board, as it is told to the page (to be put in the library when it is not there yet). */
45
+ export interface BoardPicture {
46
+ objectId: string;
47
+ fileName: string | null;
48
+ /** What the board draws: a `data:` address, a `blob:` address of the page's picture store, or an http(s) address. Null if it never arrived. */
49
+ src: string | null;
50
+ /** The library's id for the picture, when it is in the library. */
51
+ libraryFileId: string | null;
52
+ libraryFileUrl: string | null;
53
+ naturalWidth: number;
54
+ naturalHeight: number;
55
+ }
56
+ /** Where a library file ended up, once the page put a board picture in the library. */
57
+ export interface BoardPictureLibraryFile {
58
+ id: string;
59
+ url: string;
60
+ }
61
+ /** A picked list longer than this is cut: one dialog is not for a hundred files, and each is fetched. */
62
+ export declare const MAX_PICKED_FILES = 40;
63
+ /** The extension of a file name or an address, lower-cased, without the query or the hash. Empty when there is none. */
64
+ export declare function fileExtensionOf(nameOrUrl: string): string;
65
+ /** The kind of a file by what the library says it is, else by its name; null when it is not a picture the board can draw. */
66
+ export declare function boardFileKindOf(file: {
67
+ name: string;
68
+ url?: string;
69
+ mimeType?: string | null;
70
+ }): BoardFileKind | null;
71
+ /** The media type the browser needs to draw the file: the library's own when it is a picture's, else the one its extension says. */
72
+ export declare function pictureMimeTypeOf(file: {
73
+ name: string;
74
+ url?: string;
75
+ mimeType?: string | null;
76
+ }): string;
77
+ /**
78
+ * Keeps what can be drawn of what a picker answered. The answer comes from the page, so it is checked like any input: not a list is
79
+ * nothing; an entry that is not an object, has no loadable address, or is not a picture is dropped; the list is cut at
80
+ * `MAX_PICKED_FILES`; the same file twice (same id, or the same address) is kept once.
81
+ */
82
+ export declare function normalizeLibraryFiles(answer: unknown): BoardLibraryFile[];
83
+ /** Whether a picture of the board is in the library already (the page put it there, or the person picked it from there). */
84
+ export declare function isInLibrary(picture: Pick<BoardPicture, 'libraryFileId' | 'libraryFileUrl'>): boolean;
85
+ /**
86
+ * The scene with the library's answer written into one picture: the very same list when no picture has that object id, or when it
87
+ * already says the same. An answer the page gave badly (no id, an address that is not http(s) or a path of the page) changes nothing,
88
+ * so a partner's bug cannot put an address of its choosing on the board.
89
+ */
90
+ export declare function applyLibraryFile(scene: Scene, objectId: ObjectId, file: BoardPictureLibraryFile): Scene;