@canvas-components/react-drag-any 1.0.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,10 @@
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';
1
+ import { useState, useRef, useLayoutEffect, useId, Fragment as Fragment$1 } from 'react';
2
+ import { uiDeclarationId, compileUIScene } from '@canvas-components/react-canvas-ui/host';
3
+ import { drag, mountDragSurface, getDefaultContextMenuItems, dragContextMenuActions, resolveTheme } from '@canvas-components/drag-any';
3
4
  import { createPortal } from 'react-dom';
4
5
  import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
5
- import { UI, compileUIJSX } from '@canvas-components/react-canvas-ui';
6
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);
7
+ // src/components/declarative-surface.tsx
10
8
  function overlayRoot(owner) {
11
9
  const doc = owner?.ownerDocument ?? document;
12
10
  return doc.fullscreenElement ?? doc.body;
@@ -76,234 +74,34 @@ function useOverlayPosition(ref, root, anchor, parent) {
76
74
  }, [ref, root, anchor.x, anchor.y, parent]);
77
75
  return style;
78
76
  }
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;
77
+
78
+ // #style-inject:#style-inject
79
+ function styleInject(css, { insertAt } = {}) {
80
+ if (!css || typeof document === "undefined") return;
81
+ const head = document.head || document.getElementsByTagName("head")[0];
82
+ const style = document.createElement("style");
83
+ style.type = "text/css";
84
+ if (insertAt === "top") {
85
+ if (head.firstChild) {
86
+ head.insertBefore(style, head.firstChild);
87
+ } else {
88
+ head.appendChild(style);
136
89
  }
137
- event.preventDefault();
138
- event.stopPropagation();
90
+ } else {
91
+ head.appendChild(style);
139
92
  }
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)));
93
+ if (style.styleSheet) {
94
+ style.styleSheet.cssText = css;
95
+ } else {
96
+ style.appendChild(document.createTextNode(css));
305
97
  }
306
98
  }
99
+
100
+ // src/styles/theme.css
101
+ styleInject(".drag-any-overlay {\n color: var(--drag-overlay-text);\n line-height: 1.45;\n}\n.drag-any-overlay :focus-visible {\n outline: 2px solid var(--drag-overlay-focus);\n outline-offset: -2px;\n}\n");
102
+
103
+ // src/styles/dialogs.css
104
+ styleInject(".drag-any-dialog-backdrop {\n position: fixed;\n z-index: 1210;\n inset: 0;\n display: grid;\n place-items: center;\n background: rgba(15, 23, 42, 0.22);\n}\n.drag-any-dialog {\n position: static;\n box-sizing: border-box;\n width: min(390px, calc(100% - 24px));\n max-height: calc(100% - 24px);\n margin: auto;\n padding: 0;\n overflow: auto;\n color: var(--drag-overlay-text);\n font: inherit;\n border: 1px solid var(--drag-overlay-border);\n border-radius: 8px;\n background: var(--drag-overlay-bg);\n box-shadow: 0 8px 24px var(--drag-overlay-shadow);\n}\n.drag-any-dialog-backdrop:has(.drag-any-dialog:modal) {\n background: transparent;\n}\n.drag-any-dialog:modal {\n position: fixed;\n}\n.drag-any-dialog::backdrop {\n background: rgba(15, 23, 42, 0.22);\n}\n.drag-any-dialog h2 {\n position: sticky;\n top: 0;\n margin: 0;\n padding: 12px 16px;\n border-bottom: 1px solid var(--drag-overlay-border);\n background: var(--drag-overlay-bg);\n font-size: 1.1em;\n}\n.drag-any-dialog-fields {\n display: grid;\n gap: 8px;\n padding: 12px 16px;\n}\n.drag-any-dialog-fields label {\n display: grid;\n grid-template-columns: 1fr minmax(0, 1fr);\n align-items: center;\n gap: 12px;\n}\n.drag-any-dialog-fields input[type=checkbox] {\n justify-self: start;\n}\n.drag-any-dialog footer {\n position: sticky;\n bottom: 0;\n display: flex;\n justify-content: end;\n gap: 8px;\n padding: 10px 16px;\n border-top: 1px solid var(--drag-overlay-border);\n background: var(--drag-overlay-bg);\n}\n.drag-any-dialog :is(input:not([type=checkbox]), select, button) {\n box-sizing: border-box;\n min-height: 30px;\n min-width: 0;\n padding: 3px 8px;\n border: 1px solid var(--drag-overlay-border);\n border-radius: 4px;\n background: var(--drag-overlay-bg);\n color: inherit;\n font: inherit;\n}\n.drag-any-dialog button {\n cursor: pointer;\n}\n.drag-any-dialog button:is(:hover, [data-primary]) {\n background: var(--drag-overlay-hover);\n}\n.drag-any-dialog button[data-primary] {\n border-color: var(--drag-overlay-focus);\n}\n");
307
105
  var numberFields = {
308
106
  thickness: "\u539A\u5EA6",
309
107
  thumbRadius: "\u6ED1\u5757\u5706\u89D2",
@@ -597,1518 +395,529 @@ function PositionDialog(props) {
597
395
  )
598
396
  ] }, key)) });
