diff --git a/packages/svelte/.eslintrc.cjs b/packages/svelte/.eslintrc.cjs index 3ccf435f..eaf19f56 100644 --- a/packages/svelte/.eslintrc.cjs +++ b/packages/svelte/.eslintrc.cjs @@ -1,20 +1,20 @@ module.exports = { - root: true, - parser: '@typescript-eslint/parser', - extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'], - plugins: ['svelte3', '@typescript-eslint'], - ignorePatterns: ['*.cjs'], - overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], - settings: { - 'svelte3/typescript': () => require('typescript') - }, - parserOptions: { - sourceType: 'module', - ecmaVersion: 2020 - }, - env: { - browser: true, - es2017: true, - node: true - } + root: true, + parser: '@typescript-eslint/parser', + extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'], + plugins: ['svelte3', '@typescript-eslint'], + ignorePatterns: ['*.cjs'], + overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], + settings: { + 'svelte3/typescript': () => require('typescript') + }, + parserOptions: { + sourceType: 'module', + ecmaVersion: 2020 + }, + env: { + browser: true, + es2017: true, + node: true + } }; diff --git a/packages/svelte/.prettierrc b/packages/svelte/.prettierrc index a77fddea..862e74f2 100644 --- a/packages/svelte/.prettierrc +++ b/packages/svelte/.prettierrc @@ -1,9 +1,8 @@ { - "useTabs": true, - "singleQuote": true, - "trailingComma": "none", - "printWidth": 100, - "plugins": ["prettier-plugin-svelte"], - "pluginSearchDirs": ["."], - "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }] + "singleQuote": true, + "trailingComma": "none", + "printWidth": 100, + "plugins": ["prettier-plugin-svelte"], + "pluginSearchDirs": ["."], + "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }] } diff --git a/packages/svelte/package.json b/packages/svelte/package.json index cd4162bd..98f38b77 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -1,47 +1,47 @@ { - "name": "svelte", - "version": "0.0.1", - "scripts": { - "dev": "vite dev", - "build": "svelte-kit sync && svelte-package", - "prepublishOnly": "echo 'Did you mean to publish `./package/`, instead of `./`?' && exit 1", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", - "lint": "prettier --plugin-search-dir . --check . && eslint .", - "format": "prettier --plugin-search-dir . --write ." - }, - "type": "module", - "module": "index.ts", - "exports": { - ".": "./index.js" - }, - "dependencies": { - "@reactflow/edge-utils": "workspace:*", - "@reactflow/system": "workspace:*", - "@reactflow/utils": "workspace:*", - "@svelte-put/shortcut": "^2.0.0", - "classcat": "^5.0.4", - "d3-drag": "^3.0.0", - "d3-selection": "^3.0.0", - "d3-zoom": "^3.0.0", - "react": "^18.2.0", - "react-dom": "^18.2.0" - }, - "devDependencies": { - "@sveltejs/adapter-auto": "^2.0.0", - "@sveltejs/kit": "^1.5.6", - "@sveltejs/package": "^1.0.2", - "@typescript-eslint/eslint-plugin": "^5.45.0", - "@typescript-eslint/parser": "^5.45.0", - "eslint": "^8.28.0", - "eslint-config-prettier": "^8.5.0", - "eslint-plugin-svelte3": "^4.0.0", - "prettier": "^2.8.0", - "prettier-plugin-svelte": "^2.8.1", - "svelte": "^3.55.1", - "svelte-check": "^3.0.1", - "tslib": "^2.4.1", - "typescript": "^4.9.3", - "vite": "^4.1.1" - } + "name": "svelte", + "version": "0.0.1", + "scripts": { + "dev": "vite dev", + "build": "svelte-kit sync && svelte-package", + "prepublishOnly": "echo 'Did you mean to publish `./package/`, instead of `./`?' && exit 1", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", + "lint": "prettier --plugin-search-dir . --check . && eslint .", + "format": "prettier --plugin-search-dir . --write ." + }, + "type": "module", + "module": "index.ts", + "exports": { + ".": "./index.js" + }, + "dependencies": { + "@reactflow/edge-utils": "workspace:*", + "@reactflow/system": "workspace:*", + "@reactflow/utils": "workspace:*", + "@svelte-put/shortcut": "^2.0.0", + "classcat": "^5.0.4", + "d3-drag": "^3.0.0", + "d3-selection": "^3.0.0", + "d3-zoom": "^3.0.0", + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "devDependencies": { + "@sveltejs/adapter-auto": "^2.0.0", + "@sveltejs/kit": "^1.5.6", + "@sveltejs/package": "^1.0.2", + "@typescript-eslint/eslint-plugin": "^5.45.0", + "@typescript-eslint/parser": "^5.45.0", + "eslint": "^8.28.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-svelte3": "^4.0.0", + "prettier": "^2.8.0", + "prettier-plugin-svelte": "^2.8.1", + "svelte": "^3.55.1", + "svelte-check": "^3.0.1", + "tslib": "^2.4.1", + "typescript": "^4.9.3", + "vite": "^4.1.1" + } } diff --git a/packages/svelte/src/app.d.ts b/packages/svelte/src/app.d.ts index f59b884c..899c7e8f 100644 --- a/packages/svelte/src/app.d.ts +++ b/packages/svelte/src/app.d.ts @@ -1,12 +1,12 @@ // See https://kit.svelte.dev/docs/types#app // for information about these interfaces declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface Platform {} - } + namespace App { + // interface Error {} + // interface Locals {} + // interface PageData {} + // interface Platform {} + } } export {}; diff --git a/packages/svelte/src/app.html b/packages/svelte/src/app.html index 9e4c67b4..442bc220 100644 --- a/packages/svelte/src/app.html +++ b/packages/svelte/src/app.html @@ -1,21 +1,21 @@ - - - - - - %sveltekit.head% - - -
%sveltekit.body%
- + + + + + + %sveltekit.head% + + +
%sveltekit.body%
+ diff --git a/packages/svelte/src/customnodes/Custom.svelte b/packages/svelte/src/customnodes/Custom.svelte index c2be70f7..cb4dc2ee 100644 --- a/packages/svelte/src/customnodes/Custom.svelte +++ b/packages/svelte/src/customnodes/Custom.svelte @@ -1,7 +1,7 @@ {#if $connectionPath} - + @@ -43,4 +39,4 @@ stroke-width: 1; fill: none; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/components/EdgeLabelRenderer/index.svelte b/packages/svelte/src/lib/components/EdgeLabelRenderer/index.svelte index 03000191..b76d8b05 100644 --- a/packages/svelte/src/lib/components/EdgeLabelRenderer/index.svelte +++ b/packages/svelte/src/lib/components/EdgeLabelRenderer/index.svelte @@ -1,9 +1,9 @@
-
\ No newline at end of file + diff --git a/packages/svelte/src/lib/components/Handle/handler.ts b/packages/svelte/src/lib/components/Handle/handler.ts index 56be794a..d9da352f 100644 --- a/packages/svelte/src/lib/components/Handle/handler.ts +++ b/packages/svelte/src/lib/components/Handle/handler.ts @@ -1,210 +1,210 @@ import { - getHostForElement, - calcAutoPan, - getEventPosition, - pointToRendererPoint, - rendererPointToPoint + getHostForElement, + calcAutoPan, + getEventPosition, + pointToRendererPoint, + rendererPointToPoint } from '@reactflow/utils'; import type { - OnConnect, - HandleType, - Connection, - ConnectionMode, - Node, - XYPosition, - Transform + OnConnect, + HandleType, + Connection, + ConnectionMode, + Node, + XYPosition, + Transform } from '@reactflow/system'; import { - getClosestHandle, - getConnectionStatus, - getHandleLookup, - getHandleType, - isValidHandle, - resetRecentHandle, - type ConnectionHandle, - type ValidConnectionFunc + getClosestHandle, + getConnectionStatus, + getHandleLookup, + getHandleType, + isValidHandle, + resetRecentHandle, + type ConnectionHandle, + type ValidConnectionFunc } from './utils'; import { get, type Writable } from 'svelte/store'; import type { ConnectionData } from '$lib/types'; export function handlePointerDown({ - event, - handleId, - nodeId, - onConnect, - domNode, - nodes, - connectionMode, - connectionRadius, - isTarget, - transform: transformStore, - panBy, - updateConnection, - cancelConnection, - isValidConnection, - edgeUpdaterType, - onEdgeUpdateEnd + event, + handleId, + nodeId, + onConnect, + domNode, + nodes, + connectionMode, + connectionRadius, + isTarget, + transform: transformStore, + panBy, + updateConnection, + cancelConnection, + isValidConnection, + edgeUpdaterType, + onEdgeUpdateEnd }: { - event: MouseEvent | TouchEvent; - handleId: string | null; - nodeId: string; - onConnect: OnConnect; - isTarget: boolean; - connectionMode: ConnectionMode; - domNode: HTMLDivElement | null; - nodes: Node[]; - connectionRadius: number; - isValidConnection: ValidConnectionFunc; - transform: Writable; - updateConnection: (connection: Partial) => void; - cancelConnection: () => void; - panBy: (delta: XYPosition) => void; - edgeUpdaterType?: HandleType; - onEdgeUpdateEnd?: (evt: MouseEvent | TouchEvent) => void; + event: MouseEvent | TouchEvent; + handleId: string | null; + nodeId: string; + onConnect: OnConnect; + isTarget: boolean; + connectionMode: ConnectionMode; + domNode: HTMLDivElement | null; + nodes: Node[]; + connectionRadius: number; + isValidConnection: ValidConnectionFunc; + transform: Writable; + updateConnection: (connection: Partial) => void; + cancelConnection: () => void; + panBy: (delta: XYPosition) => void; + edgeUpdaterType?: HandleType; + onEdgeUpdateEnd?: (evt: MouseEvent | TouchEvent) => void; }): void { - // when react-flow is used inside a shadow root we can't use document - const doc = getHostForElement(event.target as HTMLElement); - let autoPanId = 0; - let prevClosestHandle: ConnectionHandle | null; + // when react-flow is used inside a shadow root we can't use document + const doc = getHostForElement(event.target as HTMLElement); + let autoPanId = 0; + let prevClosestHandle: ConnectionHandle | null; - const { x, y } = getEventPosition(event); - const clickedHandle = doc?.elementFromPoint(x, y); - const handleType = getHandleType(edgeUpdaterType, clickedHandle); - const containerBounds = domNode?.getBoundingClientRect(); + const { x, y } = getEventPosition(event); + const clickedHandle = doc?.elementFromPoint(x, y); + const handleType = getHandleType(edgeUpdaterType, clickedHandle); + const containerBounds = domNode?.getBoundingClientRect(); - if (!containerBounds || !handleType) { - return; - } + if (!containerBounds || !handleType) { + return; + } - let prevActiveHandle: Element; - let connectionPosition = getEventPosition(event, containerBounds); - let autoPanStarted = false; - let connection: Connection | null = null; - let isValid = false; - let handleDomNode: Element | null = null; + let prevActiveHandle: Element; + let connectionPosition = getEventPosition(event, containerBounds); + let autoPanStarted = false; + let connection: Connection | null = null; + let isValid = false; + let handleDomNode: Element | null = null; - const autoPanOnConnect = true; + const autoPanOnConnect = true; - const handleLookup = getHandleLookup({ - nodes, - nodeId, - handleId, - handleType - }); + const handleLookup = getHandleLookup({ + nodes, + nodeId, + handleId, + handleType + }); - // when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas - const autoPan = (): void => { - // @todd add prop - if (!autoPanOnConnect) { - return; - } - const [xMovement, yMovement] = calcAutoPan(connectionPosition, containerBounds); + // when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas + const autoPan = (): void => { + // @todd add prop + if (!autoPanOnConnect) { + return; + } + const [xMovement, yMovement] = calcAutoPan(connectionPosition, containerBounds); - panBy({ x: xMovement, y: yMovement }); - autoPanId = requestAnimationFrame(autoPan); - }; + panBy({ x: xMovement, y: yMovement }); + autoPanId = requestAnimationFrame(autoPan); + }; - updateConnection({ - position: connectionPosition, - nodeId, - handleId, - handleType, - status: null - }); + updateConnection({ + position: connectionPosition, + nodeId, + handleId, + handleType, + status: null + }); - // @todo add prop - // onConnectStart?.(event, { nodeId, handleId, handleType }); + // @todo add prop + // onConnectStart?.(event, { nodeId, handleId, handleType }); - function onPointerMove(event: MouseEvent | TouchEvent) { - const transform = get(transformStore); - connectionPosition = getEventPosition(event, containerBounds); + function onPointerMove(event: MouseEvent | TouchEvent) { + const transform = get(transformStore); + connectionPosition = getEventPosition(event, containerBounds); - prevClosestHandle = getClosestHandle( - pointToRendererPoint(connectionPosition, transform, false, [1, 1]), - connectionRadius, - handleLookup - ); + prevClosestHandle = getClosestHandle( + pointToRendererPoint(connectionPosition, transform, false, [1, 1]), + connectionRadius, + handleLookup + ); - if (!autoPanStarted) { - autoPan(); - autoPanStarted = true; - } + if (!autoPanStarted) { + autoPan(); + autoPanStarted = true; + } - const result = isValidHandle( - event, - prevClosestHandle, - connectionMode, - nodeId, - handleId, - isTarget ? 'target' : 'source', - isValidConnection, - doc - ); + const result = isValidHandle( + event, + prevClosestHandle, + connectionMode, + nodeId, + handleId, + isTarget ? 'target' : 'source', + isValidConnection, + doc + ); - handleDomNode = result.handleDomNode; - connection = result.connection; - isValid = result.isValid; + handleDomNode = result.handleDomNode; + connection = result.connection; + isValid = result.isValid; - updateConnection({ - position: - prevClosestHandle && isValid - ? rendererPointToPoint( - { - x: prevClosestHandle.x, - y: prevClosestHandle.y - }, - transform - ) - : connectionPosition, - status: getConnectionStatus(!!prevClosestHandle, isValid) - }); + updateConnection({ + position: + prevClosestHandle && isValid + ? rendererPointToPoint( + { + x: prevClosestHandle.x, + y: prevClosestHandle.y + }, + transform + ) + : connectionPosition, + status: getConnectionStatus(!!prevClosestHandle, isValid) + }); - if (!prevClosestHandle && !isValid && !handleDomNode) { - return resetRecentHandle(prevActiveHandle); - } + if (!prevClosestHandle && !isValid && !handleDomNode) { + return resetRecentHandle(prevActiveHandle); + } - if (connection.source !== connection.target && handleDomNode) { - resetRecentHandle(prevActiveHandle); - prevActiveHandle = handleDomNode; - // @todo: remove the old class names "react-flow__handle-" in the next major version - handleDomNode.classList.add('connecting'); - handleDomNode.classList.toggle('valid', isValid); - } - } + if (connection.source !== connection.target && handleDomNode) { + resetRecentHandle(prevActiveHandle); + prevActiveHandle = handleDomNode; + // @todo: remove the old class names "react-flow__handle-" in the next major version + handleDomNode.classList.add('connecting'); + handleDomNode.classList.toggle('valid', isValid); + } + } - function onPointerUp(event: MouseEvent | TouchEvent) { - if ((prevClosestHandle || handleDomNode) && connection && isValid) { - onConnect?.(connection); - } + function onPointerUp(event: MouseEvent | TouchEvent) { + if ((prevClosestHandle || handleDomNode) && connection && isValid) { + onConnect?.(connection); + } - // it's important to get a fresh reference from the store here - // in order to get the latest state of onConnectEnd - // @todo add onConnectEnd prop - // getState().onConnectEnd?.(event); + // it's important to get a fresh reference from the store here + // in order to get the latest state of onConnectEnd + // @todo add onConnectEnd prop + // getState().onConnectEnd?.(event); - if (edgeUpdaterType) { - onEdgeUpdateEnd?.(event); - } + if (edgeUpdaterType) { + onEdgeUpdateEnd?.(event); + } - resetRecentHandle(prevActiveHandle); - cancelConnection(); - cancelAnimationFrame(autoPanId); - autoPanStarted = false; - isValid = false; - connection = null; - handleDomNode = null; + resetRecentHandle(prevActiveHandle); + cancelConnection(); + cancelAnimationFrame(autoPanId); + autoPanStarted = false; + isValid = false; + connection = null; + handleDomNode = null; - doc.removeEventListener('mousemove', onPointerMove as EventListener); - doc.removeEventListener('mouseup', onPointerUp as EventListener); + doc.removeEventListener('mousemove', onPointerMove as EventListener); + doc.removeEventListener('mouseup', onPointerUp as EventListener); - doc.removeEventListener('touchmove', onPointerMove as EventListener); - doc.removeEventListener('touchend', onPointerUp as EventListener); - } + doc.removeEventListener('touchmove', onPointerMove as EventListener); + doc.removeEventListener('touchend', onPointerUp as EventListener); + } - doc.addEventListener('mousemove', onPointerMove as EventListener); - doc.addEventListener('mouseup', onPointerUp as EventListener); + doc.addEventListener('mousemove', onPointerMove as EventListener); + doc.addEventListener('mouseup', onPointerUp as EventListener); - doc.addEventListener('touchmove', onPointerMove as EventListener); - doc.addEventListener('touchend', onPointerUp as EventListener); + doc.addEventListener('touchmove', onPointerMove as EventListener); + doc.addEventListener('touchend', onPointerUp as EventListener); } diff --git a/packages/svelte/src/lib/components/Handle/index.svelte b/packages/svelte/src/lib/components/Handle/index.svelte index eef61a69..b722e3f8 100644 --- a/packages/svelte/src/lib/components/Handle/index.svelte +++ b/packages/svelte/src/lib/components/Handle/index.svelte @@ -1,11 +1,11 @@
- \ No newline at end of file + diff --git a/packages/svelte/src/lib/components/Handle/utils.ts b/packages/svelte/src/lib/components/Handle/utils.ts index adcc231d..6029dac0 100644 --- a/packages/svelte/src/lib/components/Handle/utils.ts +++ b/packages/svelte/src/lib/components/Handle/utils.ts @@ -3,11 +3,11 @@ import type { Connection, HandleType, XYPosition, Node, NodeHandleBounds } from import { getEventPosition } from '@reactflow/utils'; export type ConnectionHandle = { - id: string | null; - type: HandleType; - nodeId: string; - x: number; - y: number; + id: string | null; + type: HandleType; + nodeId: string; + x: number; + y: number; }; export type ValidConnectionFunc = (connection: Connection) => boolean; @@ -15,174 +15,174 @@ export type ValidConnectionFunc = (connection: Connection) => boolean; // this functions collects all handles and adds an absolute position // so that we can later find the closest handle to the mouse position export function getHandles( - node: Node, - handleBounds: NodeHandleBounds, - type: HandleType, - currentHandle: string + node: Node, + handleBounds: NodeHandleBounds, + type: HandleType, + currentHandle: string ): ConnectionHandle[] { - return (handleBounds[type] || []).reduce((res, h) => { - if (`${node.id}-${h.id}-${type}` !== currentHandle) { - res.push({ - id: h.id || null, - type, - nodeId: node.id, - x: (node.positionAbsolute?.x ?? 0) + h.x + h.width / 2, - y: (node.positionAbsolute?.y ?? 0) + h.y + h.height / 2 - }); - } - return res; - }, []); + return (handleBounds[type] || []).reduce((res, h) => { + if (`${node.id}-${h.id}-${type}` !== currentHandle) { + res.push({ + id: h.id || null, + type, + nodeId: node.id, + x: (node.positionAbsolute?.x ?? 0) + h.x + h.width / 2, + y: (node.positionAbsolute?.y ?? 0) + h.y + h.height / 2 + }); + } + return res; + }, []); } export function getClosestHandle( - pos: XYPosition, - connectionRadius: number, - handles: ConnectionHandle[] + pos: XYPosition, + connectionRadius: number, + handles: ConnectionHandle[] ): ConnectionHandle | null { - let closestHandle: ConnectionHandle | null = null; - let minDistance = Infinity; + let closestHandle: ConnectionHandle | null = null; + let minDistance = Infinity; - handles.forEach((handle) => { - const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2)); - if (distance <= connectionRadius && distance < minDistance) { - minDistance = distance; - closestHandle = handle; - } - }); + handles.forEach((handle) => { + const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2)); + if (distance <= connectionRadius && distance < minDistance) { + minDistance = distance; + closestHandle = handle; + } + }); - return closestHandle; + return closestHandle; } type Result = { - handleDomNode: Element | null; - isValid: boolean; - connection: Connection; + handleDomNode: Element | null; + isValid: boolean; + connection: Connection; }; const nullConnection: Connection = { - source: null, - target: null, - sourceHandle: null, - targetHandle: null + source: null, + target: null, + sourceHandle: null, + targetHandle: null }; // checks if and returns connection in fom of an object { source: 123, target: 312 } export function isValidHandle( - event: MouseEvent | TouchEvent, - handle: Pick | null, - connectionMode: ConnectionMode, - fromNodeId: string, - fromHandleId: string | null, - fromType: string, - isValidConnection: ValidConnectionFunc, - doc: Document | ShadowRoot + event: MouseEvent | TouchEvent, + handle: Pick | null, + connectionMode: ConnectionMode, + fromNodeId: string, + fromHandleId: string | null, + fromType: string, + isValidConnection: ValidConnectionFunc, + doc: Document | ShadowRoot ) { - const isTarget = fromType === 'target'; - const handleDomNode = doc.querySelector( - `.react-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]` - ); - const { x, y } = getEventPosition(event); - const handleBelow = doc.elementFromPoint(x, y); - const handleToCheck = handleBelow?.classList.contains('react-flow__handle') - ? handleBelow - : handleDomNode; + const isTarget = fromType === 'target'; + const handleDomNode = doc.querySelector( + `.react-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]` + ); + const { x, y } = getEventPosition(event); + const handleBelow = doc.elementFromPoint(x, y); + const handleToCheck = handleBelow?.classList.contains('react-flow__handle') + ? handleBelow + : handleDomNode; - const result: Result = { - handleDomNode: handleToCheck, - isValid: false, - connection: nullConnection - }; + const result: Result = { + handleDomNode: handleToCheck, + isValid: false, + connection: nullConnection + }; - if (handleToCheck) { - const handleType = getHandleType(undefined, handleToCheck); - const handleNodeId = handleToCheck.getAttribute('data-nodeid'); - const handleId = handleToCheck.getAttribute('data-handleid'); + if (handleToCheck) { + const handleType = getHandleType(undefined, handleToCheck); + const handleNodeId = handleToCheck.getAttribute('data-nodeid'); + const handleId = handleToCheck.getAttribute('data-handleid'); - const connection: Connection = { - source: isTarget ? handleNodeId : fromNodeId, - sourceHandle: isTarget ? handleId : fromHandleId, - target: isTarget ? fromNodeId : handleNodeId, - targetHandle: isTarget ? fromHandleId : handleId - }; + const connection: Connection = { + source: isTarget ? handleNodeId : fromNodeId, + sourceHandle: isTarget ? handleId : fromHandleId, + target: isTarget ? fromNodeId : handleNodeId, + targetHandle: isTarget ? fromHandleId : handleId + }; - result.connection = connection; + result.connection = connection; - // in strict mode we don't allow target to target or source to source connections - const isValid = - connectionMode === ConnectionMode.Strict - ? (isTarget && handleType === 'source') || (!isTarget && handleType === 'target') - : handleNodeId !== fromNodeId || handleId !== fromHandleId; + // in strict mode we don't allow target to target or source to source connections + const isValid = + connectionMode === ConnectionMode.Strict + ? (isTarget && handleType === 'source') || (!isTarget && handleType === 'target') + : handleNodeId !== fromNodeId || handleId !== fromHandleId; - if (isValid) { - result.isValid = isValidConnection(connection); - } - } + if (isValid) { + result.isValid = isValidConnection(connection); + } + } - return result; + return result; } type GetHandleLookupParams = { - nodes: Node[]; - nodeId: string; - handleId: string | null; - handleType: string; + nodes: Node[]; + nodeId: string; + handleId: string | null; + handleType: string; }; export function getHandleLookup({ nodes, nodeId, handleId, handleType }: GetHandleLookupParams) { - return nodes.reduce((res, node) => { - if (node[internalsSymbol]) { - const { handleBounds } = node[internalsSymbol]; - let sourceHandles: ConnectionHandle[] = []; - let targetHandles: ConnectionHandle[] = []; + return nodes.reduce((res, node) => { + if (node[internalsSymbol]) { + const { handleBounds } = node[internalsSymbol]; + let sourceHandles: ConnectionHandle[] = []; + let targetHandles: ConnectionHandle[] = []; - if (handleBounds) { - sourceHandles = getHandles( - node, - handleBounds, - 'source', - `${nodeId}-${handleId}-${handleType}` - ); - targetHandles = getHandles( - node, - handleBounds, - 'target', - `${nodeId}-${handleId}-${handleType}` - ); - } + if (handleBounds) { + sourceHandles = getHandles( + node, + handleBounds, + 'source', + `${nodeId}-${handleId}-${handleType}` + ); + targetHandles = getHandles( + node, + handleBounds, + 'target', + `${nodeId}-${handleId}-${handleType}` + ); + } - res.push(...sourceHandles, ...targetHandles); - } - return res; - }, []); + res.push(...sourceHandles, ...targetHandles); + } + return res; + }, []); } export function getHandleType( - edgeUpdaterType: HandleType | undefined, - handleDomNode: Element | null + edgeUpdaterType: HandleType | undefined, + handleDomNode: Element | null ): HandleType | null { - if (edgeUpdaterType) { - return edgeUpdaterType; - } else if (handleDomNode?.classList.contains('target')) { - return 'target'; - } else if (handleDomNode?.classList.contains('source')) { - return 'source'; - } + if (edgeUpdaterType) { + return edgeUpdaterType; + } else if (handleDomNode?.classList.contains('target')) { + return 'target'; + } else if (handleDomNode?.classList.contains('source')) { + return 'source'; + } - return null; + return null; } export function resetRecentHandle(handleDomNode: Element): void { - handleDomNode?.classList.remove('valid', 'connecting'); + handleDomNode?.classList.remove('valid', 'connecting'); } export function getConnectionStatus(isInsideConnectionRadius: boolean, isHandleValid: boolean) { - let connectionStatus = null; + let connectionStatus = null; - if (isHandleValid) { - connectionStatus = 'valid'; - } else if (isInsideConnectionRadius && !isHandleValid) { - connectionStatus = 'invalid'; - } + if (isHandleValid) { + connectionStatus = 'valid'; + } else if (isInsideConnectionRadius && !isHandleValid) { + connectionStatus = 'invalid'; + } - return connectionStatus as ConnectionStatus; + return connectionStatus as ConnectionStatus; } diff --git a/packages/svelte/src/lib/components/KeyHandler/KeyHandler.d.ts b/packages/svelte/src/lib/components/KeyHandler/KeyHandler.d.ts index d4fa169e..d7ef91b7 100644 --- a/packages/svelte/src/lib/components/KeyHandler/KeyHandler.d.ts +++ b/packages/svelte/src/lib/components/KeyHandler/KeyHandler.d.ts @@ -1,6 +1,6 @@ import { KeyDefinition } from '$lib/types'; export type KeyHandlerProps = { - selectionKey?: KeyDefinition; - deleteKey?: KeyDefinition; + selectionKey?: KeyDefinition; + deleteKey?: KeyDefinition; }; diff --git a/packages/svelte/src/lib/components/KeyHandler/KeyHandler.svelte b/packages/svelte/src/lib/components/KeyHandler/KeyHandler.svelte index 512a4303..adb11dae 100644 --- a/packages/svelte/src/lib/components/KeyHandler/KeyHandler.svelte +++ b/packages/svelte/src/lib/components/KeyHandler/KeyHandler.svelte @@ -2,19 +2,19 @@ import { shortcut } from '@svelte-put/shortcut'; import { useStore } from '$lib/store'; - import type { KeyHandlerProps } from './KeyHandler' - import type { KeyDefinition, KeyDefinitionObject } from '$lib/types'; + import type { KeyHandlerProps } from './KeyHandler'; + import type { KeyDefinition, KeyDefinitionObject } from '$lib/types'; const { selectionKeyPressed, deleteKeyPressed } = useStore(); type $$Props = KeyHandlerProps; - export let selectionKey: $$Props['selectionKey'] = 'Shift'; - export let deleteKey: $$Props['deleteKey'] = 'Backspace'; + export let selectionKey: $$Props['selectionKey'] = 'Shift'; + export let deleteKey: $$Props['deleteKey'] = 'Backspace'; function isKeyObject(key?: KeyDefinition): key is KeyDefinitionObject { return typeof key === 'object'; - } + } $: selectionKeyString = typeof selectionKey === 'string' ? selectionKey : selectionKey!.key; $: selectionKeyModifier = isKeyObject(selectionKey) ? selectionKey?.modifier : []; @@ -24,20 +24,44 @@ selectionKeyPressed.set(true) }], + use:shortcut={{ + trigger: [ + { + key: selectionKeyString, + modifier: selectionKeyModifier, + callback: () => selectionKeyPressed.set(true) + } + ], type: 'keydown' }} - use:shortcut={{ - trigger: [{ key: selectionKeyString, modifier: selectionKeyModifier, callback: () => selectionKeyPressed.set(false) }], + use:shortcut={{ + trigger: [ + { + key: selectionKeyString, + modifier: selectionKeyModifier, + callback: () => selectionKeyPressed.set(false) + } + ], type: 'keyup' }} - use:shortcut={{ - trigger: [{ key: deleteKeyString, modifier: deleteKeyModifier, callback: () => deleteKeyPressed.set(true) }], + use:shortcut={{ + trigger: [ + { + key: deleteKeyString, + modifier: deleteKeyModifier, + callback: () => deleteKeyPressed.set(true) + } + ], type: 'keydown' }} - use:shortcut={{ - trigger: [{ key: deleteKeyString, modifier: deleteKeyModifier, callback: () => deleteKeyPressed.set(false) }], + use:shortcut={{ + trigger: [ + { + key: deleteKeyString, + modifier: deleteKeyModifier, + callback: () => deleteKeyPressed.set(false) + } + ], type: 'keyup' }} /> diff --git a/packages/svelte/src/lib/components/NodeSelection/index.svelte b/packages/svelte/src/lib/components/NodeSelection/index.svelte index a992bc7f..5b649d36 100644 --- a/packages/svelte/src/lib/components/NodeSelection/index.svelte +++ b/packages/svelte/src/lib/components/NodeSelection/index.svelte @@ -1,15 +1,15 @@ + {#if selectedNodes}
\ No newline at end of file + diff --git a/packages/svelte/src/lib/components/Selection/index.svelte b/packages/svelte/src/lib/components/Selection/index.svelte index 9cb9a4c2..d4e41d04 100644 --- a/packages/svelte/src/lib/components/Selection/index.svelte +++ b/packages/svelte/src/lib/components/Selection/index.svelte @@ -4,7 +4,7 @@ export let width: number | null = 0; export let height: number | null = 0; export let isVisible: boolean = true; - + {#if isVisible}
+ - + {#if interactionWidth} - {label} + {label}
{/if} @@ -43,4 +39,4 @@ position: absolute; background: white; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/components/edges/BezierEdge.svelte b/packages/svelte/src/lib/components/edges/BezierEdge.svelte index c9e4cc4f..fa8b6914 100644 --- a/packages/svelte/src/lib/components/edges/BezierEdge.svelte +++ b/packages/svelte/src/lib/components/edges/BezierEdge.svelte @@ -2,7 +2,7 @@ import { getBezierPath } from '@reactflow/edge-utils'; import type { EdgeProps } from '$lib/types'; - import BaseEdge from './BaseEdge.svelte'; + import BaseEdge from './BaseEdge.svelte'; type $$Props = EdgeProps; @@ -12,13 +12,8 @@ targetX: $$props.targetX, targetY: $$props.targetY, sourcePosition: $$props.sourcePosition, - targetPosition: $$props.targetPosition, + targetPosition: $$props.targetPosition }); - + diff --git a/packages/svelte/src/lib/components/edges/EdgeWrapper.svelte b/packages/svelte/src/lib/components/edges/EdgeWrapper.svelte index 7a18f90e..8f24ab5e 100644 --- a/packages/svelte/src/lib/components/edges/EdgeWrapper.svelte +++ b/packages/svelte/src/lib/components/edges/EdgeWrapper.svelte @@ -1,10 +1,10 @@ - + - \ No newline at end of file + diff --git a/packages/svelte/src/lib/components/edges/StraightEdge.svelte b/packages/svelte/src/lib/components/edges/StraightEdge.svelte index f1d7c190..5e27ec3d 100644 --- a/packages/svelte/src/lib/components/edges/StraightEdge.svelte +++ b/packages/svelte/src/lib/components/edges/StraightEdge.svelte @@ -1,8 +1,8 @@ - \ No newline at end of file + diff --git a/packages/svelte/src/lib/components/nodes/DefaultNode.svelte b/packages/svelte/src/lib/components/nodes/DefaultNode.svelte index 22c551d8..1c10eb34 100644 --- a/packages/svelte/src/lib/components/nodes/DefaultNode.svelte +++ b/packages/svelte/src/lib/components/nodes/DefaultNode.svelte @@ -1,10 +1,10 @@
\ No newline at end of file + diff --git a/packages/svelte/src/lib/components/nodes/OutputNode.svelte b/packages/svelte/src/lib/components/nodes/OutputNode.svelte index 41c31a2f..7c42facd 100644 --- a/packages/svelte/src/lib/components/nodes/OutputNode.svelte +++ b/packages/svelte/src/lib/components/nodes/OutputNode.svelte @@ -1,6 +1,6 @@ + - + {#each $edgesLayouted as edge (edge.id)} {/each} @@ -25,4 +21,4 @@ pointer-events: none; overflow: visible; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/container/EdgeRenderer/utils.ts b/packages/svelte/src/lib/container/EdgeRenderer/utils.ts index 139a9d68..c593abf9 100644 --- a/packages/svelte/src/lib/container/EdgeRenderer/utils.ts +++ b/packages/svelte/src/lib/container/EdgeRenderer/utils.ts @@ -1,105 +1,105 @@ import { - type NodeHandleBounds, - type Rect, - type Node, - type HandleElement, - type XYPosition, - Position, - internalsSymbol + type NodeHandleBounds, + type Rect, + type Node, + type HandleElement, + type XYPosition, + Position, + internalsSymbol } from '@reactflow/system'; export function getNodeData(node?: Node): [Rect, NodeHandleBounds | null, boolean] { - const handleBounds = node?.[internalsSymbol]?.handleBounds || null; + const handleBounds = node?.[internalsSymbol]?.handleBounds || null; - const isValid = - handleBounds && - node?.width && - node?.height && - typeof node?.positionAbsolute?.x !== 'undefined' && - typeof node?.positionAbsolute?.y !== 'undefined'; + const isValid = + handleBounds && + node?.width && + node?.height && + typeof node?.positionAbsolute?.x !== 'undefined' && + typeof node?.positionAbsolute?.y !== 'undefined'; - return [ - { - x: node?.positionAbsolute?.x || 0, - y: node?.positionAbsolute?.y || 0, - width: node?.width || 0, - height: node?.height || 0 - }, - handleBounds, - !!isValid - ]; + return [ + { + x: node?.positionAbsolute?.x || 0, + y: node?.positionAbsolute?.y || 0, + width: node?.width || 0, + height: node?.height || 0 + }, + handleBounds, + !!isValid + ]; } export function getHandlePosition( - position: Position, - nodeRect: Rect, - handle: HandleElement | null = null + position: Position, + nodeRect: Rect, + handle: HandleElement | null = null ): XYPosition { - const x = (handle?.x || 0) + nodeRect.x; - const y = (handle?.y || 0) + nodeRect.y; - const width = handle?.width || nodeRect.width; - const height = handle?.height || nodeRect.height; + const x = (handle?.x || 0) + nodeRect.x; + const y = (handle?.y || 0) + nodeRect.y; + const width = handle?.width || nodeRect.width; + const height = handle?.height || nodeRect.height; - switch (position) { - case Position.Top: - return { - x: x + width / 2, - y - }; - case Position.Right: - return { - x: x + width, - y: y + height / 2 - }; - case Position.Bottom: - return { - x: x + width / 2, - y: y + height - }; - case Position.Left: - return { - x, - y: y + height / 2 - }; - } + switch (position) { + case Position.Top: + return { + x: x + width / 2, + y + }; + case Position.Right: + return { + x: x + width, + y: y + height / 2 + }; + case Position.Bottom: + return { + x: x + width / 2, + y: y + height + }; + case Position.Left: + return { + x, + y: y + height / 2 + }; + } } export function getHandle(bounds: HandleElement[], handleId?: string | null): HandleElement | null { - if (!bounds) { - return null; - } + if (!bounds) { + return null; + } - if (handleId) { - return bounds.find((d) => d.id === handleId)!; - } else if (bounds.length === 1) { - return bounds[0]; - } + if (handleId) { + return bounds.find((d) => d.id === handleId)!; + } else if (bounds.length === 1) { + return bounds[0]; + } - return null; + return null; } export type EdgePosition = { - sourceX: number; - sourceY: number; - targetX: number; - targetY: number; + sourceX: number; + sourceY: number; + targetX: number; + targetY: number; }; export function getEdgePositions( - sourceNodeRect: Rect, - sourceHandle: HandleElement, - sourcePosition: Position, - targetNodeRect: Rect, - targetHandle: HandleElement, - targetPosition: Position + sourceNodeRect: Rect, + sourceHandle: HandleElement, + sourcePosition: Position, + targetNodeRect: Rect, + targetHandle: HandleElement, + targetPosition: Position ): EdgePosition { - const sourceHandlePos = getHandlePosition(sourcePosition, sourceNodeRect, sourceHandle); - const targetHandlePos = getHandlePosition(targetPosition, targetNodeRect, targetHandle); + const sourceHandlePos = getHandlePosition(sourcePosition, sourceNodeRect, sourceHandle); + const targetHandlePos = getHandlePosition(targetPosition, targetNodeRect, targetHandle); - return { - sourceX: sourceHandlePos.x, - sourceY: sourceHandlePos.y, - targetX: targetHandlePos.x, - targetY: targetHandlePos.y - }; + return { + sourceX: sourceHandlePos.x, + sourceY: sourceHandlePos.y, + targetX: targetHandlePos.x, + targetY: targetHandlePos.y + }; } diff --git a/packages/svelte/src/lib/container/NodeRenderer/index.svelte b/packages/svelte/src/lib/container/NodeRenderer/index.svelte index 1312ecfa..74021b77 100644 --- a/packages/svelte/src/lib/container/NodeRenderer/index.svelte +++ b/packages/svelte/src/lib/container/NodeRenderer/index.svelte @@ -5,15 +5,18 @@ import { useStore } from '$lib/store'; const { nodes, updateNodeDimensions } = useStore(); - const resizeObserver: ResizeObserver | null = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver((entries: ResizeObserverEntry[]) => { - const updates = entries.map((entry: ResizeObserverEntry) => ({ - id: entry.target.getAttribute('data-id') as string, - nodeElement: entry.target as HTMLDivElement, - forceUpdate: true, - })) + const resizeObserver: ResizeObserver | null = + typeof ResizeObserver === 'undefined' + ? null + : new ResizeObserver((entries: ResizeObserverEntry[]) => { + const updates = entries.map((entry: ResizeObserverEntry) => ({ + id: entry.target.getAttribute('data-id') as string, + nodeElement: entry.target as HTMLDivElement, + forceUpdate: true + })); - updateNodeDimensions(updates); - }); + updateNodeDimensions(updates); + }); onDestroy(() => { resizeObserver?.disconnect(); @@ -33,4 +36,4 @@ pointer-events: none; transform-origin: 0 0; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/container/Pane/index.svelte b/packages/svelte/src/lib/container/Pane/index.svelte index 883fcf58..2ca1b5df 100644 --- a/packages/svelte/src/lib/container/Pane/index.svelte +++ b/packages/svelte/src/lib/container/Pane/index.svelte @@ -10,7 +10,7 @@ handler?.(event); }; - }; + } export function toggleSelected(ids: string[]) { return (item: Item) => { @@ -19,39 +19,48 @@ if (item.selected !== isSelected) { return { ...item, - selected: isSelected, + selected: isSelected }; } return item; - } + }; } -
+
@@ -46,4 +43,4 @@ left: 50%; transform: translateX(-50%); } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/container/SvelteFlow.svelte b/packages/svelte/src/lib/container/SvelteFlow.svelte index d91d8181..42157767 100644 --- a/packages/svelte/src/lib/container/SvelteFlow.svelte +++ b/packages/svelte/src/lib/container/SvelteFlow.svelte @@ -1,8 +1,8 @@
@@ -22,4 +22,4 @@ z-index: 2; pointer-events: none; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/container/Zoom/index.svelte b/packages/svelte/src/lib/container/Zoom/index.svelte index 51c7bbfd..4097d51f 100644 --- a/packages/svelte/src/lib/container/Zoom/index.svelte +++ b/packages/svelte/src/lib/container/Zoom/index.svelte @@ -20,4 +20,4 @@ left: 0; z-index: 4; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/plugins/Background/Background.svelte b/packages/svelte/src/lib/plugins/Background/Background.svelte index 75526092..c30b958f 100644 --- a/packages/svelte/src/lib/plugins/Background/Background.svelte +++ b/packages/svelte/src/lib/plugins/Background/Background.svelte @@ -4,7 +4,7 @@ import DotPattern from './DotPattern.svelte'; import LinePattern from './LinePattern.svelte'; import { useStore } from '$lib/store'; - import { BackgroundVariant } from './types'; + import { BackgroundVariant } from './types'; export let variant: BackgroundVariant = BackgroundVariant.Dots; export let gap = 20; @@ -18,13 +18,13 @@ const defaultColor = { [BackgroundVariant.Dots]: '#91919a', [BackgroundVariant.Lines]: '#eee', - [BackgroundVariant.Cross]: '#e2e2e2', + [BackgroundVariant.Cross]: '#e2e2e2' }; const defaultSize = { [BackgroundVariant.Dots]: 1, [BackgroundVariant.Lines]: 1, - [BackgroundVariant.Cross]: 6, + [BackgroundVariant.Cross]: 6 }; const { transform, id } = useStore(); @@ -43,7 +43,7 @@ : [patternDimensions[0] / 2, patternDimensions[1] / 2]; - + {:else} - + {/if} @@ -72,4 +72,4 @@ pointer-events: none; z-index: -1; } - \ No newline at end of file + diff --git a/packages/svelte/src/lib/plugins/Background/DotPattern.svelte b/packages/svelte/src/lib/plugins/Background/DotPattern.svelte index 3eb76c7e..36584230 100644 --- a/packages/svelte/src/lib/plugins/Background/DotPattern.svelte +++ b/packages/svelte/src/lib/plugins/Background/DotPattern.svelte @@ -1,6 +1,6 @@ - \ No newline at end of file + diff --git a/packages/svelte/src/lib/plugins/Background/LinePattern.svelte b/packages/svelte/src/lib/plugins/Background/LinePattern.svelte index 60dd4a8c..64c7dad7 100644 --- a/packages/svelte/src/lib/plugins/Background/LinePattern.svelte +++ b/packages/svelte/src/lib/plugins/Background/LinePattern.svelte @@ -1,13 +1,11 @@ \ No newline at end of file + d={`M${dimensions[0] / 2} 0 V${dimensions[1]} M0 ${dimensions[1] / 2} H${dimensions[0]}`} +/> diff --git a/packages/svelte/src/lib/plugins/Background/types.ts b/packages/svelte/src/lib/plugins/Background/types.ts index c6e3e390..3d252810 100644 --- a/packages/svelte/src/lib/plugins/Background/types.ts +++ b/packages/svelte/src/lib/plugins/Background/types.ts @@ -1,5 +1,5 @@ export enum BackgroundVariant { - Lines = 'lines', - Dots = 'dots', - Cross = 'cross' + Lines = 'lines', + Dots = 'dots', + Cross = 'cross' } diff --git a/packages/svelte/src/lib/plugins/Controls/ControlButton.svelte b/packages/svelte/src/lib/plugins/Controls/ControlButton.svelte index 4db8270d..27e4cc31 100644 --- a/packages/svelte/src/lib/plugins/Controls/ControlButton.svelte +++ b/packages/svelte/src/lib/plugins/Controls/ControlButton.svelte @@ -3,10 +3,15 @@ let className: string; - export { className as class } + export { className as class }; - diff --git a/packages/svelte/src/lib/plugins/Controls/Icons/Lock.svelte b/packages/svelte/src/lib/plugins/Controls/Icons/Lock.svelte index 6205cfc7..8fd1dddb 100644 --- a/packages/svelte/src/lib/plugins/Controls/Icons/Lock.svelte +++ b/packages/svelte/src/lib/plugins/Controls/Icons/Lock.svelte @@ -1,3 +1,5 @@ - - \ No newline at end of file + + diff --git a/packages/svelte/src/lib/plugins/Controls/Icons/Minus.svelte b/packages/svelte/src/lib/plugins/Controls/Icons/Minus.svelte index dc8d310b..b2f109bb 100644 --- a/packages/svelte/src/lib/plugins/Controls/Icons/Minus.svelte +++ b/packages/svelte/src/lib/plugins/Controls/Icons/Minus.svelte @@ -1,3 +1,3 @@ - \ No newline at end of file + diff --git a/packages/svelte/src/lib/plugins/Controls/Icons/Plus.svelte b/packages/svelte/src/lib/plugins/Controls/Icons/Plus.svelte index a13adbd7..feb813da 100644 --- a/packages/svelte/src/lib/plugins/Controls/Icons/Plus.svelte +++ b/packages/svelte/src/lib/plugins/Controls/Icons/Plus.svelte @@ -1,3 +1,3 @@ - \ No newline at end of file + diff --git a/packages/svelte/src/lib/plugins/Controls/Icons/Unlock.svelte b/packages/svelte/src/lib/plugins/Controls/Icons/Unlock.svelte index 2e59dbd7..82866851 100644 --- a/packages/svelte/src/lib/plugins/Controls/Icons/Unlock.svelte +++ b/packages/svelte/src/lib/plugins/Controls/Icons/Unlock.svelte @@ -1,3 +1,5 @@ - - \ No newline at end of file + + diff --git a/packages/svelte/src/lib/plugins/Minimap/Minimap.svelte b/packages/svelte/src/lib/plugins/Minimap/Minimap.svelte index 1d6f3348..cf24f1d2 100644 --- a/packages/svelte/src/lib/plugins/Minimap/Minimap.svelte +++ b/packages/svelte/src/lib/plugins/Minimap/Minimap.svelte @@ -1,10 +1,10 @@ - + {#if ariaLabel}{ariaLabel}{/if} - {#each $nodes as node(node.id)} + {#each $nodes as node (node.id)} {#if node.width && node.height} {@const pos = getNodePositionWithOrigin(node, $nodeOrigin).positionAbsolute} @@ -85,7 +92,9 @@ {/each} - \ No newline at end of file + diff --git a/packages/svelte/src/lib/plugins/Minimap/MinimapNode.svelte b/packages/svelte/src/lib/plugins/Minimap/MinimapNode.svelte index 5d549332..079ef22a 100644 --- a/packages/svelte/src/lib/plugins/Minimap/MinimapNode.svelte +++ b/packages/svelte/src/lib/plugins/Minimap/MinimapNode.svelte @@ -20,14 +20,14 @@ \ No newline at end of file +/> diff --git a/packages/svelte/src/lib/store/connection-path.ts b/packages/svelte/src/lib/store/connection-path.ts index 9b2805fa..bd3b420d 100644 --- a/packages/svelte/src/lib/store/connection-path.ts +++ b/packages/svelte/src/lib/store/connection-path.ts @@ -5,72 +5,72 @@ import type { SvelteFlowStoreState } from './types'; import { derived } from 'svelte/store'; const oppositePosition = { - [Position.Left]: Position.Right, - [Position.Right]: Position.Left, - [Position.Top]: Position.Bottom, - [Position.Bottom]: Position.Top + [Position.Left]: Position.Right, + [Position.Right]: Position.Left, + [Position.Top]: Position.Bottom, + [Position.Bottom]: Position.Top }; export function getConnectionPath(store: SvelteFlowStoreState) { - return derived( - [ - store.connection, - store.connectionLineType, - store.connectionMode, - store.nodes, - store.transform - ], - ([$connection, $connectionLineType, $connectionMode, $nodes, $transform]) => { - if (!$connection.nodeId) { - return null; - } + return derived( + [ + store.connection, + store.connectionLineType, + store.connectionMode, + store.nodes, + store.transform + ], + ([$connection, $connectionLineType, $connectionMode, $nodes, $transform]) => { + if (!$connection.nodeId) { + return null; + } - const fromNode = $nodes.find((n) => n.id === $connection.nodeId); - const fromHandleBounds = fromNode?.[internalsSymbol]?.handleBounds; - const handleBoundsStrict = fromHandleBounds?.[$connection.handleType || 'source'] || []; - const handleBoundsLoose = handleBoundsStrict - ? handleBoundsStrict - : fromHandleBounds?.[$connection.handleType === 'source' ? 'target' : 'source']!; - const handleBounds = - $connectionMode === ConnectionMode.Strict ? handleBoundsStrict : handleBoundsLoose; - const fromHandle = $connection.handleId - ? handleBounds.find((d) => d.id === $connection.handleId) - : handleBounds[0]; - const fromHandleX = fromHandle - ? fromHandle.x + fromHandle.width / 2 - : (fromNode?.width ?? 0) / 2; - const fromHandleY = fromHandle ? fromHandle.y + fromHandle.height / 2 : fromNode?.height ?? 0; - const fromX = (fromNode?.positionAbsolute?.x ?? 0) + fromHandleX; - const fromY = (fromNode?.positionAbsolute?.y ?? 0) + fromHandleY; - const fromPosition = fromHandle?.position; - const toPosition = fromPosition ? oppositePosition[fromPosition] : undefined; + const fromNode = $nodes.find((n) => n.id === $connection.nodeId); + const fromHandleBounds = fromNode?.[internalsSymbol]?.handleBounds; + const handleBoundsStrict = fromHandleBounds?.[$connection.handleType || 'source'] || []; + const handleBoundsLoose = handleBoundsStrict + ? handleBoundsStrict + : fromHandleBounds?.[$connection.handleType === 'source' ? 'target' : 'source']!; + const handleBounds = + $connectionMode === ConnectionMode.Strict ? handleBoundsStrict : handleBoundsLoose; + const fromHandle = $connection.handleId + ? handleBounds.find((d) => d.id === $connection.handleId) + : handleBounds[0]; + const fromHandleX = fromHandle + ? fromHandle.x + fromHandle.width / 2 + : (fromNode?.width ?? 0) / 2; + const fromHandleY = fromHandle ? fromHandle.y + fromHandle.height / 2 : fromNode?.height ?? 0; + const fromX = (fromNode?.positionAbsolute?.x ?? 0) + fromHandleX; + const fromY = (fromNode?.positionAbsolute?.y ?? 0) + fromHandleY; + const fromPosition = fromHandle?.position; + const toPosition = fromPosition ? oppositePosition[fromPosition] : undefined; - const pathParams = { - sourceX: fromX, - sourceY: fromY, - sourcePosition: fromPosition, - targetX: (($connection.position?.x ?? 0) - $transform[0]) / $transform[2], - targetY: (($connection.position?.y ?? 0) - $transform[1]) / $transform[2], - targetPosition: toPosition - }; + const pathParams = { + sourceX: fromX, + sourceY: fromY, + sourcePosition: fromPosition, + targetX: (($connection.position?.x ?? 0) - $transform[0]) / $transform[2], + targetY: (($connection.position?.y ?? 0) - $transform[1]) / $transform[2], + targetPosition: toPosition + }; - let path = ''; + let path = ''; - if ($connectionLineType === ConnectionLineType.Bezier) { - // we assume the destination position is opposite to the source position - [path] = getBezierPath(pathParams); - } else if ($connectionLineType === ConnectionLineType.Step) { - [path] = getSmoothStepPath({ - ...pathParams, - borderRadius: 0 - }); - } else if ($connectionLineType === ConnectionLineType.SmoothStep) { - [path] = getSmoothStepPath(pathParams); - } else { - [path] = getStraightPath(pathParams); - } + if ($connectionLineType === ConnectionLineType.Bezier) { + // we assume the destination position is opposite to the source position + [path] = getBezierPath(pathParams); + } else if ($connectionLineType === ConnectionLineType.Step) { + [path] = getSmoothStepPath({ + ...pathParams, + borderRadius: 0 + }); + } else if ($connectionLineType === ConnectionLineType.SmoothStep) { + [path] = getSmoothStepPath(pathParams); + } else { + [path] = getStraightPath(pathParams); + } - return path; - } - ); + return path; + } + ); } diff --git a/packages/svelte/src/lib/store/edges-layouted.ts b/packages/svelte/src/lib/store/edges-layouted.ts index b1acfd53..b5825e99 100644 --- a/packages/svelte/src/lib/store/edges-layouted.ts +++ b/packages/svelte/src/lib/store/edges-layouted.ts @@ -6,56 +6,56 @@ import type { WrapEdgeProps } from '$lib/types'; import type { SvelteFlowStoreState } from './types'; export function getEdgesLayouted(store: SvelteFlowStoreState) { - return derived([store.edges, store.nodes], ([$edges, $nodes]) => { - return $edges - .map((edge) => { - const sourceNode = $nodes.find((node) => node.id === edge.source); - const targetNode = $nodes.find((node) => node.id === edge.target); - const [sourceNodeRect, sourceHandleBounds, sourceIsValid] = getNodeData(sourceNode); - const [targetNodeRect, targetHandleBounds, targetIsValid] = getNodeData(targetNode); + return derived([store.edges, store.nodes], ([$edges, $nodes]) => { + return $edges + .map((edge) => { + const sourceNode = $nodes.find((node) => node.id === edge.source); + const targetNode = $nodes.find((node) => node.id === edge.target); + const [sourceNodeRect, sourceHandleBounds, sourceIsValid] = getNodeData(sourceNode); + const [targetNodeRect, targetHandleBounds, targetIsValid] = getNodeData(targetNode); - if (!sourceIsValid || !targetIsValid) { - return null; - } + if (!sourceIsValid || !targetIsValid) { + return null; + } - const edgeType = edge.type || 'default'; + const edgeType = edge.type || 'default'; - const targetNodeHandles = targetHandleBounds!.target; - const sourceHandle = getHandle(sourceHandleBounds!.source!, edge.sourceHandle); - const targetHandle = getHandle(targetNodeHandles!, edge.targetHandle); - const sourcePosition = sourceHandle?.position || Position.Bottom; - const targetPosition = targetHandle?.position || Position.Top; + const targetNodeHandles = targetHandleBounds!.target; + const sourceHandle = getHandle(sourceHandleBounds!.source!, edge.sourceHandle); + const targetHandle = getHandle(targetNodeHandles!, edge.targetHandle); + const sourcePosition = sourceHandle?.position || Position.Bottom; + const targetPosition = targetHandle?.position || Position.Top; - if (!sourceHandle || !targetHandle) { - return null; - } + if (!sourceHandle || !targetHandle) { + return null; + } - const { sourceX, sourceY, targetX, targetY } = getEdgePositions( - sourceNodeRect, - sourceHandle, - sourcePosition, - targetNodeRect, - targetHandle, - targetPosition - ); + const { sourceX, sourceY, targetX, targetY } = getEdgePositions( + sourceNodeRect, + sourceHandle, + sourcePosition, + targetNodeRect, + targetHandle, + targetPosition + ); - // we nee to do this to match the types - const sourceHandleId = edge.sourceHandle; - const targetHandleId = edge.targetHandle; + // we nee to do this to match the types + const sourceHandleId = edge.sourceHandle; + const targetHandleId = edge.targetHandle; - return { - ...edge, - type: edgeType, - sourceX, - sourceY, - targetX, - targetY, - sourcePosition, - targetPosition, - sourceHandleId, - targetHandleId - }; - }) - .filter((e) => e !== null) as WrapEdgeProps[]; - }); + return { + ...edge, + type: edgeType, + sourceX, + sourceY, + targetX, + targetY, + sourcePosition, + targetPosition, + sourceHandleId, + targetHandleId + }; + }) + .filter((e) => e !== null) as WrapEdgeProps[]; + }); } diff --git a/packages/svelte/src/lib/store/index.ts b/packages/svelte/src/lib/store/index.ts index 63da6104..5039627c 100644 --- a/packages/svelte/src/lib/store/index.ts +++ b/packages/svelte/src/lib/store/index.ts @@ -1,23 +1,23 @@ import { getContext } from 'svelte'; import { get } from 'svelte/store'; import { - type Transform, - type NodeDragItem, - type NodeDimensionUpdate, - internalsSymbol, - type NodeOrigin, - type ViewportHelperFunctionOptions, - type Node as RFNode, - type Connection, - type XYPosition, - type CoordinateExtent + type Transform, + type NodeDragItem, + type NodeDimensionUpdate, + internalsSymbol, + type NodeOrigin, + type ViewportHelperFunctionOptions, + type Node as RFNode, + type Connection, + type XYPosition, + type CoordinateExtent } from '@reactflow/system'; import { - fitView as fitViewUtil, - getConnectedEdges, - getD3Transition, - getDimensions, - addEdge as addEdgeUtil + fitView as fitViewUtil, + getConnectedEdges, + getD3Transition, + getDimensions, + addEdge as addEdgeUtil } from '@reactflow/utils'; import { zoomIdentity } from 'd3-zoom'; @@ -32,307 +32,307 @@ import type { SvelteFlowStore } from './types'; export const key = Symbol(); type CreateStoreProps = { - fitView?: boolean; - nodeOrigin?: NodeOrigin; - transform?: Transform; - nodeTypes?: NodeTypes; - edgeTypes?: EdgeTypes; - id?: string; + fitView?: boolean; + nodeOrigin?: NodeOrigin; + transform?: Transform; + nodeTypes?: NodeTypes; + edgeTypes?: EdgeTypes; + id?: string; }; export function createStore({ - transform = [0, 0, 1], - nodeOrigin = [0, 0], - fitView: fitViewOnInit = false, - nodeTypes = {}, - edgeTypes = {}, - id = '1' + transform = [0, 0, 1], + nodeOrigin = [0, 0], + fitView: fitViewOnInit = false, + nodeTypes = {}, + edgeTypes = {}, + id = '1' }: CreateStoreProps): SvelteFlowStore { - const store = { - ...initialStoreState - }; + const store = { + ...initialStoreState + }; - let fitViewOnInitDone = false; + let fitViewOnInitDone = false; - function setEdges(edges: Edge[]) { - store.edges.set(edges); - } + function setEdges(edges: Edge[]) { + store.edges.set(edges); + } - function addEdge(edgeParams: Edge | Connection) { - const edges = get(store.edges); - store.edges.set(addEdgeUtil(edgeParams, edges)); - } + function addEdge(edgeParams: Edge | Connection) { + const edges = get(store.edges); + store.edges.set(addEdgeUtil(edgeParams, edges)); + } - function setNodes(nodes: Node[]) { - store.nodes.update((currentNodes) => { - const nextNodes = nodes.map((n) => { - const currentNode = currentNodes.find((cn) => cn.id === n.id) || {}; + function setNodes(nodes: Node[]) { + store.nodes.update((currentNodes) => { + const nextNodes = nodes.map((n) => { + const currentNode = currentNodes.find((cn) => cn.id === n.id) || {}; - return { - ...currentNode, - ...n, - positionAbsolute: n.position - }; - }); + return { + ...currentNode, + ...n, + positionAbsolute: n.position + }; + }); - return nextNodes; - }); - } + return nextNodes; + }); + } - function updateNodePositions(nodeDragItems: NodeDragItem[], dragging = false) { - store.nodes.update((nds) => { - return nds.map((n) => { - const nodeDragItem = nodeDragItems.find((ndi) => ndi.id === n.id); + function updateNodePositions(nodeDragItems: NodeDragItem[], dragging = false) { + store.nodes.update((nds) => { + return nds.map((n) => { + const nodeDragItem = nodeDragItems.find((ndi) => ndi.id === n.id); - if (nodeDragItem) { - return { - ...n, - dragging, - positionAbsolute: nodeDragItem.positionAbsolute, - position: nodeDragItem.position - }; - } + if (nodeDragItem) { + return { + ...n, + dragging, + positionAbsolute: nodeDragItem.positionAbsolute, + position: nodeDragItem.position + }; + } - return n; - }); - }); - } + return n; + }); + }); + } - function updateNodeDimensions(updates: NodeDimensionUpdate[]) { - const viewportNode = document?.querySelector('.react-flow__viewport'); + function updateNodeDimensions(updates: NodeDimensionUpdate[]) { + const viewportNode = document?.querySelector('.react-flow__viewport'); - if (!viewportNode) { - return; - } + if (!viewportNode) { + return; + } - const style = window.getComputedStyle(viewportNode); - const { m22: zoom } = new window.DOMMatrixReadOnly(style.transform); + const style = window.getComputedStyle(viewportNode); + const { m22: zoom } = new window.DOMMatrixReadOnly(style.transform); - const nextNodes = get(store.nodes).map((node) => { - const update = updates.find((u) => u.id === node.id); + const nextNodes = get(store.nodes).map((node) => { + const update = updates.find((u) => u.id === node.id); - if (update) { - const dimensions = getDimensions(update.nodeElement); + if (update) { + const dimensions = getDimensions(update.nodeElement); - const doUpdate = !!( - dimensions.width && - dimensions.height && - (node.width !== dimensions.width || - node.height !== dimensions.height || - update.forceUpdate) - ); + const doUpdate = !!( + dimensions.width && + dimensions.height && + (node.width !== dimensions.width || + node.height !== dimensions.height || + update.forceUpdate) + ); - if (doUpdate) { - node[internalsSymbol] = { - ...node[internalsSymbol], - handleBounds: { - source: getHandleBounds('.source', update.nodeElement, zoom), - target: getHandleBounds('.target', update.nodeElement, zoom) - } - }; - node.width = dimensions.width; - node.height = dimensions.height; - } - } + if (doUpdate) { + node[internalsSymbol] = { + ...node[internalsSymbol], + handleBounds: { + source: getHandleBounds('.source', update.nodeElement, zoom), + target: getHandleBounds('.target', update.nodeElement, zoom) + } + }; + node.width = dimensions.width; + node.height = dimensions.height; + } + } - return node; - }); + return node; + }); - const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); + const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); - fitViewOnInitDone = - fitViewOnInitDone || (fitViewOnInit && !!d3Zoom && !!d3Selection && fitView()); + fitViewOnInitDone = + fitViewOnInitDone || (fitViewOnInit && !!d3Zoom && !!d3Selection && fitView()); - store.nodes.set(nextNodes); - } + store.nodes.set(nextNodes); + } - function zoomIn(options?: ViewportHelperFunctionOptions) { - const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); + function zoomIn(options?: ViewportHelperFunctionOptions) { + const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); - if (d3Zoom && d3Selection) { - d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1.2); - } - } + if (d3Zoom && d3Selection) { + d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1.2); + } + } - function zoomOut(options?: ViewportHelperFunctionOptions) { - const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); - if (d3Zoom && d3Selection) { - d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1 / 1.2); - } - } + function zoomOut(options?: ViewportHelperFunctionOptions) { + const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); + if (d3Zoom && d3Selection) { + d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1 / 1.2); + } + } - function fitView() { - const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); + function fitView() { + const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); - if (!d3Zoom || !d3Selection) { - return false; - } + if (!d3Zoom || !d3Selection) { + return false; + } - return fitViewUtil( - { - nodes: get(store.nodes) as RFNode[], - width: get(store.width), - height: get(store.height), - minZoom: 0.2, - maxZoom: 2, - d3Selection, - d3Zoom, - nodeOrigin: get(store.nodeOrigin) - }, - {} - ); - } + return fitViewUtil( + { + nodes: get(store.nodes) as RFNode[], + width: get(store.width), + height: get(store.height), + minZoom: 0.2, + maxZoom: 2, + d3Selection, + d3Zoom, + nodeOrigin: get(store.nodeOrigin) + }, + {} + ); + } - function resetSelectedItem(item: T) { - if (item.selected) { - return { - ...item, - selected: false - }; - } + function resetSelectedItem(item: T) { + if (item.selected) { + return { + ...item, + selected: false + }; + } - return item; - } + return item; + } - function resetSelectedElements() { - store.nodes.update((ns) => ns.map(resetSelectedItem)); - store.edges.update((es) => es.map(resetSelectedItem)); - } + function resetSelectedElements() { + store.nodes.update((ns) => ns.map(resetSelectedItem)); + store.edges.update((es) => es.map(resetSelectedItem)); + } - store.deleteKeyPressed.subscribe((deleteKeyPressed) => { - if (deleteKeyPressed) { - const nodes = get(store.nodes); - const edges = get(store.edges); - const selectedNodes = nodes.filter((node) => node.selected); - const selectedEdges = edges.filter((edge) => edge.selected); + store.deleteKeyPressed.subscribe((deleteKeyPressed) => { + if (deleteKeyPressed) { + const nodes = get(store.nodes); + const edges = get(store.edges); + const selectedNodes = nodes.filter((node) => node.selected); + const selectedEdges = edges.filter((edge) => edge.selected); - // @todo can we put this stuff into @reactflow/utils? - const nodeIds = selectedNodes.map((node) => node.id); - const edgeIds = selectedEdges.map((edge) => edge.id); - const nodesToRemove = nodes.reduce((res, node) => { - const parentHit = - !nodeIds.includes(node.id) && - node.parentNode && - res.find((n) => n.id === node.parentNode); - const deletable = typeof node.deletable === 'boolean' ? node.deletable : true; - if (deletable && (nodeIds.includes(node.id) || parentHit)) { - res.push(node); - } + // @todo can we put this stuff into @reactflow/utils? + const nodeIds = selectedNodes.map((node) => node.id); + const edgeIds = selectedEdges.map((edge) => edge.id); + const nodesToRemove = nodes.reduce((res, node) => { + const parentHit = + !nodeIds.includes(node.id) && + node.parentNode && + res.find((n) => n.id === node.parentNode); + const deletable = typeof node.deletable === 'boolean' ? node.deletable : true; + if (deletable && (nodeIds.includes(node.id) || parentHit)) { + res.push(node); + } - return res; - }, []); - const deletableEdges = edges.filter((e) => - typeof e.deletable === 'boolean' ? e.deletable : true - ); - const initialHitEdges = deletableEdges.filter((e) => edgeIds.includes(e.id)); + return res; + }, []); + const deletableEdges = edges.filter((e) => + typeof e.deletable === 'boolean' ? e.deletable : true + ); + const initialHitEdges = deletableEdges.filter((e) => edgeIds.includes(e.id)); - if (nodesToRemove || initialHitEdges) { - const connectedEdges = getConnectedEdges(nodesToRemove as RFNode[], deletableEdges); - const edgesToRemove = [...initialHitEdges, ...connectedEdges]; - const edgeIdsToRemove = edgesToRemove.reduce((res, edge) => { - if (!res.includes(edge.id)) { - res.push(edge.id); - } - return res; - }, []); + if (nodesToRemove || initialHitEdges) { + const connectedEdges = getConnectedEdges(nodesToRemove as RFNode[], deletableEdges); + const edgesToRemove = [...initialHitEdges, ...connectedEdges]; + const edgeIdsToRemove = edgesToRemove.reduce((res, edge) => { + if (!res.includes(edge.id)) { + res.push(edge.id); + } + return res; + }, []); - store.nodes.update((nds) => nds.filter((node) => !nodeIds.includes(node.id))); - store.edges.update((eds) => eds.filter((edge) => !edgeIdsToRemove.includes(edge.id))); - } - } - }); + store.nodes.update((nds) => nds.filter((node) => !nodeIds.includes(node.id))); + store.edges.update((eds) => eds.filter((edge) => !edgeIdsToRemove.includes(edge.id))); + } + } + }); - function addSelectedNodes(ids: string[]) { - store.selectionRect.set(null); - store.selectionRectMode.set(null); + function addSelectedNodes(ids: string[]) { + store.selectionRect.set(null); + store.selectionRectMode.set(null); - if (get(store.multiselectionKeyPressed)) { - // @todo handle multiselection key - } + if (get(store.multiselectionKeyPressed)) { + // @todo handle multiselection key + } - store.nodes.update((ns) => - ns.map((node) => { - return { - ...node, - selected: ids.includes(node.id) - }; - }) - ); - } + store.nodes.update((ns) => + ns.map((node) => { + return { + ...node, + selected: ids.includes(node.id) + }; + }) + ); + } - function panBy(delta: XYPosition) { - const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); - const transform = get(store.transform); - const width = get(store.width); - const height = get(store.height); + function panBy(delta: XYPosition) { + const { zoom: d3Zoom, selection: d3Selection } = get(store.d3); + const transform = get(store.transform); + const width = get(store.width); + const height = get(store.height); - if (!d3Zoom || !d3Selection || (!delta.x && !delta.y)) { - return; - } + if (!d3Zoom || !d3Selection || (!delta.x && !delta.y)) { + return; + } - const nextTransform = zoomIdentity - .translate(transform[0] + delta.x, transform[1] + delta.y) - .scale(transform[2]); + const nextTransform = zoomIdentity + .translate(transform[0] + delta.x, transform[1] + delta.y) + .scale(transform[2]); - const extent: CoordinateExtent = [ - [0, 0], - [width, height] - ]; + const extent: CoordinateExtent = [ + [0, 0], + [width, height] + ]; - const constrainedTransform = d3Zoom?.constrain()(nextTransform, extent, [ - [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY], - [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY] - ]); - d3Zoom.transform(d3Selection, constrainedTransform); - } + const constrainedTransform = d3Zoom?.constrain()(nextTransform, extent, [ + [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY], + [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY] + ]); + d3Zoom.transform(d3Selection, constrainedTransform); + } - function updateConnection(connectionUpdate: Partial | null) { - const currentConnectionData = get(store.connection); - const nextConnectionData = currentConnectionData - ? { - ...initConnectionData, - ...currentConnectionData, - ...connectionUpdate - } - : { - ...initConnectionData, - ...connectionUpdate - }; + function updateConnection(connectionUpdate: Partial | null) { + const currentConnectionData = get(store.connection); + const nextConnectionData = currentConnectionData + ? { + ...initConnectionData, + ...currentConnectionData, + ...connectionUpdate + } + : { + ...initConnectionData, + ...connectionUpdate + }; - store.connection.set(nextConnectionData); - } + store.connection.set(nextConnectionData); + } - function cancelConnection() { - updateConnection(initConnectionData); - } + function cancelConnection() { + updateConnection(initConnectionData); + } - return { - // state - ...store, + return { + // state + ...store, - // derived state - edgesLayouted: getEdgesLayouted(store), - connectionPath: getConnectionPath(store), + // derived state + edgesLayouted: getEdgesLayouted(store), + connectionPath: getConnectionPath(store), - // actions - setNodes, - setEdges, - addEdge, - updateNodePositions, - updateNodeDimensions, - zoomIn, - zoomOut, - fitView, - resetSelectedElements, - addSelectedNodes, - panBy, - updateConnection, - cancelConnection - }; + // actions + setNodes, + setEdges, + addEdge, + updateNodePositions, + updateNodeDimensions, + zoomIn, + zoomOut, + fitView, + resetSelectedElements, + addSelectedNodes, + panBy, + updateConnection, + cancelConnection + }; } export function useStore(): SvelteFlowStore { - const { getStore } = getContext<{ getStore: () => SvelteFlowStore }>(key); + const { getStore } = getContext<{ getStore: () => SvelteFlowStore }>(key); - return getStore(); + return getStore(); } diff --git a/packages/svelte/src/lib/store/initial-store.ts b/packages/svelte/src/lib/store/initial-store.ts index 43221c0b..80f74ffc 100644 --- a/packages/svelte/src/lib/store/initial-store.ts +++ b/packages/svelte/src/lib/store/initial-store.ts @@ -1,13 +1,13 @@ import { readable, writable } from 'svelte/store'; import { - SelectionMode, - type D3ZoomInstance, - type D3SelectionInstance, - ConnectionMode, - ConnectionLineType, - type Transform, - type NodeOrigin, - type Rect + SelectionMode, + type D3ZoomInstance, + type D3SelectionInstance, + ConnectionMode, + ConnectionLineType, + type Transform, + type NodeOrigin, + type Rect } from '@reactflow/system'; import DefaultNode from '$lib/components/nodes/DefaultNode.svelte'; @@ -19,47 +19,47 @@ import StraightEdge from '$lib/components/edges/StraightEdge.svelte'; import SmoothStepEdge from '$lib/components/edges/SmoothStepEdge.svelte'; export const initConnectionData = { - nodeId: null, - handleId: null, - handleType: null, - position: null, - status: null + nodeId: null, + handleId: null, + handleType: null, + position: null, + status: null }; export const initialStoreState = { - nodes: writable([]), - edges: writable([]), - edgesLayouted: readable([]), - height: writable(500), - width: writable(500), - nodeOrigin: writable([0.5, 0.5]), - d3: writable<{ zoom: D3ZoomInstance | null; selection: D3SelectionInstance | null }>({ - zoom: null, - selection: null - }), - id: writable(null), - dragging: writable(false), - selectionRect: writable<(Rect & { startX: number; startY: number }) | null>(null), - selectionKeyPressed: writable(false), - multiselectionKeyPressed: writable(false), - deleteKeyPressed: writable(false), - selectionRectMode: writable(null), - selectionMode: writable(SelectionMode.Partial), - nodeTypes: writable({ - input: InputNode, - output: OutputNode, - default: DefaultNode - }), - edgeTypes: writable({ - straight: StraightEdge, - smoothstep: SmoothStepEdge, - default: BezierEdge - }), - transform: writable([0, 0, 1]), - connectionMode: writable(ConnectionMode.Strict), - domNode: writable(null), - connectionPath: readable(null), - connection: writable(initConnectionData), - connectionRadius: writable(25), - connectionLineType: writable(ConnectionLineType.Bezier) + nodes: writable([]), + edges: writable([]), + edgesLayouted: readable([]), + height: writable(500), + width: writable(500), + nodeOrigin: writable([0.5, 0.5]), + d3: writable<{ zoom: D3ZoomInstance | null; selection: D3SelectionInstance | null }>({ + zoom: null, + selection: null + }), + id: writable(null), + dragging: writable(false), + selectionRect: writable<(Rect & { startX: number; startY: number }) | null>(null), + selectionKeyPressed: writable(false), + multiselectionKeyPressed: writable(false), + deleteKeyPressed: writable(false), + selectionRectMode: writable(null), + selectionMode: writable(SelectionMode.Partial), + nodeTypes: writable({ + input: InputNode, + output: OutputNode, + default: DefaultNode + }), + edgeTypes: writable({ + straight: StraightEdge, + smoothstep: SmoothStepEdge, + default: BezierEdge + }), + transform: writable([0, 0, 1]), + connectionMode: writable(ConnectionMode.Strict), + domNode: writable(null), + connectionPath: readable(null), + connection: writable(initConnectionData), + connectionRadius: writable(25), + connectionLineType: writable(ConnectionLineType.Bezier) }; diff --git a/packages/svelte/src/lib/store/types.d.ts b/packages/svelte/src/lib/store/types.d.ts index d9f32e4d..c7c3a4c4 100644 --- a/packages/svelte/src/lib/store/types.d.ts +++ b/packages/svelte/src/lib/store/types.d.ts @@ -1,32 +1,32 @@ import type { - NodeDimensionUpdate, - XYPosition, - ViewportHelperFunctionOptions, - Connection, - NodeDragItem + NodeDimensionUpdate, + XYPosition, + ViewportHelperFunctionOptions, + Connection, + NodeDragItem } from '@reactflow/system'; import { initialStoreState } from './initial-store'; import type { Node, Edge, ConnectionData } from '$lib/types'; export type SvelteFlowStoreActions = { - setNodes: (nodes: Node[]) => void; - setEdges: (edges: Edge[]) => void; - addEdge: (edge: Edge | Connection) => void; - zoomIn: (options?: ViewportHelperFunctionOptions) => void; - zoomOut: (options?: ViewportHelperFunctionOptions) => void; - fitView: (options?: ViewportHelperFunctionOptions) => boolean; - updateNodePositions: ( - nodeDragItems: NodeDragItem[], - positionChanged?: boolean, - dragging?: boolean - ) => void; - updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void; - resetSelectedElements: () => void; - addSelectedNodes: (ids: string[]) => void; - panBy: (delta: XYPosition) => void; - updateConnection: (connection: Partial) => void; - cancelConnection: () => void; + setNodes: (nodes: Node[]) => void; + setEdges: (edges: Edge[]) => void; + addEdge: (edge: Edge | Connection) => void; + zoomIn: (options?: ViewportHelperFunctionOptions) => void; + zoomOut: (options?: ViewportHelperFunctionOptions) => void; + fitView: (options?: ViewportHelperFunctionOptions) => boolean; + updateNodePositions: ( + nodeDragItems: NodeDragItem[], + positionChanged?: boolean, + dragging?: boolean + ) => void; + updateNodeDimensions: (updates: NodeDimensionUpdate[]) => void; + resetSelectedElements: () => void; + addSelectedNodes: (ids: string[]) => void; + panBy: (delta: XYPosition) => void; + updateConnection: (connection: Partial) => void; + cancelConnection: () => void; }; export type SvelteFlowStoreState = typeof initialStoreState; diff --git a/packages/svelte/src/lib/types/general.ts b/packages/svelte/src/lib/types/general.ts index 81f32c0a..b759fd89 100644 --- a/packages/svelte/src/lib/types/general.ts +++ b/packages/svelte/src/lib/types/general.ts @@ -7,25 +7,25 @@ export type KeyDefinitionObject = { key: string; modifier?: KeyModifier }; export type KeyDefinition = string | KeyDefinitionObject; export type ConnectionData = { - position: XYPosition | null; - nodeId: string | null; - handleId: string | null; - handleType: HandleType | null; - status: string | null; + position: XYPosition | null; + nodeId: string | null; + handleId: string | null; + handleType: HandleType | null; + status: string | null; }; export type ConnectionLineProps = {}; export type SvelteFlowProps = { - nodes: Node[]; - edges: Edge[]; + nodes: Node[]; + edges: Edge[]; - connectionLineType?: ConnectionLineType; - selectionKey?: KeyDefinition; - deleteKey?: KeyDefinition; - nodeTypes?: NodeTypes; - fitView?: boolean; - class?: string; - style?: string; - id?: string; + connectionLineType?: ConnectionLineType; + selectionKey?: KeyDefinition; + deleteKey?: KeyDefinition; + nodeTypes?: NodeTypes; + fitView?: boolean; + class?: string; + style?: string; + id?: string; }; diff --git a/packages/svelte/src/lib/types/index.ts b/packages/svelte/src/lib/types/index.ts index ced30c7a..2fccfa9a 100644 --- a/packages/svelte/src/lib/types/index.ts +++ b/packages/svelte/src/lib/types/index.ts @@ -1,10 +1,10 @@ export type { - Position, - XYPosition, - Edge, - BaseEdgeProps, - WrapEdgeProps, - EdgeProps + Position, + XYPosition, + Edge, + BaseEdgeProps, + WrapEdgeProps, + EdgeProps } from '@reactflow/system'; export * from './nodes'; diff --git a/packages/svelte/src/lib/types/nodes.ts b/packages/svelte/src/lib/types/nodes.ts index cc180f12..9b4025c5 100644 --- a/packages/svelte/src/lib/types/nodes.ts +++ b/packages/svelte/src/lib/types/nodes.ts @@ -5,43 +5,43 @@ import type { internalsSymbol, NodeHandleBounds, Position, XYPosition } from '@r // we need a base node type or helpes that accept Node like types // eslint-disable-next-line @typescript-eslint/no-explicit-any export type Node = { - id: string; - type: string; - data: NodeData; - position: XYPosition; - sourcePosition?: Position; - targetPosition?: Position; - positionAbsolute?: XYPosition; + id: string; + type: string; + data: NodeData; + position: XYPosition; + sourcePosition?: Position; + targetPosition?: Position; + positionAbsolute?: XYPosition; - width?: number; - height?: number; - selected?: boolean; - class?: string; - style?: string; - deletable?: boolean; - // not supported yet - parentNode?: string; + width?: number; + height?: number; + selected?: boolean; + class?: string; + style?: string; + deletable?: boolean; + // not supported yet + parentNode?: string; - // only used internally - [internalsSymbol]?: { - z?: number; - handleBounds?: NodeHandleBounds; - isParent?: boolean; - }; + // only used internally + [internalsSymbol]?: { + z?: number; + handleBounds?: NodeHandleBounds; + isParent?: boolean; + }; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type NodeProps = Pick< - Node, - 'id' | 'data' | 'selected' | 'sourcePosition' | 'targetPosition' + Node, + 'id' | 'data' | 'selected' | 'sourcePosition' | 'targetPosition' > & { - xPos: number; - yPos: number; - isConnectable?: boolean; + xPos: number; + yPos: number; + isConnectable?: boolean; }; export type WrapNodeProps = Node & { - resizeObserver?: ResizeObserver | null; + resizeObserver?: ResizeObserver | null; }; export type NodeTypes = Record>>; diff --git a/packages/svelte/src/routes/+page.svelte b/packages/svelte/src/routes/+page.svelte index 2eea4c7c..df9e6fb4 100644 --- a/packages/svelte/src/routes/+page.svelte +++ b/packages/svelte/src/routes/+page.svelte @@ -1,10 +1,16 @@