Line data Source code
1 : import type { LGraphCanvas, LGraphNode } from '@/lib/litegraph/src/litegraph'
2 : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
3 : import { withNodeAddSource } from '@/platform/telemetry/nodeAdded/nodeAddSource'
4 :
5 : /**
6 : * Deserialises nodes and links using a modified version of the old Litegraph (copy &) paste function
7 : * @param data The serialised nodes and links to create
8 : * @param canvas The canvas to create the serialised items in
9 : */
10 3 : export function deserialiseAndCreate(data: string, canvas: LGraphCanvas): void {
11 3 : if (!data) return
12 :
13 3 : const { graph, graph_mouse } = canvas
14 3 : if (!graph) return
15 3 : canvas.emitBeforeChange()
16 3 : try {
17 3 : graph.beforeChange()
18 :
19 3 : const deserialised = JSON.parse(data)
20 :
21 : // Find the top left point of the boundary of all pasted nodes
22 3 : const topLeft = [Infinity, Infinity]
23 3 : for (const { pos } of deserialised.nodes) {
24 16 : if (topLeft[0] > pos[0]) topLeft[0] = pos[0]
25 16 : if (topLeft[1] > pos[1]) topLeft[1] = pos[1]
26 : }
27 :
28 : // Silent default instead of throw
29 3 : if (!Number.isFinite(topLeft[0]) || !Number.isFinite(topLeft[1])) {
30 0 : topLeft[0] = graph_mouse[0]
31 0 : topLeft[1] = graph_mouse[1]
32 : }
33 :
34 : // Create nodes
35 3 : const nodes: LGraphNode[] = []
36 3 : for (const info of deserialised.nodes) {
37 16 : const node = LiteGraph.createNode(info.type)
38 16 : if (!node) continue
39 :
40 16 : node.configure(info)
41 :
42 : // Paste to the bottom right of pointer
43 16 : node.pos = [
44 : node.pos[0] + graph_mouse[0] - topLeft[0],
45 : node.pos[1] + graph_mouse[1] - topLeft[1]
46 : ]
47 :
48 16 : withNodeAddSource('paste', () => graph.add(node, true))
49 16 : nodes.push(node)
50 : }
51 :
52 : // Create links
53 3 : for (const info of deserialised.links) {
54 18 : const relativeId = info[0]
55 18 : const outNode = relativeId != null ? nodes[relativeId] : undefined
56 :
57 18 : const inNode = nodes[info[2]]
58 18 : if (outNode) outNode.connect(info[1], inNode, info[3])
59 0 : else console.warn('Warning, nodes missing on pasting')
60 : }
61 :
62 3 : canvas.selectNodes(nodes)
63 :
64 3 : graph.afterChange()
65 : } finally {
66 3 : canvas.emitAfterChange()
67 : }
68 : }
|