diff --git a/examples/vite-app/cypress/e2e/basic.cy.ts b/examples/vite-app/cypress/e2e/basic.cy.ts index a08ca021..fd4c107a 100644 --- a/examples/vite-app/cypress/e2e/basic.cy.ts +++ b/examples/vite-app/cypress/e2e/basic.cy.ts @@ -50,9 +50,9 @@ describe('Basic Flow Rendering', () => { cy.get('body') .type('{shift}', { release: false }) .wait(50) - .get('.react-flow__selectionpane') - .trigger('mousedown', 1000, 50, { which: 1, force: true }) - .trigger('mousemove', 1, 400, { which: 1 }) + .get('.react-flow__pane') + .trigger('mousedown', 1000, 50, { button: 0, force: true }) + .trigger('mousemove', 1, 400, { button: 0 }) .wait(50) .trigger('mouseup', 1, 200, { force: true }); @@ -70,9 +70,9 @@ describe('Basic Flow Rendering', () => { it('selects all nodes', () => { cy.get('body') .type('{shift}', { release: false }) - .get('.react-flow__selectionpane') - .trigger('mousedown', 'topRight', { which: 1, force: true }) - .trigger('mousemove', 'bottomLeft', { which: 1 }) + .get('.react-flow__pane') + .trigger('mousedown', 'topRight', { button: 0, force: true }) + .trigger('mousemove', 'bottomLeft', { button: 0 }) .wait(50) .trigger('mouseup', 'bottomLeft', { force: true }) .wait(50) @@ -140,7 +140,7 @@ describe('Basic Flow Rendering', () => { // https://github.com/cypress-io/cypress/issues/3441 cy.window().then((win) => { cy.get('.react-flow__pane') - .trigger('mousedown', 'topLeft', { which: 1, view: win }) + .trigger('mousedown', 'topLeft', { button: 0, view: win }) .trigger('mousemove', 'bottomLeft') .wait(50) .trigger('mouseup', { force: true, view: win }) diff --git a/examples/vite-app/cypress/e2e/controls.cy.ts b/examples/vite-app/cypress/e2e/controls.cy.ts index 74548f56..07d0548e 100644 --- a/examples/vite-app/cypress/e2e/controls.cy.ts +++ b/examples/vite-app/cypress/e2e/controls.cy.ts @@ -37,7 +37,7 @@ describe('Controls Testing', () => { // https://github.com/cypress-io/cypress/issues/3441 cy.window().then((win) => { cy.get('.react-flow__renderer') - .trigger('mousedown', 'topLeft', { which: 1, view: win }) + .trigger('mousedown', 'topLeft', { button: 0, view: win }) .trigger('mousemove', 10, 400) .wait(50) .trigger('mouseup', 10, 400, { force: true, view: win }) diff --git a/examples/vite-app/cypress/e2e/empty.cy.ts b/examples/vite-app/cypress/e2e/empty.cy.ts index 5f25dcaf..74cba86d 100644 --- a/examples/vite-app/cypress/e2e/empty.cy.ts +++ b/examples/vite-app/cypress/e2e/empty.cy.ts @@ -14,9 +14,9 @@ describe('Empty Flow Rendering', () => { cy.get('body') .type('{shift}', { release: false }) .wait(50) - .get('.react-flow__selectionpane') - .trigger('mousedown', 400, 50, { which: 1, force: true }) - .trigger('mousemove', 200, 200, { which: 1 }) + .get('.react-flow__pane') + .trigger('mousedown', 400, 50, { button: 0, force: true }) + .trigger('mousemove', 200, 200, { button: 0 }) .wait(50) .trigger('mouseup', 200, 200, { force: true }); diff --git a/examples/vite-app/cypress/e2e/figma.cy.ts b/examples/vite-app/cypress/e2e/figma.cy.ts new file mode 100644 index 00000000..e3c8563f --- /dev/null +++ b/examples/vite-app/cypress/e2e/figma.cy.ts @@ -0,0 +1,51 @@ +describe('Figma Flow UI', () => { + before(() => { + cy.visit('/figma'); + }); + + it('renders a flow with three nodes', () => { + cy.get('.react-flow__renderer'); + cy.get('.react-flow__node').should('have.length', 4); + cy.get('.react-flow__edge').should('have.length', 2); + cy.get('.react-flow__node').children('.react-flow__handle'); + }); + + it('renders a grid', () => { + cy.get('.react-flow__background'); + }); + + it('selects all nodes by drag', () => { + cy.window().then((win) => { + cy.get('.react-flow__pane') + .trigger('mousedown', 'topLeft', { button: 0, view: win }) + .trigger('mousemove', 'bottomRight', { force: true }) + .wait(50) + .trigger('mouseup', { force: true, view: win }) + .then(() => { + cy.get('.react-flow__node').should('have.class', 'selected'); + }); + }); + }); + + it('removes selection', () => { + cy.get('.react-flow__pane').click('topLeft'); + cy.get('.react-flow__node').should('not.have.class', 'selected'); + }); + + it('drags using right click', () => { + cy.window().then((win) => { + cy.get('.react-flow__node:last').isWithinViewport(); + cy.get('.react-flow__pane') + .trigger('mousedown', 'center', { button: 2, view: win }) + .trigger('mousemove', 'bottom', { force: true }) + .wait(50) + .trigger('mouseup', { force: true, view: win }) + .then(() => { + cy.get('.react-flow__node').should('not.have.class', 'selected'); + cy.get('.react-flow__node:last').isOutsideViewport(); + }); + }); + }); +}); + +export {}; diff --git a/examples/vite-app/cypress/e2e/interaction.cy.ts b/examples/vite-app/cypress/e2e/interaction.cy.ts index 625ecc57..1ad4bf2a 100644 --- a/examples/vite-app/cypress/e2e/interaction.cy.ts +++ b/examples/vite-app/cypress/e2e/interaction.cy.ts @@ -35,7 +35,18 @@ describe('Interaction Flow Rendering', () => { }); it('tries to do a selection', () => { - cy.get('body').type('{shift}', { release: false }).get('.react-flow__selectionpane').should('not.exist'); + cy.get('body') + .type('{shift}', { release: false }) + .wait(50) + .get('.react-flow__pane') + .trigger('mousedown', 1000, 50, { button: 0, force: true }) + .trigger('mousemove', 1, 400, { button: 0 }) + .wait(50) + .get('.react-flow__selection') + .should('not.exist'); + + cy.get('.react-flow__pane').trigger('mouseup', 1, 200, { force: true }); + cy.get('body').type('{shift}', { release: true }); }); diff --git a/examples/vite-app/cypress/e2e/minimap.cy.ts b/examples/vite-app/cypress/e2e/minimap.cy.ts index 46a5a819..0f0464bd 100644 --- a/examples/vite-app/cypress/e2e/minimap.cy.ts +++ b/examples/vite-app/cypress/e2e/minimap.cy.ts @@ -9,13 +9,12 @@ describe('Minimap Testing', () => { }); it('has same number of nodes as the pane', () => { - const paneNodes = Cypress.$('.react-flow__node').length; + cy.get('.react-flow__minimap-node').then(() => { + const paneNodes = Cypress.$('.react-flow__node').length; + const minimapNodes = Cypress.$('.react-flow__minimap-node').length; - cy.wait(200); - - const minimapNodes = Cypress.$('.react-flow__minimap-node').length; - - expect(paneNodes).equal(minimapNodes); + expect(paneNodes).equal(minimapNodes); + }); }); it('changes zoom level', () => { @@ -60,7 +59,7 @@ describe('Minimap Testing', () => { // https://github.com/cypress-io/cypress/issues/3441 cy.window().then((win) => { cy.get('.react-flow__pane') - .trigger('mousedown', 'topLeft', { which: 1, view: win }) + .trigger('mousedown', 'topLeft', { button: 0, view: win }) .trigger('mousemove', 'bottomLeft') .wait(50) .trigger('mouseup', { force: true, view: win }) diff --git a/examples/vite-app/cypress/support/commands.ts b/examples/vite-app/cypress/support/commands.ts index 14302409..e138e4cf 100644 --- a/examples/vite-app/cypress/support/commands.ts +++ b/examples/vite-app/cypress/support/commands.ts @@ -36,23 +36,25 @@ Cypress.Commands.add('zoomPane', (wheelDelta: number) => Cypress.Commands.add('isWithinViewport', { prevSubject: true }, (subject) => { const rect = subject[0].getBoundingClientRect(); - expect(rect.top).to.be.within(0, window.innerHeight); - expect(rect.right).to.be.within(0, window.innerWidth); - expect(rect.bottom).to.be.within(0, window.innerHeight); - expect(rect.left).to.be.within(0, window.innerWidth); + return cy.window().then((window) => { + expect(rect.top).to.be.within(0, window.innerHeight); + expect(rect.right).to.be.within(0, window.innerWidth); + expect(rect.bottom).to.be.within(0, window.innerHeight); + expect(rect.left).to.be.within(0, window.innerWidth); - return subject; + return subject; + }); }); Cypress.Commands.add('isOutsideViewport', { prevSubject: true }, (subject) => { const rect = subject[0].getBoundingClientRect(); - expect(rect.top).not.to.be.within(0, window.innerHeight); - expect(rect.right).not.to.be.within(0, window.innerWidth); - expect(rect.bottom).not.to.be.within(0, window.innerHeight); - expect(rect.left).not.to.be.within(0, window.innerWidth); + return cy.window().then((window) => { + expect(window.innerHeight < rect.top || rect.bottom < 0 || window.innerWidth < rect.left || rect.right < 0).to.be + .true; - return subject; + return subject; + }); }); export {}; diff --git a/examples/vite-app/package.json b/examples/vite-app/package.json index 2a05d338..7e88c874 100644 --- a/examples/vite-app/package.json +++ b/examples/vite-app/package.json @@ -13,7 +13,7 @@ "test-e2e": "start-server-and-test 'pnpm serve' http-get://localhost:3000 'pnpm test-e2e-cypress'" }, "dependencies": { - "@reactflow/node-resizer": "workspace:^1.0.0", + "@reactflow/node-resizer": "workspace:*", "classcat": "^5.0.3", "dagre": "^0.8.5", "localforage": "^1.10.0", diff --git a/examples/vite-app/src/App/index.tsx b/examples/vite-app/src/App/index.tsx index bb68c028..33347757 100644 --- a/examples/vite-app/src/App/index.tsx +++ b/examples/vite-app/src/App/index.tsx @@ -13,6 +13,7 @@ import Edges from '../examples/Edges'; import EdgeRenderer from '../examples/EdgeRenderer'; import EdgeTypes from '../examples/EdgeTypes'; import Empty from '../examples/Empty'; +import Figma from '../examples/Figma'; import FloatingEdges from '../examples/FloatingEdges'; import Hidden from '../examples/Hidden'; import Interaction from '../examples/Interaction'; @@ -120,6 +121,11 @@ const routes: IRoute[] = [ path: '/empty', component: Empty, }, + { + name: 'Figma', + path: '/figma', + component: Figma, + }, { name: 'Floating Edges', path: '/floating-edges', diff --git a/examples/vite-app/src/examples/Basic/index.tsx b/examples/vite-app/src/examples/Basic/index.tsx index dfba56ef..1197ef06 100644 --- a/examples/vite-app/src/examples/Basic/index.tsx +++ b/examples/vite-app/src/examples/Basic/index.tsx @@ -50,7 +50,7 @@ const initialEdges: Edge[] = [ const nodeOrigin: NodeOrigin = [0.5, 0.5]; -const defaultEdgeOptions = { zIndex: 0 }; +const defaultEdgeOptions = {}; const BasicFlow = () => { const instance = useReactFlow(); @@ -94,6 +94,8 @@ const BasicFlow = () => { fitView defaultEdgeOptions={defaultEdgeOptions} selectNodesOnDrag={false} + elevateEdgesOnSelect + elevateNodesOnSelect={false} // nodeOrigin={nodeOrigin} > diff --git a/examples/vite-app/src/examples/EdgeRenderer/CustomEdge.tsx b/examples/vite-app/src/examples/EdgeRenderer/CustomEdge.tsx index f7a42270..05d893ca 100644 --- a/examples/vite-app/src/examples/EdgeRenderer/CustomEdge.tsx +++ b/examples/vite-app/src/examples/EdgeRenderer/CustomEdge.tsx @@ -1,5 +1,5 @@ import { FC, MouseEvent } from 'react'; -import { EdgeProps, getBezierPath, EdgeLabelRenderer, useStore, ReactFlowStore } from 'reactflow'; +import { EdgeProps, getBezierPath, EdgeLabelRenderer, useStore } from 'reactflow'; const CustomEdge: FC = ({ id, @@ -14,7 +14,7 @@ const CustomEdge: FC = ({ data, }) => { const isConnectedNodeDragging = useStore((s) => - Array.from(s.nodeInternals.values()).find((n) => n.dragging && (target === n.id || source === n.id)) + s.getNodes().find((n) => n.dragging && (target === n.id || source === n.id)) ); const [edgePath, labelX, labelY] = getBezierPath({ diff --git a/examples/vite-app/src/examples/EdgeRenderer/CustomEdge2.tsx b/examples/vite-app/src/examples/EdgeRenderer/CustomEdge2.tsx index e0e8e794..ebdb1641 100644 --- a/examples/vite-app/src/examples/EdgeRenderer/CustomEdge2.tsx +++ b/examples/vite-app/src/examples/EdgeRenderer/CustomEdge2.tsx @@ -14,7 +14,7 @@ const CustomEdge: FC = ({ data, }) => { const isConnectedNodeDragging = useStore((s) => - Array.from(s.nodeInternals.values()).find((n) => n.dragging && (target === n.id || source === n.id)) + s.getNodes().find((n) => n.dragging && (target === n.id || source === n.id)) ); const [edgePath, labelX, labelY] = getBezierPath({ diff --git a/examples/vite-app/src/examples/Figma/index.tsx b/examples/vite-app/src/examples/Figma/index.tsx new file mode 100644 index 00000000..e1e20dc7 --- /dev/null +++ b/examples/vite-app/src/examples/Figma/index.tsx @@ -0,0 +1,44 @@ +import ReactFlow, { Background, BackgroundVariant, Node, Edge, SelectionMode } from 'reactflow'; + +const MULTI_SELECT_KEY = ['Meta', 'Shift']; + +const initialNodes: Node[] = [ + { id: '1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 }, className: 'light' }, + { id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 }, className: 'light' }, + { id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 }, className: 'light' }, + { id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 }, className: 'light' }, +]; + +const initialEdges: Edge[] = [ + { id: 'e1-2', source: '1', target: '2', animated: true }, + { id: 'e1-3', source: '1', target: '3' }, +]; + +const onPaneContextMenu = (e: any) => { + e.preventDefault(); + console.log('context menu'); +}; + +const panOnDrag = [1, 2]; + +const BasicFlow = () => { + return ( + + + + ); +}; + +export default BasicFlow; diff --git a/examples/vite-app/src/examples/NodeResizer/index.tsx b/examples/vite-app/src/examples/NodeResizer/index.tsx index 683f9ab5..68afe5df 100644 --- a/examples/vite-app/src/examples/NodeResizer/index.tsx +++ b/examples/vite-app/src/examples/NodeResizer/index.tsx @@ -1,4 +1,4 @@ -import { CSSProperties, useCallback, useState } from 'react'; +import { useCallback, useState } from 'react'; import ReactFlow, { Controls, addEdge, Position, Connection, useNodesState, useEdgesState, Panel } from 'reactflow'; import NodeResizerNode from './NodeResizerNode'; diff --git a/examples/vite-app/src/examples/NodeToolbar/SelectedNodesToolbar.tsx b/examples/vite-app/src/examples/NodeToolbar/SelectedNodesToolbar.tsx index 349db385..fa1697ae 100644 --- a/examples/vite-app/src/examples/NodeToolbar/SelectedNodesToolbar.tsx +++ b/examples/vite-app/src/examples/NodeToolbar/SelectedNodesToolbar.tsx @@ -1,7 +1,8 @@ import { NodeToolbar, ReactFlowState, useStore } from 'reactflow'; const selectedNodesSelector = (state: ReactFlowState) => - Array.from(state.nodeInternals.values()) + state + .getNodes() .filter((node) => node.selected) .map((node) => node.id); diff --git a/examples/vite-app/src/examples/Provider/Sidebar.tsx b/examples/vite-app/src/examples/Provider/Sidebar.tsx index 145ac718..a5205642 100644 --- a/examples/vite-app/src/examples/Provider/Sidebar.tsx +++ b/examples/vite-app/src/examples/Provider/Sidebar.tsx @@ -1,15 +1,16 @@ -import { useStore, useStoreApi } from 'reactflow'; +import { useReactFlow, useStore } from 'reactflow'; import styles from './provider.module.css'; const Sidebar = () => { - const store = useStoreApi(); - const nodeInternals = useStore((store) => store.nodeInternals); + const { setNodes } = useReactFlow(); + const nodeInfos = useStore((store) => + store.getNodes().map((n) => `Node ${n.id} - x: ${n.position.x.toFixed(2)}, y: ${n.position.y.toFixed(2)}`) + ); const transform = useStore((store) => store.transform); const selectAll = () => { - nodeInternals.forEach((node) => (node.selected = true)); - store.setState({ nodeInternals: new Map(nodeInternals) }); + setNodes((nodes) => nodes.map((n) => ({ ...n, selected: true }))); }; return ( @@ -22,10 +23,8 @@ const Sidebar = () => { [{transform[0].toFixed(2)}, {transform[1].toFixed(2)}, {transform[2].toFixed(2)}]
Nodes
- {Array.from(nodeInternals).map(([, node]) => ( -
- Node {node.id} - x: {node.position.x.toFixed(2)}, y: {node.position.y.toFixed(2)} -
+ {nodeInfos.map((info, index) => ( +
{info}
))}
diff --git a/examples/vite-app/src/examples/Subflow/index.tsx b/examples/vite-app/src/examples/Subflow/index.tsx index 55aea018..db021f52 100644 --- a/examples/vite-app/src/examples/Subflow/index.tsx +++ b/examples/vite-app/src/examples/Subflow/index.tsx @@ -11,7 +11,7 @@ import ReactFlow, { Controls, MiniMap, Background, - NodeOrigin, + Panel, } from 'reactflow'; import DebugNode from './DebugNode'; @@ -211,7 +211,7 @@ const Subflow = () => { -
+ @@ -225,7 +225,7 @@ const Subflow = () => { toggleChildNodes -
+ ); }; diff --git a/packages/background/CHANGELOG.md b/packages/background/CHANGELOG.md index bdbef9c7..dc6f8ceb 100644 --- a/packages/background/CHANGELOG.md +++ b/packages/background/CHANGELOG.md @@ -1,5 +1,33 @@ # @reactflow/background +## 11.1.0 + +### Patch Changes + +- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0 + +## 11.1.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) +- selection: do not include hidden nodes +- minimap: fix onNodeClick for nodes outside the viewport +- keys: allow multi select when input is focused + +### Patch Changes + +- Updated dependencies []: + - @reactflow/core@11.4.0-next.1 + +## 11.0.8-next.0 + +### Patch Changes + +- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0-next.0 + ## 11.0.7 ### Patch Changes diff --git a/packages/background/package.json b/packages/background/package.json index 5011906c..261af18e 100644 --- a/packages/background/package.json +++ b/packages/background/package.json @@ -1,6 +1,6 @@ { "name": "@reactflow/background", - "version": "11.0.7", + "version": "11.1.0", "description": "Background component with different variants for React Flow", "keywords": [ "react", diff --git a/packages/controls/CHANGELOG.md b/packages/controls/CHANGELOG.md index 9df35ad9..733c57cf 100644 --- a/packages/controls/CHANGELOG.md +++ b/packages/controls/CHANGELOG.md @@ -1,5 +1,33 @@ # @reactflow/controls +## 11.1.0 + +### Patch Changes + +- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0 + +## 11.1.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) +- selection: do not include hidden nodes +- minimap: fix onNodeClick for nodes outside the viewport +- keys: allow multi select when input is focused + +### Patch Changes + +- Updated dependencies []: + - @reactflow/core@11.4.0-next.1 + +## 11.0.8-next.0 + +### Patch Changes + +- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0-next.0 + ## 11.0.7 ### Patch Changes diff --git a/packages/controls/package.json b/packages/controls/package.json index 7458ee83..9253cf51 100644 --- a/packages/controls/package.json +++ b/packages/controls/package.json @@ -1,6 +1,6 @@ { "name": "@reactflow/controls", - "version": "11.0.7", + "version": "11.1.0", "description": "Component to control the viewport of a React Flow instance", "keywords": [ "react", diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index b0b48f29..df1aca10 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,69 @@ # @reactflow/core +## 11.4.0 + +## New Features + +New props for the ReactFlow component to customize the controls of the viewport and the selection box better: + +1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false}` or `panOnDrag={[1, 2]}`) +2. `panOnDrag={[0, 1, 2]}` option to configure specific mouse buttons for panning +3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`) +4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it +5. `onSelectionStart` and `onSelectionEnd` events +6. `elevateNodesOnSelect`: Defines if z-index should be increased when node is selected +7. New store function `getNodes`. You can now do `store.getState().getNodes()` instead of `Array.from(store.getNodes().nodeInternals.values())`. + +Thanks to @jackfishwick who helped a lot with the new panning and selection options. + +### Minor Changes + +- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) + - Add new props to configure viewport controls (`selectionOnDrag`, `panActivationKeyCode`, ..) +- [#2661](https://github.com/wbkd/react-flow/pull/2661) [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654) + - panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) + - selection: do not include hidden nodes + - minimap: fix onNodeClick for nodes outside the viewport + - keys: allow multi select when input is focused + +### Patch Changes + +- [#2695](https://github.com/wbkd/react-flow/pull/2695) [`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff) - Add elevateNodesOnSelect prop +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. +- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) - Use translateExtent correctly +- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) - Only trigger drag event when change happened + +## 11.4.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) +- selection: do not include hidden nodes +- minimap: fix onNodeClick for nodes outside the viewport +- keys: allow multi select when input is focused + +## 11.4.0-next.0 + +### Minor Changes + +- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features + + New props for the ReactFlow component to customize the controls of the viewport and the selection box better: + + 1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`) + 2. `panOnDrag="RightClick"` option + 3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`) + 4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it + 5. `onSelectionStart` and `onSelectionEnd` events + +### Patch Changes + +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. + +- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) Thanks [@moklick](https://github.com/moklick)! - Use translateExtent correctly + +- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) Thanks [@moklick](https://github.com/moklick)! - Only trigger drag event when change happened + ## 11.3.2 In this update we did some changes so that we could implement the new [``](https://reactflow.dev/docs/api/nodes/node-resizer/) component more smoothly. diff --git a/packages/core/package.json b/packages/core/package.json index 9bd0f67b..e1a9ea14 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@reactflow/core", - "version": "11.3.2", + "version": "11.4.0", "description": "Core components and util functions of React Flow.", "keywords": [ "react", diff --git a/packages/core/src/components/Edges/BaseEdge.tsx b/packages/core/src/components/Edges/BaseEdge.tsx index 71106854..ad7adcd8 100644 --- a/packages/core/src/components/Edges/BaseEdge.tsx +++ b/packages/core/src/components/Edges/BaseEdge.tsx @@ -1,5 +1,6 @@ import EdgeText from './EdgeText'; import type { BaseEdgeProps } from '../../types'; +import { isNumeric } from '../../utils'; const BaseEdge = ({ path, @@ -35,7 +36,7 @@ const BaseEdge = ({ className="react-flow__edge-interaction" /> )} - {label ? ( + {label && isNumeric(labelX) && isNumeric(labelY) ? ( ) => { return; } - const { snapGrid, snapToGrid } = store.getState(); - if (elementSelectionKeys.includes(event.key) && isSelectable) { const unselect = event.key === 'Escape'; if (unselect) { @@ -112,15 +110,10 @@ export default (NodeComponent: ComponentType) => { .toLowerCase()}. New position, x: ${~~xPos}, y: ${~~yPos}`, }); - // by default a node moves 5px on each key press, or 20px if shift is pressed - // if snap grid is enabled, we use that for the velocity. - const xVelo = snapToGrid ? snapGrid[0] : 5; - const yVelo = snapToGrid ? snapGrid[1] : 5; - const factor = event.shiftKey ? 4 : 1; - updatePositions({ - x: arrowKeyDiffs[event.key].x * xVelo * factor, - y: arrowKeyDiffs[event.key].y * yVelo * factor, + x: arrowKeyDiffs[event.key].x, + y: arrowKeyDiffs[event.key].y, + isShiftPressed: event.shiftKey, }); } }; diff --git a/packages/core/src/components/NodesSelection/index.tsx b/packages/core/src/components/NodesSelection/index.tsx index ed841db6..745a0550 100644 --- a/packages/core/src/components/NodesSelection/index.tsx +++ b/packages/core/src/components/NodesSelection/index.tsx @@ -27,7 +27,7 @@ const selector = (s: ReactFlowState) => ({ }); const bboxSelector = (s: ReactFlowState) => { - const selectedNodes = Array.from(s.nodeInternals.values()).filter((n) => n.selected); + const selectedNodes = s.getNodes().filter((n) => n.selected); return getRectOfNodes(selectedNodes, s.nodeOrigin); }; @@ -41,7 +41,9 @@ function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboar useEffect(() => { if (!disableKeyboardA11y) { - nodeRef.current?.focus(); + nodeRef.current?.focus({ + preventScroll: true, + }); } }, [disableKeyboardA11y]); @@ -55,14 +57,21 @@ function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboar const onContextMenu = onSelectionContextMenu ? (event: MouseEvent) => { - const selectedNodes = Array.from(store.getState().nodeInternals.values()).filter((n) => n.selected); + const selectedNodes = store + .getState() + .getNodes() + .filter((n) => n.selected); onSelectionContextMenu(event, selectedNodes); } : undefined; const onKeyDown = (event: KeyboardEvent) => { if (Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) { - updatePositions(arrowKeyDiffs[event.key]); + updatePositions({ + x: arrowKeyDiffs[event.key].x, + y: arrowKeyDiffs[event.key].y, + isShiftPressed: event.shiftKey, + }); } }; diff --git a/packages/core/src/components/SelectionListener/index.tsx b/packages/core/src/components/SelectionListener/index.tsx index 6177f53d..14c104fb 100644 --- a/packages/core/src/components/SelectionListener/index.tsx +++ b/packages/core/src/components/SelectionListener/index.tsx @@ -9,7 +9,7 @@ type SelectionListenerProps = { }; const selector = (s: ReactFlowState) => ({ - selectedNodes: Array.from(s.nodeInternals.values()).filter((n) => n.selected), + selectedNodes: s.getNodes().filter((n) => n.selected), selectedEdges: s.edges.filter((e) => e.selected), }); diff --git a/packages/core/src/components/StoreUpdater/index.tsx b/packages/core/src/components/StoreUpdater/index.tsx index 2f98a453..b784c5bd 100644 --- a/packages/core/src/components/StoreUpdater/index.tsx +++ b/packages/core/src/components/StoreUpdater/index.tsx @@ -44,6 +44,7 @@ type StoreUpdaterProps = Pick< | 'onSelectionDragStop' | 'noPanClassName' | 'nodeOrigin' + | 'elevateNodesOnSelect' > & { rfId: string }; const selector = (s: ReactFlowState) => ({ @@ -92,6 +93,7 @@ const StoreUpdater = ({ nodesConnectable, nodesFocusable, edgesFocusable, + elevateNodesOnSelect, minZoom, maxZoom, nodeExtent, @@ -151,6 +153,7 @@ const StoreUpdater = ({ useDirectStoreUpdater('nodesFocusable', nodesFocusable, store.setState); useDirectStoreUpdater('edgesFocusable', edgesFocusable, store.setState); useDirectStoreUpdater('elementsSelectable', elementsSelectable, store.setState); + useDirectStoreUpdater('elevateNodesOnSelect', elevateNodesOnSelect, store.setState); useDirectStoreUpdater('snapToGrid', snapToGrid, store.setState); useDirectStoreUpdater('snapGrid', snapGrid, store.setState); useDirectStoreUpdater('onNodesChange', onNodesChange, store.setState); diff --git a/packages/core/src/components/UserSelection/index.tsx b/packages/core/src/components/UserSelection/index.tsx index cbf1e830..34d16a36 100644 --- a/packages/core/src/components/UserSelection/index.tsx +++ b/packages/core/src/components/UserSelection/index.tsx @@ -1,163 +1,31 @@ -/** - * The user selection rectangle gets displayed when a user drags the mouse while pressing shift - */ - -import { memo, useState, useRef } from 'react'; import shallow from 'zustand/shallow'; -import { useStore, useStoreApi } from '../../hooks/useStore'; -import { getSelectionChanges } from '../../utils/changes'; -import { getConnectedEdges, getNodesInside } from '../../utils/graph'; -import type { XYPosition, ReactFlowState, NodeChange, EdgeChange, Rect } from '../../types'; - -type SelectionRect = Rect & { - startX: number; - startY: number; - draw: boolean; -}; - -type UserSelectionProps = { - selectionKeyPressed: boolean; -}; - -function getMousePosition(event: React.MouseEvent, containerBounds: DOMRect): XYPosition { - return { - x: event.clientX - containerBounds.left, - y: event.clientY - containerBounds.top, - }; -} +import { useStore } from '../../hooks/useStore'; +import type { ReactFlowState } from '../../types'; const selector = (s: ReactFlowState) => ({ userSelectionActive: s.userSelectionActive, - elementsSelectable: s.elementsSelectable, + userSelectionRect: s.userSelectionRect, }); -const initialRect: SelectionRect = { - startX: 0, - startY: 0, - x: 0, - y: 0, - width: 0, - height: 0, - draw: false, -}; +function UserSelection() { + const { userSelectionActive, userSelectionRect } = useStore(selector, shallow); + const showSelectionBox = userSelectionActive && userSelectionRect; -const UserSelection = memo(({ selectionKeyPressed }: UserSelectionProps) => { - const store = useStoreApi(); - const prevSelectedNodesCount = useRef(0); - const prevSelectedEdgesCount = useRef(0); - const containerBounds = useRef(); - const [userSelectionRect, setUserSelectionRect] = useState(initialRect); - const { userSelectionActive, elementsSelectable } = useStore(selector, shallow); - - const renderUserSelectionPane = userSelectionActive || selectionKeyPressed; - - if (!elementsSelectable || !renderUserSelectionPane) { + if (!showSelectionBox) { return null; } - const resetUserSelection = () => { - setUserSelectionRect(initialRect); - - store.setState({ userSelectionActive: false }); - - prevSelectedNodesCount.current = 0; - prevSelectedEdgesCount.current = 0; - }; - - const onMouseDown = (event: React.MouseEvent): void => { - const reactFlowNode = (event.target as Element).closest('.react-flow')!; - containerBounds.current = reactFlowNode.getBoundingClientRect(); - - const mousePos = getMousePosition(event, containerBounds.current!); - - setUserSelectionRect({ - width: 0, - height: 0, - startX: mousePos.x, - startY: mousePos.y, - x: mousePos.x, - y: mousePos.y, - draw: true, - }); - - store.setState({ userSelectionActive: true, nodesSelectionActive: false }); - }; - - const onMouseMove = (event: React.MouseEvent): void => { - if (!selectionKeyPressed || !userSelectionRect.draw || !containerBounds.current) { - return; - } - - const mousePos = getMousePosition(event, containerBounds.current!); - const startX = userSelectionRect.startX ?? 0; - const startY = userSelectionRect.startY ?? 0; - - const nextUserSelectRect = { - ...userSelectionRect, - x: mousePos.x < startX ? mousePos.x : startX, - y: mousePos.y < startY ? mousePos.y : startY, - width: Math.abs(mousePos.x - startX), - height: Math.abs(mousePos.y - startY), - }; - - const { nodeInternals, edges, transform, onNodesChange, onEdgesChange, nodeOrigin } = store.getState(); - const nodes = Array.from(nodeInternals.values()); - const selectedNodes = getNodesInside(nodeInternals, nextUserSelectRect, transform, false, true, nodeOrigin); - const selectedEdgeIds = getConnectedEdges(selectedNodes, edges).map((e) => e.id); - const selectedNodeIds = selectedNodes.map((n) => n.id); - - if (prevSelectedNodesCount.current !== selectedNodeIds.length) { - prevSelectedNodesCount.current = selectedNodeIds.length; - const changes = getSelectionChanges(nodes, selectedNodeIds) as NodeChange[]; - if (changes.length) { - onNodesChange?.(changes); - } - } - - if (prevSelectedEdgesCount.current !== selectedEdgeIds.length) { - prevSelectedEdgesCount.current = selectedEdgeIds.length; - const changes = getSelectionChanges(edges, selectedEdgeIds) as EdgeChange[]; - if (changes.length) { - onEdgesChange?.(changes); - } - } - - setUserSelectionRect(nextUserSelectRect); - }; - - const onMouseUp = () => { - store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 }); - resetUserSelection(); - }; - - const onMouseLeave = () => { - store.setState({ nodesSelectionActive: false }); - resetUserSelection(); - }; - return (
- {userSelectionRect.draw && ( -
- )} -
+ className="react-flow__selection react-flow__container" + style={{ + width: userSelectionRect.width, + height: userSelectionRect.height, + transform: `translate(${userSelectionRect.x}px, ${userSelectionRect.y}px)`, + }} + /> ); -}); - -UserSelection.displayName = 'UserSelection'; +} export default UserSelection; diff --git a/packages/core/src/container/FlowRenderer/Pane.tsx b/packages/core/src/container/FlowRenderer/Pane.tsx deleted file mode 100644 index 60502182..00000000 --- a/packages/core/src/container/FlowRenderer/Pane.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { MouseEvent } from 'react'; -import cc from 'classcat'; - -import { useStore } from '../../hooks/useStore'; -import { containerStyle } from '../../styles'; -import type { ReactFlowState } from '../../types'; -import type { FlowRendererProps } from '.'; - -type PaneProps = Pick & { - onMouseEnter?: (event: MouseEvent) => void; - onMouseMove?: (event: MouseEvent) => void; - onMouseLeave?: (event: MouseEvent) => void; -}; - -const selector = (s: ReactFlowState) => s.paneDragging; - -function Pane({ onClick, onMouseEnter, onMouseMove, onMouseLeave, onContextMenu, onWheel }: PaneProps) { - const dragging = useStore(selector); - - return ( -
- ); -} - -export default Pane; diff --git a/packages/core/src/container/FlowRenderer/index.tsx b/packages/core/src/container/FlowRenderer/index.tsx index e3faed9c..a8e9dc69 100644 --- a/packages/core/src/container/FlowRenderer/index.tsx +++ b/packages/core/src/container/FlowRenderer/index.tsx @@ -1,14 +1,13 @@ import { memo } from 'react'; -import type { ReactNode, WheelEvent, MouseEvent } from 'react'; +import type { ReactNode } from 'react'; -import { useStore, useStoreApi } from '../../hooks/useStore'; +import { useStore } from '../../hooks/useStore'; import useGlobalKeyHandler from '../../hooks/useGlobalKeyHandler'; import useKeyPress from '../../hooks/useKeyPress'; import { GraphViewProps } from '../GraphView'; import ZoomPane from '../ZoomPane'; -import UserSelection from '../../components/UserSelection'; +import Pane from '../Pane'; import NodesSelection from '../../components/NodesSelection'; -import Pane from './Pane'; import type { ReactFlowState } from '../../types'; export type FlowRendererProps = Omit< @@ -44,7 +43,12 @@ const FlowRenderer = ({ onMoveStart, onMoveEnd, selectionKeyCode, + selectionOnDrag, + selectionMode, + onSelectionStart, + onSelectionEnd, multiSelectionKeyCode, + panActivationKeyCode, zoomActivationKeyCode, elementsSelectable, zoomOnScroll, @@ -53,7 +57,7 @@ const FlowRenderer = ({ panOnScrollSpeed, panOnScrollMode, zoomOnDoubleClick, - panOnDrag, + panOnDrag: _panOnDrag, defaultViewport, translateExtent, minZoom, @@ -64,27 +68,21 @@ const FlowRenderer = ({ noPanClassName, disableKeyboardA11y, }: FlowRendererProps) => { - const store = useStoreApi(); const nodesSelectionActive = useStore(selector); const selectionKeyPressed = useKeyPress(selectionKeyCode); + const panActivationKeyPressed = useKeyPress(panActivationKeyCode); + + const panOnDrag = panActivationKeyPressed || _panOnDrag; + const isSelecting = selectionKeyPressed || (selectionOnDrag && panOnDrag !== true); useGlobalKeyHandler({ deleteKeyCode, multiSelectionKeyCode }); - const onClick = (event: MouseEvent) => { - onPaneClick?.(event); - store.getState().resetSelectedElements(); - store.setState({ nodesSelectionActive: false }); - }; - - const onContextMenu = onPaneContextMenu ? (event: MouseEvent) => onPaneContextMenu(event) : undefined; - const onWheel = onPaneScroll ? (event: WheelEvent) => onPaneScroll(event) : undefined; - return ( - {children} - - {nodesSelectionActive && ( - - )} + onSelectionStart={onSelectionStart} + onSelectionEnd={onSelectionEnd} + onPaneClick={onPaneClick} + onPaneMouseEnter={onPaneMouseEnter} + onPaneMouseMove={onPaneMouseMove} + onPaneMouseLeave={onPaneMouseLeave} + onPaneContextMenu={onPaneContextMenu} + onPaneScroll={onPaneScroll} + panOnDrag={panOnDrag} + isSelecting={!!isSelecting} + selectionMode={selectionMode} + > + {children} + {nodesSelectionActive && ( + + )} + ); }; diff --git a/packages/core/src/container/GraphView/index.tsx b/packages/core/src/container/GraphView/index.tsx index 3af02659..425d9180 100644 --- a/packages/core/src/container/GraphView/index.tsx +++ b/packages/core/src/container/GraphView/index.tsx @@ -51,12 +51,17 @@ const GraphView = ({ onNodeMouseLeave, onNodeContextMenu, onSelectionContextMenu, + onSelectionStart, + onSelectionEnd, connectionLineType, connectionLineStyle, connectionLineComponent, connectionLineContainerStyle, selectionKeyCode, + selectionOnDrag, + selectionMode, multiSelectionKeyCode, + panActivationKeyCode, zoomActivationKeyCode, deleteKeyCode, onlyRenderVisibleElements, @@ -110,7 +115,12 @@ const GraphView = ({ onPaneScroll={onPaneScroll} deleteKeyCode={deleteKeyCode} selectionKeyCode={selectionKeyCode} + selectionOnDrag={selectionOnDrag} + selectionMode={selectionMode} + onSelectionStart={onSelectionStart} + onSelectionEnd={onSelectionEnd} multiSelectionKeyCode={multiSelectionKeyCode} + panActivationKeyCode={panActivationKeyCode} zoomActivationKeyCode={zoomActivationKeyCode} elementsSelectable={elementsSelectable} onMove={onMove} diff --git a/packages/core/src/container/Pane/index.tsx b/packages/core/src/container/Pane/index.tsx new file mode 100644 index 00000000..755e0c04 --- /dev/null +++ b/packages/core/src/container/Pane/index.tsx @@ -0,0 +1,241 @@ +/** + * The user selection rectangle gets displayed when a user drags the mouse while pressing shift + */ + +import { memo, useRef, MouseEvent as ReactMouseEvent, ReactNode } from 'react'; +import shallow from 'zustand/shallow'; +import cc from 'classcat'; + +import UserSelection from '../../components/UserSelection'; +import { containerStyle } from '../../styles'; +import { useStore, useStoreApi } from '../../hooks/useStore'; +import { getSelectionChanges } from '../../utils/changes'; +import { getConnectedEdges, getNodesInside } from '../../utils/graph'; +import { SelectionMode } from '../../types'; +import type { ReactFlowProps, XYPosition, ReactFlowState, NodeChange, EdgeChange } from '../../types'; + +type PaneProps = { + isSelecting: boolean; + children: ReactNode; +} & Partial< + Pick< + ReactFlowProps, + | 'selectionMode' + | 'panOnDrag' + | 'onSelectionStart' + | 'onSelectionEnd' + | 'onPaneClick' + | 'onPaneContextMenu' + | 'onPaneScroll' + | 'onPaneMouseEnter' + | 'onPaneMouseMove' + | 'onPaneMouseLeave' + > +>; + +function getMousePosition(event: ReactMouseEvent, containerBounds: DOMRect): XYPosition { + return { + x: event.clientX - containerBounds.left, + y: event.clientY - containerBounds.top, + }; +} + +const wrapHandler = ( + handler: React.MouseEventHandler | undefined, + containerRef: React.MutableRefObject +): React.MouseEventHandler => { + return (event: ReactMouseEvent) => { + if (event.target !== containerRef.current) { + return; + } + handler?.(event); + }; +}; + +const selector = (s: ReactFlowState) => ({ + userSelectionActive: s.userSelectionActive, + elementsSelectable: s.elementsSelectable, + dragging: s.paneDragging, +}); + +const Pane = memo( + ({ + isSelecting, + selectionMode = SelectionMode.Full, + panOnDrag, + onSelectionStart, + onSelectionEnd, + onPaneClick, + onPaneContextMenu, + onPaneScroll, + onPaneMouseEnter, + onPaneMouseMove, + onPaneMouseLeave, + children, + }: PaneProps) => { + const container = useRef(null); + const store = useStoreApi(); + const prevSelectedNodesCount = useRef(0); + const prevSelectedEdgesCount = useRef(0); + const containerBounds = useRef(); + const { userSelectionActive, elementsSelectable, dragging } = useStore(selector, shallow); + + const resetUserSelection = () => { + store.setState({ userSelectionActive: false, userSelectionRect: null }); + + prevSelectedNodesCount.current = 0; + prevSelectedEdgesCount.current = 0; + }; + + const onClick = (event: ReactMouseEvent) => { + onPaneClick?.(event); + store.getState().resetSelectedElements(); + store.setState({ nodesSelectionActive: false }); + }; + + const onContextMenu = (event: ReactMouseEvent) => { + if (Array.isArray(panOnDrag) && panOnDrag?.includes(2)) { + event.preventDefault(); + return; + } + + onPaneContextMenu?.(event); + }; + + const onWheel = onPaneScroll ? (event: React.WheelEvent) => onPaneScroll(event) : undefined; + + const onMouseDown = (event: ReactMouseEvent): void => { + const { resetSelectedElements, domNode } = store.getState(); + containerBounds.current = domNode?.getBoundingClientRect(); + + if ( + !elementsSelectable || + !isSelecting || + event.button !== 0 || + event.target !== container.current || + !containerBounds.current + ) { + return; + } + + const { x, y } = getMousePosition(event, containerBounds.current); + + resetSelectedElements(); + + store.setState({ + userSelectionRect: { + width: 0, + height: 0, + startX: x, + startY: y, + x, + y, + }, + }); + + onSelectionStart?.(event); + }; + + const onMouseMove = (event: ReactMouseEvent): void => { + const { userSelectionRect, nodeInternals, edges, transform, onNodesChange, onEdgesChange, nodeOrigin, getNodes } = + store.getState(); + if (!isSelecting || !containerBounds.current || !userSelectionRect) { + return; + } + + store.setState({ userSelectionActive: true, nodesSelectionActive: false }); + + const mousePos = getMousePosition(event, containerBounds.current); + const startX = userSelectionRect.startX ?? 0; + const startY = userSelectionRect.startY ?? 0; + + const nextUserSelectRect = { + ...userSelectionRect, + x: mousePos.x < startX ? mousePos.x : startX, + y: mousePos.y < startY ? mousePos.y : startY, + width: Math.abs(mousePos.x - startX), + height: Math.abs(mousePos.y - startY), + }; + + const nodes = getNodes(); + const selectedNodes = getNodesInside( + nodeInternals, + nextUserSelectRect, + transform, + selectionMode === SelectionMode.Partial, + true, + nodeOrigin + ); + const selectedEdgeIds = getConnectedEdges(selectedNodes, edges).map((e) => e.id); + const selectedNodeIds = selectedNodes.map((n) => n.id); + + if (prevSelectedNodesCount.current !== selectedNodeIds.length) { + prevSelectedNodesCount.current = selectedNodeIds.length; + const changes = getSelectionChanges(nodes, selectedNodeIds) as NodeChange[]; + if (changes.length) { + onNodesChange?.(changes); + } + } + + if (prevSelectedEdgesCount.current !== selectedEdgeIds.length) { + prevSelectedEdgesCount.current = selectedEdgeIds.length; + const changes = getSelectionChanges(edges, selectedEdgeIds) as EdgeChange[]; + if (changes.length) { + onEdgesChange?.(changes); + } + } + + store.setState({ + userSelectionRect: nextUserSelectRect, + }); + }; + + const onMouseUp = (event: ReactMouseEvent) => { + const { userSelectionRect } = store.getState(); + // We only want to trigger click functions when in selection mode if + // the user did not move the mouse. + if (!userSelectionActive && userSelectionRect && event.target === container.current) { + onClick?.(event); + } + + store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 }); + + resetUserSelection(); + onSelectionEnd?.(event); + }; + + const onMouseLeave = (event: ReactMouseEvent) => { + if (userSelectionActive) { + store.setState({ nodesSelectionActive: prevSelectedNodesCount.current > 0 }); + onSelectionEnd?.(event); + } + + resetUserSelection(); + }; + + const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive); + + return ( +
+ {children} + +
+ ); + } +); + +Pane.displayName = 'Pane'; + +export default Pane; diff --git a/packages/core/src/container/ReactFlow/index.tsx b/packages/core/src/container/ReactFlow/index.tsx index c2748fa5..0afc251d 100644 --- a/packages/core/src/container/ReactFlow/index.tsx +++ b/packages/core/src/container/ReactFlow/index.tsx @@ -17,7 +17,7 @@ import GraphView from '../GraphView'; import Wrapper from './Wrapper'; import { infiniteExtent } from '../../store/initialState'; import { useNodeOrEdgeTypes } from './utils'; -import { ConnectionLineType, ConnectionMode, PanOnScrollMode } from '../../types'; +import { ConnectionLineType, ConnectionMode, PanOnScrollMode, SelectionMode } from '../../types'; import type { EdgeTypes, EdgeTypesWrapped, @@ -92,6 +92,8 @@ const ReactFlow = forwardRef( onSelectionDrag, onSelectionDragStop, onSelectionContextMenu, + onSelectionStart, + onSelectionEnd, connectionMode = ConnectionMode.Strict, connectionLineType = ConnectionLineType.Bezier, connectionLineStyle, @@ -99,6 +101,9 @@ const ReactFlow = forwardRef( connectionLineContainerStyle, deleteKeyCode = 'Backspace', selectionKeyCode = 'Shift', + selectionOnDrag = false, + selectionMode = SelectionMode.Full, + panActivationKeyCode = 'Space', multiSelectionKeyCode = 'Meta', zoomActivationKeyCode = 'Meta', snapToGrid = false, @@ -152,6 +157,7 @@ const ReactFlow = forwardRef( attributionPosition, proOptions, defaultEdgeOptions, + elevateNodesOnSelect = true, elevateEdgesOnSelect = false, disableKeyboardA11y = false, style, @@ -193,8 +199,11 @@ const ReactFlow = forwardRef( connectionLineComponent={connectionLineComponent} connectionLineContainerStyle={connectionLineContainerStyle} selectionKeyCode={selectionKeyCode} + selectionOnDrag={selectionOnDrag} + selectionMode={selectionMode} deleteKeyCode={deleteKeyCode} multiSelectionKeyCode={multiSelectionKeyCode} + panActivationKeyCode={panActivationKeyCode} zoomActivationKeyCode={zoomActivationKeyCode} onlyRenderVisibleElements={onlyRenderVisibleElements} selectNodesOnDrag={selectNodesOnDrag} @@ -217,6 +226,8 @@ const ReactFlow = forwardRef( onPaneScroll={onPaneScroll} onPaneContextMenu={onPaneContextMenu} onSelectionContextMenu={onSelectionContextMenu} + onSelectionStart={onSelectionStart} + onSelectionEnd={onSelectionEnd} onEdgeUpdate={onEdgeUpdate} onEdgeContextMenu={onEdgeContextMenu} onEdgeDoubleClick={onEdgeDoubleClick} @@ -251,6 +262,7 @@ const ReactFlow = forwardRef( nodesFocusable={nodesFocusable} edgesFocusable={edgesFocusable} elementsSelectable={elementsSelectable} + elevateNodesOnSelect={elevateNodesOnSelect} minZoom={minZoom} maxZoom={maxZoom} nodeExtent={nodeExtent} diff --git a/packages/core/src/container/ZoomPane/index.tsx b/packages/core/src/container/ZoomPane/index.tsx index f94bbe58..2099d9a1 100644 --- a/packages/core/src/container/ZoomPane/index.tsx +++ b/packages/core/src/container/ZoomPane/index.tsx @@ -5,19 +5,24 @@ import type { D3ZoomEvent } from 'd3-zoom'; import { select, pointer } from 'd3-selection'; import shallow from 'zustand/shallow'; -import { clamp } from '../../utils'; import useKeyPress from '../../hooks/useKeyPress'; import useResizeHandler from '../../hooks/useResizeHandler'; import { useStore, useStoreApi } from '../../hooks/useStore'; import { containerStyle } from '../../styles'; +import { clamp } from '../../utils'; +import { CoordinateExtent, PanOnScrollMode } from '../../types'; import type { FlowRendererProps } from '../FlowRenderer'; -import { PanOnScrollMode } from '../../types'; import type { Viewport, ReactFlowState } from '../../types'; type ZoomPaneProps = Omit< FlowRendererProps, - 'deleteKeyCode' | 'selectionKeyCode' | 'multiSelectionKeyCode' | 'noDragClassName' | 'disableKeyboardA11y' -> & { selectionKeyPressed: boolean }; + | 'deleteKeyCode' + | 'selectionKeyCode' + | 'multiSelectionKeyCode' + | 'noDragClassName' + | 'disableKeyboardA11y' + | 'selectionOnDrag' +>; const viewChanged = (prevViewport: Viewport, eventViewport: any): boolean => prevViewport.x !== eventViewport.x || prevViewport.y !== eventViewport.y || prevViewport.zoom !== eventViewport.k; @@ -30,23 +35,27 @@ const eventToFlowTransform = (eventViewport: any): Viewport => ({ const isWrappedWithClass = (event: any, className: string | undefined) => event.target.closest(`.${className}`); +const isRightClickPan = (panOnDrag: FlowRendererProps['panOnDrag'], usedButton: number) => + usedButton === 2 && Array.isArray(panOnDrag) && panOnDrag.includes(2); + const selector = (s: ReactFlowState) => ({ d3Zoom: s.d3Zoom, d3Selection: s.d3Selection, d3ZoomHandler: s.d3ZoomHandler, + userSelectionActive: s.userSelectionActive, }); const ZoomPane = ({ onMove, onMoveStart, onMoveEnd, + onPaneContextMenu, zoomOnScroll = true, zoomOnPinch = true, panOnScroll = false, panOnScrollSpeed = 0.5, panOnScrollMode = PanOnScrollMode.Free, zoomOnDoubleClick = true, - selectionKeyPressed, elementsSelectable, panOnDrag = true, defaultViewport, @@ -62,31 +71,36 @@ const ZoomPane = ({ const timerId = useRef>(); const store = useStoreApi(); const isZoomingOrPanning = useRef(false); + const zoomedWithRightMouseButton = useRef(false); const zoomPane = useRef(null); const prevTransform = useRef({ x: 0, y: 0, zoom: 0 }); - const { d3Zoom, d3Selection, d3ZoomHandler } = useStore(selector, shallow); + const { d3Zoom, d3Selection, d3ZoomHandler, userSelectionActive } = useStore(selector, shallow); const zoomActivationKeyPressed = useKeyPress(zoomActivationKeyCode); useResizeHandler(zoomPane); useEffect(() => { if (zoomPane.current) { + const bbox = zoomPane.current.getBoundingClientRect(); const d3ZoomInstance = zoom().scaleExtent([minZoom, maxZoom]).translateExtent(translateExtent); const selection = select(zoomPane.current as Element).call(d3ZoomInstance); + const updatedTransform = zoomIdentity + .translate(defaultViewport.x, defaultViewport.y) + .scale(clamp(defaultViewport.zoom, minZoom, maxZoom)); + const extent: CoordinateExtent = [ + [0, 0], + [bbox.width, bbox.height], + ]; - const clampedX = clamp(defaultViewport.x, translateExtent[0][0], translateExtent[1][0]); - const clampedY = clamp(defaultViewport.y, translateExtent[0][1], translateExtent[1][1]); - const clampedZoom = clamp(defaultViewport.zoom, minZoom, maxZoom); - const updatedTransform = zoomIdentity.translate(clampedX, clampedY).scale(clampedZoom); - - d3ZoomInstance.transform(selection, updatedTransform); + const constrainedTransform = d3ZoomInstance.constrain()(updatedTransform, extent, translateExtent); + d3ZoomInstance.transform(selection, constrainedTransform); store.setState({ d3Zoom: d3ZoomInstance, d3Selection: selection, d3ZoomHandler: selection.on('wheel.zoom'), // we need to pass transform because zoom handler is not registered when we set the initial transform - transform: [clampedX, clampedY, clampedZoom], + transform: [constrainedTransform.x, constrainedTransform.y, constrainedTransform.k], domNode: zoomPane.current.closest('.react-flow') as HTMLDivElement, }); } @@ -94,7 +108,7 @@ const ZoomPane = ({ useEffect(() => { if (d3Selection && d3Zoom) { - if (panOnScroll && !zoomActivationKeyPressed) { + if (panOnScroll && !zoomActivationKeyPressed && !userSelectionActive) { d3Selection.on('wheel.zoom', (event: any) => { if (isWrappedWithClass(event, noWheelClassName)) { return false; @@ -138,6 +152,7 @@ const ZoomPane = ({ } } }, [ + userSelectionActive, panOnScroll, panOnScrollMode, d3Selection, @@ -151,14 +166,17 @@ const ZoomPane = ({ useEffect(() => { if (d3Zoom) { - if (selectionKeyPressed && !isZoomingOrPanning.current) { + if (userSelectionActive && !isZoomingOrPanning.current) { d3Zoom.on('zoom', null); - } else if (!selectionKeyPressed) { + } else if (!userSelectionActive) { d3Zoom.on('zoom', (event: D3ZoomEvent) => { const { onViewportChange } = store.getState(); - store.setState({ transform: [event.transform.x, event.transform.y, event.transform.k] }); + zoomedWithRightMouseButton.current = !!( + onPaneContextMenu && isRightClickPan(panOnDrag, event.sourceEvent?.button) + ); + if (onMove || onViewportChange) { const flowTransform = eventToFlowTransform(event.transform); @@ -168,7 +186,7 @@ const ZoomPane = ({ }); } } - }, [selectionKeyPressed, d3Zoom, onMove]); + }, [userSelectionActive, d3Zoom, onMove, panOnDrag, onPaneContextMenu]); useEffect(() => { if (d3Zoom) { @@ -179,6 +197,7 @@ const ZoomPane = ({ const { onViewportChangeStart } = store.getState(); isZoomingOrPanning.current = true; + if (event.sourceEvent?.type === 'mousedown') { store.setState({ paneDragging: true }); } @@ -205,6 +224,15 @@ const ZoomPane = ({ isZoomingOrPanning.current = false; store.setState({ paneDragging: false }); + if ( + onPaneContextMenu && + isRightClickPan(panOnDrag, event.sourceEvent?.button) && + !zoomedWithRightMouseButton.current + ) { + onPaneContextMenu(event.sourceEvent); + } + zoomedWithRightMouseButton.current = false; + if ((onMoveEnd || onViewportChangeEnd) && viewChanged(prevTransform.current, event.transform)) { const flowTransform = eventToFlowTransform(event.transform); prevTransform.current = flowTransform; @@ -220,7 +248,7 @@ const ZoomPane = ({ } }); } - }, [d3Zoom, onMoveEnd, panOnScroll]); + }, [d3Zoom, panOnScroll, panOnDrag, onMoveEnd, onPaneContextMenu]); useEffect(() => { if (d3Zoom) { @@ -242,7 +270,7 @@ const ZoomPane = ({ } // during a selection we prevent all other interactions - if (selectionKeyPressed) { + if (userSelectionActive) { return false; } @@ -275,18 +303,31 @@ const ZoomPane = ({ return false; } + // if the pane is only movable using allowed clicks + if ( + Array.isArray(panOnDrag) && + !panOnDrag.includes(event.button) && + (event.type === 'mousedown' || event.type === 'touchstart') + ) { + return false; + } + + // We only allow right clicks if pan on drag is set to right click + const buttonAllowed = + (Array.isArray(panOnDrag) && panOnDrag.includes(event.button)) || !event.button || event.button <= 1; + // default filter for d3-zoom - return (!event.ctrlKey || event.type === 'wheel') && (!event.button || event.button <= 1); + return (!event.ctrlKey || event.type === 'wheel') && buttonAllowed; }); } }, [ + userSelectionActive, d3Zoom, zoomOnScroll, zoomOnPinch, panOnScroll, zoomOnDoubleClick, panOnDrag, - selectionKeyPressed, elementsSelectable, zoomActivationKeyPressed, ]); diff --git a/packages/core/src/hooks/useDrag/index.ts b/packages/core/src/hooks/useDrag/index.ts index 3ab1d0bb..7f1228a9 100644 --- a/packages/core/src/hooks/useDrag/index.ts +++ b/packages/core/src/hooks/useDrag/index.ts @@ -108,6 +108,9 @@ function useDrag({ x: pointerPos.xSnapped, y: pointerPos.ySnapped, }; + + let hasChange = false; + dragItems.current = dragItems.current.map((n) => { const nextPosition = { x: pointerPos.x - n.distance.x, y: pointerPos.y - n.distance.y }; @@ -118,12 +121,20 @@ function useDrag({ const updatedPos = calcNextPosition(n, nextPosition, nodeInternals, nodeExtent, nodeOrigin); + // we want to make sure that we only fire a change event when there is a changes + hasChange = + hasChange || n.position.x !== updatedPos.position.x || n.position.y !== updatedPos.position.y; + n.position = updatedPos.position; n.positionAbsolute = updatedPos.positionAbsolute; return n; }); + if (!hasChange) { + return; + } + const onDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag); updateNodePositions(dragItems.current, true, true); diff --git a/packages/core/src/hooks/useGlobalKeyHandler.ts b/packages/core/src/hooks/useGlobalKeyHandler.ts index f2b206e7..8665f6d0 100644 --- a/packages/core/src/hooks/useGlobalKeyHandler.ts +++ b/packages/core/src/hooks/useGlobalKeyHandler.ts @@ -18,11 +18,10 @@ export default ({ deleteKeyCode, multiSelectionKeyCode }: HookParams): void => { useEffect(() => { if (deleteKeyPressed) { - const { nodeInternals, edges } = store.getState(); - const nodes = Array.from(nodeInternals.values()); - const selectedNodes = nodes.filter((node) => node.selected); + const { edges, getNodes } = store.getState(); + const selectedNodes = getNodes().filter((node) => node.selected); const selectedEdges = edges.filter((edge) => edge.selected); - deleteElements({nodes: selectedNodes, edges: selectedEdges}); + deleteElements({ nodes: selectedNodes, edges: selectedEdges }); store.setState({ nodesSelectionActive: false }); } }, [deleteKeyPressed]); diff --git a/packages/core/src/hooks/useNodes.ts b/packages/core/src/hooks/useNodes.ts index 6a04942e..8681b4fd 100644 --- a/packages/core/src/hooks/useNodes.ts +++ b/packages/core/src/hooks/useNodes.ts @@ -1,7 +1,7 @@ import { useStore } from '../hooks/useStore'; import type { Node, ReactFlowState } from '../types'; -const nodesSelector = (state: ReactFlowState) => Array.from(state.nodeInternals.values()); +const nodesSelector = (state: ReactFlowState) => state.getNodes(); function useNodes(): Node[] { const nodes = useStore(nodesSelector); diff --git a/packages/core/src/hooks/useNodesInitialized.ts b/packages/core/src/hooks/useNodesInitialized.ts index f0ac25d2..45b14a33 100644 --- a/packages/core/src/hooks/useNodesInitialized.ts +++ b/packages/core/src/hooks/useNodesInitialized.ts @@ -7,7 +7,7 @@ const selector = (s: ReactFlowState) => { return false; } - return Array.from(s.nodeInternals.values()).every((n) => n[internalsSymbol]?.handleBounds !== undefined); + return s.getNodes().every((n) => n[internalsSymbol]?.handleBounds !== undefined); }; function useNodesInitialized(): boolean { diff --git a/packages/core/src/hooks/useReactFlow.ts b/packages/core/src/hooks/useReactFlow.ts index 0801a772..32666212 100644 --- a/packages/core/src/hooks/useReactFlow.ts +++ b/packages/core/src/hooks/useReactFlow.ts @@ -24,14 +24,14 @@ export default function useReactFlow(): ReactFlo const store = useStoreApi(); const getNodes = useCallback>(() => { - const { nodeInternals } = store.getState(); - const nodes = Array.from(nodeInternals.values()); - return nodes.map((n) => ({ ...n })); + return store + .getState() + .getNodes() + .map((n) => ({ ...n })); }, []); const getNode = useCallback>((id) => { - const { nodeInternals } = store.getState(); - return nodeInternals.get(id); + return store.getState().nodeInternals.get(id); }, []); const getEdges = useCallback>(() => { @@ -45,8 +45,8 @@ export default function useReactFlow(): ReactFlo }, []); const setNodes = useCallback>((payload) => { - const { nodeInternals, setNodes, hasDefaultNodes, onNodesChange } = store.getState(); - const nodes = Array.from(nodeInternals.values()); + const { getNodes, setNodes, hasDefaultNodes, onNodesChange } = store.getState(); + const nodes = getNodes(); const nextNodes = typeof payload === 'function' ? payload(nodes) : payload; if (hasDefaultNodes) { @@ -77,10 +77,10 @@ export default function useReactFlow(): ReactFlo const addNodes = useCallback>((payload) => { const nodes = Array.isArray(payload) ? payload : [payload]; - const { nodeInternals, setNodes, hasDefaultNodes, onNodesChange } = store.getState(); + const { getNodes, setNodes, hasDefaultNodes, onNodesChange } = store.getState(); if (hasDefaultNodes) { - const currentNodes = Array.from(nodeInternals.values()); + const currentNodes = getNodes(); const nextNodes = [...currentNodes, ...nodes]; setNodes(nextNodes); } else if (onNodesChange) { @@ -102,11 +102,10 @@ export default function useReactFlow(): ReactFlo }, []); const toObject = useCallback>(() => { - const { nodeInternals, edges = [], transform } = store.getState(); - const nodes = Array.from(nodeInternals.values()); + const { getNodes, edges = [], transform } = store.getState(); const [x, y, zoom] = transform; return { - nodes: nodes.map((n) => ({ ...n })), + nodes: getNodes().map((n) => ({ ...n })), edges: edges.map((e) => ({ ...e })), viewport: { x, @@ -119,6 +118,7 @@ export default function useReactFlow(): ReactFlo const deleteElements = useCallback(({ nodes: nodesDeleted, edges: edgesDeleted }) => { const { nodeInternals, + getNodes, edges, hasDefaultNodes, hasDefaultEdges, @@ -127,10 +127,9 @@ export default function useReactFlow(): ReactFlo onNodesChange, onEdgesChange, } = store.getState(); - const nodes = Array.from(nodeInternals.values()); const nodeIds = (nodesDeleted || []).map((node) => node.id); const edgeIds = (edgesDeleted || []).map((edge) => edge.id); - const nodesToRemove = nodes.reduce((res, node) => { + const nodesToRemove = getNodes().reduce((res, node) => { const parentHit = !nodeIds.includes(node.id) && node.parentNode && res.find((n) => n.id === node.parentNode); const deletable = typeof node.deletable === 'boolean' ? node.deletable : true; if (deletable && (nodeIds.includes(node.id) || parentHit)) { @@ -219,7 +218,7 @@ export default function useReactFlow(): ReactFlo return []; } - return (nodes || Array.from(store.getState().nodeInternals.values())).filter((n) => { + return (nodes || store.getState().getNodes()).filter((n) => { if (!isRect && (n.id === node!.id || !n.positionAbsolute)) { return false; } diff --git a/packages/core/src/hooks/useUpdateNodePositions.ts b/packages/core/src/hooks/useUpdateNodePositions.ts index eb5880e3..b20ea4d1 100644 --- a/packages/core/src/hooks/useUpdateNodePositions.ts +++ b/packages/core/src/hooks/useUpdateNodePositions.ts @@ -2,18 +2,25 @@ import { useCallback } from 'react'; import { useStoreApi } from '../hooks/useStore'; import { calcNextPosition } from './useDrag/utils'; -import type { XYPosition } from '../types'; function useUpdateNodePositions() { const store = useStoreApi(); - const updatePositions = useCallback((positionDiff: XYPosition) => { - const { nodeInternals, nodeExtent, updateNodePositions, snapToGrid, snapGrid } = store.getState(); - const selectedNodes = Array.from(nodeInternals.values()).filter((n) => n.selected); + const updatePositions = useCallback((params: { x: number; y: number; isShiftPressed: boolean }) => { + const { nodeInternals, nodeExtent, updateNodePositions, getNodes, snapToGrid, snapGrid } = store.getState(); + const selectedNodes = getNodes().filter((n) => n.selected); + // by default a node moves 5px on each key press, or 20px if shift is pressed + // if snap grid is enabled, we use that for the velocity. + const xVelo = snapToGrid ? snapGrid[0] : 5; + const yVelo = snapToGrid ? snapGrid[1] : 5; + const factor = params.isShiftPressed ? 4 : 1; + + const positionDiffX = params.x * xVelo * factor; + const positionDiffY = params.y * yVelo * factor; const nodeUpdates = selectedNodes.map((n) => { if (n.positionAbsolute) { - const nextPosition = { x: n.positionAbsolute.x + positionDiff.x, y: n.positionAbsolute.y + positionDiff.y }; + const nextPosition = { x: n.positionAbsolute.x + positionDiffX, y: n.positionAbsolute.y + positionDiffY }; if (snapToGrid) { nextPosition.x = snapGrid[0] * Math.round(nextPosition.x / snapGrid[0]); @@ -29,7 +36,7 @@ function useUpdateNodePositions() { return n; }); - updateNodePositions(nodeUpdates, true, true); + updateNodePositions(nodeUpdates, true, false); }, []); return updatePositions; diff --git a/packages/core/src/hooks/useVisibleNodes.ts b/packages/core/src/hooks/useVisibleNodes.ts index f74be159..b076b126 100644 --- a/packages/core/src/hooks/useVisibleNodes.ts +++ b/packages/core/src/hooks/useVisibleNodes.ts @@ -10,7 +10,7 @@ function useVisibleNodes(onlyRenderVisible: boolean) { (s: ReactFlowState) => onlyRenderVisible ? getNodesInside(s.nodeInternals, { x: 0, y: 0, width: s.width, height: s.height }, s.transform, true) - : Array.from(s.nodeInternals.values()), + : s.getNodes(), [onlyRenderVisible] ) ); diff --git a/packages/core/src/store/index.ts b/packages/core/src/store/index.ts index bdb02137..5ff9bf05 100644 --- a/packages/core/src/store/index.ts +++ b/packages/core/src/store/index.ts @@ -24,8 +24,11 @@ const createRFStore = () => createStore((set, get) => ({ ...initialState, setNodes: (nodes: Node[]) => { - const { nodeInternals, nodeOrigin } = get(); - set({ nodeInternals: createNodeInternals(nodes, nodeInternals, nodeOrigin) }); + const { nodeInternals, nodeOrigin, elevateNodesOnSelect } = get(); + set({ nodeInternals: createNodeInternals(nodes, nodeInternals, nodeOrigin, elevateNodesOnSelect) }); + }, + getNodes: () => { + return Array.from(get().nodeInternals.values()); }, setEdges: (edges: Edge[]) => { const { defaultEdgeOptions = {} } = get(); @@ -35,7 +38,9 @@ const createRFStore = () => const hasDefaultNodes = typeof nodes !== 'undefined'; const hasDefaultEdges = typeof edges !== 'undefined'; - const nodeInternals = hasDefaultNodes ? createNodeInternals(nodes, new Map(), get().nodeOrigin) : new Map(); + const nodeInternals = hasDefaultNodes + ? createNodeInternals(nodes, new Map(), get().nodeOrigin, get().elevateNodesOnSelect) + : new Map(); const nextEdges = hasDefaultEdges ? edges : []; set({ nodeInternals, edges: nextEdges, hasDefaultNodes, hasDefaultEdges }); @@ -125,12 +130,12 @@ const createRFStore = () => }, triggerNodeChanges: (changes: NodeChange[]) => { - const { onNodesChange, nodeInternals, hasDefaultNodes, nodeOrigin } = get(); + const { onNodesChange, nodeInternals, hasDefaultNodes, nodeOrigin, getNodes, elevateNodesOnSelect } = get(); if (changes?.length) { if (hasDefaultNodes) { - const nodes = applyNodeChanges(changes, Array.from(nodeInternals.values())); - const nextNodeInternals = createNodeInternals(nodes, nodeInternals, nodeOrigin); + const nodes = applyNodeChanges(changes, getNodes()); + const nextNodeInternals = createNodeInternals(nodes, nodeInternals, nodeOrigin, elevateNodesOnSelect); set({ nodeInternals: nextNodeInternals }); } @@ -139,14 +144,14 @@ const createRFStore = () => }, addSelectedNodes: (selectedNodeIds: string[]) => { - const { multiSelectionActive, nodeInternals, edges } = get(); + const { multiSelectionActive, edges, getNodes } = get(); let changedNodes: NodeSelectionChange[]; let changedEdges: EdgeSelectionChange[] | null = null; if (multiSelectionActive) { changedNodes = selectedNodeIds.map((nodeId) => createSelectionChange(nodeId, true)) as NodeSelectionChange[]; } else { - changedNodes = getSelectionChanges(Array.from(nodeInternals.values()), selectedNodeIds); + changedNodes = getSelectionChanges(getNodes(), selectedNodeIds); changedEdges = getSelectionChanges(edges, []); } @@ -158,7 +163,7 @@ const createRFStore = () => }); }, addSelectedEdges: (selectedEdgeIds: string[]) => { - const { multiSelectionActive, edges, nodeInternals } = get(); + const { multiSelectionActive, edges, getNodes } = get(); let changedEdges: EdgeSelectionChange[]; let changedNodes: NodeSelectionChange[] | null = null; @@ -166,7 +171,7 @@ const createRFStore = () => changedEdges = selectedEdgeIds.map((edgeId) => createSelectionChange(edgeId, true)) as EdgeSelectionChange[]; } else { changedEdges = getSelectionChanges(edges, selectedEdgeIds); - changedNodes = getSelectionChanges(Array.from(nodeInternals.values()), []); + changedNodes = getSelectionChanges(getNodes(), []); } updateNodesAndEdgesSelections({ @@ -177,8 +182,8 @@ const createRFStore = () => }); }, unselectNodesAndEdges: ({ nodes, edges }: UnselectNodesAndEdgesParams = {}) => { - const { nodeInternals, edges: storeEdges } = get(); - const nodesToUnselect = nodes ? nodes : Array.from(nodeInternals.values()); + const { edges: storeEdges, getNodes } = get(); + const nodesToUnselect = nodes ? nodes : getNodes(); const edgesToUnselect = edges ? edges : storeEdges; const changedNodes = nodesToUnselect.map((n) => { @@ -209,14 +214,13 @@ const createRFStore = () => set({ maxZoom }); }, setTranslateExtent: (translateExtent: CoordinateExtent) => { - const { d3Zoom } = get(); - d3Zoom?.translateExtent(translateExtent); + get().d3Zoom?.translateExtent(translateExtent); set({ translateExtent }); }, resetSelectedElements: () => { - const { nodeInternals, edges } = get(); - const nodes = Array.from(nodeInternals.values()); + const { edges, getNodes } = get(); + const nodes = getNodes(); const nodesToUnselect = nodes .filter((e) => e.selected) diff --git a/packages/core/src/store/initialState.ts b/packages/core/src/store/initialState.ts index ab918e65..f8cc369d 100644 --- a/packages/core/src/store/initialState.ts +++ b/packages/core/src/store/initialState.ts @@ -26,6 +26,7 @@ const initialState: ReactFlowStore = { nodeExtent: infiniteExtent, nodesSelectionActive: false, userSelectionActive: false, + userSelectionRect: null, connectionNodeId: null, connectionHandleId: null, connectionHandleType: 'source', @@ -44,6 +45,7 @@ const initialState: ReactFlowStore = { nodesFocusable: true, edgesFocusable: true, elementsSelectable: true, + elevateNodesOnSelect: true, fitViewOnInit: false, fitViewOnInitDone: false, fitViewOnInitOptions: undefined, diff --git a/packages/core/src/store/utils.ts b/packages/core/src/store/utils.ts index 02a4516b..0224e656 100644 --- a/packages/core/src/store/utils.ts +++ b/packages/core/src/store/utils.ts @@ -46,13 +46,15 @@ function calculateXYZPosition( export function createNodeInternals( nodes: Node[], nodeInternals: NodeInternals, - nodeOrigin: NodeOrigin + nodeOrigin: NodeOrigin, + elevateNodesOnSelect: boolean ): NodeInternals { const nextNodeInternals = new Map(); const parentNodes: ParentNodes = {}; + const selectedNodeZ: number = elevateNodesOnSelect ? 1000 : 0; nodes.forEach((node) => { - const z = (isNumeric(node.zIndex) ? node.zIndex : 0) + (node.selected ? 1000 : 0); + const z = (isNumeric(node.zIndex) ? node.zIndex : 0) + (node.selected ? selectedNodeZ : 0); const currInternals = nodeInternals.get(node.id); const internals: Node = { @@ -120,7 +122,7 @@ type InternalFitViewOptions = { export function fitView(get: StoreApi['getState'], options: InternalFitViewOptions = {}) { const { - nodeInternals, + getNodes, width, height, minZoom, @@ -134,9 +136,7 @@ export function fitView(get: StoreApi['getState'], options: Inte if ((options.initial && !fitViewOnInitDone && fitViewOnInit) || !options.initial) { if (d3Zoom && d3Selection) { - const nodes = Array.from(nodeInternals.values()).filter((n) => - options.includeHiddenNodes ? n.width && n.height : !n.hidden - ); + const nodes = getNodes().filter((n) => (options.includeHiddenNodes ? n.width && n.height : !n.hidden)); const nodesInitialized = nodes.every((n) => n.width && n.height); diff --git a/packages/core/src/styles/init.css b/packages/core/src/styles/init.css index a500c17d..a621794f 100644 --- a/packages/core/src/styles/init.css +++ b/packages/core/src/styles/init.css @@ -11,6 +11,10 @@ z-index: 1; cursor: grab; + &.selection { + cursor: pointer; + } + &.dragging { cursor: grabbing; } @@ -26,8 +30,8 @@ z-index: 4; } -.react-flow__selectionpane { - z-index: 5; +.react-flow__selection { + z-index: 6; } .react-flow__nodesselection-rect:focus, diff --git a/packages/core/src/types/component-props.ts b/packages/core/src/types/component-props.ts index 9b273641..0441ecdf 100644 --- a/packages/core/src/types/component-props.ts +++ b/packages/core/src/types/component-props.ts @@ -35,6 +35,7 @@ import type { NodeOrigin, EdgeMouseHandler, HandleType, + SelectionMode, } from '.'; export type ReactFlowProps = HTMLAttributes & { @@ -68,6 +69,8 @@ export type ReactFlowProps = HTMLAttributes & { onSelectionDragStart?: SelectionDragHandler; onSelectionDrag?: SelectionDragHandler; onSelectionDragStop?: SelectionDragHandler; + onSelectionStart?: (event: ReactMouseEvent) => void; + onSelectionEnd?: (event: ReactMouseEvent) => void; onSelectionContextMenu?: (event: ReactMouseEvent, nodes: Node[]) => void; onConnect?: OnConnect; onConnectStart?: OnConnectStart; @@ -94,6 +97,9 @@ export type ReactFlowProps = HTMLAttributes & { connectionMode?: ConnectionMode; deleteKeyCode?: KeyCode | null; selectionKeyCode?: KeyCode | null; + selectionOnDrag?: boolean; + selectionMode?: SelectionMode; + panActivationKeyCode?: KeyCode | null; multiSelectionKeyCode?: KeyCode | null; zoomActivationKeyCode?: KeyCode | null; snapToGrid?: boolean; @@ -107,7 +113,7 @@ export type ReactFlowProps = HTMLAttributes & { initNodeOrigin?: NodeOrigin; elementsSelectable?: boolean; selectNodesOnDrag?: boolean; - panOnDrag?: boolean; + panOnDrag?: boolean | number[]; minZoom?: number; maxZoom?: number; defaultViewport?: Viewport; @@ -130,6 +136,7 @@ export type ReactFlowProps = HTMLAttributes & { connectOnClick?: boolean; attributionPosition?: PanelPosition; proOptions?: ProOptions; + elevateNodesOnSelect?: boolean; elevateEdgesOnSelect?: boolean; disableKeyboardA11y?: boolean; }; diff --git a/packages/core/src/types/edges.ts b/packages/core/src/types/edges.ts index 7eb12816..92e10637 100644 --- a/packages/core/src/types/edges.ts +++ b/packages/core/src/types/edges.ts @@ -117,8 +117,8 @@ export type EdgeProps = Pick< export type BaseEdgeProps = Pick & EdgeLabelOptions & { - labelX: number; - labelY: number; + labelX?: number; + labelY?: number; path: string; }; diff --git a/packages/core/src/types/general.ts b/packages/core/src/types/general.ts index 472df101..9d60e839 100644 --- a/packages/core/src/types/general.ts +++ b/packages/core/src/types/general.ts @@ -3,7 +3,7 @@ import type { MouseEvent as ReactMouseEvent, ComponentType, MemoExoticComponent import type { D3DragEvent, Selection as D3Selection, SubjectPosition, ZoomBehavior } from 'd3'; import type { XYPosition, Rect, Transform, CoordinateExtent } from './utils'; -import type { NodeChange, EdgeChange, NodePositionChange } from './changes'; +import type { NodeChange, EdgeChange } from './changes'; import type { Node, NodeInternals, @@ -155,6 +155,7 @@ export type ReactFlowStore = { nodesSelectionActive: boolean; userSelectionActive: boolean; + userSelectionRect: SelectionRect | null; connectionNodeId: string | null; connectionHandleId: string | null; @@ -170,6 +171,7 @@ export type ReactFlowStore = { nodesFocusable: boolean; edgesFocusable: boolean; elementsSelectable: boolean; + elevateNodesOnSelect: boolean; multiSelectionActive: boolean; @@ -212,6 +214,7 @@ export type ReactFlowStore = { export type ReactFlowActions = { setNodes: (nodes: Node[]) => void; + getNodes: () => Node[]; setEdges: (edges: Edge[]) => void; setDefaultNodesAndEdges: (nodes?: Node[], edges?: Edge[]) => void; updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void; @@ -248,3 +251,13 @@ export type ProOptions = { }; export type UseDragEvent = D3DragEvent; + +export enum SelectionMode { + Partial = 'partial', + Full = 'full', +} + +export type SelectionRect = Rect & { + startX: number; + startY: number; +}; diff --git a/packages/core/src/utils/graph.ts b/packages/core/src/utils/graph.ts index 9a3d4c42..846050f5 100644 --- a/packages/core/src/utils/graph.ts +++ b/packages/core/src/utils/graph.ts @@ -218,9 +218,9 @@ export const getNodesInside = ( const visibleNodes: Node[] = []; nodeInternals.forEach((node) => { - const { width, height, selectable = true } = node; + const { width, height, selectable = true, hidden = false } = node; - if (excludeNonSelectableNodes && !selectable) { + if ((excludeNonSelectableNodes && !selectable) || hidden) { return false; } diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index f6e9d994..85220467 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -79,6 +79,12 @@ export function isInputDOMNode(event: KeyboardEvent | ReactKeyboardEvent): boole // using composed path for handling shadow dom const target = (kbEvent.composedPath?.()?.[0] || event.target) as HTMLElement; + // we want to be able to do a multi selection event if we are in an input field + if (event.ctrlKey || event.metaKey || event.shiftKey) { + return false; + } + + // when an input field is focused we don't want to trigger deletion or movement of nodes return ( ['INPUT', 'SELECT', 'TEXTAREA'].includes(target?.nodeName) || target?.hasAttribute('contenteditable') || diff --git a/packages/minimap/CHANGELOG.md b/packages/minimap/CHANGELOG.md index a98b4072..b8a1cced 100644 --- a/packages/minimap/CHANGELOG.md +++ b/packages/minimap/CHANGELOG.md @@ -1,5 +1,52 @@ # @reactflow/minimap +## 11.3.0 + +### Patch Changes + +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. +- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) - Use translateExtent correctly + +- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0 + +## 11.3.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) +- selection: do not include hidden nodes +- minimap: fix onNodeClick for nodes outside the viewport +- keys: allow multi select when input is focused + +### Patch Changes + +- Updated dependencies []: + - @reactflow/core@11.4.0-next.1 + +## 11.3.0-next.0 + +### Minor Changes + +- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features + + New props for the ReactFlow component to customize the controls of the viewport and the selection box better: + + 1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`) + 2. `panOnDrag="RightClick"` option + 3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`) + 4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it + 5. `onSelectionStart` and `onSelectionEnd` events + +### Patch Changes + +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. + +- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) Thanks [@moklick](https://github.com/moklick)! - Use translateExtent correctly + +- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0-next.0 + ## 11.2.3 ### Patch Changes diff --git a/packages/minimap/package.json b/packages/minimap/package.json index ce4db650..239002d1 100644 --- a/packages/minimap/package.json +++ b/packages/minimap/package.json @@ -1,6 +1,6 @@ { "name": "@reactflow/minimap", - "version": "11.2.3", + "version": "11.3.0", "description": "Minimap component for React Flow.", "keywords": [ "react", diff --git a/packages/minimap/src/MiniMap.tsx b/packages/minimap/src/MiniMap.tsx index b1d4c555..2aaf7334 100644 --- a/packages/minimap/src/MiniMap.tsx +++ b/packages/minimap/src/MiniMap.tsx @@ -14,6 +14,7 @@ import { getBoundsOfRects, useStoreApi, getNodePositionWithOrigin, + CoordinateExtent, } from '@reactflow/core'; import type { ReactFlowState, Rect } from '@reactflow/core'; @@ -26,7 +27,7 @@ const defaultWidth = 200; const defaultHeight = 150; const selector = (s: ReactFlowState) => { - const nodes = Array.from(s.nodeInternals.values()); + const nodes = s.getNodes(); const viewBB: Rect = { x: -s.transform[0] / s.transform[2], y: -s.transform[1] / s.transform[2], @@ -109,7 +110,7 @@ function MiniMap({ }; const panHandler = (event: D3ZoomEvent) => { - const { transform, d3Selection, d3Zoom } = store.getState(); + const { transform, d3Selection, d3Zoom, translateExtent, width, height } = store.getState(); if (event.sourceEvent.type !== 'mousemove' || !d3Selection || !d3Zoom) { return; @@ -120,10 +121,15 @@ function MiniMap({ x: transform[0] - event.sourceEvent.movementX * viewScaleRef.current * Math.max(1, transform[2]), y: transform[1] - event.sourceEvent.movementY * viewScaleRef.current * Math.max(1, transform[2]), }; + const extent: CoordinateExtent = [ + [0, 0], + [width, height], + ]; const nextTransform = zoomIdentity.translate(position.x, position.y).scale(transform[2]); + const constrainedTransform = d3Zoom.constrain()(nextTransform, extent, translateExtent); - d3Zoom.transform(d3Selection, nextTransform); + d3Zoom.transform(d3Selection, constrainedTransform); }; const zoomAndPanHandler = zoom() @@ -196,6 +202,7 @@ function MiniMap({ fillRule="evenodd" stroke={maskStrokeColor} strokeWidth={maskStrokeWidth} + pointerEvents="none" /> diff --git a/packages/node-resizer/CHANGELOG.md b/packages/node-resizer/CHANGELOG.md index a996183c..f0ff29d2 100644 --- a/packages/node-resizer/CHANGELOG.md +++ b/packages/node-resizer/CHANGELOG.md @@ -1,5 +1,33 @@ # @reactflow/node-resizer +## 1.2.0 + +### Patch Changes + +- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0 + +## 1.2.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) +- selection: do not include hidden nodes +- minimap: fix onNodeClick for nodes outside the viewport +- keys: allow multi select when input is focused + +### Patch Changes + +- Updated dependencies []: + - @reactflow/core@11.4.0-next.1 + +## 1.1.1-next.0 + +### Patch Changes + +- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0-next.0 + ## 1.1.0 ### Minor Changes diff --git a/packages/node-resizer/package.json b/packages/node-resizer/package.json index 29b04048..d9a42e86 100644 --- a/packages/node-resizer/package.json +++ b/packages/node-resizer/package.json @@ -1,6 +1,6 @@ { "name": "@reactflow/node-resizer", - "version": "1.1.0", + "version": "1.2.0", "description": "A helper component for resizing nodes.", "keywords": [ "react", diff --git a/packages/node-toolbar/CHANGELOG.md b/packages/node-toolbar/CHANGELOG.md index 624d1510..49057c35 100644 --- a/packages/node-toolbar/CHANGELOG.md +++ b/packages/node-toolbar/CHANGELOG.md @@ -1,5 +1,49 @@ # @reactflow/node-toolbar +## 1.1.0 + +### Patch Changes + +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. + +- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0 + +## 1.1.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) + selection: do not include hidden nodes + minimap: fix onNodeClick for nodes outside the viewport + keys: allow multi select when input is focused + +### Patch Changes + +- Updated dependencies []: + - @reactflow/core@11.4.0-next.1 + +## 1.1.0-next.0 + +### Minor Changes + +- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features + + New props for the ReactFlow component to customize the controls of the viewport and the selection box better: + + 1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`) + 2. `panOnDrag="RightClick"` option + 3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`) + 4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it + 5. `onSelectionStart` and `onSelectionEnd` events + +### Patch Changes + +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. + +- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0-next.0 + ## 1.0.2 ### Patch Changes diff --git a/packages/node-toolbar/package.json b/packages/node-toolbar/package.json index 2163d4ce..0b664881 100644 --- a/packages/node-toolbar/package.json +++ b/packages/node-toolbar/package.json @@ -1,6 +1,6 @@ { "name": "@reactflow/node-toolbar", - "version": "1.0.2", + "version": "1.1.0", "description": "A toolbar component for React Flow that can be attached to a node.", "keywords": [ "react", diff --git a/packages/node-toolbar/src/NodeToolbar.tsx b/packages/node-toolbar/src/NodeToolbar.tsx index 5c6cbc86..aed9d860 100644 --- a/packages/node-toolbar/src/NodeToolbar.tsx +++ b/packages/node-toolbar/src/NodeToolbar.tsx @@ -31,7 +31,7 @@ const nodesEqualityFn = (a: Node[], b: Node[]) => { const storeSelector = (state: ReactFlowState) => ({ transform: state.transform, nodeOrigin: state.nodeOrigin, - selectedNodesCount: Array.from(state.nodeInternals.values()).filter((node) => node.selected).length, + selectedNodesCount: state.getNodes().filter((node) => node.selected).length, }); function getTransform(nodeRect: Rect, transform: Transform, position: Position, offset: number): string { diff --git a/packages/reactflow/CHANGELOG.md b/packages/reactflow/CHANGELOG.md index dfeb78db..f6e6408f 100644 --- a/packages/reactflow/CHANGELOG.md +++ b/packages/reactflow/CHANGELOG.md @@ -1,5 +1,94 @@ # reactflow +## 11.4.0 + +## 11.4.0 + +## New Features + +New props for the ReactFlow component to customize the controls of the viewport and the selection box better: + +1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false}` or `panOnDrag={[1, 2]}`) +2. `panOnDrag={[0, 1, 2]}` option to configure specific mouse buttons for panning +3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`) +4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it +5. `onSelectionStart` and `onSelectionEnd` events +6. `elevateNodesOnSelect`: Defines if z-index should be increased when node is selected +7. New store function `getNodes`. You can now do `store.getState().getNodes()` instead of `Array.from(store.getNodes().nodeInternals.values())`. + +Thanks to @jackfishwick who helped a lot with the new panning and selection options. + +### Minor Changes + +- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) + - Add new props to configure viewport controls (`selectionOnDrag`, `panActivationKeyCode`, ..) +- [#2661](https://github.com/wbkd/react-flow/pull/2661) [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654) + - panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) + - selection: do not include hidden nodes + - minimap: fix onNodeClick for nodes outside the viewport + - keys: allow multi select when input is focused + +### Patch Changes + +- [#2695](https://github.com/wbkd/react-flow/pull/2695) [`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff) - Add elevateNodesOnSelect prop +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. +- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) - Use translateExtent correctly +- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) - Only trigger drag event when change happened + +- Updated dependencies [[`ab2ff374`](https://github.com/wbkd/react-flow/commit/ab2ff3740618da48bd4350597e816c397f3d78ff), [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`7ef29108`](https://github.com/wbkd/react-flow/commit/7ef2910808aaaee029894363d52efc0c378a7654), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0 + - @reactflow/minimap@11.3.0 + - @reactflow/node-toolbar@1.1.0 + - @reactflow/background@11.1.0 + - @reactflow/controls@11.1.0 + +## 11.4.0-next.1 + +### Minor Changes + +- panOnDrag: Use numbers for prop ([1,2] = drag via middle or right mouse button) + selection: do not include hidden nodes + minimap: fix onNodeClick for nodes outside the viewport + keys: allow multi select when input is focused + +### Patch Changes + +- Updated dependencies []: + - @reactflow/background@11.1.0-next.1 + - @reactflow/controls@11.1.0-next.1 + - @reactflow/core@11.4.0-next.1 + - @reactflow/minimap@11.3.0-next.1 + - @reactflow/node-toolbar@1.1.0-next.1 + +## 11.4.0-next.0 + +### Minor Changes + +- [#2678](https://github.com/wbkd/react-flow/pull/2678) [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493) Thanks [@moklick](https://github.com/moklick)! - ## New Features + + New props for the ReactFlow component to customize the controls of the viewport and the selection box better: + + 1. `selectionOnDrag` prop: Selection box without extra button press (need to set `panOnDrag={false} or `panOnDrag="RightClick"`) + 2. `panOnDrag="RightClick"` option + 3. `panActivationKeyCode="Space"` key code for activating dragging (useful when using `selectionOnDrag`) + 4. `selectionMode={SelectionMode.Full}`: you can chose if the selection box needs to contain a node fully (`SelectionMode.Full`) or partially (`SelectionMode.Partial`) to select it + 5. `onSelectionStart` and `onSelectionEnd` events + +### Patch Changes + +- [#2660](https://github.com/wbkd/react-flow/pull/2660) [`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0) Thanks [@moklick](https://github.com/moklick)! - Add `getNodes` function to the store so that you don't need to do `Array.from(store.getState().nodeInternals.values())` anymore. + +- [#2659](https://github.com/wbkd/react-flow/pull/2659) [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9) Thanks [@moklick](https://github.com/moklick)! - Use translateExtent correctly + +- [#2657](https://github.com/wbkd/react-flow/pull/2657) [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c) Thanks [@moklick](https://github.com/moklick)! - Only trigger drag event when change happened + +- Updated dependencies [[`50032c3d`](https://github.com/wbkd/react-flow/commit/50032c3d953bd819d0afe48e4b61f77f987cc8d0), [`baa8689e`](https://github.com/wbkd/react-flow/commit/baa8689ef629d22da4cbbef955e0c83d21df0493), [`4244bae2`](https://github.com/wbkd/react-flow/commit/4244bae25a36cb4904dc1fbba26e1c4d5d463cb9), [`23afb3ab`](https://github.com/wbkd/react-flow/commit/23afb3abebdb42fad284f68bec164afac609563c)]: + - @reactflow/core@11.4.0-next.0 + - @reactflow/minimap@11.3.0-next.0 + - @reactflow/node-toolbar@1.1.0-next.0 + - @reactflow/background@11.0.8-next.0 + - @reactflow/controls@11.0.8-next.0 + ## 11.3.3 In this update we did some changes so that we could implement the new [``](https://reactflow.dev/docs/api/nodes/node-resizer/) component (not part of the `reactflow` package!) more smoothly. diff --git a/packages/reactflow/package.json b/packages/reactflow/package.json index f1f3ecab..f4c93b25 100644 --- a/packages/reactflow/package.json +++ b/packages/reactflow/package.json @@ -1,6 +1,6 @@ { "name": "reactflow", - "version": "11.3.3", + "version": "11.4.0", "description": "A highly customizable React library for building node-based editors and interactive flow charts", "keywords": [ "react",