feat(packages): add interactive minimap

This commit is contained in:
moklick
2022-10-09 19:55:25 +02:00
parent 4aa742f6f2
commit d057a1cd34
14 changed files with 527 additions and 49 deletions
@@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: ['@reactflow/eslint-config'],
};
+42
View File
@@ -0,0 +1,42 @@
# @reactflow/minimap
## 11.0.1
### Patch Changes
- Updated dependencies [[`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab), [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4)]:
- @reactflow/core@11.1.0
## 11.0.0
### Major Changes
- **Better [Accessibility](/docs/guides/accessibility)**
- Nodes and edges are focusable, selectable, moveable and deleteable with the keyboard.
- `aria-` default attributes for all elements and controllable via `ariaLabel` options
- Keyboard controls can be disabled with the new `disableKeyboardA11y` prop
- **Better selectable edges** via new edge option: `interactionWidth` - renders invisible edge that makes it easier to interact
- **Better routing for smoothstep and step edges**: https://twitter.com/reactflowdev/status/1567535405284614145
- **Nicer edge updating behaviour**: https://twitter.com/reactflowdev/status/1564966917517021184
- **Node origin**: The new `nodeOrigin` prop lets you control the origin of a node. Useful for layouting.
- **New background pattern**: `BackgroundVariant.Cross` variant
- **[`useOnViewportChange`](/docs/api/hooks/use-on-viewport-change) hook** - handle viewport changes within a component
- **[`useOnSelectionChange`](/docs/api/hooks/use-on-selection-change) hook** - handle selection changes within a component
- **[`useNodesInitialized`](/docs/api/hooks/use-nodes-initialized) hook** - returns true if all nodes are initialized and if there is more than one node
- **Deletable option** for Nodes and edges
- **New Event handlers**: `onPaneMouseEnter`, `onPaneMouseMove` and `onPaneMouseLeave`
- **Edge `pathOptions`** for `smoothstep` and `default` edges
- **Nicer cursor defaults**: Cursor is grabbing, while dragging a node or panning
- **Pane moveable** with middle mouse button
- **Pan over nodes** when they are not draggable (`draggable=false` or `nodesDraggable` false)
- **[`<BaseEdge />`](/docs/api/edges/base-edge) component** that makes it easier to build custom edges
- **[Separately installable packages](/docs/overview/packages/)**
- @reactflow/core
- @reactflow/background
- @reactflow/controls
- @reactflow/minimap
### Patch Changes
- Updated dependencies:
- @reactflow/core@11.0.0
+10
View File
@@ -0,0 +1,10 @@
# @reactflow/minimap
Mini map component for React Flow.
## Installation
```sh
npm install @reactflow/minimap
```
+65
View File
@@ -0,0 +1,65 @@
{
"name": "@reactflow/interactive-minimap",
"version": "0.0.1-alpha.0",
"description": "Interactive Minimap component for React Flow.",
"keywords": [
"react",
"node-based UI",
"graph",
"diagram",
"workflow",
"react-flow"
],
"files": [
"dist"
],
"source": "src/index.tsx",
"main": "dist/umd/index.js",
"module": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"sideEffects": false,
"publishConfig": {
"access": "public"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/wbkd/react-flow.git",
"directory": "packages/interactive-minimap"
},
"scripts": {
"dev": "concurrently \"rollup --config node:@reactflow/rollup-config --watch\" pnpm:css-watch",
"build": "rollup --config node:@reactflow/rollup-config --environment NODE_ENV:production && npm run css",
"css": "postcss src/*.css --config ../../tooling/postcss-config/postcss.config.js --dir dist",
"css-watch": "pnpm css --watch",
"lint": "eslint --ext .js,.jsx,.ts,.tsx src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@babel/runtime": "^7.18.9",
"@reactflow/core": "workspace:*",
"classcat": "^5.0.3",
"zustand": "^4.1.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
},
"devDependencies": {
"@reactflow/eslint-config": "workspace:^0.0.0",
"@reactflow/rollup-config": "workspace:*",
"@reactflow/tsconfig": "workspace:*",
"@types/node": "^18.7.16",
"@types/react": "^18.0.19",
"react": "^18.2.0",
"typescript": "^4.8.3"
},
"rollup": {
"globals": {
"zustand": "Zustand",
"zustand/shallow": "zustandShallow",
"classcat": "cc"
},
"name": "ReactFlowMinimap"
}
}
@@ -0,0 +1,121 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { memo, useEffect, useRef } from 'react';
import cc from 'classcat';
import shallow from 'zustand/shallow';
import { zoom, D3ZoomEvent } from 'd3-zoom';
import { select } from 'd3-selection';
import { useStore, getRectOfNodes, ReactFlowState, Rect, Panel, getBoundsOfRects } from '@reactflow/core';
import MiniMapNode from './MiniMapNode';
import { MiniMapProps, GetMiniMapNodeAttribute } from './types';
declare const window: any;
const defaultWidth = 200;
const defaultHeight = 150;
const selector = (s: ReactFlowState) => {
const nodes = Array.from(s.nodeInternals.values());
const viewBB: Rect = {
x: -s.transform[0] / s.transform[2],
y: -s.transform[1] / s.transform[2],
width: s.width / s.transform[2],
height: s.height / s.transform[2],
};
return {
nodes: nodes.filter((node) => !node.hidden && node.width && node.height),
viewBB,
boundingRect: nodes.length > 0 ? getBoundsOfRects(getRectOfNodes(nodes), viewBB) : viewBB,
rfId: s.rfId,
};
};
const getAttrFunction = (func: any): GetMiniMapNodeAttribute => (func instanceof Function ? func : () => func);
const ARIA_LABEL_KEY = 'react-flow__minimap-desc';
function MiniMap({
style,
className,
nodeStrokeColor = '#555',
nodeColor = '#fff',
nodeClassName = '',
nodeBorderRadius = 5,
nodeStrokeWidth = 2,
maskColor = 'rgb(240, 242, 243, 0.7)',
position = 'bottom-right',
}: MiniMapProps) {
const svg = useRef<SVGSVGElement>(null);
const { boundingRect, viewBB, nodes, rfId } = useStore(selector, shallow);
const elementWidth = (style?.width as number) ?? defaultWidth;
const elementHeight = (style?.height as number) ?? defaultHeight;
const nodeColorFunc = getAttrFunction(nodeColor);
const nodeStrokeColorFunc = getAttrFunction(nodeStrokeColor);
const nodeClassNameFunc = getAttrFunction(nodeClassName);
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;
const shapeRendering = typeof window === 'undefined' || !!window.chrome ? 'crispEdges' : 'geometricPrecision';
const labelledBy = `${ARIA_LABEL_KEY}-${rfId}`;
useEffect(() => {
const d3ZoomInstance = zoom();
const selection = select(svg.current as Element).call(d3ZoomInstance);
d3ZoomInstance.on('zoom', (event: D3ZoomEvent<HTMLDivElement, any>) => {
console.log(event);
});
}, []);
return (
<Panel position={position} style={style} className={cc(['react-flow__minimap', className])}>
<svg
width={elementWidth}
height={elementHeight}
viewBox={`${x} ${y} ${width} ${height}`}
role="img"
aria-labelledby={labelledBy}
ref={svg}
>
<title id={labelledBy}>React Flow mini map</title>
{nodes.map((node) => {
return (
<MiniMapNode
key={node.id}
x={node.positionAbsolute?.x ?? 0}
y={node.positionAbsolute?.y ?? 0}
width={node.width!}
height={node.height!}
style={node.style}
className={nodeClassNameFunc(node)}
color={nodeColorFunc(node)}
borderRadius={nodeBorderRadius}
strokeColor={nodeStrokeColorFunc(node)}
strokeWidth={nodeStrokeWidth}
shapeRendering={shapeRendering}
/>
);
})}
<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>
</Panel>
);
}
MiniMap.displayName = 'MiniMap';
export default memo(MiniMap);
@@ -0,0 +1,53 @@
import { memo, CSSProperties } from 'react';
import cc from 'classcat';
interface MiniMapNodeProps {
x: number;
y: number;
width: number;
height: number;
borderRadius: number;
className: string;
color: string;
shapeRendering: string;
strokeColor: string;
strokeWidth: number;
style?: CSSProperties;
}
const MiniMapNode = ({
x,
y,
width,
height,
style,
color,
strokeColor,
strokeWidth,
className,
borderRadius,
shapeRendering,
}: MiniMapNodeProps) => {
const { background, backgroundColor } = style || {};
const fill = (color || background || backgroundColor) as string;
return (
<rect
className={cc(['react-flow__minimap-node', className])}
x={x}
y={y}
rx={borderRadius}
ry={borderRadius}
width={width}
height={height}
fill={fill}
stroke={strokeColor}
strokeWidth={strokeWidth}
shapeRendering={shapeRendering}
/>
);
};
MiniMapNode.displayName = 'MiniMapNode';
export default memo(MiniMapNode);
@@ -0,0 +1,2 @@
export { default as MiniMap } from './MiniMap';
export * from './types';
@@ -0,0 +1,3 @@
.react-flow__minimap {
background-color: #fff;
}
+15
View File
@@ -0,0 +1,15 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { HTMLAttributes } from 'react';
import { Node, PanelPosition } from '@reactflow/core';
export type GetMiniMapNodeAttribute<NodeData = any> = (node: Node<NodeData>) => string;
export interface MiniMapProps<NodeData = any> extends HTMLAttributes<SVGSVGElement> {
nodeColor?: string | GetMiniMapNodeAttribute<NodeData>;
nodeStrokeColor?: string | GetMiniMapNodeAttribute<NodeData>;
nodeClassName?: string | GetMiniMapNodeAttribute<NodeData>;
nodeBorderRadius?: number;
nodeStrokeWidth?: number;
maskColor?: string;
position?: PanelPosition;
}
@@ -0,0 +1,6 @@
{
"extends": "@reactflow/tsconfig/react.json",
"display": "@reactflow/minimap",
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "dist"]
}