@widgetic/canvas 0.5.40 → 0.5.42

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 (59) hide show
  1. package/README.md +7 -3
  2. package/dist/canvas/DomCanvas.svelte +4 -0
  3. package/dist/canvas/DomCanvas.svelte.d.ts +8 -0
  4. package/dist/canvas/host/CanvasHost.d.ts +6 -0
  5. package/dist/canvas/host/CanvasHost.js +39 -0
  6. package/dist/canvas/host/CanvasHostApi.d.ts +2 -2
  7. package/dist/canvas/host/CanvasHostApi.js +7 -1
  8. package/dist/canvas/ui/CanvasHint.svelte +16 -3
  9. package/dist/canvas/ui/CanvasHint.svelte.d.ts +2 -17
  10. package/dist/canvas/ui/CanvasToolbar.svelte +7 -7
  11. package/dist/canvas/ui/ToolButton.svelte +11 -3
  12. package/dist/canvas/ui/ToolButton.svelte.d.ts +2 -0
  13. package/dist/canvas/ui/sizeLabelVisibility.d.ts +1 -1
  14. package/dist/canvas/ui/sizeLabelVisibility.js +1 -1
  15. package/dist/canvas/view/SelectionOverlay.svelte +33 -14
  16. package/dist/canvas/view/geometry.d.ts +14 -4
  17. package/dist/canvas/view/geometry.js +14 -7
  18. package/dist/engine/EngineCore.d.ts +4 -1
  19. package/dist/engine/EngineCore.js +11 -4
  20. package/dist/engine/codec/canvasDocument.js +42 -6
  21. package/dist/engine/core/arrow.d.ts +10 -3
  22. package/dist/engine/core/arrow.js +10 -2
  23. package/dist/engine/core/arrowBinding.d.ts +69 -0
  24. package/dist/engine/core/arrowBinding.js +326 -0
  25. package/dist/engine/core/arrowBindingRecords.d.ts +43 -0
  26. package/dist/engine/core/arrowBindingRecords.js +126 -0
  27. package/dist/engine/core/hitTest.d.ts +3 -0
  28. package/dist/engine/core/hitTest.js +2 -1
  29. package/dist/engine/core/scene.d.ts +3 -0
  30. package/dist/engine/core/scene.js +7 -2
  31. package/dist/engine/core/types.d.ts +29 -0
  32. package/dist/engine/input/PointerController.js +23 -1
  33. package/dist/engine/input/gestures.d.ts +12 -1
  34. package/dist/engine/input/gestures.js +56 -11
  35. package/dist/engine/input/keyboard.d.ts +9 -1
  36. package/dist/engine/input/keyboard.js +18 -2
  37. package/dist/engine/state.d.ts +6 -1
  38. package/dist/engine/state.js +2 -1
  39. package/dist/i18n/shortcuts.d.ts +12 -0
  40. package/dist/i18n/shortcuts.js +19 -5
  41. package/dist/tools/components/catalog.d.ts +11 -0
  42. package/dist/tools/components/catalog.js +260 -0
  43. package/dist/tools/components/grouping.d.ts +9 -0
  44. package/dist/tools/components/grouping.js +11 -0
  45. package/dist/tools/definitions.d.ts +19 -0
  46. package/dist/tools/definitions.js +147 -0
  47. package/dist/tools/executors.d.ts +7 -0
  48. package/dist/tools/executors.js +288 -0
  49. package/dist/tools/hostAdapter.d.ts +14 -0
  50. package/dist/tools/hostAdapter.js +38 -0
  51. package/dist/tools/index.d.ts +6 -0
  52. package/dist/tools/index.js +6 -0
  53. package/dist/tools/sceneSummary.d.ts +24 -0
  54. package/dist/tools/sceneSummary.js +156 -0
  55. package/dist/tools/sketchIntent.d.ts +17 -0
  56. package/dist/tools/sketchIntent.js +158 -0
  57. package/dist/tools/types.d.ts +54 -0
  58. package/dist/tools/types.js +11 -0
  59. package/package.json +7 -2
package/README.md CHANGED
@@ -133,8 +133,8 @@ console says `[Canvas] ...` once.
133
133
  `onRecognizeStroke` (`rectangle or square`, `oval (ellipse)` …) are written for the recognizer, not for a screen: they
134
134
  stay English. Each screen says the groups and the shapes through a message (`canvas.category.*`, `canvas.shape.*`).
135
135
  - **Keys.** Names of keys that are words (`Ctrl/Cmd`, `Del`, `Click`) are messages, so a language can write "Strg" or
136
- "Entf". Letters and symbols (`V`, `↑`, `]`) are the same on every keyboard, and the `⌘` glyphs in the menus are the
137
- Mac key caps.
136
+ "Entf". Letters, digits and symbols (`V`, `3`, `↑`, `]`) are the same on every keyboard, and the `⌘` glyphs in the
137
+ menus are the Mac key caps.
138
138
  - **Right to left.** The canvas has no prop for it: its toolbar, the selection panel, the menus and the lists are laid
139
139
  out with logical sides (`start` and `end`, never `left` and `right`), so they start at the start of the line wherever
140
140
  the screen around the canvas is read right to left (the widget creator sets that on its root). The drawing board
@@ -178,7 +178,10 @@ each stroke as its line and its pressures (`ink`) and draws the outline again wh
178
178
 
179
179
  **An arrow is two points and a bend.** Its open head keeps its size when the arrow is stretched, a selected arrow has a handle
180
180
  on each end and one in the middle that bends it (**Shift** holds the direction to steps of 15°), and a board saves it as
