import type { ConnectionLookup, HandleType, NodeConnection } from '../types'; /** * Returns the key under which the connections of a node are stored in the connection lookup. * Without a handle type, the key covers all connections of the node. A handle id is only used * together with a handle type, because handle ids are only unique per handle type. * * @internal */ export function getConnectionLookupKey(nodeId: string, handleType?: HandleType | null, handleId?: string | null) { if (!handleType) { return nodeId; } return handleId ? `${nodeId}-${handleType}-${handleId}` : `${nodeId}-${handleType}`; } /** * Returns the connections of a node, optionally filtered by handle type and handle id. * * @internal */ export function getConnectionsFromLookup( connectionLookup: ConnectionLookup, { nodeId, type, handleId, }: { nodeId: string; type?: HandleType | null; handleId?: string | null; } ): NodeConnection[] { return Array.from(connectionLookup.get(getConnectionLookupKey(nodeId, type, handleId))?.values() ?? []); } /** * @internal */ export function areConnectionMapsEqual(a?: Map, b?: Map) { if (a === b) { return true; } if (!a || !b || a.size !== b.size) { return false; } if (!a.size && !b.size) { return true; } for (const [key, connection] of a) { if (b.get(key) !== connection) { return false; } } return true; } /** * Connections get recreated whenever the connection lookup is rebuilt (e.g. after the store * was reset in React StrictMode), so we compare them by value instead of by reference. */ function isSameConnection(a: NodeConnection, b?: NodeConnection) { return ( a === b || (!!b && a.edgeId === b.edgeId && a.source === b.source && a.target === b.target && a.sourceHandle == b.sourceHandle && a.targetHandle == b.targetHandle) ); } /** * We call the callback for all connections in a that are not in b * * @internal */ export function handleConnectionChange( a: Map, b: Map, cb?: (diff: NodeConnection[]) => void ) { if (!cb) { return; } const diff: NodeConnection[] = []; a.forEach((connection, key) => { if (!isSameConnection(connection, b?.get(key))) { diff.push(connection); } }); if (diff.length) { cb(diff); } } export function getConnectionStatus(isValid: boolean | null) { return isValid === null ? null : isValid ? 'valid' : 'invalid'; }