From b419b53bd583c4f882af7e4be50174f28c501a9a Mon Sep 17 00:00:00 2001 From: Chenlei Hu Date: Wed, 28 Aug 2024 10:57:42 -0400 Subject: [PATCH] Add LGraphGroup.addNodes (#94) --- public/litegraph.d.ts | 3 ++- src/litegraph.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/public/litegraph.d.ts b/public/litegraph.d.ts index fefd89e0c..7d1143779 100644 --- a/public/litegraph.d.ts +++ b/public/litegraph.d.ts @@ -485,7 +485,7 @@ export declare class LGraph { * Adds a new node instance to this graph * @param node the instance of the node */ - add(node: LGraphNode, skip_compute_order?: boolean): void; + add(node: LGraphNode | LGraphGroup, skip_compute_order?: boolean): void; /** * Called when a new node is added * @param node the instance of the node @@ -1128,6 +1128,7 @@ export declare class LGraphGroup { recomputeInsideNodes(): void; isPointInside: LGraphNode["isPointInside"]; setDirtyCanvas: LGraphNode["setDirtyCanvas"]; + addNodes(nodes: LGraphNode[], padding?: number): void; } export declare class DragAndScale { diff --git a/src/litegraph.js b/src/litegraph.js index 6b56663cc..151ccb062 100755 --- a/src/litegraph.js +++ b/src/litegraph.js @@ -4930,6 +4930,48 @@ LGraphNode.prototype.executeAction = function(action) } }; + /** + * Add nodes to the group and adjust the group's position and size accordingly + * @param {LGraphNode[]} nodes - The nodes to add to the group + * @param {number} [padding=10] - The padding around the group + * @returns {void} + */ + LGraphGroup.prototype.addNodes = function(nodes, padding = 10) { + if (!this._nodes && nodes.length === 0) return; + + const allNodes = [...(this._nodes || []), ...nodes]; + + const bounds = allNodes.reduce((acc, node) => { + const [x, y] = node.pos; + const [width, height] = node.size; + const isReroute = node.type === "Reroute"; + const isCollapsed = node.flags?.collapsed; + + const top = y - (isReroute ? 0 : LiteGraph.NODE_TITLE_HEIGHT); + const bottom = isCollapsed ? top + LiteGraph.NODE_TITLE_HEIGHT : y + height; + const right = isCollapsed && node._collapsed_width ? x + Math.round(node._collapsed_width) : x + width; + + return { + left: Math.min(acc.left, x), + top: Math.min(acc.top, top), + right: Math.max(acc.right, right), + bottom: Math.max(acc.bottom, bottom) + }; + }, { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity }); + + const groupTitleHeight = Math.round(group.font_size * 1.4); + + group.pos = [ + bounds.left - padding, + bounds.top - padding - groupTitleHeight + ]; + + group.size = [ + bounds.right - bounds.left + padding * 2, + bounds.bottom - bounds.top + padding * 2 + groupTitleHeight + ]; + } + LGraphGroup.prototype.isPointInside = LGraphNode.prototype.isPointInside; LGraphGroup.prototype.setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas;