init 🚀

This commit is contained in:
moklick
2019-07-15 16:48:04 +02:00
commit cf4441ce6d
24 changed files with 8924 additions and 0 deletions

21
.babelrc Normal file
View File

@@ -0,0 +1,21 @@
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
],
"@babel/preset-react"
],
"env": {
"test": {
"presets": [
[
"react-app"
]
]
}
},
"plugins": []
}

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.DS_Store
node_modules
dist
example/build
.cache

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
registry = "https://registry.npmjs.com/"

6
.travis.yml Normal file
View File

@@ -0,0 +1,6 @@
language: node_js
node_js:
- '11'
- '10'
- '8'
- '6'

7
LICENSE Normal file
View File

@@ -0,0 +1,7 @@
Copyright (c) 2017 [these people](https://github.com/rollup/rollup-starter-lib/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1
README.md Normal file
View File

@@ -0,0 +1 @@
# react-graph

58
example/SimpleGraph.js Normal file
View File

@@ -0,0 +1,58 @@
import React, { PureComponent } from 'react';
import Graph from '../src';
class App extends PureComponent {
onLoad(graphInstance) {
this.graphInstance = graphInstance;
console.log('graph loaded:', graphInstance);
}
onMove() {
if (!this.graphInstance) {
return false;
}
console.log('graph moved');
}
onFitView() {
if (!this.graphInstance) {
return false;
}
this.graphInstance.fitView();
}
render() {
const elements = [
{ data: { id: '1', label: 'Tests', type: 'input' }, position: { x: 0, y: 0 } },
{ data: { id: '2', label: 'This is a node This is a node This is a node This is a node' }, position: { x: 100, y: 100 } },
{ data: { id: '3', label: 'This is a node' }, position: { x: 100, y: 200 }, style: { background: '#222', color: '#fff' } },
{ data: { id: '4', label: 'nody nodes', type: 'output' }, position: { x: 50, y: 300 } },
{ data: { id: '5', label: 'Another node', type: 'output' }, position: { x: 400, y: 300 } },
{ data: { source: '1', target: '2' } },
{ data: { source: '2', target: '3' } },
{ data: { source: '3', target: '4' } },
{ data: { source: '3', target: '5' } }
];
return (
<Graph
elements={elements}
onNodeClick={node => console.log(node)}
style={{ width: '100%', height: '100%' }}
onLoad={graphInstance => this.onLoad(graphInstance)}
onMove={() => this.onMove()}
>
<button
type="button"
style={{ position: 'absolute', right: '10px', bottom: '10px' }}
onClick={() => this.onFitView()}
>
fit
</button>
</Graph>
);
}
}
export default App;

18
example/index.html Normal file
View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html, body, #root {
height: 100%;
}
</style>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>

9
example/index.js Normal file
View File

@@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import SimpleGraph from './SimpleGraph';
ReactDOM.render(
<SimpleGraph />,
document.getElementById('root')
);

8123
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

41
package.json Normal file
View File

@@ -0,0 +1,41 @@
{
"name": "react-graph",
"version": "1.0.0",
"module": "dist/ReactGraph.esm.js",
"browser": "dist/ReactGraph.umd.js",
"private": true,
"dependencies": {
"@emotion/core": "^10.0.14",
"@emotion/styled": "^10.0.14",
"d3-selection": "^1.4.0",
"d3-zoom": "^1.7.3",
"lodash.isequal": "^4.5.0",
"ms": "^2.0.0",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-draggable": "^3.3.0",
"react-sizeme": "^2.6.7"
},
"devDependencies": {
"@babel/core": "^7.5.4",
"@babel/preset-env": "^7.5.4",
"@babel/preset-react": "^7.0.0",
"babel-preset-react-app": "^9.0.0",
"parcel-bundler": "^1.12.3",
"react-dom": "^16.8.6",
"rollup": "^1.16.2",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-livereload": "^1.0.1",
"rollup-plugin-node-resolve": "^5.1.0",
"rollup-plugin-serve": "^1.0.1"
},
"scripts": {
"build": "rollup -c",
"watch": "rollup -w -c",
"dev": "parcel example/index.html -d example/build"
},
"files": [
"dist"
]
}