599
397
  }
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({
398
+
399
+ // src/styles/menu.css
400
+ styleInject(".drag-any-menu {\n position: fixed;\n z-index: 1200;\n box-sizing: border-box;\n border: 1px solid var(--drag-overlay-border);\n border-radius: 6px;\n color: var(--drag-overlay-text);\n background: var(--drag-overlay-bg);\n box-shadow: 0 6px 20px var(--drag-overlay-shadow);\n width: max-content;\n min-width: min(172px, var(--drag-overlay-max-width, 100vw));\n padding: 4px;\n overflow: auto;\n overscroll-behavior: contain;\n}\n.drag-any-menu [role=menuitem] {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n width: 100%;\n min-height: 30px;\n padding: 5px 9px;\n border: 0;\n border-radius: 4px;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: start;\n overflow-wrap: anywhere;\n cursor: pointer;\n}\n.drag-any-menu [role=menuitem]:not(:disabled):is(:hover, :focus-visible, [aria-expanded=true]) {\n background: var(--drag-overlay-hover);\n}\n.drag-any-menu [role=menuitem][data-danger=true] {\n color: var(--drag-overlay-danger);\n}\n.drag-any-menu [role=menuitem]:disabled {\n color: var(--drag-overlay-muted);\n cursor: default;\n}\n.drag-any-menu [role=separator] {\n margin: 4px;\n border-top: 1px solid var(--drag-overlay-border);\n}\n");
401
+ function MenuLevel({
402
+ items,
403
+ root,
622
404
  request,
623
- onClose,
624
- owner,
625
- theme
405
+ parent,
406
+ focusOnOpen = true,
407
+ onBack,
408
+ onSelect,
409
+ onClose
626
410
  }) {
627
411
  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
412
+ const [submenu, setSubmenu] = useState();
413
+ const style = useOverlayPosition(panel, root, request.clientAnchor, parent);
414
+ const enabled = () => Array.from(
415
+ panel.current?.querySelectorAll(
416
+ ':scope > [role="menuitem"]:not(:disabled)'
417
+ ) ?? []
646
418
  );
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);
419
+ useLayoutEffect(() => {
420
+ if (focusOnOpen)
421
+ (enabled()[0] ?? panel.current)?.focus({ preventScroll: true });
422
+ }, [focusOnOpen]);
423
+ function handleKey(event) {
424
+ const buttons = enabled();
425
+ const index = buttons.indexOf(event.target);
426
+ const button = buttons[index];
427
+ switch (event.key) {
428
+ case "ArrowDown":
429
+ buttons[(index + 1) % buttons.length]?.focus();
430
+ break;
431
+ case "ArrowUp":
432
+ buttons[(index <= 0 ? buttons.length : index) - 1]?.focus();
433
+ break;
434
+ case "Home":
435
+ buttons[0]?.focus();
436
+ break;
437
+ case "End":
438
+ buttons[buttons.length - 1]?.focus();
439
+ break;
440
+ case "Enter":
441
+ case " ":
442
+ button?.click();
443
+ break;
444
+ case "ArrowRight":
445
+ if (button?.hasAttribute("aria-haspopup")) button.click();
446
+ break;
447
+ case "ArrowLeft":
448
+ onBack?.();
449
+ break;
450
+ case "Escape":
451
+ (onBack ?? onClose)();
452
+ break;
453
+ case "Tab":
454
+ onClose();
455
+ break;
456
+ default:
457
+ return;
458
+ }
459
+ event.preventDefault();
460
+ event.stopPropagation();
719
461
  }
720
- throw new DragContentError("invalid-value", path);
462
+ const active = items.find(
463
+ (item) => item.key === submenu?.key && !item.disabled
464
+ );
465
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
466
+ /* @__PURE__ */ jsx(
467
+ "div",
468
+ {
469
+ ref: panel,
470
+ className: "drag-any-menu",
471
+ role: "menu",
472
+ "aria-label": "\u64CD\u4F5C\u83DC\u5355",
473
+ tabIndex: -1,
474
+ style,
475
+ onKeyDown: handleKey,
476
+ onScroll: (event) => {
477
+ if (!submenu) return;
478
+ event.currentTarget.focus({ preventScroll: true });
479
+ setSubmenu(void 0);
480
+ },
481
+ children: items.map((item) => /* @__PURE__ */ jsxs(Fragment$1, { children: [
482
+ item.separatorBefore && /* @__PURE__ */ jsx("div", { role: "separator" }),
483
+ /* @__PURE__ */ jsxs(
484
+ "button",
485
+ {
486
+ role: "menuitem",
487
+ type: "button",
488
+ tabIndex: -1,
489
+ disabled: item.disabled,
490
+ "data-danger": item.danger || void 0,
491
+ "aria-haspopup": item.children?.length ? "menu" : void 0,
492
+ "aria-expanded": item.children?.length ? submenu?.key === item.key : void 0,
493
+ onMouseEnter: (event) => {
494
+ if (item.disabled) return;
495
+ event.currentTarget.focus({ preventScroll: true });
496
+ setSubmenu(
497
+ item.children?.length ? {
498
+ key: item.key,
499
+ anchor: event.currentTarget,
500
+ focus: false
501
+ } : void 0
502
+ );
503
+ },
504
+ onClick: (event) => {
505
+ if (item.children?.length)
506
+ setSubmenu({
507
+ key: item.key,
508
+ anchor: event.currentTarget,
509
+ focus: true
510
+ });
511
+ else onSelect(item.key);
512
+ },
513
+ children: [
514
+ /* @__PURE__ */ jsx("span", { children: item.label }),
515
+ !!item.children?.length && /* @__PURE__ */ jsx("span", { "aria-hidden": "true", children: "\u203A" })
516
+ ]
517
+ }
518
+ )
519
+ ] }, item.key))
520
+ }
521
+ ),
522
+ submenu && !!active?.children?.length && /* @__PURE__ */ jsx(
523
+ MenuLevel,
524
+ {
525
+ items: active.children,
526
+ root,
527
+ request,
528
+ parent: submenu.anchor,
529
+ focusOnOpen: submenu.focus,
530
+ onClose,
531
+ onSelect,
532
+ onBack: () => {
533
+ submenu.anchor.focus({ preventScroll: true });
534
+ setSubmenu(void 0);
535
+ }
536
+ },
537
+ active.key
538
+ )
539
+ ] });
721
540
  }
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 };
541
+ function ContextMenuView(props) {
542
+ return /* @__PURE__ */ jsx(MenuSession, { ...props }, props.request.requestId);
736
543
  }
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;
544
+ function MenuSession({
545
+ request,
546
+ items,
547
+ onAction,
548
+ onClose,
549
+ theme,
550
+ owner,
551
+ returnFocus,
552
+ revision,
553
+ dragging,
554
+ isTargetValid
555
+ }) {
556
+ const root = overlayRoot(owner);
557
+ const doc = root.ownerDocument;
558
+ const menu = useRef(null);
559
+ const close = useRef(onClose);
560
+ close.current = onClose;
561
+ const previousFocus = useRef(returnFocus ?? doc.activeElement);
562
+ const valid = () => !dragging && (revision === void 0 || revision === request.modelRevision) && (isTargetValid?.(request) ?? true);
563
+ const invalid = !valid();
564
+ useLayoutEffect(() => {
565
+ if (invalid) onClose();
566
+ }, [invalid, onClose]);
567
+ useLayoutEffect(() => {
568
+ function outside(event) {
569
+ if (!event.composedPath().includes(menu.current)) close.current();
765
570
  }
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;
571
+ function dismiss() {
572
+ close.current();
782
573
  }
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
- };
574
+ doc.addEventListener("pointerdown", outside, true);
575
+ doc.addEventListener("scroll", outside, true);
576
+ doc.addEventListener("fullscreenchange", dismiss);
577
+ doc.defaultView?.addEventListener("blur", dismiss);
578
+ return () => {
579
+ doc.removeEventListener("pointerdown", outside, true);
580
+ doc.removeEventListener("scroll", outside, true);
581
+ doc.removeEventListener("fullscreenchange", dismiss);
582
+ doc.defaultView?.removeEventListener("blur", dismiss);
583
+ const previous = previousFocus.current;
584
+ if (previous?.isConnected) previous.focus?.({ preventScroll: true });
801
585
  };
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 }
586
+ }, [doc]);
587
+ if (invalid || !items.length) return null;
588
+ return createPortal(
589
+ /* @__PURE__ */ jsx(
590
+ "div",
591
+ {
592
+ ref: menu,
593
+ className: "drag-any-overlay",
594
+ style: overlayTheme(theme),
595
+ onPointerDown: (event) => event.stopPropagation(),
596
+ onWheel: (event) => event.stopPropagation(),
597
+ onContextMenu: (event) => {
598
+ event.preventDefault();
599
+ event.stopPropagation();
600
+ },
601
+ children: /* @__PURE__ */ jsx(
602
+ MenuLevel,
603
+ {
604
+ items,
605
+ root,
606
+ request,
607
+ onClose,
608
+ onSelect: (key) => {
609
+ const canExecute = valid();
610
+ onClose();
611
+ if (canExecute) onAction(key, request);
612
+ }
885
613
  }
886
- });
887
- return;
614
+ )
888
615
  }
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
- }
616
+ ),
617
+ root
618
+ );
619
+ }
620
+ async function copyContextMenuText(text, onError, owner) {
906
621
  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() };
