fixed useConnection hook, made derivedWarnings more specific, fixed updating when internals change

This commit is contained in:
peterkogo
2024-12-12 16:14:29 +01:00
parent 9105d22c46
commit 72c075e5fb
16 changed files with 176 additions and 154 deletions
@@ -1,5 +1,4 @@
<script lang="ts"> <script lang="ts">
import { writable } from 'svelte/store';
import { import {
SvelteFlow, SvelteFlow,
useSvelteFlow, useSvelteFlow,
@@ -19,11 +18,11 @@
} }
]; ];
const nodes = writable<Node[]>(initialNodes); let nodes = $state.raw<Node[]>(initialNodes);
const edges = writable<Edge[]>([]); let edges = $state.raw<Edge[]>([]);
let connectingNodeId: string | null = $state('0'); let connectingNodeId: string | null = $state('0');
let rect: DOMRectReadOnly = $state(); let rect = $state<DOMRectReadOnly>();
let id = 1; let id = 1;
const getId = () => `${id++}`; const getId = () => `${id++}`;
@@ -56,15 +55,12 @@
origin: [0.5, 0.0] origin: [0.5, 0.0]
}; };
$nodes.push(newNode); nodes.push(newNode);
$edges.push({ edges.push({
source: connectingNodeId, source: connectingNodeId,
target: id, target: id,
id: `${connectingNodeId}--${id}` id: `${connectingNodeId}--${id}`
}); });
$nodes = $nodes;
$edges = $edges;
} }
}; };
</script> </script>
@@ -73,8 +69,8 @@
<div class="wrapper" bind:contentRect={rect}> <div class="wrapper" bind:contentRect={rect}>
<SvelteFlow <SvelteFlow
{nodes} bind:nodes
{edges} bind:edges
fitView fitView
fitViewOptions={{ padding: 2 }} fitViewOptions={{ padding: 2 }}
onconnectstart={(_, { nodeId }) => { onconnectstart={(_, { nodeId }) => {
@@ -1,5 +1,4 @@
<script lang="ts"> <script lang="ts">
import { writable } from 'svelte/store';
import { import {
SvelteFlow, SvelteFlow,
Controls, Controls,
@@ -18,7 +17,7 @@
targetPosition: Position.Left targetPosition: Position.Left
}; };
const nodes = writable([ let nodes = $state.raw([
{ {
id: 'A', id: 'A',
position: { x: 0, y: 150 }, position: { x: 0, y: 150 },
@@ -30,16 +29,16 @@
{ id: 'D', position: { x: 250, y: 300 }, data: { label: 'D' }, ...nodeDefaults } { id: 'D', position: { x: 250, y: 300 }, data: { label: 'D' }, ...nodeDefaults }
]); ]);
const edges = writable([ let edges = $state.raw([
{ id: 'A-B', source: 'A', target: 'B' }, { id: 'A-B', source: 'A', target: 'B' },
{ id: 'A-C', source: 'A', target: 'C' }, { id: 'A-C', source: 'A', target: 'C' },
{ id: 'A-D', source: 'A', target: 'D' } { id: 'A-D', source: 'A', target: 'D' }
]); ]);
let colorMode: ColorMode = $state('light'); let colorMode: ColorMode = $state('dark');
</script> </script>
<SvelteFlow {nodes} {edges} {colorMode} fitView> <SvelteFlow bind:nodes bind:edges {colorMode} fitView>
<Controls /> <Controls />
<Background variant={BackgroundVariant.Dots} /> <Background variant={BackgroundVariant.Dots} />
<MiniMap /> <MiniMap />
@@ -1,7 +1,6 @@
<script lang="ts"> <script lang="ts">
import { SvelteFlow } from '@xyflow/svelte'; import { SvelteFlow } from '@xyflow/svelte';
import { Background, BackgroundVariant, type Edge, type Node } from '@xyflow/svelte'; import { Background, BackgroundVariant, type Edge, type Node } from '@xyflow/svelte';
import { writable } from 'svelte/store';
import CustomNode from './CustomNode.svelte'; import CustomNode from './CustomNode.svelte';
import ConnectionLine from './ConnectionLine.svelte'; import ConnectionLine from './ConnectionLine.svelte';
@@ -12,7 +11,7 @@
custom: CustomNode custom: CustomNode
}; };
const nodes = writable<Node[]>([ let nodes = $state.raw<Node[]>([
{ {
id: 'connectionline-1', id: 'connectionline-1',
type: 'custom', type: 'custom',
@@ -21,14 +20,14 @@
} }
]); ]);
const edges = writable<Edge[]>([]); let edges = $state.raw<Edge[]>([]);
</script> </script>
<div style="height:100vh;"> <div style="height:100vh;">
<SvelteFlow {nodeTypes} {nodes} {edges} fitView> <SvelteFlow bind:nodes bind:edges {nodeTypes} fitView>
{#snippet connectionLine()} {#snippet connectionLine()}
<ConnectionLine /> <ConnectionLine />
{/snippet} {/snippet}
<Background variant={BackgroundVariant.Lines} /> <Background variant={BackgroundVariant.Lines} />
</SvelteFlow> </SvelteFlow>
</div> </div>
@@ -1,11 +1,11 @@
<script lang="ts"> <script lang="ts">
import { getBezierPath, useConnection } from '@xyflow/svelte'; import { getBezierPath, useConnection } from '@xyflow/svelte';
const connection = useConnection(); const connection = $derived(useConnection());
let path: string | null = $derived.by(() => { let path: string | null = $derived.by(() => {
if ($connection.inProgress) { if (connection.inProgress) {
const { from, to, fromPosition, toPosition } = $connection; const { from, to, fromPosition, toPosition } = connection;
const pathParams = { const pathParams = {
sourceX: from.x, sourceX: from.x,
sourceY: from.y, sourceY: from.y,
@@ -21,6 +21,6 @@
}); });
</script> </script>
{#if $connection.inProgress} {#if connection.inProgress}
<path d={path} fill="none" stroke={$connection.fromHandle.id} /> <path d={path} fill="none" stroke={connection.fromHandle.id} />
{/if} {/if}
@@ -1,5 +1,13 @@
<script lang="ts" module>
// TODO: Is this the best way?
class background {
color: string = $state('#1A192B');
}
export const bg = new background();
</script>
<script lang="ts"> <script lang="ts">
import { writable } from 'svelte/store';
import { import {
SvelteFlow, SvelteFlow,
Controls, Controls,
@@ -20,9 +28,7 @@
colorNode: CustomNode colorNode: CustomNode
}; };
const bgColor = writable('#1A192B'); let nodes = $state.raw<Node[]>([
const nodes = writable<Node[]>([
{ {
id: '1', id: '1',
type: 'input', type: 'input',
@@ -33,7 +39,7 @@
{ {
id: '2', id: '2',
type: 'colorNode', type: 'colorNode',
data: { colorStore: bgColor }, data: {},
position: { x: 250, y: 50 } position: { x: 250, y: 50 }
}, },
{ {
@@ -52,7 +58,7 @@
} }
]); ]);
const edges = writable<Edge[]>([ let edges = $state.raw<Edge[]>([
{ {
id: 'e1-2', id: 'e1-2',
source: '1', source: '1',
@@ -81,10 +87,10 @@
</script> </script>
<SvelteFlow <SvelteFlow
{nodes} bind:nodes
{edges} bind:edges
{nodeTypes} {nodeTypes}
style="--xy-background-color: {$bgColor}" style="--xy-background-color: {bg.color}"
fitView fitView
onconnect={onConnect} onconnect={onConnect}
> >
@@ -1,8 +1,8 @@
<script lang="ts"> <script lang="ts">
import type { Writable } from 'svelte/store';
import { Handle, Position, type NodeProps, type Node } from '@xyflow/svelte'; import { Handle, Position, type NodeProps, type Node } from '@xyflow/svelte';
import { bg } from './+page.svelte';
let { data }: NodeProps<Node<{ colorStore: Writable<string> }>> = $props(); let { data }: NodeProps<Node> = $props();
const { colorStore } = data; const { colorStore } = data;
</script> </script>
@@ -10,13 +10,13 @@
<div class="custom"> <div class="custom">
<Handle type="target" position={Position.Left} /> <Handle type="target" position={Position.Left} />
<div> <div>
Custom Color Picker Node: <strong>{$colorStore}</strong> Custom Color Picker Node: <strong>{bg.color}</strong>
</div> </div>
<input <input
class="nodrag" class="nodrag"
type="color" type="color"
oninput={(evt) => colorStore.set(evt.currentTarget.value)} oninput={(evt) => (bg.color = evt.currentTarget.value)}
value={$colorStore} value={bg.color}
/> />
<Handle type="source" position={Position.Right} id="a" style="top: 20px;" /> <Handle type="source" position={Position.Right} id="a" style="top: 20px;" />
<Handle type="source" position={Position.Right} id="b" style="top: auto; bottom: 10px;" /> <Handle type="source" position={Position.Right} id="b" style="top: auto; bottom: 10px;" />
@@ -1,79 +1,78 @@
<script lang="ts"> <script lang="ts">
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import { SvelteFlow, Background, Position, ConnectionLineType, Panel } from '@xyflow/svelte'; import { SvelteFlow, Background, Position, ConnectionLineType, Panel } from '@xyflow/svelte';
import type { Edge, Node } from '@xyflow/svelte'; import type { Edge, Node } from '@xyflow/svelte';
import dagre from '@dagrejs/dagre'; import dagre from '@dagrejs/dagre';
import '@xyflow/svelte/dist/style.css'; import '@xyflow/svelte/dist/style.css';
import { initialNodes, initialEdges } from './nodes-and-edges'; import { initialNodes, initialEdges } from './nodes-and-edges';
const dagreGraph = new dagre.graphlib.Graph(); const dagreGraph = new dagre.graphlib.Graph();
dagreGraph.setDefaultEdgeLabel(() => ({})); dagreGraph.setDefaultEdgeLabel(() => ({}));
const nodeWidth = 172; const nodeWidth = 172;
const nodeHeight = 36; const nodeHeight = 36;
function getLayoutedElements(nodes: Node[], edges: Edge[], direction = 'TB') { function getLayoutedElements(nodes: Node[], edges: Edge[], direction = 'TB') {
const isHorizontal = direction === 'LR'; const isHorizontal = direction === 'LR';
dagreGraph.setGraph({ rankdir: direction }); dagreGraph.setGraph({ rankdir: direction });
nodes.forEach((node) => { nodes.forEach((node) => {
dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight }); dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
}); });
edges.forEach((edge) => { edges.forEach((edge) => {
dagreGraph.setEdge(edge.source, edge.target); dagreGraph.setEdge(edge.source, edge.target);
}); });
dagre.layout(dagreGraph); dagre.layout(dagreGraph);
nodes.forEach((node) => { const layoutedNodes = nodes.map((node) => {
const nodeWithPosition = dagreGraph.node(node.id); const nodeWithPosition = dagreGraph.node(node.id);
node.targetPosition = isHorizontal ? Position.Left : Position.Top;
node.sourcePosition = isHorizontal ? Position.Right : Position.Bottom;
// We are shifting the dagre node position (anchor=center center) to the top left return {
// so it matches the React Flow node anchor point (top left). ...node,
node.position = { targetPosition: isHorizontal ? Position.Left : Position.Top,
x: nodeWithPosition.x - nodeWidth / 2, sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
y: nodeWithPosition.y - nodeHeight / 2 position: {
}; x: nodeWithPosition.x - nodeWidth / 2,
}); y: nodeWithPosition.y - nodeHeight / 2
}
};
});
return { nodes, edges }; return { nodes: layoutedNodes, edges };
} }
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements( const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
initialNodes, initialNodes,
initialEdges initialEdges
); );
const nodes = writable<Node[]>(layoutedNodes); let nodes = $state.raw<Node[]>(layoutedNodes);
const edges = writable<Edge[]>(layoutedEdges); let edges = $state.raw<Edge[]>(layoutedEdges);
function onLayout(direction: string) { function onLayout(direction: string) {
const layoutedElements = getLayoutedElements($nodes, $edges, direction); const layoutedElements = getLayoutedElements(nodes, edges, direction);
$nodes = layoutedElements.nodes; nodes = layoutedElements.nodes;
$edges = layoutedElements.edges; edges = layoutedElements.edges;
// nodes.set(layoutedElements.nodes); }
// edges.set(layoutedElements.edges);
}
</script> </script>
<div style="height:100vh;"> <div style="height:100vh;">
<SvelteFlow <SvelteFlow
{nodes} bind:nodes
{edges} bind:edges
fitView fitView
connectionLineType={ConnectionLineType.SmoothStep} connectionLineType={ConnectionLineType.SmoothStep}
defaultEdgeOptions={{ type: 'smoothstep', animated: true }} defaultEdgeOptions={{ type: 'smoothstep', animated: true }}
> >
<Panel position="top-right"> <Panel position="top-right">
<button onclick={() => onLayout('TB')}>vertical layout</button> <button onclick={() => onLayout('TB')}>vertical layout</button>
<button onclick={() => onLayout('LR')}>horizontal layout</button> <button onclick={() => onLayout('LR')}>horizontal layout</button>
</Panel> </Panel>
<Background /> <Background />
</SvelteFlow> </SvelteFlow>
</div> </div>
@@ -23,8 +23,6 @@
connectionLine?: Snippet; connectionLine?: Snippet;
} = $props(); } = $props();
// $inspect(store.connection);
let path = $derived.by(() => { let path = $derived.by(() => {
if (!store.connection.inProgress) { if (!store.connection.inProgress) {
return ''; return '';
@@ -99,7 +99,7 @@
// Set store for provider context // Set store for provider context
const providerContext = getContext<ProviderContext>(key); const providerContext = getContext<ProviderContext>(key);
if (providerContext) { if (providerContext && providerContext.setStore) {
providerContext.setStore(store); providerContext.setStore(store);
} }
@@ -2,7 +2,14 @@ import { key } from '$lib/store';
import type { StoreContext } from '$lib/store/types'; import type { StoreContext } from '$lib/store/types';
import { getContext } from 'svelte'; import { getContext } from 'svelte';
export function derivedWarning(functionName: string) { /**
* Warns the user that they should use $derived() when calling a hook.
* This is not neccessarry when the hook is called inside a child of <SvelteFlowFlow />,
* however exceptions can be made if you don't want to return a closure.
* @param functionName - The name of the function that is being called
* @param force - If true, the warning will be shown regardless if child of <SvelteFlowFlow />
*/
export function derivedWarning(functionName: string, force?: boolean) {
const storeContext = getContext<StoreContext>(key); const storeContext = getContext<StoreContext>(key);
if (!storeContext) { if (!storeContext) {
@@ -11,9 +18,8 @@ export function derivedWarning(functionName: string) {
); );
} }
if (storeContext.provider && !$effect.tracking()) { if ((force || storeContext.provider) && !$effect.tracking()) {
console.warn( console.warn(`Use $derived(${functionName}()) to receive updates when values change.`);
`Use $derived(${functionName}()), when not calling inside a child of the <SvelteFlow /> component.` console.trace(functionName);
);
} }
} }
@@ -0,0 +1,18 @@
import { useStore } from '$lib/store';
import type { ConnectionState } from '@xyflow/system';
import { derivedWarning } from './derivedWarning.svelte';
/**
* Hook for receiving the current connection.
*
* @public
* @returns current connection as a readable store
*/
export function useConnection(): ConnectionState {
if (process.env.NODE_ENV === 'development') {
derivedWarning('useConnection', true);
}
return useStore().connection;
}
@@ -1,16 +0,0 @@
import type { Readable } from 'svelte/store';
import { useStore } from '$lib/store';
import type { ConnectionState } from '@xyflow/system';
/**
* Hook for receiving the current connection.
*
* @public
* @returns current connection as a readable store
*/
export function useConnection(): Readable<ConnectionState> {
const { connection } = useStore();
return connection;
}
@@ -4,18 +4,10 @@ import { errorMessages } from '@xyflow/system';
import { useStore } from '$lib/store'; import { useStore } from '$lib/store';
export function useHandleEdgeSelect() { export function useHandleEdgeSelect() {
const { const store = useStore();
edgeLookup,
selectionRect,
selectionRectMode,
multiselectionKeyPressed,
addSelectedEdges,
unselectNodesAndEdges,
elementsSelectable
} = useStore();
return (id: string) => { return (id: string) => {
const edge = get(edgeLookup).get(id); const edge = store.edgeLookup.get(id);
if (!edge) { if (!edge) {
console.warn('012', errorMessages['error012'](id)); console.warn('012', errorMessages['error012'](id));
@@ -23,16 +15,16 @@ export function useHandleEdgeSelect() {
} }
const selectable = const selectable =
edge.selectable || (get(elementsSelectable) && typeof edge.selectable === 'undefined'); edge.selectable || (store.elementsSelectable && typeof edge.selectable === 'undefined');
if (selectable) { if (selectable) {
selectionRect.set(null); store.selectionRect = null;
selectionRectMode.set(null); store.selectionRectMode = null;
if (!edge.selected) { if (!edge.selected) {
addSelectedEdges([id]); store.addSelectedEdges([id]);
} else if (edge.selected && get(multiselectionKeyPressed)) { } else if (edge.selected && store.multiselectionKeyPressed) {
unselectNodesAndEdges({ nodes: [], edges: [edge] }); store.unselectNodesAndEdges({ nodes: [], edges: [edge] });
} }
} }
}; };
+1 -1
View File
@@ -33,7 +33,7 @@ export * from '$lib/utils';
//hooks //hooks
export * from '$lib/hooks/useSvelteFlow'; export * from '$lib/hooks/useSvelteFlow';
export * from '$lib/hooks/useUpdateNodeInternals'; export * from '$lib/hooks/useUpdateNodeInternals';
export * from '$lib/hooks/useConnection'; export * from '$lib/hooks/useConnection.svelte';
export * from '$lib/hooks/useNodesEdges'; export * from '$lib/hooks/useNodesEdges';
export * from '$lib/hooks/useHandleConnections'; export * from '$lib/hooks/useHandleConnections';
export * from '$lib/hooks/useNodesData'; export * from '$lib/hooks/useNodesData';
@@ -72,7 +72,7 @@ export const initialEdgeTypes = {
export const getInitialStore = (signals: StoreSignals) => { export const getInitialStore = (signals: StoreSignals) => {
// We use a class here, because Svelte adds getters & setter for us. // We use a class here, because Svelte adds getters & setter for us.
// Inline classes have some performance implications but we just call it once. // Inline classes have some performance implications but we just call it once (max twice).
class SvelteFlowStore { class SvelteFlowStore {
get nodes() { get nodes() {
return signals.nodes; return signals.nodes;
@@ -223,6 +223,11 @@ export const getInitialStore = (signals: StoreSignals) => {
}); });
this.viewport = getViewportForBounds(bounds, this.width, this.height, 0.5, 2, 0.1); this.viewport = getViewportForBounds(bounds, this.width, this.height, 0.5, 2, 0.1);
} }
if (process.env.NODE_ENV === 'development') {
warnIfDeeplyReactive(signals.nodes, 'nodes');
warnIfDeeplyReactive(signals.edges, 'edges');
}
} }
resetStoreValues() { resetStoreValues() {
@@ -231,3 +236,16 @@ export const getInitialStore = (signals: StoreSignals) => {
} }
return new SvelteFlowStore(); return new SvelteFlowStore();
}; };
// Only way to check if an object is a proxy
// is to see if is failes to perform a structured clone
// TODO: is $state.raw really nessessary?
function warnIfDeeplyReactive(array: unknown[] | undefined, name: string) {
try {
if (array && array.length > 0) {
structuredClone(array[0]);
}
} catch {
console.warn(`Use $state.raw for ${name} to prevent performance issues.`);
}
}
+19 -12
View File
@@ -337,10 +337,13 @@ export function updateNodeInternals<NodeType extends InternalNodeBase>(
} }
if (node.hidden) { if (node.hidden) {
node.internals = { nodeLookup.set(node.id, {
...node.internals, ...node,
handleBounds: undefined, internals: {
}; ...node.internals,
handleBounds: undefined,
},
});
updatedInternals = true; updatedInternals = true;
} else { } else {
const dimensions = getDimensions(update.nodeElement); const dimensions = getDimensions(update.nodeElement);
@@ -362,15 +365,19 @@ export function updateNodeInternals<NodeType extends InternalNodeBase>(
positionAbsolute = clampPosition(positionAbsolute, extent, dimensions); positionAbsolute = clampPosition(positionAbsolute, extent, dimensions);
} }
node.measured = dimensions; nodeLookup.set(node.id, {
node.internals = { ...node,
...node.internals, measured: dimensions,
positionAbsolute, internals: {
handleBounds: { ...node.internals,
source: getHandleBounds('source', update.nodeElement, nodeBounds, zoom, node.id), positionAbsolute,
target: getHandleBounds('target', update.nodeElement, nodeBounds, zoom, node.id), handleBounds: {
source: getHandleBounds('source', update.nodeElement, nodeBounds, zoom, node.id),
target: getHandleBounds('target', update.nodeElement, nodeBounds, zoom, node.id),
},
}, },
}; });
if (node.parentId) { if (node.parentId) {
updateChildNode(node, nodeLookup, parentLookup, { nodeOrigin }); updateChildNode(node, nodeLookup, parentLookup, { nodeOrigin });
} }