Refactor Lora widget callback to prevent recursive updates and improve code clarity

This commit is contained in:
Will Miao
2025-03-02 17:55:33 +08:00
parent 3e68a7f772
commit ac07cbcd55

View File

@@ -39,6 +39,7 @@ app.registerExtension({
let existingLoras = []; let existingLoras = [];
if (node.widgets_values && node.widgets_values.length > 0) { if (node.widgets_values && node.widgets_values.length > 0) {
const savedValue = node.widgets_values[1]; const savedValue = node.widgets_values[1];
// TODO: clean up this code
try { try {
// Check if the value is already an array/object // Check if the value is already an array/object
if (typeof savedValue === 'object' && savedValue !== null) { if (typeof savedValue === 'object' && savedValue !== null) {
@@ -54,10 +55,18 @@ app.registerExtension({
// Merge the loras data // Merge the loras data
const mergedLoras = mergeLoras(node.widgets[0].value, existingLoras); const mergedLoras = mergeLoras(node.widgets[0].value, existingLoras);
// Add flag to prevent callback loops
let isUpdating = false;
// Get the widget object directly from the returned object // Get the widget object directly from the returned object
const result = addLorasWidget(node, "loras", { const result = addLorasWidget(node, "loras", {
defaultVal: mergedLoras // Pass object directly defaultVal: mergedLoras // Pass object directly
}, (value) => { }, (value) => {
// Prevent recursive calls
if (isUpdating) return;
isUpdating = true;
try {
// Remove loras that are not in the value array // Remove loras that are not in the value array
const inputWidget = node.widgets[0]; const inputWidget = node.widgets[0];
const pattern = /<lora:([^:]+):([\d\.]+)>/g; const pattern = /<lora:([^:]+):([\d\.]+)>/g;
@@ -71,6 +80,9 @@ app.registerExtension({
newText = newText.replace(/\s+/g, ' ').trim(); newText = newText.replace(/\s+/g, ' ').trim();
inputWidget.value = newText; inputWidget.value = newText;
} finally {
isUpdating = false;
}
}); });
node.lorasWidget = result.widget; node.lorasWidget = result.widget;
@@ -78,12 +90,19 @@ app.registerExtension({
// get the input widget and set a callback // get the input widget and set a callback
const inputWidget = node.widgets[0]; const inputWidget = node.widgets[0];
inputWidget.callback = (value) => { inputWidget.callback = (value) => {
// Prevent recursive calls
if (isUpdating) return;
isUpdating = true;
try {
// Merge the loras data with widget value // Merge the loras data with widget value
const currentLoras = node.lorasWidget.value || []; const currentLoras = node.lorasWidget.value || [];
const mergedLoras = mergeLoras(value, currentLoras); const mergedLoras = mergeLoras(value, currentLoras);
node.lorasWidget.value = mergedLoras; node.lorasWidget.value = mergedLoras;
// node.graph.setDirtyCanvas(true, true); } finally {
isUpdating = false;
}
}; };
}); });
} }