622
+ const clipboard = (owner?.ownerDocument.defaultView ?? window).navigator.clipboard;
623
+ if (!clipboard) throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8BBF\u95EE\u526A\u8D34\u677F");
624
+ await clipboard.writeText(text);
916
625
  } 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
626
  }
926
627
  }
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);
628
+ function Source(_props) {
629
+ throw new TypeError("Drag.Source \u5E94\u4F4D\u4E8E Drag.Surface \u5185");
951
630
  }
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;
631
+ function Target(_props) {
632
+ throw new TypeError("Drag.Target \u5E94\u4F4D\u4E8E Drag.Surface \u5185");
1037
633
  }
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, {
634
+ var sourceId = /* @__PURE__ */ Symbol.for("@canvas-components/react-drag-any/Drag.Source");
635
+ var targetId = /* @__PURE__ */ Symbol.for("@canvas-components/react-drag-any/Drag.Target");
636
+ Object.defineProperty(Source, uiDeclarationId, { value: sourceId });
637
+ Object.defineProperty(Target, uiDeclarationId, { value: targetId });
638
+ var decorators = /* @__PURE__ */ new Map([
639
+ [
640
+ sourceId,
641
+ (props, node) => drag.source(
642
+ {
643
+ id: props.id,
644
+ data: props.data,
645
+ disabled: props.disabled,
646
+ disabledStyle: props.disabledStyle
647
+ },
648
+ node
649
+ )
650
+ ],
651
+ [
652
+ targetId,
653
+ (props, node) => drag.target(
654
+ { id: props.id, canDrop: props.canDrop, slot: props.slot },
655
+ node
656
+ )
657
+ ]
658
+ ]);
659
+ function Surface({
1055
660
  id,
1056
- renderCard,
1057
- render: renderer,
1058
- renderVersion: version
661
+ group,
662
+ hasItem,
663
+ autoScrollEdge,
664
+ history,
665
+ contextMenu,
666
+ storageKey,
667
+ onNodeAction,
668
+ onMoveRequest,
669
+ onViewportChange,
670
+ children,
671
+ height = 320,
672
+ className,
673
+ style
1059
674
  }) {
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;
675
+ const [menu, setMenu] = useState();
676
+ const [dialog, setDialog] = useState();
677
+ const [scrollbar, setScrollbar] = useState();
678
+ const revision = useRef(0);
679
+ const canvas = useRef(null);
680
+ const mounted = useRef();
681
+ const actionListener = useRef(onNodeAction);
1199
682
  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]);
