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