multi-content-type-relation 2.1.2 → 2.2.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.
@@ -1,3565 +0,0 @@
1
- import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import React, { useState, useEffect, useMemo, useLayoutEffect, useRef, useCallback, memo, useReducer, createContext, useContext } from "react";
3
- import { useIntl } from "react-intl";
4
- import { useLocation } from "react-router-dom";
5
- import { Status as Status$1, Typography, Tr, Td, IconButton, Flex, Box, Table, Thead, Th, Tbody, Loader, Field, TextInput, DesignSystemProvider } from "@strapi/design-system";
6
- import { f as fetchMatchingContent, u as useTranslate, g as getContentTypeForUid, a as formatToStrapiField, v as validateCurrentRelations } from "./index-DdX2rVzB.mjs";
7
- import { unstable_batchedUpdates, createPortal } from "react-dom";
8
- import { useSortable, SortableContext, verticalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
9
- import { Drag, Eye, Plus, Trash } from "@strapi/icons";
10
- function useSearchedEntries(keyword, contentTypes, locale) {
11
- const [loading, setLoading] = useState(false);
12
- const [results, setResults] = useState([]);
13
- const [total, setTotal] = useState(0);
14
- async function fetchEntries() {
15
- setResults([]);
16
- setTotal(0);
17
- if (loading || !keyword) return;
18
- try {
19
- const { data, total: total2 } = await fetchMatchingContent(
20
- keyword,
21
- contentTypes,
22
- locale
23
- );
24
- setResults(data);
25
- setTotal(total2);
26
- } finally {
27
- setLoading(false);
28
- }
29
- }
30
- useEffect(() => {
31
- const timeout = setTimeout(() => fetchEntries(), 500);
32
- return () => clearTimeout(timeout);
33
- }, [keyword]);
34
- return useMemo(
35
- () => ({
36
- loading,
37
- results,
38
- total
39
- }),
40
- [results, total]
41
- );
42
- }
43
- const canUseDOM = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
44
- function isWindow(element) {
45
- const elementString = Object.prototype.toString.call(element);
46
- return elementString === "[object Window]" || // In Electron context the Window object serializes to [object global]
47
- elementString === "[object global]";
48
- }
49
- function isNode(node) {
50
- return "nodeType" in node;
51
- }
52
- function getWindow(target) {
53
- var _target$ownerDocument, _target$ownerDocument2;
54
- if (!target) {
55
- return window;
56
- }
57
- if (isWindow(target)) {
58
- return target;
59
- }
60
- if (!isNode(target)) {
61
- return window;
62
- }
63
- return (_target$ownerDocument = (_target$ownerDocument2 = target.ownerDocument) == null ? void 0 : _target$ownerDocument2.defaultView) != null ? _target$ownerDocument : window;
64
- }
65
- function isDocument(node) {
66
- const {
67
- Document
68
- } = getWindow(node);
69
- return node instanceof Document;
70
- }
71
- function isHTMLElement(node) {
72
- if (isWindow(node)) {
73
- return false;
74
- }
75
- return node instanceof getWindow(node).HTMLElement;
76
- }
77
- function isSVGElement(node) {
78
- return node instanceof getWindow(node).SVGElement;
79
- }
80
- function getOwnerDocument(target) {
81
- if (!target) {
82
- return document;
83
- }
84
- if (isWindow(target)) {
85
- return target.document;
86
- }
87
- if (!isNode(target)) {
88
- return document;
89
- }
90
- if (isDocument(target)) {
91
- return target;
92
- }
93
- if (isHTMLElement(target) || isSVGElement(target)) {
94
- return target.ownerDocument;
95
- }
96
- return document;
97
- }
98
- const useIsomorphicLayoutEffect = canUseDOM ? useLayoutEffect : useEffect;
99
- function useEvent(handler) {
100
- const handlerRef = useRef(handler);
101
- useIsomorphicLayoutEffect(() => {
102
- handlerRef.current = handler;
103
- });
104
- return useCallback(function() {
105
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
106
- args[_key] = arguments[_key];
107
- }
108
- return handlerRef.current == null ? void 0 : handlerRef.current(...args);
109
- }, []);
110
- }
111
- function useInterval() {
112
- const intervalRef = useRef(null);
113
- const set = useCallback((listener, duration) => {
114
- intervalRef.current = setInterval(listener, duration);
115
- }, []);
116
- const clear = useCallback(() => {
117
- if (intervalRef.current !== null) {
118
- clearInterval(intervalRef.current);
119
- intervalRef.current = null;
120
- }
121
- }, []);
122
- return [set, clear];
123
- }
124
- function useLatestValue(value, dependencies) {
125
- if (dependencies === void 0) {
126
- dependencies = [value];
127
- }
128
- const valueRef = useRef(value);
129
- useIsomorphicLayoutEffect(() => {
130
- if (valueRef.current !== value) {
131
- valueRef.current = value;
132
- }
133
- }, dependencies);
134
- return valueRef;
135
- }
136
- function useLazyMemo(callback, dependencies) {
137
- const valueRef = useRef();
138
- return useMemo(
139
- () => {
140
- const newValue = callback(valueRef.current);
141
- valueRef.current = newValue;
142
- return newValue;
143
- },
144
- // eslint-disable-next-line react-hooks/exhaustive-deps
145
- [...dependencies]
146
- );
147
- }
148
- function useNodeRef(onChange) {
149
- const onChangeHandler = useEvent(onChange);
150
- const node = useRef(null);
151
- const setNodeRef = useCallback(
152
- (element) => {
153
- if (element !== node.current) {
154
- onChangeHandler == null ? void 0 : onChangeHandler(element, node.current);
155
- }
156
- node.current = element;
157
- },
158
- //eslint-disable-next-line
159
- []
160
- );
161
- return [node, setNodeRef];
162
- }
163
- function usePrevious(value) {
164
- const ref = useRef();
165
- useEffect(() => {
166
- ref.current = value;
167
- }, [value]);
168
- return ref.current;
169
- }
170
- let ids = {};
171
- function useUniqueId(prefix, value) {
172
- return useMemo(() => {
173
- if (value) {
174
- return value;
175
- }
176
- const id = ids[prefix] == null ? 0 : ids[prefix] + 1;
177
- ids[prefix] = id;
178
- return prefix + "-" + id;
179
- }, [prefix, value]);
180
- }
181
- function createAdjustmentFn(modifier) {
182
- return function(object) {
183
- for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
184
- adjustments[_key - 1] = arguments[_key];
185
- }
186
- return adjustments.reduce((accumulator, adjustment) => {
187
- const entries = Object.entries(adjustment);
188
- for (const [key, valueAdjustment] of entries) {
189
- const value = accumulator[key];
190
- if (value != null) {
191
- accumulator[key] = value + modifier * valueAdjustment;
192
- }
193
- }
194
- return accumulator;
195
- }, {
196
- ...object
197
- });
198
- };
199
- }
200
- const add = /* @__PURE__ */ createAdjustmentFn(1);
201
- const subtract = /* @__PURE__ */ createAdjustmentFn(-1);
202
- function hasViewportRelativeCoordinates(event) {
203
- return "clientX" in event && "clientY" in event;
204
- }
205
- function isKeyboardEvent(event) {
206
- if (!event) {
207
- return false;
208
- }
209
- const {
210
- KeyboardEvent
211
- } = getWindow(event.target);
212
- return KeyboardEvent && event instanceof KeyboardEvent;
213
- }
214
- function isTouchEvent(event) {
215
- if (!event) {
216
- return false;
217
- }
218
- const {
219
- TouchEvent
220
- } = getWindow(event.target);
221
- return TouchEvent && event instanceof TouchEvent;
222
- }
223
- function getEventCoordinates(event) {
224
- if (isTouchEvent(event)) {
225
- if (event.touches && event.touches.length) {
226
- const {
227
- clientX: x,
228
- clientY: y
229
- } = event.touches[0];
230
- return {
231
- x,
232
- y
233
- };
234
- } else if (event.changedTouches && event.changedTouches.length) {
235
- const {
236
- clientX: x,
237
- clientY: y
238
- } = event.changedTouches[0];
239
- return {
240
- x,
241
- y
242
- };
243
- }
244
- }
245
- if (hasViewportRelativeCoordinates(event)) {
246
- return {
247
- x: event.clientX,
248
- y: event.clientY
249
- };
250
- }
251
- return null;
252
- }
253
- const CSS = /* @__PURE__ */ Object.freeze({
254
- Translate: {
255
- toString(transform) {
256
- if (!transform) {
257
- return;
258
- }
259
- const {
260
- x,
261
- y
262
- } = transform;
263
- return "translate3d(" + (x ? Math.round(x) : 0) + "px, " + (y ? Math.round(y) : 0) + "px, 0)";
264
- }
265
- },
266
- Scale: {
267
- toString(transform) {
268
- if (!transform) {
269
- return;
270
- }
271
- const {
272
- scaleX,
273
- scaleY
274
- } = transform;
275
- return "scaleX(" + scaleX + ") scaleY(" + scaleY + ")";
276
- }
277
- },
278
- Transform: {
279
- toString(transform) {
280
- if (!transform) {
281
- return;
282
- }
283
- return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(" ");
284
- }
285
- },
286
- Transition: {
287
- toString(_ref) {
288
- let {
289
- property,
290
- duration,
291
- easing
292
- } = _ref;
293
- return property + " " + duration + "ms " + easing;
294
- }
295
- }
296
- });
297
- const SELECTOR = "a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";
298
- function findFirstFocusableNode(element) {
299
- if (element.matches(SELECTOR)) {
300
- return element;
301
- }
302
- return element.querySelector(SELECTOR);
303
- }
304
- const hiddenStyles = {
305
- display: "none"
306
- };
307
- function HiddenText(_ref) {
308
- let {
309
- id,
310
- value
311
- } = _ref;
312
- return React.createElement("div", {
313
- id,
314
- style: hiddenStyles
315
- }, value);
316
- }
317
- function LiveRegion(_ref) {
318
- let {
319
- id,
320
- announcement,
321
- ariaLiveType = "assertive"
322
- } = _ref;
323
- const visuallyHidden = {
324
- position: "fixed",
325
- top: 0,
326
- left: 0,
327
- width: 1,
328
- height: 1,
329
- margin: -1,
330
- border: 0,
331
- padding: 0,
332
- overflow: "hidden",
333
- clip: "rect(0 0 0 0)",
334
- clipPath: "inset(100%)",
335
- whiteSpace: "nowrap"
336
- };
337
- return React.createElement("div", {
338
- id,
339
- style: visuallyHidden,
340
- role: "status",
341
- "aria-live": ariaLiveType,
342
- "aria-atomic": true
343
- }, announcement);
344
- }
345
- function useAnnouncement() {
346
- const [announcement, setAnnouncement] = useState("");
347
- const announce = useCallback((value) => {
348
- if (value != null) {
349
- setAnnouncement(value);
350
- }
351
- }, []);
352
- return {
353
- announce,
354
- announcement
355
- };
356
- }
357
- const DndMonitorContext = /* @__PURE__ */ createContext(null);
358
- function useDndMonitor(listener) {
359
- const registerListener = useContext(DndMonitorContext);
360
- useEffect(() => {
361
- if (!registerListener) {
362
- throw new Error("useDndMonitor must be used within a children of <DndContext>");
363
- }
364
- const unsubscribe = registerListener(listener);
365
- return unsubscribe;
366
- }, [listener, registerListener]);
367
- }
368
- function useDndMonitorProvider() {
369
- const [listeners] = useState(() => /* @__PURE__ */ new Set());
370
- const registerListener = useCallback((listener) => {
371
- listeners.add(listener);
372
- return () => listeners.delete(listener);
373
- }, [listeners]);
374
- const dispatch = useCallback((_ref) => {
375
- let {
376
- type,
377
- event
378
- } = _ref;
379
- listeners.forEach((listener) => {
380
- var _listener$type;
381
- return (_listener$type = listener[type]) == null ? void 0 : _listener$type.call(listener, event);
382
- });
383
- }, [listeners]);
384
- return [dispatch, registerListener];
385
- }
386
- const defaultScreenReaderInstructions = {
387
- draggable: "\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n "
388
- };
389
- const defaultAnnouncements = {
390
- onDragStart(_ref) {
391
- let {
392
- active
393
- } = _ref;
394
- return "Picked up draggable item " + active.id + ".";
395
- },
396
- onDragOver(_ref2) {
397
- let {
398
- active,
399
- over
400
- } = _ref2;
401
- if (over) {
402
- return "Draggable item " + active.id + " was moved over droppable area " + over.id + ".";
403
- }
404
- return "Draggable item " + active.id + " is no longer over a droppable area.";
405
- },
406
- onDragEnd(_ref3) {
407
- let {
408
- active,
409
- over
410
- } = _ref3;
411
- if (over) {
412
- return "Draggable item " + active.id + " was dropped over droppable area " + over.id;
413
- }
414
- return "Draggable item " + active.id + " was dropped.";
415
- },
416
- onDragCancel(_ref4) {
417
- let {
418
- active
419
- } = _ref4;
420
- return "Dragging was cancelled. Draggable item " + active.id + " was dropped.";
421
- }
422
- };
423
- function Accessibility(_ref) {
424
- let {
425
- announcements = defaultAnnouncements,
426
- container,
427
- hiddenTextDescribedById,
428
- screenReaderInstructions = defaultScreenReaderInstructions
429
- } = _ref;
430
- const {
431
- announce,
432
- announcement
433
- } = useAnnouncement();
434
- const liveRegionId = useUniqueId("DndLiveRegion");
435
- const [mounted, setMounted] = useState(false);
436
- useEffect(() => {
437
- setMounted(true);
438
- }, []);
439
- useDndMonitor(useMemo(() => ({
440
- onDragStart(_ref2) {
441
- let {
442
- active
443
- } = _ref2;
444
- announce(announcements.onDragStart({
445
- active
446
- }));
447
- },
448
- onDragMove(_ref3) {
449
- let {
450
- active,
451
- over
452
- } = _ref3;
453
- if (announcements.onDragMove) {
454
- announce(announcements.onDragMove({
455
- active,
456
- over
457
- }));
458
- }
459
- },
460
- onDragOver(_ref4) {
461
- let {
462
- active,
463
- over
464
- } = _ref4;
465
- announce(announcements.onDragOver({
466
- active,
467
- over
468
- }));
469
- },
470
- onDragEnd(_ref5) {
471
- let {
472
- active,
473
- over
474
- } = _ref5;
475
- announce(announcements.onDragEnd({
476
- active,
477
- over
478
- }));
479
- },
480
- onDragCancel(_ref6) {
481
- let {
482
- active,
483
- over
484
- } = _ref6;
485
- announce(announcements.onDragCancel({
486
- active,
487
- over
488
- }));
489
- }
490
- }), [announce, announcements]));
491
- if (!mounted) {
492
- return null;
493
- }
494
- const markup = React.createElement(React.Fragment, null, React.createElement(HiddenText, {
495
- id: hiddenTextDescribedById,
496
- value: screenReaderInstructions.draggable
497
- }), React.createElement(LiveRegion, {
498
- id: liveRegionId,
499
- announcement
500
- }));
501
- return container ? createPortal(markup, container) : markup;
502
- }
503
- var Action;
504
- (function(Action2) {
505
- Action2["DragStart"] = "dragStart";
506
- Action2["DragMove"] = "dragMove";
507
- Action2["DragEnd"] = "dragEnd";
508
- Action2["DragCancel"] = "dragCancel";
509
- Action2["DragOver"] = "dragOver";
510
- Action2["RegisterDroppable"] = "registerDroppable";
511
- Action2["SetDroppableDisabled"] = "setDroppableDisabled";
512
- Action2["UnregisterDroppable"] = "unregisterDroppable";
513
- })(Action || (Action = {}));
514
- function noop() {
515
- }
516
- function useSensor(sensor, options) {
517
- return useMemo(
518
- () => ({
519
- sensor,
520
- options: options != null ? options : {}
521
- }),
522
- // eslint-disable-next-line react-hooks/exhaustive-deps
523
- [sensor, options]
524
- );
525
- }
526
- function useSensors() {
527
- for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) {
528
- sensors[_key] = arguments[_key];
529
- }
530
- return useMemo(
531
- () => [...sensors].filter((sensor) => sensor != null),
532
- // eslint-disable-next-line react-hooks/exhaustive-deps
533
- [...sensors]
534
- );
535
- }
536
- const defaultCoordinates = /* @__PURE__ */ Object.freeze({
537
- x: 0,
538
- y: 0
539
- });
540
- function distanceBetween(p1, p2) {
541
- return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
542
- }
543
- function sortCollisionsAsc(_ref, _ref2) {
544
- let {
545
- data: {
546
- value: a
547
- }
548
- } = _ref;
549
- let {
550
- data: {
551
- value: b
552
- }
553
- } = _ref2;
554
- return a - b;
555
- }
556
- function sortCollisionsDesc(_ref3, _ref4) {
557
- let {
558
- data: {
559
- value: a
560
- }
561
- } = _ref3;
562
- let {
563
- data: {
564
- value: b
565
- }
566
- } = _ref4;
567
- return b - a;
568
- }
569
- function getFirstCollision(collisions, property) {
570
- if (!collisions || collisions.length === 0) {
571
- return null;
572
- }
573
- const [firstCollision] = collisions;
574
- return firstCollision[property];
575
- }
576
- function centerOfRectangle(rect, left, top) {
577
- if (left === void 0) {
578
- left = rect.left;
579
- }
580
- if (top === void 0) {
581
- top = rect.top;
582
- }
583
- return {
584
- x: left + rect.width * 0.5,
585
- y: top + rect.height * 0.5
586
- };
587
- }
588
- const closestCenter = (_ref) => {
589
- let {
590
- collisionRect,
591
- droppableRects,
592
- droppableContainers
593
- } = _ref;
594
- const centerRect = centerOfRectangle(collisionRect, collisionRect.left, collisionRect.top);
595
- const collisions = [];
596
- for (const droppableContainer of droppableContainers) {
597
- const {
598
- id
599
- } = droppableContainer;
600
- const rect = droppableRects.get(id);
601
- if (rect) {
602
- const distBetween = distanceBetween(centerOfRectangle(rect), centerRect);
603
- collisions.push({
604
- id,
605
- data: {
606
- droppableContainer,
607
- value: distBetween
608
- }
609
- });
610
- }
611
- }
612
- return collisions.sort(sortCollisionsAsc);
613
- };
614
- function getIntersectionRatio(entry, target) {
615
- const top = Math.max(target.top, entry.top);
616
- const left = Math.max(target.left, entry.left);
617
- const right = Math.min(target.left + target.width, entry.left + entry.width);
618
- const bottom = Math.min(target.top + target.height, entry.top + entry.height);
619
- const width = right - left;
620
- const height = bottom - top;
621
- if (left < right && top < bottom) {
622
- const targetArea = target.width * target.height;
623
- const entryArea = entry.width * entry.height;
624
- const intersectionArea = width * height;
625
- const intersectionRatio = intersectionArea / (targetArea + entryArea - intersectionArea);
626
- return Number(intersectionRatio.toFixed(4));
627
- }
628
- return 0;
629
- }
630
- const rectIntersection = (_ref) => {
631
- let {
632
- collisionRect,
633
- droppableRects,
634
- droppableContainers
635
- } = _ref;
636
- const collisions = [];
637
- for (const droppableContainer of droppableContainers) {
638
- const {
639
- id
640
- } = droppableContainer;
641
- const rect = droppableRects.get(id);
642
- if (rect) {
643
- const intersectionRatio = getIntersectionRatio(rect, collisionRect);
644
- if (intersectionRatio > 0) {
645
- collisions.push({
646
- id,
647
- data: {
648
- droppableContainer,
649
- value: intersectionRatio
650
- }
651
- });
652
- }
653
- }
654
- }
655
- return collisions.sort(sortCollisionsDesc);
656
- };
657
- function adjustScale(transform, rect1, rect2) {
658
- return {
659
- ...transform,
660
- scaleX: rect1 && rect2 ? rect1.width / rect2.width : 1,
661
- scaleY: rect1 && rect2 ? rect1.height / rect2.height : 1
662
- };
663
- }
664
- function getRectDelta(rect1, rect2) {
665
- return rect1 && rect2 ? {
666
- x: rect1.left - rect2.left,
667
- y: rect1.top - rect2.top
668
- } : defaultCoordinates;
669
- }
670
- function createRectAdjustmentFn(modifier) {
671
- return function adjustClientRect(rect) {
672
- for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
673
- adjustments[_key - 1] = arguments[_key];
674
- }
675
- return adjustments.reduce((acc, adjustment) => ({
676
- ...acc,
677
- top: acc.top + modifier * adjustment.y,
678
- bottom: acc.bottom + modifier * adjustment.y,
679
- left: acc.left + modifier * adjustment.x,
680
- right: acc.right + modifier * adjustment.x
681
- }), {
682
- ...rect
683
- });
684
- };
685
- }
686
- const getAdjustedRect = /* @__PURE__ */ createRectAdjustmentFn(1);
687
- function parseTransform(transform) {
688
- if (transform.startsWith("matrix3d(")) {
689
- const transformArray = transform.slice(9, -1).split(/, /);
690
- return {
691
- x: +transformArray[12],
692
- y: +transformArray[13],
693
- scaleX: +transformArray[0],
694
- scaleY: +transformArray[5]
695
- };
696
- } else if (transform.startsWith("matrix(")) {
697
- const transformArray = transform.slice(7, -1).split(/, /);
698
- return {
699
- x: +transformArray[4],
700
- y: +transformArray[5],
701
- scaleX: +transformArray[0],
702
- scaleY: +transformArray[3]
703
- };
704
- }
705
- return null;
706
- }
707
- function inverseTransform(rect, transform, transformOrigin) {
708
- const parsedTransform = parseTransform(transform);
709
- if (!parsedTransform) {
710
- return rect;
711
- }
712
- const {
713
- scaleX,
714
- scaleY,
715
- x: translateX,
716
- y: translateY
717
- } = parsedTransform;
718
- const x = rect.left - translateX - (1 - scaleX) * parseFloat(transformOrigin);
719
- const y = rect.top - translateY - (1 - scaleY) * parseFloat(transformOrigin.slice(transformOrigin.indexOf(" ") + 1));
720
- const w = scaleX ? rect.width / scaleX : rect.width;
721
- const h = scaleY ? rect.height / scaleY : rect.height;
722
- return {
723
- width: w,
724
- height: h,
725
- top: y,
726
- right: x + w,
727
- bottom: y + h,
728
- left: x
729
- };
730
- }
731
- const defaultOptions = {
732
- ignoreTransform: false
733
- };
734
- function getClientRect(element, options) {
735
- if (options === void 0) {
736
- options = defaultOptions;
737
- }
738
- let rect = element.getBoundingClientRect();
739
- if (options.ignoreTransform) {
740
- const {
741
- transform,
742
- transformOrigin
743
- } = getWindow(element).getComputedStyle(element);
744
- if (transform) {
745
- rect = inverseTransform(rect, transform, transformOrigin);
746
- }
747
- }
748
- const {
749
- top,
750
- left,
751
- width,
752
- height,
753
- bottom,
754
- right
755
- } = rect;
756
- return {
757
- top,
758
- left,
759
- width,
760
- height,
761
- bottom,
762
- right
763
- };
764
- }
765
- function getTransformAgnosticClientRect(element) {
766
- return getClientRect(element, {
767
- ignoreTransform: true
768
- });
769
- }
770
- function getWindowClientRect(element) {
771
- const width = element.innerWidth;
772
- const height = element.innerHeight;
773
- return {
774
- top: 0,
775
- left: 0,
776
- right: width,
777
- bottom: height,
778
- width,
779
- height
780
- };
781
- }
782
- function isFixed(node, computedStyle) {
783
- if (computedStyle === void 0) {
784
- computedStyle = getWindow(node).getComputedStyle(node);
785
- }
786
- return computedStyle.position === "fixed";
787
- }
788
- function isScrollable(element, computedStyle) {
789
- if (computedStyle === void 0) {
790
- computedStyle = getWindow(element).getComputedStyle(element);
791
- }
792
- const overflowRegex = /(auto|scroll|overlay)/;
793
- const properties2 = ["overflow", "overflowX", "overflowY"];
794
- return properties2.some((property) => {
795
- const value = computedStyle[property];
796
- return typeof value === "string" ? overflowRegex.test(value) : false;
797
- });
798
- }
799
- function getScrollableAncestors(element, limit) {
800
- const scrollParents = [];
801
- function findScrollableAncestors(node) {
802
- if (limit != null && scrollParents.length >= limit) {
803
- return scrollParents;
804
- }
805
- if (!node) {
806
- return scrollParents;
807
- }
808
- if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) {
809
- scrollParents.push(node.scrollingElement);
810
- return scrollParents;
811
- }
812
- if (!isHTMLElement(node) || isSVGElement(node)) {
813
- return scrollParents;
814
- }
815
- if (scrollParents.includes(node)) {
816
- return scrollParents;
817
- }
818
- const computedStyle = getWindow(element).getComputedStyle(node);
819
- if (node !== element) {
820
- if (isScrollable(node, computedStyle)) {
821
- scrollParents.push(node);
822
- }
823
- }
824
- if (isFixed(node, computedStyle)) {
825
- return scrollParents;
826
- }
827
- return findScrollableAncestors(node.parentNode);
828
- }
829
- if (!element) {
830
- return scrollParents;
831
- }
832
- return findScrollableAncestors(element);
833
- }
834
- function getFirstScrollableAncestor(node) {
835
- const [firstScrollableAncestor] = getScrollableAncestors(node, 1);
836
- return firstScrollableAncestor != null ? firstScrollableAncestor : null;
837
- }
838
- function getScrollableElement(element) {
839
- if (!canUseDOM || !element) {
840
- return null;
841
- }
842
- if (isWindow(element)) {
843
- return element;
844
- }
845
- if (!isNode(element)) {
846
- return null;
847
- }
848
- if (isDocument(element) || element === getOwnerDocument(element).scrollingElement) {
849
- return window;
850
- }
851
- if (isHTMLElement(element)) {
852
- return element;
853
- }
854
- return null;
855
- }
856
- function getScrollXCoordinate(element) {
857
- if (isWindow(element)) {
858
- return element.scrollX;
859
- }
860
- return element.scrollLeft;
861
- }
862
- function getScrollYCoordinate(element) {
863
- if (isWindow(element)) {
864
- return element.scrollY;
865
- }
866
- return element.scrollTop;
867
- }
868
- function getScrollCoordinates(element) {
869
- return {
870
- x: getScrollXCoordinate(element),
871
- y: getScrollYCoordinate(element)
872
- };
873
- }
874
- var Direction;
875
- (function(Direction2) {
876
- Direction2[Direction2["Forward"] = 1] = "Forward";
877
- Direction2[Direction2["Backward"] = -1] = "Backward";
878
- })(Direction || (Direction = {}));
879
- function isDocumentScrollingElement(element) {
880
- if (!canUseDOM || !element) {
881
- return false;
882
- }
883
- return element === document.scrollingElement;
884
- }
885
- function getScrollPosition(scrollingContainer) {
886
- const minScroll = {
887
- x: 0,
888
- y: 0
889
- };
890
- const dimensions = isDocumentScrollingElement(scrollingContainer) ? {
891
- height: window.innerHeight,
892
- width: window.innerWidth
893
- } : {
894
- height: scrollingContainer.clientHeight,
895
- width: scrollingContainer.clientWidth
896
- };
897
- const maxScroll = {
898
- x: scrollingContainer.scrollWidth - dimensions.width,
899
- y: scrollingContainer.scrollHeight - dimensions.height
900
- };
901
- const isTop = scrollingContainer.scrollTop <= minScroll.y;
902
- const isLeft = scrollingContainer.scrollLeft <= minScroll.x;
903
- const isBottom = scrollingContainer.scrollTop >= maxScroll.y;
904
- const isRight = scrollingContainer.scrollLeft >= maxScroll.x;
905
- return {
906
- isTop,
907
- isLeft,
908
- isBottom,
909
- isRight,
910
- maxScroll,
911
- minScroll
912
- };
913
- }
914
- const defaultThreshold = {
915
- x: 0.2,
916
- y: 0.2
917
- };
918
- function getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) {
919
- let {
920
- top,
921
- left,
922
- right,
923
- bottom
924
- } = _ref;
925
- if (acceleration === void 0) {
926
- acceleration = 10;
927
- }
928
- if (thresholdPercentage === void 0) {
929
- thresholdPercentage = defaultThreshold;
930
- }
931
- const {
932
- isTop,
933
- isBottom,
934
- isLeft,
935
- isRight
936
- } = getScrollPosition(scrollContainer);
937
- const direction = {
938
- x: 0,
939
- y: 0
940
- };
941
- const speed = {
942
- x: 0,
943
- y: 0
944
- };
945
- const threshold = {
946
- height: scrollContainerRect.height * thresholdPercentage.y,
947
- width: scrollContainerRect.width * thresholdPercentage.x
948
- };
949
- if (!isTop && top <= scrollContainerRect.top + threshold.height) {
950
- direction.y = Direction.Backward;
951
- speed.y = acceleration * Math.abs((scrollContainerRect.top + threshold.height - top) / threshold.height);
952
- } else if (!isBottom && bottom >= scrollContainerRect.bottom - threshold.height) {
953
- direction.y = Direction.Forward;
954
- speed.y = acceleration * Math.abs((scrollContainerRect.bottom - threshold.height - bottom) / threshold.height);
955
- }
956
- if (!isRight && right >= scrollContainerRect.right - threshold.width) {
957
- direction.x = Direction.Forward;
958
- speed.x = acceleration * Math.abs((scrollContainerRect.right - threshold.width - right) / threshold.width);
959
- } else if (!isLeft && left <= scrollContainerRect.left + threshold.width) {
960
- direction.x = Direction.Backward;
961
- speed.x = acceleration * Math.abs((scrollContainerRect.left + threshold.width - left) / threshold.width);
962
- }
963
- return {
964
- direction,
965
- speed
966
- };
967
- }
968
- function getScrollElementRect(element) {
969
- if (element === document.scrollingElement) {
970
- const {
971
- innerWidth,
972
- innerHeight
973
- } = window;
974
- return {
975
- top: 0,
976
- left: 0,
977
- right: innerWidth,
978
- bottom: innerHeight,
979
- width: innerWidth,
980
- height: innerHeight
981
- };
982
- }
983
- const {
984
- top,
985
- left,
986
- right,
987
- bottom
988
- } = element.getBoundingClientRect();
989
- return {
990
- top,
991
- left,
992
- right,
993
- bottom,
994
- width: element.clientWidth,
995
- height: element.clientHeight
996
- };
997
- }
998
- function getScrollOffsets(scrollableAncestors) {
999
- return scrollableAncestors.reduce((acc, node) => {
1000
- return add(acc, getScrollCoordinates(node));
1001
- }, defaultCoordinates);
1002
- }
1003
- function getScrollXOffset(scrollableAncestors) {
1004
- return scrollableAncestors.reduce((acc, node) => {
1005
- return acc + getScrollXCoordinate(node);
1006
- }, 0);
1007
- }
1008
- function getScrollYOffset(scrollableAncestors) {
1009
- return scrollableAncestors.reduce((acc, node) => {
1010
- return acc + getScrollYCoordinate(node);
1011
- }, 0);
1012
- }
1013
- function scrollIntoViewIfNeeded(element, measure) {
1014
- if (measure === void 0) {
1015
- measure = getClientRect;
1016
- }
1017
- if (!element) {
1018
- return;
1019
- }
1020
- const {
1021
- top,
1022
- left,
1023
- bottom,
1024
- right
1025
- } = measure(element);
1026
- const firstScrollableAncestor = getFirstScrollableAncestor(element);
1027
- if (!firstScrollableAncestor) {
1028
- return;
1029
- }
1030
- if (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) {
1031
- element.scrollIntoView({
1032
- block: "center",
1033
- inline: "center"
1034
- });
1035
- }
1036
- }
1037
- const properties = [["x", ["left", "right"], getScrollXOffset], ["y", ["top", "bottom"], getScrollYOffset]];
1038
- class Rect {
1039
- constructor(rect, element) {
1040
- this.rect = void 0;
1041
- this.width = void 0;
1042
- this.height = void 0;
1043
- this.top = void 0;
1044
- this.bottom = void 0;
1045
- this.right = void 0;
1046
- this.left = void 0;
1047
- const scrollableAncestors = getScrollableAncestors(element);
1048
- const scrollOffsets = getScrollOffsets(scrollableAncestors);
1049
- this.rect = {
1050
- ...rect
1051
- };
1052
- this.width = rect.width;
1053
- this.height = rect.height;
1054
- for (const [axis, keys, getScrollOffset] of properties) {
1055
- for (const key of keys) {
1056
- Object.defineProperty(this, key, {
1057
- get: () => {
1058
- const currentOffsets = getScrollOffset(scrollableAncestors);
1059
- const scrollOffsetsDeltla = scrollOffsets[axis] - currentOffsets;
1060
- return this.rect[key] + scrollOffsetsDeltla;
1061
- },
1062
- enumerable: true
1063
- });
1064
- }
1065
- }
1066
- Object.defineProperty(this, "rect", {
1067
- enumerable: false
1068
- });
1069
- }
1070
- }
1071
- class Listeners {
1072
- constructor(target) {
1073
- this.target = void 0;
1074
- this.listeners = [];
1075
- this.removeAll = () => {
1076
- this.listeners.forEach((listener) => {
1077
- var _this$target;
1078
- return (_this$target = this.target) == null ? void 0 : _this$target.removeEventListener(...listener);
1079
- });
1080
- };
1081
- this.target = target;
1082
- }
1083
- add(eventName, handler, options) {
1084
- var _this$target2;
1085
- (_this$target2 = this.target) == null ? void 0 : _this$target2.addEventListener(eventName, handler, options);
1086
- this.listeners.push([eventName, handler, options]);
1087
- }
1088
- }
1089
- function getEventListenerTarget(target) {
1090
- const {
1091
- EventTarget
1092
- } = getWindow(target);
1093
- return target instanceof EventTarget ? target : getOwnerDocument(target);
1094
- }
1095
- function hasExceededDistance(delta, measurement) {
1096
- const dx = Math.abs(delta.x);
1097
- const dy = Math.abs(delta.y);
1098
- if (typeof measurement === "number") {
1099
- return Math.sqrt(dx ** 2 + dy ** 2) > measurement;
1100
- }
1101
- if ("x" in measurement && "y" in measurement) {
1102
- return dx > measurement.x && dy > measurement.y;
1103
- }
1104
- if ("x" in measurement) {
1105
- return dx > measurement.x;
1106
- }
1107
- if ("y" in measurement) {
1108
- return dy > measurement.y;
1109
- }
1110
- return false;
1111
- }
1112
- var EventName;
1113
- (function(EventName2) {
1114
- EventName2["Click"] = "click";
1115
- EventName2["DragStart"] = "dragstart";
1116
- EventName2["Keydown"] = "keydown";
1117
- EventName2["ContextMenu"] = "contextmenu";
1118
- EventName2["Resize"] = "resize";
1119
- EventName2["SelectionChange"] = "selectionchange";
1120
- EventName2["VisibilityChange"] = "visibilitychange";
1121
- })(EventName || (EventName = {}));
1122
- function preventDefault(event) {
1123
- event.preventDefault();
1124
- }
1125
- function stopPropagation(event) {
1126
- event.stopPropagation();
1127
- }
1128
- var KeyboardCode;
1129
- (function(KeyboardCode2) {
1130
- KeyboardCode2["Space"] = "Space";
1131
- KeyboardCode2["Down"] = "ArrowDown";
1132
- KeyboardCode2["Right"] = "ArrowRight";
1133
- KeyboardCode2["Left"] = "ArrowLeft";
1134
- KeyboardCode2["Up"] = "ArrowUp";
1135
- KeyboardCode2["Esc"] = "Escape";
1136
- KeyboardCode2["Enter"] = "Enter";
1137
- KeyboardCode2["Tab"] = "Tab";
1138
- })(KeyboardCode || (KeyboardCode = {}));
1139
- const defaultKeyboardCodes = {
1140
- start: [KeyboardCode.Space, KeyboardCode.Enter],
1141
- cancel: [KeyboardCode.Esc],
1142
- end: [KeyboardCode.Space, KeyboardCode.Enter, KeyboardCode.Tab]
1143
- };
1144
- const defaultKeyboardCoordinateGetter = (event, _ref) => {
1145
- let {
1146
- currentCoordinates
1147
- } = _ref;
1148
- switch (event.code) {
1149
- case KeyboardCode.Right:
1150
- return {
1151
- ...currentCoordinates,
1152
- x: currentCoordinates.x + 25
1153
- };
1154
- case KeyboardCode.Left:
1155
- return {
1156
- ...currentCoordinates,
1157
- x: currentCoordinates.x - 25
1158
- };
1159
- case KeyboardCode.Down:
1160
- return {
1161
- ...currentCoordinates,
1162
- y: currentCoordinates.y + 25
1163
- };
1164
- case KeyboardCode.Up:
1165
- return {
1166
- ...currentCoordinates,
1167
- y: currentCoordinates.y - 25
1168
- };
1169
- }
1170
- return void 0;
1171
- };
1172
- class KeyboardSensor {
1173
- constructor(props) {
1174
- this.props = void 0;
1175
- this.autoScrollEnabled = false;
1176
- this.referenceCoordinates = void 0;
1177
- this.listeners = void 0;
1178
- this.windowListeners = void 0;
1179
- this.props = props;
1180
- const {
1181
- event: {
1182
- target
1183
- }
1184
- } = props;
1185
- this.props = props;
1186
- this.listeners = new Listeners(getOwnerDocument(target));
1187
- this.windowListeners = new Listeners(getWindow(target));
1188
- this.handleKeyDown = this.handleKeyDown.bind(this);
1189
- this.handleCancel = this.handleCancel.bind(this);
1190
- this.attach();
1191
- }
1192
- attach() {
1193
- this.handleStart();
1194
- this.windowListeners.add(EventName.Resize, this.handleCancel);
1195
- this.windowListeners.add(EventName.VisibilityChange, this.handleCancel);
1196
- setTimeout(() => this.listeners.add(EventName.Keydown, this.handleKeyDown));
1197
- }
1198
- handleStart() {
1199
- const {
1200
- activeNode,
1201
- onStart
1202
- } = this.props;
1203
- const node = activeNode.node.current;
1204
- if (node) {
1205
- scrollIntoViewIfNeeded(node);
1206
- }
1207
- onStart(defaultCoordinates);
1208
- }
1209
- handleKeyDown(event) {
1210
- if (isKeyboardEvent(event)) {
1211
- const {
1212
- active,
1213
- context,
1214
- options
1215
- } = this.props;
1216
- const {
1217
- keyboardCodes = defaultKeyboardCodes,
1218
- coordinateGetter = defaultKeyboardCoordinateGetter,
1219
- scrollBehavior = "smooth"
1220
- } = options;
1221
- const {
1222
- code
1223
- } = event;
1224
- if (keyboardCodes.end.includes(code)) {
1225
- this.handleEnd(event);
1226
- return;
1227
- }
1228
- if (keyboardCodes.cancel.includes(code)) {
1229
- this.handleCancel(event);
1230
- return;
1231
- }
1232
- const {
1233
- collisionRect
1234
- } = context.current;
1235
- const currentCoordinates = collisionRect ? {
1236
- x: collisionRect.left,
1237
- y: collisionRect.top
1238
- } : defaultCoordinates;
1239
- if (!this.referenceCoordinates) {
1240
- this.referenceCoordinates = currentCoordinates;
1241
- }
1242
- const newCoordinates = coordinateGetter(event, {
1243
- active,
1244
- context: context.current,
1245
- currentCoordinates
1246
- });
1247
- if (newCoordinates) {
1248
- const coordinatesDelta = subtract(newCoordinates, currentCoordinates);
1249
- const scrollDelta = {
1250
- x: 0,
1251
- y: 0
1252
- };
1253
- const {
1254
- scrollableAncestors
1255
- } = context.current;
1256
- for (const scrollContainer of scrollableAncestors) {
1257
- const direction = event.code;
1258
- const {
1259
- isTop,
1260
- isRight,
1261
- isLeft,
1262
- isBottom,
1263
- maxScroll,
1264
- minScroll
1265
- } = getScrollPosition(scrollContainer);
1266
- const scrollElementRect = getScrollElementRect(scrollContainer);
1267
- const clampedCoordinates = {
1268
- x: Math.min(direction === KeyboardCode.Right ? scrollElementRect.right - scrollElementRect.width / 2 : scrollElementRect.right, Math.max(direction === KeyboardCode.Right ? scrollElementRect.left : scrollElementRect.left + scrollElementRect.width / 2, newCoordinates.x)),
1269
- y: Math.min(direction === KeyboardCode.Down ? scrollElementRect.bottom - scrollElementRect.height / 2 : scrollElementRect.bottom, Math.max(direction === KeyboardCode.Down ? scrollElementRect.top : scrollElementRect.top + scrollElementRect.height / 2, newCoordinates.y))
1270
- };
1271
- const canScrollX = direction === KeyboardCode.Right && !isRight || direction === KeyboardCode.Left && !isLeft;
1272
- const canScrollY = direction === KeyboardCode.Down && !isBottom || direction === KeyboardCode.Up && !isTop;
1273
- if (canScrollX && clampedCoordinates.x !== newCoordinates.x) {
1274
- const newScrollCoordinates = scrollContainer.scrollLeft + coordinatesDelta.x;
1275
- const canScrollToNewCoordinates = direction === KeyboardCode.Right && newScrollCoordinates <= maxScroll.x || direction === KeyboardCode.Left && newScrollCoordinates >= minScroll.x;
1276
- if (canScrollToNewCoordinates && !coordinatesDelta.y) {
1277
- scrollContainer.scrollTo({
1278
- left: newScrollCoordinates,
1279
- behavior: scrollBehavior
1280
- });
1281
- return;
1282
- }
1283
- if (canScrollToNewCoordinates) {
1284
- scrollDelta.x = scrollContainer.scrollLeft - newScrollCoordinates;
1285
- } else {
1286
- scrollDelta.x = direction === KeyboardCode.Right ? scrollContainer.scrollLeft - maxScroll.x : scrollContainer.scrollLeft - minScroll.x;
1287
- }
1288
- if (scrollDelta.x) {
1289
- scrollContainer.scrollBy({
1290
- left: -scrollDelta.x,
1291
- behavior: scrollBehavior
1292
- });
1293
- }
1294
- break;
1295
- } else if (canScrollY && clampedCoordinates.y !== newCoordinates.y) {
1296
- const newScrollCoordinates = scrollContainer.scrollTop + coordinatesDelta.y;
1297
- const canScrollToNewCoordinates = direction === KeyboardCode.Down && newScrollCoordinates <= maxScroll.y || direction === KeyboardCode.Up && newScrollCoordinates >= minScroll.y;
1298
- if (canScrollToNewCoordinates && !coordinatesDelta.x) {
1299
- scrollContainer.scrollTo({
1300
- top: newScrollCoordinates,
1301
- behavior: scrollBehavior
1302
- });
1303
- return;
1304
- }
1305
- if (canScrollToNewCoordinates) {
1306
- scrollDelta.y = scrollContainer.scrollTop - newScrollCoordinates;
1307
- } else {
1308
- scrollDelta.y = direction === KeyboardCode.Down ? scrollContainer.scrollTop - maxScroll.y : scrollContainer.scrollTop - minScroll.y;
1309
- }
1310
- if (scrollDelta.y) {
1311
- scrollContainer.scrollBy({
1312
- top: -scrollDelta.y,
1313
- behavior: scrollBehavior
1314
- });
1315
- }
1316
- break;
1317
- }
1318
- }
1319
- this.handleMove(event, add(subtract(newCoordinates, this.referenceCoordinates), scrollDelta));
1320
- }
1321
- }
1322
- }
1323
- handleMove(event, coordinates) {
1324
- const {
1325
- onMove
1326
- } = this.props;
1327
- event.preventDefault();
1328
- onMove(coordinates);
1329
- }
1330
- handleEnd(event) {
1331
- const {
1332
- onEnd
1333
- } = this.props;
1334
- event.preventDefault();
1335
- this.detach();
1336
- onEnd();
1337
- }
1338
- handleCancel(event) {
1339
- const {
1340
- onCancel
1341
- } = this.props;
1342
- event.preventDefault();
1343
- this.detach();
1344
- onCancel();
1345
- }
1346
- detach() {
1347
- this.listeners.removeAll();
1348
- this.windowListeners.removeAll();
1349
- }
1350
- }
1351
- KeyboardSensor.activators = [{
1352
- eventName: "onKeyDown",
1353
- handler: (event, _ref, _ref2) => {
1354
- let {
1355
- keyboardCodes = defaultKeyboardCodes,
1356
- onActivation
1357
- } = _ref;
1358
- let {
1359
- active
1360
- } = _ref2;
1361
- const {
1362
- code
1363
- } = event.nativeEvent;
1364
- if (keyboardCodes.start.includes(code)) {
1365
- const activator = active.activatorNode.current;
1366
- if (activator && event.target !== activator) {
1367
- return false;
1368
- }
1369
- event.preventDefault();
1370
- onActivation == null ? void 0 : onActivation({
1371
- event: event.nativeEvent
1372
- });
1373
- return true;
1374
- }
1375
- return false;
1376
- }
1377
- }];
1378
- function isDistanceConstraint(constraint) {
1379
- return Boolean(constraint && "distance" in constraint);
1380
- }
1381
- function isDelayConstraint(constraint) {
1382
- return Boolean(constraint && "delay" in constraint);
1383
- }
1384
- class AbstractPointerSensor {
1385
- constructor(props, events2, listenerTarget) {
1386
- var _getEventCoordinates;
1387
- if (listenerTarget === void 0) {
1388
- listenerTarget = getEventListenerTarget(props.event.target);
1389
- }
1390
- this.props = void 0;
1391
- this.events = void 0;
1392
- this.autoScrollEnabled = true;
1393
- this.document = void 0;
1394
- this.activated = false;
1395
- this.initialCoordinates = void 0;
1396
- this.timeoutId = null;
1397
- this.listeners = void 0;
1398
- this.documentListeners = void 0;
1399
- this.windowListeners = void 0;
1400
- this.props = props;
1401
- this.events = events2;
1402
- const {
1403
- event
1404
- } = props;
1405
- const {
1406
- target
1407
- } = event;
1408
- this.props = props;
1409
- this.events = events2;
1410
- this.document = getOwnerDocument(target);
1411
- this.documentListeners = new Listeners(this.document);
1412
- this.listeners = new Listeners(listenerTarget);
1413
- this.windowListeners = new Listeners(getWindow(target));
1414
- this.initialCoordinates = (_getEventCoordinates = getEventCoordinates(event)) != null ? _getEventCoordinates : defaultCoordinates;
1415
- this.handleStart = this.handleStart.bind(this);
1416
- this.handleMove = this.handleMove.bind(this);
1417
- this.handleEnd = this.handleEnd.bind(this);
1418
- this.handleCancel = this.handleCancel.bind(this);
1419
- this.handleKeydown = this.handleKeydown.bind(this);
1420
- this.removeTextSelection = this.removeTextSelection.bind(this);
1421
- this.attach();
1422
- }
1423
- attach() {
1424
- const {
1425
- events: events2,
1426
- props: {
1427
- options: {
1428
- activationConstraint,
1429
- bypassActivationConstraint
1430
- }
1431
- }
1432
- } = this;
1433
- this.listeners.add(events2.move.name, this.handleMove, {
1434
- passive: false
1435
- });
1436
- this.listeners.add(events2.end.name, this.handleEnd);
1437
- if (events2.cancel) {
1438
- this.listeners.add(events2.cancel.name, this.handleCancel);
1439
- }
1440
- this.windowListeners.add(EventName.Resize, this.handleCancel);
1441
- this.windowListeners.add(EventName.DragStart, preventDefault);
1442
- this.windowListeners.add(EventName.VisibilityChange, this.handleCancel);
1443
- this.windowListeners.add(EventName.ContextMenu, preventDefault);
1444
- this.documentListeners.add(EventName.Keydown, this.handleKeydown);
1445
- if (activationConstraint) {
1446
- if (bypassActivationConstraint != null && bypassActivationConstraint({
1447
- event: this.props.event,
1448
- activeNode: this.props.activeNode,
1449
- options: this.props.options
1450
- })) {
1451
- return this.handleStart();
1452
- }
1453
- if (isDelayConstraint(activationConstraint)) {
1454
- this.timeoutId = setTimeout(this.handleStart, activationConstraint.delay);
1455
- this.handlePending(activationConstraint);
1456
- return;
1457
- }
1458
- if (isDistanceConstraint(activationConstraint)) {
1459
- this.handlePending(activationConstraint);
1460
- return;
1461
- }
1462
- }
1463
- this.handleStart();
1464
- }
1465
- detach() {
1466
- this.listeners.removeAll();
1467
- this.windowListeners.removeAll();
1468
- setTimeout(this.documentListeners.removeAll, 50);
1469
- if (this.timeoutId !== null) {
1470
- clearTimeout(this.timeoutId);
1471
- this.timeoutId = null;
1472
- }
1473
- }
1474
- handlePending(constraint, offset) {
1475
- const {
1476
- active,
1477
- onPending
1478
- } = this.props;
1479
- onPending(active, constraint, this.initialCoordinates, offset);
1480
- }
1481
- handleStart() {
1482
- const {
1483
- initialCoordinates
1484
- } = this;
1485
- const {
1486
- onStart
1487
- } = this.props;
1488
- if (initialCoordinates) {
1489
- this.activated = true;
1490
- this.documentListeners.add(EventName.Click, stopPropagation, {
1491
- capture: true
1492
- });
1493
- this.removeTextSelection();
1494
- this.documentListeners.add(EventName.SelectionChange, this.removeTextSelection);
1495
- onStart(initialCoordinates);
1496
- }
1497
- }
1498
- handleMove(event) {
1499
- var _getEventCoordinates2;
1500
- const {
1501
- activated,
1502
- initialCoordinates,
1503
- props
1504
- } = this;
1505
- const {
1506
- onMove,
1507
- options: {
1508
- activationConstraint
1509
- }
1510
- } = props;
1511
- if (!initialCoordinates) {
1512
- return;
1513
- }
1514
- const coordinates = (_getEventCoordinates2 = getEventCoordinates(event)) != null ? _getEventCoordinates2 : defaultCoordinates;
1515
- const delta = subtract(initialCoordinates, coordinates);
1516
- if (!activated && activationConstraint) {
1517
- if (isDistanceConstraint(activationConstraint)) {
1518
- if (activationConstraint.tolerance != null && hasExceededDistance(delta, activationConstraint.tolerance)) {
1519
- return this.handleCancel();
1520
- }
1521
- if (hasExceededDistance(delta, activationConstraint.distance)) {
1522
- return this.handleStart();
1523
- }
1524
- }
1525
- if (isDelayConstraint(activationConstraint)) {
1526
- if (hasExceededDistance(delta, activationConstraint.tolerance)) {
1527
- return this.handleCancel();
1528
- }
1529
- }
1530
- this.handlePending(activationConstraint, delta);
1531
- return;
1532
- }
1533
- if (event.cancelable) {
1534
- event.preventDefault();
1535
- }
1536
- onMove(coordinates);
1537
- }
1538
- handleEnd() {
1539
- const {
1540
- onAbort,
1541
- onEnd
1542
- } = this.props;
1543
- this.detach();
1544
- if (!this.activated) {
1545
- onAbort(this.props.active);
1546
- }
1547
- onEnd();
1548
- }
1549
- handleCancel() {
1550
- const {
1551
- onAbort,
1552
- onCancel
1553
- } = this.props;
1554
- this.detach();
1555
- if (!this.activated) {
1556
- onAbort(this.props.active);
1557
- }
1558
- onCancel();
1559
- }
1560
- handleKeydown(event) {
1561
- if (event.code === KeyboardCode.Esc) {
1562
- this.handleCancel();
1563
- }
1564
- }
1565
- removeTextSelection() {
1566
- var _this$document$getSel;
1567
- (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges();
1568
- }
1569
- }
1570
- const events = {
1571
- cancel: {
1572
- name: "pointercancel"
1573
- },
1574
- move: {
1575
- name: "pointermove"
1576
- },
1577
- end: {
1578
- name: "pointerup"
1579
- }
1580
- };
1581
- class PointerSensor extends AbstractPointerSensor {
1582
- constructor(props) {
1583
- const {
1584
- event
1585
- } = props;
1586
- const listenerTarget = getOwnerDocument(event.target);
1587
- super(props, events, listenerTarget);
1588
- }
1589
- }
1590
- PointerSensor.activators = [{
1591
- eventName: "onPointerDown",
1592
- handler: (_ref, _ref2) => {
1593
- let {
1594
- nativeEvent: event
1595
- } = _ref;
1596
- let {
1597
- onActivation
1598
- } = _ref2;
1599
- if (!event.isPrimary || event.button !== 0) {
1600
- return false;
1601
- }
1602
- onActivation == null ? void 0 : onActivation({
1603
- event
1604
- });
1605
- return true;
1606
- }
1607
- }];
1608
- const events$1 = {
1609
- move: {
1610
- name: "mousemove"
1611
- },
1612
- end: {
1613
- name: "mouseup"
1614
- }
1615
- };
1616
- var MouseButton;
1617
- (function(MouseButton2) {
1618
- MouseButton2[MouseButton2["RightClick"] = 2] = "RightClick";
1619
- })(MouseButton || (MouseButton = {}));
1620
- class MouseSensor extends AbstractPointerSensor {
1621
- constructor(props) {
1622
- super(props, events$1, getOwnerDocument(props.event.target));
1623
- }
1624
- }
1625
- MouseSensor.activators = [{
1626
- eventName: "onMouseDown",
1627
- handler: (_ref, _ref2) => {
1628
- let {
1629
- nativeEvent: event
1630
- } = _ref;
1631
- let {
1632
- onActivation
1633
- } = _ref2;
1634
- if (event.button === MouseButton.RightClick) {
1635
- return false;
1636
- }
1637
- onActivation == null ? void 0 : onActivation({
1638
- event
1639
- });
1640
- return true;
1641
- }
1642
- }];
1643
- const events$2 = {
1644
- cancel: {
1645
- name: "touchcancel"
1646
- },
1647
- move: {
1648
- name: "touchmove"
1649
- },
1650
- end: {
1651
- name: "touchend"
1652
- }
1653
- };
1654
- class TouchSensor extends AbstractPointerSensor {
1655
- constructor(props) {
1656
- super(props, events$2);
1657
- }
1658
- static setup() {
1659
- window.addEventListener(events$2.move.name, noop2, {
1660
- capture: false,
1661
- passive: false
1662
- });
1663
- return function teardown() {
1664
- window.removeEventListener(events$2.move.name, noop2);
1665
- };
1666
- function noop2() {
1667
- }
1668
- }
1669
- }
1670
- TouchSensor.activators = [{
1671
- eventName: "onTouchStart",
1672
- handler: (_ref, _ref2) => {
1673
- let {
1674
- nativeEvent: event
1675
- } = _ref;
1676
- let {
1677
- onActivation
1678
- } = _ref2;
1679
- const {
1680
- touches
1681
- } = event;
1682
- if (touches.length > 1) {
1683
- return false;
1684
- }
1685
- onActivation == null ? void 0 : onActivation({
1686
- event
1687
- });
1688
- return true;
1689
- }
1690
- }];
1691
- var AutoScrollActivator;
1692
- (function(AutoScrollActivator2) {
1693
- AutoScrollActivator2[AutoScrollActivator2["Pointer"] = 0] = "Pointer";
1694
- AutoScrollActivator2[AutoScrollActivator2["DraggableRect"] = 1] = "DraggableRect";
1695
- })(AutoScrollActivator || (AutoScrollActivator = {}));
1696
- var TraversalOrder;
1697
- (function(TraversalOrder2) {
1698
- TraversalOrder2[TraversalOrder2["TreeOrder"] = 0] = "TreeOrder";
1699
- TraversalOrder2[TraversalOrder2["ReversedTreeOrder"] = 1] = "ReversedTreeOrder";
1700
- })(TraversalOrder || (TraversalOrder = {}));
1701
- function useAutoScroller(_ref) {
1702
- let {
1703
- acceleration,
1704
- activator = AutoScrollActivator.Pointer,
1705
- canScroll,
1706
- draggingRect,
1707
- enabled,
1708
- interval = 5,
1709
- order = TraversalOrder.TreeOrder,
1710
- pointerCoordinates,
1711
- scrollableAncestors,
1712
- scrollableAncestorRects,
1713
- delta,
1714
- threshold
1715
- } = _ref;
1716
- const scrollIntent = useScrollIntent({
1717
- delta,
1718
- disabled: !enabled
1719
- });
1720
- const [setAutoScrollInterval, clearAutoScrollInterval] = useInterval();
1721
- const scrollSpeed = useRef({
1722
- x: 0,
1723
- y: 0
1724
- });
1725
- const scrollDirection = useRef({
1726
- x: 0,
1727
- y: 0
1728
- });
1729
- const rect = useMemo(() => {
1730
- switch (activator) {
1731
- case AutoScrollActivator.Pointer:
1732
- return pointerCoordinates ? {
1733
- top: pointerCoordinates.y,
1734
- bottom: pointerCoordinates.y,
1735
- left: pointerCoordinates.x,
1736
- right: pointerCoordinates.x
1737
- } : null;
1738
- case AutoScrollActivator.DraggableRect:
1739
- return draggingRect;
1740
- }
1741
- }, [activator, draggingRect, pointerCoordinates]);
1742
- const scrollContainerRef = useRef(null);
1743
- const autoScroll = useCallback(() => {
1744
- const scrollContainer = scrollContainerRef.current;
1745
- if (!scrollContainer) {
1746
- return;
1747
- }
1748
- const scrollLeft = scrollSpeed.current.x * scrollDirection.current.x;
1749
- const scrollTop = scrollSpeed.current.y * scrollDirection.current.y;
1750
- scrollContainer.scrollBy(scrollLeft, scrollTop);
1751
- }, []);
1752
- const sortedScrollableAncestors = useMemo(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]);
1753
- useEffect(
1754
- () => {
1755
- if (!enabled || !scrollableAncestors.length || !rect) {
1756
- clearAutoScrollInterval();
1757
- return;
1758
- }
1759
- for (const scrollContainer of sortedScrollableAncestors) {
1760
- if ((canScroll == null ? void 0 : canScroll(scrollContainer)) === false) {
1761
- continue;
1762
- }
1763
- const index = scrollableAncestors.indexOf(scrollContainer);
1764
- const scrollContainerRect = scrollableAncestorRects[index];
1765
- if (!scrollContainerRect) {
1766
- continue;
1767
- }
1768
- const {
1769
- direction,
1770
- speed
1771
- } = getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, rect, acceleration, threshold);
1772
- for (const axis of ["x", "y"]) {
1773
- if (!scrollIntent[axis][direction[axis]]) {
1774
- speed[axis] = 0;
1775
- direction[axis] = 0;
1776
- }
1777
- }
1778
- if (speed.x > 0 || speed.y > 0) {
1779
- clearAutoScrollInterval();
1780
- scrollContainerRef.current = scrollContainer;
1781
- setAutoScrollInterval(autoScroll, interval);
1782
- scrollSpeed.current = speed;
1783
- scrollDirection.current = direction;
1784
- return;
1785
- }
1786
- }
1787
- scrollSpeed.current = {
1788
- x: 0,
1789
- y: 0
1790
- };
1791
- scrollDirection.current = {
1792
- x: 0,
1793
- y: 0
1794
- };
1795
- clearAutoScrollInterval();
1796
- },
1797
- // eslint-disable-next-line react-hooks/exhaustive-deps
1798
- [
1799
- acceleration,
1800
- autoScroll,
1801
- canScroll,
1802
- clearAutoScrollInterval,
1803
- enabled,
1804
- interval,
1805
- // eslint-disable-next-line react-hooks/exhaustive-deps
1806
- JSON.stringify(rect),
1807
- // eslint-disable-next-line react-hooks/exhaustive-deps
1808
- JSON.stringify(scrollIntent),
1809
- setAutoScrollInterval,
1810
- scrollableAncestors,
1811
- sortedScrollableAncestors,
1812
- scrollableAncestorRects,
1813
- // eslint-disable-next-line react-hooks/exhaustive-deps
1814
- JSON.stringify(threshold)
1815
- ]
1816
- );
1817
- }
1818
- const defaultScrollIntent = {
1819
- x: {
1820
- [Direction.Backward]: false,
1821
- [Direction.Forward]: false
1822
- },
1823
- y: {
1824
- [Direction.Backward]: false,
1825
- [Direction.Forward]: false
1826
- }
1827
- };
1828
- function useScrollIntent(_ref2) {
1829
- let {
1830
- delta,
1831
- disabled
1832
- } = _ref2;
1833
- const previousDelta = usePrevious(delta);
1834
- return useLazyMemo((previousIntent) => {
1835
- if (disabled || !previousDelta || !previousIntent) {
1836
- return defaultScrollIntent;
1837
- }
1838
- const direction = {
1839
- x: Math.sign(delta.x - previousDelta.x),
1840
- y: Math.sign(delta.y - previousDelta.y)
1841
- };
1842
- return {
1843
- x: {
1844
- [Direction.Backward]: previousIntent.x[Direction.Backward] || direction.x === -1,
1845
- [Direction.Forward]: previousIntent.x[Direction.Forward] || direction.x === 1
1846
- },
1847
- y: {
1848
- [Direction.Backward]: previousIntent.y[Direction.Backward] || direction.y === -1,
1849
- [Direction.Forward]: previousIntent.y[Direction.Forward] || direction.y === 1
1850
- }
1851
- };
1852
- }, [disabled, delta, previousDelta]);
1853
- }
1854
- function useCachedNode(draggableNodes, id) {
1855
- const draggableNode = id != null ? draggableNodes.get(id) : void 0;
1856
- const node = draggableNode ? draggableNode.node.current : null;
1857
- return useLazyMemo((cachedNode) => {
1858
- var _ref;
1859
- if (id == null) {
1860
- return null;
1861
- }
1862
- return (_ref = node != null ? node : cachedNode) != null ? _ref : null;
1863
- }, [node, id]);
1864
- }
1865
- function useCombineActivators(sensors, getSyntheticHandler) {
1866
- return useMemo(() => sensors.reduce((accumulator, sensor) => {
1867
- const {
1868
- sensor: Sensor
1869
- } = sensor;
1870
- const sensorActivators = Sensor.activators.map((activator) => ({
1871
- eventName: activator.eventName,
1872
- handler: getSyntheticHandler(activator.handler, sensor)
1873
- }));
1874
- return [...accumulator, ...sensorActivators];
1875
- }, []), [sensors, getSyntheticHandler]);
1876
- }
1877
- var MeasuringStrategy;
1878
- (function(MeasuringStrategy2) {
1879
- MeasuringStrategy2[MeasuringStrategy2["Always"] = 0] = "Always";
1880
- MeasuringStrategy2[MeasuringStrategy2["BeforeDragging"] = 1] = "BeforeDragging";
1881
- MeasuringStrategy2[MeasuringStrategy2["WhileDragging"] = 2] = "WhileDragging";
1882
- })(MeasuringStrategy || (MeasuringStrategy = {}));
1883
- var MeasuringFrequency;
1884
- (function(MeasuringFrequency2) {
1885
- MeasuringFrequency2["Optimized"] = "optimized";
1886
- })(MeasuringFrequency || (MeasuringFrequency = {}));
1887
- const defaultValue = /* @__PURE__ */ new Map();
1888
- function useDroppableMeasuring(containers, _ref) {
1889
- let {
1890
- dragging,
1891
- dependencies,
1892
- config
1893
- } = _ref;
1894
- const [queue, setQueue] = useState(null);
1895
- const {
1896
- frequency,
1897
- measure,
1898
- strategy
1899
- } = config;
1900
- const containersRef = useRef(containers);
1901
- const disabled = isDisabled();
1902
- const disabledRef = useLatestValue(disabled);
1903
- const measureDroppableContainers = useCallback(function(ids2) {
1904
- if (ids2 === void 0) {
1905
- ids2 = [];
1906
- }
1907
- if (disabledRef.current) {
1908
- return;
1909
- }
1910
- setQueue((value) => {
1911
- if (value === null) {
1912
- return ids2;
1913
- }
1914
- return value.concat(ids2.filter((id) => !value.includes(id)));
1915
- });
1916
- }, [disabledRef]);
1917
- const timeoutId = useRef(null);
1918
- const droppableRects = useLazyMemo((previousValue) => {
1919
- if (disabled && !dragging) {
1920
- return defaultValue;
1921
- }
1922
- if (!previousValue || previousValue === defaultValue || containersRef.current !== containers || queue != null) {
1923
- const map = /* @__PURE__ */ new Map();
1924
- for (let container of containers) {
1925
- if (!container) {
1926
- continue;
1927
- }
1928
- if (queue && queue.length > 0 && !queue.includes(container.id) && container.rect.current) {
1929
- map.set(container.id, container.rect.current);
1930
- continue;
1931
- }
1932
- const node = container.node.current;
1933
- const rect = node ? new Rect(measure(node), node) : null;
1934
- container.rect.current = rect;
1935
- if (rect) {
1936
- map.set(container.id, rect);
1937
- }
1938
- }
1939
- return map;
1940
- }
1941
- return previousValue;
1942
- }, [containers, queue, dragging, disabled, measure]);
1943
- useEffect(() => {
1944
- containersRef.current = containers;
1945
- }, [containers]);
1946
- useEffect(
1947
- () => {
1948
- if (disabled) {
1949
- return;
1950
- }
1951
- measureDroppableContainers();
1952
- },
1953
- // eslint-disable-next-line react-hooks/exhaustive-deps
1954
- [dragging, disabled]
1955
- );
1956
- useEffect(
1957
- () => {
1958
- if (queue && queue.length > 0) {
1959
- setQueue(null);
1960
- }
1961
- },
1962
- //eslint-disable-next-line react-hooks/exhaustive-deps
1963
- [JSON.stringify(queue)]
1964
- );
1965
- useEffect(
1966
- () => {
1967
- if (disabled || typeof frequency !== "number" || timeoutId.current !== null) {
1968
- return;
1969
- }
1970
- timeoutId.current = setTimeout(() => {
1971
- measureDroppableContainers();
1972
- timeoutId.current = null;
1973
- }, frequency);
1974
- },
1975
- // eslint-disable-next-line react-hooks/exhaustive-deps
1976
- [frequency, disabled, measureDroppableContainers, ...dependencies]
1977
- );
1978
- return {
1979
- droppableRects,
1980
- measureDroppableContainers,
1981
- measuringScheduled: queue != null
1982
- };
1983
- function isDisabled() {
1984
- switch (strategy) {
1985
- case MeasuringStrategy.Always:
1986
- return false;
1987
- case MeasuringStrategy.BeforeDragging:
1988
- return dragging;
1989
- default:
1990
- return !dragging;
1991
- }
1992
- }
1993
- }
1994
- function useInitialValue(value, computeFn) {
1995
- return useLazyMemo((previousValue) => {
1996
- if (!value) {
1997
- return null;
1998
- }
1999
- if (previousValue) {
2000
- return previousValue;
2001
- }
2002
- return typeof computeFn === "function" ? computeFn(value) : value;
2003
- }, [computeFn, value]);
2004
- }
2005
- function useInitialRect(node, measure) {
2006
- return useInitialValue(node, measure);
2007
- }
2008
- function useMutationObserver(_ref) {
2009
- let {
2010
- callback,
2011
- disabled
2012
- } = _ref;
2013
- const handleMutations = useEvent(callback);
2014
- const mutationObserver = useMemo(() => {
2015
- if (disabled || typeof window === "undefined" || typeof window.MutationObserver === "undefined") {
2016
- return void 0;
2017
- }
2018
- const {
2019
- MutationObserver
2020
- } = window;
2021
- return new MutationObserver(handleMutations);
2022
- }, [handleMutations, disabled]);
2023
- useEffect(() => {
2024
- return () => mutationObserver == null ? void 0 : mutationObserver.disconnect();
2025
- }, [mutationObserver]);
2026
- return mutationObserver;
2027
- }
2028
- function useResizeObserver(_ref) {
2029
- let {
2030
- callback,
2031
- disabled
2032
- } = _ref;
2033
- const handleResize = useEvent(callback);
2034
- const resizeObserver = useMemo(
2035
- () => {
2036
- if (disabled || typeof window === "undefined" || typeof window.ResizeObserver === "undefined") {
2037
- return void 0;
2038
- }
2039
- const {
2040
- ResizeObserver
2041
- } = window;
2042
- return new ResizeObserver(handleResize);
2043
- },
2044
- // eslint-disable-next-line react-hooks/exhaustive-deps
2045
- [disabled]
2046
- );
2047
- useEffect(() => {
2048
- return () => resizeObserver == null ? void 0 : resizeObserver.disconnect();
2049
- }, [resizeObserver]);
2050
- return resizeObserver;
2051
- }
2052
- function defaultMeasure(element) {
2053
- return new Rect(getClientRect(element), element);
2054
- }
2055
- function useRect(element, measure, fallbackRect) {
2056
- if (measure === void 0) {
2057
- measure = defaultMeasure;
2058
- }
2059
- const [rect, setRect] = useState(null);
2060
- function measureRect() {
2061
- setRect((currentRect) => {
2062
- if (!element) {
2063
- return null;
2064
- }
2065
- if (element.isConnected === false) {
2066
- var _ref;
2067
- return (_ref = currentRect != null ? currentRect : fallbackRect) != null ? _ref : null;
2068
- }
2069
- const newRect = measure(element);
2070
- if (JSON.stringify(currentRect) === JSON.stringify(newRect)) {
2071
- return currentRect;
2072
- }
2073
- return newRect;
2074
- });
2075
- }
2076
- const mutationObserver = useMutationObserver({
2077
- callback(records) {
2078
- if (!element) {
2079
- return;
2080
- }
2081
- for (const record of records) {
2082
- const {
2083
- type,
2084
- target
2085
- } = record;
2086
- if (type === "childList" && target instanceof HTMLElement && target.contains(element)) {
2087
- measureRect();
2088
- break;
2089
- }
2090
- }
2091
- }
2092
- });
2093
- const resizeObserver = useResizeObserver({
2094
- callback: measureRect
2095
- });
2096
- useIsomorphicLayoutEffect(() => {
2097
- measureRect();
2098
- if (element) {
2099
- resizeObserver == null ? void 0 : resizeObserver.observe(element);
2100
- mutationObserver == null ? void 0 : mutationObserver.observe(document.body, {
2101
- childList: true,
2102
- subtree: true
2103
- });
2104
- } else {
2105
- resizeObserver == null ? void 0 : resizeObserver.disconnect();
2106
- mutationObserver == null ? void 0 : mutationObserver.disconnect();
2107
- }
2108
- }, [element]);
2109
- return rect;
2110
- }
2111
- function useRectDelta(rect) {
2112
- const initialRect = useInitialValue(rect);
2113
- return getRectDelta(rect, initialRect);
2114
- }
2115
- const defaultValue$1 = [];
2116
- function useScrollableAncestors(node) {
2117
- const previousNode = useRef(node);
2118
- const ancestors = useLazyMemo((previousValue) => {
2119
- if (!node) {
2120
- return defaultValue$1;
2121
- }
2122
- if (previousValue && previousValue !== defaultValue$1 && node && previousNode.current && node.parentNode === previousNode.current.parentNode) {
2123
- return previousValue;
2124
- }
2125
- return getScrollableAncestors(node);
2126
- }, [node]);
2127
- useEffect(() => {
2128
- previousNode.current = node;
2129
- }, [node]);
2130
- return ancestors;
2131
- }
2132
- function useScrollOffsets(elements) {
2133
- const [scrollCoordinates, setScrollCoordinates] = useState(null);
2134
- const prevElements = useRef(elements);
2135
- const handleScroll = useCallback((event) => {
2136
- const scrollingElement = getScrollableElement(event.target);
2137
- if (!scrollingElement) {
2138
- return;
2139
- }
2140
- setScrollCoordinates((scrollCoordinates2) => {
2141
- if (!scrollCoordinates2) {
2142
- return null;
2143
- }
2144
- scrollCoordinates2.set(scrollingElement, getScrollCoordinates(scrollingElement));
2145
- return new Map(scrollCoordinates2);
2146
- });
2147
- }, []);
2148
- useEffect(() => {
2149
- const previousElements = prevElements.current;
2150
- if (elements !== previousElements) {
2151
- cleanup(previousElements);
2152
- const entries = elements.map((element) => {
2153
- const scrollableElement = getScrollableElement(element);
2154
- if (scrollableElement) {
2155
- scrollableElement.addEventListener("scroll", handleScroll, {
2156
- passive: true
2157
- });
2158
- return [scrollableElement, getScrollCoordinates(scrollableElement)];
2159
- }
2160
- return null;
2161
- }).filter((entry) => entry != null);
2162
- setScrollCoordinates(entries.length ? new Map(entries) : null);
2163
- prevElements.current = elements;
2164
- }
2165
- return () => {
2166
- cleanup(elements);
2167
- cleanup(previousElements);
2168
- };
2169
- function cleanup(elements2) {
2170
- elements2.forEach((element) => {
2171
- const scrollableElement = getScrollableElement(element);
2172
- scrollableElement == null ? void 0 : scrollableElement.removeEventListener("scroll", handleScroll);
2173
- });
2174
- }
2175
- }, [handleScroll, elements]);
2176
- return useMemo(() => {
2177
- if (elements.length) {
2178
- return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements);
2179
- }
2180
- return defaultCoordinates;
2181
- }, [elements, scrollCoordinates]);
2182
- }
2183
- function useScrollOffsetsDelta(scrollOffsets, dependencies) {
2184
- if (dependencies === void 0) {
2185
- dependencies = [];
2186
- }
2187
- const initialScrollOffsets = useRef(null);
2188
- useEffect(
2189
- () => {
2190
- initialScrollOffsets.current = null;
2191
- },
2192
- // eslint-disable-next-line react-hooks/exhaustive-deps
2193
- dependencies
2194
- );
2195
- useEffect(() => {
2196
- const hasScrollOffsets = scrollOffsets !== defaultCoordinates;
2197
- if (hasScrollOffsets && !initialScrollOffsets.current) {
2198
- initialScrollOffsets.current = scrollOffsets;
2199
- }
2200
- if (!hasScrollOffsets && initialScrollOffsets.current) {
2201
- initialScrollOffsets.current = null;
2202
- }
2203
- }, [scrollOffsets]);
2204
- return initialScrollOffsets.current ? subtract(scrollOffsets, initialScrollOffsets.current) : defaultCoordinates;
2205
- }
2206
- function useSensorSetup(sensors) {
2207
- useEffect(
2208
- () => {
2209
- if (!canUseDOM) {
2210
- return;
2211
- }
2212
- const teardownFns = sensors.map((_ref) => {
2213
- let {
2214
- sensor
2215
- } = _ref;
2216
- return sensor.setup == null ? void 0 : sensor.setup();
2217
- });
2218
- return () => {
2219
- for (const teardown of teardownFns) {
2220
- teardown == null ? void 0 : teardown();
2221
- }
2222
- };
2223
- },
2224
- // TO-DO: Sensors length could theoretically change which would not be a valid dependency
2225
- // eslint-disable-next-line react-hooks/exhaustive-deps
2226
- sensors.map((_ref2) => {
2227
- let {
2228
- sensor
2229
- } = _ref2;
2230
- return sensor;
2231
- })
2232
- );
2233
- }
2234
- function useWindowRect(element) {
2235
- return useMemo(() => element ? getWindowClientRect(element) : null, [element]);
2236
- }
2237
- const defaultValue$2 = [];
2238
- function useRects(elements, measure) {
2239
- if (measure === void 0) {
2240
- measure = getClientRect;
2241
- }
2242
- const [firstElement] = elements;
2243
- const windowRect = useWindowRect(firstElement ? getWindow(firstElement) : null);
2244
- const [rects, setRects] = useState(defaultValue$2);
2245
- function measureRects() {
2246
- setRects(() => {
2247
- if (!elements.length) {
2248
- return defaultValue$2;
2249
- }
2250
- return elements.map((element) => isDocumentScrollingElement(element) ? windowRect : new Rect(measure(element), element));
2251
- });
2252
- }
2253
- const resizeObserver = useResizeObserver({
2254
- callback: measureRects
2255
- });
2256
- useIsomorphicLayoutEffect(() => {
2257
- resizeObserver == null ? void 0 : resizeObserver.disconnect();
2258
- measureRects();
2259
- elements.forEach((element) => resizeObserver == null ? void 0 : resizeObserver.observe(element));
2260
- }, [elements]);
2261
- return rects;
2262
- }
2263
- function getMeasurableNode(node) {
2264
- if (!node) {
2265
- return null;
2266
- }
2267
- if (node.children.length > 1) {
2268
- return node;
2269
- }
2270
- const firstChild = node.children[0];
2271
- return isHTMLElement(firstChild) ? firstChild : node;
2272
- }
2273
- function useDragOverlayMeasuring(_ref) {
2274
- let {
2275
- measure
2276
- } = _ref;
2277
- const [rect, setRect] = useState(null);
2278
- const handleResize = useCallback((entries) => {
2279
- for (const {
2280
- target
2281
- } of entries) {
2282
- if (isHTMLElement(target)) {
2283
- setRect((rect2) => {
2284
- const newRect = measure(target);
2285
- return rect2 ? {
2286
- ...rect2,
2287
- width: newRect.width,
2288
- height: newRect.height
2289
- } : newRect;
2290
- });
2291
- break;
2292
- }
2293
- }
2294
- }, [measure]);
2295
- const resizeObserver = useResizeObserver({
2296
- callback: handleResize
2297
- });
2298
- const handleNodeChange = useCallback((element) => {
2299
- const node = getMeasurableNode(element);
2300
- resizeObserver == null ? void 0 : resizeObserver.disconnect();
2301
- if (node) {
2302
- resizeObserver == null ? void 0 : resizeObserver.observe(node);
2303
- }
2304
- setRect(node ? measure(node) : null);
2305
- }, [measure, resizeObserver]);
2306
- const [nodeRef, setRef] = useNodeRef(handleNodeChange);
2307
- return useMemo(() => ({
2308
- nodeRef,
2309
- rect,
2310
- setRef
2311
- }), [rect, nodeRef, setRef]);
2312
- }
2313
- const defaultSensors = [{
2314
- sensor: PointerSensor,
2315
- options: {}
2316
- }, {
2317
- sensor: KeyboardSensor,
2318
- options: {}
2319
- }];
2320
- const defaultData = {
2321
- current: {}
2322
- };
2323
- const defaultMeasuringConfiguration = {
2324
- draggable: {
2325
- measure: getTransformAgnosticClientRect
2326
- },
2327
- droppable: {
2328
- measure: getTransformAgnosticClientRect,
2329
- strategy: MeasuringStrategy.WhileDragging,
2330
- frequency: MeasuringFrequency.Optimized
2331
- },
2332
- dragOverlay: {
2333
- measure: getClientRect
2334
- }
2335
- };
2336
- class DroppableContainersMap extends Map {
2337
- get(id) {
2338
- var _super$get;
2339
- return id != null ? (_super$get = super.get(id)) != null ? _super$get : void 0 : void 0;
2340
- }
2341
- toArray() {
2342
- return Array.from(this.values());
2343
- }
2344
- getEnabled() {
2345
- return this.toArray().filter((_ref) => {
2346
- let {
2347
- disabled
2348
- } = _ref;
2349
- return !disabled;
2350
- });
2351
- }
2352
- getNodeFor(id) {
2353
- var _this$get$node$curren, _this$get;
2354
- return (_this$get$node$curren = (_this$get = this.get(id)) == null ? void 0 : _this$get.node.current) != null ? _this$get$node$curren : void 0;
2355
- }
2356
- }
2357
- const defaultPublicContext = {
2358
- activatorEvent: null,
2359
- active: null,
2360
- activeNode: null,
2361
- activeNodeRect: null,
2362
- collisions: null,
2363
- containerNodeRect: null,
2364
- draggableNodes: /* @__PURE__ */ new Map(),
2365
- droppableRects: /* @__PURE__ */ new Map(),
2366
- droppableContainers: /* @__PURE__ */ new DroppableContainersMap(),
2367
- over: null,
2368
- dragOverlay: {
2369
- nodeRef: {
2370
- current: null
2371
- },
2372
- rect: null,
2373
- setRef: noop
2374
- },
2375
- scrollableAncestors: [],
2376
- scrollableAncestorRects: [],
2377
- measuringConfiguration: defaultMeasuringConfiguration,
2378
- measureDroppableContainers: noop,
2379
- windowRect: null,
2380
- measuringScheduled: false
2381
- };
2382
- const defaultInternalContext = {
2383
- activatorEvent: null,
2384
- activators: [],
2385
- active: null,
2386
- activeNodeRect: null,
2387
- ariaDescribedById: {
2388
- draggable: ""
2389
- },
2390
- dispatch: noop,
2391
- draggableNodes: /* @__PURE__ */ new Map(),
2392
- over: null,
2393
- measureDroppableContainers: noop
2394
- };
2395
- const InternalContext = /* @__PURE__ */ createContext(defaultInternalContext);
2396
- const PublicContext = /* @__PURE__ */ createContext(defaultPublicContext);
2397
- function getInitialState() {
2398
- return {
2399
- draggable: {
2400
- active: null,
2401
- initialCoordinates: {
2402
- x: 0,
2403
- y: 0
2404
- },
2405
- nodes: /* @__PURE__ */ new Map(),
2406
- translate: {
2407
- x: 0,
2408
- y: 0
2409
- }
2410
- },
2411
- droppable: {
2412
- containers: new DroppableContainersMap()
2413
- }
2414
- };
2415
- }
2416
- function reducer(state, action) {
2417
- switch (action.type) {
2418
- case Action.DragStart:
2419
- return {
2420
- ...state,
2421
- draggable: {
2422
- ...state.draggable,
2423
- initialCoordinates: action.initialCoordinates,
2424
- active: action.active
2425
- }
2426
- };
2427
- case Action.DragMove:
2428
- if (state.draggable.active == null) {
2429
- return state;
2430
- }
2431
- return {
2432
- ...state,
2433
- draggable: {
2434
- ...state.draggable,
2435
- translate: {
2436
- x: action.coordinates.x - state.draggable.initialCoordinates.x,
2437
- y: action.coordinates.y - state.draggable.initialCoordinates.y
2438
- }
2439
- }
2440
- };
2441
- case Action.DragEnd:
2442
- case Action.DragCancel:
2443
- return {
2444
- ...state,
2445
- draggable: {
2446
- ...state.draggable,
2447
- active: null,
2448
- initialCoordinates: {
2449
- x: 0,
2450
- y: 0
2451
- },
2452
- translate: {
2453
- x: 0,
2454
- y: 0
2455
- }
2456
- }
2457
- };
2458
- case Action.RegisterDroppable: {
2459
- const {
2460
- element
2461
- } = action;
2462
- const {
2463
- id
2464
- } = element;
2465
- const containers = new DroppableContainersMap(state.droppable.containers);
2466
- containers.set(id, element);
2467
- return {
2468
- ...state,
2469
- droppable: {
2470
- ...state.droppable,
2471
- containers
2472
- }
2473
- };
2474
- }
2475
- case Action.SetDroppableDisabled: {
2476
- const {
2477
- id,
2478
- key,
2479
- disabled
2480
- } = action;
2481
- const element = state.droppable.containers.get(id);
2482
- if (!element || key !== element.key) {
2483
- return state;
2484
- }
2485
- const containers = new DroppableContainersMap(state.droppable.containers);
2486
- containers.set(id, {
2487
- ...element,
2488
- disabled
2489
- });
2490
- return {
2491
- ...state,
2492
- droppable: {
2493
- ...state.droppable,
2494
- containers
2495
- }
2496
- };
2497
- }
2498
- case Action.UnregisterDroppable: {
2499
- const {
2500
- id,
2501
- key
2502
- } = action;
2503
- const element = state.droppable.containers.get(id);
2504
- if (!element || key !== element.key) {
2505
- return state;
2506
- }
2507
- const containers = new DroppableContainersMap(state.droppable.containers);
2508
- containers.delete(id);
2509
- return {
2510
- ...state,
2511
- droppable: {
2512
- ...state.droppable,
2513
- containers
2514
- }
2515
- };
2516
- }
2517
- default: {
2518
- return state;
2519
- }
2520
- }
2521
- }
2522
- function RestoreFocus(_ref) {
2523
- let {
2524
- disabled
2525
- } = _ref;
2526
- const {
2527
- active,
2528
- activatorEvent,
2529
- draggableNodes
2530
- } = useContext(InternalContext);
2531
- const previousActivatorEvent = usePrevious(activatorEvent);
2532
- const previousActiveId = usePrevious(active == null ? void 0 : active.id);
2533
- useEffect(() => {
2534
- if (disabled) {
2535
- return;
2536
- }
2537
- if (!activatorEvent && previousActivatorEvent && previousActiveId != null) {
2538
- if (!isKeyboardEvent(previousActivatorEvent)) {
2539
- return;
2540
- }
2541
- if (document.activeElement === previousActivatorEvent.target) {
2542
- return;
2543
- }
2544
- const draggableNode = draggableNodes.get(previousActiveId);
2545
- if (!draggableNode) {
2546
- return;
2547
- }
2548
- const {
2549
- activatorNode,
2550
- node
2551
- } = draggableNode;
2552
- if (!activatorNode.current && !node.current) {
2553
- return;
2554
- }
2555
- requestAnimationFrame(() => {
2556
- for (const element of [activatorNode.current, node.current]) {
2557
- if (!element) {
2558
- continue;
2559
- }
2560
- const focusableNode = findFirstFocusableNode(element);
2561
- if (focusableNode) {
2562
- focusableNode.focus();
2563
- break;
2564
- }
2565
- }
2566
- });
2567
- }
2568
- }, [activatorEvent, disabled, draggableNodes, previousActiveId, previousActivatorEvent]);
2569
- return null;
2570
- }
2571
- function applyModifiers(modifiers, _ref) {
2572
- let {
2573
- transform,
2574
- ...args
2575
- } = _ref;
2576
- return modifiers != null && modifiers.length ? modifiers.reduce((accumulator, modifier) => {
2577
- return modifier({
2578
- transform: accumulator,
2579
- ...args
2580
- });
2581
- }, transform) : transform;
2582
- }
2583
- function useMeasuringConfiguration(config) {
2584
- return useMemo(
2585
- () => ({
2586
- draggable: {
2587
- ...defaultMeasuringConfiguration.draggable,
2588
- ...config == null ? void 0 : config.draggable
2589
- },
2590
- droppable: {
2591
- ...defaultMeasuringConfiguration.droppable,
2592
- ...config == null ? void 0 : config.droppable
2593
- },
2594
- dragOverlay: {
2595
- ...defaultMeasuringConfiguration.dragOverlay,
2596
- ...config == null ? void 0 : config.dragOverlay
2597
- }
2598
- }),
2599
- // eslint-disable-next-line react-hooks/exhaustive-deps
2600
- [config == null ? void 0 : config.draggable, config == null ? void 0 : config.droppable, config == null ? void 0 : config.dragOverlay]
2601
- );
2602
- }
2603
- function useLayoutShiftScrollCompensation(_ref) {
2604
- let {
2605
- activeNode,
2606
- measure,
2607
- initialRect,
2608
- config = true
2609
- } = _ref;
2610
- const initialized = useRef(false);
2611
- const {
2612
- x,
2613
- y
2614
- } = typeof config === "boolean" ? {
2615
- x: config,
2616
- y: config
2617
- } : config;
2618
- useIsomorphicLayoutEffect(() => {
2619
- const disabled = !x && !y;
2620
- if (disabled || !activeNode) {
2621
- initialized.current = false;
2622
- return;
2623
- }
2624
- if (initialized.current || !initialRect) {
2625
- return;
2626
- }
2627
- const node = activeNode == null ? void 0 : activeNode.node.current;
2628
- if (!node || node.isConnected === false) {
2629
- return;
2630
- }
2631
- const rect = measure(node);
2632
- const rectDelta = getRectDelta(rect, initialRect);
2633
- if (!x) {
2634
- rectDelta.x = 0;
2635
- }
2636
- if (!y) {
2637
- rectDelta.y = 0;
2638
- }
2639
- initialized.current = true;
2640
- if (Math.abs(rectDelta.x) > 0 || Math.abs(rectDelta.y) > 0) {
2641
- const firstScrollableAncestor = getFirstScrollableAncestor(node);
2642
- if (firstScrollableAncestor) {
2643
- firstScrollableAncestor.scrollBy({
2644
- top: rectDelta.y,
2645
- left: rectDelta.x
2646
- });
2647
- }
2648
- }
2649
- }, [activeNode, x, y, initialRect, measure]);
2650
- }
2651
- const ActiveDraggableContext = /* @__PURE__ */ createContext({
2652
- ...defaultCoordinates,
2653
- scaleX: 1,
2654
- scaleY: 1
2655
- });
2656
- var Status;
2657
- (function(Status2) {
2658
- Status2[Status2["Uninitialized"] = 0] = "Uninitialized";
2659
- Status2[Status2["Initializing"] = 1] = "Initializing";
2660
- Status2[Status2["Initialized"] = 2] = "Initialized";
2661
- })(Status || (Status = {}));
2662
- const DndContext = /* @__PURE__ */ memo(function DndContext2(_ref) {
2663
- var _sensorContext$curren, _dragOverlay$nodeRef$, _dragOverlay$rect, _over$rect;
2664
- let {
2665
- id,
2666
- accessibility,
2667
- autoScroll = true,
2668
- children,
2669
- sensors = defaultSensors,
2670
- collisionDetection = rectIntersection,
2671
- measuring,
2672
- modifiers,
2673
- ...props
2674
- } = _ref;
2675
- const store = useReducer(reducer, void 0, getInitialState);
2676
- const [state, dispatch] = store;
2677
- const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider();
2678
- const [status, setStatus] = useState(Status.Uninitialized);
2679
- const isInitialized = status === Status.Initialized;
2680
- const {
2681
- draggable: {
2682
- active: activeId,
2683
- nodes: draggableNodes,
2684
- translate
2685
- },
2686
- droppable: {
2687
- containers: droppableContainers
2688
- }
2689
- } = state;
2690
- const node = activeId != null ? draggableNodes.get(activeId) : null;
2691
- const activeRects = useRef({
2692
- initial: null,
2693
- translated: null
2694
- });
2695
- const active = useMemo(() => {
2696
- var _node$data;
2697
- return activeId != null ? {
2698
- id: activeId,
2699
- // It's possible for the active node to unmount while dragging
2700
- data: (_node$data = node == null ? void 0 : node.data) != null ? _node$data : defaultData,
2701
- rect: activeRects
2702
- } : null;
2703
- }, [activeId, node]);
2704
- const activeRef = useRef(null);
2705
- const [activeSensor, setActiveSensor] = useState(null);
2706
- const [activatorEvent, setActivatorEvent] = useState(null);
2707
- const latestProps = useLatestValue(props, Object.values(props));
2708
- const draggableDescribedById = useUniqueId("DndDescribedBy", id);
2709
- const enabledDroppableContainers = useMemo(() => droppableContainers.getEnabled(), [droppableContainers]);
2710
- const measuringConfiguration = useMeasuringConfiguration(measuring);
2711
- const {
2712
- droppableRects,
2713
- measureDroppableContainers,
2714
- measuringScheduled
2715
- } = useDroppableMeasuring(enabledDroppableContainers, {
2716
- dragging: isInitialized,
2717
- dependencies: [translate.x, translate.y],
2718
- config: measuringConfiguration.droppable
2719
- });
2720
- const activeNode = useCachedNode(draggableNodes, activeId);
2721
- const activationCoordinates = useMemo(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]);
2722
- const autoScrollOptions = getAutoScrollerOptions();
2723
- const initialActiveNodeRect = useInitialRect(activeNode, measuringConfiguration.draggable.measure);
2724
- useLayoutShiftScrollCompensation({
2725
- activeNode: activeId != null ? draggableNodes.get(activeId) : null,
2726
- config: autoScrollOptions.layoutShiftCompensation,
2727
- initialRect: initialActiveNodeRect,
2728
- measure: measuringConfiguration.draggable.measure
2729
- });
2730
- const activeNodeRect = useRect(activeNode, measuringConfiguration.draggable.measure, initialActiveNodeRect);
2731
- const containerNodeRect = useRect(activeNode ? activeNode.parentElement : null);
2732
- const sensorContext = useRef({
2733
- activatorEvent: null,
2734
- active: null,
2735
- activeNode,
2736
- collisionRect: null,
2737
- collisions: null,
2738
- droppableRects,
2739
- draggableNodes,
2740
- draggingNode: null,
2741
- draggingNodeRect: null,
2742
- droppableContainers,
2743
- over: null,
2744
- scrollableAncestors: [],
2745
- scrollAdjustedTranslate: null
2746
- });
2747
- const overNode = droppableContainers.getNodeFor((_sensorContext$curren = sensorContext.current.over) == null ? void 0 : _sensorContext$curren.id);
2748
- const dragOverlay = useDragOverlayMeasuring({
2749
- measure: measuringConfiguration.dragOverlay.measure
2750
- });
2751
- const draggingNode = (_dragOverlay$nodeRef$ = dragOverlay.nodeRef.current) != null ? _dragOverlay$nodeRef$ : activeNode;
2752
- const draggingNodeRect = isInitialized ? (_dragOverlay$rect = dragOverlay.rect) != null ? _dragOverlay$rect : activeNodeRect : null;
2753
- const usesDragOverlay = Boolean(dragOverlay.nodeRef.current && dragOverlay.rect);
2754
- const nodeRectDelta = useRectDelta(usesDragOverlay ? null : activeNodeRect);
2755
- const windowRect = useWindowRect(draggingNode ? getWindow(draggingNode) : null);
2756
- const scrollableAncestors = useScrollableAncestors(isInitialized ? overNode != null ? overNode : activeNode : null);
2757
- const scrollableAncestorRects = useRects(scrollableAncestors);
2758
- const modifiedTranslate = applyModifiers(modifiers, {
2759
- transform: {
2760
- x: translate.x - nodeRectDelta.x,
2761
- y: translate.y - nodeRectDelta.y,
2762
- scaleX: 1,
2763
- scaleY: 1
2764
- },
2765
- activatorEvent,
2766
- active,
2767
- activeNodeRect,
2768
- containerNodeRect,
2769
- draggingNodeRect,
2770
- over: sensorContext.current.over,
2771
- overlayNodeRect: dragOverlay.rect,
2772
- scrollableAncestors,
2773
- scrollableAncestorRects,
2774
- windowRect
2775
- });
2776
- const pointerCoordinates = activationCoordinates ? add(activationCoordinates, translate) : null;
2777
- const scrollOffsets = useScrollOffsets(scrollableAncestors);
2778
- const scrollAdjustment = useScrollOffsetsDelta(scrollOffsets);
2779
- const activeNodeScrollDelta = useScrollOffsetsDelta(scrollOffsets, [activeNodeRect]);
2780
- const scrollAdjustedTranslate = add(modifiedTranslate, scrollAdjustment);
2781
- const collisionRect = draggingNodeRect ? getAdjustedRect(draggingNodeRect, modifiedTranslate) : null;
2782
- const collisions = active && collisionRect ? collisionDetection({
2783
- active,
2784
- collisionRect,
2785
- droppableRects,
2786
- droppableContainers: enabledDroppableContainers,
2787
- pointerCoordinates
2788
- }) : null;
2789
- const overId = getFirstCollision(collisions, "id");
2790
- const [over, setOver] = useState(null);
2791
- const appliedTranslate = usesDragOverlay ? modifiedTranslate : add(modifiedTranslate, activeNodeScrollDelta);
2792
- const transform = adjustScale(appliedTranslate, (_over$rect = over == null ? void 0 : over.rect) != null ? _over$rect : null, activeNodeRect);
2793
- const activeSensorRef = useRef(null);
2794
- const instantiateSensor = useCallback(
2795
- (event, _ref2) => {
2796
- let {
2797
- sensor: Sensor,
2798
- options
2799
- } = _ref2;
2800
- if (activeRef.current == null) {
2801
- return;
2802
- }
2803
- const activeNode2 = draggableNodes.get(activeRef.current);
2804
- if (!activeNode2) {
2805
- return;
2806
- }
2807
- const activatorEvent2 = event.nativeEvent;
2808
- const sensorInstance = new Sensor({
2809
- active: activeRef.current,
2810
- activeNode: activeNode2,
2811
- event: activatorEvent2,
2812
- options,
2813
- // Sensors need to be instantiated with refs for arguments that change over time
2814
- // otherwise they are frozen in time with the stale arguments
2815
- context: sensorContext,
2816
- onAbort(id2) {
2817
- const draggableNode = draggableNodes.get(id2);
2818
- if (!draggableNode) {
2819
- return;
2820
- }
2821
- const {
2822
- onDragAbort
2823
- } = latestProps.current;
2824
- const event2 = {
2825
- id: id2
2826
- };
2827
- onDragAbort == null ? void 0 : onDragAbort(event2);
2828
- dispatchMonitorEvent({
2829
- type: "onDragAbort",
2830
- event: event2
2831
- });
2832
- },
2833
- onPending(id2, constraint, initialCoordinates, offset) {
2834
- const draggableNode = draggableNodes.get(id2);
2835
- if (!draggableNode) {
2836
- return;
2837
- }
2838
- const {
2839
- onDragPending
2840
- } = latestProps.current;
2841
- const event2 = {
2842
- id: id2,
2843
- constraint,
2844
- initialCoordinates,
2845
- offset
2846
- };
2847
- onDragPending == null ? void 0 : onDragPending(event2);
2848
- dispatchMonitorEvent({
2849
- type: "onDragPending",
2850
- event: event2
2851
- });
2852
- },
2853
- onStart(initialCoordinates) {
2854
- const id2 = activeRef.current;
2855
- if (id2 == null) {
2856
- return;
2857
- }
2858
- const draggableNode = draggableNodes.get(id2);
2859
- if (!draggableNode) {
2860
- return;
2861
- }
2862
- const {
2863
- onDragStart
2864
- } = latestProps.current;
2865
- const event2 = {
2866
- activatorEvent: activatorEvent2,
2867
- active: {
2868
- id: id2,
2869
- data: draggableNode.data,
2870
- rect: activeRects
2871
- }
2872
- };
2873
- unstable_batchedUpdates(() => {
2874
- onDragStart == null ? void 0 : onDragStart(event2);
2875
- setStatus(Status.Initializing);
2876
- dispatch({
2877
- type: Action.DragStart,
2878
- initialCoordinates,
2879
- active: id2
2880
- });
2881
- dispatchMonitorEvent({
2882
- type: "onDragStart",
2883
- event: event2
2884
- });
2885
- setActiveSensor(activeSensorRef.current);
2886
- setActivatorEvent(activatorEvent2);
2887
- });
2888
- },
2889
- onMove(coordinates) {
2890
- dispatch({
2891
- type: Action.DragMove,
2892
- coordinates
2893
- });
2894
- },
2895
- onEnd: createHandler(Action.DragEnd),
2896
- onCancel: createHandler(Action.DragCancel)
2897
- });
2898
- activeSensorRef.current = sensorInstance;
2899
- function createHandler(type) {
2900
- return async function handler() {
2901
- const {
2902
- active: active2,
2903
- collisions: collisions2,
2904
- over: over2,
2905
- scrollAdjustedTranslate: scrollAdjustedTranslate2
2906
- } = sensorContext.current;
2907
- let event2 = null;
2908
- if (active2 && scrollAdjustedTranslate2) {
2909
- const {
2910
- cancelDrop
2911
- } = latestProps.current;
2912
- event2 = {
2913
- activatorEvent: activatorEvent2,
2914
- active: active2,
2915
- collisions: collisions2,
2916
- delta: scrollAdjustedTranslate2,
2917
- over: over2
2918
- };
2919
- if (type === Action.DragEnd && typeof cancelDrop === "function") {
2920
- const shouldCancel = await Promise.resolve(cancelDrop(event2));
2921
- if (shouldCancel) {
2922
- type = Action.DragCancel;
2923
- }
2924
- }
2925
- }
2926
- activeRef.current = null;
2927
- unstable_batchedUpdates(() => {
2928
- dispatch({
2929
- type
2930
- });
2931
- setStatus(Status.Uninitialized);
2932
- setOver(null);
2933
- setActiveSensor(null);
2934
- setActivatorEvent(null);
2935
- activeSensorRef.current = null;
2936
- const eventName = type === Action.DragEnd ? "onDragEnd" : "onDragCancel";
2937
- if (event2) {
2938
- const handler2 = latestProps.current[eventName];
2939
- handler2 == null ? void 0 : handler2(event2);
2940
- dispatchMonitorEvent({
2941
- type: eventName,
2942
- event: event2
2943
- });
2944
- }
2945
- });
2946
- };
2947
- }
2948
- },
2949
- // eslint-disable-next-line react-hooks/exhaustive-deps
2950
- [draggableNodes]
2951
- );
2952
- const bindActivatorToSensorInstantiator = useCallback((handler, sensor) => {
2953
- return (event, active2) => {
2954
- const nativeEvent = event.nativeEvent;
2955
- const activeDraggableNode = draggableNodes.get(active2);
2956
- if (
2957
- // Another sensor is already instantiating
2958
- activeRef.current !== null || // No active draggable
2959
- !activeDraggableNode || // Event has already been captured
2960
- nativeEvent.dndKit || nativeEvent.defaultPrevented
2961
- ) {
2962
- return;
2963
- }
2964
- const activationContext = {
2965
- active: activeDraggableNode
2966
- };
2967
- const shouldActivate = handler(event, sensor.options, activationContext);
2968
- if (shouldActivate === true) {
2969
- nativeEvent.dndKit = {
2970
- capturedBy: sensor.sensor
2971
- };
2972
- activeRef.current = active2;
2973
- instantiateSensor(event, sensor);
2974
- }
2975
- };
2976
- }, [draggableNodes, instantiateSensor]);
2977
- const activators = useCombineActivators(sensors, bindActivatorToSensorInstantiator);
2978
- useSensorSetup(sensors);
2979
- useIsomorphicLayoutEffect(() => {
2980
- if (activeNodeRect && status === Status.Initializing) {
2981
- setStatus(Status.Initialized);
2982
- }
2983
- }, [activeNodeRect, status]);
2984
- useEffect(
2985
- () => {
2986
- const {
2987
- onDragMove
2988
- } = latestProps.current;
2989
- const {
2990
- active: active2,
2991
- activatorEvent: activatorEvent2,
2992
- collisions: collisions2,
2993
- over: over2
2994
- } = sensorContext.current;
2995
- if (!active2 || !activatorEvent2) {
2996
- return;
2997
- }
2998
- const event = {
2999
- active: active2,
3000
- activatorEvent: activatorEvent2,
3001
- collisions: collisions2,
3002
- delta: {
3003
- x: scrollAdjustedTranslate.x,
3004
- y: scrollAdjustedTranslate.y
3005
- },
3006
- over: over2
3007
- };
3008
- unstable_batchedUpdates(() => {
3009
- onDragMove == null ? void 0 : onDragMove(event);
3010
- dispatchMonitorEvent({
3011
- type: "onDragMove",
3012
- event
3013
- });
3014
- });
3015
- },
3016
- // eslint-disable-next-line react-hooks/exhaustive-deps
3017
- [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y]
3018
- );
3019
- useEffect(
3020
- () => {
3021
- const {
3022
- active: active2,
3023
- activatorEvent: activatorEvent2,
3024
- collisions: collisions2,
3025
- droppableContainers: droppableContainers2,
3026
- scrollAdjustedTranslate: scrollAdjustedTranslate2
3027
- } = sensorContext.current;
3028
- if (!active2 || activeRef.current == null || !activatorEvent2 || !scrollAdjustedTranslate2) {
3029
- return;
3030
- }
3031
- const {
3032
- onDragOver
3033
- } = latestProps.current;
3034
- const overContainer = droppableContainers2.get(overId);
3035
- const over2 = overContainer && overContainer.rect.current ? {
3036
- id: overContainer.id,
3037
- rect: overContainer.rect.current,
3038
- data: overContainer.data,
3039
- disabled: overContainer.disabled
3040
- } : null;
3041
- const event = {
3042
- active: active2,
3043
- activatorEvent: activatorEvent2,
3044
- collisions: collisions2,
3045
- delta: {
3046
- x: scrollAdjustedTranslate2.x,
3047
- y: scrollAdjustedTranslate2.y
3048
- },
3049
- over: over2
3050
- };
3051
- unstable_batchedUpdates(() => {
3052
- setOver(over2);
3053
- onDragOver == null ? void 0 : onDragOver(event);
3054
- dispatchMonitorEvent({
3055
- type: "onDragOver",
3056
- event
3057
- });
3058
- });
3059
- },
3060
- // eslint-disable-next-line react-hooks/exhaustive-deps
3061
- [overId]
3062
- );
3063
- useIsomorphicLayoutEffect(() => {
3064
- sensorContext.current = {
3065
- activatorEvent,
3066
- active,
3067
- activeNode,
3068
- collisionRect,
3069
- collisions,
3070
- droppableRects,
3071
- draggableNodes,
3072
- draggingNode,
3073
- draggingNodeRect,
3074
- droppableContainers,
3075
- over,
3076
- scrollableAncestors,
3077
- scrollAdjustedTranslate
3078
- };
3079
- activeRects.current = {
3080
- initial: draggingNodeRect,
3081
- translated: collisionRect
3082
- };
3083
- }, [active, activeNode, collisions, collisionRect, draggableNodes, draggingNode, draggingNodeRect, droppableRects, droppableContainers, over, scrollableAncestors, scrollAdjustedTranslate]);
3084
- useAutoScroller({
3085
- ...autoScrollOptions,
3086
- delta: translate,
3087
- draggingRect: collisionRect,
3088
- pointerCoordinates,
3089
- scrollableAncestors,
3090
- scrollableAncestorRects
3091
- });
3092
- const publicContext = useMemo(() => {
3093
- const context = {
3094
- active,
3095
- activeNode,
3096
- activeNodeRect,
3097
- activatorEvent,
3098
- collisions,
3099
- containerNodeRect,
3100
- dragOverlay,
3101
- draggableNodes,
3102
- droppableContainers,
3103
- droppableRects,
3104
- over,
3105
- measureDroppableContainers,
3106
- scrollableAncestors,
3107
- scrollableAncestorRects,
3108
- measuringConfiguration,
3109
- measuringScheduled,
3110
- windowRect
3111
- };
3112
- return context;
3113
- }, [active, activeNode, activeNodeRect, activatorEvent, collisions, containerNodeRect, dragOverlay, draggableNodes, droppableContainers, droppableRects, over, measureDroppableContainers, scrollableAncestors, scrollableAncestorRects, measuringConfiguration, measuringScheduled, windowRect]);
3114
- const internalContext = useMemo(() => {
3115
- const context = {
3116
- activatorEvent,
3117
- activators,
3118
- active,
3119
- activeNodeRect,
3120
- ariaDescribedById: {
3121
- draggable: draggableDescribedById
3122
- },
3123
- dispatch,
3124
- draggableNodes,
3125
- over,
3126
- measureDroppableContainers
3127
- };
3128
- return context;
3129
- }, [activatorEvent, activators, active, activeNodeRect, dispatch, draggableDescribedById, draggableNodes, over, measureDroppableContainers]);
3130
- return React.createElement(DndMonitorContext.Provider, {
3131
- value: registerMonitorListener
3132
- }, React.createElement(InternalContext.Provider, {
3133
- value: internalContext
3134
- }, React.createElement(PublicContext.Provider, {
3135
- value: publicContext
3136
- }, React.createElement(ActiveDraggableContext.Provider, {
3137
- value: transform
3138
- }, children)), React.createElement(RestoreFocus, {
3139
- disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false
3140
- })), React.createElement(Accessibility, {
3141
- ...accessibility,
3142
- hiddenTextDescribedById: draggableDescribedById
3143
- }));
3144
- function getAutoScrollerOptions() {
3145
- const activeSensorDisablesAutoscroll = (activeSensor == null ? void 0 : activeSensor.autoScrollEnabled) === false;
3146
- const autoScrollGloballyDisabled = typeof autoScroll === "object" ? autoScroll.enabled === false : autoScroll === false;
3147
- const enabled = isInitialized && !activeSensorDisablesAutoscroll && !autoScrollGloballyDisabled;
3148
- if (typeof autoScroll === "object") {
3149
- return {
3150
- ...autoScroll,
3151
- enabled
3152
- };
3153
- }
3154
- return {
3155
- enabled
3156
- };
3157
- }
3158
- });
3159
- const PublicationState = ({
3160
- isPublished,
3161
- hasDraftAndPublish
3162
- }) => {
3163
- const { translate } = useTranslate();
3164
- const configuration = useMemo(() => {
3165
- const conf = {
3166
- variant: "alternative",
3167
- text: translate("publicationState.na")
3168
- };
3169
- if (hasDraftAndPublish) {
3170
- conf.variant = isPublished ? "success" : "secondary";
3171
- conf.text = isPublished ? translate("publicationState.published") : translate("publicationState.draft");
3172
- }
3173
- return conf;
3174
- }, [isPublished, hasDraftAndPublish, translate]);
3175
- return /* @__PURE__ */ jsx(
3176
- Status$1,
3177
- {
3178
- showBullet: false,
3179
- variant: configuration.variant,
3180
- size: "S",
3181
- width: "min-content",
3182
- style: { paddingLeft: 12, paddingRight: 12 },
3183
- children: /* @__PURE__ */ jsx(Typography, { fontWeight: "bold", textColor: `${configuration.variant}700`, children: configuration.text })
3184
- }
3185
- );
3186
- };
3187
- const TableItem = ({
3188
- entry,
3189
- type,
3190
- uniqueId,
3191
- disabled,
3192
- onAdd,
3193
- onDelete
3194
- }) => {
3195
- const { translate } = useTranslate();
3196
- const entryIdentifier = useMemo(
3197
- () => `${uniqueId}-${entry.uid}-${entry.item.id}`,
3198
- [entry]
3199
- );
3200
- const contentType = getContentTypeForUid(entry.uid);
3201
- const location = useLocation();
3202
- const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: entryIdentifier });
3203
- const trueRef = document.querySelector(
3204
- `[data-tableitem="${entryIdentifier}"]`
3205
- );
3206
- useEffect(() => {
3207
- if (!trueRef) return;
3208
- setNodeRef(trueRef);
3209
- }, [trueRef]);
3210
- const style = {
3211
- transform: CSS.Transform.toString(transform),
3212
- transition
3213
- };
3214
- const [currentLocale, setCurrentLocale] = useState("");
3215
- useEffect(() => {
3216
- const searchParams = new URLSearchParams(location.search);
3217
- const locale = searchParams.get("plugins[i18n][locale]");
3218
- if (!locale) return;
3219
- setCurrentLocale(locale);
3220
- }, [location]);
3221
- const goToEntry = () => {
3222
- if (!currentLocale) return;
3223
- const contentTypes = window.sessionStorage.getItem("mctr::content_types");
3224
- if (contentTypes) {
3225
- try {
3226
- const parsedContentTypes = JSON.parse(contentTypes);
3227
- if (Array.isArray(parsedContentTypes)) {
3228
- const contentType2 = parsedContentTypes.find(
3229
- (ct) => ct.uid === entry.uid
3230
- );
3231
- if (contentType2) {
3232
- const kind = contentType2.kind;
3233
- let url = `/admin/content-manager/${kind}/${entry.uid}`;
3234
- if (kind === "collectionType") {
3235
- url += `/${entry.item.id}`;
3236
- }
3237
- url += `?plugins[i18n][locale]=${currentLocale}`;
3238
- window.open(url, "_blank");
3239
- return;
3240
- }
3241
- }
3242
- } catch (e) {
3243
- console.error("[MCTR] Failed to retrieve content types");
3244
- }
3245
- } else {
3246
- alert(translate("tableItem.error"));
3247
- }
3248
- };
3249
- return /* @__PURE__ */ jsxs(
3250
- Tr,
3251
- {
3252
- style,
3253
- ...attributes,
3254
- ...listeners,
3255
- "data-tableitem": entryIdentifier,
3256
- children: [
3257
- /* @__PURE__ */ jsx(Td, { children: type === "selected" ? /* @__PURE__ */ jsx(IconButton, { noBorder: true, children: /* @__PURE__ */ jsx(Drag, {}) }) : null }),
3258
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Typography, { color: "neutral800", children: entry.item[entry.searchableField] }) }),
3259
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Typography, { color: "neutral800", children: entry.item.id }) }),
3260
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Typography, { color: "neutral800", children: entry.displayName }) }),
3261
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(
3262
- PublicationState,
3263
- {
3264
- isPublished: !!entry.item.publishedAt,
3265
- hasDraftAndPublish: contentType?.options?.draftAndPublish
3266
- }
3267
- ) }),
3268
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsxs(Flex, { children: [
3269
- /* @__PURE__ */ jsx(
3270
- IconButton,
3271
- {
3272
- label: translate("tableItem.goToEntry"),
3273
- onClick: goToEntry,
3274
- style: { "marg@in-right": "5px" },
3275
- children: /* @__PURE__ */ jsx(Eye, {})
3276
- }
3277
- ),
3278
- type === "suggestion" ? /* @__PURE__ */ jsx(
3279
- IconButton,
3280
- {
3281
- label: translate("tableItem.add"),
3282
- onClick: () => onAdd(entry),
3283
- disabled,
3284
- marginLeft: 1,
3285
- children: /* @__PURE__ */ jsx(Plus, {})
3286
- }
3287
- ) : type === "selected" ? /* @__PURE__ */ jsx(
3288
- IconButton,
3289
- {
3290
- label: translate("tableItem.delete"),
3291
- onClick: () => onDelete(entry),
3292
- marginLeft: 1,
3293
- children: /* @__PURE__ */ jsx(Trash, {})
3294
- }
3295
- ) : null
3296
- ] }) })
3297
- ]
3298
- }
3299
- );
3300
- };
3301
- function InputContentSuggestions({
3302
- uniqueId,
3303
- suggestions,
3304
- selected,
3305
- onAddEntry,
3306
- onDeleteEntry,
3307
- onEntriesSorted,
3308
- maximum,
3309
- sortable
3310
- }) {
3311
- const { translate } = useTranslate();
3312
- const suggestionAsSelectedEntry = useMemo(() => {
3313
- return (suggestions || []).flatMap(
3314
- (suggestion) => suggestion.results.map((entrySuggestion) => ({
3315
- displayName: suggestion.displayName,
3316
- item: entrySuggestion,
3317
- searchableField: suggestion.searchableField,
3318
- uid: suggestion.uid
3319
- }))
3320
- ).slice(0, 10);
3321
- }, [suggestions]);
3322
- const buildSelectedId = (entry) => {
3323
- return `${uniqueId}-${entry.uid}-${entry.item.id}`;
3324
- };
3325
- const availableSuggestions = useMemo(() => {
3326
- const selectedIdentifiers = (selected || []).map(buildSelectedId);
3327
- return suggestionAsSelectedEntry.filter(
3328
- (suggestion) => !selectedIdentifiers.includes(buildSelectedId(suggestion))
3329
- );
3330
- }, [suggestions, selected]);
3331
- const onAdd = (entry) => {
3332
- if (typeof onAddEntry === "function") {
3333
- onAddEntry(entry);
3334
- }
3335
- };
3336
- const onDelete = (entry) => {
3337
- if (typeof onDeleteEntry === "function") {
3338
- onDeleteEntry(entry);
3339
- }
3340
- };
3341
- const onSort = (entries) => {
3342
- if (typeof onEntriesSorted === "function") {
3343
- onEntriesSorted(entries);
3344
- }
3345
- };
3346
- const sensors = useSensors(
3347
- useSensor(PointerSensor, {
3348
- activationConstraint: {
3349
- distance: 5
3350
- }
3351
- })
3352
- );
3353
- const handleDragEnd = (event) => {
3354
- const { active, over } = event;
3355
- if (!active || !over) return;
3356
- if (active.id !== over.id) {
3357
- const oldIndex = selected.findIndex(
3358
- (entry) => buildSelectedId(entry) === active.id
3359
- );
3360
- const newIndex = selected.findIndex(
3361
- (entry) => buildSelectedId(entry) === over.id
3362
- );
3363
- onSort(arrayMove(selected, oldIndex, newIndex));
3364
- }
3365
- };
3366
- if (!availableSuggestions?.length && !selected?.length) return null;
3367
- return /* @__PURE__ */ jsx(Box, { padding: [2, 0, 2, 0], background: "neutral100", children: /* @__PURE__ */ jsxs(Table, { style: { whiteSpace: "unset" }, children: [
3368
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
3369
- /* @__PURE__ */ jsx(Th, {}),
3370
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: translate("contentSuggestions.title") }) }),
3371
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: translate("contentSuggestions.id") }) }),
3372
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: translate("contentSuggestions.contentType") }) }),
3373
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: translate("contentSuggestions.state") }) })
3374
- ] }) }),
3375
- /* @__PURE__ */ jsxs(Tbody, { children: [
3376
- selected?.length ? sortable ? /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(
3377
- DndContext,
3378
- {
3379
- sensors,
3380
- collisionDetection: closestCenter,
3381
- onDragEnd: handleDragEnd,
3382
- children: /* @__PURE__ */ jsx(
3383
- SortableContext,
3384
- {
3385
- items: selected.map((entry) => buildSelectedId(entry)),
3386
- strategy: verticalListSortingStrategy,
3387
- children: selected.map((entry) => /* @__PURE__ */ jsx(
3388
- TableItem,
3389
- {
3390
- uniqueId,
3391
- entry,
3392
- type: "selected",
3393
- onDelete,
3394
- sortable
3395
- },
3396
- buildSelectedId(entry)
3397
- ))
3398
- }
3399
- )
3400
- }
3401
- ) }) : (selected || []).map((entry) => /* @__PURE__ */ jsx(
3402
- TableItem,
3403
- {
3404
- uniqueId,
3405
- entry,
3406
- type: "selected",
3407
- onDelete
3408
- }
3409
- )) : null,
3410
- availableSuggestions.length && selected?.length ? /* @__PURE__ */ jsx(Tr, { style: { height: "32px" } }) : null,
3411
- availableSuggestions.map((entry) => /* @__PURE__ */ jsx(
3412
- TableItem,
3413
- {
3414
- uniqueId,
3415
- entry,
3416
- type: "suggestion",
3417
- onAdd,
3418
- disabled: typeof maximum === "number" ? (selected?.length ?? 0) >= maximum : false
3419
- },
3420
- buildSelectedId(entry)
3421
- ))
3422
- ] })
3423
- ] }) });
3424
- }
3425
- const MainInput = ({
3426
- name,
3427
- error,
3428
- description,
3429
- onChange,
3430
- value,
3431
- labelAction,
3432
- label,
3433
- attribute,
3434
- required
3435
- }) => {
3436
- const { formatMessage } = useIntl();
3437
- const { translate } = useTranslate();
3438
- const location = useLocation();
3439
- const maximumItems = attribute.options.max;
3440
- const minimumItems = attribute.options.min || 0;
3441
- const currentLocale = new URLSearchParams(location.search).get(
3442
- "plugins[i18n][locale]"
3443
- );
3444
- const [keyword, setKeyword] = useState("");
3445
- const [selected, setSelected] = useState([]);
3446
- const [loading, setLoading] = useState(true);
3447
- useEffect(() => {
3448
- const value2 = selected.length > maximumItems || selected.length < minimumItems ? [] : selected;
3449
- onChange({ target: { name, value: formatToStrapiField(value2) } });
3450
- }, [selected]);
3451
- const hint = useMemo(() => {
3452
- const minLabel = minimumItems > 0 ? `${translate("input.hint.min")} ${minimumItems} ${minimumItems > 1 ? translate("input.hint.entries") : translate("input.hint.entry")}` : "";
3453
- const maxLabel = maximumItems > 0 ? `${translate("input.hint.max")} ${maximumItems} ${maximumItems > 1 ? translate("input.hint.entries") : translate("input.hint.entry")}` : "";
3454
- return `
3455
- ${minLabel ? `${minLabel}` : ""}
3456
- ${minLabel && maxLabel ? ", " : ""}
3457
- ${maxLabel}
3458
- ${minLabel || maxLabel ? translate("input.hint.separator") : ""}
3459
- ${selected.length} ${translate("input.hint.selected")}
3460
- `;
3461
- }, [selected, maximumItems, minimumItems, translate]);
3462
- const inputError = useMemo(() => {
3463
- if (!error) return "";
3464
- if (selected.length < minimumItems)
3465
- return `${error} - ${translate("input.error.min")} ${minimumItems} ${translate("input.error.required")}`;
3466
- if (selected.length > maximumItems)
3467
- return `${error} - ${translate("input.error.max")} ${maximumItems} ${translate("input.error.required")}`;
3468
- return error;
3469
- }, [error, maximumItems, minimumItems, selected, translate]);
3470
- const { loading: searchLoading, results } = useSearchedEntries(
3471
- keyword,
3472
- attribute.options.contentTypes,
3473
- currentLocale
3474
- );
3475
- useEffect(() => {
3476
- async function validateContent() {
3477
- if (!value) {
3478
- setLoading(false);
3479
- return;
3480
- }
3481
- const entries = JSON.parse(value);
3482
- const result = await validateCurrentRelations(entries);
3483
- setSelected(result);
3484
- setLoading(false);
3485
- }
3486
- validateContent();
3487
- }, []);
3488
- const onAddEntry = (entry) => {
3489
- const alreadyDefined = selected.some(
3490
- (selectedEntry) => selectedEntry.uid === entry.uid && selectedEntry.item.id === entry.item.id
3491
- );
3492
- if (alreadyDefined) return;
3493
- setSelected([...selected, entry]);
3494
- };
3495
- const onDeleteEntry = (entry) => {
3496
- const newSelected = selected.filter(
3497
- (selectedEntry) => !(selectedEntry.uid === entry.uid && selectedEntry.item.id === entry.item.id)
3498
- );
3499
- setSelected(newSelected);
3500
- };
3501
- const onEntriesSorted = (entries) => {
3502
- setSelected(entries);
3503
- };
3504
- if (loading) return /* @__PURE__ */ jsx(Loader, {});
3505
- return /* @__PURE__ */ jsxs(
3506
- Field.Root,
3507
- {
3508
- name,
3509
- id: name,
3510
- error,
3511
- hint: description,
3512
- required,
3513
- children: [
3514
- /* @__PURE__ */ jsx(Field.Label, { action: labelAction, children: label }),
3515
- /* @__PURE__ */ jsx(
3516
- TextInput,
3517
- {
3518
- placeholder: translate("input.placeholder"),
3519
- required,
3520
- hint,
3521
- error: inputError,
3522
- value: keyword,
3523
- onChange: (e) => setKeyword(e.target.value)
3524
- }
3525
- ),
3526
- searchLoading ? /* @__PURE__ */ jsx(Loader, {}) : /* @__PURE__ */ jsx(
3527
- InputContentSuggestions,
3528
- {
3529
- uniqueId: Date.now(),
3530
- suggestions: results,
3531
- selected,
3532
- onAddEntry,
3533
- onDeleteEntry,
3534
- onEntriesSorted,
3535
- maximum: maximumItems,
3536
- sortable: true
3537
- }
3538
- )
3539
- ]
3540
- }
3541
- );
3542
- };
3543
- const Index = (props) => {
3544
- const { locale } = useIntl();
3545
- const theme = useMemo(() => ({}), []);
3546
- const attribute = useMemo(() => {
3547
- if (!props.attribute) return props.attribute;
3548
- if (!props.attribute.options) return props.attribute;
3549
- if (!props.attribute.options.contentTypes) return props.attribute;
3550
- const contentTypes = Object.keys(
3551
- props.attribute.options.contentTypes
3552
- ).filter((key) => props.attribute.options.contentTypes[key]);
3553
- return {
3554
- ...props.attribute,
3555
- options: {
3556
- ...props.attribute.options,
3557
- contentTypes: contentTypes.join(",")
3558
- }
3559
- };
3560
- }, [props.attribute]);
3561
- return /* @__PURE__ */ jsx(DesignSystemProvider, { theme, children: /* @__PURE__ */ jsx(MainInput, { ...props, attribute }) });
3562
- };
3563
- export {
3564
- Index as default
3565
- };