Line data Source code
1 : import { computed, shallowRef, toValue, watch } from 'vue'
2 : import type { ComputedRef, MaybeRefOrGetter } from 'vue'
3 :
4 : import { onCanvasFrame } from '@/lib/litegraph/src/canvas/canvasFrame'
5 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
6 : import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations'
7 : import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
8 : import { LayoutSource } from '@/renderer/core/layout/types'
9 : import type { NodeLayout } from '@comfyorg/graph-model/layout'
10 : import type { Point2D as Point } from '@comfyorg/shared-frontend-utils/geometry'
11 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
12 :
13 8015 : export function useNodeLayout(nodeIdMaybe: MaybeRefOrGetter<NodeId>) {
14 8015 : const nodeId = toValue(nodeIdMaybe)
15 8015 : const mutations = useLayoutMutations(LayoutSource.Vue)
16 8015 : const canvasStore = useCanvasStore()
17 :
18 8015 : const layoutRef = shallowRef<ComputedRef<NodeLayout | null> | null>(null)
19 8015 : watch(
20 : () => canvasStore.rootGraphId,
21 : (rootGraphId) => {
22 8015 : if (!rootGraphId) {
23 0 : layoutRef.value = null
24 0 : return
25 : }
26 :
27 8015 : layoutRef.value = layoutStore.getNodeLayoutRef(rootGraphId, nodeId)
28 : },
29 : { immediate: true }
30 : )
31 :
32 8015 : const layout = computed(() => layoutRef.value?.value ?? null)
33 :
34 8015 : const position = shallowRef(layout.value?.position ?? { x: 0, y: 0 })
35 8015 : watch(
36 : [
37 : () => layout.value?.position.x ?? 0,
38 : () => layout.value?.position.y ?? 0,
39 : () => canvasStore.canvas
40 : ],
41 : ([x, y, canvas], _, onCleanup) => {
42 5946 : if (!canvas) {
43 0 : position.value = { x, y }
44 0 : return
45 : }
46 5946 : const stop = onCanvasFrame(canvas, 'present', () => {
47 589 : position.value = { x, y }
48 589 : stop()
49 : })
50 5946 : onCleanup(stop)
51 : },
52 : { flush: 'sync' }
53 : )
54 8015 : const size = computed(() => layout.value?.size ?? { width: 200, height: 100 })
55 :
56 8015 : const zIndex = computed(() => layout.value?.zIndex ?? 0)
57 :
58 0 : function moveNodeTo(position: Point) {
59 0 : const { rootGraphId } = canvasStore
60 0 : if (!rootGraphId) return
61 :
62 0 : mutations.moveNode(rootGraphId, nodeId, position)
63 : }
64 :
65 8015 : return {
66 : position,
67 : size,
68 : zIndex,
69 :
70 : moveNodeTo
71 : }
72 : }
|