Line data Source code
1 : import {
2 : createSharedComposable,
3 : tryOnScopeDispose,
4 : useThrottleFn
5 : } from '@vueuse/core'
6 : import { computed, ref, watch } from 'vue'
7 :
8 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
9 : import { api } from '@/scripts/api'
10 : import { useApp } from '@/scripts/appInstance'
11 : import { useNodeDefStore } from '@/stores/nodeDefStore'
12 : import { reduceAllNodes } from '@/utils/graphTraversalUtil'
13 :
14 : export interface PartnerNodeInfo {
15 : nodeName: string
16 : displayName: string
17 : }
18 :
19 : /**
20 : * Scan the active graph (subgraphs included) for partner nodes right now,
21 : * deduped by def name. Synchronous and unthrottled so callers that gate a
22 : * queue decision see the current graph, not a throttled snapshot.
23 : */
24 15661 : export function scanPartnerNodesInGraph(): PartnerNodeInfo[] {
25 15661 : if (!useApp().isGraphReady) return []
26 13306 : const nodeDefStore = useNodeDefStore()
27 : const partnerNodesByName = reduceAllNodes<Map<string, PartnerNodeInfo>>(
28 : useApp().rootGraph,
29 : (found, node) => {
30 51481 : const nodeDef = nodeDefStore.fromLGraphNode(node)
31 51481 : if (nodeDef?.api_node) {
32 93 : found.set(nodeDef.name, {
33 : nodeName: nodeDef.name,
34 : displayName: nodeDef.display_name || nodeDef.name
35 : })
36 : }
37 51481 : return found
38 : },
39 : new Map()
40 : )
41 13306 : return [...partnerNodesByName.values()]
42 : }
43 :
44 : /**
45 : * Reactive list of partner nodes (node defs with `api_node: true`) in the
46 : * active graph, including nodes nested in subgraphs, deduped by def name.
47 : */
48 2356 : export const usePartnerNodesInGraph = createSharedComposable(() => {
49 2355 : const workflowStore = useWorkflowStore()
50 :
51 2355 : const graphVersion = ref(0)
52 : // Leading + trailing: gate state reacts to a topology change immediately, yet
53 : // a drag still re-scans at most twice per burst rather than every frame.
54 2355 : const bumpGraphVersion = useThrottleFn(
55 : () => {
56 5041 : graphVersion.value++
57 : },
58 : 200,
59 : true,
60 : true
61 : )
62 :
63 2355 : const onGraphChanged = () => {
64 1589 : void bumpGraphVersion()
65 : }
66 2355 : api.addEventListener('graphChanged', onGraphChanged)
67 2355 : tryOnScopeDispose(() => {
68 0 : api.removeEventListener('graphChanged', onGraphChanged)
69 : })
70 2355 : watch(
71 : () => workflowStore.activeWorkflow,
72 : () => {
73 3796 : void bumpGraphVersion()
74 : }
75 : )
76 :
77 2355 : const partnerNodes = computed<PartnerNodeInfo[]>(() => {
78 : // Dependency on graphVersion: re-scan when the graph mutates.
79 15583 : void graphVersion.value
80 15583 : return scanPartnerNodesInGraph()
81 : })
82 :
83 : const hasPartnerNodes = computed(() => partnerNodes.value.length > 0)
84 :
85 2355 : return { partnerNodes, hasPartnerNodes }
86 : })
|