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