50
rollup.config.js Normal file
View File

@@ -0,0 +1,50 @@
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import pkg from './package.json';
export default [{
input: 'src/index.js',
external: ['react'],
output: {
name: 'ReactGraph',
file: pkg.browser,
format: 'umd',
sourcemaps: true,
globals: {
react: 'React',
}
},
plugins: [
resolve(),
babel({
exclude: 'node_modules/**'
}),
commonjs({
include: /node_modules/
})
]
}
];
// {
// input: 'src/index.js',
// external: ['react', 'prop-types', 'react-draggable', 'react-sizeme'],
// output: [{
// file: pkg.module,
// format: 'es',
// globals: {
// react: 'React',
// 'react-draggable': 'ReactDraggable',
// 'react-sizeme': 'ReactSizeme'
// }
// }],
// plugins: [
// babel({
// exclude: 'node_modules/**'
// })
// ]
// }

24
src/EdgeRenderer/Edge.js Normal file
View File

@@ -0,0 +1,24 @@
import React from 'react';
import styled from '@emotion/styled';
const Path = styled.path`
fill: none;
stroke: #333;
stroke-width: 2;
`;
export default (props) => {
const { targetNode, sourceNode } = props;
const sourceX = sourceNode.position.x + (sourceNode.data.__width / 2);
const sourceY = sourceNode.position.y + sourceNode.data.__height;
const targetX = targetNode.position.x + (targetNode.data.__width / 2);
const targetY = targetNode.position.y;
return (
<Path
d={`M ${sourceX},${sourceY}L ${targetX},${targetY}`}
/>
);
};

55
src/EdgeRenderer/index.js Normal file
View File

@@ -0,0 +1,55 @@
import React, { PureComponent } from 'react';
import Edge from './Edge';
import { Consumer } from '../GraphContext';
function renderEdge(e, nodes) {
const sourceNode = nodes.find(n => n.data.id === e.data.source);
const targetNode = nodes.find(n => n.data.id === e.data.target);
if (!sourceNode) {
throw new Error(`couldn't create edge for source id: ${e.data.source}`);
}
if (!targetNode) {
throw new Error(`couldn't create edge for source id: ${e.data.target}`);
}
return (
<Edge
key={`${e.data.source}-${e.data.target}`}
sourceNode={sourceNode}
targetNode={targetNode}
/>
);
}
class EdgeRenderer extends PureComponent {
render() {
const { width, height } = this.props;
if (!width) {
return null;
}
return (
<Consumer>
{({ transform, edges, nodes }) => (
<svg
width={width}
height={height}
style={{ pointerEvents: 'none' }}
>
<g
transform={`translate(${transform.x},${transform.y}) scale(${transform.k})`}
>
{edges.map(e => renderEdge(e, nodes))}
</g>
</svg>
)}
</Consumer>
);
}
}
export default EdgeRenderer;

113
src/GraphContext/index.js Normal file
View File

