Merge branch 'main' into refactor-testing
This commit is contained in:
@@ -1,12 +1,20 @@
|
||||
# Contributing to React Flow
|
||||
|
||||
Hello there! So glad you want to help out with React Flow 🤗 You’re the best. Here’s 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 🤗 You’re the best. Here’s 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
|
||||
|
||||
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?
|
||||
|
||||
@@ -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).
|
||||
|
||||
🎬 **Create tutorials** for React Flow. Send them to us and we’ll happily share them!
|
||||
🎬 **Create tutorials**. Send them to us and we’ll 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.
|
||||
|
||||
@@ -24,7 +32,7 @@ All interactions should be done with care following our [Code of Conduct](https:
|
||||
|
||||
## 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 you’re proud of, just to learn that we’ve already been working on the same thing, or that we feel doesn’t fit into the core library.
|
||||
|
||||
|
||||
146
README.md
146
README.md
@@ -1,51 +1,50 @@
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
A highly customizable React component for building interactive graphs and node-based editors.
|
||||
|
||||
[🚀 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)
|
||||
Powerful open source libraries for building node-based UIs with React or Svelte. Ready out-of-the-box and infinitely customizable.
|
||||
|
||||
[React Flow](https://reactflow.dev/) · [Svelte Flow](https://svelteflow.dev/) · [React Flow Pro](https://reactflow.dev/pro) · [Discord](https://discord.gg/Bqt6xrs)
|
||||
</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
|
||||
- **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
|
||||
- **Fast rendering:** Only nodes that have changed are re-rendered and only those in the viewport are displayed
|
||||
- **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)
|
||||
- **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)
|
||||
- **Reliable**: Written in [Typescript](https://www.typescriptlang.org/) and tested with [cypress](https://www.cypress.io/)
|
||||
The xyflow repository is the home of four packages:
|
||||
* React Flow v11 `reactflow` [v11 branch](https://github.com/xyflow/xyflow/tree/v11)
|
||||
* React Flow v12 (not published yet) [packages/react](./packages/react)
|
||||
* Svelte Flow `@xyflow/svelte` [packages/svelte](./packages/svelte)
|
||||
* Shared helper library `@xyflow/system` [packages/system](./packages/system)
|
||||
|
||||
**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
|
||||
|
||||
**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
|
||||
```
|
||||
```
|
||||
|
||||
## 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/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
|
||||
### Basic usage
|
||||
```jsx
|
||||
import { useCallback } from 'react';
|
||||
import ReactFlow, {
|
||||
MiniMap,
|
||||
@@ -54,7 +53,7 @@ import ReactFlow, {
|
||||
useNodesState,
|
||||
useEdgesState,
|
||||
addEdge,
|
||||
} from '@xyflow/react';
|
||||
} from 'reactflow';
|
||||
|
||||
import 'reactflow/dist/style.css';
|
||||
|
||||
@@ -88,44 +87,81 @@ function 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
|
||||
|
||||
```sh
|
||||
npm install @xyflow/svelte
|
||||
```
|
||||
|
||||
Run `pnpm build` once and then you can use `pnpm dev` for local development.
|
||||
### Basic usage
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import { writable } from 'svelte/store';
|
||||
import {
|
||||
SvelteFlow,
|
||||
Controls,
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
MiniMap,
|
||||
} from '@xyflow/svelte';
|
||||
|
||||
## Testing
|
||||
import '@xyflow/svelte/dist/style.css'
|
||||
|
||||
const nodes = writable([
|
||||
{
|
||||
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 }
|
||||
}
|
||||
]);
|
||||
|
||||
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:
|
||||
const edges = writable([
|
||||
{
|
||||
id: '1-2',
|
||||
type: 'default',
|
||||
source: '1',
|
||||
target: '2',
|
||||
label: 'Edge Text'
|
||||
}
|
||||
]);
|
||||
</script>
|
||||
|
||||
```sh
|
||||
pnpm test
|
||||
<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 Möller • [Twitter](https://twitter.com/chrtze) • [Github](https://github.com/chrtze)
|
||||
- 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, 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
|
||||
|
||||
React Flow is [MIT licensed](https://github.com/wbkd/react-flow/blob/main/LICENSE).
|
||||
React Flow and Svelte Flow are [MIT licensed](./LICENSE).
|
||||
|
||||
21
examples/astro-xyflow/.gitignore
vendored
Normal file
21
examples/astro-xyflow/.gitignore
vendored
Normal 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
examples/astro-xyflow/README.md
Normal file
10
examples/astro-xyflow/README.md
Normal 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
examples/astro-xyflow/astro.config.mjs
Normal file
8
examples/astro-xyflow/astro.config.mjs
Normal 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
examples/astro-xyflow/package.json
Normal file
25
examples/astro-xyflow/package.json
Normal 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
examples/astro-xyflow/public/.gitkeep
Normal file
0
examples/astro-xyflow/public/.gitkeep
Normal file
@@ -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);
|
||||
130
examples/astro-xyflow/src/components/ReactFlowExample/index.tsx
Normal file
130
examples/astro-xyflow/src/components/ReactFlowExample/index.tsx
Normal file
@@ -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
examples/astro-xyflow/src/env.d.ts
vendored
Normal file
1
examples/astro-xyflow/src/env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="astro/client" />
|
||||
27
examples/astro-xyflow/src/pages/index.astro
Normal file
27
examples/astro-xyflow/src/pages/index.astro
Normal file
@@ -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
examples/astro-xyflow/tsconfig.json
Normal file
7
examples/astro-xyflow/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "react"
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ const DnDFlow = () => {
|
||||
|
||||
return (
|
||||
<div className={styles.dndflow}>
|
||||
<ReactFlowProvider>
|
||||
<ReactFlowProvider nodes={initialNodes} edges={[]}>
|
||||
<div className={styles.wrapper}>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
@@ -77,7 +77,6 @@ const DnDFlow = () => {
|
||||
onInit={onInit}
|
||||
onDrop={onDrop}
|
||||
onDragOver={onDragOver}
|
||||
nodeOrigin={nodeOrigin}
|
||||
>
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
|
||||
@@ -17,9 +17,11 @@ export function getNodesAndEdges(xElements = 10, yElements = 10): ElementsCollec
|
||||
const data = { label: `Node ${nodeId}` };
|
||||
const node = {
|
||||
id: nodeId.toString(),
|
||||
style: { width: 50, fontSize: 11 },
|
||||
style: { width: 50, height: 30, fontSize: 11 },
|
||||
data,
|
||||
position,
|
||||
width: 50,
|
||||
height: 30,
|
||||
};
|
||||
initialNodes.push(node);
|
||||
|
||||
|
||||
@@ -204,9 +204,6 @@ const Subflow = () => {
|
||||
onNodeDrag={onNodeDrag}
|
||||
onNodeDragStop={onNodeDragStop}
|
||||
className="react-flow-basic-example"
|
||||
defaultViewport={defaultViewport}
|
||||
minZoom={0.2}
|
||||
maxZoom={4}
|
||||
onlyRenderVisibleElements={false}
|
||||
nodeTypes={nodeTypes}
|
||||
fitView
|
||||
|
||||
@@ -23,28 +23,6 @@
|
||||
|
||||
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[]>([
|
||||
{
|
||||
id: '1',
|
||||
@@ -56,17 +34,9 @@
|
||||
{
|
||||
id: '2',
|
||||
type: 'colorNode',
|
||||
data: { onChange: onChange, color: $bgColor },
|
||||
style: 'border: 1px solid #777; padding: 10px',
|
||||
data: { colorStore: bgColor },
|
||||
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',
|
||||
type: 'output',
|
||||
@@ -115,7 +85,7 @@
|
||||
{nodes}
|
||||
{edges}
|
||||
{nodeTypes}
|
||||
style="--bgcolor: {$bgColor}"
|
||||
style="--background-color: {$bgColor}"
|
||||
fitView
|
||||
on:connect={onConnect}
|
||||
>
|
||||
@@ -123,9 +93,3 @@
|
||||
<Background variant={BackgroundVariant.Dots} />
|
||||
<MiniMap />
|
||||
</SvelteFlow>
|
||||
|
||||
<style>
|
||||
:global(.svelte-flow) {
|
||||
background: var(--bgcolor);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,21 +1,40 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from 'svelte/store';
|
||||
import { Handle, Position, type NodeProps } from '@xyflow/svelte';
|
||||
|
||||
type $$Props = NodeProps;
|
||||
|
||||
export let data: { color: string; onChange: () => void } = { color: '#111', onChange: () => {} };
|
||||
export let data: { colorStore: Writable<string> };
|
||||
|
||||
const { colorStore } = data;
|
||||
</script>
|
||||
|
||||
<Handle type="target" position={Position.Left} on:connect />
|
||||
<div>
|
||||
Custom Color Picker Node: <strong>{data.color}</strong>
|
||||
<div class="custom">
|
||||
<Handle type="target" position={Position.Left} on:connect />
|
||||
<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>
|
||||
<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 />
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Right}
|
||||
id="b"
|
||||
style="top: auto; bottom: 10px;"
|
||||
on:connect
|
||||
/>
|
||||
|
||||
<style>
|
||||
.custom {
|
||||
background-color: white;
|
||||
padding: 10px;
|
||||
border: 1px solid #777;
|
||||
border-radius: 20px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { useSvelteFlow } from '@xyflow/svelte';
|
||||
import { useNodes, useSvelteFlow } from '@xyflow/svelte';
|
||||
|
||||
const {
|
||||
zoomIn,
|
||||
@@ -10,8 +10,10 @@
|
||||
setViewport,
|
||||
getViewport,
|
||||
viewport,
|
||||
nodes
|
||||
toObject
|
||||
} = useSvelteFlow();
|
||||
|
||||
const nodes = useNodes();
|
||||
</script>
|
||||
|
||||
<aside>
|
||||
@@ -23,6 +25,12 @@
|
||||
<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={() => 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>
|
||||
{#each $nodes as node (node.id)}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"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:react": "turbo run dev --filter=react",
|
||||
"build": "turbo run build",
|
||||
|
||||
@@ -1,10 +1,134 @@
|
||||
# @reactflow/core
|
||||

|
||||

|
||||
|
||||
Core components and util functions of React Flow.
|
||||
<div align="center">
|
||||
|
||||
## Installation
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
```sh
|
||||
npm install @reactflow/core
|
||||
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
|
||||
|
||||
The easiest way to get the latest version of React Flow is to install it via npm, yarn or pnpm:
|
||||
|
||||
```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 { shallow } from 'zustand/shallow';
|
||||
|
||||
@@ -37,18 +37,9 @@ const Controls: FC<PropsWithChildren<ControlProps>> = ({
|
||||
position = 'bottom-left',
|
||||
}) => {
|
||||
const store = useStoreApi();
|
||||
const [isVisible, setIsVisible] = useState<boolean>(false);
|
||||
const { isInteractive, minZoomReached, maxZoomReached } = useStore(selector, shallow);
|
||||
const { zoomIn, zoomOut, fitView } = useReactFlow();
|
||||
|
||||
useEffect(() => {
|
||||
setIsVisible(true);
|
||||
}, []);
|
||||
|
||||
if (!isVisible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onZoomInHandler = () => {
|
||||
zoomIn();
|
||||
onZoomIn?.();
|
||||
|
||||
@@ -52,6 +52,8 @@ export default (NodeComponent: ComponentType<NodeProps>) => {
|
||||
disableKeyboardA11y,
|
||||
ariaLabel,
|
||||
rfId,
|
||||
sizeWidth,
|
||||
sizeHeight,
|
||||
}: WrapNodeProps) => {
|
||||
const store = useStoreApi();
|
||||
const nodeRef = useRef<HTMLDivElement>(null);
|
||||
@@ -70,7 +72,8 @@ export default (NodeComponent: ComponentType<NodeProps>) => {
|
||||
const { selectNodesOnDrag, nodeDragThreshold } = store.getState();
|
||||
|
||||
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({
|
||||
id,
|
||||
store,
|
||||
@@ -183,6 +186,8 @@ export default (NodeComponent: ComponentType<NodeProps>) => {
|
||||
transform: `translate(${xPosOrigin}px,${yPosOrigin}px)`,
|
||||
pointerEvents: hasPointerEvents ? 'all' : 'none',
|
||||
visibility: initialized ? 'visible' : 'hidden',
|
||||
width: sizeWidth,
|
||||
height: sizeHeight,
|
||||
...style,
|
||||
}}
|
||||
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 { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
|
||||
|
||||
import { Provider } from '../../contexts/RFStoreContext';
|
||||
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);
|
||||
|
||||
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>;
|
||||
};
|
||||
}
|
||||
|
||||
ReactFlowProvider.displayName = 'ReactFlowProvider';
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { StoreApi } from 'zustand';
|
||||
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 type { Node, Edge, ReactFlowState, ReactFlowProps, ReactFlowStore } from '../../types';
|
||||
@@ -201,7 +201,7 @@ const StoreUpdater = ({
|
||||
useDirectStoreUpdater('rfId', rfId, store.setState);
|
||||
useDirectStoreUpdater('autoPanOnConnect', autoPanOnConnect, store.setState);
|
||||
useDirectStoreUpdater('autoPanOnNodeDrag', autoPanOnNodeDrag, store.setState);
|
||||
useDirectStoreUpdater('onError', onError, store.setState);
|
||||
useDirectStoreUpdater('onError', onError || devWarn, store.setState);
|
||||
useDirectStoreUpdater('connectionRadius', connectionRadius, store.setState);
|
||||
useDirectStoreUpdater('isValidConnection', isValidConnection, store.setState);
|
||||
useDirectStoreUpdater('selectNodesOnDrag', selectNodesOnDrag, store.setState);
|
||||
|
||||
@@ -62,23 +62,13 @@ const EdgeRenderer = ({
|
||||
onEdgeUpdateEnd,
|
||||
children,
|
||||
}: EdgeRendererProps) => {
|
||||
const { width, height, edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
|
||||
const { edgesFocusable, edgesUpdatable, elementsSelectable, onError } = useStore(selector, shallow);
|
||||
const edgeTree = useVisibleEdges(onlyRenderVisibleElements, elevateEdgesOnSelect);
|
||||
|
||||
if (!width) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{edgeTree.map(({ level, edges, isMaxLevel }) => (
|
||||
<svg
|
||||
key={level}
|
||||
style={{ zIndex: level }}
|
||||
width={width}
|
||||
height={height}
|
||||
className="react-flow__edges react-flow__container"
|
||||
>
|
||||
<svg key={level} style={{ zIndex: level }} className="react-flow__edges react-flow__container">
|
||||
{isMaxLevel && <MarkerDefinitions defaultColor={defaultMarkerColor} rfId={rfId} />}
|
||||
<g>
|
||||
{edges.map((edge) => {
|
||||
|
||||
@@ -17,6 +17,7 @@ export function useNodeOrEdgeTypes(nodeOrEdgeTypes: any, createTypes: any): any
|
||||
const typesParsed = useMemo(() => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const typeKeys = Object.keys(nodeOrEdgeTypes);
|
||||
|
||||
if (shallow(typesKeysRef.current, typeKeys)) {
|
||||
store.getState().onError?.('002', errorMessages['error002']());
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
|
||||
height: node.height ?? 0,
|
||||
origin: node.origin || props.nodeOrigin,
|
||||
});
|
||||
const initialized = (!!node.width && !!node.height) || (!!node.size?.width && !!node.size?.height);
|
||||
|
||||
return (
|
||||
<NodeComponent
|
||||
@@ -105,6 +106,8 @@ const NodeRenderer = (props: NodeRendererProps) => {
|
||||
id={node.id}
|
||||
className={node.className}
|
||||
style={node.style}
|
||||
sizeWidth={node.size?.width}
|
||||
sizeHeight={node.size?.height}
|
||||
type={nodeType}
|
||||
data={node.data}
|
||||
sourcePosition={node.sourcePosition || Position.Bottom}
|
||||
@@ -131,7 +134,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
|
||||
isParent={!!node[internalsSymbol]?.isParent}
|
||||
noDragClassName={props.noDragClassName}
|
||||
noPanClassName={props.noPanClassName}
|
||||
initialized={!!node.width && !!node.height}
|
||||
initialized={initialized}
|
||||
rfId={props.rfId}
|
||||
disableKeyboardA11y={props.disableKeyboardA11y}
|
||||
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 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);
|
||||
|
||||
if (isWrapped) {
|
||||
@@ -12,8 +27,18 @@ const Wrapper: FC<PropsWithChildren<unknown>> = ({ children }) => {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return <ReactFlowProvider>{children}</ReactFlowProvider>;
|
||||
};
|
||||
return (
|
||||
<ReactFlowProvider
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
initialWidth={width}
|
||||
initialHeight={height}
|
||||
fitView={fitView}
|
||||
>
|
||||
{children}
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
|
||||
Wrapper.displayName = 'ReactFlowWrapper';
|
||||
|
||||
|
||||
@@ -166,6 +166,8 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
||||
nodeDragThreshold,
|
||||
viewport,
|
||||
onViewportChange,
|
||||
width,
|
||||
height,
|
||||
...rest
|
||||
},
|
||||
ref
|
||||
@@ -181,7 +183,7 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
||||
data-testid="rf__wrapper"
|
||||
id={id}
|
||||
>
|
||||
<Wrapper>
|
||||
<Wrapper nodes={nodes} edges={edges} width={width} height={height} fitView={fitView}>
|
||||
<GraphView
|
||||
onInit={onInit}
|
||||
onNodeClick={onNodeClick}
|
||||
|
||||
@@ -23,14 +23,12 @@ function useDrag({ nodeRef, disabled = false, noDragClassName, handleSelector, n
|
||||
xyDrag.current = XYDrag({
|
||||
domNode: nodeRef.current,
|
||||
getStoreItems: () => store.getState(),
|
||||
onNodeClick: () => {
|
||||
if (nodeId) {
|
||||
handleNodeClick({
|
||||
id: nodeId,
|
||||
store,
|
||||
nodeRef: nodeRef as RefObject<HTMLDivElement>,
|
||||
});
|
||||
}
|
||||
onNodeMouseDown: (id: string) => {
|
||||
handleNodeClick({
|
||||
id,
|
||||
store,
|
||||
nodeRef: nodeRef as RefObject<HTMLDivElement>,
|
||||
});
|
||||
},
|
||||
onDragStart: () => {
|
||||
setDragging(true);
|
||||
|
||||
@@ -178,7 +178,7 @@ export default function useReactFlow<NodeData = any, EdgeData = any>(): ReactFlo
|
||||
|
||||
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] => {
|
||||
const isRect = isRectObject(nodeOrRect);
|
||||
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 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 partiallyVisible = partially && overlappingArea > 0;
|
||||
|
||||
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!;
|
||||
return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
|
||||
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
|
||||
import { updateNodesAndEdgesSelections } from './utils';
|
||||
import initialState from './initialState';
|
||||
import getInitialState from './initialState';
|
||||
import type {
|
||||
ReactFlowState,
|
||||
Node,
|
||||
@@ -24,10 +24,22 @@ import type {
|
||||
FitViewOptions,
|
||||
} from '../types';
|
||||
|
||||
const createRFStore = () =>
|
||||
const createRFStore = ({
|
||||
nodes,
|
||||
edges,
|
||||
width,
|
||||
height,
|
||||
fitView,
|
||||
}: {
|
||||
nodes?: Node[];
|
||||
edges?: Edge[];
|
||||
width?: number;
|
||||
height?: number;
|
||||
fitView?: boolean;
|
||||
}) =>
|
||||
createWithEqualityFn<ReactFlowState>(
|
||||
(set, get) => ({
|
||||
...initialState,
|
||||
...getInitialState({ nodes, edges, width, height, fitView }),
|
||||
setNodes: (nodes: Node[]) => {
|
||||
const { nodes: storeNodes, nodeOrigin, elevateNodesOnSelect } = get();
|
||||
const nextNodes = updateNodes(nodes, storeNodes, { nodeOrigin, elevateNodesOnSelect });
|
||||
@@ -45,15 +57,27 @@ const createRFStore = () =>
|
||||
const hasDefaultNodes = typeof nodes !== 'undefined';
|
||||
const hasDefaultEdges = typeof edges !== 'undefined';
|
||||
|
||||
const nextNodes = hasDefaultNodes
|
||||
? updateNodes(nodes, [], {
|
||||
nodeOrigin: get().nodeOrigin,
|
||||
elevateNodesOnSelect: get().elevateNodesOnSelect,
|
||||
})
|
||||
: [];
|
||||
const nextEdges = hasDefaultEdges ? edges : [];
|
||||
const nextState: {
|
||||
nodes?: Node[];
|
||||
edges?: Edge[];
|
||||
hasDefaultNodes: boolean;
|
||||
hasDefaultEdges: boolean;
|
||||
} = {
|
||||
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) => {
|
||||
const { onNodesChange, fitView, nodes, fitViewOnInit, fitViewDone, fitViewOnInitOptions, domNode, nodeOrigin } =
|
||||
@@ -263,9 +287,9 @@ const createRFStore = () =>
|
||||
},
|
||||
cancelConnection: () =>
|
||||
set({
|
||||
connectionStatus: initialState.connectionStatus,
|
||||
connectionStartHandle: initialState.connectionStartHandle,
|
||||
connectionEndHandle: initialState.connectionEndHandle,
|
||||
connectionStatus: null,
|
||||
connectionStartHandle: null,
|
||||
connectionEndHandle: null,
|
||||
}),
|
||||
updateConnection: (params) => {
|
||||
const { connectionStatus, connectionStartHandle, connectionEndHandle, connectionPosition } = get();
|
||||
@@ -279,7 +303,13 @@ const createRFStore = () =>
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
@@ -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 = {
|
||||
rfId: '1',
|
||||
width: 0,
|
||||
height: 0,
|
||||
transform: [0, 0, 1],
|
||||
nodes: [],
|
||||
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,
|
||||
const getInitialState = ({
|
||||
nodes = [],
|
||||
edges = [],
|
||||
width,
|
||||
height,
|
||||
fitView,
|
||||
}: {
|
||||
nodes?: Node[];
|
||||
edges?: Edge[];
|
||||
width?: number;
|
||||
height?: number;
|
||||
fitView?: boolean;
|
||||
} = {}): ReactFlowStore => {
|
||||
const nextNodes = updateNodes(nodes, [], { nodeOrigin: [0, 0], elevateNodesOnSelect: false });
|
||||
|
||||
snapGrid: [15, 15],
|
||||
snapToGrid: false,
|
||||
let transform: Transform = [0, 0, 1];
|
||||
|
||||
nodesDraggable: true,
|
||||
nodesConnectable: true,
|
||||
nodesFocusable: true,
|
||||
edgesFocusable: true,
|
||||
edgesUpdatable: true,
|
||||
elementsSelectable: true,
|
||||
elevateNodesOnSelect: true,
|
||||
fitViewOnInit: false,
|
||||
fitViewDone: false,
|
||||
fitViewOnInitOptions: undefined,
|
||||
selectNodesOnDrag: true,
|
||||
if (fitView && width && height) {
|
||||
const nodesWithDimensions = nextNodes.map((node) => ({
|
||||
...node,
|
||||
width: node.size?.width,
|
||||
height: node.size?.height,
|
||||
}));
|
||||
const bounds = getRectOfNodes(nodesWithDimensions, [0, 0]);
|
||||
transform = getTransformForBounds(bounds, width, height, 0.5, 2, 0.1);
|
||||
}
|
||||
|
||||
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,
|
||||
connectionEndHandle: null,
|
||||
connectionClickStartHandle: null,
|
||||
connectOnClick: true,
|
||||
snapGrid: [15, 15],
|
||||
snapToGrid: false,
|
||||
|
||||
ariaLiveMessage: '',
|
||||
autoPanOnConnect: true,
|
||||
autoPanOnNodeDrag: true,
|
||||
connectionRadius: 20,
|
||||
onError: devWarn,
|
||||
isValidConnection: undefined,
|
||||
nodesDraggable: true,
|
||||
nodesConnectable: true,
|
||||
nodesFocusable: true,
|
||||
edgesFocusable: true,
|
||||
edgesUpdatable: true,
|
||||
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;
|
||||
|
||||
@@ -42,7 +42,7 @@ import type {
|
||||
EdgeMouseHandler,
|
||||
} from '.';
|
||||
|
||||
export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
|
||||
export type ReactFlowProps = Omit<HTMLAttributes<HTMLDivElement>, 'onError'> & {
|
||||
nodes?: Node[];
|
||||
edges?: Edge[];
|
||||
defaultNodes?: Node[];
|
||||
@@ -151,6 +151,8 @@ export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
|
||||
onError?: OnError;
|
||||
isValidConnection?: IsValidConnection;
|
||||
nodeDragThreshold?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
|
||||
export type ReactFlowRefType = HTMLDivElement;
|
||||
|
||||
@@ -10,8 +10,8 @@ export type ReactFlowJsonObject<NodeData = any, EdgeData = any> = {
|
||||
};
|
||||
|
||||
export type DeleteElementsOptions = {
|
||||
nodes?: (Partial<Node> & { id: Node['id'] })[];
|
||||
edges?: (Partial<Edge> & { id: Edge['id'] })[];
|
||||
nodes?: (Node | { id: Node['id'] })[];
|
||||
edges?: (Edge | { id: Edge['id'] })[];
|
||||
};
|
||||
|
||||
export namespace Instance {
|
||||
@@ -33,18 +33,18 @@ export namespace Instance {
|
||||
deletedEdges: Edge[];
|
||||
};
|
||||
export type GetIntersectingNodes<NodeData> = (
|
||||
node: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect,
|
||||
node: Node<NodeData> | { id: Node['id'] } | Rect,
|
||||
partially?: boolean,
|
||||
nodes?: Node<NodeData>[]
|
||||
) => Node<NodeData>[];
|
||||
export type IsNodeIntersecting<NodeData> = (
|
||||
node: (Partial<Node<NodeData>> & { id: Node['id'] }) | Rect,
|
||||
node: Node<NodeData> | { id: Node['id'] } | Rect,
|
||||
area: Rect,
|
||||
partially?: boolean
|
||||
) => boolean;
|
||||
export type getConnectedEdges = (id: string | (Partial<Node> & { id: Node['id'] })[]) => Edge[];
|
||||
export type getIncomers = (node: string | (Partial<Node> & { id: Node['id'] })) => Node[];
|
||||
export type getOutgoers = (node: string | (Partial<Node> & { id: Node['id'] })) => Node[];
|
||||
export type getConnectedEdges = (id: string | (Node | { id: Node['id'] })[]) => Edge[];
|
||||
export type getIncomers = (node: string | Node | { id: Node['id'] }) => Node[];
|
||||
export type getOutgoers = (node: string | Node | { id: Node['id'] }) => Node[];
|
||||
}
|
||||
|
||||
export type ReactFlowInstance<NodeData = any, EdgeData = any> = {
|
||||
|
||||
@@ -40,4 +40,6 @@ export type WrapNodeProps<NodeData = any> = Pick<
|
||||
noPanClassName: string;
|
||||
rfId: string;
|
||||
disableKeyboardA11y: boolean;
|
||||
sizeWidth?: number;
|
||||
sizeHeight?: number;
|
||||
};
|
||||
|
||||
@@ -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
|
||||
|
||||
- update node automatically when `type`, `sourcePosition` or `targetPosition` option changes
|
||||
|
||||
@@ -1,6 +1,27 @@
|
||||
# Svelte Flow (alpha)
|
||||

|
||||

|
||||
|
||||
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">
|
||||
|
||||

|
||||

|
||||
|
||||
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
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
What is “xyflow”? Learn more [here](https://wbkd.notion.site/Upcoming-Changes-at-React-Flow-1a443641891a4069927c0a115e915251).
|
||||
|
||||
## 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.
|
||||
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:
|
||||
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).
|
||||
|
||||
```svelte
|
||||
<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'
|
||||
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.
|
||||
// This also makes it easier to update nodes in user land.
|
||||
// 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.
|
||||
const nodes = writable([
|
||||
{
|
||||
id: '1',
|
||||
@@ -77,13 +92,13 @@ A basic flow looks like this:
|
||||
|
||||
## 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.
|
||||
|
||||
**Squash Bugs:** We can’t catch them all. Check existing issues and discussions first, then create a new issue to tell us what’s 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 ⭐
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
Svelte Flow is MIT Licensed.
|
||||
Svelte Flow is [MIT licensed](../../LICENSE).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"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.",
|
||||
"keywords": [
|
||||
"svelte",
|
||||
|
||||
@@ -13,15 +13,17 @@ export type UseDragParams = {
|
||||
onDrag?: OnDrag;
|
||||
onDragStart?: OnDrag;
|
||||
onDragStop?: OnDrag;
|
||||
onNodeMouseDown?: (id: string) => void;
|
||||
};
|
||||
|
||||
export default function drag(domNode: Element, params: UseDragParams) {
|
||||
const { store, onDrag, onDragStart, onDragStop } = params;
|
||||
const { store, onDrag, onDragStart, onDragStop, onNodeMouseDown } = params;
|
||||
const dragInstance = XYDrag({
|
||||
domNode,
|
||||
onDrag,
|
||||
onDragStart,
|
||||
onDragStop,
|
||||
onNodeMouseDown,
|
||||
getStoreItems: () => {
|
||||
const snapGrid = get(store.snapGrid);
|
||||
const vp = get(store.viewport);
|
||||
@@ -33,7 +35,7 @@ export default function drag(domNode: Element, params: UseDragParams) {
|
||||
snapGrid: snapGrid ? snapGrid : [0, 0],
|
||||
snapToGrid: !!snapGrid,
|
||||
nodeOrigin: [0, 0],
|
||||
multiSelectionActive: false,
|
||||
multiSelectionActive: get(store.multiselectionKeyPressed),
|
||||
domNode: get(store.domNode),
|
||||
transform: [vp.x, vp.y, vp.zoom],
|
||||
autoPanOnNodeDrag: get(store.autoPanOnNodeDrag),
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
<Panel
|
||||
{position}
|
||||
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
|
||||
href="https://reactflow.dev/svelte"
|
||||
href="https://svelteflow.dev"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="Svelte Flow attribution"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import cc from 'classcat';
|
||||
import { EdgeLabelRenderer } from '$lib/components/EdgeLabelRenderer';
|
||||
import type { BaseEdgeProps } from './types';
|
||||
|
||||
@@ -16,23 +17,26 @@
|
||||
export let interactionWidth: $$Props['interactionWidth'] = 20;
|
||||
let className: $$Props['class'] = undefined;
|
||||
export { className as class };
|
||||
|
||||
// @todo, why is interactionWidth undefined after first re-render?
|
||||
let interactionWidthValue = interactionWidth === undefined ? 20 : interactionWidth;
|
||||
</script>
|
||||
|
||||
<path
|
||||
d={path}
|
||||
{id}
|
||||
class="svelte-flow__edge-path"
|
||||
class={cc(['svelte-flow__edge-path', className])}
|
||||
marker-start={markerStart}
|
||||
marker-end={markerEnd}
|
||||
fill="none"
|
||||
{style}
|
||||
/>
|
||||
|
||||
{#if interactionWidth}
|
||||
{#if interactionWidthValue}
|
||||
<path
|
||||
d={path}
|
||||
stroke-opacity={0}
|
||||
stroke-width={interactionWidth}
|
||||
stroke-width={interactionWidthValue}
|
||||
fill="none"
|
||||
class="svelte-flow__edge-interaction"
|
||||
/>
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
<svelte:options immutable />
|
||||
|
||||
<script lang="ts">
|
||||
import cc from 'classcat';
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import { getMarkerId } from '@xyflow/system';
|
||||
import { errorMessages, getMarkerId } from '@xyflow/system';
|
||||
|
||||
import { useStore } from '$lib/store';
|
||||
import BezierEdge from '$lib/components/edges/BezierEdge.svelte';
|
||||
import type { EdgeLayouted, Edge } from '$lib/types';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
type $$Props = EdgeLayouted;
|
||||
|
||||
@@ -34,11 +36,22 @@
|
||||
export let sourcePosition: $$Props['sourcePosition'];
|
||||
export let targetPosition: $$Props['targetPosition'];
|
||||
export let ariaLabel: $$Props['ariaLabel'] = undefined;
|
||||
export let interactionWidth: $$Props['interactionWidth'] = undefined;
|
||||
|
||||
// @ todo: support edge updates
|
||||
let className: string = '';
|
||||
export { className as class };
|
||||
|
||||
const { edges, edgeTypes, flowId, addSelectedEdges } = useStore();
|
||||
const {
|
||||
edges,
|
||||
edgeTypes,
|
||||
flowId,
|
||||
selectionRect,
|
||||
selectionRectMode,
|
||||
multiselectionKeyPressed,
|
||||
addSelectedEdges,
|
||||
unselectNodesAndEdges
|
||||
} = useStore();
|
||||
const dispatch = createEventDispatcher<{
|
||||
edgeclick: { edge: Edge; event: MouseEvent | TouchEvent };
|
||||
edgecontextmenu: { edge: Edge; event: MouseEvent };
|
||||
@@ -49,15 +62,25 @@
|
||||
$: markerEndUrl = markerEnd ? `url(#${getMarkerId(markerEnd, $flowId)})` : undefined;
|
||||
|
||||
function onClick(event: MouseEvent | TouchEvent) {
|
||||
if (selectable) {
|
||||
addSelectedEdges([id]);
|
||||
}
|
||||
|
||||
const edge = $edges.find((e) => e.id === id);
|
||||
|
||||
if (edge) {
|
||||
dispatch('edgeclick', { event, edge });
|
||||
if (!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) {
|
||||
@@ -73,7 +96,7 @@
|
||||
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
|
||||
{#if !hidden}
|
||||
<g
|
||||
class="svelte-flow__edge {className}"
|
||||
class={cc(['svelte-flow__edge', className])}
|
||||
class:animated
|
||||
class:selected
|
||||
data-id={id}
|
||||
@@ -103,6 +126,7 @@
|
||||
{labelStyle}
|
||||
{data}
|
||||
{style}
|
||||
{interactionWidth}
|
||||
sourceHandleId={sourceHandle}
|
||||
targetHandleId={targetHandle}
|
||||
markerStart={markerStartUrl}
|
||||
|
||||
@@ -4,14 +4,21 @@
|
||||
import { useStore } from '$lib/store';
|
||||
import type { KeyHandlerProps } from './types';
|
||||
import type { KeyDefinition, KeyDefinitionObject } from '$lib/types';
|
||||
import { isMacOs } from '@xyflow/system';
|
||||
|
||||
type $$Props = KeyHandlerProps;
|
||||
|
||||
export let selectionKey: $$Props['selectionKey'] = 'Shift';
|
||||
export let multiSelectionKey: $$Props['multiSelectionKey'] = isMacOs() ? 'Meta' : 'Control';
|
||||
export let deleteKey: $$Props['deleteKey'] = 'Backspace';
|
||||
export let panActivationKey: $$Props['panActivationKey'] = ' ';
|
||||
|
||||
const { selectionKeyPressed, deleteKeyPressed, panActivationKeyPressed } = useStore();
|
||||
const {
|
||||
selectionKeyPressed,
|
||||
multiselectionKeyPressed,
|
||||
deleteKeyPressed,
|
||||
panActivationKeyPressed
|
||||
} = useStore();
|
||||
|
||||
function isKeyObject(key?: KeyDefinition): key is KeyDefinitionObject {
|
||||
return typeof key === 'object';
|
||||
@@ -20,6 +27,10 @@
|
||||
$: selectionKeyString = typeof selectionKey === 'string' ? selectionKey : selectionKey!.key;
|
||||
$: selectionKeyModifier = isKeyObject(selectionKey) ? selectionKey?.modifier : [];
|
||||
|
||||
$: multiSelectionKeyString =
|
||||
typeof multiSelectionKey === 'string' ? multiSelectionKey : multiSelectionKey!.key;
|
||||
$: multiSelectionKeyModifier = isKeyObject(multiSelectionKey) ? multiSelectionKey?.modifier : [];
|
||||
|
||||
$: deleteKeyString = typeof deleteKey === 'string' ? deleteKey : deleteKey!.key;
|
||||
$: deleteKeyModifier = isKeyObject(deleteKey) ? deleteKey?.modifier : [];
|
||||
|
||||
@@ -49,6 +60,26 @@
|
||||
],
|
||||
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={{
|
||||
trigger: [
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { KeyDefinition } from '$lib/types';
|
||||
|
||||
export type KeyHandlerProps = {
|
||||
selectionKey?: KeyDefinition;
|
||||
multiSelectionKey?: KeyDefinition;
|
||||
deleteKey?: KeyDefinition;
|
||||
panActivationKey?: KeyDefinition;
|
||||
};
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
SvelteComponent,
|
||||
type ComponentType
|
||||
} from 'svelte';
|
||||
import cc from 'classcat';
|
||||
import { get, writable } from 'svelte/store';
|
||||
import cc from 'classcat';
|
||||
import { errorMessages, Position, type NodeProps } from '@xyflow/system';
|
||||
|
||||
import drag from '$lib/actions/drag';
|
||||
@@ -39,11 +39,18 @@
|
||||
export let targetPosition: NodeWrapperProps['targetPosition'] = undefined;
|
||||
export let zIndex: NodeWrapperProps['zIndex'];
|
||||
export let dragHandle: NodeWrapperProps['dragHandle'] = undefined;
|
||||
export let initialized: NodeWrapperProps['initialized'] = false;
|
||||
let className: string = '';
|
||||
export { className as class };
|
||||
|
||||
const store = useStore();
|
||||
const { nodeTypes, nodeDragThreshold, addSelectedNodes, updateNodeDimensions } = store;
|
||||
const {
|
||||
nodeTypes,
|
||||
nodeDragThreshold,
|
||||
selectNodesOnDrag,
|
||||
handleNodeSelection,
|
||||
updateNodeDimensions
|
||||
} = store;
|
||||
const nodeType = type || 'default';
|
||||
|
||||
let nodeRef: HTMLDivElement;
|
||||
@@ -55,7 +62,6 @@
|
||||
|
||||
const nodeComponent: ComponentType<SvelteComponent<NodeProps>> =
|
||||
$nodeTypes[nodeType] || DefaultNode;
|
||||
const selectNodesOnDrag = false;
|
||||
const dispatch = createEventDispatcher<{
|
||||
nodeclick: { node: Node; event: MouseEvent | TouchEvent };
|
||||
nodecontextmenu: { node: Node; event: MouseEvent | TouchEvent };
|
||||
@@ -112,12 +118,12 @@
|
||||
});
|
||||
|
||||
function onSelectNodeHandler(event: MouseEvent | TouchEvent) {
|
||||
if (selectable && (!selectNodesOnDrag || !draggable || get(nodeDragThreshold) > 0)) {
|
||||
// this handler gets called within the drag start event when selectNodesOnDrag=true
|
||||
addSelectedNodes([id]);
|
||||
if (selectable && (!get(selectNodesOnDrag) || !draggable || get(nodeDragThreshold) > 0)) {
|
||||
// this handler gets called by XYDrag on drag start when selectNodesOnDrag=true
|
||||
// here we only need to call it when selectNodesOnDrag=false
|
||||
handleNodeSelection(id);
|
||||
}
|
||||
|
||||
// @todo: support multiselection
|
||||
dispatch('nodeclick', { node, event });
|
||||
}
|
||||
|
||||
@@ -134,6 +140,7 @@
|
||||
disabled: false,
|
||||
handleSelector: dragHandle,
|
||||
noDragClass: 'nodrag',
|
||||
onNodeMouseDown: handleNodeSelection,
|
||||
onDrag: (event, _, node, nodes) => {
|
||||
dispatch('nodedrag', { event, node, nodes });
|
||||
},
|
||||
@@ -157,7 +164,10 @@
|
||||
class:parent={isParent}
|
||||
style:z-index={zIndex}
|
||||
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:mouseenter={(event) => dispatch('nodemouseenter', { node, event })}
|
||||
on:mouseleave={(event) => dispatch('nodemouseleave', { node, event })}
|
||||
|
||||
@@ -27,4 +27,5 @@ export type NodeWrapperProps = Pick<
|
||||
isParent?: boolean;
|
||||
zIndex: number;
|
||||
node: Node;
|
||||
initialized: boolean;
|
||||
};
|
||||
|
||||
@@ -2,8 +2,23 @@
|
||||
import { onDestroy, setContext } from 'svelte';
|
||||
|
||||
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, {
|
||||
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;
|
||||
};
|
||||
4
packages/svelte/src/lib/components/edges/index.ts
Normal file
4
packages/svelte/src/lib/components/edges/index.ts
Normal file
@@ -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;
|
||||
|
||||
const {
|
||||
width,
|
||||
height,
|
||||
elementsSelectable,
|
||||
edgeTree,
|
||||
edges: { setDefaultOptions }
|
||||
@@ -21,7 +19,7 @@
|
||||
</script>
|
||||
|
||||
{#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}
|
||||
<g>
|
||||
{#each group.edges as edge (edge.id)}
|
||||
@@ -53,6 +51,7 @@
|
||||
sourcePosition={edge.sourcePosition}
|
||||
targetPosition={edge.targetPosition}
|
||||
ariaLabel={edge.ariaLabel}
|
||||
interactionWidth={edge.interactionWidth}
|
||||
class={edge.class}
|
||||
type={edgeType}
|
||||
{selectable}
|
||||
|
||||
@@ -35,8 +35,8 @@
|
||||
{@const posOrigin = getPositionWithOrigin({
|
||||
x: node.positionAbsolute?.x ?? 0,
|
||||
y: node.positionAbsolute?.y ?? 0,
|
||||
width: node.width ?? 0,
|
||||
height: node.height ?? 0,
|
||||
width: (node.size?.width || node.width) ?? 0,
|
||||
height: (node.size?.height || node.height) ?? 0,
|
||||
origin: node.origin
|
||||
})}
|
||||
<NodeWrapper
|
||||
@@ -65,6 +65,7 @@
|
||||
dragging={node.dragging}
|
||||
zIndex={node[internalsSymbol]?.z ?? 0}
|
||||
dragHandle={node.dragHandle}
|
||||
initialized={(!!node.width && !!node.height) || (!!node.size?.width && !!node.size?.height)}
|
||||
{resizeObserver}
|
||||
on:nodeclick
|
||||
on:nodemouseenter
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
import { key, useStore, createStoreContext } from '$lib/store';
|
||||
import type { SvelteFlowProps } from './types';
|
||||
import { updateStore, updateStoreByKeys, type UpdatableStoreProps } from './utils';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
type $$Props = SvelteFlowProps;
|
||||
|
||||
@@ -63,6 +64,8 @@
|
||||
export let attributionPosition: $$Props['attributionPosition'] = undefined;
|
||||
export let proOptions: $$Props['proOptions'] = undefined;
|
||||
export let defaultEdgeOptions: $$Props['defaultEdgeOptions'] = undefined;
|
||||
export let width: $$Props['width'] = undefined;
|
||||
export let height: $$Props['height'] = undefined;
|
||||
|
||||
export let defaultMarkerColor = '#b1b1b7';
|
||||
|
||||
@@ -74,7 +77,9 @@
|
||||
let clientWidth: 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(() => {
|
||||
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
|
||||
// where the prop names equals the store name
|
||||
$: {
|
||||
|
||||
@@ -72,6 +72,8 @@ export type SvelteFlowProps = DOMAttributes<HTMLDivElement> & {
|
||||
attributionPosition?: PanelPosition;
|
||||
proOptions?: ProOptions;
|
||||
defaultEdgeOptions?: DefaultEdgeOptions;
|
||||
width?: number;
|
||||
height?: number;
|
||||
|
||||
class?: string;
|
||||
style?: string;
|
||||
|
||||
@@ -31,26 +31,27 @@ export function useSvelteFlow(): {
|
||||
getViewport: () => Viewport;
|
||||
fitView: (options?: FitViewOptions) => void;
|
||||
getIntersectingNodes: (
|
||||
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect,
|
||||
nodeOrRect: Node | { id: Node['id'] } | Rect,
|
||||
partially?: boolean,
|
||||
nodesToIntersect?: Node[]
|
||||
) => Node[];
|
||||
isNodeIntersecting: (
|
||||
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect,
|
||||
nodeOrRect: Node | { id: Node['id'] } | Rect,
|
||||
area: Rect,
|
||||
partially?: boolean
|
||||
) => boolean;
|
||||
fitBounds: (bounds: Rect, options?: FitBoundsOptions) => void;
|
||||
deleteElements: (
|
||||
nodesToRemove?: Partial<Node> & { id: string }[],
|
||||
edgesToRemove?: Partial<Edge> & { id: string }[]
|
||||
nodesToRemove?: (Node | { id: Node['id'] })[],
|
||||
edgesToRemove?: (Edge | { id: Edge['id'] })[]
|
||||
) => { deletedNodes: Node[]; deletedEdges: Edge[] };
|
||||
screenToFlowCoordinate: (position: XYPosition) => XYPosition;
|
||||
flowToScreenCoordinate: (position: XYPosition) => XYPosition;
|
||||
viewport: Writable<Viewport>;
|
||||
getConnectedEdges: (id: string | (Partial<Node> & { id: Node['id'] })[]) => Edge[];
|
||||
getIncomers: (node: string | (Partial<Node> & { id: Node['id'] })) => Node[];
|
||||
getOutgoers: (node: string | (Partial<Node> & { id: Node['id'] })) => Node[];
|
||||
getConnectedEdges: (id: string | (Node | { id: Node['id'] })[]) => Edge[];
|
||||
getIncomers: (node: string | Node | { id: Node['id'] }) => Node[];
|
||||
getOutgoers: (node: string | Node | { id: Node['id'] }) => Node[];
|
||||
toObject: () => { nodes: Node[]; edges: Edge[]; viewport: Viewport };
|
||||
} {
|
||||
const {
|
||||
zoomIn,
|
||||
@@ -69,7 +70,7 @@ export function useSvelteFlow(): {
|
||||
} = useStore();
|
||||
|
||||
const getNodeRect = (
|
||||
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect
|
||||
nodeOrRect: Node | { id: Node['id'] } | Rect
|
||||
): [Rect | null, Node | null | undefined, boolean] => {
|
||||
const isRect = isRectObject(nodeOrRect);
|
||||
const node = isRect ? null : get(nodes).find((n) => n.id === nodeOrRect.id);
|
||||
@@ -136,7 +137,7 @@ export function useSvelteFlow(): {
|
||||
);
|
||||
},
|
||||
getIntersectingNodes: (
|
||||
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect,
|
||||
nodeOrRect: Node | { id: Node['id'] } | Rect,
|
||||
partially = true,
|
||||
nodesToIntersect?: Node[]
|
||||
) => {
|
||||
@@ -155,11 +156,11 @@ export function useSvelteFlow(): {
|
||||
const overlappingArea = getOverlappingArea(currNodeRect, nodeRect);
|
||||
const partiallyVisible = partially && overlappingArea > 0;
|
||||
|
||||
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!;
|
||||
return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
|
||||
});
|
||||
},
|
||||
isNodeIntersecting: (
|
||||
nodeOrRect: (Partial<Node> & { id: Node['id'] }) | Rect,
|
||||
nodeOrRect: Node | { id: Node['id'] } | Rect,
|
||||
area: Rect,
|
||||
partially = true
|
||||
) => {
|
||||
@@ -172,11 +173,11 @@ export function useSvelteFlow(): {
|
||||
const overlappingArea = getOverlappingArea(nodeRect, area);
|
||||
const partiallyVisible = partially && overlappingArea > 0;
|
||||
|
||||
return partiallyVisible || overlappingArea >= nodeOrRect.width! * nodeOrRect.height!;
|
||||
return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
|
||||
},
|
||||
deleteElements: (
|
||||
nodesToRemove: Partial<Node> & { id: string }[] = [],
|
||||
edgesToRemove: Partial<Edge> & { id: string }[] = []
|
||||
nodesToRemove: (Node | { id: Node['id'] })[] = [],
|
||||
edgesToRemove: (Edge | { id: Edge['id'] })[] = []
|
||||
) => {
|
||||
const _nodes = get(nodes);
|
||||
const _edges = get(edges);
|
||||
@@ -263,6 +264,19 @@ export function useSvelteFlow(): {
|
||||
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export * from '$lib/container/Panel';
|
||||
export * from '$lib/components/SvelteFlowProvider';
|
||||
export * from '$lib/components/EdgeLabelRenderer';
|
||||
export * from '$lib/components/BaseEdge';
|
||||
export * from '$lib/components/edges';
|
||||
export * from '$lib/components/Handle';
|
||||
|
||||
// plugins
|
||||
|
||||
@@ -15,7 +15,8 @@ import {
|
||||
type CoordinateExtent,
|
||||
type UpdateConnection,
|
||||
type NodeBase,
|
||||
type NodeDragItem
|
||||
type NodeDragItem,
|
||||
errorMessages
|
||||
} from '@xyflow/system';
|
||||
|
||||
import { addEdge as addEdgeUtil } from '$lib/utils';
|
||||
@@ -29,8 +30,20 @@ import { getDerivedConnectionProps } from './derived-connection-props';
|
||||
|
||||
export const key = Symbol();
|
||||
|
||||
export function createStore(): SvelteFlowStore {
|
||||
const store = getInitialStore();
|
||||
export function createStore({
|
||||
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) {
|
||||
store.nodeTypes.set({
|
||||
@@ -161,25 +174,29 @@ export function createStore(): SvelteFlowStore {
|
||||
}
|
||||
}
|
||||
|
||||
function resetSelectedItem<T extends Node | Edge>(item: T) {
|
||||
if (item.selected) {
|
||||
return {
|
||||
...item,
|
||||
selected: false
|
||||
};
|
||||
}
|
||||
function resetSelectedItem<T extends Node | Edge>(ids: string[]) {
|
||||
return (item: T) => {
|
||||
if (item.selected && ids.includes(item.id)) {
|
||||
return {
|
||||
...item,
|
||||
selected: false
|
||||
};
|
||||
}
|
||||
|
||||
return item;
|
||||
return item;
|
||||
};
|
||||
}
|
||||
|
||||
function unselectNodesAndEdges() {
|
||||
if (get(store.nodes).some((node) => node.selected)) {
|
||||
store.nodes.update((ns) => ns.map(resetSelectedItem));
|
||||
}
|
||||
function unselectNodesAndEdges(params?: { nodes?: Node[]; edges?: Edge[] }) {
|
||||
const nodeIdsToUnselect = (params?.nodes ? params.nodes : get(store.nodes)).map(
|
||||
(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.edges.update((es) => es.map(resetSelectedItem));
|
||||
}
|
||||
store.nodes.update((ns) => ns.map(resetSelectedItem(nodeIdsToUnselect)));
|
||||
store.edges.update((es) => es.map(resetSelectedItem(edgeIdsToUnselect)));
|
||||
}
|
||||
|
||||
store.deleteKeyPressed.subscribe((deleteKeyPressed) => {
|
||||
@@ -208,36 +225,74 @@ export function createStore(): SvelteFlowStore {
|
||||
});
|
||||
|
||||
function addSelectedNodes(ids: string[]) {
|
||||
store.selectionRect.set(null);
|
||||
store.selectionRectMode.set(null);
|
||||
|
||||
if (get(store.multiselectionKeyPressed)) {
|
||||
// @todo handle multiselection key
|
||||
}
|
||||
const isMultiSelection = get(store.multiselectionKeyPressed);
|
||||
|
||||
store.nodes.update((ns) =>
|
||||
ns.map((node) => {
|
||||
return {
|
||||
...node,
|
||||
selected: ids.includes(node.id)
|
||||
};
|
||||
const nodeWillBeSelected = ids.includes(node.id);
|
||||
const selected = isMultiSelection
|
||||
? 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[]) {
|
||||
if (get(store.multiselectionKeyPressed)) {
|
||||
// @todo handle multiselection key
|
||||
}
|
||||
const isMultiSelection = get(store.multiselectionKeyPressed);
|
||||
|
||||
store.edges.update((edges) =>
|
||||
edges.map((edge) => {
|
||||
return {
|
||||
...edge,
|
||||
selected: ids.includes(edge.id)
|
||||
};
|
||||
const edgeWillBeSelected = ids.includes(edge.id);
|
||||
const selected = isMultiSelection
|
||||
? 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) {
|
||||
@@ -314,6 +369,7 @@ export function createStore(): SvelteFlowStore {
|
||||
unselectNodesAndEdges,
|
||||
addSelectedNodes,
|
||||
addSelectedEdges,
|
||||
handleNodeSelection,
|
||||
panBy,
|
||||
updateConnection,
|
||||
cancelConnection,
|
||||
@@ -333,8 +389,20 @@ export function useStore(): SvelteFlowStore {
|
||||
return store.getStore();
|
||||
}
|
||||
|
||||
export function createStoreContext() {
|
||||
const store = createStore();
|
||||
export function createStoreContext({
|
||||
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, {
|
||||
getStore: () => store
|
||||
|
||||
@@ -14,7 +14,10 @@ import {
|
||||
type NodeOrigin,
|
||||
type OnError,
|
||||
devWarn,
|
||||
type Viewport
|
||||
type Viewport,
|
||||
updateNodes,
|
||||
getRectOfNodes,
|
||||
getTransformForBounds
|
||||
} from '@xyflow/system';
|
||||
|
||||
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 SmoothStepEdge from '$lib/components/edges/SmoothStepEdge.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 { initConnectionProps, type ConnectionProps } from './derived-connection-props';
|
||||
|
||||
@@ -43,51 +46,80 @@ export const initialEdgeTypes = {
|
||||
step: StepEdge
|
||||
};
|
||||
|
||||
export const getInitialStore = () => ({
|
||||
flowId: writable<string | null>(null),
|
||||
nodes: createNodesStore([]),
|
||||
visibleNodes: readable<Node[]>([]),
|
||||
edges: createEdgesStore([]),
|
||||
edgeTree: readable<GroupedEdges<EdgeLayouted>[]>([]),
|
||||
height: writable<number>(500),
|
||||
width: writable<number>(500),
|
||||
minZoom: writable<number>(0.5),
|
||||
maxZoom: writable<number>(2),
|
||||
nodeOrigin: writable<NodeOrigin>([0, 0]),
|
||||
nodeDragThreshold: writable<number>(0),
|
||||
nodeExtent: writable<CoordinateExtent>(infiniteExtent),
|
||||
translateExtent: writable<CoordinateExtent>(infiniteExtent),
|
||||
autoPanOnNodeDrag: writable<boolean>(true),
|
||||
autoPanOnConnect: writable<boolean>(true),
|
||||
fitViewOnInit: writable<boolean>(false),
|
||||
fitViewOnInitDone: writable<boolean>(false),
|
||||
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>({ x: 0, y: 0, zoom: 1 }),
|
||||
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)
|
||||
});
|
||||
export const getInitialStore = ({
|
||||
nodes = [],
|
||||
edges = [],
|
||||
width,
|
||||
height,
|
||||
fitView
|
||||
}: {
|
||||
nodes?: Node[];
|
||||
edges?: Edge[];
|
||||
width?: number;
|
||||
height?: number;
|
||||
fitView?: boolean;
|
||||
}) => {
|
||||
const nextNodes = updateNodes(nodes, [], { nodeOrigin: [0, 0], elevateNodesOnSelect: false });
|
||||
|
||||
let viewport: Viewport = { x: 0, y: 0, zoom: 1 };
|
||||
|
||||
if (fitView && width && height) {
|
||||
const nodesWithDimensions = nextNodes.map((node) => ({
|
||||
...node,
|
||||
width: node.size?.width,
|
||||
height: node.size?.height
|
||||
}));
|
||||
const bounds = getRectOfNodes(nodesWithDimensions, [0, 0]);
|
||||
const transform = getTransformForBounds(bounds, width, height, 0.5, 2, 0.1);
|
||||
viewport = { x: transform[0], y: transform[1], zoom: transform[2] };
|
||||
}
|
||||
|
||||
return {
|
||||
flowId: writable<string | null>(null),
|
||||
nodes: createNodesStore(nextNodes),
|
||||
visibleNodes: readable<Node[]>([]),
|
||||
edges: createEdgesStore(edges),
|
||||
edgeTree: readable<GroupedEdges<EdgeLayouted>[]>([]),
|
||||
height: writable<number>(500),
|
||||
width: writable<number>(500),
|
||||
minZoom: writable<number>(0.5),
|
||||
maxZoom: writable<number>(2),
|
||||
nodeOrigin: writable<NodeOrigin>([0, 0]),
|
||||
nodeDragThreshold: writable<number>(0),
|
||||
nodeExtent: writable<CoordinateExtent>(infiniteExtent),
|
||||
translateExtent: writable<CoordinateExtent>(infiniteExtent),
|
||||
autoPanOnNodeDrag: writable<boolean>(true),
|
||||
autoPanOnConnect: writable<boolean>(true),
|
||||
fitViewOnInit: writable<boolean>(false),
|
||||
fitViewOnInitDone: writable<boolean>(false),
|
||||
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)
|
||||
};
|
||||
};
|
||||
|
||||
@@ -28,9 +28,10 @@ export type SvelteFlowStoreActions = {
|
||||
fitView: (options?: FitViewOptions) => boolean;
|
||||
updateNodePositions: UpdateNodePositions;
|
||||
updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void;
|
||||
unselectNodesAndEdges: () => void;
|
||||
unselectNodesAndEdges: (params?: { nodes?: Node[]; edges?: Edge[] }) => void;
|
||||
addSelectedNodes: (ids: string[]) => void;
|
||||
addSelectedEdges: (ids: string[]) => void;
|
||||
handleNodeSelection: (id: string) => void;
|
||||
panBy: (delta: XYPosition) => boolean;
|
||||
updateConnection: UpdateConnection;
|
||||
cancelConnection: () => void;
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type Writable,
|
||||
get
|
||||
} 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';
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ export function getVisibleNodes(store: SvelteFlowStoreState) {
|
||||
[store.nodes, store.onlyRenderVisibleElements, store.width, store.height, store.viewport],
|
||||
([nodes, onlyRenderVisibleElements, width, height, viewport]) => {
|
||||
const transform: Transform = [viewport.x, viewport.y, viewport.zoom];
|
||||
|
||||
return onlyRenderVisibleElements
|
||||
? getNodesInside<Node>(nodes, { x: 0, y: 0, width, height }, transform, true)
|
||||
: nodes;
|
||||
|
||||
@@ -39,6 +39,8 @@ export type Edge<T = any> =
|
||||
|
||||
export type EdgeProps = Omit<Edge, 'sourceHandle' | 'targetHandle'> &
|
||||
EdgePosition & {
|
||||
markerStart?: string;
|
||||
markerEnd?: string;
|
||||
sourceHandleId?: string | null;
|
||||
targetHandleId?: string | null;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xyflow/system",
|
||||
"version": "0.0.8",
|
||||
"version": "0.0.9",
|
||||
"description": "xyflow core system that powers React Flow and Svelte Flow.",
|
||||
"keywords": [
|
||||
"node-based UI",
|
||||
|
||||
@@ -130,6 +130,7 @@
|
||||
.xy-flow__connectionline {
|
||||
z-index: 1001;
|
||||
overflow: visible;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.xy-flow__nodes {
|
||||
|
||||
@@ -63,7 +63,7 @@ export type FitViewOptionsBase<NodeType extends NodeBase> = {
|
||||
minZoom?: number;
|
||||
maxZoom?: number;
|
||||
duration?: number;
|
||||
nodes?: (Partial<NodeType> & { id: NodeType['id'] })[];
|
||||
nodes?: (NodeType | { id: NodeType['id'] })[];
|
||||
};
|
||||
|
||||
export type Viewport = {
|
||||
|
||||
@@ -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 HandleElement = XYPosition &
|
||||
Dimensions & {
|
||||
id?: string | null;
|
||||
position: Position;
|
||||
};
|
||||
export type HandleElement = {
|
||||
id?: string | null;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
position: Position;
|
||||
type?: HandleType;
|
||||
};
|
||||
|
||||
export type ConnectingHandle = {
|
||||
nodeId: string;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { internalsSymbol } from '../constants';
|
||||
import type { XYPosition, Position, CoordinateExtent, HandleElement } from '.';
|
||||
import { Optional } from '../utils/types';
|
||||
|
||||
// this is stuff that all nodes share independent of the framework
|
||||
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;
|
||||
focusable?: boolean;
|
||||
origin?: NodeOrigin;
|
||||
handles?: NodeHandle[];
|
||||
size?: {
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
|
||||
// only used internally
|
||||
[internalsSymbol]?: {
|
||||
@@ -89,3 +95,5 @@ export type NodeOrigin = [number, number];
|
||||
export type OnNodeDrag = (event: MouseEvent, node: NodeBase, nodes: NodeBase[]) => void;
|
||||
|
||||
export type OnSelectionDrag = (event: MouseEvent, nodes: NodeBase[]) => void;
|
||||
|
||||
export type NodeHandle = Optional<HandleElement, 'width' | 'height'>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { EdgePosition } from '../../types/edges';
|
||||
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 { errorMessages, internalsSymbol } from '../../constants';
|
||||
import { HandleElement } from '../../types';
|
||||
@@ -16,10 +16,10 @@ export type GetEdgePositionParams = {
|
||||
};
|
||||
|
||||
export function getEdgePosition(params: GetEdgePositionParams): EdgePosition | null {
|
||||
const [sourceNodeRect, sourceHandleBounds, sourceIsValid] = getHandleDataByNode(params.sourceNode);
|
||||
const [targetNodeRect, targetHandleBounds, targetIsValid] = getHandleDataByNode(params.targetNode);
|
||||
const [sourceNodeRect, sourceHandleBounds, isSourceValid] = getHandleDataByNode(params.sourceNode);
|
||||
const [targetNodeRect, targetHandleBounds, isTargetValid] = getHandleDataByNode(params.targetNode);
|
||||
|
||||
if (!sourceIsValid || !targetIsValid) {
|
||||
if (!isSourceValid || !isTargetValid) {
|
||||
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] {
|
||||
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 =
|
||||
handleBounds &&
|
||||
node?.width &&
|
||||
node?.height &&
|
||||
nodeWidth &&
|
||||
nodeHeight &&
|
||||
typeof node?.positionAbsolute?.x !== 'undefined' &&
|
||||
typeof node?.positionAbsolute?.y !== 'undefined';
|
||||
|
||||
@@ -73,8 +102,8 @@ function getHandleDataByNode(node?: NodeBase): [Rect, NodeHandleBounds | null, b
|
||||
{
|
||||
x: node?.positionAbsolute?.x || 0,
|
||||
y: node?.positionAbsolute?.y || 0,
|
||||
width: node?.width || 0,
|
||||
height: node?.height || 0,
|
||||
width: nodeWidth || 0,
|
||||
height: nodeHeight || 0,
|
||||
},
|
||||
handleBounds,
|
||||
!!isValid,
|
||||
|
||||
@@ -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);
|
||||
|
||||
export const getOutgoersBase = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>(
|
||||
node: Partial<NodeType> & { id: string },
|
||||
node: NodeType | { id: string },
|
||||
nodes: NodeType[],
|
||||
edges: EdgeType[]
|
||||
): 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>(
|
||||
node: Partial<NodeType> & { id: string },
|
||||
node: NodeType | { id: string },
|
||||
nodes: NodeType[],
|
||||
edges: EdgeType[]
|
||||
): NodeType[] => {
|
||||
|
||||
1
packages/system/src/utils/types.ts
Normal file
1
packages/system/src/utils/types.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
|
||||
@@ -46,7 +46,7 @@ type StoreItems = {
|
||||
selectNodesOnDrag: boolean;
|
||||
nodeDragThreshold: number;
|
||||
panBy: PanBy;
|
||||
unselectNodesAndEdges: () => void;
|
||||
unselectNodesAndEdges: (params?: { nodes?: NodeBase[]; edges?: EdgeBase[] }) => void;
|
||||
onError?: OnError;
|
||||
onNodeDragStart?: OnNodeDrag;
|
||||
onNodeDrag?: OnNodeDrag;
|
||||
@@ -63,7 +63,7 @@ export type XYDragParams = {
|
||||
onDragStart?: OnDrag;
|
||||
onDrag?: OnDrag;
|
||||
onDragStop?: OnDrag;
|
||||
onNodeClick?: () => void;
|
||||
onNodeMouseDown?: (id: string) => void;
|
||||
};
|
||||
|
||||
export type XYDragInstance = {
|
||||
@@ -81,7 +81,7 @@ export type DragUpdateParams = {
|
||||
|
||||
export function XYDrag({
|
||||
domNode,
|
||||
onNodeClick,
|
||||
onNodeMouseDown,
|
||||
getStoreItems,
|
||||
onDragStart,
|
||||
onDrag,
|
||||
@@ -217,8 +217,8 @@ export function XYDrag({
|
||||
}
|
||||
}
|
||||
|
||||
if (isSelectable && selectNodesOnDrag) {
|
||||
onNodeClick?.();
|
||||
if (isSelectable && selectNodesOnDrag && nodeId) {
|
||||
onNodeMouseDown?.(nodeId);
|
||||
}
|
||||
|
||||
const pointerPos = getPointerPosition(event.sourceEvent, { transform, snapGrid, snapToGrid });
|
||||
|
||||
6645
pnpm-lock.yaml
generated
6645
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -30,6 +30,7 @@ export const esmConfig = defineConfig({
|
||||
output: {
|
||||
file: pkg.module,
|
||||
format: 'esm',
|
||||
banner: '"use client"',
|
||||
},
|
||||
onwarn,
|
||||
plugins: [
|
||||
|
||||
Reference in New Issue
Block a user