@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
@@ -13,6 +13,7 @@
13
13
  * people's browsers: colours, fonts and addresses that could carry more than a value are replaced by defaults.
14
14
  */
15
15
  import { arrowPointsOfLegacyPath, buildArrow } from '../core/arrow.js';
16
+ import { dropDanglingBindings, withBindings } from '../core/arrowBindingRecords.js';
16
17
  import { BRUSH_MAX_POINTS, brushOutlineData } from '../core/brush.js';
17
18
  import { createEllipseObject, createGroupObject, createImageObject, createObjectId, createPathObject, createRectObject, createTextObject, createWidgetObject, TEXT_DEFAULTS } from '../core/defaults.js';
18
19
  import { clampNumber, roundTo } from '../core/geometry.js';
@@ -67,6 +68,12 @@ function externalizeBytes(inline, existingRef, makeRef, store) {
67
68
  store.save(ref, inline);
68
69
  return { value: null, ref };
69
70
  }
71
+ /** A tie of an arrow's end as it is saved: the shape it holds to (`target`) and, for a point of the outline, where on the shape's box. */
72
+ function writeArrowBinding(binding) {
73
+ return binding.kind === 'edge'
74
+ ? { target: binding.targetId, kind: 'edge', anchor: [roundTo(binding.anchor.x, 4), roundTo(binding.anchor.y, 4)] }
75
+ : { target: binding.targetId, kind: 'center' };
76
+ }
70
77
  function serializeObject(object, options) {
71
78
  const record = { id: object.id, [HOST_READABLE_KEYS.objectType]: object.type, parentId: object.parentId };
72
79
  const source = object;
@@ -101,8 +108,15 @@ function serializeObject(object, options) {
101
108
  // An arrow is saved as its two ends and its bend, for the same reason: its head and shaft are drawn from them when it is read.
102
109
  if (object.arrow) {
103
110
  delete record.d;
104
- const { start, end, bend } = object.arrow;
105
- record.arrow = { start: [roundTo(start.x, 3), roundTo(start.y, 3)], end: [roundTo(end.x, 3), roundTo(end.y, 3)], bend: roundTo(bend, 3) };
111
+ const { start, end, bend, startBinding, endBinding } = object.arrow;
112
+ record.arrow = {
113
+ start: [roundTo(start.x, 3), roundTo(start.y, 3)],
114
+ end: [roundTo(end.x, 3), roundTo(end.y, 3)],
115
+ bend: roundTo(bend, 3),
116
+ // What its ends are tied to, written only for an end that is tied: a board of free arrows is the text it always was.
117
+ ...(startBinding ? { startBinding: writeArrowBinding(startBinding) } : {}),
118
+ ...(endBinding ? { endBinding: writeArrowBinding(endBinding) } : {})
119
+ };
106
120
  }
107
121
  else
108
122
  delete record.arrow;
@@ -247,7 +261,26 @@ function readArrowSpec(value) {
247
261
  const end = readPoint(value.end);
248
262
  if (!start || !end)
249
263
  return null;
250
- return { start, end, bend: readNumber(value.bend, 0, -2 * MAX_SIZE, 2 * MAX_SIZE) };
264
+ return withBindings({ start, end, bend: readNumber(value.bend, 0, -2 * MAX_SIZE, 2 * MAX_SIZE) }, { startBinding: readArrowBinding(value.startBinding), endBinding: readArrowBinding(value.endBinding) });
265
+ }
266
+ /**
267
+ * What an end of an arrow is tied to, or null when the record says nothing that can be read: a shape (by its id), and for a point of
268
+ * the outline where on the shape's box (0 to 1 across and down). Whether that shape is on the board is checked once the board is read.
269
+ */
270
+ function readArrowBinding(value) {
271
+ if (!isRecord(value))
272
+ return null;
273
+ const targetId = typeof value.target === 'string' && value.target !== '' && value.target.length <= 128 ? value.target : null;
274
+ if (!targetId)
275
+ return null;
276
+ if (value.kind === 'center')
277
+ return { targetId, kind: 'center' };
278
+ if (value.kind !== 'edge' || !Array.isArray(value.anchor))
279
+ return null;
280
+ const [across, down] = value.anchor;
281
+ if (typeof across !== 'number' || typeof down !== 'number' || !Number.isFinite(across) || !Number.isFinite(down))
282
+ return null;
283
+ return { targetId, kind: 'edge', anchor: { x: clampNumber(across, 0, 1), y: clampNumber(down, 0, 1) } };
251
284
  }
252
285
  /**
253
286
  * An arrow drawn from its points. They are in the coordinates of the saved box, which is kept as it is when it holds what is drawn
@@ -256,6 +289,8 @@ function readArrowSpec(value) {
256
289
  */
257
290
  function arrowFromSpec(spec, box, strokeWidth) {
258
291
  let { start, end } = spec;
292
+ // What its ends are tied to is not a place on the board: it needs no turn.
293
+ const tiesOfSpec = { startBinding: spec.startBinding ?? null, endBinding: spec.endBinding ?? null };
259
294
  if (box.rotation !== 0) {
260
295
  const radians = degreesToRadians(box.rotation);
261
296
  const cosine = Math.cos(radians);
@@ -278,11 +313,11 @@ function arrowFromSpec(spec, box, strokeWidth) {
278
313
  if (holdsWhatIsDrawn) {
279
314
  // In the frame of the points, which is the frame of the saved box: the path comes back in the frame of its own bounds.
280
315
  const commands = translatePathCommands(geometry.commands, geometry.box.x, geometry.box.y);
281
- return { d: serializePathData(commands), arrow: { start, end, bend: geometry.spec.bend }, box };
316
+ return { d: serializePathData(commands), arrow: withBindings({ start, end, bend: geometry.spec.bend }, tiesOfSpec), box };
282
317
  }
283
318
  return {
284
319
  d: serializePathData(geometry.commands),
285
- arrow: geometry.spec,
320
+ arrow: withBindings(geometry.spec, tiesOfSpec),
286
321
  box: { ...box, rotation: 0, x: box.x + geometry.box.x, y: box.y + geometry.box.y, width: geometry.box.width, height: geometry.box.height }
287
322
  };
288
323
  }
@@ -463,7 +498,8 @@ export function parseCanvasDocument(input) {
463
498
  objects.push(object);
464
499
  });
465
500
  return {
466
- scene: normalizeScene(objects),
501
+ // An arrow tied to a shape that is not on the board (a text edited by hand, an object that was not understood) is let go.
502
+ scene: dropDanglingBindings(normalizeScene(objects)),
467
503
  viewport: sanitizeViewport(document.viewport),
468
504
  status: 'ok',
469
505
  warnings
@@ -15,6 +15,7 @@
15
15
  * in the coordinates of the box that holds it, ready to be written into a path object, together with that box and the arrow's
16
16
  * `ArrowSpec` in the same coordinates.
17
17
  */
18
+ import type { ArrowBindingChange } from './arrowBindingRecords.js';
18
19
  import type { PathCommand } from './pathData.js';
19
20
  import type { ArrowSpec, PathObject, Point, Rect, ShapeObject } from './types.js';
20
21
  /** The wings of the head open this far either side of the shaft (30 degrees). */
@@ -67,14 +68,20 @@ export declare function arrowPointsInWorld(shape: ArrowObject): {
67
68
  end: Point;
68
69
  middle: Point;
69
70
  };
70
- /** What may change in an arrow: the points in the world, the bend, the width of the line the head is sized by. */
71
- export interface ArrowChange {
71
+ /**
72
+ * What may change in an arrow: the points in the world, the bend, the width of the line the head is sized by, and what its ends are
73
+ * tied to (`startBinding` / `endBinding`: a tie sets an end, `null` frees it, a key that is left out keeps it as it is).
74
+ */
75
+ export interface ArrowChange extends ArrowBindingChange {
72
76
  start?: Point;
73
77
  end?: Point;
74
78
  bend?: number;
75
79
  strokeWidth?: number;
76
80
  }
77
- /** The arrow drawn again after a change: a new shape with the same id, the new box, path and points. */
81
+ /**
82
+ * The arrow drawn again after a change: a new shape with the same id, the new box, path and points. What its ends are tied to stays
83
+ * as it was unless the change says otherwise (the points do not move because a tie says so here: `arrowBinding.ts` places them).
84
+ */
78
85
  export declare function reshapeArrow(shape: ArrowObject, change?: ArrowChange): ArrowObject;
79
86
  /**
80
87
  * The arrow after the board around it was changed by a mapping of the world (stretched, mirrored, turned): its ends and the middle of
@@ -15,6 +15,7 @@
15
15
  * in the coordinates of the box that holds it, ready to be written into a path object, together with that box and the arrow's
16
16
  * `ArrowSpec` in the same coordinates.
17
17
  */
18
+ import { withBindings } from './arrowBindingRecords.js';
18
19
  import { clampNumber } from './geometry.js';
19
20
  import { parsePathData, pathBounds, serializePathData, translatePathCommands } from './pathData.js';
20
21
  /** The wings of the head open this far either side of the shaft (30 degrees). */
@@ -139,11 +140,18 @@ export function arrowPointsInWorld(shape) {
139
140
  const end = { x: shape.x + shape.arrow.end.x, y: shape.y + shape.arrow.end.y };
140
141
  return { start, end, middle: arrowMiddle(start, end, shape.arrow.bend) };
141
142
  }
142
- /** The arrow drawn again after a change: a new shape with the same id, the new box, path and points. */
143
+ /**
144
+ * The arrow drawn again after a change: a new shape with the same id, the new box, path and points. What its ends are tied to stays
145
+ * as it was unless the change says otherwise (the points do not move because a tie says so here: `arrowBinding.ts` places them).
146
+ */
143
147
  export function reshapeArrow(shape, change = {}) {
144
148
  const current = arrowPointsInWorld(shape);
145
149
  const strokeWidth = change.strokeWidth ?? shape.strokeWidth;
146
150
  const geometry = buildArrow(change.start ?? current.start, change.end ?? current.end, change.bend ?? shape.arrow.bend, strokeWidth);
151
+ const ties = {
152
+ startBinding: 'startBinding' in change ? change.startBinding : shape.arrow.startBinding,
153
+ endBinding: 'endBinding' in change ? change.endBinding : shape.arrow.endBinding
154
+ };
147
155
  return {
148
156
  ...shape,
149
157
  x: geometry.box.x,
@@ -153,7 +161,7 @@ export function reshapeArrow(shape, change = {}) {
153
161
  rotation: 0,
154
162
  strokeWidth,
155
163
  d: serializePathData(geometry.commands),
156
- arrow: geometry.spec
164
+ arrow: withBindings(geometry.spec, ties)
157
165
  };
158
166
  }
159
167
  /**
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Arrows that stay tied to shapes, the way tldraw's do.
3
+ *
4
+ * An end of an arrow can be tied to a shape (`ArrowBinding`, see `types.ts`). A tied end is not a point of the board any more but
5
+ * a place on the shape, so it goes where the shape goes: when the shape is moved, stretched, turned, or (for a text) grows, the
6
+ * arrow is drawn again from its new place. Two kinds of tie:
7
+ *
8
+ * - `edge`: the end rests on one point of the shape's outline, kept as a fraction of the shape's own box, so it stays at the same
9
+ * place of the shape whatever happens to the shape. It slides along the outline as the pointer slides along it.
10
+ * - `center`: the end aims at the middle of the shape and rests where the line between the middle and the other end meets the
11
+ * outline, so the arrow always points at the shape and runs round it when the other end moves.
12
+ *
13
+ * Everything here is a pure function of the records. Where the ends rest is decided in `positionBoundArrow`, and the engine runs
14
+ * `reconcileArrowBindings` over every scene it is given, so that every change of the board (a drag, a stretch, a turn, a nudge, a
15
+ * word typed, a font that loaded, an undo) moves the arrows in the same step as the shapes they are tied to. A scene in which every
16
+ * arrow is where its ties say comes back as the very same array, so nothing is recorded for a change that moved nothing.
17
+ *
18
+ * `pickArrowBinding` is the other half: which shape a pointer would tie an end to (the topmost one under it that an arrow can be tied
19
+ * to; a hollow shape only near its line, as for any click on it) and how (`edge` when the pointer is near the outline, `center` when
20
+ * it is further in).
21
+ */
22
+ import type { ArrowObject } from './arrow.js';
23
+ import type { Scene } from './scene.js';
24
+ import type { ArrowBinding, ArrowBindHint, ObjectId, Point, SceneObject, ShapeObject } from './types.js';
25
+ /** How far from a shape (screen pixels) the pointer may be and still tie an end to it: the reach a click has on a line. */
26
+ export declare const ARROW_BIND_REACH_PIXELS = 6;
27
+ /** Within this many screen pixels of the outline (inside or outside) an end rests on that point of the outline; further in it aims at the middle. */
28
+ export declare const ARROW_EDGE_BAND_PIXELS = 14;
29
+ /** The band never takes more than this fraction of the shorter side of the shape, so that a small shape still has a middle to aim at. */
30
+ export declare const ARROW_EDGE_BAND_FRACTION = 0.25;
31
+ /** Anything that finds a shape by its id: the index of a scene, usually. */
32
+ export type ShapeLookup = (id: ObjectId) => SceneObject | undefined;
33
+ /** The middle of a shape, in the world. */
34
+ export declare function centerOfShape(shape: ShapeObject): Point;
35
+ /** The point of the outline of a shape that an `edge` tie rests on, in the world. */
36
+ export declare function edgePointOf(shape: ShapeObject, anchor: Point): Point;
37
+ /**
38
+ * Where an arrow aimed from `aim` at the middle of a shape meets its outline, in the world. The middle itself when the arrow comes
39
+ * from inside the shape (or from the middle), so that it still points at it.
40
+ */
41
+ export declare function centerCrossingOf(shape: ShapeObject, aim: Point): Point;
42
+ /**
43
+ * An arrow with its tied ends where their ties say. A tie whose shape is gone is cut and its end stays where it was. The very same
44
+ * object when nothing has to move or be cut, so the function can be run again and again.
45
+ */
46
+ export declare function positionBoundArrow(arrow: ArrowObject, lookup: ShapeLookup): ArrowObject;
47
+ /**
48
+ * The scene with every tied arrow where its ties say. The very same array when none has to move (the engine runs this over every
49
+ * scene it is given, so that it must cost nothing when no arrow is tied, and must not make a change out of nothing).
50
+ */
51
+ export declare function reconcileArrowBindings(scene: Scene): Scene;
52
+ /** What a pointer over a shape would tie an end to: the tie to store, and what the board shows meanwhile. */
53
+ export interface ArrowBindingPick {
54
+ readonly binding: ArrowBinding;
55
+ readonly hint: ArrowBindHint;
56
+ }
57
+ export interface PickArrowBindingOptions {
58
+ /** The zoom of the view: the reach of the pointer and the band of the edge are given in screen pixels. */
59
+ zoom: number;
60
+ /** Shapes to look through (the shape the other end is tied to: both ends of an arrow are never tied to the same one). */
61
+ ignore?: ReadonlySet<ObjectId>;
62
+ }
63
+ /**
64
+ * The tie a pointer at a point of the world would make: the topmost shape under it that an arrow can be tied to, tied on its outline
65
+ * when the pointer is within the band of it and at its middle when it is further in. A hollow shape is under the pointer only near its
66
+ * line, as for a click, so that a frame never hides what lies inside it; only when nothing else is under the pointer is the empty
67
+ * middle of a hollow shape taken as the shape. Null when the pointer is over nothing of the kind.
68
+ */
69
+ export declare function pickArrowBinding(scene: Scene, point: Point, options: PickArrowBindingOptions): ArrowBindingPick | null;
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Arrows that stay tied to shapes, the way tldraw's do.
3
+ *
4
+ * An end of an arrow can be tied to a shape (`ArrowBinding`, see `types.ts`). A tied end is not a point of the board any more but
5
+ * a place on the shape, so it goes where the shape goes: when the shape is moved, stretched, turned, or (for a text) grows, the
6
+ * arrow is drawn again from its new place. Two kinds of tie:
7
+ *
8
+ * - `edge`: the end rests on one point of the shape's outline, kept as a fraction of the shape's own box, so it stays at the same
9
+ * place of the shape whatever happens to the shape. It slides along the outline as the pointer slides along it.
10
+ * - `center`: the end aims at the middle of the shape and rests where the line between the middle and the other end meets the
11
+ * outline, so the arrow always points at the shape and runs round it when the other end moves.
12
+ *
13
+ * Everything here is a pure function of the records. Where the ends rest is decided in `positionBoundArrow`, and the engine runs
14
+ * `reconcileArrowBindings` over every scene it is given, so that every change of the board (a drag, a stretch, a turn, a nudge, a
15
+ * word typed, a font that loaded, an undo) moves the arrows in the same step as the shapes they are tied to. A scene in which every
16
+ * arrow is where its ties say comes back as the very same array, so nothing is recorded for a change that moved nothing.
17
+ *
18
+ * `pickArrowBinding` is the other half: which shape a pointer would tie an end to (the topmost one under it that an arrow can be tied
19
+ * to; a hollow shape only near its line, as for any click on it) and how (`edge` when the pointer is near the outline, `center` when
20
+ * it is further in).
21
+ */
22
+ import { arrowPointsInWorld, isArrow, reshapeArrow } from './arrow.js';
23
+ import { ARROW_ENDS, bindingOfEnd, canBeTiedTo, hasBindings } from './arrowBindingRecords.js';
24
+ import { clampNumber, distanceBetween, pointInPolygon, worldToBoxLocal } from './geometry.js';
25
+ import { flattenedOutline, shapeContainsPoint } from './hitTest.js';
26
+ import { applyMatrixToPoint, boxToWorldMatrix } from './matrix.js';
27
+ /** How far from a shape (screen pixels) the pointer may be and still tie an end to it: the reach a click has on a line. */
28
+ export const ARROW_BIND_REACH_PIXELS = 6;
29
+ /** Within this many screen pixels of the outline (inside or outside) an end rests on that point of the outline; further in it aims at the middle. */
30
+ export const ARROW_EDGE_BAND_PIXELS = 14;
31
+ /** The band never takes more than this fraction of the shorter side of the shape, so that a small shape still has a middle to aim at. */
32
+ export const ARROW_EDGE_BAND_FRACTION = 0.25;
33
+ /** Two points closer than this (world units) are the same place: an arrow that is there already is not drawn again. */
34
+ const SAME_PLACE = 1e-6;
35
+ /** The straight pieces a quarter of a rounded corner is cut into when the outline of a rounded rectangle is walked. */
36
+ const CORNER_STEPS = 8;
37
+ /** The radius of the corners of a rectangle with a roundness of 0 to 100 (100 is a pill): the one the board draws (`cornerRadiusOf`). */
38
+ function cornerRadius(shape) {
39
+ return (clampNumber(shape.roundness, 0, 100) / 100) * (Math.min(shape.width, shape.height) / 2);
40
+ }
41
+ /** The outline of a rectangle with rounded corners, clockwise on the screen from the left end of its top edge. */
42
+ function roundedBoxLines(width, height, radius) {
43
+ const reach = clampNumber(radius, 0, Math.min(width, height) / 2);
44
+ const points = [];
45
+ const corner = (centerX, centerY, startAngle) => {
46
+ for (let step = 0; step <= CORNER_STEPS; step += 1) {
47
+ const angle = startAngle + (step / CORNER_STEPS) * (Math.PI / 2);
48
+ points.push({ x: centerX + reach * Math.cos(angle), y: centerY + reach * Math.sin(angle) });
49
+ }
50
+ };
51
+ corner(reach, reach, Math.PI);
52
+ corner(width - reach, reach, Math.PI * 1.5);
53
+ corner(width - reach, height - reach, 0);
54
+ corner(reach, height - reach, Math.PI / 2);
55
+ return { points, closed: true };
56
+ }
57
+ function outlineOf(shape) {
58
+ const { width, height } = shape;
59
+ switch (shape.type) {
60
+ case 'ellipse':
61
+ return { kind: 'ellipse', width, height };
62
+ case 'rect': {
63
+ const radius = cornerRadius(shape);
64
+ return radius > 0.5 ? { kind: 'lines', width, height, lines: [roundedBoxLines(width, height, radius)] } : { kind: 'box', width, height };
65
+ }
66
+ case 'path': {
67
+ const lines = flattenedOutline(shape.d).filter((outline) => outline.points.length >= 2);
68
+ return lines.length > 0 ? { kind: 'lines', width, height, lines } : { kind: 'box', width, height };
69
+ }
70
+ default:
71
+ // Text, pictures and widget cards are their box.
72
+ return { kind: 'box', width, height };
73
+ }
74
+ }
75
+ function closestOnSegment(point, first, second) {
76
+ const deltaX = second.x - first.x;
77
+ const deltaY = second.y - first.y;
78
+ const lengthSquared = deltaX * deltaX + deltaY * deltaY;
79
+ if (lengthSquared < 1e-12)
80
+ return first;
81
+ const along = clampNumber(((point.x - first.x) * deltaX + (point.y - first.y) * deltaY) / lengthSquared, 0, 1);
82
+ return { x: first.x + along * deltaX, y: first.y + along * deltaY };
83
+ }
84
+ /** The point of the outline nearest to a point (both in the coordinates of the box). */
85
+ function nearestOnOutline(outline, point) {
86
+ const { width, height } = outline;
87
+ if (outline.kind === 'box') {
88
+ if (point.x < 0 || point.x > width || point.y < 0 || point.y > height) {
89
+ return { x: clampNumber(point.x, 0, width), y: clampNumber(point.y, 0, height) };
90
+ }
91
+ // Inside: the nearest of the four sides.
92
+ const least = Math.min(point.x, width - point.x, point.y, height - point.y);
93
+ if (least === point.x)
94
+ return { x: 0, y: point.y };
95
+ if (least === width - point.x)
96
+ return { x: width, y: point.y };
97
+ if (least === point.y)
98
+ return { x: point.x, y: 0 };
99
+ return { x: point.x, y: height };
100
+ }
101
+ if (outline.kind === 'ellipse') {
102
+ const radiusX = Math.max(width / 2, 1e-6);
103
+ const radiusY = Math.max(height / 2, 1e-6);
104
+ const offsetX = point.x - width / 2;
105
+ const offsetY = point.y - height / 2;
106
+ const reach = Math.hypot(offsetX / radiusX, offsetY / radiusY);
107
+ // The middle has no nearest point: the one at the right will do.
108
+ if (reach < 1e-9)
109
+ return { x: width, y: height / 2 };
110
+ // The point of the ellipse on the line from the middle through the point.
111
+ return { x: width / 2 + offsetX / reach, y: height / 2 + offsetY / reach };
112
+ }
113
+ let nearest = outline.lines[0].points[0];
114
+ let nearestDistance = Infinity;
115
+ for (const line of outline.lines) {
116
+ const last = line.closed ? line.points.length : line.points.length - 1;
117
+ for (let index = 0; index < last; index += 1) {
118
+ const candidate = closestOnSegment(point, line.points[index], line.points[(index + 1) % line.points.length]);
119
+ const distance = distanceBetween(point, candidate);
120
+ if (distance < nearestDistance) {
121
+ nearest = candidate;
122
+ nearestDistance = distance;
123
+ }
124
+ }
125
+ }
126
+ return nearest;
127
+ }
128
+ /** Where the segment from `first` to `second` meets the segment from `a` to `b`, as the fraction of the first it is along; null when they do not meet. */
129
+ function segmentMeeting(first, second, a, b) {
130
+ const directionX = second.x - first.x;
131
+ const directionY = second.y - first.y;
132
+ const edgeX = b.x - a.x;
133
+ const edgeY = b.y - a.y;
134
+ const denominator = directionX * edgeY - directionY * edgeX;
135
+ if (Math.abs(denominator) < 1e-12)
136
+ return null;
137
+ const along = ((a.x - first.x) * edgeY - (a.y - first.y) * edgeX) / denominator;
138
+ const across = ((a.x - first.x) * directionY - (a.y - first.y) * directionX) / denominator;
139
+ return along >= 0 && along <= 1 && across >= 0 && across <= 1 ? along : null;
140
+ }
141
+ /**
142
+ * Where the line from a point to the middle of the shape first meets its outline (both in the coordinates of the box). Null when the
143
+ * point is inside the shape, or on it: the line meets nothing then.
144
+ */
145
+ function crossingTowardMiddle(outline, from) {
146
+ const { width, height } = outline;
147
+ const middle = { x: width / 2, y: height / 2 };
148
+ if (outline.kind === 'lines') {
149
+ let nearestAlong = Infinity;
150
+ for (const line of outline.lines) {
151
+ const last = line.closed ? line.points.length : line.points.length - 1;
152
+ for (let index = 0; index < last; index += 1) {
153
+ const along = segmentMeeting(from, middle, line.points[index], line.points[(index + 1) % line.points.length]);
154
+ if (along !== null && along < nearestAlong)
155
+ nearestAlong = along;
156
+ }
157
+ }
158
+ return nearestAlong === Infinity ? null : { x: from.x + (middle.x - from.x) * nearestAlong, y: from.y + (middle.y - from.y) * nearestAlong };
159
+ }
160
+ const radiusX = Math.max(width / 2, 1e-6);
161
+ const radiusY = Math.max(height / 2, 1e-6);
162
+ const offsetX = (from.x - middle.x) / radiusX;
163
+ const offsetY = (from.y - middle.y) / radiusY;
164
+ // How many times the box (or the ellipse) the point is from the middle: past 1 it is outside.
165
+ const reach = outline.kind === 'box' ? Math.max(Math.abs(offsetX), Math.abs(offsetY)) : Math.hypot(offsetX, offsetY);
166
+ if (reach <= 1 + 1e-9)
167
+ return null;
168
+ return { x: middle.x + (from.x - middle.x) / reach, y: middle.y + (from.y - middle.y) / reach };
169
+ }
170
+ function toWorld(shape, local) {
171
+ return applyMatrixToPoint(boxToWorldMatrix(shape), local);
172
+ }
173
+ /** The middle of a shape, in the world. */
174
+ export function centerOfShape(shape) {
175
+ return toWorld(shape, { x: shape.width / 2, y: shape.height / 2 });
176
+ }
177
+ /** The point of the outline of a shape that an `edge` tie rests on, in the world. */
178
+ export function edgePointOf(shape, anchor) {
179
+ const local = { x: anchor.x * shape.width, y: anchor.y * shape.height };
180
+ // Put back on the outline: a shape that was rebuilt (a rounded corner, a regenerated path) may have moved it a little.
181
+ return toWorld(shape, nearestOnOutline(outlineOf(shape), local));
182
+ }
183
+ /**
184
+ * Where an arrow aimed from `aim` at the middle of a shape meets its outline, in the world. The middle itself when the arrow comes
185
+ * from inside the shape (or from the middle), so that it still points at it.
186
+ */
187
+ export function centerCrossingOf(shape, aim) {
188
+ const local = worldToBoxLocal(shape, aim);
189
+ const crossing = local ? crossingTowardMiddle(outlineOf(shape), local) : null;
190
+ return crossing ? toWorld(shape, crossing) : centerOfShape(shape);
191
+ }
192
+ /** The shape an arrow's tie holds to, or null when there is none to hold to (it is gone, or an arrow cannot be tied to it). */
193
+ function targetOf(arrow, binding, lookup) {
194
+ if (!binding || binding.targetId === arrow.id)
195
+ return null;
196
+ const target = lookup(binding.targetId);
197
+ return target && canBeTiedTo(target) ? target : null;
198
+ }
199
+ /**
200
+ * An arrow with its tied ends where their ties say. A tie whose shape is gone is cut and its end stays where it was. The very same
201
+ * object when nothing has to move or be cut, so the function can be run again and again.
202
+ */
203
+ export function positionBoundArrow(arrow, lookup) {
204
+ if (!hasBindings(arrow.arrow))
205
+ return arrow;
206
+ const current = arrowPointsInWorld(arrow);
207
+ const targets = { start: null, end: null };
208
+ const bindings = { start: null, end: null };
209
+ const cut = {};
210
+ for (const end of ARROW_ENDS) {
211
+ const binding = bindingOfEnd(arrow.arrow, end);
212
+ const target = targetOf(arrow, binding, lookup);
213
+ if (binding && target) {
214
+ bindings[end] = binding;
215
+ targets[end] = target;
216
+ }
217
+ else if (binding) {
218
+ cut[end === 'start' ? 'startBinding' : 'endBinding'] = null;
219
+ }
220
+ }
221
+ // What the line to the far end is drawn to: its place on the outline, the middle of its shape, or its own place when it is free.
222
+ const lookedAt = (end) => {
223
+ const target = targets[end];
224
+ const binding = bindings[end];
225
+ if (!target || !binding)
226
+ return current[end];
227
+ return binding.kind === 'edge' ? edgePointOf(target, binding.anchor) : centerOfShape(target);
228
+ };
229
+ const placed = { start: current.start, end: current.end };
230
+ for (const end of ARROW_ENDS) {
231
+ const target = targets[end];
232
+ const binding = bindings[end];
233
+ if (!target || !binding)
234
+ continue;
235
+ placed[end] = binding.kind === 'edge' ? edgePointOf(target, binding.anchor) : centerCrossingOf(target, lookedAt(end === 'start' ? 'end' : 'start'));
236
+ }
237
+ const moved = ARROW_ENDS.some((end) => distanceBetween(placed[end], current[end]) > SAME_PLACE);
238
+ if (!moved && Object.keys(cut).length === 0)
239
+ return arrow;
240
+ return reshapeArrow(arrow, { start: placed.start, end: placed.end, ...cut });
241
+ }
242
+ /**
243
+ * The scene with every tied arrow where its ties say. The very same array when none has to move (the engine runs this over every
244
+ * scene it is given, so that it must cost nothing when no arrow is tied, and must not make a change out of nothing).
245
+ */
246
+ export function reconcileArrowBindings(scene) {
247
+ if (!scene.some((object) => object.type === 'path' && !!object.arrow && hasBindings(object.arrow)))
248
+ return scene;
249
+ const index = new Map();
250
+ for (const object of scene)
251
+ index.set(object.id, object);
252
+ const lookup = (id) => index.get(id);
253
+ let changed = false;
254
+ const next = scene.map((object) => {
255
+ if (object.type !== 'path' || !isArrow(object) || !hasBindings(object.arrow))
256
+ return object;
257
+ const placed = positionBoundArrow(object, lookup);
258
+ if (placed !== object)
259
+ changed = true;
260
+ return placed;
261
+ });
262
+ return changed ? next : scene;
263
+ }
264
+ /** How near the outline a pointer is for an end to rest on it (world units): the band, as long as a small shape allows. */
265
+ function edgeBandOf(shape, zoom) {
266
+ return Math.min(ARROW_EDGE_BAND_PIXELS / zoom, ARROW_EDGE_BAND_FRACTION * Math.min(shape.width, shape.height));
267
+ }
268
+ /** Whether a point is inside a shape, a hollow one included (the way a click is not: a click on the empty middle of a frame reaches what lies under it). */
269
+ function interiorContains(shape, point) {
270
+ const local = worldToBoxLocal(shape, point);
271
+ if (!local)
272
+ return false;
273
+ switch (shape.type) {
274
+ case 'rect':
275
+ return local.x >= 0 && local.x <= shape.width && local.y >= 0 && local.y <= shape.height;
276
+ case 'ellipse':
277
+ return Math.hypot((local.x - shape.width / 2) / Math.max(shape.width / 2, 1e-6), (local.y - shape.height / 2) / Math.max(shape.height / 2, 1e-6)) <= 1;
278
+ case 'path':
279
+ return flattenedOutline(shape.d).some((outline) => outline.points.length >= 3 && pointInPolygon(local, outline.points));
280
+ default:
281
+ return false;
282
+ }
283
+ }
284
+ /** The tie a pointer at a point makes on one shape it is over: on the outline within the band of it, at the middle further in. */
285
+ function tieOnShape(shape, point, zoom) {
286
+ const local = worldToBoxLocal(shape, point);
287
+ if (!local)
288
+ return null;
289
+ const nearest = nearestOnOutline(outlineOf(shape), local);
290
+ if (distanceBetween(local, nearest) <= edgeBandOf(shape, zoom)) {
291
+ const anchor = { x: clampNumber(nearest.x / Math.max(shape.width, 1e-6), 0, 1), y: clampNumber(nearest.y / Math.max(shape.height, 1e-6), 0, 1) };
292
+ return { binding: { targetId: shape.id, kind: 'edge', anchor }, hint: { targetId: shape.id, kind: 'edge', point: toWorld(shape, nearest) } };
293
+ }
294
+ return { binding: { targetId: shape.id, kind: 'center' }, hint: { targetId: shape.id, kind: 'center', point: centerOfShape(shape) } };
295
+ }
296
+ /**
297
+ * The tie a pointer at a point of the world would make: the topmost shape under it that an arrow can be tied to, tied on its outline
298
+ * when the pointer is within the band of it and at its middle when it is further in. A hollow shape is under the pointer only near its
299
+ * line, as for a click, so that a frame never hides what lies inside it; only when nothing else is under the pointer is the empty
300
+ * middle of a hollow shape taken as the shape. Null when the pointer is over nothing of the kind.
301
+ */
302
+ export function pickArrowBinding(scene, point, options) {
303
+ const zoom = Math.max(options.zoom, 1e-6);
304
+ const reach = ARROW_BIND_REACH_PIXELS / zoom;
305
+ for (let position = scene.length - 1; position >= 0; position -= 1) {
306
+ const object = scene[position];
307
+ if (!canBeTiedTo(object) || options.ignore?.has(object.id))
308
+ continue;
309
+ if (!shapeContainsPoint(object, point, reach))
310
+ continue;
311
+ const pick = tieOnShape(object, point, zoom);
312
+ if (pick)
313
+ return pick;
314
+ }
315
+ for (let position = scene.length - 1; position >= 0; position -= 1) {
316
+ const object = scene[position];
317
+ if (!canBeTiedTo(object) || options.ignore?.has(object.id))
318
+ continue;
319
+ if (!interiorContains(object, point))
320
+ continue;
321
+ const pick = tieOnShape(object, point, zoom);
322
+ if (pick)
323
+ return pick;
324
+ }
325
+ return null;
326
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The ties of arrows as plain records: reading one, setting or clearing one, cutting the ones that must not survive an edit,
3
+ * and pointing the ones of a copy at the copies. No geometry here and no import of anything but types, so `scene.ts` may use it
4
+ * (the geometry of ties, which reads hit tests and outlines, is in `arrowBinding.ts`).
5
+ *
6
+ * A tie is `ArrowBinding` (see `types.ts`): an end of an arrow that follows a shape. A free end has no tie, and no key either:
7
+ * every function that makes a spec writes `startBinding` and `endBinding` only while they are set, so an arrow that is tied to
8
+ * nothing is the very same record it was before ties existed.
9
+ */
10
+ import type { ArrowBinding, ArrowEnd, ArrowSpec, ObjectId, SceneObject, ShapeObject } from './types.js';
11
+ /** The two ends of an arrow, the tail first. */
12
+ export declare const ARROW_ENDS: readonly ArrowEnd[];
13
+ /** The tie of one end of an arrow, or null while that end is free. */
14
+ export declare function bindingOfEnd(spec: ArrowSpec, end: ArrowEnd): ArrowBinding | null;
15
+ /** Whether either end of an arrow is tied. */
16
+ export declare function hasBindings(spec: ArrowSpec): boolean;
17
+ /** Whether two ties say the same thing (an anchor is the same when it is the same to a billionth of the box). */
18
+ export declare function sameBinding(first: ArrowBinding | null | undefined, second: ArrowBinding | null | undefined): boolean;
19
+ /** What may be said about the ties of an arrow: a tie sets an end, `null` frees it, a key that is left out keeps it as it is. */
20
+ export interface ArrowBindingChange {
21
+ startBinding?: ArrowBinding | null;
22
+ endBinding?: ArrowBinding | null;
23
+ }
24
+ /** The spec with its ties changed. The same spec when the change says what it says already. */
25
+ export declare function withBindings(spec: ArrowSpec, change: ArrowBindingChange): ArrowSpec;
26
+ /** Whether an arrow can be tied to this object: a shape that has an outline, and is not itself a line (an arrow, a brush stroke) or a group. */
27
+ export declare function canBeTiedTo(object: SceneObject): object is ShapeObject;
28
+ /**
29
+ * An arrow that is carried, stretched or turned together with some shapes: the ties to shapes that are not among them are cut (an
30
+ * arrow that is moved by itself comes off the shapes it was tied to, the way it does in tldraw). The same object when nothing is cut.
31
+ */
32
+ export declare function releaseUnmovedEnds<T extends SceneObject>(object: T, moving: ReadonlySet<ObjectId>): T;
33
+ /**
34
+ * The ties of a copy of an arrow: a tie to a shape that was copied too points at its copy, any other is cut (a copy of an arrow
35
+ * alone is a free arrow). `idMap` says which id was copied to which.
36
+ */
37
+ export declare function remapEnds<T extends SceneObject>(object: T, idMap: ReadonlyMap<ObjectId, ObjectId>): T;
38
+ /**
39
+ * A scene in which every tie points at something an arrow can be tied to: a tie whose shape is not on the board (a board that was
40
+ * edited by hand, a shape deleted by another tool), is not a shape with an outline, or is the arrow itself is cut. The very same
41
+ * array when nothing is cut.
42
+ */
43
+ export declare function dropDanglingBindings<S extends readonly SceneObject[]>(scene: S): S;