react-grid-layout 1.5.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +1075 -432
  2. package/css/styles.css +6 -4
  3. package/dist/ResponsiveGridLayout-CH4s0tKj.d.ts +124 -0
  4. package/dist/ResponsiveGridLayout-D6lFRE3f.d.mts +124 -0
  5. package/dist/calculate-CwYDW8na.d.mts +168 -0
  6. package/dist/calculate-mgLpNJ5O.d.ts +168 -0
  7. package/dist/chunk-2KUHNJXF.mjs +90 -0
  8. package/dist/chunk-2KUHNJXF.mjs.map +1 -0
  9. package/dist/chunk-3WO4SAYB.js +868 -0
  10. package/dist/chunk-3WO4SAYB.js.map +1 -0
  11. package/dist/chunk-4HNUMWQK.mjs +822 -0
  12. package/dist/chunk-4HNUMWQK.mjs.map +1 -0
  13. package/dist/chunk-BFTKGAP3.js +1309 -0
  14. package/dist/chunk-BFTKGAP3.js.map +1 -0
  15. package/dist/chunk-F6NQPYKT.js +98 -0
  16. package/dist/chunk-F6NQPYKT.js.map +1 -0
  17. package/dist/chunk-H5KMDLY3.js +434 -0
  18. package/dist/chunk-H5KMDLY3.js.map +1 -0
  19. package/dist/chunk-PBQSHIID.js +4 -0
  20. package/dist/chunk-PBQSHIID.js.map +1 -0
  21. package/dist/chunk-R35HZZTA.mjs +1300 -0
  22. package/dist/chunk-R35HZZTA.mjs.map +1 -0
  23. package/dist/chunk-ZCXE6SR5.mjs +428 -0
  24. package/dist/chunk-ZCXE6SR5.mjs.map +1 -0
  25. package/dist/chunk-ZWN22PS2.mjs +3 -0
  26. package/dist/chunk-ZWN22PS2.mjs.map +1 -0
  27. package/dist/core.d.mts +33 -0
  28. package/dist/core.d.ts +33 -0
  29. package/dist/core.js +218 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/core.mjs +5 -0
  32. package/dist/core.mjs.map +1 -0
  33. package/dist/extras.d.mts +78 -0
  34. package/dist/extras.d.ts +78 -0
  35. package/dist/extras.js +91 -0
  36. package/dist/extras.js.map +1 -0
  37. package/dist/extras.mjs +89 -0
  38. package/dist/extras.mjs.map +1 -0
  39. package/dist/index.d.mts +7 -0
  40. package/dist/index.d.ts +7 -0
  41. package/dist/index.js +154 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/index.mjs +7 -0
  44. package/dist/index.mjs.map +1 -0
  45. package/dist/legacy.d.mts +163 -0
  46. package/dist/legacy.d.ts +163 -0
  47. package/dist/legacy.js +319 -0
  48. package/dist/legacy.js.map +1 -0
  49. package/dist/legacy.mjs +307 -0
  50. package/dist/legacy.mjs.map +1 -0
  51. package/dist/position-BmN1z36J.d.mts +319 -0
  52. package/dist/position-Dk2b4ZMS.d.ts +319 -0
  53. package/dist/react.d.mts +351 -0
  54. package/dist/react.d.ts +351 -0
  55. package/dist/react.js +96 -0
  56. package/dist/react.js.map +1 -0
  57. package/dist/react.mjs +7 -0
  58. package/dist/react.mjs.map +1 -0
  59. package/dist/responsive-C4L1ESlm.d.ts +145 -0
  60. package/dist/responsive-CJxefsYw.d.mts +145 -0
  61. package/dist/types-Cxf4nHNr.d.mts +375 -0
  62. package/dist/types-Cxf4nHNr.d.ts +375 -0
  63. package/index-dev.js +8 -0
  64. package/package.json +132 -39
  65. package/.babelrc.js +0 -22
  66. package/.browserslistrc +0 -3
  67. package/.eslintignore +0 -4
  68. package/.flowconfig +0 -20
  69. package/.prettierignore +0 -4
  70. package/.prettierrc +0 -17
  71. package/CHANGELOG.md +0 -985
  72. package/build/GridItem.js +0 -640
  73. package/build/ReactGridLayout.js +0 -744
  74. package/build/ReactGridLayoutPropTypes.js +0 -210
  75. package/build/ResponsiveReactGridLayout.js +0 -294
  76. package/build/calculateUtils.js +0 -165
  77. package/build/components/WidthProvider.js +0 -111
  78. package/build/fastRGLPropsEqual.js +0 -5
  79. package/build/responsiveUtils.js +0 -101
  80. package/build/utils.js +0 -834
  81. package/dist/react-grid-layout.min.js +0 -2
  82. package/dist/react-grid-layout.min.js.map +0 -1
  83. package/index.js.flow +0 -8
  84. package/ip_fetcher +0 -0
  85. package/ip_fetcher.c +0 -47
  86. package/lib/GridItem.jsx +0 -689
  87. package/lib/ReactGridLayout.jsx +0 -855
  88. package/lib/ReactGridLayoutPropTypes.js +0 -241
  89. package/lib/ResponsiveReactGridLayout.jsx +0 -349
  90. package/lib/calculateUtils.js +0 -169
  91. package/lib/components/WidthProvider.jsx +0 -110
  92. package/lib/fastRGLPropsEqual.js +0 -46
  93. package/lib/responsiveUtils.js +0 -118
  94. package/lib/utils.js +0 -979
