refactor(stlyes): use react-flow__container helper

This commit is contained in:
moklick
2021-11-04 15:13:14 +01:00
parent 31ad12ec9c
commit 72f1d8b4e3
12 changed files with 108 additions and 190 deletions
+2 -6
View File
@@ -28,9 +28,7 @@ const initialNodes: Node[] = [
data: { label: 'Node 4' }, data: { label: 'Node 4' },
position: { x: 100, y: 200 }, position: { x: 100, y: 200 },
className: 'light', className: 'light',
style: { backgroundColor: 'rgba(255, 0, 0, 0.8)' }, style: { backgroundColor: 'rgba(255, 0, 0, 0.8)', width: 600, height: 300 },
width: 600,
height: 300,
}, },
{ {
id: '4a', id: '4a',
@@ -44,9 +42,7 @@ const initialNodes: Node[] = [
data: { label: 'Node 4b' }, data: { label: 'Node 4b' },
position: { x: 150, y: 50 }, position: { x: 150, y: 50 },
className: 'light', className: 'light',
style: { backgroundColor: 'rgba(255, 0, 255, 0.8)' }, style: { backgroundColor: 'rgba(255, 0, 255, 0.8)', height: 300, width: 300 },
height: 300,
width: 300,
parentNode: '4', parentNode: '4',
}, },
{ {
@@ -31,7 +31,7 @@ const Background: FC<BackgroundProps> = ({
// when there are multiple flows on a page we need to make sure that every background gets its own pattern. // when there are multiple flows on a page we need to make sure that every background gets its own pattern.
const patternId = useMemo(() => `pattern-${Math.floor(Math.random() * 100000)}`, []); const patternId = useMemo(() => `pattern-${Math.floor(Math.random() * 100000)}`, []);
const bgClasses = cc(['react-flow__background', className]); const bgClasses = cc(['react-flow__background', 'react-flow__container', className]);
const scaledGap = gap * scale; const scaledGap = gap * scale;
const xOffset = x % scaledGap; const xOffset = x % scaledGap;
const yOffset = y % scaledGap; const yOffset = y % scaledGap;
+3 -5
View File
@@ -1,4 +1,5 @@
import React, { useEffect, useState, CSSProperties } from 'react'; import React, { useEffect, useState, CSSProperties } from 'react';
import shallow from 'zustand/shallow';
import { useStore } from '../../store'; import { useStore } from '../../store';
import { getBezierPath } from '../Edges/BezierEdge'; import { getBezierPath } from '../Edges/BezierEdge';
@@ -6,7 +7,6 @@ import { getSmoothStepPath } from '../Edges/SmoothStepEdge';
import { import {
ElementId, ElementId,
NodeLookupItem, NodeLookupItem,
Transform,
HandleElement, HandleElement,
Position, Position,
ConnectionLineType, ConnectionLineType,
@@ -23,13 +23,12 @@ interface ConnectionLineProps {
connectionPositionX: number; connectionPositionX: number;
connectionPositionY: number; connectionPositionY: number;
connectionLineType: ConnectionLineType; connectionLineType: ConnectionLineType;
transform: Transform;
isConnectable: boolean; isConnectable: boolean;
connectionLineStyle?: CSSProperties; connectionLineStyle?: CSSProperties;
CustomConnectionLineComponent?: ConnectionLineComponent; CustomConnectionLineComponent?: ConnectionLineComponent;
} }
const selector = (s: ReactFlowState) => s.nodeLookup; const selector = (s: ReactFlowState) => ({ nodeLookup: s.nodeLookup, transform: s.transform });
export default ({ export default ({
connectionNodeId, connectionNodeId,
@@ -39,11 +38,10 @@ export default ({
connectionPositionX, connectionPositionX,
connectionPositionY, connectionPositionY,
connectionLineType = ConnectionLineType.Bezier, connectionLineType = ConnectionLineType.Bezier,
transform,
isConnectable, isConnectable,
CustomConnectionLineComponent, CustomConnectionLineComponent,
}: ConnectionLineProps) => { }: ConnectionLineProps) => {
const nodeLookup = useStore(selector); const { nodeLookup, transform } = useStore(selector, shallow);
const [sourceNode, setSourceNode] = useState<NodeLookupItem | null>(null); const [sourceNode, setSourceNode] = useState<NodeLookupItem | null>(null);
const nodeId = connectionNodeId; const nodeId = connectionNodeId;
const handleId = connectionHandleId; const handleId = connectionHandleId;
-6
View File
@@ -23,8 +23,6 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
scale, scale,
xPos, xPos,
yPos, yPos,
width,
height,
isSelected, isSelected,
onClick, onClick,
onMouseEnter, onMouseEnter,
@@ -74,8 +72,6 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave ? 'all' : 'none', isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave ? 'all' : 'none',
// prevents jumping of nodes on start // prevents jumping of nodes on start
// opacity: isInitialized ? 1 : 0, // opacity: isInitialized ? 1 : 0,
width: isParentNode && width !== null ? width : 'auto',
height: isParentNode && height !== null ? height : 'auto',
...style, ...style,
}), }),
[ [
@@ -91,8 +87,6 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
onMouseMove, onMouseMove,
onMouseLeave, onMouseLeave,
isParentNode, isParentNode,
width,
height,
] ]
); );
+1 -1
View File
@@ -103,7 +103,7 @@ export default ({
} }
return ( return (
<div className="react-flow__nodesselection" style={style}> <div className="react-flow__nodesselection react-flow__container" style={style}>
<ReactDraggable <ReactDraggable
scale={tScale} scale={tScale}
grid={grid} grid={grid}
+2 -2
View File
@@ -36,7 +36,7 @@ const SelectionRect = () => {
return ( return (
<div <div
className="react-flow__selection" className="react-flow__selection react-flow__container"
style={{ style={{
width: userSelectionRect.width, width: userSelectionRect.width,
height: userSelectionRect.height, height: userSelectionRect.height,
@@ -102,7 +102,7 @@ export default memo(({ selectionKeyPressed }: UserSelectionProps) => {
return ( return (
<div <div
className="react-flow__selectionpane" className="react-flow__selectionpane react-flow__container"
onMouseDown={onMouseDown} onMouseDown={onMouseDown}
onMouseMove={onMouseMove} onMouseMove={onMouseMove}
onMouseUp={onMouseUp} onMouseUp={onMouseUp}
+7 -4
View File
@@ -207,7 +207,6 @@ const Edge = memo(
); );
const selector = (s: ReactFlowState) => ({ const selector = (s: ReactFlowState) => ({
transform: s.transform,
connectionNodeId: s.connectionNodeId, connectionNodeId: s.connectionNodeId,
connectionHandleId: s.connectionHandleId, connectionHandleId: s.connectionHandleId,
connectionHandleType: s.connectionHandleType, connectionHandleType: s.connectionHandleType,
@@ -222,7 +221,6 @@ const selector = (s: ReactFlowState) => ({
const EdgeRenderer = (props: EdgeRendererProps) => { const EdgeRenderer = (props: EdgeRendererProps) => {
const { const {
transform,
connectionNodeId, connectionNodeId,
connectionHandleId, connectionHandleId,
connectionHandleType, connectionHandleType,
@@ -246,7 +244,13 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
return ( return (
<> <>
{edgeTree.map(({ level, edges, isMaxLevel }) => ( {edgeTree.map(({ level, edges, isMaxLevel }) => (
<svg key={level} style={{ zIndex: level }} width={width} height={height} className="react-flow__edges"> <svg
key={level}
style={{ zIndex: level }}
width={width}
height={height}
className="react-flow__edges react-flow__container"
>
{isMaxLevel && <MarkerDefinitions defaultColor={defaultMarkerColor} />} {isMaxLevel && <MarkerDefinitions defaultColor={defaultMarkerColor} />}
<g> <g>
{edges.map((edge: Edge) => { {edges.map((edge: Edge) => {
@@ -289,7 +293,6 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
connectionHandleType={connectionHandleType!} connectionHandleType={connectionHandleType!}
connectionPositionX={connectionPosition.x} connectionPositionX={connectionPosition.x}
connectionPositionY={connectionPosition.y} connectionPositionY={connectionPosition.y}
transform={transform}
connectionLineStyle={connectionLineStyle} connectionLineStyle={connectionLineStyle}
connectionLineType={connectionLineType} connectionLineType={connectionLineType}
isConnectable={nodesConnectable} isConnectable={nodesConnectable}
+6 -1
View File
@@ -118,7 +118,12 @@ const FlowRenderer = ({
onSelectionContextMenu={onSelectionContextMenu} onSelectionContextMenu={onSelectionContextMenu}
/> />
)} )}
<div className="react-flow__pane" onClick={onClick} onContextMenu={onContextMenu} onWheel={onWheel} /> <div
className="react-flow__pane react-flow__container"
onClick={onClick}
onContextMenu={onContextMenu}
onWheel={onWheel}
/>
</ZoomPane> </ZoomPane>
); );
}; };
+6 -11
View File
@@ -1,9 +1,10 @@
import React, { useEffect, useRef, memo } from 'react'; import React, { useEffect, useRef, memo } from 'react';
import { useStoreApi, useStore } from '../../store'; import { useStoreApi } from '../../store';
import FlowRenderer from '../FlowRenderer'; import FlowRenderer from '../FlowRenderer';
import NodeRenderer from '../NodeRenderer'; import NodeRenderer from '../NodeRenderer';
import EdgeRenderer from '../EdgeRenderer'; import EdgeRenderer from '../EdgeRenderer';
import Viewport from '../Viewport';
import { onLoadProject, onLoadGetNodes, onLoadGetEdges, onLoadToObject } from '../../utils/graph'; import { onLoadProject, onLoadGetNodes, onLoadGetEdges, onLoadToObject } from '../../utils/graph';
import useZoomPanHelper from '../../hooks/useZoomPanHelper'; import useZoomPanHelper from '../../hooks/useZoomPanHelper';
@@ -83,7 +84,6 @@ const GraphView = ({
const isInitialized = useRef<boolean>(false); const isInitialized = useRef<boolean>(false);
const store = useStoreApi(); const store = useStoreApi();
const { zoomIn, zoomOut, zoomTo, transform: setTransform, fitView, initialized } = useZoomPanHelper(); const { zoomIn, zoomOut, zoomTo, transform: setTransform, fitView, initialized } = useZoomPanHelper();
const transform = useStore((s) => s.transform);
useEffect(() => { useEffect(() => {
if (!isInitialized.current && initialized) { if (!isInitialized.current && initialized) {
@@ -93,7 +93,7 @@ const GraphView = ({
zoomIn, zoomIn,
zoomOut, zoomOut,
zoomTo, zoomTo,
setTransform: setTransform, setTransform,
project: onLoadProject(store.getState), project: onLoadProject(store.getState),
getNodes: onLoadGetNodes(store.getState), getNodes: onLoadGetNodes(store.getState),
getEdges: onLoadGetEdges(store.getState), getEdges: onLoadGetEdges(store.getState),
@@ -103,12 +103,7 @@ const GraphView = ({
isInitialized.current = true; isInitialized.current = true;
} }
}, [onLoad, zoomIn, zoomOut, zoomTo, transform, fitView, initialized]); }, [onLoad, zoomIn, zoomOut, zoomTo, setTransform, fitView, initialized]);
const transformStyle = {
transform: `translate(${transform[0]}px,${transform[1]}px) scale(${transform[2]})`,
transformOrigin: '0 0',
};
return ( return (
<FlowRenderer <FlowRenderer
@@ -138,7 +133,7 @@ const GraphView = ({
onSelectionContextMenu={onSelectionContextMenu} onSelectionContextMenu={onSelectionContextMenu}
preventScrolling={preventScrolling} preventScrolling={preventScrolling}
> >
<div className="react-flow__container" style={{ zIndex: 2, ...transformStyle }}> <Viewport>
<EdgeRenderer <EdgeRenderer
edgeTypes={edgeTypes} edgeTypes={edgeTypes}
onEdgeClick={onEdgeClick} onEdgeClick={onEdgeClick}
@@ -171,7 +166,7 @@ const GraphView = ({
selectNodesOnDrag={selectNodesOnDrag} selectNodesOnDrag={selectNodesOnDrag}
onlyRenderVisibleElements={onlyRenderVisibleElements} onlyRenderVisibleElements={onlyRenderVisibleElements}
/> />
</div> </Viewport>
</FlowRenderer> </FlowRenderer>
); );
}; };
+47 -117
View File
@@ -2,7 +2,7 @@ import React, { memo, useMemo, ComponentType, MouseEvent } from 'react';
import shallow from 'zustand/shallow'; import shallow from 'zustand/shallow';
import { useStore } from '../../store'; import { useStore } from '../../store';
import { Node, NodeTypesType, ReactFlowState, WrapNodeProps, SnapGrid, NodeRendererNode } from '../../types'; import { Node, NodeTypesType, ReactFlowState, WrapNodeProps } from '../../types';
import useVisibleNodes from '../../hooks/useVisibleNodes'; import useVisibleNodes from '../../hooks/useVisibleNodes';
import useNodeLookupRef from '../../hooks/useNodeLookupRef'; import useNodeLookupRef from '../../hooks/useNodeLookupRef';
@@ -22,7 +22,7 @@ interface NodeRendererProps {
} }
const selector = (s: ReactFlowState) => ({ const selector = (s: ReactFlowState) => ({
transform: s.transform, scale: s.transform[2],
nodesDraggable: s.nodesDraggable, nodesDraggable: s.nodesDraggable,
nodesConnectable: s.nodesConnectable, nodesConnectable: s.nodesConnectable,
elementsSelectable: s.elementsSelectable, elementsSelectable: s.elementsSelectable,
@@ -31,107 +31,9 @@ const selector = (s: ReactFlowState) => ({
snapToGrid: s.snapToGrid, snapToGrid: s.snapToGrid,
}); });
interface NodeProps extends NodeRendererProps {
node: Node;
nodeType: string;
childNodes?: NodeRendererNode[];
xPos?: number;
yPos?: number;
isDraggable?: boolean;
resizeObserver: ResizeObserver | null;
scale: number;
snapToGrid: boolean;
snapGrid: SnapGrid;
nodesDraggable: boolean;
nodesConnectable: boolean;
elementsSelectable: boolean;
treeLevel?: number;
isParentNode?: boolean;
}
function Node({
node,
childNodes,
nodeType,
isDraggable,
resizeObserver,
scale,
snapToGrid,
snapGrid,
nodesDraggable,
nodesConnectable,
elementsSelectable,
treeLevel = 0,
xPos,
yPos,
isParentNode = false,
...props
}: NodeProps) {
// const onNodesChange = useStore((s) => s.onNodesChange);
const NodeComponent = (props.nodeTypes[nodeType] || props.nodeTypes.default) as ComponentType<WrapNodeProps>;
const isNodeDraggable =
typeof isDraggable !== 'undefined'
? isDraggable
: !!(node.draggable || (nodesDraggable && typeof node.draggable === 'undefined'));
const isSelectable = !!(node.selectable || (elementsSelectable && typeof node.selectable === 'undefined'));
const isConnectable = !!(node.connectable || (nodesConnectable && typeof node.connectable === 'undefined'));
const isInitialized =
node.width !== null &&
node.height !== null &&
typeof node.width !== 'undefined' &&
typeof node.height !== 'undefined';
return (
<NodeComponent
id={node.id}
className={node.className}
style={node.style}
type={nodeType}
data={node.data}
sourcePosition={node.sourcePosition}
targetPosition={node.targetPosition}
isHidden={node.isHidden}
xPos={xPos || 0}
yPos={yPos || 0}
width={node.width}
height={node.height}
isDragging={node.isDragging}
isInitialized={isInitialized}
snapGrid={snapGrid}
snapToGrid={snapToGrid}
selectNodesOnDrag={props.selectNodesOnDrag}
onClick={props.onNodeClick}
onMouseEnter={props.onNodeMouseEnter}
onMouseMove={props.onNodeMouseMove}
onMouseLeave={props.onNodeMouseLeave}
onContextMenu={props.onNodeContextMenu}
onNodeDoubleClick={props.onNodeDoubleClick}
onNodeDragStart={props.onNodeDragStart}
onNodeDrag={props.onNodeDrag}
onNodeDragStop={props.onNodeDragStop}
scale={scale}
isSelected={!!node.isSelected}
isDraggable={isNodeDraggable}
isSelectable={isSelectable}
isConnectable={isConnectable}
resizeObserver={resizeObserver}
dragHandle={node.dragHandle}
zIndex={treeLevel}
isParentNode={isParentNode}
/>
);
}
const NodeRenderer = (props: NodeRendererProps) => { const NodeRenderer = (props: NodeRendererProps) => {
const { const { scale, nodesDraggable, nodesConnectable, elementsSelectable, updateNodeDimensions, snapGrid, snapToGrid } =
transform, useStore(selector, shallow);
nodesDraggable,
nodesConnectable,
elementsSelectable,
updateNodeDimensions,
snapGrid,
snapToGrid,
} = useStore(selector, shallow);
const nodeLookup = useNodeLookupRef(); const nodeLookup = useNodeLookupRef();
const nodes = useVisibleNodes(props.onlyRenderVisibleElements); const nodes = useVisibleNodes(props.onlyRenderVisibleElements);
@@ -151,7 +53,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
}, []); }, []);
return ( return (
<div className="react-flow__nodes"> <div className="react-flow__nodes react-flow__container">
{nodes.map((node) => { {nodes.map((node) => {
const nodeType = node.type || 'default'; const nodeType = node.type || 'default';
const lookupNode = nodeLookup.current.get(node.id); const lookupNode = nodeLookup.current.get(node.id);
@@ -160,23 +62,51 @@ const NodeRenderer = (props: NodeRendererProps) => {
console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`); console.warn(`Node type "${nodeType}" not found. Using fallback type "default".`);
} }
const NodeComponent = (props.nodeTypes[nodeType] || props.nodeTypes.default) as ComponentType<WrapNodeProps>;
const isDraggable = !!(node.draggable || (nodesDraggable && typeof node.draggable === 'undefined'));
const isSelectable = !!(node.selectable || (elementsSelectable && typeof node.selectable === 'undefined'));
const isConnectable = !!(node.connectable || (nodesConnectable && typeof node.connectable === 'undefined'));
const isInitialized =
node.width !== null &&
node.height !== null &&
typeof node.width !== 'undefined' &&
typeof node.height !== 'undefined';
return ( return (
<Node <NodeComponent
key={node.id} id={node.id}
node={node} className={node.className}
nodeType={nodeType} style={node.style}
snapToGrid={snapToGrid} type={nodeType}
data={node.data}
sourcePosition={node.sourcePosition}
targetPosition={node.targetPosition}
isHidden={node.isHidden}
xPos={lookupNode?.positionAbsolute?.x || 0}
yPos={lookupNode?.positionAbsolute?.y || 0}
isDragging={node.isDragging}
isInitialized={isInitialized}
snapGrid={snapGrid} snapGrid={snapGrid}
nodesDraggable={nodesDraggable} snapToGrid={snapToGrid}
nodesConnectable={nodesConnectable} selectNodesOnDrag={props.selectNodesOnDrag}
onClick={props.onNodeClick}
onMouseEnter={props.onNodeMouseEnter}
onMouseMove={props.onNodeMouseMove}
onMouseLeave={props.onNodeMouseLeave}
onContextMenu={props.onNodeContextMenu}
onNodeDoubleClick={props.onNodeDoubleClick}
onNodeDragStart={props.onNodeDragStart}
onNodeDrag={props.onNodeDrag}
onNodeDragStop={props.onNodeDragStop}
scale={scale}
isSelected={!!node.isSelected}
isDraggable={isDraggable}
isSelectable={isSelectable}
isConnectable={isConnectable}
resizeObserver={resizeObserver} resizeObserver={resizeObserver}
elementsSelectable={elementsSelectable} dragHandle={node.dragHandle}
scale={transform[2]} zIndex={lookupNode?.treeLevel || 0}
xPos={lookupNode?.positionAbsolute?.x} isParentNode={!!lookupNode?.isParentNode}
yPos={lookupNode?.positionAbsolute?.y}
treeLevel={lookupNode?.treeLevel}
isParentNode={lookupNode?.isParentNode}
{...props}
/> />
); );
})} })}
+25
View File
@@ -0,0 +1,25 @@
import React, { ReactNode } from 'react';
import { useStore } from '../../store';
import { ReactFlowState } from '../../types';
const selector = (s: ReactFlowState) => s.transform;
type ViewportProps = {
children: ReactNode;
};
function Viewport({ children }: ViewportProps) {
const transform = useStore(selector);
return (
<div
className="react-flow__viewport react-flow__container"
style={{ transform: `translate(${transform[0]}px,${transform[1]}px) scale(${transform[2]})` }}
>
{children}
</div>
);
}
export default Viewport;
+8 -36
View File
@@ -5,12 +5,10 @@
overflow: hidden; overflow: hidden;
} }
.react-flow__renderer, .react-flow__container {
.react-flow__pane, position: absolute;
.react-flow__selectionpane {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: absolute;
top: 0; top: 0;
left: 0; left: 0;
} }
@@ -19,6 +17,11 @@
z-index: 1; z-index: 1;
} }
.react-flow__viewport {
transform-origin: 0 0;
z-index: 2;
}
.react-flow__renderer { .react-flow__renderer {
z-index: 4; z-index: 4;
} }
@@ -27,17 +30,9 @@
z-index: 5; z-index: 5;
} }
.react-flow__selection {
position: absolute;
top: 0;
left: 0;
}
.react-flow__edges { .react-flow__edges {
position: absolute;
top: 0;
left: 0;
pointer-events: none; pointer-events: none;
overflow: visible;
} }
.react-flow__edge { .react-flow__edge {
@@ -81,9 +76,6 @@
} }
.react-flow__nodes { .react-flow__nodes {
position: absolute;
width: 100%;
height: 100%;
pointer-events: none; pointer-events: none;
transform-origin: 0 0; transform-origin: 0 0;
} }
@@ -98,11 +90,6 @@
.react-flow__nodesselection { .react-flow__nodesselection {
z-index: 3; z-index: 3;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
transform-origin: left top; transform-origin: left top;
pointer-events: none; pointer-events: none;
@@ -153,14 +140,6 @@
/* additional components */ /* additional components */
.react-flow__background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.react-flow__controls { .react-flow__controls {
position: absolute; position: absolute;
z-index: 5; z-index: 5;
@@ -184,10 +163,3 @@
bottom: 10px; bottom: 10px;
right: 10px; right: 10px;
} }
.react-flow__container {
position: absolute;
width: 100%;
height: 100%;
pointer-events: none;
}