@@ -0,0 +1,113 @@
import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
import { zoomIdentity } from 'd3-zoom';
import { getBoundingBox } from '../graph-utils';
export const GraphContext = createContext({});
export const Provider = (props) => {
const {
nodes: initNodes,
edges: initEdges,
onNodeClick,
children
} = props;
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
const [d3ZoomState, initD3ZoomState] = useState({
zoom: null, selection: null, initialised: false
});
const [nodes, setNodes] = useState(initNodes);
const [edges, setEdges] = useState(initEdges);
const [transform, setTransform] = useState({ x: 0, y: 0, k: 1 });
const updateNodeData = (nodeId, updateData) => {
const updatedNodes = nodes.map((n) => {
if (n.data.id === nodeId) {
n.data = {
...n.data,
...updateData
};
}
return n;
});
setNodes(updatedNodes);
};
const updateNodePos = (nodeId, pos) => {
const updatedNodes = nodes.map((n) => {
if (n.data.id === nodeId) {
n.position = pos;
}
return n;
});
setNodes(updatedNodes);
};
const updateTransform = (nextTransform) => {
setTransform({
k: Math.round(nextTransform.k * 1000) / 1000,
x: nextTransform.x,
y: nextTransform.y
});
};
const fitView = () => {
const bounds = getBoundingBox(nodes);
const k = Math.min(width, height) / Math.max(bounds.width, bounds.height);
const boundsCenterX = bounds.x + (bounds.width / 2);
const boundsCenterY = bounds.y + (bounds.height / 2);
const translate = [(width / 2) - (boundsCenterX * k), (height / 2) - (boundsCenterY * k)];
const initialTransform = zoomIdentity.translate(translate[0], translate[1]).scale(k);
d3ZoomState.selection.call(d3ZoomState.zoom.transform, initialTransform);
};
const updateSize = (size) => {
setWidth(size.width);
setHeight(size.height);
};
const graphContext = {
width,
height,
updateSize,
d3ZoomState,
initD3ZoomState,
nodes,
setNodes,
edges,
setEdges,
updateNodeData,
updateNodePos,
transform,
updateTransform,
onNodeClick,
fitView
};
return (
<GraphContext.Provider
value={graphContext}
>
{children}
</GraphContext.Provider>
);
};
export const { Consumer } = GraphContext;
Provider.propTypes = {
nodes: PropTypes.arrayOf(PropTypes.object),
edges: PropTypes.arrayOf(PropTypes.object)
};
Provider.defaultProps = {
nodes: [],
edges: []
};

72
src/GraphView/index.js Normal file
View File

@@ -0,0 +1,72 @@
import React, { useEffect, useContext, useRef } from 'react';
import styled from '@emotion/styled';
import * as d3Zoom from 'd3-zoom';
import { select, event } from 'd3-selection';
import ReactSizeMe from 'react-sizeme';
import { GraphContext } from '../GraphContext';
import NodeRenderer from '../NodeRenderer';
import EdgeRenderer from '../EdgeRenderer';
const GraphViewWrapper = styled.div`
width: 100%;
height: 100%;
position: absolute;
`;
const ZoomNode = styled.div`
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
`;
const GraphView = (props) => {
const zoomNode = useRef(null);
const graphContext = useContext(GraphContext);
useEffect(() => {
const zoom = d3Zoom.zoom()
.scaleExtent([0.5, 2])
.on('zoom', () => {
if (event.sourceEvent && event.sourceEvent.target !== zoomNode.current) {
return false;
}
graphContext.updateTransform(event.transform);
props.onMove();
});
const selection = select(zoomNode.current).call(zoom);
graphContext.initD3ZoomState({ zoom, selection, initialised: true });
}, []);
useEffect(
() => graphContext.updateSize(props.size),
[props.size.width, props.size.height]
);
useEffect(() => {
if (graphContext.d3ZoomState.initialised) {
props.onLoad({
nodes: graphContext.nodes,
edges: graphContext.edges,
fitView: graphContext.fitView
});
}
}, [graphContext.d3ZoomState.initialised]);
return (
<GraphViewWrapper>
<NodeRenderer />
<EdgeRenderer width={graphContext.width} height={graphContext.height} />
<ZoomNode ref={zoomNode} />
</GraphViewWrapper>
);
};
export default ReactSizeMe.withSize({ monitorHeight: true })(GraphView);

View File

@@ -0,0 +1,14 @@
import React from 'react';
import styled from '@emotion/styled';
const Handle = styled.div`
position: absolute;
width: 12px;
height: 12px;
transform: translate(-50%, -50%);
background: #222;
left: 50%;
border-radius: 50%;
`;
export default props => <Handle {...props} />;

