@canvas-components/react-drag-any 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2127 @@
1
+ 'use strict';
2
+
3
+ var dragAny = require('@canvas-components/drag-any');
4
+ var react = require('react');
5
+ var reactDom = require('react-dom');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+ var reactCanvasUi = require('@canvas-components/react-canvas-ui');
8
+
9
+ var __defProp = Object.defineProperty;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
12
+ function overlayRoot(owner) {
13
+ const doc = owner?.ownerDocument ?? document;
14
+ return doc.fullscreenElement ?? doc.body;
15
+ }
16
+ function overlayTheme(theme) {
17
+ const t = dragAny.resolveTheme(theme);
18
+ return {
19
+ "--drag-overlay-bg": t.backgroundColor,
20
+ "--drag-overlay-border": t.borderColor,
21
+ "--drag-overlay-text": t.textColor,
22
+ "--drag-overlay-muted": t.mutedTextColor,
23
+ "--drag-overlay-hover": t.hoverBackgroundColor,
24
+ "--drag-overlay-shadow": t.fixedShadowColor,
25
+ "--drag-overlay-focus": t.placeholderBorderColor,
26
+ "--drag-overlay-danger": t.forbiddenColor,
27
+ fontFamily: t.fontFamily,
28
+ fontSize: t.fontSize
29
+ };
30
+ }
31
+ function useOverlayPosition(ref, root, anchor, parent) {
32
+ const [style, setStyle] = react.useState({});
33
+ react.useLayoutEffect(() => {
34
+ const el = ref.current;
35
+ const win = root.ownerDocument.defaultView;
36
+ if (!el || !win) return;
37
+ function update() {
38
+ if (!el || !win) return;
39
+ const viewport = win.visualViewport;
40
+ const visibleLeft = (viewport?.offsetLeft ?? 0) + 4;
41
+ const visibleTop = (viewport?.offsetTop ?? 0) + 4;
42
+ const visibleRight = visibleLeft + (viewport?.width ?? win.innerWidth) - 8;
43
+ const visibleBottom = visibleTop + (viewport?.height ?? win.innerHeight) - 8;
44
+ const bounds = root === root.ownerDocument.body ? void 0 : root.getBoundingClientRect();
45
+ const left = bounds ? Math.max(visibleLeft, bounds.left + 4) : visibleLeft;
46
+ const top = bounds ? Math.max(visibleTop, bounds.top + 4) : visibleTop;
47
+ const right = bounds ? Math.min(visibleRight, bounds.right - 4) : visibleRight;
48
+ const bottom = bounds ? Math.min(visibleBottom, bounds.bottom - 4) : visibleBottom;
49
+ const maxWidth = Math.max(0, right - left);
50
+ const maxHeight = Math.max(0, bottom - top);
51
+ const width = Math.min(el.offsetWidth, maxWidth);
52
+ const height = Math.min(el.offsetHeight, maxHeight);
53
+ const parentRect = parent?.getBoundingClientRect();
54
+ const x = parentRect ? parentRect.right + width > right ? parentRect.left - width : parentRect.right : anchor.x;
55
+ setStyle({
56
+ left: Math.max(left, Math.min(x, right - width)),
57
+ top: Math.max(
58
+ top,
59
+ Math.min(parentRect?.top ?? anchor.y, bottom - height)
60
+ ),
61
+ maxWidth,
62
+ maxHeight,
63
+ "--drag-overlay-max-width": `${maxWidth}px`
64
+ });
65
+ }
66
+ update();
67
+ const resize = typeof ResizeObserver === "undefined" ? void 0 : new ResizeObserver(update);
68
+ resize?.observe(el);
69
+ win.addEventListener("resize", update);
70
+ win.visualViewport?.addEventListener("resize", update);
71
+ win.visualViewport?.addEventListener("scroll", update);
72
+ return () => {
73
+ resize?.disconnect();
74
+ win.removeEventListener("resize", update);
75
+ win.visualViewport?.removeEventListener("resize", update);
76
+ win.visualViewport?.removeEventListener("scroll", update);
77
+ };
78
+ }, [ref, root, anchor.x, anchor.y, parent]);
79
+ return style;
80
+ }
81
+ function MenuLevel({
82
+ items,
83
+ root,
84
+ request,
85
+ parent,
86
+ focusOnOpen = true,
87
+ onBack,
88
+ onSelect,
89
+ onClose
90
+ }) {
91
+ const panel = react.useRef(null);
92
+ const [submenu, setSubmenu] = react.useState();
93
+ const style = useOverlayPosition(panel, root, request.clientAnchor, parent);
94
+ const enabled = () => Array.from(
95
+ panel.current?.querySelectorAll(
96
+ ':scope > [role="menuitem"]:not(:disabled)'
97
+ ) ?? []
98
+ );
99
+ react.useLayoutEffect(() => {
100
+ if (focusOnOpen)
101
+ (enabled()[0] ?? panel.current)?.focus({ preventScroll: true });
102
+ }, [focusOnOpen]);
103
+ function handleKey(event) {
104
+ const buttons = enabled();
105
+ const index = buttons.indexOf(event.target);
106
+ const button = buttons[index];
107
+ switch (event.key) {
108
+ case "ArrowDown":
109
+ buttons[(index + 1) % buttons.length]?.focus();
110
+ break;
111
+ case "ArrowUp":
112
+ buttons[(index <= 0 ? buttons.length : index) - 1]?.focus();
113
+ break;
114
+ case "Home":
115
+ buttons[0]?.focus();
116
+ break;
117
+ case "End":
118
+ buttons[buttons.length - 1]?.focus();
119
+ break;
120
+ case "Enter":
121
+ case " ":
122
+ button?.click();
123
+ break;
124
+ case "ArrowRight":
125
+ if (button?.hasAttribute("aria-haspopup")) button.click();
126
+ break;
127
+ case "ArrowLeft":
128
+ onBack?.();
129
+ break;
130
+ case "Escape":
131
+ (onBack ?? onClose)();
132
+ break;
133
+ case "Tab":
134
+ onClose();
135
+ break;
136
+ default:
137
+ return;
138
+ }
139
+ event.preventDefault();
140
+ event.stopPropagation();
141
+ }
142
+ const active = items.find(
143
+ (item) => item.key === submenu?.key && !item.disabled
144
+ );
145
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
146
+ /* @__PURE__ */ jsxRuntime.jsx(
147
+ "div",
148
+ {
149
+ ref: panel,
150
+ className: "drag-any-menu",
151
+ role: "menu",
152
+ "aria-label": "\u64CD\u4F5C\u83DC\u5355",
153
+ tabIndex: -1,
154
+ style,
155
+ onKeyDown: handleKey,
156
+ onScroll: (event) => {
157
+ if (!submenu) return;
158
+ event.currentTarget.focus({ preventScroll: true });
159
+ setSubmenu(void 0);
160
+ },
161
+ children: items.map((item) => /* @__PURE__ */ jsxRuntime.jsxs(react.Fragment, { children: [
162
+ item.separatorBefore && /* @__PURE__ */ jsxRuntime.jsx("div", { role: "separator" }),
163
+ /* @__PURE__ */ jsxRuntime.jsxs(
164
+ "button",
165
+ {
166
+ role: "menuitem",
167
+ type: "button",
168
+ tabIndex: -1,
169
+ disabled: item.disabled,
170
+ "data-danger": item.danger || void 0,
171
+ "aria-haspopup": item.children?.length ? "menu" : void 0,
172
+ "aria-expanded": item.children?.length ? submenu?.key === item.key : void 0,
173
+ onMouseEnter: (event) => {
174
+ if (item.disabled) return;
175
+ event.currentTarget.focus({ preventScroll: true });
176
+ setSubmenu(
177
+ item.children?.length ? {
178
+ key: item.key,
179
+ anchor: event.currentTarget,
180
+ focus: false
181
+ } : void 0
182
+ );
183
+ },
184
+ onClick: (event) => {
185
+ if (item.children?.length)
186
+ setSubmenu({
187
+ key: item.key,
188
+ anchor: event.currentTarget,
189
+ focus: true
190
+ });
191
+ else onSelect(item.key);
192
+ },
193
+ children: [
194
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: item.label }),
195
+ !!item.children?.length && /* @__PURE__ */ jsxRuntime.jsx("span", { "aria-hidden": "true", children: "\u203A" })
196
+ ]
197
+ }
198
+ )
199
+ ] }, item.key))
200
+ }
201
+ ),
202
+ submenu && !!active?.children?.length && /* @__PURE__ */ jsxRuntime.jsx(
203
+ MenuLevel,
204
+ {
205
+ items: active.children,
206
+ root,
207
+ request,
208
+ parent: submenu.anchor,
209
+ focusOnOpen: submenu.focus,
210
+ onClose,
211
+ onSelect,
212
+ onBack: () => {
213
+ submenu.anchor.focus({ preventScroll: true });
214
+ setSubmenu(void 0);
215
+ }
216
+ },
217
+ active.key
218
+ )
219
+ ] });
220
+ }
221
+ function ContextMenuView(props) {
222
+ return /* @__PURE__ */ jsxRuntime.jsx(MenuSession, { ...props }, props.request.requestId);
223
+ }
224
+ function MenuSession({
225
+ request,
226
+ items,
227
+ onAction,
228
+ onClose,
229
+ theme,
230
+ owner,
231
+ returnFocus,
232
+ revision,
233
+ dragging,
234
+ isTargetValid
235
+ }) {
236
+ const root = overlayRoot(owner);
237
+ const doc = root.ownerDocument;
238
+ const menu = react.useRef(null);
239
+ const close = react.useRef(onClose);
240
+ close.current = onClose;
241
+ const previousFocus = react.useRef(returnFocus ?? doc.activeElement);
242
+ const valid = () => !dragging && (revision === void 0 || revision === request.modelRevision) && (isTargetValid?.(request) ?? true);
243
+ const invalid = !valid();
244
+ react.useLayoutEffect(() => {
245
+ if (invalid) onClose();
246
+ }, [invalid, onClose]);
247
+ react.useLayoutEffect(() => {
248
+ function outside(event) {
249
+ if (!event.composedPath().includes(menu.current)) close.current();
250
+ }
251
+ function dismiss() {
252
+ close.current();
253
+ }
254
+ doc.addEventListener("pointerdown", outside, true);
255
+ doc.addEventListener("scroll", outside, true);
256
+ doc.addEventListener("fullscreenchange", dismiss);
257
+ doc.defaultView?.addEventListener("blur", dismiss);
258
+ return () => {
259
+ doc.removeEventListener("pointerdown", outside, true);
260
+ doc.removeEventListener("scroll", outside, true);
261
+ doc.removeEventListener("fullscreenchange", dismiss);
262
+ doc.defaultView?.removeEventListener("blur", dismiss);
263
+ const previous = previousFocus.current;
264
+ if (previous?.isConnected) previous.focus?.({ preventScroll: true });
265
+ };
266
+ }, [doc]);
267
+ if (invalid || !items.length) return null;
268
+ return reactDom.createPortal(
269
+ /* @__PURE__ */ jsxRuntime.jsx(
270
+ "div",
271
+ {
272
+ ref: menu,
273
+ className: "drag-any-overlay",
274
+ style: overlayTheme(theme),
275
+ onPointerDown: (event) => event.stopPropagation(),
276
+ onWheel: (event) => event.stopPropagation(),
277
+ onContextMenu: (event) => {
278
+ event.preventDefault();
279
+ event.stopPropagation();
280
+ },
281
+ children: /* @__PURE__ */ jsxRuntime.jsx(
282
+ MenuLevel,
283
+ {
284
+ items,
285
+ root,
286
+ request,
287
+ onClose,
288
+ onSelect: (key) => {
289
+ const canExecute = valid();
290
+ onClose();
291
+ if (canExecute) onAction(key, request);
292
+ }
293
+ }
294
+ )
295
+ }
296
+ ),
297
+ root
298
+ );
299
+ }
300
+ async function copyContextMenuText(text, onError, owner) {
301
+ try {
302
+ const clipboard = (owner?.ownerDocument.defaultView ?? window).navigator.clipboard;
303
+ if (!clipboard) throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8BBF\u95EE\u526A\u8D34\u677F");
304
+ await clipboard.writeText(text);
305
+ } catch (error) {
306
+ onError?.(error instanceof Error ? error : new Error(String(error)));
307
+ }
308
+ }
309
+ var numberFields = {
310
+ thickness: "\u539A\u5EA6",
311
+ thumbRadius: "\u6ED1\u5757\u5706\u89D2",
312
+ maxScrollSpeed: "\u6700\u5927\u6EDA\u52A8\u901F\u5EA6"
313
+ };
314
+ var colorFields = {
315
+ thumbColor: "\u6ED1\u5757\u989C\u8272",
316
+ trackColor: "\u8F68\u9053\u989C\u8272",
317
+ buttonColor: "\u6309\u94AE\u989C\u8272",
318
+ buttonHoverColor: "\u6309\u94AE\u60AC\u505C\u989C\u8272",
319
+ buttonPressedColor: "\u6309\u94AE\u6309\u4E0B\u989C\u8272"
320
+ };
321
+ var marginFields = [
322
+ "horizontalLeft",
323
+ "horizontalRight",
324
+ "horizontalBottom",
325
+ "verticalTop",
326
+ "verticalRight",
327
+ "verticalBottom"
328
+ ];
329
+ var numericKeys = [...Object.keys(numberFields), ...marginFields];
330
+ function storageName(key) {
331
+ return `canvas-components:drag-any:${key}:scrollbar:v1`;
332
+ }
333
+ function isSettings(value) {
334
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
335
+ const options = value;
336
+ return (options.mode === void 0 || options.mode === "button" || options.mode === "scrollbar") && (options.visible === void 0 || typeof options.visible === "boolean") && numericKeys.every(
337
+ (key) => options[key] === void 0 || Number.isFinite(options[key])
338
+ ) && Object.keys(colorFields).every(
339
+ (key) => options[key] === void 0 || typeof options[key] === "string"
340
+ ) && [options.horizontal, options.vertical].every(
341
+ (axis) => axis === void 0 || axis === false || isSettings(axis)
342
+ );
343
+ }
344
+ function readScrollbarSettings(storageKey, owner) {
345
+ if (!storageKey) return void 0;
346
+ try {
347
+ const raw = (owner?.ownerDocument.defaultView ?? window).localStorage.getItem(storageName(storageKey));
348
+ const value = raw === null ? void 0 : JSON.parse(raw);
349
+ return isSettings(value) ? value : void 0;
350
+ } catch {
351
+ return void 0;
352
+ }
353
+ }
354
+ function saveScrollbarSettings(storageKey, value, owner, onError) {
355
+ if (!storageKey) return;
356
+ try {
357
+ const storage = (owner?.ownerDocument.defaultView ?? window).localStorage;
358
+ if (value === void 0) storage.removeItem(storageName(storageKey));
359
+ else storage.setItem(storageName(storageKey), JSON.stringify(value));
360
+ } catch (error) {
361
+ onError?.(error instanceof Error ? error : new Error(String(error)));
362
+ }
363
+ }
364
+ function ScrollbarDialog({
365
+ title,
366
+ value,
367
+ onConfirm,
368
+ onClose,
369
+ storageKey,
370
+ theme,
371
+ owner,
372
+ onError,
373
+ children
374
+ }) {
375
+ const panel = react.useRef(null);
376
+ const titleId = react.useId();
377
+ const root = overlayRoot(owner);
378
+ react.useLayoutEffect(() => {
379
+ const dialog = panel.current;
380
+ const doc = root.ownerDocument;
381
+ const previous = doc.activeElement;
382
+ if (typeof dialog.showModal === "function") dialog.showModal();
383
+ else dialog.setAttribute("open", "");
384
+ (dialog.querySelector("select,input,button") ?? dialog).focus();
385
+ return () => {
386
+ if (typeof dialog.close === "function") dialog.close();
387
+ if (previous?.isConnected) previous.focus({ preventScroll: true });
388
+ };
389
+ }, [root]);
390
+ return reactDom.createPortal(
391
+ /* @__PURE__ */ jsxRuntime.jsx(
392
+ "div",
393
+ {
394
+ className: "drag-any-overlay drag-any-dialog-backdrop",
395
+ style: overlayTheme(theme),
396
+ onWheel: (event) => event.stopPropagation(),
397
+ onPointerDown: (event) => {
398
+ event.stopPropagation();
399
+ if (event.target === event.currentTarget) onClose();
400
+ },
401
+ children: /* @__PURE__ */ jsxRuntime.jsx(
402
+ "dialog",
403
+ {
404
+ ref: panel,
405
+ className: "drag-any-dialog",
406
+ role: "dialog",
407
+ "aria-modal": "true",
408
+ "aria-labelledby": titleId,
409
+ onCancel: (event) => {
410
+ event.preventDefault();
411
+ onClose();
412
+ },
413
+ onKeyDown: (event) => {
414
+ event.stopPropagation();
415
+ if (event.key === "Escape") {
416
+ event.preventDefault();
417
+ onClose();
418
+ }
419
+ },
420
+ onPointerDown: (event) => {
421
+ if (event.target === event.currentTarget) {
422
+ const bounds = event.currentTarget.getBoundingClientRect();
423
+ if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)
424
+ onClose();
425
+ }
426
+ },
427
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
428
+ "form",
429
+ {
430
+ onSubmit: (event) => {
431
+ event.preventDefault();
432
+ saveScrollbarSettings(storageKey, value, owner, onError);
433
+ onConfirm(value);
434
+ },
435
+ children: [
436
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { id: titleId, children: title }),
437
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "drag-any-dialog-fields", children }),
438
+ /* @__PURE__ */ jsxRuntime.jsxs("footer", { children: [
439
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: onClose, children: "\u53D6\u6D88" }),
440
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "submit", "data-primary": true, children: "\u786E\u5B9A" })
441
+ ] })
442
+ ]
443
+ }
444
+ )
445
+ }
446
+ )
447
+ }
448
+ ),
449
+ root
450
+ );
451
+ }
452
+ function withField(value, key, field) {
453
+ const next = { ...value };
454
+ if (field === void 0) delete next[key];
455
+ else next[key] = field;
456
+ return next;
457
+ }
458
+ function SettingsDialog(props) {
459
+ const [draft, setDraft] = react.useState(props.value);
460
+ const [scope, setScope] = react.useState(
461
+ "common"
462
+ );
463
+ const axis = scope === "common" ? draft : draft[scope];
464
+ const fields = axis || {};
465
+ function update(key, value) {
466
+ if (scope === "common") setDraft(withField(draft, key, value));
467
+ else setDraft(withField(draft, scope, withField(fields, key, value)));
468
+ }
469
+ return /* @__PURE__ */ jsxRuntime.jsxs(ScrollbarDialog, { ...props, value: draft, title: "\u6EDA\u52A8\u6761\u5C5E\u6027", children: [
470
+ /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
471
+ "\u8BBE\u7F6E\u8303\u56F4",
472
+ /* @__PURE__ */ jsxRuntime.jsxs(
473
+ "select",
474
+ {
475
+ value: scope,
476
+ onChange: (event) => setScope(event.target.value),
477
+ children: [
478
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "common", children: "\u4E24\u8F74\u5171\u7528" }),
479
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "horizontal", children: "\u6C34\u5E73\u8F74" }),
480
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "vertical", children: "\u5782\u76F4\u8F74" })
481
+ ]
482
+ }
483
+ )
484
+ ] }),
485
+ scope !== "common" && /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
486
+ "\u542F\u7528\u6B64\u8F74",
487
+ /* @__PURE__ */ jsxRuntime.jsx(
488
+ "input",
489
+ {
490
+ type: "checkbox",
491
+ checked: axis !== false,
492
+ onChange: (event) => setDraft(
493
+ withField(
494
+ draft,
495
+ scope,
496
+ event.target.checked ? void 0 : false
497
+ )
498
+ )
499
+ }
500
+ )
501
+ ] }),
502
+ axis !== false && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
503
+ /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
504
+ "\u6A21\u5F0F",
505
+ /* @__PURE__ */ jsxRuntime.jsxs(
506
+ "select",
507
+ {
508
+ value: fields.mode ?? "",
509
+ onChange: (event) => update(
510
+ "mode",
511
+ event.target.value || void 0
512
+ ),
513
+ children: [
514
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "", children: "\u9ED8\u8BA4" }),
515
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "scrollbar", children: "\u6ED1\u5757" }),
516
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "button", children: "\u6309\u94AE" })
517
+ ]
518
+ }
519
+ )
520
+ ] }),
521
+ /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
522
+ "\u53EF\u89C1\u6027",
523
+ /* @__PURE__ */ jsxRuntime.jsxs(
524
+ "select",
525
+ {
526
+ value: fields.visible === void 0 ? "" : String(fields.visible),
527
+ onChange: (event) => update(
528
+ "visible",
529
+ event.target.value ? event.target.value === "true" : void 0
530
+ ),
531
+ children: [
532
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "", children: "\u9ED8\u8BA4" }),
533
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "true", children: "\u663E\u793A" }),
534
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "false", children: "\u9690\u85CF" })
535
+ ]
536
+ }
537
+ )
538
+ ] }),
539
+ Object.keys(numberFields).map(
540
+ (key) => /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
541
+ numberFields[key],
542
+ /* @__PURE__ */ jsxRuntime.jsx(
543
+ "input",
544
+ {
545
+ type: "number",
546
+ min: 0,
547
+ step: "any",
548
+ value: fields[key] ?? "",
549
+ onChange: (event) => update(
550
+ key,
551
+ Number.isFinite(event.target.valueAsNumber) ? event.target.valueAsNumber : void 0
552
+ )
553
+ }
554
+ )
555
+ ] }, key)
556
+ ),
557
+ Object.keys(colorFields).map(
558
+ (key) => /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
559
+ colorFields[key],
560
+ /* @__PURE__ */ jsxRuntime.jsx(
561
+ "input",
562
+ {
563
+ value: fields[key] ?? "",
564
+ onChange: (event) => update(key, event.target.value || void 0)
565
+ }
566
+ )
567
+ ] }, key)
568
+ )
569
+ ] })
570
+ ] });
571
+ }
572
+ var margins = {
573
+ horizontalLeft: "\u6A2A\u6761\u5DE6\u8FB9\u8DDD",
574
+ horizontalRight: "\u6A2A\u6761\u53F3\u8FB9\u8DDD",
575
+ horizontalBottom: "\u6A2A\u6761\u4E0B\u8FB9\u8DDD",
576
+ verticalTop: "\u7AD6\u6761\u4E0A\u8FB9\u8DDD",
577
+ verticalRight: "\u7AD6\u6761\u53F3\u8FB9\u8DDD",
578
+ verticalBottom: "\u7AD6\u6761\u4E0B\u8FB9\u8DDD"
579
+ };
580
+ function PositionDialog(props) {
581
+ const [draft, setDraft] = react.useState(props.value);
582
+ return /* @__PURE__ */ jsxRuntime.jsx(ScrollbarDialog, { ...props, value: draft, title: "\u6EDA\u52A8\u6761\u4F4D\u7F6E", children: Object.keys(margins).map((key) => /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
583
+ margins[key],
584
+ /* @__PURE__ */ jsxRuntime.jsx(
585
+ "input",
586
+ {
587
+ type: "number",
588
+ min: 0,
589
+ step: "any",
590
+ value: draft[key] ?? "",
591
+ onChange: (event) => {
592
+ const value = event.target.valueAsNumber;
593
+ const next = { ...draft };
594
+ if (Number.isFinite(value)) next[key] = value;
595
+ else delete next[key];
596
+ setDraft(next);
597
+ }
598
+ }
599
+ )
600
+ ] }, key)) });
601
+ }
602
+ function Tooltip({ request, owner, theme }) {
603
+ const panel = react.useRef(null);
604
+ const root = overlayRoot(owner);
605
+ const position = useOverlayPosition(panel, root, {
606
+ x: request.clientAnchor.x + 10,
607
+ y: request.clientAnchor.y + 14
608
+ });
609
+ return reactDom.createPortal(
610
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "drag-any-overlay", style: overlayTheme(theme), children: /* @__PURE__ */ jsxRuntime.jsx(
611
+ "div",
612
+ {
613
+ ref: panel,
614
+ className: "drag-any-tooltip",
615
+ role: "tooltip",
616
+ style: position,
617
+ children: request.text
618
+ }
619
+ ) }),
620
+ root
621
+ );
622
+ }
623
+ function EditorHost({
624
+ request,
625
+ onClose,
626
+ owner,
627
+ theme
628
+ }) {
629
+ const panel = react.useRef(null);
630
+ const root = overlayRoot(owner);
631
+ const style = useOverlayPosition(panel, root, request.clientAnchor);
632
+ return reactDom.createPortal(
633
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "drag-any-overlay", style: overlayTheme(theme), children: /* @__PURE__ */ jsxRuntime.jsx(
634
+ "div",
635
+ {
636
+ ref: panel,
637
+ className: "drag-any-editor-host",
638
+ style,
639
+ onPointerDown: (event) => event.stopPropagation(),
640
+ onKeyDown: (event) => {
641
+ event.stopPropagation();
642
+ if (event.key === "Escape" && !event.defaultPrevented) onClose();
643
+ },
644
+ children: request.view
645
+ }
646
+ ) }),
647
+ root
648
+ );
649
+ }
650
+ var pixelStyles = /* @__PURE__ */ new Set([
651
+ "width",
652
+ "height",
653
+ "gap",
654
+ "padding",
655
+ "paddingTop",
656
+ "paddingRight",
657
+ "paddingBottom",
658
+ "paddingLeft",
659
+ "margin",
660
+ "marginTop",
661
+ "marginRight",
662
+ "marginBottom",
663
+ "marginLeft",
664
+ "fontSize",
665
+ "lineHeight",
666
+ "borderWidth",
667
+ "borderRadius"
668
+ ]);
669
+ var pixelValue = /^(-?(?:\d+(?:\.\d+)?|\.\d+))px$/;
670
+ var svgNumber = "[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?";
671
+ var svgViewBox = new RegExp(
672
+ `^\\s*(${svgNumber})[\\s,]+(${svgNumber})[\\s,]+(${svgNumber})[\\s,]+(${svgNumber})\\s*$`
673
+ );
674
+ var ContentCompileError = class extends dragAny.DragContentError {
675
+ constructor(cardId, code, nodePath) {
676
+ super(code, nodePath);
677
+ __publicField(this, "cardId", cardId);
678
+ this.name = "ContentCompileError";
679
+ this.message = `\u5361\u7247 ${JSON.stringify(cardId)} \u5185\u5BB9\u9519\u8BEF\uFF08${code}\uFF09\u4F4D\u4E8E ${nodePath}`;
680
+ }
681
+ };
682
+ function checkProps(props, allowed, path) {
683
+ for (const key of Object.keys(props)) {
684
+ if (!allowed.includes(key))
685
+ throw new dragAny.DragContentError("unsupported-property", `${path}.${key}`);
686
+ }
687
+ }
688
+ function mapStyle(props) {
689
+ const { style, width, height } = props;
690
+ if (style === void 0 && width === void 0 && height === void 0)
691
+ return void 0;
692
+ if (style !== void 0 && (typeof style !== "object" || style === null || ![Object.prototype, null].includes(Object.getPrototypeOf(style)))) {
693
+ return style;
694
+ }
695
+ const mapped = /* @__PURE__ */ Object.create(null);
696
+ if (width !== void 0) mapped.width = width;
697
+ if (height !== void 0) mapped.height = height;
698
+ const descriptors = {
699
+ ...Object.getOwnPropertyDescriptors(mapped),
700
+ ...style === void 0 ? {} : Object.getOwnPropertyDescriptors(style)
701
+ };
702
+ for (const key of pixelStyles) {
703
+ const descriptor = descriptors[key];
704
+ if (typeof descriptor?.value !== "string") continue;
705
+ const match = pixelValue.exec(descriptor.value);
706
+ if (match) descriptor.value = Number(match[1]);
707
+ }
708
+ return Object.defineProperties({}, descriptors);
709
+ }
710
+ function textOnly(input, path, depth) {
711
+ if (depth > 100) throw new dragAny.DragContentError("max-depth", path);
712
+ if (input == null || typeof input === "boolean") return "";
713
+ if (typeof input === "string" || typeof input === "number" && Number.isFinite(input))
714
+ return String(input);
715
+ if (Array.isArray(input)) {
716
+ return input.map((item, index) => textOnly(item, `${path}[${index}]`, depth + 1)).join("");
717
+ }
718
+ if (react.isValidElement(input) && input.type === react.Fragment) {
719
+ checkProps(input.props, ["children"], path);
720
+ return textOnly(input.props.children, path, depth + 1);
721
+ }
722
+ throw new dragAny.DragContentError("invalid-value", path);
723
+ }
724
+ function iconProps(props, path) {
725
+ const childPath = `${path}.children[0]`;
726
+ const child = props.children;
727
+ if (!react.isValidElement(child) || child.type !== "path") {
728
+ throw new dragAny.DragContentError("invalid-value", childPath);
729
+ }
730
+ checkProps(child.props, ["d"], childPath);
731
+ const result = { path: child.props.d };
732
+ if (props.viewBox === void 0) return result;
733
+ const match = typeof props.viewBox === "string" && svgViewBox.exec(props.viewBox);
734
+ if (!match || match.slice(1).some((number) => !Number.isFinite(Number(number))) || Number(match[3]) <= 0 || Number(match[4]) <= 0) {
735
+ throw new dragAny.DragContentError("invalid-value", `${path}.viewBox`);
736
+ }
737
+ return { ...result, viewBox: props.viewBox };
738
+ }
739
+ function compileJSX(input, context) {
740
+ const compiled = reactCanvasUi.compileUIJSX(input, {
741
+ owner: context.ownerKey ?? context.cardId,
742
+ onDiagnostic: context.onDiagnostic
743
+ });
744
+ if (compiled) return compiled;
745
+ const handlers = /* @__PURE__ */ new Map();
746
+ const namespace = [context.boardId, context.cardId, context.contentVersion];
747
+ const ancestors = /* @__PURE__ */ new Set();
748
+ let visited = 0;
749
+ function visit(value, nodes, parentPath, stablePath, slot, depth, root = false) {
750
+ const path = root ? parentPath : `${parentPath}.children[${nodes.length}]`;
751
+ if (depth > 100) throw new dragAny.DragContentError("max-depth", path);
752
+ if (++visited > 1e4) throw new dragAny.DragContentError("max-nodes", path);
753
+ if (value == null || typeof value === "boolean") return;
754
+ if (typeof value === "string" || typeof value === "number" && Number.isFinite(value)) {
755
+ nodes.push({ kind: "text", text: String(value) });
756
+ return;
757
+ }
758
+ if (Array.isArray(value)) {
759
+ if (ancestors.has(value)) throw new dragAny.DragContentError("cycle", path);
760
+ ancestors.add(value);
761
+ const prefix = [...stablePath, slot];
762
+ value.forEach(
763
+ (child, index) => visit(child, nodes, parentPath, prefix, String(index), depth + 1)
764
+ );
765
+ ancestors.delete(value);
766
+ return;
767
+ }
768
+ if (!react.isValidElement(value))
769
+ throw new dragAny.DragContentError("invalid-value", path);
770
+ const { type, props, key } = value;
771
+ const nodePath = [...stablePath, key === null ? slot : `key:${key}`];
772
+ if (type === react.Fragment) {
773
+ checkProps(props, ["children"], path);
774
+ visit(
775
+ props.children,
776
+ nodes,
777
+ parentPath,
778
+ nodePath,
779
+ "fragment",
780
+ depth + 1,
781
+ root && !Array.isArray(props.children)
782
+ );
783
+ return;
784
+ }
785
+ const keyed = key === null ? {} : { key };
786
+ const actions = () => {
787
+ if (props.onClick === void 0) return {};
788
+ if (typeof props.onClick !== "function")
789
+ throw new dragAny.DragContentError("invalid-value", `${path}.onClick`);
790
+ const click = `jsx:${JSON.stringify([...namespace, nodePath])}`;
791
+ if (handlers.has(click))
792
+ throw new dragAny.DragContentError("invalid-value", `${path}.key`);
793
+ handlers.set(click, props.onClick);
794
+ return { actions: { click } };
795
+ };
796
+ const decorated = () => {
797
+ const style = mapStyle(props);
798
+ return {
799
+ ...keyed,
800
+ ...style === void 0 ? {} : { style },
801
+ ...actions()
802
+ };
803
+ };
804
+ const common = ["style", "onClick"];
805
+ switch (type) {
806
+ case "div":
807
+ case "span": {
808
+ checkProps(props, [...common, "children"], path);
809
+ const children = [];
810
+ visit(props.children, children, path, nodePath, "children", depth + 1);
811
+ nodes.push({ kind: "element", tag: type, ...decorated(), children });
812
+ return;
813
+ }
814
+ case "br":
815
+ checkProps(props, [], path);
816
+ nodes.push({ kind: "break", ...keyed });
817
+ return;
818
+ case "img": {
819
+ checkProps(props, [...common, "src", "alt", "width", "height"], path);
820
+ const { src, alt } = props;
821
+ nodes.push({
822
+ kind: "leaf",
823
+ leafType: "image",
824
+ ...decorated(),
825
+ props: {
826
+ src,
827
+ ...alt === void 0 ? {} : { alt }
828
+ }
829
+ });
830
+ return;
831
+ }
832
+ case "button": {
833
+ checkProps(props, [...common, "children", "disabled", "type"], path);
834
+ const { disabled } = props;
835
+ if (props.type !== void 0 && props.type !== "button") {
836
+ throw new dragAny.DragContentError("invalid-value", `${path}.type`);
837
+ }
838
+ nodes.push({
839
+ kind: "leaf",
840
+ leafType: "button",
841
+ ...decorated(),
842
+ props: {
843
+ text: textOnly(props.children, `${path}.children`, depth + 1),
844
+ ...disabled === void 0 ? {} : { disabled }
845
+ }
846
+ });
847
+ return;
848
+ }
849
+ case "input": {
850
+ checkProps(
851
+ props,
852
+ [...common, "type", "checked", "disabled", "aria-label"],
853
+ path
854
+ );
855
+ if (props.type !== "checkbox")
856
+ throw new dragAny.DragContentError("invalid-value", `${path}.type`);
857
+ const { checked, disabled, "aria-label": label } = props;
858
+ nodes.push({
859
+ kind: "leaf",
860
+ leafType: "checkbox",
861
+ ...decorated(),
862
+ props: {
863
+ checked: checked === void 0 ? false : checked,
864
+ ...disabled === void 0 ? {} : { disabled },
865
+ ...label === void 0 ? {} : { label }
866
+ }
867
+ });
868
+ return;
869
+ }
870
+ case "progress": {
871
+ checkProps(
872
+ props,
873
+ [...common, "value", "max", "children", "aria-label"],
874
+ path
875
+ );
876
+ const { max, "aria-label": ariaLabel } = props;
877
+ const childLabel = props.children == null ? void 0 : textOnly(props.children, `${path}.children`, depth + 1);
878
+ const label = ariaLabel ?? childLabel;
879
+ nodes.push({
880
+ kind: "leaf",
881
+ leafType: "progress",
882
+ ...decorated(),
883
+ props: {
884
+ value: props.value,
885
+ ...max === void 0 ? {} : { max },
886
+ ...label === void 0 ? {} : { label }
887
+ }
888
+ });
889
+ return;
890
+ }
891
+ case "svg":
892
+ checkProps(
893
+ props,
894
+ [...common, "children", "viewBox", "width", "height"],
895
+ path
896
+ );
897
+ nodes.push({
898
+ kind: "leaf",
899
+ leafType: "icon",
900
+ ...decorated(),
901
+ props: iconProps(props, path)
902
+ });
903
+ return;
904
+ default:
905
+ throw new dragAny.DragContentError("invalid-value", path);
906
+ }
907
+ }
908
+ try {
909
+ const nodes = [];
910
+ visit(input, nodes, "$.root", [], "root", 1, true);
911
+ const root = nodes.length === 0 ? { kind: "text", text: "" } : nodes.length === 1 ? nodes[0] : { kind: "element", tag: "div", children: nodes };
912
+ const document2 = dragAny.normalizeContent({
913
+ type: "drag-content",
914
+ version: 1,
915
+ root
916
+ });
917
+ return { document: document2, handlers, dispose: () => handlers.clear() };
918
+ } catch (error) {
919
+ if (error instanceof dragAny.DragContentError) {
920
+ throw new ContentCompileError(
921
+ context.cardId ?? context.ownerKey ?? "content",
922
+ error.code,
923
+ error.nodePath
924
+ );
925
+ }
926
+ throw error;
927
+ }
928
+ }
929
+
930
+ // src/content-bindings.ts
931
+ var emptyHandlers = /* @__PURE__ */ new Map();
932
+ function compileInput(input, context) {
933
+ if (input === null || typeof input === "string" || typeof input === "number" || typeof input === "object" && Object.prototype.hasOwnProperty.call(input, "type") && !Object.prototype.hasOwnProperty.call(input, "$$typeof")) {
934
+ try {
935
+ return {
936
+ document: dragAny.normalizeContent(input),
937
+ handlers: emptyHandlers,
938
+ dispose() {
939
+ }
940
+ };
941
+ } catch (error) {
942
+ if (error instanceof dragAny.DragContentError) {
943
+ throw new ContentCompileError(
944
+ context.cardId ?? context.ownerKey ?? "content",
945
+ error.code,
946
+ error.nodePath
947
+ );
948
+ }
949
+ throw error;
950
+ }
951
+ }
952
+ return compileJSX(input, context);
953
+ }
954
+ function createContentBindings() {
955
+ let preparedBindings = /* @__PURE__ */ new WeakMap();
956
+ const active = /* @__PURE__ */ new Map();
957
+ const latest = /* @__PURE__ */ new Map();
958
+ let sequence = 0;
959
+ let destroyed = false;
960
+ function release(prepared) {
961
+ const binding = preparedBindings.get(prepared);
962
+ if (!binding) return;
963
+ if (active.get(binding.ownerKey) === prepared)
964
+ active.delete(binding.ownerKey);
965
+ preparedBindings.delete(prepared);
966
+ binding.content.dispose();
967
+ }
968
+ return {
969
+ prepare(input, context) {
970
+ const ownerKey = context.ownerKey ?? context.cardId;
971
+ const previous = active.get(ownerKey);
972
+ const binding = previous && preparedBindings.get(previous);
973
+ const reuse = react.isValidElement(input) && binding?.staticInput === input && binding.version === context.contentVersion;
974
+ const content = reuse ? {
975
+ document: binding.content.document,
976
+ handlers: emptyHandlers,
977
+ dispose() {
978
+ }
979
+ } : compileInput(input, context);
980
+ const isStatic = react.isValidElement(input) && !content.handlers.size && !("runtimeBindings" in content && content.runtimeBindings);
981
+ const prepared = {
982
+ layoutKey: isStatic ? content.document : void 0,
983
+ document: content.document,
984
+ get handlers() {
985
+ return preparedBindings.get(prepared)?.content.handlers ?? emptyHandlers;
986
+ },
987
+ dispose: () => release(prepared)
988
+ };
989
+ if (destroyed) content.dispose();
990
+ else
991
+ preparedBindings.set(prepared, {
992
+ ownerKey,
993
+ staticInput: isStatic ? input : void 0,
994
+ version: context.contentVersion,
995
+ context: context.renderContext,
996
+ order: ++sequence,
997
+ content
998
+ });
999
+ return prepared;
1000
+ },
1001
+ commit(prepared) {
1002
+ const binding = preparedBindings.get(prepared);
1003
+ if (!binding) return;
1004
+ const { ownerKey, order } = binding;
1005
+ if (order < (latest.get(ownerKey) ?? 0)) {
1006
+ release(prepared);
1007
+ return;
1008
+ }
1009
+ const previous = active.get(ownerKey);
1010
+ if (previous && previous !== prepared) release(previous);
1011
+ latest.set(ownerKey, order);
1012
+ active.set(ownerKey, prepared);
1013
+ },
1014
+ dispatch(action) {
1015
+ const { actionId } = action;
1016
+ const key = "target" in action ? dragAny.contentOwnerKey(action.target) : action.cardId;
1017
+ const prepared = active.get(key);
1018
+ const handler = prepared?.handlers.get(actionId);
1019
+ if (!handler) return false;
1020
+ if (!("target" in action)) handler();
1021
+ else handler(action, preparedBindings.get(prepared)?.context);
1022
+ return true;
1023
+ },
1024
+ release,
1025
+ destroy() {
1026
+ for (const prepared of active.values()) release(prepared);
1027
+ preparedBindings = /* @__PURE__ */ new WeakMap();
1028
+ latest.clear();
1029
+ destroyed = true;
1030
+ }
1031
+ };
1032
+ }
1033
+ function useCommitted(value) {
1034
+ const ref = react.useRef(value);
1035
+ react.useInsertionEffect(() => {
1036
+ ref.current = value;
1037
+ }, [value]);
1038
+ return ref;
1039
+ }
1040
+
1041
+ // src/hooks/use-drag-any.ts
1042
+ function shallowEqual(left, right) {
1043
+ if (left === right) return true;
1044
+ if (!left || !right) return false;
1045
+ const a = Object.entries(left);
1046
+ const b = right;
1047
+ return a.length === Object.keys(b).length && a.every(([key, value]) => Object.is(value, b[key]));
1048
+ }
1049
+ function sameScrollbar(left, right) {
1050
+ if (left === right) return true;
1051
+ if (!left || !right) return false;
1052
+ const { horizontal: leftX, vertical: leftY, ...leftCommon } = left;
1053
+ const { horizontal: rightX, vertical: rightY, ...rightCommon } = right;
1054
+ return shallowEqual(leftCommon, rightCommon) && (leftX === rightX || !!leftX && !!rightX && shallowEqual(leftX, rightX)) && (leftY === rightY || !!leftY && !!rightY && shallowEqual(leftY, rightY));
1055
+ }
1056
+ function createContent(bindings, {
1057
+ id,
1058
+ renderCard,
1059
+ render: renderer,
1060
+ renderVersion: version
1061
+ }) {
1062
+ function read(context) {
1063
+ return propsRender(context);
1064
+ }
1065
+ function propsRender(context) {
1066
+ const result = renderer?.(context);
1067
+ if (result !== void 0) return result;
1068
+ return context.target.kind === "card" && "card" in context ? renderCard ? renderCard(context) : context.card.id : context.target.kind === "corner" ? null : "id" in context.target ? context.target.id : null;
1069
+ }
1070
+ function compileContext(context) {
1071
+ return {
1072
+ boardId: id,
1073
+ ownerKey: dragAny.contentOwnerKey(context.target),
1074
+ target: context.target,
1075
+ cardId: context.target.kind === "card" ? context.target.cardId : void 0,
1076
+ contentVersion: version ?? ("card" in context ? context.card.contentVersion : void 0),
1077
+ renderContext: context
1078
+ };
1079
+ }
1080
+ return {
1081
+ contentRuntime: {
1082
+ createSnapshot(context) {
1083
+ const full = {
1084
+ ...context,
1085
+ target: {
1086
+ kind: "card",
1087
+ cardId: context.card.id,
1088
+ containerId: context.container.id
1089
+ }
1090
+ };
1091
+ const prepared = compileInput(read(full), compileContext(full));
1092
+ return {
1093
+ content: prepared.document,
1094
+ dispose: () => prepared.dispose()
1095
+ };
1096
+ },
1097
+ createRegion(context) {
1098
+ const prepared = bindings.prepare(
1099
+ read(context),
1100
+ compileContext(context)
1101
+ );
1102
+ bindings.commit(prepared);
1103
+ return {
1104
+ layoutKey: prepared.layoutKey,
1105
+ content: prepared.document,
1106
+ dispose: () => bindings.release(prepared)
1107
+ };
1108
+ },
1109
+ create(context) {
1110
+ const full = {
1111
+ ...context,
1112
+ target: {
1113
+ kind: "card",
1114
+ cardId: context.card.id,
1115
+ containerId: context.container.id
1116
+ }
1117
+ };
1118
+ const prepared = bindings.prepare(read(full), compileContext(full));
1119
+ bindings.commit(prepared);
1120
+ return {
1121
+ content: prepared.document,
1122
+ dispose: () => bindings.release(prepared)
1123
+ };
1124
+ }
1125
+ },
1126
+ renderCard(context) {
1127
+ const full = {
1128
+ ...context,
1129
+ target: {
1130
+ kind: "card",
1131
+ cardId: context.card.id,
1132
+ containerId: context.container.id
1133
+ }
1134
+ };
1135
+ const compiled = compileInput(read(full), compileContext(full));
1136
+ compiled.dispose();
1137
+ return compiled.document;
1138
+ }
1139
+ };
1140
+ }
1141
+ function useDragAny(props, owner, group, events) {
1142
+ if (group && (props.model !== void 0 || props.acknowledgedTransactionId !== void 0 || props.onMoveRequest !== void 0)) {
1143
+ throw new Error("\u753B\u5E03\u7EC4\u6210\u5458\u5FC5\u987B\u7531\u4E0A\u5C42\u753B\u5E03\u7EC4\u63D0\u4F9B\u6A21\u578B\u548C\u79FB\u52A8\u56DE\u8C03");
1144
+ }
1145
+ const latest = useCommitted(props);
1146
+ const handlers = useCommitted(events);
1147
+ const instance = react.useRef();
1148
+ function optionsFor(current, content, scrollbar, bridge2) {
1149
+ return {
1150
+ ...content,
1151
+ scrollbar,
1152
+ layout: current.layout,
1153
+ renderVersion: current.renderVersion,
1154
+ animation: current.animation,
1155
+ annotations: current.annotations,
1156
+ input: current.input,
1157
+ contentScroll: current.contentScroll,
1158
+ contextMenu: current.contextMenu,
1159
+ theme: current.theme,
1160
+ selectedCardIds: current.selectedCardIds,
1161
+ ...bridge2,
1162
+ onMoveRequest: current.onMoveRequest ? bridge2.onMoveRequest : void 0,
1163
+ canDrag: current.canDrag ? bridge2.canDrag : void 0,
1164
+ canDrop: current.canDrop ? bridge2.canDrop : void 0
1165
+ };
1166
+ }
1167
+ const bridgeRef = react.useRef();
1168
+ if (!bridgeRef.current) {
1169
+ bridgeRef.current = {
1170
+ onMoveRequest: (proposal) => latest.current.onMoveRequest?.(proposal),
1171
+ onDragCancel: (reason) => latest.current.onDragCancel?.(reason),
1172
+ onDragEnd: () => latest.current.onDragEnd?.(),
1173
+ onDragTargetChange: (target, verdict) => latest.current.onDragTargetChange?.(target, verdict),
1174
+ onSelectionChange: (cardIds) => latest.current.onSelectionChange?.(cardIds),
1175
+ onError: (error) => latest.current.onError?.(error),
1176
+ onContentError: (event) => latest.current.onContentError?.(event),
1177
+ onContextMenuRequest: (request) => handlers.current.onContextMenuRequest?.(request),
1178
+ onDragStart: (context) => handlers.current.onDragStart?.(context),
1179
+ onRegionContentAction: (action) => {
1180
+ instance.current?.bindings.dispatch(action);
1181
+ if (!action.nativeEvent.cancelBubble) {
1182
+ if (latest.current.onRegionContentAction)
1183
+ latest.current.onRegionContentAction(action);
1184
+ else if (action.target.kind === "card")
1185
+ latest.current.onContentAction?.({
1186
+ ...action,
1187
+ cardId: action.target.cardId,
1188
+ containerId: action.target.containerId
1189
+ });
1190
+ }
1191
+ },
1192
+ onContentAction: (action) => {
1193
+ if (!action.nativeEvent.cancelBubble)
1194
+ latest.current.onContentAction?.(action);
1195
+ },
1196
+ canDrag: (context) => latest.current.canDrag?.(context) ?? true,
1197
+ canDrop: (context) => latest.current.canDrop?.(context) ?? { allowed: true }
1198
+ };
1199
+ }
1200
+ const bridge = bridgeRef.current;
1201
+ react.useLayoutEffect(() => {
1202
+ function mount() {
1203
+ const host = owner.current;
1204
+ const current = latest.current;
1205
+ const model = group ? group.getModel(current.id) : current.model;
1206
+ if (!model) {
1207
+ if (group) return;
1208
+ throw new Error("\u72EC\u7ACB\u753B\u5E03\u5FC5\u987B\u63D0\u4F9B\u6A21\u578B");
1209
+ }
1210
+ const bindings = createContentBindings();
1211
+ const content = createContent(bindings, current);
1212
+ const scrollbar = readScrollbarSettings(current.storageKey, host) ?? current.scrollbar;
1213
+ const options = optionsFor(current, content, scrollbar, bridge);
1214
+ const board = dragAny.dragAnyProjection.create({
1215
+ ...options,
1216
+ id: current.id,
1217
+ model
1218
+ });
1219
+ if (group && !group.ensureGroup().register(board)) {
1220
+ board.destroy();
1221
+ bindings.destroy();
1222
+ return;
1223
+ }
1224
+ const view = host.ownerDocument.defaultView;
1225
+ let frame;
1226
+ let suspended = false;
1227
+ function updateVisibility() {
1228
+ const hidden = latest.current.active === false || !host.clientWidth || !host.clientHeight;
1229
+ if (hidden === suspended) return;
1230
+ suspended = hidden;
1231
+ if (hidden) {
1232
+ board.suspend();
1233
+ handlers.current.onContextMenuRequest?.(null);
1234
+ } else {
1235
+ board.resume();
1236
+ }
1237
+ }
1238
+ function queueVisibility() {
1239
+ frame ?? (frame = view.requestAnimationFrame(() => {
1240
+ frame = void 0;
1241
+ updateVisibility();
1242
+ }));
1243
+ }
1244
+ instance.current = {
1245
+ board,
1246
+ bindings,
1247
+ props: current,
1248
+ content,
1249
+ options,
1250
+ scrollbar,
1251
+ updateVisibility
1252
+ };
1253
+ board.mount(host);
1254
+ updateVisibility();
1255
+ const observer = view.ResizeObserver ? new view.ResizeObserver(queueVisibility) : void 0;
1256
+ observer?.observe(host);
1257
+ view.addEventListener("resize", queueVisibility);
1258
+ return () => {
1259
+ instance.current = void 0;
1260
+ if (frame !== void 0) view.cancelAnimationFrame(frame);
1261
+ view.removeEventListener("resize", queueVisibility);
1262
+ observer?.disconnect();
1263
+ board.destroy();
1264
+ bindings.destroy();
1265
+ };
1266
+ }
1267
+ let dispose = mount();
1268
+ const unsubscribe = group?.subscribe(() => {
1269
+ if (group.getModel(props.id)) {
1270
+ dispose ?? (dispose = mount());
1271
+ } else if (dispose) {
1272
+ const cleanup = dispose;
1273
+ dispose = void 0;
1274
+ cleanup();
1275
+ handlers.current.onContextMenuRequest?.(null);
1276
+ }
1277
+ });
1278
+ return () => {
1279
+ unsubscribe?.();
1280
+ dispose?.();
1281
+ };
1282
+ }, [bridge, group, handlers, latest, owner, props.id]);
1283
+ react.useLayoutEffect(() => {
1284
+ const current = instance.current;
1285
+ if (!current) return;
1286
+ const previous = current.props;
1287
+ current.props = props;
1288
+ if (previous.storageKey !== props.storageKey) {
1289
+ current.scrollbar = readScrollbarSettings(props.storageKey, owner.current) ?? props.scrollbar;
1290
+ } else if (!sameScrollbar(previous.scrollbar, props.scrollbar)) {
1291
+ current.scrollbar = props.scrollbar;
1292
+ }
1293
+ if (previous.renderCard !== props.renderCard || previous.render !== props.render || previous.renderVersion !== props.renderVersion)
1294
+ current.content = createContent(current.bindings, props);
1295
+ if (!group && props.model && (previous.model !== props.model || previous.acknowledgedTransactionId !== props.acknowledgedTransactionId)) {
1296
+ dragAny.dragAnyProjection.update(current.board, props.model, {
1297
+ transactionId: props.acknowledgedTransactionId,
1298
+ layout: props.model.documentKind ? props.layout : void 0
1299
+ });
1300
+ }
1301
+ const options = optionsFor(
1302
+ props,
1303
+ current.content,
1304
+ current.scrollbar,
1305
+ bridge
1306
+ );
1307
+ if (previous.canDrag !== props.canDrag || Object.keys(options).some(
1308
+ (key) => options[key] !== current.options[key]
1309
+ )) {
1310
+ current.options = options;
1311
+ dragAny.dragAnyProjection.configure(current.board, options);
1312
+ }
1313
+ if (previous.active !== props.active) current.updateVisibility();
1314
+ });
1315
+ return instance;
1316
+ }
1317
+ function declaration(name) {
1318
+ throw new Error(name + " \u987B\u58F0\u660E\u5728 ReactDragAny \u5185");
1319
+ }
1320
+ function Lanes(_props) {
1321
+ return declaration("Lanes");
1322
+ }
1323
+ function Lane(_props) {
1324
+ return declaration("Lane");
1325
+ }
1326
+ function SparseGrid(_props) {
1327
+ return declaration("SparseGrid");
1328
+ }
1329
+ function GridSlot(_props) {
1330
+ return declaration("GridSlot");
1331
+ }
1332
+ function Queue(_props) {
1333
+ return declaration("Queue");
1334
+ }
1335
+ function Flow(_props) {
1336
+ return declaration("Flow");
1337
+ }
1338
+ function Card(_props) {
1339
+ return declaration("Card");
1340
+ }
1341
+ function readStructureElements(input, path, depth = 0) {
1342
+ if (depth > 100) throw new dragAny.DragDocumentError(path, "\u7ED3\u6784\u5D4C\u5957\u8FC7\u6DF1");
1343
+ if (input == null || typeof input === "boolean") return [];
1344
+ if (Array.isArray(input))
1345
+ return input.flatMap(
1346
+ (item, i) => readStructureElements(item, `${path}[${i}]`, depth + 1)
1347
+ );
1348
+ if (!react.isValidElement(input))
1349
+ throw new dragAny.DragDocumentError(path, "\u987B\u4E3A\u753B\u5E03\u7ED3\u6784\u58F0\u660E");
1350
+ if (input.type === react.Fragment)
1351
+ return readStructureElements(
1352
+ input.props.children,
1353
+ path,
1354
+ depth + 1
1355
+ );
1356
+ return [input];
1357
+ }
1358
+ function readCollection(props, name, path, type, read) {
1359
+ if (props[name] !== void 0) {
1360
+ if (props.children !== void 0)
1361
+ throw new dragAny.DragDocumentError(path, `${name} \u4E0E children \u4E92\u65A5`);
1362
+ return props[name];
1363
+ }
1364
+ return readStructureElements(
1365
+ props.children,
1366
+ path + ".children"
1367
+ ).map((node, index) => {
1368
+ const at = `${path}.children[${index}]`;
1369
+ if (node.type !== type) throw new dragAny.DragDocumentError(at, "\u7ED3\u6784\u5D4C\u5957\u4E0D\u5408\u6CD5");
1370
+ return read(node.props, at);
1371
+ });
1372
+ }
1373
+ function readCard({ children, ...props }, path) {
1374
+ if (children !== void 0 && props.content !== void 0)
1375
+ throw new dragAny.DragDocumentError(path, "content \u4E0E children \u4E92\u65A5");
1376
+ return children === void 0 ? props : { ...props, content: children };
1377
+ }
1378
+ function readContainer(props, path) {
1379
+ const cards = readCollection(props, "cards", path, Card, readCard);
1380
+ const { children: _children, ...data } = props;
1381
+ return { ...data, cards };
1382
+ }
1383
+ function compileDragStructure(children) {
1384
+ const roots = readStructureElements(children, "$");
1385
+ if (roots.length !== 1) throw new dragAny.DragDocumentError("$", "\u987B\u6709\u4E00\u4E2A\u5E03\u5C40\u6839");
1386
+ const [{ type, props }] = roots;
1387
+ const { children: _children, ...data } = props;
1388
+ if (type === Lanes)
1389
+ return {
1390
+ ...data,
1391
+ type: "lanes",
1392
+ lanes: readCollection(props, "lanes", "$", Lane, readContainer)
1393
+ };
1394
+ if (type === SparseGrid)
1395
+ return {
1396
+ ...data,
1397
+ type: "sparse-grid",
1398
+ slots: readCollection(props, "slots", "$", GridSlot, readContainer)
1399
+ };
1400
+ if (type === Queue || type === Flow)
1401
+ return {
1402
+ ...readContainer(props, "$"),
1403
+ type: type === Queue ? "queue" : "flow"
1404
+ };
1405
+ throw new dragAny.DragDocumentError("$", "\u65E0\u6548\u7684\u5E03\u5C40\u6839");
1406
+ }
1407
+
1408
+ // src/components/compile-ui-structure.ts
1409
+ var pixelValue2 = /^(-?(?:\d+(?:\.\d+)?|\.\d+))px$/;
1410
+ var contentTags = new Set(Object.values(reactCanvasUi.UI));
1411
+ function readPixels(value, path, allowZero = false) {
1412
+ if (value === void 0) return void 0;
1413
+ const match = typeof value === "string" ? pixelValue2.exec(value) : null;
1414
+ const pixels = match ? Number(match[1]) : value;
1415
+ if (typeof pixels !== "number" || !Number.isFinite(pixels) || (allowZero ? pixels < 0 : pixels <= 0))
1416
+ throw new dragAny.DragDocumentError(
1417
+ path,
1418
+ allowZero ? "\u987B\u4E3A\u975E\u8D1F\u50CF\u7D20\u503C" : "\u987B\u4E3A\u6B63\u50CF\u7D20\u503C"
1419
+ );
1420
+ return pixels;
1421
+ }
1422
+ function readStyle(node, path) {
1423
+ const { style } = node.props;
1424
+ if (style === void 0) return {};
1425
+ if (style === null || typeof style !== "object" || Array.isArray(style))
1426
+ throw new dragAny.DragDocumentError(path + ".style", "\u987B\u4E3A Canvas UI \u6837\u5F0F");
1427
+ return style;
1428
+ }
1429
+ function readContainer2(node, path, axis, dimensions) {
1430
+ const style = readStyle(node, path);
1431
+ const fixedAxis = node.type === reactCanvasUi.UI.Col ? "column" : node.type === reactCanvasUi.UI.Row ? "row" : void 0;
1432
+ const direction = fixedAxis ?? (node.type === reactCanvasUi.UI.Flex ? style.flexDirection ?? node.props.direction ?? "row" : void 0);
1433
+ if (direction !== axis)
1434
+ throw new dragAny.DragDocumentError(
1435
+ path,
1436
+ axis === "row" ? "\u987B\u4F7F\u7528\u6A2A\u5411 Canvas UI \u5BB9\u5668" : "\u987B\u4F7F\u7528\u7EB5\u5411 Canvas UI \u5BB9\u5668"
1437
+ );
1438
+ const fixedStyle = {
1439
+ ...fixedAxis ? {} : { flexDirection: axis },
1440
+ display: "flex",
1441
+ flexWrap: "nowrap",
1442
+ alignItems: "stretch",
1443
+ justifyContent: "flex-start",
1444
+ ...Object.fromEntries(dimensions.map((name) => [name, style[name]]))
1445
+ };
1446
+ for (const [name, value] of Object.entries(style)) {
1447
+ if (value !== void 0 && (!Object.prototype.hasOwnProperty.call(fixedStyle, name) || fixedStyle[name] !== value))
1448
+ throw new dragAny.DragDocumentError(
1449
+ `${path}.style.${name}`,
1450
+ "\u5F53\u524D\u62D6\u62FD\u5E03\u5C40\u65E0\u6CD5\u6295\u5F71\u6B64\u6837\u5F0F"
1451
+ );
1452
+ }
1453
+ const fixedProps = {
1454
+ children: node.props.children,
1455
+ style: node.props.style,
1456
+ visible: true,
1457
+ ...dimensions.includes("gap") ? { gap: node.props.gap } : {},
1458
+ ...fixedAxis ? {} : { direction: axis },
1459
+ align: "stretch",
1460
+ justify: "flex-start"
1461
+ };
1462
+ for (const [name, value] of Object.entries(node.props)) {
1463
+ if (value !== void 0 && (!Object.prototype.hasOwnProperty.call(fixedProps, name) || fixedProps[name] !== value))
1464
+ throw new dragAny.DragDocumentError(
1465
+ `${path}.${name}`,
1466
+ "\u5F53\u524D\u62D6\u62FD\u5E03\u5C40\u65E0\u6CD5\u6295\u5F71\u6B64\u5C5E\u6027"
1467
+ );
1468
+ }
1469
+ if (dimensions.includes("flex") && style.flex !== void 0 && style.flex !== 1)
1470
+ throw new dragAny.DragDocumentError(path + ".style.flex", "\u5361\u7247\u7EC4\u4EC5\u652F\u6301 flex: 1");
1471
+ return style;
1472
+ }
1473
+ function readGap(node, style, path) {
1474
+ return style.gap === void 0 ? readPixels(node.props.gap, path + ".gap", true) : readPixels(style.gap, path + ".style.gap", true);
1475
+ }
1476
+ function readContent(node, path, dimension) {
1477
+ if (!contentTags.has(node.type))
1478
+ throw new dragAny.DragDocumentError(path, "\u5361\u7247\u548C\u6807\u9898\u987B\u4F7F\u7528 Canvas UI JSX");
1479
+ const style = readStyle(node, path);
1480
+ const size = readPixels(style[dimension], `${path}.style.${dimension}`);
1481
+ if (style.flexShrink !== void 0 && style.flexShrink !== 0)
1482
+ throw new dragAny.DragDocumentError(
1483
+ path + ".style.flexShrink",
1484
+ "\u5361\u7247\u548C\u6807\u9898\u4EC5\u652F\u6301 flexShrink: 0"
1485
+ );
1486
+ let content = node;
1487
+ if (size !== void 0 || style.flexShrink !== void 0) {
1488
+ const { [dimension]: _size, flexShrink: _shrink, ...contentStyle } = style;
1489
+ content = react.cloneElement(node, { style: contentStyle });
1490
+ }
1491
+ return { size, content };
1492
+ }
1493
+ function sharedPixels(description) {
1494
+ let current;
1495
+ return {
1496
+ read() {
1497
+ return current;
1498
+ },
1499
+ add(value, path) {
1500
+ if (value === void 0) return;
1501
+ if (current !== void 0 && current !== value)
1502
+ throw new dragAny.DragDocumentError(path, `\u6240\u6709\u6CF3\u9053\u7684${description}\u987B\u4E00\u81F4`);
1503
+ current = value;
1504
+ }
1505
+ };
1506
+ }
1507
+ function readChildren(node, path) {
1508
+ const at = path + ".children";
1509
+ return readStructureElements(node.props.children, at).map(
1510
+ (element, index) => ({ node: element, path: `${at}[${index}]` })
1511
+ );
1512
+ }
1513
+ function readId(ids, id, path) {
1514
+ if (typeof id !== "string" || id.length === 0)
1515
+ throw new dragAny.DragDocumentError(path, "\u4E1A\u52A1 ID \u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32");
1516
+ if (ids.has(id)) throw new dragAny.DragDocumentError(path, `\u4E1A\u52A1 ID \u91CD\u590D\uFF1A${id}`);
1517
+ ids.add(id);
1518
+ }
1519
+ function compileDragUIStructure(children, options) {
1520
+ const { dragLayout, getDragRole } = options;
1521
+ const roots = readStructureElements(children, "$");
1522
+ if (roots.length !== 1) throw new dragAny.DragDocumentError("$", "\u987B\u6709\u4E00\u4E2A\u5E03\u5C40\u6839");
1523
+ const root = roots[0];
1524
+ const rootStyle = readContainer2(root, "$", "column", ["gap"]);
1525
+ const rootGap = readGap(root, rootStyle, "$");
1526
+ const keys = /* @__PURE__ */ new Set();
1527
+ const cardIds = /* @__PURE__ */ new Set();
1528
+ function readRole(node, path, ...expected) {
1529
+ const key = node.key;
1530
+ if (key == null || key === "")
1531
+ throw new dragAny.DragDocumentError(path + ".key", "\u7ED3\u6784\u8282\u70B9\u987B\u58F0\u660E\u975E\u7A7A JSX key");
1532
+ if (keys.has(key))
1533
+ throw new dragAny.DragDocumentError(path + ".key", `\u7ED3\u6784\u952E\u91CD\u590D\uFF1A${key}`);
1534
+ keys.add(key);
1535
+ const role = getDragRole(key);
1536
+ if (!role || !expected.some((kind) => kind === role.kind))
1537
+ throw new dragAny.DragDocumentError(
1538
+ path,
1539
+ `\u7ED3\u6784\u8282\u70B9 ${key} \u987B\u7ED1\u5B9A\u89D2\u8272 ${expected.join(" \u6216 ")}`
1540
+ );
1541
+ return role;
1542
+ }
1543
+ function readCards(node, path, dimension) {
1544
+ return readChildren(node, path).map(({ node: card, path: at }) => {
1545
+ const role = readRole(card, at, "card");
1546
+ readId(cardIds, role.id, at);
1547
+ const { content, size } = readContent(card, at, dimension);
1548
+ return {
1549
+ id: role.id,
1550
+ data: role.data,
1551
+ content,
1552
+ ...role.disabled === void 0 ? {} : { disabled: role.disabled },
1553
+ ...size === void 0 ? {} : { size: { [dimension]: size } }
1554
+ };
1555
+ });
1556
+ }
1557
+ if (dragLayout === "queue")
1558
+ return {
1559
+ type: "queue",
1560
+ cardGap: rootGap,
1561
+ cards: readCards(root, "$", "height")
1562
+ };
1563
+ if (rootGap)
1564
+ throw new dragAny.DragDocumentError(
1565
+ rootStyle.gap === void 0 ? "$.gap" : "$.style.gap",
1566
+ "\u5F53\u524D\u5E03\u5C40\u4E0D\u652F\u6301\u6CF3\u9053\u95F4\u8DDD"
1567
+ );
1568
+ const regionIds = /* @__PURE__ */ new Set();
1569
+ const laneHeight = sharedPixels("\u9AD8\u5EA6");
1570
+ const headerWidth = sharedPixels("\u6807\u9898\u5BBD\u5EA6");
1571
+ const cardGap = sharedPixels("\u5361\u7247\u95F4\u8DDD");
1572
+ const padding = sharedPixels("\u5361\u7247\u7EC4\u5185\u8FB9\u8DDD");
1573
+ let hasHeader = false;
1574
+ const lanes = readChildren(root, "$").map(
1575
+ ({ node: lane, path }) => {
1576
+ const role = readRole(lane, path, "region");
1577
+ readId(regionIds, role.id, path);
1578
+ const laneStyle = readContainer2(lane, path, "row", ["height"]);
1579
+ const heightPath = path + ".style.height";
1580
+ laneHeight.add(readPixels(laneStyle.height, heightPath), heightPath);
1581
+ let header = null;
1582
+ let cards;
1583
+ for (const { node, path: at } of readChildren(lane, path)) {
1584
+ const childRole = readRole(node, at, "header", "items");
1585
+ if (childRole.kind === "header") {
1586
+ if (header || cards)
1587
+ throw new dragAny.DragDocumentError(
1588
+ at,
1589
+ "\u6807\u9898\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21\u4E14\u987B\u4F4D\u4E8E\u5361\u7247\u7EC4\u4E4B\u524D"
1590
+ );
1591
+ const { size, content } = readContent(node, at, "width");
1592
+ header = content;
1593
+ hasHeader = true;
1594
+ headerWidth.add(size, at + ".style.width");
1595
+ } else {
1596
+ if (cards)
1597
+ throw new dragAny.DragDocumentError(at, "\u6CF3\u9053\u987B\u6709\u4E14\u4EC5\u6709\u4E00\u4E2A\u5361\u7247\u7EC4");
1598
+ const itemsStyle = readContainer2(node, at, "row", [
1599
+ "gap",
1600
+ "flex",
1601
+ "padding"
1602
+ ]);
1603
+ cardGap.add(
1604
+ readGap(node, itemsStyle, at),
1605
+ at + (itemsStyle.gap === void 0 ? ".gap" : ".style.gap")
1606
+ );
1607
+ const paddingPath = at + ".style.padding";
1608
+ padding.add(
1609
+ readPixels(itemsStyle.padding, paddingPath, true),
1610
+ paddingPath
1611
+ );
1612
+ cards = readCards(node, at, "width");
1613
+ }
1614
+ }
1615
+ if (!cards) throw new dragAny.DragDocumentError(path, "\u6CF3\u9053\u987B\u6709\u4E00\u4E2A\u5361\u7247\u7EC4");
1616
+ return { id: role.id, dropDisabled: role.dropDisabled, header, cards };
1617
+ }
1618
+ );
1619
+ return {
1620
+ type: "lanes",
1621
+ laneHeight: laneHeight.read(),
1622
+ headerWidth: hasHeader ? headerWidth.read() : 0,
1623
+ cardGap: cardGap.read(),
1624
+ padding: padding.read(),
1625
+ lanes
1626
+ };
1627
+ }
1628
+ var DragGroupContext = react.createContext(
1629
+ null
1630
+ );
1631
+ function isEnabledAction(items, key) {
1632
+ return items.some(
1633
+ (item) => !item.disabled && (item.children?.length ? isEnabledAction(item.children, key) : item.key === key)
1634
+ );
1635
+ }
1636
+ function Board(props, ref) {
1637
+ const group = react.useContext(DragGroupContext);
1638
+ const owner = react.useRef(null);
1639
+ const [mounted, setMounted] = react.useState(false);
1640
+ const [menu, setMenu] = react.useState();
1641
+ const request = menu?.request;
1642
+ const [dialog, setDialog] = react.useState();
1643
+ const menuOpen = react.useRef(false);
1644
+ function closeMenu() {
1645
+ if (!menuOpen.current) return;
1646
+ menuOpen.current = false;
1647
+ setMenu(void 0);
1648
+ }
1649
+ const instance = useDragAny(props, owner, group, {
1650
+ onContextMenuRequest(next) {
1651
+ if (next && isTargetValid(next)) {
1652
+ const nextItems = menuItems(next);
1653
+ menuOpen.current = nextItems.length > 0;
1654
+ setMenu(
1655
+ menuOpen.current ? { request: next, items: nextItems } : void 0
1656
+ );
1657
+ } else {
1658
+ closeMenu();
1659
+ }
1660
+ props.onContextMenuRequest?.(next);
1661
+ },
1662
+ onDragStart(context) {
1663
+ closeMenu();
1664
+ props.onDragStart?.(context);
1665
+ }
1666
+ });
1667
+ react.useLayoutEffect(() => {
1668
+ setMounted(true);
1669
+ }, []);
1670
+ react.useImperativeHandle(props.rootRef, () => owner.current, []);
1671
+ react.useImperativeHandle(
1672
+ ref,
1673
+ () => ({
1674
+ scrollTo(target) {
1675
+ return instance.current?.board.scrollTo(target) ?? false;
1676
+ },
1677
+ focusCard(cardId) {
1678
+ return instance.current?.board.focusCard(cardId) ?? false;
1679
+ },
1680
+ cancelDrag(reason) {
1681
+ instance.current?.board.cancelDrag(reason);
1682
+ },
1683
+ rejectMove(transactionId, reason) {
1684
+ const board = instance.current?.board;
1685
+ return board ? (group?.ensureGroup() ?? board).rejectMove(transactionId, reason) : false;
1686
+ },
1687
+ getSnapshot: () => instance.current?.board.getSnapshot()
1688
+ }),
1689
+ [group, instance]
1690
+ );
1691
+ function isTargetValid(menu2) {
1692
+ const snapshot = instance.current?.board.getSnapshot();
1693
+ if (!snapshot || props.active === false || props.contextMenu === false || menu2.boardId !== props.id || menu2.modelRevision !== snapshot.model.revision || snapshot.session.phase !== "idle" && snapshot.session.phase !== "potential")
1694
+ return false;
1695
+ if (menu2.cardId !== void 0 && !snapshot.model.cards.has(menu2.cardId))
1696
+ return false;
1697
+ if (menu2.containerId !== void 0 && !snapshot.model.containers.has(menu2.containerId))
1698
+ return false;
1699
+ return menu2.headerId === void 0 || dragAny.getHeaderRegions(snapshot.layout, snapshot.index).some(
1700
+ (region) => region.id === menu2.headerId && region.kind === menu2.region
1701
+ );
1702
+ }
1703
+ function copyText(menu2) {
1704
+ const current = instance.current;
1705
+ const model = current?.board.getSnapshot().model;
1706
+ const card = menu2.cardId === void 0 ? void 0 : model?.cards.get(menu2.cardId);
1707
+ const container = menu2.containerId === void 0 ? void 0 : model?.containers.get(menu2.containerId);
1708
+ if (!card || !container || !current) return void 0;
1709
+ try {
1710
+ return dragAny.getContentPlainText(
1711
+ current.content.renderCard({
1712
+ card,
1713
+ container,
1714
+ selected: props.selectedCardIds?.includes(card.id) ?? false,
1715
+ disabled: !!(card.disabled || container.disabled)
1716
+ })
1717
+ );
1718
+ } catch (error) {
1719
+ props.onError?.(error);
1720
+ return void 0;
1721
+ }
1722
+ }
1723
+ function menuItems(menu2) {
1724
+ const defaults = dragAny.getDefaultContextMenuItems(menu2, copyText(menu2));
1725
+ try {
1726
+ return [
1727
+ ...defaults,
1728
+ ...props.contextMenu && props.contextMenu.getItems?.(menu2) || []
1729
+ ];
1730
+ } catch (error) {
1731
+ props.onError?.(error);
1732
+ return defaults;
1733
+ }
1734
+ }
1735
+ react.useLayoutEffect(() => {
1736
+ if (!request) return;
1737
+ if (!isTargetValid(request)) closeMenu();
1738
+ else setMenu({ request, items: menuItems(request) });
1739
+ }, [
1740
+ props.contextMenu,
1741
+ props.renderCard,
1742
+ props.active,
1743
+ props.id,
1744
+ props.layout,
1745
+ props.model
1746
+ ]);
1747
+ react.useLayoutEffect(() => {
1748
+ if (!request || !group) return;
1749
+ return group.subscribe(() => {
1750
+ if (!isTargetValid(request)) closeMenu();
1751
+ });
1752
+ }, [group, request]);
1753
+ react.useLayoutEffect(() => {
1754
+ if (props.active === false) setDialog(void 0);
1755
+ }, [props.active]);
1756
+ function applyScrollbar(value) {
1757
+ const current = instance.current;
1758
+ if (!current) return;
1759
+ current.scrollbar = value ?? props.scrollbar;
1760
+ current.options = { ...current.options, scrollbar: current.scrollbar };
1761
+ current.board.updateOptions({ scrollbar: current.scrollbar });
1762
+ props.onScrollbarChange?.(value);
1763
+ }
1764
+ function onMenuAction(key, menu2) {
1765
+ const current = instance.current;
1766
+ if (!current || !isTargetValid(menu2)) return;
1767
+ const { board } = current;
1768
+ const { index, layout, viewport } = board.getSnapshot();
1769
+ const keys = dragAny.dragContextMenuActions;
1770
+ switch (key) {
1771
+ case keys.copyText: {
1772
+ const text = copyText(menu2);
1773
+ if (text?.trim())
1774
+ void copyContextMenuText(text, props.onError, owner.current);
1775
+ return;
1776
+ }
1777
+ case keys.scrollToCard:
1778
+ if (menu2.cardId !== void 0) board.scrollTo({ cardId: menu2.cardId });
1779
+ return;
1780
+ case keys.scrollToStart:
1781
+ case keys.scrollToEnd: {
1782
+ const rect = menu2.containerId === void 0 ? void 0 : index.getContainerRect(menu2.containerId);
1783
+ if (!rect) return;
1784
+ board.scrollTo(
1785
+ key === keys.scrollToStart ? { scrollLeft: rect.x, scrollTop: rect.y } : {
1786
+ scrollLeft: Math.max(
1787
+ rect.x,
1788
+ rect.x + rect.width - viewport.width
1789
+ ),
1790
+ scrollTop: Math.max(
1791
+ rect.y,
1792
+ rect.y + rect.height - viewport.height
1793
+ )
1794
+ }
1795
+ );
1796
+ return;
1797
+ }
1798
+ case keys.scrollToHeader: {
1799
+ const region = dragAny.getHeaderRegions(layout, index).find(
1800
+ (region2) => region2.id === menu2.headerId && region2.kind === menu2.region
1801
+ );
1802
+ if (region)
1803
+ board.scrollTo(
1804
+ region.axis === "x" ? { scrollLeft: region.offset } : { scrollTop: region.offset }
1805
+ );
1806
+ return;
1807
+ }
1808
+ case keys.scrollbarTrack:
1809
+ case keys.scrollbarButton: {
1810
+ const value = {
1811
+ ...current.scrollbar,
1812
+ mode: key === keys.scrollbarTrack ? "scrollbar" : "button"
1813
+ };
1814
+ saveScrollbarSettings(
1815
+ props.storageKey,
1816
+ value,
1817
+ owner.current,
1818
+ props.onError
1819
+ );
1820
+ applyScrollbar(value);
1821
+ return;
1822
+ }
1823
+ case keys.scrollbarReset:
1824
+ saveScrollbarSettings(
1825
+ props.storageKey,
1826
+ void 0,
1827
+ owner.current,
1828
+ props.onError
1829
+ );
1830
+ applyScrollbar(void 0);
1831
+ return;
1832
+ case keys.scrollbarSettings:
1833
+ setDialog("settings");
1834
+ return;
1835
+ case keys.scrollbarPosition:
1836
+ setDialog("position");
1837
+ return;
1838
+ default:
1839
+ try {
1840
+ if (props.contextMenu && isEnabledAction(props.contextMenu.getItems?.(menu2) ?? [], key)) {
1841
+ props.contextMenu.onAction?.(key, menu2);
1842
+ }
1843
+ } catch (error) {
1844
+ props.onError?.(error);
1845
+ }
1846
+ }
1847
+ }
1848
+ const active = mounted && props.active !== false;
1849
+ const Dialog = dialog === "settings" ? SettingsDialog : PositionDialog;
1850
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1851
+ /* @__PURE__ */ jsxRuntime.jsx(
1852
+ "div",
1853
+ {
1854
+ ref: owner,
1855
+ "data-drag-any-host": "",
1856
+ role: "region",
1857
+ "aria-label": props.id,
1858
+ className: props.className,
1859
+ style: {
1860
+ position: "relative",
1861
+ width: "100%",
1862
+ height: props.height ?? 400,
1863
+ overflow: "hidden",
1864
+ ...props.style
1865
+ }
1866
+ }
1867
+ ),
1868
+ active && request && props.contextMenu !== false && /* @__PURE__ */ jsxRuntime.jsx(
1869
+ ContextMenuView,
1870
+ {
1871
+ request,
1872
+ items: menu.items,
1873
+ onAction: onMenuAction,
1874
+ onClose: closeMenu,
1875
+ owner: owner.current,
1876
+ returnFocus: owner.current,
1877
+ theme: props.theme,
1878
+ isTargetValid
1879
+ }
1880
+ ),
1881
+ active && dialog && /* @__PURE__ */ jsxRuntime.jsx(
1882
+ Dialog,
1883
+ {
1884
+ value: instance.current?.scrollbar ?? {},
1885
+ storageKey: props.storageKey,
1886
+ owner: owner.current,
1887
+ theme: props.theme,
1888
+ onError: props.onError,
1889
+ onClose: () => setDialog(void 0),
1890
+ onConfirm: (value) => {
1891
+ applyScrollbar(value);
1892
+ setDialog(void 0);
1893
+ }
1894
+ }
1895
+ ),
1896
+ active && props.tooltip && /* @__PURE__ */ jsxRuntime.jsx(
1897
+ Tooltip,
1898
+ {
1899
+ request: props.tooltip,
1900
+ owner: owner.current,
1901
+ theme: props.theme
1902
+ }
1903
+ ),
1904
+ active && props.editor && /* @__PURE__ */ jsxRuntime.jsx(
1905
+ EditorHost,
1906
+ {
1907
+ ...props.editor,
1908
+ owner: owner.current,
1909
+ theme: props.theme
1910
+ }
1911
+ )
1912
+ ] });
1913
+ }
1914
+ var ModelBoard = react.forwardRef(Board);
1915
+ function DeclarativeBoard(props, ref) {
1916
+ const { document: document2, children, store, dragLayout, getDragRole, ...board } = props;
1917
+ const stored = react.useSyncExternalStore(
1918
+ store?.subscribe ?? emptySubscription,
1919
+ store?.getSnapshot ?? emptySnapshot,
1920
+ store?.getSnapshot ?? emptySnapshot
1921
+ );
1922
+ const group = react.useContext(DragGroupContext);
1923
+ if (Number(document2 !== void 0) + Number(children !== void 0) + Number(store !== void 0) !== 1)
1924
+ throw new dragAny.DragDocumentError("$", "document\u3001children \u4E0E store \u987B\u9009\u62E9\u5176\u4E00");
1925
+ for (const key of [
1926
+ "model",
1927
+ "layout",
1928
+ "render",
1929
+ "renderCard",
1930
+ "renderVersion"
1931
+ ])
1932
+ if (board[key] !== void 0)
1933
+ throw new dragAny.DragDocumentError("$." + key, "\u4E0D\u80FD\u4E0E\u7ED3\u6784\u58F0\u660E\u540C\u65F6\u4F20\u5165");
1934
+ const prepared = react.useMemo(() => {
1935
+ try {
1936
+ let source = stored?.document ?? document2;
1937
+ if (dragLayout !== void 0 || getDragRole !== void 0) {
1938
+ if (store !== void 0 || document2 !== void 0 || children === void 0 || dragLayout !== "queue" && dragLayout !== "lanes" || typeof getDragRole !== "function")
1939
+ throw new dragAny.DragDocumentError(
1940
+ "$",
1941
+ "\u901A\u7528 JSX \u5165\u53E3\u987B\u540C\u65F6\u63D0\u4F9B children\u3001dragLayout \u548C getDragRole"
1942
+ );
1943
+ source = compileDragUIStructure(children, { dragLayout, getDragRole });
1944
+ }
1945
+ return {
1946
+ indexed: dragAny.indexDragDocument(
1947
+ source ?? compileDragStructure(children),
1948
+ 0,
1949
+ (value) => value
1950
+ )
1951
+ };
1952
+ } catch (error) {
1953
+ return { error };
1954
+ }
1955
+ }, [stored, store, document2, children, dragLayout, getDragRole]);
1956
+ const [committed, setCommitted] = react.useState({
1957
+ indexed: prepared.indexed,
1958
+ revision: stored?.revision ?? 0
1959
+ });
1960
+ const indexed = prepared.indexed ?? committed.indexed;
1961
+ if (prepared.indexed && committed.indexed !== prepared.indexed)
1962
+ setCommitted({
1963
+ indexed: prepared.indexed,
1964
+ revision: committed.revision + 1
1965
+ });
1966
+ const onError = react.useRef(board.onError);
1967
+ react.useLayoutEffect(() => {
1968
+ onError.current = board.onError;
1969
+ }, [board.onError]);
1970
+ react.useLayoutEffect(() => {
1971
+ if ("error" in prepared) onError.current?.(prepared.error);
1972
+ }, [prepared]);
1973
+ const projection = react.useMemo(
1974
+ () => indexed && {
1975
+ model: { ...indexed.model, revision: committed.revision },
1976
+ layout: indexed.layout,
1977
+ render: indexed.render
1978
+ },
1979
+ [indexed, committed.revision]
1980
+ );
1981
+ react.useLayoutEffect(
1982
+ () => projection && group?.stageProjection?.(props.id, projection),
1983
+ [group, props.id, projection]
1984
+ );
1985
+ const readProjection = react.useCallback(
1986
+ () => group?.getProjection?.(props.id),
1987
+ [group, props.id]
1988
+ );
1989
+ const published = react.useSyncExternalStore(
1990
+ group?.subscribe ?? emptySubscription,
1991
+ readProjection,
1992
+ emptySnapshot
1993
+ );
1994
+ if (!projection) throw prepared.error;
1995
+ if (group) {
1996
+ if (!published) return null;
1997
+ const {
1998
+ onMoveRequest: _move,
1999
+ acknowledgedTransactionId: _ack,
2000
+ ...member
2001
+ } = board;
2002
+ return /* @__PURE__ */ jsxRuntime.jsx(
2003
+ ModelBoard,
2004
+ {
2005
+ ...member,
2006
+ ref,
2007
+ layout: published.layout,
2008
+ render: published.render
2009
+ }
2010
+ );
2011
+ }
2012
+ return /* @__PURE__ */ jsxRuntime.jsx(
2013
+ ModelBoard,
2014
+ {
2015
+ ...board,
2016
+ ref,
2017
+ model: projection.model,
2018
+ layout: projection.layout,
2019
+ render: projection.render
2020
+ }
2021
+ );
2022
+ }
2023
+ var emptySubscription = () => () => {
2024
+ };
2025
+ var emptySnapshot = () => void 0;
2026
+ var StructureBoard = react.forwardRef(DeclarativeBoard);
2027
+ var ReactDragAny = StructureBoard;
2028
+ function Group(props, ref) {
2029
+ const committed = useCommitted(props);
2030
+ if (props.state !== void 0)
2031
+ throw new TypeError("\u753B\u5E03\u7EC4\u901A\u8FC7\u6210\u5458\u58F0\u660E\u63A5\u6536\u6570\u636E");
2032
+ const current = react.useRef();
2033
+ const listeners = react.useRef(/* @__PURE__ */ new Set());
2034
+ const projected = react.useRef(/* @__PURE__ */ new Map());
2035
+ const published = react.useRef(/* @__PURE__ */ new Map());
2036
+ const scheduled = react.useRef(false);
2037
+ const previousAck = react.useRef();
2038
+ const manager = react.useMemo(
2039
+ () => ({
2040
+ getProjection: (id) => published.current.get(id),
2041
+ stageProjection(id, projection) {
2042
+ projected.current.set(id, projection);
2043
+ queuePublish();
2044
+ return () => {
2045
+ if (projected.current.get(id) === projection) {
2046
+ projected.current.delete(id);
2047
+ queuePublish();
2048
+ }
2049
+ };
2050
+ },
2051
+ ensureGroup() {
2052
+ if (current.current) return current.current;
2053
+ const group = new dragAny.DragAnyGroup({
2054
+ get onMoveRequest() {
2055
+ return committed.current.onMoveRequest;
2056
+ },
2057
+ onError: (error) => committed.current.onError?.(error)
2058
+ });
2059
+ current.current = group;
2060
+ return group;
2061
+ },
2062
+ getModel: (id) => published.current.get(id)?.model,
2063
+ subscribe(listener) {
2064
+ listeners.current.add(listener);
2065
+ return () => {
2066
+ listeners.current.delete(listener);
2067
+ };
2068
+ }
2069
+ }),
2070
+ [committed]
2071
+ );
2072
+ function queuePublish() {
2073
+ if (scheduled.current) return;
2074
+ scheduled.current = true;
2075
+ queueMicrotask(() => {
2076
+ scheduled.current = false;
2077
+ const group = current.current;
2078
+ if (!group) return;
2079
+ const next = new Map(projected.current);
2080
+ const ack = committed.current.acknowledgedTransactionId;
2081
+ const transaction = ack !== previousAck.current ? ack : void 0;
2082
+ if (!dragAny.dragAnyGroupProjection.replaceProjected(group, next, transaction))
2083
+ return;
2084
+ previousAck.current = ack;
2085
+ published.current = next;
2086
+ for (const listener of listeners.current) listener();
2087
+ });
2088
+ }
2089
+ react.useLayoutEffect(() => {
2090
+ manager.ensureGroup();
2091
+ return () => {
2092
+ const group = current.current;
2093
+ current.current = void 0;
2094
+ group?.destroy();
2095
+ };
2096
+ }, [manager]);
2097
+ react.useLayoutEffect(queuePublish, [props.acknowledgedTransactionId, manager]);
2098
+ react.useImperativeHandle(
2099
+ ref,
2100
+ () => ({
2101
+ cancelDrag: (reason) => current.current?.cancelDrag(reason),
2102
+ rejectMove: (transactionId, reason) => current.current?.rejectMove(transactionId, reason) ?? false
2103
+ }),
2104
+ []
2105
+ );
2106
+ return /* @__PURE__ */ jsxRuntime.jsx(
2107
+ DragGroupContext.Provider,
2108
+ {
2109
+ value: manager,
2110
+ children: props.children
2111
+ }
2112
+ );
2113
+ }
2114
+ var ReactDragAnyGroup = react.forwardRef(Group);
2115
+
2116
+ exports.Card = Card;
2117
+ exports.ContentCompileError = ContentCompileError;
2118
+ exports.Flow = Flow;
2119
+ exports.GridSlot = GridSlot;
2120
+ exports.Lane = Lane;
2121
+ exports.Lanes = Lanes;
2122
+ exports.Queue = Queue;
2123
+ exports.ReactDragAny = ReactDragAny;
2124
+ exports.ReactDragAnyGroup = ReactDragAnyGroup;
2125
+ exports.SparseGrid = SparseGrid;
2126
+ exports.compileJSX = compileJSX;
2127
+ exports.createContentBindings = createContentBindings;