Merge branch 'main' into refactor/promised-panzoom
This commit is contained in:
+228
-215
@@ -1,304 +1,317 @@
|
||||
# @reactflow/core
|
||||
# @xyflow/react
|
||||
|
||||
## 11.7.2
|
||||
## 12.0.0-next.26
|
||||
|
||||
### Patch Changes
|
||||
- add `autoPanSpeed` prop
|
||||
|
||||
- [#3060](https://github.com/wbkd/react-flow/pull/3060) [`70ec97f7`](https://github.com/wbkd/react-flow/commit/70ec97f7daec6d5401215cae3edac04aea88a3ba) - fix useNodes and useEdges bug with infinite re-renderings
|
||||
- [#3064](https://github.com/wbkd/react-flow/pull/3064) [`d2d1aebc`](https://github.com/wbkd/react-flow/commit/d2d1aebc0f7fea4183406e7d1915b7fcd6995f48) - refactor(useUpdateNodeInternals): only call updateNodeDimensions once
|
||||
- [#3059](https://github.com/wbkd/react-flow/pull/3059) [`4374459e`](https://github.com/wbkd/react-flow/commit/4374459ef9fec797bbc0407231f09a1acacd245b) - fix useUpdateNodeInternals type
|
||||
## 12.0.0-next.25
|
||||
|
||||
## 11.7.1
|
||||
- `useConnection` returns `ConnectionState` with `toNode` and `toHandle`
|
||||
- add `toNode` and `toHandle` to custom connection line props
|
||||
- node origin is part of position absolute
|
||||
- refactor connection handling
|
||||
|
||||
### Patch Changes
|
||||
## 12.0.0-next.24
|
||||
|
||||
- [#3043](https://github.com/wbkd/react-flow/pull/3043) [`cf7a7d3d`](https://github.com/wbkd/react-flow/commit/cf7a7d3dad1e73215a72a5dc72e21fd50208cdbb) - handles: handles on top of each other, reduce re-renderings
|
||||
- [#3046](https://github.com/wbkd/react-flow/pull/3046) [`07b975bb`](https://github.com/wbkd/react-flow/commit/07b975bbee3580249e36a19582213b250f78093c) - base-edge: pass id to base edge path
|
||||
- [#3007](https://github.com/wbkd/react-flow/pull/3007) [`c80d269b`](https://github.com/wbkd/react-flow/commit/c80d269b85a0054221f4639c328fc36a3befbe70) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - allow array of ids as updateNodeInternals arg
|
||||
- [#3029](https://github.com/wbkd/react-flow/pull/3029) [`a3fa164c`](https://github.com/wbkd/react-flow/commit/a3fa164c34cc820c79bb031c9fd97b72a3546614) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - autopan: only update nodes when transform change happen
|
||||
- fix `window` bug for SSR for real
|
||||
|
||||
## 11.7.0
|
||||
## 12.0.0-next.23
|
||||
|
||||
Most notable updates:
|
||||
- fix `window` bug for SSR
|
||||
|
||||
- Handles: `isConnectableStart` and `isConnectableEnd` props to configure if you can start or end a connection at a certain handle
|
||||
- Edges: `updatable` option to enable updates for specific edges
|
||||
- useNodesInitialized: options to configure if hidden nodes should be included (false by default)
|
||||
## 12.0.0-next.22
|
||||
|
||||
### Minor Changes
|
||||
- ⚠️ rename `updateEdge` to `reconnectEdge` and realted APIs [#4373](https://github.com/xyflow/xyflow/pull/4373)
|
||||
- revise selection usability (capture while dragging out of the flow)
|
||||
- use correct end handle position when drawing a connection lines
|
||||
- determine correct end positions for connection lines
|
||||
|
||||
- [#2960](https://github.com/wbkd/react-flow/pull/2960) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - edges: add `updatable` option
|
||||
- [#2958](https://github.com/wbkd/react-flow/pull/2958) [`4d97a0ed`](https://github.com/wbkd/react-flow/commit/4d97a0ed168ce643fc0c99fa6b47cf1296d66065) - handles: add `isConnectableStart` and `isConnectableEnd` props
|
||||
- [#2956](https://github.com/wbkd/react-flow/pull/2956) [`923a54c4`](https://github.com/wbkd/react-flow/commit/923a54c481b90954806202817ba844cfa7203a38) - add options for `useNodesInitialized`, ignore hidden nodes by default
|
||||
## 12.0.0-next.21
|
||||
|
||||
### Patch Changes
|
||||
- fix node origin bug
|
||||
|
||||
- [#2926](https://github.com/wbkd/react-flow/pull/2926) Thanks [@Elringus](https://github.com/Elringus)! - fix non-passive wheel event listener violation
|
||||
- [#2933](https://github.com/wbkd/react-flow/pull/2933) [`fe8cac0a`](https://github.com/wbkd/react-flow/commit/fe8cac0adb359109e0e9eafe8b9261ba354076bb) - prefix error keys with "error"
|
||||
- [#2939](https://github.com/wbkd/react-flow/pull/2939) [`4a4ca171`](https://github.com/wbkd/react-flow/commit/4a4ca171955f5c8d58b23e3ad48406f1a21dc402) - add connection result to store
|
||||
## 12.0.0-next.20
|
||||
|
||||
## 11.6.1
|
||||
- add `updateEdge` and `updateEdgeData` helpers to `useReactFlow`
|
||||
- enable dynamic edge label updates
|
||||
- prevent zooming on mobile if zoomOnPinch is false
|
||||
- add straight edge to path built-in-types
|
||||
- abort drag when multiple touches are detected
|
||||
|
||||
### Patch Changes
|
||||
## 12.0.0-next.19
|
||||
|
||||
- Always create new edge object (fixes an issue with Redux toolkit and other immutable helper libs)
|
||||
- update internals on node resizer updates
|
||||
- re-observe node when `node.hidden` is toggled
|
||||
- update `updateNodeData` argument type - thanks @ogroppo
|
||||
- add `selectable`, `deletable` and `draggable` to node and edge props
|
||||
- add `parentId` to node props
|
||||
- fix parent node lookup in `evaluateAbsolutePosition`- thanks @lcsfort
|
||||
|
||||
## 11.6.0
|
||||
## 12.0.0-next.18
|
||||
|
||||
### Minor Changes
|
||||
- don't show nodeTypes warning if not necessary you've created a new nodeTypes or edgeTypes
|
||||
- add node resizer styles to base.css
|
||||
- remove `HandleComponentProps` type, only export `HandleProps` type
|
||||
- add warning when styles not loaded
|
||||
|
||||
- [#2877](https://github.com/wbkd/react-flow/pull/2877) [`b8886514`](https://github.com/wbkd/react-flow/commit/b88865140c72fa7e92a883498768000cb2cc96a7) - add `isValidConnection` prop for ReactFlow component
|
||||
- [#2847](https://github.com/wbkd/react-flow/pull/2847) [`16bf89f2`](https://github.com/wbkd/react-flow/commit/16bf89f2b7bbf8449c00d0e2c07c19c3ff6d2533) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Add option to enable/disable replacing edge id when using `updateEdge`
|
||||
## 12.0.0-next.17
|
||||
|
||||
### Patch Changes
|
||||
- fix broken `defaultNodes`
|
||||
- add string array to `UpdateNodeInternals` thanks @DenizUgur
|
||||
- pinch zoom on windows
|
||||
- drag for touch devices
|
||||
- return user node in node event handlers
|
||||
- cleanup `useReactFlow`
|
||||
- export `KeyCode` and `Align` type
|
||||
- remove `Instance` in favour of `ReactFlowInstance` type
|
||||
|
||||
- [#2895](https://github.com/wbkd/react-flow/pull/2895) [`3d5764ca`](https://github.com/wbkd/react-flow/commit/3d5764cac6548984a30cbf85899024e62fd69425) - add data-testid for controls, minimap and background
|
||||
- [#2894](https://github.com/wbkd/react-flow/pull/2894) [`83fc4675`](https://github.com/wbkd/react-flow/commit/83fc467545527729633e817dbccfe59d0040da4b) - fix(nodes): blur when node gets unselected
|
||||
- [#2892](https://github.com/wbkd/react-flow/pull/2892) [`5fabd272`](https://github.com/wbkd/react-flow/commit/5fabd2720f6367f75f79a45822d8f675a3b8e1cf) Thanks [@danielgek](https://github.com/danielgek) - track modifier keys on useKeypress
|
||||
- [#2893](https://github.com/wbkd/react-flow/pull/2893) [`8f080bd5`](https://github.com/wbkd/react-flow/commit/8f080bd5e0e7e6c71f51eee9c9f2bc4b25182861) - fix: check if handle is connectable
|
||||
## 12.0.0-next.16
|
||||
|
||||
## 11.5.5
|
||||
## Patch changes
|
||||
|
||||
### Patch Changes
|
||||
- fix batching for `setNodes`, `updateNode`, `updateNodeData` etc.
|
||||
- fix `useNodesInitialized`
|
||||
|
||||
- [#2834](https://github.com/wbkd/react-flow/pull/2834) [`23424ea6`](https://github.com/wbkd/react-flow/commit/23424ea6750f092210f83df17a00c89adb910d96) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Add `nodes` to fit view options to allow fitting view only around specified set of nodes
|
||||
- [#2836](https://github.com/wbkd/react-flow/pull/2836) [`959b1114`](https://github.com/wbkd/react-flow/commit/959b111448bba4686040473e46988be9e7befbe6) - Fix: connections for handles with bigger handles than connection radius
|
||||
- [#2819](https://github.com/wbkd/react-flow/pull/2819) [`0d259b02`](https://github.com/wbkd/react-flow/commit/0d259b028558aab650546f3371a85f3bce45252f) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Avoid triggering edge update if not using left mouse button
|
||||
- [#2832](https://github.com/wbkd/react-flow/pull/2832) [`f3de9335`](https://github.com/wbkd/react-flow/commit/f3de9335af6cd96cd77dc77f24a944eef85384e5) - fitView: return type boolean
|
||||
- [#2838](https://github.com/wbkd/react-flow/pull/2838) [`021f5a92`](https://github.com/wbkd/react-flow/commit/021f5a9210f47a968e50446cd2f9dae1f97880a4) - refactor: use key press handle modifier keys + input
|
||||
- [#2839](https://github.com/wbkd/react-flow/pull/2839) [`72216ff6`](https://github.com/wbkd/react-flow/commit/72216ff62014acd2d73999053c72bd7aeed351f6) - fix PropsWithChildren: pass default generic for v17 types
|
||||
## 12.0.0-next.15
|
||||
|
||||
## 11.5.4
|
||||
## Patch changes
|
||||
|
||||
### Patch Changes
|
||||
- re-observe nodes when using `onlyRenderVisibleElements={true}`
|
||||
- use correct positions for intersection helpers
|
||||
- fix minimap interaction for touch devices
|
||||
- pass user nodes to `onSelectionChange` instead of internal ones to work with Redux
|
||||
- call `onEnd` in XYResizer thanks @tonyf
|
||||
- cleanup `getPositionWithOrigin` usage
|
||||
- use `setAttributes` flag for dimension change when `width`/`height` should be set
|
||||
- use `replace: false` as the default for `updateNode` function
|
||||
|
||||
- [`383a074a`](https://github.com/wbkd/react-flow/commit/383a074aeae6dbec8437fa08c7c8d8240838a84e) Thanks [@bcakmakoglu](https://github.com/bcakmakoglu)! - Check if prevClosestHandle exists in onPointerUp. Fixes connections getting stuck on last handle and connecting, even when out of connectionRadius
|
||||
## 12.0.0-next.14
|
||||
|
||||
## 11.5.3
|
||||
## Patch changes
|
||||
|
||||
This release fixes some issues with the newly introduced connection radius feature. We are now not only checking the radius but the handle itself too (like in the old version). That means that you can connect to a handle that is bigger than the connection radius. We are also not snapping connections anymore when they are not valid and pass a status class to the connection line that says if the current connection is valid or not. More over we fixed a connection issue with iOS.
|
||||
- fix hidden nodes
|
||||
- use `direction=ltr` for outer wrapper to support rtl sites
|
||||
- allow pinch zoom even if `preventScrolling=false`
|
||||
- export node and edge change related types
|
||||
- only trigger dimensions updates when changes detected
|
||||
|
||||
### Patch Changes
|
||||
## 12.0.0-next.13
|
||||
|
||||
- [#2800](https://github.com/wbkd/react-flow/pull/2800) [`be8097ac`](https://github.com/wbkd/react-flow/commit/be8097acadca3054c3b236ce4296fc516010ef8c) - When node is not draggable, you can't move it with a selection either
|
||||
- [#2803](https://github.com/wbkd/react-flow/pull/2803) [`1527795d`](https://github.com/wbkd/react-flow/commit/1527795d18c3af38c8ec7059436ea0fbf6c27bbd) - connection: add status class (valid or invalid) while in connection radius
|
||||
- [#2801](https://github.com/wbkd/react-flow/pull/2801) [`3b6348a8`](https://github.com/wbkd/react-flow/commit/3b6348a8d1573afb39576327318bc172e33393c2) - fix(ios): connection error + dont snap invalid connection lines, check handle and connection radius
|
||||
## ⚠️ Breaking changes
|
||||
|
||||
## 11.5.2
|
||||
- rename `node.parentNode` to `node.parentId`
|
||||
- rename node.computed to node.measured
|
||||
- remove positionAbsolute from `node.computed`
|
||||
|
||||
### Patch Changes
|
||||
## Minor Changes
|
||||
|
||||
- [#2792](https://github.com/wbkd/react-flow/pull/2792) [`d8c679b4`](https://github.com/wbkd/react-flow/commit/d8c679b4c90c5b57d4b51e4aaa988243d6eaff5a) - Accept React 17 types as dev dependency
|
||||
- new helpers: `useInternalNode` hook, `getInternalNode` function
|
||||
|
||||
## 11.5.1
|
||||
## Patch changes
|
||||
|
||||
### Patch Changes
|
||||
- remove `internalsSymbol` (now called internals and only available for internal nodes)
|
||||
- handle parentExpand on library side instead of applyChanges
|
||||
- new type `InternalNode`
|
||||
|
||||
- [#2783](https://github.com/wbkd/react-flow/pull/2783) [`71153534`](https://github.com/wbkd/react-flow/commit/7115353418ebc7f7c81ab0e861200972bbf7dbd5) - connections: check handle below mouse before using connection radius
|
||||
## 12.0.0-next.12
|
||||
|
||||
## 11.5.0
|
||||
## Patch changes
|
||||
|
||||
Lot's of improvements are coming with this release!
|
||||
- fix useNodesData: handle invalid node id thanks @saswatax
|
||||
- fix forwardRef: use custom fixForwardRef function
|
||||
- refactor intersection helpers to use passed node value
|
||||
|
||||
- **Connecting radius**: No need to drop a connection line on top of handle anymore. You only need to be close to the handle. That radius can be configured with the `connectionRadius` prop.
|
||||
- **Auto pan**: When you drag a node, a selection or the connection line to the border of the pane, it will pan into that direction. That makes it easier to connect far away nodes for example. If you don't like it you can set `autoPnaOnNodeDrag` and `autoPanOnConnect` to false.
|
||||
- **Touch devices**: It's finally possibleto connect nodes with the connection line on touch devices. In combination with the new auto pan and connection radius the overall UX is way better.
|
||||
- **Errors**: We added an `onError` prop to get notified when an error like "couldn't find source handle" happens. This is useful if you want to log errors for example.
|
||||
- **Node type**: We added a second param to the generic `Node` type. You can not only pass `NodeData` but also the type as a second param:
|
||||
## 12.0.0-next.11
|
||||
|
||||
```ts
|
||||
type MyCustomNode = Node<MyCustomNodeData, 'custom-node-type'>;
|
||||
```
|
||||
## Patch changes
|
||||
|
||||
This makes it easier to work with different custom nodes and data types.
|
||||
- fix `ref` prop for `ReactFlow` and `Handle` component
|
||||
- unify `Edge` and `Node` type handling
|
||||
- fix safari: prevent selection of viewport
|
||||
- fix `useNodesData` hook to prevent re-renderings
|
||||
- fix edges: allow start at 0,0
|
||||
|
||||
### Minor Changes
|
||||
## 12.0.0-next.10
|
||||
|
||||
- [#2754](https://github.com/wbkd/react-flow/pull/2754) [`e96309b6`](https://github.com/wbkd/react-flow/commit/e96309b6a57b1071faeebf7b0547fef7fd418694) - Add auto pan for connecting and node dragging and `connectionRadius`
|
||||
- [#2773](https://github.com/wbkd/react-flow/pull/2773) - Add `onError` prop to get notified when an error happens
|
||||
## ⚠️ Breaking changes
|
||||
|
||||
### Patch Changes
|
||||
- `useNodesData` not only returns data objects but also the type and the id of the node
|
||||
- status class names for Handle components are slightly different. It's now "connectingfrom" and "connectingto" instead of "connecting"
|
||||
|
||||
- [#2763](https://github.com/wbkd/react-flow/pull/2763) [`85003b01`](https://github.com/wbkd/react-flow/commit/85003b01add71ea852bd5b0d2f1e7496050a6b52) - Connecting nodes: Enable connections on touch devices
|
||||
- [#2620](https://github.com/wbkd/react-flow/pull/2620) - Thanks [RichSchulz](https://github.com/RichSchulz)! - Types: improve typing for node type
|
||||
## Patch changes
|
||||
|
||||
## 11.4.2
|
||||
- better cursor defaults for the pane, nodes and edges
|
||||
- `disableKeyboardA11y` now also disables Enter and Escape for selecting/deselecting nodes and edges
|
||||
- fix bug where users couldn't drag a node after toggle nodes `hidden` attribute
|
||||
- add `initialWidth` and `initialHeight` node attributes for specifying initial dimensions for ssr
|
||||
- fix `NodeResizer` when used in combination with `nodeOrigin`
|
||||
|
||||
### Patch Changes
|
||||
## 12.0.0-next.9
|
||||
|
||||
- [#2741](https://github.com/wbkd/react-flow/pull/2741) [`e2aff6c1`](https://github.com/wbkd/react-flow/commit/e2aff6c1e4ce54b57b724b2624367ee5fefd1c39) - chore(dependencies): update and cleanup
|
||||
### Patch changes
|
||||
|
||||
## 11.4.1
|
||||
- a better `NodeResizer` that works with subflows. Child nodes do not move when parent node gets resized and parent extent is taken into account
|
||||
- refactor `setNodes` batching
|
||||
- re-measure nodes when necessary
|
||||
- don't trigger drag start / end when node is not draggable
|
||||
|
||||
### Patch Changes
|
||||
## 12.0.0-next.8
|
||||
|
||||
- [#2738](https://github.com/wbkd/react-flow/pull/2738) [`82988485`](https://github.com/wbkd/react-flow/commit/82988485b730a9e32acbdae1ddcc81b33ddccaba) - fix: fitView for subflows, context menu on right mouse pan
|
||||
- [#2740](https://github.com/wbkd/react-flow/pull/2740) [`d91e619a`](https://github.com/wbkd/react-flow/commit/d91e619a70a95db99a621ede59bc05b5a7766086) Thanks [@michaelspiss](https://github.com/michaelspiss)! - EdgeRenderer: check all handles for connection mode loose
|
||||
### Patch changes
|
||||
|
||||
## 11.4.0
|
||||
- selection box is not interrupted by selectionKey being let go
|
||||
- fix `OnNodeDrag` type
|
||||
- do not use fallback handle if a specific id is being used
|
||||
- fix `defaultEdgeOptions` markers not being applied
|
||||
- fix `getNodesBounds` and add second param for passing options
|
||||
- fix `expandParent` for child nodes
|
||||
|
||||
## New Features
|
||||
## 12.0.0-next.7
|
||||
|
||||
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
|
||||
## Minor changes
|
||||
|
||||
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())`.
|
||||
- add second option param to `screenToFlowPosition` for configuring if `snapToGrid` should be used
|
||||
|
||||
Thanks to @jackfishwick who helped a lot with the new panning and selection options.
|
||||
### Patch changes
|
||||
|
||||
### Minor Changes
|
||||
- pass `Node`/ `Edge` types to changes thanks @FelipeEmos
|
||||
- use position instead of positionAbsolute for `getNodesBounds`
|
||||
- infer types for `getIncomers`, `getOutgoers`, `updateEdge`, `addEdge` and `getConnectedEdges` thanks @joeyballentine
|
||||
- refactor handles: prefix with flow id for handling nested flows
|
||||
- add comments for types like `ReactFlowProps` or `Node` for a better developer experience
|
||||
|
||||
- [#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
|
||||
## 12.0.0-next.6
|
||||
|
||||
### Patch Changes
|
||||
### 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
|
||||
- fix `deleteElements`
|
||||
- refactor internal `applyChanges`
|
||||
- batch `setNodes` and `setEdges` from `useReactFlow`
|
||||
- add `aria-label` prop for `<Controls />`
|
||||
|
||||
## 11.4.0-next.1
|
||||
## 12.0.0-next.5
|
||||
|
||||
### Minor Changes
|
||||
### 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
|
||||
- fix applyChanges: handle multi changes for one node, deletions and expandParent
|
||||
- use `XYResizer` from @xyflow/system
|
||||
- add unit tests for `applyNodeChanges` and `applyEdgeChanges`
|
||||
|
||||
## 11.4.0-next.0
|
||||
## 12.0.0-next.4
|
||||
|
||||
### Minor Changes
|
||||
### 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
|
||||
- fix applyChanges: handle empty flows + addNodes/addEdges closes
|
||||
- cleanup exports
|
||||
|
||||
New props for the ReactFlow component to customize the controls of the viewport and the selection box better:
|
||||
## 12.0.0-next.3
|
||||
|
||||
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
|
||||
### Minor changes
|
||||
|
||||
### Patch Changes
|
||||
- fix edges styles when using base.css
|
||||
|
||||
- [#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.
|
||||
## 12.0.0-next.2
|
||||
|
||||
- [#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
|
||||
### Minor changes
|
||||
|
||||
- [#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
|
||||
- fix connection line rendering
|
||||
- fix multi handle
|
||||
|
||||
## 11.3.2
|
||||
## 12.0.0-next.1
|
||||
|
||||
In this update we did some changes so that we could implement the new [`<NodeResizer />`](https://reactflow.dev/docs/api/nodes/node-resizer/) component more smoothly.
|
||||
### Minor changes
|
||||
|
||||
### Patch Changes
|
||||
- fix edge rendering
|
||||
|
||||
- [#2646](https://github.com/wbkd/react-flow/pull/2646) [`e6b5d90f`](https://github.com/wbkd/react-flow/commit/e6b5d90f61c8ee60e817bba232a162cae2ab3e2a) - Fix getRectOfNodes
|
||||
- [#2648](https://github.com/wbkd/react-flow/pull/2648) [`6ee44e07`](https://github.com/wbkd/react-flow/commit/6ee44e076eaa6908d07578a757a5187642b732ae) - Allow middle mouse pan over edges
|
||||
- [#2647](https://github.com/wbkd/react-flow/pull/2647) [`aa69c207`](https://github.com/wbkd/react-flow/commit/aa69c20765e6978f4f9c8cc63ed7110dbf6d9d9d) Thanks [@neo](https://github.com/neo)! - Invalidate node trying to connect itself with the same handle
|
||||
- [#2626](https://github.com/wbkd/react-flow/pull/2626) [`d29c401d`](https://github.com/wbkd/react-flow/commit/d29c401d598dbf2dcd5609b7adb8d029906a6f18) - Export the useNodeId hook, refactor how changes are applied and create a helper function
|
||||
- [#2642](https://github.com/wbkd/react-flow/pull/2642) [`0df02f35`](https://github.com/wbkd/react-flow/commit/0df02f35f8d6c54dae36af18278feadc77acb2d6) - Ignore key events for nodes when input is focused
|
||||
## 12.0.0-next.0
|
||||
|
||||
## 11.3.1
|
||||
React Flow v12 is coming soon! We worked hard over the past months and tried to make as few breaking changes as possible (there are some). We are in no rush to release v12, so we’d be happy to hear any early feedback so we can adjust the API or redefine new features before launching stable v12. 🚀 The big topics for this version are:
|
||||
|
||||
### Patch Changes
|
||||
1. **Support for SSG/ SSR**: you can now render flows on the server
|
||||
2. **Reactive flows**: new hooks and helper functions to simplify data flows
|
||||
3. **Dark mode**: a new base style and easy way to switch between built in color modes
|
||||
|
||||
- [#2595](https://github.com/wbkd/react-flow/pull/2595) [`c828bfda`](https://github.com/wbkd/react-flow/commit/c828bfda0a8c4774bc43588640c7cca0cfdcb3f4) Thanks [@chrtze](https://github.com/chrtze)! - Fix and improve the behaviour when using nodeOrigin in combination with subflows
|
||||
- [#2602](https://github.com/wbkd/react-flow/pull/2602) [`b0302ce4`](https://github.com/wbkd/react-flow/commit/b0302ce4261a992bee841bae84af347d03be690f) Thanks [@sdegueldre](https://github.com/sdegueldre)! - Don't use try catch in wrapper for checking if provider is available
|
||||
- [#2601](https://github.com/wbkd/react-flow/pull/2601) [`b2c72813`](https://github.com/wbkd/react-flow/commit/b2c728137d1b53e38883f044fa447585c377a6af) Thanks [@hoondeveloper](https://github.com/hoondeveloper)! - fix isRectObject function
|
||||
Svelte Flow had a big impact on this release as well. While combing through each line of React Flow, we created framework agnostic helpers, found bugs, and made some under the hood improvements. All of these changes are baked into the v12 release as a welcome side-effect of that launch. 🙌🏻 We also improved the performance for larger flows with the help of Ivan.
|
||||
|
||||
## 11.3.0
|
||||
### Migrate from 11 to 12
|
||||
|
||||
### Minor Changes
|
||||
Before you can try out the new features, you need to do some minor updates:
|
||||
|
||||
- [#2563](https://github.com/wbkd/react-flow/pull/2563) [`98116d43`](https://github.com/wbkd/react-flow/commit/98116d431f9fcdcc9b23a5b606a94ec0740b64cd) Thanks [@chrtze](https://github.com/chrtze)! - Export a new component "NodeToolbar" that renders a fixed element attached to a node
|
||||
- **A new npm package name:** Our name changed from `reactflow` to `@xyflow/react` and the main component is no longer a default, but a named import:
|
||||
- v11: `import ReactFlow from 'reactflow';`
|
||||
- v12: `import { ReactFlow } from '@xyflow/react';`
|
||||
- **Node attribute “computed”:** All computed node values are now stored in `node.computed`
|
||||
- v11: `node.width`, `node.height` ,`node.positionAbsolute`
|
||||
- v12: `node.computed.width`, `node.computed.height` and `node.computed.positionAbsolute` . (`node.width`/ `node.height` can now be used for SSG)
|
||||
- **Updating nodes:** We are not supporting node updates with object mutations anymore. If you want to update a certain attribute, you need to create a new node.
|
||||
- v11:
|
||||
```js
|
||||
setNodes((nds) =>
|
||||
nds.map((node) => {
|
||||
node.hidden = true;
|
||||
return node;
|
||||
})
|
||||
);
|
||||
```
|
||||
- v12:
|
||||
```js
|
||||
setNodes((nds) =>
|
||||
nds.map((node) => ({
|
||||
...node,
|
||||
hidden: true,
|
||||
}))
|
||||
);
|
||||
```
|
||||
- **NodeProps:** `posX`/`posY` is now called `positionAbsoluteX`/`positionAbsoluteY`
|
||||
- **Typescript only:** We simplified types and fixed issues about functions where users could pass a `NodeData` generic. The new way is to define your own node type for the whole app and then only use that one. The big advantage of this is, that you can have multiple node types with different data structures and always be able to distinguish by checking the `node.type` attribute.
|
||||
- v11: `applyNodeChange<NodeData, NodeType>`
|
||||
- v12: `type MyNodeType = Node<{ value: number }, ‘number’> | Node<{ value: string }, ‘text’>; applyNodeChange<MyNodeType>`
|
||||
- affected functions: `useNodes`, `useNodesState`, `useEdgesState`, `applyNodeChange`, `onInit`, `applyEdgeChanges` , `MiniMapProps`
|
||||
- **Removal of deprecated functions:**
|
||||
- `getTransformForBounds` (new name: `getViewportForBounds`),
|
||||
- `getRectOfNodes` (new name: `getNodesBounds`)
|
||||
- `project` (new name: `screenToFlowPosition`)
|
||||
- `getMarkerEndId`
|
||||
|
||||
### Patch Changes
|
||||
### Main features
|
||||
|
||||
- [#2561](https://github.com/wbkd/react-flow/pull/2561) [`92cf497e`](https://github.com/wbkd/react-flow/commit/92cf497eb72f21af592a53f5af9770c9f1e6d940) Thanks [@moklick](https://github.com/moklick)! - Fix multi selection and fitView when nodeOrigin is used
|
||||
- [#2560](https://github.com/wbkd/react-flow/pull/2560) [`a39224b3`](https://github.com/wbkd/react-flow/commit/a39224b3a80afbdb83fc4490dd5f4f2be23cd4dd) Thanks [@neo](https://github.com/neo)! - Always elevate zIndex when node is selected
|
||||
- [#2573](https://github.com/wbkd/react-flow/pull/2573) [`5e8b67dd`](https://github.com/wbkd/react-flow/commit/5e8b67dd41f9bb60dcd7f5d14cc34b42c970e967) Thanks [@moklick](https://github.com/moklick)! - Fix disappearing connection line for loose flows
|
||||
- [#2558](https://github.com/wbkd/react-flow/pull/2558) [`2a1c7db6`](https://github.com/wbkd/react-flow/commit/2a1c7db6b27ac0f4f81dcef2d593f4753c4321c7) Thanks [@moklick](https://github.com/moklick)! - EdgeLabelRenderer: handle multiple instances on a page
|
||||
Now that you successfully migrated to v12, you can use all the fancy features. As mentioned above, the biggest updates for v12 are:
|
||||
|
||||
## 11.2.0
|
||||
- **SSR / SSG**: you can define `width`, `height` and `handles` for the nodes. This makes it possible to render a flow on the server and hydrate on the client: [codesandbox](https://codesandbox.io/p/devbox/reactflow-v12-next-pr66yh)
|
||||
- Details: In v11, `width` and `height` were set by the library as soon as the nodes got measured. This still happens, but we are now using `computed.width` and `computed.height` to store this information. The `positionAbsolute` attribute also gets stored in `computed` . In the previous versions there was always a lot of confusion about `width` and `height`. It’s hard to understand, that you can’t use it for passing an actual width or height. It’s also not obvious that those attributes get added by the library. We think that the new implementation solves both of the problems: `width` and `height` are optional attributes that can be used to define dimensions and everything that is set by the library, is stored in `computed`.
|
||||
- **Reactive Flows:** The new hooks `useHandleConnections` and `useNodesData` and the new `updateNode` and `updateNodeData` functions can be used for managing the data flow between your nodes: [codesandbox](https://codesandbox.io/p/sandbox/reactflow-reactive-flow-sy93yx)
|
||||
- Details: Working with reactive flows is super common. You update node A and want to react on those changes in the connected node B. Until now everyone had to come up with a custom solution. With this version we want to change this and give you performant helpers to handle this. If you are excited about this, you can check out this example:
|
||||
- **Dark mode and css variables:** React Flow now comes with a built-in dark mode, that can be toggled by using the new `colorMode` prop (”light”, “dark” or “system”): [codesandbox](https://codesandbox.io/p/sandbox/reactflow-dark-mode-256l99)
|
||||
- Details: With this version we want to make it easier to switch between dark and light modes and give you a better starting point for dark flows. If you pass colorMode=”dark”, we add the class name “dark” to the wrapper and use it to adjust the styling. To make the implementation for this new feature easier on our ends, we switched to CSS variables for most of the styles. These variables can also be used in user land to customize a flow.
|
||||
|
||||
### Minor Changes
|
||||
### More features and updates
|
||||
|
||||
- [#2535](https://github.com/wbkd/react-flow/pull/2535) [`7902a3ce`](https://github.com/wbkd/react-flow/commit/7902a3ce3188426d5cd07cf0943a68f679e67948) Thanks [@moklick](https://github.com/moklick)! - Feat: Add edge label renderer
|
||||
- [#2536](https://github.com/wbkd/react-flow/pull/2536) [`b25d499e`](https://github.com/wbkd/react-flow/commit/b25d499ec05b5c6f21ac552d03650eb37433552e) Thanks [@pengfu](https://github.com/pengfu)! - Feat: add deleteElements helper function
|
||||
- [#2539](https://github.com/wbkd/react-flow/pull/2539) [`4fc1253e`](https://github.com/wbkd/react-flow/commit/4fc1253eadf9b7dd392d8dc2348f44fa8d08f931) Thanks [@moklick](https://github.com/moklick)! - Feat: add intersection helpers
|
||||
- [#2530](https://github.com/wbkd/react-flow/pull/2530) [`8ba4dd5d`](https://github.com/wbkd/react-flow/commit/8ba4dd5d1d4b2e6f107c148de62aec0b688d8b21) Thanks [@moklick](https://github.com/moklick)! - Feat: Add pan and zoom to mini map
|
||||
There is more! Besides the new main features, we added some minor things that were on our list for a long time. We also started to use TS docs for better docs. We already started to add some docs for some types and hooks which should improve the developer experience.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2538](https://github.com/wbkd/react-flow/pull/2538) [`740659c0`](https://github.com/wbkd/react-flow/commit/740659c0e788c7572d4a1e64e1d33d60712233fc) Thanks [@neo](https://github.com/neo)! - Refactor: put React Flow in isolated stacking context
|
||||
|
||||
## 11.1.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- make pro options acc type optional
|
||||
- cleanup types
|
||||
- fix rf id handling
|
||||
- always render nodes when dragging=true
|
||||
- don't apply animations to helper edge
|
||||
|
||||
## 11.1.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [`c44413d`](https://github.com/wbkd/react-flow/commit/c44413d816604ae2d6ad81ed227c3dfde1a7bd8a) Thanks [@moklick](https://github.com/moklick)! - chore(panel): dont break user selection above panel
|
||||
- [`48c402c`](https://github.com/wbkd/react-flow/commit/48c402c4d3bd9e16dc91cd4c549324e57b6d5c57) Thanks [@moklick](https://github.com/moklick)! - refactor(aria-descriptions): render when disableKeyboardA11y is true
|
||||
- [`3a1a365`](https://github.com/wbkd/react-flow/commit/3a1a365a63fc4564d9a8d96309908986fcc86f95) Thanks [@moklick](https://github.com/moklick)! - fix(useOnSelectionChange): repair hook closes #2484
|
||||
- [`5d35094`](https://github.com/wbkd/react-flow/commit/5d350942d33ded626b3387206f0b0dee368efdfb) Thanks [@neo](https://github.com/neo)! - Add css files as sideEffects
|
||||
|
||||
## 11.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [`def11008`](https://github.com/wbkd/react-flow/commit/def11008d88749fec40e6fcba8bc41eea2511bab) Thanks [@moklick](https://github.com/moklick)! - New props: nodesFocusable and edgesFocusable
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [`d00faa6b`](https://github.com/wbkd/react-flow/commit/d00faa6b3e77388bfd655d4c02e9a5375bc515e4) Thanks [@moklick](https://github.com/moklick)! - Make nopan class name overwritable with class name option
|
||||
|
||||
## 11.0.0
|
||||
|
||||
### Major Changes
|
||||
|
||||
- **Better [Accessibility](/docs/guides/accessibility)**
|
||||
- Nodes and edges are focusable, selectable, moveable and deleteable with the keyboard.
|
||||
- `aria-` default attributes for all elements and controllable via `ariaLabel` options
|
||||
- Keyboard controls can be disabled with the new `disableKeyboardA11y` prop
|
||||
- **Better selectable edges** via new edge option: `interactionWidth` - renders invisible edge that makes it easier to interact
|
||||
- **Better routing for smoothstep and step edges**: https://twitter.com/reactflowdev/status/1567535405284614145
|
||||
- **Nicer edge updating behaviour**: https://twitter.com/reactflowdev/status/1564966917517021184
|
||||
- **Node origin**: The new `nodeOrigin` prop lets you control the origin of a node. Useful for layouting.
|
||||
- **New background pattern**: `BackgroundVariant.Cross` variant
|
||||
- **[`useOnViewportChange`](/docs/api/hooks/use-on-viewport-change) hook** - handle viewport changes within a component
|
||||
- **[`useOnSelectionChange`](/docs/api/hooks/use-on-selection-change) hook** - handle selection changes within a component
|
||||
- **[`useNodesInitialized`](/docs/api/hooks/use-nodes-initialized) hook** - returns true if all nodes are initialized and if there is more than one node
|
||||
- **Deletable option** for Nodes and edges
|
||||
- **New Event handlers**: `onPaneMouseEnter`, `onPaneMouseMove` and `onPaneMouseLeave`
|
||||
- **Edge `pathOptions`** for `smoothstep` and `default` edges
|
||||
- **Nicer cursor defaults**: Cursor is grabbing, while dragging a node or panning
|
||||
- **Pane moveable** with middle mouse button
|
||||
- **Pan over nodes** when they are not draggable (`draggable=false` or `nodesDraggable` false)
|
||||
- **[`<BaseEdge />`](/docs/api/edges/base-edge) component** that makes it easier to build custom edges
|
||||
- **[Separately installable packages](/docs/overview/packages/)**
|
||||
- @reactflow/core
|
||||
- @reactflow/background
|
||||
- @reactflow/controls
|
||||
- @reactflow/minimap
|
||||
- **`useConnection` hook:** This hook makes it possible to handle an ongoing connection. For example, you can use it for colorizing handles.
|
||||
- **`onDelete` handler**: We added a combined handler for `onDeleteNodes` and `onDeleteEdges` to make it easier to react to deletions.
|
||||
- **`isValidConnection` prop:** This makes it possible to implement one validation function for all connections. It also gets called for programatically added edges.
|
||||
- **Controlled `viewport`:** This is definitely an advanced feature. Possible use cases are to animate the viewport or round the transform for lower res screens for example. This features brings two new props: `viewport` and `onViewportChange`.
|
||||
- **`ViewportPortal` component:** This makes it possible to render elements in the viewport without the need to implement a custom node.
|
||||
- **Background component**: add `patternClassName` to be able to style the background pattern by using a class name. This is useful if you want to style the background pattern with Tailwind for example.
|
||||
- **`onMove` callback** gets triggered for library-invoked viewport updates (like fitView or zoom-in)
|
||||
- **`deleteElements`** now returns deleted nodes and deleted edges
|
||||
- add **`origin` attribute** for nodes
|
||||
- add **`selectable` attribute** for edges
|
||||
- Correct types for `BezierEdge`, `StepEdge`, `SmoothStepEdge` and `StraightEdge` components
|
||||
- New edges created by the library only have `sourceHandle` and `targetHandle` attributes when those attributes are set. (We used to pass `sourceHandle: null` and `targetHandle: null`)
|
||||
- Edges do not mount/unmount when their z-index change
|
||||
|
||||
### Internal changes
|
||||
|
||||
These changes are not really user-facing, but it could be important for folks who are working with the React Flow store:
|
||||
|
||||
- The biggest internal change is that we created a new package **@xyflow/system with framework agnostic helpers** that can be used be React Flow and Svelte Flow
|
||||
- **XYDrag** for handling dragging node(s) and selection
|
||||
- **XYPanZoom** for controlling the viewport panning and zooming
|
||||
- **XYHandle** for managing new connections
|
||||
- We replaced the `nodeInternals` map with a `nodes` array. We added a new `nodeLookup` map that serves as a lookup, but we are not creating a new map object on any change so it’s really only useful as a lookup.
|
||||
- We removed `connectionNodeId`, `connectionHandleId`, `connectionHandleType` from the store and added `connectionStartHandle.nodeId`, `connectionStartHandle.handleId`, …
|
||||
- add `data-id` to edges
|
||||
|
||||
**With v12 the `reactflow` package was renamed to `@xyflow/react` - you can find the v11 source and the [`reactflow` changelog](https://github.com/xyflow/xyflow/blob/v11/packages/reactflow/CHANGELOG.md) on the v11 branch.**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xyflow/react",
|
||||
"version": "12.0.0",
|
||||
"version": "12.0.0-next.26",
|
||||
"description": "React Flow - A highly customizable React library for building node-based editors and interactive flow charts.",
|
||||
"keywords": [
|
||||
"react",
|
||||
@@ -16,7 +16,7 @@
|
||||
],
|
||||
"source": "src/index.ts",
|
||||
"main": "dist/umd/index.js",
|
||||
"module": "dist/esm/index.mjs",
|
||||
"module": "dist/esm/index.js",
|
||||
"types": "dist/esm/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
@@ -36,8 +36,8 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/wbkd/react-flow.git",
|
||||
"directory": "packages/core"
|
||||
"url": "https://github.com/xyflow/xyflow.git",
|
||||
"directory": "packages/react"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "concurrently \"rollup --config node:@xyflow/rollup-config --watch\" pnpm:css-watch",
|
||||
@@ -48,15 +48,8 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/d3": "^7.4.0",
|
||||
"@types/d3-drag": "^3.0.1",
|
||||
"@types/d3-selection": "^3.0.3",
|
||||
"@types/d3-zoom": "^3.0.1",
|
||||
"@xyflow/system": "workspace:*",
|
||||
"classcat": "^5.0.3",
|
||||
"d3-drag": "^3.0.0",
|
||||
"d3-selection": "^3.0.0",
|
||||
"d3-zoom": "^3.0.0",
|
||||
"zustand": "^4.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
@@ -73,7 +66,7 @@
|
||||
"autoprefixer": "^10.4.15",
|
||||
"cssnano": "^6.0.1",
|
||||
"postcss": "^8.4.21",
|
||||
"postcss-cli": "^10.1.0",
|
||||
"postcss-cli": "^11.0.0",
|
||||
"postcss-combine-duplicated-selectors": "^10.0.3",
|
||||
"postcss-import": "^15.1.0",
|
||||
"postcss-nested": "^6.0.0",
|
||||
@@ -84,12 +77,9 @@
|
||||
"rollup": {
|
||||
"globals": {
|
||||
"classcat": "cc",
|
||||
"d3-selection": "d3Selection",
|
||||
"d3-zoom": "d3Zoom",
|
||||
"d3-drag": "d3Drag",
|
||||
"zustand": "zustand",
|
||||
"zustand/shallow": "zustandShallow"
|
||||
},
|
||||
"name": "ReactFlowCore"
|
||||
"name": "ReactFlow"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import { type ReactFlowState } from '../../types';
|
||||
import { BackgroundProps, BackgroundVariant } from './types';
|
||||
import { DotPattern, LinePattern } from './Patterns';
|
||||
import { containerStyle } from '../../styles/utils';
|
||||
import { type BackgroundProps, BackgroundVariant } from './types';
|
||||
import { type ReactFlowState } from '../../types';
|
||||
|
||||
const defaultSize = {
|
||||
[BackgroundVariant.Dots]: 1,
|
||||
@@ -16,7 +16,7 @@ const defaultSize = {
|
||||
|
||||
const selector = (s: ReactFlowState) => ({ transform: s.transform, patternId: `pattern-${s.rfId}` });
|
||||
|
||||
function Background({
|
||||
function BackgroundComponent({
|
||||
id,
|
||||
variant = BackgroundVariant.Dots,
|
||||
// only used for dots and cross
|
||||
@@ -55,8 +55,8 @@ function Background({
|
||||
{
|
||||
...style,
|
||||
...containerStyle,
|
||||
'--background-color-props': bgColor,
|
||||
'--background-pattern-color-props': color,
|
||||
'--xy-background-color-props': bgColor,
|
||||
'--xy-background-pattern-color-props': color,
|
||||
} as CSSProperties
|
||||
}
|
||||
ref={ref}
|
||||
@@ -87,6 +87,6 @@ function Background({
|
||||
);
|
||||
}
|
||||
|
||||
Background.displayName = 'Background';
|
||||
BackgroundComponent.displayName = 'Background';
|
||||
|
||||
export default memo(Background);
|
||||
export const Background = memo(BackgroundComponent);
|
||||
|
||||
@@ -26,6 +26,6 @@ type DotPatternProps = {
|
||||
|
||||
export function DotPattern({ radius, className }: DotPatternProps) {
|
||||
return (
|
||||
<circle cx={radius} cy={radius} r={radius} className={cc(['react-flow__background-pattern', 'dot', className])} />
|
||||
<circle cx={radius} cy={radius} r={radius} className={cc(['react-flow__background-pattern', 'dots', className])} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export { default as Background } from './Background';
|
||||
export * from './types';
|
||||
export { Background } from './Background';
|
||||
export { BackgroundVariant, type BackgroundProps } from './types';
|
||||
|
||||
@@ -8,14 +8,27 @@ export enum BackgroundVariant {
|
||||
|
||||
export type BackgroundProps = {
|
||||
id?: string;
|
||||
/** Color of the pattern */
|
||||
color?: string;
|
||||
/** Color of the background */
|
||||
bgColor?: string;
|
||||
/** Class applied to the container */
|
||||
className?: string;
|
||||
/** Class applied to the pattern */
|
||||
patternClassName?: string;
|
||||
/** Gap between repetitions of the pattern */
|
||||
gap?: number | [number, number];
|
||||
/** Size of a single pattern element */
|
||||
size?: number;
|
||||
/** Offset of the pattern */
|
||||
offset?: number;
|
||||
/** Line width of the Line pattern */
|
||||
lineWidth?: number;
|
||||
/** Variant of the pattern
|
||||
* @example BackgroundVariant.Lines, BackgroundVariant.Dots, BackgroundVariant.Cross
|
||||
* 'lines', 'dots', 'cross'
|
||||
*/
|
||||
variant?: BackgroundVariant;
|
||||
/** Style applied to the container */
|
||||
style?: CSSProperties;
|
||||
};
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import type { FC, PropsWithChildren } from 'react';
|
||||
import cc from 'classcat';
|
||||
|
||||
import type { ControlButtonProps } from './types';
|
||||
|
||||
const ControlButton: FC<PropsWithChildren<ControlButtonProps>> = ({ children, className, ...rest }) => (
|
||||
<button type="button" className={cc(['react-flow__controls-button', className])} {...rest}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
ControlButton.displayName = 'ControlButton';
|
||||
|
||||
export default ControlButton;
|
||||
export function ControlButton({ children, className, ...rest }: ControlButtonProps) {
|
||||
return (
|
||||
<button type="button" className={cc(['react-flow__controls-button', className])} {...rest}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import { memo, type FC, type PropsWithChildren } from 'react';
|
||||
import { memo } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import useReactFlow from '../../hooks/useReactFlow';
|
||||
import Panel from '../../components/Panel';
|
||||
import { useReactFlow } from '../../hooks/useReactFlow';
|
||||
import { Panel } from '../../components/Panel';
|
||||
import { type ReactFlowState } from '../../types';
|
||||
|
||||
import PlusIcon from './Icons/Plus';
|
||||
import MinusIcon from './Icons/Minus';
|
||||
import FitviewIcon from './Icons/FitView';
|
||||
import LockIcon from './Icons/Lock';
|
||||
import UnlockIcon from './Icons/Unlock';
|
||||
import ControlButton from './ControlButton';
|
||||
|
||||
import { PlusIcon } from './Icons/Plus';
|
||||
import { MinusIcon } from './Icons/Minus';
|
||||
import { FitViewIcon } from './Icons/FitView';
|
||||
import { LockIcon } from './Icons/Lock';
|
||||
import { UnlockIcon } from './Icons/Unlock';
|
||||
import { ControlButton } from './ControlButton';
|
||||
import type { ControlProps } from './types';
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
@@ -22,7 +21,7 @@ const selector = (s: ReactFlowState) => ({
|
||||
maxZoomReached: s.transform[2] >= s.maxZoom,
|
||||
});
|
||||
|
||||
const Controls: FC<PropsWithChildren<ControlProps>> = ({
|
||||
function ControlsComponent({
|
||||
style,
|
||||
showZoom = true,
|
||||
showFitView = true,
|
||||
@@ -35,7 +34,9 @@ const Controls: FC<PropsWithChildren<ControlProps>> = ({
|
||||
className,
|
||||
children,
|
||||
position = 'bottom-left',
|
||||
}) => {
|
||||
orientation = 'vertical',
|
||||
'aria-label': ariaLabel = 'React Flow controls',
|
||||
}: ControlProps) {
|
||||
const store = useStoreApi();
|
||||
const { isInteractive, minZoomReached, maxZoomReached } = useStore(selector, shallow);
|
||||
const { zoomIn, zoomOut, fitView } = useReactFlow();
|
||||
@@ -65,12 +66,15 @@ const Controls: FC<PropsWithChildren<ControlProps>> = ({
|
||||
onInteractiveChange?.(!isInteractive);
|
||||
};
|
||||
|
||||
const orientationClass = orientation === 'horizontal' ? 'horizontal' : 'vertical';
|
||||
|
||||
return (
|
||||
<Panel
|
||||
className={cc(['react-flow__controls', className])}
|
||||
className={cc(['react-flow__controls', orientationClass, className])}
|
||||
position={position}
|
||||
style={style}
|
||||
data-testid="rf__controls"
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{showZoom && (
|
||||
<>
|
||||
@@ -101,7 +105,7 @@ const Controls: FC<PropsWithChildren<ControlProps>> = ({
|
||||
title="fit view"
|
||||
aria-label="fit view"
|
||||
>
|
||||
<FitviewIcon />
|
||||
<FitViewIcon />
|
||||
</ControlButton>
|
||||
)}
|
||||
{showInteractive && (
|
||||
@@ -117,8 +121,8 @@ const Controls: FC<PropsWithChildren<ControlProps>> = ({
|
||||
{children}
|
||||
</Panel>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
Controls.displayName = 'Controls';
|
||||
ControlsComponent.displayName = 'Controls';
|
||||
|
||||
export default memo(Controls);
|
||||
export const Controls = memo(ControlsComponent);
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
function FitViewIcon() {
|
||||
export function FitViewIcon() {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 30">
|
||||
<path d="M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default FitViewIcon;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
function LockIcon() {
|
||||
export function LockIcon() {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 32">
|
||||
<path d="M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default LockIcon;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
function MinusIcon() {
|
||||
export function MinusIcon() {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 5">
|
||||
<path d="M0 0h32v4.2H0z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default MinusIcon;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
function PlusIcon() {
|
||||
export function PlusIcon() {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<path d="M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default PlusIcon;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
function UnlockIcon() {
|
||||
export function UnlockIcon() {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 32">
|
||||
<path d="M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default UnlockIcon;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export { default as Controls } from './Controls';
|
||||
export { default as ControlButton } from './ControlButton';
|
||||
export * from './types';
|
||||
export { Controls } from './Controls';
|
||||
export { ControlButton } from './ControlButton';
|
||||
export type { ControlProps, ControlButtonProps } from './types';
|
||||
|
||||
@@ -1,18 +1,37 @@
|
||||
import type { ButtonHTMLAttributes, HTMLAttributes } from 'react';
|
||||
import type { ButtonHTMLAttributes, ReactNode } from 'react';
|
||||
import type { PanelPosition } from '@xyflow/system';
|
||||
|
||||
import type { FitViewOptions } from '../../types';
|
||||
|
||||
export type ControlProps = HTMLAttributes<HTMLDivElement> & {
|
||||
export type ControlProps = {
|
||||
/** Show button for zoom in/out */
|
||||
showZoom?: boolean;
|
||||
/** Show button for fit view */
|
||||
showFitView?: boolean;
|
||||
/** Show button for toggling interactivity */
|
||||
showInteractive?: boolean;
|
||||
/** Options being used when fit view button is clicked */
|
||||
fitViewOptions?: FitViewOptions;
|
||||
/** Callback when zoom in button is clicked */
|
||||
onZoomIn?: () => void;
|
||||
/** Callback when zoom out button is clicked */
|
||||
onZoomOut?: () => void;
|
||||
/** Callback when fit view button is clicked */
|
||||
onFitView?: () => void;
|
||||
/** Callback when interactivity is toggled */
|
||||
onInteractiveChange?: (interactiveStatus: boolean) => void;
|
||||
/** Position of the controls on the pane
|
||||
* @example PanelPosition.TopLeft, PanelPosition.TopRight,
|
||||
* PanelPosition.BottomLeft, PanelPosition.BottomRight
|
||||
*/
|
||||
position?: PanelPosition;
|
||||
children?: ReactNode;
|
||||
/** Style applied to container */
|
||||
style?: React.CSSProperties;
|
||||
/** ClassName applied to container */
|
||||
className?: string;
|
||||
'aria-label'?: string;
|
||||
orientation?: 'horizontal' | 'vertical';
|
||||
};
|
||||
|
||||
export type ControlButtonProps = ButtonHTMLAttributes<HTMLButtonElement>;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { memo, useEffect, useRef, type MouseEvent, useCallback } from 'react';
|
||||
import { memo, useEffect, useRef, type MouseEvent, useCallback, CSSProperties } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { getRectOfNodes, getBoundsOfRects, XYMinimap, type Rect, type XYMinimapInstance } from '@xyflow/system';
|
||||
import { getInternalNodesBounds, getBoundsOfRects, XYMinimap, type Rect, type XYMinimapInstance } from '@xyflow/system';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import Panel from '../../components/Panel';
|
||||
import type { ReactFlowState } from '../../types';
|
||||
import { Panel } from '../../components/Panel';
|
||||
import type { ReactFlowState, Node } from '../../types';
|
||||
|
||||
import type { MiniMapProps } from './types';
|
||||
import MiniMapNodes from './MiniMapNodes';
|
||||
import type { MiniMapProps } from './types';
|
||||
|
||||
const defaultWidth = 200;
|
||||
const defaultHeight = 150;
|
||||
@@ -25,9 +25,8 @@ const selector = (s: ReactFlowState) => {
|
||||
|
||||
return {
|
||||
viewBB,
|
||||
boundingRect: s.nodes.length > 0 ? getBoundsOfRects(getRectOfNodes(s.nodes, s.nodeOrigin), viewBB) : viewBB,
|
||||
boundingRect: s.nodeLookup.size > 0 ? getBoundsOfRects(getInternalNodesBounds(s.nodeLookup), viewBB) : viewBB,
|
||||
rfId: s.rfId,
|
||||
nodeOrigin: s.nodeOrigin,
|
||||
panZoom: s.panZoom,
|
||||
translateExtent: s.translateExtent,
|
||||
flowWidth: s.width,
|
||||
@@ -37,20 +36,21 @@ const selector = (s: ReactFlowState) => {
|
||||
|
||||
const ARIA_LABEL_KEY = 'react-flow__minimap-desc';
|
||||
|
||||
function MiniMap({
|
||||
function MiniMapComponent<NodeType extends Node = Node>({
|
||||
style,
|
||||
className,
|
||||
nodeStrokeColor = 'transparent',
|
||||
nodeColor = '#e2e2e2',
|
||||
nodeStrokeColor,
|
||||
nodeColor,
|
||||
nodeClassName = '',
|
||||
nodeBorderRadius = 5,
|
||||
nodeStrokeWidth = 2,
|
||||
nodeStrokeWidth,
|
||||
// We need to rename the prop to be `CapitalCase` so that JSX will render it as
|
||||
// a component properly.
|
||||
nodeComponent,
|
||||
maskColor = 'rgb(240, 240, 240, 0.6)',
|
||||
maskStrokeColor = 'none',
|
||||
maskStrokeWidth = 1,
|
||||
bgColor,
|
||||
maskColor,
|
||||
maskStrokeColor,
|
||||
maskStrokeWidth,
|
||||
position = 'bottom-right',
|
||||
onClick,
|
||||
onNodeClick,
|
||||
@@ -60,8 +60,8 @@ function MiniMap({
|
||||
inversePan,
|
||||
zoomStep = 10,
|
||||
offsetScale = 5,
|
||||
}: MiniMapProps) {
|
||||
const store = useStoreApi();
|
||||
}: MiniMapProps<NodeType>) {
|
||||
const store = useStoreApi<NodeType>();
|
||||
const svg = useRef<SVGSVGElement>(null);
|
||||
const { boundingRect, viewBB, rfId, panZoom, translateExtent, flowWidth, flowHeight } = useStore(selector, shallow);
|
||||
const elementWidth = (style?.width as number) ?? defaultWidth;
|
||||
@@ -118,7 +118,7 @@ function MiniMap({
|
||||
|
||||
const onSvgNodeClick = onNodeClick
|
||||
? useCallback((event: MouseEvent, nodeId: string) => {
|
||||
const node = store.getState().nodes.find((n) => n.id === nodeId)!;
|
||||
const node = store.getState().nodeLookup.get(nodeId)!;
|
||||
onNodeClick(event, node);
|
||||
}, [])
|
||||
: undefined;
|
||||
@@ -126,7 +126,19 @@ function MiniMap({
|
||||
return (
|
||||
<Panel
|
||||
position={position}
|
||||
style={style}
|
||||
style={
|
||||
{
|
||||
...style,
|
||||
'--xy-minimap-background-color-props': typeof bgColor === 'string' ? bgColor : undefined,
|
||||
'--xy-minimap-mask-background-color-props': typeof maskColor === 'string' ? maskColor : undefined,
|
||||
'--xy-minimap-mask-stroke-color-props': typeof maskStrokeColor === 'string' ? maskStrokeColor : undefined,
|
||||
'--xy-minimap-mask-stroke-width-props':
|
||||
typeof maskStrokeWidth === 'number' ? maskStrokeWidth * viewScale : undefined,
|
||||
'--xy-minimap-node-background-color-props': typeof nodeColor === 'string' ? nodeColor : undefined,
|
||||
'--xy-minimap-node-stroke-color-props': typeof nodeStrokeColor === 'string' ? nodeStrokeColor : undefined,
|
||||
'--xy-minimap-node-stroke-width-props': typeof nodeStrokeWidth === 'string' ? nodeStrokeWidth : undefined,
|
||||
} as CSSProperties
|
||||
}
|
||||
className={cc(['react-flow__minimap', className])}
|
||||
data-testid="rf__minimap"
|
||||
>
|
||||
@@ -134,13 +146,14 @@ function MiniMap({
|
||||
width={elementWidth}
|
||||
height={elementHeight}
|
||||
viewBox={`${x} ${y} ${width} ${height}`}
|
||||
className="react-flow__minimap-svg"
|
||||
role="img"
|
||||
aria-labelledby={labelledBy}
|
||||
ref={svg}
|
||||
onClick={onSvgClick}
|
||||
>
|
||||
{ariaLabel && <title id={labelledBy}>{ariaLabel}</title>}
|
||||
<MiniMapNodes
|
||||
<MiniMapNodes<NodeType>
|
||||
onClick={onSvgNodeClick}
|
||||
nodeColor={nodeColor}
|
||||
nodeStrokeColor={nodeStrokeColor}
|
||||
@@ -153,10 +166,7 @@ function MiniMap({
|
||||
className="react-flow__minimap-mask"
|
||||
d={`M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z
|
||||
M${viewBB.x},${viewBB.y}h${viewBB.width}v${viewBB.height}h${-viewBB.width}z`}
|
||||
fill={maskColor}
|
||||
fillRule="evenodd"
|
||||
stroke={maskStrokeColor}
|
||||
strokeWidth={maskStrokeWidth}
|
||||
pointerEvents="none"
|
||||
/>
|
||||
</svg>
|
||||
@@ -164,6 +174,6 @@ function MiniMap({
|
||||
);
|
||||
}
|
||||
|
||||
MiniMap.displayName = 'MiniMap';
|
||||
MiniMapComponent.displayName = 'MiniMap';
|
||||
|
||||
export default memo(MiniMap);
|
||||
export const MiniMap = memo(MiniMapComponent) as typeof MiniMapComponent;
|
||||
|
||||
@@ -3,7 +3,7 @@ import cc from 'classcat';
|
||||
|
||||
import type { MiniMapNodeProps } from './types';
|
||||
|
||||
function MiniMapNode({
|
||||
function MiniMapNodeComponent({
|
||||
id,
|
||||
x,
|
||||
y,
|
||||
@@ -31,13 +31,15 @@ function MiniMapNode({
|
||||
ry={borderRadius}
|
||||
width={width}
|
||||
height={height}
|
||||
fill={fill}
|
||||
stroke={strokeColor}
|
||||
strokeWidth={strokeWidth}
|
||||
style={{
|
||||
fill,
|
||||
stroke: strokeColor,
|
||||
strokeWidth,
|
||||
}}
|
||||
shapeRendering={shapeRendering}
|
||||
onClick={onClick ? (event) => onClick(event, id) : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(MiniMapNode);
|
||||
export const MiniMapNode = memo(MiniMapNodeComponent);
|
||||
|
||||
@@ -1,66 +1,121 @@
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { memo } from 'react';
|
||||
import { ComponentType, memo } from 'react';
|
||||
import { getNodeDimensions, nodeHasDimensions } from '@xyflow/system';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { getNodePositionWithOrigin } from '@xyflow/system';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import type { ReactFlowState } from '../../types';
|
||||
import MiniMapNode from './MiniMapNode';
|
||||
import type { MiniMapNodes, GetMiniMapNodeAttribute } from './types';
|
||||
import { MiniMapNode } from './MiniMapNode';
|
||||
import type { ReactFlowState, Node, InternalNode } from '../../types';
|
||||
import type { MiniMapNodes as MiniMapNodesProps, GetMiniMapNodeAttribute, MiniMapNodeProps } from './types';
|
||||
|
||||
declare const window: any;
|
||||
|
||||
const selector = (s: ReactFlowState) => s.nodeOrigin;
|
||||
const selectorNodes = (s: ReactFlowState) => s.nodes.filter((node) => !node.hidden && node.width && node.height);
|
||||
const getAttrFunction = (func: any): GetMiniMapNodeAttribute => (func instanceof Function ? func : () => func);
|
||||
const selectorNodeIds = (s: ReactFlowState) => s.nodes.map((node) => node.id);
|
||||
const getAttrFunction = <NodeType extends Node>(func: any): GetMiniMapNodeAttribute<NodeType> =>
|
||||
func instanceof Function ? func : () => func;
|
||||
|
||||
function MiniMapNodes({
|
||||
nodeStrokeColor = 'transparent',
|
||||
nodeColor = '#e2e2e2',
|
||||
function MiniMapNodes<NodeType extends Node>({
|
||||
nodeStrokeColor,
|
||||
nodeColor,
|
||||
nodeClassName = '',
|
||||
nodeBorderRadius = 5,
|
||||
nodeStrokeWidth = 2,
|
||||
nodeStrokeWidth,
|
||||
// We need to rename the prop to be `CapitalCase` so that JSX will render it as
|
||||
// a component properly.
|
||||
nodeComponent: NodeComponent = MiniMapNode,
|
||||
onClick,
|
||||
}: MiniMapNodes) {
|
||||
const nodes = useStore(selectorNodes, shallow);
|
||||
const nodeOrigin = useStore(selector);
|
||||
const nodeColorFunc = getAttrFunction(nodeColor);
|
||||
const nodeStrokeColorFunc = getAttrFunction(nodeStrokeColor);
|
||||
const nodeClassNameFunc = getAttrFunction(nodeClassName);
|
||||
}: MiniMapNodesProps<NodeType>) {
|
||||
const nodeIds = useStore(selectorNodeIds, shallow);
|
||||
const nodeColorFunc = getAttrFunction<NodeType>(nodeColor);
|
||||
const nodeStrokeColorFunc = getAttrFunction<NodeType>(nodeStrokeColor);
|
||||
const nodeClassNameFunc = getAttrFunction<NodeType>(nodeClassName);
|
||||
|
||||
const shapeRendering = typeof window === 'undefined' || !!window.chrome ? 'crispEdges' : 'geometricPrecision';
|
||||
|
||||
return (
|
||||
<>
|
||||
{nodes.map((node) => {
|
||||
const { x, y } = getNodePositionWithOrigin(node, node.origin || nodeOrigin).positionAbsolute;
|
||||
|
||||
return (
|
||||
<NodeComponent
|
||||
key={node.id}
|
||||
x={x}
|
||||
y={y}
|
||||
width={node.width!}
|
||||
height={node.height!}
|
||||
style={node.style}
|
||||
selected={!!node.selected}
|
||||
className={nodeClassNameFunc(node)}
|
||||
color={nodeColorFunc(node)}
|
||||
borderRadius={nodeBorderRadius}
|
||||
strokeColor={nodeStrokeColorFunc(node)}
|
||||
strokeWidth={nodeStrokeWidth}
|
||||
shapeRendering={shapeRendering}
|
||||
onClick={onClick}
|
||||
id={node.id}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{nodeIds.map((nodeId) => (
|
||||
// The split of responsibilities between MiniMapNodes and
|
||||
// NodeComponentWrapper may appear weird. However, it’s designed to
|
||||
// minimize the cost of updates when individual nodes change.
|
||||
//
|
||||
// For more details, see a similar commit in `NodeRenderer/index.tsx`.
|
||||
<NodeComponentWrapper<NodeType>
|
||||
key={nodeId}
|
||||
id={nodeId}
|
||||
nodeColorFunc={nodeColorFunc}
|
||||
nodeStrokeColorFunc={nodeStrokeColorFunc}
|
||||
nodeClassNameFunc={nodeClassNameFunc}
|
||||
nodeBorderRadius={nodeBorderRadius}
|
||||
nodeStrokeWidth={nodeStrokeWidth}
|
||||
NodeComponent={NodeComponent}
|
||||
onClick={onClick}
|
||||
shapeRendering={shapeRendering}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(MiniMapNodes);
|
||||
function NodeComponentWrapperInner<NodeType extends Node>({
|
||||
id,
|
||||
nodeColorFunc,
|
||||
nodeStrokeColorFunc,
|
||||
nodeClassNameFunc,
|
||||
nodeBorderRadius,
|
||||
nodeStrokeWidth,
|
||||
shapeRendering,
|
||||
NodeComponent,
|
||||
onClick,
|
||||
}: {
|
||||
id: string;
|
||||
nodeColorFunc: GetMiniMapNodeAttribute<NodeType>;
|
||||
nodeStrokeColorFunc: GetMiniMapNodeAttribute<NodeType>;
|
||||
nodeClassNameFunc: GetMiniMapNodeAttribute<NodeType>;
|
||||
nodeBorderRadius: number;
|
||||
nodeStrokeWidth?: number;
|
||||
NodeComponent: ComponentType<MiniMapNodeProps>;
|
||||
onClick: MiniMapNodesProps['onClick'];
|
||||
shapeRendering: string;
|
||||
}) {
|
||||
const { node, x, y } = useStore((s) => {
|
||||
const node = s.nodeLookup.get(id) as InternalNode<NodeType>;
|
||||
const { x, y } = node.internals.positionAbsolute;
|
||||
|
||||
return {
|
||||
node,
|
||||
x,
|
||||
y,
|
||||
};
|
||||
}, shallow);
|
||||
|
||||
if (!node || node.hidden || !nodeHasDimensions(node)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { width, height } = getNodeDimensions(node);
|
||||
|
||||
return (
|
||||
<NodeComponent
|
||||
x={x}
|
||||
y={y}
|
||||
width={width}
|
||||
height={height}
|
||||
style={node.style}
|
||||
selected={!!node.selected}
|
||||
className={nodeClassNameFunc(node)}
|
||||
color={nodeColorFunc(node)}
|
||||
borderRadius={nodeBorderRadius}
|
||||
strokeColor={nodeStrokeColorFunc(node)}
|
||||
strokeWidth={nodeStrokeWidth}
|
||||
shapeRendering={shapeRendering}
|
||||
onClick={onClick}
|
||||
id={node.id}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const NodeComponentWrapper = memo(NodeComponentWrapperInner) as typeof NodeComponentWrapperInner;
|
||||
|
||||
export default memo(MiniMapNodes) as typeof MiniMapNodes;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export { default as MiniMap } from './MiniMap';
|
||||
export { MiniMap } from './MiniMap';
|
||||
export * from './types';
|
||||
|
||||
@@ -4,31 +4,54 @@ import type { PanelPosition, XYPosition } from '@xyflow/system';
|
||||
|
||||
import type { Node } from '../../types';
|
||||
|
||||
export type GetMiniMapNodeAttribute<NodeData = any> = (node: Node<NodeData>) => string;
|
||||
export type GetMiniMapNodeAttribute<NodeType extends Node = Node> = (node: NodeType) => string;
|
||||
|
||||
export type MiniMapProps<NodeData = any> = Omit<HTMLAttributes<SVGSVGElement>, 'onClick'> & {
|
||||
nodeColor?: string | GetMiniMapNodeAttribute<NodeData>;
|
||||
nodeStrokeColor?: string | GetMiniMapNodeAttribute<NodeData>;
|
||||
nodeClassName?: string | GetMiniMapNodeAttribute<NodeData>;
|
||||
export type MiniMapProps<NodeType extends Node = Node> = Omit<HTMLAttributes<SVGSVGElement>, 'onClick'> & {
|
||||
/** Color of nodes on minimap */
|
||||
nodeColor?: string | GetMiniMapNodeAttribute<NodeType>;
|
||||
/** Stroke color of nodes on minimap */
|
||||
nodeStrokeColor?: string | GetMiniMapNodeAttribute<NodeType>;
|
||||
/** ClassName applied to nodes on minimap */
|
||||
nodeClassName?: string | GetMiniMapNodeAttribute<NodeType>;
|
||||
/** Border radius of nodes on minimap */
|
||||
nodeBorderRadius?: number;
|
||||
/** Stroke width of nodes on minimap */
|
||||
nodeStrokeWidth?: number;
|
||||
/** Component used to render nodes on minimap */
|
||||
nodeComponent?: ComponentType<MiniMapNodeProps>;
|
||||
/** Background color of minimap */
|
||||
bgColor?: string;
|
||||
/** Color of mask representing viewport */
|
||||
maskColor?: string;
|
||||
/** Stroke color of mask representing viewport */
|
||||
maskStrokeColor?: string;
|
||||
/** Stroke width of mask representing viewport */
|
||||
maskStrokeWidth?: number;
|
||||
/** Position of minimap on pane
|
||||
* @example PanelPosition.TopLeft, PanelPosition.TopRight,
|
||||
* PanelPosition.BottomLeft, PanelPosition.BottomRight
|
||||
*/
|
||||
position?: PanelPosition;
|
||||
/** Callback caled when minimap is clicked*/
|
||||
onClick?: (event: MouseEvent, position: XYPosition) => void;
|
||||
onNodeClick?: (event: MouseEvent, node: Node<NodeData>) => void;
|
||||
/** Callback called when node on minimap is clicked */
|
||||
onNodeClick?: (event: MouseEvent, node: NodeType) => void;
|
||||
/** If true, viewport is pannable via mini map component */
|
||||
pannable?: boolean;
|
||||
/** If true, viewport is zoomable via mini map component */
|
||||
zoomable?: boolean;
|
||||
/** The aria-label attribute */
|
||||
ariaLabel?: string | null;
|
||||
/** Invert direction when panning the minimap viewport */
|
||||
inversePan?: boolean;
|
||||
/** Step size for zooming in/out on minimap */
|
||||
zoomStep?: number;
|
||||
/** Offset the viewport on the minmap, acts like a padding */
|
||||
offsetScale?: number;
|
||||
};
|
||||
|
||||
export type MiniMapNodes = Pick<
|
||||
MiniMapProps,
|
||||
export type MiniMapNodes<NodeType extends Node = Node> = Pick<
|
||||
MiniMapProps<NodeType>,
|
||||
'nodeColor' | 'nodeStrokeColor' | 'nodeClassName' | 'nodeBorderRadius' | 'nodeStrokeWidth' | 'nodeComponent'
|
||||
> & {
|
||||
onClick?: (event: MouseEvent, nodeId: string) => void;
|
||||
@@ -42,10 +65,10 @@ export type MiniMapNodeProps = {
|
||||
height: number;
|
||||
borderRadius: number;
|
||||
className: string;
|
||||
color: string;
|
||||
color?: string;
|
||||
shapeRendering: string;
|
||||
strokeColor: string;
|
||||
strokeWidth: number;
|
||||
strokeColor?: string;
|
||||
strokeWidth?: number;
|
||||
style?: CSSProperties;
|
||||
selected: boolean;
|
||||
onClick?: (event: MouseEvent, id: string) => void;
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { useRef, useEffect, memo } from 'react';
|
||||
import cc from 'classcat';
|
||||
import {
|
||||
XYResizer,
|
||||
ResizeControlVariant,
|
||||
type XYResizerInstance,
|
||||
type XYResizerChange,
|
||||
type XYResizerChildChange,
|
||||
type NodeChange,
|
||||
type NodeDimensionChange,
|
||||
type NodePositionChange,
|
||||
handleExpandParent,
|
||||
evaluateAbsolutePosition,
|
||||
ParentExpandChild,
|
||||
XYPosition,
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
import { useNodeId } from '../../contexts/NodeIdContext';
|
||||
import type { ResizeControlProps, ResizeControlLineProps } from './types';
|
||||
|
||||
function ResizeControl({
|
||||
nodeId,
|
||||
position,
|
||||
variant = ResizeControlVariant.Handle,
|
||||
className,
|
||||
style = {},
|
||||
children,
|
||||
color,
|
||||
minWidth = 10,
|
||||
minHeight = 10,
|
||||
maxWidth = Number.MAX_VALUE,
|
||||
maxHeight = Number.MAX_VALUE,
|
||||
keepAspectRatio = false,
|
||||
shouldResize,
|
||||
onResizeStart,
|
||||
onResize,
|
||||
onResizeEnd,
|
||||
}: ResizeControlProps) {
|
||||
const contextNodeId = useNodeId();
|
||||
const id = typeof nodeId === 'string' ? nodeId : contextNodeId;
|
||||
const store = useStoreApi();
|
||||
const resizeControlRef = useRef<HTMLDivElement>(null);
|
||||
const defaultPosition = variant === ResizeControlVariant.Line ? 'right' : 'bottom-right';
|
||||
const controlPosition = position ?? defaultPosition;
|
||||
|
||||
const resizer = useRef<XYResizerInstance | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!resizeControlRef.current || !id) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!resizer.current) {
|
||||
resizer.current = XYResizer({
|
||||
domNode: resizeControlRef.current,
|
||||
nodeId: id,
|
||||
getStoreItems: () => {
|
||||
const { nodeLookup, transform, snapGrid, snapToGrid, nodeOrigin } = store.getState();
|
||||
return {
|
||||
nodeLookup,
|
||||
transform,
|
||||
snapGrid,
|
||||
snapToGrid,
|
||||
nodeOrigin,
|
||||
};
|
||||
},
|
||||
onChange: (change: XYResizerChange, childChanges: XYResizerChildChange[]) => {
|
||||
const { triggerNodeChanges, nodeLookup, parentLookup, nodeOrigin } = store.getState();
|
||||
const changes: NodeChange[] = [];
|
||||
const nextPosition = { x: change.x, y: change.y };
|
||||
const node = nodeLookup.get(id);
|
||||
|
||||
if (node && node.expandParent && node.parentId) {
|
||||
const origin = node.origin ?? nodeOrigin;
|
||||
const width = change.width ?? node.measured.width!;
|
||||
const height = change.height ?? node.measured.height!;
|
||||
|
||||
const child: ParentExpandChild = {
|
||||
id: node.id,
|
||||
parentId: node.parentId,
|
||||
rect: {
|
||||
width,
|
||||
height,
|
||||
...evaluateAbsolutePosition(
|
||||
{
|
||||
x: change.x ?? node.position.x,
|
||||
y: change.y ?? node.position.y,
|
||||
},
|
||||
{ width, height },
|
||||
node.parentId,
|
||||
nodeLookup,
|
||||
origin
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
const parentExpandChanges = handleExpandParent([child], nodeLookup, parentLookup, nodeOrigin);
|
||||
changes.push(...parentExpandChanges);
|
||||
|
||||
// when the parent was expanded by the child node, its position will be clamped at
|
||||
// 0,0 when node origin is 0,0 and to width, height if it's 1,1
|
||||
nextPosition.x = change.x ? Math.max(origin[0] * width, change.x) : undefined;
|
||||
nextPosition.y = change.y ? Math.max(origin[1] * height, change.y) : undefined;
|
||||
}
|
||||
|
||||
if (nextPosition.x !== undefined && nextPosition.y !== undefined) {
|
||||
const positionChange: NodePositionChange = {
|
||||
id,
|
||||
type: 'position',
|
||||
position: { ...(nextPosition as XYPosition) },
|
||||
};
|
||||
changes.push(positionChange);
|
||||
}
|
||||
|
||||
if (change.width !== undefined && change.height !== undefined) {
|
||||
const dimensionChange: NodeDimensionChange = {
|
||||
id,
|
||||
type: 'dimensions',
|
||||
resizing: true,
|
||||
setAttributes: true,
|
||||
dimensions: {
|
||||
width: change.width,
|
||||
height: change.height,
|
||||
},
|
||||
};
|
||||
|
||||
changes.push(dimensionChange);
|
||||
}
|
||||
|
||||
for (const childChange of childChanges) {
|
||||
const positionChange: NodePositionChange = {
|
||||
...childChange,
|
||||
type: 'position',
|
||||
};
|
||||
|
||||
changes.push(positionChange);
|
||||
}
|
||||
|
||||
triggerNodeChanges(changes);
|
||||
},
|
||||
onEnd: () => {
|
||||
const dimensionChange: NodeDimensionChange = {
|
||||
id: id,
|
||||
type: 'dimensions',
|
||||
resizing: false,
|
||||
};
|
||||
store.getState().triggerNodeChanges([dimensionChange]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
resizer.current.update({
|
||||
controlPosition,
|
||||
boundaries: {
|
||||
minWidth,
|
||||
minHeight,
|
||||
maxWidth,
|
||||
maxHeight,
|
||||
},
|
||||
keepAspectRatio,
|
||||
onResizeStart,
|
||||
onResize,
|
||||
onResizeEnd,
|
||||
shouldResize,
|
||||
});
|
||||
|
||||
return () => {
|
||||
resizer.current?.destroy();
|
||||
};
|
||||
}, [
|
||||
controlPosition,
|
||||
minWidth,
|
||||
minHeight,
|
||||
maxWidth,
|
||||
maxHeight,
|
||||
keepAspectRatio,
|
||||
onResizeStart,
|
||||
onResize,
|
||||
onResizeEnd,
|
||||
shouldResize,
|
||||
]);
|
||||
|
||||
const positionClassNames = controlPosition.split('-');
|
||||
const colorStyleProp = variant === ResizeControlVariant.Line ? 'borderColor' : 'backgroundColor';
|
||||
const controlStyle = color ? { ...style, [colorStyleProp]: color } : style;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cc(['react-flow__resize-control', 'nodrag', ...positionClassNames, variant, className])}
|
||||
ref={resizeControlRef}
|
||||
style={controlStyle}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ResizeControlLine(props: ResizeControlLineProps) {
|
||||
return <ResizeControl {...props} variant={ResizeControlVariant.Line} />;
|
||||
}
|
||||
|
||||
export const NodeResizeControl = memo(ResizeControl);
|
||||
@@ -1,10 +1,9 @@
|
||||
import ResizeControl from './ResizeControl';
|
||||
import { ControlPosition, NodeResizerProps, ResizeControlVariant, ControlLinePosition } from './types';
|
||||
import { ResizeControlVariant, XY_RESIZER_HANDLE_POSITIONS, XY_RESIZER_LINE_POSITIONS } from '@xyflow/system';
|
||||
|
||||
const handleControls: ControlPosition[] = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
|
||||
const lineControls: ControlLinePosition[] = ['top', 'right', 'bottom', 'left'];
|
||||
import { NodeResizeControl } from './NodeResizeControl';
|
||||
import type { NodeResizerProps } from './types';
|
||||
|
||||
export default function NodeResizer({
|
||||
export function NodeResizer({
|
||||
nodeId,
|
||||
isVisible = true,
|
||||
handleClassName,
|
||||
@@ -28,13 +27,13 @@ export default function NodeResizer({
|
||||
|
||||
return (
|
||||
<>
|
||||
{lineControls.map((c) => (
|
||||
<ResizeControl
|
||||
key={c}
|
||||
{XY_RESIZER_LINE_POSITIONS.map((position) => (
|
||||
<NodeResizeControl
|
||||
key={position}
|
||||
className={lineClassName}
|
||||
style={lineStyle}
|
||||
nodeId={nodeId}
|
||||
position={c}
|
||||
position={position}
|
||||
variant={ResizeControlVariant.Line}
|
||||
color={color}
|
||||
minWidth={minWidth}
|
||||
@@ -48,13 +47,13 @@ export default function NodeResizer({
|
||||
onResizeEnd={onResizeEnd}
|
||||
/>
|
||||
))}
|
||||
{handleControls.map((c) => (
|
||||
<ResizeControl
|
||||
key={c}
|
||||
{XY_RESIZER_HANDLE_POSITIONS.map((position) => (
|
||||
<NodeResizeControl
|
||||
key={position}
|
||||
className={handleClassName}
|
||||
style={handleStyle}
|
||||
nodeId={nodeId}
|
||||
position={c}
|
||||
position={position}
|
||||
color={color}
|
||||
minWidth={minWidth}
|
||||
minHeight={minHeight}
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
import { useRef, useEffect, memo } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { drag } from 'd3-drag';
|
||||
import { select } from 'd3-selection';
|
||||
import { getPointerPosition, clamp } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
import { useNodeId } from '../../contexts/NodeIdContext';
|
||||
import type { NodeChange, NodeDimensionChange, NodePositionChange } from '../../types';
|
||||
import {
|
||||
type ResizeDragEvent,
|
||||
type ResizeControlProps,
|
||||
type ResizeControlLineProps,
|
||||
ResizeControlVariant,
|
||||
} from './types';
|
||||
import { getDirection } from './utils';
|
||||
|
||||
const initPrevValues = { width: 0, height: 0, x: 0, y: 0 };
|
||||
|
||||
const initStartValues = {
|
||||
...initPrevValues,
|
||||
pointerX: 0,
|
||||
pointerY: 0,
|
||||
aspectRatio: 1,
|
||||
};
|
||||
|
||||
function ResizeControl({
|
||||
nodeId,
|
||||
position,
|
||||
variant = ResizeControlVariant.Handle,
|
||||
className,
|
||||
style = {},
|
||||
children,
|
||||
color,
|
||||
minWidth = 10,
|
||||
minHeight = 10,
|
||||
maxWidth = Number.MAX_VALUE,
|
||||
maxHeight = Number.MAX_VALUE,
|
||||
keepAspectRatio = false,
|
||||
shouldResize,
|
||||
onResizeStart,
|
||||
onResize,
|
||||
onResizeEnd,
|
||||
}: ResizeControlProps) {
|
||||
const contextNodeId = useNodeId();
|
||||
const id = typeof nodeId === 'string' ? nodeId : contextNodeId;
|
||||
const store = useStoreApi();
|
||||
const resizeControlRef = useRef<HTMLDivElement>(null);
|
||||
const startValues = useRef<typeof initStartValues>(initStartValues);
|
||||
const prevValues = useRef<typeof initPrevValues>(initPrevValues);
|
||||
const defaultPosition = variant === ResizeControlVariant.Line ? 'right' : 'bottom-right';
|
||||
const controlPosition = position ?? defaultPosition;
|
||||
|
||||
useEffect(() => {
|
||||
if (!resizeControlRef.current || !id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selection = select(resizeControlRef.current);
|
||||
|
||||
const enableX = controlPosition.includes('right') || controlPosition.includes('left');
|
||||
const enableY = controlPosition.includes('bottom') || controlPosition.includes('top');
|
||||
const invertX = controlPosition.includes('left');
|
||||
const invertY = controlPosition.includes('top');
|
||||
|
||||
const dragHandler = drag<HTMLDivElement, unknown>()
|
||||
.on('start', (event: ResizeDragEvent) => {
|
||||
const { nodes, transform, snapGrid, snapToGrid } = store.getState();
|
||||
const node = nodes.find((n) => n.id === id);
|
||||
const { xSnapped, ySnapped } = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
||||
|
||||
prevValues.current = {
|
||||
width: node?.width ?? 0,
|
||||
height: node?.height ?? 0,
|
||||
x: node?.position.x ?? 0,
|
||||
y: node?.position.y ?? 0,
|
||||
};
|
||||
|
||||
startValues.current = {
|
||||
...prevValues.current,
|
||||
pointerX: xSnapped,
|
||||
pointerY: ySnapped,
|
||||
aspectRatio: prevValues.current.width / prevValues.current.height,
|
||||
};
|
||||
|
||||
onResizeStart?.(event, { ...prevValues.current });
|
||||
})
|
||||
.on('drag', (event: ResizeDragEvent) => {
|
||||
const { nodes, transform, snapGrid, snapToGrid, triggerNodeChanges } = store.getState();
|
||||
const { xSnapped, ySnapped } = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
||||
const node = nodes.find((n) => n.id === id);
|
||||
|
||||
if (node) {
|
||||
const changes: NodeChange[] = [];
|
||||
const {
|
||||
pointerX: startX,
|
||||
pointerY: startY,
|
||||
width: startWidth,
|
||||
height: startHeight,
|
||||
x: startNodeX,
|
||||
y: startNodeY,
|
||||
aspectRatio,
|
||||
} = startValues.current;
|
||||
|
||||
const { x: prevX, y: prevY, width: prevWidth, height: prevHeight } = prevValues.current;
|
||||
|
||||
const distX = Math.floor(enableX ? xSnapped - startX : 0);
|
||||
const distY = Math.floor(enableY ? ySnapped - startY : 0);
|
||||
|
||||
let width = clamp(startWidth + (invertX ? -distX : distX), minWidth, maxWidth);
|
||||
let height = clamp(startHeight + (invertY ? -distY : distY), minHeight, maxHeight);
|
||||
|
||||
if (keepAspectRatio) {
|
||||
const nextAspectRatio = width / height;
|
||||
const isDiagonal = enableX && enableY;
|
||||
const isHorizontal = enableX && !enableY;
|
||||
const isVertical = enableY && !enableX;
|
||||
|
||||
width = (nextAspectRatio <= aspectRatio && isDiagonal) || isVertical ? height * aspectRatio : width;
|
||||
height = (nextAspectRatio > aspectRatio && isDiagonal) || isHorizontal ? width / aspectRatio : height;
|
||||
|
||||
if (width >= maxWidth) {
|
||||
width = maxWidth;
|
||||
height = maxWidth / aspectRatio;
|
||||
} else if (width <= minWidth) {
|
||||
width = minWidth;
|
||||
height = minWidth / aspectRatio;
|
||||
}
|
||||
|
||||
if (height >= maxHeight) {
|
||||
height = maxHeight;
|
||||
width = maxHeight * aspectRatio;
|
||||
} else if (height <= minHeight) {
|
||||
height = minHeight;
|
||||
width = minHeight * aspectRatio;
|
||||
}
|
||||
}
|
||||
|
||||
const isWidthChange = width !== prevWidth;
|
||||
const isHeightChange = height !== prevHeight;
|
||||
|
||||
if (invertX || invertY) {
|
||||
const x = invertX ? startNodeX - (width - startWidth) : startNodeX;
|
||||
const y = invertY ? startNodeY - (height - startHeight) : startNodeY;
|
||||
|
||||
// only transform the node if the width or height changes
|
||||
const isXPosChange = x !== prevX && isWidthChange;
|
||||
const isYPosChange = y !== prevY && isHeightChange;
|
||||
|
||||
if (isXPosChange || isYPosChange) {
|
||||
const positionChange: NodePositionChange = {
|
||||
id: node.id,
|
||||
type: 'position',
|
||||
position: {
|
||||
x: isXPosChange ? x : prevX,
|
||||
y: isYPosChange ? y : prevY,
|
||||
},
|
||||
};
|
||||
|
||||
changes.push(positionChange);
|
||||
prevValues.current.x = positionChange.position!.x;
|
||||
prevValues.current.y = positionChange.position!.y;
|
||||
}
|
||||
}
|
||||
|
||||
if (isWidthChange || isHeightChange) {
|
||||
const dimensionChange: NodeDimensionChange = {
|
||||
id: id,
|
||||
type: 'dimensions',
|
||||
updateStyle: true,
|
||||
resizing: true,
|
||||
dimensions: {
|
||||
width: width,
|
||||
height: height,
|
||||
},
|
||||
};
|
||||
|
||||
changes.push(dimensionChange);
|
||||
prevValues.current.width = width;
|
||||
prevValues.current.height = height;
|
||||
}
|
||||
|
||||
if (changes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const direction = getDirection({
|
||||
width: prevValues.current.width,
|
||||
prevWidth,
|
||||
height: prevValues.current.height,
|
||||
prevHeight,
|
||||
invertX,
|
||||
invertY,
|
||||
});
|
||||
|
||||
const nextValues = { ...prevValues.current, direction };
|
||||
|
||||
const callResize = shouldResize?.(event, nextValues);
|
||||
|
||||
if (callResize === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
onResize?.(event, nextValues);
|
||||
triggerNodeChanges(changes);
|
||||
}
|
||||
})
|
||||
.on('end', (event: ResizeDragEvent) => {
|
||||
const dimensionChange: NodeDimensionChange = {
|
||||
id: id,
|
||||
type: 'dimensions',
|
||||
resizing: false,
|
||||
};
|
||||
|
||||
onResizeEnd?.(event, { ...prevValues.current });
|
||||
store.getState().triggerNodeChanges([dimensionChange]);
|
||||
});
|
||||
|
||||
selection.call(dragHandler);
|
||||
|
||||
return () => {
|
||||
selection.on('.drag', null);
|
||||
};
|
||||
}, [
|
||||
id,
|
||||
controlPosition,
|
||||
minWidth,
|
||||
minHeight,
|
||||
maxWidth,
|
||||
maxHeight,
|
||||
keepAspectRatio,
|
||||
onResizeStart,
|
||||
onResize,
|
||||
onResizeEnd,
|
||||
]);
|
||||
|
||||
const positionClassNames = controlPosition.split('-');
|
||||
const colorStyleProp = variant === ResizeControlVariant.Line ? 'borderColor' : 'backgroundColor';
|
||||
const controlStyle = color ? { ...style, [colorStyleProp]: color } : style;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cc(['react-flow__resize-control', 'nodrag', ...positionClassNames, variant, className])}
|
||||
ref={resizeControlRef}
|
||||
style={controlStyle}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ResizeControlLine(props: ResizeControlLineProps) {
|
||||
return <ResizeControl {...props} variant={ResizeControlVariant.Line} />;
|
||||
}
|
||||
|
||||
export default memo(ResizeControl);
|
||||
@@ -1,4 +1,4 @@
|
||||
export { default as NodeResizer } from './NodeResizer';
|
||||
export { default as NodeResizeControl } from './ResizeControl';
|
||||
export { NodeResizer } from './NodeResizer';
|
||||
export { NodeResizeControl } from './NodeResizeControl';
|
||||
|
||||
export * from './types';
|
||||
|
||||
@@ -1,52 +1,51 @@
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import type { D3DragEvent, SubjectPosition } from 'd3-drag';
|
||||
|
||||
export type ResizeParams = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export type ResizeParamsWithDirection = ResizeParams & {
|
||||
direction: number[];
|
||||
};
|
||||
|
||||
type OnResizeHandler<Params = ResizeParams, Result = void> = (event: ResizeDragEvent, params: Params) => Result;
|
||||
|
||||
export type ShouldResize = OnResizeHandler<ResizeParamsWithDirection, boolean>;
|
||||
export type OnResizeStart = OnResizeHandler;
|
||||
export type OnResize = OnResizeHandler<ResizeParamsWithDirection>;
|
||||
export type OnResizeEnd = OnResizeHandler;
|
||||
import type {
|
||||
ControlPosition,
|
||||
ControlLinePosition,
|
||||
ResizeControlVariant,
|
||||
ShouldResize,
|
||||
OnResizeStart,
|
||||
OnResize,
|
||||
OnResizeEnd,
|
||||
} from '@xyflow/system';
|
||||
|
||||
export type NodeResizerProps = {
|
||||
/** Id of the node it is resizing
|
||||
* @remarks optional if used inside custom node
|
||||
*/
|
||||
nodeId?: string;
|
||||
/** Color of the resize handle */
|
||||
color?: string;
|
||||
/** ClassName applied to handle */
|
||||
handleClassName?: string;
|
||||
/** Style applied to handle */
|
||||
handleStyle?: CSSProperties;
|
||||
/** ClassName applied to line */
|
||||
lineClassName?: string;
|
||||
/** Style applied to line */
|
||||
lineStyle?: CSSProperties;
|
||||
/** Are the controls visible */
|
||||
isVisible?: boolean;
|
||||
/** Minimum width of node */
|
||||
minWidth?: number;
|
||||
/** Minimum height of node */
|
||||
minHeight?: number;
|
||||
/** Maximum width of node */
|
||||
maxWidth?: number;
|
||||
/** Maximum height of node */
|
||||
maxHeight?: number;
|
||||
/** Keep aspect ratio when resizing */
|
||||
keepAspectRatio?: boolean;
|
||||
/** Callback to determine if node should resize */
|
||||
shouldResize?: ShouldResize;
|
||||
/** Callback called when resizing starts */
|
||||
onResizeStart?: OnResizeStart;
|
||||
/** Callback called when resizing */
|
||||
onResize?: OnResize;
|
||||
/** Callback called when resizing ends */
|
||||
onResizeEnd?: OnResizeEnd;
|
||||
};
|
||||
|
||||
export type ControlLinePosition = 'top' | 'bottom' | 'left' | 'right';
|
||||
|
||||
export type ControlPosition = ControlLinePosition | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
|
||||
|
||||
export enum ResizeControlVariant {
|
||||
Line = 'line',
|
||||
Handle = 'handle',
|
||||
}
|
||||
|
||||
export type ResizeControlProps = Pick<
|
||||
NodeResizerProps,
|
||||
| 'nodeId'
|
||||
@@ -61,7 +60,14 @@ export type ResizeControlProps = Pick<
|
||||
| 'onResize'
|
||||
| 'onResizeEnd'
|
||||
> & {
|
||||
/** Position of the control
|
||||
* @example ControlPosition.TopLeft, ControlPosition.TopRight,
|
||||
* ControlPosition.BottomLeft, ControlPosition.BottomRight
|
||||
*/
|
||||
position?: ControlPosition;
|
||||
/** Variant of the control
|
||||
* @example ResizeControlVariant.Handle, ResizeControlVariant.Line
|
||||
*/
|
||||
variant?: ResizeControlVariant;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
@@ -71,5 +77,3 @@ export type ResizeControlProps = Pick<
|
||||
export type ResizeControlLineProps = ResizeControlProps & {
|
||||
position?: ControlLinePosition;
|
||||
};
|
||||
|
||||
export type ResizeDragEvent = D3DragEvent<HTMLDivElement, null, SubjectPosition>;
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
type GetDirectionParams = {
|
||||
width: number;
|
||||
prevWidth: number;
|
||||
height: number;
|
||||
prevHeight: number;
|
||||
invertX: boolean;
|
||||
invertY: boolean;
|
||||
};
|
||||
|
||||
// returns an array of two numbers (0, 1 or -1) representing the direction of the resize
|
||||
// 0 = no change, 1 = increase, -1 = decrease
|
||||
export function getDirection({ width, prevWidth, height, prevHeight, invertX, invertY }: GetDirectionParams) {
|
||||
const deltaWidth = width - prevWidth;
|
||||
const deltaHeight = height - prevHeight;
|
||||
|
||||
const direction = [deltaWidth > 0 ? 1 : deltaWidth < 0 ? -1 : 0, deltaHeight > 0 ? 1 : deltaHeight < 0 ? -1 : 0];
|
||||
|
||||
if (deltaWidth && invertX) {
|
||||
direction[0] = direction[0] * -1;
|
||||
}
|
||||
|
||||
if (deltaHeight && invertY) {
|
||||
direction[1] = direction[1] * -1;
|
||||
}
|
||||
return direction;
|
||||
}
|
||||
@@ -1,75 +1,44 @@
|
||||
import { useCallback, CSSProperties } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { getRectOfNodes, Transform, Rect, Position, internalsSymbol } from '@xyflow/system';
|
||||
import { Position, getNodeToolbarTransform, getInternalNodesBounds, NodeLookup } from '@xyflow/system';
|
||||
|
||||
import { Node, ReactFlowState } from '../../types';
|
||||
import { InternalNode, ReactFlowState } from '../../types';
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import { useNodeId } from '../../contexts/NodeIdContext';
|
||||
import NodeToolbarPortal from './NodeToolbarPortal';
|
||||
import { Align, NodeToolbarProps } from './types';
|
||||
import { NodeToolbarPortal } from './NodeToolbarPortal';
|
||||
import type { NodeToolbarProps } from './types';
|
||||
|
||||
const nodeEqualityFn = (a: Node | undefined, b: Node | undefined) =>
|
||||
a?.positionAbsolute?.x === b?.positionAbsolute?.x &&
|
||||
a?.positionAbsolute?.y === b?.positionAbsolute?.y &&
|
||||
a?.width === b?.width &&
|
||||
a?.height === b?.height &&
|
||||
a?.selected === b?.selected &&
|
||||
a?.[internalsSymbol]?.z === b?.[internalsSymbol]?.z;
|
||||
const nodeEqualityFn = (a?: InternalNode, b?: InternalNode) =>
|
||||
a?.internals.positionAbsolute.x !== b?.internals.positionAbsolute.x ||
|
||||
a?.internals.positionAbsolute.y !== b?.internals.positionAbsolute.y ||
|
||||
a?.measured.width !== b?.measured.width ||
|
||||
a?.measured.height !== b?.measured.height ||
|
||||
a?.selected !== b?.selected ||
|
||||
a?.internals.z !== b?.internals.z;
|
||||
|
||||
const nodesEqualityFn = (a: Node[], b: Node[]) => {
|
||||
return a.length === b.length && a.every((node, i) => nodeEqualityFn(node, b[i]));
|
||||
const nodesEqualityFn = (a: NodeLookup, b: NodeLookup) => {
|
||||
if (a.size !== b.size) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const [key, node] of a) {
|
||||
if (nodeEqualityFn(node, b.get(key))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const storeSelector = (state: ReactFlowState) => ({
|
||||
transform: state.transform,
|
||||
nodeOrigin: state.nodeOrigin,
|
||||
x: state.transform[0],
|
||||
y: state.transform[1],
|
||||
zoom: state.transform[2],
|
||||
selectedNodesCount: state.nodes.filter((node) => node.selected).length,
|
||||
});
|
||||
|
||||
function getTransform(nodeRect: Rect, transform: Transform, position: Position, offset: number, align: Align): string {
|
||||
let alignmentOffset = 0.5;
|
||||
|
||||
if (align === 'start') {
|
||||
alignmentOffset = 0;
|
||||
} else if (align === 'end') {
|
||||
alignmentOffset = 1;
|
||||
}
|
||||
|
||||
// position === Position.Top
|
||||
// we set the x any y position of the toolbar based on the nodes position
|
||||
let pos = [
|
||||
(nodeRect.x + nodeRect.width * alignmentOffset) * transform[2] + transform[0],
|
||||
nodeRect.y * transform[2] + transform[1] - offset,
|
||||
];
|
||||
// and than shift it based on the alignment. The shift values are in %.
|
||||
let shift = [-100 * alignmentOffset, -100];
|
||||
|
||||
switch (position) {
|
||||
case Position.Right:
|
||||
pos = [
|
||||
(nodeRect.x + nodeRect.width) * transform[2] + transform[0] + offset,
|
||||
(nodeRect.y + nodeRect.height * alignmentOffset) * transform[2] + transform[1],
|
||||
];
|
||||
shift = [0, -100 * alignmentOffset];
|
||||
break;
|
||||
case Position.Bottom:
|
||||
pos[1] = (nodeRect.y + nodeRect.height) * transform[2] + transform[1] + offset;
|
||||
shift[1] = 0;
|
||||
break;
|
||||
case Position.Left:
|
||||
pos = [
|
||||
nodeRect.x * transform[2] + transform[0] - offset,
|
||||
(nodeRect.y + nodeRect.height * alignmentOffset) * transform[2] + transform[1],
|
||||
];
|
||||
shift = [-100, -100 * alignmentOffset];
|
||||
break;
|
||||
}
|
||||
|
||||
return `translate(${pos[0]}px, ${pos[1]}px) translate(${shift[0]}%, ${shift[1]}%)`;
|
||||
}
|
||||
|
||||
function NodeToolbar({
|
||||
export function NodeToolbar({
|
||||
nodeId,
|
||||
children,
|
||||
className,
|
||||
@@ -83,45 +52,56 @@ function NodeToolbar({
|
||||
const contextNodeId = useNodeId();
|
||||
|
||||
const nodesSelector = useCallback(
|
||||
(state: ReactFlowState): Node[] => {
|
||||
(state: ReactFlowState): NodeLookup => {
|
||||
const nodeIds = Array.isArray(nodeId) ? nodeId : [nodeId || contextNodeId || ''];
|
||||
|
||||
return nodeIds.reduce<Node[]>((acc, id) => {
|
||||
const node = state.nodes.find((n) => n.id === id);
|
||||
const internalNodes = nodeIds.reduce<NodeLookup>((res, id) => {
|
||||
const node = state.nodeLookup.get(id);
|
||||
if (node) {
|
||||
acc.push(node);
|
||||
res.set(node.id, node);
|
||||
}
|
||||
return acc;
|
||||
}, [] as Node[]);
|
||||
|
||||
return res;
|
||||
}, new Map());
|
||||
|
||||
return internalNodes;
|
||||
},
|
||||
[nodeId, contextNodeId]
|
||||
);
|
||||
const nodes = useStore(nodesSelector, nodesEqualityFn);
|
||||
const { transform, nodeOrigin, selectedNodesCount } = useStore(storeSelector, shallow);
|
||||
const isActive =
|
||||
typeof isVisible === 'boolean' ? isVisible : nodes.length === 1 && nodes[0].selected && selectedNodesCount === 1;
|
||||
const { x, y, zoom, selectedNodesCount } = useStore(storeSelector, shallow);
|
||||
|
||||
if (!isActive || !nodes.length) {
|
||||
// if isVisible is not set, we show the toolbar only if its node is selected and no other node is selected
|
||||
const isActive =
|
||||
typeof isVisible === 'boolean'
|
||||
? isVisible
|
||||
: nodes.size === 1 && nodes.values().next().value.selected && selectedNodesCount === 1;
|
||||
|
||||
if (!isActive || !nodes.size) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const nodeRect: Rect = getRectOfNodes(nodes, nodeOrigin);
|
||||
const zIndex: number = Math.max(...nodes.map((node) => (node[internalsSymbol]?.z || 1) + 1));
|
||||
const nodeRect = getInternalNodesBounds(nodes);
|
||||
const nodesArray = Array.from(nodes.values());
|
||||
const zIndex = Math.max(...nodesArray.map((node) => node.internals.z + 1));
|
||||
|
||||
const wrapperStyle: CSSProperties = {
|
||||
position: 'absolute',
|
||||
transform: getTransform(nodeRect, transform, position, offset, align),
|
||||
transform: getNodeToolbarTransform(nodeRect, { x, y, zoom }, position, offset, align),
|
||||
zIndex,
|
||||
...style,
|
||||
};
|
||||
|
||||
return (
|
||||
<NodeToolbarPortal>
|
||||
<div style={wrapperStyle} className={cc(['react-flow__node-toolbar', className])} {...rest}>
|
||||
<div
|
||||
style={wrapperStyle}
|
||||
className={cc(['react-flow__node-toolbar', className])}
|
||||
{...rest}
|
||||
// @todo: check if we could only do this for non-prod envs
|
||||
data-id={nodesArray.reduce((acc, node) => `${acc}${node.id} `, '').trim()}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</NodeToolbarPortal>
|
||||
);
|
||||
}
|
||||
|
||||
export default NodeToolbar;
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useStore } from '../../hooks/useStore';
|
||||
|
||||
const selector = (state: ReactFlowState) => state.domNode?.querySelector('.react-flow__renderer');
|
||||
|
||||
function NodeToolbarPortal({ children }: { children: ReactNode }) {
|
||||
export function NodeToolbarPortal({ children }: { children: ReactNode }) {
|
||||
const wrapperRef = useStore(selector);
|
||||
|
||||
if (!wrapperRef) {
|
||||
@@ -15,5 +15,3 @@ function NodeToolbarPortal({ children }: { children: ReactNode }) {
|
||||
|
||||
return createPortal(children, wrapperRef);
|
||||
}
|
||||
|
||||
export default NodeToolbarPortal;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export { default as NodeToolbar } from './NodeToolbar';
|
||||
export * from './types';
|
||||
export { NodeToolbar } from './NodeToolbar';
|
||||
export type { NodeToolbarProps } from './types';
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import type { Position } from '@xyflow/system';
|
||||
import type { Position, Align } from '@xyflow/system';
|
||||
|
||||
export type NodeToolbarProps = HTMLAttributes<HTMLDivElement> & {
|
||||
/** Id of the node, or array of ids the toolbar should be displayed at */
|
||||
nodeId?: string | string[];
|
||||
/** If true, node toolbar is visible even if node is not selected */
|
||||
isVisible?: boolean;
|
||||
/** Position of the toolbar relative to the node
|
||||
* @example Position.TopLeft, Position.TopRight,
|
||||
* Position.BottomLeft, Position.BottomRight
|
||||
*/
|
||||
position?: Position;
|
||||
/** Offset the toolbar from the node */
|
||||
offset?: number;
|
||||
/** Align the toolbar relative to the node
|
||||
* @example Align.Start, Align.Center, Align.End
|
||||
*/
|
||||
align?: Align;
|
||||
};
|
||||
|
||||
export type Align = 'center' | 'start' | 'end';
|
||||
|
||||
@@ -32,7 +32,7 @@ function AriaLiveMessage({ rfId }: { rfId: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function A11yDescriptions({ rfId, disableKeyboardA11y }: { rfId: string; disableKeyboardA11y: boolean }) {
|
||||
export function A11yDescriptions({ rfId, disableKeyboardA11y }: { rfId: string; disableKeyboardA11y: boolean }) {
|
||||
return (
|
||||
<>
|
||||
<div id={`${ARIA_NODE_DESC_KEY}-${rfId}`} style={style}>
|
||||
@@ -47,5 +47,3 @@ function A11yDescriptions({ rfId, disableKeyboardA11y }: { rfId: string; disable
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default A11yDescriptions;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import type { PanelPosition, ProOptions } from '@xyflow/system';
|
||||
|
||||
import Panel from '../Panel';
|
||||
import { Panel } from '../Panel';
|
||||
|
||||
type AttributionProps = {
|
||||
proOptions?: ProOptions;
|
||||
position?: PanelPosition;
|
||||
};
|
||||
|
||||
function Attribution({ proOptions, position = 'bottom-right' }: AttributionProps) {
|
||||
export function Attribution({ proOptions, position = 'bottom-right' }: AttributionProps) {
|
||||
if (proOptions?.hideAttribution) {
|
||||
return null;
|
||||
}
|
||||
@@ -24,5 +24,3 @@ function Attribution({ proOptions, position = 'bottom-right' }: AttributionProps
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
export default Attribution;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { createContext, ReactNode, useCallback, useContext, useMemo } from 'react';
|
||||
import { EdgeChange, NodeChange } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
import { getElementsDiffChanges } from '../../utils';
|
||||
import { Queue, QueueItem } from './types';
|
||||
import type { Edge, Node } from '../../types';
|
||||
import { useQueue } from './useQueue';
|
||||
|
||||
const BatchContext = createContext<{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
nodeQueue: Queue<any>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
edgeQueue: Queue<any>;
|
||||
} | null>(null);
|
||||
|
||||
/**
|
||||
* This is a context provider that holds and processes the node and edge update queues
|
||||
* that are needed to handle setNodes, addNodes, setEdges and addEdges.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function BatchProvider<NodeType extends Node = Node, EdgeType extends Edge = Edge>({
|
||||
children,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const store = useStoreApi<NodeType, EdgeType>();
|
||||
|
||||
const nodeQueueHandler = useCallback((queueItems: QueueItem<NodeType>[]) => {
|
||||
const { nodes = [], setNodes, hasDefaultNodes, onNodesChange, nodeLookup } = store.getState();
|
||||
|
||||
// This is essentially an `Array.reduce` in imperative clothing. Processing
|
||||
// this queue is a relatively hot path so we'd like to avoid the overhead of
|
||||
// array methods where we can.
|
||||
let next = nodes as NodeType[];
|
||||
for (const payload of queueItems) {
|
||||
next = typeof payload === 'function' ? payload(next) : payload;
|
||||
}
|
||||
|
||||
if (hasDefaultNodes) {
|
||||
setNodes(next);
|
||||
} else if (onNodesChange) {
|
||||
onNodesChange(
|
||||
getElementsDiffChanges({
|
||||
items: next,
|
||||
lookup: nodeLookup,
|
||||
}) as NodeChange<NodeType>[]
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
const nodeQueue = useQueue<NodeType>(nodeQueueHandler);
|
||||
|
||||
const edgeQueueHandler = useCallback((queueItems: QueueItem<EdgeType>[]) => {
|
||||
const { edges = [], setEdges, hasDefaultEdges, onEdgesChange, edgeLookup } = store.getState();
|
||||
|
||||
let next = edges as EdgeType[];
|
||||
for (const payload of queueItems) {
|
||||
next = typeof payload === 'function' ? payload(next) : payload;
|
||||
}
|
||||
|
||||
if (hasDefaultEdges) {
|
||||
setEdges(next);
|
||||
} else if (onEdgesChange) {
|
||||
onEdgesChange(
|
||||
getElementsDiffChanges({
|
||||
items: next,
|
||||
lookup: edgeLookup,
|
||||
}) as EdgeChange<EdgeType>[]
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
const edgeQueue = useQueue<EdgeType>(edgeQueueHandler);
|
||||
|
||||
const value = useMemo(() => ({ nodeQueue, edgeQueue }), []);
|
||||
|
||||
return <BatchContext.Provider value={value}>{children}</BatchContext.Provider>;
|
||||
}
|
||||
|
||||
export function useBatchContext() {
|
||||
const batchContext = useContext(BatchContext);
|
||||
|
||||
if (!batchContext) {
|
||||
throw new Error('useBatchContext must be used within a BatchProvider');
|
||||
}
|
||||
|
||||
return batchContext;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export type QueueItem<T> = T[] | ((items: T[]) => T[]);
|
||||
|
||||
export type Queue<T> = {
|
||||
get: () => QueueItem<T>[];
|
||||
reset: () => void;
|
||||
push: (item: QueueItem<T>) => void;
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useIsomorphicLayoutEffect } from '../../hooks/useIsomorphicLayoutEffect';
|
||||
import { Queue, QueueItem } from './types';
|
||||
|
||||
/**
|
||||
* This hook returns a queue that can be used to batch updates.
|
||||
*
|
||||
* @param runQueue - a function that gets called when the queue is flushed
|
||||
* @internal
|
||||
*
|
||||
* @returns a Queue object
|
||||
*/
|
||||
export function useQueue<T>(runQueue: (items: QueueItem<T>[]) => void) {
|
||||
// Because we're using a ref above, we need some way to let React know when to
|
||||
// actually process the queue. We flip this bit of state to `true` any time we
|
||||
// mutate the queue and then flip it back to `false` after flushing the queue.
|
||||
const [shouldFlush, setShouldFlush] = useState(false);
|
||||
|
||||
// A reference of all the batched updates to process before the next render. We
|
||||
// want a reference here so multiple synchronous calls to `setNodes` etc can be
|
||||
// batched together.
|
||||
const [queue] = useState(() => createQueue<T>(() => setShouldFlush(true)));
|
||||
|
||||
// Layout effects are guaranteed to run before the next render which means we
|
||||
// shouldn't run into any issues with stale state or weird issues that come from
|
||||
// rendering things one frame later than expected (we used to use `setTimeout`).
|
||||
useIsomorphicLayoutEffect(() => {
|
||||
// Because we need to flip the state back to false after flushing, this should
|
||||
// trigger the hook again (!). If the hook is being run again we know that any
|
||||
// updates should have been processed by now and we can safely clear the queue
|
||||
// and bail early.
|
||||
if (!shouldFlush) {
|
||||
queue.reset();
|
||||
return;
|
||||
}
|
||||
|
||||
const queueItems = queue.get();
|
||||
|
||||
if (queueItems.length) {
|
||||
runQueue(queueItems);
|
||||
|
||||
queue.reset();
|
||||
}
|
||||
|
||||
// Beacuse we're using reactive state to trigger this effect, we need to flip
|
||||
// it back to false.
|
||||
setShouldFlush(false);
|
||||
}, [shouldFlush]);
|
||||
|
||||
return queue;
|
||||
}
|
||||
|
||||
function createQueue<T>(cb: () => void): Queue<T> {
|
||||
let queue: QueueItem<T>[] = [];
|
||||
|
||||
return {
|
||||
get: () => queue,
|
||||
reset: () => {
|
||||
queue = [];
|
||||
},
|
||||
push: (item) => {
|
||||
queue.push(item);
|
||||
cb();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,130 +1,18 @@
|
||||
import { CSSProperties, useCallback } from 'react';
|
||||
import { CSSProperties } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import cc from 'classcat';
|
||||
import {
|
||||
internalsSymbol,
|
||||
Position,
|
||||
ConnectionLineType,
|
||||
ConnectionMode,
|
||||
getBezierPath,
|
||||
getSmoothStepPath,
|
||||
type ConnectionStatus,
|
||||
type HandleType,
|
||||
getConnectionStatus,
|
||||
getStraightPath,
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import { getSimpleBezierPath } from '../Edges/SimpleBezierEdge';
|
||||
import type { ConnectionLineComponent, ReactFlowState, ReactFlowStore } from '../../types';
|
||||
|
||||
type ConnectionLineProps = {
|
||||
nodeId: string;
|
||||
handleType: HandleType;
|
||||
type: ConnectionLineType;
|
||||
style?: CSSProperties;
|
||||
CustomComponent?: ConnectionLineComponent;
|
||||
connectionStatus: ConnectionStatus | null;
|
||||
};
|
||||
|
||||
const oppositePosition = {
|
||||
[Position.Left]: Position.Right,
|
||||
[Position.Right]: Position.Left,
|
||||
[Position.Top]: Position.Bottom,
|
||||
[Position.Bottom]: Position.Top,
|
||||
};
|
||||
|
||||
const ConnectionLine = ({
|
||||
nodeId,
|
||||
handleType,
|
||||
style,
|
||||
type = ConnectionLineType.Bezier,
|
||||
CustomComponent,
|
||||
connectionStatus,
|
||||
}: ConnectionLineProps) => {
|
||||
const { fromNode, handleId, toX, toY, connectionMode } = useStore(
|
||||
useCallback(
|
||||
(s: ReactFlowStore) => ({
|
||||
fromNode: s.nodes.find((n) => n.id === nodeId),
|
||||
handleId: s.connectionStartHandle?.handleId,
|
||||
toX: (s.connectionPosition.x - s.transform[0]) / s.transform[2],
|
||||
toY: (s.connectionPosition.y - s.transform[1]) / s.transform[2],
|
||||
connectionMode: s.connectionMode,
|
||||
}),
|
||||
[nodeId]
|
||||
),
|
||||
shallow
|
||||
);
|
||||
const fromHandleBounds = fromNode?.[internalsSymbol]?.handleBounds;
|
||||
let handleBounds = fromHandleBounds?.[handleType];
|
||||
|
||||
if (connectionMode === ConnectionMode.Loose) {
|
||||
handleBounds = handleBounds ? handleBounds : fromHandleBounds?.[handleType === 'source' ? 'target' : 'source'];
|
||||
}
|
||||
|
||||
if (!fromNode || !handleBounds) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fromHandle = handleId ? handleBounds.find((d) => d.id === handleId) : handleBounds[0];
|
||||
const fromHandleX = fromHandle ? fromHandle.x + fromHandle.width / 2 : (fromNode.width ?? 0) / 2;
|
||||
const fromHandleY = fromHandle ? fromHandle.y + fromHandle.height / 2 : fromNode.height ?? 0;
|
||||
const fromX = (fromNode.positionAbsolute?.x ?? 0) + fromHandleX;
|
||||
const fromY = (fromNode.positionAbsolute?.y ?? 0) + fromHandleY;
|
||||
const fromPosition = fromHandle?.position;
|
||||
const toPosition = fromPosition ? oppositePosition[fromPosition] : null;
|
||||
|
||||
if (!fromPosition || !toPosition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (CustomComponent) {
|
||||
return (
|
||||
<CustomComponent
|
||||
connectionLineType={type}
|
||||
connectionLineStyle={style}
|
||||
fromNode={fromNode}
|
||||
fromHandle={fromHandle}
|
||||
fromX={fromX}
|
||||
fromY={fromY}
|
||||
toX={toX}
|
||||
toY={toY}
|
||||
fromPosition={fromPosition}
|
||||
toPosition={toPosition}
|
||||
connectionStatus={connectionStatus}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
let dAttr = '';
|
||||
|
||||
const pathParams = {
|
||||
sourceX: fromX,
|
||||
sourceY: fromY,
|
||||
sourcePosition: fromPosition,
|
||||
targetX: toX,
|
||||
targetY: toY,
|
||||
targetPosition: toPosition,
|
||||
};
|
||||
|
||||
if (type === ConnectionLineType.Bezier) {
|
||||
// we assume the destination position is opposite to the source position
|
||||
[dAttr] = getBezierPath(pathParams);
|
||||
} else if (type === ConnectionLineType.Step) {
|
||||
[dAttr] = getSmoothStepPath({
|
||||
...pathParams,
|
||||
borderRadius: 0,
|
||||
});
|
||||
} else if (type === ConnectionLineType.SmoothStep) {
|
||||
[dAttr] = getSmoothStepPath(pathParams);
|
||||
} else if (type === ConnectionLineType.SimpleBezier) {
|
||||
[dAttr] = getSimpleBezierPath(pathParams);
|
||||
} else {
|
||||
dAttr = `M${fromX},${fromY} ${toX},${toY}`;
|
||||
}
|
||||
|
||||
return <path d={dAttr} fill="none" className="react-flow__connection-path" style={style} />;
|
||||
};
|
||||
|
||||
ConnectionLine.displayName = 'ConnectionLine';
|
||||
import type { ConnectionLineComponent, ReactFlowState } from '../../types';
|
||||
import { useConnection } from '../../hooks/useConnection';
|
||||
|
||||
type ConnectionLineWrapperProps = {
|
||||
type: ConnectionLineType;
|
||||
@@ -134,19 +22,18 @@ type ConnectionLineWrapperProps = {
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
nodeId: s.connectionStartHandle?.nodeId,
|
||||
handleType: s.connectionStartHandle?.type,
|
||||
nodesConnectable: s.nodesConnectable,
|
||||
connectionStatus: s.connectionStatus,
|
||||
isValid: s.connection.isValid,
|
||||
inProgress: s.connection.inProgress,
|
||||
width: s.width,
|
||||
height: s.height,
|
||||
});
|
||||
|
||||
function ConnectionLineWrapper({ containerStyle, style, type, component }: ConnectionLineWrapperProps) {
|
||||
const { nodeId, handleType, nodesConnectable, width, height, connectionStatus } = useStore(selector, shallow);
|
||||
const isValid = !!(nodeId && handleType && width && nodesConnectable);
|
||||
export function ConnectionLineWrapper({ containerStyle, style, type, component }: ConnectionLineWrapperProps) {
|
||||
const { nodesConnectable, width, height, isValid, inProgress } = useStore(selector, shallow);
|
||||
const renderConnection = !!(width && nodesConnectable && inProgress);
|
||||
|
||||
if (!isValid) {
|
||||
if (!renderConnection) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -155,20 +42,81 @@ function ConnectionLineWrapper({ containerStyle, style, type, component }: Conne
|
||||
style={containerStyle}
|
||||
width={width}
|
||||
height={height}
|
||||
className="react-flow__edges react-flow__connectionline react-flow__container"
|
||||
className="react-flow__connectionline react-flow__container"
|
||||
>
|
||||
<g className={cc(['react-flow__connection', connectionStatus])}>
|
||||
<ConnectionLine
|
||||
nodeId={nodeId}
|
||||
handleType={handleType}
|
||||
style={style}
|
||||
type={type}
|
||||
CustomComponent={component}
|
||||
connectionStatus={connectionStatus}
|
||||
/>
|
||||
<g className={cc(['react-flow__connection', getConnectionStatus(isValid)])}>
|
||||
<ConnectionLine style={style} type={type} CustomComponent={component} isValid={isValid} />
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default ConnectionLineWrapper;
|
||||
type ConnectionLineProps = {
|
||||
type: ConnectionLineType;
|
||||
style?: CSSProperties;
|
||||
CustomComponent?: ConnectionLineComponent;
|
||||
isValid: boolean | null;
|
||||
};
|
||||
|
||||
const ConnectionLine = ({ style, type = ConnectionLineType.Bezier, CustomComponent, isValid }: ConnectionLineProps) => {
|
||||
const { inProgress, from, fromNode, fromHandle, fromPosition, to, toNode, toHandle, toPosition } = useConnection();
|
||||
|
||||
if (!inProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (CustomComponent) {
|
||||
return (
|
||||
<CustomComponent
|
||||
connectionLineType={type}
|
||||
connectionLineStyle={style}
|
||||
fromNode={fromNode}
|
||||
fromHandle={fromHandle}
|
||||
fromX={from.x}
|
||||
fromY={from.y}
|
||||
toX={to.x}
|
||||
toY={to.y}
|
||||
fromPosition={fromPosition}
|
||||
toPosition={toPosition}
|
||||
connectionStatus={getConnectionStatus(isValid)}
|
||||
toNode={toNode}
|
||||
toHandle={toHandle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
let path = '';
|
||||
|
||||
const pathParams = {
|
||||
sourceX: from.x,
|
||||
sourceY: from.y,
|
||||
sourcePosition: fromPosition,
|
||||
targetX: to.x,
|
||||
targetY: to.y,
|
||||
targetPosition: toPosition,
|
||||
};
|
||||
|
||||
switch (type) {
|
||||
case ConnectionLineType.Bezier:
|
||||
[path] = getBezierPath(pathParams);
|
||||
break;
|
||||
case ConnectionLineType.SimpleBezier:
|
||||
[path] = getSimpleBezierPath(pathParams);
|
||||
break;
|
||||
case ConnectionLineType.Step:
|
||||
[path] = getSmoothStepPath({
|
||||
...pathParams,
|
||||
borderRadius: 0,
|
||||
});
|
||||
break;
|
||||
case ConnectionLineType.SmoothStep:
|
||||
[path] = getSmoothStepPath(pathParams);
|
||||
break;
|
||||
default:
|
||||
[path] = getStraightPath(pathParams);
|
||||
}
|
||||
|
||||
return <path d={path} fill="none" className="react-flow__connection-path" style={style} />;
|
||||
};
|
||||
|
||||
ConnectionLine.displayName = 'ConnectionLine';
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { ReactFlowState } from '../../types';
|
||||
|
||||
const selector = (s: ReactFlowState) => s.domNode?.querySelector('.react-flow__edgelabel-renderer');
|
||||
|
||||
function EdgeLabelRenderer({ children }: { children: ReactNode }) {
|
||||
export function EdgeLabelRenderer({ children }: { children: ReactNode }) {
|
||||
const edgeLabelRenderer = useStore(selector);
|
||||
|
||||
if (!edgeLabelRenderer) {
|
||||
@@ -15,5 +15,3 @@ function EdgeLabelRenderer({ children }: { children: ReactNode }) {
|
||||
|
||||
return createPortal(children, edgeLabelRenderer);
|
||||
}
|
||||
|
||||
export default EdgeLabelRenderer;
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Reconnectable edges have a anchors around their handles to reconnect the edge.
|
||||
import { XYHandle, type Connection, EdgePosition } from '@xyflow/system';
|
||||
|
||||
import { EdgeAnchor } from '../Edges/EdgeAnchor';
|
||||
import type { EdgeWrapperProps, Edge } from '../../types/edges';
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
|
||||
type EdgeUpdateAnchorsProps<EdgeType extends Edge = Edge> = {
|
||||
edge: EdgeType;
|
||||
isReconnectable: boolean | 'source' | 'target';
|
||||
reconnectRadius: EdgeWrapperProps['reconnectRadius'];
|
||||
sourceHandleId: Edge['sourceHandle'];
|
||||
targetHandleId: Edge['targetHandle'];
|
||||
onReconnect: EdgeWrapperProps<EdgeType>['onReconnect'];
|
||||
onReconnectStart: EdgeWrapperProps<EdgeType>['onReconnectStart'];
|
||||
onReconnectEnd: EdgeWrapperProps<EdgeType>['onReconnectEnd'];
|
||||
setUpdateHover: (hover: boolean) => void;
|
||||
setReconnecting: (updating: boolean) => void;
|
||||
} & EdgePosition;
|
||||
|
||||
export function EdgeUpdateAnchors<EdgeType extends Edge = Edge>({
|
||||
isReconnectable,
|
||||
reconnectRadius,
|
||||
edge,
|
||||
targetHandleId,
|
||||
sourceHandleId,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
sourcePosition,
|
||||
targetPosition,
|
||||
onReconnect,
|
||||
onReconnectStart,
|
||||
onReconnectEnd,
|
||||
setReconnecting,
|
||||
setUpdateHover,
|
||||
}: EdgeUpdateAnchorsProps<EdgeType>) {
|
||||
const store = useStoreApi();
|
||||
|
||||
const handleEdgeUpdater = (event: React.MouseEvent<SVGGElement, MouseEvent>, isSourceHandle: boolean) => {
|
||||
// avoid triggering edge updater if mouse btn is not left
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
autoPanOnConnect,
|
||||
domNode,
|
||||
isValidConnection,
|
||||
connectionMode,
|
||||
connectionRadius,
|
||||
lib,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
cancelConnection,
|
||||
nodeLookup,
|
||||
rfId: flowId,
|
||||
panBy,
|
||||
updateConnection,
|
||||
} = store.getState();
|
||||
const nodeId = isSourceHandle ? edge.target : edge.source;
|
||||
const handleId = (isSourceHandle ? targetHandleId : sourceHandleId) || null;
|
||||
const handleType = isSourceHandle ? 'target' : 'source';
|
||||
|
||||
const isTarget = isSourceHandle;
|
||||
|
||||
setReconnecting(true);
|
||||
onReconnectStart?.(event, edge, handleType);
|
||||
|
||||
const _onReconnectEnd = (evt: MouseEvent | TouchEvent) => {
|
||||
setReconnecting(false);
|
||||
onReconnectEnd?.(evt, edge, handleType);
|
||||
};
|
||||
|
||||
const onConnectEdge = (connection: Connection) => onReconnect?.(edge, connection);
|
||||
|
||||
XYHandle.onPointerDown(event.nativeEvent, {
|
||||
autoPanOnConnect,
|
||||
connectionMode,
|
||||
connectionRadius,
|
||||
domNode,
|
||||
handleId,
|
||||
nodeId,
|
||||
nodeLookup,
|
||||
isTarget,
|
||||
edgeUpdaterType: handleType,
|
||||
lib,
|
||||
flowId,
|
||||
cancelConnection,
|
||||
panBy,
|
||||
isValidConnection,
|
||||
onConnect: onConnectEdge,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
onReconnectEnd: _onReconnectEnd,
|
||||
updateConnection,
|
||||
getTransform: () => store.getState().transform,
|
||||
getFromHandle: () => store.getState().connection.fromHandle,
|
||||
});
|
||||
};
|
||||
|
||||
const onReconnectSourceMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
|
||||
handleEdgeUpdater(event, true);
|
||||
const onReconnectTargetMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
|
||||
handleEdgeUpdater(event, false);
|
||||
const onReconnectMouseEnter = () => setUpdateHover(true);
|
||||
const onReconnectMouseOut = () => setUpdateHover(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
{(isReconnectable === 'source' || isReconnectable === true) && (
|
||||
<EdgeAnchor
|
||||
position={sourcePosition}
|
||||
centerX={sourceX}
|
||||
centerY={sourceY}
|
||||
radius={reconnectRadius}
|
||||
onMouseDown={onReconnectSourceMouseDown}
|
||||
onMouseEnter={onReconnectMouseEnter}
|
||||
onMouseOut={onReconnectMouseOut}
|
||||
type="source"
|
||||
/>
|
||||
)}
|
||||
{(isReconnectable === 'target' || isReconnectable === true) && (
|
||||
<EdgeAnchor
|
||||
position={targetPosition}
|
||||
centerX={targetX}
|
||||
centerY={targetY}
|
||||
radius={reconnectRadius}
|
||||
onMouseDown={onReconnectTargetMouseDown}
|
||||
onMouseEnter={onReconnectMouseEnter}
|
||||
onMouseOut={onReconnectMouseOut}
|
||||
type="target"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import { useState, useMemo, useRef, type KeyboardEvent, useCallback } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import {
|
||||
getMarkerId,
|
||||
elementSelectionKeys,
|
||||
getEdgePosition,
|
||||
errorMessages,
|
||||
getElevatedEdgeZIndex,
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { useStoreApi, useStore } from '../../hooks/useStore';
|
||||
import { ARIA_EDGE_DESC_KEY } from '../A11yDescriptions';
|
||||
import { builtinEdgeTypes, nullPosition } from './utils';
|
||||
import { EdgeUpdateAnchors } from './EdgeUpdateAnchors';
|
||||
import type { Edge, EdgeWrapperProps } from '../../types';
|
||||
|
||||
export function EdgeWrapper<EdgeType extends Edge = Edge>({
|
||||
id,
|
||||
edgesFocusable,
|
||||
edgesReconnectable,
|
||||
elementsSelectable,
|
||||
onClick,
|
||||
onDoubleClick,
|
||||
onContextMenu,
|
||||
onMouseEnter,
|
||||
onMouseMove,
|
||||
onMouseLeave,
|
||||
reconnectRadius,
|
||||
onReconnect,
|
||||
onReconnectStart,
|
||||
onReconnectEnd,
|
||||
rfId,
|
||||
edgeTypes,
|
||||
noPanClassName,
|
||||
onError,
|
||||
disableKeyboardA11y,
|
||||
}: EdgeWrapperProps<EdgeType>): JSX.Element | null {
|
||||
let edge = useStore((s) => s.edgeLookup.get(id)!) as EdgeType;
|
||||
const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
|
||||
edge = defaultEdgeOptions ? { ...defaultEdgeOptions, ...edge } : edge;
|
||||
|
||||
let edgeType = edge.type || 'default';
|
||||
let EdgeComponent = edgeTypes?.[edgeType] || builtinEdgeTypes[edgeType];
|
||||
|
||||
if (EdgeComponent === undefined) {
|
||||
onError?.('011', errorMessages['error011'](edgeType));
|
||||
edgeType = 'default';
|
||||
EdgeComponent = builtinEdgeTypes.default;
|
||||
}
|
||||
|
||||
const isFocusable = !!(edge.focusable || (edgesFocusable && typeof edge.focusable === 'undefined'));
|
||||
const isReconnectable =
|
||||
typeof onReconnect !== 'undefined' &&
|
||||
(edge.reconnectable || (edgesReconnectable && typeof edge.reconnectable === 'undefined'));
|
||||
const isSelectable = !!(edge.selectable || (elementsSelectable && typeof edge.selectable === 'undefined'));
|
||||
|
||||
const edgeRef = useRef<SVGGElement>(null);
|
||||
const [updateHover, setUpdateHover] = useState<boolean>(false);
|
||||
const [reconnecting, setReconnecting] = useState<boolean>(false);
|
||||
const store = useStoreApi();
|
||||
|
||||
const { zIndex, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = useStore(
|
||||
useCallback(
|
||||
(store) => {
|
||||
const sourceNode = store.nodeLookup.get(edge.source);
|
||||
const targetNode = store.nodeLookup.get(edge.target);
|
||||
|
||||
if (!sourceNode || !targetNode) {
|
||||
return {
|
||||
zIndex: edge.zIndex,
|
||||
...nullPosition,
|
||||
};
|
||||
}
|
||||
|
||||
const edgePosition = getEdgePosition({
|
||||
id,
|
||||
sourceNode,
|
||||
targetNode,
|
||||
sourceHandle: edge.sourceHandle || null,
|
||||
targetHandle: edge.targetHandle || null,
|
||||
connectionMode: store.connectionMode,
|
||||
onError,
|
||||
});
|
||||
|
||||
const zIndex = getElevatedEdgeZIndex({
|
||||
selected: edge.selected,
|
||||
zIndex: edge.zIndex,
|
||||
sourceNode,
|
||||
targetNode,
|
||||
elevateOnSelect: store.elevateEdgesOnSelect,
|
||||
});
|
||||
|
||||
return {
|
||||
zIndex,
|
||||
...(edgePosition || nullPosition),
|
||||
};
|
||||
},
|
||||
[edge.source, edge.target, edge.sourceHandle, edge.targetHandle, edge.selected, edge.zIndex]
|
||||
),
|
||||
shallow
|
||||
);
|
||||
|
||||
const markerStartUrl = useMemo(
|
||||
() => (edge.markerStart ? `url('#${getMarkerId(edge.markerStart, rfId)}')` : undefined),
|
||||
[edge.markerStart, rfId]
|
||||
);
|
||||
|
||||
const markerEndUrl = useMemo(
|
||||
() => (edge.markerEnd ? `url('#${getMarkerId(edge.markerEnd, rfId)}')` : undefined),
|
||||
[edge.markerEnd, rfId]
|
||||
);
|
||||
|
||||
if (edge.hidden || sourceX === null || sourceY === null || targetX === null || targetY === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onEdgeClick = (event: React.MouseEvent<SVGGElement, MouseEvent>): void => {
|
||||
const { addSelectedEdges, unselectNodesAndEdges, multiSelectionActive } = store.getState();
|
||||
|
||||
if (isSelectable) {
|
||||
store.setState({ nodesSelectionActive: false });
|
||||
|
||||
if (edge.selected && multiSelectionActive) {
|
||||
unselectNodesAndEdges({ nodes: [], edges: [edge] });
|
||||
edgeRef.current?.blur();
|
||||
} else {
|
||||
addSelectedEdges([id]);
|
||||
}
|
||||
}
|
||||
|
||||
if (onClick) {
|
||||
onClick(event, edge);
|
||||
}
|
||||
};
|
||||
|
||||
const onEdgeDoubleClick = onDoubleClick
|
||||
? (event: React.MouseEvent) => {
|
||||
onDoubleClick(event, { ...edge });
|
||||
}
|
||||
: undefined;
|
||||
const onEdgeContextMenu = onContextMenu
|
||||
? (event: React.MouseEvent) => {
|
||||
onContextMenu(event, { ...edge });
|
||||
}
|
||||
: undefined;
|
||||
const onEdgeMouseEnter = onMouseEnter
|
||||
? (event: React.MouseEvent) => {
|
||||
onMouseEnter(event, { ...edge });
|
||||
}
|
||||
: undefined;
|
||||
const onEdgeMouseMove = onMouseMove
|
||||
? (event: React.MouseEvent) => {
|
||||
onMouseMove(event, { ...edge });
|
||||
}
|
||||
: undefined;
|
||||
const onEdgeMouseLeave = onMouseLeave
|
||||
? (event: React.MouseEvent) => {
|
||||
onMouseLeave(event, { ...edge });
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (!disableKeyboardA11y && elementSelectionKeys.includes(event.key) && isSelectable) {
|
||||
const { unselectNodesAndEdges, addSelectedEdges } = store.getState();
|
||||
const unselect = event.key === 'Escape';
|
||||
|
||||
if (unselect) {
|
||||
edgeRef.current?.blur();
|
||||
unselectNodesAndEdges({ edges: [edge] });
|
||||
} else {
|
||||
addSelectedEdges([id]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<svg style={{ zIndex }}>
|
||||
<g
|
||||
className={cc([
|
||||
'react-flow__edge',
|
||||
`react-flow__edge-${edgeType}`,
|
||||
edge.className,
|
||||
noPanClassName,
|
||||
{
|
||||
selected: edge.selected,
|
||||
animated: edge.animated,
|
||||
inactive: !isSelectable && !onClick,
|
||||
updating: updateHover,
|
||||
selectable: isSelectable,
|
||||
},
|
||||
])}
|
||||
onClick={onEdgeClick}
|
||||
onDoubleClick={onEdgeDoubleClick}
|
||||
onContextMenu={onEdgeContextMenu}
|
||||
onMouseEnter={onEdgeMouseEnter}
|
||||
onMouseMove={onEdgeMouseMove}
|
||||
onMouseLeave={onEdgeMouseLeave}
|
||||
onKeyDown={isFocusable ? onKeyDown : undefined}
|
||||
tabIndex={isFocusable ? 0 : undefined}
|
||||
role={isFocusable ? 'button' : 'img'}
|
||||
data-id={id}
|
||||
data-testid={`rf__edge-${id}`}
|
||||
aria-label={
|
||||
edge.ariaLabel === null ? undefined : edge.ariaLabel || `Edge from ${edge.source} to ${edge.target}`
|
||||
}
|
||||
aria-describedby={isFocusable ? `${ARIA_EDGE_DESC_KEY}-${rfId}` : undefined}
|
||||
ref={edgeRef}
|
||||
>
|
||||
{!reconnecting && (
|
||||
<EdgeComponent
|
||||
id={id}
|
||||
source={edge.source}
|
||||
target={edge.target}
|
||||
type={edge.type}
|
||||
selected={edge.selected}
|
||||
animated={edge.animated}
|
||||
selectable={isSelectable}
|
||||
deletable={edge.deletable ?? true}
|
||||
label={edge.label}
|
||||
labelStyle={edge.labelStyle}
|
||||
labelShowBg={edge.labelShowBg}
|
||||
labelBgStyle={edge.labelBgStyle}
|
||||
labelBgPadding={edge.labelBgPadding}
|
||||
labelBgBorderRadius={edge.labelBgBorderRadius}
|
||||
sourceX={sourceX}
|
||||
sourceY={sourceY}
|
||||
targetX={targetX}
|
||||
targetY={targetY}
|
||||
sourcePosition={sourcePosition}
|
||||
targetPosition={targetPosition}
|
||||
data={edge.data}
|
||||
style={edge.style}
|
||||
sourceHandleId={edge.sourceHandle}
|
||||
targetHandleId={edge.targetHandle}
|
||||
markerStart={markerStartUrl}
|
||||
markerEnd={markerEndUrl}
|
||||
pathOptions={'pathOptions' in edge ? edge.pathOptions : undefined}
|
||||
interactionWidth={edge.interactionWidth}
|
||||
/>
|
||||
)}
|
||||
{isReconnectable && (
|
||||
<EdgeUpdateAnchors<EdgeType>
|
||||
edge={edge}
|
||||
isReconnectable={isReconnectable}
|
||||
reconnectRadius={reconnectRadius}
|
||||
onReconnect={onReconnect}
|
||||
onReconnectStart={onReconnectStart}
|
||||
onReconnectEnd={onReconnectEnd}
|
||||
sourceX={sourceX}
|
||||
sourceY={sourceY}
|
||||
targetX={targetX}
|
||||
targetY={targetY}
|
||||
sourcePosition={sourcePosition}
|
||||
targetPosition={targetPosition}
|
||||
setUpdateHover={setUpdateHover}
|
||||
setReconnecting={setReconnecting}
|
||||
sourceHandleId={edge.sourceHandle}
|
||||
targetHandleId={edge.targetHandle}
|
||||
/>
|
||||
)}
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { EdgeTypes } from '../../types';
|
||||
import {
|
||||
BezierEdgeInternal,
|
||||
StraightEdgeInternal,
|
||||
StepEdgeInternal,
|
||||
SmoothStepEdgeInternal,
|
||||
SimpleBezierEdgeInternal,
|
||||
} from '../Edges';
|
||||
|
||||
export const builtinEdgeTypes: EdgeTypes = {
|
||||
default: BezierEdgeInternal,
|
||||
straight: StraightEdgeInternal,
|
||||
step: StepEdgeInternal,
|
||||
smoothstep: SmoothStepEdgeInternal,
|
||||
simplebezier: SimpleBezierEdgeInternal,
|
||||
};
|
||||
|
||||
export const nullPosition = {
|
||||
sourceX: null,
|
||||
sourceY: null,
|
||||
targetX: null,
|
||||
targetY: null,
|
||||
sourcePosition: null,
|
||||
targetPosition: null,
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
import { isNumeric } from '@xyflow/system';
|
||||
import cc from 'classcat';
|
||||
|
||||
import { EdgeText } from './EdgeText';
|
||||
import type { BaseEdgeProps } from '../../types';
|
||||
|
||||
import EdgeText from './EdgeText';
|
||||
|
||||
const BaseEdge = ({
|
||||
export function BaseEdge({
|
||||
id,
|
||||
path,
|
||||
labelX,
|
||||
@@ -18,8 +18,9 @@ const BaseEdge = ({
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
className,
|
||||
interactionWidth = 20,
|
||||
}: BaseEdgeProps) => {
|
||||
}: BaseEdgeProps) {
|
||||
return (
|
||||
<>
|
||||
<path
|
||||
@@ -27,7 +28,7 @@ const BaseEdge = ({
|
||||
style={style}
|
||||
d={path}
|
||||
fill="none"
|
||||
className="react-flow__edge-path"
|
||||
className={cc(['react-flow__edge-path', className])}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
/>
|
||||
@@ -54,8 +55,4 @@ const BaseEdge = ({
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
BaseEdge.displayName = 'BaseEdge';
|
||||
|
||||
export default BaseEdge;
|
||||
}
|
||||
|
||||
@@ -1,59 +1,70 @@
|
||||
import { memo } from 'react';
|
||||
import { Position, getBezierPath } from '@xyflow/system';
|
||||
|
||||
import BaseEdge from './BaseEdge';
|
||||
import { BaseEdge } from './BaseEdge';
|
||||
import type { BezierEdgeProps } from '../../types';
|
||||
|
||||
const BezierEdge = memo(
|
||||
({
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
sourcePosition = Position.Bottom,
|
||||
targetPosition = Position.Top,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
pathOptions,
|
||||
interactionWidth,
|
||||
}: BezierEdgeProps) => {
|
||||
const [path, labelX, labelY] = getBezierPath({
|
||||
function createBezierEdge(params: { isInternal: boolean }) {
|
||||
// eslint-disable-next-line react/display-name
|
||||
return memo(
|
||||
({
|
||||
id,
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
curvature: pathOptions?.curvature,
|
||||
});
|
||||
sourcePosition = Position.Bottom,
|
||||
targetPosition = Position.Top,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
pathOptions,
|
||||
interactionWidth,
|
||||
}: BezierEdgeProps) => {
|
||||
const [path, labelX, labelY] = getBezierPath({
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
curvature: pathOptions?.curvature,
|
||||
});
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
const _id = params.isInternal ? undefined : id;
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
id={_id}
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const BezierEdge = createBezierEdge({ isInternal: false });
|
||||
const BezierEdgeInternal = createBezierEdge({ isInternal: true });
|
||||
|
||||
BezierEdge.displayName = 'BezierEdge';
|
||||
BezierEdgeInternal.displayName = 'BezierEdgeInternal';
|
||||
|
||||
export default BezierEdge;
|
||||
export { BezierEdge, BezierEdgeInternal };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { FC, MouseEvent as ReactMouseEvent, SVGAttributes } from 'react';
|
||||
import type { MouseEvent as ReactMouseEvent, SVGAttributes } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { Position } from '@xyflow/system';
|
||||
|
||||
@@ -27,7 +27,7 @@ export interface EdgeAnchorProps extends SVGAttributes<SVGGElement> {
|
||||
|
||||
const EdgeUpdaterClassName = 'react-flow__edgeupdater';
|
||||
|
||||
export const EdgeAnchor: FC<EdgeAnchorProps> = ({
|
||||
export function EdgeAnchor({
|
||||
position,
|
||||
centerX,
|
||||
centerY,
|
||||
@@ -36,16 +36,18 @@ export const EdgeAnchor: FC<EdgeAnchorProps> = ({
|
||||
onMouseEnter,
|
||||
onMouseOut,
|
||||
type,
|
||||
}: EdgeAnchorProps) => (
|
||||
<circle
|
||||
onMouseDown={onMouseDown}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseOut={onMouseOut}
|
||||
className={cc([EdgeUpdaterClassName, `${EdgeUpdaterClassName}-${type}`])}
|
||||
cx={shiftX(centerX, radius, position)}
|
||||
cy={shiftY(centerY, radius, position)}
|
||||
r={radius}
|
||||
stroke="transparent"
|
||||
fill="transparent"
|
||||
/>
|
||||
);
|
||||
}: EdgeAnchorProps) {
|
||||
return (
|
||||
<circle
|
||||
onMouseDown={onMouseDown}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseOut={onMouseOut}
|
||||
className={cc([EdgeUpdaterClassName, `${EdgeUpdaterClassName}-${type}`])}
|
||||
cx={shiftX(centerX, radius, position)}
|
||||
cy={shiftY(centerY, radius, position)}
|
||||
r={radius}
|
||||
stroke="transparent"
|
||||
fill="transparent"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { memo, useRef, useState, useEffect, type FC, type PropsWithChildren } from 'react';
|
||||
import { memo, useState, useEffect, useRef } from 'react';
|
||||
import cc from 'classcat';
|
||||
import type { Rect } from '@xyflow/system';
|
||||
|
||||
import type { EdgeTextProps } from '../../types';
|
||||
|
||||
const EdgeText: FC<PropsWithChildren<EdgeTextProps>> = ({
|
||||
function EdgeTextComponent({
|
||||
x,
|
||||
y,
|
||||
label,
|
||||
@@ -16,14 +16,14 @@ const EdgeText: FC<PropsWithChildren<EdgeTextProps>> = ({
|
||||
children,
|
||||
className,
|
||||
...rest
|
||||
}) => {
|
||||
const edgeRef = useRef<SVGTextElement>(null);
|
||||
const [edgeTextBbox, setEdgeTextBbox] = useState<Rect>({ x: 0, y: 0, width: 0, height: 0 });
|
||||
}: EdgeTextProps) {
|
||||
const [edgeTextBbox, setEdgeTextBbox] = useState<Rect>({ x: 1, y: 0, width: 0, height: 0 });
|
||||
const edgeTextClasses = cc(['react-flow__edge-textwrapper', className]);
|
||||
const edgeTextRef = useRef<SVGTextElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (edgeRef.current) {
|
||||
const textBbox = edgeRef.current.getBBox();
|
||||
if (edgeTextRef.current) {
|
||||
const textBbox = edgeTextRef.current.getBBox();
|
||||
|
||||
setEdgeTextBbox({
|
||||
x: textBbox.x,
|
||||
@@ -57,11 +57,20 @@ const EdgeText: FC<PropsWithChildren<EdgeTextProps>> = ({
|
||||
ry={labelBgBorderRadius}
|
||||
/>
|
||||
)}
|
||||
<text className="react-flow__edge-text" y={edgeTextBbox.height / 2} dy="0.3em" ref={edgeRef} style={labelStyle}>
|
||||
<text
|
||||
className="react-flow__edge-text"
|
||||
y={edgeTextBbox.height / 2}
|
||||
dy="0.3em"
|
||||
ref={edgeTextRef}
|
||||
style={labelStyle}
|
||||
>
|
||||
{label}
|
||||
</text>
|
||||
{children}
|
||||
</g>
|
||||
);
|
||||
};
|
||||
export default memo(EdgeText);
|
||||
}
|
||||
|
||||
EdgeTextComponent.displayName = 'EdgeText';
|
||||
|
||||
export const EdgeText = memo(EdgeTextComponent);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { memo } from 'react';
|
||||
import { Position, getBezierEdgeCenter } from '@xyflow/system';
|
||||
|
||||
import BaseEdge from './BaseEdge';
|
||||
import type { EdgeProps } from '../../types';
|
||||
import { BaseEdge } from './BaseEdge';
|
||||
import type { SimpleBezierEdgeProps } from '../../types';
|
||||
|
||||
export interface GetSimpleBezierPathParams {
|
||||
sourceX: number;
|
||||
@@ -71,54 +71,65 @@ export function getSimpleBezierPath({
|
||||
];
|
||||
}
|
||||
|
||||
const SimpleBezierEdge = memo(
|
||||
({
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
sourcePosition = Position.Bottom,
|
||||
targetPosition = Position.Top,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
interactionWidth,
|
||||
}: EdgeProps) => {
|
||||
const [path, labelX, labelY] = getSimpleBezierPath({
|
||||
function createSimpleBezierEdge(params: { isInternal: boolean }) {
|
||||
// eslint-disable-next-line react/display-name
|
||||
return memo(
|
||||
({
|
||||
id,
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
});
|
||||
sourcePosition = Position.Bottom,
|
||||
targetPosition = Position.Top,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
interactionWidth,
|
||||
}: SimpleBezierEdgeProps) => {
|
||||
const [path, labelX, labelY] = getSimpleBezierPath({
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
});
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
const _id = params.isInternal ? undefined : id;
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
id={_id}
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const SimpleBezierEdge = createSimpleBezierEdge({ isInternal: false });
|
||||
const SimpleBezierEdgeInternal = createSimpleBezierEdge({ isInternal: true });
|
||||
|
||||
SimpleBezierEdge.displayName = 'SimpleBezierEdge';
|
||||
SimpleBezierEdgeInternal.displayName = 'SimpleBezierEdgeInternal';
|
||||
|
||||
export default SimpleBezierEdge;
|
||||
export { SimpleBezierEdge, SimpleBezierEdgeInternal };
|
||||
|
||||
@@ -1,60 +1,71 @@
|
||||
import { memo } from 'react';
|
||||
import { Position, getSmoothStepPath } from '@xyflow/system';
|
||||
|
||||
import BaseEdge from './BaseEdge';
|
||||
import { BaseEdge } from './BaseEdge';
|
||||
import type { SmoothStepEdgeProps } from '../../types';
|
||||
|
||||
const SmoothStepEdge = memo(
|
||||
({
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
sourcePosition = Position.Bottom,
|
||||
targetPosition = Position.Top,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
pathOptions,
|
||||
interactionWidth,
|
||||
}: SmoothStepEdgeProps) => {
|
||||
const [path, labelX, labelY] = getSmoothStepPath({
|
||||
function createSmoothStepEdge(params: { isInternal: boolean }) {
|
||||
// eslint-disable-next-line react/display-name
|
||||
return memo(
|
||||
({
|
||||
id,
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
borderRadius: pathOptions?.borderRadius,
|
||||
offset: pathOptions?.offset,
|
||||
});
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
sourcePosition = Position.Bottom,
|
||||
targetPosition = Position.Top,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
pathOptions,
|
||||
interactionWidth,
|
||||
}: SmoothStepEdgeProps) => {
|
||||
const [path, labelX, labelY] = getSmoothStepPath({
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
borderRadius: pathOptions?.borderRadius,
|
||||
offset: pathOptions?.offset,
|
||||
});
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
const _id = params.isInternal ? undefined : id;
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
id={_id}
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const SmoothStepEdge = createSmoothStepEdge({ isInternal: false });
|
||||
const SmoothStepEdgeInternal = createSmoothStepEdge({ isInternal: true });
|
||||
|
||||
SmoothStepEdge.displayName = 'SmoothStepEdge';
|
||||
SmoothStepEdgeInternal.displayName = 'SmoothStepEdgeInternal';
|
||||
|
||||
export default SmoothStepEdge;
|
||||
export { SmoothStepEdge, SmoothStepEdgeInternal };
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
import { memo, useMemo } from 'react';
|
||||
|
||||
import SmoothStepEdge from './SmoothStepEdge';
|
||||
import type { SmoothStepEdgeProps } from '../../types';
|
||||
import { SmoothStepEdge } from './SmoothStepEdge';
|
||||
import type { StepEdgeProps } from '../../types';
|
||||
|
||||
const StepEdge = memo((props: SmoothStepEdgeProps) => (
|
||||
<SmoothStepEdge
|
||||
{...props}
|
||||
pathOptions={useMemo(() => ({ borderRadius: 0, offset: props.pathOptions?.offset }), [props.pathOptions?.offset])}
|
||||
/>
|
||||
));
|
||||
function createStepEdge(params: { isInternal: boolean }) {
|
||||
// eslint-disable-next-line react/display-name
|
||||
return memo(({ id, ...props }: StepEdgeProps) => {
|
||||
const _id = params.isInternal ? undefined : id;
|
||||
|
||||
return (
|
||||
<SmoothStepEdge
|
||||
{...props}
|
||||
id={_id}
|
||||
pathOptions={useMemo(
|
||||
() => ({ borderRadius: 0, offset: props.pathOptions?.offset }),
|
||||
[props.pathOptions?.offset]
|
||||
)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const StepEdge = createStepEdge({ isInternal: false });
|
||||
const StepEdgeInternal = createStepEdge({ isInternal: true });
|
||||
|
||||
StepEdge.displayName = 'StepEdge';
|
||||
StepEdgeInternal.displayName = 'StepEdgeInternal';
|
||||
|
||||
export default StepEdge;
|
||||
export { StepEdge, StepEdgeInternal };
|
||||
|
||||
@@ -1,48 +1,59 @@
|
||||
import { memo } from 'react';
|
||||
import { getStraightPath } from '@xyflow/system';
|
||||
|
||||
import BaseEdge from './BaseEdge';
|
||||
import type { EdgeProps } from '../../types';
|
||||
import { BaseEdge } from './BaseEdge';
|
||||
import type { StraightEdgeProps } from '../../types';
|
||||
|
||||
const StraightEdge = memo(
|
||||
({
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
interactionWidth,
|
||||
}: EdgeProps) => {
|
||||
const [path, labelX, labelY] = getStraightPath({ sourceX, sourceY, targetX, targetY });
|
||||
function createStraightEdge(params: { isInternal: boolean }) {
|
||||
// eslint-disable-next-line react/display-name
|
||||
return memo(
|
||||
({
|
||||
id,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
interactionWidth,
|
||||
}: StraightEdgeProps) => {
|
||||
const [path, labelX, labelY] = getStraightPath({ sourceX, sourceY, targetX, targetY });
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
const _id = params.isInternal ? undefined : id;
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
id={_id}
|
||||
path={path}
|
||||
labelX={labelX}
|
||||
labelY={labelY}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
style={style}
|
||||
markerEnd={markerEnd}
|
||||
markerStart={markerStart}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const StraightEdge = createStraightEdge({ isInternal: false });
|
||||
const StraightEdgeInternal = createStraightEdge({ isInternal: true });
|
||||
|
||||
StraightEdge.displayName = 'StraightEdge';
|
||||
StraightEdgeInternal.displayName = 'StraightEdgeInternal';
|
||||
|
||||
export default StraightEdge;
|
||||
export { StraightEdge, StraightEdgeInternal };
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
export { default as SimpleBezierEdge } from './SimpleBezierEdge';
|
||||
export { default as SmoothStepEdge } from './SmoothStepEdge';
|
||||
export { default as StepEdge } from './StepEdge';
|
||||
export { default as StraightEdge } from './StraightEdge';
|
||||
export { default as BezierEdge } from './BezierEdge';
|
||||
// We distinguish between internal and exported edges
|
||||
// The internal edges are used directly like custom edges and always get an id, source and target props
|
||||
// If you import an edge from the library, the id is optional and source and target are not used at all
|
||||
|
||||
export { SimpleBezierEdge, SimpleBezierEdgeInternal } from './SimpleBezierEdge';
|
||||
export { SmoothStepEdge, SmoothStepEdgeInternal } from './SmoothStepEdge';
|
||||
export { StepEdge, StepEdgeInternal } from './StepEdge';
|
||||
export { StraightEdge, StraightEdgeInternal } from './StraightEdge';
|
||||
export { BezierEdge, BezierEdgeInternal } from './BezierEdge';
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { MouseEvent as ReactMouseEvent } from 'react';
|
||||
import type { StoreApi } from 'zustand';
|
||||
|
||||
import type { Edge, ReactFlowState } from '../../types';
|
||||
|
||||
export function getMouseHandler(
|
||||
id: string,
|
||||
getState: StoreApi<ReactFlowState>['getState'],
|
||||
handler?: (event: ReactMouseEvent<SVGGElement, MouseEvent>, edge: Edge) => void
|
||||
) {
|
||||
return handler === undefined
|
||||
? handler
|
||||
: (event: ReactMouseEvent<SVGGElement, MouseEvent>) => {
|
||||
const edge = getState().edges.find((e) => e.id === id);
|
||||
|
||||
if (edge) {
|
||||
handler(event, { ...edge });
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
import { memo, useState, useMemo, useRef, type ComponentType, type KeyboardEvent } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { getMarkerId, elementSelectionKeys, XYHandle, type Connection, getEdgePosition } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi, useStore } from '../../hooks/useStore';
|
||||
import { ARIA_EDGE_DESC_KEY } from '../A11yDescriptions';
|
||||
import { EdgeAnchor } from './EdgeAnchor';
|
||||
import { getMouseHandler } from './utils';
|
||||
import type { EdgeProps, WrapEdgeProps } from '../../types';
|
||||
|
||||
export default (EdgeComponent: ComponentType<EdgeProps>) => {
|
||||
const EdgeWrapper = ({
|
||||
id,
|
||||
className,
|
||||
type,
|
||||
data,
|
||||
onClick,
|
||||
onEdgeDoubleClick,
|
||||
selected,
|
||||
animated,
|
||||
label,
|
||||
labelStyle,
|
||||
labelShowBg,
|
||||
labelBgStyle,
|
||||
labelBgPadding,
|
||||
labelBgBorderRadius,
|
||||
style,
|
||||
source,
|
||||
target,
|
||||
isSelectable,
|
||||
hidden,
|
||||
sourceHandleId,
|
||||
targetHandleId,
|
||||
onContextMenu,
|
||||
onMouseEnter,
|
||||
onMouseMove,
|
||||
onMouseLeave,
|
||||
edgeUpdaterRadius,
|
||||
onEdgeUpdate,
|
||||
onEdgeUpdateStart,
|
||||
onEdgeUpdateEnd,
|
||||
markerEnd,
|
||||
markerStart,
|
||||
rfId,
|
||||
ariaLabel,
|
||||
isFocusable,
|
||||
isUpdatable,
|
||||
pathOptions,
|
||||
interactionWidth,
|
||||
}: WrapEdgeProps): JSX.Element | null => {
|
||||
const edgeRef = useRef<SVGGElement>(null);
|
||||
const [updateHover, setUpdateHover] = useState<boolean>(false);
|
||||
const [updating, setUpdating] = useState<boolean>(false);
|
||||
const store = useStoreApi();
|
||||
const edgePosition = useStore((state) => {
|
||||
const sourceNode = state.nodes.find((n) => n.id === source);
|
||||
const targetNode = state.nodes.find((n) => n.id === target);
|
||||
|
||||
if (!sourceNode || !targetNode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pos = getEdgePosition({
|
||||
id,
|
||||
sourceNode,
|
||||
targetNode,
|
||||
sourceHandle: sourceHandleId || null,
|
||||
targetHandle: targetHandleId || null,
|
||||
connectionMode: state.connectionMode,
|
||||
onError: state.onError,
|
||||
});
|
||||
|
||||
return pos;
|
||||
}, shallow);
|
||||
|
||||
const markerStartUrl = useMemo(() => `url(#${getMarkerId(markerStart, rfId)})`, [markerStart, rfId]);
|
||||
const markerEndUrl = useMemo(() => `url(#${getMarkerId(markerEnd, rfId)})`, [markerEnd, rfId]);
|
||||
|
||||
if (hidden || !edgePosition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onEdgeClick = (event: React.MouseEvent<SVGGElement, MouseEvent>): void => {
|
||||
const { edges, addSelectedEdges, unselectNodesAndEdges, multiSelectionActive } = store.getState();
|
||||
const edge = edges.find((e) => e.id === id);
|
||||
|
||||
if (!edge) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSelectable) {
|
||||
store.setState({ nodesSelectionActive: false });
|
||||
|
||||
if (edge.selected && multiSelectionActive) {
|
||||
unselectNodesAndEdges({ nodes: [], edges: [edge] });
|
||||
edgeRef.current?.blur();
|
||||
} else {
|
||||
addSelectedEdges([id]);
|
||||
}
|
||||
}
|
||||
|
||||
if (onClick) {
|
||||
onClick(event, edge);
|
||||
}
|
||||
};
|
||||
|
||||
const onEdgeDoubleClickHandler = getMouseHandler(id, store.getState, onEdgeDoubleClick);
|
||||
const onEdgeContextMenu = getMouseHandler(id, store.getState, onContextMenu);
|
||||
const onEdgeMouseEnter = getMouseHandler(id, store.getState, onMouseEnter);
|
||||
const onEdgeMouseMove = getMouseHandler(id, store.getState, onMouseMove);
|
||||
const onEdgeMouseLeave = getMouseHandler(id, store.getState, onMouseLeave);
|
||||
|
||||
const handleEdgeUpdater = (event: React.MouseEvent<SVGGElement, MouseEvent>, isSourceHandle: boolean) => {
|
||||
// avoid triggering edge updater if mouse btn is not left
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
autoPanOnConnect,
|
||||
domNode,
|
||||
edges,
|
||||
isValidConnection,
|
||||
connectionMode,
|
||||
connectionRadius,
|
||||
lib,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
cancelConnection,
|
||||
nodes,
|
||||
panBy,
|
||||
updateConnection,
|
||||
} = store.getState();
|
||||
const nodeId = isSourceHandle ? target : source;
|
||||
const handleId = (isSourceHandle ? targetHandleId : sourceHandleId) || null;
|
||||
const handleType = isSourceHandle ? 'target' : 'source';
|
||||
|
||||
const isTarget = isSourceHandle;
|
||||
const edge = edges.find((e) => e.id === id)!;
|
||||
|
||||
setUpdating(true);
|
||||
onEdgeUpdateStart?.(event, edge, handleType);
|
||||
|
||||
const _onEdgeUpdateEnd = (evt: MouseEvent | TouchEvent) => {
|
||||
setUpdating(false);
|
||||
onEdgeUpdateEnd?.(evt, edge, handleType);
|
||||
};
|
||||
|
||||
const onConnectEdge = (connection: Connection) => onEdgeUpdate?.(edge, connection);
|
||||
|
||||
XYHandle.onPointerDown(event.nativeEvent, {
|
||||
autoPanOnConnect,
|
||||
connectionMode,
|
||||
connectionRadius,
|
||||
domNode,
|
||||
handleId,
|
||||
nodeId,
|
||||
nodes,
|
||||
isTarget,
|
||||
edgeUpdaterType: handleType,
|
||||
lib,
|
||||
cancelConnection,
|
||||
panBy,
|
||||
isValidConnection,
|
||||
onConnect: onConnectEdge,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
onEdgeUpdateEnd: _onEdgeUpdateEnd,
|
||||
updateConnection,
|
||||
getTransform: () => store.getState().transform,
|
||||
});
|
||||
};
|
||||
|
||||
const onEdgeUpdaterSourceMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
|
||||
handleEdgeUpdater(event, true);
|
||||
const onEdgeUpdaterTargetMouseDown = (event: React.MouseEvent<SVGGElement, MouseEvent>): void =>
|
||||
handleEdgeUpdater(event, false);
|
||||
|
||||
const onEdgeUpdaterMouseEnter = () => setUpdateHover(true);
|
||||
const onEdgeUpdaterMouseOut = () => setUpdateHover(false);
|
||||
|
||||
const inactive = !isSelectable && !onClick;
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (elementSelectionKeys.includes(event.key) && isSelectable) {
|
||||
const { unselectNodesAndEdges, addSelectedEdges, edges } = store.getState();
|
||||
const unselect = event.key === 'Escape';
|
||||
|
||||
if (unselect) {
|
||||
edgeRef.current?.blur();
|
||||
unselectNodesAndEdges({ edges: [edges.find((e) => e.id === id)!] });
|
||||
} else {
|
||||
addSelectedEdges([id]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<g
|
||||
className={cc([
|
||||
'react-flow__edge',
|
||||
`react-flow__edge-${type}`,
|
||||
className,
|
||||
{ selected, animated, inactive, updating: updateHover },
|
||||
])}
|
||||
onClick={onEdgeClick}
|
||||
onDoubleClick={onEdgeDoubleClickHandler}
|
||||
onContextMenu={onEdgeContextMenu}
|
||||
onMouseEnter={onEdgeMouseEnter}
|
||||
onMouseMove={onEdgeMouseMove}
|
||||
onMouseLeave={onEdgeMouseLeave}
|
||||
onKeyDown={isFocusable ? onKeyDown : undefined}
|
||||
tabIndex={isFocusable ? 0 : undefined}
|
||||
role={isFocusable ? 'button' : 'img'}
|
||||
data-testid={`rf__edge-${id}`}
|
||||
aria-label={ariaLabel === null ? undefined : ariaLabel ? ariaLabel : `Edge from ${source} to ${target}`}
|
||||
aria-describedby={isFocusable ? `${ARIA_EDGE_DESC_KEY}-${rfId}` : undefined}
|
||||
ref={edgeRef}
|
||||
>
|
||||
{!updating && (
|
||||
<EdgeComponent
|
||||
id={id}
|
||||
source={source}
|
||||
target={target}
|
||||
selected={selected}
|
||||
animated={animated}
|
||||
label={label}
|
||||
labelStyle={labelStyle}
|
||||
labelShowBg={labelShowBg}
|
||||
labelBgStyle={labelBgStyle}
|
||||
labelBgPadding={labelBgPadding}
|
||||
labelBgBorderRadius={labelBgBorderRadius}
|
||||
data={data}
|
||||
style={style}
|
||||
sourceX={edgePosition.sourceX}
|
||||
sourceY={edgePosition.sourceY}
|
||||
targetX={edgePosition.targetX}
|
||||
targetY={edgePosition.targetY}
|
||||
sourcePosition={edgePosition.sourcePosition}
|
||||
targetPosition={edgePosition.targetPosition}
|
||||
sourceHandleId={sourceHandleId}
|
||||
targetHandleId={targetHandleId}
|
||||
markerStart={markerStartUrl}
|
||||
markerEnd={markerEndUrl}
|
||||
pathOptions={pathOptions}
|
||||
interactionWidth={interactionWidth}
|
||||
/>
|
||||
)}
|
||||
{isUpdatable && (
|
||||
<>
|
||||
{(isUpdatable === 'source' || isUpdatable === true) && (
|
||||
<EdgeAnchor
|
||||
position={edgePosition.sourcePosition}
|
||||
centerX={edgePosition.sourceX}
|
||||
centerY={edgePosition.sourceY}
|
||||
radius={edgeUpdaterRadius}
|
||||
onMouseDown={onEdgeUpdaterSourceMouseDown}
|
||||
onMouseEnter={onEdgeUpdaterMouseEnter}
|
||||
onMouseOut={onEdgeUpdaterMouseOut}
|
||||
type="source"
|
||||
/>
|
||||
)}
|
||||
{(isUpdatable === 'target' || isUpdatable === true) && (
|
||||
<EdgeAnchor
|
||||
position={edgePosition.targetPosition}
|
||||
centerX={edgePosition.targetX}
|
||||
centerY={edgePosition.targetY}
|
||||
radius={edgeUpdaterRadius}
|
||||
onMouseDown={onEdgeUpdaterTargetMouseDown}
|
||||
onMouseEnter={onEdgeUpdaterMouseEnter}
|
||||
onMouseOut={onEdgeUpdaterMouseOut}
|
||||
type="target"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
};
|
||||
|
||||
EdgeWrapper.displayName = 'EdgeWrapper';
|
||||
|
||||
return memo(EdgeWrapper);
|
||||
};
|
||||
@@ -1,4 +1,10 @@
|
||||
import { memo, HTMLAttributes, forwardRef, MouseEvent as ReactMouseEvent, TouchEvent as ReactTouchEvent } from 'react';
|
||||
import {
|
||||
type HTMLAttributes,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type TouchEvent as ReactTouchEvent,
|
||||
type ForwardedRef,
|
||||
memo,
|
||||
} from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import {
|
||||
@@ -7,210 +13,233 @@ import {
|
||||
XYHandle,
|
||||
getHostForElement,
|
||||
isMouseEvent,
|
||||
type HandleProps,
|
||||
addEdge,
|
||||
type HandleProps as HandlePropsSystem,
|
||||
type Connection,
|
||||
type HandleType,
|
||||
ConnectionMode,
|
||||
OnConnect,
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import { useNodeId } from '../../contexts/NodeIdContext';
|
||||
import { addEdge } from '../../utils/';
|
||||
import { type ReactFlowState } from '../../types';
|
||||
import { fixedForwardRef } from '../../utils';
|
||||
|
||||
export type HandleComponentProps = HandleProps & Omit<HTMLAttributes<HTMLDivElement>, 'id'>;
|
||||
export interface HandleProps extends HandlePropsSystem, Omit<HTMLAttributes<HTMLDivElement>, 'id'> {
|
||||
/** Callback called when connection is made */
|
||||
onConnect?: OnConnect;
|
||||
}
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
connectionStartHandle: s.connectionStartHandle,
|
||||
connectOnClick: s.connectOnClick,
|
||||
noPanClassName: s.noPanClassName,
|
||||
rfId: s.rfId,
|
||||
});
|
||||
|
||||
const connectingSelector =
|
||||
(nodeId: string | null, handleId: string | null, type: HandleType) => (state: ReactFlowState) => {
|
||||
const {
|
||||
connectionStartHandle: startHandle,
|
||||
connectionEndHandle: endHandle,
|
||||
connectionClickStartHandle: clickHandle,
|
||||
} = state;
|
||||
const { connectionClickStartHandle: clickHandle, connectionMode, connection } = state;
|
||||
|
||||
const { fromHandle, toHandle, isValid } = connection;
|
||||
|
||||
const connectingTo = toHandle?.nodeId === nodeId && toHandle?.id === handleId && toHandle?.type === type;
|
||||
|
||||
return {
|
||||
connecting:
|
||||
(startHandle?.nodeId === nodeId && startHandle?.handleId === handleId && startHandle?.type === type) ||
|
||||
(endHandle?.nodeId === nodeId && endHandle?.handleId === handleId && endHandle?.type === type),
|
||||
clickConnecting:
|
||||
clickHandle?.nodeId === nodeId && clickHandle?.handleId === handleId && clickHandle?.type === type,
|
||||
connectingFrom: fromHandle?.nodeId === nodeId && fromHandle?.id === handleId && fromHandle?.type === type,
|
||||
connectingTo,
|
||||
clickConnecting: clickHandle?.nodeId === nodeId && clickHandle?.id === handleId && clickHandle?.type === type,
|
||||
isPossibleEndHandle:
|
||||
connectionMode === ConnectionMode.Strict
|
||||
? fromHandle?.type !== type
|
||||
: nodeId !== fromHandle?.nodeId || handleId !== fromHandle?.id,
|
||||
connectionInProcess: !!fromHandle,
|
||||
valid: connectingTo && isValid,
|
||||
};
|
||||
};
|
||||
|
||||
const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
|
||||
(
|
||||
{
|
||||
type = 'source',
|
||||
position = Position.Top,
|
||||
isValidConnection,
|
||||
isConnectable = true,
|
||||
isConnectableStart = true,
|
||||
isConnectableEnd = true,
|
||||
id,
|
||||
onConnect,
|
||||
children,
|
||||
className,
|
||||
onMouseDown,
|
||||
onTouchStart,
|
||||
...rest
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const handleId = id || null;
|
||||
const isTarget = type === 'target';
|
||||
const store = useStoreApi();
|
||||
const nodeId = useNodeId();
|
||||
const { connectOnClick, noPanClassName } = useStore(selector, shallow);
|
||||
const { connecting, clickConnecting } = useStore(connectingSelector(nodeId, handleId, type), shallow);
|
||||
function HandleComponent(
|
||||
{
|
||||
type = 'source',
|
||||
position = Position.Top,
|
||||
isValidConnection,
|
||||
isConnectable = true,
|
||||
isConnectableStart = true,
|
||||
isConnectableEnd = true,
|
||||
id,
|
||||
onConnect,
|
||||
children,
|
||||
className,
|
||||
onMouseDown,
|
||||
onTouchStart,
|
||||
...rest
|
||||
}: HandleProps,
|
||||
ref: ForwardedRef<HTMLDivElement>
|
||||
) {
|
||||
const handleId = id || null;
|
||||
const isTarget = type === 'target';
|
||||
const store = useStoreApi();
|
||||
const nodeId = useNodeId();
|
||||
const { connectOnClick, noPanClassName, rfId } = useStore(selector, shallow);
|
||||
const { connectingFrom, connectingTo, clickConnecting, isPossibleEndHandle, connectionInProcess, valid } = useStore(
|
||||
connectingSelector(nodeId, handleId, type),
|
||||
shallow
|
||||
);
|
||||
|
||||
if (!nodeId) {
|
||||
store.getState().onError?.('010', errorMessages['error010']());
|
||||
if (!nodeId) {
|
||||
store.getState().onError?.('010', errorMessages['error010']());
|
||||
}
|
||||
|
||||
const onConnectExtended = (params: Connection) => {
|
||||
const { defaultEdgeOptions, onConnect: onConnectAction, hasDefaultEdges } = store.getState();
|
||||
|
||||
const edgeParams = {
|
||||
...defaultEdgeOptions,
|
||||
...params,
|
||||
};
|
||||
if (hasDefaultEdges) {
|
||||
const { edges, setEdges } = store.getState();
|
||||
setEdges(addEdge(edgeParams, edges));
|
||||
}
|
||||
|
||||
const onConnectExtended = (params: Connection) => {
|
||||
const { defaultEdgeOptions, onConnect: onConnectAction, hasDefaultEdges } = store.getState();
|
||||
onConnectAction?.(edgeParams);
|
||||
onConnect?.(edgeParams);
|
||||
};
|
||||
|
||||
const edgeParams = {
|
||||
...defaultEdgeOptions,
|
||||
...params,
|
||||
};
|
||||
if (hasDefaultEdges) {
|
||||
const { edges, setEdges } = store.getState();
|
||||
setEdges(addEdge(edgeParams, edges));
|
||||
}
|
||||
const onPointerDown = (event: ReactMouseEvent<HTMLDivElement> | ReactTouchEvent<HTMLDivElement>) => {
|
||||
if (!nodeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
onConnectAction?.(edgeParams);
|
||||
onConnect?.(edgeParams);
|
||||
};
|
||||
const isMouseTriggered = isMouseEvent(event.nativeEvent);
|
||||
|
||||
const onPointerDown = (event: ReactMouseEvent<HTMLDivElement> | ReactTouchEvent<HTMLDivElement>) => {
|
||||
if (!nodeId) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isConnectableStart &&
|
||||
((isMouseTriggered && (event as ReactMouseEvent<HTMLDivElement>).button === 0) || !isMouseTriggered)
|
||||
) {
|
||||
const currentStore = store.getState();
|
||||
|
||||
const isMouseTriggered = isMouseEvent(event.nativeEvent);
|
||||
|
||||
if (
|
||||
isConnectableStart &&
|
||||
((isMouseTriggered && (event as ReactMouseEvent<HTMLDivElement>).button === 0) || !isMouseTriggered)
|
||||
) {
|
||||
const currentStore = store.getState();
|
||||
|
||||
XYHandle.onPointerDown(event.nativeEvent, {
|
||||
autoPanOnConnect: currentStore.autoPanOnConnect,
|
||||
connectionMode: currentStore.connectionMode,
|
||||
connectionRadius: currentStore.connectionRadius,
|
||||
domNode: currentStore.domNode,
|
||||
nodes: currentStore.nodes,
|
||||
lib: currentStore.lib,
|
||||
isTarget,
|
||||
handleId,
|
||||
nodeId,
|
||||
panBy: currentStore.panBy,
|
||||
cancelConnection: currentStore.cancelConnection,
|
||||
onConnectStart: currentStore.onConnectStart,
|
||||
onConnectEnd: currentStore.onConnectEnd,
|
||||
updateConnection: currentStore.updateConnection,
|
||||
onConnect: onConnectExtended,
|
||||
isValidConnection: isValidConnection || currentStore.isValidConnection,
|
||||
getTransform: () => store.getState().transform,
|
||||
});
|
||||
}
|
||||
|
||||
if (isMouseTriggered) {
|
||||
onMouseDown?.(event as ReactMouseEvent<HTMLDivElement>);
|
||||
} else {
|
||||
onTouchStart?.(event as ReactTouchEvent<HTMLDivElement>);
|
||||
}
|
||||
};
|
||||
|
||||
const onClick = (event: ReactMouseEvent) => {
|
||||
const {
|
||||
onClickConnectStart,
|
||||
onClickConnectEnd,
|
||||
connectionClickStartHandle,
|
||||
connectionMode,
|
||||
isValidConnection: isValidConnectionStore,
|
||||
lib,
|
||||
} = store.getState();
|
||||
|
||||
if (!nodeId || (!connectionClickStartHandle && !isConnectableStart)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!connectionClickStartHandle) {
|
||||
onClickConnectStart?.(event.nativeEvent, { nodeId, handleId, handleType: type });
|
||||
store.setState({ connectionClickStartHandle: { nodeId, type, handleId } });
|
||||
return;
|
||||
}
|
||||
|
||||
const doc = getHostForElement(event.target as HTMLElement);
|
||||
const isValidConnectionHandler = isValidConnection || isValidConnectionStore;
|
||||
const { connection, isValid } = XYHandle.isValid(event.nativeEvent, {
|
||||
handle: {
|
||||
nodeId,
|
||||
id: handleId,
|
||||
type,
|
||||
},
|
||||
connectionMode,
|
||||
fromNodeId: connectionClickStartHandle.nodeId,
|
||||
fromHandleId: connectionClickStartHandle.handleId || null,
|
||||
fromType: connectionClickStartHandle.type,
|
||||
isValidConnection: isValidConnectionHandler,
|
||||
doc,
|
||||
lib,
|
||||
XYHandle.onPointerDown(event.nativeEvent, {
|
||||
autoPanOnConnect: currentStore.autoPanOnConnect,
|
||||
connectionMode: currentStore.connectionMode,
|
||||
connectionRadius: currentStore.connectionRadius,
|
||||
domNode: currentStore.domNode,
|
||||
nodeLookup: currentStore.nodeLookup,
|
||||
lib: currentStore.lib,
|
||||
isTarget,
|
||||
handleId,
|
||||
nodeId,
|
||||
flowId: currentStore.rfId,
|
||||
panBy: currentStore.panBy,
|
||||
cancelConnection: currentStore.cancelConnection,
|
||||
onConnectStart: currentStore.onConnectStart,
|
||||
onConnectEnd: currentStore.onConnectEnd,
|
||||
updateConnection: currentStore.updateConnection,
|
||||
onConnect: onConnectExtended,
|
||||
isValidConnection: isValidConnection || currentStore.isValidConnection,
|
||||
getTransform: () => store.getState().transform,
|
||||
getFromHandle: () => store.getState().connection.fromHandle,
|
||||
autoPanSpeed: currentStore.autoPanSpeed,
|
||||
});
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
onConnectExtended(connection);
|
||||
}
|
||||
if (isMouseTriggered) {
|
||||
onMouseDown?.(event as ReactMouseEvent<HTMLDivElement>);
|
||||
} else {
|
||||
onTouchStart?.(event as ReactTouchEvent<HTMLDivElement>);
|
||||
}
|
||||
};
|
||||
|
||||
onClickConnectEnd?.(event as unknown as MouseEvent);
|
||||
const onClick = (event: ReactMouseEvent) => {
|
||||
const {
|
||||
onClickConnectStart,
|
||||
onClickConnectEnd,
|
||||
connectionClickStartHandle,
|
||||
connectionMode,
|
||||
isValidConnection: isValidConnectionStore,
|
||||
lib,
|
||||
rfId: flowId,
|
||||
} = store.getState();
|
||||
|
||||
store.setState({ connectionClickStartHandle: null });
|
||||
};
|
||||
if (!nodeId || (!connectionClickStartHandle && !isConnectableStart)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-handleid={handleId}
|
||||
data-nodeid={nodeId}
|
||||
data-handlepos={position}
|
||||
data-id={`${nodeId}-${handleId}-${type}`}
|
||||
className={cc([
|
||||
'react-flow__handle',
|
||||
`react-flow__handle-${position}`,
|
||||
'nodrag',
|
||||
noPanClassName,
|
||||
className,
|
||||
{
|
||||
source: !isTarget,
|
||||
target: isTarget,
|
||||
connectable: isConnectable,
|
||||
connectablestart: isConnectableStart,
|
||||
connectableend: isConnectableEnd,
|
||||
connecting: clickConnecting,
|
||||
// this class is used to style the handle when the user is connecting
|
||||
connectionindicator:
|
||||
isConnectable && ((isConnectableStart && !connecting) || (isConnectableEnd && connecting)),
|
||||
},
|
||||
])}
|
||||
onMouseDown={onPointerDown}
|
||||
onTouchStart={onPointerDown}
|
||||
onClick={connectOnClick ? onClick : undefined}
|
||||
ref={ref}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
if (!connectionClickStartHandle) {
|
||||
onClickConnectStart?.(event.nativeEvent, { nodeId, handleId, handleType: type });
|
||||
store.setState({ connectionClickStartHandle: { nodeId, type, id: handleId } });
|
||||
return;
|
||||
}
|
||||
|
||||
Handle.displayName = 'Handle';
|
||||
const doc = getHostForElement(event.target as HTMLElement);
|
||||
const isValidConnectionHandler = isValidConnection || isValidConnectionStore;
|
||||
const { connection, isValid } = XYHandle.isValid(event.nativeEvent, {
|
||||
handle: {
|
||||
nodeId,
|
||||
id: handleId,
|
||||
type,
|
||||
},
|
||||
connectionMode,
|
||||
fromNodeId: connectionClickStartHandle.nodeId,
|
||||
fromHandleId: connectionClickStartHandle.id || null,
|
||||
fromType: connectionClickStartHandle.type,
|
||||
isValidConnection: isValidConnectionHandler,
|
||||
flowId,
|
||||
doc,
|
||||
lib,
|
||||
});
|
||||
|
||||
export default memo(Handle);
|
||||
if (isValid && connection) {
|
||||
onConnectExtended(connection);
|
||||
}
|
||||
|
||||
onClickConnectEnd?.(event as unknown as MouseEvent);
|
||||
|
||||
store.setState({ connectionClickStartHandle: null });
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-handleid={handleId}
|
||||
data-nodeid={nodeId}
|
||||
data-handlepos={position}
|
||||
data-id={`${rfId}-${nodeId}-${handleId}-${type}`}
|
||||
className={cc([
|
||||
'react-flow__handle',
|
||||
`react-flow__handle-${position}`,
|
||||
'nodrag',
|
||||
noPanClassName,
|
||||
className,
|
||||
{
|
||||
source: !isTarget,
|
||||
target: isTarget,
|
||||
connectable: isConnectable,
|
||||
connectablestart: isConnectableStart,
|
||||
connectableend: isConnectableEnd,
|
||||
clickconnecting: clickConnecting,
|
||||
connectingfrom: connectingFrom,
|
||||
connectingto: connectingTo,
|
||||
valid,
|
||||
// shows where you can start a connection from
|
||||
// and where you can end it while connecting
|
||||
connectionindicator:
|
||||
isConnectable &&
|
||||
(!connectionInProcess || isPossibleEndHandle) &&
|
||||
(connectionInProcess ? isConnectableEnd : isConnectableStart),
|
||||
},
|
||||
])}
|
||||
onMouseDown={onPointerDown}
|
||||
onTouchStart={onPointerDown}
|
||||
onClick={connectOnClick ? onClick : undefined}
|
||||
ref={ref}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Handle component is a UI element that is used to connect nodes.
|
||||
*/
|
||||
export const Handle = memo(fixedForwardRef(HandleComponent));
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { type MouseEvent, type KeyboardEvent } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import {
|
||||
clampPosition,
|
||||
elementSelectionKeys,
|
||||
errorMessages,
|
||||
getNodeDimensions,
|
||||
isInputDOMNode,
|
||||
nodeHasDimensions,
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import { Provider } from '../../contexts/NodeIdContext';
|
||||
import { ARIA_NODE_DESC_KEY } from '../A11yDescriptions';
|
||||
import { useDrag } from '../../hooks/useDrag';
|
||||
import { useMoveSelectedNodes } from '../../hooks/useMoveSelectedNodes';
|
||||
import { handleNodeClick } from '../Nodes/utils';
|
||||
import { arrowKeyDiffs, builtinNodeTypes, getNodeInlineStyleDimensions } from './utils';
|
||||
import { useNodeObserver } from './useNodeObserver';
|
||||
import type { InternalNode, Node, NodeWrapperProps } from '../../types';
|
||||
|
||||
export function NodeWrapper<NodeType extends Node>({
|
||||
id,
|
||||
onClick,
|
||||
onMouseEnter,
|
||||
onMouseMove,
|
||||
onMouseLeave,
|
||||
onContextMenu,
|
||||
onDoubleClick,
|
||||
nodesDraggable,
|
||||
elementsSelectable,
|
||||
nodesConnectable,
|
||||
nodesFocusable,
|
||||
resizeObserver,
|
||||
noDragClassName,
|
||||
noPanClassName,
|
||||
disableKeyboardA11y,
|
||||
rfId,
|
||||
nodeTypes,
|
||||
nodeExtent,
|
||||
onError,
|
||||
}: NodeWrapperProps<NodeType>) {
|
||||
const { node, internals, isParent } = useStore((s) => {
|
||||
const node = s.nodeLookup.get(id)! as InternalNode<NodeType>;
|
||||
const isParent = s.parentLookup.has(id);
|
||||
|
||||
return {
|
||||
node,
|
||||
internals: node.internals,
|
||||
isParent,
|
||||
};
|
||||
}, shallow);
|
||||
|
||||
let nodeType = node.type || 'default';
|
||||
let NodeComponent = nodeTypes?.[nodeType] || builtinNodeTypes[nodeType];
|
||||
|
||||
if (NodeComponent === undefined) {
|
||||
onError?.('003', errorMessages['error003'](nodeType));
|
||||
nodeType = 'default';
|
||||
NodeComponent = builtinNodeTypes.default;
|
||||
}
|
||||
|
||||
const isDraggable = !!(node.draggable || (nodesDraggable && typeof node.draggable === 'undefined'));
|
||||
const isSelectable = !!(node.selectable || (elementsSelectable && typeof node.selectable === 'undefined'));
|
||||
const isConnectable = !!(node.connectable || (nodesConnectable && typeof node.connectable === 'undefined'));
|
||||
const isFocusable = !!(node.focusable || (nodesFocusable && typeof node.focusable === 'undefined'));
|
||||
|
||||
const store = useStoreApi();
|
||||
const hasDimensions = nodeHasDimensions(node);
|
||||
const nodeRef = useNodeObserver({ node, nodeType, hasDimensions, resizeObserver });
|
||||
const dragging = useDrag({
|
||||
nodeRef,
|
||||
disabled: node.hidden || !isDraggable,
|
||||
noDragClassName,
|
||||
handleSelector: node.dragHandle,
|
||||
nodeId: id,
|
||||
isSelectable,
|
||||
});
|
||||
const moveSelectedNodes = useMoveSelectedNodes();
|
||||
|
||||
if (node.hidden) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const nodeDimensions = getNodeDimensions(node);
|
||||
const inlineDimensions = getNodeInlineStyleDimensions(node);
|
||||
// TODO: clamping should happen earlier
|
||||
const clampedPosition = nodeExtent
|
||||
? clampPosition(internals.positionAbsolute, nodeExtent)
|
||||
: internals.positionAbsolute;
|
||||
|
||||
const hasPointerEvents = isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave;
|
||||
|
||||
const onMouseEnterHandler = onMouseEnter
|
||||
? (event: MouseEvent) => onMouseEnter(event, { ...internals.userNode })
|
||||
: undefined;
|
||||
const onMouseMoveHandler = onMouseMove
|
||||
? (event: MouseEvent) => onMouseMove(event, { ...internals.userNode })
|
||||
: undefined;
|
||||
const onMouseLeaveHandler = onMouseLeave
|
||||
? (event: MouseEvent) => onMouseLeave(event, { ...internals.userNode })
|
||||
: undefined;
|
||||
const onContextMenuHandler = onContextMenu
|
||||
? (event: MouseEvent) => onContextMenu(event, { ...internals.userNode })
|
||||
: undefined;
|
||||
const onDoubleClickHandler = onDoubleClick
|
||||
? (event: MouseEvent) => onDoubleClick(event, { ...internals.userNode })
|
||||
: undefined;
|
||||
|
||||
const onSelectNodeHandler = (event: MouseEvent) => {
|
||||
const { selectNodesOnDrag, nodeDragThreshold } = store.getState();
|
||||
|
||||
if (isSelectable && (!selectNodesOnDrag || !isDraggable || nodeDragThreshold > 0)) {
|
||||
// this handler gets called by XYDrag on drag start when selectNodesOnDrag=true
|
||||
// here we only need to call it when selectNodesOnDrag=false
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
nodeRef,
|
||||
});
|
||||
}
|
||||
|
||||
if (onClick) {
|
||||
onClick(event, { ...internals.userNode });
|
||||
}
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (isInputDOMNode(event.nativeEvent) || disableKeyboardA11y) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (elementSelectionKeys.includes(event.key) && isSelectable) {
|
||||
const unselect = event.key === 'Escape';
|
||||
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
unselect,
|
||||
nodeRef,
|
||||
});
|
||||
} else if (isDraggable && node.selected && Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
|
||||
store.setState({
|
||||
ariaLiveMessage: `Moved selected node ${event.key
|
||||
.replace('Arrow', '')
|
||||
.toLowerCase()}. New position, x: ${~~clampedPosition.x}, y: ${~~clampedPosition.y}`,
|
||||
});
|
||||
|
||||
moveSelectedNodes({
|
||||
direction: arrowKeyDiffs[event.key],
|
||||
factor: event.shiftKey ? 4 : 1,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cc([
|
||||
'react-flow__node',
|
||||
`react-flow__node-${nodeType}`,
|
||||
{
|
||||
// this is overwritable by passing `nopan` as a class name
|
||||
[noPanClassName]: isDraggable,
|
||||
},
|
||||
node.className,
|
||||
{
|
||||
selected: node.selected,
|
||||
selectable: isSelectable,
|
||||
parent: isParent,
|
||||
draggable: isDraggable,
|
||||
dragging,
|
||||
},
|
||||
])}
|
||||
ref={nodeRef}
|
||||
style={{
|
||||
zIndex: internals.z,
|
||||
transform: `translate(${clampedPosition.x}px,${clampedPosition.y}px)`,
|
||||
pointerEvents: hasPointerEvents ? 'all' : 'none',
|
||||
visibility: hasDimensions ? 'visible' : 'hidden',
|
||||
...node.style,
|
||||
...inlineDimensions,
|
||||
}}
|
||||
data-id={id}
|
||||
data-testid={`rf__node-${id}`}
|
||||
onMouseEnter={onMouseEnterHandler}
|
||||
onMouseMove={onMouseMoveHandler}
|
||||
onMouseLeave={onMouseLeaveHandler}
|
||||
onContextMenu={onContextMenuHandler}
|
||||
onClick={onSelectNodeHandler}
|
||||
onDoubleClick={onDoubleClickHandler}
|
||||
onKeyDown={isFocusable ? onKeyDown : undefined}
|
||||
tabIndex={isFocusable ? 0 : undefined}
|
||||
role={isFocusable ? 'button' : undefined}
|
||||
aria-describedby={disableKeyboardA11y ? undefined : `${ARIA_NODE_DESC_KEY}-${rfId}`}
|
||||
aria-label={node.ariaLabel}
|
||||
>
|
||||
<Provider value={id}>
|
||||
<NodeComponent
|
||||
id={id}
|
||||
data={node.data}
|
||||
type={nodeType}
|
||||
positionAbsoluteX={clampedPosition.x}
|
||||
positionAbsoluteY={clampedPosition.y}
|
||||
selected={node.selected}
|
||||
selectable={isSelectable}
|
||||
draggable={isDraggable}
|
||||
deletable={node.deletable ?? true}
|
||||
isConnectable={isConnectable}
|
||||
sourcePosition={node.sourcePosition}
|
||||
targetPosition={node.targetPosition}
|
||||
dragging={dragging}
|
||||
dragHandle={node.dragHandle}
|
||||
zIndex={internals.z}
|
||||
parentId={node.parentId}
|
||||
{...nodeDimensions}
|
||||
/>
|
||||
</Provider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
import type { InternalNode } from '../../types';
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
|
||||
/**
|
||||
* Hook to handle the resize observation + internal updates for the passed node.
|
||||
*
|
||||
* @internal
|
||||
* @returns nodeRef - reference to the node element
|
||||
*/
|
||||
export function useNodeObserver({
|
||||
node,
|
||||
nodeType,
|
||||
hasDimensions,
|
||||
resizeObserver,
|
||||
}: {
|
||||
node: InternalNode;
|
||||
nodeType: string;
|
||||
hasDimensions: boolean;
|
||||
resizeObserver: ResizeObserver | null;
|
||||
}) {
|
||||
const store = useStoreApi();
|
||||
const nodeRef = useRef<HTMLDivElement | null>(null);
|
||||
const observedNode = useRef<HTMLDivElement | null>(null);
|
||||
const prevSourcePosition = useRef(node.sourcePosition);
|
||||
const prevTargetPosition = useRef(node.targetPosition);
|
||||
const prevType = useRef(nodeType);
|
||||
const isInitialized = hasDimensions && !!node.internals.handleBounds;
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef.current && !node.hidden && (!isInitialized || observedNode.current !== nodeRef.current)) {
|
||||
if (observedNode.current) {
|
||||
resizeObserver?.unobserve(observedNode.current);
|
||||
}
|
||||
resizeObserver?.observe(nodeRef.current);
|
||||
observedNode.current = nodeRef.current;
|
||||
}
|
||||
}, [isInitialized, node.hidden]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (observedNode.current) {
|
||||
resizeObserver?.unobserve(observedNode.current);
|
||||
observedNode.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef.current) {
|
||||
// when the user programmatically changes the source or handle position, we need to update the internals
|
||||
// to make sure the edges are updated correctly
|
||||
const typeChanged = prevType.current !== nodeType;
|
||||
const sourcePosChanged = prevSourcePosition.current !== node.sourcePosition;
|
||||
const targetPosChanged = prevTargetPosition.current !== node.targetPosition;
|
||||
|
||||
if (typeChanged || sourcePosChanged || targetPosChanged) {
|
||||
prevType.current = nodeType;
|
||||
prevSourcePosition.current = node.sourcePosition;
|
||||
prevTargetPosition.current = node.targetPosition;
|
||||
|
||||
store
|
||||
.getState()
|
||||
.updateNodeInternals(new Map([[node.id, { id: node.id, nodeElement: nodeRef.current, force: true }]]));
|
||||
}
|
||||
}
|
||||
}, [node.id, nodeType, node.sourcePosition, node.targetPosition]);
|
||||
|
||||
return nodeRef;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { XYPosition } from '@xyflow/system';
|
||||
|
||||
import { InputNode } from '../Nodes/InputNode';
|
||||
import { DefaultNode } from '../Nodes/DefaultNode';
|
||||
import { GroupNode } from '../Nodes/GroupNode';
|
||||
import { OutputNode } from '../Nodes/OutputNode';
|
||||
import type { InternalNode, Node, NodeTypes } from '../../types';
|
||||
|
||||
export const arrowKeyDiffs: Record<string, XYPosition> = {
|
||||
ArrowUp: { x: 0, y: -1 },
|
||||
ArrowDown: { x: 0, y: 1 },
|
||||
ArrowLeft: { x: -1, y: 0 },
|
||||
ArrowRight: { x: 1, y: 0 },
|
||||
};
|
||||
|
||||
export const builtinNodeTypes: NodeTypes = {
|
||||
input: InputNode,
|
||||
default: DefaultNode,
|
||||
output: OutputNode,
|
||||
group: GroupNode,
|
||||
};
|
||||
|
||||
export function getNodeInlineStyleDimensions<NodeType extends Node = Node>(
|
||||
node: InternalNode<NodeType>
|
||||
): {
|
||||
width: number | string | undefined;
|
||||
height: number | string | undefined;
|
||||
} {
|
||||
if (node.internals.handleBounds === undefined) {
|
||||
return {
|
||||
width: node.width ?? node.initialWidth ?? node.style?.width,
|
||||
height: node.height ?? node.initialHeight ?? node.style?.height,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
width: node.width ?? node.style?.width,
|
||||
height: node.height ?? node.style?.height,
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import { memo } from 'react';
|
||||
import { Position, type NodeProps } from '@xyflow/system';
|
||||
import { Position } from '@xyflow/system';
|
||||
|
||||
import Handle from '../../components/Handle';
|
||||
import { Handle } from '../../components/Handle';
|
||||
import type { BuiltInNode, NodeProps } from '../../types/nodes';
|
||||
|
||||
const DefaultNode = ({
|
||||
export function DefaultNode({
|
||||
data,
|
||||
isConnectable,
|
||||
targetPosition = Position.Top,
|
||||
sourcePosition = Position.Bottom,
|
||||
}: NodeProps) => {
|
||||
}: NodeProps<BuiltInNode>) {
|
||||
return (
|
||||
<>
|
||||
<Handle type="target" position={targetPosition} isConnectable={isConnectable} />
|
||||
@@ -16,8 +16,4 @@ const DefaultNode = ({
|
||||
<Handle type="source" position={sourcePosition} isConnectable={isConnectable} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
DefaultNode.displayName = 'DefaultNode';
|
||||
|
||||
export default memo(DefaultNode);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
const GroupNode = () => null;
|
||||
|
||||
GroupNode.displayName = 'GroupNode';
|
||||
|
||||
export default GroupNode;
|
||||
export function GroupNode() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { memo } from 'react';
|
||||
import { Position, type NodeProps } from '@xyflow/system';
|
||||
import { Position } from '@xyflow/system';
|
||||
|
||||
import Handle from '../../components/Handle';
|
||||
import { Handle } from '../../components/Handle';
|
||||
import type { BuiltInNode, NodeProps } from '../../types/nodes';
|
||||
|
||||
const InputNode = ({ data, isConnectable, sourcePosition = Position.Bottom }: NodeProps) => (
|
||||
<>
|
||||
{data?.label}
|
||||
<Handle type="source" position={sourcePosition} isConnectable={isConnectable} />
|
||||
</>
|
||||
);
|
||||
|
||||
InputNode.displayName = 'InputNode';
|
||||
|
||||
export default memo(InputNode);
|
||||
export function InputNode({ data, isConnectable, sourcePosition = Position.Bottom }: NodeProps<BuiltInNode>) {
|
||||
return (
|
||||
<>
|
||||
{data?.label}
|
||||
<Handle type="source" position={sourcePosition} isConnectable={isConnectable} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { memo } from 'react';
|
||||
import { Position, type NodeProps } from '@xyflow/system';
|
||||
import { Position } from '@xyflow/system';
|
||||
|
||||
import Handle from '../../components/Handle';
|
||||
import { Handle } from '../../components/Handle';
|
||||
import type { BuiltInNode, NodeProps } from '../../types/nodes';
|
||||
|
||||
const OutputNode = ({ data, isConnectable, targetPosition = Position.Top }: NodeProps) => (
|
||||
<>
|
||||
<Handle type="target" position={targetPosition} isConnectable={isConnectable} />
|
||||
{data?.label}
|
||||
</>
|
||||
);
|
||||
|
||||
OutputNode.displayName = 'OutputNode';
|
||||
|
||||
export default memo(OutputNode);
|
||||
export function OutputNode({ data, isConnectable, targetPosition = Position.Top }: NodeProps<BuiltInNode>) {
|
||||
return (
|
||||
<>
|
||||
<Handle type="target" position={targetPosition} isConnectable={isConnectable} />
|
||||
{data?.label}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,8 @@
|
||||
import type { MouseEvent, RefObject } from 'react';
|
||||
import type { RefObject } from 'react';
|
||||
import type { StoreApi } from 'zustand';
|
||||
|
||||
import type { Node, ReactFlowState } from '../../types';
|
||||
import { errorMessages } from '@xyflow/system';
|
||||
|
||||
export function getMouseHandler(
|
||||
id: string,
|
||||
getState: StoreApi<ReactFlowState>['getState'],
|
||||
handler?: (event: MouseEvent, node: Node) => void
|
||||
) {
|
||||
return handler === undefined
|
||||
? handler
|
||||
: (event: MouseEvent) => {
|
||||
const node = getState().nodes.find((n) => n.id === id)!;
|
||||
handler(event, { ...node });
|
||||
};
|
||||
}
|
||||
import type { ReactFlowState } from '../../types';
|
||||
|
||||
// this handler is called by
|
||||
// 1. the click handler when node is not draggable or selectNodesOnDrag = false
|
||||
@@ -35,8 +22,8 @@ export function handleNodeClick({
|
||||
unselect?: boolean;
|
||||
nodeRef?: RefObject<HTMLDivElement>;
|
||||
}) {
|
||||
const { addSelectedNodes, unselectNodesAndEdges, multiSelectionActive, nodes, onError } = store.getState();
|
||||
const node = nodes.find((n) => n.id === id)!;
|
||||
const { addSelectedNodes, unselectNodesAndEdges, multiSelectionActive, nodeLookup, onError } = store.getState();
|
||||
const node = nodeLookup.get(id);
|
||||
|
||||
if (!node) {
|
||||
onError?.('012', errorMessages['error012'](id));
|
||||
|
||||
@@ -1,230 +0,0 @@
|
||||
import { useEffect, useRef, memo, type ComponentType, type MouseEvent, type KeyboardEvent } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { elementSelectionKeys, isInputDOMNode, type NodeProps, type XYPosition } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
import { Provider } from '../../contexts/NodeIdContext';
|
||||
import { ARIA_NODE_DESC_KEY } from '../A11yDescriptions';
|
||||
import useDrag from '../../hooks/useDrag';
|
||||
import useUpdateNodePositions from '../../hooks/useUpdateNodePositions';
|
||||
import { getMouseHandler, handleNodeClick } from './utils';
|
||||
import type { WrapNodeProps } from '../../types';
|
||||
|
||||
export const arrowKeyDiffs: Record<string, XYPosition> = {
|
||||
ArrowUp: { x: 0, y: -1 },
|
||||
ArrowDown: { x: 0, y: 1 },
|
||||
ArrowLeft: { x: -1, y: 0 },
|
||||
ArrowRight: { x: 1, y: 0 },
|
||||
};
|
||||
|
||||
export default (NodeComponent: ComponentType<NodeProps>) => {
|
||||
const NodeWrapper = ({
|
||||
id,
|
||||
type,
|
||||
data,
|
||||
xPos,
|
||||
yPos,
|
||||
xPosOrigin,
|
||||
yPosOrigin,
|
||||
selected,
|
||||
onClick,
|
||||
onMouseEnter,
|
||||
onMouseMove,
|
||||
onMouseLeave,
|
||||
onContextMenu,
|
||||
onDoubleClick,
|
||||
style,
|
||||
className,
|
||||
isDraggable,
|
||||
isSelectable,
|
||||
isConnectable,
|
||||
isFocusable,
|
||||
sourcePosition,
|
||||
targetPosition,
|
||||
hidden,
|
||||
resizeObserver,
|
||||
dragHandle,
|
||||
zIndex,
|
||||
isParent,
|
||||
noDragClassName,
|
||||
noPanClassName,
|
||||
initialized,
|
||||
disableKeyboardA11y,
|
||||
ariaLabel,
|
||||
rfId,
|
||||
sizeWidth,
|
||||
sizeHeight,
|
||||
}: WrapNodeProps) => {
|
||||
const store = useStoreApi();
|
||||
const nodeRef = useRef<HTMLDivElement>(null);
|
||||
const prevSourcePosition = useRef(sourcePosition);
|
||||
const prevTargetPosition = useRef(targetPosition);
|
||||
const prevType = useRef(type);
|
||||
const hasPointerEvents = isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave;
|
||||
const updatePositions = useUpdateNodePositions();
|
||||
|
||||
const onMouseEnterHandler = getMouseHandler(id, store.getState, onMouseEnter);
|
||||
const onMouseMoveHandler = getMouseHandler(id, store.getState, onMouseMove);
|
||||
const onMouseLeaveHandler = getMouseHandler(id, store.getState, onMouseLeave);
|
||||
const onContextMenuHandler = getMouseHandler(id, store.getState, onContextMenu);
|
||||
const onDoubleClickHandler = getMouseHandler(id, store.getState, onDoubleClick);
|
||||
const onSelectNodeHandler = (event: MouseEvent) => {
|
||||
const { selectNodesOnDrag, nodeDragThreshold } = store.getState();
|
||||
|
||||
if (isSelectable && (!selectNodesOnDrag || !isDraggable || nodeDragThreshold > 0)) {
|
||||
// this handler gets called by XYDrag on drag start when selectNodesOnDrag=true
|
||||
// here we only need to call it when selectNodesOnDrag=false
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
nodeRef,
|
||||
});
|
||||
}
|
||||
|
||||
if (onClick) {
|
||||
const node = store.getState().nodes.find((n) => n.id === id)!;
|
||||
onClick(event, { ...node });
|
||||
}
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (isInputDOMNode(event.nativeEvent)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (elementSelectionKeys.includes(event.key) && isSelectable) {
|
||||
const unselect = event.key === 'Escape';
|
||||
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
unselect,
|
||||
nodeRef,
|
||||
});
|
||||
} else if (
|
||||
!disableKeyboardA11y &&
|
||||
isDraggable &&
|
||||
selected &&
|
||||
Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)
|
||||
) {
|
||||
store.setState({
|
||||
ariaLiveMessage: `Moved selected node ${event.key
|
||||
.replace('Arrow', '')
|
||||
.toLowerCase()}. New position, x: ${~~xPos}, y: ${~~yPos}`,
|
||||
});
|
||||
|
||||
updatePositions({
|
||||
x: arrowKeyDiffs[event.key].x,
|
||||
y: arrowKeyDiffs[event.key].y,
|
||||
isShiftPressed: event.shiftKey,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef.current && !hidden) {
|
||||
const currNode = nodeRef.current;
|
||||
resizeObserver?.observe(currNode);
|
||||
|
||||
return () => resizeObserver?.unobserve(currNode);
|
||||
}
|
||||
}, [hidden]);
|
||||
|
||||
useEffect(() => {
|
||||
// when the user programmatically changes the source or handle position, we re-initialize the node
|
||||
const typeChanged = prevType.current !== type;
|
||||
const sourcePosChanged = prevSourcePosition.current !== sourcePosition;
|
||||
const targetPosChanged = prevTargetPosition.current !== targetPosition;
|
||||
|
||||
if (nodeRef.current && (typeChanged || sourcePosChanged || targetPosChanged)) {
|
||||
if (typeChanged) {
|
||||
prevType.current = type;
|
||||
}
|
||||
if (sourcePosChanged) {
|
||||
prevSourcePosition.current = sourcePosition;
|
||||
}
|
||||
if (targetPosChanged) {
|
||||
prevTargetPosition.current = targetPosition;
|
||||
}
|
||||
store.getState().updateNodeDimensions([{ id, nodeElement: nodeRef.current, forceUpdate: true }]);
|
||||
}
|
||||
}, [id, type, sourcePosition, targetPosition]);
|
||||
|
||||
const dragging = useDrag({
|
||||
nodeRef,
|
||||
disabled: hidden || !isDraggable,
|
||||
noDragClassName,
|
||||
handleSelector: dragHandle,
|
||||
nodeId: id,
|
||||
isSelectable,
|
||||
});
|
||||
|
||||
if (hidden) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cc([
|
||||
'react-flow__node',
|
||||
`react-flow__node-${type}`,
|
||||
{
|
||||
// this is overwritable by passing `nopan` as a class name
|
||||
[noPanClassName]: isDraggable,
|
||||
},
|
||||
className,
|
||||
{
|
||||
selected,
|
||||
selectable: isSelectable,
|
||||
parent: isParent,
|
||||
dragging,
|
||||
},
|
||||
])}
|
||||
ref={nodeRef}
|
||||
style={{
|
||||
zIndex,
|
||||
transform: `translate(${xPosOrigin}px,${yPosOrigin}px)`,
|
||||
pointerEvents: hasPointerEvents ? 'all' : 'none',
|
||||
visibility: initialized ? 'visible' : 'hidden',
|
||||
width: sizeWidth,
|
||||
height: sizeHeight,
|
||||
...style,
|
||||
}}
|
||||
data-id={id}
|
||||
data-testid={`rf__node-${id}`}
|
||||
onMouseEnter={onMouseEnterHandler}
|
||||
onMouseMove={onMouseMoveHandler}
|
||||
onMouseLeave={onMouseLeaveHandler}
|
||||
onContextMenu={onContextMenuHandler}
|
||||
onClick={onSelectNodeHandler}
|
||||
onDoubleClick={onDoubleClickHandler}
|
||||
onKeyDown={isFocusable ? onKeyDown : undefined}
|
||||
tabIndex={isFocusable ? 0 : undefined}
|
||||
role={isFocusable ? 'button' : undefined}
|
||||
aria-describedby={disableKeyboardA11y ? undefined : `${ARIA_NODE_DESC_KEY}-${rfId}`}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<Provider value={id}>
|
||||
<NodeComponent
|
||||
id={id}
|
||||
data={data}
|
||||
type={type}
|
||||
xPos={xPos}
|
||||
yPos={yPos}
|
||||
selected={selected}
|
||||
isConnectable={isConnectable}
|
||||
sourcePosition={sourcePosition}
|
||||
targetPosition={targetPosition}
|
||||
dragging={dragging}
|
||||
dragHandle={dragHandle}
|
||||
zIndex={zIndex}
|
||||
/>
|
||||
</Provider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
NodeWrapper.displayName = 'NodeWrapper';
|
||||
|
||||
return memo(NodeWrapper);
|
||||
};
|
||||
@@ -2,40 +2,44 @@
|
||||
* The nodes selection rectangle gets displayed when a user
|
||||
* made a selection with on or several nodes
|
||||
*/
|
||||
|
||||
import { memo, useRef, useEffect, type MouseEvent, type KeyboardEvent } from 'react';
|
||||
import { useRef, useEffect, type MouseEvent, type KeyboardEvent } from 'react';
|
||||
import cc from 'classcat';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { getRectOfNodes } from '@xyflow/system';
|
||||
import { getInternalNodesBounds, isNumeric } from '@xyflow/system';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import useDrag from '../../hooks/useDrag';
|
||||
import { arrowKeyDiffs } from '../Nodes/wrapNode';
|
||||
import useUpdateNodePositions from '../../hooks/useUpdateNodePositions';
|
||||
import { useDrag } from '../../hooks/useDrag';
|
||||
import { useMoveSelectedNodes } from '../../hooks/useMoveSelectedNodes';
|
||||
import { arrowKeyDiffs } from '../NodeWrapper/utils';
|
||||
import type { Node, ReactFlowState } from '../../types';
|
||||
|
||||
export type NodesSelectionProps = {
|
||||
onSelectionContextMenu?: (event: MouseEvent, nodes: Node[]) => void;
|
||||
export type NodesSelectionProps<NodeType> = {
|
||||
onSelectionContextMenu?: (event: MouseEvent, nodes: NodeType[]) => void;
|
||||
noPanClassName?: string;
|
||||
disableKeyboardA11y: boolean;
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => {
|
||||
const selectedNodes = s.nodes.filter((n) => n.selected);
|
||||
const { width, height, x, y } = getRectOfNodes(selectedNodes, s.nodeOrigin);
|
||||
const { width, height, x, y } = getInternalNodesBounds(s.nodeLookup, {
|
||||
filter: (node) => !!node.selected,
|
||||
});
|
||||
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
width: isNumeric(width) ? width : null,
|
||||
height: isNumeric(height) ? height : null,
|
||||
userSelectionActive: s.userSelectionActive,
|
||||
transformString: `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]}) translate(${x}px,${y}px)`,
|
||||
};
|
||||
};
|
||||
|
||||
function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }: NodesSelectionProps) {
|
||||
const store = useStoreApi();
|
||||
export function NodesSelection<NodeType extends Node>({
|
||||
onSelectionContextMenu,
|
||||
noPanClassName,
|
||||
disableKeyboardA11y,
|
||||
}: NodesSelectionProps<NodeType>) {
|
||||
const store = useStoreApi<NodeType>();
|
||||
const { width, height, transformString, userSelectionActive } = useStore(selector, shallow);
|
||||
const updatePositions = useUpdateNodePositions();
|
||||
const moveSelectedNodes = useMoveSelectedNodes();
|
||||
|
||||
const nodeRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -64,10 +68,9 @@ function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboar
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
|
||||
updatePositions({
|
||||
x: arrowKeyDiffs[event.key].x,
|
||||
y: arrowKeyDiffs[event.key].y,
|
||||
isShiftPressed: event.shiftKey,
|
||||
moveSelectedNodes({
|
||||
direction: arrowKeyDiffs[event.key],
|
||||
factor: event.shiftKey ? 4 : 1,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -93,5 +96,3 @@ function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboar
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(NodesSelection);
|
||||
|
||||
@@ -6,13 +6,16 @@ import { useStore } from '../../hooks/useStore';
|
||||
import type { ReactFlowState } from '../../types';
|
||||
|
||||
export type PanelProps = HTMLAttributes<HTMLDivElement> & {
|
||||
position: PanelPosition;
|
||||
/** Set position of the panel
|
||||
* @example 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right'
|
||||
*/
|
||||
position?: PanelPosition;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => (s.userSelectionActive ? 'none' : 'all');
|
||||
|
||||
function Panel({ position, children, className, style, ...rest }: PanelProps) {
|
||||
export function Panel({ position = 'top-left', children, className, style, ...rest }: PanelProps) {
|
||||
const pointerEvents = useStore(selector);
|
||||
const positionClasses = `${position}`.split('-');
|
||||
|
||||
@@ -26,5 +29,3 @@ function Panel({ position, children, className, style, ...rest }: PanelProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Panel;
|
||||
|
||||
@@ -1,41 +1,50 @@
|
||||
import { useRef, type ReactNode } from 'react';
|
||||
import { type StoreApi } from 'zustand';
|
||||
import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
|
||||
import { Provider } from '../../contexts/RFStoreContext';
|
||||
import { createRFStore } from '../../store';
|
||||
import type { ReactFlowState, Node, Edge } from '../../types';
|
||||
import { Provider } from '../../contexts/StoreContext';
|
||||
import { createStore } from '../../store';
|
||||
import { BatchProvider } from '../BatchProvider';
|
||||
import type { Node, Edge } from '../../types';
|
||||
import { NodeOrigin } from '@xyflow/system';
|
||||
|
||||
function ReactFlowProvider({
|
||||
children,
|
||||
initialNodes,
|
||||
initialEdges,
|
||||
initialWidth,
|
||||
initialHeight,
|
||||
fitView,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
export type ReactFlowProviderProps = {
|
||||
initialNodes?: Node[];
|
||||
initialEdges?: Edge[];
|
||||
defaultNodes?: Node[];
|
||||
defaultEdges?: Edge[];
|
||||
initialWidth?: number;
|
||||
initialHeight?: number;
|
||||
fitView?: boolean;
|
||||
}) {
|
||||
const storeRef = useRef<UseBoundStoreWithEqualityFn<StoreApi<ReactFlowState>> | null>(null);
|
||||
nodeOrigin?: NodeOrigin;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
if (!storeRef.current) {
|
||||
storeRef.current = createRFStore({
|
||||
nodes: initialNodes,
|
||||
edges: initialEdges,
|
||||
width: initialWidth,
|
||||
height: initialHeight,
|
||||
export function ReactFlowProvider({
|
||||
initialNodes: nodes,
|
||||
initialEdges: edges,
|
||||
defaultNodes,
|
||||
defaultEdges,
|
||||
initialWidth: width,
|
||||
initialHeight: height,
|
||||
fitView,
|
||||
nodeOrigin,
|
||||
children,
|
||||
}: ReactFlowProviderProps) {
|
||||
const [store] = useState(() =>
|
||||
createStore({
|
||||
nodes,
|
||||
edges,
|
||||
defaultNodes,
|
||||
defaultEdges,
|
||||
width,
|
||||
height,
|
||||
fitView,
|
||||
});
|
||||
}
|
||||
nodeOrigin,
|
||||
})
|
||||
);
|
||||
|
||||
return <Provider value={storeRef.current}>{children}</Provider>;
|
||||
return (
|
||||
<Provider value={store}>
|
||||
<BatchProvider>{children}</BatchProvider>
|
||||
</Provider>
|
||||
);
|
||||
}
|
||||
|
||||
ReactFlowProvider.displayName = 'ReactFlowProvider';
|
||||
|
||||
export default ReactFlowProvider;
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { memo, useEffect } from 'react';
|
||||
/*
|
||||
* This is a helper component for calling the onSelectionChange listener.
|
||||
* It will only be mounted if the user has passed an onSelectionChange listener
|
||||
* or is using the useOnSelectionChange hook.
|
||||
* @TODO: Now that we have the onNodesChange and on EdgesChange listeners, do we still need this component?
|
||||
*/
|
||||
import { useEffect } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
@@ -8,10 +14,24 @@ type SelectionListenerProps = {
|
||||
onSelectionChange?: OnSelectionChangeFunc;
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
selectedNodes: s.nodes.filter((n) => n.selected),
|
||||
selectedEdges: s.edges.filter((e) => e.selected),
|
||||
});
|
||||
const selector = (s: ReactFlowState) => {
|
||||
const selectedNodes = [];
|
||||
const selectedEdges = [];
|
||||
|
||||
for (const [, node] of s.nodeLookup) {
|
||||
if (node.selected) {
|
||||
selectedNodes.push(node.internals.userNode);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [, edge] of s.edgeLookup) {
|
||||
if (edge.selected) {
|
||||
selectedEdges.push(edge);
|
||||
}
|
||||
}
|
||||
|
||||
return { selectedNodes, selectedEdges };
|
||||
};
|
||||
|
||||
type SelectorSlice = ReturnType<typeof selector>;
|
||||
|
||||
@@ -24,33 +44,28 @@ function areEqual(a: SelectorSlice, b: SelectorSlice) {
|
||||
);
|
||||
}
|
||||
|
||||
// This is just a helper component for calling the onSelectionChange listener.
|
||||
// @TODO: Now that we have the onNodesChange and on EdgesChange listeners, do we still need this component?
|
||||
const SelectionListener = memo(({ onSelectionChange }: SelectionListenerProps) => {
|
||||
function SelectionListenerInner({ onSelectionChange }: SelectionListenerProps) {
|
||||
const store = useStoreApi();
|
||||
const { selectedNodes, selectedEdges } = useStore(selector, areEqual);
|
||||
|
||||
useEffect(() => {
|
||||
const params = { nodes: selectedNodes, edges: selectedEdges };
|
||||
|
||||
onSelectionChange?.(params);
|
||||
store.getState().onSelectionChange?.(params);
|
||||
store.getState().onSelectionChangeHandlers.forEach((fn) => fn(params));
|
||||
}, [selectedNodes, selectedEdges, onSelectionChange]);
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
SelectionListener.displayName = 'SelectionListener';
|
||||
|
||||
const changeSelector = (s: ReactFlowState) => !!s.onSelectionChange;
|
||||
|
||||
function Wrapper({ onSelectionChange }: SelectionListenerProps) {
|
||||
const storeHasSelectionChange = useStore(changeSelector);
|
||||
|
||||
if (onSelectionChange || storeHasSelectionChange) {
|
||||
return <SelectionListener onSelectionChange={onSelectionChange} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default Wrapper;
|
||||
const changeSelector = (s: ReactFlowState) => !!s.onSelectionChangeHandlers;
|
||||
|
||||
export function SelectionListener({ onSelectionChange }: SelectionListenerProps) {
|
||||
const storeHasSelectionChangeHandlers = useStore(changeSelector);
|
||||
|
||||
if (onSelectionChange || storeHasSelectionChangeHandlers) {
|
||||
return <SelectionListenerInner onSelectionChange={onSelectionChange} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,220 +1,163 @@
|
||||
import { useEffect } from 'react';
|
||||
import { StoreApi } from 'zustand';
|
||||
/*
|
||||
* This component helps us to update the store with the vlues coming from the user.
|
||||
* We distinguish between values we can update directly with `useDirectStoreUpdater` (like `snapGrid`)
|
||||
* and values that have a dedicated setter function in the store (like `setNodes`).
|
||||
*/
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { devWarn, type CoordinateExtent } from '@xyflow/system';
|
||||
import { infiniteExtent, type CoordinateExtent } from '@xyflow/system';
|
||||
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import type { Node, Edge, ReactFlowState, ReactFlowProps, ReactFlowStore } from '../../types';
|
||||
import type { Node, Edge, ReactFlowState, ReactFlowProps, FitViewOptions } from '../../types';
|
||||
import { defaultNodeOrigin } from '../../container/ReactFlow/init-values';
|
||||
|
||||
type StoreUpdaterProps = Pick<
|
||||
ReactFlowProps,
|
||||
| 'nodes'
|
||||
| 'edges'
|
||||
| 'defaultNodes'
|
||||
| 'defaultEdges'
|
||||
| 'onConnect'
|
||||
| 'onConnectStart'
|
||||
| 'onConnectEnd'
|
||||
| 'onClickConnectStart'
|
||||
| 'onClickConnectEnd'
|
||||
| 'nodesDraggable'
|
||||
| 'nodesConnectable'
|
||||
| 'nodesFocusable'
|
||||
| 'edgesFocusable'
|
||||
| 'edgesUpdatable'
|
||||
| 'minZoom'
|
||||
| 'maxZoom'
|
||||
| 'nodeExtent'
|
||||
| 'onNodesChange'
|
||||
| 'onEdgesChange'
|
||||
| 'elementsSelectable'
|
||||
| 'connectionMode'
|
||||
| 'snapToGrid'
|
||||
| 'snapGrid'
|
||||
| 'translateExtent'
|
||||
| 'connectOnClick'
|
||||
| 'defaultEdgeOptions'
|
||||
| 'fitView'
|
||||
| 'fitViewOptions'
|
||||
| 'onNodesDelete'
|
||||
| 'onEdgesDelete'
|
||||
| 'onNodeDragStart'
|
||||
| 'onNodeDrag'
|
||||
| 'onNodeDragStop'
|
||||
| 'onSelectionDragStart'
|
||||
| 'onSelectionDrag'
|
||||
| 'onSelectionDragStop'
|
||||
| 'onMove'
|
||||
| 'onMoveStart'
|
||||
| 'onMoveEnd'
|
||||
| 'noPanClassName'
|
||||
| 'nodeOrigin'
|
||||
| 'elevateNodesOnSelect'
|
||||
| 'autoPanOnConnect'
|
||||
| 'autoPanOnNodeDrag'
|
||||
| 'onError'
|
||||
| 'connectionRadius'
|
||||
| 'isValidConnection'
|
||||
| 'selectNodesOnDrag'
|
||||
| 'nodeDragThreshold'
|
||||
> & { rfId: string };
|
||||
// these fields exist in the global store and we need to keep them up to date
|
||||
const reactFlowFieldsToTrack = [
|
||||
'nodes',
|
||||
'edges',
|
||||
'defaultNodes',
|
||||
'defaultEdges',
|
||||
'onConnect',
|
||||
'onConnectStart',
|
||||
'onConnectEnd',
|
||||
'onClickConnectStart',
|
||||
'onClickConnectEnd',
|
||||
'nodesDraggable',
|
||||
'nodesConnectable',
|
||||
'nodesFocusable',
|
||||
'edgesFocusable',
|
||||
'edgesReconnectable',
|
||||
'elevateNodesOnSelect',
|
||||
'elevateEdgesOnSelect',
|
||||
'minZoom',
|
||||
'maxZoom',
|
||||
'nodeExtent',
|
||||
'onNodesChange',
|
||||
'onEdgesChange',
|
||||
'elementsSelectable',
|
||||
'connectionMode',
|
||||
'snapGrid',
|
||||
'snapToGrid',
|
||||
'translateExtent',
|
||||
'connectOnClick',
|
||||
'defaultEdgeOptions',
|
||||
'fitView',
|
||||
'fitViewOptions',
|
||||
'onNodesDelete',
|
||||
'onEdgesDelete',
|
||||
'onDelete',
|
||||
'onNodeDrag',
|
||||
'onNodeDragStart',
|
||||
'onNodeDragStop',
|
||||
'onSelectionDrag',
|
||||
'onSelectionDragStart',
|
||||
'onSelectionDragStop',
|
||||
'onMoveStart',
|
||||
'onMove',
|
||||
'onMoveEnd',
|
||||
'noPanClassName',
|
||||
'nodeOrigin',
|
||||
'autoPanOnConnect',
|
||||
'autoPanOnNodeDrag',
|
||||
'onError',
|
||||
'connectionRadius',
|
||||
'isValidConnection',
|
||||
'selectNodesOnDrag',
|
||||
'nodeDragThreshold',
|
||||
'onBeforeDelete',
|
||||
'debug',
|
||||
'autoPanSpeed',
|
||||
] as const;
|
||||
|
||||
type ReactFlowFieldsToTrack = (typeof reactFlowFieldsToTrack)[number];
|
||||
type StoreUpdaterProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> = Pick<
|
||||
ReactFlowProps<NodeType, EdgeType>,
|
||||
ReactFlowFieldsToTrack
|
||||
> & {
|
||||
rfId: string;
|
||||
};
|
||||
|
||||
// rfId doesn't exist in ReactFlowProps, but it's one of the fields we want to update
|
||||
const fieldsToTrack = [...reactFlowFieldsToTrack, 'rfId'] as const;
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
setNodes: s.setNodes,
|
||||
setEdges: s.setEdges,
|
||||
setDefaultNodesAndEdges: s.setDefaultNodesAndEdges,
|
||||
setMinZoom: s.setMinZoom,
|
||||
setMaxZoom: s.setMaxZoom,
|
||||
setTranslateExtent: s.setTranslateExtent,
|
||||
setNodeExtent: s.setNodeExtent,
|
||||
reset: s.reset,
|
||||
setDefaultNodesAndEdges: s.setDefaultNodesAndEdges,
|
||||
});
|
||||
|
||||
function useStoreUpdater<T>(value: T | undefined, setStoreState: (param: T) => void) {
|
||||
useEffect(() => {
|
||||
if (typeof value !== 'undefined') {
|
||||
setStoreState(value);
|
||||
}
|
||||
}, [value]);
|
||||
}
|
||||
const initPrevValues = {
|
||||
// these are values that are also passed directly to other components
|
||||
// than the StoreUpdater. We can reduce the number of setStore calls
|
||||
// by setting the same values here as prev fields.
|
||||
translateExtent: infiniteExtent,
|
||||
nodeOrigin: defaultNodeOrigin,
|
||||
minZoom: 0.5,
|
||||
maxZoom: 2,
|
||||
elementsSelectable: true,
|
||||
noPanClassName: 'nopan',
|
||||
rfId: '1',
|
||||
};
|
||||
|
||||
// updates with values in store that don't have a dedicated setter function
|
||||
function useDirectStoreUpdater(
|
||||
key: keyof ReactFlowStore,
|
||||
value: unknown,
|
||||
setState: StoreApi<ReactFlowState>['setState']
|
||||
export function StoreUpdater<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
|
||||
props: StoreUpdaterProps<NodeType, EdgeType>
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (typeof value !== 'undefined') {
|
||||
setState({ [key]: value });
|
||||
}
|
||||
}, [value]);
|
||||
}
|
||||
|
||||
const StoreUpdater = ({
|
||||
nodes,
|
||||
edges,
|
||||
defaultNodes,
|
||||
defaultEdges,
|
||||
onConnect,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
onClickConnectStart,
|
||||
onClickConnectEnd,
|
||||
nodesDraggable,
|
||||
nodesConnectable,
|
||||
nodesFocusable,
|
||||
edgesFocusable,
|
||||
edgesUpdatable,
|
||||
elevateNodesOnSelect,
|
||||
minZoom,
|
||||
maxZoom,
|
||||
nodeExtent,
|
||||
onNodesChange,
|
||||
onEdgesChange,
|
||||
elementsSelectable,
|
||||
connectionMode,
|
||||
snapGrid,
|
||||
snapToGrid,
|
||||
translateExtent,
|
||||
connectOnClick,
|
||||
defaultEdgeOptions,
|
||||
fitView,
|
||||
fitViewOptions,
|
||||
onNodesDelete,
|
||||
onEdgesDelete,
|
||||
onNodeDrag,
|
||||
onNodeDragStart,
|
||||
onNodeDragStop,
|
||||
onSelectionDrag,
|
||||
onSelectionDragStart,
|
||||
onSelectionDragStop,
|
||||
onMoveStart,
|
||||
onMove,
|
||||
onMoveEnd,
|
||||
noPanClassName,
|
||||
nodeOrigin,
|
||||
rfId,
|
||||
autoPanOnConnect,
|
||||
autoPanOnNodeDrag,
|
||||
onError,
|
||||
connectionRadius,
|
||||
isValidConnection,
|
||||
selectNodesOnDrag,
|
||||
nodeDragThreshold,
|
||||
}: StoreUpdaterProps) => {
|
||||
const {
|
||||
setNodes,
|
||||
setEdges,
|
||||
setDefaultNodesAndEdges,
|
||||
setMinZoom,
|
||||
setMaxZoom,
|
||||
setTranslateExtent,
|
||||
setNodeExtent,
|
||||
reset,
|
||||
setDefaultNodesAndEdges,
|
||||
} = useStore(selector, shallow);
|
||||
const store = useStoreApi();
|
||||
const store = useStoreApi<NodeType, EdgeType>();
|
||||
|
||||
useEffect(() => {
|
||||
const edgesWithDefaults = defaultEdges?.map((e) => ({ ...e, ...defaultEdgeOptions }));
|
||||
setDefaultNodesAndEdges(defaultNodes, edgesWithDefaults);
|
||||
setDefaultNodesAndEdges(props.defaultNodes, props.defaultEdges);
|
||||
|
||||
return () => {
|
||||
// when we reset the store we also need to reset the previous fields
|
||||
previousFields.current = initPrevValues;
|
||||
reset();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useDirectStoreUpdater('defaultEdgeOptions', defaultEdgeOptions, store.setState);
|
||||
useDirectStoreUpdater('connectionMode', connectionMode, store.setState);
|
||||
useDirectStoreUpdater('onConnect', onConnect, store.setState);
|
||||
useDirectStoreUpdater('onConnectStart', onConnectStart, store.setState);
|
||||
useDirectStoreUpdater('onConnectEnd', onConnectEnd, store.setState);
|
||||
useDirectStoreUpdater('onClickConnectStart', onClickConnectStart, store.setState);
|
||||
useDirectStoreUpdater('onClickConnectEnd', onClickConnectEnd, store.setState);
|
||||
useDirectStoreUpdater('nodesDraggable', nodesDraggable, store.setState);
|
||||
useDirectStoreUpdater('nodesConnectable', nodesConnectable, store.setState);
|
||||
useDirectStoreUpdater('nodesFocusable', nodesFocusable, store.setState);
|
||||
useDirectStoreUpdater('edgesFocusable', edgesFocusable, store.setState);
|
||||
useDirectStoreUpdater('edgesUpdatable', edgesUpdatable, 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);
|
||||
useDirectStoreUpdater('onEdgesChange', onEdgesChange, store.setState);
|
||||
useDirectStoreUpdater('connectOnClick', connectOnClick, store.setState);
|
||||
useDirectStoreUpdater('fitViewOnInit', fitView, store.setState);
|
||||
useDirectStoreUpdater('fitViewOnInitOptions', fitViewOptions, store.setState);
|
||||
useDirectStoreUpdater('onNodesDelete', onNodesDelete, store.setState);
|
||||
useDirectStoreUpdater('onEdgesDelete', onEdgesDelete, store.setState);
|
||||
useDirectStoreUpdater('onNodeDrag', onNodeDrag, store.setState);
|
||||
useDirectStoreUpdater('onNodeDragStart', onNodeDragStart, store.setState);
|
||||
useDirectStoreUpdater('onNodeDragStop', onNodeDragStop, store.setState);
|
||||
useDirectStoreUpdater('onSelectionDrag', onSelectionDrag, store.setState);
|
||||
useDirectStoreUpdater('onSelectionDragStart', onSelectionDragStart, store.setState);
|
||||
useDirectStoreUpdater('onSelectionDragStop', onSelectionDragStop, store.setState);
|
||||
useDirectStoreUpdater('onMove', onMove, store.setState);
|
||||
useDirectStoreUpdater('onMoveStart', onMoveStart, store.setState);
|
||||
useDirectStoreUpdater('onMoveEnd', onMoveEnd, store.setState);
|
||||
useDirectStoreUpdater('noPanClassName', noPanClassName, store.setState);
|
||||
useDirectStoreUpdater('nodeOrigin', nodeOrigin, store.setState);
|
||||
useDirectStoreUpdater('rfId', rfId, store.setState);
|
||||
useDirectStoreUpdater('autoPanOnConnect', autoPanOnConnect, store.setState);
|
||||
useDirectStoreUpdater('autoPanOnNodeDrag', autoPanOnNodeDrag, store.setState);
|
||||
useDirectStoreUpdater('onError', onError || devWarn, store.setState);
|
||||
useDirectStoreUpdater('connectionRadius', connectionRadius, store.setState);
|
||||
useDirectStoreUpdater('isValidConnection', isValidConnection, store.setState);
|
||||
useDirectStoreUpdater('selectNodesOnDrag', selectNodesOnDrag, store.setState);
|
||||
useDirectStoreUpdater('nodeDragThreshold', nodeDragThreshold, store.setState);
|
||||
const previousFields = useRef<Partial<StoreUpdaterProps<NodeType, EdgeType>>>(initPrevValues);
|
||||
|
||||
useStoreUpdater<Node[]>(nodes, setNodes);
|
||||
useStoreUpdater<Edge[]>(edges, setEdges);
|
||||
useStoreUpdater<number>(minZoom, setMinZoom);
|
||||
useStoreUpdater<number>(maxZoom, setMaxZoom);
|
||||
useStoreUpdater<CoordinateExtent>(translateExtent, setTranslateExtent);
|
||||
useStoreUpdater<CoordinateExtent>(nodeExtent, setNodeExtent);
|
||||
useEffect(
|
||||
() => {
|
||||
for (const fieldName of fieldsToTrack) {
|
||||
const fieldValue = props[fieldName];
|
||||
const previousFieldValue = previousFields.current[fieldName];
|
||||
|
||||
if (fieldValue === previousFieldValue) continue;
|
||||
if (typeof props[fieldName] === 'undefined') continue;
|
||||
// Custom handling with dedicated setters for some fields
|
||||
if (fieldName === 'nodes') setNodes(fieldValue as Node[]);
|
||||
else if (fieldName === 'edges') setEdges(fieldValue as Edge[]);
|
||||
else if (fieldName === 'minZoom') setMinZoom(fieldValue as number);
|
||||
else if (fieldName === 'maxZoom') setMaxZoom(fieldValue as number);
|
||||
else if (fieldName === 'translateExtent') setTranslateExtent(fieldValue as CoordinateExtent);
|
||||
else if (fieldName === 'nodeExtent') setNodeExtent(fieldValue as CoordinateExtent);
|
||||
// Renamed fields
|
||||
else if (fieldName === 'fitView') store.setState({ fitViewOnInit: fieldValue as boolean });
|
||||
else if (fieldName === 'fitViewOptions') store.setState({ fitViewOnInitOptions: fieldValue as FitViewOptions });
|
||||
// General case
|
||||
else store.setState({ [fieldName]: fieldValue });
|
||||
}
|
||||
|
||||
previousFields.current = props;
|
||||
},
|
||||
// Only re-run the effect if one of the fields we track changes
|
||||
fieldsToTrack.map((fieldName) => props[fieldName])
|
||||
);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default StoreUpdater;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const selector = (s: ReactFlowState) => ({
|
||||
userSelectionRect: s.userSelectionRect,
|
||||
});
|
||||
|
||||
function UserSelection() {
|
||||
export function UserSelection() {
|
||||
const { userSelectionActive, userSelectionRect } = useStore(selector, shallow);
|
||||
const isActive = userSelectionActive && userSelectionRect;
|
||||
|
||||
@@ -27,5 +27,3 @@ function UserSelection() {
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default UserSelection;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import type { ReactFlowState } from '../../types';
|
||||
|
||||
const selector = (s: ReactFlowState) => s.domNode?.querySelector('.react-flow__viewport-portal');
|
||||
|
||||
export function ViewportPortal({ children }: { children: ReactNode }) {
|
||||
const viewPortalDiv = useStore(selector);
|
||||
|
||||
if (!viewPortalDiv) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return createPortal(children, viewPortalDiv);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { memo, useCallback } from 'react';
|
||||
import { memo, useMemo } from 'react';
|
||||
import { type MarkerProps, createMarkerIds } from '@xyflow/system';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import { useMarkerSymbol } from './MarkerSymbols';
|
||||
import type { ReactFlowState } from '../../types';
|
||||
|
||||
type MarkerDefinitionsProps = {
|
||||
defaultColor: string;
|
||||
@@ -43,40 +42,46 @@ const Marker = ({
|
||||
);
|
||||
};
|
||||
|
||||
const markerSelector =
|
||||
({ defaultColor, rfId }: { defaultColor: string; rfId?: string }) =>
|
||||
(s: ReactFlowState) => {
|
||||
const markers = createMarkerIds(s.edges, { id: rfId, defaultColor });
|
||||
|
||||
return markers;
|
||||
};
|
||||
|
||||
// when you have multiple flows on a page and you hide the first one, the other ones have no markers anymore
|
||||
// when they do have markers with the same ids. To prevent this the user can pass a unique id to the react flow wrapper
|
||||
// that we can then use for creating our unique marker ids
|
||||
const MarkerDefinitions = ({ defaultColor, rfId }: MarkerDefinitionsProps) => {
|
||||
const markers = useStore(
|
||||
useCallback(markerSelector({ defaultColor, rfId }), [defaultColor, rfId]),
|
||||
// the id includes all marker options, so we just need to look at that part of the marker
|
||||
(a, b) => !(a.length !== b.length || a.some((m, i) => m.id !== b[i].id))
|
||||
);
|
||||
const edges = useStore((s) => s.edges);
|
||||
const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
|
||||
|
||||
const markers = useMemo(() => {
|
||||
const markers = createMarkerIds(edges, {
|
||||
id: rfId,
|
||||
defaultColor,
|
||||
defaultMarkerStart: defaultEdgeOptions?.markerStart,
|
||||
defaultMarkerEnd: defaultEdgeOptions?.markerEnd,
|
||||
});
|
||||
|
||||
return markers;
|
||||
}, [edges, defaultEdgeOptions, rfId, defaultColor]);
|
||||
|
||||
if (!markers.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<defs>
|
||||
{markers.map((marker: MarkerProps) => (
|
||||
<Marker
|
||||
id={marker.id}
|
||||
key={marker.id}
|
||||
type={marker.type}
|
||||
color={marker.color}
|
||||
width={marker.width}
|
||||
height={marker.height}
|
||||
markerUnits={marker.markerUnits}
|
||||
strokeWidth={marker.strokeWidth}
|
||||
orient={marker.orient}
|
||||
/>
|
||||
))}
|
||||
</defs>
|
||||
<svg className="react-flow__marker">
|
||||
<defs>
|
||||
{markers.map((marker: MarkerProps) => (
|
||||
<Marker
|
||||
id={marker.id}
|
||||
key={marker.id}
|
||||
type={marker.type}
|
||||
color={marker.color}
|
||||
width={marker.width}
|
||||
height={marker.height}
|
||||
markerUnits={marker.markerUnits}
|
||||
strokeWidth={marker.strokeWidth}
|
||||
orient={marker.orient}
|
||||
/>
|
||||
))}
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -57,5 +57,3 @@ export function useMarkerSymbol(type: MarkerType) {
|
||||
|
||||
return symbol;
|
||||
}
|
||||
|
||||
export default MarkerSymbols;
|
||||
|
||||
@@ -1,145 +1,100 @@
|
||||
import { memo, ReactNode } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import cc from 'classcat';
|
||||
import { errorMessages } from '@xyflow/system';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import useVisibleEdges from '../../hooks/useVisibleEdges';
|
||||
import { useVisibleEdgeIds } from '../../hooks/useVisibleEdgeIds';
|
||||
import MarkerDefinitions from './MarkerDefinitions';
|
||||
import { GraphViewProps } from '../GraphView';
|
||||
import type { EdgeTypesWrapped, ReactFlowState } from '../../types';
|
||||
import { EdgeWrapper } from '../../components/EdgeWrapper';
|
||||
import type { Edge, ReactFlowState, Node } from '../../types';
|
||||
|
||||
type EdgeRendererProps = Pick<
|
||||
GraphViewProps,
|
||||
type EdgeRendererProps<EdgeType extends Edge = Edge> = Pick<
|
||||
GraphViewProps<Node, EdgeType>,
|
||||
| 'onEdgeClick'
|
||||
| 'onEdgeDoubleClick'
|
||||
| 'defaultMarkerColor'
|
||||
| 'onlyRenderVisibleElements'
|
||||
| 'onEdgeUpdate'
|
||||
| 'onReconnect'
|
||||
| 'onEdgeContextMenu'
|
||||
| 'onEdgeMouseEnter'
|
||||
| 'onEdgeMouseMove'
|
||||
| 'onEdgeMouseLeave'
|
||||
| 'onEdgeUpdateStart'
|
||||
| 'onEdgeUpdateEnd'
|
||||
| 'edgeUpdaterRadius'
|
||||
| 'onReconnectStart'
|
||||
| 'onReconnectEnd'
|
||||
| 'reconnectRadius'
|
||||
| 'noPanClassName'
|
||||
| 'elevateEdgesOnSelect'
|
||||
| 'rfId'
|
||||
| 'disableKeyboardA11y'
|
||||
| 'edgeTypes'
|
||||
> & {
|
||||
edgeTypes: EdgeTypesWrapped;
|
||||
elevateEdgesOnSelect: boolean;
|
||||
children: ReactNode;
|
||||
children?: ReactNode;
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
width: s.width,
|
||||
height: s.height,
|
||||
edgesFocusable: s.edgesFocusable,
|
||||
edgesUpdatable: s.edgesUpdatable,
|
||||
edgesReconnectable: s.edgesReconnectable,
|
||||
elementsSelectable: s.elementsSelectable,
|
||||
connectionMode: s.connectionMode,
|
||||
onError: s.onError,
|
||||
});
|
||||
|
||||
const EdgeRenderer = ({
|
||||
function EdgeRendererComponent<EdgeType extends Edge = Edge>({
|
||||
defaultMarkerColor,
|
||||
onlyRenderVisibleElements,
|
||||
elevateEdgesOnSelect,
|
||||
rfId,
|
||||
edgeTypes,
|
||||
noPanClassName,
|
||||
onEdgeUpdate,
|
||||
onReconnect,
|
||||
onEdgeContextMenu,
|
||||
onEdgeMouseEnter,
|
||||
onEdgeMouseMove,
|
||||
onEdgeMouseLeave,
|
||||
onEdgeClick,
|
||||
edgeUpdaterRadius,
|
||||
reconnectRadius,
|
||||
onEdgeDoubleClick,
|
||||
onEdgeUpdateStart,
|
||||
onEdgeUpdateEnd,
|
||||
children,
|
||||
}: EdgeRendererProps) => {
|
||||
const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
|
||||
const edgeTree = useVisibleEdges(onlyRenderVisibleElements, elevateEdgesOnSelect);
|
||||
onReconnectStart,
|
||||
onReconnectEnd,
|
||||
disableKeyboardA11y,
|
||||
}: EdgeRendererProps<EdgeType>) {
|
||||
const { edgesFocusable, edgesReconnectable, elementsSelectable, onError } = useStore(selector, shallow);
|
||||
const edgeIds = useVisibleEdgeIds(onlyRenderVisibleElements);
|
||||
|
||||
return (
|
||||
<>
|
||||
{edgeTree.map(({ level, edges, isMaxLevel }) => (
|
||||
<svg key={level} style={{ zIndex: level }} className="react-flow__edges react-flow__container">
|
||||
{isMaxLevel && <MarkerDefinitions defaultColor={defaultMarkerColor} rfId={rfId} />}
|
||||
<g>
|
||||
{edges.map((edge) => {
|
||||
let edgeType = edge.type || 'default';
|
||||
<div className="react-flow__edges">
|
||||
<MarkerDefinitions defaultColor={defaultMarkerColor} rfId={rfId} />
|
||||
|
||||
if (!edgeTypes[edgeType]) {
|
||||
onError?.('011', errorMessages['error011'](edgeType));
|
||||
edgeType = 'default';
|
||||
}
|
||||
|
||||
const EdgeComponent = edgeTypes[edgeType];
|
||||
const isFocusable = !!(edge.focusable || (edgesFocusable && typeof edge.focusable === 'undefined'));
|
||||
const isUpdatable =
|
||||
typeof onEdgeUpdate !== 'undefined' &&
|
||||
(edge.updatable || (edgesUpdatable && typeof edge.updatable === 'undefined'));
|
||||
const isSelectable = !!(
|
||||
edge.selectable ||
|
||||
(elementsSelectable && typeof edge.selectable === 'undefined')
|
||||
);
|
||||
|
||||
return (
|
||||
<EdgeComponent
|
||||
key={edge.id}
|
||||
id={edge.id}
|
||||
className={cc([edge.className, noPanClassName])}
|
||||
type={edge.type}
|
||||
data={edge.data}
|
||||
selected={!!edge.selected}
|
||||
animated={!!edge.animated}
|
||||
hidden={!!edge.hidden}
|
||||
label={edge.label}
|
||||
labelStyle={edge.labelStyle}
|
||||
labelShowBg={edge.labelShowBg}
|
||||
labelBgStyle={edge.labelBgStyle}
|
||||
labelBgPadding={edge.labelBgPadding}
|
||||
labelBgBorderRadius={edge.labelBgBorderRadius}
|
||||
style={edge.style}
|
||||
source={edge.source}
|
||||
target={edge.target}
|
||||
sourceHandleId={edge.sourceHandle}
|
||||
targetHandleId={edge.targetHandle}
|
||||
markerEnd={edge.markerEnd}
|
||||
markerStart={edge.markerStart}
|
||||
isSelectable={isSelectable}
|
||||
onEdgeUpdate={onEdgeUpdate}
|
||||
onContextMenu={onEdgeContextMenu}
|
||||
onMouseEnter={onEdgeMouseEnter}
|
||||
onMouseMove={onEdgeMouseMove}
|
||||
onMouseLeave={onEdgeMouseLeave}
|
||||
onClick={onEdgeClick}
|
||||
edgeUpdaterRadius={edgeUpdaterRadius}
|
||||
onEdgeDoubleClick={onEdgeDoubleClick}
|
||||
onEdgeUpdateStart={onEdgeUpdateStart}
|
||||
onEdgeUpdateEnd={onEdgeUpdateEnd}
|
||||
rfId={rfId}
|
||||
ariaLabel={edge.ariaLabel}
|
||||
isFocusable={isFocusable}
|
||||
isUpdatable={isUpdatable}
|
||||
pathOptions={'pathOptions' in edge ? edge.pathOptions : undefined}
|
||||
interactionWidth={edge.interactionWidth}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
</svg>
|
||||
))}
|
||||
{children}
|
||||
</>
|
||||
{edgeIds.map((id) => {
|
||||
return (
|
||||
<EdgeWrapper<EdgeType>
|
||||
key={id}
|
||||
id={id}
|
||||
edgesFocusable={edgesFocusable}
|
||||
edgesReconnectable={edgesReconnectable}
|
||||
elementsSelectable={elementsSelectable}
|
||||
noPanClassName={noPanClassName}
|
||||
onReconnect={onReconnect}
|
||||
onContextMenu={onEdgeContextMenu}
|
||||
onMouseEnter={onEdgeMouseEnter}
|
||||
onMouseMove={onEdgeMouseMove}
|
||||
onMouseLeave={onEdgeMouseLeave}
|
||||
onClick={onEdgeClick}
|
||||
reconnectRadius={reconnectRadius}
|
||||
onDoubleClick={onEdgeDoubleClick}
|
||||
onReconnectStart={onReconnectStart}
|
||||
onReconnectEnd={onReconnectEnd}
|
||||
rfId={rfId}
|
||||
onError={onError}
|
||||
edgeTypes={edgeTypes}
|
||||
disableKeyboardA11y={disableKeyboardA11y}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
EdgeRenderer.displayName = 'EdgeRenderer';
|
||||
EdgeRendererComponent.displayName = 'EdgeRenderer';
|
||||
|
||||
export default memo(EdgeRenderer);
|
||||
export const EdgeRenderer = memo(EdgeRendererComponent) as typeof EdgeRendererComponent;
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { ComponentType } from 'react';
|
||||
|
||||
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge, SimpleBezierEdge } from '../../components/Edges';
|
||||
import wrapEdge from '../../components/Edges/wrapEdge';
|
||||
import type { EdgeProps, EdgeTypes, EdgeTypesWrapped } from '../../types';
|
||||
|
||||
export type CreateEdgeTypes = (edgeTypes: EdgeTypes) => EdgeTypesWrapped;
|
||||
|
||||
export function createEdgeTypes(edgeTypes: EdgeTypes): EdgeTypesWrapped {
|
||||
const standardTypes: EdgeTypesWrapped = {
|
||||
default: wrapEdge((edgeTypes.default || BezierEdge) as ComponentType<EdgeProps>),
|
||||
straight: wrapEdge((edgeTypes.bezier || StraightEdge) as ComponentType<EdgeProps>),
|
||||
step: wrapEdge((edgeTypes.step || StepEdge) as ComponentType<EdgeProps>),
|
||||
smoothstep: wrapEdge((edgeTypes.step || SmoothStepEdge) as ComponentType<EdgeProps>),
|
||||
simplebezier: wrapEdge((edgeTypes.simplebezier || SimpleBezierEdge) as ComponentType<EdgeProps>),
|
||||
};
|
||||
|
||||
const wrappedTypes = {} as EdgeTypesWrapped;
|
||||
const specialTypes: EdgeTypesWrapped = Object.keys(edgeTypes)
|
||||
.filter((k) => !['default', 'bezier'].includes(k))
|
||||
.reduce((res, key) => {
|
||||
res[key] = wrapEdge((edgeTypes[key] || BezierEdge) as ComponentType<EdgeProps>);
|
||||
|
||||
return res;
|
||||
}, wrappedTypes);
|
||||
|
||||
return {
|
||||
...standardTypes,
|
||||
...specialTypes,
|
||||
};
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import { memo, type ReactNode } from 'react';
|
||||
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import useGlobalKeyHandler from '../../hooks/useGlobalKeyHandler';
|
||||
import useKeyPress from '../../hooks/useKeyPress';
|
||||
import { useGlobalKeyHandler } from '../../hooks/useGlobalKeyHandler';
|
||||
import { useKeyPress } from '../../hooks/useKeyPress';
|
||||
import { GraphViewProps } from '../GraphView';
|
||||
import ZoomPane from '../ZoomPane';
|
||||
import Pane from '../Pane';
|
||||
import NodesSelection from '../../components/NodesSelection';
|
||||
import type { ReactFlowState } from '../../types';
|
||||
import { ZoomPane } from '../ZoomPane';
|
||||
import { Pane } from '../Pane';
|
||||
import { NodesSelection } from '../../components/NodesSelection';
|
||||
import type { ReactFlowState, Node } from '../../types';
|
||||
|
||||
export type FlowRendererProps = Omit<
|
||||
GraphViewProps,
|
||||
export type FlowRendererProps<NodeType extends Node = Node> = Omit<
|
||||
GraphViewProps<NodeType>,
|
||||
| 'snapToGrid'
|
||||
| 'nodeTypes'
|
||||
| 'edgeTypes'
|
||||
@@ -22,15 +22,18 @@ export type FlowRendererProps = Omit<
|
||||
| 'selectNodesOnDrag'
|
||||
| 'defaultMarkerColor'
|
||||
| 'rfId'
|
||||
| 'nodeOrigin'
|
||||
> & {
|
||||
isControlledViewport: boolean;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => s.nodesSelectionActive;
|
||||
const win = typeof window !== 'undefined' ? window : undefined;
|
||||
|
||||
const FlowRenderer = ({
|
||||
const selector = (s: ReactFlowState) => {
|
||||
return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive };
|
||||
};
|
||||
|
||||
function FlowRendererComponent<NodeType extends Node = Node>({
|
||||
children,
|
||||
onPaneClick,
|
||||
onPaneMouseEnter,
|
||||
@@ -50,7 +53,7 @@ const FlowRenderer = ({
|
||||
elementsSelectable,
|
||||
zoomOnScroll,
|
||||
zoomOnPinch,
|
||||
panOnScroll,
|
||||
panOnScroll: _panOnScroll,
|
||||
panOnScrollSpeed,
|
||||
panOnScrollMode,
|
||||
zoomOnDoubleClick,
|
||||
@@ -66,13 +69,14 @@ const FlowRenderer = ({
|
||||
disableKeyboardA11y,
|
||||
onViewportChange,
|
||||
isControlledViewport,
|
||||
}: FlowRendererProps) => {
|
||||
const nodesSelectionActive = useStore(selector);
|
||||
const selectionKeyPressed = useKeyPress(selectionKeyCode);
|
||||
const panActivationKeyPressed = useKeyPress(panActivationKeyCode);
|
||||
}: FlowRendererProps<NodeType>) {
|
||||
const { nodesSelectionActive, userSelectionActive } = useStore(selector);
|
||||
const selectionKeyPressed = useKeyPress(selectionKeyCode, { target: win });
|
||||
const panActivationKeyPressed = useKeyPress(panActivationKeyCode, { target: win });
|
||||
|
||||
const panOnDrag = panActivationKeyPressed || _panOnDrag;
|
||||
const isSelecting = selectionKeyPressed || (selectionOnDrag && panOnDrag !== true);
|
||||
const panOnScroll = panActivationKeyPressed || _panOnScroll;
|
||||
const isSelecting = selectionKeyPressed || userSelectionActive || (selectionOnDrag && panOnDrag !== true);
|
||||
|
||||
useGlobalKeyHandler({ deleteKeyCode, multiSelectionKeyCode });
|
||||
|
||||
@@ -110,6 +114,7 @@ const FlowRenderer = ({
|
||||
panOnDrag={panOnDrag}
|
||||
isSelecting={!!isSelecting}
|
||||
selectionMode={selectionMode}
|
||||
selectionKeyPressed={selectionKeyPressed}
|
||||
>
|
||||
{children}
|
||||
{nodesSelectionActive && (
|
||||
@@ -122,8 +127,8 @@ const FlowRenderer = ({
|
||||
</Pane>
|
||||
</ZoomPane>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
FlowRenderer.displayName = 'FlowRenderer';
|
||||
FlowRendererComponent.displayName = 'FlowRenderer';
|
||||
|
||||
export default memo(FlowRenderer);
|
||||
export const FlowRenderer = memo(FlowRendererComponent) as typeof FlowRendererComponent;
|
||||
|
||||
@@ -1,26 +1,23 @@
|
||||
import { memo } from 'react';
|
||||
|
||||
import FlowRenderer from '../FlowRenderer';
|
||||
import NodeRenderer from '../NodeRenderer';
|
||||
import EdgeRenderer from '../EdgeRenderer';
|
||||
import ViewportWrapper from '../Viewport';
|
||||
import useOnInitHandler from '../../hooks/useOnInitHandler';
|
||||
import useViewportSync from '../../hooks/useViewportSync';
|
||||
import ConnectionLine from '../../components/ConnectionLine';
|
||||
import type { ReactFlowProps } from '../../types';
|
||||
import { createNodeTypes } from '../NodeRenderer/utils';
|
||||
import { createEdgeTypes } from '../EdgeRenderer/utils';
|
||||
import { useNodeOrEdgeTypes } from './utils';
|
||||
import { FlowRenderer } from '../FlowRenderer';
|
||||
import { NodeRenderer } from '../NodeRenderer';
|
||||
import { EdgeRenderer } from '../EdgeRenderer';
|
||||
import { Viewport } from '../Viewport';
|
||||
import { useOnInitHandler } from '../../hooks/useOnInitHandler';
|
||||
import { useViewportSync } from '../../hooks/useViewportSync';
|
||||
import { ConnectionLineWrapper } from '../../components/ConnectionLine';
|
||||
import { useNodeOrEdgeTypesWarning } from './useNodeOrEdgeTypesWarning';
|
||||
import type { Edge, Node, ReactFlowProps } from '../../types';
|
||||
import { useStylesLoadedWarning } from './useStylesLoadedWarning';
|
||||
|
||||
export type GraphViewProps = Omit<
|
||||
ReactFlowProps,
|
||||
'onSelectionChange' | 'nodes' | 'edges' | 'nodeTypes' | 'edgeTypes' | 'onMove' | 'onMoveStart' | 'onMoveEnd'
|
||||
export type GraphViewProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> = Omit<
|
||||
ReactFlowProps<NodeType, EdgeType>,
|
||||
'onSelectionChange' | 'nodes' | 'edges' | 'onMove' | 'onMoveStart' | 'onMoveEnd' | 'elevateEdgesOnSelect'
|
||||
> &
|
||||
Required<
|
||||
Pick<
|
||||
ReactFlowProps,
|
||||
| 'nodeTypes'
|
||||
| 'edgeTypes'
|
||||
ReactFlowProps<NodeType, EdgeType>,
|
||||
| 'selectionKeyCode'
|
||||
| 'deleteKeyCode'
|
||||
| 'multiSelectionKeyCode'
|
||||
@@ -31,18 +28,16 @@ export type GraphViewProps = Omit<
|
||||
| 'maxZoom'
|
||||
| 'defaultMarkerColor'
|
||||
| 'noDragClassName'
|
||||
| 'noDragClassName'
|
||||
| 'noWheelClassName'
|
||||
| 'noPanClassName'
|
||||
| 'defaultViewport'
|
||||
| 'disableKeyboardA11y'
|
||||
| 'nodeOrigin'
|
||||
>
|
||||
> & {
|
||||
rfId: string;
|
||||
};
|
||||
|
||||
const GraphView = ({
|
||||
function GraphViewComponent<NodeType extends Node = Node, EdgeType extends Edge = Edge>({
|
||||
nodeTypes,
|
||||
edgeTypes,
|
||||
onInit,
|
||||
@@ -89,33 +84,32 @@ const GraphView = ({
|
||||
onPaneMouseLeave,
|
||||
onPaneScroll,
|
||||
onPaneContextMenu,
|
||||
onEdgeUpdate,
|
||||
onEdgeContextMenu,
|
||||
onEdgeMouseEnter,
|
||||
onEdgeMouseMove,
|
||||
onEdgeMouseLeave,
|
||||
edgeUpdaterRadius,
|
||||
onEdgeUpdateStart,
|
||||
onEdgeUpdateEnd,
|
||||
reconnectRadius,
|
||||
onReconnect,
|
||||
onReconnectStart,
|
||||
onReconnectEnd,
|
||||
noDragClassName,
|
||||
noWheelClassName,
|
||||
noPanClassName,
|
||||
elevateEdgesOnSelect,
|
||||
disableKeyboardA11y,
|
||||
nodeOrigin,
|
||||
nodeExtent,
|
||||
rfId,
|
||||
viewport,
|
||||
onViewportChange,
|
||||
}: GraphViewProps) => {
|
||||
const nodeTypesWrapped = useNodeOrEdgeTypes(nodeTypes, createNodeTypes);
|
||||
const edgeTypesWrapped = useNodeOrEdgeTypes(edgeTypes, createEdgeTypes);
|
||||
}: GraphViewProps<NodeType, EdgeType>) {
|
||||
useNodeOrEdgeTypesWarning(nodeTypes);
|
||||
useNodeOrEdgeTypesWarning(edgeTypes);
|
||||
useStylesLoadedWarning();
|
||||
|
||||
useOnInitHandler(onInit);
|
||||
useViewportSync(viewport);
|
||||
|
||||
return (
|
||||
<FlowRenderer
|
||||
<FlowRenderer<NodeType>
|
||||
onPaneClick={onPaneClick}
|
||||
onPaneMouseEnter={onPaneMouseEnter}
|
||||
onPaneMouseMove={onPaneMouseMove}
|
||||
@@ -152,37 +146,34 @@ const GraphView = ({
|
||||
onViewportChange={onViewportChange}
|
||||
isControlledViewport={!!viewport}
|
||||
>
|
||||
<ViewportWrapper>
|
||||
<EdgeRenderer
|
||||
edgeTypes={edgeTypesWrapped}
|
||||
<Viewport>
|
||||
<EdgeRenderer<EdgeType>
|
||||
edgeTypes={edgeTypes}
|
||||
onEdgeClick={onEdgeClick}
|
||||
onEdgeDoubleClick={onEdgeDoubleClick}
|
||||
onEdgeUpdate={onEdgeUpdate}
|
||||
onReconnect={onReconnect}
|
||||
onReconnectStart={onReconnectStart}
|
||||
onReconnectEnd={onReconnectEnd}
|
||||
onlyRenderVisibleElements={onlyRenderVisibleElements}
|
||||
onEdgeContextMenu={onEdgeContextMenu}
|
||||
onEdgeMouseEnter={onEdgeMouseEnter}
|
||||
onEdgeMouseMove={onEdgeMouseMove}
|
||||
onEdgeMouseLeave={onEdgeMouseLeave}
|
||||
onEdgeUpdateStart={onEdgeUpdateStart}
|
||||
onEdgeUpdateEnd={onEdgeUpdateEnd}
|
||||
edgeUpdaterRadius={edgeUpdaterRadius}
|
||||
reconnectRadius={reconnectRadius}
|
||||
defaultMarkerColor={defaultMarkerColor}
|
||||
noPanClassName={noPanClassName}
|
||||
elevateEdgesOnSelect={!!elevateEdgesOnSelect}
|
||||
disableKeyboardA11y={disableKeyboardA11y}
|
||||
rfId={rfId}
|
||||
>
|
||||
<ConnectionLine
|
||||
style={connectionLineStyle}
|
||||
type={connectionLineType}
|
||||
component={connectionLineComponent}
|
||||
containerStyle={connectionLineContainerStyle}
|
||||
/>
|
||||
</EdgeRenderer>
|
||||
/>
|
||||
<ConnectionLineWrapper
|
||||
style={connectionLineStyle}
|
||||
type={connectionLineType}
|
||||
component={connectionLineComponent}
|
||||
containerStyle={connectionLineContainerStyle}
|
||||
/>
|
||||
<div className="react-flow__edgelabel-renderer" />
|
||||
|
||||
<NodeRenderer
|
||||
nodeTypes={nodeTypesWrapped}
|
||||
<NodeRenderer<NodeType>
|
||||
nodeTypes={nodeTypes}
|
||||
onNodeClick={onNodeClick}
|
||||
onNodeDoubleClick={onNodeDoubleClick}
|
||||
onNodeMouseEnter={onNodeMouseEnter}
|
||||
@@ -193,15 +184,15 @@ const GraphView = ({
|
||||
noPanClassName={noPanClassName}
|
||||
noDragClassName={noDragClassName}
|
||||
disableKeyboardA11y={disableKeyboardA11y}
|
||||
nodeOrigin={nodeOrigin}
|
||||
nodeExtent={nodeExtent}
|
||||
rfId={rfId}
|
||||
/>
|
||||
</ViewportWrapper>
|
||||
<div className="react-flow__viewport-portal" />
|
||||
</Viewport>
|
||||
</FlowRenderer>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
GraphView.displayName = 'GraphView';
|
||||
GraphViewComponent.displayName = 'GraphView';
|
||||
|
||||
export default memo(GraphView);
|
||||
export const GraphView = memo(GraphViewComponent) as typeof GraphViewComponent;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { errorMessages } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
import type { EdgeTypes, NodeTypes } from '../../types';
|
||||
|
||||
const emptyTypes = {};
|
||||
|
||||
/**
|
||||
* This hook warns the user if nodeTypes or edgeTypes changed.
|
||||
* It is only used in development mode.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useNodeOrEdgeTypesWarning(nodeOrEdgeTypes?: NodeTypes): void;
|
||||
export function useNodeOrEdgeTypesWarning(nodeOrEdgeTypes?: EdgeTypes): void;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function useNodeOrEdgeTypesWarning(nodeOrEdgeTypes: any = emptyTypes): any {
|
||||
const typesRef = useRef(nodeOrEdgeTypes);
|
||||
const store = useStoreApi();
|
||||
|
||||
useEffect(() => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const usedKeys = new Set([...Object.keys(typesRef.current), ...Object.keys(nodeOrEdgeTypes)]);
|
||||
|
||||
for (const key of usedKeys) {
|
||||
if (typesRef.current[key] !== nodeOrEdgeTypes[key]) {
|
||||
store.getState().onError?.('002', errorMessages['error002']());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
typesRef.current = nodeOrEdgeTypes;
|
||||
}
|
||||
}, [nodeOrEdgeTypes]);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { errorMessages } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
|
||||
export function useStylesLoadedWarning() {
|
||||
const store = useStoreApi();
|
||||
const checked = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
if (!checked.current) {
|
||||
const pane = document.querySelector('.react-flow__pane');
|
||||
|
||||
if (pane && !(window.getComputedStyle(pane).zIndex === '1')) {
|
||||
store.getState().onError?.('013', errorMessages['error013']('react'));
|
||||
}
|
||||
|
||||
checked.current = true;
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { useMemo, useRef } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { errorMessages } from '@xyflow/system';
|
||||
|
||||
import { CreateEdgeTypes } from '../EdgeRenderer/utils';
|
||||
import { CreateNodeTypes } from '../NodeRenderer/utils';
|
||||
import type { EdgeTypes, EdgeTypesWrapped, NodeTypes, NodeTypesWrapped } from '../../types';
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
|
||||
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: NodeTypes, createTypes: CreateNodeTypes): NodeTypesWrapped;
|
||||
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: EdgeTypes, createTypes: CreateEdgeTypes): EdgeTypesWrapped;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function useNodeOrEdgeTypes(nodeOrEdgeTypes: any, createTypes: any): any {
|
||||
const typesKeysRef = useRef<string[] | null>(null);
|
||||
const store = useStoreApi();
|
||||
|
||||
const typesParsed = useMemo(() => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const typeKeys = Object.keys(nodeOrEdgeTypes);
|
||||
|
||||
if (shallow(typesKeysRef.current, typeKeys)) {
|
||||
store.getState().onError?.('002', errorMessages['error002']());
|
||||
}
|
||||
|
||||
typesKeysRef.current = typeKeys;
|
||||
}
|
||||
return createTypes(nodeOrEdgeTypes);
|
||||
}, [nodeOrEdgeTypes]);
|
||||
|
||||
return typesParsed;
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
import { memo, useMemo, useEffect, useRef, type ComponentType } from 'react';
|
||||
import { memo } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { internalsSymbol, errorMessages, Position, clampPosition, getPositionWithOrigin } from '@xyflow/system';
|
||||
|
||||
import useVisibleNodes from '../../hooks/useVisibleNodes';
|
||||
import { useVisibleNodeIds } from '../../hooks/useVisibleNodeIds';
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import { containerStyle } from '../../styles/utils';
|
||||
import { GraphViewProps } from '../GraphView';
|
||||
import type { NodeTypesWrapped, ReactFlowState, WrapNodeProps } from '../../types';
|
||||
import { useResizeObserver } from './useResizeObserver';
|
||||
import { NodeWrapper } from '../../components/NodeWrapper';
|
||||
import type { Node, ReactFlowState } from '../../types';
|
||||
|
||||
type NodeRendererProps = Pick<
|
||||
GraphViewProps,
|
||||
export type NodeRendererProps<NodeType extends Node> = Pick<
|
||||
GraphViewProps<NodeType>,
|
||||
| 'onNodeClick'
|
||||
| 'onNodeDoubleClick'
|
||||
| 'onNodeMouseEnter'
|
||||
@@ -21,130 +22,78 @@ type NodeRendererProps = Pick<
|
||||
| 'noDragClassName'
|
||||
| 'rfId'
|
||||
| 'disableKeyboardA11y'
|
||||
| 'nodeOrigin'
|
||||
| 'nodeExtent'
|
||||
> & {
|
||||
nodeTypes: NodeTypesWrapped;
|
||||
};
|
||||
| 'nodeTypes'
|
||||
>;
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
nodesDraggable: s.nodesDraggable,
|
||||
nodesConnectable: s.nodesConnectable,
|
||||
nodesFocusable: s.nodesFocusable,
|
||||
elementsSelectable: s.elementsSelectable,
|
||||
updateNodeDimensions: s.updateNodeDimensions,
|
||||
onError: s.onError,
|
||||
});
|
||||
|
||||
const NodeRenderer = (props: NodeRendererProps) => {
|
||||
const { nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, updateNodeDimensions, onError } =
|
||||
useStore(selector, shallow);
|
||||
const nodes = useVisibleNodes(props.onlyRenderVisibleElements);
|
||||
const resizeObserverRef = useRef<ResizeObserver>();
|
||||
|
||||
const resizeObserver = useMemo(() => {
|
||||
if (typeof ResizeObserver === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver((entries: ResizeObserverEntry[]) => {
|
||||
const updates = entries.map((entry: ResizeObserverEntry) => ({
|
||||
id: entry.target.getAttribute('data-id') as string,
|
||||
nodeElement: entry.target as HTMLDivElement,
|
||||
forceUpdate: true,
|
||||
}));
|
||||
|
||||
updateNodeDimensions(updates);
|
||||
});
|
||||
|
||||
resizeObserverRef.current = observer;
|
||||
|
||||
return observer;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
resizeObserverRef?.current?.disconnect();
|
||||
};
|
||||
}, []);
|
||||
function NodeRendererComponent<NodeType extends Node>(props: NodeRendererProps<NodeType>) {
|
||||
const { nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, onError } = useStore(selector, shallow);
|
||||
const nodeIds = useVisibleNodeIds(props.onlyRenderVisibleElements);
|
||||
const resizeObserver = useResizeObserver();
|
||||
|
||||
return (
|
||||
<div className="react-flow__nodes" style={containerStyle}>
|
||||
{nodes.map((node) => {
|
||||
let nodeType = node.type || 'default';
|
||||
|
||||
if (!props.nodeTypes[nodeType]) {
|
||||
onError?.('003', errorMessages['error003'](nodeType));
|
||||
|
||||
nodeType = 'default';
|
||||
}
|
||||
|
||||
const NodeComponent = (props.nodeTypes[nodeType] || props.nodeTypes.default) as ComponentType<WrapNodeProps>;
|
||||
const isDraggable = !!(node.draggable || (nodesDraggable && typeof node.draggable === 'undefined'));
|
||||
const isSelectable = !!(node.selectable || (elementsSelectable && typeof node.selectable === 'undefined'));
|
||||
const isConnectable = !!(node.connectable || (nodesConnectable && typeof node.connectable === 'undefined'));
|
||||
const isFocusable = !!(node.focusable || (nodesFocusable && typeof node.focusable === 'undefined'));
|
||||
|
||||
const clampedPosition = props.nodeExtent
|
||||
? clampPosition(node.positionAbsolute, props.nodeExtent)
|
||||
: node.positionAbsolute;
|
||||
|
||||
const posX = clampedPosition?.x ?? 0;
|
||||
const posY = clampedPosition?.y ?? 0;
|
||||
const posOrigin = getPositionWithOrigin({
|
||||
x: posX,
|
||||
y: posY,
|
||||
width: node.width ?? 0,
|
||||
height: node.height ?? 0,
|
||||
origin: node.origin || props.nodeOrigin,
|
||||
});
|
||||
const initialized = (!!node.width && !!node.height) || (!!node.size?.width && !!node.size?.height);
|
||||
|
||||
{nodeIds.map((nodeId) => {
|
||||
return (
|
||||
<NodeComponent
|
||||
key={node.id}
|
||||
id={node.id}
|
||||
className={node.className}
|
||||
style={node.style}
|
||||
sizeWidth={node.size?.width}
|
||||
sizeHeight={node.size?.height}
|
||||
type={nodeType}
|
||||
data={node.data}
|
||||
sourcePosition={node.sourcePosition || Position.Bottom}
|
||||
targetPosition={node.targetPosition || Position.Top}
|
||||
hidden={node.hidden}
|
||||
xPos={posX}
|
||||
yPos={posY}
|
||||
xPosOrigin={posOrigin.x}
|
||||
yPosOrigin={posOrigin.y}
|
||||
// The split of responsibilities between NodeRenderer and
|
||||
// NodeComponentWrapper may appear weird. However, it’s designed to
|
||||
// minimize the cost of updates when individual nodes change.
|
||||
//
|
||||
// For example, when you’re dragging a single node, that node gets
|
||||
// updated multiple times per second. If `NodeRenderer` were to update
|
||||
// every time, it would have to re-run the `nodes.map()` loop every
|
||||
// time. This gets pricey with hundreds of nodes, especially if every
|
||||
// loop cycle does more than just rendering a JSX element!
|
||||
//
|
||||
// As a result of this choice, we took the following implementation
|
||||
// decisions:
|
||||
// - NodeRenderer subscribes *only* to node IDs – and therefore
|
||||
// rerender *only* when visible nodes are added or removed.
|
||||
// - NodeRenderer performs all operations the result of which can be
|
||||
// shared between nodes (such as creating the `ResizeObserver`
|
||||
// instance, or subscribing to `selector`). This means extra prop
|
||||
// drilling into `NodeComponentWrapper`, but it means we need to run
|
||||
// these operations only once – instead of once per node.
|
||||
// - Any operations that you’d normally write inside `nodes.map` are
|
||||
// moved into `NodeComponentWrapper`. This ensures they are
|
||||
// memorized – so if `NodeRenderer` *has* to rerender, it only
|
||||
// needs to regenerate the list of nodes, nothing else.
|
||||
<NodeWrapper<NodeType>
|
||||
key={nodeId}
|
||||
id={nodeId}
|
||||
nodeTypes={props.nodeTypes}
|
||||
nodeExtent={props.nodeExtent}
|
||||
onClick={props.onNodeClick}
|
||||
onMouseEnter={props.onNodeMouseEnter}
|
||||
onMouseMove={props.onNodeMouseMove}
|
||||
onMouseLeave={props.onNodeMouseLeave}
|
||||
onContextMenu={props.onNodeContextMenu}
|
||||
onDoubleClick={props.onNodeDoubleClick}
|
||||
selected={!!node.selected}
|
||||
isDraggable={isDraggable}
|
||||
isSelectable={isSelectable}
|
||||
isConnectable={isConnectable}
|
||||
isFocusable={isFocusable}
|
||||
resizeObserver={resizeObserver}
|
||||
dragHandle={node.dragHandle}
|
||||
zIndex={node[internalsSymbol]?.z ?? 0}
|
||||
isParent={!!node[internalsSymbol]?.isParent}
|
||||
noDragClassName={props.noDragClassName}
|
||||
noPanClassName={props.noPanClassName}
|
||||
initialized={initialized}
|
||||
rfId={props.rfId}
|
||||
disableKeyboardA11y={props.disableKeyboardA11y}
|
||||
ariaLabel={node.ariaLabel}
|
||||
resizeObserver={resizeObserver}
|
||||
nodesDraggable={nodesDraggable}
|
||||
nodesConnectable={nodesConnectable}
|
||||
nodesFocusable={nodesFocusable}
|
||||
elementsSelectable={elementsSelectable}
|
||||
onError={onError}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
NodeRenderer.displayName = 'NodeRenderer';
|
||||
NodeRendererComponent.displayName = 'NodeRenderer';
|
||||
|
||||
export default memo(NodeRenderer);
|
||||
export const NodeRenderer = memo(NodeRendererComponent) as typeof NodeRendererComponent;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { ReactFlowState } from '../../types';
|
||||
import { useStore } from '../../hooks/useStore';
|
||||
import { InternalNodeUpdate } from '@xyflow/system';
|
||||
|
||||
const selector = (s: ReactFlowState) => s.updateNodeInternals;
|
||||
|
||||
export function useResizeObserver() {
|
||||
const updateNodeInternals = useStore(selector);
|
||||
const [resizeObserver] = useState(() => {
|
||||
if (typeof ResizeObserver === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ResizeObserver((entries: ResizeObserverEntry[]) => {
|
||||
const updates = new Map<string, InternalNodeUpdate>();
|
||||
entries.forEach((entry: ResizeObserverEntry) => {
|
||||
const id = entry.target.getAttribute('data-id') as string;
|
||||
updates.set(id, {
|
||||
id,
|
||||
nodeElement: entry.target as HTMLDivElement,
|
||||
force: true,
|
||||
});
|
||||
});
|
||||
|
||||
updateNodeInternals(updates);
|
||||
});
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
resizeObserver?.disconnect();
|
||||
};
|
||||
}, [resizeObserver]);
|
||||
|
||||
return resizeObserver;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import type { NodeProps } from '@xyflow/system';
|
||||
|
||||
import DefaultNode from '../../components/Nodes/DefaultNode';
|
||||
import InputNode from '../../components/Nodes/InputNode';
|
||||
import OutputNode from '../../components/Nodes/OutputNode';
|
||||
import GroupNode from '../../components/Nodes/GroupNode';
|
||||
import wrapNode from '../../components/Nodes/wrapNode';
|
||||
import type { NodeTypes, NodeTypesWrapped } from '../../types';
|
||||
|
||||
export type CreateNodeTypes = (nodeTypes: NodeTypes) => NodeTypesWrapped;
|
||||
|
||||
export function createNodeTypes(nodeTypes: NodeTypes): NodeTypesWrapped {
|
||||
const standardTypes: NodeTypesWrapped = {
|
||||
input: wrapNode((nodeTypes.input || InputNode) as ComponentType<NodeProps>),
|
||||
default: wrapNode((nodeTypes.default || DefaultNode) as ComponentType<NodeProps>),
|
||||
output: wrapNode((nodeTypes.output || OutputNode) as ComponentType<NodeProps>),
|
||||
group: wrapNode((nodeTypes.group || GroupNode) as ComponentType<NodeProps>),
|
||||
};
|
||||
|
||||
const wrappedTypes = {} as NodeTypesWrapped;
|
||||
const specialTypes: NodeTypesWrapped = Object.keys(nodeTypes)
|
||||
.filter((k) => !['input', 'default', 'output', 'group'].includes(k))
|
||||
.reduce((res, key) => {
|
||||
res[key] = wrapNode((nodeTypes[key] || DefaultNode) as ComponentType<NodeProps>);
|
||||
|
||||
return res;
|
||||
}, wrappedTypes);
|
||||
|
||||
return {
|
||||
...standardTypes,
|
||||
...specialTypes,
|
||||
};
|
||||
}
|
||||
@@ -2,19 +2,25 @@
|
||||
* The user selection rectangle gets displayed when a user drags the mouse while pressing shift
|
||||
*/
|
||||
|
||||
import { memo, useRef, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react';
|
||||
import {
|
||||
useRef,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import cc from 'classcat';
|
||||
import { getNodesInside, getEventPosition, SelectionMode } from '@xyflow/system';
|
||||
import { getNodesInside, getEventPosition, SelectionMode, type NodeChange, type EdgeChange } from '@xyflow/system';
|
||||
|
||||
import UserSelection from '../../components/UserSelection';
|
||||
import { UserSelection } from '../../components/UserSelection';
|
||||
import { containerStyle } from '../../styles/utils';
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import { getSelectionChanges, getConnectedEdges } from '../../utils';
|
||||
import type { ReactFlowProps, ReactFlowState, NodeChange, EdgeChange } from '../../types';
|
||||
import { getSelectionChanges } from '../../utils';
|
||||
import type { ReactFlowProps, ReactFlowState } from '../../types';
|
||||
|
||||
type PaneProps = {
|
||||
isSelecting: boolean;
|
||||
selectionKeyPressed: boolean;
|
||||
children: ReactNode;
|
||||
} & Partial<
|
||||
Pick<
|
||||
@@ -50,185 +56,208 @@ const selector = (s: ReactFlowState) => ({
|
||||
dragging: s.paneDragging,
|
||||
});
|
||||
|
||||
const Pane = memo(
|
||||
({
|
||||
isSelecting,
|
||||
selectionMode = SelectionMode.Full,
|
||||
panOnDrag,
|
||||
onSelectionStart,
|
||||
onSelectionEnd,
|
||||
onPaneClick,
|
||||
onPaneContextMenu,
|
||||
onPaneScroll,
|
||||
onPaneMouseEnter,
|
||||
onPaneMouseMove,
|
||||
onPaneMouseLeave,
|
||||
children,
|
||||
}: PaneProps) => {
|
||||
const container = useRef<HTMLDivElement | null>(null);
|
||||
const store = useStoreApi();
|
||||
const prevSelectedNodesCount = useRef<number>(0);
|
||||
const prevSelectedEdgesCount = useRef<number>(0);
|
||||
const containerBounds = useRef<DOMRect>();
|
||||
const { userSelectionActive, elementsSelectable, dragging } = useStore(selector, shallow);
|
||||
export function Pane({
|
||||
isSelecting,
|
||||
selectionKeyPressed,
|
||||
selectionMode = SelectionMode.Full,
|
||||
panOnDrag,
|
||||
onSelectionStart,
|
||||
onSelectionEnd,
|
||||
onPaneClick,
|
||||
onPaneContextMenu,
|
||||
onPaneScroll,
|
||||
onPaneMouseEnter,
|
||||
onPaneMouseMove,
|
||||
onPaneMouseLeave,
|
||||
children,
|
||||
}: PaneProps) {
|
||||
const container = useRef<HTMLDivElement | null>(null);
|
||||
const store = useStoreApi();
|
||||
const prevSelectedNodesCount = useRef<number>(0);
|
||||
const prevSelectedEdgesCount = useRef<number>(0);
|
||||
const containerBounds = useRef<DOMRect>();
|
||||
const edgeIdLookup = useRef<Map<string, Set<string>>>(new Map());
|
||||
|
||||
const resetUserSelection = () => {
|
||||
store.setState({ userSelectionActive: false, userSelectionRect: null });
|
||||
const { userSelectionActive, elementsSelectable, dragging } = useStore(selector, shallow);
|
||||
const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive);
|
||||
|
||||
prevSelectedNodesCount.current = 0;
|
||||
prevSelectedEdgesCount.current = 0;
|
||||
// Used to prevent click events when the user lets go of the selectionKey during a selection
|
||||
const selectionInProgress = useRef<boolean>(false);
|
||||
|
||||
const resetUserSelection = () => {
|
||||
store.setState({ userSelectionActive: false, userSelectionRect: null });
|
||||
|
||||
prevSelectedNodesCount.current = 0;
|
||||
prevSelectedEdgesCount.current = 0;
|
||||
};
|
||||
|
||||
const onClick = (event: ReactMouseEvent) => {
|
||||
// We prevent click events when the user let go of the selectionKey during a selection
|
||||
if (selectionInProgress.current) {
|
||||
selectionInProgress.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
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 onPointerDown = (event: ReactPointerEvent): void => {
|
||||
const { resetSelectedElements, domNode, edgeLookup } = store.getState();
|
||||
containerBounds.current = domNode?.getBoundingClientRect();
|
||||
container.current?.setPointerCapture(event.pointerId);
|
||||
|
||||
if (
|
||||
!elementsSelectable ||
|
||||
!isSelecting ||
|
||||
event.button !== 0 ||
|
||||
event.target !== container.current ||
|
||||
!containerBounds.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
edgeIdLookup.current = new Map();
|
||||
|
||||
for (const [id, edge] of edgeLookup) {
|
||||
edgeIdLookup.current.set(edge.source, edgeIdLookup.current.get(edge.source)?.add(id) || new Set([id]));
|
||||
edgeIdLookup.current.set(edge.target, edgeIdLookup.current.get(edge.target)?.add(id) || new Set([id]));
|
||||
}
|
||||
|
||||
const { x, y } = getEventPosition(event.nativeEvent, containerBounds.current);
|
||||
|
||||
resetSelectedElements();
|
||||
|
||||
store.setState({
|
||||
userSelectionRect: {
|
||||
width: 0,
|
||||
height: 0,
|
||||
startX: x,
|
||||
startY: y,
|
||||
x,
|
||||
y,
|
||||
},
|
||||
});
|
||||
|
||||
onSelectionStart?.(event);
|
||||
};
|
||||
|
||||
const onPointerMove = (event: ReactPointerEvent): void => {
|
||||
const { userSelectionRect, edgeLookup, transform, nodeLookup, triggerNodeChanges, triggerEdgeChanges } =
|
||||
store.getState();
|
||||
|
||||
if (!containerBounds.current || !userSelectionRect) {
|
||||
return;
|
||||
}
|
||||
|
||||
selectionInProgress.current = true;
|
||||
|
||||
const { x: mouseX, y: mouseY } = getEventPosition(event.nativeEvent, containerBounds.current);
|
||||
const { startX, startY } = userSelectionRect;
|
||||
|
||||
const nextUserSelectRect = {
|
||||
startX,
|
||||
startY,
|
||||
x: mouseX < startX ? mouseX : startX,
|
||||
y: mouseY < startY ? mouseY : startY,
|
||||
width: Math.abs(mouseX - startX),
|
||||
height: Math.abs(mouseY - startY),
|
||||
};
|
||||
|
||||
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 } = getEventPosition(event.nativeEvent, 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, edges, transform, nodeOrigin, nodes, onNodesChange, onEdgesChange } = store.getState();
|
||||
if (!isSelecting || !containerBounds.current || !userSelectionRect) {
|
||||
return;
|
||||
}
|
||||
|
||||
store.setState({ userSelectionActive: true, nodesSelectionActive: false });
|
||||
|
||||
const mousePos = getEventPosition(event.nativeEvent, 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 selectedNodes = getNodesInside(
|
||||
nodes,
|
||||
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) => {
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
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 (
|
||||
<div
|
||||
className={cc(['react-flow__pane', { dragging, selection: isSelecting }])}
|
||||
onClick={hasActiveSelection ? undefined : wrapHandler(onClick, container)}
|
||||
onContextMenu={wrapHandler(onContextMenu, container)}
|
||||
onWheel={wrapHandler(onWheel, container)}
|
||||
onMouseEnter={hasActiveSelection ? undefined : onPaneMouseEnter}
|
||||
onMouseDown={hasActiveSelection ? onMouseDown : undefined}
|
||||
onMouseMove={hasActiveSelection ? onMouseMove : onPaneMouseMove}
|
||||
onMouseUp={hasActiveSelection ? onMouseUp : undefined}
|
||||
onMouseLeave={hasActiveSelection ? onMouseLeave : onPaneMouseLeave}
|
||||
ref={container}
|
||||
style={containerStyle}
|
||||
>
|
||||
{children}
|
||||
<UserSelection />
|
||||
</div>
|
||||
const selectedNodes = getNodesInside(
|
||||
nodeLookup,
|
||||
nextUserSelectRect,
|
||||
transform,
|
||||
selectionMode === SelectionMode.Partial,
|
||||
true
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
Pane.displayName = 'Pane';
|
||||
const selectedEdgeIds = new Set<string>();
|
||||
const selectedNodeIds = new Set<string>();
|
||||
|
||||
export default Pane;
|
||||
for (const selectedNode of selectedNodes) {
|
||||
selectedNodeIds.add(selectedNode.id);
|
||||
|
||||
const edgeIds = edgeIdLookup.current.get(selectedNode.id);
|
||||
|
||||
if (edgeIds) {
|
||||
for (const edgeId of edgeIds) {
|
||||
selectedEdgeIds.add(edgeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (prevSelectedNodesCount.current !== selectedNodeIds.size) {
|
||||
prevSelectedNodesCount.current = selectedNodeIds.size;
|
||||
const changes = getSelectionChanges(nodeLookup, selectedNodeIds, true) as NodeChange[];
|
||||
triggerNodeChanges(changes);
|
||||
}
|
||||
|
||||
if (prevSelectedEdgesCount.current !== selectedEdgeIds.size) {
|
||||
prevSelectedEdgesCount.current = selectedEdgeIds.size;
|
||||
const changes = getSelectionChanges(edgeLookup, selectedEdgeIds) as EdgeChange[];
|
||||
triggerEdgeChanges(changes);
|
||||
}
|
||||
|
||||
store.setState({
|
||||
userSelectionRect: nextUserSelectRect,
|
||||
userSelectionActive: true,
|
||||
nodesSelectionActive: false,
|
||||
});
|
||||
};
|
||||
|
||||
const onPointerUp = (event: ReactPointerEvent) => {
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
container.current?.releasePointerCapture(event.pointerId);
|
||||
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);
|
||||
|
||||
// If the user kept holding the selectionKey during the selection,
|
||||
// we need to reset the selectionInProgress, so the next click event is not prevented
|
||||
if (selectionKeyPressed) {
|
||||
selectionInProgress.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cc(['react-flow__pane', { draggable: panOnDrag, dragging, selection: isSelecting }])}
|
||||
onClick={hasActiveSelection ? undefined : wrapHandler(onClick, container)}
|
||||
onContextMenu={wrapHandler(onContextMenu, container)}
|
||||
onWheel={wrapHandler(onWheel, container)}
|
||||
onPointerEnter={hasActiveSelection ? undefined : onPaneMouseEnter}
|
||||
onPointerDown={hasActiveSelection ? onPointerDown : onPaneMouseMove}
|
||||
onPointerMove={hasActiveSelection ? onPointerMove : onPaneMouseMove}
|
||||
onPointerUp={hasActiveSelection ? onPointerUp : undefined}
|
||||
onPointerLeave={onPaneMouseLeave}
|
||||
ref={container}
|
||||
style={containerStyle}
|
||||
>
|
||||
{children}
|
||||
<UserSelection />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
import { useContext, type ReactNode } from 'react';
|
||||
|
||||
import StoreContext from '../../contexts/RFStoreContext';
|
||||
import ReactFlowProvider from '../../components/ReactFlowProvider';
|
||||
import StoreContext from '../../contexts/StoreContext';
|
||||
import { ReactFlowProvider } from '../../components/ReactFlowProvider';
|
||||
import type { Node, Edge } from '../../types';
|
||||
import { NodeOrigin } from '@xyflow/system';
|
||||
|
||||
function Wrapper({
|
||||
export function Wrapper({
|
||||
children,
|
||||
nodes,
|
||||
edges,
|
||||
defaultNodes,
|
||||
defaultEdges,
|
||||
width,
|
||||
height,
|
||||
fitView,
|
||||
nodeOrigin,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
nodes?: Node[];
|
||||
edges?: Edge[];
|
||||
defaultNodes?: Node[];
|
||||
defaultEdges?: Edge[];
|
||||
width?: number;
|
||||
height?: number;
|
||||
fitView?: boolean;
|
||||
nodeOrigin?: NodeOrigin;
|
||||
}) {
|
||||
const isWrapped = useContext(StoreContext);
|
||||
|
||||
@@ -31,15 +38,14 @@ function Wrapper({
|
||||
<ReactFlowProvider
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
defaultNodes={defaultNodes}
|
||||
defaultEdges={defaultEdges}
|
||||
initialWidth={width}
|
||||
initialHeight={height}
|
||||
fitView={fitView}
|
||||
nodeOrigin={nodeOrigin}
|
||||
>
|
||||
{children}
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
|
||||
Wrapper.displayName = 'ReactFlowWrapper';
|
||||
|
||||
export default Wrapper;
|
||||
|
||||
@@ -1,47 +1,17 @@
|
||||
import { forwardRef, type CSSProperties } from 'react';
|
||||
import { ForwardedRef, type CSSProperties } from 'react';
|
||||
import cc from 'classcat';
|
||||
import {
|
||||
ConnectionLineType,
|
||||
ConnectionMode,
|
||||
PanOnScrollMode,
|
||||
SelectionMode,
|
||||
infiniteExtent,
|
||||
type NodeOrigin,
|
||||
type Viewport,
|
||||
isMacOs,
|
||||
} from '@xyflow/system';
|
||||
import { ConnectionLineType, PanOnScrollMode, SelectionMode, infiniteExtent, isMacOs } from '@xyflow/system';
|
||||
|
||||
import Attribution from '../../components/Attribution';
|
||||
import { BezierEdge, SmoothStepEdge, StepEdge, StraightEdge, SimpleBezierEdge } from '../../components/Edges';
|
||||
import DefaultNode from '../../components/Nodes/DefaultNode';
|
||||
import InputNode from '../../components/Nodes/InputNode';
|
||||
import OutputNode from '../../components/Nodes/OutputNode';
|
||||
import GroupNode from '../../components/Nodes/GroupNode';
|
||||
import SelectionListener from '../../components/SelectionListener';
|
||||
import StoreUpdater from '../../components/StoreUpdater';
|
||||
import A11yDescriptions from '../../components/A11yDescriptions';
|
||||
import GraphView from '../GraphView';
|
||||
import Wrapper from './Wrapper';
|
||||
import type { EdgeTypes, NodeTypes, ReactFlowProps, ReactFlowRefType } from '../../types';
|
||||
|
||||
const defaultNodeTypes: NodeTypes = {
|
||||
input: InputNode,
|
||||
default: DefaultNode,
|
||||
output: OutputNode,
|
||||
group: GroupNode,
|
||||
};
|
||||
|
||||
const defaultEdgeTypes: EdgeTypes = {
|
||||
default: BezierEdge,
|
||||
straight: StraightEdge,
|
||||
step: StepEdge,
|
||||
smoothstep: SmoothStepEdge,
|
||||
simplebezier: SimpleBezierEdge,
|
||||
};
|
||||
|
||||
const initNodeOrigin: NodeOrigin = [0, 0];
|
||||
const initSnapGrid: [number, number] = [15, 15];
|
||||
const initDefaultViewport: Viewport = { x: 0, y: 0, zoom: 1 };
|
||||
import { A11yDescriptions } from '../../components/A11yDescriptions';
|
||||
import { Attribution } from '../../components/Attribution';
|
||||
import { SelectionListener } from '../../components/SelectionListener';
|
||||
import { StoreUpdater } from '../../components/StoreUpdater';
|
||||
import { useColorModeClass } from '../../hooks/useColorModeClass';
|
||||
import { GraphView } from '../GraphView';
|
||||
import { Wrapper } from './Wrapper';
|
||||
import type { Edge, Node, ReactFlowProps } from '../../types';
|
||||
import { defaultViewport as initViewport, defaultNodeOrigin } from './init-values';
|
||||
import { fixedForwardRef } from '../../utils/general';
|
||||
|
||||
const wrapperStyle: CSSProperties = {
|
||||
width: '100%',
|
||||
@@ -51,266 +21,271 @@ const wrapperStyle: CSSProperties = {
|
||||
zIndex: 0,
|
||||
};
|
||||
|
||||
const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
||||
(
|
||||
{
|
||||
nodes,
|
||||
edges,
|
||||
defaultNodes,
|
||||
defaultEdges,
|
||||
className,
|
||||
nodeTypes = defaultNodeTypes,
|
||||
edgeTypes = defaultEdgeTypes,
|
||||
onNodeClick,
|
||||
onEdgeClick,
|
||||
onInit,
|
||||
onMove,
|
||||
onMoveStart,
|
||||
onMoveEnd,
|
||||
onConnect,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
onClickConnectStart,
|
||||
onClickConnectEnd,
|
||||
onNodeMouseEnter,
|
||||
onNodeMouseMove,
|
||||
onNodeMouseLeave,
|
||||
onNodeContextMenu,
|
||||
onNodeDoubleClick,
|
||||
onNodeDragStart,
|
||||
onNodeDrag,
|
||||
onNodeDragStop,
|
||||
onNodesDelete,
|
||||
onEdgesDelete,
|
||||
onSelectionChange,
|
||||
onSelectionDragStart,
|
||||
onSelectionDrag,
|
||||
onSelectionDragStop,
|
||||
onSelectionContextMenu,
|
||||
onSelectionStart,
|
||||
onSelectionEnd,
|
||||
connectionMode = ConnectionMode.Strict,
|
||||
connectionLineType = ConnectionLineType.Bezier,
|
||||
connectionLineStyle,
|
||||
connectionLineComponent,
|
||||
connectionLineContainerStyle,
|
||||
deleteKeyCode = 'Backspace',
|
||||
selectionKeyCode = 'Shift',
|
||||
selectionOnDrag = false,
|
||||
selectionMode = SelectionMode.Full,
|
||||
panActivationKeyCode = 'Space',
|
||||
multiSelectionKeyCode = isMacOs() ? 'Meta' : 'Control',
|
||||
zoomActivationKeyCode = isMacOs() ? 'Meta' : 'Control',
|
||||
snapToGrid = false,
|
||||
snapGrid = initSnapGrid,
|
||||
onlyRenderVisibleElements = false,
|
||||
selectNodesOnDrag = true,
|
||||
nodesDraggable,
|
||||
nodesConnectable,
|
||||
nodesFocusable,
|
||||
nodeOrigin = initNodeOrigin,
|
||||
edgesFocusable,
|
||||
edgesUpdatable,
|
||||
elementsSelectable = true,
|
||||
defaultViewport = initDefaultViewport,
|
||||
minZoom = 0.5,
|
||||
maxZoom = 2,
|
||||
translateExtent = infiniteExtent,
|
||||
preventScrolling = true,
|
||||
nodeExtent,
|
||||
defaultMarkerColor = '#b1b1b7',
|
||||
zoomOnScroll = true,
|
||||
zoomOnPinch = true,
|
||||
panOnScroll = false,
|
||||
panOnScrollSpeed = 0.5,
|
||||
panOnScrollMode = PanOnScrollMode.Free,
|
||||
zoomOnDoubleClick = true,
|
||||
panOnDrag = true,
|
||||
onPaneClick,
|
||||
onPaneMouseEnter,
|
||||
onPaneMouseMove,
|
||||
onPaneMouseLeave,
|
||||
onPaneScroll,
|
||||
onPaneContextMenu,
|
||||
children,
|
||||
onEdgeUpdate,
|
||||
onEdgeContextMenu,
|
||||
onEdgeDoubleClick,
|
||||
onEdgeMouseEnter,
|
||||
onEdgeMouseMove,
|
||||
onEdgeMouseLeave,
|
||||
onEdgeUpdateStart,
|
||||
onEdgeUpdateEnd,
|
||||
edgeUpdaterRadius = 10,
|
||||
onNodesChange,
|
||||
onEdgesChange,
|
||||
noDragClassName = 'nodrag',
|
||||
noWheelClassName = 'nowheel',
|
||||
noPanClassName = 'nopan',
|
||||
fitView = false,
|
||||
fitViewOptions,
|
||||
connectOnClick = true,
|
||||
attributionPosition,
|
||||
proOptions,
|
||||
defaultEdgeOptions,
|
||||
elevateNodesOnSelect = true,
|
||||
elevateEdgesOnSelect = false,
|
||||
disableKeyboardA11y = false,
|
||||
autoPanOnConnect = true,
|
||||
autoPanOnNodeDrag = true,
|
||||
connectionRadius = 20,
|
||||
isValidConnection,
|
||||
onError,
|
||||
style,
|
||||
id,
|
||||
nodeDragThreshold,
|
||||
viewport,
|
||||
onViewportChange,
|
||||
width,
|
||||
height,
|
||||
...rest
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const rfId = id || '1';
|
||||
function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
|
||||
{
|
||||
nodes,
|
||||
edges,
|
||||
defaultNodes,
|
||||
defaultEdges,
|
||||
className,
|
||||
nodeTypes,
|
||||
edgeTypes,
|
||||
onNodeClick,
|
||||
onEdgeClick,
|
||||
onInit,
|
||||
onMove,
|
||||
onMoveStart,
|
||||
onMoveEnd,
|
||||
onConnect,
|
||||
onConnectStart,
|
||||
onConnectEnd,
|
||||
onClickConnectStart,
|
||||
onClickConnectEnd,
|
||||
onNodeMouseEnter,
|
||||
onNodeMouseMove,
|
||||
onNodeMouseLeave,
|
||||
onNodeContextMenu,
|
||||
onNodeDoubleClick,
|
||||
onNodeDragStart,
|
||||
onNodeDrag,
|
||||
onNodeDragStop,
|
||||
onNodesDelete,
|
||||
onEdgesDelete,
|
||||
onDelete,
|
||||
onSelectionChange,
|
||||
onSelectionDragStart,
|
||||
onSelectionDrag,
|
||||
onSelectionDragStop,
|
||||
onSelectionContextMenu,
|
||||
onSelectionStart,
|
||||
onSelectionEnd,
|
||||
onBeforeDelete,
|
||||
connectionMode,
|
||||
connectionLineType = ConnectionLineType.Bezier,
|
||||
connectionLineStyle,
|
||||
connectionLineComponent,
|
||||
connectionLineContainerStyle,
|
||||
deleteKeyCode = 'Backspace',
|
||||
selectionKeyCode = 'Shift',
|
||||
selectionOnDrag = false,
|
||||
selectionMode = SelectionMode.Full,
|
||||
panActivationKeyCode = 'Space',
|
||||
multiSelectionKeyCode = isMacOs() ? 'Meta' : 'Control',
|
||||
zoomActivationKeyCode = isMacOs() ? 'Meta' : 'Control',
|
||||
snapToGrid,
|
||||
snapGrid,
|
||||
onlyRenderVisibleElements = false,
|
||||
selectNodesOnDrag,
|
||||
nodesDraggable,
|
||||
nodesConnectable,
|
||||
nodesFocusable,
|
||||
nodeOrigin = defaultNodeOrigin,
|
||||
edgesFocusable,
|
||||
edgesReconnectable,
|
||||
elementsSelectable = true,
|
||||
defaultViewport = initViewport,
|
||||
minZoom = 0.5,
|
||||
maxZoom = 2,
|
||||
translateExtent = infiniteExtent,
|
||||
preventScrolling = true,
|
||||
nodeExtent,
|
||||
defaultMarkerColor = '#b1b1b7',
|
||||
zoomOnScroll = true,
|
||||
zoomOnPinch = true,
|
||||
panOnScroll = false,
|
||||
panOnScrollSpeed = 0.5,
|
||||
panOnScrollMode = PanOnScrollMode.Free,
|
||||
zoomOnDoubleClick = true,
|
||||
panOnDrag = true,
|
||||
onPaneClick,
|
||||
onPaneMouseEnter,
|
||||
onPaneMouseMove,
|
||||
onPaneMouseLeave,
|
||||
onPaneScroll,
|
||||
onPaneContextMenu,
|
||||
children,
|
||||
onReconnect,
|
||||
onReconnectStart,
|
||||
onReconnectEnd,
|
||||
onEdgeContextMenu,
|
||||
onEdgeDoubleClick,
|
||||
onEdgeMouseEnter,
|
||||
onEdgeMouseMove,
|
||||
onEdgeMouseLeave,
|
||||
reconnectRadius = 10,
|
||||
onNodesChange,
|
||||
onEdgesChange,
|
||||
noDragClassName = 'nodrag',
|
||||
noWheelClassName = 'nowheel',
|
||||
noPanClassName = 'nopan',
|
||||
fitView,
|
||||
fitViewOptions,
|
||||
connectOnClick,
|
||||
attributionPosition,
|
||||
proOptions,
|
||||
defaultEdgeOptions,
|
||||
elevateNodesOnSelect,
|
||||
elevateEdgesOnSelect,
|
||||
disableKeyboardA11y = false,
|
||||
autoPanOnConnect,
|
||||
autoPanOnNodeDrag,
|
||||
autoPanSpeed,
|
||||
connectionRadius,
|
||||
isValidConnection,
|
||||
onError,
|
||||
style,
|
||||
id,
|
||||
nodeDragThreshold,
|
||||
viewport,
|
||||
onViewportChange,
|
||||
width,
|
||||
height,
|
||||
colorMode = 'light',
|
||||
debug,
|
||||
...rest
|
||||
}: ReactFlowProps<NodeType, EdgeType>,
|
||||
ref: ForwardedRef<HTMLDivElement>
|
||||
) {
|
||||
const rfId = id || '1';
|
||||
const colorModeClassName = useColorModeClass(colorMode);
|
||||
|
||||
return (
|
||||
<div
|
||||
{...rest}
|
||||
style={{ ...style, ...wrapperStyle }}
|
||||
ref={ref}
|
||||
className={cc(['react-flow', className])}
|
||||
data-testid="rf__wrapper"
|
||||
id={id}
|
||||
>
|
||||
<Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}>
|
||||
<GraphView
|
||||
onInit={onInit}
|
||||
onNodeClick={onNodeClick}
|
||||
onEdgeClick={onEdgeClick}
|
||||
onNodeMouseEnter={onNodeMouseEnter}
|
||||
onNodeMouseMove={onNodeMouseMove}
|
||||
onNodeMouseLeave={onNodeMouseLeave}
|
||||
onNodeContextMenu={onNodeContextMenu}
|
||||
onNodeDoubleClick={onNodeDoubleClick}
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
connectionLineType={connectionLineType}
|
||||
connectionLineStyle={connectionLineStyle}
|
||||
connectionLineComponent={connectionLineComponent}
|
||||
connectionLineContainerStyle={connectionLineContainerStyle}
|
||||
selectionKeyCode={selectionKeyCode}
|
||||
selectionOnDrag={selectionOnDrag}
|
||||
selectionMode={selectionMode}
|
||||
deleteKeyCode={deleteKeyCode}
|
||||
multiSelectionKeyCode={multiSelectionKeyCode}
|
||||
panActivationKeyCode={panActivationKeyCode}
|
||||
zoomActivationKeyCode={zoomActivationKeyCode}
|
||||
onlyRenderVisibleElements={onlyRenderVisibleElements}
|
||||
defaultViewport={defaultViewport}
|
||||
translateExtent={translateExtent}
|
||||
minZoom={minZoom}
|
||||
maxZoom={maxZoom}
|
||||
preventScrolling={preventScrolling}
|
||||
zoomOnScroll={zoomOnScroll}
|
||||
zoomOnPinch={zoomOnPinch}
|
||||
zoomOnDoubleClick={zoomOnDoubleClick}
|
||||
panOnScroll={panOnScroll}
|
||||
panOnScrollSpeed={panOnScrollSpeed}
|
||||
panOnScrollMode={panOnScrollMode}
|
||||
panOnDrag={panOnDrag}
|
||||
onPaneClick={onPaneClick}
|
||||
onPaneMouseEnter={onPaneMouseEnter}
|
||||
onPaneMouseMove={onPaneMouseMove}
|
||||
onPaneMouseLeave={onPaneMouseLeave}
|
||||
onPaneScroll={onPaneScroll}
|
||||
onPaneContextMenu={onPaneContextMenu}
|
||||
onSelectionContextMenu={onSelectionContextMenu}
|
||||
onSelectionStart={onSelectionStart}
|
||||
onSelectionEnd={onSelectionEnd}
|
||||
onEdgeUpdate={onEdgeUpdate}
|
||||
onEdgeContextMenu={onEdgeContextMenu}
|
||||
onEdgeDoubleClick={onEdgeDoubleClick}
|
||||
onEdgeMouseEnter={onEdgeMouseEnter}
|
||||
onEdgeMouseMove={onEdgeMouseMove}
|
||||
onEdgeMouseLeave={onEdgeMouseLeave}
|
||||
onEdgeUpdateStart={onEdgeUpdateStart}
|
||||
onEdgeUpdateEnd={onEdgeUpdateEnd}
|
||||
edgeUpdaterRadius={edgeUpdaterRadius}
|
||||
defaultMarkerColor={defaultMarkerColor}
|
||||
noDragClassName={noDragClassName}
|
||||
noWheelClassName={noWheelClassName}
|
||||
noPanClassName={noPanClassName}
|
||||
elevateEdgesOnSelect={elevateEdgesOnSelect}
|
||||
rfId={rfId}
|
||||
disableKeyboardA11y={disableKeyboardA11y}
|
||||
nodeOrigin={nodeOrigin}
|
||||
nodeExtent={nodeExtent}
|
||||
viewport={viewport}
|
||||
onViewportChange={onViewportChange}
|
||||
/>
|
||||
<StoreUpdater
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
defaultNodes={defaultNodes}
|
||||
defaultEdges={defaultEdges}
|
||||
onConnect={onConnect}
|
||||
onConnectStart={onConnectStart}
|
||||
onConnectEnd={onConnectEnd}
|
||||
onClickConnectStart={onClickConnectStart}
|
||||
onClickConnectEnd={onClickConnectEnd}
|
||||
nodesDraggable={nodesDraggable}
|
||||
nodesConnectable={nodesConnectable}
|
||||
nodesFocusable={nodesFocusable}
|
||||
edgesFocusable={edgesFocusable}
|
||||
edgesUpdatable={edgesUpdatable}
|
||||
elementsSelectable={elementsSelectable}
|
||||
elevateNodesOnSelect={elevateNodesOnSelect}
|
||||
minZoom={minZoom}
|
||||
maxZoom={maxZoom}
|
||||
nodeExtent={nodeExtent}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
snapToGrid={snapToGrid}
|
||||
snapGrid={snapGrid}
|
||||
connectionMode={connectionMode}
|
||||
translateExtent={translateExtent}
|
||||
connectOnClick={connectOnClick}
|
||||
defaultEdgeOptions={defaultEdgeOptions}
|
||||
fitView={fitView}
|
||||
fitViewOptions={fitViewOptions}
|
||||
onNodesDelete={onNodesDelete}
|
||||
onEdgesDelete={onEdgesDelete}
|
||||
onNodeDragStart={onNodeDragStart}
|
||||
onNodeDrag={onNodeDrag}
|
||||
onNodeDragStop={onNodeDragStop}
|
||||
onSelectionDrag={onSelectionDrag}
|
||||
onSelectionDragStart={onSelectionDragStart}
|
||||
onSelectionDragStop={onSelectionDragStop}
|
||||
onMove={onMove}
|
||||
onMoveStart={onMoveStart}
|
||||
onMoveEnd={onMoveEnd}
|
||||
noPanClassName={noPanClassName}
|
||||
nodeOrigin={nodeOrigin}
|
||||
rfId={rfId}
|
||||
autoPanOnConnect={autoPanOnConnect}
|
||||
autoPanOnNodeDrag={autoPanOnNodeDrag}
|
||||
onError={onError}
|
||||
connectionRadius={connectionRadius}
|
||||
isValidConnection={isValidConnection}
|
||||
selectNodesOnDrag={selectNodesOnDrag}
|
||||
nodeDragThreshold={nodeDragThreshold}
|
||||
/>
|
||||
<SelectionListener onSelectionChange={onSelectionChange} />
|
||||
{children}
|
||||
<Attribution proOptions={proOptions} position={attributionPosition} />
|
||||
<A11yDescriptions rfId={rfId} disableKeyboardA11y={disableKeyboardA11y} />
|
||||
</Wrapper>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
return (
|
||||
<div
|
||||
{...rest}
|
||||
style={{ ...style, ...wrapperStyle }}
|
||||
ref={ref}
|
||||
className={cc(['react-flow', className, colorModeClassName])}
|
||||
data-testid="rf__wrapper"
|
||||
id={id}
|
||||
>
|
||||
<Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView} nodeOrigin={nodeOrigin}>
|
||||
<GraphView<NodeType, EdgeType>
|
||||
onInit={onInit}
|
||||
onNodeClick={onNodeClick}
|
||||
onEdgeClick={onEdgeClick}
|
||||
onNodeMouseEnter={onNodeMouseEnter}
|
||||
onNodeMouseMove={onNodeMouseMove}
|
||||
onNodeMouseLeave={onNodeMouseLeave}
|
||||
onNodeContextMenu={onNodeContextMenu}
|
||||
onNodeDoubleClick={onNodeDoubleClick}
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
connectionLineType={connectionLineType}
|
||||
connectionLineStyle={connectionLineStyle}
|
||||
connectionLineComponent={connectionLineComponent}
|
||||
connectionLineContainerStyle={connectionLineContainerStyle}
|
||||
selectionKeyCode={selectionKeyCode}
|
||||
selectionOnDrag={selectionOnDrag}
|
||||
selectionMode={selectionMode}
|
||||
deleteKeyCode={deleteKeyCode}
|
||||
multiSelectionKeyCode={multiSelectionKeyCode}
|
||||
panActivationKeyCode={panActivationKeyCode}
|
||||
zoomActivationKeyCode={zoomActivationKeyCode}
|
||||
onlyRenderVisibleElements={onlyRenderVisibleElements}
|
||||
defaultViewport={defaultViewport}
|
||||
translateExtent={translateExtent}
|
||||
minZoom={minZoom}
|
||||
maxZoom={maxZoom}
|
||||
preventScrolling={preventScrolling}
|
||||
zoomOnScroll={zoomOnScroll}
|
||||
zoomOnPinch={zoomOnPinch}
|
||||
zoomOnDoubleClick={zoomOnDoubleClick}
|
||||
panOnScroll={panOnScroll}
|
||||
panOnScrollSpeed={panOnScrollSpeed}
|
||||
panOnScrollMode={panOnScrollMode}
|
||||
panOnDrag={panOnDrag}
|
||||
onPaneClick={onPaneClick}
|
||||
onPaneMouseEnter={onPaneMouseEnter}
|
||||
onPaneMouseMove={onPaneMouseMove}
|
||||
onPaneMouseLeave={onPaneMouseLeave}
|
||||
onPaneScroll={onPaneScroll}
|
||||
onPaneContextMenu={onPaneContextMenu}
|
||||
onSelectionContextMenu={onSelectionContextMenu}
|
||||
onSelectionStart={onSelectionStart}
|
||||
onSelectionEnd={onSelectionEnd}
|
||||
onReconnect={onReconnect}
|
||||
onReconnectStart={onReconnectStart}
|
||||
onReconnectEnd={onReconnectEnd}
|
||||
onEdgeContextMenu={onEdgeContextMenu}
|
||||
onEdgeDoubleClick={onEdgeDoubleClick}
|
||||
onEdgeMouseEnter={onEdgeMouseEnter}
|
||||
onEdgeMouseMove={onEdgeMouseMove}
|
||||
onEdgeMouseLeave={onEdgeMouseLeave}
|
||||
reconnectRadius={reconnectRadius}
|
||||
defaultMarkerColor={defaultMarkerColor}
|
||||
noDragClassName={noDragClassName}
|
||||
noWheelClassName={noWheelClassName}
|
||||
noPanClassName={noPanClassName}
|
||||
rfId={rfId}
|
||||
disableKeyboardA11y={disableKeyboardA11y}
|
||||
nodeExtent={nodeExtent}
|
||||
viewport={viewport}
|
||||
onViewportChange={onViewportChange}
|
||||
/>
|
||||
<StoreUpdater<NodeType, EdgeType>
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
defaultNodes={defaultNodes}
|
||||
defaultEdges={defaultEdges}
|
||||
onConnect={onConnect}
|
||||
onConnectStart={onConnectStart}
|
||||
onConnectEnd={onConnectEnd}
|
||||
onClickConnectStart={onClickConnectStart}
|
||||
onClickConnectEnd={onClickConnectEnd}
|
||||
nodesDraggable={nodesDraggable}
|
||||
nodesConnectable={nodesConnectable}
|
||||
nodesFocusable={nodesFocusable}
|
||||
edgesFocusable={edgesFocusable}
|
||||
edgesReconnectable={edgesReconnectable}
|
||||
elementsSelectable={elementsSelectable}
|
||||
elevateNodesOnSelect={elevateNodesOnSelect}
|
||||
elevateEdgesOnSelect={elevateEdgesOnSelect}
|
||||
minZoom={minZoom}
|
||||
maxZoom={maxZoom}
|
||||
nodeExtent={nodeExtent}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
snapToGrid={snapToGrid}
|
||||
snapGrid={snapGrid}
|
||||
connectionMode={connectionMode}
|
||||
translateExtent={translateExtent}
|
||||
connectOnClick={connectOnClick}
|
||||
defaultEdgeOptions={defaultEdgeOptions}
|
||||
fitView={fitView}
|
||||
fitViewOptions={fitViewOptions}
|
||||
onNodesDelete={onNodesDelete}
|
||||
onEdgesDelete={onEdgesDelete}
|
||||
onDelete={onDelete}
|
||||
onNodeDragStart={onNodeDragStart}
|
||||
onNodeDrag={onNodeDrag}
|
||||
onNodeDragStop={onNodeDragStop}
|
||||
onSelectionDrag={onSelectionDrag}
|
||||
onSelectionDragStart={onSelectionDragStart}
|
||||
onSelectionDragStop={onSelectionDragStop}
|
||||
onMove={onMove}
|
||||
onMoveStart={onMoveStart}
|
||||
onMoveEnd={onMoveEnd}
|
||||
noPanClassName={noPanClassName}
|
||||
nodeOrigin={nodeOrigin}
|
||||
rfId={rfId}
|
||||
autoPanOnConnect={autoPanOnConnect}
|
||||
autoPanOnNodeDrag={autoPanOnNodeDrag}
|
||||
autoPanSpeed={autoPanSpeed}
|
||||
onError={onError}
|
||||
connectionRadius={connectionRadius}
|
||||
isValidConnection={isValidConnection}
|
||||
selectNodesOnDrag={selectNodesOnDrag}
|
||||
nodeDragThreshold={nodeDragThreshold}
|
||||
onBeforeDelete={onBeforeDelete}
|
||||
debug={debug}
|
||||
/>
|
||||
<SelectionListener onSelectionChange={onSelectionChange} />
|
||||
{children}
|
||||
<Attribution proOptions={proOptions} position={attributionPosition} />
|
||||
<A11yDescriptions rfId={rfId} disableKeyboardA11y={disableKeyboardA11y} />
|
||||
</Wrapper>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
ReactFlow.displayName = 'ReactFlow';
|
||||
|
||||
export default ReactFlow;
|
||||
export default fixedForwardRef(ReactFlow);
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { type NodeOrigin, Viewport } from '@xyflow/system';
|
||||
|
||||
export const defaultNodeOrigin: NodeOrigin = [0, 0];
|
||||
export const defaultViewport: Viewport = { x: 0, y: 0, zoom: 1 };
|
||||
@@ -9,7 +9,7 @@ type ViewportProps = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export default function Viewport({ children }: ViewportProps) {
|
||||
export function Viewport({ children }: ViewportProps) {
|
||||
const transform = useStore(selector);
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,8 +3,8 @@ import { useEffect, useRef } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { XYPanZoom, PanOnScrollMode, type Transform, type PanZoomInstance } from '@xyflow/system';
|
||||
|
||||
import useKeyPress from '../../hooks/useKeyPress';
|
||||
import useResizeHandler from '../../hooks/useResizeHandler';
|
||||
import { useKeyPress } from '../../hooks/useKeyPress';
|
||||
import { useResizeHandler } from '../../hooks/useResizeHandler';
|
||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||
import { containerStyle } from '../../styles/utils';
|
||||
import type { FlowRendererProps } from '../FlowRenderer';
|
||||
@@ -27,7 +27,7 @@ const selector = (s: ReactFlowState) => ({
|
||||
lib: s.lib,
|
||||
});
|
||||
|
||||
const ZoomPane = ({
|
||||
export function ZoomPane({
|
||||
onPaneContextMenu,
|
||||
zoomOnScroll = true,
|
||||
zoomOnPinch = true,
|
||||
@@ -47,7 +47,7 @@ const ZoomPane = ({
|
||||
noPanClassName,
|
||||
onViewportChange,
|
||||
isControlledViewport,
|
||||
}: ZoomPaneProps) => {
|
||||
}: ZoomPaneProps) {
|
||||
const store = useStoreApi();
|
||||
const zoomPane = useRef<HTMLDivElement>(null);
|
||||
const { userSelectionActive, lib } = useStore(selector, shallow);
|
||||
@@ -142,6 +142,4 @@ const ZoomPane = ({
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ZoomPane;
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
import { createRFStore } from '../store';
|
||||
|
||||
const StoreContext = createContext<ReturnType<typeof createRFStore> | null>(null);
|
||||
|
||||
export const Provider = StoreContext.Provider;
|
||||
export default StoreContext;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
import { createStore } from '../store';
|
||||
|
||||
const StoreContext = createContext<ReturnType<typeof createStore> | null>(null);
|
||||
|
||||
export const Provider = StoreContext.Provider;
|
||||
export default StoreContext;
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { ColorMode, ColorModeClass } from '@xyflow/system';
|
||||
|
||||
function getMediaQuery() {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return window.matchMedia('(prefers-color-scheme: dark)');
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for receiving the current color mode class 'dark' or 'light'.
|
||||
*
|
||||
* @internal
|
||||
* @param colorMode - The color mode to use ('dark', 'light' or 'system')
|
||||
*/
|
||||
export function useColorModeClass(colorMode: ColorMode): ColorModeClass {
|
||||
const [colorModeClass, setColorModeClass] = useState<ColorModeClass | null>(
|
||||
colorMode === 'system' ? null : colorMode
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (colorMode !== 'system') {
|
||||
setColorModeClass(colorMode);
|
||||
return;
|
||||
}
|
||||
|
||||
const mediaQuery = getMediaQuery();
|
||||
const updateColorModeClass = () => setColorModeClass(mediaQuery?.matches ? 'dark' : 'light');
|
||||
|
||||
updateColorModeClass();
|
||||
mediaQuery?.addEventListener('change', updateColorModeClass);
|
||||
|
||||
return () => {
|
||||
mediaQuery?.removeEventListener('change', updateColorModeClass);
|
||||
};
|
||||
}, [colorMode]);
|
||||
|
||||
return colorModeClass !== null ? colorModeClass : getMediaQuery()?.matches ? 'dark' : 'light';
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { shallow } from 'zustand/shallow';
|
||||
|
||||
import { useStore } from './useStore';
|
||||
import type { ReactFlowStore } from '../types/store';
|
||||
import { ConnectionState, pointToRendererPoint } from '@xyflow/system';
|
||||
|
||||
const selector = (s: ReactFlowStore): ConnectionState => {
|
||||
return s.connection.inProgress
|
||||
? { ...s.connection, to: pointToRendererPoint(s.connection.to, s.transform) }
|
||||
: { ...s.connection };
|
||||
};
|
||||
/**
|
||||
* Hook for accessing the connection state.
|
||||
*
|
||||
* @public
|
||||
* @returns ConnectionState
|
||||
*/
|
||||
export function useConnection(): ConnectionState {
|
||||
return useStore(selector, shallow);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { handleNodeClick } from '../components/Nodes/utils';
|
||||
import { useStoreApi } from './useStore';
|
||||
|
||||
type UseDragParams = {
|
||||
nodeRef: RefObject<Element>;
|
||||
nodeRef: RefObject<HTMLDivElement>;
|
||||
disabled?: boolean;
|
||||
noDragClassName?: string;
|
||||
handleSelector?: string;
|
||||
@@ -13,41 +13,50 @@ type UseDragParams = {
|
||||
isSelectable?: boolean;
|
||||
};
|
||||
|
||||
function useDrag({ nodeRef, disabled = false, noDragClassName, handleSelector, nodeId, isSelectable }: UseDragParams) {
|
||||
/**
|
||||
* Hook for calling XYDrag helper from @xyflow/system.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useDrag({
|
||||
nodeRef,
|
||||
disabled = false,
|
||||
noDragClassName,
|
||||
handleSelector,
|
||||
nodeId,
|
||||
isSelectable,
|
||||
}: UseDragParams) {
|
||||
const store = useStoreApi();
|
||||
const [dragging, setDragging] = useState<boolean>(false);
|
||||
const xyDrag = useRef<XYDragInstance>();
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef?.current) {
|
||||
xyDrag.current = XYDrag({
|
||||
domNode: nodeRef.current,
|
||||
getStoreItems: () => store.getState(),
|
||||
onNodeMouseDown: (id: string) => {
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
nodeRef: nodeRef as RefObject<HTMLDivElement>,
|
||||
});
|
||||
},
|
||||
onDragStart: () => {
|
||||
setDragging(true);
|
||||
},
|
||||
onDragStop: () => {
|
||||
setDragging(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
xyDrag.current = XYDrag({
|
||||
getStoreItems: () => store.getState(),
|
||||
onNodeMouseDown: (id: string) => {
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
nodeRef,
|
||||
});
|
||||
},
|
||||
onDragStart: () => {
|
||||
setDragging(true);
|
||||
},
|
||||
onDragStop: () => {
|
||||
setDragging(false);
|
||||
},
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled) {
|
||||
xyDrag.current?.destroy();
|
||||
} else {
|
||||
} else if (nodeRef.current) {
|
||||
xyDrag.current?.update({
|
||||
noDragClassName,
|
||||
handleSelector,
|
||||
domNode: nodeRef.current as Element,
|
||||
domNode: nodeRef.current,
|
||||
isSelectable,
|
||||
nodeId,
|
||||
});
|
||||
@@ -59,5 +68,3 @@ function useDrag({ nodeRef, disabled = false, noDragClassName, handleSelector, n
|
||||
|
||||
return dragging;
|
||||
}
|
||||
|
||||
export default useDrag;
|
||||
|
||||
@@ -5,10 +5,14 @@ import type { Edge, ReactFlowState } from '../types';
|
||||
|
||||
const edgesSelector = (state: ReactFlowState) => state.edges;
|
||||
|
||||
function useEdges<EdgeData>(): Edge<EdgeData>[] {
|
||||
const edges = useStore(edgesSelector, shallow);
|
||||
/**
|
||||
* Hook for getting the current edges from the store.
|
||||
*
|
||||
* @public
|
||||
* @returns An array of edges
|
||||
*/
|
||||
export function useEdges<EdgeType extends Edge = Edge>(): EdgeType[] {
|
||||
const edges = useStore(edgesSelector, shallow) as EdgeType[];
|
||||
|
||||
return edges;
|
||||
}
|
||||
|
||||
export default useEdges;
|
||||
|
||||
@@ -2,26 +2,32 @@ import { useEffect } from 'react';
|
||||
import type { KeyCode } from '@xyflow/system';
|
||||
|
||||
import { useStoreApi } from '../hooks/useStore';
|
||||
import useKeyPress, { UseKeyPressOptions } from './useKeyPress';
|
||||
import useReactFlow from './useReactFlow';
|
||||
import { useKeyPress, UseKeyPressOptions } from './useKeyPress';
|
||||
import { useReactFlow } from './useReactFlow';
|
||||
import { Edge, Node } from '../types';
|
||||
|
||||
const selected = (item: Node | Edge) => item.selected;
|
||||
|
||||
const deleteKeyOptions: UseKeyPressOptions = { actInsideInputWithModifier: false };
|
||||
const win = typeof window !== 'undefined' ? window : undefined;
|
||||
|
||||
export default ({
|
||||
/**
|
||||
* Hook for handling global key events.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useGlobalKeyHandler({
|
||||
deleteKeyCode,
|
||||
multiSelectionKeyCode,
|
||||
}: {
|
||||
deleteKeyCode: KeyCode | null;
|
||||
multiSelectionKeyCode: KeyCode | null;
|
||||
}): void => {
|
||||
}): void {
|
||||
const store = useStoreApi();
|
||||
const { deleteElements } = useReactFlow();
|
||||
|
||||
const deleteKeyPressed = useKeyPress(deleteKeyCode, deleteKeyOptions);
|
||||
const multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode);
|
||||
const multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode, { target: win });
|
||||
|
||||
useEffect(() => {
|
||||
if (deleteKeyPressed) {
|
||||
@@ -34,4 +40,4 @@ export default ({
|
||||
useEffect(() => {
|
||||
store.setState({ multiSelectionActive: multiSelectionKeyPressed });
|
||||
}, [multiSelectionKeyPressed]);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import {
|
||||
Connection,
|
||||
HandleConnection,
|
||||
HandleType,
|
||||
areConnectionMapsEqual,
|
||||
handleConnectionChange,
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { useStore } from './useStore';
|
||||
import { useNodeId } from '../contexts/NodeIdContext';
|
||||
|
||||
type useHandleConnectionsParams = {
|
||||
type: HandleType;
|
||||
id?: string | null;
|
||||
nodeId?: string;
|
||||
onConnect?: (connections: Connection[]) => void;
|
||||
onDisconnect?: (connections: Connection[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to check if a <Handle /> is connected to another <Handle /> and get the connections.
|
||||
*
|
||||
* @public
|
||||
* @param param.type - handle type 'source' or 'target'
|
||||
* @param param.nodeId - node id - if not provided, the node id from the NodeIdContext is used
|
||||
* @param param.id - the handle id (this is only needed if the node has multiple handles of the same type)
|
||||
* @param param.onConnect - gets called when a connection is established
|
||||
* @param param.onDisconnect - gets called when a connection is removed
|
||||
* @returns an array with handle connections
|
||||
*/
|
||||
export function useHandleConnections({
|
||||
type,
|
||||
id = null,
|
||||
nodeId,
|
||||
onConnect,
|
||||
onDisconnect,
|
||||
}: useHandleConnectionsParams): HandleConnection[] {
|
||||
const _nodeId = useNodeId();
|
||||
const currentNodeId = nodeId ?? _nodeId;
|
||||
|
||||
const prevConnections = useRef<Map<string, HandleConnection> | null>(null);
|
||||
|
||||
const connections = useStore(
|
||||
(state) => state.connectionLookup.get(`${currentNodeId}-${type}-${id}`),
|
||||
areConnectionMapsEqual
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// @todo dicuss if onConnect/onDisconnect should be called when the component mounts/unmounts
|
||||
if (prevConnections.current && prevConnections.current !== connections) {
|
||||
const _connections = connections ?? new Map();
|
||||
handleConnectionChange(prevConnections.current, _connections, onDisconnect);
|
||||
handleConnectionChange(_connections, prevConnections.current, onConnect);
|
||||
}
|
||||
|
||||
prevConnections.current = connections ?? new Map();
|
||||
}, [connections, onConnect, onDisconnect]);
|
||||
|
||||
return useMemo(() => Array.from(connections?.values() ?? []), [connections]);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useCallback } from 'react';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
|
||||
import { useStore } from './useStore';
|
||||
import type { InternalNode, Node } from '../types';
|
||||
|
||||
/**
|
||||
* Hook for getting an internal node by id
|
||||
*
|
||||
* @public
|
||||
* @param id - id of the node
|
||||
* @returns array with visible node ids
|
||||
*/
|
||||
export function useInternalNode<NodeType extends Node = Node>(id: string): InternalNode<NodeType> | undefined {
|
||||
const node = useStore(
|
||||
useCallback((s) => s.nodeLookup.get(id) as InternalNode<NodeType> | undefined, [id]),
|
||||
shallow
|
||||
);
|
||||
|
||||
return node;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { useEffect, useLayoutEffect } from 'react';
|
||||
|
||||
// we need this hook to prevent a warning when using react-flow in SSR
|
||||
export const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
|
||||
@@ -12,14 +12,22 @@ export type UseKeyPressOptions = {
|
||||
|
||||
const defaultDoc = typeof document !== 'undefined' ? document : null;
|
||||
|
||||
// the keycode can be a string 'a' or an array of strings ['a', 'a+d']
|
||||
// a string means a single key 'a' or a combination when '+' is used 'a+d'
|
||||
// an array means different possibilites. Explainer: ['a', 'd+s'] here the
|
||||
// user can use the single key 'a' or the combination 'd' + 's'
|
||||
export default (
|
||||
/**
|
||||
* Hook for handling key events.
|
||||
*
|
||||
* @public
|
||||
* @param param.keyCode - The key code (string or array of strings) to use
|
||||
* @param param.options - Options
|
||||
* @returns boolean
|
||||
*/
|
||||
export function useKeyPress(
|
||||
// the keycode can be a string 'a' or an array of strings ['a', 'a+d']
|
||||
// a string means a single key 'a' or a combination when '+' is used 'a+d'
|
||||
// an array means different possibilites. Explainer: ['a', 'd+s'] here the
|
||||
// user can use the single key 'a' or the combination 'd' + 's'
|
||||
keyCode: KeyCode | null = null,
|
||||
options: UseKeyPressOptions = { target: defaultDoc, actInsideInputWithModifier: true }
|
||||
): boolean => {
|
||||
): boolean {
|
||||
const [keyPressed, setKeyPressed] = useState(false);
|
||||
|
||||
// we need to remember if a modifier key is pressed in order to track it
|
||||
@@ -84,6 +92,12 @@ export default (
|
||||
} else {
|
||||
pressedKeys.current.delete(event[keyOrCode]);
|
||||
}
|
||||
|
||||
// fix for Mac: when cmd key is pressed, keyup is not triggered for any other key, see: https://stackoverflow.com/questions/27380018/when-cmd-key-is-kept-pressed-keyup-is-not-triggered-for-any-other-key
|
||||
if (event.key === 'Meta') {
|
||||
pressedKeys.current.clear();
|
||||
}
|
||||
|
||||
modifierPressed.current = false;
|
||||
};
|
||||
|
||||
@@ -95,17 +109,19 @@ export default (
|
||||
target?.addEventListener('keydown', downHandler as EventListenerOrEventListenerObject);
|
||||
target?.addEventListener('keyup', upHandler as EventListenerOrEventListenerObject);
|
||||
window.addEventListener('blur', resetHandler);
|
||||
window.addEventListener('contextmenu', resetHandler);
|
||||
|
||||
return () => {
|
||||
target?.removeEventListener('keydown', downHandler as EventListenerOrEventListenerObject);
|
||||
target?.removeEventListener('keyup', upHandler as EventListenerOrEventListenerObject);
|
||||
window.removeEventListener('blur', resetHandler);
|
||||
window.removeEventListener('contextmenu', resetHandler);
|
||||
};
|
||||
}
|
||||
}, [keyCode, setKeyPressed]);
|
||||
|
||||
return keyPressed;
|
||||
};
|
||||
}
|
||||
|
||||
// utils
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useCallback } from 'react';
|
||||
import { calculateNodePosition, snapPosition, type XYPosition } from '@xyflow/system';
|
||||
|
||||
import { type Node } from '../types';
|
||||
import { useStoreApi } from './useStore';
|
||||
|
||||
const selectedAndDraggable = (nodesDraggable: boolean) => (n: Node) =>
|
||||
n.selected && (n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'));
|
||||
|
||||
/**
|
||||
* Hook for updating node positions by passing a direction and factor
|
||||
*
|
||||
* @internal
|
||||
* @returns function for updating node positions
|
||||
*/
|
||||
export function useMoveSelectedNodes() {
|
||||
const store = useStoreApi();
|
||||
|
||||
const moveSelectedNodes = useCallback((params: { direction: XYPosition; factor: number }) => {
|
||||
const { nodeExtent, snapToGrid, snapGrid, nodesDraggable, onError, updateNodePositions, nodeLookup, nodeOrigin } =
|
||||
store.getState();
|
||||
const nodeUpdates = new Map();
|
||||
const isSelected = selectedAndDraggable(nodesDraggable);
|
||||
|
||||
// by default a node moves 5px on each key press
|
||||
// if snap grid is enabled, we use that for the velocity
|
||||
const xVelo = snapToGrid ? snapGrid[0] : 5;
|
||||
const yVelo = snapToGrid ? snapGrid[1] : 5;
|
||||
|
||||
const xDiff = params.direction.x * xVelo * params.factor;
|
||||
const yDiff = params.direction.y * yVelo * params.factor;
|
||||
|
||||
for (const [, node] of nodeLookup) {
|
||||
if (!isSelected(node)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let nextPosition = {
|
||||
x: node.internals.positionAbsolute.x + xDiff,
|
||||
y: node.internals.positionAbsolute.y + yDiff,
|
||||
};
|
||||
|
||||
if (snapToGrid) {
|
||||
nextPosition = snapPosition(nextPosition, snapGrid);
|
||||
}
|
||||
|
||||
const { position, positionAbsolute } = calculateNodePosition({
|
||||
nodeId: node.id,
|
||||
nextPosition,
|
||||
nodeLookup,
|
||||
nodeExtent,
|
||||
nodeOrigin,
|
||||
onError,
|
||||
});
|
||||
|
||||
node.position = position;
|
||||
node.internals.positionAbsolute = positionAbsolute;
|
||||
|
||||
nodeUpdates.set(node.id, node);
|
||||
}
|
||||
|
||||
updateNodePositions(nodeUpdates);
|
||||
}, []);
|
||||
|
||||
return moveSelectedNodes;
|
||||
}
|
||||
@@ -5,10 +5,14 @@ import type { Node, ReactFlowState } from '../types';
|
||||
|
||||
const nodesSelector = (state: ReactFlowState) => state.nodes;
|
||||
|
||||
function useNodes<NodeData>(): Node<NodeData>[] {
|
||||
const nodes = useStore(nodesSelector, shallow);
|
||||
/**
|
||||
* Hook for getting the current nodes from the store.
|
||||
*
|
||||
* @public
|
||||
* @returns An array of nodes
|
||||
*/
|
||||
export function useNodes<NodeType extends Node = Node>(): NodeType[] {
|
||||
const nodes = useStore(nodesSelector, shallow) as NodeType[];
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
export default useNodes;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useCallback } from 'react';
|
||||
import { shallowNodeData } from '@xyflow/system';
|
||||
|
||||
import { useStore } from '../hooks/useStore';
|
||||
import type { Node } from '../types';
|
||||
|
||||
/**
|
||||
* Hook for receiving data of one or multiple nodes
|
||||
*
|
||||
* @public
|
||||
* @param nodeId - The id (or ids) of the node to get the data from
|
||||
* @param guard - Optional guard function to narrow down the node type
|
||||
* @returns An object (or array of object) with {id, type, data} representing each node
|
||||
*/
|
||||
export function useNodesData<NodeType extends Node = Node>(
|
||||
nodeId: string
|
||||
): Pick<NodeType, 'id' | 'type' | 'data'> | null;
|
||||
export function useNodesData<NodeType extends Node = Node>(nodeIds: string[]): Pick<NodeType, 'id' | 'type' | 'data'>[];
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function useNodesData(nodeIds: any): any {
|
||||
const nodesData = useStore(
|
||||
useCallback(
|
||||
(s) => {
|
||||
const data = [];
|
||||
const isArrayOfIds = Array.isArray(nodeIds);
|
||||
const _nodeIds = isArrayOfIds ? nodeIds : [nodeIds];
|
||||
|
||||
for (const nodeId of _nodeIds) {
|
||||
const node = s.nodeLookup.get(nodeId);
|
||||
if (node) {
|
||||
data.push({
|
||||
id: node.id,
|
||||
type: node.type,
|
||||
data: node.data,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return isArrayOfIds ? data : data[0] ?? null;
|
||||
},
|
||||
[nodeIds]
|
||||
),
|
||||
shallowNodeData
|
||||
);
|
||||
|
||||
return nodesData;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user