forked from react-grid-layout/react-grid-layout
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactGridLayout.jsx
More file actions
1422 lines (1254 loc) · 41.3 KB
/
Copy pathReactGridLayout.jsx
File metadata and controls
1422 lines (1254 loc) · 41.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
import * as React from "react";
import { deepEqual } from "fast-equals";
import clsx from "clsx";
import {
bottom,
childrenEqual,
cloneLayoutItem,
compact,
compactType,
fastRGLPropsEqual,
getAllCollisions,
getLayoutItem,
moveElement,
noop,
synchronizeLayoutWithChildren,
withLayoutItem
} from "./utils";
import { calcXY } from "./calculateUtils";
import GridItem from "./GridItem";
import ReactGridLayoutPropTypes from "./ReactGridLayoutPropTypes";
import DragDropContext from "./DragDropContext";
import type { DragDropContextValue } from "./DragDropContext";
import type {
ChildrenArray as ReactChildrenArray,
Element as ReactElement
} from "react";
// Types
import type {
CompactType,
GridResizeEvent,
GridDragEvent,
DragOverEvent,
Layout,
DroppingPosition,
LayoutItem
} from "./utils";
import type { PositionParams } from "./calculateUtils";
type State = {
activeDrag: ?LayoutItem,
layout: Layout,
mounted: boolean,
oldDragItem: ?LayoutItem,
oldLayout: ?Layout,
oldResizeItem: ?LayoutItem,
resizing: boolean,
droppingDOMNode: ?ReactElement<any>,
droppingPosition?: DroppingPosition,
// Cross-grid drag state
isDropActive: boolean,
isDropSource: boolean,
// Mirrored props
children: ReactChildrenArray<ReactElement<any>>,
compactType?: CompactType,
propsLayout?: Layout
};
import type { Props, DefaultProps } from "./ReactGridLayoutPropTypes";
// End Types
const layoutClassName = "react-grid-layout";
let isFirefox = false;
// Try...catch will protect from navigator not existing (e.g. node) or a bad implementation of navigator
try {
isFirefox = /firefox/i.test(navigator.userAgent);
} catch (e) {
/* Ignore */
}
/**
* A reactive, fluid grid layout with draggable, resizable components.
*/
export default class ReactGridLayout extends React.Component<Props, State> {
// TODO publish internal ReactClass displayName transform
static displayName: ?string = "ReactGridLayout";
// Refactored to another module to make way for preval
static propTypes = ReactGridLayoutPropTypes;
// Context for drag and drop (grids and external containers)
static contextType = DragDropContext;
context: ?DragDropContextValue;
static defaultProps: DefaultProps = {
autoSize: true,
cols: 12,
className: "",
style: {},
draggableHandle: "",
draggableCancel: "",
containerPadding: null,
rowHeight: 150,
maxRows: Infinity, // infinite vertical growth
layout: [],
margin: [10, 10],
isBounded: false,
isDraggable: true,
isResizable: true,
allowOverlap: false,
isDroppable: false,
useCSSTransforms: true,
transformScale: 1,
verticalCompact: true,
compactType: "vertical",
preventCollision: false,
droppingItem: {
i: "__dropping-elem__",
h: 1,
w: 1
},
resizeHandles: ["se"],
onLayoutChange: noop,
onDragStart: noop,
onDrag: noop,
onDragStop: noop,
onResizeStart: noop,
onResize: noop,
onResizeStop: noop,
onDrop: noop,
onDropDragOver: noop,
// Cross-grid defaults
enableCrossGridDrag: false,
crossGridAcceptsDrop: true
};
state: State = {
activeDrag: null,
layout: synchronizeLayoutWithChildren(
this.props.layout,
this.props.children,
this.props.cols,
// Legacy support for verticalCompact: false
compactType(this.props),
this.props.allowOverlap
),
mounted: false,
oldDragItem: null,
oldLayout: null,
oldResizeItem: null,
resizing: false,
droppingDOMNode: null,
isDropActive: false,
isDropSource: false,
children: []
};
dragEnterCounter: number = 0;
gridRef: { current: ?HTMLElement } = React.createRef();
// Cache for grid bounds to avoid expensive getBoundingClientRect calls
cachedBounds: ?DOMRect = null;
cachedBoundsTime: number = 0;
// Cache TTL in milliseconds - bounds are considered stale after this time
BOUNDS_CACHE_TTL: number = 100;
componentDidMount() {
this.setState({ mounted: true });
// Possibly call back with layout on mount. This should be done after correcting the layout width
// to ensure we don't rerender with the wrong width.
this.onLayoutMaybeChanged(this.state.layout, this.props.layout);
// Register with drag-drop context if enabled
if (this.props.enableCrossGridDrag && this.context && this.props.id && this.gridRef.current) {
this.context.registerDropTarget(
this.props.id,
this.gridRef.current,
'grid',
{
cols: this.props.cols,
rowHeight: this.props.rowHeight,
containerWidth: this.props.width,
margin: this.props.margin,
acceptsDrop: this.getAcceptsDrop(),
onItemRemoved: this.onItemRemovedFromGrid
}
);
}
// Set up resize listener to invalidate bounds cache
window.addEventListener('resize', this.invalidateBoundsCache);
}
componentWillUnmount() {
// Unregister from drag-drop context
if (this.props.enableCrossGridDrag && this.context && this.props.id) {
this.context.unregisterDropTarget(this.props.id);
}
// Clean up resize listener
window.removeEventListener('resize', this.invalidateBoundsCache);
}
static getDerivedStateFromProps(
nextProps: Props,
prevState: State
): $Shape<State> | null {
let newLayoutBase;
if (prevState.activeDrag) {
return null;
}
// Legacy support for compactType
// Allow parent to set layout directly.
if (
!deepEqual(nextProps.layout, prevState.propsLayout) ||
nextProps.compactType !== prevState.compactType
) {
newLayoutBase = nextProps.layout;
} else if (!childrenEqual(nextProps.children, prevState.children)) {
// If children change, also regenerate the layout. Use our state
// as the base in case because it may be more up to date than
// what is in props.
newLayoutBase = prevState.layout;
}
// We need to regenerate the layout.
if (newLayoutBase) {
const newLayout = synchronizeLayoutWithChildren(
newLayoutBase,
nextProps.children,
nextProps.cols,
compactType(nextProps),
nextProps.allowOverlap
);
return {
layout: newLayout,
// We need to save these props to state for using
// getDerivedStateFromProps instead of componentDidMount (in which we would get extra rerender)
compactType: nextProps.compactType,
children: nextProps.children,
propsLayout: nextProps.layout
};
}
return null;
}
shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
return (
// NOTE: this is almost always unequal. Therefore the only way to get better performance
// from SCU is if the user intentionally memoizes children. If they do, and they can
// handle changes properly, performance will increase.
this.props.children !== nextProps.children ||
!fastRGLPropsEqual(this.props, nextProps, deepEqual) ||
this.state.activeDrag !== nextState.activeDrag ||
this.state.mounted !== nextState.mounted ||
this.state.droppingPosition !== nextState.droppingPosition ||
this.state.isDropActive !== nextState.isDropActive ||
this.state.isDropSource !== nextState.isDropSource
);
}
componentDidUpdate(prevProps: Props, prevState: State) {
// Update drop target config in context if width or other grid properties changed
if (this.props.enableCrossGridDrag && this.context && this.props.id) {
if (
prevProps.width !== this.props.width ||
prevProps.cols !== this.props.cols ||
prevProps.rowHeight !== this.props.rowHeight ||
prevProps.crossGridAcceptsDrop !== this.props.crossGridAcceptsDrop
) {
this.context.updateDropTargetConfig(this.props.id, {
containerWidth: this.props.width,
cols: this.props.cols,
rowHeight: this.props.rowHeight,
acceptsDrop: this.getAcceptsDrop()
});
}
}
if (!this.state.activeDrag) {
const newLayout = this.state.layout;
const oldLayout = prevState.layout;
this.onLayoutMaybeChanged(newLayout, oldLayout);
}
// Handle external drag (cross-grid)
// Only run if there's an active cross-grid drag to avoid unnecessary expensive calculations
if (this.props.enableCrossGridDrag && this.context?.dragState) {
this.handleExternalDrag();
// Also check if this grid is the SOURCE and should hide its placeholder
// This runs in componentDidUpdate to sync with target grid's placeholder showing
const { dragState } = this.context;
if (dragState.sourceId === this.props.id && this.state.activeDrag && !this.state.activeDrag.i.startsWith("__external__")) {
if (this.context.findInnermostTarget) {
const innermostTargetId = this.context.findInnermostTarget(
dragState.mouseX,
dragState.mouseY,
dragState.sourceId,
dragState.item
);
const shouldHide = innermostTargetId !== null;
if (shouldHide !== this.state.activeDrag.hidden) {
this.setState({
activeDrag: { ...this.state.activeDrag, hidden: shouldHide }
});
}
}
}
}
// Handle cross-grid drag end
if (this.props.enableCrossGridDrag && this.context) {
const hadActiveDrag = prevState.activeDrag;
const dragJustEnded = !this.context.dragState;
if (hadActiveDrag && dragJustEnded) {
// Check if this was an external placeholder drop on this grid
const hadExternalPlaceholder = hadActiveDrag.i.startsWith("__external__");
if (hadExternalPlaceholder && this.state.activeDrag) {
// The drag ended while we had an external placeholder - finalize the drop
this.handleExternalDrop();
} else if (!hadExternalPlaceholder && this.state.activeDrag) {
// This is the source grid - clear activeDrag if item was dropped elsewhere
// But DON'T clear if we're currently resizing (prevents flicker)
if (!this.state.resizing) {
this.setState({
activeDrag: null,
oldLayout: null,
...this.clearDropState()
});
}
}
}
}
}
/**
* Calculates a pixel value for the container.
* @return {String} Container height in pixels.
*/
containerHeight(): ?string {
if (!this.props.autoSize) return;
// Exclude collapsed item from height calculation
let layoutForHeight = this.state.layout;
if (this.state.activeDrag?.hidden) {
layoutForHeight = this.state.layout.filter(item => item.i !== this.state.activeDrag.i);
}
const nbRow = bottom(layoutForHeight);
const containerPaddingY = this.props.containerPadding
? this.props.containerPadding[1]
: this.props.margin[1];
return (
nbRow * this.props.rowHeight +
(nbRow - 1) * this.props.margin[1] +
containerPaddingY * 2 +
"px"
);
}
/**
* When dragging starts
* @param {String} i Id of the child
* @param {Number} x X position of the move
* @param {Number} y Y position of the move
* @param {Event} e The mousedown event
* @param {Element} node The current dragging DOM element
*/
onDragStart: (i: string, x: number, y: number, GridDragEvent) => void = (
i: string,
x: number,
y: number,
{ e, node }: GridDragEvent
) => {
const { layout } = this.state;
const l = getLayoutItem(layout, i);
if (!l) return;
// Create placeholder (display only)
const placeholder = {
w: l.w,
h: l.h,
x: l.x,
y: l.y,
placeholder: true,
i: i
};
this.setState({
oldDragItem: cloneLayoutItem(l),
oldLayout: layout,
activeDrag: placeholder
});
return this.props.onDragStart(layout, l, l, null, e, node);
};
/**
* Each drag movement create a new dragelement and move the element to the dragged location
* @param {String} i Id of the child
* @param {Number} x X position of the move
* @param {Number} y Y position of the move
* @param {Event} e The mousedown event
* @param {Element} node The current dragging DOM element
*/
onDrag: (i: string, x: number, y: number, GridDragEvent) => void = (
i,
x,
y,
{ e, node }
) => {
const { oldDragItem } = this.state;
let { layout } = this.state;
const { cols, allowOverlap, preventCollision } = this.props;
const l = getLayoutItem(layout, i);
if (!l) return;
// Collapse item when over a valid drop target (not when over empty space or self)
// Use findInnermostTarget to properly handle nested containers
let shouldCollapseItem = false;
if (this.props.enableCrossGridDrag && this.context?.dragState && oldDragItem) {
const { dragState } = this.context;
if (dragState.sourceId === this.props.id && this.context.findInnermostTarget) {
const innermostTargetId = this.context.findInnermostTarget(
dragState.mouseX,
dragState.mouseY,
dragState.sourceId,
dragState.item
);
// Only collapse if we're over a DIFFERENT target (not null/self)
// null means we're over ourselves (source), so don't collapse
if (innermostTargetId !== null) {
shouldCollapseItem = true;
}
}
}
const draggedItemW = oldDragItem?.w ?? l.w;
const draggedItemH = oldDragItem?.h ?? l.h;
const placeholder = {
w: draggedItemW,
h: draggedItemH,
x: l.x,
y: l.y,
placeholder: true,
i: i,
hidden: shouldCollapseItem
};
let layoutForCompaction = layout;
if (shouldCollapseItem) {
layoutForCompaction = layout.map(item =>
item.i === i ? { ...item, w: 0, h: 0 } : item
);
}
// Move the element to the dragged location.
const isUserAction = true;
layoutForCompaction = moveElement(
layoutForCompaction,
getLayoutItem(layoutForCompaction, i),
x,
y,
isUserAction,
preventCollision,
compactType(this.props),
cols,
allowOverlap
);
const compactedLayout = allowOverlap
? layoutForCompaction
: compact(layoutForCompaction, compactType(this.props), cols);
const finalLayout = compactedLayout.map(item =>
item.i === i ? { ...item, w: draggedItemW, h: draggedItemH } : item
);
this.props.onDrag(finalLayout, oldDragItem, l, placeholder, e, node);
const isSourceGrid = this.props.enableCrossGridDrag &&
this.context?.dragState &&
this.context.dragState.sourceId === this.props.id;
this.setState({
layout: finalLayout,
activeDrag: placeholder,
isDropSource: !!isSourceGrid,
isDropActive: isSourceGrid && !shouldCollapseItem
});
};
/**
* When dragging stops, figure out which position the element is closest to and update its x and y.
* @param {String} i Index of the child.
* @param {Number} x X position of the move
* @param {Number} y Y position of the move
* @param {Event} e The mousedown event
* @param {Element} node The current dragging DOM element
*/
onDragStop: (i: string, x: number, y: number, GridDragEvent) => void = (
i,
x,
y,
{ e, node }
) => {
if (!this.state.activeDrag) return;
// Check if this is an external item being dropped on this grid
const isExternalDrop = i.startsWith("__external__");
const { oldDragItem } = this.state;
let { layout } = this.state;
const { cols, preventCollision, allowOverlap } = this.props;
if (isExternalDrop && this.context && this.context.dragState) {
const externalItem = this.context.dragState.item;
// Remove the temporary __external__ item from layout
layout = layout.filter(item => !item.i.startsWith("__external__"));
// Get position from placeholder (it has been through collision detection)
const placeholder = this.state.activeDrag;
const newItem: LayoutItem = {
...externalItem,
i: externalItem.i, // Use original ID, not __external__
x: placeholder.x,
y: placeholder.y
};
// Add item to layout
layout = [...layout, newItem];
// Compact the layout with the new item
const newLayout = allowOverlap
? layout
: compact(layout, compactType(this.props), cols);
this.setState({
activeDrag: null,
layout: newLayout,
oldDragItem: null,
oldLayout: null,
...this.clearDropState()
});
this.onLayoutMaybeChanged(newLayout, this.state.oldLayout || layout);
return;
}
// Normal drag within same grid
const l = getLayoutItem(layout, i);
if (!l) return;
// Move the element here
const isUserAction = true;
layout = moveElement(
layout,
l,
x,
y,
isUserAction,
preventCollision,
compactType(this.props),
cols,
allowOverlap
);
// Set state
const newLayout = allowOverlap
? layout
: compact(layout, compactType(this.props), cols);
this.props.onDragStop(newLayout, oldDragItem, l, null, e, node);
const { oldLayout } = this.state;
this.setState({
activeDrag: null,
layout: newLayout,
oldDragItem: null,
oldLayout: null,
...this.clearDropState()
});
this.onLayoutMaybeChanged(newLayout, oldLayout);
};
onLayoutMaybeChanged(newLayout: Layout, oldLayout: ?Layout) {
if (!oldLayout) oldLayout = this.state.layout;
if (!deepEqual(oldLayout, newLayout)) {
this.props.onLayoutChange(newLayout);
}
}
onResizeStart: (i: string, w: number, h: number, GridResizeEvent) => void = (
i,
w,
h,
{ e, node }
) => {
const { layout } = this.state;
const l = getLayoutItem(layout, i);
if (!l) return;
this.setState({
oldResizeItem: cloneLayoutItem(l),
oldLayout: this.state.layout,
resizing: true
});
this.props.onResizeStart(layout, l, l, null, e, node);
};
onResize: (i: string, w: number, h: number, GridResizeEvent) => void = (
i,
w,
h,
{ e, node, size, handle }
) => {
const { oldResizeItem } = this.state;
const { layout } = this.state;
const { cols, preventCollision, allowOverlap } = this.props;
let shouldMoveItem = false;
let finalLayout;
let x;
let y;
const [newLayout, l] = withLayoutItem(layout, i, l => {
let hasCollisions;
x = l.x;
y = l.y;
if (["sw", "w", "nw", "n", "ne"].indexOf(handle) !== -1) {
if (["sw", "nw", "w"].indexOf(handle) !== -1) {
x = l.x + (l.w - w);
w = l.x !== x && x < 0 ? l.w : w;
x = x < 0 ? 0 : x;
}
if (["ne", "n", "nw"].indexOf(handle) !== -1) {
y = l.y + (l.h - h);
h = l.y !== y && y < 0 ? l.h : h;
y = y < 0 ? 0 : y;
}
shouldMoveItem = true;
}
// Something like quad tree should be used
// to find collisions faster
if (preventCollision && !allowOverlap) {
const collisions = getAllCollisions(layout, {
...l,
w,
h,
x,
y
}).filter(layoutItem => layoutItem.i !== l.i);
hasCollisions = collisions.length > 0;
// If we're colliding, we need adjust the placeholder.
if (hasCollisions) {
// Reset layoutItem dimensions if there were collisions
y = l.y;
h = l.h;
x = l.x;
w = l.w;
shouldMoveItem = false;
}
}
l.w = w;
l.h = h;
return l;
});
// Shouldn't ever happen, but typechecking makes it necessary
if (!l) return;
finalLayout = newLayout;
if (shouldMoveItem) {
// Move the element to the new position.
const isUserAction = true;
finalLayout = moveElement(
newLayout,
l,
x,
y,
isUserAction,
this.props.preventCollision,
compactType(this.props),
cols,
allowOverlap
);
}
// Create placeholder element (display only)
const placeholder = {
w: l.w,
h: l.h,
x: l.x,
y: l.y,
static: true,
i: i
};
this.props.onResize(finalLayout, oldResizeItem, l, placeholder, e, node);
// Re-compact the newLayout and set the drag placeholder.
this.setState({
layout: allowOverlap
? finalLayout
: compact(finalLayout, compactType(this.props), cols),
activeDrag: placeholder
});
};
onResizeStop: (i: string, w: number, h: number, GridResizeEvent) => void = (
i,
w,
h,
{ e, node }
) => {
const { layout, oldResizeItem } = this.state;
const { cols, allowOverlap } = this.props;
const l = getLayoutItem(layout, i);
// Set state
const newLayout = allowOverlap
? layout
: compact(layout, compactType(this.props), cols);
this.props.onResizeStop(newLayout, oldResizeItem, l, null, e, node);
const { oldLayout } = this.state;
this.setState({
activeDrag: null,
layout: newLayout,
oldResizeItem: null,
oldLayout: null,
resizing: false
});
this.onLayoutMaybeChanged(newLayout, oldLayout);
};
/**
* Handle external drag from another drop target
*/
handleExternalDrag = (): void => {
if (!this.props.enableCrossGridDrag || !this.context || !this.gridRef.current) return;
const { dragState } = this.context;
// If no drag or this is the source grid, clear any external drag state
if (!dragState || dragState.sourceId === this.props.id) {
// Clear activeDrag if it was from an external source
if (this.state.activeDrag && this.state.activeDrag.i.startsWith("__external__")) {
this.setState({
activeDrag: null,
layout: this.state.oldLayout || this.state.layout,
isDropActive: false
});
}
return;
}
// Check if this grid accepts drops from the source
const accepts = typeof this.props.crossGridAcceptsDrop === 'function'
? this.props.crossGridAcceptsDrop(dragState.item, dragState.sourceId)
: this.props.crossGridAcceptsDrop !== false;
if (!accepts) {
// Clear any external drag state if grid doesn't accept drops
if (this.state.activeDrag && this.state.activeDrag.i.startsWith("__external__")) {
this.setState({
activeDrag: null,
layout: this.state.oldLayout || this.state.layout,
isDropActive: false
});
}
return;
}
// Check if mouse is over this grid
if (!this.isMouseOverGrid(dragState.mouseX, dragState.mouseY)) {
// Clear activeDrag if it was from an external source
if (this.state.activeDrag && this.state.activeDrag.i.startsWith("__external__")) {
this.setState({
activeDrag: null,
layout: this.state.oldLayout || this.state.layout,
isDropActive: false
});
}
return;
}
// For nested containers: check if THIS grid is the innermost target
// If a nested grid is the actual target (or source is innermost), don't handle the drag here
if (this.context.findInnermostTarget) {
const innermostTargetId = this.context.findInnermostTarget(
dragState.mouseX,
dragState.mouseY,
dragState.sourceId,
dragState.item
);
// Only handle if THIS grid is the innermost target
// - null means source is innermost (within-grid drag, not our business)
// - different ID means another grid is the target
if (innermostTargetId !== this.props.id) {
if (this.state.activeDrag && this.state.activeDrag.i.startsWith("__external__")) {
this.setState({
activeDrag: null,
layout: this.state.oldLayout || this.state.layout,
isDropActive: false
});
}
return;
}
}
// Transform item from source grid to target grid dimensions
const sourceConfig = this.context.dropTargets.get(dragState.sourceId);
const targetConfig = {
id: this.props.id,
type: 'grid',
element: this.gridRef.current,
cols: this.props.cols,
rowHeight: this.props.rowHeight,
containerWidth: this.props.width,
margin: this.props.margin,
acceptsDrop: this.getAcceptsDrop(),
onItemRemoved: this.onItemRemovedFromGrid
};
let transformedItem = dragState.item;
if (sourceConfig) {
// Use custom transform if provided, otherwise use context's transform (which defaults to physical size preservation)
if (this.props.crossGridTransform) {
transformedItem = this.props.crossGridTransform(dragState.item, sourceConfig, targetConfig);
} else if (this.context.transformItem) {
transformedItem = this.context.transformItem(dragState.item, sourceConfig, targetConfig);
}
}
// Calculate grid position from mouse, accounting for grab offset
const gridPos = this.calcGridPositionFromMouse(
dragState.mouseX,
dragState.mouseY,
transformedItem,
dragState.offsetX,
dragState.offsetY
);
// Early exit optimization: if we already have a placeholder at this exact grid position
// and item dimensions haven't changed, skip expensive layout calculations
const externalId = `__external__${transformedItem.i}`;
const currentPlaceholder = this.state.activeDrag;
if (currentPlaceholder &&
currentPlaceholder.i === externalId &&
currentPlaceholder.x === gridPos.x &&
currentPlaceholder.y === gridPos.y &&
currentPlaceholder.w === transformedItem.w &&
currentPlaceholder.h === transformedItem.h) {
return;
}
const { cols, allowOverlap, preventCollision } = this.props;
// Save original layout on first external drag detection
// Use oldLayout as base, or current layout if this is the first external drag
let baseLayout = this.state.oldLayout;
if (!baseLayout) {
baseLayout = this.state.layout;
// Set oldLayout for future iterations and cleanup
this.setState({ oldLayout: baseLayout });
}
// Start fresh from base layout (without any external items)
let layout = baseLayout.filter(item => !item.i.startsWith("__external__"));
// Check if we already have the external item's previous position in the current layout
const existingExternalInState = getLayoutItem(this.state.layout, externalId);
// Create a temporary item to add to the layout for collision detection
// Use transformed item dimensions (w, h) from source grid to target grid
const externalItem: LayoutItem = {
...transformedItem,
i: externalId,
// Use previous position if we have it, otherwise start at current gridPos
x: existingExternalInState ? existingExternalInState.x : gridPos.x,
y: existingExternalInState ? existingExternalInState.y : gridPos.y
};
// Add the external item to the layout
layout = [...layout, externalItem];
// Get the actual item reference from layout (moveElement mutates it directly)
const layoutItem = getLayoutItem(layout, externalId);
if (!layoutItem) return;
// Apply moveElement for collision detection, just like internal drags
// Pass the NEW position (gridPos) so moveElement moves it there
const isUserAction = true;
layout = moveElement(
layout,
layoutItem,
gridPos.x,
gridPos.y,
isUserAction,
preventCollision,
compactType(this.props),
cols,
allowOverlap
);
// Compact the layout
const compactedLayout = allowOverlap
? layout
: compact(layout, compactType(this.props), cols);
// Get the updated position of the external item from the compacted layout
const updatedExternalItem = getLayoutItem(compactedLayout, externalId);
if (!updatedExternalItem) return;
// Create placeholder for display
const placeholder: LayoutItem = {
...updatedExternalItem,
placeholder: true
};
// Only update if position changed or no placeholder yet
if (!this.state.activeDrag ||
this.state.activeDrag.x !== placeholder.x ||
this.state.activeDrag.y !== placeholder.y) {
this.setState({
activeDrag: placeholder,
layout: compactedLayout,
isDropActive: true
});
} else if (!this.state.isDropActive) {
// If position hasn't changed but isDropActive is false, set it to true
this.setState({ isDropActive: true });
}
};
/**
* Handle external drop - finalize adding an external item to this grid
*/
handleExternalDrop = (): void => {
if (!this.state.activeDrag || !this.state.activeDrag.i.startsWith("__external__")) return;
const { cols, allowOverlap } = this.props;
let { layout } = this.state;
const placeholder = this.state.activeDrag;
// Get the original item ID (remove __external__ prefix)
const originalId = placeholder.i.replace("__external__", "");
// Remove the temporary __external__ item from layout
layout = layout.filter(item => !item.i.startsWith("__external__"));
// Add the real item with the original ID
const newItem: LayoutItem = {
...placeholder,
i: originalId,
placeholder: false
};
layout = [...layout, newItem];
// Compact the layout with the new item
const newLayout = allowOverlap
? layout
: compact(layout, compactType(this.props), cols);
// Update state - componentDidUpdate will call onLayoutMaybeChanged
this.setState({
activeDrag: null,
layout: newLayout,
oldLayout: null,
...this.clearDropState()
});
};
getAcceptsDrop = (): boolean | ((item: LayoutItem, sourceId: string) => boolean) => {
const { crossGridAcceptsDrop } = this.props;
return crossGridAcceptsDrop === false ? false : crossGridAcceptsDrop || true;
};
clearDropState = (): $Shape<State> => {
return {
isDropActive: false,
isDropSource: false