fix useNodeConnections callback not firing if connections.current not used

This commit is contained in:
peterkogo
2025-06-12 15:50:14 +02:00
parent 74599bb8dc
commit 5e33ac3e8b
2 changed files with 36 additions and 5 deletions

View File

@@ -16,6 +16,15 @@
handleType: 'target'
});
useNodeConnections({
onConnect: (connection) => {
console.log('Connection made:', connection);
},
onDisconnect: (connection) => {
console.log('Connection disconnected:', connection);
}
});
let nodeData = $derived(
useNodesData<MyNode>(connections.current.map((connection) => connection.source))
);

View File

@@ -17,6 +17,8 @@ type UseNodeConnectionsParams = {
onDisconnect?: (connections: Connection[]) => void;
};
type ConnectionMap = Map<string, NodeConnection>;
const initialConnections: NodeConnection[] = [];
/**
@@ -42,26 +44,46 @@ export function useNodeConnections({
const contextNodeId = getContext<string>('svelteflow__node_id');
const nodeId = id ?? contextNodeId;
let prevConnections: Map<string, NodeConnection> = new Map();
let connectionMaps: { previous: ConnectionMap; next: ConnectionMap } = {
previous: new Map(),
next: new Map()
};
let connectionsArray: NodeConnection[] = initialConnections;
const connections = $derived.by(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
edges;
const prevConnections = connectionMaps.next;
const nextConnections =
connectionLookup.get(
`${nodeId}${handleType ? (handleId ? `-${handleType}-${handleId}` : `-${handleType}`) : ''}`
) ?? new Map();
if (!areConnectionMapsEqual(nextConnections, prevConnections)) {
if (onConnect) handleConnectionChange(nextConnections, prevConnections, onConnect);
if (onDisconnect) handleConnectionChange(prevConnections, nextConnections, onDisconnect);
prevConnections = nextConnections;
connectionMaps = {
previous: prevConnections,
next: nextConnections
};
connectionsArray = Array.from(nextConnections.values() || initialConnections);
}
return connectionsArray;
});
$effect(() => {
// We subscribe to changes to the connections only when onConnect/onDisconnect are provided
if (onConnect) {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
connections;
handleConnectionChange(connectionMaps.next, connectionMaps.previous, onConnect);
}
if (onDisconnect) {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
connections;
handleConnectionChange(connectionMaps.previous, connectionMaps.next, onDisconnect);
}
});
return {
get current() {
return connections;