package/lib/utils.js DELETED
@@ -1,979 +0,0 @@
1
- // @flow
2
- import { deepEqual } from "fast-equals";
3
- import React from "react";
4
- import type {
5
- ChildrenArray as ReactChildrenArray,
6
- Element as ReactElement
7
- } from "react";
8
-
9
- export type ResizeHandleAxis =
10
- | "s"
11
- | "w"
12
- | "e"
13
- | "n"
14
- | "sw"
15
- | "nw"
16
- | "se"
17
- | "ne";
18
-
19
- export type LayoutItem = {
20
- w: number,
21
- h: number,
22
- x: number,
23
- y: number,
24
- i: string,
25
- minW?: number,
26
- minH?: number,
27
- maxW?: number,
28
- maxH?: number,
29
- moved?: boolean,
30
- static?: boolean,
31
- isDraggable?: ?boolean,
32
- isResizable?: ?boolean,
33
- resizeHandles?: Array<ResizeHandleAxis>,
34
- isBounded?: ?boolean
35
- };
36
- export type Layout = $ReadOnlyArray<LayoutItem>;
37
- export type Position = {
38
- left: number,
39
- top: number,
40
- width: number,
41
- height: number
42
- };
43
- export type ReactDraggableCallbackData = {
44
- node: HTMLElement,
45
- x?: number,
46
- y?: number,
47
- deltaX: number,
48
- deltaY: number,
49
- lastX?: number,
50
- lastY?: number
51
- };
52
-
53
- export type PartialPosition = { left: number, top: number };
54
- export type DroppingPosition = { left: number, top: number, e: Event };
55
- export type Size = { width: number, height: number };
56
- export type GridDragEvent = {
57
- e: Event,
58
- node: HTMLElement,
59
- newPosition: PartialPosition
60
- };
61
- export type GridResizeEvent = {
62
- e: Event,
63
- node: HTMLElement,
64
- size: Size,
65
- handle: string
66
- };
67
- export type DragOverEvent = MouseEvent & {
68
- nativeEvent: {
69
- layerX: number,
70
- layerY: number,
71
- ...Event
72
- }
73
- };
74
-
75
- // Helpful port from TS
76
- export type Pick<FromType, Properties: { [string]: 0 }> = $Exact<
77
- $ObjMapi<Properties, <K, V>(k: K, v: V) => $ElementType<FromType, K>>
78
- >;
79
-
80
- type REl = ReactElement<any>;
81
- export type ReactChildren = ReactChildrenArray<REl>;
82
-
83
- // All callbacks are of the signature (layout, oldItem, newItem, placeholder, e).
84
- export type EventCallback = (
85
- Layout,
86
- oldItem: ?LayoutItem,
87
- newItem: ?LayoutItem,
88
- placeholder: ?LayoutItem,
89
- Event,
90
- ?HTMLElement
91
- ) => void;
92
- export type CompactType = ?("horizontal" | "vertical");
93
-
94
- const isProduction = process.env.NODE_ENV === "production";
95
- const DEBUG = false;
96
-
97
- /**
98
- * Return the bottom coordinate of the layout.
99
- *
100
- * @param {Array} layout Layout array.
101
- * @return {Number} Bottom coordinate.
102
- */
103
- export function bottom(layout: Layout): number {
104
- let max = 0,
105
- bottomY;
106
- for (let i = 0, len = layout.length; i < len; i++) {
107
- bottomY = layout[i].y + layout[i].h;
108
- if (bottomY > max) max = bottomY;
109
- }
110
- return max;
111
- }
112
-
113
- export function cloneLayout(layout: Layout): Layout {
114
- const newLayout = Array(layout.length);
115
- for (let i = 0, len = layout.length; i < len; i++) {
116
- newLayout[i] = cloneLayoutItem(layout[i]);
117
- }
118
- return newLayout;
119
- }
120
-
121
- // Modify a layoutItem inside a layout. Returns a new Layout,
122
- // does not mutate. Carries over all other LayoutItems unmodified.
123
- export function modifyLayout(layout: Layout, layoutItem: LayoutItem): Layout {
124
- const newLayout = Array(layout.length);
125
- for (let i = 0, len = layout.length; i < len; i++) {
126
- if (layoutItem.i === layout[i].i) {
127
- newLayout[i] = layoutItem;
128
- } else {
129
- newLayout[i] = layout[i];
130
- }
131
- }
132
- return newLayout;
133
- }
134
-
135
- // Function to be called to modify a layout item.
136
- // Does defensive clones to ensure the layout is not modified.
137
- export function withLayoutItem(
138
- layout: Layout,
139
- itemKey: string,
140
- cb: LayoutItem => LayoutItem
141
- ): [Layout, ?LayoutItem] {
142
- let item = getLayoutItem(layout, itemKey);
143
- if (!item) return [layout, null];
144
- item = cb(cloneLayoutItem(item)); // defensive clone then modify
145
- // FIXME could do this faster if we already knew the index
146
- layout = modifyLayout(layout, item);
147
- return [layout, item];
148
- }
149
-
150
- // Fast path to cloning, since this is monomorphic
151
- export function cloneLayoutItem(layoutItem: LayoutItem): LayoutItem {
152
- return {
153
- w: layoutItem.w,
154
- h: layoutItem.h,
155
- x: layoutItem.x,
156
- y: layoutItem.y,
157
- i: layoutItem.i,
158
- minW: layoutItem.minW,
159
- maxW: layoutItem.maxW,
160
- minH: layoutItem.minH,
161
- maxH: layoutItem.maxH,
162
- moved: Boolean(layoutItem.moved),
163
- static: Boolean(layoutItem.static),
164
- // These can be null/undefined
165
- isDraggable: layoutItem.isDraggable,
166
- isResizable: layoutItem.isResizable,
167
- resizeHandles: layoutItem.resizeHandles,
168
- isBounded: layoutItem.isBounded
169
- };
170
- }
171
-
172
- /**
173
- * Comparing React `children` is a bit difficult. This is a good way to compare them.
174
- * This will catch differences in keys, order, and length.
175
- */
176
- export function childrenEqual(a: ReactChildren, b: ReactChildren): boolean {
177
- return (
178
- deepEqual(
179
- React.Children.map(a, c => c?.key),
180
- React.Children.map(b, c => c?.key)
181
- ) &&
182
- deepEqual(
183
- React.Children.map(a, c => c?.props["data-grid"]),
184
- React.Children.map(b, c => c?.props["data-grid"])
185
- )
186
- );
187
- }
188
-
189
- /**
190
- * See `fastRGLPropsEqual.js`.
191
- * We want this to run as fast as possible - it is called often - and to be
192
- * resilient to new props that we add. So rather than call lodash.isEqual,
193
- * which isn't suited to comparing props very well, we use this specialized
194
- * function in conjunction with preval to generate the fastest possible comparison
195
- * function, tuned for exactly our props.
196
- */
197
- type FastRGLPropsEqual = (Object, Object, Function) => boolean;
198
- export const fastRGLPropsEqual: FastRGLPropsEqual = require("./fastRGLPropsEqual");
199
-
200
- // Like the above, but a lot simpler.
201
- export function fastPositionEqual(a: Position, b: Position): boolean {
202
- return (
203
- a.left === b.left &&
204
- a.top === b.top &&
205
- a.width === b.width &&
206
- a.height === b.height
207
- );
208
- }
209
-
210
- /**
211
- * Given two layoutitems, check if they collide.
212
- */
213
- export function collides(l1: LayoutItem, l2: LayoutItem): boolean {
214
- if (l1.i === l2.i) return false; // same element
215
- if (l1.x + l1.w <= l2.x) return false; // l1 is left of l2
216
- if (l1.x >= l2.x + l2.w) return false; // l1 is right of l2
217
- if (l1.y + l1.h <= l2.y) return false; // l1 is above l2
218
- if (l1.y >= l2.y + l2.h) return false; // l1 is below l2
219
- return true; // boxes overlap
220
- }
221
-
222
- /**
223
- * Given a layout, compact it. This involves going down each y coordinate and removing gaps
224
- * between items.
225
- *
226
- * Does not modify layout items (clones). Creates a new layout array.
227
- *
228
- * @param {Array} layout Layout.
229
- * @param {Boolean} verticalCompact Whether or not to compact the layout
230
- * vertically.
231
- * @param {Boolean} allowOverlap When `true`, allows overlapping grid items.
232
- * @return {Array} Compacted Layout.
233
- */
234
- export function compact(
235
- layout: Layout,
236
- compactType: CompactType,
237
- cols: number,
238
- allowOverlap: ?boolean
239
- ): Layout {
240
- // Statics go in the compareWith array right away so items flow around them.
241
- const compareWith = getStatics(layout);
242
- // We go through the items by row and column.
243
- const sorted = sortLayoutItems(layout, compactType);
244
- // Holding for new items.
245
- const out = Array(layout.length);
246
-
247
- for (let i = 0, len = sorted.length; i < len; i++) {
248
- let l = cloneLayoutItem(sorted[i]);
249
-
250
- // Don't move static elements
251
- if (!l.static) {
252
- l = compactItem(compareWith, l, compactType, cols, sorted, allowOverlap);
253
-
254
- // Add to comparison array. We only collide with items before this one.
255
- // Statics are already in this array.
256
- compareWith.push(l);
257
- }
258
-
259
- // Add to output array to make sure they still come out in the right order.
260
- out[layout.indexOf(sorted[i])] = l;
261
-
262
- // Clear moved flag, if it exists.
263
- l.moved = false;
264
- }
265
-
266
- return out;
267
- }
268
-
269
- const heightWidth = { x: "w", y: "h" };
270
- /**
271
- * Before moving item down, it will check if the movement will cause collisions and move those items down before.
272
- */
273
- function resolveCompactionCollision(
274
- layout: Layout,
275
- item: LayoutItem,
276
- moveToCoord: number,
277
- axis: "x" | "y"
278
- ) {
279
- const sizeProp = heightWidth[axis];
280
- item[axis] += 1;
281
- const itemIndex = layout
282
- .map(layoutItem => {
283
- return layoutItem.i;
284
- })
285
- .indexOf(item.i);
286
-
287
- // Go through each item we collide with.
288
- for (let i = itemIndex + 1; i < layout.length; i++) {
289
- const otherItem = layout[i];
290
- // Ignore static items
291
- if (otherItem.static) continue;
292
-
293
- // Optimization: we can break early if we know we're past this el
294
- // We can do this b/c it's a sorted layout
295
- if (otherItem.y > item.y + item.h) break;
296
-
297
- if (collides(item, otherItem)) {
298
- resolveCompactionCollision(
299
- layout,
300
- otherItem,
301
- moveToCoord + item[sizeProp],
302
- axis
303
- );
304
- }
305
- }
306
-
307
- item[axis] = moveToCoord;
308
- }
309
-
310
- /**
311
- * Compact an item in the layout.
312
- *
313
- * Modifies item.
314
- *
315
- */
316
- export function compactItem(
317
- compareWith: Layout,
318
- l: LayoutItem,
319
- compactType: CompactType,
320
- cols: number,
321
- fullLayout: Layout,
322
- allowOverlap: ?boolean
323
- ): LayoutItem {
324
- const compactV = compactType === "vertical";
325
- const compactH = compactType === "horizontal";
326
- if (compactV) {
327
- // Bottom 'y' possible is the bottom of the layout.
328
- // This allows you to do nice stuff like specify {y: Infinity}
329
- // This is here because the layout must be sorted in order to get the correct bottom `y`.
330
- l.y = Math.min(bottom(compareWith), l.y);
331
- // Move the element up as far as it can go without colliding.
332
- while (l.y > 0 && !getFirstCollision(compareWith, l)) {
333
- l.y--;
334
- }
335
- } else if (compactH) {
336
- // Move the element left as far as it can go without colliding.
337
- while (l.x > 0 && !getFirstCollision(compareWith, l)) {
338
- l.x--;
339
- }
340
- }
341
-
342
- // Move it down, and keep moving it down if it's colliding.
343
- let collides;
344
- // Checking the compactType null value to avoid breaking the layout when overlapping is allowed.
345
- while (
346
- (collides = getFirstCollision(compareWith, l)) &&
347
- !(compactType === null && allowOverlap)
348
- ) {
349
- if (compactH) {
350
- resolveCompactionCollision(fullLayout, l, collides.x + collides.w, "x");
351
- } else {
352
- resolveCompactionCollision(fullLayout, l, collides.y + collides.h, "y");
353
- }
354
- // Since we can't grow without bounds horizontally, if we've overflown, let's move it down and try again.
355
- if (compactH && l.x + l.w > cols) {
356
- l.x = cols - l.w;
357
- l.y++;
358
- // ALso move element as left as we can
359
- while (l.x > 0 && !getFirstCollision(compareWith, l)) {
360
- l.x--;
361
- }
362
- }
363
- }
364
-
365
- // Ensure that there are no negative positions
366
- l.y = Math.max(l.y, 0);
367
- l.x = Math.max(l.x, 0);
368
-
369
- return l;
370
- }
371
-
372
- /**
373
- * Given a layout, make sure all elements fit within its bounds.
374
- *
375
- * Modifies layout items.
376
- *
377
- * @param {Array} layout Layout array.
378
- * @param {Number} bounds Number of columns.
379
- */
380
- export function correctBounds(
381
- layout: Layout,
382
- bounds: { cols: number }
383
- ): Layout {
384
- const collidesWith = getStatics(layout);
385
- for (let i = 0, len = layout.length; i < len; i++) {
386
- const l = layout[i];
387
- // Overflows right
388
- if (l.x + l.w > bounds.cols) l.x = bounds.cols - l.w;
389
- // Overflows left
390
- if (l.x < 0) {
391
- l.x = 0;
392
- l.w = bounds.cols;
393
- }
394
- if (!l.static) collidesWith.push(l);
395
- else {
396
- // If this is static and collides with other statics, we must move it down.
397
- // We have to do something nicer than just letting them overlap.
398
- while (getFirstCollision(collidesWith, l)) {
399
- l.y++;
400
- }
401
- }
402
- }
403
- return layout;
404
- }
405
-
406
- /**
407
- * Get a layout item by ID. Used so we can override later on if necessary.
408
- *
409
- * @param {Array} layout Layout array.
410
- * @param {String} id ID
411
- * @return {LayoutItem} Item at ID.
412
- */
413
- export function getLayoutItem(layout: Layout, id: string): ?LayoutItem {
414
- for (let i = 0, len = layout.length; i < len; i++) {
415
- if (layout[i].i === id) return layout[i];
416
- }
417
- }
418
-
419
- /**
420
- * Returns the first item this layout collides with.
421
- * It doesn't appear to matter which order we approach this from, although
422
- * perhaps that is the wrong thing to do.
423
- *
424
- * @param {Object} layoutItem Layout item.
425
- * @return {Object|undefined} A colliding layout item, or undefined.
426
- */
427
- export function getFirstCollision(
428
- layout: Layout,
429
- layoutItem: LayoutItem
430
- ): ?LayoutItem {
431
- for (let i = 0, len = layout.length; i < len; i++) {
432
- if (collides(layout[i], layoutItem)) return layout[i];
433
- }
434
- }
435
-
436
- export function getAllCollisions(
437
- layout: Layout,
438
- layoutItem: LayoutItem
439
- ): Array<LayoutItem> {
440
- return layout.filter(l => collides(l, layoutItem));
441
- }
442
-
443
- /**
444
- * Get all static elements.
445
- * @param {Array} layout Array of layout objects.
446
- * @return {Array} Array of static layout items..
447
- */
448
- export function getStatics(layout: Layout): Array<LayoutItem> {
449
- return layout.filter(l => l.static);
450
- }
451
-
452
- /**
453
- * Move an element. Responsible for doing cascading movements of other elements.
454
- *
455
- * Modifies layout items.
456
- *
457
- * @param {Array} layout Full layout to modify.
458
- * @param {LayoutItem} l element to move.
459
- * @param {Number} [x] X position in grid units.
460
- * @param {Number} [y] Y position in grid units.
461
- */
462
- export function moveElement(
463
- layout: Layout,
464
- l: LayoutItem,
465
- x: ?number,
466
- y: ?number,
467
- isUserAction: ?boolean,
468
- preventCollision: ?boolean,
469
- compactType: CompactType,
470
- cols: number,
471
- allowOverlap: ?boolean
472
- ): Layout {
473
- // If this is static and not explicitly enabled as draggable,
474
- // no move is possible, so we can short-circuit this immediately.
475
- if (l.static && l.isDraggable !== true) return layout;
476
-
477
- // Short-circuit if nothing to do.
478
- if (l.y === y && l.x === x) return layout;
479
-
480
- log(
481
- `Moving element ${l.i} to [${String(x)},${String(y)}] from [${l.x},${l.y}]`
482
- );
483
- const oldX = l.x;
484
- const oldY = l.y;
485
-
486
- // This is quite a bit faster than extending the object
487
- if (typeof x === "number") l.x = x;
488
- if (typeof y === "number") l.y = y;
489
- l.moved = true;
490
-
491
- // If this collides with anything, move it.
492
- // When doing this comparison, we have to sort the items we compare with
493
- // to ensure, in the case of multiple collisions, that we're getting the
494
- // nearest collision.
495
- let sorted = sortLayoutItems(layout, compactType);
496
- const movingUp =
497
- compactType === "vertical" && typeof y === "number"
498
- ? oldY >= y
499
- : compactType === "horizontal" && typeof x === "number"
500
- ? oldX >= x
501
- : false;
502
- // $FlowIgnore acceptable modification of read-only array as it was recently cloned
503
- if (movingUp) sorted = sorted.reverse();
504
- const collisions = getAllCollisions(sorted, l);
505
- const hasCollisions = collisions.length > 0;
506
-
507
- // We may have collisions. We can short-circuit if we've turned off collisions or
508
- // allowed overlap.
509
- if (hasCollisions && allowOverlap) {
510
- // Easy, we don't need to resolve collisions. But we *did* change the layout,
511
- // so clone it on the way out.
512
- return cloneLayout(layout);
513
- } else if (hasCollisions && preventCollision) {
514
- // If we are preventing collision but not allowing overlap, we need to
515
- // revert the position of this element so it goes to where it came from, rather
516
- // than the user's desired location.
517
- log(`Collision prevented on ${l.i}, reverting.`);
518
- l.x = oldX;
519
- l.y = oldY;
520
- l.moved = false;
521
- return layout; // did not change so don't clone
522
- }
523
-
524
- // Move each item that collides away from this element.
525
- for (let i = 0, len = collisions.length; i < len; i++) {
526
- const collision = collisions[i];
527
- log(
528
- `Resolving collision between ${l.i} at [${l.x},${l.y}] and ${collision.i} at [${collision.x},${collision.y}]`
529
- );
530
-
531
- // Short circuit so we can't infinite loop
532
- if (collision.moved) continue;
533
-
534
- // Don't move static items - we have to move *this* element away
535
- if (collision.static) {
536
- layout = moveElementAwayFromCollision(
537
- layout,
538
- collision,
539
- l,
540
- isUserAction,
541
- compactType,
542
- cols
543
- );
544
- } else {
545
- layout = moveElementAwayFromCollision(
546
- layout,
547
- l,
548
- collision,
549
- isUserAction,
550
- compactType,
551
- cols
552
- );
553
- }
554
- }
555
-
556
- return layout;
557
- }
558
-
559
- /**
560
- * This is where the magic needs to happen - given a collision, move an element away from the collision.
561
- * We attempt to move it up if there's room, otherwise it goes below.
562
- *
563
- * @param {Array} layout Full layout to modify.
564
- * @param {LayoutItem} collidesWith Layout item we're colliding with.
565
- * @param {LayoutItem} itemToMove Layout item we're moving.
566
- */
567
- export function moveElementAwayFromCollision(
568
- layout: Layout,
569
- collidesWith: LayoutItem,
570
- itemToMove: LayoutItem,
571
- isUserAction: ?boolean,
572
- compactType: CompactType,
573
- cols: number
574
- ): Layout {
575
- const compactH = compactType === "horizontal";
576
- // Compact vertically if not set to horizontal
577
- const compactV = compactType === "vertical";
578
- const preventCollision = collidesWith.static; // we're already colliding (not for static items)
579
-
580
- // If there is enough space above the collision to put this element, move it there.
581
- // We only do this on the main collision as this can get funky in cascades and cause
582
- // unwanted swapping behavior.
583
- if (isUserAction) {
584
- // Reset isUserAction flag because we're not in the main collision anymore.
585
- isUserAction = false;
586
-
587
- // Make a mock item so we don't modify the item here, only modify in moveElement.
588
- const fakeItem: LayoutItem = {
589
- x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,
590
- y: compactV ? Math.max(collidesWith.y - itemToMove.h, 0) : itemToMove.y,
591
- w: itemToMove.w,
592
- h: itemToMove.h,
593
- i: "-1"
594
- };
595
-
596
- const firstCollision = getFirstCollision(layout, fakeItem);
597
- const collisionNorth =
598
- firstCollision && firstCollision.y + firstCollision.h > collidesWith.y;
599
- const collisionWest =
600
- firstCollision && collidesWith.x + collidesWith.w > firstCollision.x;
601
-
602
- // No collision? If so, we can go up there; otherwise, we'll end up moving down as normal
603
- if (!firstCollision) {
604
- log(
605
- `Doing reverse collision on ${itemToMove.i} up to [${fakeItem.x},${fakeItem.y}].`
606
- );
607
- return moveElement(
608
- layout,
609
- itemToMove,
610
- compactH ? fakeItem.x : undefined,
611
- compactV ? fakeItem.y : undefined,
612
- isUserAction,
613
- preventCollision,
614
- compactType,
615
- cols
616
- );
617
- } else if (collisionNorth && compactV) {
618
- return moveElement(
619
- layout,
620
- itemToMove,
621
- undefined,
622
- collidesWith.y + 1,
623
- isUserAction,
624
- preventCollision,
625
- compactType,
626
- cols
627
- );
628
- } else if (collisionNorth && compactType == null) {
629
- collidesWith.y = itemToMove.y;
630
- itemToMove.y = itemToMove.y + itemToMove.h;
631
-
632
- return layout;
633
- } else if (collisionWest && compactH) {
634
- return moveElement(
635
- layout,
636
- collidesWith,
637
- itemToMove.x,
638
- undefined,
639
- isUserAction,
640
- preventCollision,
641
- compactType,
642
- cols
643
- );
644
- }
645
- }
646
-
647
- const newX = compactH ? itemToMove.x + 1 : undefined;
648
- const newY = compactV ? itemToMove.y + 1 : undefined;
649
-
650
- if (newX == null && newY == null) {
651
- return layout;
652
- }
653
- return moveElement(
654
- layout,
655
- itemToMove,
656
- compactH ? itemToMove.x + 1 : undefined,
657
- compactV ? itemToMove.y + 1 : undefined,
658
- isUserAction,
659
- preventCollision,
660
- compactType,
661
- cols
662
- );
663
- }
664
-
665
- /**
666
- * Helper to convert a number to a percentage string.
667
- *
668
- * @param {Number} num Any number
669
- * @return {String} That number as a percentage.
670
- */
671
- export function perc(num: number): string {
672
- return num * 100 + "%";
673
- }
674
-
675
- /**
676
- * Helper functions to constrain dimensions of a GridItem
677
- */
678
- const constrainWidth = (
679
- left: number,
680
- currentWidth: number,
681
- newWidth: number,
682
- containerWidth: number
683
- ) => {
684
- return left + newWidth > containerWidth ? currentWidth : newWidth;
685
- };
686
-
687
- const constrainHeight = (
688
- top: number,
689
- currentHeight: number,
690
- newHeight: number
691
- ) => {
692
- return top < 0 ? currentHeight : newHeight;
693
- };
694
-
695
- const constrainLeft = (left: number) => Math.max(0, left);
696
-
697
- const constrainTop = (top: number) => Math.max(0, top);
698
-
699
- const resizeNorth = (currentSize, { left, height, width }, _containerWidth) => {
700
- const top = currentSize.top - (height - currentSize.height);
701
-
702
- return {
703
- left,
704
- width,
705
- height: constrainHeight(top, currentSize.height, height),
706
- top: constrainTop(top)
707
- };
708
- };
709
-
710
- const resizeEast = (
711
- currentSize,
712
- { top, left, height, width },
713
- containerWidth
714
- ) => ({
715
- top,
716
- height,
717
- width: constrainWidth(
718
- currentSize.left,
719
- currentSize.width,
720
- width,
721
- containerWidth
722
- ),
723
- left: constrainLeft(left)
724
- });
725
-
726
- const resizeWest = (currentSize, { top, height, width }, containerWidth) => {
727
- const left = currentSize.left - (width - currentSize.width);
728
-
729
- return {
730
- height,
731
- width:
732
- left < 0
733
- ? currentSize.width
734
- : constrainWidth(
735
- currentSize.left,
736
- currentSize.width,
737
- width,
738
- containerWidth
739
- ),
740
- top: constrainTop(top),
741
- left: constrainLeft(left)
742
- };
743
- };
744
-
745
- const resizeSouth = (
746
- currentSize,
747
- { top, left, height, width },
748
- containerWidth
749
- ) => ({
750
- width,
751
- left,
752
- height: constrainHeight(top, currentSize.height, height),
753
- top: constrainTop(top)
754
- });
755
-
756
- const resizeNorthEast = (...args) =>
757
- resizeNorth(args[0], resizeEast(...args), args[2]);
758
- const resizeNorthWest = (...args) =>
759
- resizeNorth(args[0], resizeWest(...args), args[2]);
760
- const resizeSouthEast = (...args) =>
761
- resizeSouth(args[0], resizeEast(...args), args[2]);
762
- const resizeSouthWest = (...args) =>
763
- resizeSouth(args[0], resizeWest(...args), args[2]);
764
-
765
- const ordinalResizeHandlerMap = {
766
- n: resizeNorth,
767
- ne: resizeNorthEast,
768
- e: resizeEast,
769
- se: resizeSouthEast,
770
- s: resizeSouth,
771
- sw: resizeSouthWest,
772
- w: resizeWest,
773
- nw: resizeNorthWest
774
- };
775
-
776
- /**
777
- * Helper for clamping width and position when resizing an item.
778
- */
779
- export function resizeItemInDirection(
780
- direction: ResizeHandleAxis,
781
- currentSize: Position,
782
- newSize: Position,
783
- containerWidth: number
784
- ): Position {
785
- const ordinalHandler = ordinalResizeHandlerMap[direction];
786
- // Shouldn't be possible given types; that said, don't fail hard
787
- if (!ordinalHandler) return newSize;
788
- return ordinalHandler(
789
- currentSize,
790
- { ...currentSize, ...newSize },
791
- containerWidth
792
- );
793
- }
794
-
795
- export function setTransform({ top, left, width, height }: Position): Object {
796
- // Replace unitless items with px
797
- const translate = `translate(${left}px,${top}px)`;
798
- return {
799
- transform: translate,
800
- WebkitTransform: translate,
801
- MozTransform: translate,
802
- msTransform: translate,
803
- OTransform: translate,
804
- width: `${width}px`,
805
- height: `${height}px`,
806
- position: "absolute"
807
- };
808
- }
809
-
810
- export function setTopLeft({ top, left, width, height }: Position): Object {
811
- return {
812
- top: `${top}px`,
813
- left: `${left}px`,
814
- width: `${width}px`,
815
- height: `${height}px`,
816
- position: "absolute"
817
- };
818
- }
819
-
820
- /**
821
- * Get layout items sorted from top left to right and down.
822
- *
823
- * @return {Array} Array of layout objects.
824
- * @return {Array} Layout, sorted static items first.
825
- */
826
- export function sortLayoutItems(
827
- layout: Layout,
828
- compactType: CompactType
829
- ): Layout {
830
- if (compactType === "horizontal") return sortLayoutItemsByColRow(layout);
831
- if (compactType === "vertical") return sortLayoutItemsByRowCol(layout);
832
- else return layout;
833
- }
834
-
835
- /**
836
- * Sort layout items by row ascending and column ascending.
837
- *
838
- * Does not modify Layout.
839
- */
840
- export function sortLayoutItemsByRowCol(layout: Layout): Layout {
841
- // Slice to clone array as sort modifies
842
- return layout.slice(0).sort(function (a, b) {
843
- if (a.y > b.y || (a.y === b.y && a.x > b.x)) {
844
- return 1;
845
- } else if (a.y === b.y && a.x === b.x) {
846
- // Without this, we can get different sort results in IE vs. Chrome/FF
847
- return 0;
848
- }
849
- return -1;
850
- });
851
- }
852
-
853
- /**
854
- * Sort layout items by column ascending then row ascending.
855
- *
856
- * Does not modify Layout.
857
- */
858
- export function sortLayoutItemsByColRow(layout: Layout): Layout {
859
- return layout.slice(0).sort(function (a, b) {
860
- if (a.x > b.x || (a.x === b.x && a.y > b.y)) {
861
- return 1;
862
- }
863
- return -1;
864
- });
865
- }
866
-
867
- /**
868
- * Generate a layout using the initialLayout and children as a template.
869
- * Missing entries will be added, extraneous ones will be truncated.
870
- *
871
- * Does not modify initialLayout.
872
- *
873
- * @param {Array} initialLayout Layout passed in through props.
874
- * @param {String} breakpoint Current responsive breakpoint.
875
- * @param {?String} compact Compaction option.
876
- * @return {Array} Working layout.
877
- */
878
- export function synchronizeLayoutWithChildren(
879
- initialLayout: Layout,
880
- children: ReactChildren,
881
- cols: number,
882
- compactType: CompactType,
883
- allowOverlap: ?boolean
884
- ): Layout {
885
- initialLayout = initialLayout || [];
886
-
887
- // Generate one layout item per child.
888
- const layout: LayoutItem[] = [];
889
- React.Children.forEach(children, (child: ReactElement<any>) => {
890
- // Child may not exist
891
- if (child?.key == null) return;
892
-
893
- const exists = getLayoutItem(initialLayout, String(child.key));
894
- const g = child.props["data-grid"];
895
- // Don't overwrite the layout item if it's already in the initial layout.
896
- // If it has a `data-grid` property, prefer that over what's in the layout.
897
- if (exists && g == null) {
898
- layout.push(cloneLayoutItem(exists));
899
- } else {
900
- // Hey, this item has a data-grid property, use it.
901
- if (g) {
902
- if (!isProduction) {
903
- validateLayout([g], "ReactGridLayout.children");
904
- }
905
- // FIXME clone not really necessary here
906
- layout.push(cloneLayoutItem({ ...g, i: child.key }));
907
- } else {
908
- // Nothing provided: ensure this is added to the bottom
909
- // FIXME clone not really necessary here
910
- layout.push(
911
- cloneLayoutItem({
912
- w: 1,
913
- h: 1,
914
- x: 0,
915
- y: bottom(layout),
916
- i: String(child.key)
917
- })
918
- );
919
- }
920
- }
921
- });
922
-
923
- // Correct the layout.
924
- const correctedLayout = correctBounds(layout, { cols: cols });
925
- return allowOverlap
926
- ? correctedLayout
927
- : compact(correctedLayout, compactType, cols);
928
- }
929
-
930
- /**
931
- * Validate a layout. Throws errors.
932
- *
933
- * @param {Array} layout Array of layout items.
934
- * @param {String} [contextName] Context name for errors.
935
- * @throw {Error} Validation error.
936
- */
937
- export function validateLayout(
938
- layout: Layout,
939
- contextName: string = "Layout"
940
- ): void {
941
- const subProps = ["x", "y", "w", "h"];
942
- if (!Array.isArray(layout))
943
- throw new Error(contextName + " must be an array!");
944
- for (let i = 0, len = layout.length; i < len; i++) {
945
- const item = layout[i];
946
- for (let j = 0; j < subProps.length; j++) {
947
- const key = subProps[j];
948
- const value = item[key];
949
- if (typeof value !== "number" || Number.isNaN(value)) {
950
- throw new Error(
951
- `ReactGridLayout: ${contextName}[${i}].${key} must be a number! Received: ${value} (${typeof value})`
952
- );
953
- }
954
- }
955
- if (typeof item.i !== "undefined" && typeof item.i !== "string") {
956
- throw new Error(
957
- `ReactGridLayout: ${contextName}[${i}].i must be a string! Received: ${
958
- item.i
959
- } (${typeof item.i})`
960
- );
961
- }
962
- }
963
- }
964
-
965
- // Legacy support for verticalCompact: false
966
- export function compactType(
967
- props: ?{ verticalCompact: boolean, compactType: CompactType }
968
- ): CompactType {
969
- const { verticalCompact, compactType } = props || {};
970
- return verticalCompact === false ? null : compactType;
971
- }
972
-
973
- function log(...args) {
974
- if (!DEBUG) return;
975
- // eslint-disable-next-line no-console
976
- console.log(...args);
977
- }
978
-
979
- export const noop = () => {};