@haklex/rich-ext-whiteboard 0.65.7 → 0.67.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 (99) hide show
  1. package/README.md +45 -5
  2. package/dist/InteractiveScene-CpoWGP_L.js +424 -0
  3. package/dist/WhiteboardEditor-cZ32fLqJ.js +4799 -0
  4. package/dist/WhiteboardExpandShell-BBjXd5qK.js +474 -0
  5. package/dist/editor/ContextMenu.d.ts +9 -0
  6. package/dist/editor/ContextMenu.d.ts.map +1 -0
  7. package/dist/editor/MobileDock.d.ts +2 -0
  8. package/dist/editor/MobileDock.d.ts.map +1 -1
  9. package/dist/editor/TextEditor.d.ts.map +1 -1
  10. package/dist/editor/Toolbar.d.ts +1 -0
  11. package/dist/editor/Toolbar.d.ts.map +1 -1
  12. package/dist/editor/WhiteboardCanvas.d.ts +2 -1
  13. package/dist/editor/WhiteboardCanvas.d.ts.map +1 -1
  14. package/dist/editor/WhiteboardEditor.d.ts +15 -0
  15. package/dist/editor/WhiteboardEditor.d.ts.map +1 -1
  16. package/dist/editor/card-actions.d.ts +8 -0
  17. package/dist/editor/card-actions.d.ts.map +1 -0
  18. package/dist/editor/chrome.css.d.ts +3 -0
  19. package/dist/editor/chrome.css.d.ts.map +1 -1
  20. package/dist/editor/context-menu.d.ts +27 -0
  21. package/dist/editor/context-menu.d.ts.map +1 -0
  22. package/dist/editor/context-menu.test.d.ts +2 -0
  23. package/dist/editor/context-menu.test.d.ts.map +1 -0
  24. package/dist/editor/embed.test.d.ts +2 -0
  25. package/dist/editor/embed.test.d.ts.map +1 -0
  26. package/dist/editor/focus.d.ts +11 -0
  27. package/dist/editor/focus.d.ts.map +1 -0
  28. package/dist/editor/remote-edit.test.d.ts +2 -0
  29. package/dist/editor/remote-edit.test.d.ts.map +1 -0
  30. package/dist/editor/shortcuts.d.ts +1 -1
  31. package/dist/editor/shortcuts.d.ts.map +1 -1
  32. package/dist/editor/store.d.ts +10 -1
  33. package/dist/editor/store.d.ts.map +1 -1
  34. package/dist/editor/tools/card.d.ts +0 -2
  35. package/dist/editor/tools/card.d.ts.map +1 -1
  36. package/dist/editor-entry.d.ts +28 -0
  37. package/dist/editor-entry.d.ts.map +1 -0
  38. package/dist/editor.mjs +186 -0
  39. package/dist/export/export.test.d.ts +2 -0
  40. package/dist/export/export.test.d.ts.map +1 -0
  41. package/dist/export/fonts.d.ts +22 -0
  42. package/dist/export/fonts.d.ts.map +1 -0
  43. package/dist/export/index.d.ts +7 -0
  44. package/dist/export/index.d.ts.map +1 -0
  45. package/dist/export/png.d.ts +10 -0
  46. package/dist/export/png.d.ts.map +1 -0
  47. package/dist/export/svg.d.ts +19 -0
  48. package/dist/export/svg.d.ts.map +1 -0
  49. package/dist/export-B_abF5zK.js +248 -0
  50. package/dist/index.mjs +6 -4408
  51. package/dist/model/reconcile.d.ts +14 -0
  52. package/dist/model/reconcile.d.ts.map +1 -0
  53. package/dist/model/reconcile.test.d.ts +2 -0
  54. package/dist/model/reconcile.test.d.ts.map +1 -0
  55. package/dist/model/restore-fonts.test.d.ts +2 -0
  56. package/dist/model/restore-fonts.test.d.ts.map +1 -0
  57. package/dist/model/restore.d.ts +5 -0
  58. package/dist/model/restore.d.ts.map +1 -1
  59. package/dist/model/richtext-layout.d.ts +2 -0
  60. package/dist/model/richtext-layout.d.ts.map +1 -1
  61. package/dist/model/skeleton.d.ts +21 -0
  62. package/dist/model/skeleton.d.ts.map +1 -0
  63. package/dist/model/skeleton.test.d.ts +2 -0
  64. package/dist/model/skeleton.test.d.ts.map +1 -0
  65. package/dist/model/supersede.d.ts +3 -0
  66. package/dist/model/supersede.d.ts.map +1 -0
  67. package/dist/model/viewport-fit.d.ts +24 -0
  68. package/dist/model/viewport-fit.d.ts.map +1 -0
  69. package/dist/reconcile-Of9Y1rFE.js +57 -0
  70. package/dist/rich-ext-whiteboard.css +1 -1
  71. package/dist/scene/InteractiveScene.d.ts +14 -1
  72. package/dist/scene/InteractiveScene.d.ts.map +1 -1
  73. package/dist/scene/Scene.d.ts +1 -0
  74. package/dist/scene/Scene.d.ts.map +1 -1
  75. package/dist/scene/SceneControls.d.ts +10 -0
  76. package/dist/scene/SceneControls.d.ts.map +1 -0
  77. package/dist/scene/context.d.ts +2 -0
  78. package/dist/scene/context.d.ts.map +1 -1
  79. package/dist/scene/elements.d.ts.map +1 -1
  80. package/dist/scene/fonts.d.ts +2 -0
  81. package/dist/scene/fonts.d.ts.map +1 -1
  82. package/dist/scene/fonts.test.d.ts +2 -0
  83. package/dist/scene/fonts.test.d.ts.map +1 -0
  84. package/dist/scene/interactive.test.d.ts +2 -0
  85. package/dist/scene/interactive.test.d.ts.map +1 -0
  86. package/dist/scene/richtext/RichTextSvgBody.d.ts +6 -0
  87. package/dist/scene/richtext/RichTextSvgBody.d.ts.map +1 -0
  88. package/dist/scene/transform.d.ts +18 -0
  89. package/dist/scene/transform.d.ts.map +1 -0
  90. package/dist/scene/useSceneFocus.d.ts +35 -0
  91. package/dist/scene/useSceneFocus.d.ts.map +1 -0
  92. package/dist/scene/useSceneGestures.d.ts +20 -0
  93. package/dist/scene/useSceneGestures.d.ts.map +1 -0
  94. package/dist/scene-entry.d.ts +16 -0
  95. package/dist/scene-entry.d.ts.map +1 -0
  96. package/dist/scene.mjs +5 -0
  97. package/dist/static.mjs +1 -1
  98. package/dist/{WhiteboardExpandShell-D1s7iDKh.js → viewport-fit-DzCmuJXY.js} +306 -814
  99. package/package.json +13 -5