683
+ actionListener.current = onNodeAction;
684
+ }, [onNodeAction]);
685
+ const viewportListener = useRef(onViewportChange);
1281
686
  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"
687
+ viewportListener.current = onViewportChange;
688
+ }, [onViewportChange]);
689
+ const current = useRef();
690
+ const transition = history?.transition;
691
+ const previousTransition = useRef(transition);
692
+ useLayoutEffect(() => {
693
+ const next = compileUIScene(children, { owner: id }, decorators);
694
+ const surface = drag.surface(
695
+ { id, group, hasItem, autoScrollEdge, onMoveRequest },
696
+ next.document.root
1483
697
  );
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 ")}`
698
+ const previous = current.current;
699
+ current.current = next;
700
+ if (mounted.current)
701
+ mounted.current.update(
702
+ surface,
703
+ transition !== previousTransition.current ? transition : void 0
1538
704
  );
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");
705
+ else
706
+ mounted.current = mountDragSurface(canvas.current, surface, {
707
+ onViewportChange: (regions) => viewportListener.current?.(regions),
708
+ onAction(action2, event, info) {
709
+ current.current?.handlers.get(action2)?.({
710
+ nativeEvent: event,
711
+ stopPropagation: () => event.stopPropagation(),
712
+ preventDefault: () => event.preventDefault()
713
+ });
714
+ actionListener.current?.(action2, event, info);
1611
715
  }
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;
716
+ });
717
+ previousTransition.current = transition;
718
+ previous?.dispose();
719
+ revision.current++;
1645
720
  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);
721
+ }, [children, id, group, hasItem, autoScrollEdge, onMoveRequest, transition]);
722
+ useLayoutEffect(
723
+ () => () => {
724
+ mounted.current?.destroy();
725
+ mounted.current = void 0;
726
+ current.current?.dispose();
727
+ current.current = void 0;
1659
728
  },
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]
729
+ []
1688
730
  );
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))
731
+ useLayoutEffect(() => {
732
+ setScrollbar(readScrollbarSettings(storageKey, canvas.current));
733
+ setDialog(void 0);
734
+ }, [storageKey]);
735
+ useLayoutEffect(() => {
736
+ const axis = (value) => ({
737
+ ...value,
738
+ buttonHoverBackgroundColor: value.buttonHoverColor,
739
+ buttonPressedBackgroundColor: value.buttonPressedColor
740
+ });
741
+ mounted.current?.setScrollbar(
742
+ scrollbar && {
743
+ ...scrollbar,
744
+ ...axis(scrollbar),
745
+ horizontal: scrollbar.horizontal && axis(scrollbar.horizontal),
746
+ vertical: scrollbar.vertical && axis(scrollbar.vertical)
747
+ }
748
+ );
749
+ }, [scrollbar]);
750
+ function valid(request) {
751
+ if (request.modelRevision !== revision.current || request.boardId !== id)
1696
752
  return false;
1697
- return menu2.headerId === void 0 || getHeaderRegions(snapshot.layout, snapshot.index).some(
1698
- (region) => region.id === menu2.headerId && region.kind === menu2.region
753
+ const hit = mounted.current?.inspect(
754
+ request.clientAnchor.x,
755
+ request.clientAnchor.y
1699
756
  );
757
+ return !!hit && hit.itemId === request.cardId && (typeof hit.targetId === "object" ? JSON.stringify([hit.targetId.rowId, hit.targetId.columnId]) : hit.targetId) === request.containerId && request.region === "scrollbar" === hit.scrollbar;
1700
758
  }
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
- })
759
+ function action(key, request) {
760
+ if (!valid(request)) return;
761
+ if (key === dragContextMenuActions.copyText && menu?.text) {
762
+ void copyContextMenuText(menu.text, void 0, canvas.current);
763
+ return;
764
+ }
765
+ if (key === dragContextMenuActions.scrollToCard || key === dragContextMenuActions.scrollToStart || key === dragContextMenuActions.scrollToEnd) {
766
+ mounted.current?.scrollToMenuTarget(
767
+ request.clientAnchor.x,
768
+ request.clientAnchor.y,
769
+ key === dragContextMenuActions.scrollToCard ? "card" : key === dragContextMenuActions.scrollToStart ? "start" : "end"
1715
770
  );
1716
- } catch (error) {
1717
- props.onError?.(error);
1718
- return void 0;
771
+ return;
1719
772
  }
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;
773
+ if (key === dragContextMenuActions.scrollbarPosition || key === dragContextMenuActions.scrollbarSettings) {
774
+ setDialog(key === dragContextMenuActions.scrollbarPosition ? "position" : "settings");
775
+ return;
1731
776
  }
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
- }
777
+ if (key === dragContextMenuActions.scrollbarReset || key === dragContextMenuActions.scrollbarTrack || key === dragContextMenuActions.scrollbarButton) {
778
+ const value = key === dragContextMenuActions.scrollbarReset ? void 0 : {
779
+ ...scrollbar,
780
+ mode: key === dragContextMenuActions.scrollbarTrack ? "scrollbar" : "button"
781
+ };
782
+ saveScrollbarSettings(storageKey, value, canvas.current);
783
+ setScrollbar(value);
784
+ return;
1844
785
  }
