Completely updated React, fixed #11, (hopefully)

This commit is contained in:
2018-03-04 19:11:49 -05:00
parent 6e0afd6e2a
commit 34e5f5139a
13674 changed files with 333464 additions and 473223 deletions

View File

@@ -1,36 +1,67 @@
// @flow
import isEqual from 'lodash.isequal';
import React from 'react';
import type {ChildrenArray as ReactChildrenArray, Element as ReactElement} from 'react';
import isEqual from "lodash.isequal";
import React from "react";
import type {
ChildrenArray as ReactChildrenArray,
Element as ReactElement
} from "react";
export type LayoutItem = {
w: number, h: number, x: number, y: number, i: string,
minW?: number, minH?: number, maxW?: number, maxH?: number,
moved?: boolean, static?: boolean,
isDraggable?: ?boolean, isResizable?: ?boolean
w: number,
h: number,
x: number,
y: number,
i: string,
minW?: number,
minH?: number,
maxW?: number,
maxH?: number,
moved?: boolean,
static?: boolean,
isDraggable?: ?boolean,
isResizable?: ?boolean
};
export type Layout = Array<LayoutItem>;
export type Position = {left: number, top: number, width: number, height: number};
export type Position = {
left: number,
top: number,
width: number,
height: number
};
export type ReactDraggableCallbackData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number
x: number,
y: number,
deltaX: number,
deltaY: number,
lastX: number,
lastY: number
};
export type PartialPosition = {left: number, top: number};
export type Size = {width: number, height: number};
export type GridDragEvent = {e: Event, node: HTMLElement, newPosition: PartialPosition};
export type GridResizeEvent = {e: Event, node: HTMLElement, size: Size};
export type PartialPosition = { left: number, top: number };
export type Size = { width: number, height: number };
export type GridDragEvent = {
e: Event,
node: HTMLElement,
newPosition: PartialPosition
};
export type GridResizeEvent = { e: Event, node: HTMLElement, size: Size };
type REl = ReactElement<any>;
export type ReactChildren = ReactChildrenArray<REl>;
// All callbacks are of the signature (layout, oldItem, newItem, placeholder, e).
export type EventCallback =
(Layout, oldItem: ?LayoutItem, newItem: ?LayoutItem, placeholder: ?LayoutItem, Event, ?HTMLElement) => void;
export type CompactType = ?('horizontal' | 'vertical');
export type EventCallback = (
Layout,
oldItem: ?LayoutItem,
newItem: ?LayoutItem,
placeholder: ?LayoutItem,
Event,
?HTMLElement
) => void;
export type CompactType = ?("horizontal" | "vertical");
const isProduction = process.env.NODE_ENV === 'production';
const isProduction = process.env.NODE_ENV === "production";
const DEBUG = false;
/**
* Return the bottom coordinate of the layout.
@@ -39,7 +70,8 @@ const isProduction = process.env.NODE_ENV === 'production';
* @return {Number} Bottom coordinate.
*/
export function bottom(layout: Layout): number {
let max = 0, bottomY;
let max = 0,
bottomY;
for (let i = 0, len = layout.length; i < len; i++) {
bottomY = layout[i].y + layout[i].h;
if (bottomY > max) max = bottomY;
@@ -58,11 +90,20 @@ export function cloneLayout(layout: Layout): Layout {
// Fast path to cloning, since this is monomorphic
export function cloneLayoutItem(layoutItem: LayoutItem): LayoutItem {
return {
w: layoutItem.w, h: layoutItem.h, x: layoutItem.x, y: layoutItem.y, i: layoutItem.i,
minW: layoutItem.minW, maxW: layoutItem.maxW, minH: layoutItem.minH, maxH: layoutItem.maxH,
moved: Boolean(layoutItem.moved), static: Boolean(layoutItem.static),
w: layoutItem.w,
h: layoutItem.h,
x: layoutItem.x,
y: layoutItem.y,
i: layoutItem.i,
minW: layoutItem.minW,
maxW: layoutItem.maxW,
minH: layoutItem.minH,
maxH: layoutItem.maxH,
moved: Boolean(layoutItem.moved),
static: Boolean(layoutItem.static),
// These can be null
isDraggable: layoutItem.isDraggable, isResizable: layoutItem.isResizable
isDraggable: layoutItem.isDraggable,
isResizable: layoutItem.isResizable
};
}
@@ -71,8 +112,10 @@ export function cloneLayoutItem(layoutItem: LayoutItem): LayoutItem {
* This will catch differences in keys, order, and length.
*/
export function childrenEqual(a: ReactChildren, b: ReactChildren): boolean {
// $FlowIgnore: Appears to think map calls back w/array
return isEqual(React.Children.map(a, (c) => c.key), React.Children.map(b, (c) => c.key));
return isEqual(
React.Children.map(a, c => c.key),
React.Children.map(b, c => c.key)
);
}
/**
@@ -96,7 +139,11 @@ export function collides(l1: LayoutItem, l2: LayoutItem): boolean {
* vertically.
* @return {Array} Compacted Layout.
*/
export function compact(layout: Layout, compactType: CompactType, cols: number): Layout {
export function compact(
layout: Layout,
compactType: CompactType,
cols: number
): Layout {
// Statics go in the compareWith array right away so items flow around them.
const compareWith = getStatics(layout);
// We go through the items by row and column.
@@ -109,7 +156,7 @@ export function compact(layout: Layout, compactType: CompactType, cols: number):
// Don't move static elements
if (!l.static) {
l = compactItem(compareWith, l, compactType, cols);
l = compactItem(compareWith, l, compactType, cols, sorted);
// Add to comparison array. We only collide with items before this one.
// Statics are already in this array.
@@ -126,12 +173,52 @@ export function compact(layout: Layout, compactType: CompactType, cols: number):
return out;
}
const heightWidth = { x: "w", y: "h" };
/**
* Before moving item down, it will check if the movement will cause collisions and move those items down before.
*/
function resolveCompactionCollision(
layout: Layout,
item: LayoutItem,
moveToCoord: number,
axis: "x" | "y"
) {
const sizeProp = heightWidth[axis];
item[axis] += 1;
const itemIndex = layout.indexOf(item);
// Go through each item we collide with.
for (let i = itemIndex + 1; i < layout.length; i++) {
const otherItem = layout[i];
// Ignore static items
if (otherItem.static) continue;
if (collides(item, otherItem)) {
resolveCompactionCollision(
layout,
otherItem,
moveToCoord + item[sizeProp],
axis
);
}
}
item[axis] = moveToCoord;
}
/**
* Compact an item in the layout.
*/
export function compactItem(compareWith: Layout, l: LayoutItem, compactType: CompactType, cols: number): LayoutItem {
const compactV = compactType === 'vertical';
const compactH = compactType === 'horizontal';
export function compactItem(
compareWith: Layout,
l: LayoutItem,
compactType: CompactType,
cols: number,
fullLayout: Layout
): LayoutItem {
const compactV = compactType === "vertical";
const compactH = compactType === "horizontal";
if (compactV) {
// Bottom 'y' possible is the bottom of the layout.
// This allows you to do nice stuff like specify {y: Infinity}
@@ -151,11 +238,11 @@ export function compactItem(compareWith: Layout, l: LayoutItem, compactType: Com
// Move it down, and keep moving it down if it's colliding.
let collides;
while((collides = getFirstCollision(compareWith, l))) {
while ((collides = getFirstCollision(compareWith, l))) {
if (compactH) {
l.x = collides.x + collides.w;
resolveCompactionCollision(fullLayout, l, collides.x + collides.w, "x");
} else {
l.y = collides.y + collides.h;
resolveCompactionCollision(fullLayout, l, collides.y + collides.h, "y");
}
// Since we can't grow without bounds horizontally, if we've overflown, let's move it down and try again.
if (compactH && l.x + l.w > cols) {
@@ -172,7 +259,10 @@ export function compactItem(compareWith: Layout, l: LayoutItem, compactType: Com
* @param {Array} layout Layout array.
* @param {Number} bounds Number of columns.
*/
export function correctBounds(layout: Layout, bounds: {cols: number}): Layout {
export function correctBounds(
layout: Layout,
bounds: { cols: number }
): Layout {
const collidesWith = getStatics(layout);
for (let i = 0, len = layout.length; i < len; i++) {
const l = layout[i];
@@ -187,7 +277,7 @@ export function correctBounds(layout: Layout, bounds: {cols: number}): Layout {
else {
// If this is static and collides with other statics, we must move it down.
// We have to do something nicer than just letting them overlap.
while(getFirstCollision(collidesWith, l)) {
while (getFirstCollision(collidesWith, l)) {
l.y++;
}
}
@@ -216,14 +306,20 @@ export function getLayoutItem(layout: Layout, id: string): ?LayoutItem {
* @param {Object} layoutItem Layout item.
* @return {Object|undefined} A colliding layout item, or undefined.
*/
export function getFirstCollision(layout: Layout, layoutItem: LayoutItem): ?LayoutItem {
export function getFirstCollision(
layout: Layout,
layoutItem: LayoutItem
): ?LayoutItem {
for (let i = 0, len = layout.length; i < len; i++) {
if (collides(layout[i], layoutItem)) return layout[i];
}
}
export function getAllCollisions(layout: Layout, layoutItem: LayoutItem): Array<LayoutItem> {
return layout.filter((l) => collides(l, layoutItem));
export function getAllCollisions(
layout: Layout,
layoutItem: LayoutItem
): Array<LayoutItem> {
return layout.filter(l => collides(l, layoutItem));
}
/**
@@ -232,7 +328,7 @@ export function getAllCollisions(layout: Layout, layoutItem: LayoutItem): Array<
* @return {Array} Array of static layout items..
*/
export function getStatics(layout: Layout): Array<LayoutItem> {
return layout.filter((l) => l.static);
return layout.filter(l => l.static);
}
/**
@@ -242,13 +338,19 @@ export function getStatics(layout: Layout): Array<LayoutItem> {
* @param {LayoutItem} l element to move.
* @param {Number} [x] X position in grid units.
* @param {Number} [y] Y position in grid units.
* @param {Boolean} [isUserAction] If true, designates that the item we're moving is
* being dragged/resized by the user.
*/
export function moveElement(layout: Layout, l: LayoutItem, x: ?number, y: ?number,
isUserAction: ?boolean, preventCollision: ?boolean,
compactType: CompactType, cols: number): Layout {
export function moveElement(
layout: Layout,
l: LayoutItem,
x: number,
y: number,
isUserAction: ?boolean,
preventCollision: ?boolean,
compactType: CompactType,
cols: number
): Layout {
if (l.static) return layout;
log(`Moving element ${l.i} to [${x},${y}] from [${l.x},${l.y}]`);
// Short-circuit if nothing to do.
if (l.y === y && l.x === x) return layout;
@@ -256,10 +358,9 @@ export function moveElement(layout: Layout, l: LayoutItem, x: ?number, y: ?numbe
const oldX = l.x;
const oldY = l.y;
const movingUp = y && l.y > y;
// This is quite a bit faster than extending the object
if (typeof x === 'number') l.x = x;
if (typeof y === 'number') l.y = y;
l.x = x;
l.y = y;
l.moved = true;
// If this collides with anything, move it.
@@ -267,11 +368,16 @@ export function moveElement(layout: Layout, l: LayoutItem, x: ?number, y: ?numbe
// to ensure, in the case of multiple collisions, that we're getting the
// nearest collision.
let sorted = sortLayoutItems(layout, compactType);
const movingUp =
compactType === "vertical"
? oldY >= y
: compactType === "horizontal" ? oldX >= x : false;
if (movingUp) sorted = sorted.reverse();
const collisions = getAllCollisions(sorted, l);
// There was a collision; abort
if (preventCollision && collisions.length) {
log(`Collision prevented on ${l.i}, reverting.`);
l.x = oldX;
l.y = oldY;
l.moved = false;
@@ -281,20 +387,34 @@ export function moveElement(layout: Layout, l: LayoutItem, x: ?number, y: ?numbe
// Move each item that collides away from this element.
for (let i = 0, len = collisions.length; i < len; i++) {
const collision = collisions[i];
// console.log('resolving collision between', l.i, 'at', l.y, 'and', collision.i, 'at', collision.y);
log(
`Resolving collision between ${l.i} at [${l.x},${l.y}] and ${
collision.i
} at [${collision.x},${collision.y}]`
);
// Short circuit so we can't infinite loop
if (collision.moved) continue;
// This makes it feel a bit more precise by waiting to swap for just a bit when moving up.
if (l.y > collision.y && l.y - collision.y > collision.h / 4) continue;
if (l.x > collision.x && l.x - collision.x > collision.w / 4) continue;
// Don't move static items - we have to move *this* element away
if (collision.static) {
layout = moveElementAwayFromCollision(layout, collision, l, isUserAction, compactType, cols);
layout = moveElementAwayFromCollision(
layout,
collision,
l,
isUserAction,
compactType,
cols
);
} else {
layout = moveElementAwayFromCollision(layout, l, collision, isUserAction, compactType, cols);
layout = moveElementAwayFromCollision(
layout,
l,
collision,
isUserAction,
compactType,
cols
);
}
}
@@ -308,34 +428,47 @@ export function moveElement(layout: Layout, l: LayoutItem, x: ?number, y: ?numbe
* @param {Array} layout Full layout to modify.
* @param {LayoutItem} collidesWith Layout item we're colliding with.
* @param {LayoutItem} itemToMove Layout item we're moving.
* @param {Boolean} [isUserAction] If true, designates that the item we're moving is being dragged/resized
* by the user.
*/
export function moveElementAwayFromCollision(layout: Layout, collidesWith: LayoutItem, itemToMove: LayoutItem,
isUserAction: ?boolean, compactType: CompactType, cols: number): Layout {
const compactH = compactType === 'horizontal';
const compactV = compactType === 'vertical';
export function moveElementAwayFromCollision(
layout: Layout,
collidesWith: LayoutItem,
itemToMove: LayoutItem,
isUserAction: ?boolean,
compactType: CompactType,
cols: number
): Layout {
const compactH = compactType === "horizontal";
const compactV = compactType === "vertical";
const preventCollision = false; // we're already colliding
// If there is enough space above the collision to put this element, move it there.
// We only do this on the main collision as this can get funky in cascades and cause
// unwanted swapping behavior.
if (isUserAction) {
// Reset isUserAction flag because we're not in the main collision anymore.
isUserAction = false;
// Make a mock item so we don't modify the item here, only modify in moveElement.
const fakeItem: LayoutItem = {
x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,
x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,
y: !compactH ? Math.max(collidesWith.y - itemToMove.h, 0) : itemToMove.y,
w: itemToMove.w,
h: itemToMove.h,
i: '-1'
i: "-1"
};
// No collision? If so, we can go up there; otherwise, we'll end up moving down as normal
if (!getFirstCollision(layout, fakeItem)) {
log(
`Doing reverse collision on ${itemToMove.i} up to [${fakeItem.x},${
fakeItem.y
}].`
);
return moveElement(
layout,
itemToMove,
compactH ? fakeItem.x : undefined,
compactV ? fakeItem.y + 1 : undefined,
fakeItem.x,
fakeItem.y,
isUserAction,
preventCollision,
compactType,
@@ -344,13 +477,11 @@ export function moveElementAwayFromCollision(layout: Layout, collidesWith: Layou
}
}
// Previously this was optimized to move below the collision directly, but this can cause problems
// with cascading moves, as an item may actually leapflog a collision and cause a reversal in order.
return moveElement(
layout,
itemToMove,
compactH ? itemToMove.x + 1 : undefined,
compactV ? itemToMove.y + 1 : undefined,
compactH ? collidesWith.x + collidesWith.w : itemToMove.x,
compactV ? collidesWith.y + collidesWith.h : itemToMove.y,
isUserAction,
preventCollision,
compactType,
@@ -365,10 +496,10 @@ export function moveElementAwayFromCollision(layout: Layout, collidesWith: Layou
* @return {String} That number as a percentage.
*/
export function perc(num: number): string {
return num * 100 + '%';
return num * 100 + "%";
}
export function setTransform({top, left, width, height}: Position): Object {
export function setTransform({ top, left, width, height }: Position): Object {
// Replace unitless items with px
const translate = `translate(${left}px,${top}px)`;
return {
@@ -379,17 +510,17 @@ export function setTransform({top, left, width, height}: Position): Object {
OTransform: translate,
width: `${width}px`,
height: `${height}px`,
position: 'absolute'
position: "absolute"
};
}
export function setTopLeft({top, left, width, height}: Position): Object {
export function setTopLeft({ top, left, width, height }: Position): Object {
return {
top: `${top}px`,
left: `${left}px`,
width: `${width}px`,
height: `${height}px`,
position: 'absolute'
position: "absolute"
};
}
@@ -399,8 +530,11 @@ export function setTopLeft({top, left, width, height}: Position): Object {
* @return {Array} Array of layout objects.
* @return {Array} Layout, sorted static items first.
*/
export function sortLayoutItems(layout: Layout, compactType: CompactType): Layout {
if (compactType === 'horizontal') return sortLayoutItemsByColRow(layout);
export function sortLayoutItems(
layout: Layout,
compactType: CompactType
): Layout {
if (compactType === "horizontal") return sortLayoutItemsByColRow(layout);
else return sortLayoutItemsByRowCol(layout);
}
@@ -434,8 +568,12 @@ export function sortLayoutItemsByColRow(layout: Layout): Layout {
* @param {?String} compact Compaction option.
* @return {Array} Working layout.
*/
export function synchronizeLayoutWithChildren(initialLayout: Layout, children: ReactChildren,
cols: number, compactType: CompactType): Layout {
export function synchronizeLayoutWithChildren(
initialLayout: Layout,
children: ReactChildren,
cols: number,
compactType: CompactType
): Layout {
initialLayout = initialLayout || [];
// Generate one layout item per child.
@@ -447,26 +585,34 @@ export function synchronizeLayoutWithChildren(initialLayout: Layout, children: R
layout[i] = cloneLayoutItem(exists);
} else {
if (!isProduction && child.props._grid) {
console.warn('`_grid` properties on children have been deprecated as of React 15.2. ' + // eslint-disable-line
'Please use `data-grid` or add your properties directly to the `layout`.');
console.warn(
"`_grid` properties on children have been deprecated as of React 15.2. " + // eslint-disable-line
"Please use `data-grid` or add your properties directly to the `layout`."
);
}
const g = child.props['data-grid'] || child.props._grid;
const g = child.props["data-grid"] || child.props._grid;
// Hey, this item has a data-grid property, use it.
if (g) {
if (!isProduction) {
validateLayout([g], 'ReactGridLayout.children');
validateLayout([g], "ReactGridLayout.children");
}
layout[i] = cloneLayoutItem({...g, i: child.key});
layout[i] = cloneLayoutItem({ ...g, i: child.key });
} else {
// Nothing provided: ensure this is added to the bottom
layout[i] = cloneLayoutItem({w: 1, h: 1, x: 0, y: bottom(layout), i: String(child.key)});
layout[i] = cloneLayoutItem({
w: 1,
h: 1,
x: 0,
y: bottom(layout),
i: String(child.key)
});
}
}
});
// Correct the layout.
layout = correctBounds(layout, {cols: cols});
layout = correctBounds(layout, { cols: cols });
layout = compact(layout, compactType, cols);
return layout;
@@ -479,27 +625,54 @@ export function synchronizeLayoutWithChildren(initialLayout: Layout, children: R
* @param {String} [contextName] Context name for errors.
* @throw {Error} Validation error.
*/
export function validateLayout(layout: Layout, contextName: string): void {
contextName = contextName || "Layout";
const subProps = ['x', 'y', 'w', 'h'];
if (!Array.isArray(layout)) throw new Error(contextName + " must be an array!");
export function validateLayout(
layout: Layout,
contextName: string = "Layout"
): void {
const subProps = ["x", "y", "w", "h"];
if (!Array.isArray(layout))
throw new Error(contextName + " must be an array!");
for (let i = 0, len = layout.length; i < len; i++) {
const item = layout[i];
for (let j = 0; j < subProps.length; j++) {
if (typeof item[subProps[j]] !== 'number') {
throw new Error('ReactGridLayout: ' + contextName + '[' + i + '].' + subProps[j] + ' must be a number!');
if (typeof item[subProps[j]] !== "number") {
throw new Error(
"ReactGridLayout: " +
contextName +
"[" +
i +
"]." +
subProps[j] +
" must be a number!"
);
}
}
if (item.i && typeof item.i !== 'string') {
throw new Error('ReactGridLayout: ' + contextName + '[' + i + '].i must be a string!');
if (item.i && typeof item.i !== "string") {
throw new Error(
"ReactGridLayout: " + contextName + "[" + i + "].i must be a string!"
);
}
if (item.static !== undefined && typeof item.static !== 'boolean') {
throw new Error('ReactGridLayout: ' + contextName + '[' + i + '].static must be a boolean!');
if (item.static !== undefined && typeof item.static !== "boolean") {
throw new Error(
"ReactGridLayout: " +
contextName +
"[" +
i +
"].static must be a boolean!"
);
}
}
}
// Flow can't really figure this out, so we just use Object
export function autoBindHandlers(el: Object, fns: Array<string>): void {
fns.forEach((key) => el[key] = el[key].bind(el));
fns.forEach(key => (el[key] = el[key].bind(el)));
}
function log(...args) {
if (!DEBUG) return;
// eslint-disable-next-line no-console
console.log(...args);
}
export const noop = () => {};