@@ -0,0 +1,4799 @@
1
+ import { $ as boundsIntersect, A as contentRoot, B as isHandFontFamily, C as newFrameElement, D as newRichTextElement, E as newLinearElement, G as getElementBounds, H as elementsInBox, J as hitTestElement, K as getElementCenter, M as randomId, N as randomInteger, O as newSvgElement, P as DEFAULT_STYLE, Q as boundsContain, S as newElement, T as newImageElement, U as getCommonBounds, W as getElementAbsoluteCorners, X as toLocalPoint, Y as isLinear, Z as angleOf$1, _ as parseSvgSize, b as syncIndices, c as SceneHandFontContext, d as normalizeElement, et as boundsOfPoints, g as isSvgSource, h as refreshTextDimensions, i as SceneContent, j as richTextPlainText, k as newTextElement, l as resolveRichTextHeights, m as layoutBoundText, n as DARK_SCENE_FILTER, nt as normalizeBox, o as RICHTEXT_BASE_STYLE, p as _defineProperty, q as getLinearAbsolutePoints, rt as rotatePoint, tt as distanceToSegment, v as bumpVersion, w as newFreedrawElement, x as getLineHeight, z as fontFamilyToCss } from "./viewport-fit-DzCmuJXY.js";
2
+ import { i as sameContent, n as reconcileElements, r as remoteWins, t as orderByIndex } from "./reconcile-Of9Y1rFE.js";
3
+ import { Children, use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { Activity, AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowDownToLine, ArrowUp, ArrowUpToLine, Bold, Circle, Code, Copy, Diamond, Dot, Ellipsis, Equal, Eraser, Frame, GripHorizontal, Group, Hand, Hash, Heading, Highlighter, Image as Image$1, Italic, Link, List, ListOrdered, Lock, LockOpen, Menu, Minus, MousePointer2, MoveRight, Pencil, Plus, Redo2, Ruler, Slash, Spline, Square, Squircle, StickyNote, Strikethrough, Trash2, Type, Undo2, Ungroup, Waypoints } from "lucide-react";
6
+ import { ActionButton, SegmentedControl } from "@haklex/rich-editor-ui";
7
+ import { $createParagraphNode, $getSelection, $isRangeSelection, FORMAT_TEXT_COMMAND } from "lexical";
8
+ import { $isLinkNode, LinkNode, TOGGLE_LINK_COMMAND } from "@lexical/link";
9
+ import { $isListNode, INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, ListItemNode, ListNode, REMOVE_LIST_COMMAND } from "@lexical/list";
10
+ import { LexicalComposer } from "@lexical/react/LexicalComposer";
11
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
12
+ import { ContentEditable } from "@lexical/react/LexicalContentEditable";
13
+ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
14
+ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
15
+ import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
16
+ import { ListPlugin } from "@lexical/react/LexicalListPlugin";
17
+ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
18
+ import { $createHeadingNode, $isHeadingNode, HeadingNode, QuoteNode } from "@lexical/rich-text";
19
+ import { $patchStyleText, $setBlocksType } from "@lexical/selection";
20
+ import { createPortal } from "react-dom";
21
+ //#region src/editor/text-actions.ts
22
+ var TEXT_CONTAINERS = /* @__PURE__ */ new Set([
23
+ "rectangle",
24
+ "ellipse",
25
+ "diamond",
26
+ "arrow"
27
+ ]);
28
+ var created = /* @__PURE__ */ new WeakMap();
29
+ function canHoldText(el) {
30
+ return TEXT_CONTAINERS.has(el.type);
31
+ }
32
+ function getBoundTextId(el) {
33
+ return el.boundElements?.find((b) => b.type === "text")?.id ?? null;
34
+ }
35
+ function find(store, id) {
36
+ return store.getState().elements.find((el) => el.id === id);
37
+ }
38
+ function replace(store, next) {
39
+ const byId = new Map(next.map((el) => [el.id, el]));
40
+ store.updateTransient(({ elements }) => ({ elements: elements.map((el) => byId.get(el.id) ?? el) }));
41
+ }
42
+ function startTextEditing(store, opts) {
43
+ const state = store.getState();
44
+ store.beginTransient();
45
+ created.delete(store);
46
+ if (opts.containerId) {
47
+ const container = find(store, opts.containerId);
48
+ if (!container) return;
49
+ const existing = getBoundTextId(container);
50
+ if (existing && find(store, existing)) {
51
+ store.setState({
52
+ editingTextId: existing,
53
+ selectedIds: /* @__PURE__ */ new Set([container.id])
54
+ });
55
+ return;
56
+ }
57
+ const text = newTextElement({
58
+ text: "",
59
+ containerId: container.id,
60
+ textAlign: "center",
61
+ verticalAlign: "middle"
62
+ }, state.currentStyle);
63
+ const laid = layoutBoundText(container, text);
64
+ const nextContainer = bumpVersion(laid.container, { boundElements: [...container.boundElements ?? [], {
65
+ id: text.id,
66
+ type: "text"
67
+ }] });
68
+ store.updateTransient(({ elements }) => ({ elements: [...elements.map((el) => el.id === container.id ? nextContainer : el), laid.text] }));
69
+ created.set(store, text.id);
70
+ store.setState({
71
+ editingTextId: text.id,
72
+ selectedIds: /* @__PURE__ */ new Set([container.id])
73
+ });
74
+ return;
75
+ }
76
+ if (opts.elementId) {
77
+ store.setState({
78
+ editingTextId: opts.elementId,
79
+ selectedIds: /* @__PURE__ */ new Set([opts.elementId])
80
+ });
81
+ return;
82
+ }
83
+ const at = opts.at ?? [0, 0];
84
+ const style = state.currentStyle;
85
+ const lineHeightPx = style.fontSize * getLineHeight(style.fontFamily);
86
+ const text = newTextElement({
87
+ text: "",
88
+ x: at[0],
89
+ y: at[1] - lineHeightPx / 2,
90
+ height: lineHeightPx
91
+ }, style);
92
+ store.updateTransient(({ elements }) => ({ elements: [...elements, text] }));
93
+ created.set(store, text.id);
94
+ store.setState({
95
+ editingTextId: text.id,
96
+ selectedIds: /* @__PURE__ */ new Set([text.id])
97
+ });
98
+ }
99
+ function updateEditingText(store, value) {
100
+ const id = store.getState().editingTextId;
101
+ const el = id ? find(store, id) : void 0;
102
+ if (!el) return;
103
+ const draft = {
104
+ ...el,
105
+ text: value,
106
+ originalText: value
107
+ };
108
+ const container = el.containerId ? find(store, el.containerId) : void 0;
109
+ if (container) {
110
+ const laid = layoutBoundText(container, draft);
111
+ replace(store, [laid.text, laid.container]);
112
+ return;
113
+ }
114
+ replace(store, [refreshTextDimensions(draft)]);
115
+ }
116
+ function finishTextEditing(store) {
117
+ const id = store.getState().editingTextId;
118
+ if (!id) return;
119
+ const el = find(store, id);
120
+ const isNew = created.get(store) === id;
121
+ created.delete(store);
122
+ store.setState({ editingTextId: null });
123
+ if (!el) {
124
+ store.endTransient(false);
125
+ return;
126
+ }
127
+ const empty = !(el.originalText ?? el.text).trim();
128
+ if (empty && isNew) {
129
+ store.endTransient(false);
130
+ return;
131
+ }
132
+ if (empty) {
133
+ const container = el.containerId ? find(store, el.containerId) : void 0;
134
+ const updates = [bumpVersion(el, { isDeleted: true })];
135
+ if (container) updates.push(bumpVersion(container, { boundElements: (container.boundElements ?? []).filter((b) => b.id !== el.id) }));
136
+ replace(store, updates);
137
+ store.setState({ selectedIds: /* @__PURE__ */ new Set() });
138
+ } else if (!isNew) replace(store, [bumpVersion(find(store, id) ?? el)]);
139
+ store.endTransient(true);
140
+ }
141
+ function relayoutBoundTexts(elements, containerIds) {
142
+ const byId = new Map(elements.map((el) => [el.id, el]));
143
+ const updates = /* @__PURE__ */ new Map();
144
+ for (const id of containerIds) {
145
+ const container = byId.get(id);
146
+ const textId = container ? getBoundTextId(container) : null;
147
+ const text = textId ? byId.get(textId) : void 0;
148
+ if (!container || !text || text.isDeleted) continue;
149
+ const laid = layoutBoundText(container, text);
150
+ updates.set(text.id, bumpVersion(text, laid.text));
151
+ if (laid.container !== container) updates.set(container.id, laid.container);
152
+ }
153
+ if (updates.size === 0) return [...elements];
154
+ return elements.map((el) => updates.get(el.id) ?? el);
155
+ }
156
+ //#endregion
157
+ //#region src/model/supersede.ts
158
+ function supersede(current, target) {
159
+ const live = new Map(current.map((el) => [el.id, el]));
160
+ const kept = /* @__PURE__ */ new Set();
161
+ const next = target.map((el) => {
162
+ kept.add(el.id);
163
+ const now = live.get(el.id);
164
+ if (!now || now === el) return el;
165
+ return {
166
+ ...el,
167
+ version: Math.max(now.version ?? 0, el.version ?? 0) + 1,
168
+ versionNonce: randomInteger(),
169
+ updated: Date.now()
170
+ };
171
+ });
172
+ for (const el of current) {
173
+ if (kept.has(el.id)) continue;
174
+ next.push(el.isDeleted ? el : bumpVersion(el, { isDeleted: true }));
175
+ }
176
+ return next;
177
+ }
178
+ function createHistory(limit = 100) {
179
+ let undoStack = [];
180
+ let redoStack = [];
181
+ return {
182
+ push(entry) {
183
+ undoStack.push(entry);
184
+ if (undoStack.length > limit) undoStack = undoStack.slice(-limit);
185
+ redoStack = [];
186
+ },
187
+ undo(current) {
188
+ const entry = undoStack.pop();
189
+ if (!entry) return null;
190
+ redoStack.push(current);
191
+ return entry;
192
+ },
193
+ redo(current) {
194
+ const entry = redoStack.pop();
195
+ if (!entry) return null;
196
+ undoStack.push(current);
197
+ return entry;
198
+ },
199
+ rewrite(fn) {
200
+ undoStack = undoStack.map(fn);
201
+ redoStack = redoStack.map(fn);
202
+ },
203
+ canUndo: () => undoStack.length > 0,
204
+ canRedo: () => redoStack.length > 0,
205
+ clear() {
206
+ undoStack = [];
207
+ redoStack = [];
208
+ }
209
+ };
210
+ }
211
+ //#endregion
212
+ //#region src/editor/store.ts
213
+ var DEFAULT_BACKGROUND = "#ffffff";
214
+ function normalizeChanged(prev, next) {
215
+ const before = new Map(prev.map((el) => [el.id, el]));
216
+ const normalized = next.map((el) => before.get(el.id) === el ? el : normalizeElement(el));
217
+ return syncIndices(normalized);
218
+ }
219
+ function referencedFileIds(elements) {
220
+ const ids = /* @__PURE__ */ new Set();
221
+ for (const el of elements) if (!el.isDeleted && el.type === "image" && el.fileId) ids.add(el.fileId);
222
+ return ids;
223
+ }
224
+ function createWhiteboardStore(input, options = {}) {
225
+ const { sync = false } = options;
226
+ const original = input ?? {};
227
+ const originalAppState = original.appState;
228
+ const originalFiles = original.files ?? {};
229
+ const loaded = Array.isArray(original.elements) ? original.elements : [];
230
+ const initialElements = resolveRichTextHeights(sync ? orderByIndex(loaded) : loaded);
231
+ const initialBackground = originalAppState?.viewBackgroundColor ?? DEFAULT_BACKGROUND;
232
+ const initialGrid = originalAppState?.gridSize ?? null;
233
+ let state = {
234
+ elements: initialElements,
235
+ files: originalFiles,
236
+ canvasSize: {
237
+ width: 0,
238
+ height: 0
239
+ },
240
+ selectedIds: /* @__PURE__ */ new Set(),
241
+ selectedPointIndex: null,
242
+ selectionBox: null,
243
+ suggestedBindingId: null,
244
+ editingGroupId: null,
245
+ editingFrameId: null,
246
+ editingLinearId: null,
247
+ editingRichTextId: null,
248
+ editingTextId: null,
249
+ erasingIds: /* @__PURE__ */ new Set(),
250
+ tool: "selection",
251
+ toolLocked: false,
252
+ currentStyle: DEFAULT_STYLE,
253
+ viewport: {
254
+ scrollX: 0,
255
+ scrollY: 0,
256
+ zoom: 1
257
+ },
258
+ gridSize: initialGrid,
259
+ viewBackgroundColor: initialBackground
260
+ };
261
+ const listeners = /* @__PURE__ */ new Set();
262
+ const history = createHistory();
263
+ let transientSnapshot = null;
264
+ const emit = () => {
265
+ for (const listener of listeners) listener();
266
+ };
267
+ const pending = /* @__PURE__ */ new Map();
268
+ const hold = (remote) => {
269
+ const held = pending.get(remote.id);
270
+ if (held) {
271
+ if (remoteWins(held.remote, remote)) pending.set(remote.id, {
272
+ ...held,
273
+ remote
274
+ });
275
+ return;
276
+ }
277
+ const baseline = transientSnapshot?.elements.find((el) => el.id === remote.id) ?? state.elements.find((el) => el.id === remote.id);
278
+ if (baseline) pending.set(remote.id, {
279
+ baseline,
280
+ remote
281
+ });
282
+ };
283
+ const protectedIds = () => {
284
+ const ids = /* @__PURE__ */ new Set();
285
+ for (const id of [
286
+ state.editingTextId,
287
+ state.editingRichTextId,
288
+ state.editingLinearId
289
+ ]) if (id) ids.add(id);
290
+ if (state.editingTextId) {
291
+ const owner = state.elements.find((el) => el.id === state.editingTextId)?.containerId;
292
+ if (owner) ids.add(owner);
293
+ }
294
+ if (transientSnapshot) {
295
+ const before = new Map(transientSnapshot.elements.map((el) => [el.id, el]));
296
+ for (const el of state.elements) if (before.get(el.id) !== el) ids.add(el.id);
297
+ }
298
+ return ids;
299
+ };
300
+ const mergeRemote = (remote) => {
301
+ const result = reconcileElements(state.elements, remote, protectedIds());
302
+ for (const el of result.deferred) hold(el);
303
+ if (result.accepted.length === 0) return null;
304
+ const elements = resolveRichTextHeights(syncIndices(result.elements));
305
+ const acceptedIds = new Set(result.accepted.map((el) => el.id));
306
+ const accepted = elements.filter((el) => acceptedIds.has(el.id));
307
+ const taken = new Map(accepted.map((el) => [el.id, el]));
308
+ const rewrite = (doc) => {
309
+ const known = new Set(doc.elements.map((el) => el.id));
310
+ return {
311
+ ...doc,
312
+ elements: [...doc.elements.map((el) => taken.get(el.id) ?? el), ...accepted.filter((el) => !known.has(el.id))]
313
+ };
314
+ };
315
+ history.rewrite(rewrite);
316
+ if (transientSnapshot) transientSnapshot = rewrite(transientSnapshot);
317
+ const alive = new Set(elements.filter((el) => !el.isDeleted).map((el) => el.id));
318
+ return {
319
+ elements,
320
+ selectedIds: new Set([...state.selectedIds].filter((id) => alive.has(id)))
321
+ };
322
+ };
323
+ const flushPending = () => {
324
+ if (pending.size === 0) return;
325
+ const guarded = protectedIds();
326
+ const released = [...pending].filter(([id]) => !guarded.has(id));
327
+ if (released.length === 0) return;
328
+ const current = new Map(state.elements.map((el) => [el.id, el]));
329
+ const outranked = /* @__PURE__ */ new Map();
330
+ const incoming = [];
331
+ for (const [id, { baseline, remote }] of released) {
332
+ pending.delete(id);
333
+ const local = current.get(id);
334
+ if (!local || sameContent(local, baseline)) incoming.push(remote);
335
+ else if (remoteWins(local, remote)) outranked.set(id, bumpVersion({
336
+ ...local,
337
+ version: remote.version
338
+ }));
339
+ }
340
+ if (outranked.size > 0) state = {
341
+ ...state,
342
+ elements: state.elements.map((el) => outranked.get(el.id) ?? el)
343
+ };
344
+ const patch = incoming.length > 0 ? mergeRemote(incoming) : null;
345
+ if (patch) state = {
346
+ ...state,
347
+ ...patch
348
+ };
349
+ };
350
+ const set = (patch) => {
351
+ state = {
352
+ ...state,
353
+ ...patch
354
+ };
355
+ flushPending();
356
+ emit();
357
+ };
358
+ const docOf = () => ({
359
+ elements: state.elements,
360
+ files: state.files
361
+ });
362
+ const apply = (updater) => {
363
+ const current = docOf();
364
+ const result = updater(current);
365
+ if (!result) return null;
366
+ const elements = result.elements ? resolveRichTextHeights(normalizeChanged(current.elements, result.elements)) : current.elements;
367
+ const files = result.files ?? current.files;
368
+ if (elements === current.elements && files === current.files) return null;
369
+ return {
370
+ elements,
371
+ files
372
+ };
373
+ };
374
+ const restore = (doc) => {
375
+ const elements = sync ? supersede(state.elements, doc.elements) : doc.elements;
376
+ const alive = new Set(elements.filter((el) => !el.isDeleted).map((el) => el.id));
377
+ set({
378
+ elements,
379
+ files: doc.files,
380
+ selectedIds: new Set([...state.selectedIds].filter((id) => alive.has(id))),
381
+ editingTextId: null,
382
+ editingFrameId: null,
383
+ editingLinearId: null,
384
+ selectedPointIndex: null,
385
+ suggestedBindingId: null
386
+ });
387
+ };
388
+ return {
389
+ getState: () => state,
390
+ subscribe(listener) {
391
+ listeners.add(listener);
392
+ return () => listeners.delete(listener);
393
+ },
394
+ setState: set,
395
+ commit(updater) {
396
+ if (transientSnapshot) {
397
+ const next = apply(updater);
398
+ if (next) set(next);
399
+ return;
400
+ }
401
+ const before = docOf();
402
+ const next = apply(updater);
403
+ if (!next) return;
404
+ history.push(before);
405
+ set(next);
406
+ },
407
+ applyRemote(update) {
408
+ const patch = update.elements ? mergeRemote(update.elements) ?? {} : {};
409
+ if (update.files && Object.keys(update.files).length > 0) {
410
+ const added = update.files;
411
+ const withFiles = (doc) => ({
412
+ ...doc,
413
+ files: {
414
+ ...doc.files,
415
+ ...added
416
+ }
417
+ });
418
+ history.rewrite(withFiles);
419
+ if (transientSnapshot) transientSnapshot = withFiles(transientSnapshot);
420
+ patch.files = {
421
+ ...state.files,
422
+ ...added
423
+ };
424
+ }
425
+ if (Object.keys(patch).length > 0) set(patch);
426
+ },
427
+ amend(fn) {
428
+ history.rewrite(fn);
429
+ if (transientSnapshot) transientSnapshot = fn(transientSnapshot);
430
+ const next = apply((doc) => fn(doc));
431
+ if (next) set(next);
432
+ },
433
+ beginTransient() {
434
+ transientSnapshot ?? (transientSnapshot = docOf());
435
+ },
436
+ updateTransient(updater) {
437
+ const next = apply(updater);
438
+ if (next) set(next);
439
+ },
440
+ endTransient(keep) {
441
+ const snapshot = transientSnapshot;
442
+ transientSnapshot = null;
443
+ if (!snapshot) return;
444
+ const unchanged = snapshot.elements === state.elements && snapshot.files === state.files;
445
+ if (!keep) {
446
+ if (!unchanged) restore(snapshot);
447
+ return;
448
+ }
449
+ if (unchanged) return;
450
+ history.push(snapshot);
451
+ if (!sync) return;
452
+ const before = new Map(snapshot.elements.map((el) => [el.id, el]));
453
+ set({ elements: state.elements.map((el) => before.get(el.id) === el ? el : bumpVersion(el)) });
454
+ },
455
+ isTransient: () => transientSnapshot !== null,
456
+ undo() {
457
+ const entry = history.undo(docOf());
458
+ if (entry) restore(entry);
459
+ },
460
+ redo() {
461
+ const entry = history.redo(docOf());
462
+ if (entry) restore(entry);
463
+ },
464
+ canUndo: history.canUndo,
465
+ canRedo: history.canRedo,
466
+ isDirty: () => state.elements !== initialElements || state.files !== originalFiles || state.viewBackgroundColor !== initialBackground || state.gridSize !== initialGrid,
467
+ getScene() {
468
+ const scene = {
469
+ ...original,
470
+ elements: state.elements.filter((el) => !el.isDeleted)
471
+ };
472
+ const appStatePatch = {};
473
+ if (state.viewBackgroundColor !== initialBackground) appStatePatch.viewBackgroundColor = state.viewBackgroundColor;
474
+ if (state.gridSize !== initialGrid) appStatePatch.gridSize = state.gridSize;
475
+ if (originalAppState || Object.keys(appStatePatch).length > 0) scene.appState = {
476
+ ...originalAppState,
477
+ ...appStatePatch
478
+ };
479
+ const referenced = referencedFileIds(state.elements);
480
+ const files = { ...originalFiles };
481
+ for (const [id, file] of Object.entries(state.files)) if (!(id in originalFiles) && referenced.has(id)) files[id] = file;
482
+ if ("files" in original || Object.keys(files).length > 0) scene.files = files;
483
+ return scene;
484
+ }
485
+ };
486
+ }
487
+ function useStore(store, selector) {
488
+ return useSyncExternalStore(store.subscribe, () => selector(store.getState()), () => selector(store.getState()));
489
+ }
490
+ function useNarrowLayout(store) {
491
+ return useStore(store, (s) => s.canvasSize.width > 0 && s.canvasSize.width < 640);
492
+ }
493
+ //#endregion
494
+ //#region src/editor/chrome.css.ts
495
+ var floating = "_14kbw0v0";
496
+ var toolbar = "_14kbw0v1";
497
+ var toolButton = "_14kbw0v3";
498
+ var separator = "_14kbw0v5";
499
+ var contextMenu = "_14kbw0v6";
500
+ var contextMenuItem = "_14kbw0v7";
501
+ var contextMenuSeparator = "_14kbw0v8";
502
+ var panel = "_14kbw0v9";
503
+ var row = "_14kbw0va";
504
+ var rowLabel = "_14kbw0vb";
505
+ var options = "_14kbw0vc";
506
+ var swatch = "_14kbw0vd";
507
+ var transparentSwatch = "_14kbw0ve";
508
+ var range = "_14kbw0vf";
509
+ var zoom = "_14kbw0vg";
510
+ var zoomTop = "_14kbw0vi";
511
+ var dock = "_14kbw0vj";
512
+ var sheet = "_14kbw0vk";
513
+ var grabber = "_14kbw0vl";
514
+ var formatBar = "_14kbw0vn";
515
+ var formatSwatch = "_14kbw0vo";
516
+ var formatBarInput = "_14kbw0vp";
517
+ //#endregion
518
+ //#region src/editor/Toolbar.tsx
519
+ var TOOLS = [
520
+ {
521
+ tool: "hand",
522
+ icon: Hand,
523
+ key: "H",
524
+ label: "Hand"
525
+ },
526
+ {
527
+ tool: "selection",
528
+ icon: MousePointer2,
529
+ key: "V",
530
+ label: "Select"
531
+ },
532
+ {
533
+ tool: "rectangle",
534
+ icon: Square,
535
+ key: "R",
536
+ label: "Rectangle"
537
+ },
538
+ {
539
+ tool: "diamond",
540
+ icon: Diamond,
541
+ key: "D",
542
+ label: "Diamond"
543
+ },
544
+ {
545
+ tool: "ellipse",
546
+ icon: Circle,
547
+ key: "O",
548
+ label: "Ellipse"
549
+ },
550
+ {
551
+ tool: "arrow",
552
+ icon: MoveRight,
553
+ key: "A",
554
+ label: "Arrow"
555
+ },
556
+ {
557
+ tool: "line",
558
+ icon: Minus,
559
+ key: "L",
560
+ label: "Line"
561
+ },
562
+ {
563
+ tool: "freedraw",
564
+ icon: Pencil,
565
+ key: "P",
566
+ label: "Draw"
567
+ },
568
+ {
569
+ tool: "text",
570
+ icon: Type,
571
+ key: "T",
572
+ label: "Text"
573
+ },
574
+ {
575
+ tool: "card",
576
+ icon: StickyNote,
577
+ key: "N",
578
+ label: "Card"
579
+ },
580
+ {
581
+ tool: "image",
582
+ icon: Image$1,
583
+ key: "I",
584
+ label: "Image"
585
+ },
586
+ {
587
+ tool: "frame",
588
+ icon: Frame,
589
+ key: "F",
590
+ label: "Frame"
591
+ },
592
+ {
593
+ tool: "eraser",
594
+ icon: Eraser,
595
+ key: "E",
596
+ label: "Eraser"
597
+ }
598
+ ];
599
+ var WhiteboardToolbar = ({ className, onToolSelect, showKeys = true, store, tools }) => {
600
+ const tool = useStore(store, (s) => s.tool);
601
+ const locked = useStore(store, (s) => s.toolLocked);
602
+ const LockIcon = locked ? Lock : LockOpen;
603
+ return /* @__PURE__ */ jsxs("div", {
604
+ className: `${toolbar}${className ? ` ${className}` : ""}`,
605
+ role: "toolbar",
606
+ children: [
607
+ /* @__PURE__ */ jsx(ActionButton, {
608
+ icon: true,
609
+ "aria-label": locked ? "Unlock tool" : "Keep tool active",
610
+ "aria-pressed": locked,
611
+ className: toolButton,
612
+ size: "lg",
613
+ variant: "ghost",
614
+ onClick: () => store.setState({ toolLocked: !locked }),
615
+ children: /* @__PURE__ */ jsx(LockIcon, { size: 16 })
616
+ }),
617
+ /* @__PURE__ */ jsx("span", { className: separator }),
618
+ TOOLS.filter((def) => !tools || tools.has(def.tool)).map(({ tool: value, icon: Icon, key, label }) => /* @__PURE__ */ jsxs(ActionButton, {
619
+ icon: true,
620
+ "aria-label": `${label} (${key})`,
621
+ "aria-pressed": tool === value,
622
+ className: toolButton,
623
+ "data-tool": value,
624
+ size: "lg",
625
+ title: `${label} — ${key}`,
626
+ variant: "ghost",
627
+ onClick: () => {
628
+ if (onToolSelect?.(value) === false) return;
629
+ store.setState({
630
+ tool: value,
631
+ selectedIds: value === "selection" ? store.getState().selectedIds : /* @__PURE__ */ new Set()
632
+ });
633
+ },
634
+ children: [/* @__PURE__ */ jsx(Icon, { size: 16 }), showKeys && /* @__PURE__ */ jsx("span", {
635
+ className: "_14kbw0v4",
636
+ children: key
637
+ })]
638
+ }, value))
639
+ ]
640
+ });
641
+ };
642
+ //#endregion
643
+ //#region src/model/clone.ts
644
+ function remapBinding(binding, idMap) {
645
+ if (!binding) return null;
646
+ const mapped = idMap.get(binding.elementId);
647
+ return mapped ? {
648
+ ...binding,
649
+ elementId: mapped
650
+ } : null;
651
+ }
652
+ function cloneElements(source, offset) {
653
+ const idMap = new Map(source.map((el) => [el.id, randomId()]));
654
+ const groupMap = /* @__PURE__ */ new Map();
655
+ const mapGroup = (g) => {
656
+ if (!groupMap.has(g)) groupMap.set(g, randomId());
657
+ return groupMap.get(g);
658
+ };
659
+ return {
660
+ clones: source.map((el) => {
661
+ const clone = {
662
+ ...el,
663
+ id: idMap.get(el.id),
664
+ x: el.x + offset[0],
665
+ y: el.y + offset[1],
666
+ seed: randomInteger(),
667
+ version: 1,
668
+ versionNonce: randomInteger(),
669
+ updated: Date.now(),
670
+ index: null,
671
+ groupIds: (el.groupIds ?? []).map(mapGroup),
672
+ boundElements: el.boundElements?.filter((b) => idMap.has(b.id)).map((b) => ({
673
+ ...b,
674
+ id: idMap.get(b.id)
675
+ })) ?? null
676
+ };
677
+ if (el.type === "text") clone.containerId = el.containerId ? idMap.get(el.containerId) ?? null : null;
678
+ if (el.type === "arrow" || el.type === "line") {
679
+ const linear = el;
680
+ clone.startBinding = remapBinding(linear.startBinding, idMap);
681
+ clone.endBinding = remapBinding(linear.endBinding, idMap);
682
+ }
683
+ clone.frameId = el.frameId ? idMap.get(el.frameId) ?? null : null;
684
+ return clone;
685
+ }),
686
+ idMap
687
+ };
688
+ }
689
+ //#endregion
690
+ //#region src/model/frames.ts
691
+ function isFrame(el) {
692
+ return el.type === "frame" || el.type === "magicframe";
693
+ }
694
+ var containerOf = (el) => el.type === "text" ? el.containerId ?? null : null;
695
+ var encloses = (frame, el) => boundsContain(getElementBounds(frame), getElementBounds(el));
696
+ var overlaps = (frame, el) => boundsIntersect(getElementBounds(frame), getElementBounds(el));
697
+ function withFrame(el, frameId) {
698
+ return (el.frameId ?? null) === frameId ? el : bumpVersion(el, { frameId });
699
+ }
700
+ function syncBoundTexts(elements) {
701
+ const byId = new Map(elements.map((el) => [el.id, el]));
702
+ return elements.map((el) => {
703
+ const container = containerOf(el);
704
+ const owner = container ? byId.get(container) : void 0;
705
+ return owner ? withFrame(el, owner.frameId ?? null) : el;
706
+ });
707
+ }
708
+ function assignFrameMembership(elements, frameId) {
709
+ const frame = elements.find((el) => el.id === frameId);
710
+ if (!frame || frame.isDeleted) return [...elements];
711
+ return syncBoundTexts(elements.map((el) => {
712
+ if (el.id === frameId || el.isDeleted || isFrame(el) || containerOf(el)) return el;
713
+ if (el.frameId && el.frameId !== frameId) return el;
714
+ if (el.frameId === frameId) return withFrame(el, overlaps(frame, el) ? frameId : null);
715
+ return withFrame(el, encloses(frame, el) ? frameId : null);
716
+ }));
717
+ }
718
+ function updateFrameMembershipAfterMove(elements, movedIds) {
719
+ const frames = elements.filter((el) => isFrame(el) && !el.isDeleted);
720
+ return syncBoundTexts(elements.map((el) => {
721
+ if (!movedIds.has(el.id) || el.isDeleted || isFrame(el) || containerOf(el)) return el;
722
+ if (el.frameId && movedIds.has(el.frameId)) return el;
723
+ const current = el.frameId ? frames.find((frame) => frame.id === el.frameId) : void 0;
724
+ if (current && overlaps(current, el)) return el;
725
+ return withFrame(el, frames.findLast((frame) => encloses(frame, el))?.id ?? null);
726
+ }));
727
+ }
728
+ function refreshFrames(elements, changedIds) {
729
+ let current = updateFrameMembershipAfterMove(elements, changedIds);
730
+ for (const el of elements) if (changedIds.has(el.id) && isFrame(el)) current = assignFrameMembership(current, el.id);
731
+ return current;
732
+ }
733
+ function withFrameChildren(elements, ids) {
734
+ const out = new Set(ids);
735
+ const frames = new Set(elements.filter((el) => ids.has(el.id) && isFrame(el)).map((el) => el.id));
736
+ if (frames.size === 0) return out;
737
+ for (const el of elements) if (!el.isDeleted && el.frameId && frames.has(el.frameId)) out.add(el.id);
738
+ return out;
739
+ }
740
+ //#endregion
741
+ //#region src/editor/selection-utils.ts
742
+ var isAlive = (el) => !el.isDeleted;
743
+ function isSelectable(el) {
744
+ return !el.isDeleted && !el.locked;
745
+ }
746
+ function getContainerId(el) {
747
+ return el.type === "text" ? el.containerId ?? null : null;
748
+ }
749
+ function groupMembers(elements, groupId) {
750
+ return elements.filter((el) => isAlive(el) && el.groupIds?.includes(groupId)).map((el) => el.id);
751
+ }
752
+ function selectionForElement(state, el) {
753
+ const groups = el.groupIds ?? [];
754
+ if (groups.length === 0) return [el.id];
755
+ const editing = state.editingGroupId;
756
+ const depth = editing ? groups.indexOf(editing) : -1;
757
+ if (depth === 0) return [el.id];
758
+ const target = depth > 0 ? groups[depth - 1] : groups.at(-1);
759
+ return groupMembers(state.elements, target);
760
+ }
761
+ function getHitElement(elements, p, tolerance) {
762
+ const byId = new Map(elements.map((el) => [el.id, el]));
763
+ for (let i = elements.length - 1; i >= 0; i--) {
764
+ const el = elements[i];
765
+ if (!isSelectable(el)) continue;
766
+ if (!hitTestElement(el, p, tolerance)) continue;
767
+ const containerId = getContainerId(el);
768
+ const container = containerId ? byId.get(containerId) : void 0;
769
+ if (container && isSelectable(container)) return container;
770
+ return el;
771
+ }
772
+ return null;
773
+ }
774
+ function getSelectionTarget(state, p, tolerance) {
775
+ const hit = getHitElement(state.elements, p, tolerance);
776
+ if (!hit) return null;
777
+ return {
778
+ hitId: hit.id,
779
+ ids: selectionForElement(state, hit)
780
+ };
781
+ }
782
+ function withBoundText(elements, ids) {
783
+ const out = new Set(ids);
784
+ for (const el of elements) {
785
+ const containerId = getContainerId(el);
786
+ if (containerId && ids.has(containerId) && isAlive(el)) out.add(el.id);
787
+ }
788
+ return out;
789
+ }
790
+ function selectInBox(state, box) {
791
+ const candidates = state.elements.filter((el) => isSelectable(el) && !getContainerId(el));
792
+ const inside = new Set(elementsInBox(candidates, box).map((el) => el.id));
793
+ const result = /* @__PURE__ */ new Set();
794
+ for (const id of inside) {
795
+ const ids = selectionForElement(state, state.elements.find((e) => e.id === id));
796
+ if (ids.every((member) => inside.has(member))) for (const member of ids) result.add(member);
797
+ }
798
+ return result;
799
+ }
800
+ function getSelectedElements(state) {
801
+ return state.elements.filter((el) => isAlive(el) && state.selectedIds.has(el.id));
802
+ }
803
+ //#endregion
804
+ //#region src/editor/actions.ts
805
+ var DUPLICATE_OFFSET = 10;
806
+ function selectedWithText(store) {
807
+ const state = store.getState();
808
+ return withBoundText(state.elements, state.selectedIds);
809
+ }
810
+ function reorder(store, arrange) {
811
+ const ids = selectedWithText(store);
812
+ if (ids.size === 0) return;
813
+ store.commit(({ elements }) => {
814
+ const arranged = arrange([...elements], ids);
815
+ if (arranged.every((el, i) => el === elements[i])) return;
816
+ return { elements: arranged.map((el) => ids.has(el.id) ? bumpVersion(el, { index: null }) : el) };
817
+ });
818
+ }
819
+ var bringToFront = (store) => reorder(store, (els, ids) => [...els.filter((el) => !ids.has(el.id)), ...els.filter((el) => ids.has(el.id))]);
820
+ var sendToBack = (store) => reorder(store, (els, ids) => [...els.filter((el) => ids.has(el.id)), ...els.filter((el) => !ids.has(el.id))]);
821
+ var bringForward = (store) => reorder(store, (els, ids) => {
822
+ for (let i = els.length - 2; i >= 0; i--) if (ids.has(els[i].id) && !ids.has(els[i + 1].id)) [els[i], els[i + 1]] = [els[i + 1], els[i]];
823
+ return els;
824
+ });
825
+ var sendBackward = (store) => reorder(store, (els, ids) => {
826
+ for (let i = 1; i < els.length; i++) if (ids.has(els[i].id) && !ids.has(els[i - 1].id)) [els[i], els[i - 1]] = [els[i - 1], els[i]];
827
+ return els;
828
+ });
829
+ function groupSelection(store) {
830
+ const ids = selectedWithText(store);
831
+ if (getSelectedElements(store.getState()).length < 2) return;
832
+ const groupId = randomId();
833
+ store.commit(({ elements }) => ({ elements: elements.map((el) => ids.has(el.id) ? bumpVersion(el, { groupIds: [...el.groupIds ?? [], groupId] }) : el) }));
834
+ }
835
+ function ungroupSelection(store) {
836
+ const ids = selectedWithText(store);
837
+ const outer = new Set(getSelectedElements(store.getState()).map((el) => el.groupIds?.at(-1)).filter((g) => !!g));
838
+ if (outer.size === 0) return;
839
+ store.commit(({ elements }) => ({ elements: elements.map((el) => ids.has(el.id) && el.groupIds?.some((g) => outer.has(g)) ? bumpVersion(el, { groupIds: el.groupIds.filter((g) => !outer.has(g)) }) : el) }));
840
+ store.setState({ editingGroupId: null });
841
+ }
842
+ function duplicateSelection(store) {
843
+ const state = store.getState();
844
+ const ids = selectedWithText(store);
845
+ if (ids.size === 0) return;
846
+ const { clones, idMap } = cloneElements(state.elements.filter((el) => ids.has(el.id) && !el.isDeleted), [DUPLICATE_OFFSET, DUPLICATE_OFFSET]);
847
+ store.commit(({ elements }) => ({ elements: refreshFrames([...elements, ...clones], new Set(clones.map((el) => el.id))) }));
848
+ store.setState({ selectedIds: new Set([...state.selectedIds].map((id) => idMap.get(id)).filter((id) => !!id)) });
849
+ }
850
+ function deleteElements(elements, ids) {
851
+ return elements.map((el) => {
852
+ if (ids.has(el.id)) return bumpVersion(el, { isDeleted: true });
853
+ const patch = {};
854
+ if (el.boundElements?.some((b) => ids.has(b.id))) patch.boundElements = el.boundElements.filter((b) => !ids.has(b.id));
855
+ if (el.type === "arrow" || el.type === "line") {
856
+ const linear = el;
857
+ if (linear.startBinding && ids.has(linear.startBinding.elementId)) patch.startBinding = null;
858
+ if (linear.endBinding && ids.has(linear.endBinding.elementId)) patch.endBinding = null;
859
+ }
860
+ if (el.frameId && ids.has(el.frameId)) patch.frameId = null;
861
+ return Object.keys(patch).length > 0 ? bumpVersion(el, patch) : el;
862
+ });
863
+ }
864
+ function deleteSelection(store) {
865
+ const ids = selectedWithText(store);
866
+ if (ids.size === 0) return;
867
+ store.commit(({ elements }) => ({ elements: deleteElements(elements, ids) }));
868
+ store.setState({
869
+ selectedIds: /* @__PURE__ */ new Set(),
870
+ selectedPointIndex: null
871
+ });
872
+ }
873
+ function selectAll(store) {
874
+ const state = store.getState();
875
+ store.setState({
876
+ selectedIds: new Set(state.elements.filter((el) => !el.isDeleted && !el.locked && !(el.type === "text" && el.containerId)).map((el) => el.id)),
877
+ editingGroupId: null
878
+ });
879
+ }
880
+ //#endregion
881
+ //#region src/model/clipboard.ts
882
+ var CLIPBOARD_TYPE = "excalidraw/clipboard";
883
+ function serializeClipboard(elements, files) {
884
+ const used = {};
885
+ for (const el of elements) if (el.type === "image" && el.fileId && files[el.fileId]) used[el.fileId] = files[el.fileId];
886
+ return JSON.stringify({
887
+ type: CLIPBOARD_TYPE,
888
+ elements,
889
+ files: used
890
+ });
891
+ }
892
+ function parseClipboard(raw) {
893
+ const text = raw.trim();
894
+ if (!text) return null;
895
+ if (text.startsWith("{")) try {
896
+ const json = JSON.parse(text);
897
+ if ((json.type === "excalidraw/clipboard" || json.type === "excalidraw") && Array.isArray(json.elements)) return {
898
+ elements: json.elements.filter((el) => !el.isDeleted),
899
+ files: json.files ?? {}
900
+ };
901
+ return null;
902
+ } catch {
903
+ return { text: raw };
904
+ }
905
+ return { text: raw };
906
+ }
907
+ var FALLBACK_SIDE = 200;
908
+ var domSizeReader = (url) => new Promise((resolve, reject) => {
909
+ const img = new Image();
910
+ img.addEventListener("load", () => resolve({
911
+ width: img.naturalWidth,
912
+ height: img.naturalHeight
913
+ }));
914
+ img.addEventListener("error", reject);
915
+ img.src = url;
916
+ });
917
+ var readSize = domSizeReader;
918
+ function fitImageSize(width, height, max = 600) {
919
+ const scale = Math.min(1, max / Math.max(width, height));
920
+ return {
921
+ width: Math.round(width * scale),
922
+ height: Math.round(height * scale)
923
+ };
924
+ }
925
+ function readAsDataURL(file) {
926
+ return new Promise((resolve, reject) => {
927
+ const reader = new FileReader();
928
+ reader.addEventListener("load", () => resolve(String(reader.result)));
929
+ reader.addEventListener("error", () => reject(reader.error));
930
+ reader.readAsDataURL(file);
931
+ });
932
+ }
933
+ async function insertImageFile(store, file, at, options = {}) {
934
+ const dataURL = await readAsDataURL(file);
935
+ const natural = await readSize(dataURL).catch(() => null);
936
+ const { width, height } = fitImageSize(natural?.width || FALLBACK_SIDE, natural?.height || FALLBACK_SIDE);
937
+ const fileId = randomId();
938
+ const el = newImageElement({
939
+ x: at[0] - width / 2,
940
+ y: at[1] - height / 2,
941
+ width,
942
+ height,
943
+ fileId,
944
+ status: "pending"
945
+ }, store.getState().currentStyle);
946
+ const record = {
947
+ id: fileId,
948
+ mimeType: file.type || "image/png",
949
+ created: Date.now(),
950
+ dataURL
951
+ };
952
+ store.commit(({ elements, files }) => ({
953
+ elements: [...elements, el],
954
+ files: {
955
+ ...files,
956
+ [fileId]: record
957
+ }
958
+ }));
959
+ const { toolLocked, tool } = store.getState();
960
+ store.setState({
961
+ selectedIds: /* @__PURE__ */ new Set([el.id]),
962
+ tool: toolLocked ? tool : "selection"
963
+ });
964
+ let url = dataURL;
965
+ if (options.uploadFile) try {
966
+ url = await options.uploadFile(file);
967
+ } catch (error) {
968
+ options.onUploadError?.(error);
969
+ }
970
+ store.amend((doc) => {
971
+ if (!doc.elements.some((item) => item.id === el.id)) return doc;
972
+ const saved = doc.files[fileId];
973
+ return {
974
+ elements: doc.elements.map((item) => item.id === el.id ? bumpVersion(item, { status: "saved" }) : item),
975
+ files: saved ? {
976
+ ...doc.files,
977
+ [fileId]: {
978
+ ...saved,
979
+ dataURL: url
980
+ }
981
+ } : doc.files
982
+ };
983
+ });
984
+ return el.id;
985
+ }
986
+ //#endregion
987
+ //#region src/editor/clipboard-actions.ts
988
+ function copySelection(store) {
989
+ const state = store.getState();
990
+ const ids = withBoundText(state.elements, state.selectedIds);
991
+ return serializeClipboard(state.elements.filter((el) => ids.has(el.id) && !el.isDeleted), state.files);
992
+ }
993
+ function cutSelection(store) {
994
+ const data = copySelection(store);
995
+ deleteSelection(store);
996
+ return data;
997
+ }
998
+ var SVG_FALLBACK_SIDE = 200;
999
+ function pasteSvg(store, raw, at) {
1000
+ const svg = raw.trim();
1001
+ const size = parseSvgSize(svg) ?? {
1002
+ width: SVG_FALLBACK_SIDE,
1003
+ height: SVG_FALLBACK_SIDE
1004
+ };
1005
+ const scale = Math.min(1, 600 / Math.max(size.width, size.height));
1006
+ const width = size.width * scale;
1007
+ const height = size.height * scale;
1008
+ const el = newSvgElement({
1009
+ svg,
1010
+ width,
1011
+ height,
1012
+ x: at[0] - width / 2,
1013
+ y: at[1] - height / 2
1014
+ }, store.getState().currentStyle);
1015
+ store.commit(({ elements }) => ({ elements: refreshFrames([...elements, el], /* @__PURE__ */ new Set([el.id])) }));
1016
+ store.setState({
1017
+ selectedIds: /* @__PURE__ */ new Set([el.id]),
1018
+ editingGroupId: null
1019
+ });
1020
+ }
1021
+ function pasteFromClipboard(store, raw, at) {
1022
+ if (isSvgSource(raw)) {
1023
+ pasteSvg(store, raw, at);
1024
+ return true;
1025
+ }
1026
+ const content = parseClipboard(raw);
1027
+ if (!content) return false;
1028
+ const style = store.getState().currentStyle;
1029
+ if ("text" in content) {
1030
+ const lineHeight = style.fontSize * getLineHeight(style.fontFamily);
1031
+ const text = refreshTextDimensions(newTextElement({
1032
+ text: content.text,
1033
+ x: at[0],
1034
+ y: at[1] - lineHeight / 2
1035
+ }, style));
1036
+ store.commit(({ elements }) => ({ elements: [...elements, text] }));
1037
+ store.setState({ selectedIds: /* @__PURE__ */ new Set([text.id]) });
1038
+ return true;
1039
+ }
1040
+ if (content.elements.length === 0) return false;
1041
+ const [minX, minY, maxX, maxY] = getCommonBounds(content.elements);
1042
+ const offset = [at[0] - (minX + maxX) / 2, at[1] - (minY + maxY) / 2];
1043
+ const { clones } = cloneElements(content.elements, offset);
1044
+ store.commit(({ elements, files }) => ({
1045
+ elements: refreshFrames([...elements, ...clones], new Set(clones.map((el) => el.id))),
1046
+ files: {
1047
+ ...files,
1048
+ ...content.files
1049
+ }
1050
+ }));
1051
+ store.setState({
1052
+ selectedIds: new Set(clones.filter((el) => !(el.type === "text" && el.containerId)).map((el) => el.id)),
1053
+ editingGroupId: null
1054
+ });
1055
+ return true;
1056
+ }
1057
+ //#endregion
1058
+ //#region src/editor/context-menu.ts
1059
+ var isSeparator = (item) => "type" in item && item.type === "separator";
1060
+ var SEPARATOR = { type: "separator" };
1061
+ var lastCopied = "";
1062
+ function writeClipboard(text) {
1063
+ lastCopied = text;
1064
+ if (typeof navigator === "undefined" || !navigator.clipboard) return;
1065
+ navigator.clipboard.writeText(text).catch(() => {});
1066
+ }
1067
+ async function readClipboard() {
1068
+ try {
1069
+ return await navigator.clipboard.readText() || lastCopied;
1070
+ } catch {
1071
+ return lastCopied;
1072
+ }
1073
+ }
1074
+ function retarget(store, scenePoint) {
1075
+ const state = store.getState();
1076
+ const target = getSelectionTarget(state, scenePoint, 6 / state.viewport.zoom);
1077
+ if (!target) {
1078
+ if (state.selectedIds.size > 0) store.setState({ selectedIds: /* @__PURE__ */ new Set() });
1079
+ return;
1080
+ }
1081
+ if (target.ids.every((id) => state.selectedIds.has(id))) return;
1082
+ store.setState({ selectedIds: new Set(target.ids) });
1083
+ }
1084
+ function elementItems(store, selected) {
1085
+ const run = (key, label, action) => ({
1086
+ key,
1087
+ label,
1088
+ onSelect: () => action(store)
1089
+ });
1090
+ const grouping = [];
1091
+ if (selected.length > 1) grouping.push(run("group", "Group", groupSelection));
1092
+ if (selected.some((el) => (el.groupIds?.length ?? 0) > 0)) grouping.push(run("ungroup", "Ungroup", ungroupSelection));
1093
+ return [
1094
+ run("copy", "Copy", (s) => writeClipboard(copySelection(s))),
1095
+ run("cut", "Cut", (s) => writeClipboard(cutSelection(s))),
1096
+ run("duplicate", "Duplicate", duplicateSelection),
1097
+ SEPARATOR,
1098
+ run("bring-forward", "Bring forward", bringForward),
1099
+ run("send-backward", "Send backward", sendBackward),
1100
+ run("bring-to-front", "Bring to front", bringToFront),
1101
+ run("send-to-back", "Send to back", sendToBack),
1102
+ ...grouping.length > 0 ? [SEPARATOR, ...grouping] : [],
1103
+ SEPARATOR,
1104
+ {
1105
+ ...run("delete", "Delete", deleteSelection),
1106
+ danger: true
1107
+ }
1108
+ ];
1109
+ }
1110
+ function blankItems(store, scenePoint) {
1111
+ return [{
1112
+ key: "paste",
1113
+ label: "Paste",
1114
+ onSelect: () => {
1115
+ readClipboard().then((text) => {
1116
+ if (text) pasteFromClipboard(store, text, scenePoint);
1117
+ });
1118
+ }
1119
+ }, {
1120
+ key: "select-all",
1121
+ label: "Select all",
1122
+ onSelect: () => selectAll(store)
1123
+ }];
1124
+ }
1125
+ function contextMenuItems(store, scenePoint, hostItems) {
1126
+ retarget(store, scenePoint);
1127
+ const selected = getSelectedElements(store.getState());
1128
+ const builtin = selected.length > 0 ? elementItems(store, selected) : blankItems(store, scenePoint);
1129
+ const extra = hostItems?.({
1130
+ scenePoint,
1131
+ selected
1132
+ }) ?? [];
1133
+ return extra.length > 0 ? [
1134
+ ...builtin,
1135
+ SEPARATOR,
1136
+ ...extra
1137
+ ] : builtin;
1138
+ }
1139
+ //#endregion
1140
+ //#region src/editor/editor.css.ts
1141
+ var root = "_17gtqeu0";
1142
+ var canvas = "_17gtqeu1";
1143
+ var layer = "_17gtqeu2";
1144
+ var accentStroke = "var(--rc-accent)";
1145
+ //#endregion
1146
+ //#region src/editor/viewport.ts
1147
+ var MIN_ZOOM = .1;
1148
+ var MAX_ZOOM = 30;
1149
+ function clampZoom(zoom) {
1150
+ return Math.min(30, Math.max(MIN_ZOOM, zoom));
1151
+ }
1152
+ function screenToScene([sx, sy], vp) {
1153
+ return [sx / vp.zoom - vp.scrollX, sy / vp.zoom - vp.scrollY];
1154
+ }
1155
+ function sceneToScreen([x, y], vp) {
1156
+ return [(x + vp.scrollX) * vp.zoom, (y + vp.scrollY) * vp.zoom];
1157
+ }
1158
+ function zoomAt(vp, screen, nextZoom) {
1159
+ const zoom = clampZoom(nextZoom);
1160
+ const [x, y] = screenToScene(screen, vp);
1161
+ return {
1162
+ zoom,
1163
+ scrollX: screen[0] / zoom - x,
1164
+ scrollY: screen[1] / zoom - y
1165
+ };
1166
+ }
1167
+ function panBy(vp, dxScreen, dyScreen) {
1168
+ return {
1169
+ ...vp,
1170
+ scrollX: vp.scrollX + dxScreen / vp.zoom,
1171
+ scrollY: vp.scrollY + dyScreen / vp.zoom
1172
+ };
1173
+ }
1174
+ function fitToContent(bounds, size, padding = 48) {
1175
+ const [minX, minY, maxX, maxY] = bounds;
1176
+ const w = Math.max(1, maxX - minX);
1177
+ const h = Math.max(1, maxY - minY);
1178
+ const zoom = clampZoom(Math.min(1, (size.width - padding * 2) / w, (size.height - padding * 2) / h));
1179
+ return {
1180
+ zoom,
1181
+ scrollX: size.width / 2 / zoom - (minX + w / 2),
1182
+ scrollY: size.height / 2 / zoom - (minY + h / 2)
1183
+ };
1184
+ }
1185
+ //#endregion
1186
+ //#region src/editor/gestures.ts
1187
+ var midpoint = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
1188
+ function createGestureTracker() {
1189
+ const points = /* @__PURE__ */ new Map();
1190
+ let pinch = null;
1191
+ let suppressed = false;
1192
+ return {
1193
+ down(id, screen, viewport) {
1194
+ points.set(id, screen);
1195
+ if (pinch || suppressed) return "ignored";
1196
+ if (points.size < 2) return "single";
1197
+ const [a, b] = [...points.keys()].slice(-2);
1198
+ const pa = points.get(a);
1199
+ const pb = points.get(b);
1200
+ pinch = {
1201
+ ids: [a, b],
1202
+ distance: Math.max(Math.hypot(pb[0] - pa[0], pb[1] - pa[1]), 1),
1203
+ zoom: viewport.zoom,
1204
+ anchor: screenToScene(midpoint(pa, pb), viewport)
1205
+ };
1206
+ return "pinch";
1207
+ },
1208
+ move(id, screen) {
1209
+ if (!points.has(id)) return null;
1210
+ points.set(id, screen);
1211
+ if (!pinch) return null;
1212
+ const pa = points.get(pinch.ids[0]);
1213
+ const pb = points.get(pinch.ids[1]);
1214
+ const zoom = clampZoom(pinch.zoom * Math.hypot(pb[0] - pa[0], pb[1] - pa[1]) / pinch.distance);
1215
+ const [mx, my] = midpoint(pa, pb);
1216
+ return {
1217
+ zoom,
1218
+ scrollX: mx / zoom - pinch.anchor[0],
1219
+ scrollY: my / zoom - pinch.anchor[1]
1220
+ };
1221
+ },
1222
+ up(id) {
1223
+ points.delete(id);
1224
+ if (pinch) {
1225
+ pinch = null;
1226
+ suppressed = true;
1227
+ }
1228
+ if (points.size === 0) suppressed = false;
1229
+ },
1230
+ isActive: () => pinch !== null || suppressed
1231
+ };
1232
+ }
1233
+ //#endregion
1234
+ //#region src/editor/richtext-editor.css.ts
1235
+ var surface = "_1yp4ot60";
1236
+ var editable = "_1yp4ot61";
1237
+ var paragraph$1 = "_1yp4ot62";
1238
+ var h1 = "_1yp4ot63";
1239
+ var h2 = "_1yp4ot64";
1240
+ var h3 = "_1yp4ot65";
1241
+ var hOther = "_1yp4ot66";
1242
+ var quote = "_1yp4ot67";
1243
+ var list$1 = "_1yp4ot68";
1244
+ var listItem$1 = "_1yp4ot69";
1245
+ var nestedListItem = "_1yp4ot6a";
1246
+ var underline = "_1yp4ot6b";
1247
+ var strikethrough = "_1yp4ot6c";
1248
+ var underlineStrikethrough = "_1yp4ot6d";
1249
+ var link = "_1yp4ot6e";
1250
+ var editingCard = "_1yp4ot6f";
1251
+ //#endregion
1252
+ //#region src/model/bindable.ts
1253
+ var BINDABLE = /* @__PURE__ */ new Set([
1254
+ "rectangle",
1255
+ "diamond",
1256
+ "ellipse",
1257
+ "image",
1258
+ "svg",
1259
+ "richtext",
1260
+ "text",
1261
+ "embeddable",
1262
+ "iframe"
1263
+ ]);
1264
+ function isBindable(el) {
1265
+ if (el.isDeleted || !BINDABLE.has(el.type)) return false;
1266
+ return !(el.type === "text" && el.containerId);
1267
+ }
1268
+ var BEND_PENALTY = 60;
1269
+ var DIRS = [
1270
+ [1, 0],
1271
+ [0, 1],
1272
+ [-1, 0],
1273
+ [0, -1]
1274
+ ];
1275
+ var dirIndex = ([x, y]) => DIRS.findIndex((d) => d[0] === x && d[1] === y);
1276
+ var same = (a, b) => a[0] === b[0] && a[1] === b[1];
1277
+ function headingForPoint(target, p) {
1278
+ const [minX, minY, maxX, maxY] = getElementBounds(target);
1279
+ const dx = (p[0] - (minX + maxX) / 2) / Math.max((maxX - minX) / 2, 1e-9);
1280
+ const dy = (p[1] - (minY + maxY) / 2) / Math.max((maxY - minY) / 2, 1e-9);
1281
+ if (Math.abs(dx) >= Math.abs(dy)) return dx < 0 ? [-1, 0] : [1, 0];
1282
+ return dy < 0 ? [0, -1] : [0, 1];
1283
+ }
1284
+ function towards(from, to) {
1285
+ const dx = to[0] - from[0];
1286
+ const dy = to[1] - from[1];
1287
+ if (Math.abs(dx) >= Math.abs(dy)) return dx < 0 ? [-1, 0] : [1, 0];
1288
+ return dy < 0 ? [0, -1] : [0, 1];
1289
+ }
1290
+ var expand = ([minX, minY, maxX, maxY], pad) => [
1291
+ minX - pad,
1292
+ minY - pad,
1293
+ maxX + pad,
1294
+ maxY + pad
1295
+ ];
1296
+ var strictlyInside = ([x, y], [minX, minY, maxX, maxY]) => x > minX && x < maxX && y > minY && y < maxY;
1297
+ function crosses(a, b, [minX, minY, maxX, maxY]) {
1298
+ const x0 = Math.min(a[0], b[0]);
1299
+ const x1 = Math.max(a[0], b[0]);
1300
+ const y0 = Math.min(a[1], b[1]);
1301
+ const y1 = Math.max(a[1], b[1]);
1302
+ if (x0 === x1) return x0 > minX && x0 < maxX && y1 > minY && y0 < maxY;
1303
+ if (y0 === y1) return y0 > minY && y0 < maxY && x1 > minX && x0 < maxX;
1304
+ return x1 > minX && x0 < maxX && y1 > minY && y0 < maxY;
1305
+ }
1306
+ function exitPoint(p, heading, target) {
1307
+ if (!target) return p;
1308
+ const [minX, minY, maxX, maxY] = expand(getElementBounds(target), 20);
1309
+ if (heading[0] > 0) return [Math.max(maxX, p[0]), p[1]];
1310
+ if (heading[0] < 0) return [Math.min(minX, p[0]), p[1]];
1311
+ if (heading[1] > 0) return [p[0], Math.max(maxY, p[1])];
1312
+ return [p[0], Math.min(minY, p[1])];
1313
+ }
1314
+ var MinHeap = class {
1315
+ constructor() {
1316
+ _defineProperty(this, "items", []);
1317
+ _defineProperty(this, "seq", 0);
1318
+ }
1319
+ get size() {
1320
+ return this.items.length;
1321
+ }
1322
+ push(key, f) {
1323
+ const item = {
1324
+ f,
1325
+ key,
1326
+ seq: this.seq++
1327
+ };
1328
+ const { items } = this;
1329
+ items.push(item);
1330
+ let i = items.length - 1;
1331
+ while (i > 0) {
1332
+ const parent = i - 1 >> 1;
1333
+ if (!this.less(items[i], items[parent])) break;
1334
+ [items[i], items[parent]] = [items[parent], items[i]];
1335
+ i = parent;
1336
+ }
1337
+ }
1338
+ pop() {
1339
+ const { items } = this;
1340
+ const top = items[0];
1341
+ const last = items.pop();
1342
+ if (items.length > 0) {
1343
+ items[0] = last;
1344
+ let i = 0;
1345
+ for (;;) {
1346
+ const l = i * 2 + 1;
1347
+ const r = l + 1;
1348
+ let m = i;
1349
+ if (l < items.length && this.less(items[l], items[m])) m = l;
1350
+ if (r < items.length && this.less(items[r], items[m])) m = r;
1351
+ if (m === i) break;
1352
+ [items[i], items[m]] = [items[m], items[i]];
1353
+ i = m;
1354
+ }
1355
+ }
1356
+ return top.key;
1357
+ }
1358
+ less(a, b) {
1359
+ return a.f < b.f || a.f === b.f && a.seq < b.seq;
1360
+ }
1361
+ };
1362
+ var sortedUnique = (values) => [...new Set(values)].sort((a, b) => a - b);
1363
+ function searchGrid(from, to, startDir, endDir, boxes) {
1364
+ const xs = sortedUnique([
1365
+ from[0],
1366
+ to[0],
1367
+ (from[0] + to[0]) / 2,
1368
+ ...boxes.flatMap((b) => [b[0], b[2]])
1369
+ ]);
1370
+ const ys = sortedUnique([
1371
+ from[1],
1372
+ to[1],
1373
+ (from[1] + to[1]) / 2,
1374
+ ...boxes.flatMap((b) => [b[1], b[3]])
1375
+ ]);
1376
+ const cols = xs.length;
1377
+ const nodeAt = (i) => [xs[i % cols], ys[Math.floor(i / cols)]];
1378
+ const indexOf = ([x, y]) => ys.indexOf(y) * cols + xs.indexOf(x);
1379
+ const blocked = (p) => p !== from && p !== to && boxes.some((b) => strictlyInside(p, b));
1380
+ const edgeBlocked = (a, b) => boxes.some((box) => !strictlyInside(a, box) && !strictlyInside(b, box) && crosses(a, b, box));
1381
+ const startNode = indexOf(from);
1382
+ const goalNode = indexOf(to);
1383
+ const g = /* @__PURE__ */ new Map();
1384
+ const parent = /* @__PURE__ */ new Map();
1385
+ const heap = new MinHeap();
1386
+ const h = (p) => Math.abs(p[0] - to[0]) + Math.abs(p[1] - to[1]);
1387
+ const startKey = startNode * 4 + startDir;
1388
+ g.set(startKey, 0);
1389
+ heap.push(startKey, h(from));
1390
+ let best = null;
1391
+ while (heap.size > 0) {
1392
+ const key = heap.pop();
1393
+ const cost = g.get(key);
1394
+ if (best && cost >= best.cost) break;
1395
+ const node = Math.floor(key / 4);
1396
+ const dir = key % 4;
1397
+ const p = node === startNode ? from : node === goalNode ? to : nodeAt(node);
1398
+ if (node === goalNode) {
1399
+ const total = cost + (dir === endDir ? 0 : BEND_PENALTY * 1.5);
1400
+ if (!best || total < best.cost) best = {
1401
+ cost: total,
1402
+ key
1403
+ };
1404
+ continue;
1405
+ }
1406
+ const xi = node % cols;
1407
+ const yi = Math.floor(node / cols);
1408
+ for (let d = 0; d < 4; d++) {
1409
+ if ((d + 2) % 4 === dir) continue;
1410
+ const nx = xi + DIRS[d][0];
1411
+ const ny = yi + DIRS[d][1];
1412
+ if (nx < 0 || ny < 0 || nx >= cols || ny >= ys.length) continue;
1413
+ const next = ny * cols + nx;
1414
+ const q = next === goalNode ? to : nodeAt(next);
1415
+ if (blocked(q) || edgeBlocked(p, q)) continue;
1416
+ const nextKey = next * 4 + d;
1417
+ const ng = cost + Math.abs(q[0] - p[0]) + Math.abs(q[1] - p[1]) + (d === dir ? 0 : BEND_PENALTY);
1418
+ if (ng >= (g.get(nextKey) ?? Infinity)) continue;
1419
+ g.set(nextKey, ng);
1420
+ parent.set(nextKey, key);
1421
+ heap.push(nextKey, ng + h(q));
1422
+ }
1423
+ }
1424
+ if (!best) return null;
1425
+ const path = [];
1426
+ let key = best.key;
1427
+ while (key !== void 0) {
1428
+ const node = Math.floor(key / 4);
1429
+ path.push(node === startNode ? from : node === goalNode ? to : nodeAt(node));
1430
+ key = parent.get(key);
1431
+ }
1432
+ return path.reverse();
1433
+ }
1434
+ function simplify(points, keep = /* @__PURE__ */ new Set()) {
1435
+ const out = [];
1436
+ for (const p of points) {
1437
+ if (out.length > 0 && same(out.at(-1), p)) continue;
1438
+ out.push(p);
1439
+ }
1440
+ for (let i = out.length - 2; i > 0; i--) {
1441
+ const [a, b, c] = [
1442
+ out[i - 1],
1443
+ out[i],
1444
+ out[i + 1]
1445
+ ];
1446
+ if ((a[0] === b[0] && b[0] === c[0] || a[1] === b[1] && b[1] === c[1]) && !keep.has(`${b[0]},${b[1]}`)) out.splice(i, 1);
1447
+ }
1448
+ return out;
1449
+ }
1450
+ function routeElbowArrow(start, end, opts) {
1451
+ const startHeading = opts.startHeading ?? (opts.startTarget ? headingForPoint(opts.startTarget, end) : towards(start, end));
1452
+ const endHeading = opts.endHeading ?? (opts.endTarget ? headingForPoint(opts.endTarget, start) : towards(end, start));
1453
+ const from = exitPoint(start, startHeading, opts.startTarget);
1454
+ const to = exitPoint(end, endHeading, opts.endTarget);
1455
+ const targets = [opts.startTarget, opts.endTarget].filter((el) => !!el).map((el) => getElementBounds(el));
1456
+ const boxes = [...opts.obstacles, ...targets].map((b) => expand(b, 20));
1457
+ const middle = searchGrid(from, to, dirIndex(startHeading), (dirIndex(endHeading) + 2) % 4, boxes);
1458
+ if (!middle) {
1459
+ const mx = (from[0] + to[0]) / 2;
1460
+ return simplify([
1461
+ start,
1462
+ from,
1463
+ [mx, from[1]],
1464
+ [mx, to[1]],
1465
+ to,
1466
+ end
1467
+ ]);
1468
+ }
1469
+ return simplify([
1470
+ start,
1471
+ ...middle,
1472
+ end
1473
+ ]);
1474
+ }
1475
+ function sidePoint(target, heading, gap) {
1476
+ const [minX, minY, maxX, maxY] = getElementBounds(target);
1477
+ const cx = (minX + maxX) / 2;
1478
+ const cy = (minY + maxY) / 2;
1479
+ if (heading[0] > 0) return [maxX + gap, cy];
1480
+ if (heading[0] < 0) return [minX - gap, cy];
1481
+ if (heading[1] > 0) return [cx, maxY + gap];
1482
+ return [cx, minY - gap];
1483
+ }
1484
+ var centerOf = (el) => {
1485
+ const [minX, minY, maxX, maxY] = getElementBounds(el);
1486
+ return [(minX + maxX) / 2, (minY + maxY) / 2];
1487
+ };
1488
+ function elbowObstacles(elements, arrowId) {
1489
+ return elements.filter((el) => el.id !== arrowId && isBindable(el)).map((el) => getElementBounds(el));
1490
+ }
1491
+ function lookupTarget(byId, id) {
1492
+ const el = id ? byId.get(id) : void 0;
1493
+ return el && !el.isDeleted ? el : null;
1494
+ }
1495
+ function updateElbowArrow(arrow, elements) {
1496
+ const byId = new Map(elements.map((el) => [el.id, el]));
1497
+ const abs = getLinearAbsolutePoints(arrow);
1498
+ if (abs.length < 2) return arrow;
1499
+ const startTarget = lookupTarget(byId, arrow.startBinding?.elementId);
1500
+ const endTarget = lookupTarget(byId, arrow.endBinding?.elementId);
1501
+ const fixed = [...arrow.fixedSegments ?? []].sort((a, b) => a.index - b.index).map((seg) => ({
1502
+ start: [arrow.x + seg.start[0], arrow.y + seg.start[1]],
1503
+ end: [arrow.x + seg.end[0], arrow.y + seg.end[1]]
1504
+ })).filter((seg) => !same(seg.start, seg.end));
1505
+ const firstAnchor = fixed[0]?.start ?? (endTarget ? centerOf(endTarget) : abs.at(-1));
1506
+ const lastAnchor = fixed.at(-1)?.end ?? (startTarget ? centerOf(startTarget) : abs[0]);
1507
+ let start = abs[0];
1508
+ let startHeading;
1509
+ if (startTarget) {
1510
+ startHeading = headingForPoint(startTarget, firstAnchor);
1511
+ start = sidePoint(startTarget, startHeading, arrow.startBinding?.gap ?? 4);
1512
+ }
1513
+ let end = abs.at(-1);
1514
+ let endHeading;
1515
+ if (endTarget) {
1516
+ endHeading = headingForPoint(endTarget, lastAnchor);
1517
+ end = sidePoint(endTarget, endHeading, arrow.endBinding?.gap ?? 4);
1518
+ }
1519
+ const obstacles = elbowObstacles(elements, arrow.id);
1520
+ const route = [];
1521
+ let from = start;
1522
+ let fromHeading = startHeading;
1523
+ let fromTarget = startTarget;
1524
+ for (const seg of fixed) {
1525
+ const d = towards(seg.start, seg.end);
1526
+ route.push(...routeElbowArrow(from, seg.start, {
1527
+ obstacles,
1528
+ startTarget: fromTarget,
1529
+ startHeading: fromHeading,
1530
+ endHeading: [-d[0], -d[1]]
1531
+ }));
1532
+ from = seg.end;
1533
+ fromHeading = d;
1534
+ fromTarget = null;
1535
+ }
1536
+ route.push(...routeElbowArrow(from, end, {
1537
+ obstacles,
1538
+ startTarget: fromTarget,
1539
+ startHeading: fromHeading,
1540
+ endTarget,
1541
+ endHeading
1542
+ }));
1543
+ const points = simplify(route, new Set(fixed.flatMap((seg) => [seg.start, seg.end]).map((p) => `${p[0]},${p[1]}`)));
1544
+ const [ox, oy] = points[0];
1545
+ const rel = points.map(([x, y]) => [x - ox, y - oy]);
1546
+ if (ox === arrow.x && oy === arrow.y && rel.length === arrow.points.length && rel.every((p, i) => same(p, arrow.points[i])) && angleOf$1(arrow) === 0) return arrow;
1547
+ const fixedSegments = [];
1548
+ for (const seg of fixed) {
1549
+ const k = points.findIndex((p, i) => i > 0 && same(points[i - 1], seg.start) && same(p, seg.end));
1550
+ if (k > 0) fixedSegments.push({
1551
+ index: k,
1552
+ start: [seg.start[0] - ox, seg.start[1] - oy],
1553
+ end: [seg.end[0] - ox, seg.end[1] - oy]
1554
+ });
1555
+ }
1556
+ const [minX, minY, maxX, maxY] = boundsOfPoints(rel);
1557
+ return bumpVersion(arrow, {
1558
+ x: ox,
1559
+ y: oy,
1560
+ angle: 0,
1561
+ points: rel,
1562
+ width: maxX - minX,
1563
+ height: maxY - minY,
1564
+ fixedSegments: arrow.fixedSegments ? fixedSegments : arrow.fixedSegments
1565
+ });
1566
+ }
1567
+ //#endregion
1568
+ //#region src/model/linear-points.ts
1569
+ function fromAbsolutePoints(el, abs) {
1570
+ const angle = angleOf$1(el);
1571
+ const c0 = getElementCenter(el);
1572
+ const locals = abs.map((p) => rotatePoint(p, c0, -angle));
1573
+ const [minX, minY, maxX, maxY] = boundsOfPoints(locals);
1574
+ const c1 = [(minX + maxX) / 2, (minY + maxY) / 2];
1575
+ const d = [c1[0] - c0[0], c1[1] - c0[1]];
1576
+ const rd = rotatePoint(d, [0, 0], angle);
1577
+ const t = [rd[0] - d[0], rd[1] - d[1]];
1578
+ const q = locals.map(([x, y]) => [x + t[0], y + t[1]]);
1579
+ const [ox, oy] = q[0];
1580
+ const points = q.map(([x, y]) => [x - ox, y - oy]);
1581
+ return {
1582
+ ...el,
1583
+ x: ox,
1584
+ y: oy,
1585
+ points,
1586
+ width: maxX - minX,
1587
+ height: maxY - minY
1588
+ };
1589
+ }
1590
+ function movePoint(el, index, p) {
1591
+ const abs = getLinearAbsolutePoints(el);
1592
+ abs[index] = p;
1593
+ return bumpVersion(el, fromAbsolutePoints(el, abs));
1594
+ }
1595
+ var bindingKey = (end) => end === "start" ? "startBinding" : "endBinding";
1596
+ function fromLocal(el, [lx, ly]) {
1597
+ return rotatePoint([el.x + lx, el.y + ly], getElementCenter(el), angleOf$1(el));
1598
+ }
1599
+ function outlineSegments(el) {
1600
+ const { width: w, height: h } = el;
1601
+ const corners = el.type === "diamond" ? [
1602
+ [w / 2, 0],
1603
+ [w, h / 2],
1604
+ [w / 2, h],
1605
+ [0, h / 2]
1606
+ ] : [
1607
+ [0, 0],
1608
+ [w, 0],
1609
+ [w, h],
1610
+ [0, h]
1611
+ ];
1612
+ return corners.map((p, i) => [p, corners[(i + 1) % corners.length]]);
1613
+ }
1614
+ function distanceToOutline(el, p) {
1615
+ const [lx, ly] = toLocalPoint(el, p);
1616
+ const { width: w, height: h } = el;
1617
+ if (el.type === "ellipse") {
1618
+ const rx = w / 2;
1619
+ const ry = h / 2;
1620
+ if (rx <= 0 || ry <= 0) return Infinity;
1621
+ const norm = Math.hypot((lx - rx) / rx, (ly - ry) / ry);
1622
+ return norm <= 1 ? 0 : (norm - 1) * Math.min(rx, ry);
1623
+ }
1624
+ if (el.type === "diamond") {
1625
+ if (w > 0 && h > 0 && Math.abs(lx - w / 2) / (w / 2) + Math.abs(ly - h / 2) / (h / 2) <= 1) return 0;
1626
+ return Math.min(...outlineSegments(el).map(([a, b]) => distanceToSegment([lx, ly], a, b)));
1627
+ }
1628
+ return Math.hypot(Math.max(-lx, 0, lx - w), Math.max(-ly, 0, ly - h));
1629
+ }
1630
+ function getHoveredBindable(elements, p, zoom, excludeIds = /* @__PURE__ */ new Set()) {
1631
+ const threshold = 15 / zoom;
1632
+ for (let i = elements.length - 1; i >= 0; i--) {
1633
+ const el = elements[i];
1634
+ if (excludeIds.has(el.id) || !isBindable(el)) continue;
1635
+ if (distanceToOutline(el, p) <= threshold) return el;
1636
+ }
1637
+ return null;
1638
+ }
1639
+ function raySegment(o, d, a, b) {
1640
+ const e = [b[0] - a[0], b[1] - a[1]];
1641
+ const denom = d[0] * e[1] - d[1] * e[0];
1642
+ if (Math.abs(denom) < 1e-12) return null;
1643
+ const ax = a[0] - o[0];
1644
+ const ay = a[1] - o[1];
1645
+ const t = (ax * e[1] - ay * e[0]) / denom;
1646
+ const s = (ax * d[1] - ay * d[0]) / denom;
1647
+ return s >= 0 && s <= 1 ? t : null;
1648
+ }
1649
+ function rayHits(el, o, d) {
1650
+ if (el.type !== "ellipse") return outlineSegments(el).map(([a, b]) => raySegment(o, d, a, b)).filter((t) => t !== null);
1651
+ const rx = el.width / 2;
1652
+ const ry = el.height / 2;
1653
+ if (rx <= 0 || ry <= 0) return [];
1654
+ const ox = (o[0] - rx) / rx;
1655
+ const oy = (o[1] - ry) / ry;
1656
+ const dx = d[0] / rx;
1657
+ const dy = d[1] / ry;
1658
+ const a = dx * dx + dy * dy;
1659
+ const b = 2 * (ox * dx + oy * dy);
1660
+ const c = ox * ox + oy * oy - 1;
1661
+ const disc = b * b - 4 * a * c;
1662
+ if (disc < 0 || a === 0) return [];
1663
+ const root = Math.sqrt(disc);
1664
+ return [(-b - root) / (2 * a), (-b + root) / (2 * a)];
1665
+ }
1666
+ function extentAlong(el, [nx, ny]) {
1667
+ const rx = el.width / 2;
1668
+ const ry = el.height / 2;
1669
+ if (el.type === "ellipse") return Math.hypot(rx * nx, ry * ny);
1670
+ if (el.type === "diamond") return Math.max(Math.abs(rx * nx), Math.abs(ry * ny));
1671
+ return Math.abs(rx * nx) + Math.abs(ry * ny);
1672
+ }
1673
+ function frameFor(target, from) {
1674
+ const c = [target.width / 2, target.height / 2];
1675
+ const o = toLocalPoint(target, from);
1676
+ const len = Math.hypot(c[0] - o[0], c[1] - o[1]);
1677
+ if (len < 1e-9) return null;
1678
+ const u = [(c[0] - o[0]) / len, (c[1] - o[1]) / len];
1679
+ const n = [-u[1], u[0]];
1680
+ return {
1681
+ c,
1682
+ o,
1683
+ u,
1684
+ n,
1685
+ len,
1686
+ half: extentAlong(target, n)
1687
+ };
1688
+ }
1689
+ var clamp$1 = (v, min, max) => Math.min(max, Math.max(min, v));
1690
+ function computeFocus(target, from, to) {
1691
+ const f = frameFor(target, from);
1692
+ if (!f || f.half === 0) return 0;
1693
+ const p = toLocalPoint(target, to);
1694
+ const v = [p[0] - f.o[0], p[1] - f.o[1]];
1695
+ const along = v[0] * f.u[0] + v[1] * f.u[1];
1696
+ if (along < 1e-9) return 0;
1697
+ return clamp$1(f.len / along * (v[0] * f.n[0] + v[1] * f.n[1]) / f.half, -1, 1);
1698
+ }
1699
+ function getBindingPoint(target, focus, gap, otherPoint) {
1700
+ const f = frameFor(target, otherPoint);
1701
+ if (!f) return getElementCenter(target);
1702
+ const offset = clamp$1(focus, -1, 1) * f.half;
1703
+ const aim = [f.c[0] + f.n[0] * offset, f.c[1] + f.n[1] * offset];
1704
+ const dist = Math.hypot(aim[0] - f.o[0], aim[1] - f.o[1]);
1705
+ if (dist < 1e-9) return fromLocal(target, aim);
1706
+ const d = [(aim[0] - f.o[0]) / dist, (aim[1] - f.o[1]) / dist];
1707
+ const hits = rayHits(target, f.o, d).filter((t) => t > 1e-9);
1708
+ if (hits.length === 0) return fromLocal(target, aim);
1709
+ const t = Math.max(0, Math.min(...hits) - gap);
1710
+ return fromLocal(target, [f.o[0] + d[0] * t, f.o[1] + d[1] * t]);
1711
+ }
1712
+ function withBoundElement(target, id, type, present) {
1713
+ const list = target.boundElements ?? [];
1714
+ if (list.some((b) => b.id === id) === present) return target;
1715
+ return bumpVersion(target, { boundElements: present ? [...list, {
1716
+ id,
1717
+ type
1718
+ }] : list.filter((b) => b.id !== id) });
1719
+ }
1720
+ function endIndices(linear, end) {
1721
+ const last = linear.points.length - 1;
1722
+ return end === "start" ? [0, Math.min(1, last)] : [last, Math.max(0, last - 1)];
1723
+ }
1724
+ function unbindLinearEnd(elements, linearId, end) {
1725
+ const linear = elements.find((el) => el.id === linearId);
1726
+ const binding = linear?.[bindingKey(end)];
1727
+ if (!linear || !binding) return [...elements];
1728
+ const keepRegistration = linear[bindingKey(end === "start" ? "end" : "start")]?.elementId === binding.elementId;
1729
+ const next = bumpVersion(linear, { [bindingKey(end)]: null });
1730
+ return elements.map((el) => {
1731
+ if (el.id === linearId) return next;
1732
+ if (el.id === binding.elementId && !keepRegistration) return withBoundElement(el, linearId, linear.type, false);
1733
+ return el;
1734
+ });
1735
+ }
1736
+ function bindLinearEnd(elements, linearId, end, targetId) {
1737
+ let current = unbindLinearEnd(elements, linearId, end);
1738
+ const linear = current.find((el) => el.id === linearId);
1739
+ const target = current.find((el) => el.id === targetId);
1740
+ if (!linear || !target || linear.points.length < 2) return current;
1741
+ const abs = getLinearAbsolutePoints(linear);
1742
+ const [index, adjacentIndex] = endIndices(linear, end);
1743
+ const focus = computeFocus(target, abs[adjacentIndex], abs[index]);
1744
+ const binding = {
1745
+ elementId: targetId,
1746
+ focus,
1747
+ gap: 4
1748
+ };
1749
+ const next = {
1750
+ ...movePoint(linear, index, getBindingPoint(target, focus, 4, abs[adjacentIndex])),
1751
+ [bindingKey(end)]: binding
1752
+ };
1753
+ current = current.map((el) => {
1754
+ if (el.id === linearId) return next;
1755
+ if (el.id === targetId) return withBoundElement(el, linearId, linear.type, true);
1756
+ return el;
1757
+ });
1758
+ return current;
1759
+ }
1760
+ var finiteOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
1761
+ function attachmentPoint(target, binding, other) {
1762
+ const fixed = binding.fixedPoint;
1763
+ if (Array.isArray(fixed) && fixed.length === 2 && fixed.every(Number.isFinite)) return fromLocal(target, [fixed[0] * target.width, fixed[1] * target.height]);
1764
+ return getBindingPoint(target, finiteOr(binding.focus, 0), finiteOr(binding.gap, 4), other);
1765
+ }
1766
+ function recomputeEnds(linear, byId, ends) {
1767
+ const abs = getLinearAbsolutePoints(linear);
1768
+ let changed = false;
1769
+ for (const end of ends) {
1770
+ const binding = linear[bindingKey(end)];
1771
+ const target = binding && byId.get(binding.elementId);
1772
+ if (!binding || !target || target.isDeleted) continue;
1773
+ const [index, adjacentIndex] = endIndices(linear, end);
1774
+ const next = attachmentPoint(target, binding, abs[adjacentIndex]);
1775
+ if (!next.every(Number.isFinite)) continue;
1776
+ abs[index] = next;
1777
+ changed = true;
1778
+ }
1779
+ return changed ? bumpVersion(linear, fromAbsolutePoints(linear, abs)) : linear;
1780
+ }
1781
+ function updateBoundArrows(elements, changedIds) {
1782
+ const byId = new Map(elements.map((el) => [el.id, el]));
1783
+ return elements.map((el) => {
1784
+ if (changedIds.has(el.id) || el.type !== "arrow" && el.type !== "line") return el;
1785
+ const linear = el;
1786
+ const ends = ["start", "end"].filter((end) => {
1787
+ const binding = linear[bindingKey(end)];
1788
+ return !!binding && changedIds.has(binding.elementId);
1789
+ });
1790
+ if (ends.length === 0) return el;
1791
+ return linear.elbowed ? updateElbowArrow(linear, elements) : recomputeEnds(linear, byId, ends);
1792
+ });
1793
+ }
1794
+ function unbindDetached(elements, movedIds) {
1795
+ let current = [...elements];
1796
+ for (const el of elements) {
1797
+ if (!movedIds.has(el.id) || el.type !== "arrow" && el.type !== "line") continue;
1798
+ for (const end of ["start", "end"]) {
1799
+ const binding = el[bindingKey(end)];
1800
+ if (binding && !movedIds.has(binding.elementId)) current = unbindLinearEnd(current, el.id, end);
1801
+ }
1802
+ }
1803
+ return current;
1804
+ }
1805
+ //#endregion
1806
+ //#region src/editor/binding-actions.ts
1807
+ function refreshBindings(elements, changedIds) {
1808
+ const detached = unbindDetached(elements, changedIds);
1809
+ const updated = updateBoundArrows(detached, changedIds);
1810
+ const arrows = new Set(updated.filter((el, i) => el !== detached[i]).map((el) => el.id));
1811
+ return arrows.size > 0 ? relayoutBoundTexts(updated, arrows) : updated;
1812
+ }
1813
+ function excludedFor(elements, linearId) {
1814
+ const ids = /* @__PURE__ */ new Set([linearId]);
1815
+ for (const el of elements) if (el.type === "text" && el.containerId === linearId) ids.add(el.id);
1816
+ return ids;
1817
+ }
1818
+ function findBindingTarget(elements, linearId, p, zoom) {
1819
+ return getHoveredBindable(elements, p, zoom, excludedFor(elements, linearId));
1820
+ }
1821
+ function bindArrowEnds(elements, linearId, ends, zoom) {
1822
+ let current = [...elements];
1823
+ for (const end of ends) {
1824
+ const linear = current.find((el) => el.id === linearId);
1825
+ if (!linear || linear.type !== "arrow") return current;
1826
+ const abs = getLinearAbsolutePoints(linear);
1827
+ const p = end === "start" ? abs[0] : abs.at(-1);
1828
+ const target = findBindingTarget(current, linearId, p, zoom);
1829
+ current = target ? bindLinearEnd(current, linearId, end, target.id) : unbindLinearEnd(current, linearId, end);
1830
+ }
1831
+ return relayoutBoundTexts(rerouteElbow(current, linearId), /* @__PURE__ */ new Set([linearId]));
1832
+ }
1833
+ function rerouteElbow(elements, linearId) {
1834
+ return elements.map((el) => el.id === linearId && el.elbowed ? updateElbowArrow(el, elements) : el);
1835
+ }
1836
+ //#endregion
1837
+ //#region src/editor/richtext-actions.ts
1838
+ function startRichTextEditing(store, id) {
1839
+ const el = store.getState().elements.find((item) => item.id === id);
1840
+ if (!el || el.type !== "richtext" || el.isDeleted || el.locked) return;
1841
+ store.setState({
1842
+ editingRichTextId: id,
1843
+ selectedIds: /* @__PURE__ */ new Set([id]),
1844
+ editingGroupId: null
1845
+ });
1846
+ }
1847
+ function stopRichTextEditing(store) {
1848
+ if (store.getState().editingRichTextId) store.setState({ editingRichTextId: null });
1849
+ }
1850
+ function commitRichTextContent(store, id, content) {
1851
+ store.commit(({ elements }) => {
1852
+ const next = elements.map((el) => el.id === id && el.type === "richtext" ? bumpVersion(el, { content }) : el);
1853
+ return { elements: refreshBindings(resolveRichTextHeights(next), /* @__PURE__ */ new Set([id])) };
1854
+ });
1855
+ }
1856
+ //#endregion
1857
+ //#region src/editor/card-actions.ts
1858
+ var CARD_WIDTH = 200;
1859
+ var CARD_HEIGHT = 120;
1860
+ function placeCard(store, at) {
1861
+ const [card] = resolveRichTextHeights([newRichTextElement({
1862
+ x: at[0] - 100,
1863
+ y: at[1] - 60,
1864
+ width: 200,
1865
+ height: 120
1866
+ })]);
1867
+ store.commit(({ elements }) => ({ elements: [...elements, card] }));
1868
+ store.setState({ tool: "selection" });
1869
+ startRichTextEditing(store, card.id);
1870
+ return card.id;
1871
+ }
1872
+ function setTool(store, tool) {
1873
+ store.setState({
1874
+ tool,
1875
+ selectedIds: tool === "selection" ? store.getState().selectedIds : /* @__PURE__ */ new Set()
1876
+ });
1877
+ }
1878
+ //#endregion
1879
+ //#region src/editor/grid.ts
1880
+ function activeGrid(store, e) {
1881
+ const { gridSize } = store.getState();
1882
+ return gridSize && gridSize > 0 && !e.ctrlKey ? gridSize : null;
1883
+ }
1884
+ var snapValue = (value, grid) => grid ? Math.round(value / grid) * grid : value;
1885
+ var snapPoint = ([x, y], grid) => grid ? [snapValue(x, grid), snapValue(y, grid)] : [x, y];
1886
+ //#endregion
1887
+ //#region src/editor/tools/creation.ts
1888
+ function replaceElement(store, next) {
1889
+ store.updateTransient(({ elements }) => ({ elements: elements.map((el) => el.id === next.id ? next : el) }));
1890
+ }
1891
+ function appendElement(store, el) {
1892
+ store.updateTransient(({ elements }) => ({ elements: [...elements, el] }));
1893
+ }
1894
+ function finishCreation(store, id, select = true) {
1895
+ store.updateTransient(({ elements }) => ({ elements: refreshFrames(elements, /* @__PURE__ */ new Set([id])) }));
1896
+ store.endTransient(true);
1897
+ const state = store.getState();
1898
+ store.setState({
1899
+ selectedIds: select ? /* @__PURE__ */ new Set([id]) : state.selectedIds,
1900
+ tool: state.toolLocked ? state.tool : "selection"
1901
+ });
1902
+ }
1903
+ function cancelCreation(store) {
1904
+ store.endTransient(false);
1905
+ }
1906
+ function findElement(store, id) {
1907
+ return store.getState().elements.find((el) => el.id === id);
1908
+ }
1909
+ //#endregion
1910
+ //#region src/editor/tools/card.ts
1911
+ function createCardTool() {
1912
+ let id = null;
1913
+ let start = [0, 0];
1914
+ let origin = [0, 0];
1915
+ return {
1916
+ onPointerDown(ctx, e) {
1917
+ const { store } = ctx;
1918
+ origin = e.scene;
1919
+ start = snapPoint(e.scene, activeGrid(store, e));
1920
+ const el = newRichTextElement({
1921
+ x: start[0],
1922
+ y: start[1],
1923
+ width: 0,
1924
+ height: 0
1925
+ });
1926
+ id = el.id;
1927
+ store.beginTransient();
1928
+ appendElement(store, el);
1929
+ store.setState({ selectedIds: /* @__PURE__ */ new Set() });
1930
+ },
1931
+ onPointerMove(ctx, e) {
1932
+ if (!id) return;
1933
+ const current = findElement(ctx.store, id);
1934
+ if (!current) return;
1935
+ const at = snapPoint(e.scene, activeGrid(ctx.store, e));
1936
+ replaceElement(ctx.store, {
1937
+ ...current,
1938
+ x: Math.min(start[0], at[0]),
1939
+ y: Math.min(start[1], at[1]),
1940
+ width: Math.abs(at[0] - start[0]),
1941
+ height: Math.abs(at[1] - start[1])
1942
+ });
1943
+ },
1944
+ onPointerUp(ctx, e) {
1945
+ if (!id) return;
1946
+ const { store } = ctx;
1947
+ const createdId = id;
1948
+ id = null;
1949
+ const current = findElement(store, createdId);
1950
+ if (!current) {
1951
+ cancelCreation(store);
1952
+ return;
1953
+ }
1954
+ const zoom = store.getState().viewport.zoom;
1955
+ const sized = Math.hypot(e.scene[0] - origin[0], e.scene[1] - origin[1]) * zoom < 2 ? {
1956
+ ...current,
1957
+ x: origin[0] - 100,
1958
+ y: origin[1] - 60,
1959
+ width: 200,
1960
+ height: 120
1961
+ } : current;
1962
+ replaceElement(store, resolveRichTextHeights([sized])[0]);
1963
+ finishCreation(store, createdId);
1964
+ startRichTextEditing(store, createdId);
1965
+ },
1966
+ cancel(ctx) {
1967
+ if (!id) return;
1968
+ id = null;
1969
+ cancelCreation(ctx.store);
1970
+ }
1971
+ };
1972
+ }
1973
+ //#endregion
1974
+ //#region src/editor/tools/eraser.ts
1975
+ var SAMPLE_STEP = 4;
1976
+ function collect(ctx, from, to) {
1977
+ const state = ctx.store.getState();
1978
+ const tol = 6 / state.viewport.zoom;
1979
+ const erasing = new Set(state.erasingIds);
1980
+ const steps = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[1] - from[1]) / SAMPLE_STEP));
1981
+ const alive = state.elements.filter((el) => !erasing.has(el.id));
1982
+ for (let i = 0; i <= steps; i++) {
1983
+ const hit = getHitElement(alive, [from[0] + (to[0] - from[0]) * i / steps, from[1] + (to[1] - from[1]) * i / steps], tol);
1984
+ if (hit) erasing.add(hit.id);
1985
+ }
1986
+ if (erasing.size !== state.erasingIds.size) ctx.store.setState({ erasingIds: erasing });
1987
+ }
1988
+ function createEraserTool() {
1989
+ let last = null;
1990
+ return {
1991
+ onPointerDown(ctx, e) {
1992
+ last = e.scene;
1993
+ ctx.store.setState({
1994
+ erasingIds: /* @__PURE__ */ new Set(),
1995
+ selectedIds: /* @__PURE__ */ new Set()
1996
+ });
1997
+ collect(ctx, e.scene, e.scene);
1998
+ },
1999
+ onPointerMove(ctx, e) {
2000
+ if (!last) return;
2001
+ collect(ctx, last, e.scene);
2002
+ last = e.scene;
2003
+ },
2004
+ onPointerUp(ctx) {
2005
+ if (!last) return;
2006
+ last = null;
2007
+ const { store } = ctx;
2008
+ const ids = withBoundText(store.getState().elements, store.getState().erasingIds);
2009
+ store.setState({ erasingIds: /* @__PURE__ */ new Set() });
2010
+ if (ids.size === 0) return;
2011
+ store.commit(({ elements }) => ({ elements: deleteElements(elements, ids) }));
2012
+ },
2013
+ cancel(ctx) {
2014
+ last = null;
2015
+ ctx.store.setState({ erasingIds: /* @__PURE__ */ new Set() });
2016
+ }
2017
+ };
2018
+ }
2019
+ //#endregion
2020
+ //#region src/editor/tools/freedraw.ts
2021
+ function createFreedrawTool() {
2022
+ let id = null;
2023
+ return {
2024
+ onPointerDown(ctx, e) {
2025
+ const { store } = ctx;
2026
+ const isPen = e.pointerType === "pen";
2027
+ const el = newFreedrawElement({
2028
+ x: e.scene[0],
2029
+ y: e.scene[1],
2030
+ points: [[0, 0]],
2031
+ pressures: isPen ? [e.pressure] : [],
2032
+ simulatePressure: !isPen
2033
+ }, store.getState().currentStyle);
2034
+ id = el.id;
2035
+ store.beginTransient();
2036
+ appendElement(store, el);
2037
+ store.setState({ selectedIds: /* @__PURE__ */ new Set() });
2038
+ },
2039
+ onPointerMove(ctx, e) {
2040
+ if (!id) return;
2041
+ const el = findElement(ctx.store, id);
2042
+ if (!el) return;
2043
+ const points = [...el.points, [e.scene[0] - el.x, e.scene[1] - el.y]];
2044
+ const [minX, minY, maxX, maxY] = boundsOfPoints(points);
2045
+ replaceElement(ctx.store, {
2046
+ ...el,
2047
+ points,
2048
+ pressures: el.simulatePressure ? el.pressures : [...el.pressures, e.pressure],
2049
+ width: maxX - minX,
2050
+ height: maxY - minY
2051
+ });
2052
+ },
2053
+ onPointerUp(ctx) {
2054
+ if (!id) return;
2055
+ id = null;
2056
+ ctx.store.endTransient(true);
2057
+ },
2058
+ cancel(ctx) {
2059
+ if (!id) return;
2060
+ id = null;
2061
+ ctx.store.endTransient(false);
2062
+ }
2063
+ };
2064
+ }
2065
+ //#endregion
2066
+ //#region src/editor/tools/hand.ts
2067
+ function createHandTool() {
2068
+ let start = null;
2069
+ let origin = null;
2070
+ return {
2071
+ onPointerDown(ctx, e) {
2072
+ start = e.screen;
2073
+ origin = ctx.store.getState().viewport;
2074
+ },
2075
+ onPointerMove(ctx, e) {
2076
+ if (!start || !origin) return;
2077
+ ctx.store.setState({ viewport: {
2078
+ ...origin,
2079
+ scrollX: origin.scrollX + (e.screen[0] - start[0]) / origin.zoom,
2080
+ scrollY: origin.scrollY + (e.screen[1] - start[1]) / origin.zoom
2081
+ } });
2082
+ },
2083
+ onPointerUp() {
2084
+ start = null;
2085
+ origin = null;
2086
+ }
2087
+ };
2088
+ }
2089
+ //#endregion
2090
+ //#region src/editor/tools/image.ts
2091
+ function createImageTool() {
2092
+ return {
2093
+ onPointerDown(ctx, e) {
2094
+ ctx.requestImage?.(e.scene);
2095
+ },
2096
+ onPointerMove() {},
2097
+ onPointerUp() {}
2098
+ };
2099
+ }
2100
+ //#endregion
2101
+ //#region src/editor/tools/linear.ts
2102
+ var SNAP = Math.PI / 12;
2103
+ function withPoints(el, absolute) {
2104
+ const [ox, oy] = absolute[0];
2105
+ const points = absolute.map(([x, y]) => [x - ox, y - oy]);
2106
+ const [minX, minY, maxX, maxY] = boundsOfPoints(points);
2107
+ return {
2108
+ ...el,
2109
+ x: ox,
2110
+ y: oy,
2111
+ points,
2112
+ width: maxX - minX,
2113
+ height: maxY - minY
2114
+ };
2115
+ }
2116
+ function snapAngle(from, to) {
2117
+ const dx = to[0] - from[0];
2118
+ const dy = to[1] - from[1];
2119
+ const length = Math.hypot(dx, dy);
2120
+ const angle = Math.round(Math.atan2(dy, dx) / SNAP) * SNAP;
2121
+ return [from[0] + Math.cos(angle) * length, from[1] + Math.sin(angle) * length];
2122
+ }
2123
+ function absolutePoints(el) {
2124
+ return el.points.map(([x, y]) => [el.x + x, el.y + y]);
2125
+ }
2126
+ function createLinearTool(type, options = {}) {
2127
+ let id = null;
2128
+ let phase = "idle";
2129
+ let downAt = [0, 0];
2130
+ let origin = [0, 0];
2131
+ let suppressBinding = false;
2132
+ const suggest = (ctx, el, p) => {
2133
+ const { elements, viewport } = ctx.store.getState();
2134
+ const target = type === "arrow" && !suppressBinding ? findBindingTarget(elements, el.id, p, viewport.zoom) : null;
2135
+ ctx.store.setState({ suggestedBindingId: target?.id ?? null });
2136
+ };
2137
+ const update = (ctx, e) => {
2138
+ const el = id ? findElement(ctx.store, id) : void 0;
2139
+ if (!el) return;
2140
+ const at = snapPoint(e.scene, activeGrid(ctx.store, e));
2141
+ let next;
2142
+ if (el.elbowed) {
2143
+ const { elements, viewport } = ctx.store.getState();
2144
+ const targetAt = (p) => suppressBinding ? null : findBindingTarget(elements, el.id, p, viewport.zoom);
2145
+ next = withPoints(el, routeElbowArrow(origin, at, {
2146
+ obstacles: elbowObstacles(elements, el.id),
2147
+ startTarget: targetAt(origin),
2148
+ endTarget: targetAt(at)
2149
+ }));
2150
+ } else {
2151
+ const pts = absolutePoints(el);
2152
+ const anchor = pts.at(-2) ?? pts[0];
2153
+ pts[pts.length - 1] = e.shiftKey ? snapAngle(anchor, at) : at;
2154
+ next = withPoints(el, pts);
2155
+ }
2156
+ if (options.onPointMoved) next = options.onPointMoved(ctx, next, e);
2157
+ replaceElement(ctx.store, next);
2158
+ suggest(ctx, next, absolutePoints(next).at(-1));
2159
+ };
2160
+ const finish = (store, dropPreview, ctx) => {
2161
+ const el = id ? findElement(store, id) : void 0;
2162
+ const createdId = id;
2163
+ id = null;
2164
+ phase = "idle";
2165
+ if (!el || !createdId) return;
2166
+ const pts = absolutePoints(el);
2167
+ if (dropPreview && el.elbowed) pts.length = 0;
2168
+ if (dropPreview) pts.pop();
2169
+ if (pts.length < 2) {
2170
+ cancelCreation(store);
2171
+ return;
2172
+ }
2173
+ const finalEl = withPoints(el, pts);
2174
+ replaceElement(store, finalEl);
2175
+ if (type === "arrow" && !suppressBinding) {
2176
+ const zoom = store.getState().viewport.zoom;
2177
+ store.updateTransient(({ elements }) => ({ elements: bindArrowEnds(elements, createdId, ["start", "end"], zoom) }));
2178
+ }
2179
+ store.setState({ suggestedBindingId: null });
2180
+ finishCreation(store, createdId);
2181
+ if (ctx) options.onFinished?.(ctx, finalEl);
2182
+ };
2183
+ return {
2184
+ onPointerDown(ctx, e) {
2185
+ const { store } = ctx;
2186
+ downAt = e.screen;
2187
+ suppressBinding = e.ctrlKey;
2188
+ if (phase !== "multi") origin = snapPoint(e.scene, activeGrid(store, e));
2189
+ if (phase === "multi" && id) {
2190
+ const el = findElement(store, id);
2191
+ if (el.elbowed) {
2192
+ update(ctx, e);
2193
+ finish(store, false, ctx);
2194
+ return;
2195
+ }
2196
+ const pts = absolutePoints(el);
2197
+ replaceElement(store, withPoints(el, [...pts, pts.at(-1)]));
2198
+ return;
2199
+ }
2200
+ const el = newLinearElement(type, {
2201
+ x: origin[0],
2202
+ y: origin[1],
2203
+ points: [[0, 0], [0, 0]]
2204
+ }, store.getState().currentStyle);
2205
+ id = el.id;
2206
+ phase = "dragging";
2207
+ store.beginTransient();
2208
+ appendElement(store, el);
2209
+ store.setState({ selectedIds: /* @__PURE__ */ new Set() });
2210
+ },
2211
+ onPointerMove(ctx, e) {
2212
+ if (phase === "idle") return;
2213
+ suppressBinding = e.ctrlKey;
2214
+ update(ctx, e);
2215
+ },
2216
+ onPointerUp(ctx, e) {
2217
+ if (phase !== "dragging") return;
2218
+ suppressBinding = e.ctrlKey;
2219
+ if (Math.hypot(e.screen[0] - downAt[0], e.screen[1] - downAt[1]) < 2) {
2220
+ phase = "multi";
2221
+ return;
2222
+ }
2223
+ finish(ctx.store, false, ctx);
2224
+ },
2225
+ onDoubleClick(ctx) {
2226
+ if (phase === "multi") finish(ctx.store, true, ctx);
2227
+ },
2228
+ onKeyDown(ctx, e) {
2229
+ if (phase === "idle") return false;
2230
+ if (e.key === "Enter" || e.key === "Escape") {
2231
+ finish(ctx.store, true, ctx);
2232
+ return true;
2233
+ }
2234
+ return false;
2235
+ },
2236
+ cancel(ctx) {
2237
+ if (!id) return;
2238
+ if (phase === "multi") {
2239
+ finish(ctx.store, true, ctx);
2240
+ return;
2241
+ }
2242
+ id = null;
2243
+ phase = "idle";
2244
+ ctx.store.setState({ suggestedBindingId: null });
2245
+ cancelCreation(ctx.store);
2246
+ }
2247
+ };
2248
+ }
2249
+ function isEditableLinear(el) {
2250
+ return !!el && (el.type === "line" || el.type === "arrow") && !el.locked;
2251
+ }
2252
+ function insertPoint(el, segmentIndex, p) {
2253
+ const abs = getLinearAbsolutePoints(el);
2254
+ abs.splice(segmentIndex + 1, 0, p);
2255
+ return bumpVersion(el, fromAbsolutePoints(el, abs));
2256
+ }
2257
+ function removePoint(el, index) {
2258
+ if (el.points.length <= 2) return el;
2259
+ const abs = getLinearAbsolutePoints(el);
2260
+ abs.splice(index, 1);
2261
+ return bumpVersion(el, fromAbsolutePoints(el, abs));
2262
+ }
2263
+ function getMidpoints(el) {
2264
+ const abs = getLinearAbsolutePoints(el);
2265
+ const mids = [];
2266
+ for (let i = 0; i < abs.length - 1; i++) mids.push([(abs[i][0] + abs[i + 1][0]) / 2, (abs[i][1] + abs[i + 1][1]) / 2]);
2267
+ return mids;
2268
+ }
2269
+ function getEditedLinear(state) {
2270
+ const selected = getSelectedElements(state);
2271
+ if (selected.length !== 1) return null;
2272
+ return isEditableLinear(selected[0]) ? selected[0] : null;
2273
+ }
2274
+ function getElbowSegmentHandles(el) {
2275
+ const abs = getLinearAbsolutePoints(el);
2276
+ const handles = [];
2277
+ for (let i = 1; i < abs.length - 2; i++) handles.push({
2278
+ index: i,
2279
+ point: [(abs[i][0] + abs[i + 1][0]) / 2, (abs[i][1] + abs[i + 1][1]) / 2]
2280
+ });
2281
+ return handles;
2282
+ }
2283
+ function moveElbowSegment(el, index, p) {
2284
+ const abs = getLinearAbsolutePoints(el);
2285
+ const axis = abs[index][1] === abs[index + 1][1] ? 1 : 0;
2286
+ abs[index][axis] = p[axis];
2287
+ abs[index + 1][axis] = p[axis];
2288
+ const moved = fromAbsolutePoints(el, abs);
2289
+ const rel = (q) => [q[0] - moved.x, q[1] - moved.y];
2290
+ const others = (el.fixedSegments ?? []).filter((seg) => seg.index !== index + 1);
2291
+ return bumpVersion(el, {
2292
+ ...moved,
2293
+ fixedSegments: [...others, {
2294
+ index: index + 1,
2295
+ start: rel(abs[index]),
2296
+ end: rel(abs[index + 1])
2297
+ }].sort((a, b) => a.index - b.index)
2298
+ });
2299
+ }
2300
+ function hitPointHandle(el, p, zoom) {
2301
+ const radius = 8 / zoom;
2302
+ const near = ([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= radius;
2303
+ const abs = getLinearAbsolutePoints(el);
2304
+ for (let i = abs.length - 1; i >= 0; i--) if ((i === 0 || i === abs.length - 1 || !el.elbowed) && near(abs[i])) return {
2305
+ kind: "point",
2306
+ index: i
2307
+ };
2308
+ if (el.elbowed) {
2309
+ for (const handle of getElbowSegmentHandles(el)) if (near(handle.point)) return {
2310
+ kind: "segment",
2311
+ index: handle.index
2312
+ };
2313
+ return null;
2314
+ }
2315
+ const mids = getMidpoints(el);
2316
+ for (let i = 0; i < mids.length; i++) if (near(mids[i])) return {
2317
+ kind: "midpoint",
2318
+ index: i
2319
+ };
2320
+ return null;
2321
+ }
2322
+ //#endregion
2323
+ //#region src/editor/tools/point-gesture.ts
2324
+ function startPointGesture(ctx, e, onMove) {
2325
+ const { store } = ctx;
2326
+ const state = store.getState();
2327
+ const el = getEditedLinear(state);
2328
+ if (!el) return null;
2329
+ const hit = hitPointHandle(el, e.scene, state.viewport.zoom);
2330
+ if (!hit) return null;
2331
+ const original = el;
2332
+ const baseIndex = hit.kind === "point" ? hit.index : hit.kind === "midpoint" ? hit.index + 1 : -1;
2333
+ let index = baseIndex;
2334
+ let moved = false;
2335
+ let suppressBinding = e.ctrlKey;
2336
+ const downAt = e.screen;
2337
+ const endOf = (i, count) => el.type !== "arrow" ? null : i === 0 ? "start" : i === count - 1 ? "end" : null;
2338
+ store.setState({ selectedPointIndex: hit.kind === "point" ? hit.index : null });
2339
+ store.beginTransient();
2340
+ return {
2341
+ cancel() {
2342
+ store.setState({ suggestedBindingId: null });
2343
+ store.endTransient(false);
2344
+ index = -1;
2345
+ },
2346
+ move(ev) {
2347
+ if (!moved && Math.hypot(ev.screen[0] - downAt[0], ev.screen[1] - downAt[1]) < 2) return;
2348
+ moved = true;
2349
+ let next;
2350
+ if (hit.kind === "segment") next = moveElbowSegment(original, hit.index, ev.scene);
2351
+ else if (hit.kind === "midpoint") next = movePoint(insertPoint(original, hit.index, ev.scene), baseIndex, ev.scene);
2352
+ else next = movePoint(original, baseIndex, ev.scene);
2353
+ const dragged = endOf(baseIndex, next.points.length);
2354
+ if (original.elbowed && dragged) {
2355
+ const key = dragged === "start" ? "startBinding" : "endBinding";
2356
+ next = {
2357
+ ...updateElbowArrow({
2358
+ ...next,
2359
+ [key]: null
2360
+ }, store.getState().elements),
2361
+ [key]: original[key]
2362
+ };
2363
+ index = dragged === "start" ? 0 : next.points.length - 1;
2364
+ }
2365
+ if (onMove) next = onMove(ctx, next, index, ev);
2366
+ store.updateTransient(({ elements }) => ({ elements: relayoutBoundTexts(elements.map((item) => item.id === next.id ? next : item), /* @__PURE__ */ new Set([next.id])) }));
2367
+ suppressBinding = ev.ctrlKey;
2368
+ const end = endOf(index, next.points.length);
2369
+ const { elements, viewport } = store.getState();
2370
+ const target = end && !suppressBinding ? findBindingTarget(elements, next.id, ev.scene, viewport.zoom) : null;
2371
+ store.setState({
2372
+ selectedPointIndex: index >= 0 ? index : null,
2373
+ suggestedBindingId: target?.id ?? null
2374
+ });
2375
+ },
2376
+ end() {
2377
+ const current = store.getState().elements.find((item) => item.id === el.id);
2378
+ const end = current && moved ? endOf(index, current.points.length) : null;
2379
+ if (end) {
2380
+ const zoom = store.getState().viewport.zoom;
2381
+ store.updateTransient(({ elements }) => ({ elements: suppressBinding ? unbindLinearEnd(elements, el.id, end) : bindArrowEnds(elements, el.id, [end], zoom) }));
2382
+ }
2383
+ store.setState({ suggestedBindingId: null });
2384
+ store.endTransient(moved);
2385
+ index = -1;
2386
+ }
2387
+ };
2388
+ }
2389
+ var MIN_SIZE = 1;
2390
+ var SNAP_ANGLE = Math.PI / 12;
2391
+ function unrotatedBox(el) {
2392
+ if (isLinear(el)) {
2393
+ const [minX, minY, maxX, maxY] = boundsOfPoints(el.points.length ? el.points : [[0, 0]]);
2394
+ return [
2395
+ el.x + minX,
2396
+ el.y + minY,
2397
+ el.x + maxX,
2398
+ el.y + maxY
2399
+ ];
2400
+ }
2401
+ return [
2402
+ el.x,
2403
+ el.y,
2404
+ el.x + el.width,
2405
+ el.y + el.height
2406
+ ];
2407
+ }
2408
+ function getTransformFrame(elements) {
2409
+ if (elements.length === 1) {
2410
+ const el = elements[0];
2411
+ return {
2412
+ box: unrotatedBox(el),
2413
+ angle: angleOf$1(el),
2414
+ center: getElementCenter(el)
2415
+ };
2416
+ }
2417
+ const box = getCommonBounds(elements);
2418
+ return {
2419
+ box,
2420
+ angle: 0,
2421
+ center: [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]
2422
+ };
2423
+ }
2424
+ function getTransformHandles(box, zoom, angle = 0) {
2425
+ const pad = 8 / zoom;
2426
+ const [x1, y1, x2, y2] = [
2427
+ box[0] - pad,
2428
+ box[1] - pad,
2429
+ box[2] + pad,
2430
+ box[3] + pad
2431
+ ];
2432
+ const cx = (box[0] + box[2]) / 2;
2433
+ const cy = (box[1] + box[3]) / 2;
2434
+ const raw = {
2435
+ nw: [x1, y1],
2436
+ n: [cx, y1],
2437
+ ne: [x2, y1],
2438
+ e: [x2, cy],
2439
+ se: [x2, y2],
2440
+ s: [cx, y2],
2441
+ sw: [x1, y2],
2442
+ w: [x1, cy],
2443
+ rotation: [cx, y1 - 24 / zoom]
2444
+ };
2445
+ if (!angle) return raw;
2446
+ const out = {};
2447
+ for (const [k, p] of Object.entries(raw)) out[k] = rotatePoint(p, [cx, cy], angle);
2448
+ return out;
2449
+ }
2450
+ function hitTransformHandle(handles, p, zoom) {
2451
+ const radius = 8 / zoom;
2452
+ for (const [k, [hx, hy]] of Object.entries(handles)) if (Math.hypot(p[0] - hx, p[1] - hy) <= radius) return k;
2453
+ return null;
2454
+ }
2455
+ function resizeBox(box, handle, delta, opts) {
2456
+ let [x1, y1, x2, y2] = box;
2457
+ const [dx, dy] = delta;
2458
+ if (handle.includes("e")) x2 += dx;
2459
+ if (handle.includes("w")) x1 += dx;
2460
+ if (handle.includes("s")) y2 += dy;
2461
+ if (handle.includes("n")) y1 += dy;
2462
+ if (opts.fromCenter) {
2463
+ if (handle.includes("e")) x1 -= dx;
2464
+ if (handle.includes("w")) x2 -= dx;
2465
+ if (handle.includes("s")) y1 -= dy;
2466
+ if (handle.includes("n")) y2 -= dy;
2467
+ }
2468
+ if (opts.keepRatio) {
2469
+ const ow = box[2] - box[0] || 1;
2470
+ const oh = box[3] - box[1] || 1;
2471
+ const horizontal = handle.includes("e") || handle.includes("w");
2472
+ const vertical = handle.includes("n") || handle.includes("s");
2473
+ const sx = (x2 - x1) / ow;
2474
+ const sy = (y2 - y1) / oh;
2475
+ const s = horizontal && vertical ? Math.abs(sx) > Math.abs(sy) ? sx : sy : horizontal ? sx : sy;
2476
+ const w = ow * s;
2477
+ const h = oh * s;
2478
+ const cx = (box[0] + box[2]) / 2;
2479
+ const cy = (box[1] + box[3]) / 2;
2480
+ if (opts.fromCenter) return [
2481
+ cx - w / 2,
2482
+ cy - h / 2,
2483
+ cx + w / 2,
2484
+ cy + h / 2
2485
+ ];
2486
+ const ax = handle.includes("w") ? box[2] : handle.includes("e") ? box[0] : cx - w / 2;
2487
+ const ay = handle.includes("n") ? box[3] : handle.includes("s") ? box[1] : cy - h / 2;
2488
+ const nx1 = handle.includes("w") ? ax - w : ax;
2489
+ const ny1 = handle.includes("n") ? ay - h : ay;
2490
+ return [
2491
+ nx1,
2492
+ ny1,
2493
+ nx1 + w,
2494
+ ny1 + h
2495
+ ];
2496
+ }
2497
+ return [
2498
+ Math.min(x1, x2),
2499
+ Math.min(y1, y2),
2500
+ Math.max(x1, x2),
2501
+ Math.max(y1, y2)
2502
+ ];
2503
+ }
2504
+ function placeElement(el, frame, next, single) {
2505
+ const [ox1, oy1, ox2, oy2] = frame.box;
2506
+ const sx = (next[2] - next[0]) / (ox2 - ox1 || 1);
2507
+ const sy = (next[3] - next[1]) / (oy2 - oy1 || 1);
2508
+ const elBox = unrotatedBox(el);
2509
+ const newElBox = single ? next : [
2510
+ next[0] + (elBox[0] - ox1) * sx,
2511
+ next[1] + (elBox[1] - oy1) * sy,
2512
+ next[0] + (elBox[2] - ox1) * sx,
2513
+ next[1] + (elBox[3] - oy1) * sy
2514
+ ];
2515
+ const w = Math.max(MIN_SIZE, newElBox[2] - newElBox[0]);
2516
+ const h = Math.max(MIN_SIZE, newElBox[3] - newElBox[1]);
2517
+ const localCenter = [(newElBox[0] + newElBox[2]) / 2, (newElBox[1] + newElBox[3]) / 2];
2518
+ const center = single ? rotatePoint(localCenter, frame.center, frame.angle) : localCenter;
2519
+ const patch = {
2520
+ width: w,
2521
+ height: h
2522
+ };
2523
+ if (isLinear(el)) {
2524
+ const pts = el.points.length ? el.points : [[0, 0]];
2525
+ const [minX, minY] = boundsOfPoints(pts);
2526
+ patch.points = pts.map(([px, py]) => [minX + (px - minX) * sx, minY + (py - minY) * sy]);
2527
+ patch.x = center[0] - w / 2 - minX;
2528
+ patch.y = center[1] - h / 2 - minY;
2529
+ } else {
2530
+ patch.x = center[0] - w / 2;
2531
+ patch.y = center[1] - h / 2;
2532
+ }
2533
+ if (el.type === "text") patch.fontSize = el.fontSize * Math.min(sx, sy);
2534
+ return bumpVersion(el, patch);
2535
+ }
2536
+ function resizeElements(elements, handle, start, current, opts) {
2537
+ if (elements.length === 0 || handle === "rotation") return [...elements];
2538
+ const frame = getTransformFrame(elements);
2539
+ const delta = rotatePoint([current[0] - start[0], current[1] - start[1]], [0, 0], -frame.angle);
2540
+ const keepRatio = opts.keepRatio || elements.every((el) => el.type === "text" || el.type === "svg");
2541
+ const next = resizeBox(frame.box, handle, delta, {
2542
+ ...opts,
2543
+ keepRatio
2544
+ });
2545
+ const single = elements.length === 1;
2546
+ return resolveRichTextHeights(elements.map((el) => placeElement(el, frame, next, single)));
2547
+ }
2548
+ function normalizeAngle(angle) {
2549
+ const full = Math.PI * 2;
2550
+ return (angle % full + full) % full;
2551
+ }
2552
+ function rotateElements(elements, center, delta, opts) {
2553
+ if (elements.length === 1) {
2554
+ const el = elements[0];
2555
+ let angle = normalizeAngle(angleOf$1(el) + delta);
2556
+ if (opts.snap) angle = normalizeAngle(Math.round(angle / SNAP_ANGLE) * SNAP_ANGLE);
2557
+ return [bumpVersion(el, { angle })];
2558
+ }
2559
+ const step = opts.snap ? Math.round(delta / SNAP_ANGLE) * SNAP_ANGLE : delta;
2560
+ return elements.map((el) => {
2561
+ const c = getElementCenter(el);
2562
+ const [nx, ny] = rotatePoint(c, center, step);
2563
+ return bumpVersion(el, {
2564
+ x: el.x + nx - c[0],
2565
+ y: el.y + ny - c[1],
2566
+ angle: normalizeAngle(angleOf$1(el) + step)
2567
+ });
2568
+ });
2569
+ }
2570
+ function nudge(elements, ids, dx, dy) {
2571
+ return elements.map((el) => ids.has(el.id) ? bumpVersion(el, {
2572
+ x: el.x + dx,
2573
+ y: el.y + dy
2574
+ }) : el);
2575
+ }
2576
+ //#endregion
2577
+ //#region src/editor/tools/transform-gesture.ts
2578
+ function getTransformTargets(state) {
2579
+ const selected = getSelectedElements(state).filter((el) => !(el.type === "text" && el.containerId));
2580
+ if (selected.length === 0) return [];
2581
+ if (selected.length === 1) {
2582
+ const [el] = selected;
2583
+ if (el.locked) return [];
2584
+ if (isLinear(el) && el.type !== "freedraw" && el.points.length <= 2) return [];
2585
+ if (el.type === "arrow" && el.elbowed) return [];
2586
+ if (state.editingLinearId === el.id) return [];
2587
+ }
2588
+ return selected;
2589
+ }
2590
+ function getActiveHandles(state) {
2591
+ const targets = getTransformTargets(state);
2592
+ if (targets.length === 0) return null;
2593
+ const frame = getTransformFrame(targets);
2594
+ return getTransformHandles(frame.box, state.viewport.zoom, frame.angle);
2595
+ }
2596
+ var angleOf = (p, c) => Math.atan2(p[1] - c[1], p[0] - c[0]);
2597
+ function startTransformGesture(ctx, e) {
2598
+ const { store } = ctx;
2599
+ const state = store.getState();
2600
+ const handles = getActiveHandles(state);
2601
+ if (!handles) return null;
2602
+ const handle = hitTransformHandle(handles, e.scene, state.viewport.zoom);
2603
+ if (!handle) return null;
2604
+ const originals = getTransformTargets(state);
2605
+ const ids = new Set(originals.map((el) => el.id));
2606
+ const frame = getTransformFrame(originals);
2607
+ const start = e.scene;
2608
+ const startAngle = angleOf(start, frame.center);
2609
+ let changed = false;
2610
+ store.beginTransient();
2611
+ const replace = (next) => {
2612
+ const byId = new Map(next.map((el) => [el.id, el]));
2613
+ store.updateTransient(({ elements }) => ({ elements: refreshFrames(refreshBindings(relayoutBoundTexts(elements.map((el) => ids.has(el.id) ? byId.get(el.id) : el), ids), ids), ids) }));
2614
+ };
2615
+ return {
2616
+ move(ev) {
2617
+ changed = true;
2618
+ if (handle === "rotation") {
2619
+ const delta = angleOf(ev.scene, frame.center) - startAngle;
2620
+ replace(rotateElements(originals, frame.center, delta, { snap: ev.shiftKey }));
2621
+ return;
2622
+ }
2623
+ replace(resizeElements(originals, handle, start, snapPoint(ev.scene, activeGrid(store, ev)), {
2624
+ keepRatio: ev.shiftKey,
2625
+ fromCenter: ev.altKey
2626
+ }));
2627
+ },
2628
+ end(keep) {
2629
+ store.endTransient(keep && changed);
2630
+ }
2631
+ };
2632
+ }
2633
+ //#endregion
2634
+ //#region src/editor/tools/selection.ts
2635
+ function moveElements(originals, dx, dy) {
2636
+ return (elements) => elements.map((el) => {
2637
+ const original = originals.get(el.id);
2638
+ return original ? bumpVersion(original, {
2639
+ x: original.x + dx,
2640
+ y: original.y + dy
2641
+ }) : el;
2642
+ });
2643
+ }
2644
+ function createSelectionTool(options = {}) {
2645
+ let mode = "idle";
2646
+ let start = [0, 0];
2647
+ let moved = false;
2648
+ let originals = /* @__PURE__ */ new Map();
2649
+ let dragOrigin = [0, 0];
2650
+ let baseSelection = /* @__PURE__ */ new Set();
2651
+ let gesture = null;
2652
+ let pointGesture = null;
2653
+ return {
2654
+ onPointerDown(ctx, e) {
2655
+ const { store } = ctx;
2656
+ pointGesture = startPointGesture(ctx, e, options.onPointMove);
2657
+ if (pointGesture) {
2658
+ mode = "point";
2659
+ return;
2660
+ }
2661
+ gesture = startTransformGesture(ctx, e);
2662
+ if (gesture) {
2663
+ mode = "transform";
2664
+ return;
2665
+ }
2666
+ const state = store.getState();
2667
+ const target = getSelectionTarget(state, e.scene, 6 / state.viewport.zoom);
2668
+ start = e.scene;
2669
+ moved = false;
2670
+ if (!target) {
2671
+ baseSelection = e.shiftKey ? new Set(state.selectedIds) : /* @__PURE__ */ new Set();
2672
+ store.setState({
2673
+ selectedIds: baseSelection,
2674
+ editingGroupId: e.shiftKey ? state.editingGroupId : null,
2675
+ selectedPointIndex: null
2676
+ });
2677
+ mode = "box";
2678
+ return;
2679
+ }
2680
+ let selected = new Set(state.selectedIds);
2681
+ if (e.shiftKey) {
2682
+ const all = target.ids.every((id) => selected.has(id));
2683
+ for (const id of target.ids) if (all) selected.delete(id);
2684
+ else selected.add(id);
2685
+ } else if (!selected.has(target.hitId)) selected = new Set(target.ids);
2686
+ store.setState({
2687
+ selectedIds: selected,
2688
+ selectedPointIndex: null
2689
+ });
2690
+ if (!selected.has(target.hitId)) {
2691
+ mode = "idle";
2692
+ return;
2693
+ }
2694
+ const ids = withBoundText(state.elements, withFrameChildren(state.elements, selected));
2695
+ originals = new Map(state.elements.filter((el) => ids.has(el.id)).map((el) => [el.id, el]));
2696
+ const [minX, minY] = getCommonBounds([...originals.values()]);
2697
+ dragOrigin = [minX, minY];
2698
+ mode = "drag";
2699
+ store.beginTransient();
2700
+ },
2701
+ onPointerMove(ctx, e) {
2702
+ const { store } = ctx;
2703
+ if (mode === "transform") {
2704
+ gesture?.move(e);
2705
+ return;
2706
+ }
2707
+ if (mode === "point") {
2708
+ pointGesture?.move(e);
2709
+ return;
2710
+ }
2711
+ let dx = e.scene[0] - start[0];
2712
+ let dy = e.scene[1] - start[1];
2713
+ if (mode === "drag") {
2714
+ const zoom = store.getState().viewport.zoom;
2715
+ if (!moved && Math.hypot(dx, dy) * zoom < 2) return;
2716
+ moved = true;
2717
+ const grid = activeGrid(store, e);
2718
+ if (grid) {
2719
+ dx = snapValue(dragOrigin[0] + dx, grid) - dragOrigin[0];
2720
+ dy = snapValue(dragOrigin[1] + dy, grid) - dragOrigin[1];
2721
+ }
2722
+ const move = moveElements(originals, dx, dy);
2723
+ const ids = new Set(originals.keys());
2724
+ store.updateTransient(({ elements }) => ({ elements: refreshFrames(refreshBindings(move(elements), ids), ids) }));
2725
+ return;
2726
+ }
2727
+ if (mode === "box") {
2728
+ const box = normalizeBox(start, e.scene);
2729
+ const inside = selectInBox(store.getState(), box);
2730
+ store.setState({
2731
+ selectionBox: box,
2732
+ selectedIds: /* @__PURE__ */ new Set([...baseSelection, ...inside])
2733
+ });
2734
+ }
2735
+ },
2736
+ onPointerUp(ctx) {
2737
+ const { store } = ctx;
2738
+ if (mode === "transform") gesture?.end(true);
2739
+ if (mode === "point") pointGesture?.end();
2740
+ gesture = null;
2741
+ pointGesture = null;
2742
+ if (mode === "drag") store.endTransient(moved);
2743
+ if (mode === "box") store.setState({ selectionBox: null });
2744
+ mode = "idle";
2745
+ },
2746
+ cancel(ctx) {
2747
+ const { store } = ctx;
2748
+ if (mode === "transform") gesture?.end(false);
2749
+ if (mode === "point") pointGesture?.cancel();
2750
+ if (mode === "drag") store.endTransient(false);
2751
+ if (mode === "box") store.setState({ selectionBox: null });
2752
+ gesture = null;
2753
+ pointGesture = null;
2754
+ mode = "idle";
2755
+ },
2756
+ onDoubleClick(ctx, e) {
2757
+ const { store } = ctx;
2758
+ const state = store.getState();
2759
+ const target = getSelectionTarget(state, e.scene, 6 / state.viewport.zoom);
2760
+ if (!target) {
2761
+ store.setState({ editingGroupId: null });
2762
+ startTextEditing(store, { at: e.scene });
2763
+ return;
2764
+ }
2765
+ const el = state.elements.find((item) => item.id === target.hitId);
2766
+ if (!el) return;
2767
+ if (el.type === "frame" || el.type === "magicframe") {
2768
+ store.setState({
2769
+ editingFrameId: el.id,
2770
+ selectedIds: /* @__PURE__ */ new Set([el.id])
2771
+ });
2772
+ return;
2773
+ }
2774
+ const groups = el.groupIds ?? [];
2775
+ const depth = state.editingGroupId ? groups.indexOf(state.editingGroupId) : groups.length;
2776
+ if (groups.length > 0 && depth > 0) {
2777
+ const nextGroup = groups[depth - 1];
2778
+ const inner = depth - 1 > 0 ? groups[depth - 2] : null;
2779
+ const members = inner ? state.elements.filter((item) => item.groupIds?.includes(inner)).map((item) => item.id) : [el.id];
2780
+ store.setState({
2781
+ editingGroupId: nextGroup,
2782
+ selectedIds: new Set(members)
2783
+ });
2784
+ return;
2785
+ }
2786
+ if (el.type === "richtext") startRichTextEditing(store, el.id);
2787
+ else if (el.type === "text") startTextEditing(store, { elementId: el.id });
2788
+ else if (canHoldText(el)) startTextEditing(store, { containerId: el.id });
2789
+ }
2790
+ };
2791
+ }
2792
+ //#endregion
2793
+ //#region src/editor/tools/shape.ts
2794
+ function shapeBox(start, current, square, fromCenter) {
2795
+ let w = current[0] - start[0];
2796
+ let h = current[1] - start[1];
2797
+ if (square) {
2798
+ const size = Math.max(Math.abs(w), Math.abs(h));
2799
+ w = Math.sign(w || 1) * size;
2800
+ h = Math.sign(h || 1) * size;
2801
+ }
2802
+ if (fromCenter) return {
2803
+ x: start[0] - Math.abs(w),
2804
+ y: start[1] - Math.abs(h),
2805
+ width: Math.abs(w) * 2,
2806
+ height: Math.abs(h) * 2
2807
+ };
2808
+ return {
2809
+ x: Math.min(start[0], start[0] + w),
2810
+ y: Math.min(start[1], start[1] + h),
2811
+ width: Math.abs(w),
2812
+ height: Math.abs(h)
2813
+ };
2814
+ }
2815
+ function createShapeTool(type, options = {}) {
2816
+ let id = null;
2817
+ let start = [0, 0];
2818
+ return {
2819
+ onPointerDown(ctx, e) {
2820
+ const { store } = ctx;
2821
+ const style = store.getState().currentStyle;
2822
+ start = snapPoint(e.scene, activeGrid(store, e));
2823
+ const partial = {
2824
+ x: start[0],
2825
+ y: start[1],
2826
+ width: 0,
2827
+ height: 0
2828
+ };
2829
+ const el = type === "frame" ? newFrameElement(partial, style) : newElement(type, partial, style);
2830
+ id = el.id;
2831
+ store.beginTransient();
2832
+ appendElement(store, el);
2833
+ store.setState({ selectedIds: /* @__PURE__ */ new Set() });
2834
+ },
2835
+ onPointerMove(ctx, e) {
2836
+ if (!id) return;
2837
+ const current = findElement(ctx.store, id);
2838
+ if (!current) return;
2839
+ const at = snapPoint(e.scene, activeGrid(ctx.store, e));
2840
+ replaceElement(ctx.store, {
2841
+ ...current,
2842
+ ...shapeBox(start, at, e.shiftKey, e.altKey)
2843
+ });
2844
+ },
2845
+ onPointerUp(ctx) {
2846
+ if (!id) return;
2847
+ const { store } = ctx;
2848
+ const el = findElement(store, id);
2849
+ const zoom = store.getState().viewport.zoom;
2850
+ const createdId = id;
2851
+ id = null;
2852
+ if (!el || Math.max(el.width, el.height) * zoom < 2) {
2853
+ cancelCreation(store);
2854
+ return;
2855
+ }
2856
+ finishCreation(store, createdId);
2857
+ options.onCreated?.(ctx, el);
2858
+ },
2859
+ cancel(ctx) {
2860
+ if (!id) return;
2861
+ id = null;
2862
+ cancelCreation(ctx.store);
2863
+ }
2864
+ };
2865
+ }
2866
+ //#endregion
2867
+ //#region src/editor/tools/text.ts
2868
+ function createTextTool() {
2869
+ let downAt = null;
2870
+ return {
2871
+ onPointerDown(_ctx, e) {
2872
+ downAt = e.scene;
2873
+ },
2874
+ onPointerMove() {},
2875
+ onPointerUp(ctx) {
2876
+ const at = downAt;
2877
+ downAt = null;
2878
+ if (!at) return;
2879
+ const { store } = ctx;
2880
+ const state = store.getState();
2881
+ const hit = getHitElement(state.elements, at, 6 / state.viewport.zoom);
2882
+ if (!state.toolLocked) store.setState({ tool: "selection" });
2883
+ if (hit?.type === "text") startTextEditing(store, { elementId: hit.id });
2884
+ else if (hit && canHoldText(hit) && hit.type !== "arrow") startTextEditing(store, { containerId: hit.id });
2885
+ else startTextEditing(store, { at });
2886
+ },
2887
+ cancel() {
2888
+ downAt = null;
2889
+ }
2890
+ };
2891
+ }
2892
+ //#endregion
2893
+ //#region src/editor/tools/index.ts
2894
+ function createToolHandlers() {
2895
+ return {
2896
+ selection: createSelectionTool(),
2897
+ hand: createHandTool(),
2898
+ rectangle: createShapeTool("rectangle"),
2899
+ diamond: createShapeTool("diamond"),
2900
+ ellipse: createShapeTool("ellipse"),
2901
+ frame: createShapeTool("frame"),
2902
+ arrow: createLinearTool("arrow"),
2903
+ line: createLinearTool("line"),
2904
+ freedraw: createFreedrawTool(),
2905
+ eraser: createEraserTool(),
2906
+ text: createTextTool(),
2907
+ card: createCardTool(),
2908
+ image: createImageTool()
2909
+ };
2910
+ }
2911
+ function getToolHandler(handlers, tool) {
2912
+ return handlers[tool] ?? handlers.selection;
2913
+ }
2914
+ //#endregion
2915
+ //#region src/editor/WhiteboardCanvas.tsx
2916
+ var DOT_SPACING = 16;
2917
+ var CHROME_ATTR = "data-whiteboard-chrome";
2918
+ function isChromeTarget(target) {
2919
+ return target instanceof Element && !!target.closest(`[data-whiteboard-chrome]`);
2920
+ }
2921
+ var WHEEL_ZOOM_FACTOR = .01;
2922
+ var WhiteboardCanvas = ({ children, context, handlers, onContextMenu, store, theme }) => {
2923
+ const ref = useRef(null);
2924
+ const activeRef = useRef(null);
2925
+ const spaceRef = useRef(false);
2926
+ const lastPointerRef = useRef(null);
2927
+ const gesturesRef = useRef(createGestureTracker());
2928
+ const elements = useStore(store, (s) => s.elements);
2929
+ const files = useStore(store, (s) => s.files);
2930
+ const viewport = useStore(store, (s) => s.viewport);
2931
+ const editingTextId = useStore(store, (s) => s.editingTextId);
2932
+ const editingRichTextId = useStore(store, (s) => s.editingRichTextId);
2933
+ const erasingIds = useStore(store, (s) => s.erasingIds);
2934
+ const tool = useStore(store, (s) => s.tool);
2935
+ const gridSize = useStore(store, (s) => s.gridSize);
2936
+ const toolRef = useRef(tool);
2937
+ useEffect(() => {
2938
+ const previous = toolRef.current;
2939
+ toolRef.current = tool;
2940
+ if (previous === tool) return;
2941
+ const handler = getToolHandler(handlers, previous);
2942
+ handler.cancel?.(context);
2943
+ if (activeRef.current === handler) activeRef.current = null;
2944
+ }, [
2945
+ context,
2946
+ handlers,
2947
+ tool
2948
+ ]);
2949
+ const scene = useMemo(() => ({
2950
+ type: "excalidraw",
2951
+ appState: {},
2952
+ elements,
2953
+ files
2954
+ }), [elements, files]);
2955
+ const hiddenIds = useMemo(() => editingTextId ? /* @__PURE__ */ new Set([editingTextId]) : void 0, [editingTextId]);
2956
+ const elementProps = useCallback((el) => {
2957
+ if (el.id === editingRichTextId) return { className: editingCard };
2958
+ if (erasingIds.has(el.id)) return { opacity: .25 };
2959
+ if (el.type === "image" && el.status === "pending") return { opacity: .5 };
2960
+ }, [erasingIds, editingRichTextId]);
2961
+ const toPointer = useCallback((e) => {
2962
+ const rect = ref.current.getBoundingClientRect();
2963
+ const screen = [e.clientX - rect.left, e.clientY - rect.top];
2964
+ return {
2965
+ screen,
2966
+ scene: screenToScene(screen, store.getState().viewport),
2967
+ shiftKey: !!e.shiftKey,
2968
+ altKey: !!e.altKey,
2969
+ ctrlKey: !!(e.ctrlKey || e.metaKey),
2970
+ pressure: e.pressure ?? .5,
2971
+ pointerType: e.pointerType ?? "mouse",
2972
+ pointerId: e.pointerId ?? 1
2973
+ };
2974
+ }, [store]);
2975
+ const onPointerDown = (e) => {
2976
+ if (e.button === 2 || isChromeTarget(e.target)) return;
2977
+ ref.current?.focus({ preventScroll: true });
2978
+ e.currentTarget.setPointerCapture?.(e.pointerId);
2979
+ if (e.pointerType === "touch") {
2980
+ const start = gesturesRef.current.down(e.pointerId, toPointer(e).screen, store.getState().viewport);
2981
+ if (start === "pinch") {
2982
+ activeRef.current?.cancel?.(context);
2983
+ activeRef.current = null;
2984
+ }
2985
+ if (start !== "single") return;
2986
+ }
2987
+ const handler = e.button === 1 || spaceRef.current ? handlers.hand : getToolHandler(handlers, store.getState().tool);
2988
+ activeRef.current = handler;
2989
+ handler.onPointerDown(context, toPointer(e));
2990
+ };
2991
+ const onPointerMove = (e) => {
2992
+ if (e.pointerType === "touch") {
2993
+ const gestures = gesturesRef.current;
2994
+ const viewport = gestures.move(e.pointerId, toPointer(e).screen);
2995
+ if (viewport) store.setState({ viewport });
2996
+ if (gestures.isActive()) return;
2997
+ }
2998
+ const handler = activeRef.current ?? getToolHandler(handlers, store.getState().tool);
2999
+ const info = toPointer(e);
3000
+ lastPointerRef.current = info.scene;
3001
+ handler.onPointerMove(context, info);
3002
+ };
3003
+ const onPointerUp = (e) => {
3004
+ if (e.pointerType === "touch") {
3005
+ const gestures = gesturesRef.current;
3006
+ const wasActive = gestures.isActive();
3007
+ gestures.up(e.pointerId);
3008
+ if (wasActive) return;
3009
+ }
3010
+ const handler = activeRef.current;
3011
+ activeRef.current = null;
3012
+ handler?.onPointerUp(context, toPointer(e));
3013
+ };
3014
+ useEffect(() => {
3015
+ const node = ref.current;
3016
+ if (!node) return;
3017
+ const onWheel = (e) => {
3018
+ if (isChromeTarget(e.target)) return;
3019
+ e.preventDefault();
3020
+ const vp = store.getState().viewport;
3021
+ const rect = node.getBoundingClientRect();
3022
+ const screen = [e.clientX - rect.left, e.clientY - rect.top];
3023
+ if (e.ctrlKey || e.metaKey) {
3024
+ store.setState({ viewport: zoomAt(vp, screen, vp.zoom * Math.exp(-e.deltaY * WHEEL_ZOOM_FACTOR)) });
3025
+ return;
3026
+ }
3027
+ const dx = e.shiftKey && !e.deltaX ? e.deltaY : e.deltaX;
3028
+ const dy = e.shiftKey && !e.deltaX ? 0 : e.deltaY;
3029
+ store.setState({ viewport: {
3030
+ ...vp,
3031
+ scrollX: vp.scrollX - dx / vp.zoom,
3032
+ scrollY: vp.scrollY - dy / vp.zoom
3033
+ } });
3034
+ };
3035
+ const onKey = (e) => {
3036
+ if (e.key === " " && !(e.target instanceof HTMLTextAreaElement)) spaceRef.current = e.type === "keydown";
3037
+ };
3038
+ const measure = () => {
3039
+ const rect = node.getBoundingClientRect();
3040
+ store.setState({ canvasSize: {
3041
+ width: rect.width,
3042
+ height: rect.height
3043
+ } });
3044
+ };
3045
+ measure();
3046
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
3047
+ observer?.observe(node);
3048
+ const pasteTarget = () => {
3049
+ if (lastPointerRef.current) return lastPointerRef.current;
3050
+ const { viewport, canvasSize } = store.getState();
3051
+ return screenToScene([canvasSize.width / 2, canvasSize.height / 2], viewport);
3052
+ };
3053
+ const onCopy = (e) => {
3054
+ if (!e.clipboardData || store.getState().editingTextId || store.getState().editingRichTextId || store.getState().selectedIds.size === 0) return;
3055
+ e.preventDefault();
3056
+ e.clipboardData.setData("text/plain", e.type === "cut" ? cutSelection(store) : copySelection(store));
3057
+ };
3058
+ const onPaste = (e) => {
3059
+ const { editingRichTextId: editingCard, editingTextId: editingText } = store.getState();
3060
+ if (!e.clipboardData || editingText || editingCard) return;
3061
+ const files = [...e.clipboardData.files ?? []].filter((f) => f.type.startsWith("image/"));
3062
+ if (files.length > 0 && context.onFiles) {
3063
+ e.preventDefault();
3064
+ context.onFiles(files, pasteTarget());
3065
+ return;
3066
+ }
3067
+ if (pasteFromClipboard(store, e.clipboardData.getData("text/plain"), pasteTarget())) e.preventDefault();
3068
+ };
3069
+ node.addEventListener("copy", onCopy);
3070
+ node.addEventListener("cut", onCopy);
3071
+ node.addEventListener("paste", onPaste);
3072
+ node.addEventListener("wheel", onWheel, { passive: false });
3073
+ window.addEventListener("keydown", onKey);
3074
+ window.addEventListener("keyup", onKey);
3075
+ return () => {
3076
+ observer?.disconnect();
3077
+ node.removeEventListener("copy", onCopy);
3078
+ node.removeEventListener("cut", onCopy);
3079
+ node.removeEventListener("paste", onPaste);
3080
+ node.removeEventListener("wheel", onWheel);
3081
+ window.removeEventListener("keydown", onKey);
3082
+ window.removeEventListener("keyup", onKey);
3083
+ };
3084
+ }, [context, store]);
3085
+ const dot = (gridSize ?? DOT_SPACING) * viewport.zoom;
3086
+ const isDark = theme === "dark";
3087
+ return /* @__PURE__ */ jsxs("div", {
3088
+ "data-whiteboard-canvas": true,
3089
+ className: canvas,
3090
+ ref,
3091
+ tabIndex: 0,
3092
+ style: {
3093
+ backgroundSize: `${dot}px ${dot}px`,
3094
+ backgroundPosition: `${viewport.scrollX * viewport.zoom}px ${viewport.scrollY * viewport.zoom}px`
3095
+ },
3096
+ onPointerCancel: onPointerUp,
3097
+ onPointerDown,
3098
+ onPointerMove,
3099
+ onPointerUp,
3100
+ onContextMenu: (e) => {
3101
+ if (isChromeTarget(e.target)) return;
3102
+ if (onContextMenu?.(toPointer(e))) e.preventDefault();
3103
+ },
3104
+ onDoubleClick: (e) => {
3105
+ if (isChromeTarget(e.target)) return;
3106
+ getToolHandler(handlers, store.getState().tool).onDoubleClick?.(context, toPointer(e));
3107
+ },
3108
+ onDragOver: (e) => {
3109
+ if (e.dataTransfer.types.includes("Files")) e.preventDefault();
3110
+ },
3111
+ onDrop: (e) => {
3112
+ const dropped = [...e.dataTransfer.files ?? []].filter((f) => f.type.startsWith("image/"));
3113
+ if (dropped.length === 0 || !context.onFiles) return;
3114
+ e.preventDefault();
3115
+ context.onFiles(dropped, toPointer(e).scene);
3116
+ },
3117
+ children: [/* @__PURE__ */ jsx("svg", {
3118
+ className: layer,
3119
+ style: isDark ? { filter: DARK_SCENE_FILTER } : void 0,
3120
+ children: /* @__PURE__ */ jsx("g", {
3121
+ transform: `scale(${viewport.zoom}) translate(${viewport.scrollX} ${viewport.scrollY})`,
3122
+ children: /* @__PURE__ */ jsx(SceneContent, {
3123
+ dark: isDark,
3124
+ elementProps,
3125
+ files,
3126
+ hiddenIds,
3127
+ scene
3128
+ })
3129
+ })
3130
+ }), children]
3131
+ });
3132
+ };
3133
+ //#endregion
3134
+ //#region src/editor/ContextMenu.tsx
3135
+ var EDGE_GAP = 8;
3136
+ var ContextMenu = ({ at, items, onClose }) => {
3137
+ const ref = useRef(null);
3138
+ const [position, setPosition] = useState(at);
3139
+ useLayoutEffect(() => {
3140
+ const node = ref.current;
3141
+ const parent = node?.offsetParent;
3142
+ if (!node || !parent) return;
3143
+ const bounds = parent.getBoundingClientRect();
3144
+ const size = node.getBoundingClientRect();
3145
+ if (!bounds.width || !bounds.height) return;
3146
+ setPosition([Math.max(EDGE_GAP, Math.min(at[0], bounds.width - size.width - EDGE_GAP)), Math.max(EDGE_GAP, Math.min(at[1], bounds.height - size.height - EDGE_GAP))]);
3147
+ }, [at]);
3148
+ useEffect(() => {
3149
+ const node = ref.current;
3150
+ node?.querySelector("[role=\"menuitem\"]:not([disabled])")?.focus();
3151
+ const onPress = (e) => {
3152
+ if (e.target instanceof Node && node?.contains(e.target)) return;
3153
+ onClose();
3154
+ };
3155
+ const onKey = (e) => {
3156
+ if (e.key !== "Escape") return;
3157
+ e.stopPropagation();
3158
+ e.preventDefault();
3159
+ onClose();
3160
+ };
3161
+ document.addEventListener("pointerdown", onPress, true);
3162
+ document.addEventListener("wheel", onPress, true);
3163
+ document.addEventListener("keydown", onKey, true);
3164
+ window.addEventListener("blur", onClose);
3165
+ window.addEventListener("resize", onClose);
3166
+ return () => {
3167
+ document.removeEventListener("pointerdown", onPress, true);
3168
+ document.removeEventListener("wheel", onPress, true);
3169
+ document.removeEventListener("keydown", onKey, true);
3170
+ window.removeEventListener("blur", onClose);
3171
+ window.removeEventListener("resize", onClose);
3172
+ };
3173
+ }, [onClose]);
3174
+ const onKeyDown = (e) => {
3175
+ e.stopPropagation();
3176
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
3177
+ e.preventDefault();
3178
+ const entries = [...e.currentTarget.querySelectorAll("[role=\"menuitem\"]:not([disabled])")];
3179
+ if (entries.length === 0) return;
3180
+ entries[(entries.indexOf(document.activeElement) + (e.key === "ArrowDown" ? 1 : -1) + entries.length) % entries.length].focus();
3181
+ };
3182
+ return /* @__PURE__ */ jsx("div", {
3183
+ className: `${floating} ${contextMenu}`,
3184
+ ref,
3185
+ role: "menu",
3186
+ style: {
3187
+ left: position[0],
3188
+ top: position[1]
3189
+ },
3190
+ onContextMenu: (e) => e.preventDefault(),
3191
+ onKeyDown,
3192
+ [CHROME_ATTR]: "",
3193
+ children: items.map((item, i) => isSeparator(item) ? /* @__PURE__ */ jsx("div", {
3194
+ className: contextMenuSeparator,
3195
+ role: "separator"
3196
+ }, `separator-${i}`) : /* @__PURE__ */ jsx("button", {
3197
+ className: contextMenuItem,
3198
+ "data-danger": item.danger || void 0,
3199
+ disabled: item.disabled,
3200
+ role: "menuitem",
3201
+ type: "button",
3202
+ onClick: () => {
3203
+ onClose();
3204
+ item.onSelect();
3205
+ },
3206
+ children: item.label
3207
+ }, item.key))
3208
+ });
3209
+ };
3210
+ function useContextMenu(store, hostItems, onRequest) {
3211
+ const [state, setState] = useState(null);
3212
+ const hostItemsRef = useRef(hostItems);
3213
+ hostItemsRef.current = hostItems;
3214
+ const onRequestRef = useRef(onRequest);
3215
+ onRequestRef.current = onRequest;
3216
+ const open = useCallback((info) => {
3217
+ const { editingRichTextId, editingTextId } = store.getState();
3218
+ if (editingTextId || editingRichTextId) return false;
3219
+ const items = contextMenuItems(store, info.scene, hostItemsRef.current);
3220
+ if (onRequestRef.current) {
3221
+ onRequestRef.current({
3222
+ items,
3223
+ scenePoint: info.scene,
3224
+ screenPoint: info.screen
3225
+ });
3226
+ return true;
3227
+ }
3228
+ setState({
3229
+ at: info.screen,
3230
+ items
3231
+ });
3232
+ return true;
3233
+ }, [store]);
3234
+ const close = useCallback(() => setState(null), []);
3235
+ return {
3236
+ open,
3237
+ menu: state ? /* @__PURE__ */ jsx(ContextMenu, {
3238
+ at: state.at,
3239
+ items: state.items,
3240
+ onClose: close
3241
+ }) : null
3242
+ };
3243
+ }
3244
+ //#endregion
3245
+ //#region src/editor/text-editor.css.ts
3246
+ var textEditor = "gb4lm20";
3247
+ var frameNameEditor = "gb4lm21";
3248
+ //#endregion
3249
+ //#region src/editor/FrameNameEditor.tsx
3250
+ var Editor = ({ frame, store }) => {
3251
+ const [value, setValue] = useState(frame.name ?? "");
3252
+ const ref = useRef(null);
3253
+ const viewport = useStore(store, (s) => s.viewport);
3254
+ const [left, top] = sceneToScreen([frame.x, frame.y - 20], viewport);
3255
+ useEffect(() => {
3256
+ ref.current?.focus();
3257
+ ref.current?.select();
3258
+ }, []);
3259
+ const closedRef = useRef(false);
3260
+ const close = (save) => {
3261
+ if (closedRef.current) return;
3262
+ closedRef.current = true;
3263
+ store.setState({ editingFrameId: null });
3264
+ if (!save) return;
3265
+ const name = value.trim() || null;
3266
+ if (name === (frame.name ?? null)) return;
3267
+ store.commit(({ elements }) => ({ elements: elements.map((el) => el.id === frame.id ? bumpVersion(el, { name }) : el) }));
3268
+ };
3269
+ return /* @__PURE__ */ jsx("input", {
3270
+ "data-frame-name-editor": true,
3271
+ className: frameNameEditor,
3272
+ ref,
3273
+ value,
3274
+ [CHROME_ATTR]: "",
3275
+ style: {
3276
+ left,
3277
+ top,
3278
+ height: 20 * viewport.zoom
3279
+ },
3280
+ onBlur: () => close(true),
3281
+ onChange: (e) => setValue(e.currentTarget.value),
3282
+ onKeyDown: (e) => {
3283
+ e.stopPropagation();
3284
+ if (e.key === "Enter") close(true);
3285
+ if (e.key === "Escape") close(false);
3286
+ }
3287
+ });
3288
+ };
3289
+ var FrameNameEditor = ({ store }) => {
3290
+ const frame = useStore(store, (s) => s.editingFrameId ? s.elements.find((el) => el.id === s.editingFrameId) : void 0);
3291
+ if (!frame || frame.isDeleted) return null;
3292
+ return /* @__PURE__ */ jsx(Editor, {
3293
+ frame,
3294
+ store
3295
+ }, frame.id);
3296
+ };
3297
+ //#endregion
3298
+ //#region src/editor/MobileDock.tsx
3299
+ var MobileDock = ({ store, tools }) => /* @__PURE__ */ jsx("div", {
3300
+ "data-mobile-dock": true,
3301
+ "data-whiteboard-chrome": true,
3302
+ className: `${floating} ${dock}`,
3303
+ children: /* @__PURE__ */ jsx(WhiteboardToolbar, {
3304
+ showKeys: false,
3305
+ store,
3306
+ tools
3307
+ })
3308
+ });
3309
+ //#endregion
3310
+ //#region src/editor/overlay/LinearHandles.tsx
3311
+ var LinearHandles = ({ store }) => {
3312
+ const state = useStore(store, (s) => s);
3313
+ if (state.selectionBox || state.editingTextId || state.tool !== "selection") return null;
3314
+ const el = getEditedLinear(state);
3315
+ if (!el) return null;
3316
+ const points = getLinearAbsolutePoints(el).map((p, i, all) => ({
3317
+ i,
3318
+ p: sceneToScreen(p, state.viewport),
3319
+ end: i === 0 || i === all.length - 1
3320
+ })).filter(({ end }) => end || !el.elbowed);
3321
+ const mids = el.elbowed ? [] : getMidpoints(el).map((p) => sceneToScreen(p, state.viewport));
3322
+ const segments = el.elbowed ? getElbowSegmentHandles(el).map((h) => ({
3323
+ ...h,
3324
+ point: sceneToScreen(h.point, state.viewport)
3325
+ })) : [];
3326
+ return /* @__PURE__ */ jsxs("g", {
3327
+ "data-linear-handles": true,
3328
+ children: [
3329
+ mids.map(([x, y], i) => /* @__PURE__ */ jsx("circle", {
3330
+ cx: x,
3331
+ cy: y,
3332
+ "data-midpoint": i,
3333
+ fill: accentStroke,
3334
+ fillOpacity: .25,
3335
+ r: 3.5
3336
+ }, `m${i}`)),
3337
+ segments.map(({ index, point: [x, y] }) => /* @__PURE__ */ jsx("rect", {
3338
+ "data-segment": index,
3339
+ fill: "#fff",
3340
+ height: 6,
3341
+ rx: 3,
3342
+ stroke: accentStroke,
3343
+ strokeWidth: 1.5,
3344
+ width: 12,
3345
+ x: x - 6,
3346
+ y: y - 3
3347
+ }, `s${index}`)),
3348
+ points.map(({ i, p: [x, y] }) => /* @__PURE__ */ jsx("circle", {
3349
+ cx: x,
3350
+ cy: y,
3351
+ "data-point": i,
3352
+ fill: state.selectedPointIndex === i ? accentStroke : "#fff",
3353
+ r: 5,
3354
+ stroke: accentStroke,
3355
+ strokeWidth: 1.5
3356
+ }, `p${i}`))
3357
+ ]
3358
+ });
3359
+ };
3360
+ //#endregion
3361
+ //#region src/editor/overlay/TransformHandles.tsx
3362
+ var HANDLE_RADIUS = 4.5;
3363
+ var ROTATION_RADIUS = 5;
3364
+ var TransformHandles = ({ store }) => {
3365
+ const state = useStore(store, (s) => s);
3366
+ if (state.selectionBox || state.editingTextId) return null;
3367
+ const handles = getActiveHandles(state);
3368
+ if (!handles) return null;
3369
+ return /* @__PURE__ */ jsx("g", {
3370
+ "data-transform-handles": true,
3371
+ children: Object.entries(handles).map(([name, point]) => {
3372
+ const [x, y] = sceneToScreen(point, state.viewport);
3373
+ return /* @__PURE__ */ jsx("circle", {
3374
+ cx: x,
3375
+ cy: y,
3376
+ "data-handle": name,
3377
+ fill: "#fff",
3378
+ r: name === "rotation" ? ROTATION_RADIUS : HANDLE_RADIUS,
3379
+ stroke: accentStroke,
3380
+ strokeWidth: 1.5
3381
+ }, name);
3382
+ })
3383
+ });
3384
+ };
3385
+ //#endregion
3386
+ //#region src/editor/overlay/SelectionOverlay.tsx
3387
+ function outline(el) {
3388
+ if (isLinear(el)) {
3389
+ const [minX, minY, maxX, maxY] = getCommonBounds([el]);
3390
+ return [
3391
+ [minX, minY],
3392
+ [maxX, minY],
3393
+ [maxX, maxY],
3394
+ [minX, maxY]
3395
+ ];
3396
+ }
3397
+ return getElementAbsoluteCorners(el);
3398
+ }
3399
+ var toPoints = (points) => points.map(([x, y]) => `${x},${y}`).join(" ");
3400
+ var SelectionOverlay = ({ store }) => {
3401
+ const state = useStore(store, (s) => s);
3402
+ const { viewport, selectionBox } = state;
3403
+ const selected = getSelectedElements(state).filter((el) => !(el.type === "text" && el.containerId));
3404
+ const suggested = state.suggestedBindingId ? state.elements.find((el) => el.id === state.suggestedBindingId && !el.isDeleted) : void 0;
3405
+ const box = selectionBox ? [sceneToScreen([selectionBox[0], selectionBox[1]], viewport), sceneToScreen([selectionBox[2], selectionBox[3]], viewport)] : null;
3406
+ return /* @__PURE__ */ jsxs("svg", {
3407
+ "data-whiteboard-overlay": true,
3408
+ className: layer,
3409
+ children: [
3410
+ suggested && /* @__PURE__ */ jsx("polygon", {
3411
+ "data-binding-highlight": suggested.id,
3412
+ fill: "none",
3413
+ opacity: .6,
3414
+ points: toPoints(outline(suggested).map((p) => sceneToScreen(p, viewport))),
3415
+ stroke: "var(--rc-accent)",
3416
+ strokeWidth: 3
3417
+ }),
3418
+ selected.length > 1 && selected.map((el) => /* @__PURE__ */ jsx("polygon", {
3419
+ fill: "none",
3420
+ opacity: .5,
3421
+ points: toPoints(outline(el).map((p) => sceneToScreen(p, viewport))),
3422
+ stroke: "var(--rc-accent)",
3423
+ strokeWidth: 1
3424
+ }, el.id)),
3425
+ selected.length === 1 && /* @__PURE__ */ jsx("polygon", {
3426
+ "data-selection-frame": true,
3427
+ fill: "none",
3428
+ points: toPoints(outline(selected[0]).map((p) => sceneToScreen(p, viewport))),
3429
+ stroke: "var(--rc-accent)",
3430
+ strokeWidth: 1
3431
+ }),
3432
+ /* @__PURE__ */ jsx(TransformHandles, { store }),
3433
+ /* @__PURE__ */ jsx(LinearHandles, { store }),
3434
+ box && /* @__PURE__ */ jsx("rect", {
3435
+ "data-selection-box": true,
3436
+ fill: "var(--rc-accent)",
3437
+ fillOpacity: .08,
3438
+ height: box[1][1] - box[0][1],
3439
+ stroke: "var(--rc-accent)",
3440
+ strokeWidth: 1,
3441
+ width: box[1][0] - box[0][0],
3442
+ x: box[0][0],
3443
+ y: box[0][1]
3444
+ })
3445
+ ]
3446
+ });
3447
+ };
3448
+ //#endregion
3449
+ //#region src/model/richtext-editable.ts
3450
+ var ELEMENT = {
3451
+ direction: null,
3452
+ format: "",
3453
+ indent: 0,
3454
+ version: 1
3455
+ };
3456
+ var text = (value, from) => ({
3457
+ type: "text",
3458
+ text: value,
3459
+ format: typeof from?.format === "number" ? from.format : 0,
3460
+ style: typeof from?.style === "string" ? from.style : "",
3461
+ detail: 0,
3462
+ mode: "normal",
3463
+ version: 1
3464
+ });
3465
+ function inline(node) {
3466
+ switch (node.type) {
3467
+ case "text": return [text(node.text ?? "", node)];
3468
+ case "linebreak":
3469
+ case "tab": return [{
3470
+ type: node.type,
3471
+ version: 1
3472
+ }];
3473
+ case "link":
3474
+ case "autolink": return [{
3475
+ ...ELEMENT,
3476
+ type: "link",
3477
+ url: typeof node.url === "string" ? node.url : "",
3478
+ rel: "noopener noreferrer",
3479
+ target: "_blank",
3480
+ title: null,
3481
+ children: (node.children ?? []).flatMap(inline)
3482
+ }];
3483
+ default: {
3484
+ const value = richTextPlainText(node);
3485
+ return value ? [text(value)] : [];
3486
+ }
3487
+ }
3488
+ }
3489
+ var paragraph = (children) => ({
3490
+ ...ELEMENT,
3491
+ type: "paragraph",
3492
+ textFormat: 0,
3493
+ textStyle: "",
3494
+ children
3495
+ });
3496
+ function listItem(node, index) {
3497
+ const children = (node.children ?? []).flatMap((child) => child.type === "list" ? [list(child)] : inline(child));
3498
+ return {
3499
+ ...ELEMENT,
3500
+ type: "listitem",
3501
+ value: index + 1,
3502
+ checked: void 0,
3503
+ children
3504
+ };
3505
+ }
3506
+ function list(node) {
3507
+ const listType = node.listType === "number" || node.listType === "check" ? node.listType : "bullet";
3508
+ return {
3509
+ ...ELEMENT,
3510
+ type: "list",
3511
+ listType,
3512
+ start: 1,
3513
+ tag: listType === "number" ? "ol" : "ul",
3514
+ children: (node.children ?? []).map((item, i) => listItem(item.type === "listitem" ? item : {
3515
+ type: "listitem",
3516
+ children: [item]
3517
+ }, i))
3518
+ };
3519
+ }
3520
+ function block(node) {
3521
+ switch (node.type) {
3522
+ case "paragraph": return paragraph((node.children ?? []).flatMap(inline));
3523
+ case "heading": {
3524
+ const tag = /^h[1-6]$/.test(node.tag ?? "") ? node.tag : "h3";
3525
+ return {
3526
+ ...ELEMENT,
3527
+ type: "heading",
3528
+ tag,
3529
+ children: (node.children ?? []).flatMap(inline)
3530
+ };
3531
+ }
3532
+ case "quote": return {
3533
+ ...ELEMENT,
3534
+ type: "quote",
3535
+ children: (node.children ?? []).flatMap(inline)
3536
+ };
3537
+ case "list": return list(node);
3538
+ default: return paragraph(inline(node));
3539
+ }
3540
+ }
3541
+ function toEditableContent(content) {
3542
+ const blocks = (contentRoot(content).children ?? []).map(block);
3543
+ return { root: {
3544
+ ...ELEMENT,
3545
+ type: "root",
3546
+ children: blocks.length > 0 ? blocks : [paragraph([])]
3547
+ } };
3548
+ }
3549
+ //#endregion
3550
+ //#region src/editor/RichTextFormatBar.tsx
3551
+ var CARD_TEXT_COLORS = [
3552
+ "#1e1e1e",
3553
+ "#868e96",
3554
+ "#e03131",
3555
+ "#2f9e44",
3556
+ "#1971c2",
3557
+ "#f08c00"
3558
+ ];
3559
+ var FORMATS = [
3560
+ {
3561
+ format: "bold",
3562
+ icon: Bold,
3563
+ label: "Bold"
3564
+ },
3565
+ {
3566
+ format: "italic",
3567
+ icon: Italic,
3568
+ label: "Italic"
3569
+ },
3570
+ {
3571
+ format: "strikethrough",
3572
+ icon: Strikethrough,
3573
+ label: "Strikethrough"
3574
+ },
3575
+ {
3576
+ format: "code",
3577
+ icon: Code,
3578
+ label: "Inline code"
3579
+ },
3580
+ {
3581
+ format: "highlight",
3582
+ icon: Highlighter,
3583
+ label: "Highlight"
3584
+ }
3585
+ ];
3586
+ var DISCRETE = { discrete: true };
3587
+ var keepFocus = (e) => e.preventDefault();
3588
+ function selectionBlock() {
3589
+ const selection = $getSelection();
3590
+ if (!$isRangeSelection(selection)) return null;
3591
+ return selection.anchor.getNode().getTopLevelElement();
3592
+ }
3593
+ function toggleHeading(editor) {
3594
+ editor.update(() => {
3595
+ const selection = $getSelection();
3596
+ if (!$isRangeSelection(selection)) return;
3597
+ const heading = $isHeadingNode(selectionBlock());
3598
+ $setBlocksType(selection, () => heading ? $createParagraphNode() : $createHeadingNode("h3"));
3599
+ }, DISCRETE);
3600
+ }
3601
+ function toggleList(editor, ordered) {
3602
+ if (editor.getEditorState().read(() => $isListNode(selectionBlock()))) editor.dispatchCommand(REMOVE_LIST_COMMAND, void 0);
3603
+ else editor.dispatchCommand(ordered ? INSERT_ORDERED_LIST_COMMAND : INSERT_UNORDERED_LIST_COMMAND, void 0);
3604
+ }
3605
+ function selectionHasLink(editor) {
3606
+ return editor.getEditorState().read(() => {
3607
+ const selection = $getSelection();
3608
+ if (!$isRangeSelection(selection)) return false;
3609
+ return selection.getNodes().some((node) => $isLinkNode(node) || $isLinkNode(node.getParent()));
3610
+ });
3611
+ }
3612
+ function normalizeUrl(raw) {
3613
+ const value = raw.trim();
3614
+ if (!value) return null;
3615
+ if (/^(?:https?:|mailto:)/i.test(value)) return value;
3616
+ if (/^[a-z][\w+.-]*:/i.test(value)) return null;
3617
+ return `https://${value}`;
3618
+ }
3619
+ var RichTextFormatBar = ({ at, host }) => {
3620
+ const [editor] = useLexicalComposerContext();
3621
+ const [visible, setVisible] = useState(false);
3622
+ const [linking, setLinking] = useState(false);
3623
+ useEffect(() => editor.registerUpdateListener(({ editorState }) => {
3624
+ editorState.read(() => {
3625
+ const selection = $getSelection();
3626
+ setVisible($isRangeSelection(selection) && !selection.isCollapsed());
3627
+ });
3628
+ }), [editor]);
3629
+ if (!host || !visible && !linking) return null;
3630
+ const button = (label, Icon, run) => /* @__PURE__ */ jsx(ActionButton, {
3631
+ icon: true,
3632
+ "aria-label": label,
3633
+ size: "sm",
3634
+ title: label,
3635
+ variant: "ghost",
3636
+ onClick: run,
3637
+ onMouseDown: keepFocus,
3638
+ children: /* @__PURE__ */ jsx(Icon, { size: 15 })
3639
+ }, label);
3640
+ return createPortal(/* @__PURE__ */ jsx("div", {
3641
+ "data-richtext-format-bar": true,
3642
+ className: `${floating} ${formatBar}`,
3643
+ style: {
3644
+ left: at[0],
3645
+ top: at[1]
3646
+ },
3647
+ onPointerDown: (e) => e.stopPropagation(),
3648
+ children: linking ? /* @__PURE__ */ jsx("input", {
3649
+ autoFocus: true,
3650
+ "aria-label": "Link URL",
3651
+ className: formatBarInput,
3652
+ placeholder: "https://",
3653
+ onBlur: () => setLinking(false),
3654
+ onKeyDown: (e) => {
3655
+ e.stopPropagation();
3656
+ if (e.key === "Escape") setLinking(false);
3657
+ if (e.key !== "Enter") return;
3658
+ const url = normalizeUrl(e.currentTarget.value);
3659
+ setLinking(false);
3660
+ if (url) editor.dispatchCommand(TOGGLE_LINK_COMMAND, url);
3661
+ editor.focus();
3662
+ }
3663
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
3664
+ FORMATS.map(({ format, icon, label }) => button(label, icon, () => editor.dispatchCommand(FORMAT_TEXT_COMMAND, format))),
3665
+ CARD_TEXT_COLORS.map((color) => /* @__PURE__ */ jsx("button", {
3666
+ "aria-label": `Text colour ${color}`,
3667
+ className: formatSwatch,
3668
+ "data-richtext-color": color,
3669
+ style: { background: color },
3670
+ type: "button",
3671
+ onMouseDown: keepFocus,
3672
+ onClick: () => editor.update(() => {
3673
+ const selection = $getSelection();
3674
+ if ($isRangeSelection(selection)) $patchStyleText(selection, { color });
3675
+ }, DISCRETE)
3676
+ }, color)),
3677
+ button("Heading", Heading, () => toggleHeading(editor)),
3678
+ button("Bulleted list", List, () => toggleList(editor, false)),
3679
+ button("Numbered list", ListOrdered, () => toggleList(editor, true)),
3680
+ button("Link", Link, () => {
3681
+ if (selectionHasLink(editor)) editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
3682
+ else setLinking(true);
3683
+ })
3684
+ ] })
3685
+ }), host);
3686
+ };
3687
+ //#endregion
3688
+ //#region src/editor/RichTextEditor.tsx
3689
+ var THEME = {
3690
+ paragraph: paragraph$1,
3691
+ heading: {
3692
+ h1,
3693
+ h2,
3694
+ h3,
3695
+ h4: hOther,
3696
+ h5: hOther,
3697
+ h6: hOther
3698
+ },
3699
+ quote,
3700
+ list: {
3701
+ ul: list$1,
3702
+ ol: list$1,
3703
+ listitem: listItem$1,
3704
+ nested: { listitem: nestedListItem }
3705
+ },
3706
+ link,
3707
+ text: {
3708
+ underline,
3709
+ strikethrough,
3710
+ underlineStrikethrough
3711
+ }
3712
+ };
3713
+ var BAR_WIDTH = 440;
3714
+ var BAR_MARGIN = 8;
3715
+ var clamp = (value, min, max) => Math.min(Math.max(value, min), max);
3716
+ function formatBarPosition(left, top, canvas) {
3717
+ const maxLeft = Math.max(BAR_MARGIN, canvas.width - BAR_WIDTH - BAR_MARGIN);
3718
+ const minTop = 44;
3719
+ const maxTop = Math.max(minTop, canvas.height - BAR_MARGIN);
3720
+ return [clamp(left, BAR_MARGIN, maxLeft), clamp(top - BAR_MARGIN, minTop, maxTop)];
3721
+ }
3722
+ var NODES = [
3723
+ HeadingNode,
3724
+ QuoteNode,
3725
+ ListNode,
3726
+ ListItemNode,
3727
+ LinkNode
3728
+ ];
3729
+ var EditorBridge = ({ onReady }) => {
3730
+ const [editor] = useLexicalComposerContext();
3731
+ useEffect(() => {
3732
+ onReady(editor);
3733
+ editor.focus();
3734
+ }, [editor, onReady]);
3735
+ return null;
3736
+ };
3737
+ var Surface = ({ dark, el, store }) => {
3738
+ const viewport = useStore(store, (s) => s.viewport);
3739
+ const canvas = useStore(store, (s) => s.canvasSize);
3740
+ const editorRef = useRef(null);
3741
+ const [host, setHost] = useState(null);
3742
+ const initialRef = useRef(null);
3743
+ const id = el.id;
3744
+ const initialConfig = useMemo(() => ({
3745
+ namespace: "whiteboard-card",
3746
+ nodes: NODES,
3747
+ theme: THEME,
3748
+ editorState: JSON.stringify(toEditableContent(el.content)),
3749
+ onError: (error) => {
3750
+ throw error;
3751
+ }
3752
+ }), [id]);
3753
+ useEffect(() => () => {
3754
+ const editor = editorRef.current;
3755
+ if (!editor) return;
3756
+ const json = JSON.stringify(editor.getEditorState().toJSON());
3757
+ if (json === initialRef.current) return;
3758
+ commitRichTextContent(store, id, JSON.parse(json));
3759
+ }, [id, store]);
3760
+ const onReady = useCallback((editor) => {
3761
+ editorRef.current = editor;
3762
+ initialRef.current ?? (initialRef.current = JSON.stringify(editor.getEditorState().toJSON()));
3763
+ }, []);
3764
+ const [left, top] = sceneToScreen([el.x, el.y], viewport);
3765
+ const angle = angleOf$1(el);
3766
+ const rotate = angle ? ` translate(${el.width / 2}px, ${el.height / 2}px) rotate(${angle}rad) translate(${-el.width / 2}px, ${-el.height / 2}px)` : "";
3767
+ return /* @__PURE__ */ jsx("div", {
3768
+ className: surface,
3769
+ "data-whiteboard-richtext-editor": id,
3770
+ ref: (node) => setHost(node?.parentElement ?? null),
3771
+ style: {
3772
+ ...RICHTEXT_BASE_STYLE,
3773
+ left,
3774
+ top,
3775
+ width: el.width,
3776
+ minHeight: el.height,
3777
+ padding: 12,
3778
+ opacity: el.opacity / 100,
3779
+ transform: `scale(${viewport.zoom})${rotate}`,
3780
+ filter: dark ? DARK_SCENE_FILTER : void 0
3781
+ },
3782
+ onPointerDown: (e) => e.stopPropagation(),
3783
+ onBlur: (e) => {
3784
+ const next = e.relatedTarget;
3785
+ if (e.currentTarget.contains(next) || next?.closest("[data-richtext-format-bar]")) return;
3786
+ stopRichTextEditing(store);
3787
+ },
3788
+ onKeyDown: (e) => {
3789
+ e.stopPropagation();
3790
+ if (e.key === "Escape") {
3791
+ e.preventDefault();
3792
+ stopRichTextEditing(store);
3793
+ }
3794
+ },
3795
+ children: /* @__PURE__ */ jsxs(LexicalComposer, {
3796
+ initialConfig,
3797
+ children: [
3798
+ /* @__PURE__ */ jsx(RichTextPlugin, {
3799
+ ErrorBoundary: LexicalErrorBoundary,
3800
+ contentEditable: /* @__PURE__ */ jsx(ContentEditable, { className: editable })
3801
+ }),
3802
+ /* @__PURE__ */ jsx(HistoryPlugin, {}),
3803
+ /* @__PURE__ */ jsx(ListPlugin, {}),
3804
+ /* @__PURE__ */ jsx(LinkPlugin, {}),
3805
+ /* @__PURE__ */ jsx(EditorBridge, { onReady }),
3806
+ /* @__PURE__ */ jsx(RichTextFormatBar, {
3807
+ at: formatBarPosition(left, top, canvas),
3808
+ host
3809
+ })
3810
+ ]
3811
+ })
3812
+ });
3813
+ };
3814
+ var RichTextEditor = ({ dark = false, store }) => {
3815
+ const el = useStore(store, (s) => s.editingRichTextId ? s.elements.find((e) => e.id === s.editingRichTextId && e.type === "richtext") : void 0);
3816
+ if (!el) return null;
3817
+ return /* @__PURE__ */ jsx(Surface, {
3818
+ dark,
3819
+ el,
3820
+ store
3821
+ }, el.id);
3822
+ };
3823
+ //#endregion
3824
+ //#region src/editor/shortcuts.ts
3825
+ var ARROWS = {
3826
+ ArrowLeft: [-1, 0],
3827
+ ArrowRight: [1, 0],
3828
+ ArrowUp: [0, -1],
3829
+ ArrowDown: [0, 1]
3830
+ };
3831
+ var TOOL_KEYS = {
3832
+ v: "selection",
3833
+ h: "hand",
3834
+ r: "rectangle",
3835
+ d: "diamond",
3836
+ o: "ellipse",
3837
+ a: "arrow",
3838
+ l: "line",
3839
+ p: "freedraw",
3840
+ t: "text",
3841
+ i: "image",
3842
+ f: "frame",
3843
+ e: "eraser",
3844
+ n: "card"
3845
+ };
3846
+ var ZOOM_STEP = 1.2;
3847
+ function zoomBy(store, factor) {
3848
+ const { viewport, canvasSize } = store.getState();
3849
+ const center = [canvasSize.width / 2, canvasSize.height / 2];
3850
+ store.setState({ viewport: zoomAt(viewport, center, viewport.zoom * factor) });
3851
+ }
3852
+ function resetZoom(store) {
3853
+ const { viewport, canvasSize } = store.getState();
3854
+ store.setState({ viewport: zoomAt(viewport, [canvasSize.width / 2, canvasSize.height / 2], 1) });
3855
+ }
3856
+ function zoomToFit(store) {
3857
+ const { elements, canvasSize } = store.getState();
3858
+ const alive = elements.filter((el) => !el.isDeleted);
3859
+ if (alive.length === 0 || canvasSize.width === 0) return;
3860
+ store.setState({ viewport: fitToContent(getCommonBounds(alive), canvasSize) });
3861
+ }
3862
+ function handleModified(store, e) {
3863
+ const k = e.key.toLowerCase();
3864
+ if (k === "z") {
3865
+ if (e.shiftKey) store.redo();
3866
+ else store.undo();
3867
+ return true;
3868
+ }
3869
+ if (k === "y") {
3870
+ store.redo();
3871
+ return true;
3872
+ }
3873
+ if (k === "g") {
3874
+ if (e.shiftKey) ungroupSelection(store);
3875
+ else groupSelection(store);
3876
+ return true;
3877
+ }
3878
+ if (k === "d") {
3879
+ duplicateSelection(store);
3880
+ return true;
3881
+ }
3882
+ if (k === "a") {
3883
+ selectAll(store);
3884
+ return true;
3885
+ }
3886
+ if (e.key === "]" || e.key === "}") {
3887
+ if (e.shiftKey) bringToFront(store);
3888
+ else bringForward(store);
3889
+ return true;
3890
+ }
3891
+ if (e.key === "[" || e.key === "{") {
3892
+ if (e.shiftKey) sendToBack(store);
3893
+ else sendBackward(store);
3894
+ return true;
3895
+ }
3896
+ if (e.key === "=" || e.key === "+") {
3897
+ zoomBy(store, ZOOM_STEP);
3898
+ return true;
3899
+ }
3900
+ if (e.key === "-") {
3901
+ zoomBy(store, 1 / ZOOM_STEP);
3902
+ return true;
3903
+ }
3904
+ if (e.key === "0") {
3905
+ resetZoom(store);
3906
+ return true;
3907
+ }
3908
+ if (e.key === "'") {
3909
+ store.setState({ gridSize: store.getState().gridSize ? null : 20 });
3910
+ return true;
3911
+ }
3912
+ return false;
3913
+ }
3914
+ function handleShortcut(store, e, allowedTools) {
3915
+ const state = store.getState();
3916
+ if (state.editingTextId || state.editingRichTextId) return false;
3917
+ if (e.ctrlKey || e.metaKey) return handleModified(store, e);
3918
+ const arrow = ARROWS[e.key];
3919
+ if (arrow && state.selectedIds.size > 0) {
3920
+ const step = e.shiftKey ? 10 : 1;
3921
+ const ids = withBoundText(state.elements, withFrameChildren(state.elements, state.selectedIds));
3922
+ store.commit(({ elements }) => ({ elements: refreshFrames(refreshBindings(nudge(elements, ids, arrow[0] * step, arrow[1] * step), ids), ids) }));
3923
+ return true;
3924
+ }
3925
+ if (e.key === "Delete" || e.key === "Backspace") {
3926
+ const linear = getEditedLinear(state);
3927
+ if (linear && state.selectedPointIndex !== null && linear.points.length > 2) {
3928
+ const index = state.selectedPointIndex;
3929
+ store.commit(({ elements }) => ({ elements: elements.map((el) => el.id === linear.id ? removePoint(linear, index) : el) }));
3930
+ store.setState({ selectedPointIndex: null });
3931
+ return true;
3932
+ }
3933
+ deleteSelection(store);
3934
+ return true;
3935
+ }
3936
+ if (e.key === "Escape") {
3937
+ store.setState({
3938
+ selectedIds: /* @__PURE__ */ new Set(),
3939
+ editingGroupId: null,
3940
+ editingLinearId: null,
3941
+ selectedPointIndex: null,
3942
+ tool: state.toolLocked ? state.tool : "selection"
3943
+ });
3944
+ return true;
3945
+ }
3946
+ if (e.key === "Enter" && state.selectedIds.size === 1) {
3947
+ const [id] = state.selectedIds;
3948
+ if (state.elements.find((item) => item.id === id)?.type === "richtext") {
3949
+ startRichTextEditing(store, id);
3950
+ return true;
3951
+ }
3952
+ }
3953
+ if (e.key === "!" || e.shiftKey && e.key === "1") {
3954
+ zoomToFit(store);
3955
+ return true;
3956
+ }
3957
+ if (e.key.toLowerCase() === "q") {
3958
+ store.setState({ toolLocked: !state.toolLocked });
3959
+ return true;
3960
+ }
3961
+ const tool = !e.altKey && !e.shiftKey ? TOOL_KEYS[e.key.toLowerCase()] : void 0;
3962
+ if (tool && allowedTools && !allowedTools.has(tool)) return false;
3963
+ if (tool) {
3964
+ store.setState({
3965
+ tool,
3966
+ selectedIds: tool === "selection" ? state.selectedIds : /* @__PURE__ */ new Set()
3967
+ });
3968
+ return true;
3969
+ }
3970
+ return false;
3971
+ }
3972
+ //#endregion
3973
+ //#region src/editor/style-options.ts
3974
+ var STROKE_COLORS = [
3975
+ "#1e1e1e",
3976
+ "#e03131",
3977
+ "#2f9e44",
3978
+ "#1971c2",
3979
+ "#f08c00"
3980
+ ];
3981
+ var BACKGROUND_COLORS = [
3982
+ "transparent",
3983
+ "#ffc9c9",
3984
+ "#b2f2bb",
3985
+ "#a5d8ff",
3986
+ "#ffec99"
3987
+ ];
3988
+ var FILL_STYLES = [
3989
+ {
3990
+ value: "hachure",
3991
+ label: "Hachure",
3992
+ icon: Slash
3993
+ },
3994
+ {
3995
+ value: "cross-hatch",
3996
+ label: "Cross-hatch",
3997
+ icon: Hash
3998
+ },
3999
+ {
4000
+ value: "solid",
4001
+ label: "Solid",
4002
+ icon: Square
4003
+ }
4004
+ ];
4005
+ var STROKE_WIDTHS = [
4006
+ {
4007
+ value: 1,
4008
+ label: "Thin",
4009
+ icon: Minus
4010
+ },
4011
+ {
4012
+ value: 2,
4013
+ label: "Bold",
4014
+ icon: Equal
4015
+ },
4016
+ {
4017
+ value: 4,
4018
+ label: "Extra bold",
4019
+ icon: Menu
4020
+ }
4021
+ ];
4022
+ var STROKE_STYLES = [
4023
+ {
4024
+ value: "solid",
4025
+ label: "Solid",
4026
+ icon: Minus
4027
+ },
4028
+ {
4029
+ value: "dashed",
4030
+ label: "Dashed",
4031
+ icon: GripHorizontal
4032
+ },
4033
+ {
4034
+ value: "dotted",
4035
+ label: "Dotted",
4036
+ icon: Ellipsis
4037
+ }
4038
+ ];
4039
+ var ROUGHNESS = [
4040
+ {
4041
+ value: 0,
4042
+ label: "Architect",
4043
+ icon: Ruler
4044
+ },
4045
+ {
4046
+ value: 1,
4047
+ label: "Artist",
4048
+ icon: Spline
4049
+ },
4050
+ {
4051
+ value: 2,
4052
+ label: "Cartoonist",
4053
+ icon: Activity
4054
+ }
4055
+ ];
4056
+ var ROUNDNESS = [{
4057
+ value: "sharp",
4058
+ label: "Sharp",
4059
+ icon: Square
4060
+ }, {
4061
+ value: "round",
4062
+ label: "Round",
4063
+ icon: Squircle
4064
+ }];
4065
+ var SHADOWS = [{
4066
+ value: false,
4067
+ label: "None"
4068
+ }, {
4069
+ value: true,
4070
+ label: "Soft"
4071
+ }];
4072
+ var FONT_SIZES = [
4073
+ {
4074
+ value: 16,
4075
+ label: "S"
4076
+ },
4077
+ {
4078
+ value: 20,
4079
+ label: "M"
4080
+ },
4081
+ {
4082
+ value: 28,
4083
+ label: "L"
4084
+ },
4085
+ {
4086
+ value: 36,
4087
+ label: "XL"
4088
+ }
4089
+ ];
4090
+ var FONT_FAMILIES = [
4091
+ {
4092
+ value: 5,
4093
+ label: "Hand"
4094
+ },
4095
+ {
4096
+ value: 2,
4097
+ label: "Sans"
4098
+ },
4099
+ {
4100
+ value: 3,
4101
+ label: "Mono"
4102
+ }
4103
+ ];
4104
+ var TEXT_ALIGNS = [
4105
+ {
4106
+ value: "left",
4107
+ label: "Left",
4108
+ icon: AlignLeft
4109
+ },
4110
+ {
4111
+ value: "center",
4112
+ label: "Center",
4113
+ icon: AlignCenter
4114
+ },
4115
+ {
4116
+ value: "right",
4117
+ label: "Right",
4118
+ icon: AlignRight
4119
+ }
4120
+ ];
4121
+ var ARROWHEADS = [
4122
+ {
4123
+ value: null,
4124
+ label: "None",
4125
+ icon: Minus
4126
+ },
4127
+ {
4128
+ value: "arrow",
4129
+ label: "Arrow",
4130
+ icon: MoveRight
4131
+ },
4132
+ {
4133
+ value: "triangle",
4134
+ label: "Triangle",
4135
+ icon: Slash
4136
+ },
4137
+ {
4138
+ value: "dot",
4139
+ label: "Dot",
4140
+ icon: Dot
4141
+ },
4142
+ {
4143
+ value: "bar",
4144
+ label: "Bar",
4145
+ icon: Menu
4146
+ }
4147
+ ];
4148
+ var ARROW_TYPES = [
4149
+ {
4150
+ value: "sharp",
4151
+ label: "Sharp",
4152
+ icon: Slash
4153
+ },
4154
+ {
4155
+ value: "round",
4156
+ label: "Curved",
4157
+ icon: Spline
4158
+ },
4159
+ {
4160
+ value: "elbow",
4161
+ label: "Elbow",
4162
+ icon: Waypoints
4163
+ }
4164
+ ];
4165
+ //#endregion
4166
+ //#region src/editor/style-props.ts
4167
+ var SHAPE = [
4168
+ "stroke",
4169
+ "background",
4170
+ "fillStyle",
4171
+ "strokeWidth",
4172
+ "strokeStyle",
4173
+ "roughness"
4174
+ ];
4175
+ var TEXT = [
4176
+ "stroke",
4177
+ "fontSize",
4178
+ "fontFamily",
4179
+ "textAlign"
4180
+ ];
4181
+ var ALWAYS = [
4182
+ "opacity",
4183
+ "layers",
4184
+ "actions"
4185
+ ];
4186
+ function propsFor(el) {
4187
+ const hasText = el.boundElements?.some((b) => b.type === "text") ? TEXT : [];
4188
+ switch (el.type) {
4189
+ case "rectangle":
4190
+ case "diamond": return [
4191
+ ...SHAPE,
4192
+ "roundness",
4193
+ "shadow",
4194
+ ...hasText
4195
+ ];
4196
+ case "ellipse": return [
4197
+ ...SHAPE,
4198
+ "shadow",
4199
+ ...hasText
4200
+ ];
4201
+ case "arrow": return [
4202
+ "stroke",
4203
+ "strokeWidth",
4204
+ "strokeStyle",
4205
+ "roughness",
4206
+ "arrowheads",
4207
+ "arrowType",
4208
+ ...hasText
4209
+ ];
4210
+ case "line": return [
4211
+ "stroke",
4212
+ "background",
4213
+ "fillStyle",
4214
+ "strokeWidth",
4215
+ "strokeStyle",
4216
+ "roughness",
4217
+ "roundness"
4218
+ ];
4219
+ case "freedraw": return ["stroke", "strokeWidth"];
4220
+ case "text": return TEXT;
4221
+ case "richtext": return [
4222
+ "stroke",
4223
+ "background",
4224
+ "strokeWidth",
4225
+ "roundness",
4226
+ "shadow"
4227
+ ];
4228
+ case "image":
4229
+ case "svg": return ["shadow"];
4230
+ default: return [];
4231
+ }
4232
+ }
4233
+ function getApplicableProps(elements) {
4234
+ if (elements.length === 0) return /* @__PURE__ */ new Set();
4235
+ let common = new Set(propsFor(elements[0]));
4236
+ for (const el of elements.slice(1)) {
4237
+ const next = new Set(propsFor(el));
4238
+ common = new Set([...common].filter((p) => next.has(p)));
4239
+ }
4240
+ for (const p of ALWAYS) common.add(p);
4241
+ return common;
4242
+ }
4243
+ function readValue(el, key) {
4244
+ if (key === "roundness") return el.roundness ? "round" : "sharp";
4245
+ if (key === "shadow") return el.shadow === true;
4246
+ if (key === "arrowType") {
4247
+ const arrow = el;
4248
+ return arrow.elbowed ? "elbow" : arrow.roundness ? "round" : "sharp";
4249
+ }
4250
+ return el[key];
4251
+ }
4252
+ function getCommonValue(elements, key) {
4253
+ if (elements.length === 0) return void 0;
4254
+ const first = readValue(elements[0], key);
4255
+ return elements.every((el) => readValue(el, key) === first) ? first : "mixed";
4256
+ }
4257
+ var isText = (el) => el.type === "text";
4258
+ var isArrow = (el) => el.type === "arrow";
4259
+ function patchElement(el, patch) {
4260
+ const out = {};
4261
+ const props = /* @__PURE__ */ new Set([...propsFor(el), ...isText(el) ? TEXT : []]);
4262
+ if (patch.strokeColor !== void 0 && props.has("stroke")) out.strokeColor = patch.strokeColor;
4263
+ if (patch.backgroundColor !== void 0 && props.has("background")) out.backgroundColor = patch.backgroundColor;
4264
+ if (patch.fillStyle !== void 0 && props.has("fillStyle")) out.fillStyle = patch.fillStyle;
4265
+ if (patch.strokeWidth !== void 0 && props.has("strokeWidth")) out.strokeWidth = patch.strokeWidth;
4266
+ if (patch.strokeStyle !== void 0 && props.has("strokeStyle")) out.strokeStyle = patch.strokeStyle;
4267
+ if (patch.roughness !== void 0 && props.has("roughness")) out.roughness = patch.roughness;
4268
+ if (patch.opacity !== void 0) out.opacity = patch.opacity;
4269
+ if (patch.shadow !== void 0 && props.has("shadow")) out.shadow = patch.shadow;
4270
+ if (patch.roundness !== void 0 && props.has("roundness")) {
4271
+ const round = el.type === "line" ? { type: 2 } : { type: 3 };
4272
+ out.roundness = patch.roundness === "round" ? round : null;
4273
+ }
4274
+ if (isText(el)) {
4275
+ if (patch.fontSize !== void 0) out.fontSize = patch.fontSize;
4276
+ if (patch.fontFamily !== void 0) out.fontFamily = patch.fontFamily;
4277
+ if (patch.textAlign !== void 0 && !el.containerId) out.textAlign = patch.textAlign;
4278
+ }
4279
+ if (isArrow(el)) {
4280
+ if (patch.startArrowhead !== void 0) out.startArrowhead = patch.startArrowhead;
4281
+ if (patch.endArrowhead !== void 0) out.endArrowhead = patch.endArrowhead;
4282
+ if (patch.arrowType !== void 0) {
4283
+ out.elbowed = patch.arrowType === "elbow";
4284
+ out.roundness = patch.arrowType === "round" ? { type: 2 } : null;
4285
+ if (!out.elbowed && el.fixedSegments) out.fixedSegments = null;
4286
+ }
4287
+ }
4288
+ if (Object.keys(out).length === 0) return el;
4289
+ const next = bumpVersion(el, out);
4290
+ return isText(next) && !next.containerId ? refreshTextDimensions(next) : next;
4291
+ }
4292
+ function applyStyle(store, patch) {
4293
+ const state = store.getState();
4294
+ store.setState({ currentStyle: {
4295
+ ...state.currentStyle,
4296
+ ...patch
4297
+ } });
4298
+ if (state.selectedIds.size === 0) return;
4299
+ const ids = withBoundText(state.elements, state.selectedIds);
4300
+ store.commit(({ elements }) => {
4301
+ const patched = elements.map((el) => ids.has(el.id) ? patchElement(el, patch) : el);
4302
+ return { elements: relayoutBoundTexts(patched.map((el, i) => el.type === "arrow" && el.elbowed && !elements[i].elbowed ? updateElbowArrow(el, patched) : el), state.selectedIds) };
4303
+ });
4304
+ }
4305
+ //#endregion
4306
+ //#region src/editor/style-rows.tsx
4307
+ function previewElements(state) {
4308
+ const selected = getSelectedElements(state).filter((el) => !(el.type === "text" && el.containerId));
4309
+ if (selected.length > 0) return selected;
4310
+ switch (state.tool) {
4311
+ case "rectangle":
4312
+ case "diamond":
4313
+ case "ellipse": return [newElement(state.tool, {}, state.currentStyle)];
4314
+ case "arrow":
4315
+ case "line":
4316
+ case "freedraw": return state.tool === "freedraw" ? [{
4317
+ ...newElement("rectangle", {}),
4318
+ type: "freedraw"
4319
+ }] : [newLinearElement(state.tool, {}, state.currentStyle)];
4320
+ case "text": return [newTextElement({ text: "" }, state.currentStyle)];
4321
+ default: return [];
4322
+ }
4323
+ }
4324
+ var Row = ({ children, label, name }) => /* @__PURE__ */ jsxs("div", {
4325
+ className: row,
4326
+ "data-style-row": name ?? "",
4327
+ children: [/* @__PURE__ */ jsx("span", {
4328
+ className: rowLabel,
4329
+ children: label
4330
+ }), children]
4331
+ });
4332
+ function Segment({ choices, current, onPick }) {
4333
+ const items = choices.map((c) => ({
4334
+ value: String(c.value),
4335
+ label: c.icon ? /* @__PURE__ */ jsx(c.icon, {
4336
+ "aria-label": c.label,
4337
+ size: 15
4338
+ }) : c.label
4339
+ }));
4340
+ return /* @__PURE__ */ jsx(SegmentedControl, {
4341
+ fullWidth: true,
4342
+ items,
4343
+ size: "sm",
4344
+ value: String(current),
4345
+ onChange: (v) => {
4346
+ const choice = choices.find((c) => String(c.value) === v);
4347
+ if (choice) onPick(choice.value);
4348
+ }
4349
+ });
4350
+ }
4351
+ function useStyleRows(store) {
4352
+ const state = useStore(store, (s) => s);
4353
+ if (state.editingTextId || state.selectionBox) return null;
4354
+ const elements = previewElements(state);
4355
+ if (elements.length === 0) return null;
4356
+ const props = getApplicableProps(elements);
4357
+ const hasSelection = state.selectedIds.size > 0;
4358
+ const value = (key) => getCommonValue(elements, key);
4359
+ const set = (patch) => applyStyle(store, patch);
4360
+ const swatches = (key, colors) => /* @__PURE__ */ jsx("div", {
4361
+ className: options,
4362
+ children: colors.map((color) => /* @__PURE__ */ jsx("button", {
4363
+ "aria-label": color,
4364
+ "aria-pressed": value(key) === color,
4365
+ className: `${swatch}${color === "transparent" ? ` ${transparentSwatch}` : ""}`,
4366
+ "data-swatch": `${key}:${color}`,
4367
+ style: color === "transparent" ? void 0 : { background: color },
4368
+ type: "button",
4369
+ onClick: () => set({ [key]: color })
4370
+ }, color))
4371
+ });
4372
+ const action = (label, icon, run) => /* @__PURE__ */ jsx(ActionButton, {
4373
+ icon: true,
4374
+ "aria-label": label,
4375
+ size: "sm",
4376
+ title: label,
4377
+ variant: "ghost",
4378
+ onClick: () => run(store),
4379
+ children: icon
4380
+ }, label);
4381
+ const grouped = elements.some((el) => (el.groupIds ?? []).length > 0);
4382
+ const rows = /* @__PURE__ */ jsxs(Fragment, { children: [
4383
+ props.has("stroke") && /* @__PURE__ */ jsx(Row, {
4384
+ label: "Stroke",
4385
+ children: swatches("strokeColor", STROKE_COLORS)
4386
+ }),
4387
+ props.has("background") && /* @__PURE__ */ jsx(Row, {
4388
+ label: "Background",
4389
+ children: swatches("backgroundColor", BACKGROUND_COLORS)
4390
+ }),
4391
+ props.has("fillStyle") && /* @__PURE__ */ jsx(Row, {
4392
+ label: "Fill",
4393
+ children: /* @__PURE__ */ jsx(Segment, {
4394
+ choices: FILL_STYLES,
4395
+ current: value("fillStyle"),
4396
+ onPick: (v) => set({ fillStyle: v })
4397
+ })
4398
+ }),
4399
+ props.has("strokeWidth") && /* @__PURE__ */ jsx(Row, {
4400
+ label: "Stroke width",
4401
+ children: /* @__PURE__ */ jsx(Segment, {
4402
+ choices: STROKE_WIDTHS,
4403
+ current: value("strokeWidth"),
4404
+ onPick: (v) => set({ strokeWidth: v })
4405
+ })
4406
+ }),
4407
+ props.has("strokeStyle") && /* @__PURE__ */ jsx(Row, {
4408
+ label: "Stroke style",
4409
+ children: /* @__PURE__ */ jsx(Segment, {
4410
+ choices: STROKE_STYLES,
4411
+ current: value("strokeStyle"),
4412
+ onPick: (v) => set({ strokeStyle: v })
4413
+ })
4414
+ }),
4415
+ props.has("roughness") && /* @__PURE__ */ jsx(Row, {
4416
+ label: "Sloppiness",
4417
+ children: /* @__PURE__ */ jsx(Segment, {
4418
+ choices: ROUGHNESS,
4419
+ current: value("roughness"),
4420
+ onPick: (v) => set({ roughness: v })
4421
+ })
4422
+ }),
4423
+ props.has("roundness") && /* @__PURE__ */ jsx(Row, {
4424
+ label: "Edges",
4425
+ children: /* @__PURE__ */ jsx(Segment, {
4426
+ choices: ROUNDNESS,
4427
+ current: value("roundness"),
4428
+ onPick: (v) => set({ roundness: v })
4429
+ })
4430
+ }),
4431
+ props.has("shadow") && /* @__PURE__ */ jsx(Row, {
4432
+ label: "Shadow",
4433
+ name: "shadow",
4434
+ children: /* @__PURE__ */ jsx(Segment, {
4435
+ choices: SHADOWS,
4436
+ current: value("shadow"),
4437
+ onPick: (v) => set({ shadow: v })
4438
+ })
4439
+ }),
4440
+ props.has("arrowType") && /* @__PURE__ */ jsx(Row, {
4441
+ label: "Arrow type",
4442
+ children: /* @__PURE__ */ jsx(Segment, {
4443
+ choices: ARROW_TYPES,
4444
+ current: value("arrowType"),
4445
+ onPick: (v) => set({ arrowType: v })
4446
+ })
4447
+ }),
4448
+ props.has("arrowheads") && /* @__PURE__ */ jsxs(Row, {
4449
+ label: "Arrowheads",
4450
+ children: [/* @__PURE__ */ jsx(Segment, {
4451
+ choices: ARROWHEADS,
4452
+ current: value("startArrowhead"),
4453
+ onPick: (v) => set({ startArrowhead: v })
4454
+ }), /* @__PURE__ */ jsx(Segment, {
4455
+ choices: ARROWHEADS,
4456
+ current: value("endArrowhead"),
4457
+ onPick: (v) => set({ endArrowhead: v })
4458
+ })]
4459
+ }),
4460
+ props.has("fontSize") && /* @__PURE__ */ jsx(Row, {
4461
+ label: "Font size",
4462
+ children: /* @__PURE__ */ jsx(Segment, {
4463
+ choices: FONT_SIZES,
4464
+ current: value("fontSize"),
4465
+ onPick: (v) => set({ fontSize: v })
4466
+ })
4467
+ }),
4468
+ props.has("fontFamily") && /* @__PURE__ */ jsx(Row, {
4469
+ label: "Font",
4470
+ children: /* @__PURE__ */ jsx(Segment, {
4471
+ choices: FONT_FAMILIES,
4472
+ current: value("fontFamily"),
4473
+ onPick: (v) => set({ fontFamily: v })
4474
+ })
4475
+ }),
4476
+ props.has("textAlign") && /* @__PURE__ */ jsx(Row, {
4477
+ label: "Align",
4478
+ children: /* @__PURE__ */ jsx(Segment, {
4479
+ choices: TEXT_ALIGNS,
4480
+ current: value("textAlign"),
4481
+ onPick: (v) => set({ textAlign: v })
4482
+ })
4483
+ }),
4484
+ /* @__PURE__ */ jsx(Row, {
4485
+ label: "Opacity",
4486
+ children: /* @__PURE__ */ jsx("input", {
4487
+ "aria-label": "Opacity",
4488
+ className: range,
4489
+ max: 100,
4490
+ min: 0,
4491
+ step: 10,
4492
+ type: "range",
4493
+ value: typeof value("opacity") === "number" ? value("opacity") : 100,
4494
+ onChange: (e) => set({ opacity: Number(e.target.value) })
4495
+ })
4496
+ }),
4497
+ hasSelection && /* @__PURE__ */ jsx(Row, {
4498
+ label: "Layers",
4499
+ children: /* @__PURE__ */ jsxs("div", {
4500
+ className: "_14kbw0vc",
4501
+ children: [
4502
+ action("Send to back", /* @__PURE__ */ jsx(ArrowDownToLine, {}), sendToBack),
4503
+ action("Send backward", /* @__PURE__ */ jsx(ArrowDown, {}), sendBackward),
4504
+ action("Bring forward", /* @__PURE__ */ jsx(ArrowUp, {}), bringForward),
4505
+ action("Bring to front", /* @__PURE__ */ jsx(ArrowUpToLine, {}), bringToFront)
4506
+ ]
4507
+ })
4508
+ }),
4509
+ hasSelection && /* @__PURE__ */ jsx(Row, {
4510
+ label: "Actions",
4511
+ children: /* @__PURE__ */ jsxs("div", {
4512
+ className: "_14kbw0vc",
4513
+ children: [
4514
+ action("Duplicate", /* @__PURE__ */ jsx(Copy, {}), duplicateSelection),
4515
+ elements.length > 1 && action("Group", /* @__PURE__ */ jsx(Group, {}), groupSelection),
4516
+ grouped && action("Ungroup", /* @__PURE__ */ jsx(Ungroup, {}), ungroupSelection),
4517
+ action("Delete", /* @__PURE__ */ jsx(Trash2, {}), deleteSelection)
4518
+ ]
4519
+ })
4520
+ })
4521
+ ] });
4522
+ return Children.toArray(rows.props.children);
4523
+ }
4524
+ //#endregion
4525
+ //#region src/editor/StylePanel.tsx
4526
+ var StylePanel = ({ store }) => {
4527
+ const rows = useStyleRows(store);
4528
+ if (!rows) return null;
4529
+ return /* @__PURE__ */ jsx("div", {
4530
+ "data-style-panel": true,
4531
+ "data-whiteboard-chrome": true,
4532
+ className: `${floating} ${panel}`,
4533
+ children: rows
4534
+ });
4535
+ };
4536
+ var StyleSheet = ({ store }) => {
4537
+ const rows = useStyleRows(store);
4538
+ const hasSelection = useStore(store, (s) => s.selectedIds.size > 0);
4539
+ const [expanded, setExpanded] = useState(false);
4540
+ if (!rows || !hasSelection) return null;
4541
+ const visible = expanded ? rows : rows.slice(0, 4);
4542
+ return /* @__PURE__ */ jsxs("div", {
4543
+ "data-style-sheet": true,
4544
+ "data-whiteboard-chrome": true,
4545
+ className: sheet,
4546
+ children: [
4547
+ /* @__PURE__ */ jsx("div", { className: grabber }),
4548
+ visible,
4549
+ rows.length > 4 && /* @__PURE__ */ jsx("button", {
4550
+ "data-style-more": true,
4551
+ className: "_14kbw0vm",
4552
+ type: "button",
4553
+ onClick: () => setExpanded((v) => !v),
4554
+ children: expanded ? "Fewer options" : "More styles and actions"
4555
+ })
4556
+ ]
4557
+ });
4558
+ };
4559
+ //#endregion
4560
+ //#region src/editor/TextEditor.tsx
4561
+ var MIN_WIDTH = 24;
4562
+ var TextEditor = ({ dark = false, store }) => {
4563
+ const editingId = useStore(store, (s) => s.editingTextId);
4564
+ const el = useStore(store, (s) => s.editingTextId ? s.elements.find((e) => e.id === s.editingTextId) : void 0);
4565
+ const viewport = useStore(store, (s) => s.viewport);
4566
+ const ref = useRef(null);
4567
+ useEffect(() => {
4568
+ const node = ref.current;
4569
+ if (!node) return;
4570
+ node.focus({ preventScroll: true });
4571
+ node.setSelectionRange(node.value.length, node.value.length);
4572
+ }, [editingId]);
4573
+ const handFont = use(SceneHandFontContext);
4574
+ if (!editingId || !el) return null;
4575
+ const [left, top] = sceneToScreen([el.x, el.y], viewport);
4576
+ const zoom = viewport.zoom;
4577
+ const lineHeight = el.lineHeight ?? getLineHeight(el.fontFamily);
4578
+ return /* @__PURE__ */ jsx("textarea", {
4579
+ "data-whiteboard-text-editor": true,
4580
+ className: textEditor,
4581
+ ref,
4582
+ spellCheck: false,
4583
+ value: el.originalText ?? el.text,
4584
+ wrap: el.containerId ? "soft" : "off",
4585
+ style: {
4586
+ left,
4587
+ top,
4588
+ width: Math.max(MIN_WIDTH, el.width) * zoom,
4589
+ height: Math.max(el.height, el.fontSize * lineHeight) * zoom,
4590
+ fontSize: el.fontSize * zoom,
4591
+ lineHeight,
4592
+ fontFamily: handFont && isHandFontFamily(el.fontFamily) ? handFont : fontFamilyToCss(el.fontFamily),
4593
+ color: el.strokeColor,
4594
+ textAlign: el.textAlign,
4595
+ opacity: el.opacity / 100,
4596
+ transform: angleOf$1(el) ? `rotate(${angleOf$1(el)}rad)` : void 0,
4597
+ filter: dark ? DARK_SCENE_FILTER : void 0
4598
+ },
4599
+ onBlur: () => finishTextEditing(store),
4600
+ onChange: (e) => updateEditingText(store, e.target.value),
4601
+ onPointerDown: (e) => e.stopPropagation(),
4602
+ onKeyDown: (e) => {
4603
+ e.stopPropagation();
4604
+ if (e.key === "Escape" || e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
4605
+ e.preventDefault();
4606
+ finishTextEditing(store);
4607
+ }
4608
+ }
4609
+ });
4610
+ };
4611
+ //#endregion
4612
+ //#region src/editor/ZoomControls.tsx
4613
+ var ZoomControls = ({ compact = false, store }) => {
4614
+ const zoom$1 = useStore(store, (s) => s.viewport.zoom);
4615
+ useStore(store, (s) => s.elements);
4616
+ return /* @__PURE__ */ jsxs("div", {
4617
+ "data-whiteboard-chrome": true,
4618
+ className: `${floating} ${zoom}${compact ? ` ${zoomTop}` : ""}`,
4619
+ children: [
4620
+ /* @__PURE__ */ jsx(ActionButton, {
4621
+ icon: true,
4622
+ "aria-label": "Undo",
4623
+ disabled: !store.canUndo(),
4624
+ size: "sm",
4625
+ variant: "ghost",
4626
+ onClick: () => store.undo(),
4627
+ children: /* @__PURE__ */ jsx(Undo2, {})
4628
+ }),
4629
+ /* @__PURE__ */ jsx(ActionButton, {
4630
+ icon: true,
4631
+ "aria-label": "Redo",
4632
+ disabled: !store.canRedo(),
4633
+ size: "sm",
4634
+ variant: "ghost",
4635
+ onClick: () => store.redo(),
4636
+ children: /* @__PURE__ */ jsx(Redo2, {})
4637
+ }),
4638
+ !compact && /* @__PURE__ */ jsxs(Fragment, { children: [
4639
+ /* @__PURE__ */ jsx("span", { className: "_14kbw0v5" }),
4640
+ /* @__PURE__ */ jsx(ActionButton, {
4641
+ icon: true,
4642
+ "aria-label": "Zoom out",
4643
+ size: "sm",
4644
+ variant: "ghost",
4645
+ onClick: () => zoomBy(store, 1 / 1.2),
4646
+ children: /* @__PURE__ */ jsx(Minus, {})
4647
+ }),
4648
+ /* @__PURE__ */ jsxs("button", {
4649
+ "aria-label": "Reset zoom",
4650
+ className: "_14kbw0vh",
4651
+ type: "button",
4652
+ onClick: () => resetZoom(store),
4653
+ children: [Math.round(zoom$1 * 100), "%"]
4654
+ }),
4655
+ /* @__PURE__ */ jsx(ActionButton, {
4656
+ icon: true,
4657
+ "aria-label": "Zoom in",
4658
+ size: "sm",
4659
+ variant: "ghost",
4660
+ onClick: () => zoomBy(store, 1.2),
4661
+ children: /* @__PURE__ */ jsx(Plus, {})
4662
+ })
4663
+ ] })
4664
+ ]
4665
+ });
4666
+ };
4667
+ //#endregion
4668
+ //#region src/editor/WhiteboardEditor.tsx
4669
+ var MULTI_IMAGE_OFFSET = 20;
4670
+ var ARROW_KEYS = /* @__PURE__ */ new Set([
4671
+ "ArrowLeft",
4672
+ "ArrowRight",
4673
+ "ArrowUp",
4674
+ "ArrowDown"
4675
+ ]);
4676
+ function isTypingTarget(target) {
4677
+ return target instanceof Element && (target.matches("input, textarea, select") || target.isContentEditable);
4678
+ }
4679
+ var WhiteboardEditor = ({ chrome = {}, contextMenuItems, handFontOverride, initialFit = true, onContextMenu, store, theme, toolbar = "inline", tools, uploadFile, onUploadError }) => {
4680
+ const allowedTools = useMemo(() => tools ? new Set(tools) : void 0, [tools]);
4681
+ const handlers = useMemo(createToolHandlers, []);
4682
+ const inputRef = useRef(null);
4683
+ const pickAtRef = useRef(null);
4684
+ const optionsRef = useRef({});
4685
+ optionsRef.current = {
4686
+ uploadFile,
4687
+ onUploadError
4688
+ };
4689
+ const context = useMemo(() => {
4690
+ const onFiles = (files, at) => {
4691
+ files.forEach((file, i) => {
4692
+ const offset = i * MULTI_IMAGE_OFFSET;
4693
+ insertImageFile(store, file, [at[0] + offset, at[1] + offset], optionsRef.current);
4694
+ });
4695
+ };
4696
+ const requestImage = (at) => {
4697
+ pickAtRef.current = at;
4698
+ inputRef.current?.click();
4699
+ };
4700
+ return {
4701
+ store,
4702
+ onFiles,
4703
+ requestImage
4704
+ };
4705
+ }, [store]);
4706
+ const contextMenu = useContextMenu(store, contextMenuItems, onContextMenu);
4707
+ const tool = useStore(store, (s) => s.tool);
4708
+ const narrow = useNarrowLayout(store);
4709
+ const canvasWidth = useStore(store, (s) => s.canvasSize.width);
4710
+ const positionedRef = useRef(false);
4711
+ useEffect(() => {
4712
+ if (positionedRef.current || canvasWidth <= 0) return;
4713
+ positionedRef.current = true;
4714
+ if (!initialFit) return;
4715
+ const { elements, canvasSize } = store.getState();
4716
+ const alive = elements.filter((el) => !el.isDeleted);
4717
+ if (alive.length === 0) return;
4718
+ store.setState({ viewport: fitToContent(getCommonBounds(alive), canvasSize) });
4719
+ }, [
4720
+ canvasWidth,
4721
+ initialFit,
4722
+ store
4723
+ ]);
4724
+ useEffect(() => {
4725
+ if (tool !== "image") return;
4726
+ const { viewport, canvasSize, toolLocked } = store.getState();
4727
+ context.requestImage?.(screenToScene([canvasSize.width / 2, canvasSize.height / 2], viewport));
4728
+ if (!toolLocked) store.setState({ tool: "selection" });
4729
+ }, [
4730
+ context,
4731
+ store,
4732
+ tool
4733
+ ]);
4734
+ const onKeyDown = (e) => {
4735
+ if (isTypingTarget(e.target)) return;
4736
+ if (!(e.target instanceof Element && e.target.hasAttribute("data-whiteboard-canvas")) && ARROW_KEYS.has(e.key)) return;
4737
+ if (getToolHandler(handlers, store.getState().tool).onKeyDown?.(context, e.nativeEvent) || handleShortcut(store, e, allowedTools)) e.preventDefault();
4738
+ };
4739
+ return /* @__PURE__ */ jsx(SceneHandFontContext, {
4740
+ value: handFontOverride ?? null,
4741
+ children: /* @__PURE__ */ jsxs("div", {
4742
+ "data-whiteboard-editor": true,
4743
+ className: root,
4744
+ onKeyDown,
4745
+ children: [
4746
+ toolbar === "inline" && chrome.toolbar !== false && !narrow && /* @__PURE__ */ jsx("div", {
4747
+ className: "_14kbw0v2",
4748
+ children: /* @__PURE__ */ jsx(WhiteboardToolbar, {
4749
+ store,
4750
+ tools: allowedTools
4751
+ })
4752
+ }),
4753
+ /* @__PURE__ */ jsxs(WhiteboardCanvas, {
4754
+ context,
4755
+ handlers,
4756
+ store,
4757
+ theme,
4758
+ onContextMenu: chrome.contextMenu === false ? void 0 : contextMenu.open,
4759
+ children: [
4760
+ /* @__PURE__ */ jsx(SelectionOverlay, { store }),
4761
+ /* @__PURE__ */ jsx(TextEditor, {
4762
+ dark: theme === "dark",
4763
+ store
4764
+ }),
4765
+ /* @__PURE__ */ jsx(RichTextEditor, {
4766
+ dark: theme === "dark",
4767
+ store
4768
+ }),
4769
+ /* @__PURE__ */ jsx(FrameNameEditor, { store }),
4770
+ chrome.stylePanel !== false && (narrow ? /* @__PURE__ */ jsx(StyleSheet, { store }) : /* @__PURE__ */ jsx(StylePanel, { store })),
4771
+ chrome.zoom !== false && /* @__PURE__ */ jsx(ZoomControls, {
4772
+ compact: narrow,
4773
+ store
4774
+ }),
4775
+ contextMenu.menu,
4776
+ narrow && chrome.mobileDock !== false && /* @__PURE__ */ jsx(MobileDock, {
4777
+ store,
4778
+ tools: allowedTools
4779
+ })
4780
+ ]
4781
+ }),
4782
+ /* @__PURE__ */ jsx("input", {
4783
+ hidden: true,
4784
+ multiple: true,
4785
+ accept: "image/*",
4786
+ ref: inputRef,
4787
+ type: "file",
4788
+ onChange: (e) => {
4789
+ const files = [...e.currentTarget.files ?? []];
4790
+ e.currentTarget.value = "";
4791
+ if (files.length > 0 && pickAtRef.current) context.onFiles?.(files, pickAtRef.current);
4792
+ }
4793
+ })
4794
+ ]
4795
+ })
4796
+ });
4797
+ };
4798
+ //#endregion
4799
+ export { sendToBack as A, bringToFront as C, groupSelection as D, duplicateSelection as E, createWhiteboardStore as F, useStore as I, finishTextEditing as L, getSelectedElements as M, WhiteboardToolbar as N, selectAll as O, useNarrowLayout as P, bringForward as S, deleteSelection as T, screenToScene as _, CHROME_ATTR as a, cutSelection as b, placeCard as c, MAX_ZOOM as d, MIN_ZOOM as f, sceneToScreen as g, panBy as h, getCommonValue as i, ungroupSelection as j, sendBackward as k, setTool as l, fitToContent as m, applyStyle as n, CARD_HEIGHT as o, clampZoom as p, getApplicableProps as r, CARD_WIDTH as s, WhiteboardEditor as t, bindLinearEnd as u, zoomAt as v, deleteElements as w, pasteFromClipboard as x, copySelection as y };