181
- `arrow` and draws the outline again when it is read. An arrow does not attach to a shape. **The eraser marks** the shapes the
181
+ `arrow` and draws the outline again when it is read. **An end of an arrow can be tied to a shape**, the way tldraw's can: dragged
182
+ over a shape, it rests on the nearest point of the outline (near the edge) or aims at the middle of the shape (further in), the
183
+ board shows which shape and where, and the arrow follows the shape when it is moved, stretched, turned or typed in (**Alt** while
184
+ drawing or dragging an end ties nothing; moving the arrow by itself lets go). **The eraser marks** the shapes the
182
185
  pointer passes over, dimmed, and removes them all in one step on release (**Esc** leaves them).
183
186
 
184
187
  **The toolbar and the zoom control stand at one of eight places:** `toolbarPosition` and `panZoomPosition` take `TL` `TC` `TR`
@@ -224,6 +227,7 @@ ORIGIN=http://127.0.0.1:5181 node scripts/browser/handles.mjs # handles an
224
227
  ORIGIN=http://127.0.0.1:5181 node scripts/browser/marquee.mjs # what a marquee would take is outlined while it is dragged
225
228
  ORIGIN=http://127.0.0.1:5181 node scripts/browser/outlinePixels.mjs # ... and that outline is the pointer's, pixel for pixel
226
229
  ORIGIN=http://127.0.0.1:5181 node scripts/browser/arrows.mjs # arrows and their handles
230
+ ORIGIN=http://127.0.0.1:5181 node scripts/browser/arrowTies.mjs # arrows tied to shapes follow them
227
231
  npm run build && npx vite preview --port 5182 # a production build, in one terminal ...
228
232
  node scripts/browser/stress.mjs # ... and the frame cost, in another
