const zeroUuid = "00000000-0000-0000-0000-000000000000";
const randomStorage = new Uint32Array(31);
function createUuidv4() {
if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
if (typeof crypto?.getRandomValues === "function") {
const random = crypto.getRandomValues(randomStorage);
let i = 0;
return "10000000-1000-4000-8000-100000000000".replaceAll(/[018]/g, (a) => (Number(a) ^ random[i++] * 3725290298461914e-24 >> Number(a) * 0.25).toString(16));
}
return "10000000-1000-4000-8000-100000000000".replaceAll(/[018]/g, (a) => (Number(a) ^ Math.random() * 16 >> Number(a) * 0.25).toString(16));
}
class CustomEventTarget extends EventTarget {
dispatch(type, detail) {
const event = new CustomEvent(type, { detail, cancelable: true });
return super.dispatchEvent(event);
}
addEventListener(type, listener, options) {
super.addEventListener(type, listener, options);
}
removeEventListener(type, listener, options) {
super.removeEventListener(type, listener, options);
}
/** @deprecated Use {@link dispatch}. */
dispatchEvent(event) {
return super.dispatchEvent(event);
}
}
class LLink {
/** Link ID */
id;
parentId;
type;
/** Output node ID */
origin_id;
/** Output slot index */
origin_slot;
/** Input node ID */
target_id;
/** Input slot index */
target_slot;
data;
_data;
/** Centre point of the link, calculated during render only - can be inaccurate */
_pos;
/** @todo Clean up - never implemented in comfy. */
_last_time;
/** The last canvas 2D path that was used to render this link */
path;
/** @inheritdoc */
_centreAngle;
/** @inheritdoc */
_dragging;
#color;
/** Custom colour for this link only */
get color() {
return this.#color;
}
set color(value) {
this.#color = value === "" ? null : value;
}
get isFloatingOutput() {
return this.origin_id === -1 && this.origin_slot === -1;
}
get isFloatingInput() {
return this.target_id === -1 && this.target_slot === -1;
}
get isFloating() {
return this.isFloatingOutput || this.isFloatingInput;
}
constructor(id, type, origin_id, origin_slot, target_id, target_slot, parentId) {
this.id = id;
this.type = type;
this.origin_id = origin_id;
this.origin_slot = origin_slot;
this.target_id = target_id;
this.target_slot = target_slot;
this.parentId = parentId;
this._data = null;
this._pos = new Float32Array(2);
}
/** @deprecated Use {@link LLink.create} */
static createFromArray(data) {
return new LLink(data[0], data[5], data[1], data[2], data[3], data[4]);
}
/**
* LLink static factory: creates a new LLink from the provided data.
* @param data Serialised LLink data to create the link from
* @returns A new LLink
*/
static create(data) {
return new LLink(
data.id,
data.type,
data.origin_id,
data.origin_slot,
data.target_id,
data.target_slot,
data.parentId
);
}
/**
* Gets all reroutes from the output slot to this segment. If this segment is a reroute, it will not be included.
* @returns An ordered array of all reroutes from the node output to
* this reroute or the reroute before it. Otherwise, an empty array.
*/
static getReroutes(network, linkSegment) {
if (!linkSegment.parentId) return [];
return network.reroutes.get(linkSegment.parentId)?.getReroutes() ?? [];
}
static getFirstReroute(network, linkSegment) {
return LLink.getReroutes(network, linkSegment).at(0);
}
/**
* Finds the reroute in the chain after the provided reroute ID.
* @param network The network this link belongs to
* @param linkSegment The starting point of the search (input side).
* Typically the LLink object itself, but can be any link segment.
* @param rerouteId The matching reroute will have this set as its {@link parentId}.
* @returns The reroute that was found, `undefined` if no reroute was found, or `null` if an infinite loop was detected.
*/
static findNextReroute(network, linkSegment, rerouteId) {
if (!linkSegment.parentId) return;
return network.reroutes.get(linkSegment.parentId)?.findNextReroute(rerouteId);
}
/**
* Gets the origin node of a link.
* @param network The network to search
* @param linkId The ID of the link to get the origin node of
* @returns The origin node of the link, or `undefined` if the link is not found or the origin node is not found
*/
static getOriginNode(network, linkId) {
const id = network.links.get(linkId)?.origin_id;
return network.getNodeById(id) ?? void 0;
}
/**
* Gets the target node of a link.
* @param network The network to search
* @param linkId The ID of the link to get the target node of
* @returns The target node of the link, or `undefined` if the link is not found or the target node is not found
*/
static getTargetNode(network, linkId) {
const id = network.links.get(linkId)?.target_id;
return network.getNodeById(id) ?? void 0;
}
/**
* Resolves a link ID to the link, node, and slot objects.
* @param linkId The {@link id} of the link to resolve
* @param network The link network to search
* @returns An object containing the input and output nodes, as well as the input and output slots.
* @remarks This method is heavier than others; it will always resolve all objects.
* Whilst the performance difference should in most cases be negligible,
* it is recommended to use simpler methods where appropriate.
*/
static resolve(linkId, network) {
return network.getLink(linkId)?.resolve(network);
}
/**
* Resolves a list of link IDs to the link, node, and slot objects.
* Discards invalid link IDs.
* @param linkIds An iterable of link {@link id}s to resolve
* @param network The link network to search
* @returns An array of resolved connections. If a link is not found, it is not included in the array.
* @see {@link LLink.resolve}
*/
static resolveMany(linkIds, network) {
const resolved = [];
for (const id of linkIds) {
const r = network.getLink(id)?.resolve(network);
if (r) resolved.push(r);
}
return resolved;
}
/**
* Resolves the primitive ID values stored in the link to the referenced objects.
* @param network The link network to search
* @returns An object containing the input and output nodes, as well as the input and output slots.
* @remarks This method is heavier than others; it will always resolve all objects.
* Whilst the performance difference should in most cases be negligible,
* it is recommended to use simpler methods where appropriate.
*/
resolve(network) {
const inputNode = this.target_id === -1 ? void 0 : network.getNodeById(this.target_id) ?? void 0;
const outputNode = this.origin_id === -1 ? void 0 : network.getNodeById(this.origin_id) ?? void 0;
const input = inputNode?.inputs[this.target_slot];
const output = outputNode?.outputs[this.origin_slot];
return { inputNode, outputNode, input, output, link: this };
}
configure(o) {
if (Array.isArray(o)) {
this.id = o[0];
this.origin_id = o[1];
this.origin_slot = o[2];
this.target_id = o[3];
this.target_slot = o[4];
this.type = o[5];
} else {
this.id = o.id;
this.type = o.type;
this.origin_id = o.origin_id;
this.origin_slot = o.origin_slot;
this.target_id = o.target_id;
this.target_slot = o.target_slot;
this.parentId = o.parentId;
}
}
/**
* Checks if the specified node id and output index are this link's origin (output side).
* @param nodeId ID of the node to check
* @param outputIndex The array index of the node output
* @returns `true` if the origin matches, otherwise `false`.
*/
hasOrigin(nodeId, outputIndex) {
return this.origin_id === nodeId && this.origin_slot === outputIndex;
}
/**
* Checks if the specified node id and input index are this link's target (input side).
* @param nodeId ID of the node to check
* @param inputIndex The array index of the node input
* @returns `true` if the target matches, otherwise `false`.
*/
hasTarget(nodeId, inputIndex) {
return this.target_id === nodeId && this.target_slot === inputIndex;
}
/**
* Creates a floating link from this link.
* @param slotType The side of the link that is still connected
* @param parentId The parent reroute ID of the link
* @returns A new LLink that is floating
*/
toFloating(slotType, parentId) {
const exported = this.asSerialisable();
exported.id = -1;
exported.parentId = parentId;
if (slotType === "input") {
exported.origin_id = -1;
exported.origin_slot = -1;
} else {
exported.target_id = -1;
exported.target_slot = -1;
}
return LLink.create(exported);
}
/**
* Disconnects a link and removes it from the graph, cleaning up any reroutes that are no longer used
* @param network The container (LGraph) where reroutes should be updated
* @param keepReroutes If `undefined`, reroutes will be automatically removed if no links remain.
* If `input` or `output`, reroutes will not be automatically removed, and retain a connection to the input or output, respectively.
*/
disconnect(network, keepReroutes) {
const reroutes = LLink.getReroutes(network, this);
const lastReroute = reroutes.at(-1);
const outputFloating = keepReroutes === "output" && lastReroute?.linkIds.size === 1 && lastReroute.floatingLinkIds.size === 0;
if (outputFloating || keepReroutes === "input" && lastReroute) {
const newLink = LLink.create(this);
newLink.id = -1;
if (keepReroutes === "input") {
newLink.origin_id = -1;
newLink.origin_slot = -1;
lastReroute.floating = { slotType: "input" };
} else {
newLink.target_id = -1;
newLink.target_slot = -1;
lastReroute.floating = { slotType: "output" };
}
network.addFloatingLink(newLink);
}
for (const reroute of reroutes) {
reroute.linkIds.delete(this.id);
if (!keepReroutes && !reroute.totalLinks) {
network.reroutes.delete(reroute.id);
}
}
network.links.delete(this.id);
}
/**
* @deprecated Prefer {@link LLink.asSerialisable} (returns an object, not an array)
* @returns An array representing this LLink
*/
serialize() {
return [
this.id,
this.origin_id,
this.origin_slot,
this.target_id,
this.target_slot,
this.type
];
}
asSerialisable() {
const copy = {
id: this.id,
origin_id: this.origin_id,
origin_slot: this.origin_slot,
target_id: this.target_id,
target_slot: this.target_slot,
type: this.type
};
if (this.parentId) copy.parentId = this.parentId;
return copy;
}
}
var NodeSlotType = /* @__PURE__ */ ((NodeSlotType2) => {
NodeSlotType2[NodeSlotType2["INPUT"] = 1] = "INPUT";
NodeSlotType2[NodeSlotType2["OUTPUT"] = 2] = "OUTPUT";
return NodeSlotType2;
})(NodeSlotType || {});
var RenderShape = /* @__PURE__ */ ((RenderShape2) => {
RenderShape2[RenderShape2["BOX"] = 1] = "BOX";
RenderShape2[RenderShape2["ROUND"] = 2] = "ROUND";
RenderShape2[RenderShape2["CIRCLE"] = 3] = "CIRCLE";
RenderShape2[RenderShape2["CARD"] = 4] = "CARD";
RenderShape2[RenderShape2["ARROW"] = 5] = "ARROW";
RenderShape2[RenderShape2["GRID"] = 6] = "GRID";
RenderShape2[RenderShape2["HollowCircle"] = 7] = "HollowCircle";
return RenderShape2;
})(RenderShape || {});
var CanvasItem = /* @__PURE__ */ ((CanvasItem2) => {
CanvasItem2[CanvasItem2["Nothing"] = 0] = "Nothing";
CanvasItem2[CanvasItem2["Node"] = 1] = "Node";
CanvasItem2[CanvasItem2["Group"] = 2] = "Group";
CanvasItem2[CanvasItem2["Reroute"] = 4] = "Reroute";
CanvasItem2[CanvasItem2["Link"] = 8] = "Link";
CanvasItem2[CanvasItem2["RerouteSlot"] = 32] = "RerouteSlot";
return CanvasItem2;
})(CanvasItem || {});
var LinkDirection = /* @__PURE__ */ ((LinkDirection2) => {
LinkDirection2[LinkDirection2["NONE"] = 0] = "NONE";
LinkDirection2[LinkDirection2["UP"] = 1] = "UP";
LinkDirection2[LinkDirection2["DOWN"] = 2] = "DOWN";
LinkDirection2[LinkDirection2["LEFT"] = 3] = "LEFT";
LinkDirection2[LinkDirection2["RIGHT"] = 4] = "RIGHT";
LinkDirection2[LinkDirection2["CENTER"] = 5] = "CENTER";
return LinkDirection2;
})(LinkDirection || {});
var LinkRenderType = /* @__PURE__ */ ((LinkRenderType2) => {
LinkRenderType2[LinkRenderType2["HIDDEN_LINK"] = -1] = "HIDDEN_LINK";
LinkRenderType2[LinkRenderType2["STRAIGHT_LINK"] = 0] = "STRAIGHT_LINK";
LinkRenderType2[LinkRenderType2["LINEAR_LINK"] = 1] = "LINEAR_LINK";
LinkRenderType2[LinkRenderType2["SPLINE_LINK"] = 2] = "SPLINE_LINK";
return LinkRenderType2;
})(LinkRenderType || {});
var LinkMarkerShape = /* @__PURE__ */ ((LinkMarkerShape2) => {
LinkMarkerShape2[LinkMarkerShape2["None"] = 0] = "None";
LinkMarkerShape2[LinkMarkerShape2["Circle"] = 1] = "Circle";
LinkMarkerShape2[LinkMarkerShape2["Arrow"] = 2] = "Arrow";
return LinkMarkerShape2;
})(LinkMarkerShape || {});
var TitleMode = /* @__PURE__ */ ((TitleMode2) => {
TitleMode2[TitleMode2["NORMAL_TITLE"] = 0] = "NORMAL_TITLE";
TitleMode2[TitleMode2["NO_TITLE"] = 1] = "NO_TITLE";
TitleMode2[TitleMode2["TRANSPARENT_TITLE"] = 2] = "TRANSPARENT_TITLE";
TitleMode2[TitleMode2["AUTOHIDE_TITLE"] = 3] = "AUTOHIDE_TITLE";
return TitleMode2;
})(TitleMode || {});
var LGraphEventMode = /* @__PURE__ */ ((LGraphEventMode2) => {
LGraphEventMode2[LGraphEventMode2["ALWAYS"] = 0] = "ALWAYS";
LGraphEventMode2[LGraphEventMode2["ON_EVENT"] = 1] = "ON_EVENT";
LGraphEventMode2[LGraphEventMode2["NEVER"] = 2] = "NEVER";
LGraphEventMode2[LGraphEventMode2["ON_TRIGGER"] = 3] = "ON_TRIGGER";
LGraphEventMode2[LGraphEventMode2["BYPASS"] = 4] = "BYPASS";
return LGraphEventMode2;
})(LGraphEventMode || {});
var EaseFunction = /* @__PURE__ */ ((EaseFunction2) => {
EaseFunction2["LINEAR"] = "linear";
EaseFunction2["EASE_IN_QUAD"] = "easeInQuad";
EaseFunction2["EASE_OUT_QUAD"] = "easeOutQuad";
EaseFunction2["EASE_IN_OUT_QUAD"] = "easeInOutQuad";
return EaseFunction2;
})(EaseFunction || {});
class FloatingRenderLink {
constructor(network, link, toType, fromReroute, dragDirection = LinkDirection.CENTER) {
this.network = network;
this.link = link;
this.toType = toType;
this.fromReroute = fromReroute;
this.dragDirection = dragDirection;
const {
origin_id: outputNodeId,
target_id: inputNodeId,
origin_slot: outputIndex,
target_slot: inputIndex
} = link;
if (outputNodeId !== -1) {
const outputNode = network.getNodeById(outputNodeId) ?? void 0;
if (!outputNode) throw new Error(`Creating DraggingRenderLink for link [${link.id}] failed: Output node [${outputNodeId}] not found.`);
const outputSlot = outputNode?.outputs.at(outputIndex);
if (!outputSlot) throw new Error(`Creating DraggingRenderLink for link [${link.id}] failed: Output slot [${outputIndex}] not found.`);
this.outputNodeId = outputNodeId;
this.outputNode = outputNode;
this.outputSlot = outputSlot;
this.outputIndex = outputIndex;
this.outputPos = outputNode.getOutputPos(outputIndex);
this.node = outputNode;
this.fromSlot = outputSlot;
this.fromPos = fromReroute?.pos ?? this.outputPos;
this.fromDirection = LinkDirection.LEFT;
this.dragDirection = LinkDirection.RIGHT;
this.fromSlotIndex = outputIndex;
} else {
const inputNode = network.getNodeById(inputNodeId) ?? void 0;
if (!inputNode) throw new Error(`Creating DraggingRenderLink for link [${link.id}] failed: Input node [${inputNodeId}] not found.`);
const inputSlot = inputNode?.inputs.at(inputIndex);
if (!inputSlot) throw new Error(`Creating DraggingRenderLink for link [${link.id}] failed: Input slot [${inputIndex}] not found.`);
this.inputNodeId = inputNodeId;
this.inputNode = inputNode;
this.inputSlot = inputSlot;
this.inputIndex = inputIndex;
this.inputPos = inputNode.getInputPos(inputIndex);
this.node = inputNode;
this.fromSlot = inputSlot;
this.fromDirection = LinkDirection.RIGHT;
this.fromSlotIndex = inputIndex;
}
this.fromPos = fromReroute.pos;
}
node;
fromSlot;
fromPos;
fromDirection;
fromSlotIndex;
outputNodeId = -1;
outputNode;
outputSlot;
outputIndex = -1;
outputPos;
inputNodeId = -1;
inputNode;
inputSlot;
inputIndex = -1;
inputPos;
canConnectToInput() {
return this.toType === "input";
}
canConnectToOutput() {
return this.toType === "output";
}
canConnectToReroute(reroute) {
if (this.toType === "input") {
if (reroute.origin_id === this.inputNode?.id) return false;
} else {
if (reroute.origin_id === this.outputNode?.id) return false;
}
return true;
}
connectToInput(node2, input, _events) {
const floatingLink = this.link;
floatingLink.target_id = node2.id;
floatingLink.target_slot = node2.inputs.indexOf(input);
node2.disconnectInput(node2.inputs.indexOf(input));
this.fromSlot._floatingLinks?.delete(floatingLink);
input._floatingLinks ??= /* @__PURE__ */ new Set();
input._floatingLinks.add(floatingLink);
}
connectToOutput(node2, output, _events) {
const floatingLink = this.link;
floatingLink.origin_id = node2.id;
floatingLink.origin_slot = node2.outputs.indexOf(output);
this.fromSlot._floatingLinks?.delete(floatingLink);
output._floatingLinks ??= /* @__PURE__ */ new Set();
output._floatingLinks.add(floatingLink);
}
connectToRerouteInput(reroute, { node: inputNode, input }, events) {
const floatingLink = this.link;
floatingLink.target_id = inputNode.id;
floatingLink.target_slot = inputNode.inputs.indexOf(input);
this.fromSlot._floatingLinks?.delete(floatingLink);
input._floatingLinks ??= /* @__PURE__ */ new Set();
input._floatingLinks.add(floatingLink);
events.dispatch("input-moved", this);
}
connectToRerouteOutput(reroute, outputNode, output, events) {
const floatingLink = this.link;
floatingLink.origin_id = outputNode.id;
floatingLink.origin_slot = outputNode.outputs.indexOf(output);
this.fromSlot._floatingLinks?.delete(floatingLink);
output._floatingLinks ??= /* @__PURE__ */ new Set();
output._floatingLinks.add(floatingLink);
events.dispatch("output-moved", this);
}
}
class MovingLinkBase {
constructor(network, link, toType, fromReroute, dragDirection = LinkDirection.CENTER) {
this.network = network;
this.link = link;
this.toType = toType;
this.fromReroute = fromReroute;
this.dragDirection = dragDirection;
const {
origin_id: outputNodeId,
target_id: inputNodeId,
origin_slot: outputIndex,
target_slot: inputIndex
} = link;
const outputNode = network.getNodeById(outputNodeId) ?? void 0;
if (!outputNode) throw new Error(`Creating MovingRenderLink for link [${link.id}] failed: Output node [${outputNodeId}] not found.`);
const outputSlot = outputNode.outputs.at(outputIndex);
if (!outputSlot) throw new Error(`Creating MovingRenderLink for link [${link.id}] failed: Output slot [${outputIndex}] not found.`);
this.outputNodeId = outputNodeId;
this.outputNode = outputNode;
this.outputSlot = outputSlot;
this.outputIndex = outputIndex;
this.outputPos = outputNode.getOutputPos(outputIndex);
const inputNode = network.getNodeById(inputNodeId) ?? void 0;
if (!inputNode) throw new Error(`Creating DraggingRenderLink for link [${link.id}] failed: Input node [${inputNodeId}] not found.`);
const inputSlot = inputNode.inputs.at(inputIndex);
if (!inputSlot) throw new Error(`Creating DraggingRenderLink for link [${link.id}] failed: Input slot [${inputIndex}] not found.`);
this.inputNodeId = inputNodeId;
this.inputNode = inputNode;
this.inputSlot = inputSlot;
this.inputIndex = inputIndex;
this.inputPos = inputNode.getInputPos(inputIndex);
}
outputNodeId;
outputNode;
outputSlot;
outputIndex;
outputPos;
inputNodeId;
inputNode;
inputSlot;
inputIndex;
inputPos;
}
class MovingInputLink extends MovingLinkBase {
toType = "input";
node;
fromSlot;
fromPos;
fromDirection;
fromSlotIndex;
constructor(network, link, fromReroute, dragDirection = LinkDirection.CENTER) {
super(network, link, "input", fromReroute, dragDirection);
this.node = this.outputNode;
this.fromSlot = this.outputSlot;
this.fromPos = fromReroute?.pos ?? this.outputPos;
this.fromDirection = LinkDirection.NONE;
this.fromSlotIndex = this.outputIndex;
}
canConnectToInput(inputNode, input) {
return this.node.canConnectTo(inputNode, input, this.outputSlot);
}
canConnectToOutput() {
return false;
}
canConnectToReroute(reroute) {
return reroute.origin_id !== this.inputNode.id;
}
connectToInput(inputNode, input, events) {
if (input === this.inputSlot) return;
this.inputNode.disconnectInput(this.inputIndex, true);
const link = this.outputNode.connectSlots(this.outputSlot, inputNode, input, this.fromReroute?.id);
if (link) events.dispatch("input-moved", this);
return link;
}
connectToOutput() {
throw new Error("MovingInputLink cannot connect to an output.");
}
connectToRerouteInput(reroute, { node: inputNode, input, link: existingLink }, events, originalReroutes) {
const { outputNode, outputSlot, fromReroute } = this;
for (const reroute2 of originalReroutes) {
if (reroute2.id === this.link.parentId) break;
if (reroute2.totalLinks === 1) reroute2.remove();
}
reroute.parentId = fromReroute?.id;
const newLink = outputNode.connectSlots(outputSlot, inputNode, input, existingLink.parentId);
if (newLink) events.dispatch("input-moved", this);
}
connectToRerouteOutput() {
throw new Error("MovingInputLink cannot connect to an output.");
}
disconnect() {
return this.inputNode.disconnectInput(this.inputIndex, true);
}
}
class MovingOutputLink extends MovingLinkBase {
toType = "output";
node;
fromSlot;
fromPos;
fromDirection;
fromSlotIndex;
constructor(network, link, fromReroute, dragDirection = LinkDirection.CENTER) {
super(network, link, "output", fromReroute, dragDirection);
this.node = this.inputNode;
this.fromSlot = this.inputSlot;
this.fromPos = fromReroute?.pos ?? this.inputPos;
this.fromDirection = LinkDirection.LEFT;
this.fromSlotIndex = this.inputIndex;
}
canConnectToInput() {
return false;
}
canConnectToOutput(outputNode, output) {
return outputNode.canConnectTo(this.node, this.inputSlot, output);
}
canConnectToReroute(reroute) {
return reroute.origin_id !== this.outputNode.id;
}
connectToInput() {
throw new Error("MovingOutputLink cannot connect to an input.");
}
connectToOutput(outputNode, output, events) {
if (output === this.outputSlot) return;
const link = outputNode.connectSlots(output, this.inputNode, this.inputSlot, this.link.parentId);
if (link) events.dispatch("output-moved", this);
return link;
}
connectToRerouteInput() {
throw new Error("MovingOutputLink cannot connect to an input.");
}
connectToRerouteOutput(reroute, outputNode, output, events) {
const { inputNode, inputSlot, fromReroute } = this;
const floatingTerminus = reroute?.floating?.slotType === "output";
if (fromReroute) {
fromReroute.parentId = reroute.id;
} else {
this.link.parentId = reroute.id;
}
outputNode.connectSlots(output, inputNode, inputSlot, this.link.parentId);
if (floatingTerminus) reroute.removeAllFloatingLinks();
events.dispatch("output-moved", this);
}
disconnect() {
return this.outputNode.disconnectOutput(this.outputIndex, this.inputNode);
}
}
class ToInputRenderLink {
constructor(network, node2, fromSlot, fromReroute, dragDirection = LinkDirection.CENTER) {
this.network = network;
this.node = node2;
this.fromSlot = fromSlot;
this.fromReroute = fromReroute;
this.dragDirection = dragDirection;
const outputIndex = node2.outputs.indexOf(fromSlot);
if (outputIndex === -1) throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);
this.fromSlotIndex = outputIndex;
this.fromPos = fromReroute ? fromReroute.pos : this.node.getOutputPos(outputIndex);
}
toType = "input";
fromPos;
fromSlotIndex;
fromDirection = LinkDirection.RIGHT;
canConnectToInput(inputNode, input) {
return this.node.canConnectTo(inputNode, input, this.fromSlot);
}
canConnectToOutput() {
return false;
}
connectToInput(node2, input, events) {
const { node: outputNode, fromSlot, fromReroute } = this;
if (node2 === outputNode) return;
const newLink = outputNode.connectSlots(fromSlot, node2, input, fromReroute?.id);
events.dispatch("link-created", newLink);
}
connectToRerouteInput(reroute, {
node: inputNode,
input,
link
}, events, originalReroutes) {
const { node: outputNode, fromSlot, fromReroute } = this;
const floatingTerminus = fromReroute?.floating?.slotType === "output";
reroute.parentId = fromReroute?.id;
const newLink = outputNode.connectSlots(fromSlot, inputNode, input, link.parentId);
if (floatingTerminus) fromReroute.removeAllFloatingLinks();
for (const reroute2 of originalReroutes) {
if (reroute2.id === fromReroute?.id) break;
reroute2.removeLink(link);
if (reroute2.totalLinks === 0) {
if (link.isFloating) {
reroute2.remove();
} else {
const cl = link.toFloating("output", reroute2.id);
this.network.addFloatingLink(cl);
reroute2.floating = { slotType: "output" };
}
}
}
events.dispatch("link-created", newLink);
}
connectToOutput() {
throw new Error("ToInputRenderLink cannot connect to an output.");
}
connectToRerouteOutput() {
throw new Error("ToInputRenderLink cannot connect to an output.");
}
}
class ToOutputRenderLink {
constructor(network, node2, fromSlot, fromReroute, dragDirection = LinkDirection.CENTER) {
this.network = network;
this.node = node2;
this.fromSlot = fromSlot;
this.fromReroute = fromReroute;
this.dragDirection = dragDirection;
const inputIndex = node2.inputs.indexOf(fromSlot);
if (inputIndex === -1) throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);
this.fromSlotIndex = inputIndex;
this.fromPos = fromReroute ? fromReroute.pos : this.node.getInputPos(inputIndex);
}
toType = "output";
fromPos;
fromSlotIndex;
fromDirection = LinkDirection.LEFT;
canConnectToInput() {
return false;
}
canConnectToOutput(outputNode, output) {
return this.node.canConnectTo(outputNode, this.fromSlot, output);
}
canConnectToReroute(reroute) {
if (reroute.origin_id === this.node.id) return false;
return true;
}
connectToOutput(node2, output, events) {
const { node: inputNode, fromSlot, fromReroute } = this;
if (!inputNode) return;
const newLink = node2.connectSlots(output, inputNode, fromSlot, fromReroute?.id);
events.dispatch("link-created", newLink);
}
connectToRerouteOutput(reroute, outputNode, output, events) {
const { node: inputNode, fromSlot } = this;
const newLink = outputNode.connectSlots(output, inputNode, fromSlot, reroute?.id);
events.dispatch("link-created", newLink);
}
connectToInput() {
throw new Error("ToOutputRenderLink cannot connect to an input.");
}
connectToRerouteInput() {
throw new Error("ToOutputRenderLink cannot connect to an input.");
}
}
class ToOutputFromRerouteLink extends ToOutputRenderLink {
constructor(network, node2, fromSlot, fromReroute, linkConnector) {
super(network, node2, fromSlot, fromReroute);
this.fromReroute = fromReroute;
this.linkConnector = linkConnector;
}
canConnectToReroute() {
return false;
}
connectToOutput(node2, output) {
const nuRenderLink = new ToInputRenderLink(this.network, node2, output);
this.linkConnector._connectOutputToReroute(this.fromReroute, nuRenderLink);
}
}
class LinkConnector {
/**
* Link connection state POJO. Source of truth for state of link drag operations.
*
* Can be replaced or proxied to allow notifications.
* Is always dereferenced at the start of an operation.
*/
state = {
connectingTo: void 0,
multi: false,
draggingExistingLinks: false,
snapLinksPos: void 0
};
events = new CustomEventTarget();
/** Contains information for rendering purposes only. */
renderLinks = [];
/** Existing links that are being moved **to** a new input slot. */
inputLinks = [];
/** Existing links that are being moved **to** a new output slot. */
outputLinks = [];
/** Existing floating links that are being moved to a new slot. */
floatingLinks = [];
hiddenReroutes = /* @__PURE__ */ new Set();
/** The widget beneath the pointer, if it is a valid connection target. */
overWidget;
/** The type (returned by downstream callback) for {@link overWidget} */
overWidgetType;
/** The reroute beneath the pointer, if it is a valid connection target. */
overReroute;
#setConnectingLinks;
constructor(setConnectingLinks) {
this.#setConnectingLinks = setConnectingLinks;
}
get isConnecting() {
return this.state.connectingTo !== void 0;
}
get draggingExistingLinks() {
return this.state.draggingExistingLinks;
}
/** Drag an existing link to a different input. */
moveInputLink(network, input) {
if (this.isConnecting) throw new Error("Already dragging links.");
const { state, inputLinks, renderLinks } = this;
const linkId = input.link;
if (linkId == null) {
const floatingLink = input._floatingLinks?.values().next().value;
if (floatingLink?.parentId == null) return;
try {
const reroute = network.reroutes.get(floatingLink.parentId);
if (!reroute) throw new Error(`Invalid reroute id: [${floatingLink.parentId}] for floating link id: [${floatingLink.id}].`);
const renderLink = new FloatingRenderLink(network, floatingLink, "input", reroute);
const mayContinue = this.events.dispatch("before-move-input", renderLink);
if (mayContinue === false) return;
renderLinks.push(renderLink);
} catch (error) {
console.warn(`Could not create render link for link id: [${floatingLink.id}].`, floatingLink, error);
}
floatingLink._dragging = true;
this.floatingLinks.push(floatingLink);
} else {
const link = network.links.get(linkId);
if (!link) return;
try {
const reroute = network.getReroute(link.parentId);
const renderLink = new MovingInputLink(network, link, reroute);
const mayContinue = this.events.dispatch("before-move-input", renderLink);
if (mayContinue === false) return;
renderLinks.push(renderLink);
this.listenUntilReset("input-moved", (e2) => {
e2.detail.link.disconnect(network, "output");
});
} catch (error) {
console.warn(`Could not create render link for link id: [${link.id}].`, link, error);
return;
}
link._dragging = true;
inputLinks.push(link);
}
state.connectingTo = "input";
state.draggingExistingLinks = true;
this.#setLegacyLinks(false);
}
/** Drag all links from an output to a new output. */
moveOutputLink(network, output) {
if (this.isConnecting) throw new Error("Already dragging links.");
const { state, renderLinks } = this;
if (output._floatingLinks?.size) {
for (const floatingLink of output._floatingLinks.values()) {
try {
const reroute = LLink.getFirstReroute(network, floatingLink);
if (!reroute) throw new Error(`Invalid reroute id: [${floatingLink.parentId}] for floating link id: [${floatingLink.id}].`);
const renderLink = new FloatingRenderLink(network, floatingLink, "output", reroute);
const mayContinue = this.events.dispatch("before-move-output", renderLink);
if (mayContinue === false) continue;
renderLinks.push(renderLink);
this.floatingLinks.push(floatingLink);
} catch (error) {
console.warn(`Could not create render link for link id: [${floatingLink.id}].`, floatingLink, error);
}
}
}
if (output.links?.length) {
for (const linkId of output.links) {
const link = network.links.get(linkId);
if (!link) continue;
const firstReroute = LLink.getFirstReroute(network, link);
if (firstReroute) {
firstReroute._dragging = true;
this.hiddenReroutes.add(firstReroute);
} else {
link._dragging = true;
}
this.outputLinks.push(link);
try {
const renderLink = new MovingOutputLink(network, link, firstReroute, LinkDirection.RIGHT);
const mayContinue = this.events.dispatch("before-move-output", renderLink);
if (mayContinue === false) continue;
renderLinks.push(renderLink);
} catch (error) {
console.warn(`Could not create render link for link id: [${link.id}].`, link, error);
continue;
}
}
}
if (renderLinks.length === 0) return;
state.draggingExistingLinks = true;
state.multi = true;
state.connectingTo = "output";
this.#setLegacyLinks(true);
}
/**
* Drags a new link from an output slot to an input slot.
* @param network The network that the link being connected belongs to
* @param node The node the link is being dragged from
* @param output The output slot that the link is being dragged from
*/
dragNewFromOutput(network, node2, output, fromReroute) {
if (this.isConnecting) throw new Error("Already dragging links.");
const { state } = this;
const renderLink = new ToInputRenderLink(network, node2, output, fromReroute);
this.renderLinks.push(renderLink);
state.connectingTo = "input";
this.#setLegacyLinks(false);
}
/**
* Drags a new link from an input slot to an output slot.
* @param network The network that the link being connected belongs to
* @param node The node the link is being dragged from
* @param input The input slot that the link is being dragged from
*/
dragNewFromInput(network, node2, input, fromReroute) {
if (this.isConnecting) throw new Error("Already dragging links.");
const { state } = this;
const renderLink = new ToOutputRenderLink(network, node2, input, fromReroute);
this.renderLinks.push(renderLink);
state.connectingTo = "output";
this.#setLegacyLinks(true);
}
/**
* Drags a new link from a reroute to an input slot.
* @param network The network that the link being connected belongs to
* @param reroute The reroute that the link is being dragged from
*/
dragFromReroute(network, reroute) {
if (this.isConnecting) throw new Error("Already dragging links.");
const link = reroute.firstLink ?? reroute.firstFloatingLink;
if (!link) {
console.warn("No link found for reroute.");
return;
}
const outputNode = network.getNodeById(link.origin_id);
if (!outputNode) {
console.warn("No output node found for link.", link);
return;
}
const outputSlot = outputNode.outputs.at(link.origin_slot);
if (!outputSlot) {
console.warn("No output slot found for link.", link);
return;
}
const renderLink = new ToInputRenderLink(network, outputNode, outputSlot, reroute);
renderLink.fromDirection = LinkDirection.NONE;
this.renderLinks.push(renderLink);
this.state.connectingTo = "input";
this.#setLegacyLinks(false);
}
/**
* Drags a new link from a reroute to an output slot.
* @param network The network that the link being connected belongs to
* @param reroute The reroute that the link is being dragged from
*/
dragFromRerouteToOutput(network, reroute) {
if (this.isConnecting) throw new Error("Already dragging links.");
const link = reroute.firstLink ?? reroute.firstFloatingLink;
if (!link) {
console.warn("No link found for reroute.");
return;
}
const inputNode = network.getNodeById(link.target_id);
if (!inputNode) {
console.warn("No input node found for link.", link);
return;
}
const inputSlot = inputNode.inputs.at(link.target_slot);
if (!inputSlot) {
console.warn("No input slot found for link.", link);
return;
}
const renderLink = new ToOutputFromRerouteLink(network, inputNode, inputSlot, reroute, this);
renderLink.fromDirection = LinkDirection.LEFT;
this.renderLinks.push(renderLink);
this.state.connectingTo = "output";
this.#setLegacyLinks(true);
}
dragFromLinkSegment(network, linkSegment) {
if (this.isConnecting) throw new Error("Already dragging links.");
const { state } = this;
if (linkSegment.origin_id == null || linkSegment.origin_slot == null) return;
const node2 = network.getNodeById(linkSegment.origin_id);
if (!node2) return;
const slot = node2.outputs.at(linkSegment.origin_slot);
if (!slot) return;
const reroute = network.getReroute(linkSegment.parentId);
const renderLink = new ToInputRenderLink(network, node2, slot, reroute);
renderLink.fromDirection = LinkDirection.NONE;
this.renderLinks.push(renderLink);
state.connectingTo = "input";
this.#setLegacyLinks(false);
}
/**
* Connects the links being droppe
* @param event Contains the drop location, in canvas space
*/
dropLinks(locator, event) {
if (!this.isConnecting) {
console.warn("Attempted to drop links when not connecting to anything.");
return;
}
const { renderLinks } = this;
const mayContinue = this.events.dispatch("before-drop-links", { renderLinks, event });
if (mayContinue === false) return;
const { canvasX, canvasY } = event;
const node2 = locator.getNodeOnPos(canvasX, canvasY) ?? void 0;
if (node2) {
this.dropOnNode(node2, event);
} else {
const reroute = locator.getRerouteOnPos(canvasX, canvasY);
if (reroute && this.isRerouteValidDrop(reroute)) {
this.dropOnReroute(reroute, event);
} else {
this.dropOnNothing(event);
}
}
this.events.dispatch("after-drop-links", { renderLinks, event });
}
dropOnNode(node2, event) {
const { renderLinks, state } = this;
const { connectingTo } = state;
const { canvasX, canvasY } = event;
if (renderLinks.every((link) => link.node === node2)) return;
if (connectingTo === "output") {
const output = node2.getOutputOnPos([canvasX, canvasY]);
if (output) {
this.#dropOnOutput(node2, output);
} else {
this.connectToNode(node2, event);
}
} else if (connectingTo === "input") {
const input = node2.getInputOnPos([canvasX, canvasY]);
const inputOrSocket = input ?? node2.getSlotFromWidget(this.overWidget);
if (inputOrSocket) {
this.#dropOnInput(node2, inputOrSocket);
} else {
this.connectToNode(node2, event);
}
}
}
dropOnReroute(reroute, event) {
const mayContinue = this.events.dispatch("dropped-on-reroute", { reroute, event });
if (mayContinue === false) return;
if (this.state.connectingTo === "input") {
if (this.renderLinks.length !== 1) throw new Error(`Attempted to connect ${this.renderLinks.length} input links to a reroute.`);
const renderLink = this.renderLinks[0];
this._connectOutputToReroute(reroute, renderLink);
return;
}
for (const link of this.renderLinks) {
if (link.toType !== "output") continue;
const result = reroute.findSourceOutput();
if (!result) continue;
const { node: node2, output } = result;
if (!link.canConnectToOutput(node2, output)) continue;
link.connectToRerouteOutput(reroute, node2, output, this.events);
}
}
/** @internal Temporary workaround - requires refactor. */
_connectOutputToReroute(reroute, renderLink) {
const results = reroute.findTargetInputs();
if (!results?.length) return;
const maybeReroutes = reroute.getReroutes();
if (maybeReroutes === null) throw new Error("Reroute loop detected.");
const originalReroutes = maybeReroutes.slice(0, -1).reverse();
if (renderLink instanceof ToInputRenderLink) {
const { node: node2, fromSlot, fromSlotIndex, fromReroute } = renderLink;
reroute.setFloatingLinkOrigin(node2, fromSlot, fromSlotIndex);
if (fromReroute != null) {
for (const originalReroute of originalReroutes) {
if (originalReroute.id === fromReroute.id) break;
for (const linkId of reroute.floatingLinkIds) {
originalReroute.floatingLinkIds.delete(linkId);
}
}
}
}
const filtered = results.filter((result) => renderLink.toType === "input" && canConnectInputLinkToReroute(renderLink, result.node, result.input, reroute));
for (const result of filtered) {
renderLink.connectToRerouteInput(reroute, result, this.events, originalReroutes);
}
return;
}
dropOnNothing(event) {
const mayContinue = this.events.dispatch("dropped-on-canvas", event);
if (mayContinue === false) return;
this.disconnectLinks();
}
/**
* Disconnects all moving links.
* @remarks This is called when the links are dropped on the canvas.
* May be called by consumers to e.g. drag links into a bin / void.
*/
disconnectLinks() {
for (const link of this.renderLinks) {
if (link instanceof MovingLinkBase) {
link.disconnect();
}
}
}
/**
* Connects the links being dropped onto a node to the first matching slot.
* @param node The node that the links are being dropped on
* @param event Contains the drop location, in canvas space
*/
connectToNode(node2, event) {
const { state: { connectingTo } } = this;
const mayContinue = this.events.dispatch("dropped-on-node", { node: node2, event });
if (mayContinue === false) return;
const firstLink = this.renderLinks[0];
if (!firstLink) return;
if (connectingTo === "output") {
const output = node2.findOutputByType(firstLink.fromSlot.type)?.slot;
if (!output) {
console.warn(`Could not find slot for link type: [${firstLink.fromSlot.type}].`);
return;
}
this.#dropOnOutput(node2, output);
} else if (connectingTo === "input") {
const input = node2.findInputByType(firstLink.fromSlot.type)?.slot;
if (!input) {
console.warn(`Could not find slot for link type: [${firstLink.fromSlot.type}].`);
return;
}
this.#dropOnInput(node2, input);
}
}
#dropOnInput(node2, input) {
for (const link of this.renderLinks) {
if (!link.canConnectToInput(node2, input)) continue;
link.connectToInput(node2, input, this.events);
}
}
#dropOnOutput(node2, output) {
for (const link of this.renderLinks) {
if (!link.canConnectToOutput(node2, output)) {
if (link instanceof MovingOutputLink && link.link.parentId !== void 0) {
link.outputNode.connectSlots(link.outputSlot, link.inputNode, link.inputSlot, void 0);
}
continue;
}
link.connectToOutput(node2, output, this.events);
}
}
isInputValidDrop(node2, input) {
return this.renderLinks.some((link) => link.canConnectToInput(node2, input));
}
isNodeValidDrop(node2) {
if (this.state.connectingTo === "output") {
return node2.outputs.some((output) => this.renderLinks.some((link) => link.canConnectToOutput(node2, output)));
}
return node2.inputs.some((input) => this.renderLinks.some((link) => link.canConnectToInput(node2, input)));
}
/**
* Checks if a reroute is a valid drop target for any of the links being connected.
* @param reroute The reroute that would be dropped on.
* @returns `true` if any of the current links being connected are valid for the given reroute.
*/
isRerouteValidDrop(reroute) {
if (this.state.connectingTo === "input") {
const results = reroute.findTargetInputs();
if (!results?.length) return false;
for (const { node: node2, input } of results) {
for (const renderLink of this.renderLinks) {
if (renderLink.toType !== "input") continue;
if (canConnectInputLinkToReroute(renderLink, node2, input, reroute)) return true;
}
}
} else {
const result = reroute.findSourceOutput();
if (!result) return false;
const { node: node2, output } = result;
for (const renderLink of this.renderLinks) {
if (renderLink.toType !== "output") continue;
if (!renderLink.canConnectToReroute(reroute)) continue;
if (renderLink.canConnectToOutput(node2, output)) return true;
}
}
return false;
}
/** Sets connecting_links, used by some extensions still. */
#setLegacyLinks(fromSlotIsInput) {
const links = this.renderLinks.map((link) => {
const input = fromSlotIsInput ? link.fromSlot : null;
const output = fromSlotIsInput ? null : link.fromSlot;
const afterRerouteId = link instanceof MovingLinkBase ? link.link?.parentId : link.fromReroute?.id;
return {
node: link.node,
slot: link.fromSlotIndex,
input,
output,
pos: link.fromPos,
afterRerouteId
};
});
this.#setConnectingLinks(links);
}
/**
* Exports the current state of the link connector.
* @param network The network that the links being connected belong to.
* @returns A POJO with the state of the link connector, links being connected, and their network.
* @remarks Other than {@link network}, all properties are shallow cloned.
*/
export(network) {
return {
renderLinks: [...this.renderLinks],
inputLinks: [...this.inputLinks],
outputLinks: [...this.outputLinks],
floatingLinks: [...this.floatingLinks],
state: { ...this.state },
network
};
}
/**
* Adds an event listener that will be automatically removed when the reset event is fired.
* @param eventName The event to listen for.
* @param listener The listener to call when the event is fired.
*/
listenUntilReset(eventName, listener, options) {
this.events.addEventListener(eventName, listener, options);
this.events.addEventListener("reset", () => this.events.removeEventListener(eventName, listener), { once: true });
}
/**
* Resets everything to its initial state.
*
* Effectively cancels moving or connecting links.
*/
reset(force = false) {
const mayContinue = this.events.dispatch("reset", force);
if (mayContinue === false) return;
const { state, outputLinks, inputLinks, hiddenReroutes, renderLinks, floatingLinks } = this;
if (!force && state.connectingTo === void 0) return;
state.connectingTo = void 0;
for (const link of outputLinks) delete link._dragging;
for (const link of inputLinks) delete link._dragging;
for (const link of floatingLinks) delete link._dragging;
for (const reroute of hiddenReroutes) delete reroute._dragging;
renderLinks.length = 0;
inputLinks.length = 0;
outputLinks.length = 0;
floatingLinks.length = 0;
hiddenReroutes.clear();
state.multi = false;
state.draggingExistingLinks = false;
state.snapLinksPos = void 0;
}
}
function canConnectInputLinkToReroute(link, inputNode, input, reroute) {
const { fromReroute } = link;
if (!link.canConnectToInput(inputNode, input) || // Would result in no change
fromReroute?.id === reroute.id || // Cannot connect from child to parent reroute
fromReroute?.getReroutes()?.includes(reroute)) {
return false;
}
if (link instanceof ToInputRenderLink) {
if (reroute.parentId == null) {
if (reroute.firstLink?.hasOrigin(link.node.id, link.fromSlotIndex)) return false;
} else if (link.fromReroute?.id === reroute.parentId) {
return false;
}
}
return true;
}
function distance(a, b) {
return Math.sqrt(
(b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])
);
}
function dist2(x1, y1, x2, y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
function isInRectangle(x2, y, left, top, width2, height) {
return x2 >= left && x2 < left + width2 && y >= top && y < top + height;
}
function isPointInRect(point, rect) {
return point[0] >= rect[0] && point[0] < rect[0] + rect[2] && point[1] >= rect[1] && point[1] < rect[1] + rect[3];
}
function isInRect(x2, y, rect) {
return x2 >= rect[0] && x2 < rect[0] + rect[2] && y >= rect[1] && y < rect[1] + rect[3];
}
function isInsideRectangle(x2, y, left, top, width2, height) {
return left < x2 && left + width2 > x2 && top < y && top + height > y;
}
function overlapBounding(a, b) {
const aRight = a[0] + a[2];
const aBottom = a[1] + a[3];
const bRight = b[0] + b[2];
const bBottom = b[1] + b[3];
return a[0] > bRight || a[1] > bBottom || aRight < b[0] || aBottom < b[1] ? false : true;
}
function getCentre(rect) {
return [
rect[0] + rect[2] * 0.5,
rect[1] + rect[3] * 0.5
];
}
function containsCentre(a, b) {
const centreX = b[0] + b[2] * 0.5;
const centreY = b[1] + b[3] * 0.5;
return isInRect(centreX, centreY, a);
}
function containsRect(a, b) {
const aRight = a[0] + a[2];
const aBottom = a[1] + a[3];
const bRight = b[0] + b[2];
const bBottom = b[1] + b[3];
const identical = a[0] === b[0] && a[1] === b[1] && aRight === bRight && aBottom === bBottom;
return !identical && a[0] <= b[0] && a[1] <= b[1] && aRight >= bRight && aBottom >= bBottom;
}
function findPointOnCurve(out, a, b, controlA, controlB, t = 0.5) {
const iT = 1 - t;
const c1 = iT * iT * iT;
const c2 = 3 * (iT * iT) * t;
const c3 = 3 * iT * (t * t);
const c4 = t * t * t;
out[0] = c1 * a[0] + c2 * controlA[0] + c3 * controlB[0] + c4 * b[0];
out[1] = c1 * a[1] + c2 * controlA[1] + c3 * controlB[1] + c4 * b[1];
}
function createBounds(objects, padding = 10) {
const bounds = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
for (const obj of objects) {
const rect = obj.boundingRect;
bounds[0] = Math.min(bounds[0], rect[0]);
bounds[1] = Math.min(bounds[1], rect[1]);
bounds[2] = Math.max(bounds[2], rect[0] + rect[2]);
bounds[3] = Math.max(bounds[3], rect[1] + rect[3]);
}
if (!bounds.every((x2) => isFinite(x2))) return null;
return [
bounds[0] - padding,
bounds[1] - padding,
bounds[2] - bounds[0] + 2 * padding,
bounds[3] - bounds[1] + 2 * padding
];
}
function snapPoint(pos, snapTo) {
if (!snapTo) return false;
pos[0] = snapTo * Math.round(pos[0] / snapTo);
pos[1] = snapTo * Math.round(pos[1] / snapTo);
return true;
}
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function getNodeInputOnPos(node2, x2, y) {
const { inputs } = node2;
if (!inputs) return;
for (const [index, input] of inputs.entries()) {
const pos = node2.getInputPos(index);
const nameLength = input.label?.length ?? input.localized_name?.length ?? input.name?.length;
const width2 = 20 + (nameLength || 3) * 7;
if (isInRectangle(
x2,
y,
pos[0] - 10,
pos[1] - 10,
width2,
20
)) {
return { index, input, pos };
}
}
}
function getNodeOutputOnPos(node2, x2, y) {
const { outputs } = node2;
if (!outputs) return;
for (const [index, output] of outputs.entries()) {
const pos = node2.getOutputPos(index);
if (isInRectangle(
x2,
y,
pos[0] - 10,
pos[1] - 10,
40,
20
)) {
return { index, output, pos };
}
}
}
function isOverNodeInput(node2, canvasx, canvasy, slot_pos) {
const result = getNodeInputOnPos(node2, canvasx, canvasy);
if (!result) return -1;
if (slot_pos) {
slot_pos[0] = result.pos[0];
slot_pos[1] = result.pos[1];
}
return result.index;
}
function isOverNodeOutput(node2, canvasx, canvasy, slot_pos) {
const result = getNodeOutputOnPos(node2, canvasx, canvasy);
if (!result) return -1;
if (slot_pos) {
slot_pos[0] = result.pos[0];
slot_pos[1] = result.pos[1];
}
return result.index;
}
class CanvasPointer {
/** Maximum time in milliseconds to ignore click drift */
static bufferTime = 150;
/** Maximum gap between pointerup and pointerdown events to be considered as a double click */
static doubleClickTime = 300;
/** Maximum offset from click location */
static get maxClickDrift() {
return this.#maxClickDrift;
}
static set maxClickDrift(value) {
this.#maxClickDrift = value;
this.#maxClickDrift2 = value * value;
}
static #maxClickDrift = 6;
/** {@link maxClickDrift} squared. Used to calculate click drift without `sqrt`. */
static #maxClickDrift2 = this.#maxClickDrift ** 2;
/** The element this PointerState should capture input against when dragging. */
element;
/** Pointer ID used by drag capture. */
pointerId;
/** Set to true when if the pointer moves far enough after a down event, before the corresponding up event is fired. */
dragStarted = false;
/** The {@link eUp} from the last successful click */
eLastDown;
/** Used downstream for touch event support. */
isDouble = false;
/** Used downstream for touch event support. */
isDown = false;
/** The resize handle currently being hovered or dragged */
resizeDirection;
/**
* If `true`, {@link eDown}, {@link eMove}, and {@link eUp} will be set to
* `undefined` when {@link reset} is called.
*
* Default: `true`
*/
clearEventsOnReset = true;
/** The last pointerdown event for the primary button */
eDown;
/** The last pointermove event for the primary button */
eMove;
/** The last pointerup event for the primary button */
eUp;
/**
* Run-once callback, called at the end of any click or drag, whether or not it was successful in any way.
*
* The setter of this callback will call the existing value before replacing it.
* Therefore, simply setting this value twice will execute the first callback.
*/
get finally() {
return this.#finally;
}
set finally(value) {
try {
this.#finally?.();
} finally {
this.#finally = value;
}
}
#finally;
constructor(element) {
this.element = element;
}
/**
* Callback for `pointerdown` events. To be used as the event handler (or called by it).
* @param e The `pointerdown` event
*/
down(e2) {
this.reset();
this.eDown = e2;
this.pointerId = e2.pointerId;
this.element.setPointerCapture(e2.pointerId);
}
/**
* Callback for `pointermove` events. To be used as the event handler (or called by it).
* @param e The `pointermove` event
*/
move(e2) {
const { eDown } = this;
if (!eDown) return;
if (!e2.buttons) {
this.reset();
return;
}
if (!(e2.buttons & eDown.buttons)) {
this.#completeClick(e2);
this.reset();
return;
}
this.eMove = e2;
this.onDrag?.(e2);
if (this.dragStarted) return;
const longerThanBufferTime = e2.timeStamp - eDown.timeStamp > CanvasPointer.bufferTime;
if (longerThanBufferTime || !this.#hasSamePosition(e2, eDown)) {
this.#setDragStarted(e2);
}
}
/**
* Callback for `pointerup` events. To be used as the event handler (or called by it).
* @param e The `pointerup` event
*/
up(e2) {
if (e2.button !== this.eDown?.button) return false;
this.#completeClick(e2);
const { dragStarted } = this;
this.reset();
return !dragStarted;
}
#completeClick(e2) {
const { eDown } = this;
if (!eDown) return;
this.eUp = e2;
if (this.dragStarted) {
this.onDragEnd?.(e2);
} else if (!this.#hasSamePosition(e2, eDown)) {
this.#setDragStarted();
this.onDragEnd?.(e2);
} else if (this.onDoubleClick && this.#isDoubleClick()) {
this.onDoubleClick(e2);
this.eLastDown = void 0;
} else {
this.onClick?.(e2);
this.eLastDown = eDown;
}
}
/**
* Checks if two events occurred near each other - not further apart than the maximum click drift.
* @param a The first event to compare
* @param b The second event to compare
* @param tolerance2 The maximum distance (squared) before the positions are considered different
* @returns `true` if the two events were no more than {@link maxClickDrift} apart, otherwise `false`
*/
#hasSamePosition(a, b, tolerance2 = CanvasPointer.#maxClickDrift2) {
const drift = dist2(a.clientX, a.clientY, b.clientX, b.clientY);
return drift <= tolerance2;
}
/**
* Checks whether the pointer is currently past the max click drift threshold.
* @returns `true` if the latest pointer event is past the the click drift threshold
*/
#isDoubleClick() {
const { eDown, eLastDown } = this;
if (!eDown || !eLastDown) return false;
const tolerance2 = (3 * CanvasPointer.#maxClickDrift) ** 2;
const diff = eDown.timeStamp - eLastDown.timeStamp;
return diff > 0 && diff < CanvasPointer.doubleClickTime && this.#hasSamePosition(eDown, eLastDown, tolerance2);
}
#setDragStarted(eMove) {
this.dragStarted = true;
this.onDragStart?.(this, eMove);
delete this.onDragStart;
}
/**
* Resets the state of this {@link CanvasPointer} instance.
*
* The {@link finally} callback is first executed, then all callbacks and intra-click
* state is cleared.
*/
reset() {
this.finally = void 0;
delete this.onClick;
delete this.onDoubleClick;
delete this.onDragStart;
delete this.onDrag;
delete this.onDragEnd;
this.isDown = false;
this.isDouble = false;
this.dragStarted = false;
this.resizeDirection = void 0;
if (this.clearEventsOnReset) {
this.eDown = void 0;
this.eMove = void 0;
this.eUp = void 0;
}
const { element, pointerId } = this;
this.pointerId = void 0;
if (typeof pointerId === "number" && element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
}
}
class DragAndScale {
/**
* The state of this DragAndScale instance.
*
* Implemented as a POCO that can be proxied without side-effects.
*/
state;
lastState = {
offset: [0, 0],
scale: 0
};
/** Maximum scale (zoom in) */
max_scale;
/** Minimum scale (zoom out) */
min_scale;
enabled;
last_mouse;
element;
visible_area;
dragging;
viewport;
get offset() {
return this.state.offset;
}
set offset(value) {
this.state.offset[0] = value[0];
this.state.offset[1] = value[1];
}
get scale() {
return this.state.scale;
}
set scale(value) {
this.state.scale = value;
}
constructor(element) {
this.state = {
offset: [0, 0],
scale: 1
};
this.max_scale = 10;
this.min_scale = 0.1;
this.enabled = true;
this.last_mouse = [0, 0];
this.visible_area = new Rectangle();
this.element = element;
}
/**
* Returns `true` if the current state has changed from the previous state.
* @returns `true` if the current state has changed from the previous state, otherwise `false`.
*/
#stateHasChanged() {
const current = this.state;
const previous = this.lastState;
return current.scale !== previous.scale || current.offset[0] !== previous.offset[0] || current.offset[1] !== previous.offset[1];
}
computeVisibleArea(viewport) {
const { scale, offset, visible_area } = this;
if (this.#stateHasChanged()) {
this.onChanged?.(scale, offset);
copyState(this.state, this.lastState);
}
if (!this.element) {
visible_area[0] = visible_area[1] = visible_area[2] = visible_area[3] = 0;
return;
}
let { width: width2, height } = this.element;
let startx = -offset[0];
let starty = -offset[1];
if (viewport) {
startx += viewport[0] / scale;
starty += viewport[1] / scale;
width2 = viewport[2];
height = viewport[3];
}
const endx = startx + width2 / scale;
const endy = starty + height / scale;
visible_area[0] = startx;
visible_area[1] = starty;
visible_area.resizeBottomRight(endx, endy);
}
toCanvasContext(ctx) {
ctx.scale(this.scale, this.scale);
ctx.translate(this.offset[0], this.offset[1]);
}
convertOffsetToCanvas(pos) {
return [
(pos[0] + this.offset[0]) * this.scale,
(pos[1] + this.offset[1]) * this.scale
];
}
convertCanvasToOffset(pos, out) {
out = out || [0, 0];
out[0] = pos[0] / this.scale - this.offset[0];
out[1] = pos[1] / this.scale - this.offset[1];
return out;
}
/** @deprecated Has not been kept up to date */
mouseDrag(x2, y) {
this.offset[0] += x2 / this.scale;
this.offset[1] += y / this.scale;
this.onredraw?.(this);
}
changeScale(value, zooming_center, roundToScaleOne = true) {
if (value < this.min_scale) {
value = this.min_scale;
} else if (value > this.max_scale) {
value = this.max_scale;
}
if (value == this.scale) return;
const rect = this.element.getBoundingClientRect();
if (!rect) return;
zooming_center = zooming_center ?? [rect.width * 0.5, rect.height * 0.5];
const normalizedCenter = [
zooming_center[0] - rect.x,
zooming_center[1] - rect.y
];
const center = this.convertCanvasToOffset(normalizedCenter);
this.scale = value;
if (roundToScaleOne && Math.abs(this.scale - 1) < 0.01) this.scale = 1;
const new_center = this.convertCanvasToOffset(normalizedCenter);
const delta_offset = [
new_center[0] - center[0],
new_center[1] - center[1]
];
this.offset[0] += delta_offset[0];
this.offset[1] += delta_offset[1];
this.onredraw?.(this);
}
changeDeltaScale(value, zooming_center) {
this.changeScale(this.scale * value, zooming_center);
}
/**
* Fits the view to the specified bounds.
* @param bounds The bounds to fit the view to, defined by a rectangle.
*/
fitToBounds(bounds, { zoom = 0.75 } = {}) {
const cw = this.element.width / window.devicePixelRatio;
const ch = this.element.height / window.devicePixelRatio;
let targetScale = this.scale;
if (zoom > 0) {
const targetScaleX = zoom * cw / Math.max(bounds[2], 300);
const targetScaleY = zoom * ch / Math.max(bounds[3], 300);
targetScale = Math.min(targetScaleX, targetScaleY, this.max_scale);
}
const scaledWidth = cw / targetScale;
const scaledHeight = ch / targetScale;
const targetX = -bounds[0] - bounds[2] * 0.5 + scaledWidth * 0.5;
const targetY = -bounds[1] - bounds[3] * 0.5 + scaledHeight * 0.5;
this.offset[0] = targetX;
this.offset[1] = targetY;
this.scale = targetScale;
}
/**
* Starts an animation to fit the view around the specified selection of nodes.
* @param bounds The bounds to animate the view to, defined by a rectangle.
*/
animateToBounds(bounds, setDirty, {
duration = 350,
zoom = 0.75,
easing = EaseFunction.EASE_IN_OUT_QUAD
} = {}) {
if (!(duration > 0)) throw new RangeError("Duration must be greater than 0");
const easeFunctions = {
linear: (t) => t,
easeInQuad: (t) => t * t,
easeOutQuad: (t) => t * (2 - t),
easeInOutQuad: (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
};
const easeFunction = easeFunctions[easing] ?? easeFunctions.linear;
const startTimestamp = performance.now();
const cw = this.element.width / window.devicePixelRatio;
const ch = this.element.height / window.devicePixelRatio;
const startX = this.offset[0];
const startY = this.offset[1];
const startX2 = startX - cw / this.scale;
const startY2 = startY - ch / this.scale;
const startScale = this.scale;
let targetScale = startScale;
if (zoom > 0) {
const targetScaleX = zoom * cw / Math.max(bounds[2], 300);
const targetScaleY = zoom * ch / Math.max(bounds[3], 300);
targetScale = Math.min(targetScaleX, targetScaleY, this.max_scale);
}
const scaledWidth = cw / targetScale;
const scaledHeight = ch / targetScale;
const targetX = -bounds[0] - bounds[2] * 0.5 + scaledWidth * 0.5;
const targetY = -bounds[1] - bounds[3] * 0.5 + scaledHeight * 0.5;
const targetX2 = targetX - scaledWidth;
const targetY2 = targetY - scaledHeight;
const animate = (timestamp) => {
const elapsed = timestamp - startTimestamp;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easeFunction(progress);
const currentX = startX + (targetX - startX) * easedProgress;
const currentY = startY + (targetY - startY) * easedProgress;
this.offset[0] = currentX;
this.offset[1] = currentY;
if (zoom > 0) {
const currentX2 = startX2 + (targetX2 - startX2) * easedProgress;
const currentY2 = startY2 + (targetY2 - startY2) * easedProgress;
const currentWidth = Math.abs(currentX2 - currentX);
const currentHeight = Math.abs(currentY2 - currentY);
this.scale = Math.min(cw / currentWidth, ch / currentHeight);
}
setDirty();
if (progress < 1) {
animationId = requestAnimationFrame(animate);
} else {
cancelAnimationFrame(animationId);
}
};
let animationId = requestAnimationFrame(animate);
}
reset() {
this.scale = 1;
this.offset[0] = 0;
this.offset[1] = 0;
}
}
function copyState(from, to) {
to.scale = from.scale;
to.offset[0] = from.offset[0];
to.offset[1] = from.offset[1];
}
const ELLIPSIS = "…";
const TWO_DOT_LEADER = "‥";
const ONE_DOT_LEADER = "․";
var SlotType = /* @__PURE__ */ ((SlotType2) => {
SlotType2["Array"] = "array";
SlotType2[SlotType2["Event"] = -1] = "Event";
return SlotType2;
})(SlotType || {});
var SlotShape = ((SlotShape2) => {
SlotShape2[SlotShape2["Box"] = RenderShape.BOX] = "Box";
SlotShape2[SlotShape2["Arrow"] = RenderShape.ARROW] = "Arrow";
SlotShape2[SlotShape2["Grid"] = RenderShape.GRID] = "Grid";
SlotShape2[SlotShape2["Circle"] = RenderShape.CIRCLE] = "Circle";
SlotShape2[SlotShape2["HollowCircle"] = RenderShape.HollowCircle] = "HollowCircle";
return SlotShape2;
})(SlotShape || {});
var SlotDirection = ((SlotDirection2) => {
SlotDirection2[SlotDirection2["Up"] = LinkDirection.UP] = "Up";
SlotDirection2[SlotDirection2["Right"] = LinkDirection.RIGHT] = "Right";
SlotDirection2[SlotDirection2["Down"] = LinkDirection.DOWN] = "Down";
SlotDirection2[SlotDirection2["Left"] = LinkDirection.LEFT] = "Left";
return SlotDirection2;
})(SlotDirection || {});
var LabelPosition = /* @__PURE__ */ ((LabelPosition2) => {
LabelPosition2["Left"] = "left";
LabelPosition2["Right"] = "right";
return LabelPosition2;
})(LabelPosition || {});
function strokeShape(ctx, area, {
shape = RenderShape.BOX,
round_radius,
title_height,
title_mode = TitleMode.NORMAL_TITLE,
color,
padding = 6,
collapsed = false,
lineWidth: thickness = 1
} = {}) {
round_radius ??= LiteGraph.ROUND_RADIUS;
color ??= LiteGraph.NODE_BOX_OUTLINE_COLOR;
if (title_mode === TitleMode.TRANSPARENT_TITLE) {
const height2 = title_height ?? LiteGraph.NODE_TITLE_HEIGHT;
area[1] -= height2;
area[3] += height2;
}
const { lineWidth, strokeStyle } = ctx;
ctx.lineWidth = thickness;
ctx.globalAlpha = 0.8;
ctx.strokeStyle = color;
ctx.beginPath();
const [x2, y, width2, height] = area;
switch (shape) {
case RenderShape.BOX: {
ctx.rect(
x2 - padding,
y - padding,
width2 + 2 * padding,
height + 2 * padding
);
break;
}
case RenderShape.ROUND:
case RenderShape.CARD: {
const radius = round_radius + padding;
const isCollapsed = shape === RenderShape.CARD && collapsed;
const cornerRadii = isCollapsed || shape === RenderShape.ROUND ? [radius] : [radius, 2, radius, 2];
ctx.roundRect(
x2 - padding,
y - padding,
width2 + 2 * padding,
height + 2 * padding,
cornerRadii
);
break;
}
case RenderShape.CIRCLE: {
const centerX = x2 + width2 / 2;
const centerY = y + height / 2;
const radius = Math.max(width2, height) / 2 + padding;
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
break;
}
}
ctx.stroke();
ctx.lineWidth = lineWidth;
ctx.strokeStyle = strokeStyle;
ctx.globalAlpha = 1;
}
function truncateTextToWidth(ctx, text, maxWidth) {
if (!(maxWidth > 0)) return "";
const fullWidth = ctx.measureText(text).width;
if (fullWidth <= maxWidth) return text;
const ellipsisWidth = ctx.measureText(ELLIPSIS).width * 0.75;
if (ellipsisWidth > maxWidth) {
const twoDotsWidth = ctx.measureText(TWO_DOT_LEADER).width * 0.75;
if (twoDotsWidth < maxWidth) return TWO_DOT_LEADER;
const oneDotWidth = ctx.measureText(ONE_DOT_LEADER).width * 0.75;
return oneDotWidth < maxWidth ? ONE_DOT_LEADER : "";
}
let min = 0;
let max = text.length;
let bestLen = 0;
while (min <= max) {
const mid = Math.floor((min + max) * 0.5);
if (mid === 0) {
min = mid + 1;
continue;
}
const sub = text.substring(0, mid);
const currentWidth = ctx.measureText(sub).width + ellipsisWidth;
if (currentWidth <= maxWidth) {
bestLen = mid;
min = mid + 1;
} else {
max = mid - 1;
}
}
return bestLen === 0 ? ELLIPSIS : text.substring(0, bestLen) + ELLIPSIS;
}
function drawTextInArea({ ctx, text, area, align = "left" }) {
const { left, right, bottom, width: width2, centreX } = area;
const fullWidth = ctx.measureText(text).width;
if (fullWidth <= width2) {
ctx.textAlign = align;
const x2 = align === "left" ? left : align === "right" ? right : centreX;
ctx.fillText(text, x2, bottom);
return;
}
const truncated = truncateTextToWidth(ctx, text, width2);
if (truncated.length === 0) return;
ctx.textAlign = "left";
ctx.fillText(truncated.slice(0, -1), left, bottom);
ctx.rect(left, bottom, width2, 1);
ctx.textAlign = "right";
const ellipsis = truncated.at(-1);
ctx.fillText(ellipsis, right, bottom, ctx.measureText(ellipsis).width * 0.75);
}
class NullGraphError extends Error {
constructor(message = "Attempted to access LGraph reference that was null or undefined.", cause) {
super(message, { cause });
this.name = "NullGraphError";
}
}
class LGraphIcon {
unicode;
fontFamily;
color;
bgColor;
fontSize;
circlePadding;
xOffset;
yOffset;
constructor({
unicode,
fontFamily = "PrimeIcons",
color = "#e6c200",
bgColor,
fontSize = 16,
circlePadding = 2,
xOffset = 0,
yOffset = 0
}) {
this.unicode = unicode;
this.fontFamily = fontFamily;
this.color = color;
this.bgColor = bgColor;
this.fontSize = fontSize;
this.circlePadding = circlePadding;
this.xOffset = xOffset;
this.yOffset = yOffset;
}
draw(ctx, x2, y) {
x2 += this.xOffset;
y += this.yOffset;
const { font, textBaseline, textAlign, fillStyle } = ctx;
ctx.font = `${this.fontSize}px '${this.fontFamily}'`;
ctx.textBaseline = "middle";
ctx.textAlign = "center";
const iconRadius = this.fontSize / 2 + this.circlePadding;
if (this.bgColor) {
ctx.beginPath();
ctx.arc(x2 + iconRadius, y, iconRadius, 0, 2 * Math.PI);
ctx.fillStyle = this.bgColor;
ctx.fill();
}
ctx.fillStyle = this.color;
ctx.fillText(this.unicode, x2 + iconRadius, y);
ctx.font = font;
ctx.textBaseline = textBaseline;
ctx.textAlign = textAlign;
ctx.fillStyle = fillStyle;
}
}
var BadgePosition = /* @__PURE__ */ ((BadgePosition2) => {
BadgePosition2["TopLeft"] = "top-left";
BadgePosition2["TopRight"] = "top-right";
return BadgePosition2;
})(BadgePosition || {});
class LGraphBadge {
text;
fgColor;
bgColor;
fontSize;
padding;
height;
cornerRadius;
icon;
xOffset;
yOffset;
constructor({
text,
fgColor = "white",
bgColor = "#0F1F0F",
fontSize = 12,
padding = 6,
height = 20,
cornerRadius = 5,
iconOptions,
xOffset = 0,
yOffset = 0
}) {
this.text = text;
this.fgColor = fgColor;
this.bgColor = bgColor;
this.fontSize = fontSize;
this.padding = padding;
this.height = height;
this.cornerRadius = cornerRadius;
if (iconOptions) {
this.icon = new LGraphIcon(iconOptions);
}
this.xOffset = xOffset;
this.yOffset = yOffset;
}
get visible() {
return this.text.length > 0 || !!this.icon;
}
getWidth(ctx) {
if (!this.visible) return 0;
const { font } = ctx;
let iconWidth = 0;
if (this.icon) {
ctx.font = `${this.icon.fontSize}px '${this.icon.fontFamily}'`;
iconWidth = ctx.measureText(this.icon.unicode).width + this.padding;
}
ctx.font = `${this.fontSize}px sans-serif`;
const textWidth = this.text ? ctx.measureText(this.text).width : 0;
ctx.font = font;
return iconWidth + textWidth + this.padding * 2;
}
draw(ctx, x2, y) {
if (!this.visible) return;
x2 += this.xOffset;
y += this.yOffset;
const { font, fillStyle, textBaseline, textAlign } = ctx;
ctx.font = `${this.fontSize}px sans-serif`;
const badgeWidth = this.getWidth(ctx);
const badgeX = 0;
ctx.fillStyle = this.bgColor;
ctx.beginPath();
if (ctx.roundRect) {
ctx.roundRect(x2 + badgeX, y, badgeWidth, this.height, this.cornerRadius);
} else {
ctx.rect(x2 + badgeX, y, badgeWidth, this.height);
}
ctx.fill();
let drawX = x2 + badgeX + this.padding;
const centerY = y + this.height / 2;
if (this.icon) {
this.icon.draw(ctx, drawX, centerY);
drawX += this.icon.fontSize + this.padding / 2 + 4;
}
if (this.text) {
ctx.fillStyle = this.fgColor;
ctx.textBaseline = "middle";
ctx.textAlign = "left";
ctx.fillText(this.text, drawX, centerY + 1);
}
ctx.font = font;
ctx.fillStyle = fillStyle;
ctx.textBaseline = textBaseline;
ctx.textAlign = textAlign;
}
}
class SlotBase {
name;
localized_name;
label;
type;
dir;
removable;
shape;
color_off;
color_on;
locked;
nameLocked;
widget;
_floatingLinks;
hasErrors;
boundingRect;
constructor(name, type, boundingRect) {
this.name = name;
this.type = type;
this.boundingRect = boundingRect;
}
renderingColor(colorContext) {
return this.isConnected ? this.color_on || colorContext.getConnectedColor(this.type) : this.color_off || colorContext.getDisconnectedColor(this.type);
}
}
class NodeSlot extends SlotBase {
pos;
/** The offset from the parent node to the centre point of this slot. */
get #centreOffset() {
const nodePos = this.node.pos;
const { boundingRect } = this;
const diameter = boundingRect[3];
return getCentre([
boundingRect[0] - nodePos[0],
boundingRect[1] - nodePos[1],
diameter,
diameter
]);
}
#node;
get node() {
return this.#node;
}
get highlightColor() {
return LiteGraph.NODE_TEXT_HIGHLIGHT_COLOR ?? LiteGraph.NODE_SELECTED_TITLE_COLOR ?? LiteGraph.NODE_TEXT_COLOR;
}
constructor(slot, node2) {
super(slot.name, slot.type, slot.boundingRect ?? [0, 0, 0, 0]);
Object.assign(this, slot);
this.#node = node2;
}
/**
* The label to display in the UI.
*/
get renderingLabel() {
return this.label || this.localized_name || this.name || "";
}
draw(ctx, {
colorContext,
labelPosition = LabelPosition.Right,
lowQuality = false,
highlight = false,
doStroke = false
}) {
const originalFillStyle = ctx.fillStyle;
const originalStrokeStyle = ctx.strokeStyle;
const originalLineWidth = ctx.lineWidth;
const labelColor = highlight ? this.highlightColor : LiteGraph.NODE_TEXT_COLOR;
const pos = this.#centreOffset;
const slot_type = this.type;
const slot_shape = slot_type === SlotType.Array ? SlotShape.Grid : this.shape;
ctx.beginPath();
let doFill = true;
ctx.fillStyle = this.renderingColor(colorContext);
ctx.lineWidth = 1;
if (slot_type === SlotType.Event || slot_shape === SlotShape.Box) {
ctx.rect(pos[0] - 6 + 0.5, pos[1] - 5 + 0.5, 14, 10);
} else if (slot_shape === SlotShape.Arrow) {
ctx.moveTo(pos[0] + 8, pos[1] + 0.5);
ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5);
ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5);
ctx.closePath();
} else if (slot_shape === SlotShape.Grid) {
const gridSize = 3;
const cellSize = 2;
const spacing = 3;
for (let x2 = 0; x2 < gridSize; x2++) {
for (let y = 0; y < gridSize; y++) {
ctx.rect(
pos[0] - 4 + x2 * spacing,
pos[1] - 4 + y * spacing,
cellSize,
cellSize
);
}
}
doStroke = false;
} else {
if (lowQuality) {
ctx.rect(pos[0] - 4, pos[1] - 4, 8, 8);
} else {
let radius;
if (slot_shape === SlotShape.HollowCircle) {
doFill = false;
doStroke = true;
ctx.lineWidth = 3;
ctx.strokeStyle = ctx.fillStyle;
radius = highlight ? 4 : 3;
} else {
radius = highlight ? 5 : 4;
}
ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);
}
}
if (doFill) ctx.fill();
if (!lowQuality && doStroke) ctx.stroke();
const hideLabel = lowQuality || this.isWidgetInputSlot;
if (!hideLabel) {
const text = this.renderingLabel;
if (text) {
ctx.fillStyle = labelColor;
if (labelPosition === LabelPosition.Right) {
if (this.dir == LinkDirection.UP) {
ctx.fillText(text, pos[0], pos[1] - 10);
} else {
ctx.fillText(text, pos[0] + 10, pos[1] + 5);
}
} else {
if (this.dir == LinkDirection.DOWN) {
ctx.fillText(text, pos[0], pos[1] - 8);
} else {
ctx.fillText(text, pos[0] - 10, pos[1] + 5);
}
}
}
}
if (this.hasErrors) {
ctx.lineWidth = 2;
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.arc(pos[0], pos[1], 12, 0, Math.PI * 2);
ctx.stroke();
}
ctx.fillStyle = originalFillStyle;
ctx.strokeStyle = originalStrokeStyle;
ctx.lineWidth = originalLineWidth;
}
drawCollapsed(ctx) {
const [x2, y] = this.collapsedPos;
const { fillStyle } = ctx;
ctx.fillStyle = "#686";
ctx.beginPath();
if (this.type === SlotType.Event || this.shape === RenderShape.BOX) {
ctx.rect(x2 - 7 + 0.5, y - 4, 14, 8);
} else if (this.shape === RenderShape.ARROW) {
const isInput = this instanceof NodeInputSlot;
if (isInput) {
ctx.moveTo(x2 + 8, y);
ctx.lineTo(x2 - 4, y - 4);
ctx.lineTo(x2 - 4, y + 4);
} else {
ctx.moveTo(x2 + 6, y);
ctx.lineTo(x2 - 6, y - 4);
ctx.lineTo(x2 - 6, y + 4);
}
ctx.closePath();
} else {
ctx.arc(x2, y, 4, 0, Math.PI * 2);
}
ctx.fill();
ctx.fillStyle = fillStyle;
}
}
class NodeInputSlot extends NodeSlot {
link;
get isWidgetInputSlot() {
return !!this.widget;
}
get collapsedPos() {
return [0, LiteGraph.NODE_TITLE_HEIGHT * -0.5];
}
constructor(slot, node2) {
super(slot, node2);
this.link = slot.link;
}
get isConnected() {
return this.link != null;
}
isValidTarget(fromSlot) {
return "links" in fromSlot && LiteGraph.isValidConnection(this.type, fromSlot.type);
}
draw(ctx, options) {
const { textAlign } = ctx;
ctx.textAlign = "left";
super.draw(ctx, {
...options,
labelPosition: LabelPosition.Right,
doStroke: false
});
ctx.textAlign = textAlign;
}
}
class NodeOutputSlot extends NodeSlot {
#node;
links;
_data;
slot_index;
get isWidgetInputSlot() {
return false;
}
get collapsedPos() {
return [
this.#node._collapsed_width ?? LiteGraph.NODE_COLLAPSED_WIDTH,
LiteGraph.NODE_TITLE_HEIGHT * -0.5
];
}
constructor(slot, node2) {
super(slot, node2);
this.links = slot.links;
this._data = slot._data;
this.slot_index = slot.slot_index;
this.#node = node2;
}
isValidTarget(fromSlot) {
return "link" in fromSlot && LiteGraph.isValidConnection(this.type, fromSlot.type);
}
get isConnected() {
return this.links != null && this.links.length > 0;
}
draw(ctx, options) {
const { textAlign, strokeStyle } = ctx;
ctx.textAlign = "right";
ctx.strokeStyle = "black";
super.draw(ctx, {
...options,
labelPosition: LabelPosition.Left,
doStroke: true
});
ctx.textAlign = textAlign;
ctx.strokeStyle = strokeStyle;
}
}
function shallowCloneCommonProps(slot) {
const { color_off, color_on, dir, label, localized_name, locked, name, nameLocked, removable, shape, type } = slot;
return { color_off, color_on, dir, label, localized_name, locked, name, nameLocked, removable, shape, type };
}
function inputAsSerialisable(slot) {
const { link } = slot;
const widgetOrPos = slot.widget ? { widget: { name: slot.widget.name } } : { pos: slot.pos };
return {
...shallowCloneCommonProps(slot),
...widgetOrPos,
link
};
}
function outputAsSerialisable(slot) {
const { pos, slot_index, links, widget } = slot;
const outputWidget = widget ? { widget: { name: widget.name } } : null;
return {
...shallowCloneCommonProps(slot),
...outputWidget,
pos,
slot_index,
links
};
}
function isINodeInputSlot(slot) {
return "link" in slot;
}
function isWidgetInputSlot(slot) {
return !!slot.widget;
}
function stringOrEmpty(value) {
return value == null ? "" : String(value);
}
function parseSlotTypes(type) {
return type == "" || type == "0" ? ["*"] : String(type).toLowerCase().split(",");
}
function getAllNestedItems(items) {
const allItems = /* @__PURE__ */ new Set();
if (items) {
for (const item of items) addRecursively(item, allItems);
}
return allItems;
function addRecursively(item, flatSet) {
if (flatSet.has(item) || item.pinned) return;
flatSet.add(item);
if (item.children) {
for (const child of item.children) addRecursively(child, flatSet);
}
}
}
function findFirstNode(items) {
for (const item of items) {
if (item instanceof LGraphNode) return item;
}
}
function findFreeSlotOfType(slots, type) {
if (!slots?.length) return;
let occupiedSlot;
let wildSlot;
let occupiedWildSlot;
const validTypes = parseSlotTypes(type);
for (const [index, slot] of slots.entries()) {
const slotTypes = parseSlotTypes(slot.type);
for (const validType of validTypes) {
for (const slotType of slotTypes) {
if (slotType === validType) {
if (slot.link == null && !slot.links?.length) {
return { index, slot };
}
occupiedSlot ??= { index, slot };
} else if (!wildSlot && (validType === "*" || slotType === "*")) {
if (slot.link == null && !slot.links?.length) {
wildSlot = { index, slot };
} else {
occupiedWildSlot ??= { index, slot };
}
}
}
}
}
return wildSlot ?? occupiedSlot ?? occupiedWildSlot;
}
const UNIQUE_MESSAGE_LIMIT = 1e4;
const sentWarnings = /* @__PURE__ */ new Set();
function warnDeprecated(message, source) {
if (!LiteGraph.alwaysRepeatWarnings) {
if (sentWarnings.has(message)) return;
if (sentWarnings.size > UNIQUE_MESSAGE_LIMIT) return;
sentWarnings.add(message);
}
for (const callback of LiteGraph.onDeprecationWarning) {
callback(message, source);
}
}
function distributeSpace(totalSpace, requests) {
if (requests.length === 0) return [];
const totalMinSize = requests.reduce((sum, req) => sum + req.minSize, 0);
if (totalSpace < totalMinSize) {
return requests.map((req) => req.minSize);
}
let allocations = requests.map((req) => ({
computedSize: req.minSize,
maxSize: req.maxSize ?? Infinity,
remaining: (req.maxSize ?? Infinity) - req.minSize
}));
let remainingSpace = totalSpace - totalMinSize;
while (remainingSpace > 0 && allocations.some((alloc) => alloc.remaining > 0)) {
const growableItems = allocations.filter(
(alloc) => alloc.remaining > 0
).length;
if (growableItems === 0) break;
const sharePerItem = remainingSpace / growableItems;
let spaceUsedThisRound = 0;
allocations = allocations.map((alloc) => {
if (alloc.remaining <= 0) return alloc;
const growth = Math.min(sharePerItem, alloc.remaining);
spaceUsedThisRound += growth;
return {
...alloc,
computedSize: alloc.computedSize + growth,
remaining: alloc.remaining - growth
};
});
remainingSpace -= spaceUsedThisRound;
if (spaceUsedThisRound === 0) break;
}
return allocations.map(({ computedSize }) => computedSize);
}
function toClass(cls, ...args) {
return args[0] instanceof cls ? args[0] : new cls(...args);
}
function isColorable(obj) {
return typeof obj === "object" && obj !== null && "setColorOption" in obj && "getColorOption" in obj;
}
class Rectangle extends Float64Array {
#pos;
#size;
constructor(x2 = 0, y = 0, width2 = 0, height = 0) {
super(4);
this[0] = x2;
this[1] = y;
this[2] = width2;
this[3] = height;
}
subarray(begin = 0, end) {
const byteOffset = begin << 3;
const length = end === void 0 ? end : end - begin;
return new Float64Array(this.buffer, byteOffset, length);
}
/**
* A reference to the position of the top-left corner of this rectangle.
*
* Updating the values of the returned object will update this rectangle.
*/
get pos() {
this.#pos ??= this.subarray(0, 2);
return this.#pos;
}
set pos(value) {
this[0] = value[0];
this[1] = value[1];
}
/**
* A reference to the size of this rectangle.
*
* Updating the values of the returned object will update this rectangle.
*/
get size() {
this.#size ??= this.subarray(2, 4);
return this.#size;
}
set size(value) {
this[2] = value[0];
this[3] = value[1];
}
// #region Property accessors
/** The x co-ordinate of the top-left corner of this rectangle. */
get x() {
return this[0];
}
set x(value) {
this[0] = value;
}
/** The y co-ordinate of the top-left corner of this rectangle. */
get y() {
return this[1];
}
set y(value) {
this[1] = value;
}
/** The width of this rectangle. */
get width() {
return this[2];
}
set width(value) {
this[2] = value;
}
/** The height of this rectangle. */
get height() {
return this[3];
}
set height(value) {
this[3] = value;
}
/** The x co-ordinate of the left edge of this rectangle. */
get left() {
return this[0];
}
set left(value) {
this[0] = value;
}
/** The y co-ordinate of the top edge of this rectangle. */
get top() {
return this[1];
}
set top(value) {
this[1] = value;
}
/** The x co-ordinate of the right edge of this rectangle. */
get right() {
return this[0] + this[2];
}
set right(value) {
this[0] = value - this[2];
}
/** The y co-ordinate of the bottom edge of this rectangle. */
get bottom() {
return this[1] + this[3];
}
set bottom(value) {
this[1] = value - this[3];
}
/** The x co-ordinate of the centre of this rectangle. */
get centreX() {
return this[0] + this[2] * 0.5;
}
/** The y co-ordinate of the centre of this rectangle. */
get centreY() {
return this[1] + this[3] * 0.5;
}
// #endregion Property accessors
/**
* Updates the rectangle to the values of {@link rect}.
* @param rect The rectangle to update to.
*/
updateTo(rect) {
this[0] = rect[0];
this[1] = rect[1];
this[2] = rect[2];
this[3] = rect[3];
}
/**
* Checks if the point [{@link x}, {@link y}] is inside this rectangle.
* @param x The x-coordinate to check
* @param y The y-coordinate to check
* @returns `true` if the point is inside this rectangle, otherwise `false`.
*/
containsXy(x2, y) {
const { x: left, y: top, width: width2, height } = this;
return x2 >= left && x2 < left + width2 && y >= top && y < top + height;
}
/**
* Checks if {@link point} is inside this rectangle.
* @param point The point to check
* @returns `true` if {@link point} is inside this rectangle, otherwise `false`.
*/
containsPoint(point) {
return this.x <= point[0] && this.y <= point[1] && this.x + this.width >= point[0] && this.y + this.height >= point[1];
}
/**
* Checks if {@link rect} is inside this rectangle.
* @param rect The rectangle to check
* @returns `true` if {@link rect} is inside this rectangle, otherwise `false`.
*/
containsRect(rect) {
return this.x <= rect[0] && this.y <= rect[1] && this.x + this.width >= rect[0] + rect[2] && this.y + this.height >= rect[1] + rect[3];
}
/**
* Checks if {@link rect} overlaps with this rectangle.
* @param rect The rectangle to check
* @returns `true` if {@link rect} overlaps with this rectangle, otherwise `false`.
*/
overlaps(rect) {
return this.x < rect[0] + rect[2] && this.y < rect[1] + rect[3] && this.x + this.width > rect[0] && this.y + this.height > rect[1];
}
/**
* Finds the corner (if any) of this rectangle that contains the point [{@link x}, {@link y}].
* @param x The x-coordinate to check
* @param y The y-coordinate to check
* @param cornerSize Each corner is treated as an inset square with this width and height.
* @returns The compass direction of the corner that contains the point, or `undefined` if the point is not in any corner.
*/
findContainingCorner(x2, y, cornerSize) {
if (this.isInTopLeftCorner(x2, y, cornerSize)) return "NW";
if (this.isInTopRightCorner(x2, y, cornerSize)) return "NE";
if (this.isInBottomLeftCorner(x2, y, cornerSize)) return "SW";
if (this.isInBottomRightCorner(x2, y, cornerSize)) return "SE";
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the top-left corner of this rectangle, otherwise `false`. */
isInTopLeftCorner(x2, y, cornerSize) {
return isInRectangle(x2, y, this.x, this.y, cornerSize, cornerSize);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the top-right corner of this rectangle, otherwise `false`. */
isInTopRightCorner(x2, y, cornerSize) {
return isInRectangle(x2, y, this.right - cornerSize, this.y, cornerSize, cornerSize);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the bottom-left corner of this rectangle, otherwise `false`. */
isInBottomLeftCorner(x2, y, cornerSize) {
return isInRectangle(x2, y, this.x, this.bottom - cornerSize, cornerSize, cornerSize);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the bottom-right corner of this rectangle, otherwise `false`. */
isInBottomRightCorner(x2, y, cornerSize) {
return isInRectangle(x2, y, this.right - cornerSize, this.bottom - cornerSize, cornerSize, cornerSize);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the top edge of this rectangle, otherwise `false`. */
isInTopEdge(x2, y, edgeSize) {
return isInRectangle(x2, y, this.x, this.y, this.width, edgeSize);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the bottom edge of this rectangle, otherwise `false`. */
isInBottomEdge(x2, y, edgeSize) {
return isInRectangle(x2, y, this.x, this.bottom - edgeSize, this.width, edgeSize);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the left edge of this rectangle, otherwise `false`. */
isInLeftEdge(x2, y, edgeSize) {
return isInRectangle(x2, y, this.x, this.y, edgeSize, this.height);
}
/** @returns `true` if the point [{@link x}, {@link y}] is in the right edge of this rectangle, otherwise `false`. */
isInRightEdge(x2, y, edgeSize) {
return isInRectangle(x2, y, this.right - edgeSize, this.y, edgeSize, this.height);
}
/** @returns The centre point of this rectangle, as a new {@link Point}. */
getCentre() {
return [this.centreX, this.centreY];
}
/** @returns The area of this rectangle. */
getArea() {
return this.width * this.height;
}
/** @returns The perimeter of this rectangle. */
getPerimeter() {
return 2 * (this.width + this.height);
}
/** @returns The top-left corner of this rectangle, as a new {@link Point}. */
getTopLeft() {
return [this[0], this[1]];
}
/** @returns The bottom-right corner of this rectangle, as a new {@link Point}. */
getBottomRight() {
return [this.right, this.bottom];
}
/** @returns The width and height of this rectangle, as a new {@link Size}. */
getSize() {
return [this[2], this[3]];
}
/** @returns The offset from the top-left of this rectangle to the point [{@link x}, {@link y}], as a new {@link Point}. */
getOffsetTo([x2, y]) {
return [x2 - this[0], y - this[1]];
}
/** @returns The offset from the point [{@link x}, {@link y}] to the top-left of this rectangle, as a new {@link Point}. */
getOffsetFrom([x2, y]) {
return [this[0] - x2, this[1] - y];
}
/** Resizes the rectangle without moving it, setting its top-left corner to [{@link x}, {@link y}]. */
resizeTopLeft(x1, y1) {
this[2] += this[0] - x1;
this[3] += this[1] - y1;
this[0] = x1;
this[1] = y1;
}
/** Resizes the rectangle without moving it, setting its bottom-left corner to [{@link x}, {@link y}]. */
resizeBottomLeft(x1, y2) {
this[2] += this[0] - x1;
this[3] = y2 - this[1];
this[0] = x1;
}
/** Resizes the rectangle without moving it, setting its top-right corner to [{@link x}, {@link y}]. */
resizeTopRight(x2, y1) {
this[2] = x2 - this[0];
this[3] += this[1] - y1;
this[1] = y1;
}
/** Resizes the rectangle without moving it, setting its bottom-right corner to [{@link x}, {@link y}]. */
resizeBottomRight(x2, y2) {
this[2] = x2 - this[0];
this[3] = y2 - this[1];
}
/** Sets the width without moving the right edge (changes position) */
setWidthRightAnchored(width2) {
const currentWidth = this[2];
this[2] = width2;
this[0] += currentWidth - width2;
}
/** Sets the height without moving the bottom edge (changes position) */
setHeightBottomAnchored(height) {
const currentHeight = this[3];
this[3] = height;
this[1] += currentHeight - height;
}
/** Alias of {@link export}. */
toArray() {
return this.export();
}
/** @returns A new, untyped array (serializable) containing the values of this rectangle. */
export() {
return [this[0], this[1], this[2], this[3]];
}
/** Draws a debug outline of this rectangle. */
_drawDebug(ctx, colour = "red") {
const { strokeStyle, lineWidth } = ctx;
try {
ctx.strokeStyle = colour;
ctx.lineWidth = 0.5;
ctx.beginPath();
ctx.strokeRect(this[0], this[1], this[2], this[3]);
} finally {
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
}
}
}
class BaseWidget {
/** From node edge to widget edge */
static margin = 15;
/** From widget edge to tip of arrow button */
static arrowMargin = 6;
/** Arrow button width */
static arrowWidth = 10;
/** Absolute minimum display width of widget values */
static minValueWidth = 42;
/** Minimum gap between label and value */
static labelValueGap = 5;
#node;
/** The node that this widget belongs to. */
get node() {
return this.#node;
}
linkedWidgets;
name;
options;
label;
type;
y = 0;
last_y;
width;
disabled;
computedDisabled;
hidden;
advanced;
tooltip;
element;
#value;
get value() {
return this.#value;
}
set value(value) {
this.#value = value;
}
constructor(widget, node2) {
this.#node = node2 ?? widget.node;
this.name = widget.name;
this.options = widget.options;
this.type = widget.type;
const { node: _, outline_color, background_color, height, text_color, secondary_text_color, disabledTextColor, displayName, displayValue, labelBaseline, ...safeValues } = widget;
Object.assign(this, safeValues);
}
get outline_color() {
return this.advanced ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR : LiteGraph.WIDGET_OUTLINE_COLOR;
}
get background_color() {
return LiteGraph.WIDGET_BGCOLOR;
}
get height() {
return LiteGraph.NODE_WIDGET_HEIGHT;
}
get text_color() {
return LiteGraph.WIDGET_TEXT_COLOR;
}
get secondary_text_color() {
return LiteGraph.WIDGET_SECONDARY_TEXT_COLOR;
}
get disabledTextColor() {
return LiteGraph.WIDGET_DISABLED_TEXT_COLOR;
}
get displayName() {
return this.label || this.name;
}
// TODO: Resolve this workaround. Ref: https://github.com/Comfy-Org/litegraph.js/issues/1022
get _displayValue() {
return String(this.value);
}
get labelBaseline() {
return this.y + this.height * 0.7;
}
/**
* Draws the standard widget shape - elongated capsule. The path of the widget shape is not
* cleared, and may be used for further drawing.
* @param ctx The canvas context
* @param options The options for drawing the widget
* @remarks Leaves {@link ctx} dirty.
*/
drawWidgetShape(ctx, { width: width2, showText }) {
const { height, y } = this;
const { margin } = BaseWidget;
ctx.textAlign = "left";
ctx.strokeStyle = this.outline_color;
ctx.fillStyle = this.background_color;
ctx.beginPath();
if (showText) {
ctx.roundRect(margin, y, width2 - margin * 2, height, [height * 0.5]);
} else {
ctx.rect(margin, y, width2 - margin * 2, height);
}
ctx.fill();
if (showText && !this.computedDisabled) ctx.stroke();
}
/**
* A shared routine for drawing a label and value as text, truncated
* if they exceed the available width.
*/
drawTruncatingText({
ctx,
width: width2,
leftPadding = 5,
rightPadding = 20
}) {
const { height, y } = this;
const { margin } = BaseWidget;
const { displayName, _displayValue } = this;
const labelWidth = ctx.measureText(displayName).width;
const valueWidth = ctx.measureText(_displayValue).width;
const gap = BaseWidget.labelValueGap;
const x2 = margin * 2 + leftPadding;
const totalWidth = width2 - x2 - 2 * margin - rightPadding;
const requiredWidth = labelWidth + gap + valueWidth;
const area = new Rectangle(x2, y, totalWidth, height * 0.7);
ctx.fillStyle = this.secondary_text_color;
if (requiredWidth <= totalWidth) {
drawTextInArea({ ctx, text: displayName, area, align: "left" });
} else if (LiteGraph.truncateWidgetTextEvenly) {
const scale = (totalWidth - gap) / (requiredWidth - gap);
area.width = labelWidth * scale;
drawTextInArea({ ctx, text: displayName, area, align: "left" });
area.right = x2 + totalWidth;
area.setWidthRightAnchored(valueWidth * scale);
} else if (LiteGraph.truncateWidgetValuesFirst) {
const cappedLabelWidth = Math.min(labelWidth, totalWidth);
area.width = cappedLabelWidth;
drawTextInArea({ ctx, text: displayName, area, align: "left" });
area.right = x2 + totalWidth;
area.setWidthRightAnchored(Math.max(totalWidth - gap - cappedLabelWidth, 0));
} else {
const cappedValueWidth = Math.min(valueWidth, totalWidth);
area.width = Math.max(totalWidth - gap - cappedValueWidth, 0);
drawTextInArea({ ctx, text: displayName, area, align: "left" });
area.right = x2 + totalWidth;
area.setWidthRightAnchored(cappedValueWidth);
}
ctx.fillStyle = this.text_color;
drawTextInArea({ ctx, text: _displayValue, area, align: "right" });
}
/**
* Sets the value of the widget
* @param value The value to set
* @param options The options for setting the value
*/
setValue(value, { e: e2, node: node2, canvas: canvas2 }) {
const oldValue = this.value;
if (value === this.value) return;
const v2 = this.type === "number" ? Number(value) : value;
this.value = v2;
if (this.options?.property && node2.properties[this.options.property] !== void 0) {
node2.setProperty(this.options.property, v2);
}
const pos = canvas2.graph_mouse;
this.callback?.(this.value, canvas2, node2, pos, e2);
node2.onWidgetChanged?.(this.name ?? "", v2, oldValue, this);
if (node2.graph) node2.graph._version++;
}
}
class BooleanWidget extends BaseWidget {
type = "toggle";
drawWidget(ctx, {
width: width2,
showText = true
}) {
const { height, y } = this;
const { margin } = BaseWidget;
this.drawWidgetShape(ctx, { width: width2, showText });
ctx.fillStyle = this.value ? "#89A" : "#333";
ctx.beginPath();
ctx.arc(
width2 - margin * 2,
y + height * 0.5,
height * 0.36,
0,
Math.PI * 2
);
ctx.fill();
if (showText) {
this.drawLabel(ctx, margin * 2);
this.drawValue(ctx, width2 - 40);
}
}
drawLabel(ctx, x2) {
ctx.fillStyle = this.secondary_text_color;
const { displayName } = this;
if (displayName) ctx.fillText(displayName, x2, this.labelBaseline);
}
drawValue(ctx, x2) {
ctx.fillStyle = this.value ? this.text_color : this.secondary_text_color;
ctx.textAlign = "right";
const value = this.value ? this.options.on || "true" : this.options.off || "false";
ctx.fillText(value, x2, this.labelBaseline);
}
onClick(options) {
this.setValue(!this.value, options);
}
}
class ButtonWidget extends BaseWidget {
type = "button";
clicked;
constructor(widget, node2) {
super(widget, node2);
this.clicked ??= false;
}
/**
* Draws the widget
* @param ctx The canvas context
* @param options The options for drawing the widget
*/
drawWidget(ctx, {
width: width2,
showText = true
}) {
const { fillStyle, strokeStyle, textAlign } = ctx;
const { height, y } = this;
const { margin } = BaseWidget;
ctx.fillStyle = this.background_color;
if (this.clicked) {
ctx.fillStyle = "#AAA";
this.clicked = false;
}
ctx.fillRect(margin, y, width2 - margin * 2, height);
if (showText && !this.computedDisabled) {
ctx.strokeStyle = this.outline_color;
ctx.strokeRect(margin, y, width2 - margin * 2, height);
}
if (showText) this.drawLabel(ctx, width2 * 0.5);
Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
}
drawLabel(ctx, x2) {
ctx.textAlign = "center";
ctx.fillStyle = this.text_color;
ctx.fillText(this.displayName, x2, this.y + this.height * 0.7);
}
onClick({ e: e2, node: node2, canvas: canvas2 }) {
const pos = canvas2.graph_mouse;
this.clicked = true;
canvas2.setDirty(true);
this.callback?.(this, canvas2, node2, pos, e2);
}
}
class BaseSteppedWidget extends BaseWidget {
/**
* Draw the arrow buttons for the widget
* @param ctx The canvas rendering context
* @param width The width of the widget
*/
drawArrowButtons(ctx, width2) {
const { height, text_color, disabledTextColor, y } = this;
const { arrowMargin, arrowWidth, margin } = BaseWidget;
const arrowTipX = margin + arrowMargin;
const arrowInnerX = arrowTipX + arrowWidth;
ctx.fillStyle = this.canDecrement() ? text_color : disabledTextColor;
ctx.beginPath();
ctx.moveTo(arrowInnerX, y + 5);
ctx.lineTo(arrowTipX, y + height * 0.5);
ctx.lineTo(arrowInnerX, y + height - 5);
ctx.fill();
ctx.fillStyle = this.canIncrement() ? text_color : disabledTextColor;
ctx.beginPath();
ctx.moveTo(width2 - arrowInnerX, y + 5);
ctx.lineTo(width2 - arrowTipX, y + height * 0.5);
ctx.lineTo(width2 - arrowInnerX, y + height - 5);
ctx.fill();
}
drawWidget(ctx, options) {
const { fillStyle, strokeStyle, textAlign } = ctx;
this.drawWidgetShape(ctx, options);
if (options.showText) {
if (!this.computedDisabled) this.drawArrowButtons(ctx, options.width);
this.drawTruncatingText({ ctx, width: options.width });
}
Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
}
}
function toArray(values) {
return Array.isArray(values) ? values : Object.keys(values);
}
class ComboWidget extends BaseSteppedWidget {
type = "combo";
get _displayValue() {
const { values: rawValues } = this.options;
if (rawValues) {
const values = typeof rawValues === "function" ? rawValues() : rawValues;
if (values && !Array.isArray(values)) {
return values[this.value];
}
}
return typeof this.value === "number" ? String(this.value) : this.value;
}
#getValues(node2) {
const { values } = this.options;
if (values == null) throw new Error("[ComboWidget]: values is required");
return typeof values === "function" ? values(this, node2) : values;
}
/**
* Checks if the value is {@link Array.at at} the given index in the combo list.
* @param increment `true` if checking the use of the increment button, `false` for decrement
* @returns `true` if the value is at the given index, otherwise `false`.
*/
#canUseButton(increment) {
const { values } = this.options;
if (typeof values === "function") return false;
const valuesArray = toArray(values);
if (!(valuesArray.length > 1)) return false;
const firstValue = valuesArray.at(0);
const lastValue = valuesArray.at(-1);
if (firstValue === lastValue) return true;
return this.value !== (increment ? lastValue : firstValue);
}
/**
* Returns `true` if the current value is not the last value in the list.
* Handles edge case where the value is both the first and last item in the list.
*/
canIncrement() {
return this.#canUseButton(true);
}
canDecrement() {
return this.#canUseButton(false);
}
incrementValue(options) {
this.#tryChangeValue(1, options);
}
decrementValue(options) {
this.#tryChangeValue(-1, options);
}
#tryChangeValue(delta2, options) {
const values = this.#getValues(options.node);
const indexedValues = toArray(values);
options.canvas.last_mouseclick = 0;
const foundIndex = typeof values === "object" ? indexedValues.indexOf(String(this.value)) + delta2 : indexedValues.indexOf(this.value) + delta2;
const index = clamp(foundIndex, 0, indexedValues.length - 1);
const value = Array.isArray(values) ? values[index] : index;
this.setValue(value, options);
}
onClick({ e: e2, node: node2, canvas: canvas2 }) {
const x2 = e2.canvasX - node2.pos[0];
const width2 = this.width || node2.size[0];
if (typeof this.options.values === "function") {
warnDeprecated("Using a function for values is deprecated. Use an array of unique values instead.");
}
if (x2 < 40) return this.decrementValue({ e: e2, node: node2, canvas: canvas2 });
if (x2 > width2 - 40) return this.incrementValue({ e: e2, node: node2, canvas: canvas2 });
const values = this.#getValues(node2);
const values_list = toArray(values);
const text_values = values != values_list ? Object.values(values) : values;
new LiteGraph.ContextMenu(text_values, {
scale: Math.max(1, canvas2.ds.scale),
event: e2,
className: "dark",
callback: (value) => {
this.setValue(
values != values_list ? text_values.indexOf(value) : value,
{ e: e2, node: node2, canvas: canvas2 }
);
}
});
}
}
function getWidgetStep(options) {
return options.step2 || (options.step || 10) * 0.1;
}
class KnobWidget extends BaseWidget {
type = "knob";
/**
* Compute the layout size of the widget.
* @returns The layout size of the widget.
*/
computeLayoutSize() {
return {
minHeight: 60,
minWidth: 20,
maxHeight: 1e6,
maxWidth: 1e6
};
}
get height() {
return this.computedHeight || super.height;
}
drawWidget(ctx, {
width: width2,
showText = true
}) {
const { fillStyle, strokeStyle, textAlign } = ctx;
const { y } = this;
const { margin } = BaseWidget;
const { gradient_stops = "rgb(14, 182, 201); rgb(0, 216, 72)" } = this.options;
const effective_height = this.computedHeight || this.height;
const size_modifier = Math.min(this.computedHeight || this.height, this.width || 20) / 20;
const arc_center = { x: width2 / 2, y: effective_height / 2 + y };
ctx.lineWidth = (Math.min(width2, effective_height) - margin * size_modifier) / 6;
const arc_size = (Math.min(width2, effective_height) - margin * size_modifier - ctx.lineWidth) / 2;
{
const gradient2 = ctx.createRadialGradient(
arc_center.x,
arc_center.y,
arc_size + ctx.lineWidth,
0,
0,
arc_size + ctx.lineWidth
);
gradient2.addColorStop(0, "rgb(29, 29, 29)");
gradient2.addColorStop(1, "rgb(116, 116, 116)");
ctx.fillStyle = gradient2;
}
ctx.beginPath();
{
ctx.arc(
arc_center.x,
arc_center.y,
arc_size + ctx.lineWidth / 2,
0,
Math.PI * 2,
false
);
ctx.fill();
ctx.closePath();
}
const arc = {
start_angle: Math.PI * 0.6,
end_angle: Math.PI * 2.4
};
ctx.beginPath();
{
const gradient2 = ctx.createRadialGradient(
arc_center.x,
arc_center.y,
arc_size + ctx.lineWidth,
0,
0,
arc_size + ctx.lineWidth
);
gradient2.addColorStop(0, "rgb(99, 99, 99)");
gradient2.addColorStop(1, "rgb(36, 36, 36)");
ctx.strokeStyle = gradient2;
}
ctx.arc(
arc_center.x,
arc_center.y,
arc_size,
arc.start_angle,
arc.end_angle,
false
);
ctx.stroke();
ctx.closePath();
const range = this.options.max - this.options.min;
let nvalue = (this.value - this.options.min) / range;
nvalue = clamp(nvalue, 0, 1);
ctx.beginPath();
const gradient = ctx.createConicGradient(
arc.start_angle,
arc_center.x,
arc_center.y
);
const gs = gradient_stops.split(";");
for (const [index, stop] of gs.entries()) {
gradient.addColorStop(index, stop.trim());
}
ctx.strokeStyle = gradient;
const value_end_angle = (arc.end_angle - arc.start_angle) * nvalue + arc.start_angle;
ctx.arc(
arc_center.x,
arc_center.y,
arc_size,
arc.start_angle,
value_end_angle,
false
);
ctx.stroke();
ctx.closePath();
if (showText && !this.computedDisabled) {
ctx.strokeStyle = this.outline_color;
ctx.beginPath();
ctx.strokeStyle = this.outline_color;
ctx.arc(
arc_center.x,
arc_center.y,
arc_size + ctx.lineWidth / 2,
0,
Math.PI * 2,
false
);
ctx.lineWidth = 1;
ctx.stroke();
ctx.closePath();
}
if (showText) {
ctx.textAlign = "center";
ctx.fillStyle = this.text_color;
const fixedValue = Number(this.value).toFixed(this.options.precision ?? 3);
ctx.fillText(
`${this.label || this.name}
${fixedValue}`,
width2 * 0.5,
y + effective_height * 0.5
);
}
Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
}
onClick() {
this.current_drag_offset = 0;
}
current_drag_offset = 0;
onDrag(options) {
if (this.options.read_only) return;
const { e: e2 } = options;
const step = getWidgetStep(this.options);
const range = this.options.max - this.options.min;
const range_10_percent = range / 10;
const range_1_percent = range / 100;
const step_for = {
shift: range_10_percent > step ? range_10_percent - range_10_percent % step : step,
delta_y: range_1_percent > step ? range_1_percent - range_1_percent % step : step
// 1% increments
};
const use_y = Math.abs(e2.movementY) > Math.abs(e2.movementX);
const delta2 = use_y ? -e2.movementY : e2.movementX;
const drag_threshold = 15;
this.current_drag_offset += delta2;
let adjustment = 0;
if (this.current_drag_offset > drag_threshold) {
adjustment += 1;
this.current_drag_offset -= drag_threshold;
} else if (this.current_drag_offset < -15) {
adjustment -= 1;
this.current_drag_offset += drag_threshold;
}
const step_with_shift_modifier = e2.shiftKey ? step_for.shift : use_y ? step_for.delta_y : step;
const deltaValue = adjustment * step_with_shift_modifier;
const newValue2 = clamp(
this.value + deltaValue,
this.options.min,
this.options.max
);
if (newValue2 !== this.value) {
this.setValue(newValue2, options);
}
}
}
class LegacyWidget extends BaseWidget {
drawWidget(ctx, options) {
const H = LiteGraph.NODE_WIDGET_HEIGHT;
this.draw?.(ctx, this.node, options.width, this.y, H, !!options.showText);
}
onClick() {
console.warn("Custom widget wrapper onClick was just called. Handling for third party widgets is done via LGraphCanvas - the mouse callback.");
}
}
class NumberWidget extends BaseSteppedWidget {
type = "number";
get _displayValue() {
return Number(this.value).toFixed(
this.options.precision !== void 0 ? this.options.precision : 3
);
}
canIncrement() {
const { max } = this.options;
return max == null || this.value < max;
}
canDecrement() {
const { min } = this.options;
return min == null || this.value > min;
}
incrementValue(options) {
this.setValue(this.value + getWidgetStep(this.options), options);
}
decrementValue(options) {
this.setValue(this.value - getWidgetStep(this.options), options);
}
setValue(value, options) {
let newValue2 = value;
if (this.options.min != null && newValue2 < this.options.min) {
newValue2 = this.options.min;
}
if (this.options.max != null && newValue2 > this.options.max) {
newValue2 = this.options.max;
}
super.setValue(newValue2, options);
}
onClick({ e, node, canvas }) {
const x = e.canvasX - node.pos[0];
const width = this.width || node.size[0];
const delta = x < 40 ? -1 : x > width - 40 ? 1 : 0;
if (delta) {
this.setValue(this.value + delta * getWidgetStep(this.options), { e, node, canvas });
return;
}
canvas.prompt("Value", this.value, (v) => {
if (/^[\d\s()*+/-]+|\d+\.\d+$/.test(v)) {
try {
v = eval(v);
} catch {
}
}
const newValue = Number(v);
if (!isNaN(newValue)) {
this.setValue(newValue, { e, node, canvas });
}
}, e);
}
/**
* Handles drag events for the number widget
* @param options The options for handling the drag event
*/
onDrag({ e: e2, node: node2, canvas: canvas2 }) {
const width2 = this.width || node2.width;
const x2 = e2.canvasX - node2.pos[0];
const delta2 = x2 < 40 ? -1 : x2 > width2 - 40 ? 1 : 0;
if (delta2 && (x2 > -3 && x2 < width2 + 3)) return;
this.setValue(this.value + (e2.deltaX ?? 0) * getWidgetStep(this.options), { e: e2, node: node2, canvas: canvas2 });
}
}
class SliderWidget extends BaseWidget {
type = "slider";
marker;
/**
* Draws the widget
* @param ctx The canvas context
* @param options The options for drawing the widget
*/
drawWidget(ctx, {
width: width2,
showText = true
}) {
const { fillStyle, strokeStyle, textAlign } = ctx;
const { height, y } = this;
const { margin } = BaseWidget;
ctx.fillStyle = this.background_color;
ctx.fillRect(margin, y, width2 - margin * 2, height);
const range = this.options.max - this.options.min;
let nvalue = (this.value - this.options.min) / range;
nvalue = clamp(nvalue, 0, 1);
ctx.fillStyle = this.options.slider_color ?? "#678";
ctx.fillRect(margin, y, nvalue * (width2 - margin * 2), height);
if (showText && !this.computedDisabled) {
ctx.strokeStyle = this.outline_color;
ctx.strokeRect(margin, y, width2 - margin * 2, height);
}
if (this.marker != null) {
let marker_nvalue = (this.marker - this.options.min) / range;
marker_nvalue = clamp(marker_nvalue, 0, 1);
ctx.fillStyle = this.options.marker_color ?? "#AA9";
ctx.fillRect(
margin + marker_nvalue * (width2 - margin * 2),
y,
2,
height
);
}
if (showText) {
ctx.textAlign = "center";
ctx.fillStyle = this.text_color;
const fixedValue = Number(this.value).toFixed(this.options.precision ?? 3);
ctx.fillText(
`${this.label || this.name} ${fixedValue}`,
width2 * 0.5,
y + height * 0.7
);
}
Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
}
/**
* Handles click events for the slider widget
*/
onClick(options) {
if (this.options.read_only) return;
const { e: e2, node: node2 } = options;
const width2 = this.width || node2.size[0];
const x2 = e2.canvasX - node2.pos[0];
const slideFactor = clamp((x2 - 15) / (width2 - 30), 0, 1);
const newValue2 = this.options.min + (this.options.max - this.options.min) * slideFactor;
if (newValue2 !== this.value) {
this.setValue(newValue2, options);
}
}
/**
* Handles drag events for the slider widget
*/
onDrag(options) {
if (this.options.read_only) return false;
const { e: e2, node: node2 } = options;
const width2 = this.width || node2.size[0];
const x2 = e2.canvasX - node2.pos[0];
const slideFactor = clamp((x2 - 15) / (width2 - 30), 0, 1);
const newValue2 = this.options.min + (this.options.max - this.options.min) * slideFactor;
if (newValue2 !== this.value) {
this.setValue(newValue2, options);
}
}
}
class TextWidget extends BaseWidget {
constructor(widget, node2) {
super(widget, node2);
this.type ??= "string";
this.value = widget.value?.toString() ?? "";
}
/**
* Draws the widget
* @param ctx The canvas context
* @param options The options for drawing the widget
*/
drawWidget(ctx, {
width: width2,
showText = true
}) {
const { fillStyle, strokeStyle, textAlign } = ctx;
this.drawWidgetShape(ctx, { width: width2, showText });
if (showText) {
this.drawTruncatingText({ ctx, width: width2, leftPadding: 0, rightPadding: 0 });
}
Object.assign(ctx, { textAlign, strokeStyle, fillStyle });
}
onClick({ e: e2, node: node2, canvas: canvas2 }) {
canvas2.prompt(
"Value",
this.value,
(v2) => {
if (v2 !== null) {
this.setValue(v2, { e: e2, node: node2, canvas: canvas2 });
}
},
e2,
this.options?.multiline ?? false
);
}
}
function toConcreteWidget(widget, node2, wrapLegacyWidgets = true) {
if (widget instanceof BaseWidget) return widget;
const narrowedWidget = widget;
switch (narrowedWidget.type) {
case "button":
return toClass(ButtonWidget, narrowedWidget, node2);
case "toggle":
return toClass(BooleanWidget, narrowedWidget, node2);
case "slider":
return toClass(SliderWidget, narrowedWidget, node2);
case "knob":
return toClass(KnobWidget, narrowedWidget, node2);
case "combo":
return toClass(ComboWidget, narrowedWidget, node2);
case "number":
return toClass(NumberWidget, narrowedWidget, node2);
case "string":
return toClass(TextWidget, narrowedWidget, node2);
case "text":
return toClass(TextWidget, narrowedWidget, node2);
default: {
if (wrapLegacyWidgets) return toClass(LegacyWidget, widget, node2);
}
}
}
function isComboWidget(widget) {
return widget.type === "combo";
}
class LGraphNode {
// Static properties used by dynamic child classes
static title;
static MAX_CONSOLE;
static type;
static category;
static filter;
static skip_list;
static resizeHandleSize = 15;
static resizeEdgeSize = 5;
/** Default setting for {@link LGraphNode.connectInputToOutput}. @see {@link INodeFlags.keepAllLinksOnBypass} */
static keepAllLinksOnBypass = false;
/** The title text of the node. */
title;
/**
* The font style used to render the node's title text.
*/
get titleFontStyle() {
return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
}
get innerFontStyle() {
return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
}
graph = null;
id;
type = "";
inputs = [];
outputs = [];
#concreteInputs = [];
#concreteOutputs = [];
properties = {};
properties_info = [];
flags = {};
widgets;
/**
* The amount of space available for widgets to grow into.
* @see {@link layoutWidgets}
*/
freeWidgetSpace;
locked;
/** Execution order, automatically computed during run @see {@link LGraph.computeExecutionOrder} */
order = 0;
mode = LGraphEventMode.ALWAYS;
last_serialization;
serialize_widgets;
/**
* The overridden fg color used to render the node.
* @see {@link renderingColor}
*/
color;
/**
* The overridden bg color used to render the node.
* @see {@link renderingBgColor}
*/
bgcolor;
/**
* The overridden box color used to render the node.
* @see {@link renderingBoxColor}
*/
boxcolor;
/** The fg color used to render the node. */
get renderingColor() {
return this.color || this.constructor.color || LiteGraph.NODE_DEFAULT_COLOR;
}
/** The bg color used to render the node. */
get renderingBgColor() {
return this.bgcolor || this.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR;
}
/** The box color used to render the node. */
get renderingBoxColor() {
if (this.boxcolor) return this.boxcolor;
if (LiteGraph.node_box_coloured_when_on) {
if (this.action_triggered) return "#FFF";
if (this.execute_triggered) return "#AAA";
}
if (LiteGraph.node_box_coloured_by_mode) {
const modeColour = LiteGraph.NODE_MODES_COLORS[this.mode ?? LGraphEventMode.ALWAYS];
if (modeColour) return modeColour;
}
return LiteGraph.NODE_DEFAULT_BOXCOLOR;
}
/** @inheritdoc {@link IColorable.setColorOption} */
setColorOption(colorOption) {
if (colorOption == null) {
delete this.color;
delete this.bgcolor;
} else {
this.color = colorOption.color;
this.bgcolor = colorOption.bgcolor;
}
}
/** @inheritdoc {@link IColorable.getColorOption} */
getColorOption() {
return Object.values(LGraphCanvas.node_colors).find(
(colorOption) => colorOption.color === this.color && colorOption.bgcolor === this.bgcolor
) ?? null;
}
/**
* The stroke styles that should be applied to the node.
*/
strokeStyles;
/**
* The progress of node execution. Used to render a progress bar. Value between 0 and 1.
*/
progress;
exec_version;
action_call;
execute_triggered;
action_triggered;
widgets_up;
widgets_start_y;
lostFocusAt;
gotFocusAt;
badges = [];
badgePosition = BadgePosition.TopLeft;
/**
* The width of the node when collapsed.
* Updated by {@link LGraphCanvas.drawNode}
*/
_collapsed_width;
console;
_level;
_shape;
mouseOver;
redraw_on_mouse;
resizable;
clonable;
_relative_id;
clip_area;
ignore_remove;
has_errors;
removable;
block_delete;
selected;
showAdvanced;
/** @inheritdoc {@link renderArea} */
#renderArea = new Float32Array(4);
/**
* Rect describing the node area, including shadows and any protrusions.
* Determines if the node is visible. Calculated once at the start of every frame.
*/
get renderArea() {
return this.#renderArea;
}
/** @inheritdoc {@link boundingRect} */
#boundingRect = new Rectangle();
/**
* Cached node position & area as `x, y, width, height`. Includes changes made by {@link onBounding}, if present.
*
* Determines the node hitbox and other rendering effects. Calculated once at the start of every frame.
*/
get boundingRect() {
return this.#boundingRect;
}
/** {@link pos} and {@link size} values are backed by this {@link Rect}. */
_posSize = new Float32Array(4);
_pos = this._posSize.subarray(0, 2);
_size = this._posSize.subarray(2, 4);
get pos() {
return this._pos;
}
/** Node position does not necessarily correlate to the top-left corner. */
set pos(value) {
if (!value || value.length < 2) return;
this._pos[0] = value[0];
this._pos[1] = value[1];
}
get size() {
return this._size;
}
set size(value) {
if (!value || value.length < 2) return;
this._size[0] = value[0];
this._size[1] = value[1];
}
/**
* The size of the node used for rendering.
*/
get renderingSize() {
return this.flags.collapsed ? [this._collapsed_width ?? 0, 0] : this._size;
}
get shape() {
return this._shape;
}
set shape(v2) {
switch (v2) {
case "default":
delete this._shape;
break;
case "box":
this._shape = RenderShape.BOX;
break;
case "round":
this._shape = RenderShape.ROUND;
break;
case "circle":
this._shape = RenderShape.CIRCLE;
break;
case "card":
this._shape = RenderShape.CARD;
break;
default:
this._shape = v2;
}
}
/**
* The shape of the node used for rendering. @see {@link RenderShape}
*/
get renderingShape() {
return this._shape || this.constructor.shape || LiteGraph.NODE_DEFAULT_SHAPE;
}
get is_selected() {
return this.selected;
}
set is_selected(value) {
this.selected = value;
}
get title_mode() {
return this.constructor.title_mode ?? TitleMode.NORMAL_TITLE;
}
#getErrorStrokeStyle() {
if (this.has_errors) {
return {
padding: 12,
lineWidth: 10,
color: LiteGraph.NODE_ERROR_COLOUR
};
}
}
#getSelectedStrokeStyle() {
if (this.selected) {
return {
padding: this.has_errors ? 20 : void 0
};
}
}
constructor(title, type) {
this.id = LiteGraph.use_uuids ? LiteGraph.uuidv4() : -1;
this.title = title || "Unnamed";
this.type = type ?? "";
this.size = [LiteGraph.NODE_WIDTH, 60];
this.pos = [10, 10];
this.strokeStyles = {
error: this.#getErrorStrokeStyle,
selected: this.#getSelectedStrokeStyle
};
}
/**
* configure a node from an object containing the serialized info
*/
configure(info) {
if (this.graph) {
this.graph._version++;
}
for (const j in info) {
if (j == "properties") {
for (const k in info.properties) {
this.properties[k] = info.properties[k];
this.onPropertyChanged?.(k, info.properties[k]);
}
continue;
}
if (info[j] == null) {
continue;
} else if (typeof info[j] == "object") {
if (this[j]?.configure) {
this[j]?.configure(info[j]);
} else {
this[j] = LiteGraph.cloneObject(info[j], this[j]);
}
} else {
this[j] = info[j];
}
}
if (!info.title) {
this.title = this.constructor.title;
}
this.inputs ??= [];
this.inputs = this.inputs.map((input) => toClass(NodeInputSlot, input, this));
for (const [i, input] of this.inputs.entries()) {
const link = this.graph && input.link != null ? this.graph._links.get(input.link) : null;
this.onConnectionsChange?.(NodeSlotType.INPUT, i, true, link, input);
this.onInputAdded?.(input);
}
this.outputs ??= [];
this.outputs = this.outputs.map((output) => toClass(NodeOutputSlot, output, this));
for (const [i, output] of this.outputs.entries()) {
if (!output.links) continue;
for (const linkId of output.links) {
const link = this.graph ? this.graph._links.get(linkId) : null;
this.onConnectionsChange?.(NodeSlotType.OUTPUT, i, true, link, output);
}
this.onOutputAdded?.(output);
}
if (this.widgets) {
for (const w of this.widgets) {
if (!w) continue;
if (w.options?.property && this.properties[w.options.property] != void 0)
w.value = JSON.parse(JSON.stringify(this.properties[w.options.property]));
}
if (info.widgets_values) {
const widgetsWithValue = this.widgets.filter((w) => w.serialize !== false);
for (let i = 0; i < info.widgets_values.length; ++i) {
const widget = widgetsWithValue[i];
if (widget) {
widget.value = info.widgets_values[i];
}
}
}
}
if (this.pinned) this.resizable = false;
this.onConfigure?.(info);
}
/**
* serialize the content
*/
serialize() {
const o = {
id: this.id,
type: this.type,
pos: [this.pos[0], this.pos[1]],
size: [this.size[0], this.size[1]],
flags: LiteGraph.cloneObject(this.flags),
order: this.order,
mode: this.mode,
showAdvanced: this.showAdvanced
};
if (this.constructor === LGraphNode && this.last_serialization)
return this.last_serialization;
if (this.inputs) o.inputs = this.inputs.map((input) => inputAsSerialisable(input));
if (this.outputs) o.outputs = this.outputs.map((output) => outputAsSerialisable(output));
if (this.title && this.title != this.constructor.title) o.title = this.title;
if (this.properties) o.properties = LiteGraph.cloneObject(this.properties);
const { widgets } = this;
if (widgets && this.serialize_widgets) {
o.widgets_values = [];
for (const [i, widget] of widgets.entries()) {
if (widget.serialize === false) continue;
o.widgets_values[i] = widget ? widget.value : null;
}
}
if (!o.type) o.type = this.constructor.type;
if (this.color) o.color = this.color;
if (this.bgcolor) o.bgcolor = this.bgcolor;
if (this.boxcolor) o.boxcolor = this.boxcolor;
if (this.shape) o.shape = this.shape;
if (this.onSerialize?.(o)) console.warn("node onSerialize shouldnt return anything, data should be stored in the object pass in the first parameter");
return o;
}
/* Creates a clone of this node */
clone() {
if (this.type == null) return null;
const node2 = LiteGraph.createNode(this.type);
if (!node2) return null;
const data = LiteGraph.cloneObject(this.serialize());
const { inputs, outputs } = data;
if (inputs) {
for (const input of inputs) {
input.link = null;
}
}
if (outputs) {
for (const { links } of outputs) {
if (links) links.length = 0;
}
}
delete data.id;
if (LiteGraph.use_uuids) data.id = LiteGraph.uuidv4();
node2.configure(data);
return node2;
}
/**
* serialize and stringify
*/
toString() {
return JSON.stringify(this.serialize());
}
/**
* get the title string
*/
getTitle() {
return this.title || this.constructor.title;
}
/**
* sets the value of a property
* @param name
* @param value
*/
setProperty(name, value) {
this.properties ||= {};
if (value === this.properties[name]) return;
const prev_value = this.properties[name];
this.properties[name] = value;
if (this.onPropertyChanged?.(name, value, prev_value) === false)
this.properties[name] = prev_value;
if (this.widgets) {
for (const w of this.widgets) {
if (!w) continue;
if (w.options.property == name) {
w.value = value;
break;
}
}
}
}
/**
* sets the output data
* @param slot
* @param data
*/
setOutputData(slot, data) {
const { outputs } = this;
if (!outputs) return;
if (slot == -1 || slot >= outputs.length) return;
const output_info = outputs[slot];
if (!output_info) return;
output_info._data = data;
if (!this.graph) throw new NullGraphError();
const { links } = outputs[slot];
if (links) {
for (const id of links) {
const link = this.graph._links.get(id);
if (link) link.data = data;
}
}
}
/**
* sets the output data type, useful when you want to be able to overwrite the data type
*/
setOutputDataType(slot, type) {
const { outputs } = this;
if (!outputs || (slot == -1 || slot >= outputs.length)) return;
const output_info = outputs[slot];
if (!output_info) return;
output_info.type = type;
if (!this.graph) throw new NullGraphError();
const { links } = outputs[slot];
if (links) {
for (const id of links) {
const link = this.graph._links.get(id);
if (link) link.type = type;
}
}
}
/**
* Retrieves the input data (data traveling through the connection) from one slot
* @param slot
* @param force_update if set to true it will force the connected node of this slot to output data into this link
* @returns data or if it is not connected returns undefined
*/
getInputData(slot, force_update) {
if (!this.inputs) return;
if (slot >= this.inputs.length || this.inputs[slot].link == null) return;
if (!this.graph) throw new NullGraphError();
const link_id = this.inputs[slot].link;
const link = this.graph._links.get(link_id);
if (!link) return null;
if (!force_update) return link.data;
const node2 = this.graph.getNodeById(link.origin_id);
if (!node2) return link.data;
if (node2.updateOutputData) {
node2.updateOutputData(link.origin_slot);
} else {
node2.onExecute?.();
}
return link.data;
}
/**
* Retrieves the input data type (in case this supports multiple input types)
* @param slot
* @returns datatype in string format
*/
getInputDataType(slot) {
if (!this.inputs) return null;
if (slot >= this.inputs.length || this.inputs[slot].link == null) return null;
if (!this.graph) throw new NullGraphError();
const link_id = this.inputs[slot].link;
const link = this.graph._links.get(link_id);
if (!link) return null;
const node2 = this.graph.getNodeById(link.origin_id);
if (!node2) return link.type;
const output_info = node2.outputs[link.origin_slot];
return output_info ? output_info.type : null;
}
/**
* Retrieves the input data from one slot using its name instead of slot number
* @param slot_name
* @param force_update if set to true it will force the connected node of this slot to output data into this link
* @returns data or if it is not connected returns null
*/
getInputDataByName(slot_name, force_update) {
const slot = this.findInputSlot(slot_name);
return slot == -1 ? null : this.getInputData(slot, force_update);
}
/**
* tells you if there is a connection in one input slot
* @param slot The 0-based index of the input to check
* @returns `true` if the input slot has a link ID (does not perform validation)
*/
isInputConnected(slot) {
if (!this.inputs) return false;
return slot < this.inputs.length && this.inputs[slot].link != null;
}
/**
* tells you info about an input connection (which node, type, etc)
* @returns object or null { link: id, name: string, type: string or 0 }
*/
getInputInfo(slot) {
return !this.inputs || !(slot < this.inputs.length) ? null : this.inputs[slot];
}
/**
* Returns the link info in the connection of an input slot
* @returns object or null
*/
getInputLink(slot) {
if (!this.inputs) return null;
if (slot < this.inputs.length) {
if (!this.graph) throw new NullGraphError();
const input = this.inputs[slot];
if (input.link != null) {
return this.graph._links.get(input.link) ?? null;
}
}
return null;
}
/**
* returns the node connected in the input slot
* @returns node or null
*/
getInputNode(slot) {
if (!this.inputs) return null;
if (slot >= this.inputs.length) return null;
const input = this.inputs[slot];
if (!input || input.link === null) return null;
if (!this.graph) throw new NullGraphError();
const link_info = this.graph._links.get(input.link);
if (!link_info) return null;
return this.graph.getNodeById(link_info.origin_id);
}
/**
* returns the value of an input with this name, otherwise checks if there is a property with that name
* @returns value
*/
getInputOrProperty(name) {
const { inputs } = this;
if (!inputs?.length) {
return this.properties ? this.properties[name] : null;
}
if (!this.graph) throw new NullGraphError();
for (const input of inputs) {
if (name == input.name && input.link != null) {
const link = this.graph._links.get(input.link);
if (link) return link.data;
}
}
return this.properties[name];
}
/**
* tells you the last output data that went in that slot
* @returns object or null
*/
getOutputData(slot) {
if (!this.outputs) return null;
if (slot >= this.outputs.length) return null;
const info = this.outputs[slot];
return info._data;
}
/**
* tells you info about an output connection (which node, type, etc)
* @returns object or null { name: string, type: string, links: [ ids of links in number ] }
*/
getOutputInfo(slot) {
return !this.outputs || !(slot < this.outputs.length) ? null : this.outputs[slot];
}
/**
* tells you if there is a connection in one output slot
*/
isOutputConnected(slot) {
if (!this.outputs) return false;
return slot < this.outputs.length && Number(this.outputs[slot].links?.length) > 0;
}
/**
* tells you if there is any connection in the output slots
*/
isAnyOutputConnected() {
const { outputs } = this;
if (!outputs) return false;
for (const output of outputs) {
if (output.links?.length) return true;
}
return false;
}
/**
* retrieves all the nodes connected to this output slot
*/
getOutputNodes(slot) {
const { outputs } = this;
if (!outputs || outputs.length == 0) return null;
if (slot >= outputs.length) return null;
const { links } = outputs[slot];
if (!links || links.length == 0) return null;
if (!this.graph) throw new NullGraphError();
const r = [];
for (const id of links) {
const link = this.graph._links.get(id);
if (link) {
const target_node = this.graph.getNodeById(link.target_id);
if (target_node) {
r.push(target_node);
}
}
}
return r;
}
addOnTriggerInput() {
const trigS = this.findInputSlot("onTrigger");
if (trigS == -1) {
this.addInput("onTrigger", LiteGraph.EVENT, {
nameLocked: true
});
return this.findInputSlot("onTrigger");
}
return trigS;
}
addOnExecutedOutput() {
const trigS = this.findOutputSlot("onExecuted");
if (trigS == -1) {
this.addOutput("onExecuted", LiteGraph.ACTION, {
nameLocked: true
});
return this.findOutputSlot("onExecuted");
}
return trigS;
}
onAfterExecuteNode(param, options) {
const trigS = this.findOutputSlot("onExecuted");
if (trigS != -1) {
this.triggerSlot(trigS, param, null, options);
}
}
changeMode(modeTo) {
switch (modeTo) {
case LGraphEventMode.ON_EVENT:
break;
case LGraphEventMode.ON_TRIGGER:
this.addOnTriggerInput();
this.addOnExecutedOutput();
break;
case LGraphEventMode.NEVER:
break;
case LGraphEventMode.ALWAYS:
break;
// @ts-expect-error Not impl.
case LiteGraph.ON_REQUEST:
break;
default:
return false;
}
this.mode = modeTo;
return true;
}
/**
* Triggers the node code execution, place a boolean/counter to mark the node as being executed
*/
doExecute(param, options) {
options = options || {};
if (this.onExecute) {
options.action_call ||= `${this.id}_exec_${Math.floor(Math.random() * 9999)}`;
if (!this.graph) throw new NullGraphError();
this.graph.nodes_executing[this.id] = true;
this.onExecute(param, options);
this.graph.nodes_executing[this.id] = false;
this.exec_version = this.graph.iteration;
if (options?.action_call) {
this.action_call = options.action_call;
this.graph.nodes_executedAction[this.id] = options.action_call;
}
}
this.execute_triggered = 2;
this.onAfterExecuteNode?.(param, options);
}
/**
* Triggers an action, wrapped by logics to control execution flow
* @param action name
*/
actionDo(action, param, options) {
options = options || {};
if (this.onAction) {
options.action_call ||= `${this.id}_${action || "action"}_${Math.floor(Math.random() * 9999)}`;
if (!this.graph) throw new NullGraphError();
this.graph.nodes_actioning[this.id] = action || "actioning";
this.onAction(action, param, options);
this.graph.nodes_actioning[this.id] = false;
if (options?.action_call) {
this.action_call = options.action_call;
this.graph.nodes_executedAction[this.id] = options.action_call;
}
}
this.action_triggered = 2;
this.onAfterExecuteNode?.(param, options);
}
/**
* Triggers an event in this node, this will trigger any output with the same name
* @param action name ( "on_play", ... ) if action is equivalent to false then the event is send to all
*/
trigger(action, param, options) {
const { outputs } = this;
if (!outputs || !outputs.length) {
return;
}
if (this.graph) this.graph._last_trigger_time = LiteGraph.getTime();
for (const [i, output] of outputs.entries()) {
if (!output || output.type !== LiteGraph.EVENT || action && output.name != action) {
continue;
}
this.triggerSlot(i, param, null, options);
}
}
/**
* Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes
* @param slot the index of the output slot
* @param link_id [optional] in case you want to trigger and specific output link in a slot
*/
triggerSlot(slot, param, link_id, options) {
options = options || {};
if (!this.outputs) return;
if (slot == null) {
console.error("slot must be a number");
return;
}
if (typeof slot !== "number")
console.warn("slot must be a number, use node.trigger('name') if you want to use a string");
const output = this.outputs[slot];
if (!output) return;
const links = output.links;
if (!links || !links.length) return;
if (!this.graph) throw new NullGraphError();
this.graph._last_trigger_time = LiteGraph.getTime();
for (const id of links) {
if (link_id != null && link_id != id) continue;
const link_info = this.graph._links.get(id);
if (!link_info) continue;
link_info._last_time = LiteGraph.getTime();
const node2 = this.graph.getNodeById(link_info.target_id);
if (!node2) continue;
if (node2.mode === LGraphEventMode.ON_TRIGGER) {
if (!options.action_call)
options.action_call = `${this.id}_trigg_${Math.floor(Math.random() * 9999)}`;
node2.doExecute?.(param, options);
} else if (node2.onAction) {
if (!options.action_call)
options.action_call = `${this.id}_act_${Math.floor(Math.random() * 9999)}`;
const target_connection = node2.inputs[link_info.target_slot];
node2.actionDo(target_connection.name, param, options);
}
}
}
/**
* clears the trigger slot animation
* @param slot the index of the output slot
* @param link_id [optional] in case you want to trigger and specific output link in a slot
*/
clearTriggeredSlot(slot, link_id) {
if (!this.outputs) return;
const output = this.outputs[slot];
if (!output) return;
const links = output.links;
if (!links || !links.length) return;
if (!this.graph) throw new NullGraphError();
for (const id of links) {
if (link_id != null && link_id != id) continue;
const link_info = this.graph._links.get(id);
if (!link_info) continue;
link_info._last_time = 0;
}
}
/**
* changes node size and triggers callback
*/
setSize(size) {
this.size = size;
this.onResize?.(this.size);
}
/**
* Expands the node size to fit its content.
*/
expandToFitContent() {
const newSize = this.computeSize();
this.setSize([
Math.max(this.size[0], newSize[0]),
Math.max(this.size[1], newSize[1])
]);
}
/**
* add a new property to this node
* @param type string defining the output type ("vec3","number",...)
* @param extra_info this can be used to have special properties of the property (like values, etc)
*/
addProperty(name, default_value, type, extra_info) {
const o = { name, type, default_value };
if (extra_info) Object.assign(o, extra_info);
this.properties_info ||= [];
this.properties_info.push(o);
this.properties ||= {};
this.properties[name] = default_value;
return o;
}
/**
* add a new output slot to use in this node
* @param type string defining the output type ("vec3","number",...)
* @param extra_info this can be used to have special properties of an output (label, special color, position, etc)
*/
addOutput(name, type, extra_info) {
const output = Object.assign(
new NodeOutputSlot({ name, type, links: null }, this),
extra_info
);
this.outputs ||= [];
this.outputs.push(output);
this.onOutputAdded?.(output);
if (LiteGraph.auto_load_slot_types)
LiteGraph.registerNodeAndSlotType(this, type, true);
this.expandToFitContent();
this.setDirtyCanvas(true, true);
return output;
}
/**
* remove an existing output slot
*/
removeOutput(slot) {
this.disconnectOutput(slot);
const { outputs } = this;
outputs.splice(slot, 1);
for (let i = slot; i < outputs.length; ++i) {
const output = outputs[i];
if (!output || !output.links) continue;
for (const linkId of output.links) {
if (!this.graph) throw new NullGraphError();
const link = this.graph._links.get(linkId);
if (link) link.origin_slot--;
}
}
this.onOutputRemoved?.(slot);
this.setDirtyCanvas(true, true);
}
/**
* add a new input slot to use in this node
* @param type string defining the input type ("vec3","number",...), it its a generic one use 0
* @param extra_info this can be used to have special properties of an input (label, color, position, etc)
*/
addInput(name, type, extra_info) {
type ||= 0;
const input = Object.assign(
new NodeInputSlot({ name, type, link: null }, this),
extra_info
);
this.inputs ||= [];
this.inputs.push(input);
this.expandToFitContent();
this.onInputAdded?.(input);
LiteGraph.registerNodeAndSlotType(this, type);
this.setDirtyCanvas(true, true);
return input;
}
/**
* remove an existing input slot
*/
removeInput(slot) {
this.disconnectInput(slot, true);
const { inputs } = this;
const slot_info = inputs.splice(slot, 1);
for (let i = slot; i < inputs.length; ++i) {
const input = inputs[i];
if (!input?.link) continue;
if (!this.graph) throw new NullGraphError();
const link = this.graph._links.get(input.link);
if (link) link.target_slot--;
}
this.onInputRemoved?.(slot, slot_info[0]);
this.setDirtyCanvas(true, true);
}
/**
* computes the minimum size of a node according to its inputs and output slots
* @returns the total size
*/
computeSize(out) {
const ctorSize = this.constructor.size;
if (ctorSize) return [ctorSize[0], ctorSize[1]];
const { inputs, outputs, widgets } = this;
let rows = Math.max(
inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1,
outputs ? outputs.length : 1
);
const size = out || new Float32Array([0, 0]);
rows = Math.max(rows, 1);
const font_size = LiteGraph.NODE_TEXT_SIZE;
const padLeft = LiteGraph.NODE_TITLE_HEIGHT;
const padRight = padLeft * 0.33;
const title_width = padLeft + compute_text_size(this.title, this.titleFontStyle) + padRight;
let input_width = 0;
let widgetWidth = 0;
let output_width = 0;
if (inputs) {
for (const input of inputs) {
const text = input.label || input.localized_name || input.name || "";
const text_width = compute_text_size(text, this.innerFontStyle);
if (isWidgetInputSlot(input)) {
const widget = this.getWidgetFromSlot(input);
if (widget && !this.isWidgetVisible(widget)) continue;
if (text_width > widgetWidth) widgetWidth = text_width;
} else {
if (text_width > input_width) input_width = text_width;
}
}
}
if (outputs) {
for (const output of outputs) {
const text = output.label || output.localized_name || output.name || "";
const text_width = compute_text_size(text, this.innerFontStyle);
if (output_width < text_width)
output_width = text_width;
}
}
const minWidth = LiteGraph.NODE_WIDTH * (widgets?.length ? 1.5 : 1);
const centrePadding = input_width && output_width ? 5 : 0;
const slotsWidth = input_width + output_width + 2 * LiteGraph.NODE_SLOT_HEIGHT + centrePadding;
const widgetMargin = BaseWidget.margin + BaseWidget.arrowMargin + BaseWidget.arrowWidth;
const widgetPadding = BaseWidget.minValueWidth + 2 * widgetMargin;
if (widgetWidth) widgetWidth += widgetPadding;
size[0] = Math.max(slotsWidth, widgetWidth, title_width, minWidth);
size[1] = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;
let widgets_height = 0;
if (widgets?.length) {
for (const widget of widgets) {
if (!this.isWidgetVisible(widget)) continue;
let widget_height = 0;
if (widget.computeSize) {
widget_height += widget.computeSize(size[0])[1];
} else if (widget.computeLayoutSize) {
const { minHeight, minWidth: minWidth2 } = widget.computeLayoutSize(this);
const widgetWidth2 = minWidth2 + widgetPadding;
if (widgetWidth2 > size[0]) size[0] = widgetWidth2;
widget_height += minHeight;
} else {
widget_height += LiteGraph.NODE_WIDGET_HEIGHT;
}
widgets_height += widget_height + 4;
}
widgets_height += 8;
}
if (this.widgets_up)
size[1] = Math.max(size[1], widgets_height);
else if (this.widgets_start_y != null)
size[1] = Math.max(size[1], widgets_height + this.widgets_start_y);
else
size[1] += widgets_height;
function compute_text_size(text, fontStyle) {
return LGraphCanvas._measureText?.(text, fontStyle) ?? font_size * (text?.length ?? 0) * 0.6;
}
if (this.constructor.min_height && size[1] < this.constructor.min_height) {
size[1] = this.constructor.min_height;
}
size[1] += 6;
return size;
}
inResizeCorner(canvasX, canvasY) {
const rows = this.outputs ? this.outputs.length : 1;
const outputs_offset = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;
return isInRectangle(
canvasX,
canvasY,
this.pos[0] + this.size[0] - 15,
this.pos[1] + Math.max(this.size[1] - 15, outputs_offset),
20,
20
);
}
/**
* Returns which resize corner the point is over, if any.
* @param canvasX X position in canvas coordinates
* @param canvasY Y position in canvas coordinates
* @returns The compass corner the point is in, otherwise `undefined`.
*/
findResizeDirection(canvasX, canvasY) {
if (this.resizable === false) return;
const { boundingRect } = this;
if (!boundingRect.containsXy(canvasX, canvasY)) return;
return boundingRect.findContainingCorner(canvasX, canvasY, LGraphNode.resizeHandleSize);
}
/**
* returns all the info available about a property of this node.
* @param property name of the property
* @returns the object with all the available info
*/
getPropertyInfo(property) {
let info = null;
const { properties_info } = this;
if (properties_info) {
for (const propInfo of properties_info) {
if (propInfo.name == property) {
info = propInfo;
break;
}
}
}
if (this.constructor[`@${property}`]) info = this.constructor[`@${property}`];
if (this.constructor.widgets_info?.[property])
info = this.constructor.widgets_info[property];
if (!info && this.onGetPropertyInfo) {
info = this.onGetPropertyInfo(property);
}
info ||= {};
info.type ||= typeof this.properties[property];
if (info.widget == "combo") info.type = "enum";
return info;
}
/**
* Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties
* @param type the widget type
* @param name the text to show on the widget
* @param value the default value
* @param callback function to call when it changes (optionally, it can be the name of the property to modify)
* @param options the object that contains special properties of this widget
* @returns the created widget object
*/
addWidget(type, name, value, callback, options) {
this.widgets ||= [];
if (!options && callback && typeof callback === "object") {
options = callback;
callback = null;
}
options ||= {};
if (typeof options === "string")
options = { property: options };
if (callback && typeof callback === "string") {
options.property = callback;
callback = null;
}
const w = {
// @ts-expect-error
type: type.toLowerCase(),
name,
value,
callback: typeof callback !== "function" ? void 0 : callback,
options,
y: 0
};
if (w.options.y !== void 0) {
w.y = w.options.y;
}
if (!callback && !w.options.callback && !w.options.property) {
console.warn("LiteGraph addWidget(...) without a callback or property assigned");
}
if (type == "combo" && !w.options.values) {
throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }";
}
const widget = this.addCustomWidget(w);
this.expandToFitContent();
return widget;
}
addCustomWidget(custom_widget) {
this.widgets ||= [];
const widget = toConcreteWidget(custom_widget, this, false) ?? custom_widget;
this.widgets.push(widget);
return widget;
}
move(deltaX, deltaY) {
if (this.pinned) return;
this.pos[0] += deltaX;
this.pos[1] += deltaY;
}
/**
* Internal method to measure the node for rendering. Prefer {@link boundingRect} where possible.
*
* Populates {@link out} with the results in graph space.
* Populates {@link _collapsed_width} with the collapsed width if the node is collapsed.
* Adjusts for title and collapsed status, but does not call {@link onBounding}.
* @param out `x, y, width, height` are written to this array.
* @param ctx The canvas context to use for measuring text.
*/
measure(out, ctx) {
const titleMode = this.title_mode;
const renderTitle = titleMode != TitleMode.TRANSPARENT_TITLE && titleMode != TitleMode.NO_TITLE;
const titleHeight = renderTitle ? LiteGraph.NODE_TITLE_HEIGHT : 0;
out[0] = this.pos[0];
out[1] = this.pos[1] + -titleHeight;
if (!this.flags?.collapsed) {
out[2] = this.size[0];
out[3] = this.size[1] + titleHeight;
} else {
ctx.font = this.innerFontStyle;
this._collapsed_width = Math.min(
this.size[0],
ctx.measureText(this.getTitle() ?? "").width + LiteGraph.NODE_TITLE_HEIGHT * 2
);
out[2] = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
out[3] = LiteGraph.NODE_TITLE_HEIGHT;
}
}
/**
* returns the bounding of the object, used for rendering purposes
* @param out {Float32Array[4]?} [optional] a place to store the output, to free garbage
* @param includeExternal {boolean?} [optional] set to true to
* include the shadow and connection points in the bounding calculation
* @returns the bounding box in format of [topleft_cornerx, topleft_cornery, width, height]
*/
getBounding(out, includeExternal) {
out ||= new Float32Array(4);
const rect = includeExternal ? this.renderArea : this.boundingRect;
out[0] = rect[0];
out[1] = rect[1];
out[2] = rect[2];
out[3] = rect[3];
return out;
}
/**
* Calculates the render area of this node, populating both {@link boundingRect} and {@link renderArea}.
* Called automatically at the start of every frame.
*/
updateArea(ctx) {
const bounds = this.#boundingRect;
this.measure(bounds, ctx);
this.onBounding?.(bounds);
const renderArea = this.#renderArea;
renderArea.set(bounds);
renderArea[0] -= 4;
renderArea[1] -= 4;
renderArea[2] += 6 + 4;
renderArea[3] += 5 + 4;
}
/**
* checks if a point is inside the shape of a node
*/
isPointInside(x2, y) {
return isInRect(x2, y, this.boundingRect);
}
/**
* Checks if the provided point is inside this node's collapse button area.
* @param x X co-ordinate to check
* @param y Y co-ordinate to check
* @returns true if the x,y point is in the collapse button area, otherwise false
*/
isPointInCollapse(x2, y) {
const squareLength = LiteGraph.NODE_TITLE_HEIGHT;
return isInRectangle(
x2,
y,
this.pos[0],
this.pos[1] - squareLength,
squareLength,
squareLength
);
}
/**
* Returns the input slot at the given position. Uses full 20 height, and approximates the label length.
* @param pos The graph co-ordinates to check
* @returns The input slot at the given position if found, otherwise `undefined`.
*/
getInputOnPos(pos) {
return getNodeInputOnPos(this, pos[0], pos[1])?.input;
}
/**
* Returns the output slot at the given position. Uses full 20x20 box for the slot.
* @param pos The graph co-ordinates to check
* @returns The output slot at the given position if found, otherwise `undefined`.
*/
getOutputOnPos(pos) {
return getNodeOutputOnPos(this, pos[0], pos[1])?.output;
}
/**
* Returns the input or output slot at the given position.
*
* Tries {@link getNodeInputOnPos} first, then {@link getNodeOutputOnPos}.
* @param pos The graph co-ordinates to check
* @returns The input or output slot at the given position if found, otherwise `undefined`.
*/
getSlotOnPos(pos) {
if (!isPointInRect(pos, this.boundingRect)) return;
return this.getInputOnPos(pos) ?? this.getOutputOnPos(pos);
}
/**
* @deprecated Use {@link getSlotOnPos} instead.
* checks if a point is inside a node slot, and returns info about which slot
* @param x
* @param y
* @returns if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] }
*/
getSlotInPosition(x2, y) {
const { inputs, outputs } = this;
if (inputs) {
for (const [i, input] of inputs.entries()) {
const pos = this.getInputPos(i);
if (isInRectangle(x2, y, pos[0] - 10, pos[1] - 10, 20, 20)) {
return { input, slot: i, link_pos: pos };
}
}
}
if (outputs) {
for (const [i, output] of outputs.entries()) {
const pos = this.getOutputPos(i);
if (isInRectangle(x2, y, pos[0] - 10, pos[1] - 10, 20, 20)) {
return { output, slot: i, link_pos: pos };
}
}
}
return null;
}
/**
* Gets the widget on this node at the given co-ordinates.
* @param canvasX X co-ordinate in graph space
* @param canvasY Y co-ordinate in graph space
* @returns The widget found, otherwise `null`
*/
getWidgetOnPos(canvasX, canvasY, includeDisabled = false) {
const { widgets, pos, size } = this;
if (!widgets?.length) return;
const x2 = canvasX - pos[0];
const y = canvasY - pos[1];
const nodeWidth = size[0];
for (const widget of widgets) {
if (widget.computedDisabled && !includeDisabled || !this.isWidgetVisible(widget)) {
continue;
}
const h = widget.computedHeight ?? widget.computeSize?.(nodeWidth)[1] ?? LiteGraph.NODE_WIDGET_HEIGHT;
const w = widget.width || nodeWidth;
if (widget.last_y !== void 0 && isInRectangle(x2, y, 6, widget.last_y, w - 12, h)) {
return widget;
}
}
}
findInputSlot(name, returnObj = false) {
const { inputs } = this;
if (!inputs) return -1;
for (const [i, input] of inputs.entries()) {
if (name == input.name) {
return !returnObj ? i : input;
}
}
return -1;
}
findOutputSlot(name, returnObj = false) {
const { outputs } = this;
if (!outputs) return -1;
for (const [i, output] of outputs.entries()) {
if (name == output.name) {
return !returnObj ? i : output;
}
}
return -1;
}
findInputSlotFree(optsIn) {
return this.#findFreeSlot(this.inputs, optsIn);
}
findOutputSlotFree(optsIn) {
return this.#findFreeSlot(this.outputs, optsIn);
}
/**
* Finds the next free slot
* @param slots The slots to search, i.e. this.inputs or this.outputs
*/
#findFreeSlot(slots, options) {
const defaults = {
returnObj: false,
typesNotAccepted: []
};
const opts = Object.assign(defaults, options || {});
const length = slots?.length;
if (!(length > 0)) return -1;
for (let i = 0; i < length; ++i) {
const slot = slots[i];
if (!slot || slot.link || slot.links?.length) continue;
if (opts.typesNotAccepted?.includes?.(slot.type)) continue;
return !opts.returnObj ? i : slot;
}
return -1;
}
findInputSlotByType(type, returnObj, preferFreeSlot, doNotUseOccupied) {
return this.#findSlotByType(
this.inputs,
type,
returnObj,
preferFreeSlot,
doNotUseOccupied
);
}
findOutputSlotByType(type, returnObj, preferFreeSlot, doNotUseOccupied) {
return this.#findSlotByType(
this.outputs,
type,
returnObj,
preferFreeSlot,
doNotUseOccupied
);
}
findSlotByType(input, type, returnObj, preferFreeSlot, doNotUseOccupied) {
return input ? this.#findSlotByType(
this.inputs,
type,
returnObj,
preferFreeSlot,
doNotUseOccupied
) : this.#findSlotByType(
this.outputs,
type,
returnObj,
preferFreeSlot,
doNotUseOccupied
);
}
/**
* Finds a matching slot from those provided, returning the slot itself or its index in {@link slots}.
* @param slots Slots to search (this.inputs or this.outputs)
* @param type Type of slot to look for
* @param returnObj If true, returns the slot itself. Otherwise, the index.
* @param preferFreeSlot Prefer a free slot, but if none are found, fall back to an occupied slot.
* @param doNotUseOccupied Do not fall back to occupied slots.
* @see {findSlotByType}
* @see {findOutputSlotByType}
* @see {findInputSlotByType}
* @returns If a match is found, the slot if returnObj is true, otherwise the index. If no matches are found, -1
*/
#findSlotByType(slots, type, returnObj, preferFreeSlot, doNotUseOccupied) {
const length = slots?.length;
if (!length) return -1;
if (type == "" || type == "*") type = 0;
const sourceTypes = String(type).toLowerCase().split(",");
let occupiedSlot = null;
for (let i = 0; i < length; ++i) {
const slot = slots[i];
const destTypes = slot.type == "0" || slot.type == "*" ? ["0"] : String(slot.type).toLowerCase().split(",");
for (const sourceType of sourceTypes) {
const source = sourceType == "_event_" ? LiteGraph.EVENT : sourceType;
for (const destType of destTypes) {
const dest = destType == "_event_" ? LiteGraph.EVENT : destType;
if (source == dest || source === "*" || dest === "*") {
if (preferFreeSlot && (slot.links?.length || slot.link != null)) {
occupiedSlot ??= returnObj ? slot : i;
continue;
}
return returnObj ? slot : i;
}
}
}
}
return doNotUseOccupied ? -1 : occupiedSlot ?? -1;
}
/**
* Determines the slot index to connect to when attempting to connect by type.
* @param findInputs If true, searches for an input. Otherwise, an output.
* @param node The node at the other end of the connection.
* @param slotType The type of slot at the other end of the connection.
* @param options Search restrictions to adhere to.
* @see {connectByType}
* @see {connectByTypeOutput}
*/
findConnectByTypeSlot(findInputs, node2, slotType, options) {
if (options && typeof options === "object") {
if ("firstFreeIfInputGeneralInCase" in options) options.wildcardToTyped = !!options.firstFreeIfInputGeneralInCase;
if ("firstFreeIfOutputGeneralInCase" in options) options.wildcardToTyped = !!options.firstFreeIfOutputGeneralInCase;
if ("generalTypeInCase" in options) options.typedToWildcard = !!options.generalTypeInCase;
}
const optsDef = {
createEventInCase: true,
wildcardToTyped: true,
typedToWildcard: true
};
const opts = Object.assign(optsDef, options);
if (!this.graph) throw new NullGraphError();
if (node2 && typeof node2 === "number") {
const nodeById = this.graph.getNodeById(node2);
if (!nodeById) return;
node2 = nodeById;
}
const slot = node2.findSlotByType(findInputs, slotType, false, true);
if (slot >= 0 && slot !== null) return slot;
if (opts.createEventInCase && slotType == LiteGraph.EVENT) {
if (findInputs) return -1;
if (LiteGraph.do_add_triggers_slots) return node2.addOnExecutedOutput();
}
if (opts.typedToWildcard) {
const generalSlot = node2.findSlotByType(findInputs, 0, false, true, true);
if (generalSlot >= 0) return generalSlot;
}
if (opts.wildcardToTyped && (slotType == 0 || slotType == "*" || slotType == "")) {
const opt = { typesNotAccepted: [LiteGraph.EVENT] };
const nonEventSlot = findInputs ? node2.findInputSlotFree(opt) : node2.findOutputSlotFree(opt);
if (nonEventSlot >= 0) return nonEventSlot;
}
}
/**
* Finds the first free output slot with any of the comma-delimited types in {@link type}.
*
* If no slots are free, falls back in order to:
* - The first free wildcard slot
* - The first occupied slot
* - The first occupied wildcard slot
* @param type The {@link ISlotType type} of slot to find
* @returns The index and slot if found, otherwise `undefined`.
*/
findOutputByType(type) {
return findFreeSlotOfType(this.outputs, type);
}
/**
* Finds the first free input slot with any of the comma-delimited types in {@link type}.
*
* If no slots are free, falls back in order to:
* - The first free wildcard slot
* - The first occupied slot
* - The first occupied wildcard slot
* @param type The {@link ISlotType type} of slot to find
* @returns The index and slot if found, otherwise `undefined`.
*/
findInputByType(type) {
return findFreeSlotOfType(this.inputs, type);
}
/**
* connect this node output to the input of another node BY TYPE
* @param slot (could be the number of the slot or the string with the name of the slot)
* @param target_node the target node
* @param target_slotType the input slot type of the target node
* @returns the link_info is created, otherwise null
*/
connectByType(slot, target_node, target_slotType, optsIn) {
const slotIndex = this.findConnectByTypeSlot(
true,
target_node,
target_slotType,
optsIn
);
if (slotIndex !== void 0)
return this.connect(slot, target_node, slotIndex, optsIn?.afterRerouteId);
console.debug("[connectByType]: no way to connect type:", target_slotType, "to node:", target_node);
return null;
}
/**
* connect this node input to the output of another node BY TYPE
* @param slot (could be the number of the slot or the string with the name of the slot)
* @param source_node the target node
* @param source_slotType the output slot type of the target node
* @returns the link_info is created, otherwise null
*/
connectByTypeOutput(slot, source_node, source_slotType, optsIn) {
if (typeof optsIn === "object") {
if ("firstFreeIfInputGeneralInCase" in optsIn) optsIn.wildcardToTyped = !!optsIn.firstFreeIfInputGeneralInCase;
if ("generalTypeInCase" in optsIn) optsIn.typedToWildcard = !!optsIn.generalTypeInCase;
}
const slotIndex = this.findConnectByTypeSlot(
false,
source_node,
source_slotType,
optsIn
);
if (slotIndex !== void 0)
return source_node.connect(slotIndex, this, slot, optsIn?.afterRerouteId);
console.debug("[connectByType]: no way to connect type:", source_slotType, "to node:", source_node);
return null;
}
canConnectTo(node2, toSlot, fromSlot) {
return this.id !== node2.id && LiteGraph.isValidConnection(fromSlot.type, toSlot.type);
}
/**
* Connect an output of this node to an input of another node
* @param slot (could be the number of the slot or the string with the name of the slot)
* @param target_node the target node
* @param target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger)
* @returns the link_info is created, otherwise null
*/
connect(slot, target_node, target_slot, afterRerouteId) {
let targetIndex;
const { graph, outputs } = this;
if (!graph) {
console.log("Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them.");
return null;
}
if (typeof slot === "string") {
slot = this.findOutputSlot(slot);
if (slot == -1) {
if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${slot}`);
return null;
}
} else if (!outputs || slot >= outputs.length) {
if (LiteGraph.debug) console.log("Connect: Error, slot number not found");
return null;
}
if (target_node && typeof target_node === "number") {
const nodeById = graph.getNodeById(target_node);
if (!nodeById) throw "target node is null";
target_node = nodeById;
}
if (!target_node) throw "target node is null";
if (target_node == this) return null;
if (typeof target_slot === "string") {
targetIndex = target_node.findInputSlot(target_slot);
if (targetIndex == -1) {
if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${targetIndex}`);
return null;
}
} else if (target_slot === LiteGraph.EVENT) {
if (LiteGraph.do_add_triggers_slots) {
target_node.changeMode(LGraphEventMode.ON_TRIGGER);
targetIndex = target_node.findInputSlot("onTrigger");
} else {
return null;
}
} else if (typeof target_slot === "number") {
targetIndex = target_slot;
} else {
targetIndex = 0;
}
if (target_node.onBeforeConnectInput) {
const requestedIndex = target_node.onBeforeConnectInput(targetIndex, target_slot);
targetIndex = typeof requestedIndex === "number" ? requestedIndex : null;
}
if (targetIndex === null || !target_node.inputs || targetIndex >= target_node.inputs.length) {
if (LiteGraph.debug) console.log("Connect: Error, slot number not found");
return null;
}
const input = target_node.inputs[targetIndex];
const output = outputs[slot];
if (!output) return null;
if (output.links?.length) {
if (output.type === LiteGraph.EVENT && !LiteGraph.allow_multi_output_for_events) {
graph.beforeChange();
this.disconnectOutput(slot, false, { doProcessChange: false });
}
}
const link = this.connectSlots(output, target_node, input, afterRerouteId);
return link ?? null;
}
/**
* Connect two slots between two nodes
* @param output The output slot to connect
* @param inputNode The node that the input slot is on
* @param input The input slot to connect
* @param afterRerouteId The reroute ID to use for the link
* @returns The link that was created, or null if the connection was blocked
*/
connectSlots(output, inputNode, input, afterRerouteId) {
const { graph } = this;
if (!graph) throw new NullGraphError();
const outputIndex = this.outputs.indexOf(output);
if (outputIndex === -1) {
console.warn("connectSlots: output not found");
return;
}
const inputIndex = inputNode.inputs.indexOf(input);
if (inputIndex === -1) {
console.warn("connectSlots: input not found");
return;
}
if (!LiteGraph.isValidConnection(output.type, input.type)) {
this.setDirtyCanvas(false, true);
return null;
}
if (inputNode.onConnectInput?.(inputIndex, output.type, output, this, outputIndex) === false)
return null;
if (this.onConnectOutput?.(outputIndex, input.type, input, inputNode, inputIndex) === false)
return null;
if (inputNode.inputs[inputIndex]?.link != null) {
graph.beforeChange();
inputNode.disconnectInput(inputIndex, true);
}
const link = new LLink(
++graph.state.lastLinkId,
input.type || output.type,
this.id,
outputIndex,
inputNode.id,
inputIndex,
afterRerouteId
);
graph._links.set(link.id, link);
output.links ??= [];
output.links.push(link.id);
inputNode.inputs[inputIndex].link = link.id;
const reroutes = LLink.getReroutes(graph, link);
for (const reroute of reroutes) {
reroute.linkIds.add(link.id);
if (reroute.floating) delete reroute.floating;
reroute._dragging = void 0;
}
const lastReroute = reroutes.at(-1);
if (lastReroute) {
for (const linkId of lastReroute.floatingLinkIds) {
const link2 = graph.floatingLinks.get(linkId);
if (link2?.parentId === lastReroute.id) {
graph.removeFloatingLink(link2);
}
}
}
graph._version++;
this.onConnectionsChange?.(
NodeSlotType.OUTPUT,
outputIndex,
true,
link,
output
);
inputNode.onConnectionsChange?.(
NodeSlotType.INPUT,
inputIndex,
true,
link,
input
);
this.setDirtyCanvas(false, true);
graph.afterChange();
graph.connectionChange(this);
return link;
}
connectFloatingReroute(pos, slot, afterRerouteId) {
const { graph, id } = this;
if (!graph) throw new NullGraphError();
const inputIndex = this.inputs.indexOf(slot);
const outputIndex = this.outputs.indexOf(slot);
if (inputIndex === -1 && outputIndex === -1) throw new Error("Invalid slot");
const slotType = outputIndex === -1 ? "input" : "output";
const reroute = graph.setReroute({
pos,
parentId: afterRerouteId,
linkIds: [],
floating: { slotType }
});
const parentReroute = graph.getReroute(afterRerouteId);
const fromLastFloatingReroute = parentReroute?.floating?.slotType === "output";
if (afterRerouteId == null || !fromLastFloatingReroute) {
const link2 = new LLink(
-1,
slot.type,
outputIndex === -1 ? -1 : id,
outputIndex,
inputIndex === -1 ? -1 : id,
inputIndex
);
link2.parentId = reroute.id;
graph.addFloatingLink(link2);
return reroute;
}
if (!parentReroute) throw new Error("[connectFloatingReroute] Parent reroute not found");
const link = parentReroute.getFloatingLinks("output")?.[0];
if (!link) throw new Error("[connectFloatingReroute] Floating link not found");
reroute.floatingLinkIds.add(link.id);
link.parentId = reroute.id;
delete parentReroute.floating;
return reroute;
}
/**
* disconnect one output to an specific node
* @param slot (could be the number of the slot or the string with the name of the slot)
* @param target_node the target node to which this slot is connected [Optional,
* if not target_node is specified all nodes will be disconnected]
* @returns if it was disconnected successfully
*/
disconnectOutput(slot, target_node) {
if (typeof slot === "string") {
slot = this.findOutputSlot(slot);
if (slot == -1) {
if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${slot}`);
return false;
}
} else if (!this.outputs || slot >= this.outputs.length) {
if (LiteGraph.debug) console.log("Connect: Error, slot number not found");
return false;
}
const output = this.outputs[slot];
if (!output) return false;
if (output._floatingLinks) {
for (const link of output._floatingLinks) {
if (link.hasOrigin(this.id, slot)) {
this.graph?.removeFloatingLink(link);
}
}
}
if (!output.links || output.links.length == 0) return false;
const { links } = output;
const graph = this.graph;
if (!graph) throw new NullGraphError();
if (target_node) {
const target = typeof target_node === "number" ? graph.getNodeById(target_node) : target_node;
if (!target) throw "Target Node not found";
for (const [i, link_id] of links.entries()) {
const link_info = graph._links.get(link_id);
if (link_info?.target_id != target.id) continue;
links.splice(i, 1);
const input = target.inputs[link_info.target_slot];
input.link = null;
link_info.disconnect(graph, "input");
graph._version++;
target.onConnectionsChange?.(
NodeSlotType.INPUT,
link_info.target_slot,
false,
link_info,
input
);
this.onConnectionsChange?.(
NodeSlotType.OUTPUT,
slot,
false,
link_info,
output
);
break;
}
} else {
for (const link_id of links) {
const link_info = graph._links.get(link_id);
if (!link_info) continue;
const target = graph.getNodeById(link_info.target_id);
graph._version++;
if (target) {
const input = target.inputs[link_info.target_slot];
input.link = null;
target.onConnectionsChange?.(
NodeSlotType.INPUT,
link_info.target_slot,
false,
link_info,
input
);
}
link_info.disconnect(graph, "input");
this.onConnectionsChange?.(
NodeSlotType.OUTPUT,
slot,
false,
link_info,
output
);
}
output.links = null;
}
this.setDirtyCanvas(false, true);
graph.connectionChange(this);
return true;
}
/**
* Disconnect one input
* @param slot Input slot index, or the name of the slot
* @param keepReroutes If `true`, reroutes will not be garbage collected.
* @returns true if disconnected successfully or already disconnected, otherwise false
*/
disconnectInput(slot, keepReroutes) {
if (typeof slot === "string") {
slot = this.findInputSlot(slot);
if (slot == -1) {
if (LiteGraph.debug) console.log(`Connect: Error, no slot of name ${slot}`);
return false;
}
} else if (!this.inputs || slot >= this.inputs.length) {
if (LiteGraph.debug) {
console.log("Connect: Error, slot number not found");
}
return false;
}
const input = this.inputs[slot];
if (!input) return false;
const { graph } = this;
if (!graph) throw new NullGraphError();
if (input._floatingLinks?.size) {
for (const link of input._floatingLinks) {
graph.removeFloatingLink(link);
}
}
const link_id = this.inputs[slot].link;
if (link_id != null) {
this.inputs[slot].link = null;
const link_info = graph._links.get(link_id);
if (link_info) {
const target_node = graph.getNodeById(link_info.origin_id);
if (!target_node) return false;
const output = target_node.outputs[link_info.origin_slot];
if (!output?.links?.length) return false;
let i = 0;
for (const l = output.links.length; i < l; i++) {
if (output.links[i] == link_id) {
output.links.splice(i, 1);
break;
}
}
link_info.disconnect(graph, keepReroutes ? "output" : void 0);
if (graph) graph._version++;
this.onConnectionsChange?.(
NodeSlotType.INPUT,
slot,
false,
link_info,
input
);
target_node.onConnectionsChange?.(
NodeSlotType.OUTPUT,
i,
false,
link_info,
output
);
}
}
this.setDirtyCanvas(false, true);
graph?.connectionChange(this);
return true;
}
/**
* @deprecated Use {@link getInputPos} or {@link getOutputPos} instead.
* returns the center of a connection point in canvas coords
* @param is_input true if if a input slot, false if it is an output
* @param slot_number (could be the number of the slot or the string with the name of the slot)
* @param out [optional] a place to store the output, to free garbage
* @returns the position
*/
getConnectionPos(is_input, slot_number, out) {
out ||= new Float32Array(2);
const { pos: [nodeX, nodeY], inputs, outputs } = this;
if (this.flags.collapsed) {
const w = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
out[0] = is_input ? nodeX : nodeX + w;
out[1] = nodeY - LiteGraph.NODE_TITLE_HEIGHT * 0.5;
return out;
}
if (is_input && slot_number == -1) {
out[0] = nodeX + LiteGraph.NODE_TITLE_HEIGHT * 0.5;
out[1] = nodeY + LiteGraph.NODE_TITLE_HEIGHT * 0.5;
return out;
}
const inputPos = inputs?.[slot_number]?.pos;
const outputPos = outputs?.[slot_number]?.pos;
if (is_input && inputPos) {
out[0] = nodeX + inputPos[0];
out[1] = nodeY + inputPos[1];
return out;
} else if (!is_input && outputPos) {
out[0] = nodeX + outputPos[0];
out[1] = nodeY + outputPos[1];
return out;
}
const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
const slotIndex = is_input ? this.#defaultVerticalInputs.indexOf(this.inputs[slot_number]) : this.#defaultVerticalOutputs.indexOf(this.outputs[slot_number]);
out[0] = is_input ? nodeX + offset : nodeX + this.size[0] + 1 - offset;
out[1] = nodeY + (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + (this.constructor.slot_start_y || 0);
return out;
}
/**
* @internal The inputs that are not positioned with absolute coordinates.
*/
get #defaultVerticalInputs() {
return this.inputs.filter(
(slot) => !slot.pos && !(this.widgets?.length && isWidgetInputSlot(slot))
);
}
/**
* @internal The outputs that are not positioned with absolute coordinates.
*/
get #defaultVerticalOutputs() {
return this.outputs.filter((slot) => !slot.pos);
}
/**
* Gets the position of an input slot, in graph co-ordinates.
*
* This method is preferred over the legacy {@link getConnectionPos} method.
* @param slot Input slot index
* @returns Position of the input slot
*/
getInputPos(slot) {
return this.getInputSlotPos(this.inputs[slot]);
}
/**
* Gets the position of an input slot, in graph co-ordinates.
* @param input The actual node input object
* @returns Position of the centre of the input slot in graph co-ordinates.
*/
getInputSlotPos(input) {
const { pos: [nodeX, nodeY] } = this;
if (this.flags.collapsed) {
const halfTitle = LiteGraph.NODE_TITLE_HEIGHT * 0.5;
return [nodeX, nodeY - halfTitle];
}
const { pos } = input;
if (pos) return [nodeX + pos[0], nodeY + pos[1]];
const offsetX = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
const nodeOffsetY = this.constructor.slot_start_y || 0;
const slotIndex = this.#defaultVerticalInputs.indexOf(input);
const slotY = (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT;
return [nodeX + offsetX, nodeY + slotY + nodeOffsetY];
}
/**
* Gets the position of an output slot, in graph co-ordinates.
*
* This method is preferred over the legacy {@link getConnectionPos} method.
* @param slot Output slot index
* @returns Position of the output slot
*/
getOutputPos(slot) {
const { pos: [nodeX, nodeY], outputs, size: [width2] } = this;
if (this.flags.collapsed) {
const width22 = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
const halfTitle = LiteGraph.NODE_TITLE_HEIGHT * 0.5;
return [nodeX + width22, nodeY - halfTitle];
}
const outputPos = outputs?.[slot]?.pos;
if (outputPos) return [nodeX + outputPos[0], nodeY + outputPos[1]];
const offsetX = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
const nodeOffsetY = this.constructor.slot_start_y || 0;
const slotIndex = this.#defaultVerticalOutputs.indexOf(this.outputs[slot]);
const slotY = (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT;
return [nodeX + width2 + 1 - offsetX, nodeY + slotY + nodeOffsetY];
}
/** @inheritdoc */
snapToGrid(snapTo) {
return this.pinned ? false : snapPoint(this.pos, snapTo);
}
/** @see {@link snapToGrid} */
alignToGrid() {
this.snapToGrid(LiteGraph.CANVAS_GRID_SIZE);
}
/* Console output */
trace(msg) {
this.console ||= [];
this.console.push(msg);
if (this.console.length > LGraphNode.MAX_CONSOLE)
this.console.shift();
}
/* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */
setDirtyCanvas(dirty_foreground, dirty_background) {
this.graph?.canvasAction((c) => c.setDirty(dirty_foreground, dirty_background));
}
loadImage(url) {
const img = new Image();
img.src = LiteGraph.node_images_path + url;
img.ready = false;
const dirty = () => this.setDirtyCanvas(true);
img.addEventListener("load", function() {
this.ready = true;
dirty();
});
return img;
}
/**
* Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus
* @deprecated Use {@link LGraphCanvas.pointer} instead.
*/
captureInput(v2) {
warnDeprecated("[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead.");
if (!this.graph || !this.graph.list_of_graphcanvas) return;
const list = this.graph.list_of_graphcanvas;
for (const c of list) {
if (!v2 && c.node_capturing_input != this) continue;
c.node_capturing_input = v2 ? this : null;
}
}
get collapsed() {
return !!this.flags.collapsed;
}
get collapsible() {
return !this.pinned && this.constructor.collapsable !== false;
}
/**
* Toggle node collapse (makes it smaller on the canvas)
*/
collapse(force) {
if (!this.collapsible && !force) return;
if (!this.graph) throw new NullGraphError();
this.graph._version++;
this.flags.collapsed = !this.flags.collapsed;
this.setDirtyCanvas(true, true);
}
/**
* Toggles advanced mode of the node, showing advanced widgets
*/
toggleAdvanced() {
if (!this.widgets?.some((w) => w.advanced)) return;
if (!this.graph) throw new NullGraphError();
this.graph._version++;
this.showAdvanced = !this.showAdvanced;
this.expandToFitContent();
this.setDirtyCanvas(true, true);
}
get pinned() {
return !!this.flags.pinned;
}
/**
* Prevents the node being accidentally moved or resized by mouse interaction.
* Toggles pinned state if no value is provided.
*/
pin(v2) {
if (!this.graph) throw new NullGraphError();
this.graph._version++;
this.flags.pinned = v2 ?? !this.flags.pinned;
this.resizable = !this.pinned;
if (!this.pinned) delete this.flags.pinned;
}
unpin() {
this.pin(false);
}
localToScreen(x2, y, dragAndScale) {
return [
(x2 + this.pos[0]) * dragAndScale.scale + dragAndScale.offset[0],
(y + this.pos[1]) * dragAndScale.scale + dragAndScale.offset[1]
];
}
get width() {
return this.collapsed ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH : this.size[0];
}
/**
* Returns the height of the node, including the title bar.
*/
get height() {
return LiteGraph.NODE_TITLE_HEIGHT + this.bodyHeight;
}
/**
* Returns the height of the node, excluding the title bar.
*/
get bodyHeight() {
return this.collapsed ? 0 : this.size[1];
}
drawBadges(ctx, { gap = 2 } = {}) {
const badgeInstances = this.badges.map((badge) => badge instanceof LGraphBadge ? badge : badge());
const isLeftAligned = this.badgePosition === BadgePosition.TopLeft;
let currentX = isLeftAligned ? 0 : this.width - badgeInstances.reduce((acc, badge) => acc + badge.getWidth(ctx) + gap, 0);
const y = -(LiteGraph.NODE_TITLE_HEIGHT + gap);
for (const badge of badgeInstances) {
badge.draw(ctx, currentX, y - badge.height);
currentX += badge.getWidth(ctx) + gap;
}
}
/**
* Renders the node's title bar background
*/
drawTitleBarBackground(ctx, {
scale,
title_height = LiteGraph.NODE_TITLE_HEIGHT,
low_quality = false
}) {
const fgcolor = this.renderingColor;
const shape = this.renderingShape;
const size = this.renderingSize;
if (this.onDrawTitleBar) {
this.onDrawTitleBar(ctx, title_height, size, scale, fgcolor);
return;
}
if (this.title_mode === TitleMode.TRANSPARENT_TITLE) {
return;
}
if (this.collapsed) {
ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;
}
ctx.fillStyle = this.constructor.title_color || fgcolor;
ctx.beginPath();
if (shape == RenderShape.BOX || low_quality) {
ctx.rect(0, -title_height, size[0], title_height);
} else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) {
ctx.roundRect(
0,
-title_height,
size[0],
title_height,
this.collapsed ? [LiteGraph.ROUND_RADIUS] : [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0]
);
}
ctx.fill();
ctx.shadowColor = "transparent";
}
/**
* Renders the node's title box, i.e. the dot in front of the title text that
* when clicked toggles the node's collapsed state. The term `title box` comes
* from the original LiteGraph implementation.
*/
drawTitleBox(ctx, {
scale,
low_quality = false,
title_height = LiteGraph.NODE_TITLE_HEIGHT,
box_size = 10
}) {
const size = this.renderingSize;
const shape = this.renderingShape;
if (this.onDrawTitleBox) {
this.onDrawTitleBox(ctx, title_height, size, scale);
return;
}
if ([RenderShape.ROUND, RenderShape.CIRCLE, RenderShape.CARD].includes(shape)) {
if (low_quality) {
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(
title_height * 0.5,
title_height * -0.5,
box_size * 0.5 + 1,
0,
Math.PI * 2
);
ctx.fill();
}
ctx.fillStyle = this.renderingBoxColor;
if (low_quality) {
ctx.fillRect(
title_height * 0.5 - box_size * 0.5,
title_height * -0.5 - box_size * 0.5,
box_size,
box_size
);
} else {
ctx.beginPath();
ctx.arc(
title_height * 0.5,
title_height * -0.5,
box_size * 0.5,
0,
Math.PI * 2
);
ctx.fill();
}
} else {
if (low_quality) {
ctx.fillStyle = "black";
ctx.fillRect(
(title_height - box_size) * 0.5 - 1,
(title_height + box_size) * -0.5 - 1,
box_size + 2,
box_size + 2
);
}
ctx.fillStyle = this.renderingBoxColor;
ctx.fillRect(
(title_height - box_size) * 0.5,
(title_height + box_size) * -0.5,
box_size,
box_size
);
}
}
/**
* Renders the node's title text.
*/
drawTitleText(ctx, {
scale,
default_title_color,
low_quality = false,
title_height = LiteGraph.NODE_TITLE_HEIGHT
}) {
const size = this.renderingSize;
const selected = this.selected;
if (this.onDrawTitleText) {
this.onDrawTitleText(
ctx,
title_height,
size,
scale,
this.titleFontStyle,
selected
);
return;
}
if (low_quality) {
return;
}
ctx.font = this.titleFontStyle;
const rawTitle = this.getTitle() ?? `❌ ${this.type}`;
const title = String(rawTitle) + (this.pinned ? "📌" : "");
if (title) {
if (selected) {
ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR;
} else {
ctx.fillStyle = this.constructor.title_text_color || default_title_color;
}
if (this.collapsed) {
ctx.textAlign = "left";
ctx.fillText(
// avoid urls too long
title.substr(0, 20),
title_height,
LiteGraph.NODE_TITLE_TEXT_Y - title_height
);
ctx.textAlign = "left";
} else {
ctx.textAlign = "left";
ctx.fillText(
title,
title_height,
LiteGraph.NODE_TITLE_TEXT_Y - title_height
);
}
}
}
/**
* Attempts to gracefully bypass this node in all of its connections by reconnecting all links.
*
* Each input is checked against each output. This is done on a matching index basis, i.e. input 3 -> output 3.
* If there are any input links remaining,
* and {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `true`,
* each input will check for outputs that match, and take the first one that matches
* `true`: Try the index matching first, then every input to every output.
* `false`: Only matches indexes, e.g. input 3 to output 3.
*
* If {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `undefined`, it will fall back to
* the static {@link keepAllLinksOnBypass}.
* @returns `true` if any new links were established, otherwise `false`.
* @todo Decision: Change API to return array of new links instead?
*/
connectInputToOutput() {
const { inputs, outputs, graph } = this;
if (!inputs || !outputs) return;
if (!graph) throw new NullGraphError();
const { _links } = graph;
let madeAnyConnections = false;
for (const [index, input] of inputs.entries()) {
if (input.link == null) continue;
const output = outputs[index];
if (!output || !LiteGraph.isValidConnection(input.type, output.type)) continue;
const inLink = _links.get(input.link);
if (!inLink) continue;
const inNode = graph.getNodeById(inLink?.origin_id);
if (!inNode) continue;
bypassAllLinks(output, inNode, inLink, graph);
}
if (!(this.flags.keepAllLinksOnBypass ?? LGraphNode.keepAllLinksOnBypass))
return madeAnyConnections;
for (const input of inputs) {
if (input.link == null) continue;
const inLink = _links.get(input.link);
if (!inLink) continue;
const inNode = graph.getNodeById(inLink?.origin_id);
if (!inNode) continue;
for (const output of outputs) {
if (!LiteGraph.isValidConnection(input.type, output.type)) continue;
bypassAllLinks(output, inNode, inLink, graph);
break;
}
}
return madeAnyConnections;
function bypassAllLinks(output, inNode, inLink, graph2) {
const outLinks = output.links?.map((x2) => _links.get(x2)).filter((x2) => !!x2);
if (!outLinks?.length) return;
for (const outLink of outLinks) {
const outNode = graph2.getNodeById(outLink.target_id);
if (!outNode) continue;
const result = inNode.connect(
inLink.origin_slot,
outNode,
outLink.target_slot,
inLink.parentId
);
madeAnyConnections ||= !!result;
}
}
}
/**
* Returns `true` if the widget is visible, otherwise `false`.
*/
isWidgetVisible(widget) {
const isHidden = this.collapsed || widget.hidden || widget.advanced && !this.showAdvanced;
return !isHidden;
}
drawWidgets(ctx, {
lowQuality = false,
editorAlpha = 1
}) {
if (!this.widgets) return;
const nodeWidth = this.size[0];
const { widgets } = this;
const H = LiteGraph.NODE_WIDGET_HEIGHT;
const showText = !lowQuality;
ctx.save();
ctx.globalAlpha = editorAlpha;
for (const widget of widgets) {
if (!this.isWidgetVisible(widget)) continue;
const { y } = widget;
const outlineColour = widget.advanced ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR : LiteGraph.WIDGET_OUTLINE_COLOR;
widget.last_y = y;
widget.computedDisabled = widget.disabled || this.getSlotFromWidget(widget)?.link != null;
ctx.strokeStyle = outlineColour;
ctx.fillStyle = "#222";
ctx.textAlign = "left";
if (widget.computedDisabled) ctx.globalAlpha *= 0.5;
const width2 = widget.width || nodeWidth;
if (typeof widget.draw === "function") {
widget.draw(ctx, this, width2, y, H, lowQuality);
} else {
toConcreteWidget(widget, this, false)?.drawWidget(ctx, { width: width2, showText });
}
ctx.globalAlpha = editorAlpha;
}
ctx.restore();
}
/**
* When {@link LGraphNode.collapsed} is `true`, this method draws the node's collapsed slots.
*/
drawCollapsedSlots(ctx) {
for (const slot of this.#concreteInputs) {
if (slot.link != null) {
slot.drawCollapsed(ctx);
break;
}
}
for (const slot of this.#concreteOutputs) {
if (slot.links?.length) {
slot.drawCollapsed(ctx);
break;
}
}
}
get slots() {
return [...this.inputs, ...this.outputs];
}
#measureSlot(slot, slotIndex, isInput) {
const pos = isInput ? this.getInputPos(slotIndex) : this.getOutputPos(slotIndex);
slot.boundingRect[0] = pos[0] - LiteGraph.NODE_SLOT_HEIGHT * 0.5;
slot.boundingRect[1] = pos[1] - LiteGraph.NODE_SLOT_HEIGHT * 0.5;
slot.boundingRect[2] = slot.isWidgetInputSlot ? BaseWidget.margin : LiteGraph.NODE_SLOT_HEIGHT;
slot.boundingRect[3] = LiteGraph.NODE_SLOT_HEIGHT;
}
#measureSlots() {
const slots = [];
for (const [slotIndex, slot] of this.#concreteInputs.entries()) {
if (this.widgets?.length && isWidgetInputSlot(slot)) continue;
this.#measureSlot(slot, slotIndex, true);
slots.push(slot);
}
for (const [slotIndex, slot] of this.#concreteOutputs.entries()) {
this.#measureSlot(slot, slotIndex, false);
slots.push(slot);
}
return slots.length ? createBounds(slots, 0) : null;
}
#getMouseOverSlot(slot) {
const isInput = isINodeInputSlot(slot);
const mouseOverId = this.mouseOver?.[isInput ? "inputId" : "outputId"] ?? -1;
if (mouseOverId === -1) {
return null;
}
return isInput ? this.inputs[mouseOverId] : this.outputs[mouseOverId];
}
#isMouseOverSlot(slot) {
return this.#getMouseOverSlot(slot) === slot;
}
#isMouseOverWidget(widget) {
if (!widget) return false;
return this.mouseOver?.overWidget === widget;
}
/**
* Returns the input slot that is associated with the given widget.
*/
getSlotFromWidget(widget) {
if (widget) return this.inputs.find((slot) => isWidgetInputSlot(slot) && slot.widget.name === widget.name);
}
/**
* Returns the widget that is associated with the given input slot.
*/
getWidgetFromSlot(slot) {
if (!isWidgetInputSlot(slot)) return;
return this.widgets?.find((w) => w.name === slot.widget.name);
}
/**
* Draws the node's input and output slots.
*/
drawSlots(ctx, {
fromSlot,
colorContext,
editorAlpha,
lowQuality
}) {
for (const slot of [...this.#concreteInputs, ...this.#concreteOutputs]) {
const isValidTarget = fromSlot && slot.isValidTarget(fromSlot);
const isMouseOverSlot = this.#isMouseOverSlot(slot);
const isValid = !fromSlot || isValidTarget;
const highlight = isValid && isMouseOverSlot;
if (isMouseOverSlot || isValidTarget || !slot.isWidgetInputSlot || this.#isMouseOverWidget(this.getWidgetFromSlot(slot)) || slot.isConnected) {
ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha;
slot.draw(ctx, {
colorContext,
lowQuality,
highlight
});
}
}
}
/**
* Arranges the node's widgets vertically.
* Sets following properties on each widget:
* - {@link IBaseWidget.computedHeight}
* - {@link IBaseWidget.y}
* @param widgetStartY The y-coordinate of the first widget
*/
#arrangeWidgets(widgetStartY) {
if (!this.widgets || !this.widgets.length) return;
const bodyHeight = this.bodyHeight;
const startY = this.widgets_start_y ?? (this.widgets_up ? 0 : widgetStartY) + 2;
let freeSpace = bodyHeight - startY;
let fixedWidgetHeight = 0;
const growableWidgets = [];
for (const w of this.widgets) {
if (w.computeSize) {
const height = w.computeSize()[1] + 4;
w.computedHeight = height;
fixedWidgetHeight += height;
} else if (w.computeLayoutSize) {
const { minHeight, maxHeight } = w.computeLayoutSize(this);
growableWidgets.push({
minHeight,
prefHeight: maxHeight,
w
});
} else {
const height = LiteGraph.NODE_WIDGET_HEIGHT + 4;
w.computedHeight = height;
fixedWidgetHeight += height;
}
}
freeSpace -= fixedWidgetHeight;
this.freeWidgetSpace = freeSpace;
const spaceRequests = growableWidgets.map((d) => ({
minSize: d.minHeight,
maxSize: d.prefHeight
}));
const allocations = distributeSpace(Math.max(0, freeSpace), spaceRequests);
for (const [i, d] of growableWidgets.entries()) {
d.w.computedHeight = allocations[i];
}
let y = startY;
for (const w of this.widgets) {
w.y = y;
y += w.computedHeight ?? 0;
}
if (!this.graph) throw new NullGraphError();
if (y > bodyHeight) {
this.setSize([this.size[0], y]);
this.graph.setDirtyCanvas(false, true);
}
}
/**
* Arranges the layout of the node's widget input slots.
*/
#arrangeWidgetInputSlots() {
if (!this.widgets) return;
const slotByWidgetName = /* @__PURE__ */ new Map();
for (const [i, slot] of this.inputs.entries()) {
if (!isWidgetInputSlot(slot)) continue;
slotByWidgetName.set(slot.widget.name, { ...slot, index: i });
}
if (!slotByWidgetName.size) return;
for (const widget of this.widgets) {
const slot = slotByWidgetName.get(widget.name);
if (!slot) continue;
const actualSlot = this.#concreteInputs[slot.index];
const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5;
actualSlot.pos = [offset, widget.y + offset];
this.#measureSlot(actualSlot, slot.index, true);
}
}
/**
* @internal Sets the internal concrete slot arrays, ensuring they are instances of
* {@link NodeInputSlot} or {@link NodeOutputSlot}.
*
* A temporary workaround until duck-typed inputs and outputs
* have been removed from the ecosystem.
*/
_setConcreteSlots() {
this.#concreteInputs = this.inputs.map((slot) => toClass(NodeInputSlot, slot, this));
this.#concreteOutputs = this.outputs.map((slot) => toClass(NodeOutputSlot, slot, this));
}
/**
* Arranges node elements in preparation for rendering (slots & widgets).
*/
arrange() {
const slotsBounds = this.#measureSlots();
const widgetStartY = slotsBounds ? slotsBounds[1] + slotsBounds[3] - this.pos[1] : 0;
this.#arrangeWidgets(widgetStartY);
this.#arrangeWidgetInputSlots();
}
/**
* Draws a progress bar on the node.
* @param ctx The canvas context to draw on
*/
drawProgressBar(ctx) {
if (!this.progress) return;
const originalFillStyle = ctx.fillStyle;
ctx.fillStyle = "green";
ctx.fillRect(
0,
0,
this.width * this.progress,
6
);
ctx.fillStyle = originalFillStyle;
}
}
class LGraphGroup {
static minWidth = 140;
static minHeight = 80;
static resizeLength = 10;
static padding = 4;
static defaultColour = "#335";
id;
color;
title;
font;
font_size = LiteGraph.DEFAULT_GROUP_FONT || 24;
_bounding = new Float32Array([
10,
10,
LGraphGroup.minWidth,
LGraphGroup.minHeight
]);
_pos = this._bounding.subarray(0, 2);
_size = this._bounding.subarray(2, 4);
/** @deprecated See {@link _children} */
_nodes = [];
_children = /* @__PURE__ */ new Set();
graph;
flags = {};
selected;
constructor(title, id) {
this.id = id ?? -1;
this.title = title || "Group";
const { pale_blue } = LGraphCanvas.node_colors;
this.color = pale_blue ? pale_blue.groupcolor : "#AAA";
}
/** @inheritdoc {@link IColorable.setColorOption} */
setColorOption(colorOption) {
if (colorOption == null) {
delete this.color;
} else {
this.color = colorOption.groupcolor;
}
}
/** @inheritdoc {@link IColorable.getColorOption} */
getColorOption() {
return Object.values(LGraphCanvas.node_colors).find(
(colorOption) => colorOption.groupcolor === this.color
) ?? null;
}
/** Position of the group, as x,y co-ordinates in graph space */
get pos() {
return this._pos;
}
set pos(v2) {
if (!v2 || v2.length < 2) return;
this._pos[0] = v2[0];
this._pos[1] = v2[1];
}
/** Size of the group, as width,height in graph units */
get size() {
return this._size;
}
set size(v2) {
if (!v2 || v2.length < 2) return;
this._size[0] = Math.max(LGraphGroup.minWidth, v2[0]);
this._size[1] = Math.max(LGraphGroup.minHeight, v2[1]);
}
get boundingRect() {
return this._bounding;
}
get nodes() {
return this._nodes;
}
get titleHeight() {
return this.font_size * 1.4;
}
get children() {
return this._children;
}
get pinned() {
return !!this.flags.pinned;
}
/**
* Prevents the group being accidentally moved or resized by mouse interaction.
* Toggles pinned state if no value is provided.
*/
pin(value) {
const newState = value === void 0 ? !this.pinned : value;
if (newState) this.flags.pinned = true;
else delete this.flags.pinned;
}
unpin() {
this.pin(false);
}
configure(o) {
this.id = o.id;
this.title = o.title;
this._bounding.set(o.bounding);
this.color = o.color;
this.flags = o.flags || this.flags;
if (o.font_size) this.font_size = o.font_size;
}
serialize() {
const b = this._bounding;
return {
id: this.id,
title: this.title,
bounding: [...b],
color: this.color,
font_size: this.font_size,
flags: this.flags
};
}
/**
* Draws the group on the canvas
* @param graphCanvas
* @param ctx
*/
draw(graphCanvas, ctx) {
const { padding, resizeLength, defaultColour } = LGraphGroup;
const font_size = this.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE;
const [x2, y] = this._pos;
const [width2, height] = this._size;
const color = this.color || defaultColour;
ctx.globalAlpha = 0.25 * graphCanvas.editor_alpha;
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.beginPath();
ctx.rect(x2 + 0.5, y + 0.5, width2, font_size * 1.4);
ctx.fill();
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.beginPath();
ctx.rect(x2 + 0.5, y + 0.5, width2, height);
ctx.fill();
ctx.globalAlpha = graphCanvas.editor_alpha;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x2 + width2, y + height);
ctx.lineTo(x2 + width2 - resizeLength, y + height);
ctx.lineTo(x2 + width2, y + height - resizeLength);
ctx.fill();
ctx.font = `${font_size}px ${LiteGraph.GROUP_FONT}`;
ctx.textAlign = "left";
ctx.fillText(this.title + (this.pinned ? "📌" : ""), x2 + padding, y + font_size);
if (LiteGraph.highlight_selected_group && this.selected) {
strokeShape(ctx, this._bounding, {
title_height: this.titleHeight,
padding
});
}
}
resize(width2, height) {
if (this.pinned) return false;
this._size[0] = Math.max(LGraphGroup.minWidth, width2);
this._size[1] = Math.max(LGraphGroup.minHeight, height);
return true;
}
move(deltaX, deltaY, skipChildren = false) {
if (this.pinned) return;
this._pos[0] += deltaX;
this._pos[1] += deltaY;
if (skipChildren === true) return;
for (const item of this._children) {
item.move(deltaX, deltaY);
}
}
/** @inheritdoc */
snapToGrid(snapTo) {
return this.pinned ? false : snapPoint(this.pos, snapTo);
}
recomputeInsideNodes() {
if (!this.graph) throw new NullGraphError();
const { nodes, reroutes, groups } = this.graph;
const children = this._children;
this._nodes.length = 0;
children.clear();
for (const node2 of nodes) {
if (containsCentre(this._bounding, node2.boundingRect)) {
this._nodes.push(node2);
children.add(node2);
}
}
for (const reroute of reroutes.values()) {
if (isPointInRect(reroute.pos, this._bounding))
children.add(reroute);
}
for (const group of groups) {
if (containsRect(this._bounding, group._bounding))
children.add(group);
}
groups.sort((a, b) => {
if (a === this) {
return children.has(b) ? -1 : 0;
} else if (b === this) {
return children.has(a) ? 1 : 0;
} else {
return 0;
}
});
}
/**
* Resizes and moves the group to neatly fit all given {@link objects}.
* @param objects All objects that should be inside the group
* @param padding Value in graph units to add to all sides of the group. Default: 10
*/
resizeTo(objects, padding = 10) {
const boundingBox = createBounds(objects, padding);
if (boundingBox === null) return;
this.pos[0] = boundingBox[0];
this.pos[1] = boundingBox[1] - this.titleHeight;
this.size[0] = boundingBox[2];
this.size[1] = boundingBox[3] + this.titleHeight;
}
/**
* Add nodes to the group and adjust the group's position and size accordingly
* @param nodes The nodes to add to the group
* @param padding The padding around the group
*/
addNodes(nodes, padding = 10) {
if (!this._nodes && nodes.length === 0) return;
this.resizeTo([...this.children, ...this._nodes, ...nodes], padding);
}
getMenuOptions() {
return [
{
content: this.pinned ? "Unpin" : "Pin",
callback: () => {
if (this.pinned) this.unpin();
else this.pin();
this.setDirtyCanvas(false, true);
}
},
null,
{ content: "Title", callback: LGraphCanvas.onShowPropertyEditor },
{
content: "Color",
has_submenu: true,
callback: LGraphCanvas.onMenuNodeColors
},
{
content: "Font size",
property: "font_size",
type: "Number",
callback: LGraphCanvas.onShowPropertyEditor
},
null,
{ content: "Remove", callback: LGraphCanvas.onMenuNodeRemove }
];
}
isPointInTitlebar(x2, y) {
const b = this.boundingRect;
return isInRectangle(x2, y, b[0], b[1], b[2], this.titleHeight);
}
isInResize(x2, y) {
const b = this.boundingRect;
const right = b[0] + b[2];
const bottom = b[1] + b[3];
return x2 < right && y < bottom && x2 - right + (y - bottom) > -LGraphGroup.resizeLength;
}
isPointInside = LGraphNode.prototype.isPointInside;
setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas;
}
class Reroute {
/**
* Initialises a new link reroute object.
* @param id Unique identifier for this reroute
* @param network The network of links this reroute belongs to. Internally converted to a WeakRef.
* @param pos Position in graph coordinates
* @param linkIds Link IDs ({@link LLink.id}) of all links that use this reroute
*/
constructor(id, network, pos, parentId, linkIds, floatingLinkIds) {
this.id = id;
this.#network = new WeakRef(network);
this.parentId = parentId;
if (pos) this.pos = pos;
this.linkIds = new Set(linkIds);
this.floatingLinkIds = new Set(floatingLinkIds);
}
static radius = 10;
/** Maximum distance from reroutes to their bezier curve control points. */
static maxSplineOffset = 80;
static drawIdBadge = false;
static slotRadius = 5;
/** Distance from reroute centre to slot centre. */
static get slotOffset() {
const gap = Reroute.slotRadius * 0.33;
return Reroute.radius + gap + Reroute.slotRadius;
}
#malloc = new Float32Array(8);
/** The network this reroute belongs to. Contains all valid links and reroutes. */
#network;
#parentId;
get parentId() {
return this.#parentId;
}
/** Ignores attempts to create an infinite loop. @inheritdoc */
set parentId(value) {
if (value === this.id) return;
if (this.getReroutes() === null) return;
this.#parentId = value;
}
get parent() {
return this.#network.deref()?.getReroute(this.#parentId);
}
/** This property is only defined on the last reroute of a floating reroute chain (closest to input end). */
floating;
#pos = this.#malloc.subarray(0, 2);
/** @inheritdoc */
get pos() {
return this.#pos;
}
set pos(value) {
if (!(value?.length >= 2))
throw new TypeError("Reroute.pos is an x,y point, and expects an indexable with at least two values.");
this.#pos[0] = value[0];
this.#pos[1] = value[1];
}
/** @inheritdoc */
get boundingRect() {
const { radius } = Reroute;
const [x2, y] = this.#pos;
return [x2 - radius, y - radius, 2 * radius, 2 * radius];
}
/**
* Slightly over-sized rectangle, guaranteed to contain the entire surface area for hover detection.
* Eliminates most hover positions using an extremely cheap check.
*/
get #hoverArea() {
const xOffset = 2 * Reroute.slotOffset;
const yOffset = 2 * Math.max(Reroute.radius, Reroute.slotRadius);
const [x2, y] = this.#pos;
return [x2 - xOffset, y - yOffset, 2 * xOffset, 2 * yOffset];
}
/** The total number of links & floating links using this reroute */
get totalLinks() {
return this.linkIds.size + this.floatingLinkIds.size;
}
/** @inheritdoc */
selected;
/** The ID ({@link LLink.id}) of every link using this reroute */
linkIds;
/** The ID ({@link LLink.id}) of every floating link using this reroute */
floatingLinkIds;
/** Cached cos */
cos = 0;
sin = 0;
/** Bezier curve control point for the "target" (input) side of the link */
controlPoint = this.#malloc.subarray(4, 6);
/** @inheritdoc */
path;
/** @inheritdoc */
_centreAngle;
/** @inheritdoc */
_pos = this.#malloc.subarray(6, 8);
/** @inheritdoc */
_dragging;
/** Colour of the first link that rendered this reroute */
_colour;
/** Colour of the first link that rendered this reroute */
get colour() {
return this._colour ?? "#18184d";
}
/**
* Used to ensure reroute angles are only executed once per frame.
* @todo Calculate on change instead.
*/
#lastRenderTime = -Infinity;
#inputSlot = new RerouteSlot(this, true);
#outputSlot = new RerouteSlot(this, false);
get isSlotHovered() {
return this.isInputHovered || this.isOutputHovered;
}
get isInputHovered() {
return this.#inputSlot.hovering;
}
get isOutputHovered() {
return this.#outputSlot.hovering;
}
get firstLink() {
const linkId = this.linkIds.values().next().value;
return linkId === void 0 ? void 0 : this.#network.deref()?.links.get(linkId);
}
get firstFloatingLink() {
const linkId = this.floatingLinkIds.values().next().value;
return linkId === void 0 ? void 0 : this.#network.deref()?.floatingLinks.get(linkId);
}
/** @inheritdoc */
get origin_id() {
return this.firstLink?.origin_id;
}
/** @inheritdoc */
get origin_slot() {
return this.firstLink?.origin_slot;
}
/**
* Applies a new parentId to the reroute, and optinoally a new position and linkId.
* Primarily used for deserialisation.
* @param parentId The ID of the reroute prior to this reroute, or
* `undefined` if it is the first reroute connected to a nodes output
* @param pos The position of this reroute
* @param linkIds All link IDs that pass through this reroute
*/
update(parentId, pos, linkIds, floating) {
this.parentId = parentId;
if (pos) this.pos = pos;
if (linkIds) this.linkIds = new Set(linkIds);
this.floating = floating;
}
/**
* Validates the linkIds this reroute has. Removes broken links.
* @param links Collection of valid links
* @returns true if any links remain after validation
*/
validateLinks(links, floatingLinks) {
const { linkIds, floatingLinkIds } = this;
for (const linkId of linkIds) {
if (!links.has(linkId)) linkIds.delete(linkId);
}
for (const linkId of floatingLinkIds) {
if (!floatingLinks.has(linkId)) floatingLinkIds.delete(linkId);
}
return linkIds.size > 0 || floatingLinkIds.size > 0;
}
/**
* Retrieves an ordered array of all reroutes from the node output.
* @param visited Internal. A set of reroutes that this function
* has already visited whilst recursing up the chain.
* @returns An ordered array of all reroutes from the node output to this reroute, inclusive.
* `null` if an infinite loop is detected.
* `undefined` if the reroute chain or {@link LinkNetwork} are invalid.
*/
getReroutes(visited = /* @__PURE__ */ new Set()) {
if (this.#parentId === void 0) return [this];
if (visited.has(this)) return null;
visited.add(this);
const parent = this.#network.deref()?.reroutes.get(this.#parentId);
if (!parent) {
this.#parentId = void 0;
return [this];
}
const reroutes = parent.getReroutes(visited);
reroutes?.push(this);
return reroutes;
}
/**
* Internal. Called by {@link LLink.findNextReroute}. Not intended for use by itself.
* @param withParentId The rerouteId to look for
* @param visited A set of reroutes that have already been visited
* @returns The reroute that was found, `undefined` if no reroute was found, or `null` if an infinite loop was detected.
*/
findNextReroute(withParentId, visited = /* @__PURE__ */ new Set()) {
if (this.#parentId === withParentId) return this;
if (visited.has(this)) return null;
visited.add(this);
if (this.#parentId === void 0) return;
return this.#network.deref()?.reroutes.get(this.#parentId)?.findNextReroute(withParentId, visited);
}
/**
* Finds the output node and output slot of the first link passing through this reroute.
* @returns The output node and output slot of the first link passing through this reroute, or `undefined` if no link is found.
*/
findSourceOutput() {
const link = this.firstLink ?? this.firstFloatingLink;
if (!link) return;
const node2 = this.#network.deref()?.getNodeById(link.origin_id);
if (!node2) return;
return {
node: node2,
output: node2.outputs[link.origin_slot]
};
}
/**
* Finds the inputs and nodes of (floating) links passing through this reroute.
* @returns An array of objects containing the node and input slot of each link passing through this reroute.
*/
findTargetInputs() {
const network = this.#network.deref();
if (!network) return;
const results = [];
addAllResults(network, this.linkIds, network.links);
addAllResults(network, this.floatingLinkIds, network.floatingLinks);
return results;
function addAllResults(network2, linkIds, links) {
for (const linkId of linkIds) {
const link = links.get(linkId);
if (!link) continue;
const node2 = network2.getNodeById(link.target_id);
const input = node2?.inputs[link.target_slot];
if (!input) continue;
results.push({ node: node2, input, link });
}
}
}
/**
* Retrieves all floating links passing through this reroute.
* @param from Filters the links by the currently connected link side.
* @returns An array of floating links
*/
getFloatingLinks(from) {
const floatingLinks = this.#network.deref()?.floatingLinks;
if (!floatingLinks) return;
const idProp = from === "input" ? "origin_id" : "target_id";
const out = [];
for (const linkId of this.floatingLinkIds) {
const link = floatingLinks.get(linkId);
if (link?.[idProp] === -1) out.push(link);
}
return out;
}
/**
* Changes the origin node/output of all floating links that pass through this reroute.
* @param node The new origin node
* @param output The new origin output slot
* @param index The slot index of {@link output}
*/
setFloatingLinkOrigin(node2, output, index) {
const network = this.#network.deref();
const floatingOutLinks = this.getFloatingLinks("output");
if (!floatingOutLinks) throw new Error("[setFloatingLinkOrigin]: Invalid network.");
if (!floatingOutLinks.length) return;
output._floatingLinks ??= /* @__PURE__ */ new Set();
for (const link of floatingOutLinks) {
output._floatingLinks.add(link);
network?.getNodeById(link.origin_id)?.outputs[link.origin_slot]?._floatingLinks?.delete(link);
link.origin_id = node2.id;
link.origin_slot = index;
}
}
/** @inheritdoc */
move(deltaX, deltaY) {
this.#pos[0] += deltaX;
this.#pos[1] += deltaY;
}
/** @inheritdoc */
snapToGrid(snapTo) {
if (!snapTo) return false;
const { pos } = this;
pos[0] = snapTo * Math.round(pos[0] / snapTo);
pos[1] = snapTo * Math.round(pos[1] / snapTo);
return true;
}
removeAllFloatingLinks() {
for (const linkId of this.floatingLinkIds) {
this.removeFloatingLink(linkId);
}
}
removeFloatingLink(linkId) {
const network = this.#network.deref();
if (!network) return;
const floatingLink = network.floatingLinks.get(linkId);
if (!floatingLink) {
console.warn(`[Reroute.removeFloatingLink] Floating link not found: ${linkId}, ignoring and discarding ID.`);
this.floatingLinkIds.delete(linkId);
return;
}
network.removeFloatingLink(floatingLink);
}
/**
* Removes a link or floating link from this reroute, by matching link object instance equality.
* @param link The link to remove.
* @remarks Does not remove the link from the network.
*/
removeLink(link) {
const network = this.#network.deref();
if (!network) return;
const floatingLink = network.floatingLinks.get(link.id);
if (link === floatingLink) {
this.floatingLinkIds.delete(link.id);
} else {
this.linkIds.delete(link.id);
}
}
remove() {
const network = this.#network.deref();
if (!network) return;
network.removeReroute(this.id);
}
calculateAngle(lastRenderTime, network, linkStart) {
if (!(lastRenderTime > this.#lastRenderTime)) return;
this.#lastRenderTime = lastRenderTime;
const { id, pos: thisPos } = this;
const angles = [];
let sum = 0;
calculateAngles(this.linkIds, network.links);
calculateAngles(this.floatingLinkIds, network.floatingLinks);
if (!angles.length) {
this.cos = 0;
this.sin = 0;
this.controlPoint[0] = 0;
this.controlPoint[1] = 0;
return;
}
sum /= angles.length;
const originToReroute = Math.atan2(
this.#pos[1] - linkStart[1],
this.#pos[0] - linkStart[0]
);
let diff = (originToReroute - sum) * 0.5;
if (Math.abs(diff) > Math.PI * 0.5) diff += Math.PI;
const dist = Math.min(Reroute.maxSplineOffset, distance(linkStart, this.#pos) * 0.25);
const originDiff = originToReroute - diff;
const cos = Math.cos(originDiff);
const sin = Math.sin(originDiff);
this.cos = cos;
this.sin = sin;
this.controlPoint[0] = dist * -cos;
this.controlPoint[1] = dist * -sin;
function calculateAngles(linkIds, links) {
for (const linkId of linkIds) {
const link = links.get(linkId);
const pos = getNextPos(network, link, id);
if (!pos) continue;
const angle = getDirection(thisPos, pos);
angles.push(angle);
sum += angle;
}
}
}
/**
* Renders the reroute on the canvas.
* @param ctx Canvas context to draw on
* @param backgroundPattern The canvas background pattern; used to make floating reroutes appear washed out.
* @remarks Leaves {@link ctx}.fillStyle, strokeStyle, and lineWidth dirty (perf.).
*/
draw(ctx, backgroundPattern) {
const { globalAlpha } = ctx;
const { pos } = this;
ctx.beginPath();
ctx.arc(pos[0], pos[1], Reroute.radius, 0, 2 * Math.PI);
if (this.linkIds.size === 0) {
ctx.fillStyle = backgroundPattern ?? "#797979";
ctx.fill();
ctx.globalAlpha = globalAlpha * 0.33;
}
ctx.fillStyle = this.colour;
ctx.lineWidth = Reroute.radius * 0.1;
ctx.strokeStyle = "rgb(0,0,0,0.5)";
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#ffffff55";
ctx.strokeStyle = "rgb(0,0,0,0.3)";
ctx.beginPath();
ctx.arc(pos[0], pos[1], Reroute.radius * 0.8, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
if (this.selected) {
ctx.strokeStyle = "#fff";
ctx.beginPath();
ctx.arc(pos[0], pos[1], Reroute.radius * 1.2, 0, 2 * Math.PI);
ctx.stroke();
}
if (Reroute.drawIdBadge) {
const idBadge = new LGraphBadge({ text: this.id.toString() });
const x2 = pos[0] - idBadge.getWidth(ctx) * 0.5;
const y = pos[1] - idBadge.height - Reroute.radius - 2;
idBadge.draw(ctx, x2, y);
}
ctx.globalAlpha = globalAlpha;
}
/**
* Draws the input and output slots on the canvas, if the slots are visible.
* @param ctx The canvas context to draw on.
*/
drawSlots(ctx) {
this.#inputSlot.draw(ctx);
this.#outputSlot.draw(ctx);
}
drawHighlight(ctx, colour) {
const { pos } = this;
const { strokeStyle, lineWidth } = ctx;
ctx.strokeStyle = colour;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(pos[0], pos[1], Reroute.radius * 1.5, 0, 2 * Math.PI);
ctx.stroke();
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
}
/**
* Updates visibility of the input and output slots, based on the position of the pointer.
* @param pos The position of the pointer.
* @returns `true` if any changes require a redraw.
*/
updateVisibility(pos) {
const input = this.#inputSlot;
const output = this.#outputSlot;
input.dirty = false;
output.dirty = false;
const { firstFloatingLink } = this;
const hasLink = !!this.firstLink;
const showInput = hasLink || firstFloatingLink?.isFloatingOutput;
const showOutput = hasLink || firstFloatingLink?.isFloatingInput;
const showEither = showInput || showOutput;
if (showEither && isPointInRect(pos, this.#hoverArea)) {
const outlineOnly = this.#contains(pos);
if (showInput) input.update(pos, outlineOnly);
if (showOutput) output.update(pos, outlineOnly);
} else {
this.hideSlots();
}
return input.dirty || output.dirty;
}
/** Prevents rendering of the input and output slots. */
hideSlots() {
this.#inputSlot.hide();
this.#outputSlot.hide();
}
/**
* Precisely determines if {@link pos} is inside this reroute.
* @param pos The position to check (canvas space)
* @returns `true` if {@link pos} is within the reroute's radius.
*/
containsPoint(pos) {
return isPointInRect(pos, this.#hoverArea) && this.#contains(pos);
}
#contains(pos) {
return distance(this.pos, pos) <= Reroute.radius;
}
/** @inheritdoc */
asSerialisable() {
const { id, parentId, pos, linkIds } = this;
return {
id,
parentId,
pos: [pos[0], pos[1]],
linkIds: [...linkIds],
floating: this.floating ? { slotType: this.floating.slotType } : void 0
};
}
}
class RerouteSlot {
/** The reroute that the slot belongs to. */
#reroute;
#offsetMultiplier;
/** Centre point of this slot. */
get pos() {
const [x2, y] = this.#reroute.pos;
return [x2 + Reroute.slotOffset * this.#offsetMultiplier, y];
}
/** Whether any changes require a redraw. */
dirty = false;
#hovering = false;
/** Whether the pointer is hovering over the slot itself. */
get hovering() {
return this.#hovering;
}
set hovering(value) {
if (!Object.is(this.#hovering, value)) {
this.#hovering = value;
this.dirty = true;
}
}
#showOutline = false;
/** Whether the slot outline / faint background is visible. */
get showOutline() {
return this.#showOutline;
}
set showOutline(value) {
if (!Object.is(this.#showOutline, value)) {
this.#showOutline = value;
this.dirty = true;
}
}
constructor(reroute, isInput) {
this.#reroute = reroute;
this.#offsetMultiplier = isInput ? -1 : 1;
}
/**
* Updates the slot's visibility based on the position of the pointer.
* @param pos The position of the pointer.
* @param outlineOnly If `true`, slot will display with the faded outline only ({@link showOutline}).
*/
update(pos, outlineOnly) {
if (outlineOnly) {
this.hovering = false;
this.showOutline = true;
} else {
const dist = distance(this.pos, pos);
this.hovering = dist <= 2 * Reroute.slotRadius;
this.showOutline = dist <= 5 * Reroute.slotRadius;
}
}
/** Hides the slot. */
hide() {
this.hovering = false;
this.showOutline = false;
}
/**
* Draws the slot on the canvas.
* @param ctx The canvas context to draw on.
*/
draw(ctx) {
const { fillStyle, strokeStyle, lineWidth } = ctx;
const { showOutline, hovering, pos: [x2, y] } = this;
if (!showOutline) return;
try {
ctx.fillStyle = hovering ? this.#reroute.colour : "rgba(127,127,127,0.3)";
ctx.strokeStyle = "rgb(0,0,0,0.5)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(x2, y, Reroute.slotRadius, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
} finally {
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
}
}
}
function getNextPos(network, link, id) {
if (!link) return;
const linkPos = LLink.findNextReroute(network, link, id)?.pos;
if (linkPos) return linkPos;
if (link.target_id === -1 || link.target_slot === -1) return;
return network.getNodeById(link.target_id)?.getInputPos(link.target_slot);
}
function getDirection(fromPos, toPos) {
return Math.atan2(toPos[1] - fromPos[1], toPos[0] - fromPos[0]);
}
function getBoundaryNodes(nodes) {
const valid = nodes?.find((x2) => x2);
if (!valid) return null;
let top = valid;
let right = valid;
let bottom = valid;
let left = valid;
for (const node2 of nodes) {
if (!node2) continue;
const [x2, y] = node2.pos;
const [width2, height] = node2.size;
if (y < top.pos[1]) top = node2;
if (x2 + width2 > right.pos[0] + right.size[0]) right = node2;
if (y + height > bottom.pos[1] + bottom.size[1]) bottom = node2;
if (x2 < left.pos[0]) left = node2;
}
return {
top,
right,
bottom,
left
};
}
function distributeNodes(nodes, horizontal) {
const nodeCount = nodes?.length;
if (!(nodeCount > 1)) return;
const index = horizontal ? 0 : 1;
let total = 0;
let highest = -Infinity;
for (const node2 of nodes) {
total += node2.size[index];
const high = node2.pos[index] + node2.size[index];
if (high > highest) highest = high;
}
const sorted = [...nodes].sort((a, b) => a.pos[index] - b.pos[index]);
const lowest = sorted[0].pos[index];
const gap = (highest - lowest - total) / (nodeCount - 1);
let startAt = lowest;
for (let i = 0; i < nodeCount; i++) {
const node2 = sorted[i];
node2.pos[index] = startAt + gap * i;
startAt += node2.size[index];
}
}
function alignNodes(nodes, direction, align_to) {
if (!nodes) return;
const boundary = align_to === void 0 ? getBoundaryNodes(nodes) : { top: align_to, right: align_to, bottom: align_to, left: align_to };
if (boundary === null) return;
for (const node2 of nodes) {
switch (direction) {
case "right":
node2.pos[0] = boundary.right.pos[0] + boundary.right.size[0] - node2.size[0];
break;
case "left":
node2.pos[0] = boundary.left.pos[0];
break;
case "top":
node2.pos[1] = boundary.top.pos[1];
break;
case "bottom":
node2.pos[1] = boundary.bottom.pos[1] + boundary.bottom.size[1] - node2.size[1];
break;
}
}
}
const cursors = {
NE: "nesw-resize",
SE: "nwse-resize",
SW: "nesw-resize",
NW: "nwse-resize"
};
class LGraphCanvas {
// Optimised buffers used during rendering
static #temp = new Float32Array(4);
static #temp_vec2 = new Float32Array(2);
static #tmp_area = new Float32Array(4);
static #margin_area = new Float32Array(4);
static #link_bounding = new Float32Array(4);
static #lTempA = new Float32Array(2);
static #lTempB = new Float32Array(2);
static #lTempC = new Float32Array(2);
static DEFAULT_BACKGROUND_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=";
static DEFAULT_EVENT_LINK_COLOR = "#A86";
/** Link type to colour dictionary. */
static link_type_colors = {
"-1": LGraphCanvas.DEFAULT_EVENT_LINK_COLOR,
"number": "#AAA",
"node": "#DCA"
};
static gradients = {};
static search_limit = -1;
static node_colors = {
red: { color: "#322", bgcolor: "#533", groupcolor: "#A88" },
brown: { color: "#332922", bgcolor: "#593930", groupcolor: "#b06634" },
green: { color: "#232", bgcolor: "#353", groupcolor: "#8A8" },
blue: { color: "#223", bgcolor: "#335", groupcolor: "#88A" },
pale_blue: {
color: "#2a363b",
bgcolor: "#3f5159",
groupcolor: "#3f789e"
},
cyan: { color: "#233", bgcolor: "#355", groupcolor: "#8AA" },
purple: { color: "#323", bgcolor: "#535", groupcolor: "#a1309b" },
yellow: { color: "#432", bgcolor: "#653", groupcolor: "#b58b2a" },
black: { color: "#222", bgcolor: "#000", groupcolor: "#444" }
};
/**
* @internal Exclusively a workaround for design limitation in {@link LGraphNode.computeSize}.
*/
static _measureText;
/**
* The state of this canvas, e.g. whether it is being dragged, or read-only.
*
* Implemented as a POCO that can be proxied without side-effects.
*/
state = {
draggingItems: false,
draggingCanvas: false,
readOnly: false,
hoveringOver: CanvasItem.Nothing,
shouldSetCursor: true,
selectionChanged: false
};
#updateCursorStyle() {
if (!this.state.shouldSetCursor) return;
let cursor = "default";
if (this.state.draggingCanvas) {
cursor = "grabbing";
} else if (this.state.readOnly) {
cursor = "grab";
} else if (this.pointer.resizeDirection) {
cursor = cursors[this.pointer.resizeDirection] ?? cursors.SE;
} else if (this.state.hoveringOver & CanvasItem.Node) {
cursor = "crosshair";
} else if (this.state.hoveringOver & CanvasItem.Reroute) {
cursor = "grab";
} else if (this.state.hoveringOver & CanvasItem.RerouteSlot) {
cursor = "crosshair";
}
this.canvas.style.cursor = cursor;
}
// Whether the canvas was previously being dragged prior to pressing space key.
// null if space key is not pressed.
_previously_dragging_canvas = null;
// #region Legacy accessors
/** @deprecated @inheritdoc {@link LGraphCanvasState.readOnly} */
get read_only() {
return this.state.readOnly;
}
set read_only(value) {
this.state.readOnly = value;
this.#updateCursorStyle();
}
get isDragging() {
return this.state.draggingItems;
}
set isDragging(value) {
this.state.draggingItems = value;
}
get hoveringOver() {
return this.state.hoveringOver;
}
set hoveringOver(value) {
this.state.hoveringOver = value;
this.#updateCursorStyle();
}
/** @deprecated Replace all references with {@link pointer}.{@link CanvasPointer.isDown isDown}. */
get pointer_is_down() {
return this.pointer.isDown;
}
/** @deprecated Replace all references with {@link pointer}.{@link CanvasPointer.isDouble isDouble}. */
get pointer_is_double() {
return this.pointer.isDouble;
}
/** @deprecated @inheritdoc {@link LGraphCanvasState.draggingCanvas} */
get dragging_canvas() {
return this.state.draggingCanvas;
}
set dragging_canvas(value) {
this.state.draggingCanvas = value;
this.#updateCursorStyle();
}
/**
* @deprecated Use {@link LGraphNode.titleFontStyle} instead.
*/
get title_text_font() {
return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
}
// #endregion Legacy accessors
get inner_text_font() {
return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}`;
}
#maximumFrameGap = 0;
/** Maximum frames per second to render. 0: unlimited. Default: 0 */
get maximumFps() {
return this.#maximumFrameGap > Number.EPSILON ? this.#maximumFrameGap / 1e3 : 0;
}
set maximumFps(value) {
this.#maximumFrameGap = value > Number.EPSILON ? 1e3 / value : 0;
}
/**
* @deprecated Use {@link LiteGraphGlobal.ROUND_RADIUS} instead.
*/
get round_radius() {
return LiteGraph.ROUND_RADIUS;
}
/**
* @deprecated Use {@link LiteGraphGlobal.ROUND_RADIUS} instead.
*/
set round_radius(value) {
LiteGraph.ROUND_RADIUS = value;
}
/**
* Render low quality when zoomed out.
*/
get low_quality() {
return this.ds.scale < this.low_quality_zoom_threshold;
}
options;
background_image;
ds;
pointer;
zoom_modify_alpha;
zoom_speed;
node_title_color;
default_link_color;
default_connection_color;
default_connection_color_byType;
default_connection_color_byTypeOff;
/** Gets link colours. Extremely basic impl. until the legacy object dictionaries are removed. */
colourGetter = {
getConnectedColor: (type) => this.default_connection_color_byType[type] || this.default_connection_color.output_on,
getDisconnectedColor: (type) => this.default_connection_color_byTypeOff[type] || this.default_connection_color_byType[type] || this.default_connection_color.output_off
};
highquality_render;
use_gradients;
editor_alpha;
pause_rendering;
clear_background;
clear_background_color;
render_only_selected;
show_info;
allow_dragcanvas;
allow_dragnodes;
allow_interaction;
multi_select;
allow_searchbox;
allow_reconnect_links;
align_to_grid;
drag_mode;
dragging_rectangle;
filter;
set_canvas_dirty_on_mouse_event;
always_render_background;
render_shadows;
render_canvas_border;
render_connections_shadows;
render_connections_border;
render_curved_connections;
render_connection_arrows;
render_collapsed_slots;
render_execution_order;
render_link_tooltip;
/** Shape of the markers shown at the midpoint of links. Default: Circle */
linkMarkerShape = LinkMarkerShape.Circle;
links_render_mode;
/** Zoom threshold for low quality rendering. Zoom below this threshold will render low quality. */
low_quality_zoom_threshold = 0.6;
/** mouse in canvas coordinates, where 0,0 is the top-left corner of the blue rectangle */
mouse;
/** mouse in graph coordinates, where 0,0 is the top-left corner of the blue rectangle */
graph_mouse;
/** @deprecated LEGACY: REMOVE THIS, USE {@link graph_mouse} INSTEAD */
canvas_mouse;
/** to personalize the search box */
onSearchBox;
onSearchBoxSelection;
onMouse;
/** to render background objects (behind nodes and connections) in the canvas affected by transform */
onDrawBackground;
/** to render foreground objects (above nodes and connections) in the canvas affected by transform */
onDrawForeground;
connections_width;
/** The current node being drawn by {@link drawNode}. This should NOT be used to determine the currently selected node. See {@link selectedItems} */
current_node;
/** used for widgets */
node_widget;
/** The link to draw a tooltip for. */
over_link_center;
last_mouse_position;
/** The visible area of this canvas. Tightly coupled with {@link ds}. */
visible_area;
/** Contains all links and reroutes that were rendered. Repopulated every render cycle. */
renderedPaths = /* @__PURE__ */ new Set();
/** @deprecated Replaced by {@link renderedPaths}, but length is set to 0 by some extensions. */
visible_links = [];
/** @deprecated This array is populated and cleared to support legacy extensions. The contents are ignored by Litegraph. */
connecting_links;
linkConnector = new LinkConnector((links) => this.connecting_links = links);
/** The viewport of this canvas. Tightly coupled with {@link ds}. */
viewport;
autoresize;
static active_canvas;
frame = 0;
last_draw_time = 0;
render_time = 0;
fps = 0;
/** @deprecated See {@link LGraphCanvas.selectedItems} */
selected_nodes = {};
/** All selected nodes, groups, and reroutes */
selectedItems = /* @__PURE__ */ new Set();
/** The group currently being resized. */
resizingGroup = null;
/** @deprecated See {@link LGraphCanvas.selectedItems} */
selected_group = null;
/** The nodes that are currently visible on the canvas. */
visible_nodes = [];
/**
* The IDs of the nodes that are currently visible on the canvas. More
* performant than {@link visible_nodes} for visibility checks.
*/
#visible_node_ids = /* @__PURE__ */ new Set();
node_over;
node_capturing_input;
highlighted_links = {};
#visibleReroutes = /* @__PURE__ */ new Set();
dirty_canvas = true;
dirty_bgcanvas = true;
/** A map of nodes that require selective-redraw */
dirty_nodes = /* @__PURE__ */ new Map();
dirty_area;
/** @deprecated Unused */
node_in_panel;
last_mouse = [0, 0];
last_mouseclick = 0;
graph;
canvas;
bgcanvas;
ctx;
_events_binded;
bgctx;
is_rendering;
/** @deprecated Panels */
block_click;
/** @deprecated Panels */
last_click_position;
resizing_node;
/** @deprecated See {@link LGraphCanvas.resizingGroup} */
selected_group_resizing;
/** @deprecated See {@link pointer}.{@link CanvasPointer.dragStarted dragStarted} */
last_mouse_dragging;
onMouseDown;
_highlight_pos;
_highlight_input;
// TODO: Check if panels are used
/** @deprecated Panels */
node_panel;
/** @deprecated Panels */
options_panel;
_bg_img;
_pattern;
_pattern_img;
// TODO: This looks like another panel thing
prompt_box;
search_box;
/** @deprecated Panels */
SELECTED_NODE;
/** @deprecated Panels */
NODEPANEL_IS_OPEN;
/** Once per frame check of snap to grid value. @todo Update on change. */
#snapToGrid;
/** Set on keydown, keyup. @todo */
#shiftDown = false;
/** If true, enable drag zoom. Ctrl+Shift+Drag Up/Down: zoom canvas. */
dragZoomEnabled = false;
/** The start position of the drag zoom. */
#dragZoomStart = null;
static active_node;
onClear;
/** called after moving a node @deprecated Does not handle multi-node move, and can return the wrong node. */
onNodeMoved;
/** @deprecated Called with the deprecated {@link selected_nodes} when the selection changes. Replacement not yet impl. */
onSelectionChange;
/** called when rendering a tooltip */
onDrawLinkTooltip;
/** to render foreground objects not affected by transform (for GUIs) */
onDrawOverlay;
onRenderBackground;
onNodeDblClicked;
onShowNodePanel;
onNodeSelected;
onNodeDeselected;
onRender;
/**
* Creates a new instance of LGraphCanvas.
* @param canvas The canvas HTML element (or its id) to use, or null / undefined to leave blank.
* @param graph The graph that owns this canvas.
* @param options
*/
constructor(canvas2, graph, options) {
options ||= {};
this.options = options;
this.background_image = LGraphCanvas.DEFAULT_BACKGROUND_IMAGE;
this.ds = new DragAndScale(canvas2);
this.pointer = new CanvasPointer(canvas2);
this.linkConnector.events.addEventListener("reset", () => {
this.connecting_links = null;
});
this.linkConnector.events.addEventListener("dropped-on-canvas", (customEvent) => {
if (!this.connecting_links) return;
const e2 = customEvent.detail;
this.emitEvent({
subType: "empty-release",
originalEvent: e2,
linkReleaseContext: { links: this.connecting_links }
});
const firstLink = this.linkConnector.renderLinks[0];
if (LiteGraph.release_link_on_empty_shows_menu) {
const linkReleaseContext = this.linkConnector.state.connectingTo === "input" ? {
node_from: firstLink.node,
slot_from: firstLink.fromSlot,
type_filter_in: firstLink.fromSlot.type
} : {
node_to: firstLink.node,
slot_from: firstLink.fromSlot,
type_filter_out: firstLink.fromSlot.type
};
const afterRerouteId = firstLink.fromReroute?.id;
if ("shiftKey" in e2 && e2.shiftKey) {
if (this.allow_searchbox) {
this.showSearchBox(e2, linkReleaseContext);
}
} else if (this.linkConnector.state.connectingTo === "input") {
this.showConnectionMenu({ nodeFrom: firstLink.node, slotFrom: firstLink.fromSlot, e: e2, afterRerouteId });
} else {
this.showConnectionMenu({ nodeTo: firstLink.node, slotTo: firstLink.fromSlot, e: e2, afterRerouteId });
}
}
});
this.zoom_modify_alpha = true;
this.zoom_speed = 1.1;
this.node_title_color = LiteGraph.NODE_TITLE_COLOR;
this.default_link_color = LiteGraph.LINK_COLOR;
this.default_connection_color = {
input_off: "#778",
input_on: "#7F7",
output_off: "#778",
output_on: "#7F7"
};
this.default_connection_color_byType = {
/* number: "#7F7",
string: "#77F",
boolean: "#F77", */
};
this.default_connection_color_byTypeOff = {
/* number: "#474",
string: "#447",
boolean: "#744", */
};
this.highquality_render = true;
this.use_gradients = false;
this.editor_alpha = 1;
this.pause_rendering = false;
this.clear_background = true;
this.clear_background_color = "#222";
this.render_only_selected = true;
this.show_info = true;
this.allow_dragcanvas = true;
this.allow_dragnodes = true;
this.allow_interaction = true;
this.multi_select = false;
this.allow_searchbox = true;
this.allow_reconnect_links = true;
this.align_to_grid = false;
this.drag_mode = false;
this.dragging_rectangle = null;
this.filter = null;
this.set_canvas_dirty_on_mouse_event = true;
this.always_render_background = false;
this.render_shadows = true;
this.render_canvas_border = true;
this.render_connections_shadows = false;
this.render_connections_border = true;
this.render_curved_connections = false;
this.render_connection_arrows = false;
this.render_collapsed_slots = true;
this.render_execution_order = false;
this.render_link_tooltip = true;
this.links_render_mode = LinkRenderType.SPLINE_LINK;
this.mouse = [0, 0];
this.graph_mouse = [0, 0];
this.canvas_mouse = this.graph_mouse;
this.connections_width = 3;
this.current_node = null;
this.node_widget = null;
this.last_mouse_position = [0, 0];
this.visible_area = this.ds.visible_area;
this.connecting_links = null;
this.viewport = options.viewport || null;
this.graph = graph;
graph?.attachCanvas(this);
this.canvas = void 0;
this.bgcanvas = void 0;
this.ctx = void 0;
this.setCanvas(canvas2, options.skip_events);
this.clear();
LGraphCanvas._measureText = (text, fontStyle = this.inner_text_font) => {
const { ctx } = this;
const { font } = ctx;
try {
ctx.font = fontStyle;
return ctx.measureText(text).width;
} finally {
ctx.font = font;
}
};
if (!options.skip_render) {
this.startRendering();
}
this.autoresize = options.autoresize;
}
static onGroupAdd(info, entry, mouse_event) {
const canvas2 = LGraphCanvas.active_canvas;
const group = new LiteGraph.LGraphGroup();
group.pos = canvas2.convertEventToCanvasOffset(mouse_event);
if (!canvas2.graph) throw new NullGraphError();
canvas2.graph.add(group);
}
/**
* @deprecated Functionality moved to {@link getBoundaryNodes}. The new function returns null on failure, instead of an object with all null properties.
* Determines the furthest nodes in each direction
* @param nodes the nodes to from which boundary nodes will be extracted
* @returns
*/
static getBoundaryNodes(nodes) {
const _nodes = Array.isArray(nodes) ? nodes : Object.values(nodes);
return getBoundaryNodes(_nodes) ?? {
top: null,
right: null,
bottom: null,
left: null
};
}
/**
* @deprecated Functionality moved to {@link alignNodes}. The new function does not set dirty canvas.
* @param nodes a list of nodes
* @param direction Direction to align the nodes
* @param align_to Node to align to (if null, align to the furthest node in the given direction)
*/
static alignNodes(nodes, direction, align_to) {
alignNodes(Object.values(nodes), direction, align_to);
LGraphCanvas.active_canvas.setDirty(true, true);
}
static onNodeAlign(value, options, event, prev_menu, node2) {
new LiteGraph.ContextMenu(["Top", "Bottom", "Left", "Right"], {
event,
callback: inner_clicked,
parentMenu: prev_menu
});
function inner_clicked(value2) {
alignNodes(
Object.values(LGraphCanvas.active_canvas.selected_nodes),
value2.toLowerCase(),
node2
);
LGraphCanvas.active_canvas.setDirty(true, true);
}
}
static onGroupAlign(value, options, event, prev_menu) {
new LiteGraph.ContextMenu(["Top", "Bottom", "Left", "Right"], {
event,
callback: inner_clicked,
parentMenu: prev_menu
});
function inner_clicked(value2) {
alignNodes(
Object.values(LGraphCanvas.active_canvas.selected_nodes),
value2.toLowerCase()
);
LGraphCanvas.active_canvas.setDirty(true, true);
}
}
static createDistributeMenu(value, options, event, prev_menu) {
new LiteGraph.ContextMenu(["Vertically", "Horizontally"], {
event,
callback: inner_clicked,
parentMenu: prev_menu
});
function inner_clicked(value2) {
const canvas2 = LGraphCanvas.active_canvas;
distributeNodes(Object.values(canvas2.selected_nodes), value2 === "Horizontally");
canvas2.setDirty(true, true);
}
}
static onMenuAdd(value, options, e2, prev_menu, callback) {
const canvas2 = LGraphCanvas.active_canvas;
const ref_window = canvas2.getCanvasWindow();
const { graph } = canvas2;
if (!graph) return;
inner_onMenuAdded("", prev_menu);
return false;
function inner_onMenuAdded(base_category, prev_menu2) {
if (!graph) return;
const categories = LiteGraph.getNodeTypesCategories(canvas2.filter || graph.filter).filter((category) => category.startsWith(base_category));
const entries = [];
for (const category of categories) {
if (!category) continue;
const base_category_regex = new RegExp(`^(${base_category})`);
const category_name = category.replace(base_category_regex, "").split("/", 1)[0];
const category_path = base_category === "" ? `${category_name}/` : `${base_category}${category_name}/`;
let name = category_name;
if (name.includes("::")) name = name.split("::", 2)[1];
const index = entries.findIndex((entry) => entry.value === category_path);
if (index === -1) {
entries.push({
value: category_path,
content: name,
has_submenu: true,
callback: function(value2, event, mouseEvent, contextMenu) {
inner_onMenuAdded(value2.value, contextMenu);
}
});
}
}
const nodes = LiteGraph.getNodeTypesInCategory(
base_category.slice(0, -1),
canvas2.filter || graph.filter
);
for (const node2 of nodes) {
if (node2.skip_list) continue;
const entry = {
value: node2.type,
content: node2.title,
has_submenu: false,
callback: function(value2, event, mouseEvent, contextMenu) {
if (!canvas2.graph) throw new NullGraphError();
const first_event = contextMenu.getFirstEvent();
canvas2.graph.beforeChange();
const node22 = LiteGraph.createNode(value2.value);
if (node22) {
if (!first_event) throw new TypeError("Context menu event was null. This should not occur in normal usage.");
node22.pos = canvas2.convertEventToCanvasOffset(first_event);
canvas2.graph.add(node22);
} else {
console.warn("Failed to create node of type:", value2.value);
}
callback?.(node22);
canvas2.graph.afterChange();
}
};
entries.push(entry);
}
new LiteGraph.ContextMenu(entries, { event: e2, parentMenu: prev_menu2 }, ref_window);
}
}
static onMenuCollapseAll() {
}
static onMenuNodeEdit() {
}
/** @param _options Parameter is never used */
static showMenuNodeOptionalOutputs(v2, _options, e2, prev_menu, node2) {
if (!node2) return;
const canvas2 = LGraphCanvas.active_canvas;
let entries = [];
if (LiteGraph.do_add_triggers_slots && node2.findOutputSlot("onExecuted") == -1) {
entries.push({ content: "On Executed", value: ["onExecuted", LiteGraph.EVENT, { nameLocked: true }], className: "event" });
}
const retEntries = node2.onMenuNodeOutputs?.(entries);
if (retEntries) entries = retEntries;
if (!entries.length) return;
new LiteGraph.ContextMenu(
entries,
{
event: e2,
callback: inner_clicked,
parentMenu: prev_menu,
node: node2
}
);
function inner_clicked(v22, e22, prev) {
if (!node2) return;
if (v22.callback) v22.callback.call(this, node2, v22, e22, prev);
if (!v22.value) return;
const value = v22.value[1];
if (value && (typeof value === "object" || Array.isArray(value))) {
const entries2 = [];
for (const i in value) {
entries2.push({ content: i, value: value[i] });
}
new LiteGraph.ContextMenu(entries2, {
event: e22,
callback: inner_clicked,
parentMenu: prev_menu,
node: node2
});
return false;
}
const { graph } = node2;
if (!graph) throw new NullGraphError();
graph.beforeChange();
node2.addOutput(v22.value[0], v22.value[1], v22.value[2]);
node2.onNodeOutputAdd?.(v22.value);
canvas2.setDirty(true, true);
graph.afterChange();
}
return false;
}
/** @param value Parameter is never used */
static onShowMenuNodeProperties(value, options, e2, prev_menu, node2) {
if (!node2 || !node2.properties) return;
const canvas2 = LGraphCanvas.active_canvas;
const ref_window = canvas2.getCanvasWindow();
const entries = [];
for (const i in node2.properties) {
value = node2.properties[i] !== void 0 ? node2.properties[i] : " ";
if (typeof value == "object")
value = JSON.stringify(value);
const info = node2.getPropertyInfo(i);
if (info.type == "enum" || info.type == "combo")
value = LGraphCanvas.getPropertyPrintableValue(value, info.values);
value = LGraphCanvas.decodeHTML(stringOrEmpty(value));
entries.push({
content: `${info.label || i}${value}`,
value: i
});
}
if (!entries.length) {
return;
}
new LiteGraph.ContextMenu(
entries,
{
event: e2,
callback: inner_clicked,
parentMenu: prev_menu,
allow_html: true,
node: node2
},
// @ts-expect-error Unused
ref_window
);
function inner_clicked(v2) {
if (!node2) return;
const rect = this.getBoundingClientRect();
canvas2.showEditPropertyValue(node2, v2.value, {
position: [rect.left, rect.top]
});
}
return false;
}
/** @deprecated */
static decodeHTML(str) {
const e2 = document.createElement("div");
e2.textContent = str;
return e2.innerHTML;
}
static onMenuResizeNode(value, options, e2, menu, node2) {
if (!node2) return;
const fApplyMultiNode = function(node22) {
node22.setSize(node22.computeSize());
};
const canvas2 = LGraphCanvas.active_canvas;
if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
fApplyMultiNode(node2);
} else {
for (const i in canvas2.selected_nodes) {
fApplyMultiNode(canvas2.selected_nodes[i]);
}
}
canvas2.setDirty(true, true);
}
// TODO refactor :: this is used fot title but not for properties!
static onShowPropertyEditor(item, options, e2, menu, node2) {
const property = item.property || "title";
const value = node2[property];
const title = document.createElement("span");
title.className = "name";
title.textContent = property;
const input = document.createElement("input");
Object.assign(input, { type: "text", className: "value", autofocus: true });
const button = document.createElement("button");
button.textContent = "OK";
const dialog = Object.assign(document.createElement("div"), {
is_modified: false,
className: "graphdialog",
close: () => dialog.remove()
});
dialog.append(title, input, button);
input.value = String(value);
input.addEventListener("blur", function() {
this.focus();
});
input.addEventListener("keydown", (e22) => {
dialog.is_modified = true;
if (e22.key == "Escape") {
dialog.close();
} else if (e22.key == "Enter") {
inner();
} else if (!e22.target || !("localName" in e22.target) || e22.target.localName != "textarea") {
return;
}
e22.preventDefault();
e22.stopPropagation();
});
const canvas2 = LGraphCanvas.active_canvas;
const canvasEl = canvas2.canvas;
const rect = canvasEl.getBoundingClientRect();
const offsetx = rect ? -20 - rect.left : -20;
const offsety = rect ? -20 - rect.top : -20;
if (e2) {
dialog.style.left = `${e2.clientX + offsetx}px`;
dialog.style.top = `${e2.clientY + offsety}px`;
} else {
dialog.style.left = `${canvasEl.width * 0.5 + offsetx}px`;
dialog.style.top = `${canvasEl.height * 0.5 + offsety}px`;
}
button.addEventListener("click", inner);
if (canvasEl.parentNode == null) throw new TypeError("canvasEl.parentNode was null");
canvasEl.parentNode.append(dialog);
input.focus();
let dialogCloseTimer;
dialog.addEventListener("mouseleave", function() {
if (LiteGraph.dialog_close_on_mouse_leave) {
if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) {
dialogCloseTimer = setTimeout(
dialog.close,
LiteGraph.dialog_close_on_mouse_leave_delay
);
}
}
});
dialog.addEventListener("mouseenter", function() {
if (LiteGraph.dialog_close_on_mouse_leave) {
if (dialogCloseTimer) clearTimeout(dialogCloseTimer);
}
});
function inner() {
if (input) setValue(input.value);
}
function setValue(value2) {
if (item.type == "Number") {
value2 = Number(value2);
} else if (item.type == "Boolean") {
value2 = Boolean(value2);
}
node2[property] = value2;
dialog.remove();
canvas2.setDirty(true, true);
}
}
static getPropertyPrintableValue(value, values) {
if (!values) return String(value);
if (Array.isArray(values)) {
return String(value);
}
if (typeof values === "object") {
let desc_value = "";
for (const k in values) {
if (values[k] != value) continue;
desc_value = k;
break;
}
return `${String(value)} (${desc_value})`;
}
}
static onMenuNodeCollapse(value, options, e2, menu, node2) {
if (!node2.graph) throw new NullGraphError();
node2.graph.beforeChange();
const fApplyMultiNode = function(node22) {
node22.collapse();
};
const graphcanvas = LGraphCanvas.active_canvas;
if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {
fApplyMultiNode(node2);
} else {
for (const i in graphcanvas.selected_nodes) {
fApplyMultiNode(graphcanvas.selected_nodes[i]);
}
}
node2.graph.afterChange();
}
static onMenuToggleAdvanced(value, options, e2, menu, node2) {
if (!node2.graph) throw new NullGraphError();
node2.graph.beforeChange();
const fApplyMultiNode = function(node22) {
node22.toggleAdvanced();
};
const graphcanvas = LGraphCanvas.active_canvas;
if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {
fApplyMultiNode(node2);
} else {
for (const i in graphcanvas.selected_nodes) {
fApplyMultiNode(graphcanvas.selected_nodes[i]);
}
}
node2.graph.afterChange();
}
static onMenuNodeMode(value, options, e2, menu, node2) {
new LiteGraph.ContextMenu(
LiteGraph.NODE_MODES,
{ event: e2, callback: inner_clicked, parentMenu: menu, node: node2 }
);
function inner_clicked(v2) {
if (!node2) return;
const kV = Object.values(LiteGraph.NODE_MODES).indexOf(v2);
const fApplyMultiNode = function(node22) {
if (kV !== -1 && LiteGraph.NODE_MODES[kV]) {
node22.changeMode(kV);
} else {
console.warn(`unexpected mode: ${v2}`);
node22.changeMode(LGraphEventMode.ALWAYS);
}
};
const graphcanvas = LGraphCanvas.active_canvas;
if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {
fApplyMultiNode(node2);
} else {
for (const i in graphcanvas.selected_nodes) {
fApplyMultiNode(graphcanvas.selected_nodes[i]);
}
}
}
return false;
}
/** @param value Parameter is never used */
static onMenuNodeColors(value, options, e2, menu, node2) {
if (!node2) throw "no node for color";
const values = [];
values.push({
value: null,
content: "No color"
});
for (const i in LGraphCanvas.node_colors) {
const color = LGraphCanvas.node_colors[i];
value = {
value: i,
content: `${i}`
};
values.push(value);
}
new LiteGraph.ContextMenu(values, {
event: e2,
callback: inner_clicked,
parentMenu: menu,
node: node2
});
function inner_clicked(v2) {
if (!node2) return;
const fApplyColor = function(item) {
const colorOption = v2.value ? LGraphCanvas.node_colors[v2.value] : null;
item.setColorOption(colorOption);
};
const canvas2 = LGraphCanvas.active_canvas;
if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
fApplyColor(node2);
} else {
for (const i in canvas2.selected_nodes) {
fApplyColor(canvas2.selected_nodes[i]);
}
}
canvas2.setDirty(true, true);
}
return false;
}
static onMenuNodeShapes(value, options, e2, menu, node2) {
if (!node2) throw "no node passed";
new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, {
event: e2,
callback: inner_clicked,
parentMenu: menu,
node: node2
});
function inner_clicked(v2) {
if (!node2) return;
if (!node2.graph) throw new NullGraphError();
node2.graph.beforeChange();
const fApplyMultiNode = function(node22) {
node22.shape = v2;
};
const canvas2 = LGraphCanvas.active_canvas;
if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
fApplyMultiNode(node2);
} else {
for (const i in canvas2.selected_nodes) {
fApplyMultiNode(canvas2.selected_nodes[i]);
}
}
node2.graph.afterChange();
canvas2.setDirty(true);
}
return false;
}
static onMenuNodeRemove() {
LGraphCanvas.active_canvas.deleteSelected();
}
static onMenuNodeClone(value, options, e2, menu, node2) {
const { graph } = node2;
if (!graph) throw new NullGraphError();
graph.beforeChange();
const newSelected = /* @__PURE__ */ new Set();
const fApplyMultiNode = function(node22, newNodes) {
if (node22.clonable === false) return;
const newnode = node22.clone();
if (!newnode) return;
newnode.pos = [node22.pos[0] + 5, node22.pos[1] + 5];
if (!node22.graph) throw new NullGraphError();
node22.graph.add(newnode);
newNodes.add(newnode);
};
const canvas2 = LGraphCanvas.active_canvas;
if (!canvas2.selected_nodes || Object.keys(canvas2.selected_nodes).length <= 1) {
fApplyMultiNode(node2, newSelected);
} else {
for (const i in canvas2.selected_nodes) {
fApplyMultiNode(canvas2.selected_nodes[i], newSelected);
}
}
if (newSelected.size) {
canvas2.selectNodes([...newSelected]);
}
graph.afterChange();
canvas2.setDirty(true, true);
}
/**
* clears all the data inside
*
*/
clear() {
this.frame = 0;
this.last_draw_time = 0;
this.render_time = 0;
this.fps = 0;
this.dragging_rectangle = null;
this.selected_nodes = {};
this.selected_group = null;
this.selectedItems.clear();
this.state.selectionChanged = true;
this.onSelectionChange?.(this.selected_nodes);
this.visible_nodes = [];
this.node_over = void 0;
this.node_capturing_input = null;
this.connecting_links = null;
this.highlighted_links = {};
this.dragging_canvas = false;
this.#dirty();
this.dirty_area = null;
this.node_in_panel = null;
this.node_widget = null;
this.last_mouse = [0, 0];
this.last_mouseclick = 0;
this.pointer.reset();
this.visible_area.set([0, 0, 0, 0]);
this.onClear?.();
}
/**
* Assigns a new graph to this canvas.
*/
setGraph(newGraph) {
const { graph } = this;
if (newGraph === graph) return;
const options = {
bubbles: true,
detail: { newGraph, oldGraph: graph }
};
this.clear();
newGraph.attachCanvas(this);
this.canvas.dispatchEvent(new CustomEvent("litegraph:set-graph", options));
this.#dirty();
}
/**
* @returns the visually active graph (in case there are more in the stack)
*/
getCurrentGraph() {
return this.graph;
}
/**
* Finds the canvas if required, throwing on failure.
* @param canvas Canvas element, or its element ID
* @returns The canvas element
* @throws If {@link canvas} is an element ID that does not belong to a valid HTML canvas element
*/
#validateCanvas(canvas2) {
if (typeof canvas2 === "string") {
const el = document.getElementById(canvas2);
if (!(el instanceof HTMLCanvasElement)) throw "Error validating LiteGraph canvas: Canvas element not found";
return el;
}
return canvas2;
}
/**
* Sets the current HTML canvas element.
* Calls bindEvents to add input event listeners, and (re)creates the background canvas.
* @param canvas The canvas element to assign, or its HTML element ID. If null or undefined, the current reference is cleared.
* @param skip_events If true, events on the previous canvas will not be removed. Has no effect on the first invocation.
*/
setCanvas(canvas2, skip_events) {
const element = this.#validateCanvas(canvas2);
if (element === this.canvas) return;
if (!element && this.canvas && !skip_events) this.unbindEvents();
this.canvas = element;
this.ds.element = element;
this.pointer.element = element;
if (!element) return;
element.className += " lgraphcanvas";
element.data = this;
this.bgcanvas = document.createElement("canvas");
this.bgcanvas.width = this.canvas.width;
this.bgcanvas.height = this.canvas.height;
const ctx = element.getContext?.("2d");
if (ctx == null) {
if (element.localName != "canvas") {
throw `Element supplied for LGraphCanvas must be a