Merge branch 'main' into refactor-testing

This commit is contained in:
Peter
2023-11-02 11:37:00 +01:00
74 changed files with 6234 additions and 2178 deletions
+13 -5
View File
@@ -1,12 +1,20 @@
# Contributing to React Flow # Contributing to React Flow
Hello there! So glad you want to help out with React Flow 🤗 Youre the best. Heres a guide for how you can contribute to the project. Hello there! So glad you want to help out with React Flow and Svelte Flow 🤗 Youre the best. Heres a guide for how you can contribute to the project.
# The new xyflow organization
Just recently we renamed our organization and repository of React Flow to "xyflow". Now you can not only find the source code of React Flow but also of Svelte Flow in this repository. We are in a state of transition. This is the current structure:
* React Flow `reactflow` version v11 is on branch v11
* Svelte Flow `@xyflow/svelte` can be found under [packages/svelte](./packages/svelte)
* React Flow v12 (not published yet) can be found under [packages/react](./packages/react)
# Our Contributing Philosophy # Our Contributing Philosophy
The direction of React Flow and which new features are added, and which are left out, is decided by the core team (sometimes referred to as a “cathedral” style of development). The core team is paid to do this work ([see how here](https://reactflow.dev/blog/asking-for-money-for-open-source/)). With this model we ensure that the people doing the most work on the library are paid for their time and effort, and that we prevent the library from bloating. The direction of React Flow and Svelte Flow and which new features are added, and which are left out, is decided by the core team (sometimes referred to as a “cathedral” style of development). The core team is paid to do this work ([see how here](https://xyflow.com/blog/asking-for-money-for-open-source/)). With this model we ensure that the people doing the most work on the library are paid for their time and effort, and that we prevent the library from bloating.
That being said, React Flow is only interesting because of the people who make things with it, share their work, and discuss it. Some of the most important and undervalued work in open source is from non-code contributions, and that is where we can use the most help from you. That being said, our libraries are only interesting because of the people who make things with it, share their work, and discuss it. Some of the most important and undervalued work in open source is from non-code contributions, and that is where we can use the most help from you.
# How can I help? # How can I help?
@@ -16,7 +24,7 @@ The things we need the most help for the library and its community are:
**💬 Answering questions** in our [Discord Server](https://discord.gg/Bqt6xrs) and [Github discussions](https://github.com/wbkd/react-flow/discussions). **💬 Answering questions** in our [Discord Server](https://discord.gg/Bqt6xrs) and [Github discussions](https://github.com/wbkd/react-flow/discussions).
🎬 **Create tutorials** for React Flow. Send them to us and well happily share them! 🎬 **Create tutorials**. Send them to us and well happily share them!
**✏️ Edit our [Docs](https://reactflow.dev/docs/introduction/)**: Make changes in the [react-flow-docs repo](https://github.com/wbkd/react-flow-docs), or click the "edit this page” button that lives on every doc site. **✏️ Edit our [Docs](https://reactflow.dev/docs/introduction/)**: Make changes in the [react-flow-docs repo](https://github.com/wbkd/react-flow-docs), or click the "edit this page” button that lives on every doc site.
@@ -24,7 +32,7 @@ All interactions should be done with care following our [Code of Conduct](https:
## Enhancements ## Enhancements
If you have an idea or suggestion for an enhancement to the React Flow library, please use the [New Features](https://github.com/wbkd/react-flow/discussions/categories/new-features) discussion section. If you want to build it yourself, **please reach out to us before you dive into a new pull request.** The direction of React Flow and which new features are added are discussed in our Discord Server and in [this Github discussions section](https://github.com/wbkd/react-flow/discussions/categories/new-features), and in the end they are decided by the core team. If you have an idea or suggestion for an enhancement to the React Flow or Svelte Flow library, please use the [New Features](https://github.com/wbkd/react-flow/discussions/categories/new-features) discussion section. If you want to build it yourself, **please reach out to us before you dive into a new pull request.** The direction of React Flow/ Svelte Flow and which new features are added are discussed in our Discord Server and in [this Github discussions section](https://github.com/wbkd/react-flow/discussions/categories/new-features), and in the end they are decided by the core team.
Talking to us first about the enhancement you want to build will be the most likely way to get your pull request into the library (see Our Contributing Philosophy above). We would hate to see you write code youre proud of, just to learn that weve already been working on the same thing, or that we feel doesnt fit into the core library. Talking to us first about the enhancement you want to build will be the most likely way to get your pull request into the library (see Our Contributing Philosophy above). We would hate to see you write code youre proud of, just to learn that weve already been working on the same thing, or that we feel doesnt fit into the core library.
+91 -55
View File
@@ -1,51 +1,50 @@
![readme-header-dark](https://user-images.githubusercontent.com/3797215/156384064-08a889d6-73c0-4cbf-8ff3-28dc601d1f5f.svg#gh-dark-mode-only) ![xyflow-header](https://user-images.githubusercontent.com/2857535/279643999-ffda9f91-6b6d-447d-82be-fcbd6103edb6.svg#gh-light-mode-only)
![readme-header](https://user-images.githubusercontent.com/3797215/156259138-fb9f59f8-52f2-474a-b78c-6570867e4ead.svg#gh-light-mode-only) ![xyflow-header-dark](https://user-images.githubusercontent.com/2857535/279644026-a01c231c-6c6e-4b41-96e0-a85c75c9acee.svg#gh-dark-mode-only)
<div align="center"> <div align="center">
![GitHub License MIT](https://img.shields.io/github/license/wbkd/react-flow?color=%23ff0072) ![GitHub License MIT](https://img.shields.io/github/license/wbkd/react-flow?color=%23ff0072)
![npm downloads](https://img.shields.io/npm/dt/reactflow?color=%23FF0072&label=downloads) ![npm downloads](https://img.shields.io/npm/dt/reactflow?color=%23FF0072&label=React%20Flow%20downloads)
![GitHub Repo stars](https://img.shields.io/github/stars/wbkd/react-flow?color=%23FF0072) ![npm downloads](https://img.shields.io/npm/dt/@xyflow/svelte?color=%23FF3E00&label=Svelte%20Flow%20downloads)
![GitHub release (latest by date)](https://img.shields.io/github/v/release/wbkd/react-flow?color=%23FF0072)
A highly customizable React component for building interactive graphs and node-based editors. Powerful open source libraries for building node-based UIs with React or Svelte. Ready out-of-the-box and infinitely customizable.
[🚀 Getting Started](https://reactflow.dev/docs/quickstart/) | [📖 Documentation](https://reactflow.dev/docs/api/react-flow-props) | [📺 Examples](https://reactflow.dev/docs/examples/overview) | [☎️ Discord](https://discord.gg/RVmnytFmGW) | [💎 React Flow Pro](https://pro.reactflow.dev)
[React Flow](https://reactflow.dev/) · [Svelte Flow](https://svelteflow.dev/) · [React Flow Pro](https://reactflow.dev/pro) · [Discord](https://discord.gg/Bqt6xrs)
</div> </div>
--- ---
## Key Features ## The xyflow mono repo
- **Easy to use:** Seamless zooming and panning, single- and multi selection of graph elements and keyboard shortcuts are supported out of the box The xyflow repository is the home of four packages:
- **Customizable:** Different [node](https://reactflow.dev/docs/api/nodes/node-types) and [edge types](https://reactflow.dev/docs/api/edges/edge-types) and support for custom nodes with multiple handles and custom edges * React Flow v11 `reactflow` [v11 branch](https://github.com/xyflow/xyflow/tree/v11)
- **Fast rendering:** Only nodes that have changed are re-rendered and only those in the viewport are displayed * React Flow v12 (not published yet) [packages/react](./packages/react)
- **Hooks and Utils:** [Hooks](https://reactflow.dev/docs/api/hooks/use-react-flow) for handling nodes, edges and the viewport and graph [helper functions](https://reactflow.dev/docs/api/graph-util-functions) * Svelte Flow `@xyflow/svelte` [packages/svelte](./packages/svelte)
- **Plugin Components:** [Background](https://reactflow.dev/docs/api/plugin-components/background), [MiniMap](https://reactflow.dev/docs/api/plugin-components/minimap) and [Controls](https://reactflow.dev/docs/api/plugin-components/controls) * Shared helper library `@xyflow/system` [packages/system](./packages/system)
- **Reliable**: Written in [Typescript](https://www.typescriptlang.org/) and tested with [cypress](https://www.cypress.io/)
**We just moved repositories** from the @wbkd org to this one. React Flow v11 will remain on the [v11 branch](https://github.com/xyflow/xyflow/tree/v11). When we have a stable v12, the package name of React Flow will change from `reactflow` to `@xyflow/react`.
## Commercial Usage ## Commercial Usage
**Are you using React Flow for a personal project?** Great! No sponsorship needed, you can support us by reporting any bugs you find, sending us screenshots of your projects, and starring us on Github 🌟 **Are you using React Flow or Svelte Flow for a personal project?** Great! No sponsorship needed, you can support us by reporting any bugs you find, sending us screenshots of your projects, and starring us on Github 🌟
**Are you using React Flow at your organization and making money from it?** Awesome! We rely on your support to keep React Flow developed and maintained under an MIT License, just how we like it. You can do that on the [React Flow Pro website](https://pro.reactflow.dev) or through [Github Sponsors](https://github.com/sponsors/wbkd). **Are you using React Flow or Svelte Flow at your organization and making money from it?** Awesome! We rely on your support to keep our libraries developed and maintained under an MIT License, just how we like it. For React Flow you can do that on the [React Flow Pro website](https://reactflow.dev/pro) and for both of our libraries you can do it through [Github Sponsors](https://github.com/sponsors/xyflow).
You can find more information in our [React Flow Pro FAQs](https://pro.reactflow.dev/info). ## Getting Started
## Installation The best way to get started is to check out the [React Flow](https://reactflow.dev/learn) or [Svelte Flow](https://svelteflow.dev/learn) learn section. However if you want to get a sneak peek of how to install the and use the libraries you can see it here:
The easiest way to get the latest version of React Flow is to install it via npm, yarn or pnpm: <details>
<summary><strong>React Flow</strong> basic usage</summary>
```bash ### Installation
```sh
npm install reactflow npm install reactflow
``` ```
## Quickstart ### Basic usage
```jsx
This is only a very basic usage example of React Flow. To see everything that is possible with the library, please refer to the [website](https://reactflow.dev) for [guides](https://reactflow.dev/docs/guides/custom-nodes), [examples](https://reactflow.dev/docs/examples/overview) and the full [API reference](https://reactflow.dev/docs/api/react-flow-props).
```jsx
import { useCallback } from 'react'; import { useCallback } from 'react';
import ReactFlow, { import ReactFlow, {
MiniMap, MiniMap,
@@ -54,7 +53,7 @@ import ReactFlow, {
useNodesState, useNodesState,
useEdgesState, useEdgesState,
addEdge, addEdge,
} from '@xyflow/react'; } from 'reactflow';
import 'reactflow/dist/style.css'; import 'reactflow/dist/style.css';
@@ -88,44 +87,81 @@ function Flow() {
export default Flow; export default Flow;
``` ```
</details>
## Development <details>
<summary><strong>Svelte Flow</strong> basic usage</summary>
Before you can start developing please make sure that you have [pnpm](https://pnpm.io/) installed (`npm i -g pnpm`). Then install the dependencies using pnpm: `pnpm install`. ### Installation
Run `pnpm build` once and then you can use `pnpm dev` for local development. ```sh
npm install @xyflow/svelte
```
## Testing ### Basic usage
```svelte
<script lang="ts">
import { writable } from 'svelte/store';
import {
SvelteFlow,
Controls,
Background,
BackgroundVariant,
MiniMap,
} from '@xyflow/svelte';
Testing is done with cypress. You can find the tests in the [`examples/vite-app/cypress`](/examples/vite-app/cypress/) folder. In order to run the tests do: import '@xyflow/svelte/dist/style.css'
```sh const nodes = writable([
pnpm test {
id: '1',
type: 'input',
data: { label: 'Input Node' },
position: { x: 0, y: 0 }
},
{
id: '2',
type: 'custom',
data: { label: 'Node' },
position: { x: 0, y: 150 }
}
]);
const edges = writable([
{
id: '1-2',
type: 'default',
source: '1',
target: '2',
label: 'Edge Text'
}
]);
</script>
<SvelteFlow
{nodes}
{edges}
fitView
on:nodeclick={(event) => console.log('on node click', event)}
>
<Controls />
<Background variant={BackgroundVariant.Dots} />
<MiniMap />
</SvelteFlow>
``` ```
</details>
## Maintainers ## The xyflow team
React Flow is the full-time project of Moritz and Christopher of [webkid](https://webkid.io/), based in Berlin. If you need help or want to talk to us about a collaboration, reach out through our [contact form](https://pro.reactflow.dev/contact) or by joining the [React Flow Discord Server](https://discord.gg/Bqt6xrs). React Flow and Svelte Flow are maintained by the team behind [xyflow](https://xyflow.com). If you need help or want to talk to us about a collaboration, reach out through our [contact form](https://xyflow.com/contact) or by joining our [Discord Server](https://discord.gg/Bqt6xrs).
- Moritz Klack • [Twitter](https://twitter.com/moklick) • [Github](https://github.com/moklick) - Christopher • [Twitter](https://twitter.com/chrtze) • [Github](https://github.com/chrtze)
- Christopher Möller • [Twitter](https://twitter.com/chrtze) • [Github](https://github.com/chrtze) - Hayleigh • [Twitter](https://twitter.com/hayleighdotdev) • [Github](https://github.com/hayleigh-dot-dev)
- John • [Website](https://johnrobbdesign.com/) • [Mastodon](https://mastodon.social/@johnrobbjr)
- Moritz • [Twitter](https://twitter.com/moklick) • [Github](https://github.com/moklick)
- Peter • [Github](https://github.com/peterkogo)
Any support you provide goes directly towards the development and maintenance of React Flow, allowing us to continue to operate as an independent company, working on what we think is best for React Flow as an open-source library.
## Community Packages
- [useUndoable](https://github.com/xplato/useUndoable) - Hook for undo/redo functionality with an explicit React Flow example
- [react-flow-smart-edge](https://github.com/tisoap/react-flow-smart-edge) - Custom edge that doesn't intersect with nodes
- [Feliz.ReactFlow](https://github.com/tforkmann/Feliz.ReactFlow) - Feliz React Bindings for React Flow
## Credits
React Flow was initially developed for [datablocks](https://datablocks.pro), a graph-based editor for transforming, analyzing and visualizing data in the browser. Under the hood, React Flow depends on these great libraries:
- [d3-zoom](https://github.com/d3/d3-zoom) - used for zoom, pan and drag interactions with the graph canvas
- [d3-drag](https://github.com/d3/d3-drag) - used for making the nodes draggable
- [zustand](https://github.com/pmndrs/zustand) - internal state management
## License ## License
React Flow is [MIT licensed](https://github.com/wbkd/react-flow/blob/main/LICENSE). React Flow and Svelte Flow are [MIT licensed](./LICENSE).
+21
View File
@@ -0,0 +1,21 @@
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store
+10
View File
@@ -0,0 +1,10 @@
# Astro examples
Tiny app for testing React Flow and Svelte Flow with Astro.
## Start local dev server
```sh
pnpm dev
```
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
import svelte from '@astrojs/svelte';
// https://astro.build/config
export default defineConfig({
integrations: [react(), svelte()],
});
+25
View File
@@ -0,0 +1,25 @@
{
"name": "astro",
"type": "module",
"private": true,
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@astrojs/react": "^3.0.2",
"@astrojs/svelte": "^4.0.2",
"@types/react": "^18.2.24",
"@types/react-dom": "^18.2.8",
"@xyflow/react": "workspace:^",
"@xyflow/svelte": "workspace:^",
"astro": "^3.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"svelte": "^4.2.1"
}
}
@@ -0,0 +1,32 @@
import { memo, type FC, type CSSProperties } from 'react';
import { Handle, Position, type NodeProps } from '@xyflow/react';
const sourceHandleStyleA: CSSProperties = { left: 50 };
const sourceHandleStyleB: CSSProperties = {
right: 50,
left: 'auto',
};
const CustomNode: FC<NodeProps> = ({ data, xPos, yPos }) => {
return (
<>
<Handle type="target" position={Position.Top} />
<div>
<div>
Label: <strong>{data.label}</strong>
</div>
<div>
Position:{' '}
<strong>
{xPos.toFixed(2)},{yPos.toFixed(2)}
</strong>
</div>
</div>
<Handle type="source" position={Position.Bottom} id="a" style={sourceHandleStyleA} />
<Handle type="source" position={Position.Bottom} id="b" style={sourceHandleStyleB} />
</>
);
};
export default memo(CustomNode);
@@ -0,0 +1,130 @@
import { useCallback } from 'react';
import {
ReactFlow,
addEdge,
useEdgesState,
useNodesState,
Background,
Controls,
type Connection,
type Edge,
type Node,
Position,
} from '@xyflow/react';
import CustomNode from './CustomNode';
import '@xyflow/react/dist/style.css';
const nodeSize = {
width: 100,
height: 40,
};
const initialNodes: Node[] = [
{
id: '1',
type: 'input',
data: { label: 'Node 1' },
position: { x: 250, y: 5 },
size: nodeSize,
handles: [
{
type: 'source',
position: Position.Bottom,
x: nodeSize.width * 0.5,
y: nodeSize.height,
},
],
},
{
id: '2',
data: { label: 'Node 2' },
position: { x: 100, y: 100 },
size: nodeSize,
handles: [
{
type: 'source',
position: Position.Bottom,
x: nodeSize.width * 0.5,
y: nodeSize.height,
width: 1,
height: 1,
},
{
type: 'target',
position: Position.Top,
x: nodeSize.width * 0.5,
y: 0,
width: 1,
height: 1,
},
],
},
{
id: '3',
data: { label: 'Node 3' },
position: { x: 400, y: 100 },
size: nodeSize,
handles: [
{
type: 'source',
position: Position.Bottom,
x: nodeSize.width * 0.5,
y: nodeSize.height,
width: 1,
height: 1,
},
{
type: 'target',
position: Position.Top,
x: nodeSize.width * 0.5,
y: 0,
width: 1,
height: 1,
},
],
},
{
id: '4',
data: { label: 'Node 4' },
position: { x: 400, y: 200 },
type: 'custom',
},
];
const initialEdges: Edge[] = [
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3', animated: true },
];
const nodeTypes = {
custom: CustomNode,
};
function Flow() {
const [nodes, , onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect = useCallback((params: Connection | Edge) => setEdges((eds) => addEdge(params, eds)), [setEdges]);
return (
<div style={{ width: 700, height: 400 }}>
<ReactFlow
nodes={nodes}
onNodesChange={onNodesChange}
edges={edges}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
nodeTypes={nodeTypes}
fitView
width={700}
height={400}
>
<Background />
<Controls />
</ReactFlow>
</div>
);
}
export default Flow;
@@ -0,0 +1,86 @@
<script lang="ts">
import { writable } from 'svelte/store';
import { SvelteFlow, Controls, Background, BackgroundVariant, Position, type Node, type Edge } from '@xyflow/svelte';
import '@xyflow/svelte/dist/style.css';
const nodes = writable<Node[]>([
{
id: '0',
position: { x: 0, y: 150 },
data: { label: 'Node 0' },
sourcePosition: Position.Right,
targetPosition: Position.Left,
size: {
width: 100,
height: 40,
},
handles: [
{ type: 'source', x: 100, y: 20, position: Position.Right },
{ type: 'target', x: 0, y: 20, position: Position.Left },
],
},
{
id: 'A',
position: { x: 250, y: 0 },
data: { label: 'A' },
sourcePosition: Position.Right,
targetPosition: Position.Left,
size: {
width: 100,
height: 40,
},
handles: [
{ type: 'source', x: 100, y: 20, position: Position.Right },
{ type: 'target', x: 0, y: 20, position: Position.Left },
],
},
{
id: 'B',
position: { x: 250, y: 150 },
data: { label: 'B' },
sourcePosition: Position.Right,
targetPosition: Position.Left,
size: {
width: 100,
height: 40,
},
handles: [
{ type: 'source', x: 100, y: 20, position: Position.Right },
{ type: 'target', x: 0, y: 20, position: Position.Left },
],
},
{
id: 'C',
position: { x: 250, y: 300 },
data: { label: 'C' },
sourcePosition: Position.Right,
targetPosition: Position.Left,
size: {
width: 100,
height: 40,
},
handles: [
{ type: 'source', x: 100, y: 20, position: Position.Right },
{ type: 'target', x: 0, y: 20, position: Position.Left },
],
},
]);
const edges = writable<Edge[]>([
{ id: '0A', source: '0', target: 'A', animated: true },
{ id: '0B', source: '0', target: 'B', animated: true },
{ id: '0C', source: '0', target: 'C', animated: true },
]);
const defaultEdgeOptions = {
animated: true,
};
</script>
<div style="height: 400px; width: 700px;">
<SvelteFlow {nodes} {edges} fitView {defaultEdgeOptions} width={700} height={400}>
<Controls />
<Background variant={BackgroundVariant.Dots} />
</SvelteFlow>
</div>
+1
View File
@@ -0,0 +1 @@
/// <reference types="astro/client" />
@@ -0,0 +1,27 @@
---
import ReactFlowApp from '../components/ReactFlowExample'
import SvelteFlowApp from '../components/SvelteFlowExample/index.svelte'
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>Astro example for React Flow and Svelte Flow</title>
<style>
html, body {
margin:0;
font-family: sans-serif;
}
</style>
</head>
<body>
<h2>Svelte Flow</h2>
<SvelteFlowApp />
<h2>React Flow</h2>
<ReactFlowApp />
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "astro/tsconfigs/strict",
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "react"
}
}
@@ -66,7 +66,7 @@ const DnDFlow = () => {
return ( return (
<div className={styles.dndflow}> <div className={styles.dndflow}>
<ReactFlowProvider> <ReactFlowProvider nodes={initialNodes} edges={[]}>
<div className={styles.wrapper}> <div className={styles.wrapper}>
<ReactFlow <ReactFlow
nodes={nodes} nodes={nodes}
@@ -77,7 +77,6 @@ const DnDFlow = () => {
onInit={onInit} onInit={onInit}
onDrop={onDrop} onDrop={onDrop}
onDragOver={onDragOver} onDragOver={onDragOver}
nodeOrigin={nodeOrigin}
> >
<Controls /> <Controls />
</ReactFlow> </ReactFlow>
+3 -1
View File
@@ -17,9 +17,11 @@ export function getNodesAndEdges(xElements = 10, yElements = 10): ElementsCollec
const data = { label: `Node ${nodeId}` }; const data = { label: `Node ${nodeId}` };
const node = { const node = {
id: nodeId.toString(), id: nodeId.toString(),
style: { width: 50, fontSize: 11 }, style: { width: 50, height: 30, fontSize: 11 },
data, data,
position, position,
width: 50,
height: 30,
}; };
initialNodes.push(node); initialNodes.push(node);
@@ -204,9 +204,6 @@ const Subflow = () => {
onNodeDrag={onNodeDrag} onNodeDrag={onNodeDrag}
onNodeDragStop={onNodeDragStop} onNodeDragStop={onNodeDragStop}
className="react-flow-basic-example" className="react-flow-basic-example"
defaultViewport={defaultViewport}
minZoom={0.2}
maxZoom={4}
onlyRenderVisibleElements={false} onlyRenderVisibleElements={false}
nodeTypes={nodeTypes} nodeTypes={nodeTypes}
fitView fitView
@@ -23,28 +23,6 @@
const bgColor = writable('#1A192B'); const bgColor = writable('#1A192B');
const onChange: ChangeEventHandler<HTMLInputElement> = (event) => {
nodes.update((nds) =>
nds.map((node) => {
if (node.type !== 'colorNode') {
return node;
}
const color = (event.target as HTMLInputElement)?.value;
bgColor.set(color);
return {
...node,
data: {
...node.data,
color
}
};
})
);
};
const nodes = writable<Node[]>([ const nodes = writable<Node[]>([
{ {
id: '1', id: '1',
@@ -56,17 +34,9 @@
{ {
id: '2', id: '2',
type: 'colorNode', type: 'colorNode',
data: { onChange: onChange, color: $bgColor }, data: { colorStore: bgColor },
style: 'border: 1px solid #777; padding: 10px',
position: { x: 250, y: 50 } position: { x: 250, y: 50 }
}, },
{
id: '2a',
type: 'colorNode',
data: { onChange: onChange, color: $bgColor },
style: 'border: 1px solid #777; padding: 10px',
position: { x: 250, y: 520 }
},
{ {
id: '3', id: '3',
type: 'output', type: 'output',
@@ -115,7 +85,7 @@
{nodes} {nodes}
{edges} {edges}
{nodeTypes} {nodeTypes}
style="--bgcolor: {$bgColor}" style="--background-color: {$bgColor}"
fitView fitView
on:connect={onConnect} on:connect={onConnect}
> >
@@ -123,9 +93,3 @@
<Background variant={BackgroundVariant.Dots} /> <Background variant={BackgroundVariant.Dots} />
<MiniMap /> <MiniMap />
</SvelteFlow> </SvelteFlow>
<style>
:global(.svelte-flow) {
background: var(--bgcolor);
}
</style>
@@ -1,21 +1,40 @@
<script lang="ts"> <script lang="ts">
import type { Writable } from 'svelte/store';
import { Handle, Position, type NodeProps } from '@xyflow/svelte'; import { Handle, Position, type NodeProps } from '@xyflow/svelte';
type $$Props = NodeProps; type $$Props = NodeProps;
export let data: { color: string; onChange: () => void } = { color: '#111', onChange: () => {} }; export let data: { colorStore: Writable<string> };
const { colorStore } = data;
</script> </script>
<Handle type="target" position={Position.Left} on:connect /> <div class="custom">
<div> <Handle type="target" position={Position.Left} on:connect />
Custom Color Picker Node: <strong>{data.color}</strong> <div>
Custom Color Picker Node: <strong>{$colorStore}</strong>
</div>
<input
class="nodrag"
type="color"
on:input={(evt) => colorStore.set(evt.currentTarget.value)}
value={$colorStore}
/>
<Handle type="source" position={Position.Right} id="a" style="top: 20px;" on:connect />
<Handle
type="source"
position={Position.Right}
id="b"
style="top: auto; bottom: 10px;"
on:connect
/>
</div> </div>
<input class="nodrag" type="color" on:input={data.onChange} value={data.color} />
<Handle type="source" position={Position.Right} id="a" style="top: 10px;" on:connect /> <style>
<Handle .custom {
type="source" background-color: white;
position={Position.Right} padding: 10px;
id="b" border: 1px solid #777;
style="top: auto; bottom: 10px;" border-radius: 20px;
on:connect }
/> </style>
@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { useSvelteFlow } from '@xyflow/svelte'; import { useNodes, useSvelteFlow } from '@xyflow/svelte';
const { const {
zoomIn, zoomIn,
@@ -10,8 +10,10 @@
setViewport, setViewport,
getViewport, getViewport,
viewport, viewport,
nodes toObject
} = useSvelteFlow(); } = useSvelteFlow();
const nodes = useNodes();
</script> </script>
<aside> <aside>
@@ -23,6 +25,12 @@
<button on:click={() => setCenter(0, 0)}>setCenter 0, 0</button> <button on:click={() => setCenter(0, 0)}>setCenter 0, 0</button>
<button on:click={() => setViewport({ x: 100, y: 100, zoom: 2 })}>setViewport</button> <button on:click={() => setViewport({ x: 100, y: 100, zoom: 2 })}>setViewport</button>
<button on:click={() => console.log(getViewport())}>getViewport</button> <button on:click={() => console.log(getViewport())}>getViewport</button>
<button
on:click={() => {
const { nodes, edges, viewport } = toObject();
console.log(nodes, edges, viewport);
}}>toObject</button
>
<div class="label">Nodes:</div> <div class="label">Nodes:</div>
{#each $nodes as node (node.id)} {#each $nodes as node (node.id)}
+1 -1
View File
@@ -7,7 +7,7 @@
"private": true, "private": true,
"scripts": { "scripts": {
"preinstall": "npx only-allow pnpm", "preinstall": "npx only-allow pnpm",
"dev": "turbo run dev --parallel", "dev": "turbo run dev --parallel --concurrency 12",
"dev:svelte": "turbo run dev --filter=svelte --filter=system", "dev:svelte": "turbo run dev --filter=svelte --filter=system",
"dev:react": "turbo run dev --filter=react", "dev:react": "turbo run dev --filter=react",
"build": "turbo run build", "build": "turbo run build",
+128 -4
View File
@@ -1,10 +1,134 @@
# @reactflow/core ![readme-header](https://user-images.githubusercontent.com/2857535/279691008-efd8f0d2-d235-4f19-b136-6e81e5ba974d.svg#gh-light-mode-only)
![readme-header-dark](https://user-images.githubusercontent.com/2857535/279691021-f1cbf9e6-ea4d-43e8-935d-dd4c4983c0d9.svg#gh-dark-mode-only)
Core components and util functions of React Flow. <div align="center">
![GitHub License MIT](https://img.shields.io/github/license/wbkd/react-flow?color=%23ff0072)
![npm downloads](https://img.shields.io/npm/dt/reactflow?color=%23FF0072&label=downloads)
![GitHub Repo stars](https://img.shields.io/github/stars/wbkd/react-flow?color=%23FF0072)
![GitHub release (latest by date)](https://img.shields.io/github/v/release/wbkd/react-flow?color=%23FF0072)
A highly customizable React component for building interactive graphs and node-based editors.
[🚀 Getting Started](https://reactflow.dev/learn) | [📖 Documentation](https://reactflow.dev/api-reference/react-flow) | [📺 Examples](https://reactflow.dev/examples/overview) | [☎️ Discord](https://discord.gg/RVmnytFmGW) | [💎 React Flow Pro](https://pro.reactflow.dev)
</div>
---
## Key Features
- **Easy to use:** Seamless zooming and panning, single- and multi selection of graph elements and keyboard shortcuts are supported out of the box
- **Customizable:** Different [node](https://reactflow.dev/examples) and [edge types](https://reactflow.dev/examples/edges/edge-types) and support for custom nodes with multiple handles and custom edges
- **Fast rendering:** Only nodes that have changed are re-rendered
- **Hooks and Utils:** [Hooks](https://reactflow.dev/api-reference/hooks) for handling nodes, edges and the viewport and graph [helper functions](https://reactflow.dev/api-reference/utils)
- **Plugin Components:** [Background](https://reactflow.dev/api-reference/components/background), [MiniMap](https://reactflow.dev/api-reference/components/minimap) and [Controls](https://reactflow.dev/api-reference/components/controls)
- **Reliable**: Written in [Typescript](https://www.typescriptlang.org/) and tested with [cypress](https://www.cypress.io/)
## Commercial Usage
**Are you using React Flow for a personal project?** Great! No sponsorship needed, you can support us by reporting any bugs you find, sending us screenshots of your projects, and starring us on Github 🌟
**Are you using React Flow at your organization and making money from it?** Awesome! We rely on your support to keep React Flow developed and maintained under an MIT License, just how we like it. You can do that on the [React Flow Pro website](https://pro.reactflow.dev) or through [Github Sponsors](https://github.com/sponsors/wbkd).
You can find more information in our [React Flow Pro FAQs](https://pro.reactflow.dev/info).
## Installation ## Installation
```sh The easiest way to get the latest version of React Flow is to install it via npm, yarn or pnpm:
npm install @reactflow/core
```bash
npm install reactflow
``` ```
## Quickstart
This is only a very basic usage example of React Flow. To see everything that is possible with the library, please refer to the [website](https://reactflow.dev) for [guides](https://reactflow.dev/learn/customization/custom-nodes), [examples](https://reactflow.dev/examples/overview) and the full [API reference](https://reactflow.dev/api-reference/react-flow).
```jsx
import { useCallback } from 'react';
import ReactFlow, {
MiniMap,
Controls,
Background,
useNodesState,
useEdgesState,
addEdge,
} from 'reactflow';
import 'reactflow/dist/style.css';
const initialNodes = [
{ id: '1', position: { x: 0, y: 0 }, data: { label: '1' } },
{ id: '2', position: { x: 0, y: 100 }, data: { label: '2' } },
];
const initialEdges = [{ id: 'e1-2', source: '1', target: '2' }];
function Flow() {
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect = useCallback((params) => setEdges((eds) => addEdge(params, eds)), [setEdges]);
return (
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
>
<MiniMap />
<Controls />
<Background />
</ReactFlow>
);
}
export default Flow;
```
## Development
Before you can start developing please make sure that you have [pnpm](https://pnpm.io/) installed (`npm i -g pnpm`). Then install the dependencies using pnpm: `pnpm install`.
Run `pnpm build` once and then you can use `pnpm dev` for local development.
## Testing
Testing is done with cypress. You can find the tests in the [`examples/vite-app/cypress`](/examples/vite-app/cypress/) folder. In order to run the tests do:
```sh
pnpm test
```
## xyflow Team
React Flow is maintained by the team behind [xyflow](https://xyflow.com). If you need help or want to talk to us about a collaboration, reach out through our [contact form](https://xyflow.com/contact) or by joining our [Discord Server](https://discord.gg/Bqt6xrs).
- Christopher • [Twitter](https://twitter.com/chrtze) • [Github](https://github.com/chrtze)
- Hayleigh • [Twitter](https://twitter.com/hayleighdotdev) • [Github](https://github.com/hayleigh-dot-dev)
- John • [Website](https://johnrobbdesign.com/) • [Mastodon](https://mastodon.social/@johnrobbjr)
- Moritz • [Twitter](https://twitter.com/moklick) • [Github](https://github.com/moklick)
- Peter • [Github](https://github.com/peterkogo)
Any support you provide goes directly towards the development and maintenance of React Flow and Svelte Flow, allowing us to continue to operate as an independent company, working on what we think is best for our open-source libraries.
## Community Packages
- [useUndoable](https://github.com/xplato/useUndoable) - Hook for undo/redo functionality with an explicit React Flow example
- [react-flow-smart-edge](https://github.com/tisoap/react-flow-smart-edge) - Custom edge that doesn't intersect with nodes
- [Feliz.ReactFlow](https://github.com/tforkmann/Feliz.ReactFlow) - Feliz React Bindings for React Flow
## Credits
React Flow was initially developed for [datablocks](https://datablocks.pro), a graph-based editor for transforming, analyzing and visualizing data in the browser. Under the hood, React Flow depends on these great libraries:
- [d3-zoom](https://github.com/d3/d3-zoom) - used for zoom, pan and drag interactions with the graph canvas
- [d3-drag](https://github.com/d3/d3-drag) - used for making the nodes draggable
- [zustand](https://github.com/pmndrs/zustand) - internal state management
## License
React Flow is [MIT licensed](../../LICENSE).
@@ -1,4 +1,4 @@
import { memo, useEffect, useState, type FC, type PropsWithChildren } from 'react'; import { memo, type FC, type PropsWithChildren } from 'react';
import cc from 'classcat'; import cc from 'classcat';
import { shallow } from 'zustand/shallow'; import { shallow } from 'zustand/shallow';
@@ -37,18 +37,9 @@ const Controls: FC<PropsWithChildren<ControlProps>> = ({
position = 'bottom-left', position = 'bottom-left',
}) => { }) => {
const store = useStoreApi(); const store = useStoreApi();
const [isVisible, setIsVisible] = useState<boolean>(false);
const { isInteractive, minZoomReached, maxZoomReached } = useStore(selector, shallow); const { isInteractive, minZoomReached, maxZoomReached } = useStore(selector, shallow);
const { zoomIn, zoomOut, fitView } = useReactFlow(); const { zoomIn, zoomOut, fitView } = useReactFlow();
useEffect(() => {
setIsVisible(true);
}, []);
if (!isVisible) {
return null;
}
const onZoomInHandler = () => { const onZoomInHandler = () => {
zoomIn(); zoomIn();
onZoomIn?.(); onZoomIn?.();
@@ -52,6 +52,8 @@ export default (NodeComponent: ComponentType<NodeProps>) => {
disableKeyboardA11y, disableKeyboardA11y,
ariaLabel, ariaLabel,
rfId, rfId,
sizeWidth,
sizeHeight,
}: WrapNodeProps) => { }: WrapNodeProps) => {
const store = useStoreApi(); const store = useStoreApi();
const nodeRef = useRef<HTMLDivElement>(null); const nodeRef = useRef<HTMLDivElement>(null);
@@ -70,7 +72,8 @@ export default (NodeComponent: ComponentType<NodeProps>) => {
const { selectNodesOnDrag, nodeDragThreshold } = store.getState(); const { selectNodesOnDrag, nodeDragThreshold } = store.getState();
if (isSelectable && (!selectNodesOnDrag || !isDraggable || nodeDragThreshold > 0)) { if (isSelectable && (!selectNodesOnDrag || !isDraggable || nodeDragThreshold > 0)) {
// this handler gets called within the drag start event when selectNodesOnDrag=true // this handler gets called by XYDrag on drag start when selectNodesOnDrag=true
// here we only need to call it when selectNodesOnDrag=false
handleNodeClick({ handleNodeClick({
id, id,
store, store,
@@ -183,6 +186,8 @@ export default (NodeComponent: ComponentType<NodeProps>) => {
transform: `translate(${xPosOrigin}px,${yPosOrigin}px)`, transform: `translate(${xPosOrigin}px,${yPosOrigin}px)`,
pointerEvents: hasPointerEvents ? 'all' : 'none', pointerEvents: hasPointerEvents ? 'all' : 'none',
visibility: initialized ? 'visible' : 'hidden', visibility: initialized ? 'visible' : 'hidden',
width: sizeWidth,
height: sizeHeight,
...style, ...style,
}} }}
data-id={id} data-id={id}
@@ -1,20 +1,40 @@
import { useRef, type FC, type PropsWithChildren } from 'react'; import { useRef, type ReactNode } from 'react';
import { type StoreApi } from 'zustand'; import { type StoreApi } from 'zustand';
import { UseBoundStoreWithEqualityFn } from 'zustand/traditional'; import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
import { Provider } from '../../contexts/RFStoreContext'; import { Provider } from '../../contexts/RFStoreContext';
import { createRFStore } from '../../store'; import { createRFStore } from '../../store';
import type { ReactFlowState } from '../../types'; import type { ReactFlowState, Node, Edge } from '../../types';
const ReactFlowProvider: FC<PropsWithChildren<unknown>> = ({ children }) => { function ReactFlowProvider({
children,
initialNodes,
initialEdges,
initialWidth,
initialHeight,
fitView,
}: {
children: ReactNode;
initialNodes?: Node[];
initialEdges?: Edge[];
initialWidth?: number;
initialHeight?: number;
fitView?: boolean;
}) {
const storeRef = useRef<UseBoundStoreWithEqualityFn<StoreApi<ReactFlowState>> | null>(null); const storeRef = useRef<UseBoundStoreWithEqualityFn<StoreApi<ReactFlowState>> | null>(null);
if (!storeRef.current) { if (!storeRef.current) {
storeRef.current = createRFStore(); storeRef.current = createRFStore({
nodes: initialNodes,
edges: initialEdges,
width: initialWidth,
height: initialHeight,
fitView,
});
} }
return <Provider value={storeRef.current}>{children}</Provider>; return <Provider value={storeRef.current}>{children}</Provider>;
}; }
ReactFlowProvider.displayName = 'ReactFlowProvider'; ReactFlowProvider.displayName = 'ReactFlowProvider';
@@ -1,7 +1,7 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { StoreApi } from 'zustand'; import { StoreApi } from 'zustand';
import { shallow } from 'zustand/shallow'; import { shallow } from 'zustand/shallow';
import type { CoordinateExtent } from '@xyflow/system'; import { devWarn, type CoordinateExtent } from '@xyflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore'; import { useStore, useStoreApi } from '../../hooks/useStore';
import type { Node, Edge, ReactFlowState, ReactFlowProps, ReactFlowStore } from '../../types'; import type { Node, Edge, ReactFlowState, ReactFlowProps, ReactFlowStore } from '../../types';
@@ -201,7 +201,7 @@ const StoreUpdater = ({
useDirectStoreUpdater('rfId', rfId, store.setState); useDirectStoreUpdater('rfId', rfId, store.setState);
useDirectStoreUpdater('autoPanOnConnect', autoPanOnConnect, store.setState); useDirectStoreUpdater('autoPanOnConnect', autoPanOnConnect, store.setState);
useDirectStoreUpdater('autoPanOnNodeDrag', autoPanOnNodeDrag, store.setState); useDirectStoreUpdater('autoPanOnNodeDrag', autoPanOnNodeDrag, store.setState);
useDirectStoreUpdater('onError', onError, store.setState); useDirectStoreUpdater('onError', onError || devWarn, store.setState);
useDirectStoreUpdater('connectionRadius', connectionRadius, store.setState); useDirectStoreUpdater('connectionRadius', connectionRadius, store.setState);
useDirectStoreUpdater('isValidConnection', isValidConnection, store.setState); useDirectStoreUpdater('isValidConnection', isValidConnection, store.setState);
useDirectStoreUpdater('selectNodesOnDrag', selectNodesOnDrag, store.setState); useDirectStoreUpdater('selectNodesOnDrag', selectNodesOnDrag, store.setState);
@@ -62,23 +62,13 @@ const EdgeRenderer = ({
onEdgeUpdateEnd, onEdgeUpdateEnd,
children, children,
}: EdgeRendererProps) => { }: EdgeRendererProps) => {
const { width, height, edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow); const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
const edgeTree = useVisibleEdges(onlyRenderVisibleElements, elevateEdgesOnSelect); const edgeTree = useVisibleEdges(onlyRenderVisibleElements, elevateEdgesOnSelect);
if (!width) {
return null;
}
return ( return (
<> <>
{edgeTree.map(({ level, edges, isMaxLevel }) => ( {edgeTree.map(({ level, edges, isMaxLevel }) => (
<svg <svg key={level} style={{ zIndex: level }} className="react-flow__edges react-flow__container">
key={level}
style={{ zIndex: level }}
width={width}
height={height}
className="react-flow__edges react-flow__container"
>
{isMaxLevel && <MarkerDefinitions defaultColor={defaultMarkerColor} rfId={rfId} />} {isMaxLevel && <MarkerDefinitions defaultColor={defaultMarkerColor} rfId={rfId} />}
<g> <g>
{edges.map((edge) => { {edges.map((edge) => {
@@ -17,6 +17,7 @@ export function useNodeOrEdgeTypes(nodeOrEdgeTypes: any, createTypes: any): any
const typesParsed = useMemo(() => { const typesParsed = useMemo(() => {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const typeKeys = Object.keys(nodeOrEdgeTypes); const typeKeys = Object.keys(nodeOrEdgeTypes);
if (shallow(typesKeysRef.current, typeKeys)) { if (shallow(typesKeysRef.current, typeKeys)) {
store.getState().onError?.('002', errorMessages['error002']()); store.getState().onError?.('002', errorMessages['error002']());
} }
@@ -98,6 +98,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
height: node.height ?? 0, height: node.height ?? 0,
origin: node.origin || props.nodeOrigin, origin: node.origin || props.nodeOrigin,
}); });
const initialized = (!!node.width && !!node.height) || (!!node.size?.width && !!node.size?.height);
return ( return (
<NodeComponent <NodeComponent
@@ -105,6 +106,8 @@ const NodeRenderer = (props: NodeRendererProps) => {
id={node.id} id={node.id}
className={node.className} className={node.className}
style={node.style} style={node.style}
sizeWidth={node.size?.width}
sizeHeight={node.size?.height}
type={nodeType} type={nodeType}
data={node.data} data={node.data}
sourcePosition={node.sourcePosition || Position.Bottom} sourcePosition={node.sourcePosition || Position.Bottom}
@@ -131,7 +134,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
isParent={!!node[internalsSymbol]?.isParent} isParent={!!node[internalsSymbol]?.isParent}
noDragClassName={props.noDragClassName} noDragClassName={props.noDragClassName}
noPanClassName={props.noPanClassName} noPanClassName={props.noPanClassName}
initialized={!!node.width && !!node.height} initialized={initialized}
rfId={props.rfId} rfId={props.rfId}
disableKeyboardA11y={props.disableKeyboardA11y} disableKeyboardA11y={props.disableKeyboardA11y}
ariaLabel={node.ariaLabel} ariaLabel={node.ariaLabel}
@@ -1,9 +1,24 @@
import { useContext, type FC, type PropsWithChildren } from 'react'; import { useContext, type ReactNode } from 'react';
import StoreContext from '../../contexts/RFStoreContext'; import StoreContext from '../../contexts/RFStoreContext';
import ReactFlowProvider from '../../components/ReactFlowProvider'; import ReactFlowProvider from '../../components/ReactFlowProvider';
import type { Node, Edge } from '../../types';
const Wrapper: FC<PropsWithChildren<unknown>> = ({ children }) => { function Wrapper({
children,
nodes,
edges,
width,
height,
fitView,
}: {
children: ReactNode;
nodes?: Node[];
edges?: Edge[];
width?: number;
height?: number;
fitView?: boolean;
}) {
const isWrapped = useContext(StoreContext); const isWrapped = useContext(StoreContext);
if (isWrapped) { if (isWrapped) {
@@ -12,8 +27,18 @@ const Wrapper: FC<PropsWithChildren<unknown>> = ({ children }) => {
return <>{children}</>; return <>{children}</>;
} }
return <ReactFlowProvider>{children}</ReactFlowProvider>; return (
}; <ReactFlowProvider
initialNodes={nodes}
initialEdges={edges}
initialWidth={width}
initialHeight={height}
fitView={fitView}
>
{children}
</ReactFlowProvider>
);
}
Wrapper.displayName = 'ReactFlowWrapper'; Wrapper.displayName = 'ReactFlowWrapper';
@@ -166,6 +166,8 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
nodeDragThreshold, nodeDragThreshold,
viewport, viewport,
onViewportChange, onViewportChange,
width,
height,
...rest ...rest
}, },
ref ref
@@ -181,7 +183,7 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
data-testid="rf__wrapper" data-testid="rf__wrapper"
id={id} id={id}
> >
<Wrapper> <Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}>
<GraphView <GraphView
onInit={onInit} onInit={onInit}
onNodeClick={onNodeClick} onNodeClick={onNodeClick}
+6 -8
View File
@@ -23,14 +23,12 @@ function useDrag({ nodeRef, disabled = false, noDragClassName, handleSelector, n
xyDrag.current = XYDrag({ xyDrag.current = XYDrag({
domNode: nodeRef.current, domNode: nodeRef.current,
getStoreItems: () => store.getState(), getStoreItems: () => store.getState(),
onNodeClick: () => { onNodeMouseDown: (id: string) => {
if (nodeId) { handleNodeClick({
handleNodeClick({ id,
id: nodeId, store,
store, nodeRef: nodeRef as RefObject<HTMLDivElement>,
nodeRef: nodeRef as RefObject<HTMLDivElement>, });
});
}
}, },
onDragStart: () => { onDragStart: () => {
setDragging(true); setDragging(true);
+3 -3
View File
@@ -178,7 +178,7 @@ export default function useReactFlow<NodeData = any, EdgeData = any>(): ReactFlo
const getNodeRect = useCallback( const getNodeRect = useCallback(
( (
nodeOrRect: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect nodeOrRect: Node<NodeData> | { id: Node['id'] } | Rect
): [Rect | null, Node<NodeData> | null | undefined, boolean] => { ): [Rect | null, Node<NodeData> | null | undefined, boolean] => {
const isRect = isRectObject(nodeOrRect); const isRect = isRectObject(nodeOrRect);
const node = isRect ? null : store.getState().nodes.find((n) => n.id === nodeOrRect.id); const node = isRect ? null : store.getState().nodes.find((n) => n.id === nodeOrRect.id);
@@ -211,7 +211,7 @@ export default function useReactFlow<NodeData = any, EdgeData = any>(): ReactFlo
const overlappingArea = getOverlappingArea(currNodeRect, nodeRect); const overlappingArea = getOverlappingArea(currNodeRect, nodeRect);
const partiallyVisible = partially && overlappingArea > 0; const partiallyVisible = partially && overlappingArea > 0;
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!; return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
}); });
}, },
[] []
@@ -228,7 +228,7 @@ export default function useReactFlow<NodeData = any, EdgeData = any>(): ReactFlo
const overlappingArea = getOverlappingArea(nodeRect, area); const overlappingArea = getOverlappingArea(nodeRect, area);
const partiallyVisible = partially && overlappingArea > 0; const partiallyVisible = partially && overlappingArea > 0;
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!; return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
}, },
[] []
); );
+45 -15
View File
@@ -11,7 +11,7 @@ import {
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes'; import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
import { updateNodesAndEdgesSelections } from './utils'; import { updateNodesAndEdgesSelections } from './utils';
import initialState from './initialState'; import getInitialState from './initialState';
import type { import type {
ReactFlowState, ReactFlowState,
Node, Node,
@@ -24,10 +24,22 @@ import type {
FitViewOptions, FitViewOptions,
} from '../types'; } from '../types';
const createRFStore = () => const createRFStore = ({
nodes,
edges,
width,
height,
fitView,
}: {
nodes?: Node[];
edges?: Edge[];
width?: number;
height?: number;
fitView?: boolean;
}) =>
createWithEqualityFn<ReactFlowState>( createWithEqualityFn<ReactFlowState>(
(set, get) => ({ (set, get) => ({
...initialState, ...getInitialState({ nodes, edges, width, height, fitView }),
setNodes: (nodes: Node[]) => { setNodes: (nodes: Node[]) => {
const { nodes: storeNodes, nodeOrigin, elevateNodesOnSelect } = get(); const { nodes: storeNodes, nodeOrigin, elevateNodesOnSelect } = get();
const nextNodes = updateNodes(nodes, storeNodes, { nodeOrigin, elevateNodesOnSelect }); const nextNodes = updateNodes(nodes, storeNodes, { nodeOrigin, elevateNodesOnSelect });
@@ -45,15 +57,27 @@ const createRFStore = () =>
const hasDefaultNodes = typeof nodes !== 'undefined'; const hasDefaultNodes = typeof nodes !== 'undefined';
const hasDefaultEdges = typeof edges !== 'undefined'; const hasDefaultEdges = typeof edges !== 'undefined';
const nextNodes = hasDefaultNodes const nextState: {
? updateNodes(nodes, [], { nodes?: Node[];
nodeOrigin: get().nodeOrigin, edges?: Edge[];
elevateNodesOnSelect: get().elevateNodesOnSelect, hasDefaultNodes: boolean;
}) hasDefaultEdges: boolean;
: []; } = {
const nextEdges = hasDefaultEdges ? edges : []; hasDefaultNodes,
hasDefaultEdges,
};
set({ nodes: nextNodes, edges: nextEdges, hasDefaultNodes, hasDefaultEdges }); if (hasDefaultNodes) {
nextState.nodes = updateNodes(nodes, [], {
nodeOrigin: get().nodeOrigin,
elevateNodesOnSelect: get().elevateNodesOnSelect,
});
}
if (hasDefaultEdges) {
nextState.edges = edges;
}
set(nextState);
}, },
updateNodeDimensions: (updates) => { updateNodeDimensions: (updates) => {
const { onNodesChange, fitView, nodes, fitViewOnInit, fitViewDone, fitViewOnInitOptions, domNode, nodeOrigin } = const { onNodesChange, fitView, nodes, fitViewOnInit, fitViewDone, fitViewOnInitOptions, domNode, nodeOrigin } =
@@ -263,9 +287,9 @@ const createRFStore = () =>
}, },
cancelConnection: () => cancelConnection: () =>
set({ set({
connectionStatus: initialState.connectionStatus, connectionStatus: null,
connectionStartHandle: initialState.connectionStartHandle, connectionStartHandle: null,
connectionEndHandle: initialState.connectionEndHandle, connectionEndHandle: null,
}), }),
updateConnection: (params) => { updateConnection: (params) => {
const { connectionStatus, connectionStartHandle, connectionEndHandle, connectionPosition } = get(); const { connectionStatus, connectionStartHandle, connectionEndHandle, connectionPosition } = get();
@@ -279,7 +303,13 @@ const createRFStore = () =>
set(currentConnection); set(currentConnection);
}, },
reset: () => set({ ...initialState }), reset: () => {
// @todo: what should we do about this? Do we still need it?
// if you are on a SPA with multiple flows, we want to make sure that the store gets resetted
// when you switch pages. Does this reset solves this? Currently it always gets called. This
// leads to an emtpy nodes array at the beginning.
// set({ ...getInitialState() });
},
}), }),
Object.is Object.is
); );
+90 -55
View File
@@ -1,65 +1,100 @@
import { devWarn, infiniteExtent, ConnectionMode } from '@xyflow/system'; import {
infiniteExtent,
ConnectionMode,
updateNodes,
getRectOfNodes,
getTransformForBounds,
Transform,
} from '@xyflow/system';
import type { ReactFlowStore } from '../types'; import type { Edge, Node, ReactFlowStore } from '../types';
const initialState: ReactFlowStore = { const getInitialState = ({
rfId: '1', nodes = [],
width: 0, edges = [],
height: 0, width,
transform: [0, 0, 1], height,
nodes: [], fitView,
edges: [], }: {
onNodesChange: null, nodes?: Node[];
onEdgesChange: null, edges?: Edge[];
hasDefaultNodes: false, width?: number;
hasDefaultEdges: false, height?: number;
panZoom: null, fitView?: boolean;
minZoom: 0.5, } = {}): ReactFlowStore => {
maxZoom: 2, const nextNodes = updateNodes(nodes, [], { nodeOrigin: [0, 0], elevateNodesOnSelect: false });
translateExtent: infiniteExtent,
nodeExtent: infiniteExtent,
nodesSelectionActive: false,
userSelectionActive: false,
userSelectionRect: null,
connectionPosition: { x: 0, y: 0 },
connectionStatus: null,
connectionMode: ConnectionMode.Strict,
domNode: null,
paneDragging: false,
noPanClassName: 'nopan',
nodeOrigin: [0, 0],
nodeDragThreshold: 0,
snapGrid: [15, 15], let transform: Transform = [0, 0, 1];
snapToGrid: false,
nodesDraggable: true, if (fitView && width && height) {
nodesConnectable: true, const nodesWithDimensions = nextNodes.map((node) => ({
nodesFocusable: true, ...node,
edgesFocusable: true, width: node.size?.width,
edgesUpdatable: true, height: node.size?.height,
elementsSelectable: true, }));
elevateNodesOnSelect: true, const bounds = getRectOfNodes(nodesWithDimensions, [0, 0]);
fitViewOnInit: false, transform = getTransformForBounds(bounds, width, height, 0.5, 2, 0.1);
fitViewDone: false, }
fitViewOnInitOptions: undefined,
selectNodesOnDrag: true,
multiSelectionActive: false, return {
rfId: '1',
width: 0,
height: 0,
transform,
nodes: nextNodes,
edges: edges,
onNodesChange: null,
onEdgesChange: null,
hasDefaultNodes: false,
hasDefaultEdges: false,
panZoom: null,
minZoom: 0.5,
maxZoom: 2,
translateExtent: infiniteExtent,
nodeExtent: infiniteExtent,
nodesSelectionActive: false,
userSelectionActive: false,
userSelectionRect: null,
connectionPosition: { x: 0, y: 0 },
connectionStatus: null,
connectionMode: ConnectionMode.Strict,
domNode: null,
paneDragging: false,
noPanClassName: 'nopan',
nodeOrigin: [0, 0],
nodeDragThreshold: 0,
connectionStartHandle: null, snapGrid: [15, 15],
connectionEndHandle: null, snapToGrid: false,
connectionClickStartHandle: null,
connectOnClick: true,
ariaLiveMessage: '', nodesDraggable: true,
autoPanOnConnect: true, nodesConnectable: true,
autoPanOnNodeDrag: true, nodesFocusable: true,
connectionRadius: 20, edgesFocusable: true,
onError: devWarn, edgesUpdatable: true,
isValidConnection: undefined, elementsSelectable: true,
elevateNodesOnSelect: true,
fitViewOnInit: false,
fitViewDone: false,
fitViewOnInitOptions: undefined,
selectNodesOnDrag: true,
lib: 'react', multiSelectionActive: false,
connectionStartHandle: null,
connectionEndHandle: null,
connectionClickStartHandle: null,
connectOnClick: true,
ariaLiveMessage: '',
autoPanOnConnect: true,
autoPanOnNodeDrag: true,
connectionRadius: 20,
onError: () => null,
isValidConnection: undefined,
lib: 'react',
};
}; };
export default initialState; export default getInitialState;
+3 -1
View File
@@ -42,7 +42,7 @@ import type {
EdgeMouseHandler, EdgeMouseHandler,
} from '.'; } from '.';
export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & { export type ReactFlowProps = Omit<HTMLAttributes<HTMLDivElement>, 'onError'> & {
nodes?: Node[]; nodes?: Node[];
edges?: Edge[]; edges?: Edge[];
defaultNodes?: Node[]; defaultNodes?: Node[];
@@ -151,6 +151,8 @@ export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
onError?: OnError; onError?: OnError;
isValidConnection?: IsValidConnection; isValidConnection?: IsValidConnection;
nodeDragThreshold?: number; nodeDragThreshold?: number;
width?: number;
height?: number;
}; };
export type ReactFlowRefType = HTMLDivElement; export type ReactFlowRefType = HTMLDivElement;
+7 -7
View File
@@ -10,8 +10,8 @@ export type ReactFlowJsonObject<NodeData = any, EdgeData = any> = {
}; };
export type DeleteElementsOptions = { export type DeleteElementsOptions = {
nodes?: (Partial<Node> & { id: Node['id'] })[]; nodes?: (Node | { id: Node['id'] })[];
edges?: (Partial<Edge> & { id: Edge['id'] })[]; edges?: (Edge | { id: Edge['id'] })[];
}; };
export namespace Instance { export namespace Instance {
@@ -33,18 +33,18 @@ export namespace Instance {
deletedEdges: Edge[]; deletedEdges: Edge[];
}; };
export type GetIntersectingNodes<NodeData> = ( export type GetIntersectingNodes<NodeData> = (
node: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect, node: Node<NodeData> | { id: Node['id'] } | Rect,
partially?: boolean, partially?: boolean,
nodes?: Node<NodeData>[] nodes?: Node<NodeData>[]
) => Node<NodeData>[]; ) => Node<NodeData>[];
export type IsNodeIntersecting<NodeData> = ( export type IsNodeIntersecting<NodeData> = (
node: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect, node: Node<NodeData> | { id: Node['id'] } | Rect,
area: Rect, area: Rect,
partially?: boolean partially?: boolean
) => boolean; ) => boolean;
export type getConnectedEdges = (id: string | (Partial<Node> & { id: Node['id'] })[]) => Edge[]; export type getConnectedEdges = (id: string | (Node | { id: Node['id'] })[]) => Edge[];
export type getIncomers = (node: string | (Partial<Node> & { id: Node['id'] })) => Node[]; export type getIncomers = (node: string | Node | { id: Node['id'] }) => Node[];
export type getOutgoers = (node: string | (Partial<Node> & { id: Node['id'] })) => Node[]; export type getOutgoers = (node: string | Node | { id: Node['id'] }) => Node[];
} }
export type ReactFlowInstance<NodeData = any, EdgeData = any> = { export type ReactFlowInstance<NodeData = any, EdgeData = any> = {
+2
View File
@@ -40,4 +40,6 @@ export type WrapNodeProps<NodeData = any> = Pick<
noPanClassName: string; noPanClassName: string;
rfId: string; rfId: string;
disableKeyboardA11y: boolean; disableKeyboardA11y: boolean;
sizeWidth?: number;
sizeHeight?: number;
}; };
+9
View File
@@ -1,3 +1,12 @@
## 0.0.25
- add `toObject` to `useSvelteFlow` hook
- export `BezierEdge`, `StepEdge` and `SmoothStepEdge` components
- handle window resize (Minimap updates its viewport)
- fix wrongly selected nodes
- fix connection line z-index
- fix broken edges (`interactionWidth` was missing)
## 0.0.24 ## 0.0.24
- update node automatically when `type`, `sourcePosition` or `targetPosition` option changes - update node automatically when `type`, `sourcePosition` or `targetPosition` option changes
+38 -13
View File
@@ -1,6 +1,27 @@
# Svelte Flow (alpha) ![readme-header](https://user-images.githubusercontent.com/2857535/279691030-dd853bef-88c5-433b-a51a-10294dc82d2b.svg#gh-light-mode-only)
![readme-header-dark](https://user-images.githubusercontent.com/2857535/279691048-accf12e0-da89-4c79-8d66-dee0c43585cd.svg#gh-dark-mode-only)
Svelte Flow is a highly customizable component for building interactive graphs and node-based editors, built by the creators of React Flow. **This package is currently under heavy development and the API is very likely to change.** <div align="center">
![GitHub License MIT](https://img.shields.io/github/license/wbkd/react-flow?color=%23ff0072)
![npm downloads](https://img.shields.io/npm/dt/@xyflow/svelte?color=%23FF0072&label=downloads)
Svelte Flow is a highly customizable component for building interactive graphs and node-based editors, built by the creators of React Flow.
☣️ **Svelte Flow is still alpha and currently under heavy development. The API is relatively stable but some things might change.** ☣️
[🚀 Getting Started](https://svelteflow.dev/learn) | [📖 Documentation](https://svelteflow.dev/api-reference/svelte-flow) | [📺 Examples](https://svelteflow.dev/examples/overview) | [☎️ Discord](https://discord.gg/RVmnytFmGW)
</div>
## Key Features
- **Easy to use:** Seamless zooming and panning, single- and multi selection of graph elements and keyboard shortcuts are supported out of the box
- **Customizable:** Different [node](https://svelteflow.dev/examples) and [edge types](https://svelteflow.dev/examples/edges/edge-types) and support for custom nodes with multiple handles and custom edges
- **Fast rendering:** Only nodes that have changed are re-rendered
- **Hooks and Utils:** [Hooks](https://svelteflow.dev/api-reference/hooks) for handling nodes, edges and the viewport and graph [helper functions](https://svelteflow.dev/api-reference/utils)
- **Plugin Components:** [Background](https://svelteflow.dev/api-reference/components/background), [MiniMap](https://svelteflow.dev/api-reference/components/minimap) and [Controls](https://svelteflow.dev/api-reference/components/controls)
- **Reliable**: Written in [Typescript](https://www.typescriptlang.org) and tested with [Playwright](https://www.playwright.dev)
## Installation ## Installation
@@ -10,14 +31,9 @@ The easiest way to get the latest version of Svelte Flow is to install it via np
npm install @xyflow/svelte npm install @xyflow/svelte
``` ```
What is “xyflow”? Learn more [here](https://wbkd.notion.site/Upcoming-Changes-at-React-Flow-1a443641891a4069927c0a115e915251).
## Getting started ## Getting started
We are working on a new website and everything so there are no docs for Svelte Flow yet. Everything is typed, so your IDE should help you a bit and you can also the [React Flow docs](https://reactflow.dev/docs) because the API is very similar. You can also check out the [Svelte Flow examples](https://github.com/wbkd/react-flow/tree/xyflow/packages/svelte/src/routes) in this repo. You only need a few lines to get a fully interactive (e.g. select and drag nodes or pan and zoom) flow. If you want to learn more, please refer to the [learn section](https://svelteflow.dev/learn), the [examples](https://svelteflow.dev/examples) or the [API reference](https://svelteflow.dev/api-reference).
If you want to start right away you can check out the [Svelte Flow examples Stackblitz project](https://stackblitz.com/edit/svelte-flow-examples?file=src%2Froutes%2Foverview%2F%2Bpage.svelte).
A basic flow looks like this:
```svelte ```svelte
<script lang="ts"> <script lang="ts">
@@ -34,8 +50,7 @@ A basic flow looks like this:
// if you just want to load the basic styleds, you can import '@xyflow/svelte/dist/base.css' // if you just want to load the basic styleds, you can import '@xyflow/svelte/dist/base.css'
import '@xyflow/svelte/dist/style.css' import '@xyflow/svelte/dist/style.css'
// We are using writables for the nodes and edges to sync them easily. When a user drags a node for example, Svelte Flow updates its position. // We are using writables for the nodes and edges to sync them easily. When a user drags a node for example, Svelte Flow updates its position. This also makes it easier to update nodes in user land.
// This also makes it easier to update nodes in user land.
const nodes = writable([ const nodes = writable([
{ {
id: '1', id: '1',
@@ -77,13 +92,13 @@ A basic flow looks like this:
## How to Contribute ## How to Contribute
**Show us what you make:** Drop it in into our [Discord Server](https://discord.com/invite/Bqt6xrs), [tweet](https://twitter.com/reactflowdev) at us, or email us at info@reactflow.dev **Show us what you make:** Drop it in into our [Discord Server](https://discord.com/invite/Bqt6xrs), [tweet](https://twitter.com/reactflowdev) at us, or email us at info@xyflow.com
**Community Participation:** Ask and answer questions in our [Discord Server](https://discord.com/invite/Bqt6xrs) or jump in on Github discussions. **Community Participation:** Ask and answer questions in our [Discord Server](https://discord.com/invite/Bqt6xrs) or jump in on Github discussions.
**Squash Bugs:** We cant catch them all. Check existing issues and discussions first, then create a new issue to tell us whats up. **Squash Bugs:** We cant catch them all. Check existing issues and discussions first, then create a new issue to tell us whats up.
**Financial Support:** If you are an organization who wants to make sure Svelte Flow continues to be maintained, reach out to us at info@reactflow.dev **Financial Support:** If you are an organization who wants to make sure Svelte Flow continues to be maintained, reach out to us at info@xyflow.com
And of course, we love Github stars ⭐ And of course, we love Github stars ⭐
@@ -99,6 +114,16 @@ If you want to check out the current version you need to run the following comma
You can now access the examples under http://127.0.0.1:5173 You can now access the examples under http://127.0.0.1:5173
## Maintainers
Svelte Flow is maintained by the team behind [xyflow](https://xyflow.com). If you need help or want to talk to us about a collaboration, reach out through our [contact form](https://xyflow.com/contact) or by joining our [Discord Server](https://discord.gg/Bqt6xrs).
- Christopher • [Twitter](https://twitter.com/chrtze) • [Github](https://github.com/chrtze)
- Hayleigh • [Twitter](https://twitter.com/hayleighdotdev) • [Github](https://github.com/hayleigh-dot-dev)
- John • [Website](https://johnrobbdesign.com/) • [Mastodon](https://mastodon.social/@johnrobbjr)
- Moritz • [Twitter](https://twitter.com/moklick) • [Github](https://github.com/moklick)
- Peter • [Github](https://github.com/peterkogo)
# License # License
Svelte Flow is MIT Licensed. Svelte Flow is [MIT licensed](../../LICENSE).
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@xyflow/svelte", "name": "@xyflow/svelte",
"version": "0.0.24", "version": "0.0.26",
"description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.", "description": "Svelte Flow - A highly customizable Svelte library for building node-based editors, workflow systems, diagrams and more.",
"keywords": [ "keywords": [
"svelte", "svelte",
@@ -13,15 +13,17 @@ export type UseDragParams = {
onDrag?: OnDrag; onDrag?: OnDrag;
onDragStart?: OnDrag; onDragStart?: OnDrag;
onDragStop?: OnDrag; onDragStop?: OnDrag;
onNodeMouseDown?: (id: string) => void;
}; };
export default function drag(domNode: Element, params: UseDragParams) { export default function drag(domNode: Element, params: UseDragParams) {
const { store, onDrag, onDragStart, onDragStop } = params; const { store, onDrag, onDragStart, onDragStop, onNodeMouseDown } = params;
const dragInstance = XYDrag({ const dragInstance = XYDrag({
domNode, domNode,
onDrag, onDrag,
onDragStart, onDragStart,
onDragStop, onDragStop,
onNodeMouseDown,
getStoreItems: () => { getStoreItems: () => {
const snapGrid = get(store.snapGrid); const snapGrid = get(store.snapGrid);
const vp = get(store.viewport); const vp = get(store.viewport);
@@ -33,7 +35,7 @@ export default function drag(domNode: Element, params: UseDragParams) {
snapGrid: snapGrid ? snapGrid : [0, 0], snapGrid: snapGrid ? snapGrid : [0, 0],
snapToGrid: !!snapGrid, snapToGrid: !!snapGrid,
nodeOrigin: [0, 0], nodeOrigin: [0, 0],
multiSelectionActive: false, multiSelectionActive: get(store.multiselectionKeyPressed),
domNode: get(store.domNode), domNode: get(store.domNode),
transform: [vp.x, vp.y, vp.zoom], transform: [vp.x, vp.y, vp.zoom],
autoPanOnNodeDrag: get(store.autoPanOnNodeDrag), autoPanOnNodeDrag: get(store.autoPanOnNodeDrag),
@@ -12,10 +12,10 @@
<Panel <Panel
{position} {position}
class="svelte-flow__attribution" class="svelte-flow__attribution"
data-message="Please only hide this attribution when you are subscribed to Svelte Flow Pro: https://pro.reactflow.dev" data-message="Feel free to remove the attribution or check out how you could support us: https://svelteflow.dev/support-us"
> >
<a <a
href="https://reactflow.dev/svelte" href="https://svelteflow.dev"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
aria-label="Svelte Flow attribution" aria-label="Svelte Flow attribution"
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import cc from 'classcat';
import { EdgeLabelRenderer } from '$lib/components/EdgeLabelRenderer'; import { EdgeLabelRenderer } from '$lib/components/EdgeLabelRenderer';
import type { BaseEdgeProps } from './types'; import type { BaseEdgeProps } from './types';
@@ -16,23 +17,26 @@
export let interactionWidth: $$Props['interactionWidth'] = 20; export let interactionWidth: $$Props['interactionWidth'] = 20;
let className: $$Props['class'] = undefined; let className: $$Props['class'] = undefined;
export { className as class }; export { className as class };
// @todo, why is interactionWidth undefined after first re-render?
let interactionWidthValue = interactionWidth === undefined ? 20 : interactionWidth;
</script> </script>
<path <path
d={path} d={path}
{id} {id}
class="svelte-flow__edge-path" class={cc(['svelte-flow__edge-path', className])}
marker-start={markerStart} marker-start={markerStart}
marker-end={markerEnd} marker-end={markerEnd}
fill="none" fill="none"
{style} {style}
/> />
{#if interactionWidth} {#if interactionWidthValue}
<path <path
d={path} d={path}
stroke-opacity={0} stroke-opacity={0}
stroke-width={interactionWidth} stroke-width={interactionWidthValue}
fill="none" fill="none"
class="svelte-flow__edge-interaction" class="svelte-flow__edge-interaction"
/> />
@@ -1,12 +1,14 @@
<svelte:options immutable /> <svelte:options immutable />
<script lang="ts"> <script lang="ts">
import cc from 'classcat';
import { createEventDispatcher } from 'svelte'; import { createEventDispatcher } from 'svelte';
import { getMarkerId } from '@xyflow/system'; import { errorMessages, getMarkerId } from '@xyflow/system';
import { useStore } from '$lib/store'; import { useStore } from '$lib/store';
import BezierEdge from '$lib/components/edges/BezierEdge.svelte'; import BezierEdge from '$lib/components/edges/BezierEdge.svelte';
import type { EdgeLayouted, Edge } from '$lib/types'; import type { EdgeLayouted, Edge } from '$lib/types';
import { get } from 'svelte/store';
type $$Props = EdgeLayouted; type $$Props = EdgeLayouted;
@@ -34,11 +36,22 @@
export let sourcePosition: $$Props['sourcePosition']; export let sourcePosition: $$Props['sourcePosition'];
export let targetPosition: $$Props['targetPosition']; export let targetPosition: $$Props['targetPosition'];
export let ariaLabel: $$Props['ariaLabel'] = undefined; export let ariaLabel: $$Props['ariaLabel'] = undefined;
export let interactionWidth: $$Props['interactionWidth'] = undefined;
// @ todo: support edge updates // @ todo: support edge updates
let className: string = ''; let className: string = '';
export { className as class }; export { className as class };
const { edges, edgeTypes, flowId, addSelectedEdges } = useStore(); const {
edges,
edgeTypes,
flowId,
selectionRect,
selectionRectMode,
multiselectionKeyPressed,
addSelectedEdges,
unselectNodesAndEdges
} = useStore();
const dispatch = createEventDispatcher<{ const dispatch = createEventDispatcher<{
edgeclick: { edge: Edge; event: MouseEvent | TouchEvent }; edgeclick: { edge: Edge; event: MouseEvent | TouchEvent };
edgecontextmenu: { edge: Edge; event: MouseEvent }; edgecontextmenu: { edge: Edge; event: MouseEvent };
@@ -49,15 +62,25 @@
$: markerEndUrl = markerEnd ? `url(#${getMarkerId(markerEnd, $flowId)})` : undefined; $: markerEndUrl = markerEnd ? `url(#${getMarkerId(markerEnd, $flowId)})` : undefined;
function onClick(event: MouseEvent | TouchEvent) { function onClick(event: MouseEvent | TouchEvent) {
if (selectable) {
addSelectedEdges([id]);
}
const edge = $edges.find((e) => e.id === id); const edge = $edges.find((e) => e.id === id);
if (edge) { if (!edge) {
dispatch('edgeclick', { event, edge }); console.warn('012', errorMessages['error012'](id));
return;
} }
if (selectable) {
selectionRect.set(null);
selectionRectMode.set(null);
if (!edge.selected) {
addSelectedEdges([id]);
} else if (edge.selected && get(multiselectionKeyPressed)) {
unselectNodesAndEdges({ nodes: [], edges: [edge] });
}
}
dispatch('edgeclick', { event, edge });
} }
function onContextMenu(event: MouseEvent) { function onContextMenu(event: MouseEvent) {
@@ -73,7 +96,7 @@
<!-- svelte-ignore a11y-no-noninteractive-element-interactions --> <!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
{#if !hidden} {#if !hidden}
<g <g
class="svelte-flow__edge {className}" class={cc(['svelte-flow__edge', className])}
class:animated class:animated
class:selected class:selected
data-id={id} data-id={id}
@@ -103,6 +126,7 @@
{labelStyle} {labelStyle}
{data} {data}
{style} {style}
{interactionWidth}
sourceHandleId={sourceHandle} sourceHandleId={sourceHandle}
targetHandleId={targetHandle} targetHandleId={targetHandle}
markerStart={markerStartUrl} markerStart={markerStartUrl}
@@ -4,14 +4,21 @@
import { useStore } from '$lib/store'; import { useStore } from '$lib/store';
import type { KeyHandlerProps } from './types'; import type { KeyHandlerProps } from './types';
import type { KeyDefinition, KeyDefinitionObject } from '$lib/types'; import type { KeyDefinition, KeyDefinitionObject } from '$lib/types';
import { isMacOs } from '@xyflow/system';
type $$Props = KeyHandlerProps; type $$Props = KeyHandlerProps;
export let selectionKey: $$Props['selectionKey'] = 'Shift'; export let selectionKey: $$Props['selectionKey'] = 'Shift';
export let multiSelectionKey: $$Props['multiSelectionKey'] = isMacOs() ? 'Meta' : 'Control';
export let deleteKey: $$Props['deleteKey'] = 'Backspace'; export let deleteKey: $$Props['deleteKey'] = 'Backspace';
export let panActivationKey: $$Props['panActivationKey'] = ' '; export let panActivationKey: $$Props['panActivationKey'] = ' ';
const { selectionKeyPressed, deleteKeyPressed, panActivationKeyPressed } = useStore(); const {
selectionKeyPressed,
multiselectionKeyPressed,
deleteKeyPressed,
panActivationKeyPressed
} = useStore();
function isKeyObject(key?: KeyDefinition): key is KeyDefinitionObject { function isKeyObject(key?: KeyDefinition): key is KeyDefinitionObject {
return typeof key === 'object'; return typeof key === 'object';
@@ -20,6 +27,10 @@
$: selectionKeyString = typeof selectionKey === 'string' ? selectionKey : selectionKey!.key; $: selectionKeyString = typeof selectionKey === 'string' ? selectionKey : selectionKey!.key;
$: selectionKeyModifier = isKeyObject(selectionKey) ? selectionKey?.modifier : []; $: selectionKeyModifier = isKeyObject(selectionKey) ? selectionKey?.modifier : [];
$: multiSelectionKeyString =
typeof multiSelectionKey === 'string' ? multiSelectionKey : multiSelectionKey!.key;
$: multiSelectionKeyModifier = isKeyObject(multiSelectionKey) ? multiSelectionKey?.modifier : [];
$: deleteKeyString = typeof deleteKey === 'string' ? deleteKey : deleteKey!.key; $: deleteKeyString = typeof deleteKey === 'string' ? deleteKey : deleteKey!.key;
$: deleteKeyModifier = isKeyObject(deleteKey) ? deleteKey?.modifier : []; $: deleteKeyModifier = isKeyObject(deleteKey) ? deleteKey?.modifier : [];
@@ -49,6 +60,26 @@
], ],
type: 'keyup' type: 'keyup'
}} }}
use:shortcut={{
trigger: [
{
key: multiSelectionKeyString,
modifier: multiSelectionKeyModifier,
callback: () => multiselectionKeyPressed.set(true)
}
],
type: 'keydown'
}}
use:shortcut={{
trigger: [
{
key: multiSelectionKeyString,
modifier: multiSelectionKeyModifier,
callback: () => multiselectionKeyPressed.set(false)
}
],
type: 'keyup'
}}
use:shortcut={{ use:shortcut={{
trigger: [ trigger: [
{ {
@@ -2,6 +2,7 @@ import type { KeyDefinition } from '$lib/types';
export type KeyHandlerProps = { export type KeyHandlerProps = {
selectionKey?: KeyDefinition; selectionKey?: KeyDefinition;
multiSelectionKey?: KeyDefinition;
deleteKey?: KeyDefinition; deleteKey?: KeyDefinition;
panActivationKey?: KeyDefinition; panActivationKey?: KeyDefinition;
}; };
@@ -8,8 +8,8 @@
SvelteComponent, SvelteComponent,
type ComponentType type ComponentType
} from 'svelte'; } from 'svelte';
import cc from 'classcat';
import { get, writable } from 'svelte/store'; import { get, writable } from 'svelte/store';
import cc from 'classcat';
import { errorMessages, Position, type NodeProps } from '@xyflow/system'; import { errorMessages, Position, type NodeProps } from '@xyflow/system';
import drag from '$lib/actions/drag'; import drag from '$lib/actions/drag';
@@ -39,11 +39,18 @@
export let targetPosition: NodeWrapperProps['targetPosition'] = undefined; export let targetPosition: NodeWrapperProps['targetPosition'] = undefined;
export let zIndex: NodeWrapperProps['zIndex']; export let zIndex: NodeWrapperProps['zIndex'];
export let dragHandle: NodeWrapperProps['dragHandle'] = undefined; export let dragHandle: NodeWrapperProps['dragHandle'] = undefined;
export let initialized: NodeWrapperProps['initialized'] = false;
let className: string = ''; let className: string = '';
export { className as class }; export { className as class };
const store = useStore(); const store = useStore();
const { nodeTypes, nodeDragThreshold, addSelectedNodes, updateNodeDimensions } = store; const {
nodeTypes,
nodeDragThreshold,
selectNodesOnDrag,
handleNodeSelection,
updateNodeDimensions
} = store;
const nodeType = type || 'default'; const nodeType = type || 'default';
let nodeRef: HTMLDivElement; let nodeRef: HTMLDivElement;
@@ -55,7 +62,6 @@
const nodeComponent: ComponentType<SvelteComponent<NodeProps>> = const nodeComponent: ComponentType<SvelteComponent<NodeProps>> =
$nodeTypes[nodeType] || DefaultNode; $nodeTypes[nodeType] || DefaultNode;
const selectNodesOnDrag = false;
const dispatch = createEventDispatcher<{ const dispatch = createEventDispatcher<{
nodeclick: { node: Node; event: MouseEvent | TouchEvent }; nodeclick: { node: Node; event: MouseEvent | TouchEvent };
nodecontextmenu: { node: Node; event: MouseEvent | TouchEvent }; nodecontextmenu: { node: Node; event: MouseEvent | TouchEvent };
@@ -112,12 +118,12 @@
}); });
function onSelectNodeHandler(event: MouseEvent | TouchEvent) { function onSelectNodeHandler(event: MouseEvent | TouchEvent) {
if (selectable && (!selectNodesOnDrag || !draggable || get(nodeDragThreshold) > 0)) { if (selectable && (!get(selectNodesOnDrag) || !draggable || get(nodeDragThreshold) > 0)) {
// this handler gets called within the drag start event when selectNodesOnDrag=true // this handler gets called by XYDrag on drag start when selectNodesOnDrag=true
addSelectedNodes([id]); // here we only need to call it when selectNodesOnDrag=false
handleNodeSelection(id);
} }
// @todo: support multiselection
dispatch('nodeclick', { node, event }); dispatch('nodeclick', { node, event });
} }
@@ -134,6 +140,7 @@
disabled: false, disabled: false,
handleSelector: dragHandle, handleSelector: dragHandle,
noDragClass: 'nodrag', noDragClass: 'nodrag',
onNodeMouseDown: handleNodeSelection,
onDrag: (event, _, node, nodes) => { onDrag: (event, _, node, nodes) => {
dispatch('nodedrag', { event, node, nodes }); dispatch('nodedrag', { event, node, nodes });
}, },
@@ -157,7 +164,10 @@
class:parent={isParent} class:parent={isParent}
style:z-index={zIndex} style:z-index={zIndex}
style:transform="translate({positionOrigin?.x ?? 0}px, {positionOrigin?.y ?? 0}px)" style:transform="translate({positionOrigin?.x ?? 0}px, {positionOrigin?.y ?? 0}px)"
{style} style:visibility={initialized ? 'visible' : 'hidden'}
style="{style} {node.size?.width ? `;width=${node.size?.width}px` : ''} {node.size?.height
? `;height=${node.size?.height}px;`
: ''}"
on:click={onSelectNodeHandler} on:click={onSelectNodeHandler}
on:mouseenter={(event) => dispatch('nodemouseenter', { node, event })} on:mouseenter={(event) => dispatch('nodemouseenter', { node, event })}
on:mouseleave={(event) => dispatch('nodemouseleave', { node, event })} on:mouseleave={(event) => dispatch('nodemouseleave', { node, event })}
@@ -27,4 +27,5 @@ export type NodeWrapperProps = Pick<
isParent?: boolean; isParent?: boolean;
zIndex: number; zIndex: number;
node: Node; node: Node;
initialized: boolean;
}; };
@@ -2,8 +2,23 @@
import { onDestroy, setContext } from 'svelte'; import { onDestroy, setContext } from 'svelte';
import { createStore, key } from '$lib/store'; import { createStore, key } from '$lib/store';
import type { SvelteFlowProviderProps } from './types';
const store = createStore(); type $$Props = SvelteFlowProviderProps;
export let initialNodes: $$Props['initialNodes'] = undefined;
export let initialEdges: $$Props['initialEdges'] = undefined;
export let initialWidth: $$Props['initialWidth'] = undefined;
export let initialHeight: $$Props['initialHeight'] = undefined;
export let fitView: $$Props['fitView'] = undefined;
const store = createStore({
nodes: initialNodes,
edges: initialEdges,
width: initialWidth,
height: initialHeight,
fitView
});
setContext(key, { setContext(key, {
getStore: () => store getStore: () => store
@@ -0,0 +1,9 @@
import type { Edge, Node } from '$lib/types';
export type SvelteFlowProviderProps = {
initialNodes?: Node[];
initialEdges?: Edge[];
initialWidth?: number;
initialHeight?: number;
fitView?: boolean;
};
@@ -0,0 +1,4 @@
export { default as BezierEdge } from './BezierEdge.svelte';
export { default as StraightEdge } from './StraightEdge.svelte';
export { default as SmoothStepEdge } from './SmoothStepEdge.svelte';
export { default as StepEdge } from './StepEdge.svelte';
@@ -8,8 +8,6 @@
export let defaultEdgeOptions: DefaultEdgeOptions | undefined; export let defaultEdgeOptions: DefaultEdgeOptions | undefined;
const { const {
width,
height,
elementsSelectable, elementsSelectable,
edgeTree, edgeTree,
edges: { setDefaultOptions } edges: { setDefaultOptions }
@@ -21,7 +19,7 @@
</script> </script>
{#each $edgeTree as group (group.level)} {#each $edgeTree as group (group.level)}
<svg width={$width} height={$height} style="z-index: {group.level}" class="svelte-flow__edges"> <svg style="z-index: {group.level}" class="svelte-flow__edges">
{#if group.isMaxLevel} <MarkerDefinition />{/if} {#if group.isMaxLevel} <MarkerDefinition />{/if}
<g> <g>
{#each group.edges as edge (edge.id)} {#each group.edges as edge (edge.id)}
@@ -53,6 +51,7 @@
sourcePosition={edge.sourcePosition} sourcePosition={edge.sourcePosition}
targetPosition={edge.targetPosition} targetPosition={edge.targetPosition}
ariaLabel={edge.ariaLabel} ariaLabel={edge.ariaLabel}
interactionWidth={edge.interactionWidth}
class={edge.class} class={edge.class}
type={edgeType} type={edgeType}
{selectable} {selectable}
@@ -35,8 +35,8 @@
{@const posOrigin = getPositionWithOrigin({ {@const posOrigin = getPositionWithOrigin({
x: node.positionAbsolute?.x ?? 0, x: node.positionAbsolute?.x ?? 0,
y: node.positionAbsolute?.y ?? 0, y: node.positionAbsolute?.y ?? 0,
width: node.width ?? 0, width: (node.size?.width || node.width) ?? 0,
height: node.height ?? 0, height: (node.size?.height || node.height) ?? 0,
origin: node.origin origin: node.origin
})} })}
<NodeWrapper <NodeWrapper
@@ -65,6 +65,7 @@
dragging={node.dragging} dragging={node.dragging}
zIndex={node[internalsSymbol]?.z ?? 0} zIndex={node[internalsSymbol]?.z ?? 0}
dragHandle={node.dragHandle} dragHandle={node.dragHandle}
initialized={(!!node.width && !!node.height) || (!!node.size?.width && !!node.size?.height)}
{resizeObserver} {resizeObserver}
on:nodeclick on:nodeclick
on:nodemouseenter on:nodemouseenter
@@ -16,6 +16,7 @@
import { key, useStore, createStoreContext } from '$lib/store'; import { key, useStore, createStoreContext } from '$lib/store';
import type { SvelteFlowProps } from './types'; import type { SvelteFlowProps } from './types';
import { updateStore, updateStoreByKeys, type UpdatableStoreProps } from './utils'; import { updateStore, updateStoreByKeys, type UpdatableStoreProps } from './utils';
import { get } from 'svelte/store';
type $$Props = SvelteFlowProps; type $$Props = SvelteFlowProps;
@@ -63,6 +64,8 @@
export let attributionPosition: $$Props['attributionPosition'] = undefined; export let attributionPosition: $$Props['attributionPosition'] = undefined;
export let proOptions: $$Props['proOptions'] = undefined; export let proOptions: $$Props['proOptions'] = undefined;
export let defaultEdgeOptions: $$Props['defaultEdgeOptions'] = undefined; export let defaultEdgeOptions: $$Props['defaultEdgeOptions'] = undefined;
export let width: $$Props['width'] = undefined;
export let height: $$Props['height'] = undefined;
export let defaultMarkerColor = '#b1b1b7'; export let defaultMarkerColor = '#b1b1b7';
@@ -74,7 +77,9 @@
let clientWidth: number; let clientWidth: number;
let clientHeight: number; let clientHeight: number;
const store = hasContext(key) ? useStore() : createStoreContext(); const store = hasContext(key)
? useStore()
: createStoreContext({ nodes: get(nodes), edges: get(edges), width, height, fitView });
onMount(() => { onMount(() => {
store.width.set(clientWidth); store.width.set(clientWidth);
@@ -106,6 +111,14 @@
}; };
}); });
// Update width & height on resize
$: {
if (clientWidth !== undefined && clientHeight !== undefined) {
store.width.set(clientWidth);
store.height.set(clientHeight);
}
}
// this updates the store for simple changes // this updates the store for simple changes
// where the prop names equals the store name // where the prop names equals the store name
$: { $: {
@@ -72,6 +72,8 @@ export type SvelteFlowProps = DOMAttributes<HTMLDivElement> & {
attributionPosition?: PanelPosition; attributionPosition?: PanelPosition;
proOptions?: ProOptions; proOptions?: ProOptions;
defaultEdgeOptions?: DefaultEdgeOptions; defaultEdgeOptions?: DefaultEdgeOptions;
width?: number;
height?: number;
class?: string; class?: string;
style?: string; style?: string;
+28 -14
View File
@@ -31,26 +31,27 @@ export function useSvelteFlow(): {
getViewport: () => Viewport; getViewport: () => Viewport;
fitView: (options?: FitViewOptions) => void; fitView: (options?: FitViewOptions) => void;
getIntersectingNodes: ( getIntersectingNodes: (
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect, nodeOrRect: Node | { id: Node['id'] } | Rect,
partially?: boolean, partially?: boolean,
nodesToIntersect?: Node[] nodesToIntersect?: Node[]
) => Node[]; ) => Node[];
isNodeIntersecting: ( isNodeIntersecting: (
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect, nodeOrRect: Node | { id: Node['id'] } | Rect,
area: Rect, area: Rect,
partially?: boolean partially?: boolean
) => boolean; ) => boolean;
fitBounds: (bounds: Rect, options?: FitBoundsOptions) => void; fitBounds: (bounds: Rect, options?: FitBoundsOptions) => void;
deleteElements: ( deleteElements: (
nodesToRemove?: Partial<Node> & { id: string }[], nodesToRemove?: (Node | { id: Node['id'] })[],
edgesToRemove?: Partial<Edge> & { id: string }[] edgesToRemove?: (Edge | { id: Edge['id'] })[]
) => { deletedNodes: Node[]; deletedEdges: Edge[] }; ) => { deletedNodes: Node[]; deletedEdges: Edge[] };
screenToFlowCoordinate: (position: XYPosition) => XYPosition; screenToFlowCoordinate: (position: XYPosition) => XYPosition;
flowToScreenCoordinate: (position: XYPosition) => XYPosition; flowToScreenCoordinate: (position: XYPosition) => XYPosition;
viewport: Writable<Viewport>; viewport: Writable<Viewport>;
getConnectedEdges: (id: string | (Partial<Node> & { id: Node['id'] })[]) => Edge[]; getConnectedEdges: (id: string | (Node | { id: Node['id'] })[]) => Edge[];
getIncomers: (node: string | (Partial<Node> & { id: Node['id'] })) => Node[]; getIncomers: (node: string | Node | { id: Node['id'] }) => Node[];
getOutgoers: (node: string | (Partial<Node> & { id: Node['id'] })) => Node[]; getOutgoers: (node: string | Node | { id: Node['id'] }) => Node[];
toObject: () => { nodes: Node[]; edges: Edge[]; viewport: Viewport };
} { } {
const { const {
zoomIn, zoomIn,
@@ -69,7 +70,7 @@ export function useSvelteFlow(): {
} = useStore(); } = useStore();
const getNodeRect = ( const getNodeRect = (
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect nodeOrRect: Node | { id: Node['id'] } | Rect
): [Rect | null, Node | null | undefined, boolean] => { ): [Rect | null, Node | null | undefined, boolean] => {
const isRect = isRectObject(nodeOrRect); const isRect = isRectObject(nodeOrRect);
const node = isRect ? null : get(nodes).find((n) => n.id === nodeOrRect.id); const node = isRect ? null : get(nodes).find((n) => n.id === nodeOrRect.id);
@@ -136,7 +137,7 @@ export function useSvelteFlow(): {
); );
}, },
getIntersectingNodes: ( getIntersectingNodes: (
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect, nodeOrRect: Node | { id: Node['id'] } | Rect,
partially = true, partially = true,
nodesToIntersect?: Node[] nodesToIntersect?: Node[]
) => { ) => {
@@ -155,11 +156,11 @@ export function useSvelteFlow(): {
const overlappingArea = getOverlappingArea(currNodeRect, nodeRect); const overlappingArea = getOverlappingArea(currNodeRect, nodeRect);
const partiallyVisible = partially && overlappingArea > 0; const partiallyVisible = partially && overlappingArea > 0;
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!; return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
}); });
}, },
isNodeIntersecting: ( isNodeIntersecting: (
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect, nodeOrRect: Node | { id: Node['id'] } | Rect,
area: Rect, area: Rect,
partially = true partially = true
) => { ) => {
@@ -172,11 +173,11 @@ export function useSvelteFlow(): {
const overlappingArea = getOverlappingArea(nodeRect, area); const overlappingArea = getOverlappingArea(nodeRect, area);
const partiallyVisible = partially && overlappingArea > 0; const partiallyVisible = partially && overlappingArea > 0;
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!; return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
}, },
deleteElements: ( deleteElements: (
nodesToRemove: Partial<Node> & { id: string }[] = [], nodesToRemove: (Node | { id: Node['id'] })[] = [],
edgesToRemove: Partial<Edge> & { id: string }[] = [] edgesToRemove: (Edge | { id: Edge['id'] })[] = []
) => { ) => {
const _nodes = get(nodes); const _nodes = get(nodes);
const _edges = get(edges); const _edges = get(edges);
@@ -263,6 +264,19 @@ export function useSvelteFlow(): {
return getOutgoersBase(_node, get(nodes), get(edges)); return getOutgoersBase(_node, get(nodes), get(edges));
}, },
toObject: () => {
return {
nodes: get(nodes).map((node) => ({
...node,
// we want to make sure that changes to the nodes object that gets returned by toObject
// do not affect the nodes object
position: { ...node.position },
data: { ...node.data }
})),
edges: get(edges).map((edge) => ({ ...edge })),
viewport: { ...get(viewport) }
};
},
viewport viewport
}; };
} }
+1
View File
@@ -7,6 +7,7 @@ export * from '$lib/container/Panel';
export * from '$lib/components/SvelteFlowProvider'; export * from '$lib/components/SvelteFlowProvider';
export * from '$lib/components/EdgeLabelRenderer'; export * from '$lib/components/EdgeLabelRenderer';
export * from '$lib/components/BaseEdge'; export * from '$lib/components/BaseEdge';
export * from '$lib/components/edges';
export * from '$lib/components/Handle'; export * from '$lib/components/Handle';
// plugins // plugins
+105 -37
View File
@@ -15,7 +15,8 @@ import {
type CoordinateExtent, type CoordinateExtent,
type UpdateConnection, type UpdateConnection,
type NodeBase, type NodeBase,
type NodeDragItem type NodeDragItem,
errorMessages
} from '@xyflow/system'; } from '@xyflow/system';
import { addEdge as addEdgeUtil } from '$lib/utils'; import { addEdge as addEdgeUtil } from '$lib/utils';
@@ -29,8 +30,20 @@ import { getDerivedConnectionProps } from './derived-connection-props';
export const key = Symbol(); export const key = Symbol();
export function createStore(): SvelteFlowStore { export function createStore({
const store = getInitialStore(); nodes,
edges,
width,
height,
fitView: fitViewOnCreate
}: {
nodes?: Node[];
edges?: Edge[];
width?: number;
height?: number;
fitView?: boolean;
}): SvelteFlowStore {
const store = getInitialStore({ nodes, edges, width, height, fitView: fitViewOnCreate });
function setNodeTypes(nodeTypes: NodeTypes) { function setNodeTypes(nodeTypes: NodeTypes) {
store.nodeTypes.set({ store.nodeTypes.set({
@@ -161,25 +174,29 @@ export function createStore(): SvelteFlowStore {
} }
} }
function resetSelectedItem<T extends Node | Edge>(item: T) { function resetSelectedItem<T extends Node | Edge>(ids: string[]) {
if (item.selected) { return (item: T) => {
return { if (item.selected && ids.includes(item.id)) {
...item, return {
selected: false ...item,
}; selected: false
} };
}
return item; return item;
};
} }
function unselectNodesAndEdges() { function unselectNodesAndEdges(params?: { nodes?: Node[]; edges?: Edge[] }) {
if (get(store.nodes).some((node) => node.selected)) { const nodeIdsToUnselect = (params?.nodes ? params.nodes : get(store.nodes)).map(
store.nodes.update((ns) => ns.map(resetSelectedItem)); (item) => item.id
} );
const edgeIdsToUnselect = (params?.edges ? params.edges : get(store.edges)).map(
(item) => item.id
);
if (get(store.edges).some((edge) => edge.selected)) { store.nodes.update((ns) => ns.map(resetSelectedItem(nodeIdsToUnselect)));
store.edges.update((es) => es.map(resetSelectedItem)); store.edges.update((es) => es.map(resetSelectedItem(edgeIdsToUnselect)));
}
} }
store.deleteKeyPressed.subscribe((deleteKeyPressed) => { store.deleteKeyPressed.subscribe((deleteKeyPressed) => {
@@ -208,36 +225,74 @@ export function createStore(): SvelteFlowStore {
}); });
function addSelectedNodes(ids: string[]) { function addSelectedNodes(ids: string[]) {
store.selectionRect.set(null); const isMultiSelection = get(store.multiselectionKeyPressed);
store.selectionRectMode.set(null);
if (get(store.multiselectionKeyPressed)) {
// @todo handle multiselection key
}
store.nodes.update((ns) => store.nodes.update((ns) =>
ns.map((node) => { ns.map((node) => {
return { const nodeWillBeSelected = ids.includes(node.id);
...node, const selected = isMultiSelection
selected: ids.includes(node.id) ? node.selected || nodeWillBeSelected
}; : nodeWillBeSelected;
// we need to mutate the node here in order to have the correct selected state in the drag handler
node.selected = selected;
return node;
}) })
); );
if (!isMultiSelection) {
store.edges.update((es) =>
es.map((edge) => {
edge.selected = false;
return edge;
})
);
}
} }
function addSelectedEdges(ids: string[]) { function addSelectedEdges(ids: string[]) {
if (get(store.multiselectionKeyPressed)) { const isMultiSelection = get(store.multiselectionKeyPressed);
// @todo handle multiselection key
}
store.edges.update((edges) => store.edges.update((edges) =>
edges.map((edge) => { edges.map((edge) => {
return { const edgeWillBeSelected = ids.includes(edge.id);
...edge, const selected = isMultiSelection
selected: ids.includes(edge.id) ? edge.selected || edgeWillBeSelected
}; : edgeWillBeSelected;
edge.selected = selected;
return edge;
}) })
); );
if (!isMultiSelection) {
store.nodes.update((ns) =>
ns.map((node) => {
node.selected = false;
return node;
})
);
}
}
function handleNodeSelection(id: string) {
const node = get(store.nodes)?.find((n) => n.id === id);
if (!node) {
console.warn('012', errorMessages['error012'](id));
return;
}
store.selectionRect.set(null);
store.selectionRectMode.set(null);
if (!node.selected) {
addSelectedNodes([id]);
} else if (node.selected && get(store.multiselectionKeyPressed)) {
unselectNodesAndEdges({ nodes: [node], edges: [] });
}
} }
function panBy(delta: XYPosition) { function panBy(delta: XYPosition) {
@@ -314,6 +369,7 @@ export function createStore(): SvelteFlowStore {
unselectNodesAndEdges, unselectNodesAndEdges,
addSelectedNodes, addSelectedNodes,
addSelectedEdges, addSelectedEdges,
handleNodeSelection,
panBy, panBy,
updateConnection, updateConnection,
cancelConnection, cancelConnection,
@@ -333,8 +389,20 @@ export function useStore(): SvelteFlowStore {
return store.getStore(); return store.getStore();
} }
export function createStoreContext() { export function createStoreContext({
const store = createStore(); nodes,
edges,
width,
height,
fitView
}: {
nodes?: Node[];
edges?: Edge[];
width?: number;
height?: number;
fitView?: boolean;
}) {
const store = createStore({ nodes, edges, width, height, fitView });
setContext(key, { setContext(key, {
getStore: () => store getStore: () => store
+82 -50
View File
@@ -14,7 +14,10 @@ import {
type NodeOrigin, type NodeOrigin,
type OnError, type OnError,
devWarn, devWarn,
type Viewport type Viewport,
updateNodes,
getRectOfNodes,
getTransformForBounds
} from '@xyflow/system'; } from '@xyflow/system';
import DefaultNode from '$lib/components/nodes/DefaultNode.svelte'; import DefaultNode from '$lib/components/nodes/DefaultNode.svelte';
@@ -25,7 +28,7 @@ import BezierEdge from '$lib/components/edges/BezierEdge.svelte';
import StraightEdge from '$lib/components/edges/StraightEdge.svelte'; import StraightEdge from '$lib/components/edges/StraightEdge.svelte';
import SmoothStepEdge from '$lib/components/edges/SmoothStepEdge.svelte'; import SmoothStepEdge from '$lib/components/edges/SmoothStepEdge.svelte';
import StepEdge from '$lib/components/edges/StepEdge.svelte'; import StepEdge from '$lib/components/edges/StepEdge.svelte';
import type { NodeTypes, EdgeTypes, EdgeLayouted, Node, FitViewOptions } from '$lib/types'; import type { NodeTypes, EdgeTypes, EdgeLayouted, Node, Edge, FitViewOptions } from '$lib/types';
import { createNodesStore, createEdgesStore } from './utils'; import { createNodesStore, createEdgesStore } from './utils';
import { initConnectionProps, type ConnectionProps } from './derived-connection-props'; import { initConnectionProps, type ConnectionProps } from './derived-connection-props';
@@ -43,51 +46,80 @@ export const initialEdgeTypes = {
step: StepEdge step: StepEdge
}; };
export const getInitialStore = () => ({ export const getInitialStore = ({
flowId: writable<string | null>(null), nodes = [],
nodes: createNodesStore([]), edges = [],
visibleNodes: readable<Node[]>([]), width,
edges: createEdgesStore([]), height,
edgeTree: readable<GroupedEdges<EdgeLayouted>[]>([]), fitView
height: writable<number>(500), }: {
width: writable<number>(500), nodes?: Node[];
minZoom: writable<number>(0.5), edges?: Edge[];
maxZoom: writable<number>(2), width?: number;
nodeOrigin: writable<NodeOrigin>([0, 0]), height?: number;
nodeDragThreshold: writable<number>(0), fitView?: boolean;
nodeExtent: writable<CoordinateExtent>(infiniteExtent), }) => {
translateExtent: writable<CoordinateExtent>(infiniteExtent), const nextNodes = updateNodes(nodes, [], { nodeOrigin: [0, 0], elevateNodesOnSelect: false });
autoPanOnNodeDrag: writable<boolean>(true),
autoPanOnConnect: writable<boolean>(true), let viewport: Viewport = { x: 0, y: 0, zoom: 1 };
fitViewOnInit: writable<boolean>(false),
fitViewOnInitDone: writable<boolean>(false), if (fitView && width && height) {
fitViewOptions: writable<FitViewOptions>(undefined), const nodesWithDimensions = nextNodes.map((node) => ({
panZoom: writable<PanZoomInstance | null>(null), ...node,
snapGrid: writable<SnapGrid | null>(null), width: node.size?.width,
dragging: writable<boolean>(false), height: node.size?.height
selectionRect: writable<SelectionRect | null>(null), }));
selectionKeyPressed: writable<boolean>(false), const bounds = getRectOfNodes(nodesWithDimensions, [0, 0]);
multiselectionKeyPressed: writable<boolean>(false), const transform = getTransformForBounds(bounds, width, height, 0.5, 2, 0.1);
deleteKeyPressed: writable<boolean>(false), viewport = { x: transform[0], y: transform[1], zoom: transform[2] };
panActivationKeyPressed: writable<boolean>(false), }
selectionRectMode: writable<string | null>(null),
selectionMode: writable<SelectionMode>(SelectionMode.Partial), return {
nodeTypes: writable<NodeTypes>(initialNodeTypes), flowId: writable<string | null>(null),
edgeTypes: writable<EdgeTypes>(initialEdgeTypes), nodes: createNodesStore(nextNodes),
viewport: writable<Viewport>({ x: 0, y: 0, zoom: 1 }), visibleNodes: readable<Node[]>([]),
connectionMode: writable<ConnectionMode>(ConnectionMode.Strict), edges: createEdgesStore(edges),
domNode: writable<HTMLDivElement | null>(null), edgeTree: readable<GroupedEdges<EdgeLayouted>[]>([]),
connection: readable<ConnectionProps>(initConnectionProps), height: writable<number>(500),
connectionLineType: writable<ConnectionLineType>(ConnectionLineType.Bezier), width: writable<number>(500),
connectionRadius: writable<number>(20), minZoom: writable<number>(0.5),
isValidConnection: writable<IsValidConnection>(() => true), maxZoom: writable<number>(2),
nodesDraggable: writable<boolean>(true), nodeOrigin: writable<NodeOrigin>([0, 0]),
nodesConnectable: writable<boolean>(true), nodeDragThreshold: writable<number>(0),
elementsSelectable: writable<boolean>(true), nodeExtent: writable<CoordinateExtent>(infiniteExtent),
selectNodesOnDrag: writable<boolean>(true), translateExtent: writable<CoordinateExtent>(infiniteExtent),
markers: readable<MarkerProps[]>([]), autoPanOnNodeDrag: writable<boolean>(true),
defaultMarkerColor: writable<string>('#b1b1b7'), autoPanOnConnect: writable<boolean>(true),
lib: readable<string>('svelte'), fitViewOnInit: writable<boolean>(false),
onlyRenderVisibleElements: writable<boolean>(false), fitViewOnInitDone: writable<boolean>(false),
onError: writable<OnError>(devWarn) fitViewOptions: writable<FitViewOptions>(undefined),
}); panZoom: writable<PanZoomInstance | null>(null),
snapGrid: writable<SnapGrid | null>(null),
dragging: writable<boolean>(false),
selectionRect: writable<SelectionRect | null>(null),
selectionKeyPressed: writable<boolean>(false),
multiselectionKeyPressed: writable<boolean>(false),
deleteKeyPressed: writable<boolean>(false),
panActivationKeyPressed: writable<boolean>(false),
selectionRectMode: writable<string | null>(null),
selectionMode: writable<SelectionMode>(SelectionMode.Partial),
nodeTypes: writable<NodeTypes>(initialNodeTypes),
edgeTypes: writable<EdgeTypes>(initialEdgeTypes),
viewport: writable<Viewport>(viewport),
connectionMode: writable<ConnectionMode>(ConnectionMode.Strict),
domNode: writable<HTMLDivElement | null>(null),
connection: readable<ConnectionProps>(initConnectionProps),
connectionLineType: writable<ConnectionLineType>(ConnectionLineType.Bezier),
connectionRadius: writable<number>(20),
isValidConnection: writable<IsValidConnection>(() => true),
nodesDraggable: writable<boolean>(true),
nodesConnectable: writable<boolean>(true),
elementsSelectable: writable<boolean>(true),
selectNodesOnDrag: writable<boolean>(true),
markers: readable<MarkerProps[]>([]),
defaultMarkerColor: writable<string>('#b1b1b7'),
lib: readable<string>('svelte'),
onlyRenderVisibleElements: writable<boolean>(false),
onError: writable<OnError>(devWarn)
};
};
+2 -1
View File
@@ -28,9 +28,10 @@ export type SvelteFlowStoreActions = {
fitView: (options?: FitViewOptions) => boolean; fitView: (options?: FitViewOptions) => boolean;
updateNodePositions: UpdateNodePositions; updateNodePositions: UpdateNodePositions;
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void; updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void;
unselectNodesAndEdges: () => void; unselectNodesAndEdges: (params?: { nodes?: Node[]; edges?: Edge[] }) => void;
addSelectedNodes: (ids: string[]) => void; addSelectedNodes: (ids: string[]) => void;
addSelectedEdges: (ids: string[]) => void; addSelectedEdges: (ids: string[]) => void;
handleNodeSelection: (id: string) => void;
panBy: (delta: XYPosition) => boolean; panBy: (delta: XYPosition) => boolean;
updateConnection: UpdateConnection; updateConnection: UpdateConnection;
cancelConnection: () => void; cancelConnection: () => void;
+1 -1
View File
@@ -6,7 +6,7 @@ import {
type Writable, type Writable,
get get
} from 'svelte/store'; } from 'svelte/store';
import { updateNodes, type Transform, type Viewport, type PanZoomInstance } from '@xyflow/system'; import { updateNodes, type Viewport, type PanZoomInstance } from '@xyflow/system';
import type { DefaultEdgeOptions, DefaultNodeOptions, Edge, Node } from '$lib/types'; import type { DefaultEdgeOptions, DefaultNodeOptions, Edge, Node } from '$lib/types';
@@ -9,6 +9,7 @@ export function getVisibleNodes(store: SvelteFlowStoreState) {
[store.nodes, store.onlyRenderVisibleElements, store.width, store.height, store.viewport], [store.nodes, store.onlyRenderVisibleElements, store.width, store.height, store.viewport],
([nodes, onlyRenderVisibleElements, width, height, viewport]) => { ([nodes, onlyRenderVisibleElements, width, height, viewport]) => {
const transform: Transform = [viewport.x, viewport.y, viewport.zoom]; const transform: Transform = [viewport.x, viewport.y, viewport.zoom];
return onlyRenderVisibleElements return onlyRenderVisibleElements
? getNodesInside<Node>(nodes, { x: 0, y: 0, width, height }, transform, true) ? getNodesInside<Node>(nodes, { x: 0, y: 0, width, height }, transform, true)
: nodes; : nodes;
+2
View File
@@ -39,6 +39,8 @@ export type Edge<T = any> =
export type EdgeProps = Omit<Edge, 'sourceHandle' | 'targetHandle'> & export type EdgeProps = Omit<Edge, 'sourceHandle' | 'targetHandle'> &
EdgePosition & { EdgePosition & {
markerStart?: string;
markerEnd?: string;
sourceHandleId?: string | null; sourceHandleId?: string | null;
targetHandleId?: string | null; targetHandleId?: string | null;
}; };
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@xyflow/system", "name": "@xyflow/system",
"version": "0.0.8", "version": "0.0.9",
"description": "xyflow core system that powers React Flow and Svelte Flow.", "description": "xyflow core system that powers React Flow and Svelte Flow.",
"keywords": [ "keywords": [
"node-based UI", "node-based UI",
+1
View File
@@ -130,6 +130,7 @@
.xy-flow__connectionline { .xy-flow__connectionline {
z-index: 1001; z-index: 1001;
overflow: visible; overflow: visible;
position: absolute;
} }
.xy-flow__nodes { .xy-flow__nodes {
+1 -1
View File
@@ -63,7 +63,7 @@ export type FitViewOptionsBase<NodeType extends NodeBase> = {
minZoom?: number; minZoom?: number;
maxZoom?: number; maxZoom?: number;
duration?: number; duration?: number;
nodes?: (Partial<NodeType> & { id: NodeType['id'] })[]; nodes?: (NodeType | { id: NodeType['id'] })[];
}; };
export type Viewport = { export type Viewport = {
+10 -6
View File
@@ -1,12 +1,16 @@
import type { XYPosition, Position, Dimensions, OnConnect, IsValidConnection } from '.'; import type { Position, OnConnect, IsValidConnection } from '.';
export type HandleType = 'source' | 'target'; export type HandleType = 'source' | 'target';
export type HandleElement = XYPosition & export type HandleElement = {
Dimensions & { id?: string | null;
id?: string | null; x: number;
position: Position; y: number;
}; width: number;
height: number;
position: Position;
type?: HandleType;
};
export type ConnectingHandle = { export type ConnectingHandle = {
nodeId: string; nodeId: string;
+8
View File
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import { internalsSymbol } from '../constants'; import { internalsSymbol } from '../constants';
import type { XYPosition, Position, CoordinateExtent, HandleElement } from '.'; import type { XYPosition, Position, CoordinateExtent, HandleElement } from '.';
import { Optional } from '../utils/types';
// this is stuff that all nodes share independent of the framework // this is stuff that all nodes share independent of the framework
export type NodeBase<T = any, U extends string | undefined = string | undefined> = { export type NodeBase<T = any, U extends string | undefined = string | undefined> = {
@@ -28,6 +29,11 @@ export type NodeBase<T = any, U extends string | undefined = string | undefined>
ariaLabel?: string; ariaLabel?: string;
focusable?: boolean; focusable?: boolean;
origin?: NodeOrigin; origin?: NodeOrigin;
handles?: NodeHandle[];
size?: {
width?: number;
height?: number;
};
// only used internally // only used internally
[internalsSymbol]?: { [internalsSymbol]?: {
@@ -89,3 +95,5 @@ export type NodeOrigin = [number, number];
export type OnNodeDrag = (event: MouseEvent, node: NodeBase, nodes: NodeBase[]) => void; export type OnNodeDrag = (event: MouseEvent, node: NodeBase, nodes: NodeBase[]) => void;
export type OnSelectionDrag = (event: MouseEvent, nodes: NodeBase[]) => void; export type OnSelectionDrag = (event: MouseEvent, nodes: NodeBase[]) => void;
export type NodeHandle = Optional<HandleElement, 'width' | 'height'>;
+38 -9
View File
@@ -1,6 +1,6 @@
import { EdgePosition } from '../../types/edges'; import { EdgePosition } from '../../types/edges';
import { ConnectionMode, OnError } from '../../types/general'; import { ConnectionMode, OnError } from '../../types/general';
import { NodeBase, NodeHandleBounds } from '../../types/nodes'; import { NodeBase, NodeHandle, NodeHandleBounds } from '../../types/nodes';
import { Position, Rect, XYPosition } from '../../types/utils'; import { Position, Rect, XYPosition } from '../../types/utils';
import { errorMessages, internalsSymbol } from '../../constants'; import { errorMessages, internalsSymbol } from '../../constants';
import { HandleElement } from '../../types'; import { HandleElement } from '../../types';
@@ -16,10 +16,10 @@ export type GetEdgePositionParams = {
}; };
export function getEdgePosition(params: GetEdgePositionParams): EdgePosition | null { export function getEdgePosition(params: GetEdgePositionParams): EdgePosition | null {
const [sourceNodeRect, sourceHandleBounds, sourceIsValid] = getHandleDataByNode(params.sourceNode); const [sourceNodeRect, sourceHandleBounds, isSourceValid] = getHandleDataByNode(params.sourceNode);
const [targetNodeRect, targetHandleBounds, targetIsValid] = getHandleDataByNode(params.targetNode); const [targetNodeRect, targetHandleBounds, isTargetValid] = getHandleDataByNode(params.targetNode);
if (!sourceIsValid || !targetIsValid) { if (!isSourceValid || !isTargetValid) {
return null; return null;
} }
@@ -59,13 +59,42 @@ export function getEdgePosition(params: GetEdgePositionParams): EdgePosition | n
}; };
} }
function toHandleBounds(handles?: NodeHandle[]) {
if (!handles) {
return null;
}
return handles.reduce<NodeHandleBounds>(
(res, item) => {
item.width = item.width || 1;
item.height = item.height || 1;
if (item.type === 'source') {
res.source?.push(item as HandleElement);
}
if (item.type === 'target') {
res.target?.push(item as HandleElement);
}
return res;
},
{
source: [],
target: [],
}
);
}
function getHandleDataByNode(node?: NodeBase): [Rect, NodeHandleBounds | null, boolean] { function getHandleDataByNode(node?: NodeBase): [Rect, NodeHandleBounds | null, boolean] {
const handleBounds = node?.[internalsSymbol]?.handleBounds || null; const handleBounds = node?.[internalsSymbol]?.handleBounds || toHandleBounds(node?.handles) || null;
const nodeWidth = node?.width || node?.size?.width;
const nodeHeight = node?.height || node?.size?.height;
const isValid = const isValid =
handleBounds && handleBounds &&
node?.width && nodeWidth &&
node?.height && nodeHeight &&
typeof node?.positionAbsolute?.x !== 'undefined' && typeof node?.positionAbsolute?.x !== 'undefined' &&
typeof node?.positionAbsolute?.y !== 'undefined'; typeof node?.positionAbsolute?.y !== 'undefined';
@@ -73,8 +102,8 @@ function getHandleDataByNode(node?: NodeBase): [Rect, NodeHandleBounds | null, b
{ {
x: node?.positionAbsolute?.x || 0, x: node?.positionAbsolute?.x || 0,
y: node?.positionAbsolute?.y || 0, y: node?.positionAbsolute?.y || 0,
width: node?.width || 0, width: nodeWidth || 0,
height: node?.height || 0, height: nodeHeight || 0,
}, },
handleBounds, handleBounds,
!!isValid, !!isValid,
+2 -2
View File
@@ -35,7 +35,7 @@ export const isNodeBase = <NodeType extends NodeBase = NodeBase, EdgeType extend
): element is NodeType => 'id' in element && !('source' in element) && !('target' in element); ): element is NodeType => 'id' in element && !('source' in element) && !('target' in element);
export const getOutgoersBase = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>( export const getOutgoersBase = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>(
node: Partial<NodeType> & { id: string }, node: NodeType | { id: string },
nodes: NodeType[], nodes: NodeType[],
edges: EdgeType[] edges: EdgeType[]
): NodeType[] => { ): NodeType[] => {
@@ -54,7 +54,7 @@ export const getOutgoersBase = <NodeType extends NodeBase = NodeBase, EdgeType e
}; };
export const getIncomersBase = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>( export const getIncomersBase = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>(
node: Partial<NodeType> & { id: string }, node: NodeType | { id: string },
nodes: NodeType[], nodes: NodeType[],
edges: EdgeType[] edges: EdgeType[]
): NodeType[] => { ): NodeType[] => {
+1
View File
@@ -0,0 +1 @@
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
+5 -5
View File
@@ -46,7 +46,7 @@ type StoreItems = {
selectNodesOnDrag: boolean; selectNodesOnDrag: boolean;
nodeDragThreshold: number; nodeDragThreshold: number;
panBy: PanBy; panBy: PanBy;
unselectNodesAndEdges: () => void; unselectNodesAndEdges: (params?: { nodes?: NodeBase[]; edges?: EdgeBase[] }) => void;
onError?: OnError; onError?: OnError;
onNodeDragStart?: OnNodeDrag; onNodeDragStart?: OnNodeDrag;
onNodeDrag?: OnNodeDrag; onNodeDrag?: OnNodeDrag;
@@ -63,7 +63,7 @@ export type XYDragParams = {
onDragStart?: OnDrag; onDragStart?: OnDrag;
onDrag?: OnDrag; onDrag?: OnDrag;
onDragStop?: OnDrag; onDragStop?: OnDrag;
onNodeClick?: () => void; onNodeMouseDown?: (id: string) => void;
}; };
export type XYDragInstance = { export type XYDragInstance = {
@@ -81,7 +81,7 @@ export type DragUpdateParams = {
export function XYDrag({ export function XYDrag({
domNode, domNode,
onNodeClick, onNodeMouseDown,
getStoreItems, getStoreItems,
onDragStart, onDragStart,
onDrag, onDrag,
@@ -217,8 +217,8 @@ export function XYDrag({
} }
} }
if (isSelectable && selectNodesOnDrag) { if (isSelectable && selectNodesOnDrag && nodeId) {
onNodeClick?.(); onNodeMouseDown?.(nodeId);
} }
const pointerPos = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid }); const pointerPos = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
+4890 -1755
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -30,6 +30,7 @@ export const esmConfig = defineConfig({
output: { output: {
file: pkg.module, file: pkg.module,
format: 'esm', format: 'esm',
banner: '"use client"',
}, },
onwarn, onwarn,
plugins: [ plugins: [