229
233
  ```
@@ -397,6 +397,10 @@
397
397
  // Added to the contract. The widget creator's in-flight branches call it, and the simple-board branch
398
398
  // (feat/shopify-feedback-canvas) adds the same function (same name, same answer).
399
399
  export const removeSketchObjectsKeepingWidget = forwardToHost(host, 'removeSketchObjectsKeepingWidget');
400
+ export const getSketchSceneSummary = forwardToHost(host, 'getSketchSceneSummary');
401
+ export const executeSketchTool = forwardToHost(host, 'executeSketchTool');
402
+ export const beginSketchToolBatch = forwardToHost(host, 'beginSketchToolBatch');
403
+ export const endSketchToolBatch = forwardToHost(host, 'endSketchToolBatch');
400
404
  </script>
401
405
 
402
406
  <Tooltip.Provider delayDuration={400} skipDelayDuration={200}>
@@ -145,6 +145,10 @@ declare const DomCanvas: $$__sveltets_2_IsomorphicComponent<{
145
145
  addFrame?: () => null;
146
146
  addImage?: () => Promise<void>;
147
147
  removeSketchObjectsKeepingWidget?: (widgetId: string) => number;
148
+ getSketchSceneSummary?: () => import("../tools/types.js").SceneSummary;
149
+ executeSketchTool?: (name: string, args: Record<string, unknown>) => import("../tools/types.js").ToolResult;
150
+ beginSketchToolBatch?: () => void;
151
+ endSketchToolBatch?: () => void;
148
152
  }, {
149
153
  [evt: string]: CustomEvent<any>;
150
154
  }, {}, {
@@ -221,6 +225,10 @@ declare const DomCanvas: $$__sveltets_2_IsomorphicComponent<{
221
225
  addFrame: () => null;
222
226
  addImage: () => Promise<void>;
223
227
  removeSketchObjectsKeepingWidget: (widgetId: string) => number;
228
+ getSketchSceneSummary: () => import("../tools/types.js").SceneSummary;
229
+ executeSketchTool: (name: string, args: Record<string, unknown>) => import("../tools/types.js").ToolResult;
230
+ beginSketchToolBatch: () => void;
231
+ endSketchToolBatch: () => void;
224
232
  }, string>;
225
233
  type DomCanvas = InstanceType<typeof DomCanvas>;
226
234
  export default DomCanvas;
@@ -376,4 +376,10 @@ export declare class CanvasHost {
376
376
  createId(prefix?: string): ObjectId;
377
377
  /** A plain rectangle in the middle of the view (used by the stress page). */
378
378
  makeRect(fields?: Partial<Parameters<typeof createRectObject>[0]>): ObjectId;
379
+ /** Scene summary for the sketch assistant (ids, labels, bounding boxes). */
380
+ getSketchSceneSummary(): import("../../tools/types.js").SceneSummary;
381
+ beginSketchToolBatch(): void;
382
+ endSketchToolBatch(): void;
383
+ /** Run one allow-listed sketch tool (batched into one undo step when a batch is open). */
384
+ executeSketchTool(name: string, args: Record<string, unknown>): import("../../tools/types.js").ToolResult;
379
385
  }
@@ -35,6 +35,8 @@ import { announceSelectTool, announceWidgetPointerBlock } from './pageEvents.js'
35
35
  import { hostObjectById, selectedHostObject } from './hostObject.js';
36
36
  import { screenRectOfBounds, widgetPreviewGeometry } from './screenRects.js';
37
37
  import { isShapeSnapOn, snapDrawnStroke } from './strokeSnap.js';
38
+ import { createCanvasToolHostFromEngine, executeCanvasTool, summarizeScene } from '../../tools/index.js';
39
+ import { isCanvasToolName } from '../../tools/definitions.js';
38
40
  /** What each prop is until the page sets it (the values the canvas this one replaces had, but for `panZoomPosition`). */
39
41
  export const DEFAULT_HOST_PROPS = Object.freeze({
40
42
  showContainerFrame: true,
@@ -1838,4 +1840,41 @@ export class CanvasHost {
1838
1840
  const rect = createRectObject({ id: this.engine.services.createId('obj'), x: center.x - 50, y: center.y - 50, width: 100, height: 100, ...fields });
1839
1841
  return this.engine.addObjects([rect])[0];
1840
1842
  }
1843
+ /** Scene summary for the sketch assistant (ids, labels, bounding boxes). */
1844
+ getSketchSceneSummary() {
1845
+ const host = createCanvasToolHostFromEngine({
1846
+ engine: this.engine,
1847
+ bounds: { width: this.engine.state.viewSize.width || 1200, height: this.engine.state.viewSize.height || 800 }
1848
+ });
1849
+ return summarizeScene(host.getScene(), host.bounds);
1850
+ }
1851
+ #sketchToolBatchBase = null;
1852
+ beginSketchToolBatch() {
1853
+ if (this.#sketchToolBatchBase === null) {
1854
+ // One undo step for the whole sketch turn: the tools run `transient` and `endSketchToolBatch` pushes one step.
1855
+ // The author's own undo history stays as it is (an assistant turn must never make earlier edits un-undoable).
1856
+ this.#sketchToolBatchBase = this.engine.state.scene;
1857
+ }
1858
+ }
1859
+ endSketchToolBatch() {
1860
+ if (this.#sketchToolBatchBase === null)
1861
+ return;
1862
+ const finalScene = this.engine.state.scene;
1863
+ if (finalScene !== this.#sketchToolBatchBase) {
1864
+ this.engine.applyScene(finalScene, 'push');
1865
+ }
1866
+ this.#sketchToolBatchBase = null;
1867
+ }
1868
+ /** Run one allow-listed sketch tool (batched into one undo step when a batch is open). */
1869
+ executeSketchTool(name, args) {
1870
+ if (!isCanvasToolName(name)) {
1871
+ return { ok: false, error: `Unknown tool ${name}`, code: 'invalid_args' };
1872
+ }
1873
+ const host = createCanvasToolHostFromEngine({
1874
+ engine: this.engine,
1875
+ bounds: { width: this.engine.state.viewSize.width || 1200, height: this.engine.state.viewSize.height || 800 },
1876
+ commitMode: this.#sketchToolBatchBase ? 'transient' : 'push'
1877
+ });
1878
+ return executeCanvasTool(host, name, args);
1879
+ }
1841
1880
  }
@@ -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"];
20
+ export declare const CANVAS_ADDED_FUNCTION_NAMES: readonly ["removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch"];
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"];
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"];
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>;
@@ -82,7 +82,13 @@ export const CANVAS_CONTRACT_FUNCTION_NAMES = [
82
82
  * (feat/shopify-feedback-canvas) adds the same one, so it keeps the name and the answer (how many objects went): removes
83
83
  * the sketch objects around one widget card and keeps the card.
84
84
  */
85
- export const CANVAS_ADDED_FUNCTION_NAMES = ['removeSketchObjectsKeepingWidget'];
85
+ export const CANVAS_ADDED_FUNCTION_NAMES = [
86
+ 'removeSketchObjectsKeepingWidget',
87
+ 'getSketchSceneSummary',
88
+ 'executeSketchTool',
89
+ 'beginSketchToolBatch',
90
+ 'endSketchToolBatch'
91
+ ];
86
92
  /** Every function the shell exports. */
87
93
  export const CANVAS_EXPORTED_FUNCTION_NAMES = [...CANVAS_CONTRACT_FUNCTION_NAMES, ...CANVAS_ADDED_FUNCTION_NAMES];
88
94
  /**
@@ -1,21 +1,34 @@
1
1
  <!--
2
2
  Figma "Canvas Hint": what an empty board says. A 40 px tile with a pencil, a title and one line under it, centred on the
3
3
  board and never in the way of the pointer. It is shown while the board holds nothing, and goes the moment something is
4
- drawn.
4
+ drawn. A page that words the line under the title as an empty message (`messages`) gets the tile and the title only.
5
+
6
+ Where it stands: in the middle of the board above the toolbar (the toolbar is 44 px high and stands 16 px from the bottom,
7
+ so the room above it ends 60 px from the bottom), so a short board such as the 320 px card of the Home page shows the whole
8
+ hint. Figma puts it 312 px from the top of a tall board and it stays there: the space over the hint is capped at 312 px,
9
+ the rest goes under it. A phone (max-md) centres it on the whole board, as before.
5
10
  -->
6
11
  <script lang="ts">
7
12
  import { useCanvasLanguage } from '../../i18n/language.js';
8
13
  import { IconPencil } from './icons.js';
9
14
 
10
15
  const { t } = useCanvasLanguage();
16
+
17
+ // The line under the title. Empty when the page left it out: the line is then not drawn at all, so it leaves no gap either.
18
+ const hintDescription = $derived($t('canvas.hint.description'));
11
19
  </script>
12
20
 
13
- <div class="pointer-events-none absolute inset-x-0 top-0 flex justify-center pt-[312px] max-md:inset-0 max-md:items-center max-md:pt-0 max-md:p-6" data-canvas-hint>
21
+ <div class="pointer-events-none absolute inset-x-0 top-0 bottom-[60px] flex flex-col items-center max-md:inset-0 max-md:justify-center max-md:p-6" data-canvas-hint>
22
+ <!-- The space over the hint and the space under it share what the board has left; the one over it never grows past 312 px. -->
23
+ <div class="max-h-[312px] min-h-0 flex-1 max-md:hidden"></div>
14
24
  <div class="flex w-80 max-w-full flex-col items-center gap-2.5 text-center">
15
25
  <div class="flex size-9 items-center justify-center rounded-lg border border-border bg-background text-foreground">
16
26
  <IconPencil class="size-4 stroke-[1.333]" aria-hidden="true" />
17
27
  </div>
18
28
  <p class="text-body-medium text-foreground">{$t('canvas.hint.title')}</p>
19
- <p class="text-body text-muted-foreground">{$t('canvas.hint.description')}</p>
29
+ {#if hintDescription}
30
+ <p class="text-body text-muted-foreground" data-canvas-hint-description>{hintDescription}</p>
31
+ {/if}
20
32
  </div>
33
+ <div class="min-h-0 flex-1 max-md:hidden"></div>
21
34
  </div>
@@ -1,18 +1,3 @@
1
- interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {
2
- new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & {
3
- $$bindings?: Bindings;
4
- } & Exports;
5
- (internal: unknown, props: {
6
- $$events?: Events;
7
- $$slots?: Slots;
8
- }): Exports & {
9
- $set?: any;
10
- $on?: any;
11
- };
12
- z_$$bindings?: Bindings;
13
- }
14
- declare const CanvasHint: $$__sveltets_2_IsomorphicComponent<Record<string, never>, {
15
- [evt: string]: CustomEvent<any>;
16
- }, {}, {}, string>;
17
- type CanvasHint = InstanceType<typeof CanvasHint>;
1
+ declare const CanvasHint: import("svelte").Component<Record<string, never>, {}, "">;
2
+ type CanvasHint = ReturnType<typeof CanvasHint>;
18
3
  export default CanvasHint;
@@ -4,7 +4,7 @@
4
4
 
5
5
  Left to right: the drawing group (select, draw, erase, arrow, text), a divider, the Shapes menu, a divider and the history
6
6
  group (undo, redo). Every button is the design system's Icon Button with a tooltip, 36 px square, and the tool in use has
7
- the brand tint. The page's `showDrawingTools` hides the drawing group (and with it the letters that choose those tools).
7
+ the brand tint. The page's `showDrawingTools` hides the drawing group (and with it the letters and numbers that choose those tools).
8
8
  The Shapes menu and the history group are always on the bar: a page that wants a leaner canvas hides the bar itself. On a
9
9
  board narrower than the whole bar and its edges (381 px, so Figma's 358 px phone) the history group leaves the bar.
10
10
 
@@ -18,7 +18,7 @@
18
18
  import { Separator } from '@widgetic/design-system/components';
19
19
  import type { EngineState } from '../../engine/state.js';
20
20
  import { useCanvasLanguage } from '../../i18n/language.js';
21
- import { TOOL_KEYS } from '../../i18n/shortcuts.js';
21
+ import { TOOL_DIGIT_KEYS, TOOL_KEYS } from '../../i18n/shortcuts.js';
22
22
  import { isSideAnchor, popoverSideFor } from '../chromeLayout.js';
23
23
  import type { ChromeAnchor } from '../chromeLayout.js';
24
24
  import type { CanvasHost, HostUiState } from '../host/CanvasHost.js';
@@ -56,19 +56,19 @@
56
56
  data-canvas-ui
57
57
  >
58
58
  {#if showDrawingTools}
59
- <ToolButton toggle label={$t('canvas.tool.select')} shortcut={TOOL_KEYS.select} active={state.tool === 'select'} onclick={() => host.onSelectSelectTool()}>
59
+ <ToolButton toggle label={$t('canvas.tool.select')} shortcut={TOOL_KEYS.select} alternateShortcut={TOOL_DIGIT_KEYS.select} active={state.tool === 'select'} onclick={() => host.onSelectSelectTool()}>
60
60
  <IconPointer />
61
61
  </ToolButton>
62
- <ToolButton toggle label={$t('canvas.tool.draw')} shortcut={TOOL_KEYS.draw} active={state.tool === 'draw'} onclick={() => host.onSelectDrawTool()}>
62
+ <ToolButton toggle label={$t('canvas.tool.draw')} shortcut={TOOL_KEYS.draw} alternateShortcut={TOOL_DIGIT_KEYS.draw} active={state.tool === 'draw'} onclick={() => host.onSelectDrawTool()}>
63
63
  <IconPencil />
64
64
  </ToolButton>
65
- <ToolButton toggle label={$t('canvas.tool.erase')} shortcut={TOOL_KEYS.erase} active={state.tool === 'erase'} onclick={() => host.onSelectEraseTool()}>
65
+ <ToolButton toggle label={$t('canvas.tool.erase')} shortcut={TOOL_KEYS.erase} alternateShortcut={TOOL_DIGIT_KEYS.erase} active={state.tool === 'erase'} onclick={() => host.onSelectEraseTool()}>
66
66
  <IconEraser />
67
67
  </ToolButton>
68
- <ToolButton toggle label={$t('canvas.tool.arrow')} shortcut={TOOL_KEYS.arrow} active={state.tool === 'arrow'} onclick={() => host.onSelectArrowTool()}>
68
+ <ToolButton toggle label={$t('canvas.tool.arrow')} shortcut={TOOL_KEYS.arrow} alternateShortcut={TOOL_DIGIT_KEYS.arrow} active={state.tool === 'arrow'} onclick={() => host.onSelectArrowTool()}>
69
69
  <IconArrowUpRight />
70
70
  </ToolButton>
71
- <ToolButton toggle label={$t('canvas.tool.text')} shortcut={TOOL_KEYS.text} active={state.tool === 'text'} onclick={() => host.onSelectTextTool()}>
71
+ <ToolButton toggle label={$t('canvas.tool.text')} shortcut={TOOL_KEYS.text} alternateShortcut={TOOL_DIGIT_KEYS.text} active={state.tool === 'text'} onclick={() => host.onSelectTextTool()}>
72
72
  <IconTypography />
73
73
  </ToolButton>
74
74
 
@@ -17,6 +17,8 @@
17
17
  label: string;
18
18
  /** The key that does the same, as it is printed on a key cap ("V"), or nothing. It is also the button's `aria-keyshortcuts`. */
19
19
  shortcut?: string | undefined;
20
+ /** A second key that does the same ("1", the number of the tool): a second key cap in the tooltip, and a second entry of `aria-keyshortcuts`. */
21
+ alternateShortcut?: string | undefined;
20
22
  /** The tool this button chooses is the one in use. */
21
23
  active?: boolean;
22
24
  /** Whether the button acts like a switch (it then says whether it is on to a screen reader). */
@@ -29,7 +31,10 @@
29
31
  children: Snippet;
30
32
  }
31
33
 
32
- let { label, shortcut = undefined, active = false, toggle = false, disabled = false, size = 'toolbar', class: className = '', onclick, children }: Props = $props();
34
+ let { label, shortcut = undefined, alternateShortcut = undefined, active = false, toggle = false, disabled = false, size = 'toolbar', class: className = '', onclick, children }: Props = $props();
35
+
36
+ // `aria-keyshortcuts` lists the keys that do the same, separated by a space ("V 1").
37
+ const keyShortcuts = $derived([shortcut, alternateShortcut].filter(Boolean).join(' ') || undefined);
33
38
 
34
39
  // The tooltip is drawn into the canvas's floating layer, not in place: see floatingLayer.ts.
35
40
  const floatingLayer = useFloatingLayer();
@@ -46,7 +51,7 @@
46
51
  <Tooltip.Trigger>
47
52
  {#snippet child({ props }: { props: Record<string, unknown> })}
48
53
  {#if size === 'level'}
49
- <button {...props} type="button" aria-label={label} aria-keyshortcuts={shortcut} {disabled} {onclick} class="{LEVEL_CLASSES} {className}">
54
+ <button {...props} type="button" aria-label={label} aria-keyshortcuts={keyShortcuts} {disabled} {onclick} class="{LEVEL_CLASSES} {className}">
50
55
  {@render children()}
51
56
  </button>
52
57
  {:else}
@@ -56,7 +61,7 @@
56
61
  {disabled}
57
62
  {onclick}
58
63
  aria-pressed={toggle ? active : undefined}
59
- aria-keyshortcuts={shortcut}
64
+ aria-keyshortcuts={keyShortcuts}
60
65
  data-active={active ? '' : undefined}
61
66
  class="{SQUARE_CLASSES[size]} data-[active]:bg-brand-subtle data-[active]:text-foreground {className}"
62
67
  >
@@ -72,6 +77,9 @@
72
77
  {#if shortcut}
73
78
  <kbd class="rounded-sm bg-muted px-1.5 py-0.5 font-sans text-xs text-muted-foreground">{shortcut}</kbd>
74
79
  {/if}
80
+ {#if alternateShortcut}
81
+ <kbd class="rounded-sm bg-muted px-1.5 py-0.5 font-sans text-xs text-muted-foreground">{alternateShortcut}</kbd>
82
+ {/if}
75
83
  </span>
76
84
  </Tooltip.Content>
77
85
  </Tooltip.Portal>
@@ -4,6 +4,8 @@ interface Props {
4
4
  label: string;
5
5
  /** The key that does the same, as it is printed on a key cap ("V"), or nothing. It is also the button's `aria-keyshortcuts`. */
6
6
  shortcut?: string | undefined;
7
+ /** A second key that does the same ("1", the number of the tool): a second key cap in the tooltip, and a second entry of `aria-keyshortcuts`. */
8
+ alternateShortcut?: string | undefined;
7
9
  /** The tool this button chooses is the one in use. */
8
10
  active?: boolean;
9
11
  /** Whether the button acts like a switch (it then says whether it is on to a screen reader). */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * When the size label under a selection is visible (item B21).
2
+ * When the size label in the middle of a selection is visible (item B21).
3
3
  */
4
4
  import type { SelectionDrag } from '../../engine/state.js';
5
5
  export interface SizeLabelVisibilityInput {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * When the size label under a selection is visible (item B21).
2
+ * When the size label in the middle of a selection is visible (item B21).
3
3
  */
4
4
  /**
5
5
  * True only while the selection is being resized (Figma "Selection Box" keeps the size chip hidden at rest;
@@ -5,7 +5,7 @@
5
5
  in the middle of a selection that is stretched or turned, and the arrow of a text's corner while it is dragged.
6
6
 
7
7
  Figma "Selection Box": a 1.5 px ring outline, 8 px handles (background fill, 1.5 px ring border, 2 px corners) and a size
8
- label of inverse colours under the frame. It is drawn in the board's pixels rather than inside the world layer, so a line
8
+ label of inverse colours in the middle of the frame. It is drawn in the board's pixels rather than inside the world layer, so a line
9
9
  and a handle are the same size at every zoom. The engine finds the handles itself (selectionHandles.ts), so on the board
10
10
  nothing here takes the pointer.
11
11
 
@@ -15,7 +15,10 @@
15
15
 
16
16
  One selected arrow has no frame at all (the way tldraw shows one): its own thin outline, a round handle on each end and one in
17
17
  the middle that bends it. No corners, no turning dot, no size: an arrow is a line from here to there, and it points where its
18
- ends are. A handle grows under the pointer and while it is dragged.
18
+ ends are. A handle grows under the pointer and while it is dragged. The handle of an end that is tied to a shape is filled.
19
+
20
+ While an arrow is drawn or an end of it is dragged over a shape, the shape it would be tied to is outlined and a dot rests where
21
+ the end would stay: on the edge, or in the middle of the shape. The Arrow tool shows the same over a shape before anything is pressed.
19
22
 
20
23
  It is mounted twice when the page lays live widgets over the board. The board's copy draws everything but the frame of a
21
24
  selected widget card; the copy in the page's own layer (`layer="above-widgets"`) draws only that frame, above the live
@@ -34,6 +37,7 @@
34
37
  import type { CanvasHost } from '../host/CanvasHost.js';
35
38
  import { shouldShowRestingSizeLabel } from '../ui/sizeLabelVisibility.js';
36
39
  import {
40
+ arrowBindMarkOf,
37
41
  arrowOutlinePlacement,
38
42
  cssCursor,
39
43
  formatReadout,
@@ -98,14 +102,17 @@
98
102
  const arrow = singleArrowOf(host.engine.selectedShapes(), state.selectedIds);
99
103
  if (!arrow) return null;
100
104
  const positions = arrowHandlePositions(arrow, state.viewport);
101
- const handles: { id: ArrowHandleId; point: Point }[] = [
102
- { id: 'start', point: positions.start },
103
- { id: 'end', point: positions.end }
105
+ const handles: { id: ArrowHandleId; point: Point; bound: boolean }[] = [
106
+ { id: 'start', point: positions.start, bound: !!arrow.arrow.startBinding },
107
+ { id: 'end', point: positions.end, bound: !!arrow.arrow.endBinding }
104
108
  ];
105
- if (bendHandleAvailable(positions)) handles.push({ id: 'bend', point: positions.bend });
109
+ if (bendHandleAvailable(positions)) handles.push({ id: 'bend', point: positions.bend, bound: false });
106
110
  return { arrow, handles };
107
111
  });
108
112
 
113
+ // The shape an arrow end would be tied to, and the place on it: drawn while an arrow is drawn, or an end of it dragged, over a shape.
114
+ const bindMark = $derived(onBoard ? arrowBindMarkOf(state.scene, state.overlay.arrowBind, state.viewport) : null);
115
+
109
116
  const frame = $derived.by(() => {
110
117
  if (!frameVisible || arrowSelection) return null;
111
118
  // The scene and the selection are what the frame is made from: read them so it follows both.
@@ -199,7 +206,8 @@
199
206
  : []
200
207
  );
201
208
 
202
- // The size sits under the frame, at rest and while the frame is stretched, so it does not cover the widget.
209
+ // The size sits in the middle of the frame (the middle of the box round everything selected), where the figure of a stretch
210
+ // sits too. Once the stretch has its figure, that one pill says the size and the label is not drawn a second time on it.
203
211
  const sizeLabel = $derived.by(() => {
204
212
  if (
205
213
  !shouldShowRestingSizeLabel({
@@ -210,19 +218,17 @@
210
218
  ) {
211
219
  return null;
212
220
  }
213
- if (!frame) return null;
221
+ if (!frame || state.overlay.readout) return null;
214
222
  const text = formatReadout({ kind: 'size', width: Math.round(frame.world.width), height: Math.round(frame.world.height) });
215
223
  const at = restingSizeLabelPoint(frame.screen, text);
216
224
  if (!at) return null;
217
225
  return { x: at.x, y: at.y, text };
218
226
  });
219
227
 
228
+ // The figure of a stretch (the size) or of a turn (the angle) stands in the middle of the frame, in both cases.
220
229
  const readoutPoint = $derived.by(() => {
221
230
  if (!frame || !state.overlay.readout) return null;
222
- if (state.overlay.readout.kind === 'size') {
223
- return restingSizeLabelPoint(frame.screen, formatReadout(state.overlay.readout));
224
- }
225
- return { x: frame.screen.centerX, y: frame.screen.centerY };
231
+ return restingSizeLabelPoint(frame.screen, formatReadout(state.overlay.readout));
226
232
  });
227
233
 
228
234
  /** Where one handle sits on the frame, as the percentages of its width and height. */
@@ -288,6 +294,16 @@
288
294
  {@render arrowOutline(hoverArrow, true)}
289
295
  {/if}
290
296
 
297
+ <!-- The shape an arrow end would be tied to (outlined in 2 px, one more than a shape under the pointer) and the place the end would stay. -->
298
+ {#if bindMark}
299
+ <div class="absolute outline outline-2 outline-ring" style={screenFrameStyle(bindMark.frame)} data-canvas-bind-target></div>
300
+ <span
301
+ class="absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-[1.5px] border-background bg-ring"
302
+ style={layerPointStyle(bindMark.point)}
303
+ data-canvas-bind-dot={bindMark.kind}
304
+ ></span>
305
+ {/if}
306
+
291
307
  <!--
292
308
  What the marquee would take, outlined exactly as a unit under the pointer is (the same line of 1 px just outside the edge,
293
309
  the same band round an arrow). The boxes are two paths in the board's pixels, whatever their number; the one of the boxes
@@ -317,10 +333,13 @@
317
333
  ? 'size-3.5 bg-ring'
318
334
  : handle.id === 'bend'
319
335
  ? 'size-2 bg-background'
320
- : 'size-2.5 bg-background'}"
336
+ : handle.bound
337
+ ? 'size-2.5 bg-ring'
338
+ : 'size-2.5 bg-background'}"
321
339
  style={layerPointStyle(handle.point)}
322
340
  data-canvas-arrow-handle={handle.id}
323
341
  data-active={active}
342
+ data-bound={handle.bound}
324
343
  ></span>
325
344
  {/each}
326
345
  {/if}
@@ -418,7 +437,7 @@
418
437
  {/if}
419
438
 
420
439
  {#if readoutPoint && readoutText}
421
- <!-- The size of a stretch sits under the frame. The angle of a turn stays in the middle. -->
440
+ <!-- The size of a stretch and the angle of a turn both stand in the middle of the frame. -->
422
441
  <span
423
442
  class="absolute -translate-x-1/2 -translate-y-1/2 whitespace-nowrap rounded-sm bg-inverse px-1.5 py-0.5 text-xs font-medium tabular-nums text-inverse-foreground"
424
443
  style={layerPointStyle(readoutPoint)}
@@ -6,7 +6,7 @@
6
6
  import type { ArrowObject } from '../../engine/core/arrow.js';
7
7
  import type { Scene } from '../../engine/core/scene.js';
8
8
  import type { SelectionFrame } from '../../engine/core/transform.js';
9
- import type { ObjectId, PaintProps, Point, Rect, SceneObject, ShapeObject, TextObject, Viewport } from '../../engine/core/types.js';
9
+ import type { ArrowBindHint, ObjectId, PaintProps, Point, Rect, SceneObject, ShapeObject, TextObject, Viewport } from '../../engine/core/types.js';
10
10
  import type { Readout } from '../../engine/state.js';
11
11
  /**
12
12
  * The CSS transform that puts a box where it stands in the world layer: its turn about its own middle, then its move.
@@ -93,11 +93,12 @@ export declare function screenFrameStyle(frame: ScreenFrame): string;
93
93
  */
94
94
  export declare function formatReadout(readout: Readout): string;
95
95
  /**
96
- * Where the size label sits at rest: centred under the bottom edge, clear of the frame
97
- * and of the rotation dot (21px under that edge). A label in the middle covers the widget.
96
+ * Where the size label sits: in the middle of the selection (the middle of the frame, whatever its turn, and of the box around
97
+ * all of it when several things are selected), where the figure of a stretch or a turn sits too, so the number is always at
98
+ * the same place and never moves off the thing it measures.
98
99
  */
99
100
  export declare function restingSizeLabelPoint(frame: ScreenFrame, _text: string): Point | null;
100
- /** A point at `distance` pixels below the bottom edge of a turned frame, in the middle of that edge: where the size label goes. */
101
+ /** A point at `distance` pixels below the bottom edge of a turned frame, in the middle of that edge: where the turning dot goes. */
101
102
  export declare function pointBelowFrame(frame: ScreenFrame, distance: number): Point;
102
103
  /**
103
104
  * The outline to draw around a unit (a shape, or a group with all of its members): the shape's own turned box for one
@@ -106,6 +107,15 @@ export declare function pointBelowFrame(frame: ScreenFrame, distance: number): P
106
107
  export declare function outlineOfUnit(scene: Scene, id: ObjectId): (Rect & {
107
108
  rotation: number;
108
109
  }) | null;
110
+ /** What the board shows while an arrow end would be tied to a shape: the shape's box on the screen, and where on the screen the end would rest. */
111
+ export interface ArrowBindMark {
112
+ frame: ScreenFrame;
113
+ point: Point;
114
+ /** `edge`: the end rests on the outline. `center`: the end aims at the middle of the shape. */
115
+ kind: ArrowBindHint['kind'];
116
+ }
117
+ /** The mark for the tie the engine says is in the offing, or null when there is none (or its shape is not on the board any more). */
118
+ export declare function arrowBindMarkOf(scene: Scene, hint: ArrowBindHint | null, viewport: Viewport): ArrowBindMark | null;
109
119
  /**
110
120
  * What is drawn round the units a marquee would take: the box of each shape or group as it stands on the screen, and each
111
121
  * arrow by itself (an arrow is outlined along its line, as it is when the pointer is over it).
@@ -119,17 +119,15 @@ export function screenFrameStyle(frame) {
119
119
  export function formatReadout(readout) {
120
120
  return readout.kind === 'size' ? `${readout.width} × ${readout.height}` : `${readout.degrees}°`;
121
121
  }
122
- /** Height of the size label (text-xs + vertical padding), so it clears the rotation dot. */
123
- const SIZE_LABEL_HEIGHT = 22;
124
122
  /**
125
- * Where the size label sits at rest: centred under the bottom edge, clear of the frame
126
- * and of the rotation dot (21px under that edge). A label in the middle covers the widget.
123
+ * Where the size label sits: in the middle of the selection (the middle of the frame, whatever its turn, and of the box around
124
+ * all of it when several things are selected), where the figure of a stretch or a turn sits too, so the number is always at
125
+ * the same place and never moves off the thing it measures.
127
126
  */
128
127
  export function restingSizeLabelPoint(frame, _text) {
129
- const belowRotationDot = 21 + 8 + SIZE_LABEL_HEIGHT / 2;
130
- return pointBelowFrame(frame, belowRotationDot);
128
+ return { x: frame.centerX, y: frame.centerY };
131
129
  }
132
- /** A point at `distance` pixels below the bottom edge of a turned frame, in the middle of that edge: where the size label goes. */
130
+ /** A point at `distance` pixels below the bottom edge of a turned frame, in the middle of that edge: where the turning dot goes. */
133
131
  export function pointBelowFrame(frame, distance) {
134
132
  const radians = degreesToRadians(frame.rotation);
135
133
  const reach = frame.height / 2 + distance;
@@ -150,6 +148,15 @@ export function outlineOfUnit(scene, id) {
150
148
  const bounds = boundsOfObjects(scene, [id]);
151
149
  return bounds ? { ...bounds, rotation: 0 } : null;
152
150
  }
151
+ /** The mark for the tie the engine says is in the offing, or null when there is none (or its shape is not on the board any more). */
152
+ export function arrowBindMarkOf(scene, hint, viewport) {
153
+ if (!hint)
154
+ return null;
155
+ const outline = outlineOfUnit(scene, hint.targetId);
156
+ if (!outline)
157
+ return null;
158
+ return { frame: screenFrameOf(outline, viewport), point: worldToScreen(viewport, hint.point), kind: hint.kind };
159
+ }
153
160
  /** What a marquee that takes nothing draws: the one shared empty answer, so a derived value that holds it stays the same. */
154
161
  export const NO_MARQUEE_OUTLINES = Object.freeze({ frames: Object.freeze([]), arrows: Object.freeze([]) });
155
162
  /**
@@ -118,8 +118,11 @@ export declare class EngineCore {
118
118
  /**
119
119
  * Puts a new scene on the board. `transient` is for the frames of a gesture (nothing is recorded), `push`
120
120
  * records one undo step and tells the host the board changed, `replace` changes the current step.
121
+ *
122
+ * Whatever the change was (a drag, a stretch, a word typed, an undo), the arrows that are tied to shapes are drawn again from
123
+ * where their shapes are now, in the same scene and the same step: nothing else has to know about the ties.
121
124
  */
122
- applyScene(next: Scene, mode?: 'transient' | 'push' | 'replace'): boolean;
125
+ applyScene(requested: Scene, mode?: 'transient' | 'push' | 'replace'): boolean;
123
126
  /**
124
127
  * Puts a scene on the board with no undo step and without telling the host that the board changed: a repair
125
128
  * of what was loaded (a name filled in), not an edit.
@@ -13,6 +13,7 @@
13
13
  import { parseCanvasDocument, serializeCanvasDocument } from './codec/canvasDocument.js';
14
14
  import { rotationAfterResetProgress, rotationResetProgress } from './core/rotationReset.js';
15
15
  import { alignObjects, distributeObjects } from './core/arrange.js';
16
+ import { reconcileArrowBindings } from './core/arrowBinding.js';
16
17
  import { createImageObject, createObjectId, createRectObject, createTextObject, createWidgetObject, TEXT_DEFAULTS } from './core/defaults.js';
17
18
  import { HistoryStack } from './core/history.js';
18
19
  import { hitTestPoint, hitTestRect, hitTestStack } from './core/hitTest.js';
@@ -189,7 +190,8 @@ export class EngineCore {
189
190
  /** Shows a canvas that was read from saved data. History starts again from it, and it is not "changed". */
190
191
  load(parsed, options = {}) {
191
192
  this.#textSession = null;
192
- const scene = this.#fitTexts(parsed.scene);
193
+ // The texts are laid out first: an arrow tied to one rests on the box its letters make.
194
+ const scene = reconcileArrowBindings(this.#fitTexts(parsed.scene));
193
195
  this.#history.reset(scene);
194
196
  const viewport = options.fitView ? this.#fittedViewport(scene) : parsed.viewport;
195
197
  this.#set({
@@ -266,9 +268,13 @@ export class EngineCore {
266
268
  /**
267
269
  * Puts a new scene on the board. `transient` is for the frames of a gesture (nothing is recorded), `push`
268
270
  * records one undo step and tells the host the board changed, `replace` changes the current step.
271
+ *
272
+ * Whatever the change was (a drag, a stretch, a word typed, an undo), the arrows that are tied to shapes are drawn again from
273
+ * where their shapes are now, in the same scene and the same step: nothing else has to know about the ties.
269
274
  */
270
- applyScene(next, mode = 'push') {
275
+ applyScene(requested, mode = 'push') {
271
276
  const previous = this.#state.scene;
277
+ const next = reconcileArrowBindings(requested);
272
278
  if (next === previous)
273
279
  return mode === 'push' ? this.commit() : false;
274
280
  const patch = { scene: next, revision: this.#state.revision + 1 };
@@ -308,7 +314,8 @@ export class EngineCore {
308
314
  if (next === this.#state.scene)
309
315
  return;
310
316
  this.applyScene(next, 'transient');
311
- this.#history.replaceCurrent(next);
317
+ // What the board holds now (the arrows tied to shapes drawn again), not the scene that was asked for.
318
+ this.#history.replaceCurrent(this.#state.scene);
312
319
  }
313
320
  /** Records the scene as it is now as one undo step (the end of a gesture). False when nothing changed since the last step. */
314
321
  commit() {
@@ -676,7 +683,7 @@ export class EngineCore {
676
683
  notifyFontsChanged() {
677
684
  // Not a change the person made: no undo step, and nothing is saved because of it.
678
685
  const committed = this.#history.current;
679
- const refitCommitted = this.#fitTexts(committed);
686
+ const refitCommitted = reconcileArrowBindings(this.#fitTexts(committed));
680
687
  if (refitCommitted !== committed)
681
688
  this.#history.replaceCurrent(refitCommitted);
682
689
  this.#set({ fontRevision: this.#state.fontRevision + 1 });