View File

@@ -0,0 +1,18 @@
import React from 'react';
import styled from '@emotion/styled';
import wrapNode from './wrapNode';
import Handle from '../Handle';
const Wrapper = styled.div`
background: #ff6060;
padding: 10px;
`;
export default wrapNode(({ data, style }) => (
<Wrapper style={style}>
<Handle style={{ top: 0 }} />
{data.label}
<Handle style={{ bottom: 0, top: 'auto', transform: 'translate(-50%, 50%)' }} />
</Wrapper>
));

View File

@@ -0,0 +1,17 @@
import React from 'react';
import styled from '@emotion/styled';
import wrapNode from './wrapNode';
import Handle from '../Handle';
const Wrapper = styled.div`
background: #9999ff;
padding: 10px;
`;
export default wrapNode(({ data, style }) => (
<Wrapper style={style}>
{data.label}
<Handle style={{ bottom: 0, top: 'auto', transform: 'translate(-50%, 50%)' }} />
</Wrapper>
));

View File

@@ -0,0 +1,17 @@
import React from 'react';
import styled from '@emotion/styled';
import wrapNode from './wrapNode';
import Handle from '../Handle';
const Wrapper = styled.div`
background: #55ff99;
padding: 10px;
`;
export default wrapNode(({ data, style }) => (
<Wrapper style={style}>
<Handle style={{ top: 0 }} />
{data.label}
</Wrapper>
));

View File

@@ -0,0 +1,76 @@
import React, { useEffect, useRef, useContext } from 'react';
import styled from '@emotion/styled';
import ReactDraggable from 'react-draggable';
import { GraphContext } from '../../GraphContext';
const NodeWrapper = styled.div`
position: absolute;
width: 150px;
color: #222;
font-family: sans-serif;
font-size: 12px;
text-align: center;
cursor: grab;
border: 1px solid #ddd;
border-radius: 2px;
user-select: none;
pointer-events: all;
transform-origin: 0 0;
&:hover {
box-shadow: 0 1px 5px 2px rgba(0, 0, 0, 0.08);
}
`;
export default NodeComponent => (props) => {
const { position, data, onNodeClick } = props;
const { id, __width, __height } = data;
const nodeElement = useRef(null);
const graphContext = useContext(GraphContext);
const { x, y, k } = graphContext.transform;
useEffect(() => {
const bounds = nodeElement.current.getBoundingClientRect();
if (__width !== bounds.width || __height !== bounds.height) {
graphContext.updateNodeData(id, { __width: bounds.width, __height: bounds.height });
}
}, []);
const nodePosition = {
x: (k * position.x) + x,
y: (k * position.y) + y
};
return (
<ReactDraggable.DraggableCore
grid={[1, 1]}
onStart={(e) => {
const offsetX = e.clientX - position.x - x;
const offsetY = e.clientY - position.y - y;
graphContext.updateNodeData(id, { __offsetX: offsetX, __offsetY: offsetY });
}}
onDrag={(e, d) => {
const { __offsetX = 0, __offsetY = 0 } = data;
graphContext.updateNodePos(id, {
x: e.clientX - x - __offsetX,
y: e.clientY - y - __offsetY
});
}}
scale={k}
>
<NodeWrapper
className="node"
ref={nodeElement}
style={{ transform: `translate(${position.x}px,${position.y}px)` }}
onClick={() => onNodeClick(data)}
// style={{ transform: `translate(${nodePosition.x}px,${nodePosition.y}px) scale(${k})` }}
>
<NodeComponent {...props} />
</NodeWrapper>
</ReactDraggable.DraggableCore>
);
};

60
src/NodeRenderer/index.js Normal file
View File

