Feat/minimap (#44)

* feat: New minimap

* imporved preview

* better start values

* smarter destructure

* getNodesInside refactor

* refactor(minimap): add maskColor and nodeBorderRadius props

* refactor(gitignore): add dist

* refactor(minimap): show empty minimap when there are no nodes

closes #39
This commit is contained in:
AndyLnd
2019-10-22 14:15:36 +02:00
committed by Moritz
parent 99dcc775b4
commit dcc38b23d8
14 changed files with 2525 additions and 504 deletions
+1172 -151
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+1172 -151
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+5 -4
View File
@@ -1,9 +1,10 @@
import React from 'react'; import React from 'react';
import { Node } from '../../types'; import { Node } from '../../types';
declare type StringFunc = (node: Node) => string; declare type StringFunc = (node: Node) => string;
interface MiniMapProps extends React.HTMLAttributes<HTMLCanvasElement> { interface MiniMapProps extends React.HTMLAttributes<SVGSVGElement> {
bgColor?: string; nodeColor: string | StringFunc;
nodeColor?: string | StringFunc; nodeBorderRadius: number;
maskColor: string;
} }
declare const _default: ({ style, className, bgColor, nodeColor, }: MiniMapProps) => JSX.Element; declare const _default: ({ style, className, nodeColor, nodeBorderRadius, maskColor, }: MiniMapProps) => JSX.Element;
export default _default; export default _default;
+6 -8
View File
@@ -20,9 +20,11 @@ export interface Dimensions {
width: number; width: number;
height: number; height: number;
} }
export interface Rect extends Dimensions { export interface Rect extends Dimensions, XYPosition {
x: number; }
y: number; export interface Box extends XYPosition {
x2: number;
y2: number;
} }
export interface SelectionRect extends Rect { export interface SelectionRect extends Rect {
startX: number; startX: number;
@@ -90,13 +92,9 @@ export declare type Connection = {
target: ElementId | null; target: ElementId | null;
}; };
export declare type OnConnectFunc = (params: Connection) => void; export declare type OnConnectFunc = (params: Connection) => void;
export interface HandleElement { export interface HandleElement extends XYPosition, Dimensions {
id?: ElementId | null; id?: ElementId | null;
position: Position; position: Position;
x: number;
y: number;
width: number;
height: number;
} }
export interface EdgeCompProps { export interface EdgeCompProps {
id: ElementId; id: ElementId;
+3 -2
View File
@@ -5,9 +5,10 @@ export declare const getOutgoers: (node: Node, elements: (Node | Edge)[]) => (No
export declare const removeElements: (elementsToRemove: (Node | Edge)[], elements: (Node | Edge)[]) => (Node | Edge)[]; export declare const removeElements: (elementsToRemove: (Node | Edge)[], elements: (Node | Edge)[]) => (Node | Edge)[];
export declare const addEdge: (edgeParams: Edge, elements: (Node | Edge)[]) => (Node | Edge)[]; export declare const addEdge: (edgeParams: Edge, elements: (Node | Edge)[]) => (Node | Edge)[];
export declare const parseElement: (element: Node | Edge, transform: [number, number, number], snapToGrid: boolean, snapGrid: [number, number]) => Node | Edge; export declare const parseElement: (element: Node | Edge, transform: [number, number, number], snapToGrid: boolean, snapGrid: [number, number]) => Node | Edge;
export declare const getBoundingBox: (nodes: Node[]) => Rect; export declare const getBoundsofRects: (rect1: Rect, rect2: Rect) => Rect;
export declare const getRectOfNodes: (nodes: Node[]) => Rect;
export declare const graphPosToZoomedPos: (pos: XYPosition, transform: [number, number, number]) => XYPosition; export declare const graphPosToZoomedPos: (pos: XYPosition, transform: [number, number, number]) => XYPosition;
export declare const getNodesInside: (nodes: Node[], bbox: Rect, transform?: [number, number, number], partially?: boolean) => Node[]; export declare const getNodesInside: (nodes: Node[], rect: Rect, [tx, ty, tScale]?: [number, number, number], partially?: boolean) => Node[];
export declare const getConnectedEdges: (nodes: Node[], edges: Edge[]) => Edge[]; export declare const getConnectedEdges: (nodes: Node[], edges: Edge[]) => Edge[];
export declare const fitView: ({ padding }?: FitViewParams) => void; export declare const fitView: ({ padding }?: FitViewParams) => void;
export declare const zoomIn: () => void; export declare const zoomIn: () => void;
+1 -1
View File
@@ -149,7 +149,7 @@ class App extends PureComponent {
snapGrid={[16, 16]} snapGrid={[16, 16]}
> >
<MiniMap <MiniMap
style={{ position: 'absolute', right: 10, bottom: 10 }} style={{ position: 'absolute', right: 10, bottom: 10, backgroundColor: '#f8f8f8'}}
nodeColor={n => { nodeColor={n => {
if (n.type === 'input') return 'blue'; if (n.type === 'input') return 'blue';
if (n.type === 'output') return 'green'; if (n.type === 'output') return 'green';
+2 -1
View File
@@ -1,6 +1,6 @@
import React, { PureComponent } from 'react'; import React, { PureComponent } from 'react';
import Graph, { removeElements, addEdge, getOutgoers } from 'react-flow'; import Graph, { removeElements, addEdge, getOutgoers, MiniMap } from 'react-flow';
const onNodeDragStop = node => console.log('drag stop', node); const onNodeDragStop = node => console.log('drag stop', node);
@@ -68,6 +68,7 @@ class App extends PureComponent {
style={{ width: '100%', height: '100%' }} style={{ width: '100%', height: '100%' }}
backgroundType="lines" backgroundType="lines"
> >
<MiniMap />
<button <button
type="button" type="button"
onClick={() => this.onAdd()} onClick={() => this.onAdd()}
+2 -1
View File
@@ -1,4 +1,5 @@
module.exports = { module.exports = {
trailingComma: 'es5', trailingComma: 'es5',
singleQuote: true singleQuote: true,
printWidth: 120
}; };
+98 -76
View File
@@ -1,15 +1,21 @@
import React, { useRef, useEffect, CSSProperties } from 'react'; import React, { CSSProperties } from 'react';
import classnames from 'classnames'; import classnames from 'classnames';
import { useStoreState } from '../../store/hooks'; import { useStoreState } from '../../store/hooks';
import { getNodesInside } from '../../utils/graph'; import { getRectOfNodes, getBoundsofRects } from '../../utils/graph';
import { Node } from '../../types'; import { Node, Rect } from '../../types';
type StringFunc = (node: Node) => string; type StringFunc = (node: Node) => string;
interface MiniMapProps extends React.HTMLAttributes<HTMLCanvasElement> { interface MiniMapProps extends React.HTMLAttributes<SVGSVGElement> {
bgColor?: string; nodeColor: string | StringFunc;
nodeColor?: string | StringFunc; nodeBorderRadius: number;
maskColor: string;
}
interface MiniMapNodeProps {
node: Node;
color: string;
borderRadius: number;
} }
const baseStyle: CSSProperties = { const baseStyle: CSSProperties = {
@@ -18,81 +24,97 @@ const baseStyle: CSSProperties = {
bottom: 10, bottom: 10,
right: 10, right: 10,
width: 200, width: 200,
height: 150,
}; };
export default ({ const MiniMapNode = ({ node, color, borderRadius }: MiniMapNodeProps) => {
style = {}, const {
className, position: { x, y },
bgColor = '#f8f8f8', width,
nodeColor = '#ddd', height,
}: MiniMapProps) => { } = node.__rg;
const canvasNode = useRef<HTMLCanvasElement>(null); const { background, backgroundColor } = node.style || {};
const state = useStoreState(s => ({ const fill = (background || backgroundColor || color) as string;
width: s.width,
height: s.height,
nodes: s.nodes,
transform: s.transform,
}));
const mapClasses = classnames('react-flow__minimap', className);
const nodePositions = state.nodes.map(n => n.__rg.position);
const width: number = +(style.width || baseStyle.width || 0);
const height = (state.height / (state.width || 1)) * width;
const bbox = { x: 0, y: 0, width: state.width, height: state.height };
const scaleFactor = width / state.width;
const nodeColorFunc = (nodeColor instanceof Function
? nodeColor
: () => nodeColor) as StringFunc;
useEffect(() => {
if (!canvasNode || !canvasNode.current) {
return;
}
const ctx = canvasNode.current.getContext('2d');
if (!ctx) {
return;
}
const nodesInside = getNodesInside(
state.nodes,
bbox,
state.transform,
true
);
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, width, height);
nodesInside.forEach(n => {
const pos = n.__rg.position;
const transformX = state.transform[0];
const transformY = state.transform[1];
const x = pos.x * state.transform[2] + transformX;
const y = pos.y * state.transform[2] + transformY;
ctx.fillStyle = nodeColorFunc(n);
ctx.fillRect(
x * scaleFactor,
y * scaleFactor,
n.__rg.width * scaleFactor * state.transform[2],
n.__rg.height * scaleFactor * state.transform[2]
);
});
}, [canvasNode.current, nodePositions, state.transform, height]);
return ( return (
<canvas <rect
style={{ className="react-flow__minimap-node"
...baseStyle, x={x}
...style, y={y}
height, rx={borderRadius}
}} ry={borderRadius}
width={width} width={width}
height={height} height={height}
className={mapClasses} fill={fill}
ref={canvasNode}
/> />
); );
}; };
export default ({
style = { backgroundColor: '#f8f8f8' },
className,
nodeColor = '#ddd',
nodeBorderRadius = 5,
maskColor = 'rgba(10, 10, 10, .25)',
}: MiniMapProps) => {
const state = useStoreState(({ width, height, nodes, transform: [tX, tY, tScale] }) => ({
width,
height,
nodes,
tX,
tY,
tScale,
}));
const mapClasses = classnames('react-flow__minimap', className);
const elementWidth = (style.width || baseStyle.width)! as number;
const elementHeight = (style.height || baseStyle.height)! as number;
const nodeColorFunc = (nodeColor instanceof Function ? nodeColor : () => nodeColor) as StringFunc;
const hasNodes = state.nodes && state.nodes.length;
const bb = getRectOfNodes(state.nodes);
const viewBB: Rect = {
x: -state.tX / state.tScale,
y: -state.tY / state.tScale,
width: state.width / state.tScale,
height: state.height / state.tScale,
};
const boundingRect = hasNodes ? getBoundsofRects(bb, viewBB) : viewBB;
const scaledWidth = boundingRect.width / elementWidth;
const scaledHeight = boundingRect.height / elementHeight;
const viewScale = Math.max(scaledWidth, scaledHeight);
const viewWidth = viewScale * elementWidth;
const viewHeight = viewScale * elementHeight;
const offset = 5 * viewScale;
const x = boundingRect.x - (viewWidth - boundingRect.width) / 2 - offset;
const y = boundingRect.y - (viewHeight - boundingRect.height) / 2 - offset;
const width = viewWidth + offset * 2;
const height = viewHeight + offset * 2;
return (
<svg
width={elementWidth}
height={elementHeight}
viewBox={`${x} ${y} ${width} ${height}`}
style={{
...baseStyle,
...style,
}}
className={mapClasses}
>
{state.nodes.map(node => (
<MiniMapNode key={node.id} node={node} color={nodeColorFunc(node)} borderRadius={nodeBorderRadius} />
))}
<path
className="react-flow__minimap-mask"
d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z
M${viewBB.x},${viewBB.y}h${viewBB.width}v${viewBB.height}h${-viewBB.width}z`}
fill={maskColor}
fillRule="evenodd"
/>
</svg>
);
};
+2 -2
View File
@@ -3,9 +3,9 @@ import isEqual from 'fast-deep-equal';
import { Selection as D3Selection, ZoomBehavior } from 'd3'; import { Selection as D3Selection, ZoomBehavior } from 'd3';
import { import {
getBoundingBox,
getNodesInside, getNodesInside,
getConnectedEdges, getConnectedEdges,
getRectOfNodes,
} from '../utils/graph'; } from '../utils/graph';
import { import {
ElementId, ElementId,
@@ -200,7 +200,7 @@ const storeModel: StoreModel = {
selection, selection,
state.transform state.transform
); );
const selectedNodesBbox = getBoundingBox(selectedNodes); const selectedNodesBbox = getRectOfNodes(selectedNodes);
state.selection = selection; state.selection = selection;
state.nodesSelectionActive = true; state.nodesSelectionActive = true;
+6 -8
View File
@@ -29,9 +29,11 @@ export interface Dimensions {
height: number; height: number;
} }
export interface Rect extends Dimensions { export interface Rect extends Dimensions, XYPosition {}
x: number;
y: number; export interface Box extends XYPosition {
x2: number;
y2: number;
} }
export interface SelectionRect extends Rect { export interface SelectionRect extends Rect {
@@ -112,13 +114,9 @@ export type Connection = {
export type OnConnectFunc = (params: Connection) => void; export type OnConnectFunc = (params: Connection) => void;
export interface HandleElement { export interface HandleElement extends XYPosition, Dimensions {
id?: ElementId | null; id?: ElementId | null;
position: Position; position: Position;
x: number;
y: number;
width: number;
height: number;
} }
export interface EdgeCompProps { export interface EdgeCompProps {
+53 -96
View File
@@ -1,16 +1,7 @@
import { zoomIdentity } from 'd3-zoom'; import { zoomIdentity } from 'd3-zoom';
import store from '../store'; import store from '../store';
import { import { ElementId, Node, Edge, Elements, Transform, XYPosition, Rect, FitViewParams, Box } from '../types';
ElementId,
Node,
Edge,
Elements,
Transform,
XYPosition,
Rect,
FitViewParams,
} from '../types';
export const isEdge = (element: Node | Edge): boolean => export const isEdge = (element: Node | Edge): boolean =>
element.hasOwnProperty('source') && element.hasOwnProperty('target'); element.hasOwnProperty('source') && element.hasOwnProperty('target');
@@ -23,16 +14,11 @@ export const getOutgoers = (node: Node, elements: Elements): Elements => {
return []; return [];
} }
const outgoerIds = (elements as Edge[]) const outgoerIds = (elements as Edge[]).filter(e => e.source === node.id).map(e => e.target);
.filter(e => e.source === node.id)
.map(e => e.target);
return elements.filter(e => outgoerIds.includes(e.id)); return elements.filter(e => outgoerIds.includes(e.id));
}; };
export const removeElements = ( export const removeElements = (elementsToRemove: Elements, elements: Elements): Elements => {
elementsToRemove: Elements,
elements: Elements
): Elements => {
const nodeIdsToRemove = elementsToRemove.map(n => n.id); const nodeIdsToRemove = elementsToRemove.map(n => n.id);
return elements.filter(element => { return elements.filter(element => {
@@ -56,10 +42,7 @@ export const addEdge = (edgeParams: Edge, elements: Elements): Elements => {
return elements.concat({ return elements.concat({
...edgeParams, ...edgeParams,
id: id: typeof edgeParams.id !== 'undefined' ? edgeParams.id : getEdgeId(edgeParams),
typeof edgeParams.id !== 'undefined'
? edgeParams.id
: getEdgeId(edgeParams),
}); });
}; };
@@ -112,12 +95,7 @@ export const parseElement = (
id: nodeElement.id.toString(), id: nodeElement.id.toString(),
type: nodeElement.type || 'default', type: nodeElement.type || 'default',
__rg: { __rg: {
position: pointToRendererPoint( position: pointToRendererPoint(nodeElement.position, transform, snapToGrid, snapGrid),
nodeElement.position,
transform,
snapToGrid,
snapGrid
),
width: null, width: null,
height: null, height: null,
handleBounds: {}, handleBounds: {},
@@ -125,51 +103,41 @@ export const parseElement = (
}; };
}; };
export const getBoundingBox = (nodes: Node[]): Rect => { const getBoundsOfBoxes = (box1: Box, box2: Box): Box => ({
const bbox = nodes.reduce( x: Math.min(box1.x, box2.x),
(res, node) => { y: Math.min(box1.y, box2.y),
const { position } = node.__rg; x2: Math.max(box1.x2, box2.x2),
const x2 = position.x + node.__rg.width; y2: Math.max(box1.y2, box2.y2),
const y2 = position.y + node.__rg.height; });
if (position.x < res.minX) { const rectToBox = ({ x, y, width, height }: Rect): Box => ({
res.minX = position.x; x,
} y,
x2: x + width,
y2: y + height,
});
if (x2 > res.maxX) { const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({
res.maxX = x2; x,
} y,
width: x2 - x,
height: y2 - y,
});
if (position.y < res.minY) { export const getBoundsofRects = (rect1: Rect, rect2: Rect): Rect =>
res.minY = position.y; boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)));
}
if (y2 > res.maxY) { export const getRectOfNodes = (nodes: Node[]): Rect => {
res.maxY = y2; const box = nodes.reduce(
} (currBox, { __rg: { position, width, height } }) =>
getBoundsOfBoxes(currBox, rectToBox({ ...position, width, height })),
return res; { x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }
},
{
minX: Number.MAX_VALUE,
minY: Number.MAX_VALUE,
maxX: 0,
maxY: 0,
}
); );
return { return boxToRect(box);
x: bbox.minX,
y: bbox.minY,
width: bbox.maxX - bbox.minX,
height: bbox.maxY - bbox.minY,
};
}; };
export const graphPosToZoomedPos = ( export const graphPosToZoomedPos = (pos: XYPosition, transform: Transform): XYPosition => {
pos: XYPosition,
transform: Transform
): XYPosition => {
return { return {
x: pos.x * transform[2] + transform[0], x: pos.x * transform[2] + transform[0],
y: pos.y * transform[2] + transform[1], y: pos.y * transform[2] + transform[1],
@@ -178,29 +146,25 @@ export const graphPosToZoomedPos = (
export const getNodesInside = ( export const getNodesInside = (
nodes: Node[], nodes: Node[],
bbox: Rect, rect: Rect,
transform: Transform = [0, 0, 1], [tx, ty, tScale]: Transform = [0, 0, 1],
partially: boolean = false partially: boolean = false
): Node[] => { ): Node[] => {
return nodes.filter(n => { const rBox = rectToBox({
const bboxPos = { x: (rect.x - tx) / tScale,
x: (bbox.x - transform[0]) * (1 / transform[2]), y: (rect.y - ty) / tScale,
y: (bbox.y - transform[1]) * (1 / transform[2]), width: rect.width / tScale,
}; height: rect.height / tScale,
const bboxWidth = bbox.width * (1 / transform[2]); });
const bboxHeight = bbox.height * (1 / transform[2]); return nodes.filter(({ __rg: { position, width, height } }) => {
const { position, width, height } = n.__rg; const nBox = rectToBox({ ...position, width, height });
const nodeWidth = partially ? -width : width; const overlappingArea =
const nodeHeight = partially ? 0 : height; (Math.max(rBox.x, nBox.x) - Math.min(rBox.x2, nBox.x2)) * (Math.max(rBox.y, nBox.y) - Math.min(rBox.y2, nBox.y2));
const offsetX = partially ? width : 0; if (partially) {
const offsetY = partially ? height : 0; return overlappingArea > 0;
}
return ( const area = width * height;
position.x + offsetX > bboxPos.x && return overlappingArea === area;
position.x + nodeWidth < bboxPos.x + bboxWidth &&
(position.y + offsetY > bboxPos.y &&
position.y + nodeHeight < bboxPos.y + bboxHeight)
);
}); });
}; };
@@ -225,20 +189,13 @@ export const fitView = ({ padding }: FitViewParams = { padding: 0 }): void => {
return; return;
} }
const bounds = getBoundingBox(state.nodes); const bounds = getRectOfNodes(state.nodes);
const maxBoundsSize = Math.max(bounds.width, bounds.height); const maxBoundsSize = Math.max(bounds.width, bounds.height);
const k = const k = Math.min(state.width, state.height) / (maxBoundsSize + maxBoundsSize * padding);
Math.min(state.width, state.height) /
(maxBoundsSize + maxBoundsSize * padding);
const boundsCenterX = bounds.x + bounds.width / 2; const boundsCenterX = bounds.x + bounds.width / 2;
const boundsCenterY = bounds.y + bounds.height / 2; const boundsCenterY = bounds.y + bounds.height / 2;
const transform = [ const transform = [state.width / 2 - boundsCenterX * k, state.height / 2 - boundsCenterY * k];
state.width / 2 - boundsCenterX * k, const fittedTransform = zoomIdentity.translate(transform[0], transform[1]).scale(k);
state.height / 2 - boundsCenterY * k,
];
const fittedTransform = zoomIdentity
.translate(transform[0], transform[1])
.scale(k);
state.d3Selection.call(state.d3Zoom.transform, fittedTransform); state.d3Selection.call(state.d3Zoom.transform, fittedTransform);
}; };