Line data Source code
1 : import type { Size2D } from '@comfyorg/shared-frontend-utils/geometry'
2 : import type { ChannelData, GroupData, NodeBase, SceneNode } from './node'
3 :
4 : export interface DocGuide {
5 : axis: 'x' | 'y'
6 : pos: number
7 : }
8 :
9 : export interface Document extends Size2D {
10 : version: 2
11 : root: GroupData
12 : channels: ChannelData[]
13 : selectionId?: string
14 : guides?: DocGuide[]
15 : }
16 :
17 : export interface NodeLocation {
18 : node: SceneNode
19 : parent: GroupData
20 : index: number
21 : }
22 :
23 114 : export function walk(
24 : root: GroupData,
25 : fn: (node: SceneNode, parent: GroupData, depth: number) => boolean | void,
26 : depth = 0
27 : ): void {
28 114 : for (const child of root.children) {
29 : const recurse = fn(child, root, depth)
30 248 : if (recurse !== false && child.kind === 'group') {
31 0 : walk(child, fn, depth + 1)
32 : }
33 : }
34 : }
35 :
36 90 : export function findNode(root: GroupData, id: string): NodeLocation | null {
37 90 : let found: NodeLocation | null = null
38 90 : walk(root, (node, parent, _d) => {
39 204 : if (found) return false
40 204 : if (node.id === id) {
41 90 : found = { node, parent, index: parent.children.indexOf(node) }
42 90 : return false
43 : }
44 : })
45 90 : return found
46 : }
47 :
48 : export function parentOf(root: GroupData, id: string): GroupData | null {
49 : return findNode(root, id)?.parent ?? null
50 : }
51 :
52 24 : export function filterTopmost(
53 : root: GroupData,
54 : ids: Iterable<string>
55 : ): string[] {
56 24 : const want = new Set(ids)
57 24 : const out: string[] = []
58 24 : walk(root, (node) => {
59 44 : if (want.has(node.id)) {
60 20 : out.push(node.id)
61 20 : return false
62 : }
63 : })
64 24 : return out
65 : }
66 :
67 0 : export function flattenTree(root: GroupData): SceneNode[] {
68 0 : const out: SceneNode[] = []
69 0 : walk(root, (n) => {
70 0 : out.push(n)
71 : })
72 0 : return out
73 : }
74 :
75 : export function allContentRefs(
76 : doc: Document,
77 : refsOf: (n: NodeBase) => string[]
78 : ): Set<string> {
79 : const set = new Set<string>()
80 : walk(doc.root, (n) => {
81 : for (const id of refsOf(n)) set.add(id)
82 : })
83 : for (const ch of doc.channels) set.add(ch.contentId)
84 : return set
85 : }
|