@@ -0,0 +1,60 @@
import React, { PureComponent } from 'react';
import styled from '@emotion/styled';
import { Consumer } from '../GraphContext';
import DefaultNode from './NodeTypes/DefaultNode';
import InputNode from './NodeTypes/InputNode';
import OutputNode from './NodeTypes/OutputNode';
const Nodes = styled.div`
width: 100%;
height: 100%;
position: absolute;
z-index: 2;
pointer-events: none;
transform-origin: 0 0;
`;
class NodeRenderer extends PureComponent {
renderNode(d, onNodeClick) {
const nodeType = d.data.type || 'default';
const NodeComponent = this.props.nodeTypes[nodeType];
return (
<NodeComponent
key={d.data.id}
position={d.position}
data={d.data}
style={d.style || {}}
onNodeClick={onNodeClick}
/>
);
}
render() {
return (
<Consumer>
{({ transform, nodes, onNodeClick }) => (
<Nodes
style={{
transform: `translate(${transform.x}px,${transform.y}px) scale(${transform.k})`
}}
>
{nodes.map(d => this.renderNode(d, onNodeClick))}
</Nodes>
)}
</Consumer>
);
}
}
NodeRenderer.defaultProps = {
nodeTypes: {
input: InputNode,
default: DefaultNode,
output: OutputNode
}
};
export default NodeRenderer;

49
src/graph-utils.js Normal file
View File

@@ -0,0 +1,49 @@
export const isEdge = element => element.data.source && element.data.target;
export const separateElements = elements => ({
nodes: elements.filter(e => !isEdge(e)),
edges: elements.filter(e => isEdge(e))
});
export const getBoundingBox = (nodes) => {
const bbox = nodes.reduce((res, node) => {
const x2 = node.position.x + node.data.__width;
const y2 = node.position.y + node.data.__height;
if (node.position.x < res.minX) {
res.minX = node.position.x;
}
if (x2 > res.maxX) {
res.maxX = x2;
}
if (node.position.y < res.minY) {
res.minY = node.position.y;
}
if (y2 > res.maxY) {
res.maxY = y2;
}
return res;
}, {
minX: Number.MAX_VALUE,
minY: Number.MAX_VALUE,
maxX: 0,
maxY: 0
});
return {
x: bbox.minX,
y: bbox.minY,
width: bbox.maxX - bbox.minX,
height: bbox.maxY - bbox.minY
};
};
export default {
isEdge,
separateElements,
getBoundingBox
};

69
src/index.js Normal file
View File

@@ -0,0 +1,69 @@
import React, { PureComponent } from 'react';
import isEqual from 'lodash.isequal';
import styled from '@emotion/styled';
import { separateElements } from './graph-utils';
import GraphView from './GraphView';
import { Provider } from './GraphContext';
const GraphWrapper = styled.div`
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
`;
class ReactGraph extends PureComponent {
constructor(props) {
super();
const { elements } = props;
this.state = {
...separateElements(elements)
};
}
componentDidUpdate(prevProps, prevState) {
const { elements } = this.props;
const { nodes, edges } = separateElements(elements);
const nodesChanged = !isEqual(nodes, prevState.nodes);
const edgesChanged = !isEqual(edges, prevState.edges);
if (!nodesChanged && !edgesChanged) {
return false;
}
if (nodesChanged) {
this.setState({ nodes });
}
if (edgesChanged) {
this.setState({ edges });
}
}
render() {
const {
style, onNodeClick, children, onLoad, onMove
} = this.props;
const { nodes, edges } = this.state;
return (
<GraphWrapper style={style}>
<Provider nodes={nodes} edges={edges} onNodeClick={onNodeClick}>
<GraphView onLoad={onLoad} onMove={onMove} />
{children}
</Provider>
</GraphWrapper>
);
}
}
ReactGraph.defaultProps = {
onNodeClick: () => {},
onLoad: () => {},
onMove: () => {}
};
export default ReactGraph;