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