Add files via upload

This commit is contained in:
CGlide
2026-06-02 12:22:23 +02:00
committed by GitHub
parent 0604d7fb0e
commit 32a8bfa511
41 changed files with 40726 additions and 40471 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +1,17 @@
import { app } from "../../scripts/app.js";
// LTX Director Guide is a pure pass-through processor node.
// All configuration (images, insert frames, strengths) comes from
// the guide_data output of Prompt Relay Encode (Timeline).
// No dynamic widgets or sync logic needed.
app.registerExtension({
name: "Comfy.LTXDirectorGuide",
async nodeCreated(node) {
if (node.comfyClass !== "LTXDirectorGuide") return;
// Nothing to initialize — the node has no configurable widgets.
},
});
// Nothing to initialize — the node has no configurable widgets.
},
import { app } from "../../scripts/app.js";
// LTX Director Guide is a pure pass-through processor node.
// All configuration (images, insert frames, strengths) comes from
// the guide_data output of Prompt Relay Encode (Timeline).
// No dynamic widgets or sync logic needed.
app.registerExtension({
name: "Comfy.LTXDirectorGuide",
async nodeCreated(node) {
if (node.comfyClass !== "LTXDirectorGuide") return;
// Nothing to initialize — the node has no configurable widgets.
},
});
// Nothing to initialize — the node has no configurable widgets.
},
});

View File

