merge next

This commit is contained in:
peterkogo
2024-01-30 12:36:04 +01:00
54 changed files with 718 additions and 167 deletions
@@ -0,0 +1,14 @@
<script lang="ts">
import { onMount } from 'svelte';
let _onMount: (() => void) | undefined = undefined;
export { _onMount as onMount };
let _onDestroy: (() => void) | undefined = undefined;
export { _onDestroy as onDestroy };
onMount(() => {
_onMount?.();
return _onDestroy;
});
</script>
@@ -0,0 +1 @@
export { default as CallOnMount } from './CallOnMount.svelte';
@@ -134,7 +134,7 @@ The Handle component is the part of a node that can be used to connect nodes.
data-handleid={handleId}
data-nodeid={nodeId}
data-handlepos={position}
data-id="{flowId}-{nodeId}-{id || null}-{type}"
data-id="{$flowId}-{nodeId}-{id || null}-{type}"
class={cc([
'svelte-flow__handle',
`svelte-flow__handle-${position}`,
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { EdgeWrapper } from '$lib/components/EdgeWrapper';
import { CallOnMount } from '$lib/components/CallOnMount';
import { MarkerDefinition } from '$lib/container/EdgeRenderer/MarkerDefinition';
import { useStore } from '$lib/store';
import type { DefaultEdgeOptions } from '$lib/types';
@@ -8,8 +9,8 @@
export let defaultEdgeOptions: DefaultEdgeOptions | undefined;
const {
elementsSelectable,
visibleEdges,
edgesInitialized,
edges: { setDefaultOptions }
} = useStore();
@@ -54,4 +55,15 @@
on:edgecontextmenu
/>
{/each}
{#if $visibleEdges.length > 0}
<CallOnMount
onMount={() => {
$edgesInitialized = true;
}}
onDestroy={() => {
$edgesInitialized = false;
}}
/>
{/if}
</div>
@@ -73,7 +73,8 @@
let selectedNodes: Node[] = [];
$: _panOnDrag = $panActivationKeyPressed || panOnDrag;
$: isSelecting = $selectionKeyPressed || (selectionOnDrag && _panOnDrag !== true);
$: isSelecting =
$selectionKeyPressed || $selectionRect || (selectionOnDrag && _panOnDrag !== true);
$: hasActiveSelection = $elementsSelectable && (isSelecting || $selectionRectMode === 'user');
function onClick(event: MouseEvent | TouchEvent) {
@@ -77,6 +77,7 @@
export let onconnectstart: $$Props['onconnectstart'] = undefined;
export let onconnectend: $$Props['onconnectend'] = undefined;
export let onbeforedelete: $$Props['onbeforedelete'] = undefined;
export let oninit: $$Props['oninit'] = undefined;
export let defaultMarkerColor = '#b1b1b7';
@@ -130,6 +131,16 @@
}
}
// Call oninit once when flow is intialized
const { initialized } = store;
let onInitCalled = false;
$: {
if (!onInitCalled && $initialized) {
oninit?.();
onInitCalled = true;
}
}
// this updates the store for simple changes
// where the prop names equals the store name
$: {
@@ -333,4 +333,6 @@ export type SvelteFlowProps = DOMAttributes<HTMLDivElement> & {
onconnectstart?: OnConnectStart;
/** When a user stops dragging a connection line, this event gets fired. */
onconnectend?: OnConnectEnd;
/** This handler gets called when the flow is finished initializing */
oninit?: () => void;
};
@@ -4,6 +4,7 @@
import { useStore } from '$lib/store';
import zoom from '$lib/actions/zoom';
import type { ZoomProps } from './types';
import { onMount } from 'svelte';
type $$Props = ZoomProps;
@@ -29,12 +30,17 @@
translateExtent,
lib,
panActivationKeyPressed,
zoomActivationKeyPressed
zoomActivationKeyPressed,
viewportInitialized
} = useStore();
$: viewPort = initialViewport || { x: 0, y: 0, zoom: 1 };
$: _panOnDrag = $panActivationKeyPressed || panOnDrag;
$: _panOnScroll = $panActivationKeyPressed || panOnScroll;
onMount(() => {
$viewportInitialized = true;
});
</script>
<div
@@ -0,0 +1,24 @@
import { useStore } from '$lib/store';
import type { Readable } from 'svelte/store';
/**
* Hook for seeing if nodes are initialized
* @returns - nodesInitialized Writable
*/
export function useNodesInitialized() {
const { nodesInitialized } = useStore();
return {
subscribe: nodesInitialized.subscribe
} as Readable<boolean>;
}
/**
* Hook for seeing if the flow is initialized
* @returns - initialized Writable
*/
export function useInitialized() {
const { initialized } = useStore();
return {
subscribe: initialized.subscribe
} as Readable<boolean>;
}
+159 -2
View File
@@ -24,32 +24,136 @@ import { isNode } from '$lib/utils';
* Hook for accessing the ReactFlow instance.
*
* @public
*
* @returns helper functions
*/
export function useSvelteFlow(): {
/**
* Zooms viewport in by 1.2.
*
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomIn: ZoomInOut;
/**
* Zooms viewport out by 1 / 1.2.
*
* @param options.duration - optional duration. If set, a transition will be applied
*/
zoomOut: ZoomInOut;
/**
* Returns a node by id.
*
* @param id - the node id
* @returns the node or undefined if no node was found
*/
getNode: (id: string) => Node | undefined;
/**
* Returns nodes.
*
* @returns nodes array
*/
getNodes: (ids?: string[]) => Node[];
/**
* Returns an edge by id.
*
* @param id - the edge id
* @returns the edge or undefined if no edge was found
*/
getEdge: (id: string) => Edge | undefined;
/**
* Returns edges.
*
* @returns edges array
*/
getEdges: (ids?: string[]) => Edge[];
/**
* Sets the current zoom level.
*
* @param zoomLevel - the zoom level to set
* @param options.duration - optional duration. If set, a transition will be applied
*/
setZoom: (zoomLevel: number, options?: ViewportHelperFunctionOptions) => void;
/**
* Returns the current zoom level.
*
* @returns current zoom as a number
*/
getZoom: () => number;
/**
* Sets the center of the view to the given position.
*
* @param x - x position
* @param y - y position
* @param options.zoom - optional zoom
*/
setCenter: (x: number, y: number, options?: SetCenterOptions) => void;
/**
* Sets the current viewport.
*
* @param viewport - the viewport to set
* @param options.duration - optional duration. If set, a transition will be applied
*/
setViewport: (viewport: Viewport, options?: ViewportHelperFunctionOptions) => void;
/**
* Returns the current viewport.
*
* @returns Viewport
*/
getViewport: () => Viewport;
/**
* Fits the view.
*
* @param options.padding - optional padding
* @param options.includeHiddenNodes - optional includeHiddenNodes
* @param options.minZoom - optional minZoom
* @param options.maxZoom - optional maxZoom
* @param options.duration - optional duration. If set, a transition will be applied
* @param options.nodes - optional nodes to fit the view to
*/
fitView: (options?: FitViewOptions) => void;
/**
* Returns all nodes that intersect with the given node or rect.
*
* @param node - the node or rect to check for intersections
* @param partially - if true, the node is considered to be intersecting if it partially overlaps with the passed node or rect
* @param nodes - optional nodes array to check for intersections
*
* @returns an array of intersecting nodes
*/
getIntersectingNodes: (
nodeOrRect: Node | { id: Node['id'] } | Rect,
partially?: boolean,
nodesToIntersect?: Node[]
) => Node[];
/**
* Checks if the given node or rect intersects with the passed rect.
*
* @param node - the node or rect to check for intersections
* @param area - the rect to check for intersections
* @param partially - if true, the node is considered to be intersecting if it partially overlaps with the passed react
*
* @returns true if the node or rect intersects with the given area
*/
isNodeIntersecting: (
nodeOrRect: Node | { id: Node['id'] } | Rect,
area: Rect,
partially?: boolean
) => boolean;
/**
* Fits the view to the given bounds .
*
* @param bounds - the bounds ({ x: number, y: number, width: number, height: number }) to fit the view to
* @param options.padding - optional padding
*/
fitBounds: (bounds: Rect, options?: FitBoundsOptions) => void;
/**
* Deletes nodes and edges.
*
* @param params.nodes - optional nodes array to delete
* @param params.edges - optional edges array to delete
*
* @returns a promise that resolves with the deleted nodes and edges
*/
deleteElements: ({
nodes,
edges
@@ -57,19 +161,66 @@ export function useSvelteFlow(): {
nodes?: (Node | { id: Node['id'] })[];
edges?: (Edge | { id: Edge['id'] })[];
}) => Promise<{ deletedNodes: Node[]; deletedEdges: Edge[] }>;
screenToFlowPosition: (position: XYPosition, options?: { snapToGrid: boolean }) => XYPosition;
flowToScreenPosition: (position: XYPosition) => XYPosition;
/**
* Converts a screen / client position to a flow position.
*
* @param clientPosition - the screen / client position. When you are working with events you can use event.clientX and event.clientY
* @param options.snapToGrid - if true, the converted position will be snapped to the grid
* @returns position as { x: number, y: number }
*
* @example
* const flowPosition = screenToFlowPosition({ x: event.clientX, y: event.clientY })
*/
screenToFlowPosition: (
clientPosition: XYPosition,
options?: { snapToGrid: boolean }
) => XYPosition;
/**
* Converts a flow position to a screen / client position.
*
* @param flowPosition - the screen / client position. When you are working with events you can use event.clientX and event.clientY
* @returns position as { x: number, y: number }
*
* @example
* const clientPosition = flowToScreenPosition({ x: node.position.x, y: node.position.y })
*/
flowToScreenPosition: (flowPosition: XYPosition) => XYPosition;
viewport: Writable<Viewport>;
/**
* Updates a node.
*
* @param id - id of the node to update
* @param nodeUpdate - the node update as an object or a function that receives the current node and returns the node update
* @param options.replace - if true, the node is replaced with the node update, otherwise the changes get merged
*
* @example
* updateNode('node-1', (node) => ({ position: { x: node.position.x + 10, y: node.position.y } }));
*/
updateNode: (
id: string,
nodeUpdate: Partial<Node> | ((node: Node) => Partial<Node>),
options?: { replace: boolean }
) => void;
/**
* Updates the data attribute of a node.
*
* @param id - id of the node to update
* @param dataUpdate - the data update as an object or a function that receives the current data and returns the data update
* @param options.replace - if true, the data is replaced with the data update, otherwise the changes get merged
*
* @example
* updateNodeData('node-1', { label: 'A new label' });
*/
updateNodeData: (
id: string,
dataUpdate: object | ((node: Node) => object),
options?: { replace: boolean }
) => void;
/**
* Returns the nodes, edges and the viewport as a JSON object.
*
* @returns the nodes, edges and the viewport as a JSON object
*/
toObject: () => { nodes: Node[]; edges: Edge[]; viewport: Viewport };
} {
const {
@@ -263,6 +414,11 @@ export function useSvelteFlow(): {
_snapGrid || [1, 1]
);
},
/**
*
* @param position
* @returns
*/
flowToScreenPosition: (position: XYPosition) => {
const _domNode = get(domNode);
@@ -279,6 +435,7 @@ export function useSvelteFlow(): {
y: rendererPosition.y + domY
};
},
toObject: () => {
return {
nodes: get(nodes).map((node) => ({
+1
View File
@@ -31,6 +31,7 @@ export * from '$lib/hooks/useConnection';
export * from '$lib/hooks/useNodesEdges';
export * from '$lib/hooks/useHandleConnections';
export * from '$lib/hooks/useNodesData';
export { useInitialized, useNodesInitialized } from '$lib/hooks/useInitialized';
// types
export type {
@@ -58,7 +58,7 @@
height: toolbarNode.computed?.height ?? toolbarNode.height ?? 0
};
} else if (toolbarNodes.length > 1) {
nodeRect = getNodesBounds(toolbarNodes, $nodeOrigin);
nodeRect = getNodesBounds(toolbarNodes, { nodeOrigin: $nodeOrigin });
}
if (nodeRect) {
+27
View File
@@ -105,6 +105,10 @@ export function createStore({
}
store.nodes.set(nextNodes);
if (!get(store.nodesInitialized)) {
store.nodesInitialized.set(true);
}
}
function fitView(nodes: Node[], options?: FitViewOptions) {
@@ -347,6 +351,29 @@ export function createStore({
[store.edges, store.defaultMarkerColor, store.flowId],
([edges, defaultColor, id]) => createMarkerIds(edges, { defaultColor, id })
),
initialized: (() => {
let initialized = false;
const initialNodesLength = get(store.nodes).length;
const initialEdgesLength = get(store.edges).length;
return derived(
[store.nodesInitialized, store.edgesInitialized, store.viewportInitialized],
([nodesInitialized, edgesInitialized, viewportInitialized]) => {
// If it was already initialized, return true from then on
if (initialized) return initialized;
// if it hasn't been initialised check if it's now
if (initialNodesLength === 0) {
initialized = viewportInitialized;
} else if (initialEdgesLength === 0) {
initialized = viewportInitialized && nodesInitialized;
} else {
initialized = viewportInitialized && nodesInitialized && edgesInitialized;
}
return initialized;
}
);
})(),
// actions
syncNodeStores: (nodes) => syncNodeStores(store.nodes, nodes),
@@ -23,7 +23,6 @@ import {
type OnConnectStart,
type OnConnectEnd,
type NodeLookup,
type OnBeforeDelete,
type EdgeLookup
} from '@xyflow/system';
@@ -47,7 +46,8 @@ import type {
Edge,
FitViewOptions,
OnDelete,
OnEdgeCreate
OnEdgeCreate,
OnBeforeDelete
} from '$lib/types';
import { createNodesStore, createEdgesStore } from './utils';
import { initConnectionProps, type ConnectionProps } from './derived-connection-props';
@@ -92,7 +92,8 @@ export const getInitialStore = ({
if (fitView && width && height) {
const nodesWithDimensions = nextNodes.filter((node) => node.width && node.height);
const bounds = getNodesBounds(nodesWithDimensions, [0, 0]);
// @todo users nodeOrigin should be used here
const bounds = getNodesBounds(nodesWithDimensions, { nodeOrigin: [0, 0] });
viewport = getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
}
@@ -152,6 +153,10 @@ export const getInitialStore = ({
onconnect: writable<OnConnect>(undefined),
onconnectstart: writable<OnConnectStart>(undefined),
onconnectend: writable<OnConnectEnd>(undefined),
onbeforedelete: writable<OnBeforeDelete>(undefined)
onbeforedelete: writable<OnBeforeDelete>(undefined),
nodesInitialized: writable<boolean>(false),
edgesInitialized: writable<boolean>(false),
viewportInitialized: writable<boolean>(false),
initialized: readable<boolean>(false)
};
};
+6 -1
View File
@@ -5,7 +5,8 @@ import type {
Position,
XYPosition,
ConnectingHandle,
Connection
Connection,
OnBeforeDeleteBase
} from '@xyflow/system';
import type { Node } from './nodes';
@@ -52,3 +53,7 @@ export type FitViewOptions = FitViewOptionsBase<Node>;
export type OnDelete = (params: { nodes: Node[]; edges: Edge[] }) => void;
export type OnEdgeCreate = (connection: Connection) => Edge | Connection | void;
export type OnBeforeDelete<
NodeType extends Node = Node,
EdgeType extends Edge = Edge
> = OnBeforeDeleteBase<NodeType, EdgeType>;