@zsherman/canvas 0.0.0-stage → 0.1.0

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 +7 -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 +1353 -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 +55 -4
@@ -0,0 +1,697 @@
1
+ import { expectOk } from "./kernel.jsx";
2
+ import { randomId } from "./random-id.jsx";
3
+ import { createPresenceMotion, stepCamera } from "./motion.jsx";
4
+ // src/canvas/canvas-controller.ts
5
+ /**
6
+ * Inputs that move the view from where it is shown: while the camera is
7
+ * still easing, the editor first takes the shown view, so the move starts
8
+ * from what the viewer sees instead of jumping to where the camera was going.
9
+ */
10
+ const MOVES_SHOWN_VIEW = /* @__PURE__ */ new Set([
11
+ "Pan",
12
+ "Wheel",
13
+ "Zoom"
14
+ ]);
15
+ /**
16
+ * Inputs by which the viewer starts working on the board. The first ends
17
+ * the opening fit, so chrome that appears in answer, such as the style bar
18
+ * for a chosen tool, never moves the view under them.
19
+ */
20
+ const ENDS_OPENING_FIT = /* @__PURE__ */ new Set([
21
+ "Action",
22
+ "BeginUpload",
23
+ "DoubleClick",
24
+ "Follow",
25
+ "KeyDown",
26
+ "Pan",
27
+ "Paste",
28
+ "PasteText",
29
+ "PointerDown",
30
+ "Select",
31
+ "Style",
32
+ "Wheel",
33
+ "Zoom",
34
+ "ZoomTo"
35
+ ]);
36
+ const systemClock = {
37
+ cancel: (handle) => "cancelAnimationFrame" in globalThis ? cancelAnimationFrame(handle) : clearTimeout(handle),
38
+ frame: (callback) => "requestAnimationFrame" in globalThis ? requestAnimationFrame(callback) : Number(setTimeout(() => callback(performance.now()), 16)),
39
+ now: () => performance.now()
40
+ };
41
+ /** The kernel's actions only a host with comments offers. */
42
+ const COMMENT_ACTIONS = /* @__PURE__ */ new Set(["tool-comment"]);
43
+ /** Epoch milliseconds: the instant a timestamp shape keeps. */
44
+ const epochNow = () => Date.now();
45
+ function sessionId() {
46
+ return `s${Math.random().toString(36).slice(2, 12)}`;
47
+ }
48
+ /**
49
+ * The kernel's sentences that refuse what the viewer asked for, which the
50
+ * board's notice shows as well as reads out: "Can't …", an undo or redo that
51
+ * left shapes alone ("…, except …"), a shape someone else holds ("Lee Park
52
+ * is editing this", "You're editing this in another tab"), and a command on a
53
+ * read-only board. Everything else it says (selection, "Grouped", "Pen
54
+ * tool", "Stopped following: they left the board") narrates what the viewer
55
+ * already sees, so it is only read out.
56
+ */
57
+ const REFUSAL = /^Can't |, except | editing this|^This board is read-only$/;
58
+ /** What to tell the viewer when a change cannot be made, by why. */
59
+ function problemText(error) {
60
+ switch (error?._tag) {
61
+ case "Claimed": return "Someone else is editing that right now";
62
+ case "HistoryExpired": return "That change is too old to undo or review";
63
+ case "Locked": return "That shape is locked. Unlock it to change it";
64
+ case "ShapeNotFound":
65
+ case "TransactionNotFound": return "Someone else changed that first";
66
+ case "TooLarge": return "That is too much to change at once. Try fewer shapes";
67
+ case "Invalid":
68
+ case void 0: return "That change could not be saved";
69
+ }
70
+ }
71
+ function prefersReducedMotion() {
72
+ return "matchMedia" in globalThis && matchMedia("(prefers-reduced-motion: reduce)").matches;
73
+ }
74
+ /**
75
+ * Runs the kernel's host loop for one viewer: inputs go through `editor`,
76
+ * transactions are planned, applied and handed to the store, and refusals
77
+ * roll back. The shown camera eases toward the editor's view, and other
78
+ * people's presence is smoothed between samples, on animation frames that
79
+ * run only while something moves.
80
+ */
81
+ function createCanvasController({ canvas, clock = systemClock, comments: withComments = false, onClipboard, onError, readOnly = false, store, view: given }) {
82
+ const start = given ?? {
83
+ x: 0,
84
+ y: 0,
85
+ zoom: 1
86
+ };
87
+ /**
88
+ * With no given view, the board keeps its content fitted as its size and
89
+ * chrome settle, until the viewer starts working: moves the view, picks a
90
+ * tool, selects, or changes the board.
91
+ */
92
+ let autoFit = given === void 0;
93
+ const { kernel } = canvas;
94
+ let state = expectOk(kernel.initialEditor(store.connection ?? sessionId(), {
95
+ ...start,
96
+ h: 768 / start.zoom,
97
+ viewer: store.actor,
98
+ w: 1024 / start.zoom
99
+ }));
100
+ let cursor = "default";
101
+ let announcement = null;
102
+ let board = store.getBoard();
103
+ /** Everyone else's presence as it last arrived: the editor and planning read it. */
104
+ let presence = store.getPresence();
105
+ const motion = createPresenceMotion({ reduced: prefersReducedMotion });
106
+ motion.push(presence, clock.now());
107
+ motion.board(board, clock.now(), false);
108
+ let committing = false;
109
+ /** The last copy or cut, to paste shapes back when only text survived the system clipboard. */
110
+ let lastClipboard = null;
111
+ let problem = null;
112
+ let unsaved = null;
113
+ /** Transactions sent to the store and not yet settled. */
114
+ const unsettled = /* @__PURE__ */ new Set();
115
+ const listeners = /* @__PURE__ */ new Set();
116
+ const drawListeners = /* @__PURE__ */ new Set();
117
+ const placeListeners = /* @__PURE__ */ new Set();
118
+ /** Clicks with the comment or timestamp tool, carried out once their input's step is done. */
119
+ let placed = [];
120
+ let comments = withComments;
121
+ /** The camera: the view as drawn, easing toward `state.view`. */
122
+ let shown = state.view;
123
+ let camera = null;
124
+ /** The viewer's presence, published once per frame with the latest. */
125
+ let outgoing = null;
126
+ let frameHandle = null;
127
+ let frame = {
128
+ presence,
129
+ view: shown
130
+ };
131
+ const take = () => ({
132
+ announcement,
133
+ board,
134
+ comments,
135
+ cursor,
136
+ pending: unsettled.size,
137
+ presence,
138
+ problem,
139
+ state,
140
+ unsaved
141
+ });
142
+ let snapshot = take();
143
+ /** Redraws the board, for a new snapshot or a frame that moved. */
144
+ const draw = () => {
145
+ for (const listener of Array.from(drawListeners)) listener();
146
+ };
147
+ const emit = () => {
148
+ snapshot = take();
149
+ refreshFrame(clock.now());
150
+ for (const listener of Array.from(listeners)) listener();
151
+ draw();
152
+ };
153
+ /** Brings the frame up to `now`; true when it changed. */
154
+ function refreshFrame(now) {
155
+ const sampled = motion.sample(now);
156
+ if (camera !== null) {
157
+ const step = stepCamera(shown, state.view, camera, now);
158
+ shown = step.view;
159
+ camera = step.motion;
160
+ }
161
+ if (sampled.presence === frame.presence && shown === frame.view) return false;
162
+ frame = {
163
+ presence: sampled.presence,
164
+ view: shown
165
+ };
166
+ return true;
167
+ }
168
+ function tick(now) {
169
+ frameHandle = null;
170
+ if (outgoing !== null) {
171
+ const sending = outgoing;
172
+ outgoing = null;
173
+ store.publish(sending, state.session);
174
+ }
175
+ if (refreshFrame(now)) draw();
176
+ if (camera !== null || motion.sample(now).moving) schedule();
177
+ }
178
+ function schedule() {
179
+ frameHandle ??= clock.frame(tick);
180
+ }
181
+ /** Sends the presence waiting for the next frame now, such as on unmount. */
182
+ function flushPresence() {
183
+ if (outgoing === null) return;
184
+ const sending = outgoing;
185
+ outgoing = null;
186
+ store.publish(sending, state.session);
187
+ }
188
+ /** Stops the camera where the editor's view is. */
189
+ function settleCamera() {
190
+ camera = null;
191
+ shown = state.view;
192
+ }
193
+ /** Reads `text` out and, when `visible`, shows it as the board's notice. */
194
+ const announce = (text, visible = REFUSAL.test(text)) => {
195
+ announcement = {
196
+ id: (announcement?.id ?? 0) + 1,
197
+ text
198
+ };
199
+ if (visible) problem = {
200
+ id: (problem?.id ?? 0) + 1,
201
+ text
202
+ };
203
+ };
204
+ /** Rolls a refused change back in the editor, then tells the viewer and the host why. */
205
+ function refuse(transaction, error) {
206
+ unsettled.delete(transaction);
207
+ run({
208
+ _tag: "Rejected",
209
+ transaction
210
+ });
211
+ const text = problemText(error);
212
+ announce(text, true);
213
+ onError?.({
214
+ error,
215
+ text,
216
+ transaction
217
+ });
218
+ }
219
+ /** Settles a commit: a confirmation only clears it; a refusal rolls it back. */
220
+ function settle(transaction, result) {
221
+ if (!unsettled.has(transaction)) return;
222
+ if (result._tag === "Confirmed") {
223
+ unsettled.delete(transaction);
224
+ return;
225
+ }
226
+ board = store.getBoard();
227
+ motion.board(board, clock.now(), false);
228
+ refuse(transaction, result.error);
229
+ }
230
+ function commit(change) {
231
+ const id = change.transaction.id;
232
+ unsettled.add(id);
233
+ committing = true;
234
+ let result;
235
+ try {
236
+ result = store.commit(change);
237
+ } catch {
238
+ result = {
239
+ _tag: "Refused",
240
+ error: null
241
+ };
242
+ } finally {
243
+ committing = false;
244
+ }
245
+ board = store.getBoard();
246
+ motion.board(board, clock.now(), false);
247
+ if (!(result instanceof Promise)) {
248
+ settle(id, result);
249
+ return;
250
+ }
251
+ result.catch(() => ({
252
+ _tag: "Refused",
253
+ error: null
254
+ })).then((settled) => {
255
+ settle(id, settled);
256
+ emit();
257
+ });
258
+ }
259
+ function planAndApply(transaction) {
260
+ const plan = kernel.plan(board, transaction, store.actor, presence, state.session);
261
+ if ("error" in plan) return plan;
262
+ const next = kernel.apply(board, plan.ok);
263
+ if ("error" in next) return next;
264
+ return { ok: {
265
+ board: next.ok,
266
+ plan: plan.ok
267
+ } };
268
+ }
269
+ /** Points the camera at a view the kernel chose: eased, or at once. */
270
+ function aim(view, animate) {
271
+ if (!animate || prefersReducedMotion()) {
272
+ camera = null;
273
+ shown = view;
274
+ return;
275
+ }
276
+ const now = clock.now();
277
+ camera = state.following === null ? {
278
+ _tag: "Glide",
279
+ began: now,
280
+ from: shown
281
+ } : {
282
+ _tag: "Follow",
283
+ last: camera?._tag === "Follow" ? camera.last : now
284
+ };
285
+ schedule();
286
+ }
287
+ /** Carries out one editor action; a copy or cut returns what it copied. */
288
+ function perform(action) {
289
+ switch (action._tag) {
290
+ case "Apply": {
291
+ autoFit = false;
292
+ const outcome = planAndApply(action.transaction);
293
+ if ("error" in outcome) {
294
+ refuse(action.transaction.id, outcome.error);
295
+ return null;
296
+ }
297
+ commit({
298
+ ...outcome.ok,
299
+ transaction: action.transaction
300
+ });
301
+ return null;
302
+ }
303
+ case "Presence":
304
+ outgoing = action.presence;
305
+ schedule();
306
+ return null;
307
+ case "Viewport":
308
+ aim(action.view, action.animate);
309
+ return null;
310
+ case "Clipboard":
311
+ lastClipboard = action.data;
312
+ return action.data;
313
+ case "Announce":
314
+ announce(action.text);
315
+ return null;
316
+ case "Unsaved":
317
+ unsaved = {
318
+ id: (unsaved?.id ?? 0) + 1,
319
+ target: action.id,
320
+ text: action.text
321
+ };
322
+ return null;
323
+ case "Place":
324
+ placed.push(action);
325
+ return null;
326
+ }
327
+ }
328
+ /**
329
+ * Carries out the last input's clicks: a timestamp is created holding the
330
+ * instant of the click, as a change the viewer can undo; a comment click
331
+ * goes to the listeners, which open a new thread there. A timestamp placed
332
+ * on a shape joins that shape's group, so it moves and is deleted with the
333
+ * shape; a locked shape cannot be grouped, so its timestamp stands alone.
334
+ */
335
+ function place() {
336
+ const clicks = placed;
337
+ placed = [];
338
+ for (const click of clicks) if (click.tool === "timestamp") {
339
+ const id = randomId();
340
+ const under = board.shapes.find((row) => row.id === click.shape);
341
+ const commands = [{
342
+ _tag: "Create",
343
+ place: {
344
+ _tag: "At",
345
+ x: click.at.x,
346
+ y: click.at.y
347
+ },
348
+ shape: {
349
+ at: epochNow(),
350
+ id,
351
+ kind: "Timestamp"
352
+ }
353
+ }];
354
+ if (under !== void 0 && !under.locked) {
355
+ const ids = [under.id, id];
356
+ commands.push(under.group === null ? {
357
+ _tag: "Group",
358
+ ids
359
+ } : {
360
+ _tag: "Group",
361
+ group: under.group,
362
+ ids
363
+ });
364
+ }
365
+ run({
366
+ _tag: "Run",
367
+ commands,
368
+ reason: null
369
+ });
370
+ } else if (comments) for (const listener of Array.from(placeListeners)) listener(click);
371
+ }
372
+ /** True when the input asks for an action the host does not offer. */
373
+ function unavailable(input) {
374
+ if (comments) return false;
375
+ if (input._tag === "Action") return COMMENT_ACTIONS.has(input.action);
376
+ if (input._tag !== "KeyDown") return false;
377
+ const key = input.key.toLowerCase();
378
+ const { modifiers } = input;
379
+ return expectOk(kernel.actions(state, board, presence)).some((action) => COMMENT_ACTIONS.has(action.id) && action.shortcuts.some((shortcut) => shortcut.key.toLowerCase() === key && shortcut.meta === modifiers.meta && shortcut.alt === modifiers.alt && shortcut.shift === modifiers.shift));
380
+ }
381
+ /** One input through the editor, then its actions in order. */
382
+ function run(input) {
383
+ const before = state.view;
384
+ const outcome = kernel.editor(state, board, input, presence);
385
+ if ("error" in outcome) {
386
+ announce(input._tag === "Paste" || input._tag === "PasteText" ? "That can't be pasted on the board" : "That didn't work on the board", true);
387
+ return {
388
+ clipboard: null,
389
+ handled: false
390
+ };
391
+ }
392
+ state = outcome.ok.state;
393
+ cursor = outcome.ok.cursor;
394
+ let copied = null;
395
+ for (const action of outcome.ok.actions) copied = perform(action) ?? copied;
396
+ if (camera === null && state.view !== before) shown = state.view;
397
+ return {
398
+ clipboard: copied,
399
+ handled: outcome.ok.handled
400
+ };
401
+ }
402
+ if (readOnly) run({
403
+ _tag: "ReadOnly",
404
+ readOnly: true
405
+ });
406
+ settleCamera();
407
+ frame = {
408
+ presence,
409
+ view: shown
410
+ };
411
+ snapshot = take();
412
+ /**
413
+ * Ends text editing the way Escape does, keeping the draft. The kernel keeps
414
+ * editing through a blur and drops the draft on read-only, so the board
415
+ * finishes first whenever the editor loses the viewer.
416
+ */
417
+ function finishText() {
418
+ if (state.mode._tag !== "EditingText") return;
419
+ run({
420
+ _tag: "KeyDown",
421
+ key: "Escape",
422
+ modifiers: {
423
+ alt: false,
424
+ meta: false,
425
+ shift: false
426
+ }
427
+ });
428
+ }
429
+ /** The view centred on `point`, at the current zoom, the same size on screen. */
430
+ function centredOn(point) {
431
+ const view = state.view;
432
+ return {
433
+ ...view,
434
+ x: point.x - view.w / 2,
435
+ y: point.y - view.h / 2
436
+ };
437
+ }
438
+ /** A point in the surface, in screen pixels from its top left, on the board as shown. */
439
+ function toBoard(x, y) {
440
+ return {
441
+ x: shown.x + x / shown.zoom,
442
+ y: shown.y + y / shown.zoom
443
+ };
444
+ }
445
+ /** Shows and announces something the board could not do, such as a file it can't add. */
446
+ function notify(text) {
447
+ announce(text, true);
448
+ emit();
449
+ }
450
+ /** The name of the actor the viewer follows, if they are still here. */
451
+ function leaderName() {
452
+ const { following } = state;
453
+ return presence.find((other) => other.actor === following)?.name;
454
+ }
455
+ /**
456
+ * Opens on the whole board: the largest zoom, never above 100%, at which
457
+ * its shapes fit the area the chrome leaves clear, centred there. Other
458
+ * people's cursors do not count. Zooming in is one control away.
459
+ */
460
+ function openOnContent() {
461
+ run({
462
+ _tag: "ZoomTo",
463
+ to: "fit"
464
+ });
465
+ settleCamera();
466
+ }
467
+ /** Takes the store's latest board and presence; true when anything changed. */
468
+ function pull() {
469
+ const nextPresence = store.getPresence();
470
+ const nextBoard = store.getBoard();
471
+ if (nextBoard === board && nextPresence === presence) return false;
472
+ if (nextPresence !== presence) {
473
+ presence = nextPresence;
474
+ motion.push(presence, clock.now());
475
+ schedule();
476
+ }
477
+ if (nextBoard !== board) {
478
+ motion.board(nextBoard, clock.now(), true);
479
+ schedule();
480
+ }
481
+ board = nextBoard;
482
+ run({ _tag: "Sync" });
483
+ return true;
484
+ }
485
+ const onStore = () => {
486
+ if (!committing && pull()) emit();
487
+ };
488
+ let unsubscribe = null;
489
+ /** The last actions asked for, by the state, board and presence they were for. */
490
+ let actionsFor = null;
491
+ return {
492
+ /**
493
+ * Every action for a snapshot, asked of the kernel once however many
494
+ * menus and toolbars read it.
495
+ */
496
+ actions(of) {
497
+ if (actionsFor?.state === of.state && actionsFor.board === of.board && actionsFor.presence === of.presence) return actionsFor.actions;
498
+ const actions = new Map(expectOk(kernel.actions(of.state, of.board, of.presence)).map((action) => [action.id, action]));
499
+ actionsFor = {
500
+ actions,
501
+ board: of.board,
502
+ presence: of.presence,
503
+ state: of.state
504
+ };
505
+ return actions;
506
+ },
507
+ /** Sends an input from the person or the host, and redraws. */
508
+ dispatch(input) {
509
+ if (unavailable(input)) return {
510
+ clipboard: null,
511
+ handled: false
512
+ };
513
+ if (camera !== null && MOVES_SHOWN_VIEW.has(input._tag)) {
514
+ if (state.following !== null) run({
515
+ _tag: "Follow",
516
+ actor: null
517
+ });
518
+ run({
519
+ _tag: "SetView",
520
+ view: shown
521
+ });
522
+ settleCamera();
523
+ }
524
+ if (input._tag === "SetView") camera = null;
525
+ if (input._tag === "Blur") finishText();
526
+ const before = state.view;
527
+ const step = run(input);
528
+ place();
529
+ if ((before.x !== state.view.x || before.y !== state.view.y || before.zoom !== state.view.zoom) && input._tag !== "SetView" || ENDS_OPENING_FIT.has(input._tag)) autoFit = false;
530
+ if (step.clipboard !== null && input._tag === "Action") onClipboard?.(step.clipboard);
531
+ emit();
532
+ return step;
533
+ },
534
+ /**
535
+ * Shapes copied from a board, read from clipboard text; null for
536
+ * anything else. A board clipboard this board can't read says so.
537
+ */
538
+ readClipboard(text) {
539
+ const decoded = canvas.decodeClipboard(text);
540
+ if (decoded._tag === "Shapes") return decoded.clipboard;
541
+ if (decoded._tag === "Invalid") notify("Those shapes can't be pasted here. Copy them again from the board.");
542
+ return null;
543
+ },
544
+ /** Shows and announces something the board could not do, such as a file it can't add. */
545
+ /** Says something to assistive technology only, such as why an upload failed. */
546
+ announce(text) {
547
+ announce(text);
548
+ emit();
549
+ },
550
+ notify,
551
+ /** Forgets the unsaved text once the viewer has dealt with it. */
552
+ dismissUnsaved() {
553
+ if (unsaved === null) return;
554
+ unsaved = null;
555
+ emit();
556
+ },
557
+ /** Glides the view to centre on a board point, keeping the zoom. */
558
+ centerOn(point) {
559
+ autoFit = false;
560
+ run({
561
+ _tag: "Follow",
562
+ actor: null
563
+ });
564
+ run({
565
+ _tag: "SetView",
566
+ view: centredOn(point)
567
+ });
568
+ aim(state.view, true);
569
+ emit();
570
+ },
571
+ /**
572
+ * Tracks another person's or agent's view until the viewer pans or zooms,
573
+ * or `follow(null)`; a second call with the same actor stops it. The
574
+ * kernel fits the leader's view and the camera eases there.
575
+ */
576
+ follow(actor) {
577
+ const leader = presence.find((other) => other.actor === actor);
578
+ if (actor === null || actor === state.following || leader === void 0) {
579
+ const name = leaderName();
580
+ run({
581
+ _tag: "Follow",
582
+ actor: null
583
+ });
584
+ if (name !== void 0) announce(`Stopped following ${name}`);
585
+ } else {
586
+ autoFit = false;
587
+ run({
588
+ _tag: "Follow",
589
+ actor
590
+ });
591
+ announce(`Following ${leader.name}`);
592
+ }
593
+ emit();
594
+ },
595
+ /** The camera and smoothed presence to draw now. */
596
+ getFrame: () => frame,
597
+ getSnapshot: () => snapshot,
598
+ lastClipboard: () => lastClipboard,
599
+ kernel,
600
+ metrics: canvas.metrics,
601
+ /** The surface's size in screen pixels changed. */
602
+ resize(width, height) {
603
+ if (width <= 0 || height <= 0) return;
604
+ const view = state.view;
605
+ const w = width / view.zoom;
606
+ const h = height / view.zoom;
607
+ if (Math.abs(w - view.w) < .01 && Math.abs(h - view.h) < .01) return;
608
+ run({
609
+ _tag: "SetView",
610
+ view: {
611
+ ...view,
612
+ h,
613
+ w
614
+ }
615
+ });
616
+ if (autoFit) openOnContent();
617
+ emit();
618
+ },
619
+ /** Screen pixels the chrome covers on each edge; fits and zoom steps keep clear of them. */
620
+ setInset(inset) {
621
+ const current = state.inset;
622
+ if (current.top === inset.top && current.right === inset.right && current.bottom === inset.bottom && current.left === inset.left) return;
623
+ run({
624
+ _tag: "Inset",
625
+ inset
626
+ });
627
+ if (autoFit) openOnContent();
628
+ emit();
629
+ },
630
+ store,
631
+ subscribe(listener) {
632
+ if (listeners.size === 0) {
633
+ unsubscribe = store.subscribe(onStore);
634
+ if (pull()) emit();
635
+ }
636
+ listeners.add(listener);
637
+ return () => {
638
+ listeners.delete(listener);
639
+ if (listeners.size > 0) return;
640
+ settleCamera();
641
+ finishText();
642
+ flushPresence();
643
+ if (frameHandle !== null) clock.cancel(frameHandle);
644
+ frameHandle = null;
645
+ unsubscribe?.();
646
+ unsubscribe = null;
647
+ };
648
+ },
649
+ /**
650
+ * Turns the comment tool on or off with the host's comments; turning it
651
+ * off while it is in use goes back to Select.
652
+ */
653
+ setComments(next) {
654
+ if (next === comments) return;
655
+ comments = next;
656
+ if (!next && state.tool === "comment") run({
657
+ _tag: "Action",
658
+ action: "tool-select"
659
+ });
660
+ emit();
661
+ },
662
+ /** Calls back on each click with the comment tool. Returns an unsubscribe. */
663
+ subscribePlace(listener) {
664
+ placeListeners.add(listener);
665
+ return () => {
666
+ placeListeners.delete(listener);
667
+ };
668
+ },
669
+ /** Redraws on every snapshot and every animation frame that moved. */
670
+ subscribeDraw(listener) {
671
+ drawListeners.add(listener);
672
+ return () => {
673
+ drawListeners.delete(listener);
674
+ };
675
+ },
676
+ /** The board point at the middle of the area the chrome leaves clear. */
677
+ centre() {
678
+ const { inset } = state;
679
+ const w = shown.w * shown.zoom;
680
+ const h = shown.h * shown.zoom;
681
+ const clearW = w - inset.left - inset.right;
682
+ const clearH = h - inset.top - inset.bottom;
683
+ return clearW > 0 && clearH > 0 ? toBoard(inset.left + clearW / 2, inset.top + clearH / 2) : toBoard(w / 2, h / 2);
684
+ },
685
+ toBoard,
686
+ setReadOnly(next) {
687
+ if (next === state.readOnly) return;
688
+ if (next) finishText();
689
+ run({
690
+ _tag: "ReadOnly",
691
+ readOnly: next
692
+ });
693
+ emit();
694
+ }
695
+ };
696
+ }
697
+ export { createCanvasController };