@zsherman/canvas 0.0.0-stage → 0.1.1

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 (196) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +373 -0
  3. package/README.md +15 -2
  4. package/THIRD_PARTY_NOTICES.md +117 -0
  5. package/dist/dom/canvas/assets.js +89 -0
  6. package/dist/dom/canvas/board-store.js +56 -0
  7. package/dist/dom/canvas/canvas-actions.js +78 -0
  8. package/dist/dom/canvas/canvas-board.js +557 -0
  9. package/dist/dom/canvas/canvas-board.styles.js +110 -0
  10. package/dist/dom/canvas/canvas-chrome.js +1167 -0
  11. package/dist/dom/canvas/canvas-chrome.styles.js +220 -0
  12. package/dist/dom/canvas/canvas-comments.js +950 -0
  13. package/dist/dom/canvas/canvas-comments.styles.js +231 -0
  14. package/dist/dom/canvas/canvas-context.js +196 -0
  15. package/dist/dom/canvas/canvas-controller.js +697 -0
  16. package/dist/dom/canvas/canvas-cursor-chat.js +120 -0
  17. package/dist/dom/canvas/canvas-cursor-chat.styles.js +55 -0
  18. package/dist/dom/canvas/canvas-menus.js +276 -0
  19. package/dist/dom/canvas/canvas-menus.styles.js +7 -0
  20. package/dist/dom/canvas/canvas-style-bar.js +930 -0
  21. package/dist/dom/canvas/canvas-style-bar.styles.js +52 -0
  22. package/dist/dom/canvas/canvas-surface.js +1354 -0
  23. package/dist/dom/canvas/canvas-surface.styles.js +345 -0
  24. package/dist/dom/canvas/canvas-tool-rail.js +406 -0
  25. package/dist/dom/canvas/canvas-tool-rail.styles.js +20 -0
  26. package/dist/dom/canvas/comments.js +58 -0
  27. package/dist/dom/canvas/equality.js +13 -0
  28. package/dist/dom/canvas/export-png.js +496 -0
  29. package/dist/dom/canvas/gesture-machine.js +91 -0
  30. package/dist/dom/canvas/handlers.js +18 -0
  31. package/dist/dom/canvas/index.js +9 -0
  32. package/dist/dom/canvas/input.js +85 -0
  33. package/dist/dom/canvas/instant.js +28 -0
  34. package/dist/dom/canvas/kernel.js +39 -0
  35. package/dist/dom/canvas/motion.js +686 -0
  36. package/dist/dom/canvas/palette.js +165 -0
  37. package/dist/dom/canvas/random-id.js +15 -0
  38. package/dist/dom/canvas/scene-renderer.js +559 -0
  39. package/dist/dom/canvas/scene.styles.js +7 -0
  40. package/dist/dom/canvas/surface-model.js +324 -0
  41. package/dist/dom/canvas/uploads.js +294 -0
  42. package/dist/dom/index.js +9 -0
  43. package/dist/dom/kernel/actions.js +455 -0
  44. package/dist/dom/kernel/board.js +856 -0
  45. package/dist/dom/kernel/claims.js +40 -0
  46. package/dist/dom/kernel/clipboard.js +30 -0
  47. package/dist/dom/kernel/constants.js +210 -0
  48. package/dist/dom/kernel/contract.js +0 -0
  49. package/dist/dom/kernel/decode.js +85 -0
  50. package/dist/dom/kernel/editor.js +2077 -0
  51. package/dist/dom/kernel/errors.js +82 -0
  52. package/dist/dom/kernel/fonts/inter.js +7924 -0
  53. package/dist/dom/kernel/fractional-index.js +54 -0
  54. package/dist/dom/kernel/geometry.js +123 -0
  55. package/dist/dom/kernel/hit-test.js +156 -0
  56. package/dist/dom/kernel/index.js +22 -0
  57. package/dist/dom/kernel/inspect.js +116 -0
  58. package/dist/dom/kernel/kernel.js +251 -0
  59. package/dist/dom/kernel/outline.js +64 -0
  60. package/dist/dom/kernel/plan.js +1370 -0
  61. package/dist/dom/kernel/rev.js +173 -0
  62. package/dist/dom/kernel/scene.js +580 -0
  63. package/dist/dom/kernel/schema.js +1109 -0
  64. package/dist/dom/kernel/snap.js +258 -0
  65. package/dist/dom/kernel/svg.js +148 -0
  66. package/dist/dom/kernel/text.js +142 -0
  67. package/dist/solid/canvas/assets.jsx +89 -0
  68. package/dist/solid/canvas/board-store.jsx +56 -0
  69. package/dist/solid/canvas/canvas-actions.jsx +78 -0
  70. package/dist/solid/canvas/canvas-board.jsx +326 -0
  71. package/dist/solid/canvas/canvas-board.styles.jsx +110 -0
  72. package/dist/solid/canvas/canvas-chrome.jsx +612 -0
  73. package/dist/solid/canvas/canvas-chrome.styles.jsx +220 -0
  74. package/dist/solid/canvas/canvas-comments.jsx +435 -0
  75. package/dist/solid/canvas/canvas-comments.styles.jsx +231 -0
  76. package/dist/solid/canvas/canvas-context.jsx +174 -0
  77. package/dist/solid/canvas/canvas-controller.jsx +697 -0
  78. package/dist/solid/canvas/canvas-cursor-chat.jsx +87 -0
  79. package/dist/solid/canvas/canvas-cursor-chat.styles.jsx +55 -0
  80. package/dist/solid/canvas/canvas-menus.jsx +223 -0
  81. package/dist/solid/canvas/canvas-menus.styles.jsx +7 -0
  82. package/dist/solid/canvas/canvas-style-bar.jsx +486 -0
  83. package/dist/solid/canvas/canvas-style-bar.styles.jsx +52 -0
  84. package/dist/solid/canvas/canvas-surface.jsx +681 -0
  85. package/dist/solid/canvas/canvas-surface.styles.jsx +345 -0
  86. package/dist/solid/canvas/canvas-tool-rail.jsx +195 -0
  87. package/dist/solid/canvas/canvas-tool-rail.styles.jsx +20 -0
  88. package/dist/solid/canvas/comments.jsx +58 -0
  89. package/dist/solid/canvas/equality.jsx +13 -0
  90. package/dist/solid/canvas/export-png.jsx +496 -0
  91. package/dist/solid/canvas/gesture-machine.jsx +91 -0
  92. package/dist/solid/canvas/handlers.jsx +18 -0
  93. package/dist/solid/canvas/index.jsx +9 -0
  94. package/dist/solid/canvas/input.jsx +85 -0
  95. package/dist/solid/canvas/instant.jsx +28 -0
  96. package/dist/solid/canvas/kernel.jsx +39 -0
  97. package/dist/solid/canvas/motion.jsx +686 -0
  98. package/dist/solid/canvas/palette.jsx +165 -0
  99. package/dist/solid/canvas/random-id.jsx +15 -0
  100. package/dist/solid/canvas/scene-renderer.jsx +559 -0
  101. package/dist/solid/canvas/scene.styles.jsx +7 -0
  102. package/dist/solid/canvas/surface-model.jsx +324 -0
  103. package/dist/solid/canvas/uploads.jsx +294 -0
  104. package/dist/solid/index.jsx +9 -0
  105. package/dist/solid/kernel/actions.jsx +455 -0
  106. package/dist/solid/kernel/board.jsx +856 -0
  107. package/dist/solid/kernel/claims.jsx +40 -0
  108. package/dist/solid/kernel/clipboard.jsx +30 -0
  109. package/dist/solid/kernel/constants.jsx +210 -0
  110. package/dist/solid/kernel/contract.jsx +0 -0
  111. package/dist/solid/kernel/decode.jsx +85 -0
  112. package/dist/solid/kernel/editor.jsx +2077 -0
  113. package/dist/solid/kernel/errors.jsx +82 -0
  114. package/dist/solid/kernel/fonts/inter.jsx +7924 -0
  115. package/dist/solid/kernel/fractional-index.jsx +54 -0
  116. package/dist/solid/kernel/geometry.jsx +123 -0
  117. package/dist/solid/kernel/hit-test.jsx +156 -0
  118. package/dist/solid/kernel/index.jsx +22 -0
  119. package/dist/solid/kernel/inspect.jsx +116 -0
  120. package/dist/solid/kernel/kernel.jsx +251 -0
  121. package/dist/solid/kernel/outline.jsx +64 -0
  122. package/dist/solid/kernel/plan.jsx +1370 -0
  123. package/dist/solid/kernel/rev.jsx +173 -0
  124. package/dist/solid/kernel/scene.jsx +580 -0
  125. package/dist/solid/kernel/schema.jsx +1109 -0
  126. package/dist/solid/kernel/snap.jsx +258 -0
  127. package/dist/solid/kernel/svg.jsx +148 -0
  128. package/dist/solid/kernel/text.jsx +142 -0
  129. package/dist/styles.css +1 -0
  130. package/dist/types/canvas/assets.d.ts +111 -0
  131. package/dist/types/canvas/board-store.d.ts +86 -0
  132. package/dist/types/canvas/canvas-actions.d.ts +21 -0
  133. package/dist/types/canvas/canvas-board.d.ts +53 -0
  134. package/dist/types/canvas/canvas-board.styles.d.ts +94 -0
  135. package/dist/types/canvas/canvas-chrome.d.ts +109 -0
  136. package/dist/types/canvas/canvas-chrome.styles.d.ts +193 -0
  137. package/dist/types/canvas/canvas-comments.d.ts +20 -0
  138. package/dist/types/canvas/canvas-comments.styles.d.ts +208 -0
  139. package/dist/types/canvas/canvas-context.d.ts +104 -0
  140. package/dist/types/canvas/canvas-controller.d.ts +159 -0
  141. package/dist/types/canvas/canvas-cursor-chat.d.ts +13 -0
  142. package/dist/types/canvas/canvas-cursor-chat.styles.d.ts +54 -0
  143. package/dist/types/canvas/canvas-menus.d.ts +21 -0
  144. package/dist/types/canvas/canvas-menus.styles.d.ts +6 -0
  145. package/dist/types/canvas/canvas-style-bar.d.ts +19 -0
  146. package/dist/types/canvas/canvas-style-bar.styles.d.ts +43 -0
  147. package/dist/types/canvas/canvas-surface.d.ts +15 -0
  148. package/dist/types/canvas/canvas-surface.styles.d.ts +313 -0
  149. package/dist/types/canvas/canvas-tool-rail.d.ts +41 -0
  150. package/dist/types/canvas/canvas-tool-rail.styles.d.ts +15 -0
  151. package/dist/types/canvas/comments.d.ts +106 -0
  152. package/dist/types/canvas/equality.d.ts +4 -0
  153. package/dist/types/canvas/export-png.d.ts +77 -0
  154. package/dist/types/canvas/gesture-machine.d.ts +46 -0
  155. package/dist/types/canvas/handlers.d.ts +7 -0
  156. package/dist/types/canvas/index.d.ts +18 -0
  157. package/dist/types/canvas/input.d.ts +63 -0
  158. package/dist/types/canvas/instant.d.ts +13 -0
  159. package/dist/types/canvas/kernel.d.ts +27 -0
  160. package/dist/types/canvas/motion.d.ts +72 -0
  161. package/dist/types/canvas/palette.d.ts +46 -0
  162. package/dist/types/canvas/random-id.d.ts +6 -0
  163. package/dist/types/canvas/scene-renderer.d.ts +27 -0
  164. package/dist/types/canvas/scene.styles.d.ts +4 -0
  165. package/dist/types/canvas/surface-model.d.ts +113 -0
  166. package/dist/types/canvas/uploads.d.ts +58 -0
  167. package/dist/types/index.d.ts +1 -0
  168. package/dist/types/kernel/actions.d.ts +19 -0
  169. package/dist/types/kernel/board.d.ts +137 -0
  170. package/dist/types/kernel/claims.d.ts +29 -0
  171. package/dist/types/kernel/clipboard.d.ts +10 -0
  172. package/dist/types/kernel/constants.d.ts +195 -0
  173. package/dist/types/kernel/contract.d.ts +1533 -0
  174. package/dist/types/kernel/decode.d.ts +60 -0
  175. package/dist/types/kernel/editor.d.ts +12 -0
  176. package/dist/types/kernel/errors.d.ts +11 -0
  177. package/dist/types/kernel/fractional-index.d.ts +7 -0
  178. package/dist/types/kernel/geometry.d.ts +42 -0
  179. package/dist/types/kernel/hit-test.d.ts +16 -0
  180. package/dist/types/kernel/index.d.ts +8 -0
  181. package/dist/types/kernel/inspect.d.ts +6 -0
  182. package/dist/types/kernel/kernel.d.ts +6 -0
  183. package/dist/types/kernel/outline.d.ts +4 -0
  184. package/dist/types/kernel/plan.d.ts +20 -0
  185. package/dist/types/kernel/rev.d.ts +21 -0
  186. package/dist/types/kernel/scene.d.ts +16 -0
  187. package/dist/types/kernel/schema.d.ts +3436 -0
  188. package/dist/types/kernel/snap.d.ts +41 -0
  189. package/dist/types/kernel/svg.d.ts +3 -0
  190. package/dist/types/kernel/text.d.ts +21 -0
  191. package/docs/api.json +207 -0
  192. package/docs/canvas.md +444 -0
  193. package/docs/kernel.md +108 -0
  194. package/docs/llms.txt +41 -0
  195. package/docs/search-index.json +52 -0
  196. package/package.json +60 -4