@@ -1,419 +1,419 @@
import { app } from "../../scripts/app.js";
// Global registry to track all LTXKeyframer nodes across all subgraphs
window._LTXKeyframerGlobalNodes = window._LTXKeyframerGlobalNodes || new Set();
// ComfyUI native trick to cleanly hide/show widgets without deleting them
function toggleWidget(widget, visible) {
if (visible) {
if (widget.origType !== undefined) {
widget.type = widget.origType;
widget.computeSize = widget.origComputeSize;
delete widget.origType;
delete widget.origComputeSize;
}
} else {
if (widget.type !== "hidden") {
widget.origType = widget.type;
widget.origComputeSize = widget.computeSize;
widget.type = "hidden";
widget.computeSize = () => [0, -4];
}
}
}
// --- NEW SYNC HELPER FUNCTION ---
// Finds all other LTXKeyframer nodes globally and mirrors the value to them
function syncWidgetAcrossNodes(sourceNode, widgetName, value) {
if (!window._LTXKeyframerGlobalNodes) return;
for (const targetNode of window._LTXKeyframerGlobalNodes) {
// Target all OTHER LTXKeyframer nodes by direct object reference
if (targetNode !== sourceNode) {
// 1. Always update the hidden properties cache so it remembers the sync
// even if the widget isn't currently visible (e.g. fewer images loaded right now)
targetNode.properties[widgetName] = value;
// 2. If the widget is currently visible on the UI, update it visually
if (targetNode.widgets) {
const targetWidget = targetNode.widgets.find(w => w.name === widgetName);
if (targetWidget && targetWidget.value !== value) {
targetWidget.value = value;
targetNode.setDirtyCanvas(true, false);
}
}
}
}
}
app.registerExtension({
name: "Comfy.LTXKeyframer.DynamicInputs",
async nodeCreated(node) {
if (node.comfyClass !== "LTXKeyframer") return;
// Register this node instance globally
window._LTXKeyframerGlobalNodes.add(node);
node._currentImageCount = -1; // Force first update
// Initialize persistent properties cache
node.properties = node.properties || {};
// Add subtle separator line above images_loaded
node.addCustomWidget({
name: "num_images_separator",
type: "text",
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
ctx.strokeStyle = "#444";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, y + 5);
ctx.lineTo(widget_width - 10, y + 5);
ctx.stroke();
ctx.restore();
},
computeSize(width) {
return [width, 10];
}
});
// Move separator before num_images
const moveSeparator = () => {
const idx = node.widgets.findIndex(w => w.name === "num_images");
const sepIdx = node.widgets.findIndex(w => w.name === "num_images_separator");
if (idx !== -1 && sepIdx !== -1) {
const separator = node.widgets.splice(sepIdx, 1)[0];
node.widgets.splice(idx, 0, separator);
}
};
setTimeout(moveSeparator, 50); // Small delay to ensure num_images is present
// Core update: synchronize widget visibility to match imageCount
node._applyWidgetCount = function(count) {
const isInitialLoad = this._currentImageCount === -1;
if (this._currentImageCount === count && !isInitialLoad) return;
this._currentImageCount = count;
const initialWidth = this.size[0];
const numWidget = this.widgets?.find(w => w.name === "num_images");
if (numWidget) {
numWidget.label = "images_loaded";
numWidget.value = Math.max(0, Math.min(count || 0, 50));
}
// 1. Store current widget values in properties BEFORE removing them
// We skip reading from `this.widgets` on the initial load because it might be scrambling.
if (!isInitialLoad && this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
this.properties[w.name] = w.value;
}
});
}
// 2. Remove all existing dynamic insert_frame/strength/header widgets
if (this.widgets) {
this.widgets = this.widgets.filter(w =>
!w.name.startsWith("insert_frame_") &&
!w.name.startsWith("strength_") &&
!w.name.startsWith("header_")
);
} else {
this.widgets = [];
}
// 3. Add back exactly the right amount of widgets using the cached values
for (let i = 1; i <= count; i++) {
// Add header/separator widget for grouping
const headerName = `header_${i}`;
this.addCustomWidget({
name: headerName,
type: "text",
value: `Image #${i}`,
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
const margin = 10;
const topPadding = 15;
// Subtle separator line
ctx.strokeStyle = "#333";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(margin, y + 5);
ctx.lineTo(widget_width - margin, y + 5);
ctx.stroke();
// Text label
ctx.fillStyle = "#dddddd"; // Light gray
ctx.font = "bold 12px Arial";
ctx.textAlign = "left";
ctx.fillText(`Image #${i}`, margin, y + topPadding + 10);
ctx.restore();
},
computeSize(width) {
return [width, 35]; // Vertical gap + label height
}
});
const insertFrameWidgetName = `insert_frame_${i}`;
const strengthWidgetName = `strength_${i}`;
// Add insert_frame widget with Sync Callback
const savedInsertFrameValue = this.properties[insertFrameWidgetName];
this.addWidget("number", insertFrameWidgetName,
savedInsertFrameValue !== undefined ? savedInsertFrameValue : 0,
(value) => {
const rounded = Math.round(value);
this.properties[insertFrameWidgetName] = rounded;
syncWidgetAcrossNodes(this, insertFrameWidgetName, rounded); // Sync out
}, { min: -9999, max: 9999, step: 10, precision: 0 }
);
// Add strength widget with Sync Callback
const savedStrengthValue = this.properties[strengthWidgetName];
this.addWidget("number", strengthWidgetName,
savedStrengthValue !== undefined ? savedStrengthValue : 1.0,
(value) => {
this.properties[strengthWidgetName] = value;
syncWidgetAcrossNodes(this, strengthWidgetName, value); // Sync out
}, { min: 0.0, max: 1.0, step: 0.01 }
);
}
this.setDirtyCanvas(true, true);
requestAnimationFrame(() => {
if (this.computeSize) {
this.setSize(this.computeSize());
this.size[0] = initialWidth; // keep width fixed when restructuring
}
});
};
// --- STRICT ARRAY MAPPER: FIXES ALL SHIFTING FOREVER ---
// This runs the exact instant the node is loaded, before any UI widgets shift indices.
// It locks the perfectly mapped array values directly into our properties dictionary.
const origConfigure = node.configure;
node.configure = function(info) {
if (origConfigure) {
origConfigure.apply(this, arguments);
}
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name === "num_images" || w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
this.properties[w.name] = w.value;
}
});
}
};
// Handle deserialization to load properties properly from JSON
const originalOnConfigure = node.onConfigure;
node.onConfigure = function(info) {
if (originalOnConfigure) {
originalOnConfigure.apply(this, arguments);
}
if (info.properties) {
this.properties = { ...this.properties, ...info.properties };
}
setTimeout(() => {
const count = readSourceImageCount(this);
// Fallback to properties.num_images if source node disconnected
let targetCount = count !== null ? count : (this.properties.num_images || 0);
this._applyWidgetCount(targetCount);
}, 100);
};
// --- STRICT ARRAY GENERATOR ---
// Completely detach from ComfyUI's blind visual array saving.
// We construct an exact 101-element strict array that Python expects.
// This makes your node 100% immune to UI/Header index shifting.
const originalOnSerialize = node.onSerialize;
node.onSerialize = function(info) {
// Ensure properties are strictly synced with current widget values before building
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name === "num_images" || w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
this.properties[w.name] = w.value;
}
});
}
if (originalOnSerialize) {
originalOnSerialize.apply(this, arguments);
}
info.properties = { ...this.properties };
// Build the exact strict array that maps 1-to-1 to the Python backend
const strictArray = [];
const numWidgetVal = this.properties["num_images"];
strictArray.push(numWidgetVal !== undefined ? numWidgetVal : 1);
for (let i = 1; i <= 50; i++) {
const fVal = this.properties[`insert_frame_${i}`];
const sVal = this.properties[`strength_${i}`];
strictArray.push(fVal !== undefined ? fVal : 0);
strictArray.push(sVal !== undefined ? sVal : 1.0);
}
info.widgets_values = strictArray;
};
// Set up manual num_images widget callback
setTimeout(() => {
const numWidget = node.widgets?.find(w => w.name === "num_images");
if (numWidget) {
numWidget.callback = (val) => {
node.properties["num_images"] = val;
node._applyWidgetCount(val);
};
}
}, 100);
// Exposed receiver for push-based notifications
node._syncImageCount = function(count) {
this._applyWidgetCount(count);
};
// Helper: read image count from a connected MultiImageLoader node
function readSourceImageCount(self) {
const multiInput = self.inputs?.find(inp => inp.name === "multi_input");
if (!multiInput || !multiInput.link) return null;
const nodeGraph = self.graph || app.graph;
// Helper to safely trace back through Reroutes and ComfyUI Group Nodes/Subgraphs
function traceUpstream(graph, linkId, visited = new Set()) {
if (!linkId || visited.has(linkId)) return null;
visited.add(linkId);
const link = graph.links[linkId];
if (!link) return null;
const originNode = graph.getNodeById(link.origin_id);
if (!originNode) return null;
if (originNode.comfyClass === "MultiImageLoader") {
return originNode;
}
// Traverse Reroute nodes
if (originNode.type === "Reroute" || originNode.comfyClass === "Reroute") {
if (originNode.inputs && originNode.inputs.length > 0 && originNode.inputs[0].link) {
return traceUpstream(graph, originNode.inputs[0].link, visited);
}
}
// Traverse standard ComfyUI Group Nodes (subgraphs)
if (typeof originNode.getInnerNode === "function") {
try {
const innerNode = originNode.getInnerNode(link.origin_slot);
if (innerNode && innerNode.comfyClass === "MultiImageLoader") {
return innerNode;
}
} catch (e) {
console.warn("Could not trace inner node", e);
}
}
return null;
}
let sourceNode = traceUpstream(nodeGraph, multiInput.link);
// Helper to extract the count once we find a node
function getCountFromNode(n) {
if (typeof n._imageCount === "number") return n._imageCount;
const pathsWidget = n.widgets?.find(w => w.name === "image_paths");
if (pathsWidget) {
return (pathsWidget.value || "").split('\n').map(p => p.trim()).filter(p => p.length > 0).length;
}
return null;
}
if (sourceNode) {
return getCountFromNode(sourceNode);
}
// Fallback Strategy: If it is connected to something, but we couldn't resolve it
// directly (e.g. complex nested 3rd party subgraphs), scan the entire UI.
// If there is EXACTLY ONE MultiImageLoader in the workspace, safely assume that's the one.
let multiImageLoaders = [];
function findAllLoaders(nodes) {
if (!nodes) return;
for (let n of nodes) {
if (n.comfyClass === "MultiImageLoader") {
multiImageLoaders.push(n);
}
if (n.subgraph && n.subgraph._nodes) {
findAllLoaders(n.subgraph._nodes);
}
}
}
if (app.graph && app.graph._nodes) {
findAllLoaders(app.graph._nodes);
}
if (multiImageLoaders.length === 1) {
return getCountFromNode(multiImageLoaders[0]);
}
return null;
}
// --- Backup polling via setInterval (4 Hz) ---
const pollInterval = setInterval(() => {
if (!node.graph) {
clearInterval(pollInterval);
return;
}
const count = readSourceImageCount(node);
if (count !== null) {
node._applyWidgetCount(count);
}
}, 250);
// Clean up the interval when the node is deleted
const origOnRemoved = node.onRemoved;
node.onRemoved = function() {
// Unregister this node instance
window._LTXKeyframerGlobalNodes.delete(node);
clearInterval(pollInterval);
if (origOnRemoved) origOnRemoved.apply(this, arguments);
};
// --- Connection change handler ---
const onConnectionsChange = node.onConnectionsChange;
node.onConnectionsChange = function(type, index, connected, link_info) {
if (onConnectionsChange) onConnectionsChange.apply(this, arguments);
if (type === 1) { // 1 = Input
const input = this.inputs[index];
if (input && input.name === "multi_input") {
if (connected) {
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
} else {
this._applyWidgetCount(0);
}
}
}
};
// --- Initial sync when first placed on canvas ---
const origOnAdded = node.onAdded;
node.onAdded = function() {
if (origOnAdded) origOnAdded.apply(this, arguments);
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
};
}
import { app } from "../../scripts/app.js";
// Global registry to track all LTXKeyframer nodes across all subgraphs
window._LTXKeyframerGlobalNodes = window._LTXKeyframerGlobalNodes || new Set();
// ComfyUI native trick to cleanly hide/show widgets without deleting them
function toggleWidget(widget, visible) {
if (visible) {
if (widget.origType !== undefined) {
widget.type = widget.origType;
widget.computeSize = widget.origComputeSize;
delete widget.origType;
delete widget.origComputeSize;
}
} else {
if (widget.type !== "hidden") {
widget.origType = widget.type;
widget.origComputeSize = widget.computeSize;
widget.type = "hidden";
widget.computeSize = () => [0, -4];
}
}
}
// --- NEW SYNC HELPER FUNCTION ---
// Finds all other LTXKeyframer nodes globally and mirrors the value to them
function syncWidgetAcrossNodes(sourceNode, widgetName, value) {
if (!window._LTXKeyframerGlobalNodes) return;
for (const targetNode of window._LTXKeyframerGlobalNodes) {
// Target all OTHER LTXKeyframer nodes by direct object reference
if (targetNode !== sourceNode) {
// 1. Always update the hidden properties cache so it remembers the sync
// even if the widget isn't currently visible (e.g. fewer images loaded right now)
targetNode.properties[widgetName] = value;
// 2. If the widget is currently visible on the UI, update it visually
if (targetNode.widgets) {
const targetWidget = targetNode.widgets.find(w => w.name === widgetName);
if (targetWidget && targetWidget.value !== value) {
targetWidget.value = value;
targetNode.setDirtyCanvas(true, false);
}
}
}
}
}
app.registerExtension({
name: "Comfy.LTXKeyframer.DynamicInputs",
async nodeCreated(node) {
if (node.comfyClass !== "LTXKeyframer") return;
// Register this node instance globally
window._LTXKeyframerGlobalNodes.add(node);
node._currentImageCount = -1; // Force first update
// Initialize persistent properties cache
node.properties = node.properties || {};
// Add subtle separator line above images_loaded
node.addCustomWidget({
name: "num_images_separator",
type: "text",
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
ctx.strokeStyle = "#444";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, y + 5);
ctx.lineTo(widget_width - 10, y + 5);
ctx.stroke();
ctx.restore();
},
computeSize(width) {
return [width, 10];
}
});
// Move separator before num_images
const moveSeparator = () => {
const idx = node.widgets.findIndex(w => w.name === "num_images");
const sepIdx = node.widgets.findIndex(w => w.name === "num_images_separator");
if (idx !== -1 && sepIdx !== -1) {
const separator = node.widgets.splice(sepIdx, 1)[0];
node.widgets.splice(idx, 0, separator);
}
};
setTimeout(moveSeparator, 50); // Small delay to ensure num_images is present
// Core update: synchronize widget visibility to match imageCount
node._applyWidgetCount = function(count) {
const isInitialLoad = this._currentImageCount === -1;
if (this._currentImageCount === count && !isInitialLoad) return;
this._currentImageCount = count;
const initialWidth = this.size[0];
const numWidget = this.widgets?.find(w => w.name === "num_images");
if (numWidget) {
numWidget.label = "images_loaded";
numWidget.value = Math.max(0, Math.min(count || 0, 50));
}
// 1. Store current widget values in properties BEFORE removing them
// We skip reading from `this.widgets` on the initial load because it might be scrambling.
if (!isInitialLoad && this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
this.properties[w.name] = w.value;
}
});
}
// 2. Remove all existing dynamic insert_frame/strength/header widgets
if (this.widgets) {
this.widgets = this.widgets.filter(w =>
!w.name.startsWith("insert_frame_") &&
!w.name.startsWith("strength_") &&
!w.name.startsWith("header_")
);
} else {
this.widgets = [];
}
// 3. Add back exactly the right amount of widgets using the cached values
for (let i = 1; i <= count; i++) {
// Add header/separator widget for grouping
const headerName = `header_${i}`;
this.addCustomWidget({
name: headerName,
type: "text",
value: `Image #${i}`,
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
const margin = 10;
const topPadding = 15;
// Subtle separator line
ctx.strokeStyle = "#333";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(margin, y + 5);
ctx.lineTo(widget_width - margin, y + 5);
ctx.stroke();
// Text label
ctx.fillStyle = "#dddddd"; // Light gray
ctx.font = "bold 12px Arial";
ctx.textAlign = "left";
ctx.fillText(`Image #${i}`, margin, y + topPadding + 10);
ctx.restore();
},
computeSize(width) {
return [width, 35]; // Vertical gap + label height
}
});
const insertFrameWidgetName = `insert_frame_${i}`;
const strengthWidgetName = `strength_${i}`;
// Add insert_frame widget with Sync Callback
const savedInsertFrameValue = this.properties[insertFrameWidgetName];
this.addWidget("number", insertFrameWidgetName,
savedInsertFrameValue !== undefined ? savedInsertFrameValue : 0,
(value) => {
const rounded = Math.round(value);
this.properties[insertFrameWidgetName] = rounded;
syncWidgetAcrossNodes(this, insertFrameWidgetName, rounded); // Sync out
}, { min: -9999, max: 9999, step: 10, precision: 0 }
);
// Add strength widget with Sync Callback
const savedStrengthValue = this.properties[strengthWidgetName];
this.addWidget("number", strengthWidgetName,
savedStrengthValue !== undefined ? savedStrengthValue : 1.0,
(value) => {
this.properties[strengthWidgetName] = value;
syncWidgetAcrossNodes(this, strengthWidgetName, value); // Sync out
}, { min: 0.0, max: 1.0, step: 0.01 }
);
}
this.setDirtyCanvas(true, true);
requestAnimationFrame(() => {
if (this.computeSize) {
this.setSize(this.computeSize());
this.size[0] = initialWidth; // keep width fixed when restructuring
}
});
};
// --- STRICT ARRAY MAPPER: FIXES ALL SHIFTING FOREVER ---
// This runs the exact instant the node is loaded, before any UI widgets shift indices.
// It locks the perfectly mapped array values directly into our properties dictionary.
const origConfigure = node.configure;
node.configure = function(info) {
if (origConfigure) {
origConfigure.apply(this, arguments);
}
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name === "num_images" || w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
this.properties[w.name] = w.value;
}
});
}
};
// Handle deserialization to load properties properly from JSON
const originalOnConfigure = node.onConfigure;
node.onConfigure = function(info) {
if (originalOnConfigure) {
originalOnConfigure.apply(this, arguments);
}
if (info.properties) {
this.properties = { ...this.properties, ...info.properties };
}
setTimeout(() => {
const count = readSourceImageCount(this);
// Fallback to properties.num_images if source node disconnected
let targetCount = count !== null ? count : (this.properties.num_images || 0);
this._applyWidgetCount(targetCount);
}, 100);
};
// --- STRICT ARRAY GENERATOR ---
// Completely detach from ComfyUI's blind visual array saving.
// We construct an exact 101-element strict array that Python expects.
// This makes your node 100% immune to UI/Header index shifting.
const originalOnSerialize = node.onSerialize;
node.onSerialize = function(info) {
// Ensure properties are strictly synced with current widget values before building
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name === "num_images" || w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
this.properties[w.name] = w.value;
}
});
}
if (originalOnSerialize) {
originalOnSerialize.apply(this, arguments);
}
info.properties = { ...this.properties };
// Build the exact strict array that maps 1-to-1 to the Python backend
const strictArray = [];
const numWidgetVal = this.properties["num_images"];
strictArray.push(numWidgetVal !== undefined ? numWidgetVal : 1);
for (let i = 1; i <= 50; i++) {
const fVal = this.properties[`insert_frame_${i}`];
const sVal = this.properties[`strength_${i}`];
strictArray.push(fVal !== undefined ? fVal : 0);
strictArray.push(sVal !== undefined ? sVal : 1.0);
}
info.widgets_values = strictArray;
};
// Set up manual num_images widget callback
setTimeout(() => {
const numWidget = node.widgets?.find(w => w.name === "num_images");
if (numWidget) {
numWidget.callback = (val) => {
node.properties["num_images"] = val;
node._applyWidgetCount(val);
};
}
}, 100);
// Exposed receiver for push-based notifications
node._syncImageCount = function(count) {
this._applyWidgetCount(count);
};
// Helper: read image count from a connected MultiImageLoader node
function readSourceImageCount(self) {
const multiInput = self.inputs?.find(inp => inp.name === "multi_input");
if (!multiInput || !multiInput.link) return null;
const nodeGraph = self.graph || app.graph;
// Helper to safely trace back through Reroutes and ComfyUI Group Nodes/Subgraphs
function traceUpstream(graph, linkId, visited = new Set()) {
if (!linkId || visited.has(linkId)) return null;
visited.add(linkId);
const link = graph.links[linkId];
if (!link) return null;
const originNode = graph.getNodeById(link.origin_id);
if (!originNode) return null;
if (originNode.comfyClass === "MultiImageLoader") {
return originNode;
}
// Traverse Reroute nodes
if (originNode.type === "Reroute" || originNode.comfyClass === "Reroute") {
if (originNode.inputs && originNode.inputs.length > 0 && originNode.inputs[0].link) {
return traceUpstream(graph, originNode.inputs[0].link, visited);
}
}
// Traverse standard ComfyUI Group Nodes (subgraphs)
if (typeof originNode.getInnerNode === "function") {
try {
const innerNode = originNode.getInnerNode(link.origin_slot);
if (innerNode && innerNode.comfyClass === "MultiImageLoader") {
return innerNode;
}
} catch (e) {
console.warn("Could not trace inner node", e);
}
}
return null;
}
let sourceNode = traceUpstream(nodeGraph, multiInput.link);
// Helper to extract the count once we find a node
function getCountFromNode(n) {
if (typeof n._imageCount === "number") return n._imageCount;
const pathsWidget = n.widgets?.find(w => w.name === "image_paths");
if (pathsWidget) {
return (pathsWidget.value || "").split('\n').map(p => p.trim()).filter(p => p.length > 0).length;
}
return null;
}
if (sourceNode) {
return getCountFromNode(sourceNode);
}
// Fallback Strategy: If it is connected to something, but we couldn't resolve it
// directly (e.g. complex nested 3rd party subgraphs), scan the entire UI.
// If there is EXACTLY ONE MultiImageLoader in the workspace, safely assume that's the one.
let multiImageLoaders = [];
function findAllLoaders(nodes) {
if (!nodes) return;
for (let n of nodes) {
if (n.comfyClass === "MultiImageLoader") {
multiImageLoaders.push(n);
}
if (n.subgraph && n.subgraph._nodes) {
findAllLoaders(n.subgraph._nodes);
}
}
}
if (app.graph && app.graph._nodes) {
findAllLoaders(app.graph._nodes);
}
if (multiImageLoaders.length === 1) {
return getCountFromNode(multiImageLoaders[0]);
}
return null;
}
// --- Backup polling via setInterval (4 Hz) ---
const pollInterval = setInterval(() => {
if (!node.graph) {
clearInterval(pollInterval);
return;
}
const count = readSourceImageCount(node);
if (count !== null) {
node._applyWidgetCount(count);
}
}, 250);
// Clean up the interval when the node is deleted
const origOnRemoved = node.onRemoved;
node.onRemoved = function() {
// Unregister this node instance
window._LTXKeyframerGlobalNodes.delete(node);
clearInterval(pollInterval);
if (origOnRemoved) origOnRemoved.apply(this, arguments);
};
// --- Connection change handler ---
const onConnectionsChange = node.onConnectionsChange;
node.onConnectionsChange = function(type, index, connected, link_info) {
if (onConnectionsChange) onConnectionsChange.apply(this, arguments);
if (type === 1) { // 1 = Input
const input = this.inputs[index];
if (input && input.name === "multi_input") {
if (connected) {
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
} else {
this._applyWidgetCount(0);
}
}
}
};
// --- Initial sync when first placed on canvas ---
const origOnAdded = node.onAdded;
node.onAdded = function() {
if (origOnAdded) origOnAdded.apply(this, arguments);
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
};
}
});

