Line data Source code
1 : import { nextTick } from 'vue'
2 :
3 : import { visibleCanvasViewport } from '@/composables/canvas/visibleCanvasViewport'
4 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
5 : import { app } from '@/scripts/app'
6 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
7 : import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore'
8 : import { getNodeByExecutionId } from '@/utils/graphTraversalUtil'
9 :
10 0 : async function waitForAnimationFrame() {
11 0 : await new Promise<void>((resolve) => {
12 0 : const timeoutId = window.setTimeout(resolve, 100)
13 0 : requestAnimationFrame(() => {
14 0 : window.clearTimeout(timeoutId)
15 0 : resolve()
16 : })
17 : })
18 : }
19 :
20 0 : async function waitForCanvasNavigation() {
21 0 : await nextTick()
22 :
23 : // Double frame waits for LiteGraph's internal canvas cycle. The timeout
24 : // keeps focus calls from hanging while the document is backgrounded.
25 0 : await waitForAnimationFrame()
26 0 : await waitForAnimationFrame()
27 : }
28 :
29 201 : export function useFocusNode() {
30 201 : const canvasStore = useCanvasStore()
31 201 : const navigationStore = useSubgraphNavigationStore()
32 :
33 5 : async function focusNodeInstance(node: LGraphNode) {
34 5 : const canvas = canvasStore.canvas
35 5 : if (!canvas || !node.graph) return
36 :
37 5 : const graphChanged = canvas.graph !== node.graph
38 : const navigated = await navigationStore.navigateToGraph(node.graph)
39 5 : if (!navigated) return
40 5 : if (graphChanged) await waitForCanvasNavigation()
41 :
42 5 : const activeCanvas = canvasStore.canvas
43 5 : if (
44 : !activeCanvas ||
45 : activeCanvas.graph !== node.graph ||
46 : !node.graph.nodes.includes(node)
47 : ) {
48 0 : return
49 : }
50 5 : activeCanvas.animateToBounds(node.boundingRect, {
51 : viewport: visibleCanvasViewport(activeCanvas)
52 : })
53 : }
54 :
55 : /* Locate and focus a node on the canvas by its execution ID. */
56 5 : async function focusNode(
57 : nodeId: string,
58 : executionIdMap?: Map<string, LGraphNode>
59 : ) {
60 5 : if (!canvasStore.canvas) return
61 :
62 5 : const graphNode = executionIdMap
63 : ? executionIdMap.get(nodeId)
64 : : getNodeByExecutionId(app.rootGraph, nodeId)
65 5 : if (!graphNode?.graph) return
66 :
67 5 : await focusNodeInstance(graphNode)
68 : }
69 :
70 201 : return {
71 : focusNode,
72 : focusNodeInstance
73 : }
74 : }
|