-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
useNodesData.ts
47 lines (42 loc) · 1.51 KB
/
useNodesData.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { derived, type Readable } from 'svelte/store';
import { shallowNodeData } from '@xyflow/system';
import type { Node } from '$lib/types';
import { useStore } from '$lib/store';
/**
* Hook for receiving data of one or multiple nodes
*
* @public
* @param nodeId - The id (or ids) of the node to get the data from
* @returns A readable store with an array of data objects
*/
export function useNodesData<NodeType extends Node = Node>(
nodeId: string
): Readable<Pick<NodeType, 'id' | 'data' | 'type'> | null>;
export function useNodesData<NodeType extends Node = Node>(
nodeIds: string[]
): Readable<Pick<NodeType, 'id' | 'data' | 'type'>[]>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useNodesData(nodeIds: any): any {
const { nodes, nodeLookup } = useStore();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let prevNodesData: any[] = [];
return derived([nodes, nodeLookup], ([, nodeLookup], set) => {
const nextNodesData = [];
const isArrayOfIds = Array.isArray(nodeIds);
const _nodeIds = isArrayOfIds ? nodeIds : [nodeIds];
for (const nodeId of _nodeIds) {
const node = nodeLookup.get(nodeId)?.internals.userNode;
if (node) {
nextNodesData.push({
id: node.id,
type: node.type,
data: node.data
});
}
}
if (!shallowNodeData(nextNodesData, prevNodesData)) {
prevNodesData = nextNodesData;
set(isArrayOfIds ? nextNodesData : nextNodesData[0] ?? null);
}
});
}