@canvas-components/react-drag-any 1.0.4 → 2.0.1

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