From d484f3e5d1ffa6d58eb5d6a5da8a31bc38b48ddb Mon Sep 17 00:00:00 2001 From: chflame163 Date: Wed, 21 Feb 2024 16:43:52 +0800 Subject: [PATCH] fix bug of nodes use the mtb's ComfyUI web extention --- js/comfy_shared.js | 168 ++++----------------------------------------- js/debug.js | 17 +---- js/mtb_widgets.js | 92 ++++--------------------- 3 files changed, 26 insertions(+), 251 deletions(-) diff --git a/js/comfy_shared.js b/js/comfy_shared.js index a60602e..c96fbdd 100644 --- a/js/comfy_shared.js +++ b/js/comfy_shared.js @@ -9,68 +9,6 @@ import { app } from '../../scripts/app.js' -// - crude uuid -export function makeUUID() { - let dt = new Date().getTime() - const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { - const r = (dt + Math.random() * 16) % 16 | 0 - dt = Math.floor(dt / 16) - return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16) - }) - return uuid -} - -//- local storage manager -export class LocalStorageManager { - constructor(namespace) { - this.namespace = namespace; - } - - _namespacedKey(key) { - return `${this.namespace}:${key}`; - } - - set(key, value) { - const serializedValue = JSON.stringify(value); - localStorage.setItem(this._namespacedKey(key), serializedValue); - } - - get(key, default_val = null) { - const value = localStorage.getItem(this._namespacedKey(key)); - return value ? JSON.parse(value) : default_val; - } - - remove(key) { - localStorage.removeItem(this._namespacedKey(key)); - } - - clear() { - Object.keys(localStorage) - .filter(k => k.startsWith(this.namespace + ':')) - .forEach(k => localStorage.removeItem(k)); - } -} - - -// - log utilities - -function createLogger(emoji, color, consoleMethod = 'log') { - return function (message, ...args) { - if (window.MTB?.DEBUG) { - console[consoleMethod]( - `%c${emoji} ${message}`, - `color: ${color};`, - ...args - ) - } - } -} - -export const infoLogger = createLogger('ℹ️', 'yellow') -export const warnLogger = createLogger('⚠️', 'orange', 'warn') -export const errorLogger = createLogger('🔥', 'red', 'error') -export const successLogger = createLogger('✅', 'green') - export const log = (...args) => { if (window.MTB?.DEBUG) { console.debug(...args) @@ -154,38 +92,14 @@ export function getWidgetType(config) { } return { type, linkType } } -export const setupDynamicConnections = (nodeType, prefix, inputType) => { - const onNodeCreated = nodeType.prototype.onNodeCreated - nodeType.prototype.onNodeCreated = function () { - const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined - this.addInput(`${prefix}_1`, inputType) - return r - } - const onConnectionsChange = nodeType.prototype.onConnectionsChange - nodeType.prototype.onConnectionsChange = function ( - type, - index, - connected, - link_info - ) { - const r = onConnectionsChange - ? onConnectionsChange.apply(this, arguments) - : undefined - dynamic_connection(this, index, connected, `${prefix}_`, inputType) - } -} export const dynamic_connection = ( node, index, connected, connectionPrefix = 'input_', - connectionType = 'PSDLAYER', - nameArray = [] + connectionType = 'PSDLAYER' ) => { - if (!node.inputs[index].name.startsWith(connectionPrefix)) { - return - } // remove all non connected inputs if (!connected && node.inputs.length > 1) { log(`Removing input ${index} (${node.inputs[index].name})`) @@ -200,46 +114,25 @@ export const dynamic_connection = ( // make inputs sequential again for (let i = 0; i < node.inputs.length; i++) { - const name = - i < nameArray.length ? nameArray[i] : `${connectionPrefix}${i + 1}` - node.inputs[i].label = name - node.inputs[i].name = name + node.inputs[i].label = `${connectionPrefix}${i + 1}` } } // add an extra input if (node.inputs[node.inputs.length - 1].link != undefined) { - const nextIndex = node.inputs.length - const name = - nextIndex < nameArray.length - ? nameArray[nextIndex] - : `${connectionPrefix}${nextIndex + 1}` + log( + `Adding input ${node.inputs.length + 1} (${connectionPrefix}${ + node.inputs.length + 1 + })` + ) - log(`Adding input ${nextIndex + 1} (${name})`) - - node.addInput(name, connectionType) + node.addInput( + `${connectionPrefix}${node.inputs.length + 1}`, + connectionType + ) } } -export function calculateTotalChildrenHeight(parentElement) { - let totalHeight = 0 - - for (const child of parentElement.children) { - const style = window.getComputedStyle(child) - - // Get height as an integer (without 'px') - const height = parseInt(style.height, 10) - - // Get vertical margin as integers - const marginTop = parseInt(style.marginTop, 10) - const marginBottom = parseInt(style.marginBottom, 10) - - // Sum up height and vertical margins - totalHeight += height + marginTop + marginBottom - } - - return totalHeight -} /** * Appends a callback to the extra menu options of a given node type. * @param {*} nodeType @@ -410,48 +303,11 @@ function getBrightness(rgbObj) { (parseInt(rgbObj[0]) * 299 + parseInt(rgbObj[1]) * 587 + parseInt(rgbObj[2]) * 114) / - 1000 + 1000 ) } //- HTML / CSS UTILS -export const loadScript = ( - FILE_URL, - async = true, - type = 'text/javascript' -) => { - return new Promise((resolve, reject) => { - try { - // Check if the script already exists - const existingScript = document.querySelector(`script[src="${FILE_URL}"]`) - if (existingScript) { - resolve({ status: true, message: 'Script already loaded' }) - return - } - - const scriptEle = document.createElement('script') - scriptEle.type = type - scriptEle.async = async - scriptEle.src = FILE_URL - - scriptEle.addEventListener('load', (ev) => { - resolve({ status: true }) - }) - - scriptEle.addEventListener('error', (ev) => { - reject({ - status: false, - message: `Failed to load the script ${FILE_URL}`, - }) - }) - - document.body.appendChild(scriptEle) - } catch (error) { - reject(error) - } - }) -} - export function defineClass(className, classStyles) { const styleSheets = document.styleSheets diff --git a/js/debug.js b/js/debug.js index 319bf1b..0f144c7 100644 --- a/js/debug.js +++ b/js/debug.js @@ -27,15 +27,6 @@ app.registerExtension({ name: 'mtb.Debug', async beforeRegisterNodeDef(nodeType, nodeData, app) { if (nodeData.name === 'Debug (mtb)') { - const onNodeCreated = nodeType.prototype.onNodeCreated - nodeType.prototype.onNodeCreated = function () { - const r = onNodeCreated - ? onNodeCreated.apply(this, arguments) - : undefined - this.addInput(`anything_1`, '*') - return r - } - const onConnectionsChange = nodeType.prototype.onConnectionsChange nodeType.prototype.onConnectionsChange = function ( type, @@ -75,14 +66,11 @@ app.registerExtension({ // const pos = this.widgets.findIndex((w) => w.name === "anything_1"); // if (pos !== -1) { for (let i = 0; i < this.widgets.length; i++) { - if (this.widgets[i].name !== 'output_to_console') { - this.widgets[i].onRemoved?.() - } + this.widgets[i].onRemoved?.() } - this.widgets.length = 1 + this.widgets.length = 0 } let widgetI = 1 - if (message.text) { for (const txt of message.text) { const w = this.addCustomWidget( @@ -112,7 +100,6 @@ app.registerExtension({ if (this.widgets[y].canvas) { this.widgets[y].canvas.remove() } - shared.cleanupNode(this) this.widgets[y].onRemoved?.() } } diff --git a/js/mtb_widgets.js b/js/mtb_widgets.js index 5f88a20..da11de2 100644 --- a/js/mtb_widgets.js +++ b/js/mtb_widgets.js @@ -7,12 +7,10 @@ * */ -// TODO: Use the builtin addDOMWidget everywhere appropriate - import { app } from '../../scripts/app.js' import { api } from '../../scripts/api.js' -import parseCss from './extern/parse-css.js' +import parseCss from './parse-css.js' import * as shared from './comfy_shared.js' import { log } from './comfy_shared.js' @@ -195,7 +193,7 @@ export const MtbWidgets = { try { //solve the equation if possible v = eval(v) - } catch (e) { } + } catch (e) {} } this.value = Number(v) shared.inner_value_change(this, this.value, event) @@ -419,7 +417,7 @@ const mtb_widgets = { setup: () => { app.ui.settings.addSetting({ id: 'mtb.Debug.enabled', - name: '[⚡mtb] Enable Debug (py and js)', + name: '[mtb] Enable Debug (py and js)', type: 'boolean', defaultValue: false, @@ -445,7 +443,7 @@ const mtb_widgets = { enabled: value, }), }) - .then((response) => { }) + .then((response) => {}) .catch((error) => { console.error('Error:', error) }) @@ -563,10 +561,6 @@ const mtb_widgets = { } } - if (!nodeData.name.endsWith('(mtb)')) { - return - } - //- Extending Python Nodes switch (nodeData.name) { case 'Psd Save (mtb)': { @@ -723,7 +717,8 @@ const mtb_widgets = { onReset() // this could maybe be a setting or checkbox app.queuePrompt(0, total_frames.value * loop_count.value) window.MTB?.notify?.( - `Started a queue of ${total_frames.value} frames (for ${loop_count.value + `Started a queue of ${total_frames.value} frames (for ${ + loop_count.value } loop, so ${total_frames.value * loop_count.value})`, 5000 ) @@ -738,14 +733,16 @@ const mtb_widgets = { this.value++ raw_loop.value = Math.floor(this.value / total_frames.value) - value_preview.value = `frame: ${raw_iteration.value % total_frames.value - } / ${total_frames.value - 1}` + value_preview.value = `frame: ${ + raw_iteration.value % total_frames.value + } / ${total_frames.value - 1}` if (raw_loop.value + 1 > loop_count.value) { loop_preview.value = 'Done 😎!' } else { - loop_preview.value = `current loop: ${raw_loop.value + 1}/${loop_count.value - }` + loop_preview.value = `current loop: ${raw_loop.value + 1}/${ + loop_count.value + }` } } @@ -880,71 +877,6 @@ const mtb_widgets = { break } - case 'Add To Playlist (mtb)': { - shared.setupDynamicConnections(nodeType, 'video', 'VIDEO') - break - } - case 'Stack Images (mtb)': - case 'Concat Images (mtb)': { - shared.setupDynamicConnections(nodeType, 'image', 'IMAGE') - - break - } - case 'Batch Float Assemble (mtb)': - case 'Plot Batch Float (mtb)': { - shared.setupDynamicConnections(nodeType, 'floats', 'FLOATS') - break - } - case 'Batch Merge (mtb)': { - shared.setupDynamicConnections(nodeType, 'batches', 'IMAGE') - - break - } - // TODO: remove this, recommend pythongoss's version that is much better - case 'Math Expression (mtb)': { - const onNodeCreated = nodeType.prototype.onNodeCreated - nodeType.prototype.onNodeCreated = function () { - const r = onNodeCreated - ? onNodeCreated.apply(this, arguments) - : undefined - this.addInput(`x`, '*') - return r - } - - const onConnectionsChange = nodeType.prototype.onConnectionsChange - nodeType.prototype.onConnectionsChange = function ( - type, - index, - connected, - link_info - ) { - const r = onConnectionsChange - ? onConnectionsChange.apply(this, arguments) - : undefined - shared.dynamic_connection(this, index, connected, 'var_', '*', [ - 'x', - 'y', - 'z', - ]) - - //- infer type - if (link_info) { - const fromNode = this.graph._nodes.find( - (otherNode) => otherNode.id == link_info.origin_id - ) - const type = fromNode.outputs[link_info.origin_slot].type - this.inputs[index].type = type - // this.inputs[index].label = type.toLowerCase() - } - //- restore dynamic input - if (!connected) { - this.inputs[index].type = '*' - this.inputs[index].label = `number_${index + 1}` - } - } - - break - } case 'Save Tensors (mtb)': { const onDrawBackground = nodeType.prototype.onDrawBackground nodeType.prototype.onDrawBackground = function (ctx, canvas) {