View File

@@ -1,398 +1,398 @@
import { app } from "../../scripts/app.js";
// Global registry to track all LTXSequencer nodes across all subgraphs
window._LTXSequencerGlobalNodes = window._LTXSequencerGlobalNodes || new Set();
// ComfyUI native trick to cleanly hide/show widgets without deleting them
function toggleWidget(widget, visible) {
if (visible) {
if (widget.origType !== undefined) {
widget.type = widget.origType;
widget.computeSize = widget.origComputeSize;
delete widget.origType;
delete widget.origComputeSize;
}
} else {
if (widget.type !== "hidden") {
widget.origType = widget.type;
widget.origComputeSize = widget.computeSize;
widget.type = "hidden";
widget.computeSize = () => [0, -4];
}
}
}
/**
* FULL STATE SYNC:
* Instead of syncing one widget, we push the entire properties object
* to ensure no values are ever lost during subgraph transitions or deletions.
*/
function syncFullStateAcrossNodes(sourceNode) {
if (!window._LTXSequencerGlobalNodes) return;
for (const targetNode of window._LTXSequencerGlobalNodes) {
if (targetNode === sourceNode) continue;
// 1. Mirror the properties object completely
// We use a shallow copy to ensure we don't accidentally share object references
const newState = { ...sourceNode.properties };
targetNode.properties = { ...targetNode.properties, ...newState };
// 2. Check if we need to rebuild the widget list (if num_images changed)
const targetImageCount = targetNode.properties["num_images"] || 0;
const currentVisibleCount = targetNode._currentImageCount;
if (targetImageCount !== currentVisibleCount) {
targetNode._applyWidgetCount(targetImageCount);
}
// 3. Update all existing widget values visually
if (targetNode.widgets) {
let modeChanged = false;
targetNode.widgets.forEach(w => {
const newValue = targetNode.properties[w.name];
if (newValue !== undefined && w.value !== newValue) {
w.value = newValue;
if (w.name === "insert_mode") modeChanged = true;
}
});
if (modeChanged && targetNode._updateVisibility) {
targetNode._updateVisibility();
}
}
targetNode.setDirtyCanvas(true, false);
}
}
app.registerExtension({
name: "Comfy.LTXSequencer.DynamicInputs",
async nodeCreated(node) {
if (node.comfyClass !== "LTXSequencer") return;
// Register this node instance globally
window._LTXSequencerGlobalNodes.add(node);
node._currentImageCount = -1; // Force first update
// Initialize persistent properties cache
node.properties = node.properties || {};
// Add subtle separator line above images_loaded
node.addCustomWidget({
name: "num_images_separator",
type: "text",
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
ctx.strokeStyle = "#444";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, y + 5);
ctx.lineTo(widget_width - 10, y + 5);
ctx.stroke();
ctx.restore();
},
computeSize(width) {
return [width, 10];
}
});
// Move separator before num_images
const moveSeparator = () => {
const idx = node.widgets.findIndex(w => w.name === "num_images");
const sepIdx = node.widgets.findIndex(w => w.name === "num_images_separator");
if (idx !== -1 && sepIdx !== -1) {
const separator = node.widgets.splice(sepIdx, 1)[0];
node.widgets.splice(idx, 0, separator);
}
};
setTimeout(moveSeparator, 50);
// Binds custom callbacks to python-schema generated widgets
node._hookStaticWidgets = function() {
if (!this.widgets) return;
const staticNames = ["num_images", "insert_mode", "frame_rate"];
staticNames.forEach(name => {
const w = this.widgets.find(w => w.name === name);
if (w && !w._has_custom_callback) {
const orig = w.callback;
w.callback = (val) => {
this.properties[name] = val;
if (name === "num_images") {
this._applyWidgetCount(val);
}
// Push full state to siblings
syncFullStateAcrossNodes(this);
if (name === "insert_mode") {
this._updateVisibility();
}
if (orig) orig.apply(w, [val]);
};
w._has_custom_callback = true;
}
});
};
// Handles show/hiding widgets based on insertion method
node._updateVisibility = function() {
const mode = this.properties["insert_mode"] || "frames";
if (!this.widgets) return;
let changed = false;
for (const w of this.widgets) {
let shouldBeVisible = true;
if (w.name.startsWith("insert_frame_")) {
shouldBeVisible = (mode === "frames");
} else if (w.name.startsWith("insert_second_")) {
shouldBeVisible = (mode === "seconds");
}
const isHidden = (w.type === "hidden");
if (shouldBeVisible && isHidden) {
toggleWidget(w, true);
changed = true;
} else if (!shouldBeVisible && !isHidden) {
toggleWidget(w, false);
changed = true;
}
}
if (changed) {
this.setDirtyCanvas(true, true);
requestAnimationFrame(() => {
if (this.computeSize) {
this.setSize(this.computeSize());
}
});
}
};
// Core update: synchronize widget visibility to match imageCount
node._applyWidgetCount = function(count) {
this._hookStaticWidgets();
const isInitialLoad = this._currentImageCount === -1;
if (this._currentImageCount === count && !isInitialLoad) return;
this._currentImageCount = count;
const initialWidth = this.size[0];
const numWidget = this.widgets?.find(w => w.name === "num_images");
if (numWidget) {
numWidget.label = "images_loaded";
numWidget.value = Math.max(0, Math.min(count || 0, 50));
}
// 1. Update properties from current widget values before restructuring
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
if (w.type !== "hidden" && w.type !== "button") this.properties[w.name] = w.value;
}
});
}
// 2. Clear dynamic widgets
if (this.widgets) {
this.widgets = this.widgets.filter(w =>
!w.name.startsWith("insert_frame_") &&
!w.name.startsWith("insert_second_") &&
!w.name.startsWith("strength_") &&
!w.name.startsWith("header_")
);
} else {
this.widgets = [];
}
// 3. Rebuild precisely
for (let i = 1; i <= count; i++) {
// Header
const headerName = `header_${i}`;
this.addCustomWidget({
name: headerName,
type: "text",
value: `Image #${i}`,
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
const margin = 10;
const topPadding = 15;
ctx.strokeStyle = "#333";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(margin, y + 5);
ctx.lineTo(widget_width - margin, y + 5);
ctx.stroke();
ctx.fillStyle = "#dddddd";
ctx.font = "bold 12px Arial";
ctx.textAlign = "left";
ctx.fillText(`Image #${i}`, margin, y + topPadding + 10);
ctx.restore();
},
computeSize(width) { return [width, 35]; }
});
// Helper to add widget with full sync
const addSyncedWidget = (type, name, def, options) => {
const saved = this.properties[name];
return this.addWidget(type, name, saved !== undefined ? saved : def, (val) => {
this.properties[name] = val;
syncFullStateAcrossNodes(this);
}, options);
};
addSyncedWidget("number", `insert_frame_${i}`, 0, { min: -9999, max: 9999, step: 10, precision: 0 });
addSyncedWidget("number", `insert_second_${i}`, 0.0, { min: 0.0, max: 9999.0, step: 0.1, precision: 2 });
addSyncedWidget("number", `strength_${i}`, 1.0, { min: 0.0, max: 1.0, step: 0.01 });
}
this._updateVisibility();
this.setDirtyCanvas(true, true);
requestAnimationFrame(() => {
if (this.computeSize) {
this.setSize(this.computeSize());
this.size[0] = initialWidth;
}
});
};
const origConfigure = node.configure;
node.configure = function(info) {
if (origConfigure) origConfigure.apply(this, arguments);
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
if (w.type !== "button") this.properties[w.name] = w.value;
}
});
}
};
node.onConfigure = function(info) {
if (info.properties) {
this.properties = { ...this.properties, ...info.properties };
}
this._hookStaticWidgets();
setTimeout(() => {
const count = readSourceImageCount(this);
let targetCount = count !== null ? count : (this.properties.num_images || 0);
this._applyWidgetCount(targetCount);
this._updateVisibility();
}, 100);
};
const originalOnSerialize = node.onSerialize;
node.onSerialize = function(info) {
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
if (w.type !== "hidden" && w.type !== "button") this.properties[w.name] = w.value;
}
});
}
if (originalOnSerialize) originalOnSerialize.apply(this, arguments);
info.properties = { ...this.properties };
const strictArray = [];
strictArray.push(this.properties["num_images"] !== undefined ? this.properties["num_images"] : 1);
strictArray.push(this.properties["insert_mode"] !== undefined ? this.properties["insert_mode"] : "frames");
strictArray.push(this.properties["frame_rate"] !== undefined ? this.properties["frame_rate"] : 24);
for (let i = 1; i <= 50; i++) {
strictArray.push(this.properties[`insert_frame_${i}`] !== undefined ? this.properties[`insert_frame_${i}`] : 0);
strictArray.push(this.properties[`insert_second_${i}`] !== undefined ? this.properties[`insert_second_${i}`] : 0.0);
strictArray.push(this.properties[`strength_${i}`] !== undefined ? this.properties[`strength_${i}`] : 1.0);
}
info.widgets_values = strictArray;
};
function readSourceImageCount(self) {
const multiInput = self.inputs?.find(inp => inp.name === "multi_input");
if (!multiInput || !multiInput.link) return null;
const nodeGraph = self.graph || app.graph;
function traceUpstream(graph, linkId, visited = new Set()) {
if (!linkId || visited.has(linkId)) return null;
visited.add(linkId);
const link = graph.links[linkId];
if (!link) return null;
const originNode = graph.getNodeById(link.origin_id);
if (!originNode) return null;
if (originNode.comfyClass === "MultiImageLoader") return originNode;
if (originNode.type === "Reroute" || originNode.comfyClass === "Reroute") {
if (originNode.inputs?.[0]?.link) return traceUpstream(graph, originNode.inputs[0].link, visited);
}
if (typeof originNode.getInnerNode === "function") {
try {
const innerNode = originNode.getInnerNode(link.origin_slot);
if (innerNode?.comfyClass === "MultiImageLoader") return innerNode;
} catch (e) {}
}
return null;
}
let sourceNode = traceUpstream(nodeGraph, multiInput.link);
function getCountFromNode(n) {
if (typeof n._imageCount === "number") return n._imageCount;
const pathsWidget = n.widgets?.find(w => w.name === "image_paths");
return pathsWidget ? (pathsWidget.value || "").split('\n').filter(p => p.trim()).length : null;
}
if (sourceNode) return getCountFromNode(sourceNode);
let multiImageLoaders = [];
function findAllLoaders(nodes) {
if (!nodes) return;
for (let n of nodes) {
if (n.comfyClass === "MultiImageLoader") multiImageLoaders.push(n);
if (n.subgraph?._nodes) findAllLoaders(n.subgraph._nodes);
}
}
if (app.graph?._nodes) findAllLoaders(app.graph._nodes);
if (multiImageLoaders.length === 1) return getCountFromNode(multiImageLoaders[0]);
return null;
}
const pollInterval = setInterval(() => {
if (!node.graph) {
clearInterval(pollInterval);
return;
}
const count = readSourceImageCount(node);
if (count !== null && count !== node._currentImageCount) {
node._applyWidgetCount(count);
syncFullStateAcrossNodes(node); // Sync the new count to others
}
}, 500);
const origOnRemoved = node.onRemoved;
node.onRemoved = function() {
window._LTXSequencerGlobalNodes.delete(node);
clearInterval(pollInterval);
if (origOnRemoved) origOnRemoved.apply(this, arguments);
};
node.onConnectionsChange = function(type, index, connected) {
if (type === 1 && this.inputs[index]?.name === "multi_input") {
if (connected) {
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
} else {
this._applyWidgetCount(0);
}
}
};
node.onAdded = function() {
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
};
}
import { app } from "../../scripts/app.js";
// Global registry to track all LTXSequencer nodes across all subgraphs
window._LTXSequencerGlobalNodes = window._LTXSequencerGlobalNodes || new Set();
// ComfyUI native trick to cleanly hide/show widgets without deleting them
function toggleWidget(widget, visible) {
if (visible) {
if (widget.origType !== undefined) {
widget.type = widget.origType;
widget.computeSize = widget.origComputeSize;
delete widget.origType;
delete widget.origComputeSize;
}
} else {
if (widget.type !== "hidden") {
widget.origType = widget.type;
widget.origComputeSize = widget.computeSize;
widget.type = "hidden";
widget.computeSize = () => [0, -4];
}
}
}
/**
* FULL STATE SYNC:
* Instead of syncing one widget, we push the entire properties object
* to ensure no values are ever lost during subgraph transitions or deletions.
*/
function syncFullStateAcrossNodes(sourceNode) {
if (!window._LTXSequencerGlobalNodes) return;
for (const targetNode of window._LTXSequencerGlobalNodes) {
if (targetNode === sourceNode) continue;
// 1. Mirror the properties object completely
// We use a shallow copy to ensure we don't accidentally share object references
const newState = { ...sourceNode.properties };
targetNode.properties = { ...targetNode.properties, ...newState };
// 2. Check if we need to rebuild the widget list (if num_images changed)
const targetImageCount = targetNode.properties["num_images"] || 0;
const currentVisibleCount = targetNode._currentImageCount;
if (targetImageCount !== currentVisibleCount) {
targetNode._applyWidgetCount(targetImageCount);
}
// 3. Update all existing widget values visually
if (targetNode.widgets) {
let modeChanged = false;
targetNode.widgets.forEach(w => {
const newValue = targetNode.properties[w.name];
if (newValue !== undefined && w.value !== newValue) {
w.value = newValue;
if (w.name === "insert_mode") modeChanged = true;
}
});
if (modeChanged && targetNode._updateVisibility) {
targetNode._updateVisibility();
}
}
targetNode.setDirtyCanvas(true, false);
}
}
app.registerExtension({
name: "Comfy.LTXSequencer.DynamicInputs",
async nodeCreated(node) {
if (node.comfyClass !== "LTXSequencer") return;
// Register this node instance globally
window._LTXSequencerGlobalNodes.add(node);
node._currentImageCount = -1; // Force first update
// Initialize persistent properties cache
node.properties = node.properties || {};
// Add subtle separator line above images_loaded
node.addCustomWidget({
name: "num_images_separator",
type: "text",
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
ctx.strokeStyle = "#444";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, y + 5);
ctx.lineTo(widget_width - 10, y + 5);
ctx.stroke();
ctx.restore();
},
computeSize(width) {
return [width, 10];
}
});
// Move separator before num_images
const moveSeparator = () => {
const idx = node.widgets.findIndex(w => w.name === "num_images");
const sepIdx = node.widgets.findIndex(w => w.name === "num_images_separator");
if (idx !== -1 && sepIdx !== -1) {
const separator = node.widgets.splice(sepIdx, 1)[0];
node.widgets.splice(idx, 0, separator);
}
};
setTimeout(moveSeparator, 50);
// Binds custom callbacks to python-schema generated widgets
node._hookStaticWidgets = function() {
if (!this.widgets) return;
const staticNames = ["num_images", "insert_mode", "frame_rate"];
staticNames.forEach(name => {
const w = this.widgets.find(w => w.name === name);
if (w && !w._has_custom_callback) {
const orig = w.callback;
w.callback = (val) => {
this.properties[name] = val;
if (name === "num_images") {
this._applyWidgetCount(val);
}
// Push full state to siblings
syncFullStateAcrossNodes(this);
if (name === "insert_mode") {
this._updateVisibility();
}
if (orig) orig.apply(w, [val]);
};
w._has_custom_callback = true;
}
});
};
// Handles show/hiding widgets based on insertion method
node._updateVisibility = function() {
const mode = this.properties["insert_mode"] || "frames";
if (!this.widgets) return;
let changed = false;
for (const w of this.widgets) {
let shouldBeVisible = true;
if (w.name.startsWith("insert_frame_")) {
shouldBeVisible = (mode === "frames");
} else if (w.name.startsWith("insert_second_")) {
shouldBeVisible = (mode === "seconds");
}
const isHidden = (w.type === "hidden");
if (shouldBeVisible && isHidden) {
toggleWidget(w, true);
changed = true;
} else if (!shouldBeVisible && !isHidden) {
toggleWidget(w, false);
changed = true;
}
}
if (changed) {
this.setDirtyCanvas(true, true);
requestAnimationFrame(() => {
if (this.computeSize) {
this.setSize(this.computeSize());
}
});
}
};
// Core update: synchronize widget visibility to match imageCount
node._applyWidgetCount = function(count) {
this._hookStaticWidgets();
const isInitialLoad = this._currentImageCount === -1;
if (this._currentImageCount === count && !isInitialLoad) return;
this._currentImageCount = count;
const initialWidth = this.size[0];
const numWidget = this.widgets?.find(w => w.name === "num_images");
if (numWidget) {
numWidget.label = "images_loaded";
numWidget.value = Math.max(0, Math.min(count || 0, 50));
}
// 1. Update properties from current widget values before restructuring
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
if (w.type !== "hidden" && w.type !== "button") this.properties[w.name] = w.value;
}
});
}
// 2. Clear dynamic widgets
if (this.widgets) {
this.widgets = this.widgets.filter(w =>
!w.name.startsWith("insert_frame_") &&
!w.name.startsWith("insert_second_") &&
!w.name.startsWith("strength_") &&
!w.name.startsWith("header_")
);
} else {
this.widgets = [];
}
// 3. Rebuild precisely
for (let i = 1; i <= count; i++) {
// Header
const headerName = `header_${i}`;
this.addCustomWidget({
name: headerName,
type: "text",
value: `Image #${i}`,
draw(ctx, node, widget_width, y, widget_height) {
ctx.save();
const margin = 10;
const topPadding = 15;
ctx.strokeStyle = "#333";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(margin, y + 5);
ctx.lineTo(widget_width - margin, y + 5);
ctx.stroke();
ctx.fillStyle = "#dddddd";
ctx.font = "bold 12px Arial";
ctx.textAlign = "left";
ctx.fillText(`Image #${i}`, margin, y + topPadding + 10);
ctx.restore();
},
computeSize(width) { return [width, 35]; }
});
// Helper to add widget with full sync
const addSyncedWidget = (type, name, def, options) => {
const saved = this.properties[name];
return this.addWidget(type, name, saved !== undefined ? saved : def, (val) => {
this.properties[name] = val;
syncFullStateAcrossNodes(this);
}, options);
};
addSyncedWidget("number", `insert_frame_${i}`, 0, { min: -9999, max: 9999, step: 10, precision: 0 });
addSyncedWidget("number", `insert_second_${i}`, 0.0, { min: 0.0, max: 9999.0, step: 0.1, precision: 2 });
addSyncedWidget("number", `strength_${i}`, 1.0, { min: 0.0, max: 1.0, step: 0.01 });
}
this._updateVisibility();
this.setDirtyCanvas(true, true);
requestAnimationFrame(() => {
if (this.computeSize) {
this.setSize(this.computeSize());
this.size[0] = initialWidth;
}
});
};
const origConfigure = node.configure;
node.configure = function(info) {
if (origConfigure) origConfigure.apply(this, arguments);
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
if (w.type !== "button") this.properties[w.name] = w.value;
}
});
}
};
node.onConfigure = function(info) {
if (info.properties) {
this.properties = { ...this.properties, ...info.properties };
}
this._hookStaticWidgets();
setTimeout(() => {
const count = readSourceImageCount(this);
let targetCount = count !== null ? count : (this.properties.num_images || 0);
this._applyWidgetCount(targetCount);
this._updateVisibility();
}, 100);
};
const originalOnSerialize = node.onSerialize;
node.onSerialize = function(info) {
if (this.widgets) {
this.widgets.forEach(w => {
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
if (w.type !== "hidden" && w.type !== "button") this.properties[w.name] = w.value;
}
});
}
if (originalOnSerialize) originalOnSerialize.apply(this, arguments);
info.properties = { ...this.properties };
const strictArray = [];
strictArray.push(this.properties["num_images"] !== undefined ? this.properties["num_images"] : 1);
strictArray.push(this.properties["insert_mode"] !== undefined ? this.properties["insert_mode"] : "frames");
strictArray.push(this.properties["frame_rate"] !== undefined ? this.properties["frame_rate"] : 24);
for (let i = 1; i <= 50; i++) {
strictArray.push(this.properties[`insert_frame_${i}`] !== undefined ? this.properties[`insert_frame_${i}`] : 0);
strictArray.push(this.properties[`insert_second_${i}`] !== undefined ? this.properties[`insert_second_${i}`] : 0.0);
strictArray.push(this.properties[`strength_${i}`] !== undefined ? this.properties[`strength_${i}`] : 1.0);
}
info.widgets_values = strictArray;
};
function readSourceImageCount(self) {
const multiInput = self.inputs?.find(inp => inp.name === "multi_input");
if (!multiInput || !multiInput.link) return null;
const nodeGraph = self.graph || app.graph;
function traceUpstream(graph, linkId, visited = new Set()) {
if (!linkId || visited.has(linkId)) return null;
visited.add(linkId);
const link = graph.links[linkId];
if (!link) return null;
const originNode = graph.getNodeById(link.origin_id);
if (!originNode) return null;
if (originNode.comfyClass === "MultiImageLoader") return originNode;
if (originNode.type === "Reroute" || originNode.comfyClass === "Reroute") {
if (originNode.inputs?.[0]?.link) return traceUpstream(graph, originNode.inputs[0].link, visited);
}
if (typeof originNode.getInnerNode === "function") {
try {
const innerNode = originNode.getInnerNode(link.origin_slot);
if (innerNode?.comfyClass === "MultiImageLoader") return innerNode;
} catch (e) {}
}
return null;
}
let sourceNode = traceUpstream(nodeGraph, multiInput.link);
function getCountFromNode(n) {
if (typeof n._imageCount === "number") return n._imageCount;
const pathsWidget = n.widgets?.find(w => w.name === "image_paths");
return pathsWidget ? (pathsWidget.value || "").split('\n').filter(p => p.trim()).length : null;
}
if (sourceNode) return getCountFromNode(sourceNode);
let multiImageLoaders = [];
function findAllLoaders(nodes) {
if (!nodes) return;
for (let n of nodes) {
if (n.comfyClass === "MultiImageLoader") multiImageLoaders.push(n);
if (n.subgraph?._nodes) findAllLoaders(n.subgraph._nodes);
}
}
if (app.graph?._nodes) findAllLoaders(app.graph._nodes);
if (multiImageLoaders.length === 1) return getCountFromNode(multiImageLoaders[0]);
return null;
}
const pollInterval = setInterval(() => {
if (!node.graph) {
clearInterval(pollInterval);
return;
}
const count = readSourceImageCount(node);
if (count !== null && count !== node._currentImageCount) {
node._applyWidgetCount(count);
syncFullStateAcrossNodes(node); // Sync the new count to others
}
}, 500);
const origOnRemoved = node.onRemoved;
node.onRemoved = function() {
window._LTXSequencerGlobalNodes.delete(node);
clearInterval(pollInterval);
if (origOnRemoved) origOnRemoved.apply(this, arguments);
};
node.onConnectionsChange = function(type, index, connected) {
if (type === 1 && this.inputs[index]?.name === "multi_input") {
if (connected) {
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
} else {
this._applyWidgetCount(0);
}
}
};
node.onAdded = function() {
setTimeout(() => {
const count = readSourceImageCount(this);
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
}, 100);
};
}
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,336 +1,336 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
// 1. DEFINE CSS STYLES GLOBALLY ONCE
// We use DOM elements instead of Canvas drawing so it works flawlessly in ComfyUI V3
const cssStyles = `
.slc-ui-container {
width: 100%;
height: 100%;
min-height: 260px; /* Increased from 220px to prevent V1 cropping */
background-color: rgba(15, 15, 19, 0.7);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 12px;
box-sizing: border-box;
display: flex;
flex-direction: column;
font-family: sans-serif;
color: #ffffff;
overflow: hidden;
pointer-events: auto; /* allows text selection */
}
.slc-empty {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.slc-empty-title { color: #aaaaaa; font-size: 14px; font-weight: 500; margin-bottom: 4px; }
.slc-empty-sub { color: #777777; font-size: 11px; }
.slc-headers {
display: flex;
gap: 8px;
margin-bottom: 12px;
}
.slc-header-block {
flex: 1;
background-color: rgba(0, 0, 0, 0.4);
border-radius: 6px;
padding: 8px 0;
display: flex;
flex-direction: column;
align-items: center;
}
.slc-header-title { color: #888888; font-size: 9px; font-weight: bold; margin-bottom: 4px; }
.slc-header-value { color: #ffffff; font-size: 16px; font-weight: bold; }
.slc-cards {
display: flex;
flex-direction: column;
gap: 8px;
}
.slc-card {
display: flex;
justify-content: space-between;
align-items: center;
background-color: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(255, 255, 255, 0.05);
border-radius: 4px;
padding: 8px 12px 8px 16px;
position: relative;
overflow: hidden;
}
.slc-card::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 4px;
}
.slc-card.slow::before { background-color: #93c5fd; }
.slc-card.avg::before { background-color: #86efac; }
.slc-card.fast::before { background-color: #fca5a5; }
.slc-card-left { display: flex; flex-direction: column; }
.slc-card-speed { font-size: 12px; font-weight: bold; margin-bottom: 2px; }
.slc-card.slow .slc-card-speed { color: #93c5fd; }
.slc-card.avg .slc-card-speed { color: #86efac; }
.slc-card.fast .slc-card-speed { color: #fca5a5; }
.slc-card-wpm { font-size: 10px; color: #aaaaaa; }
.slc-card-right { display: flex; flex-direction: column; align-items: flex-end; }
.slc-card-time { font-size: 13px; font-weight: bold; color: #ffffff; margin-bottom: 2px; }
.slc-card-frames { font-size: 11px; font-family: monospace; color: #888888; }
.slc-legend {
margin-top: auto;
padding-top: 8px;
color: #999999;
font-size: 10px;
font-weight: 500;
}
`;
// Inject styles to document head safely
if (!document.getElementById("speech-length-calculator-styles")) {
const styleEl = document.createElement("style");
styleEl.id = "speech-length-calculator-styles";
styleEl.textContent = cssStyles;
document.head.appendChild(styleEl);
}
// 2. HELPER TO GENERATE THE HTML CONTENT
function buildUIHTML(statsData) {
if (!statsData || statsData.empty) {
return `
<div class="slc-empty">
<div class="slc-empty-title">Awaiting Script</div>
<div class="slc-empty-sub">Wrap spoken text inside "quotes"</div>
</div>
`;
}
return `
<div class="slc-headers">
<div class="slc-header-block">
<div class="slc-header-title">SPOKEN WORDS</div>
<div class="slc-header-value">${statsData.wordCount}</div>
</div>
<div class="slc-header-block">
<div class="slc-header-title">ADDED TIME</div>
<div class="slc-header-value">${statsData.additionalTime}s</div>
</div>
</div>
<div class="slc-cards">
<div class="slc-card slow">
<div class="slc-card-left">
<div class="slc-card-speed">SLOW</div>
<div class="slc-card-wpm">100 WPM</div>
</div>
<div class="slc-card-right">
<div class="slc-card-time">${statsData.slow.time}</div>
<div class="slc-card-frames">${statsData.slow.frames} frames</div>
</div>
</div>
<div class="slc-card avg">
<div class="slc-card-left">
<div class="slc-card-speed">AVG</div>
<div class="slc-card-wpm">130 WPM</div>
</div>
<div class="slc-card-right">
<div class="slc-card-time">${statsData.avg.time}</div>
<div class="slc-card-frames">${statsData.avg.frames} frames</div>
</div>
</div>
<div class="slc-card fast">
<div class="slc-card-left">
<div class="slc-card-speed">FAST</div>
<div class="slc-card-wpm">160 WPM</div>
</div>
<div class="slc-card-right">
<div class="slc-card-time">${statsData.fast.time}</div>
<div class="slc-card-frames">${statsData.fast.frames} frames</div>
</div>
</div>
</div>
<div class="slc-legend">WPM = Words Per Minute</div>
`;
}
app.registerExtension({
name: "Comfy.SpeechLengthCalculator",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "SpeechLengthCalculator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
// 3. CREATE THE DOM WIDGET
const uiContainer = document.createElement("div");
uiContainer.className = "slc-ui-container";
uiContainer.innerHTML = buildUIHTML({ empty: true });
// Attach to node: standard addDOMWidget works natively in both V1 and V3 Frontends
let statsWidget;
if (typeof this.addDOMWidget === "function") {
statsWidget = this.addDOMWidget("Stats", "HTML", uiContainer, {
serialize: false,
hideOnZoom: false
});
} else {
// Fallback for very old unpatched V1 installations
statsWidget = ComfyWidgets["STRING"](this, "Stats", ["STRING", { multiline: true }], app).widget;
if (statsWidget.inputEl) {
statsWidget.inputEl.style.display = "none";
if (statsWidget.inputEl.parentNode) {
statsWidget.inputEl.parentNode.appendChild(uiContainer);
}
}
}
// Tell LiteGraph exactly how much vertical space to hold for our UI
statsWidget.computeSize = function() {
return [0, 280]; // Increased from 240 to prevent bottom cropping in V1
};
// Ensure the node is wide enough on initial creation
requestAnimationFrame(() => {
const minWidth = 340;
if (this.size[0] < minWidth) this.size[0] = minWidth;
// Fine tune initial height to account for the larger computeSize and make text box taller
if (this.size[1] < 500) this.size[1] = 500;
this.setDirtyCanvas(true, true);
});
// Fetch text from input link OR widget
this._getCurrentText = () => {
const inputSlot = this.inputs && this.inputs.find(i => i.name === "text_input" || (i.name === "text" && i.link));
if (inputSlot && inputSlot.link) {
const link = app.graph.links[inputSlot.link];
if (link) {
const sourceNode = app.graph.getNodeById(link.origin_id);
if (sourceNode && sourceNode.widgets) {
const w = sourceNode.widgets.find(w => w.name === "value" || w.name === "text" || w.name === "Text" || w.type === "customtext" || w.type === "STRING");
if (w && typeof w.value === "string") return w.value;
}
}
}
const textWidget = this.widgets && this.widgets.find(w => w.name === "text");
return textWidget ? (textWidget.value || "") : "";
};
this._lastState = { text: null, fps: null, addTime: null };
const updateStats = () => {
const fpsWidget = this.widgets && this.widgets.find(w => w.name === "fps");
const additionalTimeWidget = this.widgets && this.widgets.find(w => w.name === "additional_time");
if (!fpsWidget) return;
const text = this._getCurrentText();
const fps = fpsWidget.value || 24;
const additionalTime = additionalTimeWidget ? parseFloat(additionalTimeWidget.value) || 0 : 0;
// Skip expensive calculations if nothing changed
if (this._lastState.text === text &&
this._lastState.fps === fps &&
this._lastState.addTime === additionalTime) {
return;
}
this._lastState.text = text;
this._lastState.fps = fps;
this._lastState.addTime = additionalTime;
const regex = /"([^"]*)"|'([^']*)'|“([^”]*)”|([^]*)/g;
let match;
let quotedText = "";
while ((match = regex.exec(text)) !== null) {
quotedText += (match[1] || match[2] || match[3] || match[4] || "") + " ";
}
const words = quotedText.trim().split(/\s+/).filter(w => w.length > 0);
const wordCount = words.length;
const formatTime = (wpm) => {
const baseMins = wordCount / wpm;
const totalSecs = (baseMins * 60) + additionalTime;
const mins = Math.floor(totalSecs / 60);
let secs = totalSecs % 60;
secs = Math.ceil(secs * 10) / 10;
const frames = Math.ceil(totalSecs * fps);
const secsStr = secs.toFixed(1);
const timeStr = mins > 0 ? `${mins}m ${secsStr}s` : `${secsStr}s`;
return {
time: timeStr,
frames: frames.toString()
};
};
const statsData = {
empty: (wordCount === 0 && additionalTime === 0),
wordCount: wordCount,
additionalTime: additionalTime,
slow: formatTime(100),
avg: formatTime(130),
fast: formatTime(160)
};
// 4. INJECT HTML TO THE DOM
// Replaces the heavy canvas redrawing!
uiContainer.innerHTML = buildUIHTML(statsData);
this.setDirtyCanvas(true, false);
};
// We still use onDrawBackground as an efficient silent trigger
// to auto-update in case upstream nodes silently change their text
const onDrawBackground = this.onDrawBackground;
this.onDrawBackground = function(ctx) {
if (onDrawBackground) onDrawBackground.apply(this, arguments);
updateStats();
};
// Bind events to update in real time based on node interactions
setTimeout(() => {
const textWidget = this.widgets && this.widgets.find(w => w.name === "text");
const fpsWidget = this.widgets && this.widgets.find(w => w.name === "fps");
const additionalTimeWidget = this.widgets && this.widgets.find(w => w.name === "additional_time");
if (textWidget) {
const origCallback = textWidget.callback;
textWidget.callback = function() {
if (origCallback) origCallback.apply(this, arguments);
updateStats();
}
}
if (fpsWidget) {
const origFpsCallback = fpsWidget.callback;
fpsWidget.callback = function() {
if (origFpsCallback) origFpsCallback.apply(this, arguments);
updateStats();
}
}
if (additionalTimeWidget) {
const origAddCallback = additionalTimeWidget.callback;
additionalTimeWidget.callback = function() {
if (origAddCallback) origAddCallback.apply(this, arguments);
updateStats();
}
}
updateStats();
}, 100);
return r;
};
}
}
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
// 1. DEFINE CSS STYLES GLOBALLY ONCE
// We use DOM elements instead of Canvas drawing so it works flawlessly in ComfyUI V3
const cssStyles = `
.slc-ui-container {
width: 100%;
height: 100%;
min-height: 260px; /* Increased from 220px to prevent V1 cropping */
background-color: rgba(15, 15, 19, 0.7);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 12px;
box-sizing: border-box;
display: flex;
flex-direction: column;
font-family: sans-serif;
color: #ffffff;
overflow: hidden;
pointer-events: auto; /* allows text selection */
}
.slc-empty {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.slc-empty-title { color: #aaaaaa; font-size: 14px; font-weight: 500; margin-bottom: 4px; }
.slc-empty-sub { color: #777777; font-size: 11px; }
.slc-headers {
display: flex;
gap: 8px;
margin-bottom: 12px;
}
.slc-header-block {
flex: 1;
background-color: rgba(0, 0, 0, 0.4);
border-radius: 6px;
padding: 8px 0;
display: flex;
flex-direction: column;
align-items: center;
}
.slc-header-title { color: #888888; font-size: 9px; font-weight: bold; margin-bottom: 4px; }
.slc-header-value { color: #ffffff; font-size: 16px; font-weight: bold; }
.slc-cards {
display: flex;
flex-direction: column;
gap: 8px;
}
.slc-card {
display: flex;
justify-content: space-between;
align-items: center;
background-color: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(255, 255, 255, 0.05);
border-radius: 4px;
padding: 8px 12px 8px 16px;
position: relative;
overflow: hidden;
}
.slc-card::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 4px;
}
.slc-card.slow::before { background-color: #93c5fd; }
.slc-card.avg::before { background-color: #86efac; }
.slc-card.fast::before { background-color: #fca5a5; }
.slc-card-left { display: flex; flex-direction: column; }
.slc-card-speed { font-size: 12px; font-weight: bold; margin-bottom: 2px; }
.slc-card.slow .slc-card-speed { color: #93c5fd; }
.slc-card.avg .slc-card-speed { color: #86efac; }
.slc-card.fast .slc-card-speed { color: #fca5a5; }
.slc-card-wpm { font-size: 10px; color: #aaaaaa; }
.slc-card-right { display: flex; flex-direction: column; align-items: flex-end; }
.slc-card-time { font-size: 13px; font-weight: bold; color: #ffffff; margin-bottom: 2px; }
.slc-card-frames { font-size: 11px; font-family: monospace; color: #888888; }
.slc-legend {
margin-top: auto;
padding-top: 8px;
color: #999999;
font-size: 10px;
font-weight: 500;
}
`;
// Inject styles to document head safely
if (!document.getElementById("speech-length-calculator-styles")) {
const styleEl = document.createElement("style");
styleEl.id = "speech-length-calculator-styles";
styleEl.textContent = cssStyles;
document.head.appendChild(styleEl);
}
// 2. HELPER TO GENERATE THE HTML CONTENT
function buildUIHTML(statsData) {
if (!statsData || statsData.empty) {
return `
<div class="slc-empty">
<div class="slc-empty-title">Awaiting Script</div>
<div class="slc-empty-sub">Wrap spoken text inside "quotes"</div>
</div>
`;
}
return `
<div class="slc-headers">
<div class="slc-header-block">
<div class="slc-header-title">SPOKEN WORDS</div>
<div class="slc-header-value">${statsData.wordCount}</div>
</div>
<div class="slc-header-block">
<div class="slc-header-title">ADDED TIME</div>
<div class="slc-header-value">${statsData.additionalTime}s</div>
</div>
</div>
<div class="slc-cards">
<div class="slc-card slow">
<div class="slc-card-left">
<div class="slc-card-speed">SLOW</div>
<div class="slc-card-wpm">100 WPM</div>
</div>
<div class="slc-card-right">
<div class="slc-card-time">${statsData.slow.time}</div>
<div class="slc-card-frames">${statsData.slow.frames} frames</div>
</div>
</div>
<div class="slc-card avg">
<div class="slc-card-left">
<div class="slc-card-speed">AVG</div>
<div class="slc-card-wpm">130 WPM</div>
</div>
<div class="slc-card-right">
<div class="slc-card-time">${statsData.avg.time}</div>
<div class="slc-card-frames">${statsData.avg.frames} frames</div>
</div>
</div>
<div class="slc-card fast">
<div class="slc-card-left">
<div class="slc-card-speed">FAST</div>
<div class="slc-card-wpm">160 WPM</div>
</div>
<div class="slc-card-right">
<div class="slc-card-time">${statsData.fast.time}</div>
<div class="slc-card-frames">${statsData.fast.frames} frames</div>
</div>
</div>
</div>
<div class="slc-legend">WPM = Words Per Minute</div>
`;
}
app.registerExtension({
name: "Comfy.SpeechLengthCalculator",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "SpeechLengthCalculator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
// 3. CREATE THE DOM WIDGET
const uiContainer = document.createElement("div");
uiContainer.className = "slc-ui-container";
uiContainer.innerHTML = buildUIHTML({ empty: true });
// Attach to node: standard addDOMWidget works natively in both V1 and V3 Frontends
let statsWidget;
if (typeof this.addDOMWidget === "function") {
statsWidget = this.addDOMWidget("Stats", "HTML", uiContainer, {
serialize: false,
hideOnZoom: false
});
} else {
// Fallback for very old unpatched V1 installations
statsWidget = ComfyWidgets["STRING"](this, "Stats", ["STRING", { multiline: true }], app).widget;
if (statsWidget.inputEl) {
statsWidget.inputEl.style.display = "none";
if (statsWidget.inputEl.parentNode) {
statsWidget.inputEl.parentNode.appendChild(uiContainer);
}
}
}
// Tell LiteGraph exactly how much vertical space to hold for our UI
statsWidget.computeSize = function() {
return [0, 280]; // Increased from 240 to prevent bottom cropping in V1
};
// Ensure the node is wide enough on initial creation
requestAnimationFrame(() => {
const minWidth = 340;
if (this.size[0] < minWidth) this.size[0] = minWidth;
// Fine tune initial height to account for the larger computeSize and make text box taller
if (this.size[1] < 500) this.size[1] = 500;
this.setDirtyCanvas(true, true);
});
// Fetch text from input link OR widget
this._getCurrentText = () => {
const inputSlot = this.inputs && this.inputs.find(i => i.name === "text_input" || (i.name === "text" && i.link));
if (inputSlot && inputSlot.link) {
const link = app.graph.links[inputSlot.link];
if (link) {
const sourceNode = app.graph.getNodeById(link.origin_id);
if (sourceNode && sourceNode.widgets) {
const w = sourceNode.widgets.find(w => w.name === "value" || w.name === "text" || w.name === "Text" || w.type === "customtext" || w.type === "STRING");
if (w && typeof w.value === "string") return w.value;
}
}
}
const textWidget = this.widgets && this.widgets.find(w => w.name === "text");
return textWidget ? (textWidget.value || "") : "";
};
this._lastState = { text: null, fps: null, addTime: null };
const updateStats = () => {
const fpsWidget = this.widgets && this.widgets.find(w => w.name === "fps");
const additionalTimeWidget = this.widgets && this.widgets.find(w => w.name === "additional_time");
if (!fpsWidget) return;
const text = this._getCurrentText();
const fps = fpsWidget.value || 24;
const additionalTime = additionalTimeWidget ? parseFloat(additionalTimeWidget.value) || 0 : 0;
// Skip expensive calculations if nothing changed
if (this._lastState.text === text &&
this._lastState.fps === fps &&
this._lastState.addTime === additionalTime) {
return;
}
this._lastState.text = text;
this._lastState.fps = fps;
this._lastState.addTime = additionalTime;
const regex = /"([^"]*)"|'([^']*)'|“([^”]*)”|([^]*)/g;
let match;
let quotedText = "";
while ((match = regex.exec(text)) !== null) {
quotedText += (match[1] || match[2] || match[3] || match[4] || "") + " ";
}
const words = quotedText.trim().split(/\s+/).filter(w => w.length > 0);
const wordCount = words.length;
const formatTime = (wpm) => {
const baseMins = wordCount / wpm;
const totalSecs = (baseMins * 60) + additionalTime;
const mins = Math.floor(totalSecs / 60);
let secs = totalSecs % 60;
secs = Math.ceil(secs * 10) / 10;
const frames = Math.ceil(totalSecs * fps);
const secsStr = secs.toFixed(1);
const timeStr = mins > 0 ? `${mins}m ${secsStr}s` : `${secsStr}s`;
return {
time: timeStr,
frames: frames.toString()
};
};
const statsData = {
empty: (wordCount === 0 && additionalTime === 0),
wordCount: wordCount,
additionalTime: additionalTime,
slow: formatTime(100),
avg: formatTime(130),
fast: formatTime(160)
};
// 4. INJECT HTML TO THE DOM
// Replaces the heavy canvas redrawing!
uiContainer.innerHTML = buildUIHTML(statsData);
this.setDirtyCanvas(true, false);
};
// We still use onDrawBackground as an efficient silent trigger
// to auto-update in case upstream nodes silently change their text
const onDrawBackground = this.onDrawBackground;
this.onDrawBackground = function(ctx) {
if (onDrawBackground) onDrawBackground.apply(this, arguments);
updateStats();
};
// Bind events to update in real time based on node interactions
setTimeout(() => {
const textWidget = this.widgets && this.widgets.find(w => w.name === "text");
const fpsWidget = this.widgets && this.widgets.find(w => w.name === "fps");
const additionalTimeWidget = this.widgets && this.widgets.find(w => w.name === "additional_time");
if (textWidget) {
const origCallback = textWidget.callback;
textWidget.callback = function() {
if (origCallback) origCallback.apply(this, arguments);
updateStats();
}
}
if (fpsWidget) {
const origFpsCallback = fpsWidget.callback;
fpsWidget.callback = function() {
if (origFpsCallback) origFpsCallback.apply(this, arguments);
updateStats();
}
}
if (additionalTimeWidget) {
const origAddCallback = additionalTimeWidget.callback;
additionalTimeWidget.callback = function() {
if (origAddCallback) origAddCallback.apply(this, arguments);
updateStats();
}
}
updateStats();
}, 100);
return r;
};
}
}
});