786
+ if (contextMenu) contextMenu.onAction?.(key, request);
1845
787
  }
1846
- const active = mounted && props.active !== false;
1847
- const Dialog = dialog === "settings" ? SettingsDialog : PositionDialog;
788
+ const Dialog = dialog === "position" ? PositionDialog : SettingsDialog;
1848
789
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1849
790
  /* @__PURE__ */ jsx(
1850
- "div",
791
+ "canvas",
1851
792
  {
1852
- ref: owner,
793
+ tabIndex: 0,
1853
794
  "data-drag-any-host": "",
1854
- role: "region",
1855
- "aria-label": props.id,
1856
- className: props.className,
795
+ "aria-label": id,
796
+ onPointerDown: () => setMenu(void 0),
797
+ onKeyDown: (event) => {
798
+ if (!history || event.defaultPrevented || event.altKey || !(event.ctrlKey || event.metaKey))
799
+ return;
800
+ const key = event.key.toLowerCase();
801
+ if (key === "z" && !event.shiftKey && history.canUndo) {
802
+ event.preventDefault();
803
+ history.undo();
804
+ } else if ((key === "z" && event.shiftKey || key === "y") && history.canRedo) {
805
+ event.preventDefault();
806
+ history.redo();
807
+ }
808
+ },
809
+ onContextMenu: (event) => {
810
+ const hit = mounted.current?.inspect(event.clientX, event.clientY);
811
+ if (!hit || contextMenu === false) return;
812
+ event.preventDefault();
813
+ setMenu({
814
+ boardId: id,
815
+ requestId: id + "-" + event.timeStamp,
816
+ text: hit.text,
817
+ region: hit.scrollbar ? "scrollbar" : hit.itemId ? "card" : hit.targetId ? "container" : "background",
818
+ cardId: hit.itemId,
819
+ containerId: typeof hit.targetId === "object" ? JSON.stringify([hit.targetId.rowId, hit.targetId.columnId]) : hit.targetId,
820
+ logicalPoint: hit.point,
821
+ clientAnchor: { x: event.clientX, y: event.clientY },
822
+ modelRevision: revision.current
823
+ });
824
+ },
825
+ ref: canvas,
826
+ className,
1857
827
  style: {
1858
- position: "relative",
828
+ display: "block",
1859
829
  width: "100%",
1860
- height: props.height ?? 400,
1861
- overflow: "hidden",
1862
- ...props.style
830
+ height,
831
+ touchAction: "none",
832
+ ...style
1863
833
  }
1864
834
  }
1865
835
  ),
