refactor(store): use redux instead of easy-peasy

This commit is contained in:
moklick
2021-01-19 13:58:24 +01:00
parent 11f385c4b8
commit e9a7ade236
18 changed files with 10527 additions and 441 deletions
+375 -375
View File
@@ -1,19 +1,17 @@
import { createStore, Action, action, Thunk, thunk, computed, Computed } from 'easy-peasy';
import isEqual from 'fast-deep-equal';
import { Selection as D3Selection, ZoomBehavior } from 'd3';
import { getDimensions } from '../utils';
import { getNodesInside, getConnectedEdges, getRectOfNodes, isNode, isEdge, parseElement } from '../utils/graph';
import { getHandleBounds } from '../components/Nodes/utils';
import configureStore from './configure-store';
import {
ElementId,
Elements,
Transform,
Node,
Edge,
Rect,
Dimensions,
XYPosition,
OnConnectFunc,
OnConnectStartFunc,
@@ -21,39 +19,57 @@ import {
OnConnectEndFunc,
SelectionRect,
HandleType,
SetConnectionId,
NodePosUpdate,
NodeDiffUpdate,
TranslateExtent,
SnapGrid,
ConnectionMode,
FlowElement,
} from '../types';
type NodeDimensionUpdate = {
id: ElementId;
nodeElement: HTMLDivElement;
};
import {
ActionTypes,
ADD_SELECTED_ELEMENTS,
BATCH_UPDATE_NODE_DIMENSIONS,
INIT_D3ZOOM,
RESET_SELECTED_ELEMENTS,
SET_CONNECTION_MODE,
SET_CONNECTION_NODEID,
SET_CONNECTION_POSITION,
SET_ELEMENTS,
SET_ELEMENTS_SELECTABLE,
SET_INTERACTIVE,
SET_MAXZOOM,
SET_MINZOOM,
SET_MULTI_SELECTION_ACTIVE,
SET_NODES_CONNECTABLE,
SET_NODES_DRAGGABLE,
SET_ON_CONNECT,
SET_ON_CONNECT_END,
SET_ON_CONNECT_START,
SET_ON_CONNECT_STOP,
SET_SELECTED_ELEMENTS,
SET_SNAPGRID,
SET_SNAPTOGRID,
SET_TRANSLATEEXTENT,
SET_USER_SELECTION,
UNSET_USER_SELECTION,
UPDATE_NODE_DIMENSIONS,
UPDATE_NODE_POS,
UPDATE_NODE_POS_DIFF,
UPDATE_SIZE,
UPDATE_TRANSFORM,
UPDATE_USER_SELECTION,
} from './action-types';
type NodeDimensionUpdates = {
updates: NodeDimensionUpdate[];
};
type InitD3Zoom = {
d3Zoom: ZoomBehavior<Element, unknown>;
d3Selection: D3Selection<Element, unknown, null, undefined>;
d3ZoomHandler: ((this: Element, event: any, d: unknown) => void) | undefined;
transform: Transform;
};
export interface StoreModel {
export interface ReactFlowState {
width: number;
height: number;
transform: Transform;
elements: Elements;
nodes: Computed<StoreModel, Node[]>;
edges: Computed<StoreModel, Edge[]>;
// nodes: Computed<StoreModel, Node[]>;
// edges: Computed<StoreModel, Edge[]>;
selectedElements: Elements | null;
selectedNodesBbox: Rect;
viewportBox: Computed<StoreModel, Rect>;
// viewportBox: Computed<StoreModel, Rect>;
d3Zoom: ZoomBehavior<Element, unknown> | null;
d3Selection: D3Selection<Element, unknown, null, undefined> | null;
@@ -88,70 +104,18 @@ export interface StoreModel {
onConnectStart?: OnConnectStartFunc;
onConnectStop?: OnConnectStopFunc;
onConnectEnd?: OnConnectEndFunc;
setOnConnect: Action<StoreModel, OnConnectFunc>;
setOnConnectStart: Action<StoreModel, OnConnectStartFunc>;
setOnConnectStop: Action<StoreModel, OnConnectStopFunc>;
setOnConnectEnd: Action<StoreModel, OnConnectEndFunc>;
setElements: Action<StoreModel, Elements>;
batchUpdateNodeDimensions: Action<StoreModel, NodeDimensionUpdates>;
updateNodeDimensions: Action<StoreModel, NodeDimensionUpdate>;
updateNodePos: Action<StoreModel, NodePosUpdate>;
updateNodePosDiff: Action<StoreModel, NodeDiffUpdate>;
setSelection: Action<StoreModel, boolean>;
unsetNodesSelection: Action<StoreModel>;
resetSelectedElements: Action<StoreModel>;
setSelectedElements: Action<StoreModel, Elements | Node | Edge>;
addSelectedElements: Thunk<StoreModel, Elements | Node | Edge>;
updateTransform: Action<StoreModel, Transform>;
updateSize: Action<StoreModel, Dimensions>;
initD3Zoom: Action<StoreModel, InitD3Zoom>;
setMinZoom: Action<StoreModel, number>;
setMaxZoom: Action<StoreModel, number>;
setTranslateExtent: Action<StoreModel, TranslateExtent>;
setSnapToGrid: Action<StoreModel, boolean>;
setSnapGrid: Action<StoreModel, SnapGrid>;
setConnectionPosition: Action<StoreModel, XYPosition>;
setConnectionNodeId: Action<StoreModel, SetConnectionId>;
setInteractive: Action<StoreModel, boolean>;
setNodesDraggable: Action<StoreModel, boolean>;
setNodesConnectable: Action<StoreModel, boolean>;
setElementsSelectable: Action<StoreModel, boolean>;
setUserSelection: Action<StoreModel, XYPosition>;
updateUserSelection: Action<StoreModel, XYPosition>;
unsetUserSelection: Action<StoreModel>;
setMultiSelectionActive: Action<StoreModel, boolean>;
setConnectionMode: Action<StoreModel, ConnectionMode>;
}
export const storeModel: StoreModel = {
export const initialState: ReactFlowState = {
width: 0,
height: 0,
transform: [0, 0, 1],
elements: [],
nodes: computed((state) => state.elements.filter(isNode)),
edges: computed((state) => state.elements.filter(isEdge)),
// nodes: computed((state) => state.elements.filter(isNode)),
// edges: computed((state) => state.elements.filter(isEdge)),
selectedElements: null,
selectedNodesBbox: { x: 0, y: 0, width: 0, height: 0 },
viewportBox: computed((state) => ({ x: 0, y: 0, width: state.width, height: state.height })),
// viewportBox: computed((state) => ({ x: 0, y: 0, width: state.width, height: state.height })),
d3Zoom: null,
d3Selection: null,
@@ -191,327 +155,363 @@ export const storeModel: StoreModel = {
multiSelectionActive: false,
reactFlowVersion: typeof __REACT_FLOW_VERSION__ !== 'undefined' ? __REACT_FLOW_VERSION__ : '-',
};
setOnConnect: action((state, onConnect) => {
state.onConnect = onConnect;
}),
setOnConnectStart: action((state, onConnectStart) => {
state.onConnectStart = onConnectStart;
}),
setOnConnectStop: action((state, onConnectStop) => {
state.onConnectStop = onConnectStop;
}),
setOnConnectEnd: action((state, onConnectEnd) => {
state.onConnectEnd = onConnectEnd;
}),
export function reactFlowReducer(state = initialState, action: ActionTypes): ReactFlowState {
switch (action.type) {
case SET_ELEMENTS: {
const propElements = action.elements;
setElements: action((state, propElements) => {
// remove deleted elements
for (let i = 0; i < state.elements.length; i++) {
const se = state.elements[i];
const elementExistsInProps = propElements.find((pe) => pe.id === se.id);
const nextElements = propElements.map((el: FlowElement) => {
let storeElement = state.elements.find((se) => se.id === el.id);
if (!elementExistsInProps) {
state.elements.splice(i, 1);
i--;
}
}
// update existing element
if (storeElement) {
if (isNode(storeElement)) {
const propNode = el as Node;
const positionChanged =
storeElement.position.x !== propNode.position.x || storeElement.position.y !== propNode.position.y;
const typeChanged = typeof propNode.type !== 'undefined' && propNode.type !== storeElement.type;
propElements.forEach((el) => {
const storeElementIndex = state.elements.findIndex((se) => se.id === el.id);
storeElement = {
...storeElement,
...propNode,
};
// update existing element
if (storeElementIndex !== -1) {
const storeElement = state.elements[storeElementIndex];
if (positionChanged) {
(storeElement as Node).__rf.position = propNode.position;
}
if (isNode(storeElement)) {
const propNode = el as Node;
const positionChanged =
storeElement.position.x !== propNode.position.x || storeElement.position.y !== propNode.position.y;
const typeChanged = typeof propNode.type !== 'undefined' && propNode.type !== storeElement.type;
state.elements[storeElementIndex] = {
...storeElement,
...propNode,
};
if (positionChanged) {
(state.elements[storeElementIndex] as Node).__rf.position = propNode.position;
if (typeChanged) {
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
(storeElement as Node).__rf.width = null;
}
} else {
storeElement = {
...storeElement,
...el,
};
}
if (typeChanged) {
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
// When the type of a node changes it is possible that the number or positions of handles changes too.
(state.elements[storeElementIndex] as Node).__rf.width = null;
}
return storeElement;
} else {
state.elements[storeElementIndex] = {
...storeElement,
// add new element
return parseElement(el);
}
});
return { ...state, elements: nextElements };
}
case BATCH_UPDATE_NODE_DIMENSIONS: {
const updatedElements = state.elements.map((el) => {
const update = action.updates.find((u) => u.id === el.id);
if (update) {
const dimensions = getDimensions(update.nodeElement);
const nodeToUpdate = el as Node;
if (
dimensions.width &&
dimensions.height &&
(nodeToUpdate.__rf.width !== dimensions.width || nodeToUpdate.__rf.height !== dimensions.height)
) {
const handleBounds = getHandleBounds(update.nodeElement, state.transform[2]);
return {
...nodeToUpdate,
__rf: {
...nodeToUpdate.__rf,
...dimensions,
handleBounds,
},
};
}
}
return el;
});
return {
...state,
elements: updatedElements,
};
}
case UPDATE_NODE_DIMENSIONS: {
const { nodeElement, id } = action.payload;
const dimensions = getDimensions(nodeElement);
if (!dimensions.width || !dimensions.height) {
return state;
}
const nextElements = state.elements.map((el) => {
if (el.id === id && isNode(el)) {
const handleBounds = getHandleBounds(nodeElement, state.transform[2]);
return {
...el,
__rf: {
...el.__rf,
width: dimensions.width,
height: dimensions.height,
handleBounds,
},
};
}
} else {
// add new element
state.elements.push(parseElement(el));
}
});
}),
batchUpdateNodeDimensions: action((state, { updates }) => {
updates.forEach((update) => {
const dimensions = getDimensions(update.nodeElement);
const matchingIndex = state.elements.findIndex((n) => n.id === update.id);
const matchingNode = state.elements[matchingIndex] as Node;
return el;
});
if (
matchingIndex !== -1 &&
dimensions.width &&
dimensions.height &&
(matchingNode.__rf.width !== dimensions.width || matchingNode.__rf.height !== dimensions.height)
) {
const handleBounds = getHandleBounds(update.nodeElement, state.transform[2]);
(state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
(state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
(state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
}
});
}),
updateNodeDimensions: action((state, { id, nodeElement }) => {
const dimensions = getDimensions(nodeElement);
const matchingIndex = state.elements.findIndex((n) => n.id === id);
if (matchingIndex !== -1 && dimensions.width && dimensions.height) {
const handleBounds = getHandleBounds(nodeElement, state.transform[2]);
(state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
(state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
(state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
return { ...state, elements: nextElements };
}
}),
case UPDATE_NODE_POS: {
const { id, pos } = action.payload;
updateNodePos: action((state, { id, pos }) => {
let position: XYPosition = pos;
let position: XYPosition = pos;
if (state.snapToGrid) {
const [gridSizeX, gridSizeY] = state.snapGrid;
position = {
x: gridSizeX * Math.round(pos.x / gridSizeX),
y: gridSizeY * Math.round(pos.y / gridSizeY),
if (state.snapToGrid) {
const [gridSizeX, gridSizeY] = state.snapGrid;
position = {
x: gridSizeX * Math.round(pos.x / gridSizeX),
y: gridSizeY * Math.round(pos.y / gridSizeY),
};
}
const nextElements = state.elements.map((el) => {
if (el.id === id && isNode(el)) {
return {
...el,
__rf: {
...el.__rf,
position,
},
};
}
return el;
});
return { ...state, elements: nextElements };
}
case UPDATE_NODE_POS_DIFF: {
const { id, diff, isDragging } = action.payload;
const nextElements = state.elements.map((el) => {
if (isNode(el) && (id === el.id || state.selectedElements?.find((sNode) => sNode.id === el.id))) {
if (diff) {
return {
...el,
__rf: {
...el.__rf,
isDragging,
position: {
x: el.__rf.position.x + diff.x,
y: el.__rf.position.x + diff.y,
},
},
};
}
return {
...el,
__rf: {
...el.__rf,
isDragging,
},
};
}
return el;
});
return { ...state, elements: nextElements };
}
case SET_USER_SELECTION: {
const { mousePos } = action;
const userSelectionRect = {
width: 0,
height: 0,
startX: mousePos.x,
startY: mousePos.y,
x: mousePos.x,
y: mousePos.y,
draw: true,
};
return {
...state,
userSelectionRect,
selectionActive: true,
};
}
case UPDATE_USER_SELECTION: {
const { mousePos } = action;
const startX = state.userSelectionRect.startX || 0;
const startY = state.userSelectionRect.startY || 0;
const negativeX = mousePos.x < startX;
const negativeY = mousePos.y < startY;
const nextUserSelectRect = {
...state.userSelectionRect,
x: negativeX ? mousePos.x : state.userSelectionRect.x,
y: negativeY ? mousePos.y : state.userSelectionRect.y,
width: Math.abs(mousePos.x - startX),
height: Math.abs(mousePos.y - startY),
};
const nodes = state.elements.filter(isNode);
const edges = state.elements.filter(isEdge);
const selectedNodes = getNodesInside(nodes, nextUserSelectRect, state.transform);
const selectedEdges = getConnectedEdges(selectedNodes, edges);
const nextSelectedElements = [...selectedNodes, ...selectedEdges];
const selectedElementsUpdated = !isEqual(nextSelectedElements, state.selectedElements);
if (selectedElementsUpdated) {
return {
...state,
selectedElements: nextSelectedElements.length > 0 ? nextSelectedElements : null,
userSelectionRect: nextUserSelectRect,
};
}
return {
...state,
userSelectionRect: nextUserSelectRect,
};
}
case UNSET_USER_SELECTION: {
const selectedNodes = state.selectedElements?.filter((node) => isNode(node) && node.__rf) as Node[];
const selectionActive = false;
const userSelectionRect = {
...state.userSelectionRect,
draw: false,
};
if (!selectedNodes || selectedNodes.length === 0) {
return {
...state,
selectionActive,
userSelectionRect,
selectedElements: null,
nodesSelectionActive: false,
};
}
const selectedNodesBbox = getRectOfNodes(selectedNodes);
return {
...state,
selectionActive,
userSelectionRect,
selectedNodesBbox,
nodesSelectionActive: true,
};
}
case SET_SELECTED_ELEMENTS: {
const { elements } = action;
const selectedElementsArr = Array.isArray(elements) ? elements : [elements];
const selectedElementsUpdated = !isEqual(selectedElementsArr, state.selectedElements);
const selectedElements = selectedElementsUpdated ? selectedElementsArr : state.selectedElements;
return {
...state,
selectedElements,
};
}
case ADD_SELECTED_ELEMENTS: {
const { multiSelectionActive, selectedElements } = state;
const { elements } = action;
const selectedElementsArr = Array.isArray(elements) ? elements : [elements];
let nextElements = selectedElementsArr;
if (multiSelectionActive) {
nextElements = selectedElements ? [...selectedElements, ...selectedElementsArr] : selectedElementsArr;
}
const selectedElementsUpdated = !isEqual(nextElements, state.selectedElements);
const nextSelectedElements = selectedElementsUpdated ? nextElements : state.selectedElements;
return { ...state, selectedElements: nextSelectedElements };
}
case INIT_D3ZOOM: {
const { d3Zoom, d3Selection, d3ZoomHandler, transform } = action.payload;
return {
...state,
d3Zoom,
d3Selection,
d3ZoomHandler,
transform,
};
}
case SET_MINZOOM: {
const { minZoom } = action.payload;
if (state.d3Zoom) {
state.d3Zoom.scaleExtent([minZoom, state.maxZoom]);
}
return {
...state,
minZoom,
};
}
state.elements.forEach((n) => {
if (n.id === id && isNode(n)) {
n.__rf.position = position;
case SET_MAXZOOM: {
const { maxZoom } = action.payload;
if (state.d3Zoom) {
state.d3Zoom.scaleExtent([state.minZoom, maxZoom]);
}
});
}),
updateNodePosDiff: action((state, { id = null, diff = null, isDragging = true }) => {
state.elements.forEach((n) => {
if (isNode(n) && (id === n.id || state.selectedElements?.find((sNode) => sNode.id === n.id))) {
if (diff) {
n.__rf.position = {
x: n.__rf.position.x + diff.x,
y: n.__rf.position.y + diff.y,
};
}
n.__rf.isDragging = isDragging;
return {
...state,
maxZoom,
};
}
case SET_TRANSLATEEXTENT: {
const { translateExtent } = action.payload;
if (state.d3Zoom) {
state.d3Zoom.translateExtent(translateExtent);
}
});
}),
setUserSelection: action((state, mousePos) => {
state.userSelectionRect = {
width: 0,
height: 0,
startX: mousePos.x,
startY: mousePos.y,
x: mousePos.x,
y: mousePos.y,
draw: true,
};
state.selectionActive = true;
}),
updateUserSelection: action((state, mousePos) => {
const startX = state.userSelectionRect.startX || 0;
const startY = state.userSelectionRect.startY || 0;
const negativeX = mousePos.x < startX;
const negativeY = mousePos.y < startY;
const nextRect = {
...state.userSelectionRect,
x: negativeX ? mousePos.x : state.userSelectionRect.x,
y: negativeY ? mousePos.y : state.userSelectionRect.y,
width: Math.abs(mousePos.x - startX),
height: Math.abs(mousePos.y - startY),
};
const selectedNodes = getNodesInside(state.nodes, nextRect, state.transform);
const selectedEdges = getConnectedEdges(selectedNodes, state.edges);
const nextSelectedElements = [...selectedNodes, ...selectedEdges];
const selectedElementsUpdated = !isEqual(nextSelectedElements, state.selectedElements);
state.userSelectionRect = nextRect;
if (selectedElementsUpdated) {
state.selectedElements = nextSelectedElements.length > 0 ? nextSelectedElements : null;
return {
...state,
translateExtent,
};
}
}),
case SET_ON_CONNECT:
case SET_ON_CONNECT_START:
case SET_ON_CONNECT_STOP:
case SET_ON_CONNECT_END:
case RESET_SELECTED_ELEMENTS:
case UPDATE_TRANSFORM:
case UPDATE_SIZE:
case SET_CONNECTION_POSITION:
case SET_CONNECTION_NODEID:
case SET_SNAPTOGRID:
case SET_SNAPGRID:
case SET_INTERACTIVE:
case SET_NODES_DRAGGABLE:
case SET_NODES_CONNECTABLE:
case SET_ELEMENTS_SELECTABLE:
case SET_MULTI_SELECTION_ACTIVE:
case SET_CONNECTION_MODE:
return { ...state, ...action.payload };
default:
return state;
}
}
unsetUserSelection: action((state) => {
const selectedNodes = state.selectedElements?.filter((node) => isNode(node) && node.__rf) as Node[];
const store = configureStore(initialState);
if (!selectedNodes || selectedNodes.length === 0) {
state.selectionActive = false;
state.userSelectionRect.draw = false;
state.nodesSelectionActive = false;
state.selectedElements = null;
return;
}
const selectedNodesBbox = getRectOfNodes(selectedNodes);
state.nodesSelectionActive = true;
state.selectedNodesBbox = selectedNodesBbox;
state.userSelectionRect.draw = false;
state.selectionActive = false;
}),
setSelection: action((state, isActive) => {
state.selectionActive = isActive;
}),
unsetNodesSelection: action((state) => {
state.nodesSelectionActive = false;
}),
resetSelectedElements: action((state) => {
state.selectedElements = null;
}),
setSelectedElements: action((state, elements) => {
const selectedElementsArr = Array.isArray(elements) ? elements : [elements];
const selectedElementsUpdated = !isEqual(selectedElementsArr, state.selectedElements);
const selectedElements = selectedElementsUpdated ? selectedElementsArr : state.selectedElements;
state.selectedElements = selectedElements;
}),
addSelectedElements: thunk((actions, elements, helpers) => {
const { multiSelectionActive, selectedElements } = helpers.getState();
const selectedElementsArr = Array.isArray(elements) ? elements : [elements];
if (multiSelectionActive) {
const nextElements = selectedElements ? [...selectedElements, ...selectedElementsArr] : selectedElementsArr;
actions.setSelectedElements(nextElements);
return;
}
actions.setSelectedElements(elements);
}),
updateTransform: action((state, transform) => {
state.transform[0] = transform[0];
state.transform[1] = transform[1];
state.transform[2] = transform[2];
}),
updateSize: action((state, size) => {
// when parent has no size we use these default values
// so that the calculations don't throw any errors
state.width = size.width || 500;
state.height = size.height || 500;
}),
initD3Zoom: action((state, { d3Zoom, d3Selection, d3ZoomHandler, transform }) => {
state.d3Zoom = d3Zoom;
state.d3Selection = d3Selection;
state.d3ZoomHandler = d3ZoomHandler;
state.transform[0] = transform[0];
state.transform[1] = transform[1];
state.transform[2] = transform[2];
}),
setMinZoom: action((state, minZoom) => {
state.minZoom = minZoom;
if (state.d3Zoom) {
state.d3Zoom.scaleExtent([minZoom, state.maxZoom]);
}
}),
setMaxZoom: action((state, maxZoom) => {
state.maxZoom = maxZoom;
if (state.d3Zoom) {
state.d3Zoom.scaleExtent([state.minZoom, maxZoom]);
}
}),
setTranslateExtent: action((state, translateExtent) => {
state.translateExtent = translateExtent;
if (state.d3Zoom) {
state.d3Zoom.translateExtent(translateExtent);
}
}),
setConnectionPosition: action((state, position) => {
state.connectionPosition = position;
}),
setConnectionNodeId: action((state, { connectionNodeId, connectionHandleId, connectionHandleType }) => {
state.connectionNodeId = connectionNodeId;
state.connectionHandleId = connectionHandleId;
state.connectionHandleType = connectionHandleType;
}),
setSnapToGrid: action((state, snapToGrid) => {
state.snapToGrid = snapToGrid;
}),
setSnapGrid: action((state, snapGrid) => {
state.snapGrid[0] = snapGrid[0];
state.snapGrid[1] = snapGrid[1];
}),
setInteractive: action((state, isInteractive) => {
state.nodesDraggable = isInteractive;
state.nodesConnectable = isInteractive;
state.elementsSelectable = isInteractive;
}),
setNodesDraggable: action((state, nodesDraggable) => {
state.nodesDraggable = nodesDraggable;
}),
setNodesConnectable: action((state, nodesConnectable) => {
state.nodesConnectable = nodesConnectable;
}),
setElementsSelectable: action((state, elementsSelectable) => {
state.elementsSelectable = elementsSelectable;
}),
setMultiSelectionActive: action((state, isActive) => {
state.multiSelectionActive = isActive;
}),
setConnectionMode: action((state, connectionMode) => {
state.connectionMode = connectionMode;
}),
};
const nodeEnv: string = (typeof __ENV__ !== 'undefined' && __ENV__) as string;
const store = createStore(storeModel, { devTools: nodeEnv === 'development' });
export type AppDispatch = typeof store.dispatch;
export default store;