@@ -0,0 +1,856 @@
1
+ import { BRUSH, HISTORY, INK_WIDTH, PADDING } from "./constants.js";
2
+ import { center, distanceToSegment, ellipseExit, formatNumber, rectExit, round, roundUp, union } from "./geometry.js";
3
+ import { baselineOffset, fontRef, naturalWidth, wrap } from "./text.js";
4
+ // src/kernel/board.ts
5
+ /** The board model: ordering, text layout in shapes, connector routes, ink paths and row changes. */
6
+ const compareStrings = (a, b) => a < b ? -1 : a > b ? 1 : 0;
7
+ /** Draw order: ascending z, ties by id. */
8
+ const compareShapes = (a, b) => compareStrings(a.z, b.z) || compareStrings(a.id, b.id);
9
+ const toMap = (shapes) => new Map(shapes.map((shape) => [shape.id, shape]));
10
+ /** Shapes back to front. */
11
+ const ordered = (shapes) => [...shapes.values()].sort(compareShapes);
12
+ const sortedIds = (ids) => [...ids].sort(compareStrings);
13
+ const hasText = (shape) => shape.kind === "Sticky" || shape.kind === "Box" || shape.kind === "Text";
14
+ const padding = (shape) => shape.kind === "Sticky" ? PADDING.sticky : shape.kind === "Box" ? PADDING.box : 0;
15
+ /**
16
+ * Lays out a shape's text. Stickies and text start at the top; boxes center
17
+ * their text block vertically. Each line starts where `align` puts it in the
18
+ * padded area.
19
+ */
20
+ const layouts = /* @__PURE__ */ new WeakMap();
21
+ const layoutText = (fonts, shape) => {
22
+ let byShape = layouts.get(fonts);
23
+ if (byShape === void 0) {
24
+ byShape = /* @__PURE__ */ new WeakMap();
25
+ layouts.set(fonts, byShape);
26
+ }
27
+ const cached = byShape.get(shape);
28
+ if (cached !== void 0) return cached;
29
+ const layout = computeLayout(fonts, shape);
30
+ byShape.set(shape, layout);
31
+ return layout;
32
+ };
33
+ const computeLayout = (fonts, shape) => {
34
+ const font = fontRef(fonts, shape.style.size);
35
+ const pad = padding(shape);
36
+ const area = {
37
+ x: shape.x + pad,
38
+ y: shape.y + pad,
39
+ w: Math.max(shape.w - pad * 2, 1),
40
+ h: Math.max(shape.h - pad * 2, 0)
41
+ };
42
+ const wrapped = wrap(fonts, shape.text, shape.style.size, area.w);
43
+ const blockHeight = wrapped.length * font.lineHeight;
44
+ const align = shape.style.align;
45
+ const top = shape.kind === "Box" ? shape.y + (shape.h - blockHeight) / 2 : area.y;
46
+ const baseline = baselineOffset(fonts, font);
47
+ return {
48
+ font,
49
+ area,
50
+ align,
51
+ lines: wrapped.map((line, index) => ({
52
+ text: line.text,
53
+ x: round(align === "center" ? area.x + (area.w - line.width) / 2 : align === "end" ? area.x + area.w - line.width : area.x),
54
+ y: round(top + baseline + index * font.lineHeight),
55
+ width: round(line.width)
56
+ })),
57
+ neededHeight: blockHeight + pad * 2
58
+ };
59
+ };
60
+ /**
61
+ * A text shape's box after a change: a text shape's height is its lines', an
62
+ * auto-width text's width is its text's, and stickies and boxes grow to fit.
63
+ */
64
+ const fitText = (fonts, shape) => {
65
+ if (shape.kind === "Text") {
66
+ const w = shape.style.width === "auto" ? roundUp(Math.max(naturalWidth(fonts, shape.text, shape.style.size), 16)) : shape.w;
67
+ const sized = {
68
+ ...shape,
69
+ w
70
+ };
71
+ return {
72
+ ...sized,
73
+ h: round(layoutText(fonts, sized).neededHeight)
74
+ };
75
+ }
76
+ const needed = round(layoutText(fonts, shape).neededHeight);
77
+ return needed > shape.h ? {
78
+ ...shape,
79
+ h: needed
80
+ } : shape;
81
+ };
82
+ /** Ramer–Douglas–Peucker: drops points within `tolerance` of the simplified line. */
83
+ const simplify = (points, tolerance) => {
84
+ if (points.length <= 2) return points;
85
+ const keep = new Array(points.length).fill(false);
86
+ keep[0] = true;
87
+ keep[points.length - 1] = true;
88
+ const stack = [[0, points.length - 1]];
89
+ for (let span = stack.pop(); span !== void 0; span = stack.pop()) {
90
+ const [first, last] = span;
91
+ const a = points[first];
92
+ const b = points[last];
93
+ if (a === void 0 || b === void 0) continue;
94
+ let farthest = -1;
95
+ let farthestDistance = tolerance;
96
+ for (let index = first + 1; index < last; index++) {
97
+ const p = points[index];
98
+ if (p === void 0) continue;
99
+ const d = distanceToSegment(p, a, b);
100
+ if (d > farthestDistance) {
101
+ farthest = index;
102
+ farthestDistance = d;
103
+ }
104
+ }
105
+ if (farthest !== -1) {
106
+ keep[farthest] = true;
107
+ stack.push([first, farthest], [farthest, last]);
108
+ }
109
+ }
110
+ return points.filter((_, index) => keep[index] === true);
111
+ };
112
+ /** Ink from board-coordinate points: simplified, rounded, relative to its box. */
113
+ const inkGeometry = (absolute, tolerance) => {
114
+ const simplified = simplify(absolute.map((p) => ({
115
+ x: round(p.x),
116
+ y: round(p.y)
117
+ })), tolerance);
118
+ const box = union(simplified.map((p) => ({
119
+ x: p.x,
120
+ y: p.y,
121
+ w: 0,
122
+ h: 0
123
+ }))) ?? {
124
+ x: 0,
125
+ y: 0,
126
+ w: 0,
127
+ h: 0
128
+ };
129
+ return {
130
+ x: box.x,
131
+ y: box.y,
132
+ w: round(box.w),
133
+ h: round(box.h),
134
+ points: simplified.map((p) => ({
135
+ x: round(p.x - box.x),
136
+ y: round(p.y - box.y)
137
+ }))
138
+ };
139
+ };
140
+ const inkPoints = (ink) => ink.points.map((p) => ({
141
+ x: ink.x + p.x,
142
+ y: ink.y + p.y
143
+ }));
144
+ const pair = (p) => `${formatNumber(p.x)} ${formatNumber(p.y)}`;
145
+ /** A smooth path through stroke points: quadratic curves through the midpoints. */
146
+ const strokePath = (points) => {
147
+ const [first, ...rest] = points;
148
+ if (first === void 0) return "";
149
+ if (rest.length === 0) return `M${pair(first)}L${pair(first)}`;
150
+ if (rest.length === 1) return `M${pair(first)}L${pair(rest[0] ?? first)}`;
151
+ let d = `M${pair(first)}`;
152
+ for (let index = 1; index < points.length - 1; index++) {
153
+ const p = points[index];
154
+ const next = points[index + 1];
155
+ if (p === void 0 || next === void 0) continue;
156
+ d += `Q${pair(p)} ${pair({
157
+ x: round((p.x + next.x) / 2),
158
+ y: round((p.y + next.y) / 2)
159
+ })}`;
160
+ }
161
+ const last = points[points.length - 1] ?? first;
162
+ return `${d}L${pair(last)}`;
163
+ };
164
+ /**
165
+ * The curve `strokePath` draws, as a polyline: each quadratic in up to 64
166
+ * straight pieces, within 0.25 units of the curve unless the curve bends
167
+ * over more than 4,096 units (then within 1/16,384 of its bend).
168
+ */
169
+ const strokeCurve = (points) => {
170
+ if (points.length < 3) return points;
171
+ const out = [];
172
+ let from = points[0] ?? {
173
+ x: 0,
174
+ y: 0
175
+ };
176
+ out.push(from);
177
+ for (let index = 1; index < points.length - 1; index++) {
178
+ const c = points[index] ?? from;
179
+ const next = points[index + 1] ?? c;
180
+ const to = {
181
+ x: round((c.x + next.x) / 2),
182
+ y: round((c.y + next.y) / 2)
183
+ };
184
+ const bend = Math.hypot(from.x - 2 * c.x + to.x, from.y - 2 * c.y + to.y);
185
+ const k = Math.min(64, Math.max(1, Math.ceil(Math.sqrt(bend))));
186
+ for (let i = 1; i <= k; i++) {
187
+ const t = i / k;
188
+ const u = 1 - t;
189
+ out.push({
190
+ x: u * u * from.x + 2 * u * t * c.x + t * t * to.x,
191
+ y: u * u * from.y + 2 * u * t * c.y + t * t * to.y
192
+ });
193
+ }
194
+ from = to;
195
+ }
196
+ out.push(points[points.length - 1] ?? from);
197
+ return out;
198
+ };
199
+ const polylinePath = (points) => points.map((p, index) => `${index === 0 ? "M" : "L"}${pair(p)}`).join("");
200
+ /** The shape an anchor binds to, when it exists and can hold a connector. */
201
+ const bound = (shapes, anchor, arrowId) => {
202
+ if (anchor._tag !== "Shape" || anchor.id === arrowId) return null;
203
+ const shape = shapes.get(anchor.id);
204
+ return shape === void 0 || shape.kind === "Arrow" ? null : shape;
205
+ };
206
+ const isEllipse = (shape) => shape.kind === "Box" && shape.style.form === "ellipse";
207
+ const exit = (shape, toward) => isEllipse(shape) ? ellipseExit(shape, toward) : rectExit(shape, toward);
208
+ const spot = (shape, at) => ({
209
+ x: shape.x + shape.w * at.x,
210
+ y: shape.y + shape.h * at.y
211
+ });
212
+ /** The outward normal of the side of `shape` nearest `p`. */
213
+ const sideNormal = (shape, p) => {
214
+ const distances = [
215
+ {
216
+ d: Math.abs(p.y - shape.y),
217
+ dir: {
218
+ x: 0,
219
+ y: -1
220
+ }
221
+ },
222
+ {
223
+ d: Math.abs(shape.x + shape.w - p.x),
224
+ dir: {
225
+ x: 1,
226
+ y: 0
227
+ }
228
+ },
229
+ {
230
+ d: Math.abs(shape.y + shape.h - p.y),
231
+ dir: {
232
+ x: 0,
233
+ y: 1
234
+ }
235
+ },
236
+ {
237
+ d: Math.abs(p.x - shape.x),
238
+ dir: {
239
+ x: -1,
240
+ y: 0
241
+ }
242
+ }
243
+ ];
244
+ let best = distances[0] ?? {
245
+ d: 0,
246
+ dir: {
247
+ x: 0,
248
+ y: -1
249
+ }
250
+ };
251
+ for (const candidate of distances) if (candidate.d < best.d) best = candidate;
252
+ return best.dir;
253
+ };
254
+ /** The middle of the side of `shape` that faces `toward`. */
255
+ const facingSide = (shape, toward) => {
256
+ const c = center(shape);
257
+ const dx = (toward.x - c.x) / Math.max(shape.w, 1);
258
+ const dy = (toward.y - c.y) / Math.max(shape.h, 1);
259
+ if (Math.abs(dx) >= Math.abs(dy)) {
260
+ const right = dx >= 0;
261
+ return {
262
+ point: {
263
+ x: right ? shape.x + shape.w : shape.x,
264
+ y: c.y
265
+ },
266
+ out: {
267
+ x: right ? 1 : -1,
268
+ y: 0
269
+ }
270
+ };
271
+ }
272
+ const down = dy >= 0;
273
+ return {
274
+ point: {
275
+ x: c.x,
276
+ y: down ? shape.y + shape.h : shape.y
277
+ },
278
+ out: {
279
+ x: 0,
280
+ y: down ? 1 : -1
281
+ }
282
+ };
283
+ };
284
+ const dedupe = (points) => {
285
+ const out = [];
286
+ for (const p of points) {
287
+ const last = out[out.length - 1];
288
+ if (last !== void 0 && last.x === p.x && last.y === p.y) continue;
289
+ const before = out[out.length - 2];
290
+ if (last !== void 0 && before !== void 0 && (before.x === last.x && last.x === p.x || before.y === last.y && last.y === p.y)) {
291
+ out[out.length - 1] = p;
292
+ continue;
293
+ }
294
+ out.push(p);
295
+ }
296
+ return out.length >= 2 ? out : [out[0] ?? {
297
+ x: 0,
298
+ y: 0
299
+ }, out[0] ?? {
300
+ x: 0,
301
+ y: 0
302
+ }];
303
+ };
304
+ const elbow = (start, end) => {
305
+ const s = start.point;
306
+ const e = end.point;
307
+ const horizontal = Math.abs(e.x - s.x) >= Math.abs(e.y - s.y);
308
+ const startOut = start.out ?? (horizontal ? {
309
+ x: Math.sign(e.x - s.x) || 1,
310
+ y: 0
311
+ } : {
312
+ x: 0,
313
+ y: Math.sign(e.y - s.y) || 1
314
+ });
315
+ const endOut = end.out ?? (horizontal ? {
316
+ x: Math.sign(s.x - e.x) || 1,
317
+ y: 0
318
+ } : {
319
+ x: 0,
320
+ y: Math.sign(s.y - e.y) || 1
321
+ });
322
+ const stubS = start.out === null ? s : {
323
+ x: s.x + startOut.x * 24,
324
+ y: s.y + startOut.y * 24
325
+ };
326
+ const stubE = end.out === null ? e : {
327
+ x: e.x + endOut.x * 24,
328
+ y: e.y + endOut.y * 24
329
+ };
330
+ const startHorizontal = startOut.y === 0;
331
+ const endHorizontal = endOut.y === 0;
332
+ let middle;
333
+ if (startHorizontal && endHorizontal) {
334
+ const mx = (stubS.x + stubE.x) / 2;
335
+ middle = [{
336
+ x: mx,
337
+ y: stubS.y
338
+ }, {
339
+ x: mx,
340
+ y: stubE.y
341
+ }];
342
+ } else if (!startHorizontal && !endHorizontal) {
343
+ const my = (stubS.y + stubE.y) / 2;
344
+ middle = [{
345
+ x: stubS.x,
346
+ y: my
347
+ }, {
348
+ x: stubE.x,
349
+ y: my
350
+ }];
351
+ } else if (startHorizontal) middle = [{
352
+ x: stubE.x,
353
+ y: stubS.y
354
+ }];
355
+ else middle = [{
356
+ x: stubS.x,
357
+ y: stubE.y
358
+ }];
359
+ return [
360
+ s,
361
+ stubS,
362
+ ...middle,
363
+ stubE,
364
+ e
365
+ ];
366
+ };
367
+ /**
368
+ * A connector's route. A bound end with a spot sits on that spot; a floating
369
+ * bound end leaves its shape's outline toward the other end (straight) or
370
+ * from the middle of the side facing it (elbow). An end bound to a missing
371
+ * shape, or both ends bound to one shape without spots, falls back to the
372
+ * connector's last planned route.
373
+ */
374
+ const route = (shapes, arrow) => {
375
+ const fallbackStart = {
376
+ x: arrow.x,
377
+ y: arrow.y
378
+ };
379
+ const fallbackEnd = {
380
+ x: arrow.x + arrow.w,
381
+ y: arrow.y + arrow.h
382
+ };
383
+ let fromShape = bound(shapes, arrow.from, arrow.id);
384
+ let toShape = bound(shapes, arrow.to, arrow.id);
385
+ const fromAt = arrow.from._tag === "Shape" ? arrow.from.at : null;
386
+ const toAt = arrow.to._tag === "Shape" ? arrow.to.at : null;
387
+ if (fromShape !== null && toShape !== null && fromShape.id === toShape.id && (fromAt === null || toAt === null)) {
388
+ fromShape = null;
389
+ toShape = null;
390
+ }
391
+ const reference = (shape, anchor, at, fallback) => shape !== null ? at !== null ? spot(shape, at) : center(shape) : anchor._tag === "Point" ? anchor : fallback;
392
+ const fromRef = reference(fromShape, arrow.from, fromAt, fallbackStart);
393
+ const toRef = reference(toShape, arrow.to, toAt, fallbackEnd);
394
+ const resolve = (shape, at, ref, other) => {
395
+ if (shape === null) return {
396
+ point: ref,
397
+ out: null
398
+ };
399
+ if (at !== null) return {
400
+ point: ref,
401
+ out: sideNormal(shape, ref)
402
+ };
403
+ if (arrow.style.route === "elbow") return facingSide(shape, other);
404
+ return {
405
+ point: exit(shape, other),
406
+ out: null
407
+ };
408
+ };
409
+ const start = resolve(fromShape, fromAt, fromRef, toRef);
410
+ const end = resolve(toShape, toAt, toRef, fromRef);
411
+ const raw = arrow.style.route === "elbow" ? elbow(start, end) : [start.point, end.point];
412
+ return { points: dedupe(raw.map((p) => ({
413
+ x: round(p.x),
414
+ y: round(p.y)
415
+ }))) };
416
+ };
417
+ const routeStart = (r) => r.points[0] ?? {
418
+ x: 0,
419
+ y: 0
420
+ };
421
+ const routeEnd = (r) => r.points[r.points.length - 1] ?? routeStart(r);
422
+ const pointsBox = (points) => union(points.map((p) => ({
423
+ x: p.x,
424
+ y: p.y,
425
+ w: 0,
426
+ h: 0
427
+ }))) ?? {
428
+ x: 0,
429
+ y: 0,
430
+ w: 0,
431
+ h: 0
432
+ };
433
+ /** The connector with its stored route brought up to date. */
434
+ const withRoute = (shapes, arrow) => {
435
+ const r = route(shapes, arrow);
436
+ const start = routeStart(r);
437
+ const end = routeEnd(r);
438
+ const w = round(end.x - start.x);
439
+ const h = round(end.y - start.y);
440
+ return arrow.x === start.x && arrow.y === start.y && arrow.w === w && arrow.h === h ? arrow : {
441
+ ...arrow,
442
+ x: start.x,
443
+ y: start.y,
444
+ w,
445
+ h
446
+ };
447
+ };
448
+ /** The box a shape occupies: its own, or its route's for a connector. */
449
+ const bounds = (shapes, shape) => shape.kind === "Arrow" ? pointsBox(route(shapes, shape).points) : {
450
+ x: shape.x,
451
+ y: shape.y,
452
+ w: shape.w,
453
+ h: shape.h
454
+ };
455
+ const boundsOf = (shapes, ids) => {
456
+ const boxes = [];
457
+ for (const id of ids) {
458
+ const shape = shapes.get(id);
459
+ if (shape !== void 0) boxes.push(bounds(shapes, shape));
460
+ }
461
+ return union(boxes);
462
+ };
463
+ /** Field order for patches and diffs. */
464
+ const FIELDS = [
465
+ "x",
466
+ "y",
467
+ "w",
468
+ "h",
469
+ "z",
470
+ "group",
471
+ "locked",
472
+ "text",
473
+ "style",
474
+ "from",
475
+ "to",
476
+ "points",
477
+ "asset",
478
+ "alt",
479
+ "updatedBy"
480
+ ];
481
+ const jsonEqual = (a, b) => {
482
+ if (a === b) return true;
483
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, index) => jsonEqual(item, b[index]));
484
+ if (typeof a === "object" && typeof b === "object" && a !== null && b !== null) {
485
+ if (Array.isArray(a) || Array.isArray(b)) return false;
486
+ const keysA = Object.keys(a);
487
+ const keysB = Object.keys(b);
488
+ return keysA.length === keysB.length && keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && jsonEqual(Reflect.get(a, key), Reflect.get(b, key)));
489
+ }
490
+ return false;
491
+ };
492
+ /** A one-field patch holding a shape's value of `field`, or null when its kind has no such field. */
493
+ const pick = (shape, field) => {
494
+ switch (field) {
495
+ case "x":
496
+ case "y":
497
+ case "w":
498
+ case "h": return { [field]: shape[field] };
499
+ case "z": return { z: shape.z };
500
+ case "updatedBy": return { updatedBy: shape.updatedBy };
501
+ case "group": return { group: shape.group };
502
+ case "locked": return { locked: shape.locked };
503
+ case "style": return shape.kind === "Image" || shape.kind === "Timestamp" ? null : { style: shape.style };
504
+ case "text": return hasText(shape) ? { text: shape.text } : null;
505
+ case "from": return shape.kind === "Arrow" ? { from: shape.from } : null;
506
+ case "to": return shape.kind === "Arrow" ? { to: shape.to } : null;
507
+ case "points": return shape.kind === "Ink" ? { points: shape.points } : null;
508
+ case "asset": return shape.kind === "Image" ? { asset: shape.asset } : null;
509
+ case "alt": return shape.kind === "Image" ? { alt: shape.alt } : null;
510
+ }
511
+ };
512
+ /**
513
+ * Applies a patch to a shape. Returns null when a field does not belong to
514
+ * the shape's kind, or a style is not that kind's style.
515
+ */
516
+ const patchShape = (shape, fields) => {
517
+ const base = {
518
+ x: fields.x ?? shape.x,
519
+ y: fields.y ?? shape.y,
520
+ w: fields.w ?? shape.w,
521
+ h: fields.h ?? shape.h,
522
+ z: fields.z ?? shape.z,
523
+ group: fields.group === void 0 ? shape.group : fields.group,
524
+ locked: fields.locked ?? shape.locked,
525
+ updatedBy: fields.updatedBy ?? shape.updatedBy
526
+ };
527
+ const style = fields.style;
528
+ const textless = fields.text === void 0;
529
+ const unanchored = fields.from === void 0 && fields.to === void 0;
530
+ const pointless = fields.points === void 0;
531
+ if (shape.kind !== "Arrow" && (base.w < 0 || base.h < 0)) return null;
532
+ if (shape.kind !== "Image" && (fields.alt !== void 0 || fields.asset !== void 0)) return null;
533
+ switch (shape.kind) {
534
+ case "Timestamp":
535
+ if (!textless || !unanchored || !pointless || style !== void 0) return null;
536
+ return {
537
+ ...shape,
538
+ ...base
539
+ };
540
+ case "Image":
541
+ if (!textless || !unanchored || !pointless || style !== void 0) return null;
542
+ return {
543
+ ...shape,
544
+ ...base,
545
+ asset: fields.asset ?? shape.asset,
546
+ alt: fields.alt ?? shape.alt
547
+ };
548
+ case "Arrow":
549
+ if (!textless || !pointless) return null;
550
+ if (style !== void 0 && !("route" in style)) return null;
551
+ return {
552
+ ...shape,
553
+ ...base,
554
+ from: fields.from ?? shape.from,
555
+ to: fields.to ?? shape.to,
556
+ style: style ?? shape.style
557
+ };
558
+ case "Ink":
559
+ if (!textless || !unanchored) return null;
560
+ if (style !== void 0 && !("brush" in style)) return null;
561
+ return {
562
+ ...shape,
563
+ ...base,
564
+ points: fields.points ?? shape.points,
565
+ style: style ?? shape.style
566
+ };
567
+ case "Box":
568
+ if (!unanchored || !pointless) return null;
569
+ if (style !== void 0 && !("form" in style)) return null;
570
+ return {
571
+ ...shape,
572
+ ...base,
573
+ text: fields.text ?? shape.text,
574
+ style: style ?? shape.style
575
+ };
576
+ case "Text":
577
+ if (!unanchored || !pointless) return null;
578
+ if (style !== void 0 && !("width" in style)) return null;
579
+ return {
580
+ ...shape,
581
+ ...base,
582
+ text: fields.text ?? shape.text,
583
+ style: style ?? shape.style
584
+ };
585
+ case "Sticky":
586
+ if (!unanchored || !pointless) return null;
587
+ if (style !== void 0 && !isStickyStyle(style)) return null;
588
+ return {
589
+ ...shape,
590
+ ...base,
591
+ text: fields.text ?? shape.text,
592
+ style: style ?? shape.style
593
+ };
594
+ }
595
+ };
596
+ const isStickyStyle = (style) => !("form" in style) && !("width" in style) && !("route" in style) && !("brush" in style);
597
+ /** Applies row changes in order. Strict: every change must apply. */
598
+ const applyChanges = (shapes, changes) => {
599
+ for (const [index, change] of changes.entries()) switch (change.op) {
600
+ case "set":
601
+ shapes.set(change.shape.id, change.shape);
602
+ break;
603
+ case "remove":
604
+ if (!shapes.delete(change.id)) return {
605
+ _tag: "Missing",
606
+ index,
607
+ id: change.id
608
+ };
609
+ break;
610
+ case "patch": {
611
+ const current = shapes.get(change.id);
612
+ if (current === void 0) return {
613
+ _tag: "Missing",
614
+ index,
615
+ id: change.id
616
+ };
617
+ const next = patchShape(current, change.fields);
618
+ if (next === null) return {
619
+ _tag: "Mismatch",
620
+ index,
621
+ id: change.id
622
+ };
623
+ shapes.set(change.id, next);
624
+ break;
625
+ }
626
+ }
627
+ return null;
628
+ };
629
+ const fieldsOf = (shape, fields) => {
630
+ let out = {};
631
+ for (const field of fields) {
632
+ const one = pick(shape, field);
633
+ if (one !== null) out = {
634
+ ...out,
635
+ ...one
636
+ };
637
+ }
638
+ return out;
639
+ };
640
+ /**
641
+ * The changes that turn `before` into `after`, one per shape in id order,
642
+ * and their inverse.
643
+ */
644
+ const diff = (before, after) => {
645
+ const changes = [];
646
+ const inverse = [];
647
+ for (const id of sortedIds(/* @__PURE__ */ new Set([...before.keys(), ...after.keys()]))) {
648
+ const old = before.get(id);
649
+ const next = after.get(id);
650
+ if (old === void 0 && next !== void 0) {
651
+ changes.push({
652
+ op: "set",
653
+ shape: next
654
+ });
655
+ inverse.push({
656
+ op: "remove",
657
+ id
658
+ });
659
+ } else if (old !== void 0 && next === void 0) {
660
+ changes.push({
661
+ op: "remove",
662
+ id
663
+ });
664
+ inverse.push({
665
+ op: "set",
666
+ shape: old
667
+ });
668
+ } else if (old !== void 0 && next !== void 0 && !jsonEqual(old, next)) {
669
+ const changed = FIELDS.filter((field) => !jsonEqual(pick(old, field), pick(next, field)));
670
+ changes.push({
671
+ op: "patch",
672
+ id,
673
+ fields: fieldsOf(next, changed)
674
+ });
675
+ inverse.push({
676
+ op: "patch",
677
+ id,
678
+ fields: fieldsOf(old, changed)
679
+ });
680
+ }
681
+ }
682
+ return {
683
+ changes,
684
+ inverse
685
+ };
686
+ };
687
+ /** The fields a patch sets, in field order. */
688
+ const patchedFields = (fields) => FIELDS.filter((field) => Object.prototype.hasOwnProperty.call(fields, field));
689
+ /** A one-field patch of `fields`, or null when it does not set `field`. */
690
+ const pickField = (fields, field) => {
691
+ switch (field) {
692
+ case "x": return fields.x === void 0 ? null : { x: fields.x };
693
+ case "y": return fields.y === void 0 ? null : { y: fields.y };
694
+ case "w": return fields.w === void 0 ? null : { w: fields.w };
695
+ case "h": return fields.h === void 0 ? null : { h: fields.h };
696
+ case "z": return fields.z === void 0 ? null : { z: fields.z };
697
+ case "group": return fields.group === void 0 ? null : { group: fields.group };
698
+ case "locked": return fields.locked === void 0 ? null : { locked: fields.locked };
699
+ case "text": return fields.text === void 0 ? null : { text: fields.text };
700
+ case "style": return fields.style === void 0 ? null : { style: fields.style };
701
+ case "from": return fields.from === void 0 ? null : { from: fields.from };
702
+ case "to": return fields.to === void 0 ? null : { to: fields.to };
703
+ case "points": return fields.points === void 0 ? null : { points: fields.points };
704
+ case "asset": return fields.asset === void 0 ? null : { asset: fields.asset };
705
+ case "alt": return fields.alt === void 0 ? null : { alt: fields.alt };
706
+ case "updatedBy": return fields.updatedBy === void 0 ? null : { updatedBy: fields.updatedBy };
707
+ }
708
+ };
709
+ /** The current value of `field` on `shape`, as a one-field patch. */
710
+ const currentField = (shape, field) => pick(shape, field);
711
+ const history = (board) => historyOf(board.transactions);
712
+ const historyOf = (log) => {
713
+ const records = /* @__PURE__ */ new Map();
714
+ const resolvedBy = /* @__PURE__ */ new Map();
715
+ for (const record of log) {
716
+ records.set(record.id, record);
717
+ for (const target of record.accepts) if (!resolvedBy.has(target)) resolvedBy.set(target, {
718
+ by: record.id,
719
+ as: "accepted"
720
+ });
721
+ for (const target of record.reverts) if (!resolvedBy.has(target)) resolvedBy.set(target, {
722
+ by: record.id,
723
+ as: "reverted"
724
+ });
725
+ }
726
+ return {
727
+ records,
728
+ resolvedBy
729
+ };
730
+ };
731
+ const isPending = (record, h) => record.mode === "propose" && !h.resolvedBy.has(record.id);
732
+ /** UTF-8 length of a string. JSON text has no lone surrogates. */
733
+ const utf8Length = (text) => {
734
+ let length = 0;
735
+ for (let i = 0; i < text.length; i++) {
736
+ const code = text.charCodeAt(i);
737
+ if (code < 128) length += 1;
738
+ else if (code < 2048) length += 2;
739
+ else if (code >= 55296 && code <= 56319) {
740
+ length += 4;
741
+ i++;
742
+ } else length += 3;
743
+ }
744
+ return length;
745
+ };
746
+ const sizes = /* @__PURE__ */ new WeakMap();
747
+ /** A record's size: UTF-8 bytes of its compact JSON. Key order does not change it. */
748
+ const recordBytes = (record) => {
749
+ const known = sizes.get(record);
750
+ if (known !== void 0) return known;
751
+ const size = utf8Length(JSON.stringify(record));
752
+ sizes.set(record, size);
753
+ return size;
754
+ };
755
+ /**
756
+ * Drops the oldest settled records until the log fits `HISTORY`. Pending
757
+ * proposals and the newest record stay. A record is settled once nothing can
758
+ * resolve it, and whatever resolved it is newer, so it goes first.
759
+ */
760
+ const trimHistory = (log) => {
761
+ let count = log.length;
762
+ let bytes = 0;
763
+ for (const record of log) bytes += recordBytes(record);
764
+ if (count <= HISTORY.records && bytes <= HISTORY.bytes) return log;
765
+ const h = historyOf(log);
766
+ const newest = log[log.length - 1];
767
+ return log.filter((record) => {
768
+ if (count <= HISTORY.records && bytes <= HISTORY.bytes) return true;
769
+ if (record === newest || isPending(record, h)) return true;
770
+ count -= 1;
771
+ bytes -= recordBytes(record);
772
+ return false;
773
+ });
774
+ };
775
+ /** Pending proposals in log order. */
776
+ const pendingProposals = (board, h) => board.transactions.filter((record) => isPending(record, h));
777
+ /**
778
+ * Applies a proposal's changes to the current rows, leniently: a patch or
779
+ * removal of a shape that is gone is skipped, as is a patch the shape's kind
780
+ * no longer takes. Returns the id of a shape the proposal creates that
781
+ * already exists, if any, and applies nothing more after it.
782
+ */
783
+ const applyProposal = (shapes, record) => {
784
+ for (const change of record.changes) if (change.op === "set") {
785
+ if (shapes.has(change.shape.id)) return change.shape.id;
786
+ shapes.set(change.shape.id, change.shape);
787
+ } else if (change.op === "remove") shapes.delete(change.id);
788
+ else {
789
+ const current = shapes.get(change.id);
790
+ if (current === void 0) continue;
791
+ shapes.set(change.id, patchShape(current, change.fields) ?? current);
792
+ }
793
+ return null;
794
+ };
795
+ /** Connectors that are among `ids` or attach to one of them, in id order. */
796
+ const affectedArrows = (shapes, ids) => {
797
+ const out = [];
798
+ for (const shape of shapes.values()) {
799
+ if (shape.kind !== "Arrow") continue;
800
+ if (ids.has(shape.id) || shape.from._tag === "Shape" && ids.has(shape.from.id) || shape.to._tag === "Shape" && ids.has(shape.to.id)) out.push(shape.id);
801
+ }
802
+ return sortedIds(out);
803
+ };
804
+ /** Brings stored routes up to date for the given connectors. */
805
+ const refreshRoutes = (shapes, arrowIds) => {
806
+ for (const id of arrowIds) {
807
+ const arrow = shapes.get(id);
808
+ if (arrow?.kind === "Arrow") shapes.set(id, withRoute(shapes, arrow));
809
+ }
810
+ };
811
+ const indexes = /* @__PURE__ */ new WeakMap();
812
+ const indexBoard = (board) => {
813
+ const cached = indexes.get(board);
814
+ if (cached !== void 0) return cached;
815
+ const index = {
816
+ shapes: toMap(board.shapes),
817
+ ordered: [...board.shapes].sort(compareShapes)
818
+ };
819
+ indexes.set(board, index);
820
+ return index;
821
+ };
822
+ /** Stroke width and opacity of ink. */
823
+ const inkStroke = (style) => ({
824
+ width: INK_WIDTH[style.size] * BRUSH[style.brush].width,
825
+ opacity: BRUSH[style.brush].opacity
826
+ });
827
+ const rectPath = (b) => `M${pair(b)}H${formatNumber(b.x + b.w)}V${formatNumber(b.y + b.h)}H${formatNumber(b.x)}Z`;
828
+ const ellipsePath = (b) => {
829
+ const rx = b.w / 2;
830
+ const ry = b.h / 2;
831
+ const cy = b.y + ry;
832
+ const arc = `A${formatNumber(rx)} ${formatNumber(ry)} 0 1 1`;
833
+ return `M${pair({
834
+ x: b.x,
835
+ y: cy
836
+ })}${arc} ${pair({
837
+ x: b.x + b.w,
838
+ y: cy
839
+ })}${arc} ${pair({
840
+ x: b.x,
841
+ y: cy
842
+ })}Z`;
843
+ };
844
+ /** A shape's outline as SVG path data, for hover and selection outlines. */
845
+ const outlinePath = (shapes, shape) => {
846
+ switch (shape.kind) {
847
+ case "Arrow": return polylinePath(route(shapes, shape).points);
848
+ case "Ink": return strokePath(inkPoints(shape));
849
+ case "Box": return shape.style.form === "ellipse" ? ellipsePath(shape) : rectPath(shape);
850
+ case "Sticky":
851
+ case "Text":
852
+ case "Image":
853
+ case "Timestamp": return rectPath(shape);
854
+ }
855
+ };
856
+ export { affectedArrows, applyChanges, applyProposal, bounds, boundsOf, compareShapes, currentField, diff, fitText, hasText, history, indexBoard, inkGeometry, inkPoints, inkStroke, jsonEqual, layoutText, ordered, outlinePath, patchShape, patchedFields, pendingProposals, pickField, polylinePath, recordBytes, refreshRoutes, route, routeEnd, routeStart, sortedIds, strokeCurve, strokePath, toMap, trimHistory, withRoute };