1866
- active && request && props.contextMenu !== false && /* @__PURE__ */ jsx(
836
+ menu && contextMenu !== false && /* @__PURE__ */ jsx(
1867
837
  ContextMenuView,
1868
838
  {
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
839
+ owner: canvas.current,
840
+ request: menu,
841
+ items: [
842
+ ...getDefaultContextMenuItems(menu, menu.text),
843
+ ...contextMenu?.getItems?.(menu) ?? []
844
+ ],
845
+ onAction: action,
846
+ isTargetValid: valid,
847
+ returnFocus: canvas.current,
848
+ onClose: () => setMenu(void 0)
1877
849
  }
1878
850
  ),
1879
- active && dialog && /* @__PURE__ */ jsx(
851
+ dialog && /* @__PURE__ */ jsx(
1880
852
  Dialog,
1881
853
  {
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),
854
+ owner: canvas.current,
855
+ storageKey,
856
+ value: scrollbar ?? {},
1888
857
  onConfirm: (value) => {
1889
- applyScrollbar(value);
858
+ setScrollbar(value);
1890
859
  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
860
+ },
861
+ onClose: () => setDialog(void 0)
1908
862
  }
1909
863
  )
1910
864
  ] });
1911
865
  }
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
- }
866
+ var Drag = { Surface, Source, Target };
867
+ function resolve(action, previous) {
868
+ return typeof action === "function" ? action(previous) : action;
869
+ }
870
+ function useDragHistory(initial, limit = 50) {
871
+ if (!Number.isSafeInteger(limit) || limit < 1)
872
+ throw new RangeError("\u5386\u53F2\u5BB9\u91CF\u987B\u4E3A\u6B63\u6574\u6570");
873
+ const [state, set] = useState(() => ({
874
+ past: [],
875
+ value: typeof initial === "function" ? initial() : initial,
876
+ future: []
877
+ }));
878
+ function commit(action, itemId) {
879
+ set((current) => {
880
+ const value = resolve(action, current.value);
881
+ if (Object.is(value, current.value)) return current;
1943
882
  return {
1944
- indexed: indexDragDocument(
1945
- source ?? compileDragStructure(children),
1946
- 0,
1947
- (value) => value
1948
- )
883
+ past: [...current.past, { value: current.value, itemId }].slice(-limit),
884
+ value,
885
+ future: []
1949
886
  };
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
887
  });
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
888
  }
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();
889
+ function reset(action) {
890
+ set((current) => ({
891
+ past: [],
892
+ value: resolve(action, current.value),
893
+ future: []
894
+ }));
895
+ }
896
+ function replay(direction) {
897
+ set((current) => {
898
+ const undoing = direction === "undo";
899
+ const source = undoing ? current.past : current.future;
900
+ const entry = source[source.length - 1];
901
+ if (!entry) return current;
902
+ const inverse = { value: current.value, itemId: entry.itemId };
903
+ return {
904
+ past: undoing ? source.slice(0, -1) : [...current.past, inverse].slice(-limit),
905
+ value: entry.value,
906
+ future: undoing ? [...current.future, inverse] : source.slice(0, -1),
907
+ transition: { itemId: entry.itemId }
908
+ };
2085
909
  });
2086
910
  }
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
- );
911
+ return {
912
+ value: state.value,
913
+ commit,
914
+ reset,
915
+ undo: () => replay("undo"),
916
+ redo: () => replay("redo"),
917
+ canUndo: !!state.past.length,
918
+ canRedo: !!state.future.length,
919
+ transition: state.transition
920
+ };
2111
921
  }
2112
- var ReactDragAnyGroup = forwardRef(Group);
2113
922
 
2114
- export { Card, ContentCompileError, Flow, GridSlot, Lane, Lanes, Queue, ReactDragAny, ReactDragAnyGroup, SparseGrid, compileJSX, createContentBindings };
923
+ export { Drag, useDragHistory };