|
| 1 | +import type { ComputedRef, MaybeRefOrGetter } from 'vue' |
| 2 | +import { computed, toValue } from 'vue' |
| 3 | +import type { Edge, GraphEdge } from '../types' |
| 4 | +import { warn } from '../utils' |
| 5 | +import { useVueFlow } from './useVueFlow' |
| 6 | + |
| 7 | +interface EdgeData<EdgeType extends Edge = GraphEdge> { |
| 8 | + id: string |
| 9 | + type: EdgeType['type'] |
| 10 | + data: NonNullable<EdgeType['data']> | null |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Composable for receiving data of one or multiple nodes |
| 15 | + * |
| 16 | + * @public |
| 17 | + * @param edgeId - The id (or ids) of the node to get the data from |
| 18 | + * @param guard - Optional guard function to narrow down the node type |
| 19 | + * @returns An array of data objects |
| 20 | + */ |
| 21 | +export function useEdgesData<EdgeType extends Edge = GraphEdge>( |
| 22 | + edgeId: MaybeRefOrGetter<string>, |
| 23 | +): ComputedRef<EdgeData<EdgeType> | null> |
| 24 | +export function useEdgesData<EdgeType extends Edge = GraphEdge>( |
| 25 | + edgeIds: MaybeRefOrGetter<string[]>, |
| 26 | +): ComputedRef<EdgeData<EdgeType>[]> |
| 27 | +export function useEdgesData<EdgeType extends Edge = GraphEdge>( |
| 28 | + edgeIds: MaybeRefOrGetter<string[]>, |
| 29 | + guard: (node: Edge) => node is EdgeType, |
| 30 | +): ComputedRef<EdgeData<EdgeType>[]> |
| 31 | +export function useEdgesData(_edgeIds: any): any { |
| 32 | + const { findEdge } = useVueFlow() |
| 33 | + |
| 34 | + return computed({ |
| 35 | + get() { |
| 36 | + const edgeIds = toValue(_edgeIds) |
| 37 | + |
| 38 | + if (!Array.isArray(edgeIds)) { |
| 39 | + const edge = findEdge(edgeIds) |
| 40 | + |
| 41 | + if (edge) { |
| 42 | + return { |
| 43 | + id: edge.id, |
| 44 | + type: edge.type, |
| 45 | + data: edge.data ?? null, |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return null |
| 50 | + } |
| 51 | + |
| 52 | + const data: EdgeData<Edge>[] = [] |
| 53 | + |
| 54 | + for (const edgeId of edgeIds) { |
| 55 | + const edge = findEdge(edgeId) |
| 56 | + |
| 57 | + if (edge) { |
| 58 | + data.push({ |
| 59 | + id: edge.id, |
| 60 | + type: edge.type, |
| 61 | + data: edge.data ?? null, |
| 62 | + }) |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return data |
| 67 | + }, |
| 68 | + set() { |
| 69 | + // noop |
| 70 | + warn('You are trying to set edge data via useEdgesData. This is not supported.') |
| 71 | + }, |
| 72 | + }) |
| 73 | +} |
0 commit comments