diff --git a/.disabled/comfyui-kjnodes@nightly/__pycache__/__init__.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9cb124857360c557e574714efe1a5db8a2a4ca2 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/__pycache__/__init__.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/kjweb_async/marked.min.js b/.disabled/comfyui-kjnodes@nightly/kjweb_async/marked.min.js new file mode 100644 index 0000000000000000000000000000000000000000..ba7976efddaa97edaf2a7600e851308b747cfd83 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/kjweb_async/marked.min.js @@ -0,0 +1,6 @@ +/** + * marked v12.0.1 - a markdown parser + * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).marked={})}(this,(function(e){"use strict";function t(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function n(t){e.defaults=t}e.defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};const s=/[&<>"']/,r=new RegExp(s.source,"g"),i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l=new RegExp(i.source,"g"),o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=e=>o[e];function c(e,t){if(t){if(s.test(e))return e.replace(r,a)}else if(i.test(e))return e.replace(l,a);return e}const h=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(e){return e.replace(h,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const u=/(^|[^\[])\^/g;function k(e,t){let n="string"==typeof e?e:e.source;t=t||"";const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(u,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}function g(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const f={exec:()=>null};function d(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:x(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=x(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const e=x(t[0].replace(/^ *>[ \t]?/gm,""),"\n"),n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let l="",o="",a=!1;for(;e;){let n=!1;if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let s=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=0;this.options.pedantic?(h=2,o=s.trimStart()):(h=t[2].search(/[^ ]/),h=h>4?1:h,o=s.slice(h),h+=t[1].length);let p=!1;if(!s&&/^ *$/.test(c)&&(l+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,h-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:\`\`\`|~~~)`),i=new RegExp(`^ {0,${Math.min(3,h-1)}}#`);for(;e;){const a=e.split("\n",1)[0];if(c=a,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),r.test(c))break;if(i.test(c))break;if(t.test(c))break;if(n.test(e))break;if(c.search(/[^ ]/)>=h||!c.trim())o+="\n"+c.slice(h);else{if(p)break;if(s.search(/[^ ]/)>=4)break;if(r.test(s))break;if(i.test(s))break;if(n.test(s))break;o+="\n"+c}p||c.trim()||(p=!0),l+=a+"\n",e=e.substring(a.length+1),s=c.slice(h)}}r.loose||(a?r.loose=!0:/\n *\n *$/.test(l)&&(a=!0));let u,k=null;this.options.gfm&&(k=/^\[[ xX]\] /.exec(o),k&&(u="[ ] "!==k[0],o=o.replace(/^\[[ xX]\] +/,""))),r.items.push({type:"list_item",raw:l,task:!!k,checked:u,loose:!1,text:o,tokens:[]}),r.raw+=l}r.items[r.items.length-1].raw=l.trimEnd(),r.items[r.items.length-1].text=o.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=d(t[1]),s=t[2].replace(/^\||\| *$/g,"").split("|"),r=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const e of s)/^ *-+: *$/.test(e)?i.align.push("right"):/^ *:-+: *$/.test(e)?i.align.push("center"):/^ *:-+ *$/.test(e)?i.align.push("left"):i.align.push(null);for(const e of n)i.header.push({text:e,tokens:this.lexer.inline(e)});for(const e of r)i.rows.push(d(e,i.header.length).map((e=>({text:e,tokens:this.lexer.inline(e)}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:c(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^$/.test(e))return;const t=x(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^$/.test(e)?n.slice(1):n.slice(1,-1)),b(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return b(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...s[0]].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=[...s[0]][0].length,a=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=a.slice(1,-1);return{type:"em",raw:a,text:e,tokens:this.lexer.inlineTokens(e)}}const c=a.slice(2,-2);return{type:"strong",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=c(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=c(t[1]),n="mailto:"+e):(e=c(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=c(t[0]),n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=c(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:c(t[0]),{type:"text",raw:t[0],text:e}}}}const m=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,$=k(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,y).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),z=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,T=/(?!\s*\])(?:\\.|[^\[\]\\])+/,R=k(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",T).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_=k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),A="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",S=/|$))/,I=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",S).replace("tag",A).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),E=k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),q={blockquote:k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",E).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:R,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:m,html:I,lheading:$,list:_,newline:/^(?: *(?:\n|$))+/,paragraph:E,table:f,text:/^[^\n]+/},Z=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),L={...q,table:Z,paragraph:k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Z).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex()},P={...q,html:k("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",S).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:f,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(z).replace("hr",m).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,v=/^( {2,}|\\)\n(?!\s*$)/,B="\\p{P}\\p{S}",C=k(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,B).getRegex(),M=k(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,B).getRegex(),O=k("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,B).getRegex(),D=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,B).getRegex(),j=k(/\\([punct])/,"gu").replace(/punct/g,B).getRegex(),H=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),U=k(S).replace("(?:--\x3e|$)","--\x3e").getRegex(),X=k("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",U).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,N=k(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),G=k(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",T).getRegex(),J=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",T).getRegex(),K={_backpedal:f,anyPunctuation:j,autolink:H,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:v,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:f,emStrongLDelim:M,emStrongRDelimAst:O,emStrongRDelimUnd:D,escape:Q,link:N,nolink:J,punctuation:C,reflink:G,reflinkSearch:k("reflink|nolink(?!\\()","g").replace("reflink",G).replace("nolink",J).getRegex(),tag:X,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(a));)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class se{options;constructor(t){this.options=t||e.defaults}code(e,t,n){const s=(t||"").match(/^\S*/)?.[0];return e=e.replace(/\n$/,"")+"\n",s?'
'+(n?e:c(e,!0))+"
\n":"
"+(n?e:c(e,!0))+"
\n"}blockquote(e){return`
\n${e}
\n`}html(e,t){return e}heading(e,t,n){return`${e}\n`}hr(){return"
\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"}listitem(e,t,n){return`
  • ${e}
  • \n`}checkbox(e){return"'}paragraph(e){return`

    ${e}

    \n`}table(e,t){return t&&(t=`${t}`),"\n\n"+e+"\n"+t+"
    \n"}tablerow(e){return`\n${e}\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`\n`}strong(e){return`${e}`}em(e){return`${e}`}codespan(e){return`${e}`}br(){return"
    "}del(e){return`${e}`}link(e,t,n){const s=g(e);if(null===s)return n;let r='
    ",r}image(e,t,n){const s=g(e);if(null===s)return n;let r=`${n}0&&"paragraph"===n.tokens[0].type?(n.tokens[0].text=e+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&"text"===n.tokens[0].tokens[0].type&&(n.tokens[0].tokens[0].text=e+" "+n.tokens[0].tokens[0].text)):n.tokens.unshift({type:"text",text:e+" "}):o+=e+" "}o+=this.parse(n.tokens,i),l+=this.renderer.listitem(o,r,!!s)}n+=this.renderer.list(l,t,s);continue}case"html":{const e=r;n+=this.renderer.html(e.text,e.block);continue}case"paragraph":{const e=r;n+=this.renderer.paragraph(this.parseInline(e.tokens));continue}case"text":{let i=r,l=i.tokens?this.parseInline(i.tokens):i.text;for(;s+1{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new se(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new w(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new le;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.hooks[s],i=t[s];le.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ne.lex(e,t??this.defaults)}parser(e,t){return ie.parse(e,t??this.defaults)}#e(e,t){return(n,s)=>{const r={...s},i={...this.defaults,...r};!0===this.defaults.async&&!1===r.async&&(i.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i.async=!0);const l=this.#t(!!i.silent,!!i.async);if(null==n)return l(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i),i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(n):n).then((t=>e(t,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>t(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(l);try{i.hooks&&(n=i.hooks.preprocess(n));let s=e(n,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let r=t(s,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return l(e)}}}#t(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="

    An error occurred:

    "+c(n.message+"",!0)+"
    ";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const ae=new oe;function ce(e,t){return ae.parse(e,t)}ce.options=ce.setOptions=function(e){return ae.setOptions(e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.getDefaults=t,ce.defaults=e.defaults,ce.use=function(...e){return ae.use(...e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.walkTokens=function(e,t){return ae.walkTokens(e,t)},ce.parseInline=ae.parseInline,ce.Parser=ie,ce.parser=ie.parse,ce.Renderer=se,ce.TextRenderer=re,ce.Lexer=ne,ce.lexer=ne.lex,ce.Tokenizer=w,ce.Hooks=le,ce.parse=ce;const he=ce.options,pe=ce.setOptions,ue=ce.use,ke=ce.walkTokens,ge=ce.parseInline,fe=ce,de=ie.parse,xe=ne.lex;e.Hooks=le,e.Lexer=ne,e.Marked=oe,e.Parser=ie,e.Renderer=se,e.TextRenderer=re,e.Tokenizer=w,e.getDefaults=t,e.lexer=xe,e.marked=ce,e.options=he,e.parse=fe,e.parseInline=ge,e.parser=de,e.setOptions=pe,e.use=ue,e.walkTokens=ke})); diff --git a/.disabled/comfyui-kjnodes@nightly/kjweb_async/purify.min.js b/.disabled/comfyui-kjnodes@nightly/kjweb_async/purify.min.js new file mode 100644 index 0000000000000000000000000000000000000000..42e7f3bdb08798be14106228c1316b2ee837d4ea --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/kjweb_async/purify.min.js @@ -0,0 +1,3 @@ +/*! @license DOMPurify 3.0.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.11/LICENSE */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).DOMPurify=t()}(this,(function(){"use strict";const{entries:e,setPrototypeOf:t,isFrozen:n,getPrototypeOf:o,getOwnPropertyDescriptor:r}=Object;let{freeze:i,seal:a,create:l}=Object,{apply:c,construct:s}="undefined"!=typeof Reflect&&Reflect;i||(i=function(e){return e}),a||(a=function(e){return e}),c||(c=function(e,t,n){return e.apply(t,n)}),s||(s=function(e,t){return new e(...t)});const u=b(Array.prototype.forEach),m=b(Array.prototype.pop),p=b(Array.prototype.push),f=b(String.prototype.toLowerCase),d=b(String.prototype.toString),h=b(String.prototype.match),g=b(String.prototype.replace),T=b(String.prototype.indexOf),y=b(String.prototype.trim),E=b(Object.prototype.hasOwnProperty),A=b(RegExp.prototype.test),_=(N=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n1?n-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:f;t&&t(e,null);let i=o.length;for(;i--;){let t=o[i];if("string"==typeof t){const e=r(t);e!==t&&(n(o)||(o[i]=e),t=e)}e[t]=!0}return e}function R(e){for(let t=0;t/gm),B=a(/\${[\w\W]*}/gm),W=a(/^data-[\-\w.\u00B7-\uFFFF]/),G=a(/^aria-[\-\w]+$/),Y=a(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),j=a(/^(?:\w+script|data):/i),X=a(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),q=a(/^html$/i),$=a(/^[a-z][.\w]*(-[.\w]+)+$/i);var K=Object.freeze({__proto__:null,MUSTACHE_EXPR:H,ERB_EXPR:z,TMPLIT_EXPR:B,DATA_ATTR:W,ARIA_ATTR:G,IS_ALLOWED_URI:Y,IS_SCRIPT_OR_DATA:j,ATTR_WHITESPACE:X,DOCTYPE_NAME:q,CUSTOM_ELEMENT:$});const V=function(){return"undefined"==typeof window?null:window},Z=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}};var J=function t(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:V();const o=e=>t(e);if(o.version="3.0.11",o.removed=[],!n||!n.document||9!==n.document.nodeType)return o.isSupported=!1,o;let{document:r}=n;const a=r,c=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:N,Node:b,Element:R,NodeFilter:H,NamedNodeMap:z=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:B,DOMParser:W,trustedTypes:G}=n,j=R.prototype,X=L(j,"cloneNode"),$=L(j,"nextSibling"),J=L(j,"childNodes"),Q=L(j,"parentNode");if("function"==typeof N){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let ee,te="";const{implementation:ne,createNodeIterator:oe,createDocumentFragment:re,getElementsByTagName:ie}=r,{importNode:ae}=a;let le={};o.isSupported="function"==typeof e&&"function"==typeof Q&&ne&&void 0!==ne.createHTMLDocument;const{MUSTACHE_EXPR:ce,ERB_EXPR:se,TMPLIT_EXPR:ue,DATA_ATTR:me,ARIA_ATTR:pe,IS_SCRIPT_OR_DATA:fe,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:he}=K;let{IS_ALLOWED_URI:ge}=K,Te=null;const ye=S({},[...D,...C,...O,...v,...M]);let Ee=null;const Ae=S({},[...I,...U,...P,...F]);let _e=Object.seal(l(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ne=null,be=null,Se=!0,Re=!0,we=!1,Le=!0,De=!1,Ce=!0,Oe=!1,xe=!1,ve=!1,ke=!1,Me=!1,Ie=!1,Ue=!0,Pe=!1;const Fe="user-content-";let He=!0,ze=!1,Be={},We=null;const Ge=S({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ye=null;const je=S({},["audio","video","img","source","image","track"]);let Xe=null;const qe=S({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),$e="http://www.w3.org/1998/Math/MathML",Ke="http://www.w3.org/2000/svg",Ve="http://www.w3.org/1999/xhtml";let Ze=Ve,Je=!1,Qe=null;const et=S({},[$e,Ke,Ve],d);let tt=null;const nt=["application/xhtml+xml","text/html"],ot="text/html";let rt=null,it=null;const at=r.createElement("form"),lt=function(e){return e instanceof RegExp||e instanceof Function},ct=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!it||it!==e){if(e&&"object"==typeof e||(e={}),e=w(e),tt=-1===nt.indexOf(e.PARSER_MEDIA_TYPE)?ot:e.PARSER_MEDIA_TYPE,rt="application/xhtml+xml"===tt?d:f,Te=E(e,"ALLOWED_TAGS")?S({},e.ALLOWED_TAGS,rt):ye,Ee=E(e,"ALLOWED_ATTR")?S({},e.ALLOWED_ATTR,rt):Ae,Qe=E(e,"ALLOWED_NAMESPACES")?S({},e.ALLOWED_NAMESPACES,d):et,Xe=E(e,"ADD_URI_SAFE_ATTR")?S(w(qe),e.ADD_URI_SAFE_ATTR,rt):qe,Ye=E(e,"ADD_DATA_URI_TAGS")?S(w(je),e.ADD_DATA_URI_TAGS,rt):je,We=E(e,"FORBID_CONTENTS")?S({},e.FORBID_CONTENTS,rt):Ge,Ne=E(e,"FORBID_TAGS")?S({},e.FORBID_TAGS,rt):{},be=E(e,"FORBID_ATTR")?S({},e.FORBID_ATTR,rt):{},Be=!!E(e,"USE_PROFILES")&&e.USE_PROFILES,Se=!1!==e.ALLOW_ARIA_ATTR,Re=!1!==e.ALLOW_DATA_ATTR,we=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Le=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,De=e.SAFE_FOR_TEMPLATES||!1,Ce=!1!==e.SAFE_FOR_XML,Oe=e.WHOLE_DOCUMENT||!1,ke=e.RETURN_DOM||!1,Me=e.RETURN_DOM_FRAGMENT||!1,Ie=e.RETURN_TRUSTED_TYPE||!1,ve=e.FORCE_BODY||!1,Ue=!1!==e.SANITIZE_DOM,Pe=e.SANITIZE_NAMED_PROPS||!1,He=!1!==e.KEEP_CONTENT,ze=e.IN_PLACE||!1,ge=e.ALLOWED_URI_REGEXP||Y,Ze=e.NAMESPACE||Ve,_e=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&<(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(_e.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&<(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(_e.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(_e.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),De&&(Re=!1),Me&&(ke=!0),Be&&(Te=S({},M),Ee=[],!0===Be.html&&(S(Te,D),S(Ee,I)),!0===Be.svg&&(S(Te,C),S(Ee,U),S(Ee,F)),!0===Be.svgFilters&&(S(Te,O),S(Ee,U),S(Ee,F)),!0===Be.mathMl&&(S(Te,v),S(Ee,P),S(Ee,F))),e.ADD_TAGS&&(Te===ye&&(Te=w(Te)),S(Te,e.ADD_TAGS,rt)),e.ADD_ATTR&&(Ee===Ae&&(Ee=w(Ee)),S(Ee,e.ADD_ATTR,rt)),e.ADD_URI_SAFE_ATTR&&S(Xe,e.ADD_URI_SAFE_ATTR,rt),e.FORBID_CONTENTS&&(We===Ge&&(We=w(We)),S(We,e.FORBID_CONTENTS,rt)),He&&(Te["#text"]=!0),Oe&&S(Te,["html","head","body"]),Te.table&&(S(Te,["tbody"]),delete Ne.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw _('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw _('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=e.TRUSTED_TYPES_POLICY,te=ee.createHTML("")}else void 0===ee&&(ee=Z(G,c)),null!==ee&&"string"==typeof te&&(te=ee.createHTML(""));i&&i(e),it=e}},st=S({},["mi","mo","mn","ms","mtext"]),ut=S({},["foreignobject","desc","title","annotation-xml"]),mt=S({},["title","style","font","a","script"]),pt=S({},[...C,...O,...x]),ft=S({},[...v,...k]),dt=function(e){let t=Q(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const n=f(e.tagName),o=f(t.tagName);return!!Qe[e.namespaceURI]&&(e.namespaceURI===Ke?t.namespaceURI===Ve?"svg"===n:t.namespaceURI===$e?"svg"===n&&("annotation-xml"===o||st[o]):Boolean(pt[n]):e.namespaceURI===$e?t.namespaceURI===Ve?"math"===n:t.namespaceURI===Ke?"math"===n&&ut[o]:Boolean(ft[n]):e.namespaceURI===Ve?!(t.namespaceURI===Ke&&!ut[o])&&(!(t.namespaceURI===$e&&!st[o])&&(!ft[n]&&(mt[n]||!pt[n]))):!("application/xhtml+xml"!==tt||!Qe[e.namespaceURI]))},ht=function(e){p(o.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.remove()}},gt=function(e,t){try{p(o.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){p(o.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e&&!Ee[e])if(ke||Me)try{ht(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Tt=function(e){let t=null,n=null;if(ve)e=""+e;else{const t=h(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===tt&&Ze===Ve&&(e=''+e+"");const o=ee?ee.createHTML(e):e;if(Ze===Ve)try{t=(new W).parseFromString(o,tt)}catch(e){}if(!t||!t.documentElement){t=ne.createDocument(Ze,"template",null);try{t.documentElement.innerHTML=Je?te:o}catch(e){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),Ze===Ve?ie.call(t,Oe?"html":"body")[0]:Oe?t.documentElement:i},yt=function(e){return oe.call(e.ownerDocument||e,e,H.SHOW_ELEMENT|H.SHOW_COMMENT|H.SHOW_TEXT|H.SHOW_PROCESSING_INSTRUCTION|H.SHOW_CDATA_SECTION,null)},Et=function(e){return e instanceof B&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof z)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},At=function(e){return"function"==typeof b&&e instanceof b},_t=function(e,t,n){le[e]&&u(le[e],(e=>{e.call(o,t,n,it)}))},Nt=function(e){let t=null;if(_t("beforeSanitizeElements",e,null),Et(e))return ht(e),!0;const n=rt(e.nodeName);if(_t("uponSanitizeElement",e,{tagName:n,allowedTags:Te}),e.hasChildNodes()&&!At(e.firstElementChild)&&A(/<[/\w]/g,e.innerHTML)&&A(/<[/\w]/g,e.textContent))return ht(e),!0;if(7===e.nodeType)return ht(e),!0;if(Ce&&8===e.nodeType&&A(/<[/\w]/g,e.data))return ht(e),!0;if(!Te[n]||Ne[n]){if(!Ne[n]&&St(n)){if(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,n))return!1;if(_e.tagNameCheck instanceof Function&&_e.tagNameCheck(n))return!1}if(He&&!We[n]){const t=Q(e)||e.parentNode,n=J(e)||e.childNodes;if(n&&t){for(let o=n.length-1;o>=0;--o)t.insertBefore(X(n[o],!0),$(e))}}return ht(e),!0}return e instanceof R&&!dt(e)?(ht(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!A(/<\/no(script|embed|frames)/i,e.innerHTML)?(De&&3===e.nodeType&&(t=e.textContent,u([ce,se,ue],(e=>{t=g(t,e," ")})),e.textContent!==t&&(p(o.removed,{element:e.cloneNode()}),e.textContent=t)),_t("afterSanitizeElements",e,null),!1):(ht(e),!0)},bt=function(e,t,n){if(Ue&&("id"===t||"name"===t)&&(n in r||n in at))return!1;if(Re&&!be[t]&&A(me,t));else if(Se&&A(pe,t));else if(!Ee[t]||be[t]){if(!(St(e)&&(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,e)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(e))&&(_e.attributeNameCheck instanceof RegExp&&A(_e.attributeNameCheck,t)||_e.attributeNameCheck instanceof Function&&_e.attributeNameCheck(t))||"is"===t&&_e.allowCustomizedBuiltInElements&&(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,n)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(n))))return!1}else if(Xe[t]);else if(A(ge,g(n,de,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==T(n,"data:")||!Ye[e]){if(we&&!A(fe,g(n,de,"")));else if(n)return!1}else;return!0},St=function(e){return"annotation-xml"!==e&&h(e,he)},Rt=function(e){_t("beforeSanitizeAttributes",e,null);const{attributes:t}=e;if(!t)return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ee};let r=t.length;for(;r--;){const i=t[r],{name:a,namespaceURI:l,value:c}=i,s=rt(a);let p="value"===a?c:y(c);if(n.attrName=s,n.attrValue=p,n.keepAttr=!0,n.forceKeepAttr=void 0,_t("uponSanitizeAttribute",e,n),p=n.attrValue,n.forceKeepAttr)continue;if(gt(a,e),!n.keepAttr)continue;if(!Le&&A(/\/>/i,p)){gt(a,e);continue}De&&u([ce,se,ue],(e=>{p=g(p,e," ")}));const f=rt(e.nodeName);if(bt(f,s,p)){if(!Pe||"id"!==s&&"name"!==s||(gt(a,e),p=Fe+p),ee&&"object"==typeof G&&"function"==typeof G.getAttributeType)if(l);else switch(G.getAttributeType(f,s)){case"TrustedHTML":p=ee.createHTML(p);break;case"TrustedScriptURL":p=ee.createScriptURL(p)}try{l?e.setAttributeNS(l,a,p):e.setAttribute(a,p),m(o.removed)}catch(e){}}}_t("afterSanitizeAttributes",e,null)},wt=function e(t){let n=null;const o=yt(t);for(_t("beforeSanitizeShadowDOM",t,null);n=o.nextNode();)_t("uponSanitizeShadowNode",n,null),Nt(n)||(n.content instanceof s&&e(n.content),Rt(n));_t("afterSanitizeShadowDOM",t,null)};return o.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,i=null,l=null;if(Je=!e,Je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!At(e)){if("function"!=typeof e.toString)throw _("toString is not a function");if("string"!=typeof(e=e.toString()))throw _("dirty is not a string, aborting")}if(!o.isSupported)return e;if(xe||ct(t),o.removed=[],"string"==typeof e&&(ze=!1),ze){if(e.nodeName){const t=rt(e.nodeName);if(!Te[t]||Ne[t])throw _("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof b)n=Tt("\x3c!----\x3e"),r=n.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r);else{if(!ke&&!De&&!Oe&&-1===e.indexOf("<"))return ee&&Ie?ee.createHTML(e):e;if(n=Tt(e),!n)return ke?null:Ie?te:""}n&&ve&&ht(n.firstChild);const c=yt(ze?e:n);for(;i=c.nextNode();)Nt(i)||(i.content instanceof s&&wt(i.content),Rt(i));if(ze)return e;if(ke){if(Me)for(l=re.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(Ee.shadowroot||Ee.shadowrootmode)&&(l=ae.call(a,l,!0)),l}let m=Oe?n.outerHTML:n.innerHTML;return Oe&&Te["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&A(q,n.ownerDocument.doctype.name)&&(m="\n"+m),De&&u([ce,se,ue],(e=>{m=g(m,e," ")})),ee&&Ie?ee.createHTML(m):m},o.setConfig=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};ct(e),xe=!0},o.clearConfig=function(){it=null,xe=!1},o.isValidAttribute=function(e,t,n){it||ct({});const o=rt(e),r=rt(t);return bt(o,r,n)},o.addHook=function(e,t){"function"==typeof t&&(le[e]=le[e]||[],p(le[e],t))},o.removeHook=function(e){if(le[e])return m(le[e])},o.removeHooks=function(e){le[e]&&(le[e]=[])},o.removeAllHooks=function(){le={}},o}();return J})); +//# sourceMappingURL=purify.min.js.map diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/model_optimization_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/model_optimization_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb3944eb86c4d53538ac0087719e4711bd937b9b Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/model_optimization_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa0a9e0b2bed917492dba024e151fc7e03719dc3 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/sharpen_nodes.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/sharpen_nodes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7b21470959cd13e9bc54f404ea6ee65489b0fd2 Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/sharpen_nodes.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..5c882613dbbe82bb48226028a1fa4d0926adf21e --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/nodes.py @@ -0,0 +1,3389 @@ +import torch +import torch.nn as nn +import numpy as np +from PIL import Image +import json +import re +import os +import time +import math +import importlib +import logging + +from comfy import model_management +import folder_paths +from nodes import MAX_RESOLUTION +from comfy.utils import common_upscale, ProgressBar, load_torch_file, save_torch_file +from comfy.comfy_types.node_typing import IO +from comfy_api.latest import io, ui +import comfy.latent_formats +import node_helpers +from io import BytesIO + +script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +folder_paths.add_model_folder_path("kjnodes_fonts", os.path.join(script_directory, "fonts")) + +class BOOLConstant: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "value": ("BOOLEAN", {"default": True}), + }, + } + RETURN_TYPES = ("BOOLEAN",) + RETURN_NAMES = ("value",) + FUNCTION = "get_value" + CATEGORY = "KJNodes/constants" + SEARCH_ALIASES = ["boolean", "value"] + + def get_value(self, value): + return (value,) + +class INTConstant: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "value": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff}), + }, + } + RETURN_TYPES = ("INT",) + RETURN_NAMES = ("value",) + FUNCTION = "get_value" + CATEGORY = "KJNodes/constants" + SEARCH_ALIASES = ["integer", "value"] + + def get_value(self, value): + return (value,) + +class FloatConstant: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "value": ("FLOAT", {"default": 0.0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 0.00001}), + }, + } + + RETURN_TYPES = ("FLOAT",) + RETURN_NAMES = ("value",) + FUNCTION = "get_value" + CATEGORY = "KJNodes/constants" + SEARCH_ALIASES = ["float", "value"] + + def get_value(self, value): + return (round(value, 6),) + +class StringConstant: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "string": ("STRING", {"default": '', "multiline": False}), + } + } + RETURN_TYPES = ("STRING",) + FUNCTION = "passtring" + CATEGORY = "KJNodes/constants" + SEARCH_ALIASES = ["text", "value"] + + def passtring(self, string): + return (string, ) + +class StringConstantMultiline: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "string": ("STRING", {"default": "", "multiline": True}), + "strip_newlines": ("BOOLEAN", {"default": True}), + } + } + RETURN_TYPES = ("STRING",) + FUNCTION = "stringify" + CATEGORY = "KJNodes/constants" + SEARCH_ALIASES = ["text", "value"] + + def stringify(self, string, strip_newlines): + new_string = string + if strip_newlines: + new_string = new_string.replace('\n', '').strip() + return (new_string,) + + + +class ScaleBatchPromptSchedule: + + RETURN_TYPES = ("STRING",) + FUNCTION = "scaleschedule" + CATEGORY = "KJNodes/misc" + DESCRIPTION = """ +Scales a batch schedule from Fizz' nodes BatchPromptSchedule +to a different frame count. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "input_str": ("STRING", {"forceInput": True,"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n"}), + "old_frame_count": ("INT", {"forceInput": True,"default": 1,"min": 1, "max": 4096, "step": 1}), + "new_frame_count": ("INT", {"forceInput": True,"default": 1,"min": 1, "max": 4096, "step": 1}), + + }, + } + + def scaleschedule(self, old_frame_count, input_str, new_frame_count): + pattern = r'"(\d+)"\s*:\s*"(.*?)"(?:,|\Z)' + frame_strings = dict(re.findall(pattern, input_str)) + + # Calculate the scaling factor + scaling_factor = (new_frame_count - 1) / (old_frame_count - 1) + + # Initialize a dictionary to store the new frame numbers and strings + new_frame_strings = {} + + # Iterate over the frame numbers and strings + for old_frame, string in frame_strings.items(): + # Calculate the new frame number + new_frame = int(round(int(old_frame) * scaling_factor)) + + # Store the new frame number and corresponding string + new_frame_strings[new_frame] = string + + # Format the output string + output_str = ', '.join([f'"{k}":"{v}"' for k, v in sorted(new_frame_strings.items())]) + return (output_str,) + + +class GetLatentsFromBatchIndexed: + + RETURN_TYPES = ("LATENT",) + FUNCTION = "indexedlatentsfrombatch" + CATEGORY = "KJNodes/latents" + DESCRIPTION = """ +Selects and returns the latents at the specified indices as an latent batch. +""" + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "latents": ("LATENT",), + "indexes": ("STRING", {"default": "0, 1, 2", "multiline": True}), + "latent_format": (["BCHW", "BTCHW", "BCTHW"], {"default": "BCHW"}), + }, + } + + def indexedlatentsfrombatch(self, latents, indexes, latent_format): + + samples = latents.copy() + latent_samples = samples["samples"] + + # Parse the indexes string into a list of integers + index_list = [int(index.strip()) for index in indexes.split(',')] + + # Convert list of indices to a PyTorch tensor + indices_tensor = torch.tensor(index_list, dtype=torch.long) + + # Select the latents at the specified indices + if latent_format == "BCHW": + chosen_latents = latent_samples[indices_tensor] + elif latent_format == "BTCHW": + chosen_latents = latent_samples[:, indices_tensor] + elif latent_format == "BCTHW": + chosen_latents = latent_samples[:, :, indices_tensor] + + samples["samples"] = chosen_latents + return (samples,) + + +class ConditioningMultiCombine: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 20, "step": 1}), + "operation": (["combine", "concat"], {"default": "combine"}), + "conditioning_1": ("CONDITIONING", ), + "conditioning_2": ("CONDITIONING", ), + }, + } + + RETURN_TYPES = ("CONDITIONING", "INT") + RETURN_NAMES = ("combined", "inputcount") + FUNCTION = "combine" + CATEGORY = "KJNodes/masking/conditioning" + DESCRIPTION = """ +Combines multiple conditioning nodes into one +""" + + def combine(self, inputcount, operation, **kwargs): + from nodes import ConditioningCombine + from nodes import ConditioningConcat + cond_combine_node = ConditioningCombine() + cond_concat_node = ConditioningConcat() + cond = kwargs["conditioning_1"] + for c in range(1, inputcount): + new_cond = kwargs[f"conditioning_{c + 1}"] + if operation == "combine": + cond = cond_combine_node.combine(cond, new_cond)[0] + elif operation == "concat": + cond = cond_concat_node.concat(cond, new_cond)[0] + return (cond, inputcount,) + +class AppendStringsToList: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "string1": ("STRING", {"default": '', "forceInput": True}), + "string2": ("STRING", {"default": '', "forceInput": True}), + } + } + RETURN_TYPES = ("STRING",) + FUNCTION = "joinstring" + CATEGORY = "KJNodes/text" + + def joinstring(self, string1, string2): + if not isinstance(string1, list): + string1 = [string1] + if not isinstance(string2, list): + string2 = [string2] + + joined_string = string1 + string2 + return (joined_string, ) + +class JoinStrings: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "delimiter": ("STRING", {"default": ' ', "multiline": False}), + }, + "optional": { + "string1": ("STRING", {"default": '', "forceInput": True}), + "string2": ("STRING", {"default": '', "forceInput": True}), + } + } + RETURN_TYPES = ("STRING",) + FUNCTION = "joinstring" + CATEGORY = "KJNodes/text" + + def joinstring(self, delimiter, string1="", string2=""): + joined_string = string1 + delimiter + string2 + return (joined_string, ) + +class JoinStringMulti: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}), + "string_1": ("STRING", {"default": '', "forceInput": True}), + "delimiter": ("STRING", {"default": ' ', "multiline": False}), + "return_list": ("BOOLEAN", {"default": False}), + }, + "optional": { + "string_2": ("STRING", {"default": '', "forceInput": True}), + } + } + + RETURN_TYPES = ("STRING",) + RETURN_NAMES = ("string",) + FUNCTION = "combine" + CATEGORY = "KJNodes/text" + DESCRIPTION = """ +Creates single string, or a list of strings, from +multiple input strings. +You can set how many inputs the node has, +with the **inputcount** and clicking update. +""" + + def combine(self, inputcount, delimiter, **kwargs): + string = kwargs["string_1"] + return_list = kwargs["return_list"] + strings = [string] # Initialize a list with the first string + for c in range(1, inputcount): + new_string = kwargs.get(f"string_{c + 1}", "") + if not new_string: + continue + if return_list: + strings.append(new_string) # Add new string to the list + else: + string = string + delimiter + new_string + if return_list: + return (strings,) # Return the list of strings + else: + return (string,) # Return the combined string + +class CondPassThrough: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + }, + "optional": { + "positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + }, + } + + RETURN_TYPES = ("CONDITIONING", "CONDITIONING",) + RETURN_NAMES = ("positive", "negative") + FUNCTION = "passthrough" + CATEGORY = "KJNodes/misc" + DESCRIPTION = """ + Simply passes through the positive and negative conditioning, + workaround for Set node not allowing bypassed inputs. +""" + + def passthrough(self, positive=None, negative=None): + return (positive, negative,) + +class ModelPassThrough: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + }, + "optional": { + "model": ("MODEL", ), + }, + } + + RETURN_TYPES = ("MODEL", ) + RETURN_NAMES = ("model",) + FUNCTION = "passthrough" + CATEGORY = "KJNodes/misc" + DESCRIPTION = """ + Simply passes through the model, + workaround for Set node not allowing bypassed inputs. +""" + + def passthrough(self, model=None): + return (model,) + +def append_helper(t, mask, c, set_area_to_bounds, strength): + n = [t[0], t[1].copy()] + _, h, w = mask.shape + n[1]['mask'] = mask + n[1]['set_area_to_bounds'] = set_area_to_bounds + n[1]['mask_strength'] = strength + c.append(n) + +class ConditioningSetMaskAndCombine: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "positive_1": ("CONDITIONING", ), + "negative_1": ("CONDITIONING", ), + "positive_2": ("CONDITIONING", ), + "negative_2": ("CONDITIONING", ), + "mask_1": ("MASK", ), + "mask_2": ("MASK", ), + "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "set_cond_area": (["default", "mask bounds"],), + } + } + + RETURN_TYPES = ("CONDITIONING","CONDITIONING",) + RETURN_NAMES = ("combined_positive", "combined_negative",) + FUNCTION = "append" + CATEGORY = "KJNodes/masking/conditioning" + DESCRIPTION = """ +Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes +""" + + def append(self, positive_1, negative_1, positive_2, negative_2, mask_1, mask_2, set_cond_area, mask_1_strength, mask_2_strength): + c = [] + c2 = [] + set_area_to_bounds = False + if set_cond_area != "default": + set_area_to_bounds = True + if len(mask_1.shape) < 3: + mask_1 = mask_1.unsqueeze(0) + if len(mask_2.shape) < 3: + mask_2 = mask_2.unsqueeze(0) + for t in positive_1: + append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength) + for t in positive_2: + append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength) + for t in negative_1: + append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength) + for t in negative_2: + append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength) + return (c, c2) + +class ConditioningSetMaskAndCombine3: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "positive_1": ("CONDITIONING", ), + "negative_1": ("CONDITIONING", ), + "positive_2": ("CONDITIONING", ), + "negative_2": ("CONDITIONING", ), + "positive_3": ("CONDITIONING", ), + "negative_3": ("CONDITIONING", ), + "mask_1": ("MASK", ), + "mask_2": ("MASK", ), + "mask_3": ("MASK", ), + "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_3_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "set_cond_area": (["default", "mask bounds"],), + } + } + + RETURN_TYPES = ("CONDITIONING","CONDITIONING",) + RETURN_NAMES = ("combined_positive", "combined_negative",) + FUNCTION = "append" + CATEGORY = "KJNodes/masking/conditioning" + DESCRIPTION = """ +Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes +""" + + def append(self, positive_1, negative_1, positive_2, positive_3, negative_2, negative_3, mask_1, mask_2, mask_3, set_cond_area, mask_1_strength, mask_2_strength, mask_3_strength): + c = [] + c2 = [] + set_area_to_bounds = False + if set_cond_area != "default": + set_area_to_bounds = True + if len(mask_1.shape) < 3: + mask_1 = mask_1.unsqueeze(0) + if len(mask_2.shape) < 3: + mask_2 = mask_2.unsqueeze(0) + if len(mask_3.shape) < 3: + mask_3 = mask_3.unsqueeze(0) + for t in positive_1: + append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength) + for t in positive_2: + append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength) + for t in positive_3: + append_helper(t, mask_3, c, set_area_to_bounds, mask_3_strength) + for t in negative_1: + append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength) + for t in negative_2: + append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength) + for t in negative_3: + append_helper(t, mask_3, c2, set_area_to_bounds, mask_3_strength) + return (c, c2) + +class ConditioningSetMaskAndCombine4: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "positive_1": ("CONDITIONING", ), + "negative_1": ("CONDITIONING", ), + "positive_2": ("CONDITIONING", ), + "negative_2": ("CONDITIONING", ), + "positive_3": ("CONDITIONING", ), + "negative_3": ("CONDITIONING", ), + "positive_4": ("CONDITIONING", ), + "negative_4": ("CONDITIONING", ), + "mask_1": ("MASK", ), + "mask_2": ("MASK", ), + "mask_3": ("MASK", ), + "mask_4": ("MASK", ), + "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_3_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_4_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "set_cond_area": (["default", "mask bounds"],), + } + } + + RETURN_TYPES = ("CONDITIONING","CONDITIONING",) + RETURN_NAMES = ("combined_positive", "combined_negative",) + FUNCTION = "append" + CATEGORY = "KJNodes/masking/conditioning" + DESCRIPTION = """ +Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes +""" + + def append(self, positive_1, negative_1, positive_2, positive_3, positive_4, negative_2, negative_3, negative_4, mask_1, mask_2, mask_3, mask_4, set_cond_area, mask_1_strength, mask_2_strength, mask_3_strength, mask_4_strength): + c = [] + c2 = [] + set_area_to_bounds = False + if set_cond_area != "default": + set_area_to_bounds = True + if len(mask_1.shape) < 3: + mask_1 = mask_1.unsqueeze(0) + if len(mask_2.shape) < 3: + mask_2 = mask_2.unsqueeze(0) + if len(mask_3.shape) < 3: + mask_3 = mask_3.unsqueeze(0) + if len(mask_4.shape) < 3: + mask_4 = mask_4.unsqueeze(0) + for t in positive_1: + append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength) + for t in positive_2: + append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength) + for t in positive_3: + append_helper(t, mask_3, c, set_area_to_bounds, mask_3_strength) + for t in positive_4: + append_helper(t, mask_4, c, set_area_to_bounds, mask_4_strength) + for t in negative_1: + append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength) + for t in negative_2: + append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength) + for t in negative_3: + append_helper(t, mask_3, c2, set_area_to_bounds, mask_3_strength) + for t in negative_4: + append_helper(t, mask_4, c2, set_area_to_bounds, mask_4_strength) + return (c, c2) + +class ConditioningSetMaskAndCombine5: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "positive_1": ("CONDITIONING", ), + "negative_1": ("CONDITIONING", ), + "positive_2": ("CONDITIONING", ), + "negative_2": ("CONDITIONING", ), + "positive_3": ("CONDITIONING", ), + "negative_3": ("CONDITIONING", ), + "positive_4": ("CONDITIONING", ), + "negative_4": ("CONDITIONING", ), + "positive_5": ("CONDITIONING", ), + "negative_5": ("CONDITIONING", ), + "mask_1": ("MASK", ), + "mask_2": ("MASK", ), + "mask_3": ("MASK", ), + "mask_4": ("MASK", ), + "mask_5": ("MASK", ), + "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_3_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_4_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "mask_5_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "set_cond_area": (["default", "mask bounds"],), + } + } + + RETURN_TYPES = ("CONDITIONING","CONDITIONING",) + RETURN_NAMES = ("combined_positive", "combined_negative",) + FUNCTION = "append" + CATEGORY = "KJNodes/masking/conditioning" + DESCRIPTION = """ +Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes +""" + + def append(self, positive_1, negative_1, positive_2, positive_3, positive_4, positive_5, negative_2, negative_3, negative_4, negative_5, mask_1, mask_2, mask_3, mask_4, mask_5, set_cond_area, mask_1_strength, mask_2_strength, mask_3_strength, mask_4_strength, mask_5_strength): + c = [] + c2 = [] + set_area_to_bounds = False + if set_cond_area != "default": + set_area_to_bounds = True + if len(mask_1.shape) < 3: + mask_1 = mask_1.unsqueeze(0) + if len(mask_2.shape) < 3: + mask_2 = mask_2.unsqueeze(0) + if len(mask_3.shape) < 3: + mask_3 = mask_3.unsqueeze(0) + if len(mask_4.shape) < 3: + mask_4 = mask_4.unsqueeze(0) + if len(mask_5.shape) < 3: + mask_5 = mask_5.unsqueeze(0) + for t in positive_1: + append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength) + for t in positive_2: + append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength) + for t in positive_3: + append_helper(t, mask_3, c, set_area_to_bounds, mask_3_strength) + for t in positive_4: + append_helper(t, mask_4, c, set_area_to_bounds, mask_4_strength) + for t in positive_5: + append_helper(t, mask_5, c, set_area_to_bounds, mask_5_strength) + for t in negative_1: + append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength) + for t in negative_2: + append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength) + for t in negative_3: + append_helper(t, mask_3, c2, set_area_to_bounds, mask_3_strength) + for t in negative_4: + append_helper(t, mask_4, c2, set_area_to_bounds, mask_4_strength) + for t in negative_5: + append_helper(t, mask_5, c2, set_area_to_bounds, mask_5_strength) + return (c, c2) + +class VRAM_Debug: + + @classmethod + + def INPUT_TYPES(s): + return { + "required": { + + "empty_cache": ("BOOLEAN", {"default": True}), + "gc_collect": ("BOOLEAN", {"default": True}), + "unload_all_models": ("BOOLEAN", {"default": False}), + }, + "optional": { + "any_input": (IO.ANY,), + "image_pass": ("IMAGE",), + "model_pass": ("MODEL",), + } + } + + RETURN_TYPES = (IO.ANY, "IMAGE","MODEL","INT", "INT",) + RETURN_NAMES = ("any_output", "image_pass", "model_pass", "freemem_before", "freemem_after") + FUNCTION = "VRAMdebug" + CATEGORY = "KJNodes/memory" + DESCRIPTION = """ +Returns the inputs unchanged, they are only used as triggers, +and performs comfy model management functions and garbage collection, +reports free VRAM before and after the operations. +""" + + def VRAMdebug(self, gc_collect, empty_cache, unload_all_models, image_pass=None, model_pass=None, any_input=None): + freemem_before = model_management.get_free_memory() + logging.info(f"VRAMdebug: free memory before: {freemem_before:,.0f}") + if empty_cache: + model_management.soft_empty_cache() + if unload_all_models: + model_management.unload_all_models() + if gc_collect: + import gc + gc.collect() + freemem_after = model_management.get_free_memory() + logging.info(f"VRAMdebug: free memory after: {freemem_after:,.0f}") + logging.info(f"VRAMdebug: freed memory: {freemem_after - freemem_before:,.0f}") + return {"ui": { + "text": [f"{freemem_before:,.0f}x{freemem_after:,.0f}"]}, + "result": (any_input, image_pass, model_pass, freemem_before, freemem_after) + } + +class SomethingToString: + @classmethod + + def INPUT_TYPES(s): + return { + "required": { + "input": (IO.ANY, ), + }, + "optional": { + "prefix": ("STRING", {"default": ""}), + "suffix": ("STRING", {"default": ""}), + } + } + RETURN_TYPES = ("STRING",) + FUNCTION = "stringify" + CATEGORY = "KJNodes/text" + DESCRIPTION = """ +Converts any type to a string. +""" + + def stringify(self, input, prefix="", suffix=""): + if isinstance(input, (int, float, bool, str)): + stringified = str(input) + elif isinstance(input, list): + stringified = ', '.join(str(item) for item in input) + else: + return input, + if prefix: # Check if prefix is not empty + stringified = prefix + stringified # Add the prefix + if suffix: # Check if suffix is not empty + stringified = stringified + suffix # Add the suffix + + return (stringified,) + +class Sleep: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "input": (IO.ANY, ), + "minutes": ("INT", {"default": 0, "min": 0, "max": 1439}), + "seconds": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 59.99, "step": 0.01}), + }, + } + RETURN_TYPES = (IO.ANY,) + FUNCTION = "sleepdelay" + CATEGORY = "KJNodes/misc" + DESCRIPTION = """ +Delays the execution for the input amount of time. +""" + + def sleepdelay(self, input, minutes, seconds): + total_seconds = minutes * 60 + seconds + time.sleep(total_seconds) + return input, + +class EmptyLatentImagePresets: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "dimensions": ( + [ + '512 x 512 (1:1)', + '768 x 512 (1.5:1)', + '960 x 512 (1.875:1)', + '1024 x 512 (2:1)', + '1024 x 576 (1.778:1)', + '1536 x 640 (2.4:1)', + '1344 x 768 (1.75:1)', + '1216 x 832 (1.46:1)', + '1152 x 896 (1.286:1)', + '1024 x 1024 (1:1)', + ], + { + "default": '512 x 512 (1:1)' + }), + + "invert": ("BOOLEAN", {"default": False}), + "batch_size": ("INT", { + "default": 1, + "min": 1, + "max": 4096 + }), + }, + } + + RETURN_TYPES = ("LATENT", "INT", "INT") + RETURN_NAMES = ("Latent", "Width", "Height") + FUNCTION = "generate" + CATEGORY = "KJNodes/latents" + + def generate(self, dimensions, invert, batch_size): + from nodes import EmptyLatentImage + result = [x.strip() for x in dimensions.split('x')] + + # Remove the aspect ratio part + result[0] = result[0].split('(')[0].strip() + result[1] = result[1].split('(')[0].strip() + + if invert: + width = int(result[1].split(' ')[0]) + height = int(result[0]) + else: + width = int(result[0]) + height = int(result[1].split(' ')[0]) + latent = EmptyLatentImage().generate(width, height, batch_size)[0] + + return (latent, int(width), int(height),) + +class EmptyLatentImageCustomPresets: + @classmethod + def INPUT_TYPES(cls): + try: + with open(os.path.join(script_directory, 'custom_dimensions.json')) as f: + dimensions_dict = json.load(f) + except FileNotFoundError: + dimensions_dict = [] + return { + "required": { + "dimensions": ( + [f"{d['label']} - {d['value']}" for d in dimensions_dict], + ), + + "invert": ("BOOLEAN", {"default": False}), + "batch_size": ("INT", { + "default": 1, + "min": 1, + "max": 4096 + }), + }, + } + + RETURN_TYPES = ("LATENT", "INT", "INT") + RETURN_NAMES = ("Latent", "Width", "Height") + FUNCTION = "generate" + CATEGORY = "KJNodes/latents" + DESCRIPTION = """ +Generates an empty latent image with the specified dimensions. +The choices are loaded from 'custom_dimensions.json' in the nodes folder. +""" + + def generate(self, dimensions, invert, batch_size): + from nodes import EmptyLatentImage + # Split the string into label and value + label, value = dimensions.split(' - ') + # Split the value into width and height + width, height = [x.strip() for x in value.split('x')] + + if invert: + width, height = height, width + + latent = EmptyLatentImage().generate(int(width), int(height), batch_size)[0] + + return (latent, int(width), int(height),) + +class WidgetToString: + @classmethod + def IS_CHANGED(cls,*,id,node_title,any_input,**kwargs): + if any_input is not None and (id != 0 or node_title != ""): + return float("NaN") + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "id": ("INT", {"default": 0, "min": 0, "max": 100000, "step": 1}), + "widget_name": ("STRING", {"multiline": False}), + "return_all": ("BOOLEAN", {"default": False}), + }, + "optional": { + "any_input": (IO.ANY, ), + "node_title": ("STRING", {"multiline": False}), + "allowed_float_decimals": ("INT", {"default": 2, "min": 0, "max": 10, "tooltip": "Number of decimal places to display for float values"}), + }, + "hidden": {"extra_pnginfo": "EXTRA_PNGINFO", + "prompt": "PROMPT", + "unique_id": "UNIQUE_ID",}, + } + + RETURN_TYPES = ("STRING", ) + FUNCTION = "get_widget_value" + CATEGORY = "KJNodes/text" + DESCRIPTION = """ +Selects a node and it's specified widget and outputs the value as a string. +If no node id or title is provided it will use the 'any_input' link and use that node. +To see node id's, enable "Node ID Badge Mode" in main settings. +Alternatively you can search with the node title. Node titles ONLY exist if they +are manually edited! +'widget_name' can be a comma separated list. +The 'any_input' is required for making sure the node you want the value from exists in the workflow. +""" + + def get_widget_value(self, id, widget_name, extra_pnginfo, prompt, unique_id, return_all=False, any_input=None, node_title="", allowed_float_decimals=2): + workflow = extra_pnginfo["workflow"] + #print(json.dumps(workflow, indent=4)) + results = [] + node_id = link_id = subgraph_prefix = None + link_to_node_map = {} + node_to_subgraph_map = {} # Track which subgraph each node belongs to + + # Parse unique_id - handle both "parent:id" format and simple int format + if isinstance(unique_id, str) and ":" in unique_id: + unique_id_parts = unique_id.split(":") + unique_id_int = int(unique_id_parts[-1]) # Use the last part as the node id + subgraph_prefix = ":".join(unique_id_parts[:-1]) # Store the parent prefix (e.g., "14") + else: + unique_id_int = int(unique_id) + + # Collect all nodes from main workflow and subgraphs + all_nodes = list(workflow.get("nodes", [])) + definitions = workflow.get("definitions", {}) + subgraphs = definitions.get("subgraphs", []) + + # Find which main workflow node references each subgraph + subgraph_id_to_parent = {} + for node in workflow.get("nodes", []): + node_type = node.get("type", "") + # Subgraph nodes have a UUID as their type + if "-" in node_type and len(node_type) == 36: # UUID format check + subgraph_id_to_parent[node_type] = node["id"] + + for subgraph in subgraphs: + subgraph_id = subgraph.get("id", "") + parent_node_id = subgraph_id_to_parent.get(subgraph_id) + + subgraph_nodes = subgraph.get("nodes", []) + for node in subgraph_nodes: + # Track which subgraph (parent node) this node belongs to + if parent_node_id is not None: + node_to_subgraph_map[node["id"]] = parent_node_id + all_nodes.extend(subgraph_nodes) + + # Also build link_to_node_map from subgraph links + subgraph_links = subgraph.get("links", []) + for link in subgraph_links: + # link format: [link_id, origin_id, origin_slot, target_id, target_slot, type] + if isinstance(link, dict): + link_to_node_map[link["id"]] = link["origin_id"] + elif isinstance(link, list) and len(link) >= 2: + link_to_node_map[link[0]] = link[1] + + for node in all_nodes: + if node_title: + if "title" in node: + if node["title"] == node_title: + node_id = node["id"] + break + else: + logging.warning("Node title not found.") + elif id != 0: + if node["id"] == id: + node_id = id + break + elif any_input is not None: + if node["type"] == "WidgetToString" and node["id"] == unique_id_int and not link_id: + for node_input in node["inputs"]: + if node_input["name"] == "any_input": + link_id = node_input["link"] + + # Construct a map of links to node IDs for future reference + node_outputs = node.get("outputs", None) + if not node_outputs: + continue + for output in node_outputs: + node_links = output.get("links", None) + if not node_links: + continue + for link in node_links: + link_to_node_map[link] = node["id"] + if link_id and link == link_id: + break + + if link_id: + node_id = link_to_node_map.get(link_id, None) + + if node_id is None: + raise ValueError("No matching node found for the given title or id") + + # Determine the correct prompt key + # First check if the target node is in a subgraph + target_subgraph_parent = node_to_subgraph_map.get(node_id) + + if target_subgraph_parent is not None: + # Target node is in a subgraph, use the parent node id as prefix + prompt_key = f"{target_subgraph_parent}:{node_id}" + elif subgraph_prefix is not None: + # We're in a subgraph, use our prefix + prompt_key = f"{subgraph_prefix}:{node_id}" + else: + prompt_key = str(node_id) + + # Try the prefixed key first, then fall back to just the node_id + if prompt_key not in prompt: + prompt_key = str(node_id) + + if prompt_key not in prompt: + raise KeyError(f"Node not found in prompt. Tried keys: '{target_subgraph_parent}:{node_id}' and '{node_id}'") + + values = prompt[prompt_key] + if "inputs" in values: + inputs = values["inputs"] + + # support comma-separated list and trim whitespace + widget_names = [] + if widget_name: + widget_names = [w.strip() for w in widget_name.split(",") if w.strip()] + + if return_all: + # Format items based on type + formatted_items = [] + for k, v in inputs.items(): + if isinstance(v, float): + item = f"{k}: {v:.{allowed_float_decimals}f}" + else: + item = f"{k}: {str(v)}" + formatted_items.append(item) + results.append(", ".join(formatted_items)) + + # Single widget name (trimmed) + elif len(widget_names) == 1: + name = widget_names[0] + if name in inputs: + v = inputs[name] + if isinstance(v, float): + v = f"{v:.{allowed_float_decimals}f}" + else: + v = str(v) + return (v, ) + else: + raise NameError(f"Widget not found: {node_id}.{name}") + + # Multiple widget names: return "name: value" pairs + elif len(widget_names) > 1: + formatted_items = [] + for name in widget_names: + if name not in inputs: + raise NameError(f"Widget not found: {node_id}.{name}") + v = inputs[name] + if isinstance(v, float): + v = f"{v:.{allowed_float_decimals}f}" + else: + v = str(v) + formatted_items.append(f"{name}: {v}") + return (", ".join(formatted_items), ) + + else: + # No valid widget name provided + raise NameError(f"Widget not found: {node_id}.{widget_name}") + + return (", ".join(results).strip(", "), ) + + +class DummyOut: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "any_input": (IO.ANY, ), + } + } + + RETURN_TYPES = (IO.ANY,) + FUNCTION = "dummy" + CATEGORY = "KJNodes/misc" + OUTPUT_NODE = True + DESCRIPTION = """ +Does nothing, used to trigger generic workflow output. +A way to get previews in the UI without saving anything to disk. +""" + + def dummy(self, any_input): + return (any_input,) + +class FlipSigmasAdjusted: + @classmethod + def INPUT_TYPES(s): + return {"required": + {"sigmas": ("SIGMAS", ), + "divide_by_last_sigma": ("BOOLEAN", {"default": False}), + "divide_by": ("FLOAT", {"default": 1,"min": 1, "max": 255, "step": 0.01}), + "offset_by": ("INT", {"default": 1,"min": -100, "max": 100, "step": 1}), + } + } + RETURN_TYPES = ("SIGMAS", "STRING",) + RETURN_NAMES = ("SIGMAS", "sigmas_string",) + CATEGORY = "KJNodes/noise" + FUNCTION = "get_sigmas_adjusted" + + def get_sigmas_adjusted(self, sigmas, divide_by_last_sigma, divide_by, offset_by): + + sigmas = sigmas.flip(0) + if sigmas[0] == 0: + sigmas[0] = 0.0001 + adjusted_sigmas = sigmas.clone() + #offset sigma + for i in range(1, len(sigmas)): + offset_index = i - offset_by + if 0 <= offset_index < len(sigmas): + adjusted_sigmas[i] = sigmas[offset_index] + else: + adjusted_sigmas[i] = 0.0001 + if adjusted_sigmas[0] == 0: + adjusted_sigmas[0] = 0.0001 + if divide_by_last_sigma: + adjusted_sigmas = adjusted_sigmas / adjusted_sigmas[-1] + + sigma_np_array = adjusted_sigmas.numpy() + array_string = np.array2string(sigma_np_array, precision=2, separator=', ', threshold=np.inf) + adjusted_sigmas = adjusted_sigmas / divide_by + return (adjusted_sigmas, array_string,) + +class CustomSigmas: + @classmethod + def INPUT_TYPES(s): + return {"required": + { + "sigmas_string" :("STRING", {"default": "14.615, 6.475, 3.861, 2.697, 1.886, 1.396, 0.963, 0.652, 0.399, 0.152, 0.029","multiline": True}), + "interpolate_to_steps": ("INT", {"default": 10,"min": 0, "max": 255, "step": 1}), + } + } + RETURN_TYPES = ("SIGMAS",) + RETURN_NAMES = ("SIGMAS",) + CATEGORY = "KJNodes/noise" + FUNCTION = "customsigmas" + DESCRIPTION = """ +Creates a sigmas tensor from a string of comma separated values. +Examples: + +Nvidia's optimized AYS 10 step schedule for SD 1.5: +14.615, 6.475, 3.861, 2.697, 1.886, 1.396, 0.963, 0.652, 0.399, 0.152, 0.029 +SDXL: +14.615, 6.315, 3.771, 2.181, 1.342, 0.862, 0.555, 0.380, 0.234, 0.113, 0.029 +SVD: +700.00, 54.5, 15.886, 7.977, 4.248, 1.789, 0.981, 0.403, 0.173, 0.034, 0.002 +""" + def customsigmas(self, sigmas_string, interpolate_to_steps): + sigmas_list = sigmas_string.split(', ') + sigmas_float_list = [float(sigma) for sigma in sigmas_list] + sigmas_tensor = torch.FloatTensor(sigmas_float_list) + if len(sigmas_tensor) != interpolate_to_steps + 1: + sigmas_tensor = self.loglinear_interp(sigmas_tensor, interpolate_to_steps + 1) + sigmas_tensor[-1] = 0 + return (sigmas_tensor.float(),) + + def loglinear_interp(self, t_steps, num_steps): + """ + Performs log-linear interpolation of a given array of decreasing numbers. + """ + t_steps_np = t_steps.numpy() + + xs = np.linspace(0, 1, len(t_steps_np)) + ys = np.log(t_steps_np[::-1]) + + new_xs = np.linspace(0, 1, num_steps) + new_ys = np.interp(new_xs, xs, ys) + + interped_ys = np.exp(new_ys)[::-1].copy() + interped_ys_tensor = torch.tensor(interped_ys) + return interped_ys_tensor + +class StringToFloatList: + @classmethod + def INPUT_TYPES(s): + return {"required": + { + "string" :("STRING", {"default": "1, 2, 3", "multiline": True}), + } + } + RETURN_TYPES = ("FLOAT",) + RETURN_NAMES = ("FLOAT",) + CATEGORY = "KJNodes/misc" + FUNCTION = "createlist" + + def createlist(self, string): + float_list = [float(x.strip()) for x in string.split(',')] + return (float_list,) + + +class InjectNoiseToLatent: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "latents":("LATENT",), + "strength": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 200.0, "step": 0.0001}), + "noise": ("LATENT",), + "normalize": ("BOOLEAN", {"default": False}), + "average": ("BOOLEAN", {"default": False}), + }, + "optional":{ + "mask": ("MASK", ), + "mix_randn_amount": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.001}), + "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), + } + } + + RETURN_TYPES = ("LATENT",) + FUNCTION = "injectnoise" + CATEGORY = "KJNodes/noise" + + def injectnoise(self, latents, strength, noise, normalize, average, mix_randn_amount=0, seed=None, mask=None): + samples = latents["samples"].clone().cpu() + noise = noise["samples"].clone().cpu() + if samples.shape != samples.shape: + raise ValueError("InjectNoiseToLatent: Latent and noise must have the same shape") + if average: + noised = (samples + noise) / 2 + else: + noised = samples + noise * strength + if normalize: + noised = noised / noised.std() + if mask is not None: + mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(noised.shape[2], noised.shape[3]), mode="bilinear") + mask = mask.expand((-1,noised.shape[1],-1,-1)) + if mask.shape[0] < noised.shape[0]: + mask = mask.repeat((noised.shape[0] -1) // mask.shape[0] + 1, 1, 1, 1)[:noised.shape[0]] + noised = mask * noised + (1-mask) * samples + if mix_randn_amount > 0: + if seed is not None: + generator = torch.manual_seed(seed) + rand_noise = torch.randn(noised.size(), dtype=noised.dtype, layout=noised.layout, generator=generator, device="cpu") + noised = noised + (mix_randn_amount * rand_noise) + + return ({"samples":noised},) + +class SoundReactive: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "sound_level": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 99999, "step": 0.01}), + "start_range_hz": ("INT", {"default": 150, "min": 0, "max": 9999, "step": 1}), + "end_range_hz": ("INT", {"default": 2000, "min": 0, "max": 9999, "step": 1}), + "multiplier": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 99999, "step": 0.01}), + "smoothing_factor": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), + "normalize": ("BOOLEAN", {"default": False}), + }, + } + + RETURN_TYPES = ("FLOAT","INT",) + RETURN_NAMES =("sound_level", "sound_level_int",) + FUNCTION = "react" + CATEGORY = "KJNodes/audio" + DESCRIPTION = """ +Reacts to the sound level of the input. +Uses your browsers sound input options and requires. +Meant to be used with realtime diffusion with autoqueue. +""" + + def react(self, sound_level, start_range_hz, end_range_hz, smoothing_factor, multiplier, normalize): + + sound_level *= multiplier + + if normalize: + sound_level /= 255 + + sound_level_int = int(sound_level) + return (sound_level, sound_level_int, ) + +class GenerateNoise: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), + "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), + "multiplier": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 4096, "step": 0.01}), + "constant_batch_noise": ("BOOLEAN", {"default": False}), + "normalize": ("BOOLEAN", {"default": False}), + }, + "optional": { + "model": ("MODEL", ), + "sigmas": ("SIGMAS", ), + "latent_channels": (['4', '16', ],), + "shape": (["BCHW", "BCTHW","BTCHW",],), + } + } + + RETURN_TYPES = ("LATENT",) + FUNCTION = "generatenoise" + CATEGORY = "KJNodes/noise" + DESCRIPTION = """ +Generates noise for injection or to be used as empty latents on samplers with add_noise off. +""" + + def generatenoise(self, batch_size, width, height, seed, multiplier, constant_batch_noise, normalize, sigmas=None, model=None, latent_channels=4, shape="BCHW"): + + generator = torch.manual_seed(seed) + if shape == "BCHW": + noise = torch.randn([batch_size, int(latent_channels), height // 8, width // 8], dtype=torch.float32, layout=torch.strided, generator=generator, device="cpu") + elif shape == "BCTHW": + noise = torch.randn([1, int(latent_channels), batch_size,height // 8, width // 8], dtype=torch.float32, layout=torch.strided, generator=generator, device="cpu") + elif shape == "BTCHW": + noise = torch.randn([1, batch_size, int(latent_channels), height // 8, width // 8], dtype=torch.float32, layout=torch.strided, generator=generator, device="cpu") + if sigmas is not None: + sigma = sigmas[0] - sigmas[-1] + sigma /= model.model.latent_format.scale_factor + noise *= sigma + + noise *=multiplier + + if normalize: + noise = noise / noise.std() + if constant_batch_noise: + noise = noise[0].repeat(batch_size, 1, 1, 1) + + + return ({"samples":noise}, ) + +def camera_embeddings(elevation, azimuth): + elevation = torch.as_tensor([elevation]) + azimuth = torch.as_tensor([azimuth]) + embeddings = torch.stack( + [ + torch.deg2rad( + (90 - elevation) - (90) + ), # Zero123 polar is 90-elevation + torch.sin(torch.deg2rad(azimuth)), + torch.cos(torch.deg2rad(azimuth)), + torch.deg2rad( + 90 - torch.full_like(elevation, 0) + ), + ], dim=-1).unsqueeze(1) + + return embeddings + +def interpolate_angle(start, end, fraction): + # Calculate the difference in angles and adjust for wraparound if necessary + diff = (end - start + 540) % 360 - 180 + # Apply fraction to the difference + interpolated = start + fraction * diff + # Normalize the result to be within the range of -180 to 180 + return (interpolated + 180) % 360 - 180 + + +class StableZero123_BatchSchedule: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_vision": ("CLIP_VISION",), + "init_image": ("IMAGE",), + "vae": ("VAE",), + "width": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],), + "azimuth_points_string": ("STRING", {"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n", "multiline": True}), + "elevation_points_string": ("STRING", {"default": "0:(0.0),\n7:(0.0),\n15:(0.0)\n", "multiline": True}), + }} + + RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") + RETURN_NAMES = ("positive", "negative", "latent") + FUNCTION = "encode" + CATEGORY = "KJNodes/experimental" + + def encode(self, clip_vision, init_image, vae, width, height, batch_size, azimuth_points_string, elevation_points_string, interpolation): + output = clip_vision.encode_image(init_image) + pooled = output.image_embeds.unsqueeze(0) + pixels = common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1) + encode_pixels = pixels[:,:,:,:3] + t = vae.encode(encode_pixels) + + def ease_in(t): + return t * t + def ease_out(t): + return 1 - (1 - t) * (1 - t) + def ease_in_out(t): + return 3 * t * t - 2 * t * t * t + + # Parse the azimuth input string into a list of tuples + azimuth_points = [] + azimuth_points_string = azimuth_points_string.rstrip(',\n') + for point_str in azimuth_points_string.split(','): + frame_str, azimuth_str = point_str.split(':') + frame = int(frame_str.strip()) + azimuth = float(azimuth_str.strip()[1:-1]) + azimuth_points.append((frame, azimuth)) + # Sort the points by frame number + azimuth_points.sort(key=lambda x: x[0]) + + # Parse the elevation input string into a list of tuples + elevation_points = [] + elevation_points_string = elevation_points_string.rstrip(',\n') + for point_str in elevation_points_string.split(','): + frame_str, elevation_str = point_str.split(':') + frame = int(frame_str.strip()) + elevation_val = float(elevation_str.strip()[1:-1]) + elevation_points.append((frame, elevation_val)) + # Sort the points by frame number + elevation_points.sort(key=lambda x: x[0]) + + # Index of the next point to interpolate towards + next_point = 1 + next_elevation_point = 1 + + positive_cond_out = [] + positive_pooled_out = [] + negative_cond_out = [] + negative_pooled_out = [] + + #azimuth interpolation + for i in range(batch_size): + # Find the interpolated azimuth for the current frame + while next_point < len(azimuth_points) and i >= azimuth_points[next_point][0]: + next_point += 1 + # If next_point is equal to the length of points, we've gone past the last point + if next_point == len(azimuth_points): + next_point -= 1 # Set next_point to the last index of points + prev_point = max(next_point - 1, 0) # Ensure prev_point is not less than 0 + + # Calculate fraction + if azimuth_points[next_point][0] != azimuth_points[prev_point][0]: # Prevent division by zero + fraction = (i - azimuth_points[prev_point][0]) / (azimuth_points[next_point][0] - azimuth_points[prev_point][0]) + if interpolation == "ease_in": + fraction = ease_in(fraction) + elif interpolation == "ease_out": + fraction = ease_out(fraction) + elif interpolation == "ease_in_out": + fraction = ease_in_out(fraction) + + # Use the new interpolate_angle function + interpolated_azimuth = interpolate_angle(azimuth_points[prev_point][1], azimuth_points[next_point][1], fraction) + else: + interpolated_azimuth = azimuth_points[prev_point][1] + # Interpolate the elevation + next_elevation_point = 1 + while next_elevation_point < len(elevation_points) and i >= elevation_points[next_elevation_point][0]: + next_elevation_point += 1 + if next_elevation_point == len(elevation_points): + next_elevation_point -= 1 + prev_elevation_point = max(next_elevation_point - 1, 0) + + if elevation_points[next_elevation_point][0] != elevation_points[prev_elevation_point][0]: + fraction = (i - elevation_points[prev_elevation_point][0]) / (elevation_points[next_elevation_point][0] - elevation_points[prev_elevation_point][0]) + if interpolation == "ease_in": + fraction = ease_in(fraction) + elif interpolation == "ease_out": + fraction = ease_out(fraction) + elif interpolation == "ease_in_out": + fraction = ease_in_out(fraction) + + interpolated_elevation = interpolate_angle(elevation_points[prev_elevation_point][1], elevation_points[next_elevation_point][1], fraction) + else: + interpolated_elevation = elevation_points[prev_elevation_point][1] + + cam_embeds = camera_embeddings(interpolated_elevation, interpolated_azimuth) + cond = torch.cat([pooled, cam_embeds.repeat((pooled.shape[0], 1, 1))], dim=-1) + + positive_pooled_out.append(t) + positive_cond_out.append(cond) + negative_pooled_out.append(torch.zeros_like(t)) + negative_cond_out.append(torch.zeros_like(pooled)) + + # Concatenate the conditions and pooled outputs + final_positive_cond = torch.cat(positive_cond_out, dim=0) + final_positive_pooled = torch.cat(positive_pooled_out, dim=0) + final_negative_cond = torch.cat(negative_cond_out, dim=0) + final_negative_pooled = torch.cat(negative_pooled_out, dim=0) + + # Structure the final output + final_positive = [[final_positive_cond, {"concat_latent_image": final_positive_pooled}]] + final_negative = [[final_negative_cond, {"concat_latent_image": final_negative_pooled}]] + + latent = torch.zeros([batch_size, 4, height // 8, width // 8]) + return (final_positive, final_negative, {"samples": latent}) + +def linear_interpolate(start, end, fraction): + return start + (end - start) * fraction + +class SV3D_BatchSchedule: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_vision": ("CLIP_VISION",), + "init_image": ("IMAGE",), + "vae": ("VAE",), + "width": ("INT", {"default": 576, "min": 16, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 576, "min": 16, "max": MAX_RESOLUTION, "step": 8}), + "batch_size": ("INT", {"default": 21, "min": 1, "max": 4096}), + "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],), + "azimuth_points_string": ("STRING", {"default": "0:(0.0),\n9:(180.0),\n20:(360.0)\n", "multiline": True}), + "elevation_points_string": ("STRING", {"default": "0:(0.0),\n9:(0.0),\n20:(0.0)\n", "multiline": True}), + }} + + RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") + RETURN_NAMES = ("positive", "negative", "latent") + FUNCTION = "encode" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = """ +Allow scheduling of the azimuth and elevation conditions for SV3D. +Note that SV3D is still a video model and the schedule needs to always go forward +https://huggingface.co/stabilityai/sv3d +""" + + def encode(self, clip_vision, init_image, vae, width, height, batch_size, azimuth_points_string, elevation_points_string, interpolation): + output = clip_vision.encode_image(init_image) + pooled = output.image_embeds.unsqueeze(0) + pixels = common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1) + encode_pixels = pixels[:,:,:,:3] + t = vae.encode(encode_pixels) + + def ease_in(t): + return t * t + def ease_out(t): + return 1 - (1 - t) * (1 - t) + def ease_in_out(t): + return 3 * t * t - 2 * t * t * t + + # Parse the azimuth input string into a list of tuples + azimuth_points = [] + azimuth_points_string = azimuth_points_string.rstrip(',\n') + for point_str in azimuth_points_string.split(','): + frame_str, azimuth_str = point_str.split(':') + frame = int(frame_str.strip()) + azimuth = float(azimuth_str.strip()[1:-1]) + azimuth_points.append((frame, azimuth)) + # Sort the points by frame number + azimuth_points.sort(key=lambda x: x[0]) + + # Parse the elevation input string into a list of tuples + elevation_points = [] + elevation_points_string = elevation_points_string.rstrip(',\n') + for point_str in elevation_points_string.split(','): + frame_str, elevation_str = point_str.split(':') + frame = int(frame_str.strip()) + elevation_val = float(elevation_str.strip()[1:-1]) + elevation_points.append((frame, elevation_val)) + # Sort the points by frame number + elevation_points.sort(key=lambda x: x[0]) + + # Index of the next point to interpolate towards + next_point = 1 + next_elevation_point = 1 + elevations = [] + azimuths = [] + # For azimuth interpolation + for i in range(batch_size): + # Find the interpolated azimuth for the current frame + while next_point < len(azimuth_points) and i >= azimuth_points[next_point][0]: + next_point += 1 + if next_point == len(azimuth_points): + next_point -= 1 + prev_point = max(next_point - 1, 0) + + if azimuth_points[next_point][0] != azimuth_points[prev_point][0]: + fraction = (i - azimuth_points[prev_point][0]) / (azimuth_points[next_point][0] - azimuth_points[prev_point][0]) + # Apply the ease function to the fraction + if interpolation == "ease_in": + fraction = ease_in(fraction) + elif interpolation == "ease_out": + fraction = ease_out(fraction) + elif interpolation == "ease_in_out": + fraction = ease_in_out(fraction) + + interpolated_azimuth = linear_interpolate(azimuth_points[prev_point][1], azimuth_points[next_point][1], fraction) + else: + interpolated_azimuth = azimuth_points[prev_point][1] + + # Interpolate the elevation + next_elevation_point = 1 + while next_elevation_point < len(elevation_points) and i >= elevation_points[next_elevation_point][0]: + next_elevation_point += 1 + if next_elevation_point == len(elevation_points): + next_elevation_point -= 1 + prev_elevation_point = max(next_elevation_point - 1, 0) + + if elevation_points[next_elevation_point][0] != elevation_points[prev_elevation_point][0]: + fraction = (i - elevation_points[prev_elevation_point][0]) / (elevation_points[next_elevation_point][0] - elevation_points[prev_elevation_point][0]) + # Apply the ease function to the fraction + if interpolation == "ease_in": + fraction = ease_in(fraction) + elif interpolation == "ease_out": + fraction = ease_out(fraction) + elif interpolation == "ease_in_out": + fraction = ease_in_out(fraction) + + interpolated_elevation = linear_interpolate(elevation_points[prev_elevation_point][1], elevation_points[next_elevation_point][1], fraction) + else: + interpolated_elevation = elevation_points[prev_elevation_point][1] + + azimuths.append(interpolated_azimuth) + elevations.append(interpolated_elevation) + + #print("azimuths", azimuths) + #print("elevations", elevations) + + # Structure the final output + final_positive = [[pooled, {"concat_latent_image": t, "elevation": elevations, "azimuth": azimuths}]] + final_negative = [[torch.zeros_like(pooled), {"concat_latent_image": torch.zeros_like(t),"elevation": elevations, "azimuth": azimuths}]] + + latent = torch.zeros([batch_size, 4, height // 8, width // 8]) + return (final_positive, final_negative, {"samples": latent}) + +class LoadResAdapterNormalization: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "resadapter_path": (folder_paths.get_filename_list("checkpoints"), ) + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "load_res_adapter" + CATEGORY = "KJNodes/experimental" + + def load_res_adapter(self, model, resadapter_path): + logging.info("ResAdapter: Checking ResAdapter path") + resadapter_full_path = folder_paths.get_full_path("checkpoints", resadapter_path) + if not os.path.exists(resadapter_full_path): + raise Exception("Invalid model path") + else: + logging.info("ResAdapter: Loading ResAdapter normalization weights") + prefix_to_remove = 'diffusion_model.' + model_clone = model.clone() + norm_state_dict = load_torch_file(resadapter_full_path) + new_values = {key[len(prefix_to_remove):]: value for key, value in norm_state_dict.items() if key.startswith(prefix_to_remove)} + logging.info("ResAdapter: Attempting to add patches with ResAdapter weights") + try: + for key in model.model.diffusion_model.state_dict().keys(): + if key in new_values: + original_tensor = model.model.diffusion_model.state_dict()[key] + new_tensor = new_values[key].to(model.model.diffusion_model.dtype) + if original_tensor.shape == new_tensor.shape: + model_clone.add_object_patch(f"diffusion_model.{key}.data", new_tensor) + else: + logging.warning("ResAdapter: No match for key: %s", key) + except: + raise Exception("Could not patch model, this way of patching was added to ComfyUI on March 3rd 2024, is your ComfyUI up to date?") + logging.info("ResAdapter: Added resnet normalization patches") + return (model_clone, ) + +class Superprompt: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "instruction_prompt": ("STRING", {"default": 'Expand the following prompt to add more detail', "multiline": True}), + "prompt": ("STRING", {"default": '', "multiline": True, "forceInput": True}), + "max_new_tokens": ("INT", {"default": 128, "min": 1, "max": 4096, "step": 1}), + } + } + + RETURN_TYPES = ("STRING",) + FUNCTION = "process" + CATEGORY = "KJNodes/text" + DESCRIPTION = """ +# SuperPrompt +A T5 model fine-tuned on the SuperPrompt dataset for +upsampling text prompts to more detailed descriptions. +Meant to be used as a pre-generation step for text-to-image +models that benefit from more detailed prompts. +https://huggingface.co/roborovski/superprompt-v1 +""" + + def process(self, instruction_prompt, prompt, max_new_tokens): + device = model_management.get_torch_device() + from transformers import T5Tokenizer, T5ForConditionalGeneration + + checkpoint_path = os.path.join(script_directory, "models","superprompt-v1") + if not os.path.exists(checkpoint_path): + logging.info(f"Downloading model to: {checkpoint_path}") + from huggingface_hub import snapshot_download + snapshot_download(repo_id="roborovski/superprompt-v1", + local_dir=checkpoint_path, + local_dir_use_symlinks=False) + tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-small", legacy=False) + + model = T5ForConditionalGeneration.from_pretrained(checkpoint_path, device_map=device) + model.to(device) + input_text = instruction_prompt + ": " + prompt + + input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to(device) + outputs = model.generate(input_ids, max_new_tokens=max_new_tokens) + out = (tokenizer.decode(outputs[0])) + out = out.replace('', '') + out = out.replace('', '') + + return (out, ) + + +class CameraPoseVisualizer: + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "pose_file_path": ("STRING", {"default": '', "multiline": False}), + "base_xval": ("FLOAT", {"default": 0.2,"min": 0, "max": 100, "step": 0.01}), + "zval": ("FLOAT", {"default": 0.3,"min": 0, "max": 100, "step": 0.01}), + "scale": ("FLOAT", {"default": 1.0,"min": 0.01, "max": 10.0, "step": 0.01}), + "use_exact_fx": ("BOOLEAN", {"default": False}), + "relative_c2w": ("BOOLEAN", {"default": True}), + "use_viewer": ("BOOLEAN", {"default": False}), + }, + "optional": { + "cameractrl_poses": ("CAMERACTRL_POSES", {"default": None}), + } + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "plot" + CATEGORY = "KJNodes/misc" + DESCRIPTION = """ +Visualizes the camera poses, from Animatediff-Evolved CameraCtrl Pose +or a .txt file with RealEstate camera intrinsics and coordinates, in a 3D plot. +""" + + def plot(self, pose_file_path, scale, base_xval, zval, use_exact_fx, relative_c2w, use_viewer, cameractrl_poses=None): + import matplotlib as mpl + import matplotlib.pyplot as plt + from torchvision.transforms import ToTensor + + x_min = -2.0 * scale + x_max = 2.0 * scale + y_min = -2.0 * scale + y_max = 2.0 * scale + z_min = -2.0 * scale + z_max = 2.0 * scale + plt.rcParams['text.color'] = '#999999' + self.fig = plt.figure(figsize=(18, 7)) + self.fig.patch.set_facecolor('#353535') + self.ax = self.fig.add_subplot(projection='3d') + self.ax.set_facecolor('#353535') # Set the background color here + self.ax.grid(color='#999999', linestyle='-', linewidth=0.5) + self.plotly_data = None # plotly data traces + self.ax.set_aspect("auto") + self.ax.set_xlim(x_min, x_max) + self.ax.set_ylim(y_min, y_max) + self.ax.set_zlim(z_min, z_max) + self.ax.set_xlabel('x', color='#999999') + self.ax.set_ylabel('y', color='#999999') + self.ax.set_zlabel('z', color='#999999') + for text in self.ax.get_xticklabels() + self.ax.get_yticklabels() + self.ax.get_zticklabels(): + text.set_color('#999999') + logging.info('initialize camera pose visualizer') + + if pose_file_path != "": + with open(pose_file_path, 'r') as f: + poses = f.readlines() + w2cs = [np.asarray([float(p) for p in pose.strip().split(' ')[7:]]).reshape(3, 4) for pose in poses[1:]] + fxs = [float(pose.strip().split(' ')[1]) for pose in poses[1:]] + #print(poses) + elif cameractrl_poses is not None: + poses = cameractrl_poses + w2cs = [np.array(pose[7:]).reshape(3, 4) for pose in cameractrl_poses] + fxs = [pose[1] for pose in cameractrl_poses] + else: + raise ValueError("Please provide either pose_file_path or cameractrl_poses") + + total_frames = len(w2cs) + transform_matrix = np.asarray([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]]).reshape(4, 4) + last_row = np.zeros((1, 4)) + last_row[0, -1] = 1.0 + + w2cs = [np.concatenate((w2c, last_row), axis=0) for w2c in w2cs] + c2ws = self.get_c2w(w2cs, transform_matrix, relative_c2w) + + for frame_idx, c2w in enumerate(c2ws): + self.extrinsic2pyramid(c2w, frame_idx / total_frames, hw_ratio=1/1, base_xval=base_xval, + zval=(fxs[frame_idx] if use_exact_fx else zval)) + + # Create the colorbar + cmap = mpl.cm.rainbow + norm = mpl.colors.Normalize(vmin=0, vmax=total_frames) + colorbar = self.fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), ax=self.ax, orientation='vertical') + + # Change the colorbar label + colorbar.set_label('Frame', color='#999999') # Change the label and its color + + # Change the tick colors + colorbar.ax.yaxis.set_tick_params(colors='#999999') # Change the tick color + + # Change the tick frequency + # Assuming you want to set the ticks at every 10th frame + ticks = np.arange(0, total_frames, 10) + colorbar.ax.yaxis.set_ticks(ticks) + + plt.title('') + plt.draw() + buf = BytesIO() + plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0) + buf.seek(0) + img = Image.open(buf) + tensor_img = ToTensor()(img) + buf.close() + tensor_img = tensor_img.permute(1, 2, 0).unsqueeze(0) + if use_viewer: + time.sleep(1) + plt.show() + return (tensor_img,) + + def extrinsic2pyramid(self, extrinsic, color_map='red', hw_ratio=1/1, base_xval=1, zval=3): + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d.art3d import Poly3DCollection + vertex_std = np.array([[0, 0, 0, 1], + [base_xval, -base_xval * hw_ratio, zval, 1], + [base_xval, base_xval * hw_ratio, zval, 1], + [-base_xval, base_xval * hw_ratio, zval, 1], + [-base_xval, -base_xval * hw_ratio, zval, 1]]) + vertex_transformed = vertex_std @ extrinsic.T + meshes = [[vertex_transformed[0, :-1], vertex_transformed[1][:-1], vertex_transformed[2, :-1]], + [vertex_transformed[0, :-1], vertex_transformed[2, :-1], vertex_transformed[3, :-1]], + [vertex_transformed[0, :-1], vertex_transformed[3, :-1], vertex_transformed[4, :-1]], + [vertex_transformed[0, :-1], vertex_transformed[4, :-1], vertex_transformed[1, :-1]], + [vertex_transformed[1, :-1], vertex_transformed[2, :-1], vertex_transformed[3, :-1], vertex_transformed[4, :-1]]] + + color = color_map if isinstance(color_map, str) else plt.cm.rainbow(color_map) + + self.ax.add_collection3d( + Poly3DCollection(meshes, facecolors=color, linewidths=0.3, edgecolors=color, alpha=0.25)) + + def customize_legend(self, list_label): + from matplotlib.patches import Patch + import matplotlib.pyplot as plt + list_handle = [] + for idx, label in enumerate(list_label): + color = plt.cm.rainbow(idx / len(list_label)) + patch = Patch(color=color, label=label) + list_handle.append(patch) + plt.legend(loc='right', bbox_to_anchor=(1.8, 0.5), handles=list_handle) + + def get_c2w(self, w2cs, transform_matrix, relative_c2w): + if relative_c2w: + target_cam_c2w = np.array([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]) + abs2rel = target_cam_c2w @ w2cs[0] + ret_poses = [target_cam_c2w, ] + [abs2rel @ np.linalg.inv(w2c) for w2c in w2cs[1:]] + else: + ret_poses = [np.linalg.inv(w2c) for w2c in w2cs] + ret_poses = [transform_matrix @ x for x in ret_poses] + return np.array(ret_poses, dtype=np.float32) + + + +class CheckpointPerturbWeights: + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "joint_blocks": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 10.0, "step": 0.001}), + "final_layer": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 10.0, "step": 0.001}), + "rest_of_the_blocks": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 10.0, "step": 0.001}), + "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), + } + } + RETURN_TYPES = ("MODEL",) + FUNCTION = "mod" + OUTPUT_NODE = True + + CATEGORY = "KJNodes/experimental" + + def mod(self, seed, model, joint_blocks, final_layer, rest_of_the_blocks): + import copy + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + device = model_management.get_torch_device() + model_copy = copy.deepcopy(model) + model_copy.model.to(device) + keys = model_copy.model.diffusion_model.state_dict().keys() + + dict = {} + for key in keys: + dict[key] = model_copy.model.diffusion_model.state_dict()[key] + + pbar = ProgressBar(len(keys)) + for k in keys: + v = dict[k] + logging.info(f'{k}: {v.std()}') + if k.startswith('joint_blocks'): + multiplier = joint_blocks + elif k.startswith('final_layer'): + multiplier = final_layer + else: + multiplier = rest_of_the_blocks + dict[k] += torch.normal(torch.zeros_like(v) * v.mean(), torch.ones_like(v) * v.std() * multiplier).to(device) + pbar.update(1) + model_copy.model.diffusion_model.load_state_dict(dict) + return model_copy, + +class DifferentialDiffusionAdvanced(): + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL", ), + "samples": ("LATENT",), + "mask": ("MASK",), + "multiplier": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.001}), + }} + RETURN_TYPES = ("MODEL", "LATENT") + FUNCTION = "apply" + CATEGORY = "_for_testing" + INIT = False + + def apply(self, model, samples, mask, multiplier): + self.multiplier = multiplier + model = model.clone() + model.set_model_denoise_mask_function(self.forward) + s = samples.copy() + s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])) + return (model, s) + + def forward(self, sigma: torch.Tensor, denoise_mask: torch.Tensor, extra_options: dict): + model = extra_options["model"] + step_sigmas = extra_options["sigmas"] + sigma_to = model.inner_model.model_sampling.sigma_min + if step_sigmas[-1] > sigma_to: + sigma_to = step_sigmas[-1] + sigma_from = step_sigmas[0] + + ts_from = model.inner_model.model_sampling.timestep(sigma_from) + ts_to = model.inner_model.model_sampling.timestep(sigma_to) + current_ts = model.inner_model.model_sampling.timestep(sigma[0]) + + threshold = (current_ts - ts_to) / (ts_from - ts_to) / self.multiplier + + return (denoise_mask >= threshold).to(denoise_mask.dtype) + +class FluxBlockLoraSelect: + def __init__(self): + self.loaded_lora = None + + @classmethod + def INPUT_TYPES(s): + arg_dict = {} + argument = ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.01}) + + for i in range(19): + arg_dict["double_blocks.{}.".format(i)] = argument + + for i in range(38): + arg_dict["single_blocks.{}.".format(i)] = argument + + return {"required": arg_dict} + + RETURN_TYPES = ("SELECTEDDITBLOCKS", ) + RETURN_NAMES = ("blocks", ) + OUTPUT_TOOLTIPS = ("The modified diffusion model.",) + FUNCTION = "load_lora" + + CATEGORY = "KJNodes/experimental" + DESCRIPTION = "Select individual block alpha values, value of 0 removes the block altogether" + + def load_lora(self, **kwargs): + return (kwargs,) + +class HunyuanVideoBlockLoraSelect: + @classmethod + def INPUT_TYPES(s): + arg_dict = {} + argument = ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.01}) + + for i in range(20): + arg_dict["double_blocks.{}.".format(i)] = argument + + for i in range(40): + arg_dict["single_blocks.{}.".format(i)] = argument + + return {"required": arg_dict} + + RETURN_TYPES = ("SELECTEDDITBLOCKS", ) + RETURN_NAMES = ("blocks", ) + OUTPUT_TOOLTIPS = ("The modified diffusion model.",) + FUNCTION = "load_lora" + + CATEGORY = "KJNodes/hunyuanvideo" + DESCRIPTION = "Select individual block alpha values, value of 0 removes the block altogether" + + def load_lora(self, **kwargs): + return (kwargs,) + +class Wan21BlockLoraSelect: + @classmethod + def INPUT_TYPES(s): + arg_dict = {} + argument = ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.01}) + + for i in range(40): + arg_dict["blocks.{}.".format(i)] = argument + + return {"required": arg_dict} + + RETURN_TYPES = ("SELECTEDDITBLOCKS", ) + RETURN_NAMES = ("blocks", ) + OUTPUT_TOOLTIPS = ("The modified diffusion model.",) + FUNCTION = "load_lora" + + CATEGORY = "KJNodes/wan" + DESCRIPTION = "Select individual block alpha values, value of 0 removes the block altogether" + + def load_lora(self, **kwargs): + return (kwargs,) + +class LTX2BlockLoraSelect: + @classmethod + def INPUT_TYPES(s): + arg_dict = {} + argument = ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.01}) + + for i in range(48): + arg_dict["blocks.{}.".format(i)] = argument + + return {"required": arg_dict} + + RETURN_TYPES = ("SELECTEDDITBLOCKS", ) + RETURN_NAMES = ("blocks", ) + OUTPUT_TOOLTIPS = ("The modified diffusion model.",) + FUNCTION = "load_lora" + + CATEGORY = "KJNodes/ltxv" + DESCRIPTION = "Select individual block alpha values, value of 0 removes the block altogether" + + def load_lora(self, **kwargs): + return (kwargs,) + + +class DiTBlockLoraLoader: + def __init__(self): + self.loaded_lora = None + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL", {"tooltip": "The diffusion model the LoRA will be applied to."}), + "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the diffusion model. This value can be negative."}), + + }, + "optional": { + "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}), + "opt_lora_path": ("STRING", {"forceInput": True, "tooltip": "Absolute path of the LoRA."}), + "blocks": ("SELECTEDDITBLOCKS",), + } + } + + RETURN_TYPES = ("MODEL", "STRING", ) + RETURN_NAMES = ("model", "rank", ) + OUTPUT_TOOLTIPS = ("The modified diffusion model.", "possible rank of the LoRA.") + FUNCTION = "load_lora" + CATEGORY = "KJNodes/lora" + + def load_lora(self, model, strength_model, lora_name=None, opt_lora_path=None, blocks=None): + + import comfy.lora + + if opt_lora_path: + lora_path = opt_lora_path + else: + lora_path = folder_paths.get_full_path("loras", lora_name) + + lora = None + if self.loaded_lora is not None: + if self.loaded_lora[0] == lora_path: + lora = self.loaded_lora[1] + else: + self.loaded_lora = None + + if lora is None: + lora = load_torch_file(lora_path, safe_load=True) + self.loaded_lora = (lora_path, lora) + + # Find the first key that ends with "weight" + rank = "unknown" + weight_key = next((key for key in lora.keys() if key.endswith('weight')), None) + # Print the shape of the value corresponding to the key + if weight_key: + logging.info(f"Shape of the first 'weight' key ({weight_key}): {lora[weight_key].shape}") + rank = str(lora[weight_key].shape[0]) + else: + logging.warning("No key ending with 'weight' found.") + rank = "Couldn't find rank" + self.loaded_lora = (lora_path, lora) + + key_map = {} + if model is not None: + key_map = comfy.lora.model_lora_keys_unet(model.model, key_map) + + loaded = comfy.lora.load_lora(lora, key_map) + + if blocks is not None: + keys_to_delete = [] + + for block in blocks: + for key in list(loaded.keys()): + match = False + if isinstance(key, str) and block in key: + match = True + elif isinstance(key, tuple): + for k in key: + if block in k: + match = True + break + + if match: + ratio = blocks[block] + if ratio == 0: + keys_to_delete.append(key) + else: + # Only modify LoRA adapters, skip diff tuples + value = loaded[key] + if hasattr(value, 'weights'): + logging.info(f"Modifying LoRA adapter for key: {key}") + weights_list = list(value.weights) + weights_list[2] = ratio + loaded[key].weights = tuple(weights_list) + else: + logging.info(f"Skipping non-LoRA entry for key: {key}") + + for key in keys_to_delete: + del loaded[key] + + logging.info("loading lora keys:") + for key, value in loaded.items(): + if hasattr(value, 'weights'): + logging.info(f"Key: {key}, Alpha: {value.weights[2]}") + else: + logging.info(f"Key: {key}, Type: {type(value)}") + + if model is not None: + new_modelpatcher = model.clone() + k = new_modelpatcher.add_patches(loaded, strength_model) + + k = set(k) + for x in loaded: + if (x not in k): + logging.warning(f"NOT LOADED {x}") + + return (new_modelpatcher, rank) + +class CustomControlNetWeightsFluxFromList: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "list_of_floats": ("FLOAT", {"forceInput": True}, ), + }, + "optional": { + "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ), + "cn_extras": ("CN_WEIGHTS_EXTRAS",), + "autosize": ("ACNAUTOSIZE", {"padding": 0}), + } + } + + RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",) + RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT") + FUNCTION = "load_weights" + DESCRIPTION = "Creates controlnet weights from a list of floats for Advanced-ControlNet" + + CATEGORY = "KJNodes/controlnet" + + def load_weights(self, list_of_floats: list[float], + uncond_multiplier: float=1.0, cn_extras: dict[str]={}): + + adv_control = importlib.import_module("ComfyUI-Advanced-ControlNet.adv_control") + ControlWeights = adv_control.utils.ControlWeights + TimestepKeyframeGroup = adv_control.utils.TimestepKeyframeGroup + TimestepKeyframe = adv_control.utils.TimestepKeyframe + + weights = ControlWeights.controlnet(weights_input=list_of_floats, uncond_multiplier=uncond_multiplier, extras=cn_extras) + logging.info(weights.weights_input) + return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights))) + +SHAKKERLABS_UNION_CONTROLNET_TYPES = { + "canny": 0, + "tile": 1, + "depth": 2, + "blur": 3, + "pose": 4, + "gray": 5, + "low quality": 6, +} + +class SetShakkerLabsUnionControlNetType: + @classmethod + def INPUT_TYPES(s): + return {"required": {"control_net": ("CONTROL_NET", ), + "type": (["auto"] + list(SHAKKERLABS_UNION_CONTROLNET_TYPES.keys()),) + }} + + CATEGORY = "conditioning/controlnet" + RETURN_TYPES = ("CONTROL_NET",) + + FUNCTION = "set_controlnet_type" + + def set_controlnet_type(self, control_net, type): + control_net = control_net.copy() + type_number = SHAKKERLABS_UNION_CONTROLNET_TYPES.get(type, -1) + if type_number >= 0: + control_net.set_extra_arg("control_type", [type_number]) + else: + control_net.set_extra_arg("control_type", []) + + return (control_net,) + +class ModelSaveKJ: + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + + @classmethod + def INPUT_TYPES(s): + return {"required": { "model": ("MODEL",), + "filename_prefix": ("STRING", {"default": "diffusion_models/ComfyUI"}), + "model_key_prefix": ("STRING", {"default": "model.diffusion_model."}), + }, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},} + RETURN_TYPES = () + FUNCTION = "save" + OUTPUT_NODE = True + + CATEGORY = "advanced/model_merging" + + def save(self, model, filename_prefix, model_key_prefix, prompt=None, extra_pnginfo=None): + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir) + + output_checkpoint = f"{filename}_{counter:05}_.safetensors" + output_checkpoint = os.path.join(full_output_folder, output_checkpoint) + + load_models = [model] + + model_management.load_models_gpu(load_models, force_patch_weights=True) + default_prefix = "model.diffusion_model." + + sd = model.state_dict_for_saving(None, None, None) + + new_sd = {} + for k in sd: + if k.startswith(default_prefix): + new_key = model_key_prefix + k[len(default_prefix):] + else: + new_key = k # In case the key doesn't start with the default prefix, keep it unchanged + t = sd[k] + if not t.is_contiguous(): + t = t.contiguous() + new_sd[new_key] = t + logging.info(f"full_output_folder: {full_output_folder}") + if not os.path.exists(full_output_folder): + os.makedirs(full_output_folder) + save_torch_file(new_sd, os.path.join(full_output_folder, output_checkpoint)) + return {} + +class StyleModelApplyAdvanced: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "style_model": ("STYLE_MODEL", ), + "clip_vision_output": ("CLIP_VISION_OUTPUT", ), + "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.001}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_stylemodel" + CATEGORY = "KJNodes/experimental" + DESCRIPTION = "StyleModelApply but with strength parameter" + + def apply_stylemodel(self, clip_vision_output, style_model, conditioning, strength=1.0): + cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0) + cond = strength * cond + c = [] + for t in conditioning: + n = [torch.cat((t[0], cond), dim=1), t[1].copy()] + c.append(n) + return (c, ) + +class AudioConcatenate: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "audio1": ("AUDIO",), + "audio2": ("AUDIO",), + "direction": ( + [ 'right', + 'left', + ], + { + "default": 'right' + }), + }} + + RETURN_TYPES = ("AUDIO",) + FUNCTION = "concanate" + CATEGORY = "KJNodes/audio" + DESCRIPTION = """ +Concatenates the audio1 to audio2 in the specified direction. +""" + + def concanate(self, audio1, audio2, direction): + sample_rate_1 = audio1["sample_rate"] + sample_rate_2 = audio2["sample_rate"] + if sample_rate_1 != sample_rate_2: + raise Exception("Sample rates of the two audios do not match") + + waveform_1 = audio1["waveform"] + waveform_2 = audio2["waveform"] + + # Concatenate based on the specified direction + if direction == 'right': + concatenated_audio = torch.cat((waveform_1, waveform_2), dim=2) # Concatenate along width + elif direction == 'left': + concatenated_audio= torch.cat((waveform_2, waveform_1), dim=2) # Concatenate along width + return ({"waveform": concatenated_audio, "sample_rate": sample_rate_1},) + +class LeapfusionHunyuanI2V: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "latent": ("LATENT",), + "index": ("INT", {"default": 0, "min": -1, "max": 1000, "step": 1,"tooltip": "The index of the latent to be replaced. 0 for first frame and -1 for last"}), + "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The start percentage of steps to apply"}), + "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The end percentage of steps to apply"}), + "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.001}), + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + + CATEGORY = "KJNodes/hunyuanvideo" + + def patch(self, model, latent, index, strength, start_percent, end_percent): + + def outer_wrapper(samples, index, start_percent, end_percent): + def unet_wrapper(apply_model, args): + steps = args["c"]["transformer_options"]["sample_sigmas"] + inp, timestep, c = args["input"], args["timestep"], args["c"] + matched_step_index = (steps == timestep).nonzero() + if len(matched_step_index) > 0: + current_step_index = matched_step_index.item() + else: + for i in range(len(steps) - 1): + # walk from beginning of steps until crossing the timestep + if (steps[i] - timestep[0]) * (steps[i + 1] - timestep[0]) <= 0: + current_step_index = i + break + else: + current_step_index = 0 + current_percent = current_step_index / (len(steps) - 1) + if samples is not None: + if start_percent <= current_percent <= end_percent: + inp[:, :, [index], :, :] = samples[:, :, [0], :, :].to(inp) + else: + inp[:, :, [index], :, :] = torch.zeros(1) + return apply_model(inp, timestep, **c) + return unet_wrapper + + samples = latent["samples"] * 0.476986 * strength + m = model.clone() + m.set_model_unet_function_wrapper(outer_wrapper(samples, index, start_percent, end_percent)) + + return (m,) + +class ImageNoiseAugmentation: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "noise_aug_strength": ("FLOAT", {"default": None, "min": 0.0, "max": 100.0, "step": 0.001}), + "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}), + } + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "add_noise" + CATEGORY = "KJNodes/image" + DESCRIPTION = """ + Add noise to an image. + """ + + def add_noise(self, image, noise_aug_strength, seed): + torch.manual_seed(seed) + sigma = torch.ones((image.shape[0],)).to(image.device, image.dtype) * noise_aug_strength + image_noise = torch.randn_like(image) * sigma[:, None, None, None] + image_noise = torch.where(image==-1, torch.zeros_like(image), image_noise) + image_out = image + image_noise + return image_out, + +class VAELoaderKJ: + video_taes = ["taehv", "lighttaew2_2", "lighttaew2_1", "lighttaehy1_5"] + image_taes = ["taesd", "taesdxl", "taesd3", "taef1"] + @staticmethod + def vae_list(s): + vaes = folder_paths.get_filename_list("vae") + approx_vaes = folder_paths.get_filename_list("vae_approx") + sdxl_taesd_enc = False + sdxl_taesd_dec = False + sd1_taesd_enc = False + sd1_taesd_dec = False + sd3_taesd_enc = False + sd3_taesd_dec = False + f1_taesd_enc = False + f1_taesd_dec = False + + for v in approx_vaes: + if v.startswith("taesd_decoder."): + sd1_taesd_dec = True + elif v.startswith("taesd_encoder."): + sd1_taesd_enc = True + elif v.startswith("taesdxl_decoder."): + sdxl_taesd_dec = True + elif v.startswith("taesdxl_encoder."): + sdxl_taesd_enc = True + elif v.startswith("taesd3_decoder."): + sd3_taesd_dec = True + elif v.startswith("taesd3_encoder."): + sd3_taesd_enc = True + elif v.startswith("taef1_encoder."): + f1_taesd_dec = True + elif v.startswith("taef1_decoder."): + f1_taesd_enc = True + else: + for tae in s.video_taes: + if v.startswith(tae): + vaes.append(v) + + if sd1_taesd_dec and sd1_taesd_enc: + vaes.append("taesd") + if sdxl_taesd_dec and sdxl_taesd_enc: + vaes.append("taesdxl") + if sd3_taesd_dec and sd3_taesd_enc: + vaes.append("taesd3") + if f1_taesd_dec and f1_taesd_enc: + vaes.append("taef1") + vaes.append("pixel_space") + return vaes + + @staticmethod + def load_taesd(name): + sd = {} + approx_vaes = folder_paths.get_filename_list("vae_approx") + + encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes)) + decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes)) + + enc = load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", encoder)) + for k in enc: + sd["taesd_encoder.{}".format(k)] = enc[k] + + dec = load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", decoder)) + for k in dec: + sd["taesd_decoder.{}".format(k)] = dec[k] + + if name == "taesd": + sd["vae_scale"] = torch.tensor(0.18215) + sd["vae_shift"] = torch.tensor(0.0) + elif name == "taesdxl": + sd["vae_scale"] = torch.tensor(0.13025) + sd["vae_shift"] = torch.tensor(0.0) + elif name == "taesd3": + sd["vae_scale"] = torch.tensor(1.5305) + sd["vae_shift"] = torch.tensor(0.0609) + elif name == "taef1": + sd["vae_scale"] = torch.tensor(0.3611) + sd["vae_shift"] = torch.tensor(0.1159) + return sd + + @classmethod + def INPUT_TYPES(s): + return { + "required": { "vae_name": (s.vae_list(s), ), + "device": (["main_device", "cpu"],), + "weight_dtype": (["bf16", "fp16", "fp32" ],), + } + } + + RETURN_TYPES = ("VAE",) + FUNCTION = "load_vae" + CATEGORY = "KJNodes/vae" + + def load_vae(self, vae_name, device, weight_dtype): + from comfy.sd import VAE + metadata = None + dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[weight_dtype] + if device == "main_device": + device = model_management.get_torch_device() + elif device == "cpu": + device = torch.device("cpu") + + if vae_name == "pixel_space": + sd = {} + sd["pixel_space_vae"] = torch.tensor(1.0) + elif vae_name in self.image_taes: + sd = self.load_taesd(vae_name) + else: + if os.path.splitext(vae_name)[0] in self.video_taes: + vae_path = folder_paths.get_full_path_or_raise("vae_approx", vae_name) + else: + vae_path = folder_paths.get_full_path_or_raise("vae", vae_name) + sd, metadata = load_torch_file(vae_path, return_metadata=True) + + if "vocoder.conv_post.weight" in sd or "vocoder.vocoder.conv_post.weight" in sd: + from comfy.ldm.lightricks.vae.audio_vae import AudioVAE + vae = AudioVAE(sd, metadata) + else: + vae = VAE(sd=sd, device=device, dtype=dtype, metadata=metadata) + vae.throw_exception_if_invalid() + return (vae,) + +from comfy.samplers import sampling_function, CFGGuider +class Guider_ScheduledCFG(CFGGuider): + + def set_cfg(self, cfg, start_percent, end_percent): + self.cfg = cfg + self.start_percent = start_percent + self.end_percent = end_percent + + def predict_noise(self, x, timestep, model_options={}, seed=None): + steps = model_options["transformer_options"]["sample_sigmas"] + if isinstance(timestep, torch.Tensor): + timestep_value = timestep.reshape(-1)[0].to(steps) + else: + timestep_value = torch.tensor(timestep, device=steps.device, dtype=steps.dtype) + matched_step_index = torch.isclose(steps, timestep_value).nonzero() + assert not (isinstance(self.cfg, list) and len(self.cfg) != (len(steps) - 1)), "cfg list length must match step count" + if len(matched_step_index) > 0: + current_step_index = matched_step_index.item() + else: + for i in range(len(steps) - 1): + # walk from beginning of steps until crossing the timestep + if (steps[i] - timestep_value) * (steps[i + 1] - timestep_value) <= 0: + current_step_index = i + break + else: + current_step_index = 0 + current_percent = current_step_index / (len(steps) - 1) + + if self.start_percent <= current_percent <= self.end_percent: + if isinstance(self.cfg, list): + cfg = self.cfg[current_step_index] + else: + cfg = self.cfg + uncond = self.conds.get("negative", None) + else: + uncond = None + cfg = 1.0 + + return sampling_function(self.inner_model, x, timestep, uncond, self.conds.get("positive", None), cfg, model_options=model_options, seed=seed) + +class ScheduledCFGGuidance: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "cfg": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 100.0, "step": 0.01}), + "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step":0.01}), + "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step":0.01}), + }, + } + RETURN_TYPES = ("GUIDER",) + FUNCTION = "get_guider" + CATEGORY = "KJNodes/experimental" + DESCRiPTION = """ +CFG Guider that allows for scheduled CFG changes over steps, the steps outside the range will use CFG 1.0 thus being processed faster. +cfg input can be a list of floats matching step count, or a single float for all steps. +""" + + def get_guider(self, model, cfg, positive, negative, start_percent, end_percent): + guider = Guider_ScheduledCFG(model) + guider.set_conds(positive, negative) + guider.set_cfg(cfg, start_percent, end_percent) + return (guider, ) + + +class ApplyRifleXRoPE_WanVideo: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "latent": ("LATENT", {"tooltip": "Only used to get the latent count"}), + "k": ("INT", {"default": 6, "min": 1, "max": 100, "step": 1, "tooltip": "Index of intrinsic frequency"}), + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + CATEGORY = "KJNodes/wan" + EXPERIMENTAL = True + DESCRIPTION = "Extends the potential frame count of HunyuanVideo using this method: https://github.com/thu-ml/RIFLEx" + + def patch(self, model, latent, k): + model_class = model.model.diffusion_model + + model_clone = model.clone() + num_frames = latent["samples"].shape[2] + d = model_class.dim // model_class.num_heads + + rope_embedder = EmbedND_RifleX( + d, + 10000.0, + [d - 4 * (d // 6), 2 * (d // 6), 2 * (d // 6)], + num_frames, + k + ) + + model_clone.add_object_patch(f"diffusion_model.rope_embedder", rope_embedder) + + return (model_clone, ) + +class ApplyRifleXRoPE_HunuyanVideo: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "latent": ("LATENT", {"tooltip": "Only used to get the latent count"}), + "k": ("INT", {"default": 4, "min": 1, "max": 100, "step": 1, "tooltip": "Index of intrinsic frequency"}), + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + CATEGORY = "KJNodes/hunyuanvideo" + EXPERIMENTAL = True + DESCRIPTION = "Extends the potential frame count of HunyuanVideo using this method: https://github.com/thu-ml/RIFLEx" + + def patch(self, model, latent, k): + model_class = model.model.diffusion_model + + model_clone = model.clone() + num_frames = latent["samples"].shape[2] + + pe_embedder = EmbedND_RifleX( + model_class.params.hidden_size // model_class.params.num_heads, + model_class.params.theta, + model_class.params.axes_dim, + num_frames, + k + ) + + model_clone.add_object_patch(f"diffusion_model.pe_embedder", pe_embedder) + + return (model_clone, ) + +def rope_riflex(pos, dim, theta, L_test, k): + from einops import rearrange + assert dim % 2 == 0 + if model_management.is_device_mps(pos.device) or model_management.is_intel_xpu() or model_management.is_directml_enabled(): + device = torch.device("cpu") + else: + device = pos.device + + scale = torch.linspace(0, (dim - 2) / dim, steps=dim//2, dtype=torch.float64, device=device) + omega = 1.0 / (theta**scale) + + # RIFLEX modification - adjust last frequency component if L_test and k are provided + if k and L_test: + omega[k-1] = 0.9 * 2 * torch.pi / L_test + + out = torch.einsum("...n,d->...nd", pos.to(dtype=torch.float32, device=device), omega) + out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1) + out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2) + return out.to(dtype=torch.float32, device=pos.device) + +class EmbedND_RifleX(nn.Module): + def __init__(self, dim, theta, axes_dim, num_frames, k): + super().__init__() + self.dim = dim + self.theta = theta + self.axes_dim = axes_dim + self.num_frames = num_frames + self.k = k + + def forward(self, ids): + n_axes = ids.shape[-1] + emb = torch.cat( + [rope_riflex(ids[..., i], self.axes_dim[i], self.theta, self.num_frames, self.k if i == 0 else 0) for i in range(n_axes)], + dim=-3, + ) + return emb.unsqueeze(1) + + +class Timer: + def __init__(self, name): + self.name = name + self.start_time = None + self.elapsed = 0 + +class TimerNodeKJ: + @classmethod + + def INPUT_TYPES(s): + return { + "required": { + "any_input": (IO.ANY, ), + "mode": (["start", "stop"],), + "name": ("STRING", {"default": "Timer"}), + }, + "optional": { + "timer": ("TIMER",), + }, + } + + RETURN_TYPES = (IO.ANY, "TIMER", "INT", ) + RETURN_NAMES = ("any_output", "timer", "time") + FUNCTION = "timer" + CATEGORY = "KJNodes/misc" + + def timer(self, mode, name, any_input=None, timer=None): + if timer is None: + if mode == "start": + timer = Timer(name=name) + timer.start_time = time.time() + return {"ui": { + "text": [f"{timer.start_time}"]}, + "result": (any_input, timer, 0) + } + elif mode == "stop" and timer is not None: + end_time = time.time() + timer.elapsed = int((end_time - timer.start_time) * 1000) + timer.start_time = None + return (any_input, timer, timer.elapsed) + +class HunyuanVideoEncodeKeyframesToCond: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL",), + "positive": ("CONDITIONING", ), + "vae": ("VAE", ), + "start_frame": ("IMAGE", ), + "end_frame": ("IMAGE", ), + "num_frames": ("INT", {"default": 33, "min": 2, "max": 4096, "step": 1}), + "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 64}), + "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32}), + "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to encode at a time."}), + "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap."}), + }, + "optional": { + "negative": ("CONDITIONING", ), + } + } + + RETURN_TYPES = ("MODEL", "CONDITIONING","CONDITIONING","LATENT") + RETURN_NAMES = ("model", "positive", "negative", "latent") + FUNCTION = "encode" + + CATEGORY = "KJNodes/hunyuanvideo" + + def encode(self, model, positive, start_frame, end_frame, num_frames, vae, tile_size, overlap, temporal_size, temporal_overlap, negative=None): + + model_clone = model.clone() + + model_clone.add_object_patch("concat_keys", ("concat_image",)) + + + x = (start_frame.shape[1] // 8) * 8 + y = (start_frame.shape[2] // 8) * 8 + + if start_frame.shape[1] != x or start_frame.shape[2] != y: + x_offset = (start_frame.shape[1] % 8) // 2 + y_offset = (start_frame.shape[2] % 8) // 2 + start_frame = start_frame[:,x_offset:x + x_offset, y_offset:y + y_offset,:] + if end_frame.shape[1] != x or end_frame.shape[2] != y: + x_offset = (start_frame.shape[1] % 8) // 2 + y_offset = (start_frame.shape[2] % 8) // 2 + end_frame = end_frame[:,x_offset:x + x_offset, y_offset:y + y_offset,:] + + video_frames = torch.zeros(num_frames-2, start_frame.shape[1], start_frame.shape[2], start_frame.shape[3], device=start_frame.device, dtype=start_frame.dtype) + video_frames = torch.cat([start_frame, video_frames, end_frame], dim=0) + + concat_latent = vae.encode_tiled(video_frames[:,:,:,:3], tile_x=tile_size, tile_y=tile_size, overlap=overlap, tile_t=temporal_size, overlap_t=temporal_overlap) + + out_latent = {} + out_latent["samples"] = torch.zeros_like(concat_latent) + + out = [] + for conditioning in [positive, negative if negative is not None else []]: + c = [] + for t in conditioning: + d = t[1].copy() + d["concat_latent_image"] = concat_latent + n = [t[0], d] + c.append(n) + out.append(c) + if len(out) == 1: + out.append(out[0]) + return (model_clone, out[0], out[1], out_latent) + + +class LazySwitchKJ: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "switch": ("BOOLEAN",), + "on_false": (IO.ANY, {"lazy": True}), + "on_true": (IO.ANY, {"lazy": True}), + }, + } + + RETURN_TYPES = (IO.ANY,) + FUNCTION = "switch" + CATEGORY = "KJNodes/misc" + DESCRIPTION = "Controls flow of execution based on a boolean switch." + + def check_lazy_status(self, switch, on_false=None, on_true=None): + if switch and on_true is None: + return ["on_true"] + if not switch and on_false is None: + return ["on_false"] + + def switch(self, switch, on_false = None, on_true=None): + value = on_true if switch else on_false + return (value,) + + +from comfy.patcher_extension import WrappersMP +from comfy.sampler_helpers import prepare_mask +class TTM_OuterSampleWrapper: + def __init__(self, mask, steps): + self.mask = mask + self.steps = steps + + def __call__(self, executor, noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes): + guider = executor.class_obj + guider.model_options + wrappers = guider.model_options["transformer_options"]["wrappers"] + w = wrappers.setdefault(WrappersMP.APPLY_MODEL, {}) + + if self.mask is not None: + motion_mask = self.mask.reshape((-1, 1, self.mask.shape[-2], self.mask.shape[-1])) + shape = latent_shapes[0] + motion_mask = prepare_mask(motion_mask, shape, noise.device) + + scale_latent_inpaint = guider.model_patcher.model.scale_latent_inpaint + w["TTM_ApplyModel_Wrapper"] = [TTM_ApplyModel_Wrapper(latent_image, noise, motion_mask, self.steps, scale_latent_inpaint)] + + out = executor(noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes) + + return out + + +class TTM_ApplyModel_Wrapper: + def __init__(self, reference_samples, noise, motion_mask, steps, scale_latent_inpaint): + self.reference_samples = reference_samples + self.noise = noise + self.motion_mask = motion_mask + self.steps = steps + self.scale_latent_inpaint = scale_latent_inpaint + + def __call__(self, executor, x, t, c_concat, c_crossattn, control, transformer_options, **kwargs): + sigmas = transformer_options["sample_sigmas"] + + matched = (sigmas == t).nonzero(as_tuple=True)[0] + if matched.numel() > 0: + current_step_index = matched.item() + else: + crossing = ((sigmas[:-1] - t) * (sigmas[1:] - t) <= 0).nonzero(as_tuple=True)[0] + current_step_index = crossing.item() if crossing.numel() > 0 else 0 + + next_sigma = sigmas[current_step_index + 1] if current_step_index < len(sigmas) - 1 else sigmas[current_step_index] + + if current_step_index != 0 and current_step_index < self.steps: + noisy_latent = self.scale_latent_inpaint(x=x, sigma=torch.tensor([next_sigma]), noise=self.noise.to(x), latent_image=self.reference_samples.to(x)) + if self.motion_mask is not None: + x = x * (1-self.motion_mask).to(x) + noisy_latent * self.motion_mask.to(x) + else: + x = noisy_latent + + return executor(x, t, c_concat, c_crossattn, control, transformer_options, **kwargs) + + +class LatentInpaintTTM: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "model": ("MODEL", ), + "steps": ("INT", {"default": 7, "min": 0, "max": 888, "step": 1, "tooltip": "Number of steps to apply TTM inpainting for."}), + }, + "optional": { + "mask": ("MASK", {"tooltip": "Latent mask where white (1.0) is the area to inpaint and black (0.0) is the area to keep unchanged."}), + } + } + RETURN_TYPES = ("MODEL",) + FUNCTION = "patch" + EXPERIMENTAL = True + DESCRIPTION = "https://github.com/time-to-move/TTM" + SEARCH_ALIASES = ["time to move"] + CATEGORY = "KJNodes/experimental" + + def patch(self, model, steps, mask=None): + m = model.clone() + m.add_wrapper_with_key(WrappersMP.OUTER_SAMPLE, "TTM_OuterSampleWrapper", TTM_OuterSampleWrapper(mask, steps)) + return (m, ) + + +class SimpleCalculatorKJ(io.ComfyNode): + @classmethod + def define_schema(cls): + template = io.Autogrow.TemplateNames(input=io.MultiType.Input("var", [io.Int, io.Float, io.Boolean], optional=True), names=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"], min=2) + return io.Schema( + node_id="SimpleCalculatorKJ", + category="KJNodes/misc", + description=""" +Calculator node that evaluates a mathematical expression using inputs a and b. + Supported operations: +, -, *, /, //, %, **, <<, >>, unary +/- + Supported comparisons: ==, !=, <, <=, >, >= + Supported logic: and, or, not + Supported functions: abs(), round(), min(), max(), pow(), sqrt(), sin(), cos(), tan(), log(), log10(), exp(), floor(), ceil() + Supported constants: pi, euler, True, False +""", + search_aliases=["math", "arithmetic", "expression", "logic"], + inputs=[ + io.String.Input("expression", default="a + b", multiline=True), + io.Autogrow.Input("variables", template=template), + ], + outputs=[ + io.Float.Output(), + io.Int.Output(), + io.Boolean.Output(), + ], + ) + + @classmethod + def execute(cls, variables, expression, a=None, b=None) -> io.NodeOutput: + import ast + import operator + + # Allowed operations + allowed_operators = { + ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, + ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow, + ast.USub: operator.neg, ast.UAdd: operator.pos, ast.LShift: operator.lshift, + ast.RShift: operator.rshift, ast.Eq: operator.eq, ast.NotEq: operator.ne, ast.Lt: operator.lt, + ast.LtE: operator.le, ast.Gt: operator.gt, ast.GtE: operator.ge, ast.And: operator.and_, + ast.Or: operator.or_, ast.Not: operator.not_, + } + + # Allowed functions + allowed_functions = { + 'abs': abs, 'round': round, 'min': min, 'max': max, + 'pow': pow, 'sqrt': math.sqrt, 'sin': math.sin, + 'cos': math.cos, 'tan': math.tan, 'log': math.log, + 'log10': math.log10, 'exp': math.exp, 'floor': math.floor, + 'ceil': math.ceil + } + + # Allowed constants - start with pi, e, True, False + allowed_names = {'pi': math.pi, 'euler': math.e, 'True': True, 'False': False} + + # Add all variables from autogrow to allowed_names + for var_name, var_value in variables.items(): + allowed_names[var_name] = var_value + + # Backwards compatibility: add a and b if they're provided (for old workflows) + if a is not None: + allowed_names['a'] = a + if b is not None: + allowed_names['b'] = b + + def eval_node(node): + if isinstance(node, ast.Constant): # Numbers and booleans + return node.value + elif isinstance(node, ast.Name): # Variables + if node.id in allowed_names: + return allowed_names[node.id] + raise ValueError(f"Name '{node.id}' is not allowed") + elif isinstance(node, ast.BinOp): # Binary operations + if type(node.op) not in allowed_operators: + raise ValueError(f"Operator {type(node.op).__name__} is not allowed") + left = eval_node(node.left) + right = eval_node(node.right) + return allowed_operators[type(node.op)](left, right) + elif isinstance(node, ast.UnaryOp): # Unary operations + if type(node.op) not in allowed_operators: + raise ValueError(f"Operator {type(node.op).__name__} is not allowed") + operand = eval_node(node.operand) + return allowed_operators[type(node.op)](operand) + elif isinstance(node, ast.Compare): # Comparison operations + left = eval_node(node.left) + for op, comparator in zip(node.ops, node.comparators): + if type(op) not in allowed_operators: + raise ValueError(f"Operator {type(op).__name__} is not allowed") + right = eval_node(comparator) + result = allowed_operators[type(op)](left, right) + if not result: + return False + left = right + return True + elif isinstance(node, ast.BoolOp): # Boolean operations (and, or) + if type(node.op) not in allowed_operators: + raise ValueError(f"Operator {type(node.op).__name__} is not allowed") + values = [eval_node(value) for value in node.values] + if isinstance(node.op, ast.And): + return all(values) + elif isinstance(node.op, ast.Or): + return any(values) + elif isinstance(node, ast.Call): # Function calls + if not isinstance(node.func, ast.Name): + raise ValueError("Only simple function calls are allowed") + if node.func.id not in allowed_functions: + raise ValueError(f"Function '{node.func.id}' is not allowed") + args = [eval_node(arg) for arg in node.args] + return allowed_functions[node.func.id](*args) + else: + raise ValueError(f"Node type {type(node).__name__} is not allowed") + + try: + tree = ast.parse(expression, mode='eval') + result = eval_node(tree.body) + return io.NodeOutput(float(result), int(result), bool(result)) + except Exception as e: + logging.error(f"CalculatorKJ Error: {str(e)}") + return io.NodeOutput(0.0, 0, False) + + +class GetTrackRange(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="GetTrackRange", + category="conditioning/video_models", + inputs=[ + io.Tracks.Input("tracks"), + io.Int.Input("start_index", default=24, min=-10000, max=10000, step=1), + io.Int.Input("num_frames", default=10, min=1, max=10000, step=1), + ], + outputs=[ + io.Tracks.Output(), + ], + ) + + @classmethod + def execute(cls, tracks, start_index, num_frames) -> io.NodeOutput: + track_path = tracks["track_path"] + mask = tracks["track_visibility"] + total_frames = track_path.shape[0] + + if start_index < 0: + start_index = total_frames + start_index + start_index = max(0, min(start_index, total_frames)) + + # Clamp end_index + end_index = max(0, min(start_index + num_frames, total_frames)) + + tracks_out = track_path[start_index:end_index, ...] + mask_out = mask[start_index:end_index, ...] + + out_track = { + "track_path": tracks_out, + "track_visibility": mask_out, + } + return io.NodeOutput(out_track) + +class AddNoiseToTrackPath(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="AddNoiseToTrackPath", + category="conditioning/video_models", + inputs=[ + io.Tracks.Input("tracks"), + io.Float.Input("strength", default=1.0, min=0.0, max=100.0, step=0.01), + io.Int.Input("seed", default=0, min=0, max=0xffffffffffffffff, step=1), + io.Float.Input("noise_x_ratio", default=1.0, min=0.0, max=100.0, step=0.01, + tooltip="Multiplier for horizontal noise component"), + io.Float.Input("noise_y_ratio", default=1.0, min=0.0, max=100.0, step=0.01, + tooltip="Multiplier for vertical noise component"), + io.Float.Input("noise_temporal_ratio", default=1.0, min=0.0, max=100.0, step=0.01, + tooltip="Multiplier for temporal (frame-to-frame) noise"), + ], + outputs=[ + io.Tracks.Output(), + ], + ) + + @classmethod + def execute(cls, tracks, strength, seed, noise_x_ratio, noise_y_ratio, noise_temporal_ratio) -> io.NodeOutput: + track_path = tracks["track_path"].clone() + mask = tracks["track_visibility"] + + torch.manual_seed(seed) + noise = torch.randn_like(track_path) * strength + + # Apply directional scaling to noise + noise[..., 0] *= noise_x_ratio # X coordinate noise + noise[..., 1] *= noise_y_ratio # Y coordinate noise + + # Apply temporal smoothing if temporal ratio is less than 1 + if noise_temporal_ratio < 1.0: + num_frames = track_path.shape[0] + smoothed_noise = noise.clone() + kernel_size = max(1, int((1.0 - noise_temporal_ratio) * 10)) + + for i in range(num_frames): + start_idx = max(0, i - kernel_size // 2) + end_idx = min(num_frames, i + kernel_size // 2 + 1) + smoothed_noise[i] = noise[start_idx:end_idx].mean(dim=0) + + noise = smoothed_noise * noise_temporal_ratio + noise * (1 - noise_temporal_ratio) + + track_path = track_path + noise + + out_track = { + "track_path": track_path, + "track_visibility": mask, + } + return io.NodeOutput(out_track) + + +class VAEDecodeLoopKJ: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "samples": ("LATENT", {"tooltip": "The latent to be decoded."}), + "vae": ("VAE", {"tooltip": "The VAE model used for decoding the latent."}), + "overlap_latent_frames": ("INT", {"default": 2, "min": 2, "max": 8, "step": 1, "tooltip": "Number of frames to blend for seamless loop, for Wan 2 works and HunyuanVideo 1.5 should use 4"}), + } + } + RETURN_TYPES = ("IMAGE",) + OUTPUT_TOOLTIPS = ("The decoded images.",) + FUNCTION = "decode" + CATEGORY = "KJNodes/vae" + DESCRIPTION = "Video latent VAE decoding to fix artifacts on loop seams." + + def decode(self, vae, samples, overlap_latent_frames): + latents = samples["samples"] + + images = vae.decode(latents) + if overlap_latent_frames <= 0: + if len(images.shape) == 5: + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + return (images, ) + + end_frames = overlap_latent_frames + 1 + start_frames = overlap_latent_frames + + temp_images = vae.decode(torch.cat([latents[:, :, -end_frames:]] + [latents[:, :, :start_frames]], dim=2)).cpu().float() + + total_concat = end_frames + start_frames + temp_start = total_concat * 2 - 1 + main_start = total_concat + (overlap_latent_frames if overlap_latent_frames > 2 else 0) + + images = torch.cat([temp_images[:, temp_start:].to(images), images[:, main_start:]], dim=1) + if len(images.shape) == 5: + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + + return (images, ) + +class WanImageToVideoSVIPro(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="WanImageToVideoSVIPro", + category="conditioning/video_models", + inputs=[ + io.Conditioning.Input("positive"), + io.Conditioning.Input("negative"), + io.Int.Input("length", default=81, min=1, max=MAX_RESOLUTION, step=4), + io.Latent.Input("anchor_samples"), + io.Latent.Input("prev_samples", optional=True), + io.Int.Input("motion_latent_count", default=1, min=0, max=128, step=1), + ], + outputs=[ + io.Conditioning.Output(display_name="positive"), + io.Conditioning.Output(display_name="negative"), + io.Latent.Output(display_name="latent"), + ], + ) + + @classmethod + def execute(cls, positive, negative, length, motion_latent_count, anchor_samples, prev_samples=None) -> io.NodeOutput: + anchor_latent = anchor_samples["samples"].clone() + + B, C, T, H, W = anchor_latent.shape + empty_latent = torch.zeros([B, 16, ((length - 1) // 4) + 1, H, W], device=model_management.intermediate_device()) + + total_latents = (length - 1) // 4 + 1 + device = anchor_latent.device + dtype = anchor_latent.dtype + + if prev_samples is None or motion_latent_count == 0: + padding_size = total_latents - anchor_latent.shape[2] + image_cond_latent = anchor_latent + else: + motion_latent = prev_samples["samples"][:, :, -motion_latent_count:].clone() + padding_size = total_latents - anchor_latent.shape[2] - motion_latent.shape[2] + image_cond_latent = torch.cat([anchor_latent, motion_latent], dim=2) + + padding = torch.zeros(1, C, padding_size, H, W, dtype=dtype, device=device) + padding = comfy.latent_formats.Wan21().process_out(padding) + image_cond_latent = torch.cat([image_cond_latent, padding], dim=2) + + mask = torch.ones((1, 1, empty_latent.shape[2], H, W), device=device, dtype=dtype) + mask[:, :, :1] = 0.0 + + positive = node_helpers.conditioning_set_values(positive, {"concat_latent_image": image_cond_latent, "concat_mask": mask}) + negative = node_helpers.conditioning_set_values(negative, {"concat_latent_image": image_cond_latent, "concat_mask": mask}) + + out_latent = {} + out_latent["samples"] = empty_latent + return io.NodeOutput(positive, negative, out_latent) + +class DeprecatedCompileNodeKJ: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": (IO.ANY,), + }, + } + RETURN_TYPES = (IO.ANY,) + FUNCTION = "passthrough" + CATEGORY = "KJNodes/deprecated" + DESCRIPTION = "This node has been replaced with TorchCompileModelAdvanced node, please use that instead." + def passthrough(self, model): + return (model,) + + +class VisualizeSigmasKJ(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="VisualizeSigmasKJ", + category="KJNodes/misc", + inputs=[ + io.Sigmas.Input("sigmas"), + io.Int.Input("start_step", default=0, min=-1, max=1000, step=1, + tooltip="Step index to mark as the start of a range (inclusive). Set to -1 to disable."), + io.Int.Input("end_step", default=-1, min=-1, max=1000, step=1, + tooltip="Step index to mark as the end of a range (inclusive). Set to - 1 to disable."), + ], + outputs=[ + io.Sigmas.Output(display_name="sigmas_out"), + io.Image.Output(display_name="image"), + ], + ) + + @classmethod + def execute(cls, sigmas, start_step=0, end_step=-1) -> io.NodeOutput: + + start_idx = 0 + end_idx = len(sigmas) - 1 + + if isinstance(start_step, float): + idxs = (sigmas <= start_step).nonzero(as_tuple=True)[0] + if len(idxs) > 0: + start_idx = idxs[0].item() + elif isinstance(start_step, int): + if start_step > 0: + start_idx = start_step + + if isinstance(end_step, float): + idxs = (sigmas >= end_step).nonzero(as_tuple=True)[0] + if len(idxs) > 0: + end_idx = idxs[-1].item() + elif isinstance(end_step, int): + if end_step != -1: + end_idx = end_step - 1 + + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + sigmas_np = sigmas.cpu().numpy() + if not np.isclose(sigmas_np[-1], 0.0, atol=1e-6): + sigmas_np = np.append(sigmas_np, 0.0) + buf = BytesIO() + fig = plt.figure(facecolor='#353535') + ax = fig.add_subplot(111) + ax.set_facecolor('#353535') # Set axes background color + x_values = range(0, len(sigmas_np)) + ax.plot(x_values, sigmas_np) + # Annotate each sigma value + ax.scatter(x_values, sigmas_np, color='white', s=20, zorder=3) # Small dots at each sigma + for x, y in zip(x_values, sigmas_np): + # Show all annotations if few steps, or just show split step annotations + show_annotation = len(sigmas_np) <= 10 + is_split_step = (start_idx > 0 and x == start_idx) or (end_idx != -1 and x == end_idx + 1) + + if show_annotation or is_split_step: + color = 'orange' + if is_split_step: + color = 'yellow' + ax.annotate(f"{y:.3f}", (x, y), textcoords="offset points", xytext=(10, 1), ha='center', color=color, fontsize=12) + ax.set_xticks(x_values) + ax.set_title("Sigmas", color='white') # Title font color + ax.set_xlabel("Step", color='white') # X label font color + ax.set_ylabel("Sigma Value", color='white') # Y label font color + ax.tick_params(axis='x', colors='white', labelsize=10) # X tick color + ax.tick_params(axis='y', colors='white', labelsize=10) # Y tick color + # Add split point if end_step is defined + end_idx += 1 + if end_idx != -1 and 0 <= end_idx < len(sigmas_np) - 1: + ax.axvline(end_idx, color='red', linestyle='--', linewidth=2, label='end_step split') + # Add split point if start_step is defined + if start_idx > 0 and 0 <= start_idx < len(sigmas_np): + ax.axvline(start_idx, color='green', linestyle='--', linewidth=2, label='start_step split') + if (end_idx != -1 and 0 <= end_idx < len(sigmas_np)) or (start_idx > 0 and 0 <= start_idx < len(sigmas_np)): + handles, labels = ax.get_legend_handles_labels() + if labels: + ax.legend() + # Draw shaded range + range_start_idx = start_idx if start_idx > 0 else 0 + range_end_idx = end_idx if end_idx > 0 and end_idx < len(sigmas_np) else len(sigmas_np) - 1 + if range_start_idx < range_end_idx: + ax.axvspan(range_start_idx, range_end_idx, color='lightblue', alpha=0.1, label='Sampled Range') + + + plt.tight_layout() + fig.canvas.draw() + w, h = fig.canvas.get_width_height() + try: + buf = np.frombuffer(fig.canvas.tostring_argb(), dtype=np.uint8) + buf = buf.reshape(h, w, 4) + buf = buf[:, :, [1, 2, 3]] # Convert ARGB to RGB + except: + buf = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) + buf = buf.reshape(h, w, 3).copy() + image = torch.from_numpy(buf).float() / 255.0 + image = image.unsqueeze(0) #(H, W, C) -> (1, H, W, C) + plt.close(fig) + + sigmas_out = sigmas[start_idx:end_idx + 1] if end_idx != -1 else sigmas[start_idx:] + + return io.NodeOutput(sigmas_out,image) + +class PreviewLatentNoiseMask(io.ComfyNode): + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PreviewLatentNoiseMask", + category="KJNodes/latents", + description="Previews the latent noise mask", + inputs=[ + io.Latent.Input("latent",), + ], + outputs=[ + io.Mask.Output(display_name="mask"), + ], + ) + + @classmethod + def execute(cls, latent) -> io.NodeOutput: + noise_mask = latent.get("noise_mask", None) + if noise_mask is None: + return io.NodeOutput(torch.zeros((1, 64, 64))) + noise_mask = noise_mask.clone() + + if noise_mask.ndim == 5: + noise_mask = noise_mask[0, 0] + + return io.NodeOutput(noise_mask) + +class PlaySoundKJ(io.ComfyNode): + """Plays audio in the browser when execution reaches this node.""" + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PlaySoundKJ", + category="KJNodes/audio", + description="Plays the input audio in the browser. Modes: 'always' plays on every execution, 'on_empty_queue' plays only when the queue finishes, 'on_change' plays only when the audio content changes. Duration limits playback length (0 = full audio).", + inputs=[ + io.AnyType.Input("any_input", optional=True), + io.Audio.Input("audio", optional=True), + io.String.Input("audio_path", default="", tooltip="Path to an audio file. Used when audio input is not connected."), + io.Combo.Input("mode", options=["always", "on_empty_queue", "on_change"], default="always"), + io.Float.Input("volume", default=0.5, min=0.0, max=1.0, step=0.01), + io.Float.Input("duration", default=5.0, min=0.0, max=300.0, step=0.1, tooltip="Duration in seconds to play. 0 = play full audio."), + ], + outputs=[ + io.AnyType.Output("any_output", display_name="any_output"), + ], + is_output_node=True, + ) + + @classmethod + def fingerprint_inputs(cls, **kwargs): + if kwargs.get("mode") == "on_change": + return False + return float("NaN") + + @staticmethod + def _generate_chime(): + sr = 32000 + C, Ab, Bb = 523.26, 421.30, 466.16 # note frequencies + e = 0.14 # eighth note — adjust to change tempo + S, M, H = 16, 7, 2.5 # staccato / medium / held decay + melody = [ + (C,e,S), (C,e,S), (C,e,S), (C,e*3,M), + (Ab,e*3,M), (Bb,e*3,M), (C,e*2,S), (Bb,e,S), (C,e*5,H), + ] + k = torch.exp(-torch.linspace(-2, 2, 15) ** 2) + k = (k / k.sum()).reshape(1, 1, -1) + parts = [] + for freq, dur, decay in melody: + t = torch.linspace(0, dur, int(sr * dur)) + tone = torch.tanh(3 * torch.sin(2 * math.pi * freq * t)) + tone = torch.nn.functional.conv1d(tone.reshape(1, 1, -1), k, padding=7).squeeze() + parts.append(tone * torch.exp(-t * decay)) + wav = torch.cat(parts) * 0.45 + return {"waveform": wav.unsqueeze(0).unsqueeze(0), "sample_rate": sr} + + @classmethod + def execute(cls, audio=None, audio_path="", mode="always", volume=0.5, duration=5.0, any_input=None) -> io.NodeOutput: + if audio is None: + if audio_path: + import av + with av.open(audio_path) as af: + stream = af.streams.audio[0] + sr = stream.codec_context.sample_rate + frames = [] + for frame in af.decode(streams=stream.index): + buf = torch.from_numpy(frame.to_ndarray()) + if buf.shape[0] != stream.channels: + buf = buf.view(-1, stream.channels).t() + frames.append(buf) + wav = torch.cat(frames, dim=1).float() + audio = {"waveform": wav.unsqueeze(0), "sample_rate": sr} + else: + audio = cls._generate_chime() + + preview = ui.PreviewAudio(audio, cls=cls) + ui_dict = preview.as_dict() + ui_dict["audio_hash"] = [hash(audio["waveform"].sum().item())] + return io.NodeOutput( + any_input, + ui=ui_dict, + ) diff --git a/.disabled/comfyui-kjnodes@nightly/nodes/sharpen_nodes.py b/.disabled/comfyui-kjnodes@nightly/nodes/sharpen_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..3635a21e900cfe4393f34defc251c5b34b12429d --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/nodes/sharpen_nodes.py @@ -0,0 +1,259 @@ +import torch +import torch.nn.functional as F + +from comfy import model_management +from comfy_api.latest import io + +class ImageSharpenKJ(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ImageSharpenKJ", + category="KJNodes/image", + display_name="Image Sharpen KJ", + search_aliases=["sharpen", "unsharp mask", "deconvolution", "cas", "rcas", "high-pass", "postprocessing"], + description="""GPU-accelerated image sharpening with multiple methods. + +**RCAS** — AMD's Robust Contrast-Adaptive Sharpening (from FSR). +Single 5-tap cross filter that adapts to local contrast. +Minimal artifacts, good for general use with little tuning. + +**Adaptive USM** — Unsharp mask with local variance modulation. +Sharpens detail-rich areas more, flat/noisy areas less. +More controllable than RCAS via radius and threshold parameters. + +**High-Pass** — Extracts high-frequency detail and blends it back. +Gives a "clarity" enhancement feel. Uses radius to control detail scale. + +**Deconvolution** — Richardson-Lucy iterative deconvolution. +Can recover actual lost detail from blur, not just enhance edges. +Uses radius as the estimated blur kernel and iterations to control convergence.""", + inputs=[ + io.MatchType.Input("image", io.MatchType.Template("img_or_mask", [io.Image, io.Mask])), + io.DynamicCombo.Input("method", options=[ + io.DynamicCombo.Option(key="rcas", inputs=[ + io.Float.Input("strength", default=0.8, min=0.0, max=1.0, step=0.01, + tooltip="0 = no sharpening, 1 = full RCAS sharpening."), + ]), + io.DynamicCombo.Option(key="adaptive_usm", inputs=[ + io.Float.Input("strength", default=0.5, min=0.0, max=3.0, step=0.01, + tooltip="Sharpening multiplier. Values above 1.0 give aggressive sharpening."), + io.Float.Input("radius", default=1.0, min=0.5, max=5.0, step=0.1, + tooltip="Gaussian blur sigma for the unsharp mask. Larger = enhances coarser detail."), + io.Float.Input("threshold", default=0.05, min=0.0, max=1.0, step=0.01, + tooltip="Noise gate. Higher = only sharpen areas with more texture/detail. 0 = sharpen everything."), + ]), + io.DynamicCombo.Option(key="high_pass", inputs=[ + io.Float.Input("strength", default=0.5, min=0.0, max=3.0, step=0.01, + tooltip="Blend factor for high-frequency detail. Values above 1.0 give a punchier effect."), + io.Float.Input("radius", default=1.0, min=0.5, max=5.0, step=0.1, + tooltip="Gaussian blur sigma defining the frequency cutoff. Larger = enhances coarser detail."), + ]), + io.DynamicCombo.Option(key="deconvolution", inputs=[ + io.Float.Input("strength", default=0.5, min=0.0, max=1.0, step=0.01, + tooltip="Blend between original (0) and fully deconvolved (1)."), + io.Float.Input("radius", default=1.0, min=0.5, max=5.0, step=0.1, + tooltip="Sigma of the assumed Gaussian blur to reverse."), + io.Int.Input("iterations", default=10, min=1, max=100, step=1, + tooltip="Richardson-Lucy iterations. More = sharper but slower, diminishing returns past ~20."), + ]), + ]), + ], + outputs=[ + io.MatchType.Output(io.MatchType.Template("img_or_mask", [io.Image, io.Mask]), display_name="output"), + ], + ) + + @classmethod + def execute(cls, image, method) -> io.NodeOutput: + selected = method["method"] + strength = method.get("strength", 0.5) + if strength == 0: + return io.NodeOutput(image) + + is_mask = image.ndim == 3 # BHW + if is_mask: + image = image.unsqueeze(-1) # BHW -> BHWC with C=1 + + radius = method.get("radius", 1.0) + threshold = method.get("threshold", 0.05) + iterations = method.get("iterations", 10) + if selected == "rcas": + result = _rcas(image, strength) + elif selected == "adaptive_usm": + result = _adaptive_usm(image, strength, radius, threshold) + elif selected == "high_pass": + result = _high_pass(image, strength, radius) + else: + result = _deconvolution(image, strength, radius, iterations) + + if is_mask: + result = result.squeeze(-1) # BHWC -> BHW + + return io.NodeOutput(result) + + +def _rcas(image: torch.Tensor, strength: float) -> torch.Tensor: + """AMD FidelityFX RCAS — 5-tap cross filter with contrast-adaptive lobe.""" + device = model_management.get_torch_device() + intermediate_device = model_management.intermediate_device() + dtype = model_management.intermediate_dtype() + + B, H, W, C = image.shape + out = torch.empty(B, H, W, C, device=intermediate_device, dtype=dtype) + attenuation = strength + + for i in range(B): + img = image[i:i+1].to(device=device, dtype=dtype).permute(0, 3, 1, 2) + padded = F.pad(img, (1, 1, 1, 1), mode='reflect') + + n = padded[:, :, 0:H, 1:W+1] + s = padded[:, :, 2:H+2, 1:W+1] + w = padded[:, :, 1:H+1, 0:W] + e = padded[:, :, 1:H+1, 2:W+2] + center = img + + mn = torch.min(torch.min(torch.min(torch.min(n, s), w), e), center) + mx = torch.max(torch.max(torch.max(torch.max(n, s), w), e), center) + + # hitMin = -mn / (4*mx), hitMax = -(1-mx) / (4*(1-mn)) + hit_min = mn.div(mx * 4.0 + 1e-6).neg_() + hit_max = mx.neg().add_(1.0).div_(mn.neg().add_(1.0).mul_(4.0).add_(1e-6)).neg_() + + torch.max(hit_min, hit_max, out=hit_min) + lobe = hit_min.min(dim=1, keepdim=True).values + + lobe.mul_(attenuation) + lobe.clamp_(-0.1875, 0.0) + + # (center + lobe*(n+s+e+w)) / (1 + 4*lobe) + norm = lobe.mul(4.0).add_(1.0).reciprocal_() + neighbors = n + s + neighbors.add_(e).add_(w) + neighbors.mul_(lobe).add_(center).mul_(norm) + neighbors.clamp_(0.0, 1.0) + + out[i:i+1] = neighbors.permute(0, 2, 3, 1).to(device=intermediate_device) + + return out + + +def _gaussian_kernel_1d(sigma: float, device: torch.device, dtype: torch.dtype) -> torch.Tensor: + radius = max(int(3.0 * sigma + 0.5), 1) + x = torch.arange(-radius, radius + 1, device=device, dtype=dtype) + kernel = torch.exp(-0.5 * (x / sigma) ** 2) + kernel.div_(kernel.sum()) + return kernel + + +def _gaussian_blur(img: torch.Tensor, sigma: float) -> torch.Tensor: + """Separable Gaussian blur on BCHW tensor.""" + kernel_1d = _gaussian_kernel_1d(sigma, img.device, img.dtype) + k = kernel_1d.shape[0] + C = img.shape[1] + pad = k // 2 + + kh = kernel_1d.view(1, 1, 1, k).expand(C, -1, -1, -1) + blurred = F.conv2d(F.pad(img, (pad, pad, 0, 0), mode='reflect'), kh, groups=C) + + kv = kernel_1d.view(1, 1, k, 1).expand(C, -1, -1, -1) + blurred = F.conv2d(F.pad(blurred, (0, 0, pad, pad), mode='reflect'), kv, groups=C) + + return blurred + + +def _adaptive_usm(image: torch.Tensor, strength: float, radius: float, threshold: float) -> torch.Tensor: + """Unsharp mask modulated by local variance — sharpens texture, skips flat areas.""" + device = model_management.get_torch_device() + intermediate_device = model_management.intermediate_device() + dtype = model_management.intermediate_dtype() + + B, H, W, C = image.shape + out = torch.empty(B, H, W, C, device=intermediate_device, dtype=dtype) + var_sigma = radius * 1.5 + + for i in range(B): + img = image[i:i+1].to(device=device, dtype=dtype, copy=True).permute(0, 3, 1, 2) + + blurred = _gaussian_blur(img, radius) + detail = img - blurred + + # Local variance: E[x^2] - E[x]^2 + local_mean = _gaussian_blur(img, var_sigma) + local_mean_sq = _gaussian_blur(img.square(), var_sigma) + local_mean_sq.sub_(local_mean * local_mean).clamp_(min=0.0) + + # Convert to std deviation so threshold is in pixel-intensity scale + modulation = local_mean_sq.mean(dim=1, keepdim=True).sqrt_() + + if threshold > 0: + modulation.div_(threshold).clamp_(0.0, 1.0) + else: + modulation.fill_(1.0) + + img.addcmul_(detail, modulation, value=strength).clamp_(0.0, 1.0) + + out[i:i+1] = img.permute(0, 2, 3, 1).to(device=intermediate_device) + + return out + + +def _high_pass(image: torch.Tensor, strength: float, radius: float) -> torch.Tensor: + """High-pass sharpening: original + strength * (original - blur).""" + device = model_management.get_torch_device() + intermediate_device = model_management.intermediate_device() + dtype = model_management.intermediate_dtype() + + B, H, W, C = image.shape + out = torch.empty(B, H, W, C, device=intermediate_device, dtype=dtype) + + for i in range(B): + img = image[i:i+1].to(device=device, dtype=dtype).permute(0, 3, 1, 2) + + low_pass = _gaussian_blur(img, radius) + low_pass.neg_().add_(img).mul_(strength).add_(img).clamp_(0.0, 1.0) + + out[i:i+1] = low_pass.permute(0, 2, 3, 1).to(device=intermediate_device) + + return out + + +def _deconvolution(image: torch.Tensor, strength: float, radius: float, iterations: int) -> torch.Tensor: + """Richardson-Lucy deconvolution with Gaussian PSF.""" + device = model_management.get_torch_device() + intermediate_device = model_management.intermediate_device() + dtype = model_management.intermediate_dtype() + + B, H, W, C = image.shape + out = torch.empty(B, H, W, C, device=intermediate_device, dtype=dtype) + + # Gaussian PSF kernel (symmetric, so PSF^T = PSF) + kernel_1d = _gaussian_kernel_1d(radius, device, dtype) + k = kernel_1d.shape[0] + pad = k // 2 + kh = kernel_1d.view(1, 1, 1, k).expand(C, -1, -1, -1) + kv = kernel_1d.view(1, 1, k, 1).expand(C, -1, -1, -1) + + for i in range(B): + img = image[i:i+1].to(device=device, dtype=dtype).permute(0, 3, 1, 2) + estimate = img.clone() + + for _ in range(iterations): + # estimate *= (observed / (estimate * PSF)) * PSF^T + blurred = F.conv2d(F.pad(estimate, (pad, pad, 0, 0), mode='reflect'), kh, groups=C) + blurred = F.conv2d(F.pad(blurred, (0, 0, pad, pad), mode='reflect'), kv, groups=C) + + blurred.add_(1e-6) + torch.div(img, blurred, out=blurred) + + correction = F.conv2d(F.pad(blurred, (pad, pad, 0, 0), mode='reflect'), kh, groups=C) + correction = F.conv2d(F.pad(correction, (0, 0, pad, pad), mode='reflect'), kv, groups=C) + + estimate.mul_(correction) + + torch.lerp(img, estimate, strength, out=estimate) + estimate.clamp_(0.0, 1.0) + + out[i:i+1] = estimate.permute(0, 2, 3, 1).to(device=intermediate_device) + + return out diff --git a/.disabled/comfyui-kjnodes@nightly/utility/__pycache__/utility.cpython-310.pyc b/.disabled/comfyui-kjnodes@nightly/utility/__pycache__/utility.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ad4bfcc167c5097b4d402f28313839ffa02ab6d Binary files /dev/null and b/.disabled/comfyui-kjnodes@nightly/utility/__pycache__/utility.cpython-310.pyc differ diff --git a/.disabled/comfyui-kjnodes@nightly/utility/fluid.py b/.disabled/comfyui-kjnodes@nightly/utility/fluid.py new file mode 100644 index 0000000000000000000000000000000000000000..f6387b8c27831c685537877e39e38323adc82c1e --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/utility/fluid.py @@ -0,0 +1,67 @@ +import numpy as np +from scipy.ndimage import map_coordinates, spline_filter +from scipy.sparse.linalg import factorized + +from .numerical import difference, operator + + +class Fluid: + def __init__(self, shape, *quantities, pressure_order=1, advect_order=3): + self.shape = shape + self.dimensions = len(shape) + + # Prototyping is simplified by dynamically + # creating advected quantities as needed. + self.quantities = quantities + for q in quantities: + setattr(self, q, np.zeros(shape)) + + self.indices = np.indices(shape) + self.velocity = np.zeros((self.dimensions, *shape)) + + laplacian = operator(shape, difference(2, pressure_order)) + self.pressure_solver = factorized(laplacian) + + self.advect_order = advect_order + + def step(self): + # Advection is computed backwards in time as described in Stable Fluids. + advection_map = self.indices - self.velocity + + # SciPy's spline filter introduces checkerboard divergence. + # A linear blend of the filtered and unfiltered fields based + # on some value epsilon eliminates this error. + def advect(field, filter_epsilon=10e-2, mode='constant'): + filtered = spline_filter(field, order=self.advect_order, mode=mode) + field = filtered * (1 - filter_epsilon) + field * filter_epsilon + return map_coordinates(field, advection_map, prefilter=False, order=self.advect_order, mode=mode) + + # Apply advection to each axis of the + # velocity field and each user-defined quantity. + for d in range(self.dimensions): + self.velocity[d] = advect(self.velocity[d]) + + for q in self.quantities: + setattr(self, q, advect(getattr(self, q))) + + # Compute the jacobian at each point in the + # velocity field to extract curl and divergence. + jacobian_shape = (self.dimensions,) * 2 + partials = tuple(np.gradient(d) for d in self.velocity) + jacobian = np.stack(partials).reshape(*jacobian_shape, *self.shape) + + divergence = jacobian.trace() + + # If this curl calculation is extended to 3D, the y-axis value must be negated. + # This corresponds to the coefficients of the levi-civita symbol in that dimension. + # Higher dimensions do not have a vector -> scalar, or vector -> vector, + # correspondence between velocity and curl due to differing isomorphisms + # between exterior powers in dimensions != 2 or 3 respectively. + curl_mask = np.triu(np.ones(jacobian_shape, dtype=bool), k=1) + curl = (jacobian[curl_mask] - jacobian[curl_mask.T]).squeeze() + + # Apply the pressure correction to the fluid's velocity field. + pressure = self.pressure_solver(divergence.flatten()).reshape(self.shape) + self.velocity -= np.gradient(pressure) + + return divergence, curl, pressure \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/utility/magictex.py b/.disabled/comfyui-kjnodes@nightly/utility/magictex.py new file mode 100644 index 0000000000000000000000000000000000000000..44986bf4b8e74b9533896a34a2fb2aa24a5d00fd --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/utility/magictex.py @@ -0,0 +1,95 @@ +"""Generates psychedelic color textures in the spirit of Blender's magic texture shader using Python/Numpy + +https://github.com/cheind/magic-texture +""" +from typing import Tuple, Optional +import numpy as np + + +def coordinate_grid(shape: Tuple[int, int], dtype=np.float32): + """Returns a three-dimensional coordinate grid of given shape for use in `magic`.""" + x = np.linspace(-1, 1, shape[1], endpoint=True, dtype=dtype) + y = np.linspace(-1, 1, shape[0], endpoint=True, dtype=dtype) + X, Y = np.meshgrid(x, y) + XYZ = np.stack((X, Y, np.ones_like(X)), -1) + return XYZ + + +def random_transform(coords: np.ndarray, rng: np.random.Generator = None): + """Returns randomly transformed coordinates""" + H, W = coords.shape[:2] + rng = rng or np.random.default_rng() + m = rng.uniform(-1.0, 1.0, size=(3, 3)).astype(coords.dtype) + return (coords.reshape(-1, 3) @ m.T).reshape(H, W, 3) + + +def magic( + coords: np.ndarray, + depth: Optional[int] = None, + distortion: Optional[int] = None, + rng: np.random.Generator = None, +): + """Returns color magic color texture. + + The implementation is based on Blender's (https://www.blender.org/) magic + texture shader. The following adaptions have been made: + - we exchange the nested if-cascade by a probabilistic iterative approach + + Kwargs + ------ + coords: HxWx3 array + Coordinates transformed into colors by this method. See + `magictex.coordinate_grid` to generate the default. + depth: int (optional) + Number of transformations applied. Higher numbers lead to more + nested patterns. If not specified, randomly sampled. + distortion: float (optional) + Distortion of patterns. Larger values indicate more distortion, + lower values tend to generate smoother patterns. If not specified, + randomly sampled. + rng: np.random.Generator + Optional random generator to draw samples from. + + Returns + ------- + colors: HxWx3 array + Three channel color image in range [0,1] + """ + rng = rng or np.random.default_rng() + if distortion is None: + distortion = rng.uniform(1, 4) + if depth is None: + depth = rng.integers(1, 5) + + H, W = coords.shape[:2] + XYZ = coords + x = np.sin((XYZ[..., 0] + XYZ[..., 1] + XYZ[..., 2]) * distortion) + y = np.cos((-XYZ[..., 0] + XYZ[..., 1] - XYZ[..., 2]) * distortion) + z = -np.cos((-XYZ[..., 0] - XYZ[..., 1] + XYZ[..., 2]) * distortion) + + if depth > 0: + x *= distortion + y *= distortion + z *= distortion + y = -np.cos(x - y + z) + y *= distortion + + xyz = [x, y, z] + fns = [np.cos, np.sin] + for _ in range(1, depth): + axis = rng.choice(3) + fn = fns[rng.choice(2)] + signs = rng.binomial(n=1, p=0.5, size=4) * 2 - 1 + + xyz[axis] = signs[-1] * fn( + signs[0] * xyz[0] + signs[1] * xyz[1] + signs[2] * xyz[2] + ) + xyz[axis] *= distortion + + x, y, z = xyz + x /= 2 * distortion + y /= 2 * distortion + z /= 2 * distortion + c = 0.5 - np.stack((x, y, z), -1) + np.clip(c, 0, 1.0) + return c \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/utility/numerical.py b/.disabled/comfyui-kjnodes@nightly/utility/numerical.py new file mode 100644 index 0000000000000000000000000000000000000000..96dd7fe1e6f51260f7e9545f7114141973ded6e0 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/utility/numerical.py @@ -0,0 +1,25 @@ +from functools import reduce +from itertools import cycle +from math import factorial + +import numpy as np +import scipy.sparse as sp + + +def difference(derivative, accuracy=1): + # Central differences implemented based on the article here: + # http://web.media.mit.edu/~crtaylor/calculator.html + derivative += 1 + radius = accuracy + derivative // 2 - 1 + points = range(-radius, radius + 1) + coefficients = np.linalg.inv(np.vander(points)) + return coefficients[-derivative] * factorial(derivative - 1), points + + +def operator(shape, *differences): + # Credit to Philip Zucker for figuring out + # that kronsum's argument order is reversed. + # Without that bit of wisdom I'd have lost it. + differences = zip(shape, cycle(differences)) + factors = (sp.diags(*diff, shape=(dim,) * 2) for dim, diff in differences) + return reduce(lambda a, f: sp.kronsum(f, a, format='csc'), factors) \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/utility/utility.py b/.disabled/comfyui-kjnodes@nightly/utility/utility.py new file mode 100644 index 0000000000000000000000000000000000000000..91a39d7c4d46ae60e769297da75df23b19a6c505 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/utility/utility.py @@ -0,0 +1,88 @@ +import torch +import numpy as np +from PIL import Image, ImageColor +from typing import Union, List +import logging + +# Utility functions from mtb nodes: https://github.com/melMass/comfy_mtb +def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor: + if isinstance(image, list): + return torch.cat([pil2tensor(img) for img in image], dim=0) + + return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) + + +def np2tensor(img_np: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor: + if isinstance(img_np, list): + return torch.cat([np2tensor(img) for img in img_np], dim=0) + + return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0) + + +def tensor2np(tensor: torch.Tensor): + if len(tensor.shape) == 3: # Single image + return np.clip(255.0 * tensor.cpu().numpy(), 0, 255).astype(np.uint8) + else: # Batch of images + return [np.clip(255.0 * t.cpu().numpy(), 0, 255).astype(np.uint8) for t in tensor] + +def tensor2pil(image: torch.Tensor) -> List[Image.Image]: + batch_count = image.size(0) if len(image.shape) > 3 else 1 + if batch_count > 1: + out = [] + for i in range(batch_count): + out.extend(tensor2pil(image[i])) + return out + + return [ + Image.fromarray( + np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8) + ) + ] + +def string_to_color(color_string: str) -> List[int]: + color_list = [0, 0, 0] # Default fallback (black) + + if ',' in color_string: + # Handle CSV format (e.g., "255, 0, 0" or "255, 0, 0, 128" or "1.0, 0.5, 0.0") + try: + values = [float(channel.strip()) for channel in color_string.split(',')] + # Convert to 0-255 range if values are in 0-1 range + if all(0 <= v <= 1 for v in values): + color_list = [int(v * 255) for v in values] + else: + color_list = [int(v) for v in values] + except ValueError: + logging.warning(f"Invalid color format: {color_string}. Using default black.") + elif color_string.startswith('#') or (color_string.lstrip('#').isalnum() and not color_string.lstrip('#').replace('.', '', 1).isdigit()): + # Could be Hex format or color name + color_string_stripped = color_string.lstrip('#') + # Try hex first + if len(color_string_stripped) in [6, 8] and all(c in '0123456789ABCDEFabcdef' for c in color_string_stripped): + if len(color_string_stripped) == 6: # #RRGGBB + color_list = [int(color_string_stripped[i:i+2], 16) for i in (0, 2, 4)] + elif len(color_string_stripped) == 8: # #RRGGBBAA + color_list = [int(color_string_stripped[i:i+2], 16) for i in (0, 2, 4, 6)] + else: + # Try color name (e.g., "red", "blue", "cyan") + try: + rgb = ImageColor.getrgb(color_string) + color_list = list(rgb) + except ValueError: + logging.warning(f"Invalid color name or hex format: {color_string}. Using default black.") + else: + # Handle single value (grayscale) - can be int or float + try: + value = float(color_string.strip()) + # Convert to 0-255 range if it's a float between 0-1 + if 0 <= value <= 1: + value = int(value * 255) + else: + value = int(value) + color_list = [value, value, value] + except ValueError: + logging.warning(f"Invalid color format: {color_string}. Using default black.") + + # Clip values to valid range + color_list = np.clip(color_list, 0, 255).tolist() + + return color_list diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/appearance.js b/.disabled/comfyui-kjnodes@nightly/web/js/appearance.js new file mode 100644 index 0000000000000000000000000000000000000000..43a7e74c49bf3324d641c7a7d347bd546eea4953 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/appearance.js @@ -0,0 +1,23 @@ +const { app } = window.comfyAPI.app; + +app.registerExtension({ + name: "KJNodes.appearance", + nodeCreated(node) { + switch (node.comfyClass) { + case "INTConstant": + node.setSize([200, 58]); + node.color = "#1b4669"; + node.bgcolor = "#29699c"; + break; + case "FloatConstant": + node.setSize([200, 58]); + node.color = LGraphCanvas.node_colors.green.color; + node.bgcolor = LGraphCanvas.node_colors.green.bgcolor; + break; + case "ConditioningMultiCombine": + node.color = LGraphCanvas.node_colors.brown.color; + node.bgcolor = LGraphCanvas.node_colors.brown.bgcolor; + break; + } + } +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/canvas_background.js b/.disabled/comfyui-kjnodes@nightly/web/js/canvas_background.js new file mode 100644 index 0000000000000000000000000000000000000000..7413510a4f02d1263220fa8725ea646b8561d7c5 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/canvas_background.js @@ -0,0 +1,476 @@ +const { app } = window.comfyAPI.app; + +// ── Helpers ───────────────────────────────────────────────────────────────── + +/** Linearly mix two hex colors: 0 = pure a, 1 = pure b. */ +function mixColors(a, b, t) { + const parse = (hex) => { + if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`; + return [parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16)]; + }; + const ca = parse(a), cb = parse(b); + const r = Math.round(ca[0] + (cb[0] - ca[0]) * t); + const g = Math.round(ca[1] + (cb[1] - ca[1]) * t); + const bl = Math.round(ca[2] + (cb[2] - ca[2]) * t); + return `#${((1 << 24) | (r << 16) | (g << 8) | bl).toString(16).slice(1)}`; +} + +/** Ensure a color string has a leading '#' (PrimeVue ColorPicker omits it). */ +function asHex(color, fallback = "#000000") { + if (!color) return fallback; + return color.startsWith("#") ? color : `#${color}`; +} + +function getSetting(id, fallback) { + return app.ui.settings.getSettingValue(id) ?? fallback; +} + +// ── Pattern generators ────────────────────────────────────────────────────── +// Each returns an OffscreenCanvas to be used with createPattern("repeat"). +// `size` = tile size, `fg`/`bg` = hex colors, `t` = feature thickness. + +function makeDots(size, fg, bg, t) { + const c = new OffscreenCanvas(size, size); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, size, size); + ctx.fillStyle = fg; + ctx.beginPath(); + ctx.arc(size / 2, size / 2, t * 2, 0, Math.PI * 2); + ctx.fill(); + return c; +} + +function makeGrid(size, fg, bg, t) { + const c = new OffscreenCanvas(size, size); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, size, size); + ctx.fillStyle = fg; + ctx.fillRect(size - t, 0, t, size - t); + ctx.fillRect(0, size - t, size, t); + return c; +} + +function makeCrossDots(size, fg, bg, t) { + const c = new OffscreenCanvas(size, size); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, size, size); + const half = size / 2; + const arm = Math.max(t + 1, size * 0.08); + const ht = t / 2; + ctx.fillStyle = fg; + ctx.fillRect(half - arm, half - ht, arm * 2, t); + ctx.fillRect(half - ht, half - arm, t, arm * 2); + return c; +} + +function makeBlueprint(size, fg, bg, t) { + const c = new OffscreenCanvas(size, size); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, size, size); + const sub = size / 4; + const subColor = mixColors(bg, fg, 0.3); + ctx.fillStyle = subColor; + for (let i = sub; i < size; i += sub) { + ctx.fillRect(i, 0, t, size - t); + ctx.fillRect(0, i, size, t); + } + ctx.fillStyle = fg; + ctx.fillRect(size - t, 0, t, size - t); + ctx.fillRect(0, size - t, size, t); + return c; +} + +function makeIsometric(size, fg, bg, t) { + const w = size; + const h = Math.round(size / 2); + const c = new OffscreenCanvas(w, h); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, w, h); + ctx.strokeStyle = fg; + ctx.lineWidth = t; + ctx.beginPath(); + ctx.moveTo(0, h / 2); + ctx.lineTo(w / 2, 0); + ctx.lineTo(w, h / 2); + ctx.moveTo(0, h / 2); + ctx.lineTo(w / 2, h); + ctx.lineTo(w, h / 2); + ctx.stroke(); + return c; +} + +function makeHexagons(size, fg, bg, t) { + const r = size / 2; + const w = r * 3; + const h = Math.round(r * Math.sqrt(3)); + const c = new OffscreenCanvas(w, h); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, w, h); + ctx.strokeStyle = fg; + ctx.lineWidth = t; + + function hex(cx, cy) { + ctx.beginPath(); + for (let i = 0; i < 6; i++) { + const a = Math.PI / 3 * i; + const px = cx + r * Math.cos(a); + const py = cy + r * Math.sin(a); + if (i === 0) ctx.moveTo(px, py); + else ctx.lineTo(px, py); + } + ctx.closePath(); + ctx.stroke(); + } + + hex(r, h / 2); + hex(r * 2.5, 0); + hex(r * 2.5, h); + return c; +} + +function makeOctagons(size, fg, bg, t) { + const c = new OffscreenCanvas(size, size); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, size, size); + ctx.strokeStyle = fg; + ctx.lineWidth = t; + + const s = size / (1 + Math.SQRT2); + const d = (size - s) / 2; + + ctx.beginPath(); + ctx.moveTo(d, 0); + ctx.lineTo(size - d, 0); + ctx.lineTo(size, d); + ctx.lineTo(size, size - d); + ctx.lineTo(size - d, size); + ctx.lineTo(d, size); + ctx.lineTo(0, size - d); + ctx.lineTo(0, d); + ctx.closePath(); + ctx.stroke(); + return c; +} + +function makeWaves(size, fg, bg, t) { + const c = new OffscreenCanvas(size, size); + const ctx = c.getContext("2d"); + ctx.fillStyle = bg; + ctx.fillRect(0, 0, size, size); + ctx.lineWidth = t; + + const lines = Math.max(2, Math.round(size / 20)); + const spacing = size / lines; + + for (let i = 0; i < lines; i++) { + const blend = 0.1 + (i % 3) * 0.07; + ctx.strokeStyle = mixColors(bg, fg, blend); + const baseY = spacing * i + spacing / 2; + const amp = spacing * (0.15 + (i % 4) * 0.05); + + ctx.beginPath(); + for (let x = 0; x <= size; x++) { + const y = baseY + Math.sin((x / size) * Math.PI * 2 + i * 0.8) * amp; + if (x === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + ctx.stroke(); + } + return c; +} + +function makeCarbonFiber(size, fg, bg, t) { + const cell = Math.max(2, Math.round(size / 4)); + const s = cell * 4; + const c = new OffscreenCanvas(s, s); + const ctx = c.getContext("2d"); + + const dark = bg; + const light = mixColors(bg, fg, 0.2); + const groove = mixColors(bg, fg, 0.07); + + for (let row = 0; row < 4; row++) { + for (let col = 0; col < 4; col++) { + const phase = (col + row) % 4; + ctx.fillStyle = (phase < 2) ? light : dark; + ctx.fillRect(col * cell, row * cell, cell, cell); + } + } + + ctx.fillStyle = groove; + const gt = Math.max(1, Math.round(t)); + for (let i = 1; i < 4; i++) { + ctx.fillRect(0, i * cell, s, gt); + ctx.fillRect(i * cell, 0, gt, s); + } + return c; +} + + +const PATTERNS = { + default: null, + none: null, + dots: makeDots, + grid: makeGrid, + "cross dots": makeCrossDots, + blueprint: makeBlueprint, + isometric: makeIsometric, + hexagons: makeHexagons, + octagons: makeOctagons, + waves: makeWaves, + "carbon fiber": makeCarbonFiber, +}; + +// ── State ─────────────────────────────────────────────────────────────────── + +let currentType = "default"; +let currentFg = "#444444"; +let currentBg = "#212121"; +let currentSize = 32; +let currentThickness = 2; +let dirty = true; + +function invalidateCache() { + dirty = true; + app.canvas?.setDirty(true, true); +} + + + +function readSettings() { + currentType = getSetting("KJNodes.canvasBg.pattern", "default"); + currentFg = asHex(getSetting("KJNodes.canvasBg.patternColor", "#444444")); + currentBg = asHex(getSetting("KJNodes.canvasBg.bgColor", "#212121")); + currentSize = getSetting("KJNodes.canvasBg.scale", 32); + currentThickness = getSetting("KJNodes.canvasBg.thickness", 2); +} + +// ── Commands ──────────────────────────────────────────────────────────────── + +const patternCommands = Object.keys(PATTERNS).map((key) => ({ + id: `KJNodes.canvasBg.setPattern.${key}`, + label: key.charAt(0).toUpperCase() + key.slice(1), + menubarLabel: key.charAt(0).toUpperCase() + key.slice(1), + function: () => { + app.ui.settings.setSettingValue("KJNodes.canvasBg.pattern", key); + }, + active: () => getSetting("KJNodes.canvasBg.pattern", "default") === key, +})); + +// Single source of truth for slider bounds — commands reference these same objects. +const SCALE_ATTRS = { min: 8, max: 512, step: 4 }; +const THICKNESS_ATTRS = { min: 0.5, max: 20, step: 0.5 }; + +function stepSetting(id, fallback, attrs, direction) { + const cur = getSetting(id, fallback); + const next = cur + attrs.step * direction; + if (next >= attrs.min && next <= attrs.max) { + app.ui.settings.setSettingValue(id, next); + } +} + +const scaleCommands = [ + { + id: "KJNodes.canvasBg.increaseScale", + label: "Increase pattern scale", + menubarLabel: "Increase scale", + function: () => stepSetting("KJNodes.canvasBg.scale", 32, SCALE_ATTRS, 1), + active: () => false, + }, + { + id: "KJNodes.canvasBg.decreaseScale", + label: "Decrease pattern scale", + menubarLabel: "Decrease scale", + function: () => stepSetting("KJNodes.canvasBg.scale", 32, SCALE_ATTRS, -1), + active: () => false, + }, +]; + +const thicknessCommands = [ + { + id: "KJNodes.canvasBg.increaseThickness", + label: "Increase pattern thickness", + menubarLabel: "Increase thickness", + function: () => stepSetting("KJNodes.canvasBg.thickness", 2, THICKNESS_ATTRS, 1), + active: () => false, + }, + { + id: "KJNodes.canvasBg.decreaseThickness", + label: "Decrease pattern thickness", + menubarLabel: "Decrease thickness", + function: () => stepSetting("KJNodes.canvasBg.thickness", 2, THICKNESS_ATTRS, -1), + active: () => false, + }, +]; + +// ── Extension ─────────────────────────────────────────────────────────────── + +app.registerExtension({ + name: "KJNodes.CanvasBackground", + + commands: [...patternCommands, ...scaleCommands, ...thicknessCommands], + + menuCommands: [ + { + path: ["KJNodes", "Canvas Background"], + commands: patternCommands.map((c) => c.id), + }, + { + path: ["KJNodes", "Canvas Background"], + commands: scaleCommands.map((c) => c.id), + }, + { + path: ["KJNodes", "Canvas Background"], + commands: thicknessCommands.map((c) => c.id), + }, + ], + + settings: [ + { + id: "KJNodes.canvasBg.pattern", + name: "Background pattern", + category: ["KJNodes", "Canvas Background", "Pattern"], + tooltip: "Choose a background pattern for the node graph canvas. 'default' uses LiteGraph's built-in dot grid. 'none' disables all background drawing.", + type: "combo", + defaultValue: "default", + options: Object.keys(PATTERNS), + onChange: invalidateCache, + }, + { + id: "KJNodes.canvasBg.patternColor", + name: "Pattern color", + category: ["KJNodes", "Canvas Background", "Pattern color"], + tooltip: "Foreground color of the pattern", + type: "color", + defaultValue: "#444444", + onChange: invalidateCache, + }, + { + id: "KJNodes.canvasBg.bgColor", + name: "Background color", + category: ["KJNodes", "Canvas Background", "Background color"], + tooltip: "Background fill color behind the pattern", + type: "color", + defaultValue: "#212121", + onChange: invalidateCache, + }, + { + id: "KJNodes.canvasBg.scale", + name: "Pattern scale", + category: ["KJNodes", "Canvas Background", "Pattern scale"], + tooltip: "Size of one pattern tile in pixels", + type: "slider", + defaultValue: 32, + attrs: SCALE_ATTRS, + onChange: invalidateCache, + }, + { + id: "KJNodes.canvasBg.thickness", + name: "Pattern thickness", + category: ["KJNodes", "Canvas Background", "Pattern thickness"], + tooltip: "Thickness of lines and size of dots in pixels", + type: "slider", + defaultValue: 2, + attrs: THICKNESS_ATTRS, + onChange: invalidateCache, + }, + ], + + setup() { + const canvas = app.canvas; + if (!canvas) return; + + let patternToken = null; // null = default, "" = none, string = custom + // Snapshot palette values lazily on first override so we capture post-palette state + let origBackgroundImage = null; + let origClearBgColor = null; + let origsCaptured = false; + + function captureOriginals() { + if (origsCaptured) return; + origsCaptured = true; + origBackgroundImage = canvas.background_image; + origClearBgColor = canvas.clear_background_color; + } + + function applyToLiteGraph() { + if (!dirty) return; + dirty = false; + readSettings(); + + // If ComfyUI's own background image setting is active, don't interfere + if (getSetting("Comfy.Canvas.BackgroundImage", "")) { + patternToken = null; + return; + } + + if (currentType === "default") { + if (origsCaptured) { + canvas.background_image = origBackgroundImage; + canvas.clear_background_color = origClearBgColor; + canvas._pattern = undefined; + canvas._bg_img = undefined; + } + patternToken = null; + canvas.setDirty(true, true); + return; + } + + // Capture originals before we overwrite them for the first time + captureOriginals(); + + if (currentType === "none") { + canvas.background_image = ""; + canvas.clear_background_color = currentBg; + canvas._pattern = undefined; + canvas._bg_img = undefined; + patternToken = ""; + canvas.setDirty(true, true); + return; + } + + // Generate tile as OffscreenCanvas — passed directly to LiteGraph's + // createPattern which accepts any CanvasImageSource. + const gen = PATTERNS[currentType]; + if (!gen) return; + + const tile = gen(currentSize, currentFg, currentBg, currentThickness); + patternToken = `kjbg_${currentType}_${currentSize}_${currentThickness}_${currentFg}_${currentBg}`; + tile.name = patternToken; + + canvas.background_image = patternToken; + canvas.clear_background_color = currentBg; + canvas._bg_img = tile; + canvas._pattern = undefined; + canvas.setDirty(true, true); + } + + applyToLiteGraph(); + + // Enforce our values if palette service overwrites them. + // Returns false — LiteGraph's native code does all drawing. + const origCallback = canvas.onRenderBackground; + canvas.onRenderBackground = function (cvs, ctx) { + if (origCallback) { + const result = origCallback.call(this, cvs, ctx); + if (result) return true; + } + + applyToLiteGraph(); + + // If palette service overwrote our values, mark dirty for next frame. + if (!dirty && patternToken !== null && this.background_image !== patternToken) { + dirty = true; + } + + return false; + }; + }, +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/contextmenu.js b/.disabled/comfyui-kjnodes@nightly/web/js/contextmenu.js new file mode 100644 index 0000000000000000000000000000000000000000..e311681eda8cb1dba43d44e034d165aac4ddcb85 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/contextmenu.js @@ -0,0 +1,256 @@ +const { app } = window.comfyAPI.app; + +function addNode(name, nextTo, options) { + options = { side: "left", select: true, shiftY: 0, shiftX: 0, ...(options || {}) }; + const node = LiteGraph.createNode(name); + const graph = app.canvas?.graph || app.graph; + graph.add(node); + + node.pos = [ + options.side === "left" ? nextTo.pos[0] - (node.size[0] + options.offset): nextTo.pos[0] + nextTo.size[0] + options.offset, + nextTo.pos[1] + options.shiftY, + ]; + + // Automatically connect nodes + if (options.side === "left") { + // New node on left: connect new node's first output to nextTo's first free input + if (node.outputs && node.outputs.length > 0 && nextTo.inputs && nextTo.inputs.length > 0) { + for (let i = 0; i < nextTo.inputs.length; i++) { + if (!nextTo.inputs[i].link) { + node.pos[1] += i * (node.size[1] + 32); + node.connect(0, nextTo, i); + break; + } + } + } + } else { + // New node on right: connect nextTo's first free output to new node's first free input + if (nextTo.outputs && nextTo.outputs.length > 0 && node.inputs && node.inputs.length > 0) { + for (let o = 0; o < nextTo.outputs.length; o++) { + if (!nextTo.outputs[o].links || nextTo.outputs[o].links.length === 0) { + // Offset vertically by slot index so multiple Set nodes don't overlap + node.pos[1] += o * (node.size[1] + 32); + for (let i = 0; i < node.inputs.length; i++) { + if (!node.inputs[i].link) { + nextTo.connect(o, node, i); + break; + } + } + break; + } + } + } + } + + if (options.select) { + app.canvas.selectNode(node, false); + } + return node; +} + +// Expose addNode for use in setgetnodes.js +window.kjNodes = window.kjNodes || {}; +window.kjNodes.addNode = addNode; + +app.registerExtension({ + name: "KJNodes.Contextmenu", + settings: [ + { + id: "KJNodes.nodeAutoColor", + name: "Auto-color nodes", + category: ["KJNodes", "Set & Get", "Auto-color nodes"], + tooltip: "Automatically color Set/Get nodes based on their connection type", + type: "boolean", + defaultValue: true, + }, + { + id: "KJNodes.disablePrefix", + name: "Disable Set_/Get_ prefix", + category: ["KJNodes", "Set & Get", "Disable Set_/Get_ prefix"], + tooltip: "Prevents automatically adding Set_ and Get_ prefixes to node titles", + defaultValue: false, + type: "boolean", + }, + { + id: "KJNodes.helpPopup", + name: "Help popups", + category: ["KJNodes", "General", "Help popups"], + tooltip: "Show help popups when hovering over KJNodes", + defaultValue: true, + type: "boolean", + }, + { + id: "KJNodes.shiftMiddleClickSetGet", + name: "Shift+middle-click creates Set/Get", + category: ["KJNodes", "Set & Get", "Shift+middle-click creates Set/Get"], + tooltip: "Shift+middle-click on a slot creates a connected SetNode (output) or GetNode (input) instead of Reroute", + type: "boolean", + defaultValue: true, + }, + { + id: "KJNodes.middleClickSetGet", + name: "Middle-click creates Set/Get", + category: ["KJNodes", "Set & Get", "Middle-click creates Set/Get"], + tooltip: "Middle-click on a slot creates Set/Get instead of Reroute (overrides core behavior)", + type: "boolean", + defaultValue: false, + }, + { + id: "KJNodes.showSetGetInConnectionMenu", + name: "Show Set/Get in connection menu", + category: ["KJNodes", "Set & Get", "Show Set/Get in connection menu"], + tooltip: "Add Set/Get entries to the slot connection menu (next to Add Reroute)", + type: "boolean", + defaultValue: true, + }, + ], + getNodeMenuItems(node) { + if (!node.inputs || node.inputs.length === 0) return []; + const selectedForConvert = window.kjNodes.snapshotSelectedNodes(node); + return [ + { + content: "Add GetNode", + callback: () => { addNode("GetNode", node, { side: "left", offset: 30 }); } + }, + { + content: "Add SetNode", + callback: () => { addNode("SetNode", node, { side: "right", offset: 30 }); } + }, + { + content: "Add PreviewAsTextNode", + callback: () => { addNode("PreviewAny", node, { side: "right", offset: 30 }); } + }, + { + content: "Convert all outputs to Set/Get", + callback: () => { + for (const n of selectedForConvert) window.kjNodes.convertOutputsToSetGet(node.graph, n); + } + }, + ]; + }, + async setup(app) { + // Patch showConnectionMenu to inject "Add SetNode" / "Add GetNode" entries. + const origShowConnectionMenu = app.canvas.showConnectionMenu.bind(app.canvas); + app.canvas.showConnectionMenu = function(optPass) { + if (!(app.ui.settings.getSettingValue("KJNodes.showSetGetInConnectionMenu") ?? true)) return origShowConnectionMenu(optPass); + + const isFrom = optPass.nodeFrom && optPass.slotFrom; + const nodeType = isFrom ? "SetNode" : "GetNode"; + const label = isFrom ? "Add SetNode" : "Add GetNode"; + + // Capture original canvas position from the event + const origEvent = optPass.e; + + const OrigCM = LiteGraph.ContextMenu; + let interceptActive = true; + LiteGraph.ContextMenu = function(options, menuOpts) { + // Always restore before doing anything else + LiteGraph.ContextMenu = OrigCM; + + // If another caller triggered this, pass through untouched + if (!interceptActive) return new OrigCM(options, menuOpts); + interceptActive = false; + + // Insert after "Add Reroute" + const idx = options.indexOf("Add Reroute"); + if (idx !== -1) options.splice(idx + 1, 0, label); + + // Wrap callback to handle our entry + const origCb = menuOpts.callback; + menuOpts.callback = function(v, cbOpts, e) { + if (v === label) { + const canvas = app.canvas; + const graph = canvas.graph || app.graph; + const node = LiteGraph.createNode(nodeType); + if (!node || !graph) return; + + // Use the original drag event's canvas position + node.pos = [origEvent?.canvasX ?? 0, origEvent?.canvasY ?? 0]; + graph.add(node); + + if (isFrom && optPass.nodeFrom) { + const slotObj = optPass.slotFrom; + const slotIdx = typeof slotObj === 'number' + ? slotObj + : optPass.nodeFrom.findOutputSlot(slotObj.name); + optPass.nodeFrom.connect(slotIdx, node, 0); + } else if (optPass.nodeTo) { + const slotObj = optPass.slotTo; + const slotIdx = typeof slotObj === 'number' + ? slotObj + : optPass.nodeTo.findInputSlot(slotObj.name); + node.connect(0, optPass.nodeTo, slotIdx); + } + graph.change(); + canvas.setDirty(true, true); + return; + } + return origCb?.call(this, v, cbOpts, e); + }; + + return new OrigCM(options, menuOpts); + }; + LiteGraph.ContextMenu.prototype = OrigCM.prototype; + + const result = origShowConnectionMenu(optPass); + // Safety: ensure restoration even if origShowConnectionMenu didn't trigger the constructor + LiteGraph.ContextMenu = OrigCM; + interceptActive = false; + return result; + }; + + // Middle-click Set/Get: let the core do slot hit detection, then intercept + // createDefaultNodeForSlot to create Set/Get instead of reroute. + let _fromMiddleClick = false; + let _lastMiddleClickShift = false; + const origProcessMiddle = LGraphCanvas.prototype._processMiddleButton; + LGraphCanvas.prototype._processMiddleButton = function(e, node) { + _fromMiddleClick = true; + _lastMiddleClickShift = !!e.shiftKey; + const wantSetGet = _lastMiddleClickShift + ? app.ui.settings.getSettingValue("KJNodes.shiftMiddleClickSetGet") ?? true + : app.ui.settings.getSettingValue("KJNodes.middleClickSetGet") ?? false; + const saved = LiteGraph.middle_click_slot_add_default_node; + if (wantSetGet) { + LiteGraph.middle_click_slot_add_default_node = true; + } else { + // Workaround: core slotDefaults.init() resets this flag to true + const coreSetting = app.ui.settings.getSettingValue("Comfy.Node.MiddleClickRerouteNode"); + if (coreSetting === false) LiteGraph.middle_click_slot_add_default_node = false; + } + const result = origProcessMiddle.call(this, e, node); + LiteGraph.middle_click_slot_add_default_node = saved; + return result; + }; + const origCreateDefault = LGraphCanvas.prototype.createDefaultNodeForSlot; + LGraphCanvas.prototype.createDefaultNodeForSlot = function(optPass) { + if (!_fromMiddleClick) return origCreateDefault.call(this, optPass); + _fromMiddleClick = false; + const wantSetGet = _lastMiddleClickShift + ? app.ui.settings.getSettingValue("KJNodes.shiftMiddleClickSetGet") ?? true + : app.ui.settings.getSettingValue("KJNodes.middleClickSetGet") ?? false; + if (!wantSetGet) return origCreateDefault.call(this, optPass); + + const isFrom = optPass.nodeFrom && optPass.slotFrom !== null; + const sourceNode = isFrom ? optPass.nodeFrom : optPass.nodeTo; + const slotIndex = isFrom ? optPass.slotFrom : optPass.slotTo; + if (!sourceNode || slotIndex == null) return origCreateDefault.call(this, optPass); + const graph = this.graph || app.graph; + if (!graph) return origCreateDefault.call(this, optPass); + + const newNode = LiteGraph.createNode(isFrom ? "SetNode" : "GetNode"); + if (!newNode) return false; + const bounding = sourceNode.getBounding(); + newNode.pos = [ + isFrom ? bounding[0] + bounding[2] + 30 : bounding[0] - 200, + optPass.position?.[1] ?? bounding[1] + ]; + graph.add(newNode); + if (isFrom) sourceNode.connect(slotIndex, newNode, 0); + else newNode.connect(0, sourceNode, slotIndex); + graph.change(); + this.setDirty(true, true); + return true; + }; +} +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/editors/editor_base.js b/.disabled/comfyui-kjnodes@nightly/web/js/editors/editor_base.js new file mode 100644 index 0000000000000000000000000000000000000000..c9d55b5ebdf757ce400df71bd14e4d4bf6c8d785 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/editors/editor_base.js @@ -0,0 +1,707 @@ +import { addMiddleClickPan, chainCallback, makeUUID, watchImageInputs } from '../utility.js'; + +export function createEditorStylesheet(id, className) { + let styleTag = document.head.querySelector(`#${id}`) + if (!styleTag) { + styleTag = document.createElement('style') + styleTag.type = 'text/css' + styleTag.id = id + styleTag.innerHTML = ` + .${className} { + position: absolute; + font: 12px monospace; + line-height: 1.5em; + padding: 10px; + z-index: 0; + overflow: hidden; + } + .${className} canvas { + position: relative; + z-index: 2; + } + ` + document.head.appendChild(styleTag) + } +} + +function styleMenuItem(menuItem) { + menuItem.style.display = "block"; + menuItem.style.padding = "5px"; + menuItem.style.color = "#FFF"; + menuItem.style.fontFamily = "Arial, sans-serif"; + menuItem.style.fontSize = "16px"; + menuItem.style.textDecoration = "none"; + menuItem.style.marginBottom = "5px"; +} + +function createMenuItem(id, textContent) { + let menuItem = document.createElement("a"); + menuItem.href = "#"; + menuItem.dataset.menuId = id; + menuItem.textContent = textContent; + styleMenuItem(menuItem); + return menuItem; +} + +function setupMenuItems(contextMenu, menuItems) { + menuItems.forEach(mi => { + mi.addEventListener('mouseover', function () { this.style.backgroundColor = "gray"; }); + mi.addEventListener('mouseout', function () { this.style.backgroundColor = "#202020"; }); + contextMenu.appendChild(mi); + }); +} + +export function createContextMenuElement(className) { + const menu = document.createElement("div"); + if (className) menu.className = className; + menu.id = `context-menu-${Math.random().toString(36).slice(2, 10)}`; + menu.style.display = "none"; + menu.style.position = "absolute"; + menu.style.backgroundColor = "#202020"; + menu.style.minWidth = "100px"; + menu.style.boxShadow = "0px 8px 16px 0px rgba(0,0,0,0.2)"; + menu.style.zIndex = "100"; + menu.style.padding = "5px"; + return menu; +} + +// ─── Base Editor Canvas ─── + +const maxDisplayDim = 1024; + +export class BaseEditorCanvas { + constructor(context, reset = false) { + this.node = context; + this.reset = reset; + this.bgImage = null; + this.margin = 14; + this.dragIndex = -1; + this.dragType = null; + this.dragOffset = null; + + this._uploadGeneration = 0; + } + + // ─── Shared Methods ─── + + setNodeWidth(width) { + this.node.setSize([width, this.node.size[1]]); + const nodeEl = document.querySelector(`[data-node-id="${this.node.id}"]`); + if (nodeEl) nodeEl.style.setProperty('--node-width', `${width}px`); + } + + // Scale factors: coord space → canvas space + get scaleX() { return this.width / this.coordWidth; } + get scaleY() { return this.height / this.coordHeight; } + + // Returns mouse position in coord space + getLocalMouse(e) { + const rect = this.canvas.getBoundingClientRect(); + const canvasScaleX = this.canvas.width / rect.width; + const canvasScaleY = this.canvas.height / rect.height; + const canvasX = (e.clientX - rect.left) * canvasScaleX - this.margin; + const canvasY = (e.clientY - rect.top) * canvasScaleY - this.margin; + return { + x: canvasX / this.scaleX, + y: canvasY / this.scaleY + }; + } + + // Clamp to coord space + clamp(x, y) { + return { + x: Math.max(0, Math.min(this.coordWidth, x)), + y: Math.max(0, Math.min(this.coordHeight, y)) + }; + } + + // ─── Canvas Setup ─── + + createCanvas(parentElement) { + this.canvas = document.createElement('canvas'); + this.canvas.width = this.width + this.margin * 2; + this.canvas.height = this.height + this.margin * 2; + this.ctx = this.canvas.getContext('2d'); + parentElement.appendChild(this.canvas); + } + + resizeCanvas() { + this.canvas.width = this.width + this.margin * 2; + this.canvas.height = this.height + this.margin * 2; + } + + // ─── Event Listeners ─── + + setupEventListeners() { + this._onDragMove = (e) => this.onMouseMove(e); + this._onDragEnd = (e) => this.onMouseUp(e); + this._removeMiddleClickPan = addMiddleClickPan(this.canvas); + this._onCanvasPointerDown = (e) => { e.stopPropagation(); this.onMouseDown(e); }; + this._onCanvasPointerMove = (e) => this.onMouseMove(e); + this._onCanvasContextMenu = (e) => { e.preventDefault(); e.stopPropagation(); }; + this.canvas.addEventListener('pointerdown', this._onCanvasPointerDown); + this.canvas.addEventListener('pointermove', this._onCanvasPointerMove); + this.canvas.addEventListener('contextmenu', this._onCanvasContextMenu); + } + + removeEventListeners() { + if (this.canvas) { + this.canvas.removeEventListener('pointerdown', this._onCanvasPointerDown); + this.canvas.removeEventListener('pointermove', this._onCanvasPointerMove); + this.canvas.removeEventListener('pointermove', this._onDragMove); + this.canvas.removeEventListener('pointerup', this._onDragEnd); + this.canvas.removeEventListener('contextmenu', this._onCanvasContextMenu); + } + document.removeEventListener('pointermove', this._onDragMove); + document.removeEventListener('pointerup', this._onDragEnd); + if (this._removeMiddleClickPan) this._removeMiddleClickPan(); + } + + startDocumentDrag(e) { + if (e && e.pointerId !== undefined) { + this.canvas.setPointerCapture(e.pointerId); + this._capturedPointerId = e.pointerId; + // With pointer capture, events fire on the canvas, not document + this.canvas.addEventListener('pointermove', this._onDragMove); + this.canvas.addEventListener('pointerup', this._onDragEnd); + } else { + document.addEventListener('pointermove', this._onDragMove); + document.addEventListener('pointerup', this._onDragEnd); + } + } + + endDrag() { + this.dragIndex = -1; + this.dragType = null; + this.dragOffset = null; + this.canvas.style.cursor = 'default'; + if (this._capturedPointerId !== undefined) { + try { this.canvas.releasePointerCapture(this._capturedPointerId); } catch (_) {} + this._capturedPointerId = undefined; + this.canvas.removeEventListener('pointermove', this._onDragMove); + this.canvas.removeEventListener('pointerup', this._onDragEnd); + } else { + document.removeEventListener('pointermove', this._onDragMove); + document.removeEventListener('pointerup', this._onDragEnd); + } + } + + // ─── Render Batching ─── + + render() { + if (this._renderPending) return; + this._renderPending = true; + requestAnimationFrame(() => { + this._renderPending = false; + this._render(); + }); + } + + // Subclasses must implement _render() + + // ─── Common Render Helpers ─── + + // Convert coord-space point to canvas-space pixel + toCanvas(x, y) { + return { x: x * this.scaleX, y: y * this.scaleY }; + } + + // Call at start of _render() — clears and draws background + beginRender() { + const ctx = this.ctx; + ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + ctx.save(); + ctx.translate(this.margin, this.margin); + ctx.fillStyle = '#222'; + ctx.fillRect(0, 0, this.width, this.height); + ctx.strokeStyle = 'gray'; + ctx.lineWidth = 2; + ctx.strokeRect(0, 0, this.width, this.height); + if (this.bgImage) { + ctx.drawImage(this.bgImage, 0, 0, this.width, this.height); + } + } + + endRender() { + this.ctx.restore(); + } + + // ─── Image Handling ─── + + handleImageLoad = (img, downscaledImg) => { + // Set coord space to image dimensions + this.coordWidth = img.width; + this.coordHeight = img.height; + this.widthWidget.value = img.width; + this.heightWidget.value = img.height; + this.onImageResize?.(img); + + // Cap display size, preserving aspect ratio + let displayW = img.width, displayH = img.height; + if (displayW > maxDisplayDim || displayH > maxDisplayDim) { + const scale = maxDisplayDim / Math.max(displayW, displayH); + displayW = Math.round(displayW * scale); + displayH = Math.round(displayH * scale); + } + + if (displayW !== this.width || displayH !== this.height) { + this.width = displayW; + this.height = displayH; + this.resizeCanvas(); + + if (displayW > 256) this.setNodeWidth(displayW + 45); + this.onSizeChanged(); + if (this.node.graph) { + try { this.node.arrange?.(); } catch (_) {} + this.node.graph.setDirtyCanvas(true, true); + } + } + + // Use downscaled image if available to avoid holding full-res in memory + this.bgImage = downscaledImg || img; + this.render(); + this.onDataChanged(); + }; + + // resizeCanvas: if true (default), resize editor canvas to match image. + // If false, just store the image and update the background without resizing. + processImage = (img, { resize = true } = {}) => { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + let width = img.width, height = img.height; + if (width > maxDisplayDim || height > maxDisplayDim) { + const scale = maxDisplayDim / Math.max(width, height); + width = Math.round(width * scale); + height = Math.round(height * scale); + } + canvas.width = width; + canvas.height = height; + ctx.drawImage(img, 0, 0, width, height); + + const { app } = window.comfyAPI.app; + const embed = app.ui.settings.getSettingValue("KJNodes.editors.embedBackgroundImage") ?? false; + + // Use the downscaled canvas directly as bgImage — drawImage accepts canvas elements, + // avoids a data URL round-trip, and is immediately available (no async decode). + const onStored = () => { + if (resize) { + this.handleImageLoad(img, canvas); + } else { + this.bgImage = canvas; + this.render(); + } + }; + + const gen = ++this._uploadGeneration; + if (embed) { + const base64String = canvas.toDataURL('image/webp', 0.5).replace(/^data:.+?,/, ''); + if (gen !== this._uploadGeneration) return; + this.node.properties.imgData = { type: 'image/webp', base64: base64String }; + onStored(); + } else { + canvas.toBlob((blob) => { + if (gen !== this._uploadGeneration) return; + const filename = `editor_bg_${this.node.id}_${Date.now()}.webp`; + const formData = new FormData(); + formData.append('image', blob, filename); + formData.append('type', 'temp'); + formData.append('overwrite', 'true'); + fetch('/upload/image', { method: 'POST', body: formData }) + .then(r => r.json()) + .then(result => { + if (gen !== this._uploadGeneration) return; + this.node.properties.imgData = { type: 'temp', filename: result.name }; + onStored(); + }) + .catch(e => console.error("Failed to upload editor background:", e)); + }, 'image/webp', 0.5); + } + }; + + handleImageFile = (file) => { + const url = URL.createObjectURL(file); + const img = new Image(); + img.onload = () => { URL.revokeObjectURL(url); this.processImage(img); }; + img.onerror = () => URL.revokeObjectURL(url); + img.src = url; + }; + + refreshBackgroundImage = () => { + const imgData = this.node.properties.imgData; + if (!imgData) return; + + const img = new Image(); + img.onerror = (e) => console.error("Background image failed to load:", e); + img.onload = () => { + // Just set the background — don't resize canvas, widget values are already correct from serialization + this.bgImage = img; + this.render(); + }; + + if (imgData.base64) { + const mimeType = imgData.type || 'image/png'; + img.src = `data:${mimeType};base64,${imgData.base64}`; + } else if (imgData.filename) { + img.src = `/view?filename=${encodeURIComponent(imgData.filename)}&type=temp&no-cache=${Date.now()}`; + } + }; + + // ─── Context Menu Helpers ─── + + // Set up document-level listeners for context menu behavior + setupContextMenuListeners(editorIdPrefix) { + this._onContextMenu = (e) => { + if (e.target.closest(`#${editorIdPrefix}-${this.node.uuid}`) || + this.node.contextMenu.contains(e.target)) { + e.preventDefault(); + } + }; + this._onDocClick = (e) => { + if (!this.node.contextMenu.contains(e.target)) { + this.node.contextMenu.style.display = 'none'; + } + }; + document.addEventListener('contextmenu', this._onContextMenu); + document.addEventListener('click', this._onDocClick); + } + + // Clean up previous editor instance + cleanupPreviousEditor(context) { + if (context.editor) { + context.editor.destroy(); + } + } + + // Full cleanup — override in subclass to add additional cleanup + destroy() { + this._uploadGeneration++; // Invalidate any pending async image uploads + this.removeEventListeners(); + if (this._onContextMenu) document.removeEventListener('contextmenu', this._onContextMenu); + if (this._onDocClick) document.removeEventListener('click', this._onDocClick); + if (this._onKeyUp) document.removeEventListener('keyup', this._onKeyUp); + } + + // Common menu actions + openImageFilePicker() { + const fileInput = document.createElement('input'); + fileInput.type = 'file'; + fileInput.accept = 'image/*'; + fileInput.addEventListener('change', (event) => { + const file = event.target.files[0]; + if (file) this.handleImageFile(file); + }); + fileInput.click(); + } + + clearBackgroundImage() { + this.bgImage = null; + this.node.properties.imgData = null; + this.render(); + } + + // Find a widget by name on the node + findWidget(name) { + const w = this.node.widgets.find(w => w.name === name); + if (!w) console.warn(`${this.constructor.name}: widget "${name}" not found`); + return w; + } + + // Show context menu at mouse position + showContextMenu(e) { + this._updateMenuToggleStates(); + const menu = this.node.contextMenu; + menu.style.display = 'block'; + menu.style.left = `${e.clientX}px`; + menu.style.top = `${e.clientY}px`; + // Adjust if menu overflows viewport + const rect = menu.getBoundingClientRect(); + if (rect.right > window.innerWidth) menu.style.left = `${Math.max(0, e.clientX - rect.width)}px`; + if (rect.bottom > window.innerHeight) menu.style.top = `${Math.max(0, e.clientY - rect.height)}px`; + } + + // ─── Width/Height Resize ─── + + setupSizeCallbacks() { + this.widthWidget.callback = () => { + const oldCoordW = this.coordWidth; + this.coordWidth = this.widthWidget.value; + this.onCoordSpaceResized(oldCoordW, this.coordHeight); + this.render(); + this.onDataChanged(); + }; + this.heightWidget.callback = () => { + const oldCoordH = this.coordHeight; + this.coordHeight = this.heightWidget.value; + this.onCoordSpaceResized(this.coordWidth, oldCoordH); + this.render(); + this.onDataChanged(); + }; + } + + // ─── imgData persistence ─── + // Call once from onNodeCreated to ensure imgData survives save/reload + static setupImgDataPersistence(node) { + chainCallback(node, "onSerialize", function (o) { + if (this.properties.imgData && o.properties) { + o.properties.imgData = this.properties.imgData; + } + }); + chainCallback(node, "onConfigure", function (info) { + if (info?.properties?.imgData) { + this.properties.imgData = info.properties.imgData; + } + }); + } + + // ─── Node registration helper ─── + // Call from onNodeCreated to set up the common editor scaffolding. + // config: { editorClass, editorKey, heightKey, className, menuItems, hiddenWidgets, initialSize, extraProperties } + // editorClass: the editor constructor (e.g. SplineEditor) + // editorKey: node property name for the DOM widget (e.g. 'splineEditor') + // heightKey: node property name for editor height (e.g. 'splineEditorHeight') + // className: CSS class for the editor container + // menuItems: { id: { label, action(editor), toggle?(editor) }, ... } — context menu definition + // menuClassName: optional CSS class for the context menu + // hiddenWidgets: widget names to hide + // initialSize: [width, height] for the node + // extraProperties: array of [name, default, type] to register via addProperty on first create + static setupNode(node, nodeData, config) { + const { editorClass, editorKey, heightKey, className, menuItems, + menuClassName, hiddenWidgets, initialSize, extraProperties } = config; + + if (!node.properties) node.properties = {}; + if (node.properties.imgData === undefined) node.properties.imgData = null; + + // File handling — set up once per node, delegate to current editor + node.pasteFile = (file) => { + if (node.editor && file.type.startsWith("image/")) { + node.editor.handleImageFile(file); + return true; + } + return false; + }; + node.onDragOver = (e) => { + if (node.editor && e.dataTransfer && e.dataTransfer.items) { + return [...e.dataTransfer.items].some(f => f.kind === "file" && f.type.startsWith("image/")); + } + return false; + }; + node.onDragDrop = (e) => { + if (!node.editor) return false; + let handled = false; + for (const file of e.dataTransfer.files) { + if (file.type.startsWith("image/")) { + node.editor.handleImageFile(file); + handled = true; + } + } + return handled; + }; + + for (const name of (hiddenWidgets || [])) { + const w = node.widgets.find(w => w.name === name); + if (w) w.hidden = true; + } + + const element = document.createElement("div"); + node.uuid = makeUUID(); + element.id = `${className}-${node.uuid}`; + node.previewMediaType = 'image'; + + node[editorKey] = node.addDOMWidget(nodeData.name, `${editorClass.name}Widget`, element, { + serialize: false, hideOnZoom: false, + getMinHeight: () => node[heightKey] || 550, + getMaxHeight: () => node[heightKey] || 550, + getHeight: () => node[heightKey] || 550, + }); + node[heightKey] = 550; + + node.contextMenu = createContextMenuElement(menuClassName); + node._menuDef = menuItems; + const menuEls = Object.entries(menuItems).map(([id, def]) => createMenuItem(id, def.label || id)); + setupMenuItems(node.contextMenu, menuEls); + document.body.appendChild(node.contextMenu); + + node.addWidget("button", "Reset canvas", null, () => { + try { node.editor = new editorClass(node, true); } + catch (error) { console.error(`Error creating ${editorClass.name}:`, error); } + }); + + node.setSize(initialSize); + node[editorKey].parentEl = document.createElement("div"); + node[editorKey].parentEl.className = className; + node[editorKey].parentEl.id = `${className}-${node.uuid}`; + element.appendChild(node[editorKey].parentEl); + + // Auto-create for new nodes; onConfigure cancels this for saved workflows + node._autoCreatePending = setTimeout(() => { + if (!node.editor) { + try { + node.editor = new editorClass(node); + for (const [name, value, type] of (extraProperties || [])) { + node.addProperty(name, value, type); + } + } catch (error) { console.error(`Error creating ${editorClass.name}:`, error); } + } + }, 0); + + BaseEditorCanvas.setupImgDataPersistence(node); + + chainCallback(node, "onResize", function () { + const editor = this.editor; + if (!editor) return; + const newWidth = Math.max(64, Math.round(this.size[0] - 45)); + if (newWidth === editor.width) return; + + // Only change display size — coord space stays the same + editor.width = newWidth; + editor.height = Math.round(newWidth * (editor.coordHeight / editor.coordWidth)); + + editor.resizeCanvas(); + editor.onSizeChanged(); + editor.render(); + }); + + chainCallback(node, "onConfigure", function () { + clearTimeout(this._autoCreatePending); + try { this.editor = new editorClass(this); } + catch (error) { console.error(`Error configuring ${editorClass.name}:`, error); } + // Allow watchImageInputs to operate only after configure + a delay, + // so refreshBackgroundImage has time to restore the saved image first. + node._bgWatchReady = false; + setTimeout(() => { node._bgWatchReady = true; }, 500); + }); + + chainCallback(node, "onExecuted", function (message) { + let bg_image = message["bg_image"]; + if (Array.isArray(bg_image)) bg_image = bg_image[0]; + if (bg_image) { + const img = new Image(); + img.src = `data:image/jpeg;base64,${bg_image}`; + img.onload = () => { + if (this.editor) this.editor.processImage(img); + }; + } + }); + + // Load background image from connected source node (LoadImage, VHS, etc.) + // _bgWatchReady is false during reload until the editor has restored its saved background. + // _bgFromConnectedSource tracks whether the current bg came from a connection (vs execution/paste). + node._bgFromConnectedSource = false; + node._bgWatchReady = true; // true for new nodes, set false during onConfigure + watchImageInputs(node, "bg_image", (sources) => { + if (!node.editor || !node._bgWatchReady) return; + const source = sources[0]; + if (source && !source.isVideo) { + node._bgFromConnectedSource = true; + const img = new Image(); + img.crossOrigin = "anonymous"; + img.onerror = (e) => console.error("[Editor] source image load error:", e); + img.onload = () => { if (node.editor) node.editor.processImage(img); }; + img.src = source.url; + } else if (!source && node._bgFromConnectedSource) { + node._bgFromConnectedSource = false; + node.editor.clearBackgroundImage(); + } + }); + + chainCallback(node, "onRemoved", function () { + if (this.editor) this.editor.destroy(); + if (this.contextMenu?.parentNode) this.contextMenu.parentNode.removeChild(this.contextMenu); + }); + } + + // ─── Shared constructor flow ─── + // Call from subclass constructor after setting up widgets and data. + // editorKey: e.g. 'pointsEditor' or 'splineEditor' + // heightKey: e.g. 'pointsEditorHeight' or 'splineEditorHeight' + // heightOffset: pixels added to canvas height for full node height (e.g. 310 or 460) + initEditor(editorKey, heightKey, heightOffset) { + this._editorKey = editorKey; + this._heightKey = heightKey; + this._heightOffset = heightOffset; + + this.createCanvas(this.node[editorKey].element); + + if (this.width > 256) this.setNodeWidth(this.width + 45); + this.node[heightKey] = this.height + 40; + this.node.setSize([this.node.size[0], this.height + heightOffset]); + + this.setupEventListeners(); + this.render(); + } + + // Shared onSizeChanged — uses stored heightKey/heightOffset + onSizeChanged() { + this.node[this._heightKey] = this.height + 40; + this.node.setSize([this.node.size[0], this.height + this._heightOffset]); + if (this.node.graph) this.node.graph.setDirtyCanvas(true, true); + } + + // Shared constructor preamble — cleanup, reset, context menu, coord/display init + initEditorPreamble(editorKey, className) { + this._className = className; + this.cleanupPreviousEditor(this.node); + if (this.reset && this.node[editorKey].element) { + this.node[editorKey].element.innerHTML = ''; + } + this.createContextMenu(); + } + + // Shared coord/display size init from widgets + saved node size + initDisplaySize() { + this.coordWidth = this.widthWidget.value; + this.coordHeight = this.heightWidget.value; + const savedWidth = Math.max(64, Math.round(this.node.size[0] - 45)); + this.width = Math.min(savedWidth, maxDisplayDim); + this.height = Math.round(this.width * (this.coordHeight / this.coordWidth)); + } + + // Shared context menu creation — clone to clear stale listeners, wire up action handlers + createContextMenu() { + const oldMenu = this.node.contextMenu; + const newMenu = oldMenu.cloneNode(true); + oldMenu.parentNode.replaceChild(newMenu, oldMenu); + this.node.contextMenu = newMenu; + this.setupContextMenuListeners(this._className); + + const self = this; + newMenu.addEventListener('click', (e) => { + e.preventDefault(); + if (e.target.tagName !== 'A') return; + const id = e.target.dataset.menuId; + const def = this.node._menuDef[id]; + if (def?.action) { + def.action(self); + self._updateMenuToggleStates(); + } + newMenu.style.display = 'none'; + }); + } + + // Update toggle item styling from menu definitions + _updateMenuToggleStates() { + const menuDef = this.node._menuDef; + this.node.contextMenu.querySelectorAll('a').forEach(item => { + const def = menuDef[item.dataset.menuId]; + if (def?.toggle) { + const on = def.toggle(this); + item.style.color = on ? '#4fc3f7' : '#FFF'; + item.style.borderLeft = on ? '3px solid #4fc3f7' : '3px solid transparent'; + item.style.paddingLeft = '8px'; + } + }); + } + + // ─── Hooks for subclasses ─── + // Override these instead of duplicating logic: + + // Called after data changes (render + update widgets) + onDataChanged() {} + + // Called on image load for editor-specific state (e.g., drawRuler = false) + onImageResize() {} + + // Called when coord space changes — override to rescale coordinates + onCoordSpaceResized(_oldWidth, _oldHeight) {} +} diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/editors/interpolation.js b/.disabled/comfyui-kjnodes@nightly/web/js/editors/interpolation.js new file mode 100644 index 0000000000000000000000000000000000000000..3a5500dbe8ac356de74c5818c7b04042c5086323 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/editors/interpolation.js @@ -0,0 +1,211 @@ +// ─── Interpolation: SVG path d-string builders ─── +// Ported from protovis basis/cardinal/monotone/hermite algorithms + +const Interpolation = { + _basisPoint(t0, p0, t1, p1, t2, p2, t3, p3) { + return t0 * p0 + t1 * p1 + t2 * p2 + t3 * p3; + }, + + _pathBasis(p0, p1, p2, p3) { + const bp = Interpolation._basisPoint; + const x1 = bp(0, p0.x, 2/3, p1.x, 1/3, p2.x, 0, p3.x); + const y1 = bp(0, p0.y, 2/3, p1.y, 1/3, p2.y, 0, p3.y); + const x2 = bp(0, p0.x, 1/3, p1.x, 2/3, p2.x, 0, p3.x); + const y2 = bp(0, p0.y, 1/3, p1.y, 2/3, p2.y, 0, p3.y); + const x = bp(0, p0.x, 1/6, p1.x, 2/3, p2.x, 1/6, p3.x); + const y = bp(0, p0.y, 1/6, p1.y, 2/3, p2.y, 1/6, p3.y); + return `C${x1},${y1},${x2},${y2},${x},${y}`; + }, + + basis(points) { + if (points.length <= 2) return Interpolation.linear(points); + let d = ''; + let b0 = points[0], b1 = points[0], b2 = points[0], b3 = points[1]; + d += Interpolation._pathBasis(b0, b1, b2, b3); + for (let i = 2; i < points.length; i++) { + b0 = b1; b1 = b2; b2 = b3; b3 = points[i]; + d += Interpolation._pathBasis(b0, b1, b2, b3); + } + b0 = b1; b1 = b2; b2 = b3; + d += Interpolation._pathBasis(b0, b1, b2, b3); + b0 = b1; b1 = b2; + d += Interpolation._pathBasis(b0, b1, b2, b3); + return d; + }, + + _cardinalTangents(points, tension) { + const alpha = (1 - tension) / 2; + const tangents = []; + let f = points[0], g = points[1], h = points[2]; + for (let i = 3; i < points.length; i++) { + tangents.push({ x: alpha * (h.x - f.x), y: alpha * (h.y - f.y) }); + f = g; g = h; h = points[i]; + } + tangents.push({ x: alpha * (h.x - f.x), y: alpha * (h.y - f.y) }); + return tangents; + }, + + _hermite(points, tangents) { + if (tangents.length < 1 || + (points.length !== tangents.length && points.length !== tangents.length + 2)) + return ''; + const quad = points.length !== tangents.length; + let d = ''; + let g = points[0], h = points[1], i = tangents[0], j = i, k = 1; + + if (quad) { + d += `Q${h.x - i.x * 2/3},${h.y - i.y * 2/3},${h.x},${h.y}`; + g = points[1]; k = 2; + } + if (tangents.length > 1) { + j = tangents[1]; h = points[k]; k++; + d += `C${g.x + i.x},${g.y + i.y},${h.x - j.x},${h.y - j.y},${h.x},${h.y}`; + for (let idx = 2; idx < tangents.length; idx++, k++) { + h = points[k]; j = tangents[idx]; + d += `S${h.x - j.x},${h.y - j.y},${h.x},${h.y}`; + } + } + if (quad) { + const last = points[k]; + d += `Q${h.x + j.x * 2/3},${h.y + j.y * 2/3},${last.x},${last.y}`; + } + return d; + }, + + cardinal(points, tension) { + if (points.length <= 2) return Interpolation.linear(points); + return Interpolation._hermite(points, Interpolation._cardinalTangents(points, tension)); + }, + + _monotoneTangents(points) { + const n = points.length; + const d = [], m = [], dx = []; + for (let i = 0; i < n - 1; i++) d.push((points[i + 1].y - points[i].y) / (points[i + 1].x - points[i].x)); + m.push(d[0]); + for (let i = 1; i < n - 1; i++) m.push((d[i - 1] + d[i]) / 2); + m.push(d[n - 2]); + dx.push(points[1].x - points[0].x); + for (let i = 1; i < n - 1; i++) dx.push((points[i + 1].x - points[i - 1].x) / 2); + dx.push(points[n - 1].x - points[n - 2].x); + for (let i = 0; i < n - 1; i++) { if (Math.abs(d[i]) < 1e-7) { m[i] = 0; m[i + 1] = 0; } } + for (let i = 0; i < n - 1; i++) { + if (Math.abs(m[i]) >= 1e-5 && Math.abs(m[i + 1]) >= 1e-5) { + const alpha = m[i] / d[i], beta = m[i + 1] / d[i], sigma = alpha * alpha + beta * beta; + if (sigma > 9) { const k = 3 / Math.sqrt(sigma); m[i] = k * alpha * d[i]; m[i + 1] = k * beta * d[i]; } + } + } + const tangents = []; + for (let i = 0; i < n; i++) { const denom = 1 + m[i] * m[i]; tangents.push({ x: dx[i] / 3 / denom, y: m[i] * dx[i] / 3 / denom }); } + return tangents; + }, + + monotone(points) { + if (points.length <= 2) return Interpolation.linear(points); + return Interpolation._hermite(points, Interpolation._monotoneTangents(points)); + }, + + linear(points) { let d = ''; for (let i = 1; i < points.length; i++) d += `L${points[i].x},${points[i].y}`; return d; }, + stepBefore(points) { let d = ''; for (let i = 1; i < points.length; i++) d += `V${points[i].y}H${points[i].x}`; return d; }, + stepAfter(points) { let d = ''; for (let i = 1; i < points.length; i++) d += `H${points[i].x}V${points[i].y}`; return d; }, + + bezier(points) { + let d = ''; + for (let i = 1; i < points.length; i++) { + const prev = points[i - 1], cur = points[i]; + d += `C${prev.h2x ?? prev.x},${prev.h2y ?? prev.y},${cur.h1x ?? cur.x},${cur.h1y ?? cur.y},${cur.x},${cur.y}`; + } + return d; + }, + + ensureBezierHandles(points) { + for (let i = 0; i < points.length; i++) { + if (points[i].h1x !== undefined) continue; + const prev = points[Math.max(0, i - 1)], next = points[Math.min(points.length - 1, i + 1)]; + const dx = (next.x - prev.x) * 0.25, dy = (next.y - prev.y) * 0.25; + points[i].h1x = points[i].x - dx; points[i].h1y = points[i].y - dy; + points[i].h2x = points[i].x + dx; points[i].h2y = points[i].y + dy; + } + }, + + buildPathD(points, interpolation, tension) { + if (!points || points.length === 0) return ''; + let d = `M${points[0].x},${points[0].y}`; + if (points.length === 1) return d; + switch (interpolation) { + case 'basis': d += Interpolation.basis(points); break; + case 'cardinal': d += Interpolation.cardinal(points, tension); break; + case 'monotone': d += Interpolation.monotone(points); break; + case 'step-before': d += Interpolation.stepBefore(points); break; + case 'step-after': d += Interpolation.stepAfter(points); break; + case 'bezier': Interpolation.ensureBezierHandles(points); d += Interpolation.bezier(points); break; + case 'linear': default: d += Interpolation.linear(points); break; + } + return d; + }, + + drawOnCanvas(ctx, points, interpolation, tension) { + if (!points || points.length < 2) return; + ctx.beginPath(); + ctx.moveTo(points[0].x, points[0].y); + switch (interpolation) { + case 'basis': + if (points.length < 3) { ctx.lineTo(points[1].x, points[1].y); break; } + Interpolation._drawBasisCanvas(ctx, points); break; + case 'cardinal': + if (points.length < 3) { ctx.lineTo(points[1].x, points[1].y); break; } + Interpolation._drawHermiteCanvas(ctx, points, Interpolation._cardinalTangents(points, tension)); break; + case 'monotone': + if (points.length < 3) { ctx.lineTo(points[1].x, points[1].y); break; } + Interpolation._drawHermiteCanvas(ctx, points, Interpolation._monotoneTangents(points)); break; + case 'step-before': + for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i - 1].x, points[i].y); ctx.lineTo(points[i].x, points[i].y); } break; + case 'step-after': + for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i - 1].y); ctx.lineTo(points[i].x, points[i].y); } break; + case 'bezier': + Interpolation.ensureBezierHandles(points); + for (let i = 1; i < points.length; i++) { + const prev = points[i - 1], cur = points[i]; + ctx.bezierCurveTo(prev.h2x ?? prev.x, prev.h2y ?? prev.y, cur.h1x ?? cur.x, cur.h1y ?? cur.y, cur.x, cur.y); + } break; + case 'linear': default: + for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].x, points[i].y); break; + } + }, + + _drawBasisCanvas(ctx, points) { + const bp = Interpolation._basisPoint; + const drawSeg = (p0, p1, p2, p3) => { + ctx.bezierCurveTo( + bp(0,p0.x,2/3,p1.x,1/3,p2.x,0,p3.x), bp(0,p0.y,2/3,p1.y,1/3,p2.y,0,p3.y), + bp(0,p0.x,1/3,p1.x,2/3,p2.x,0,p3.x), bp(0,p0.y,1/3,p1.y,2/3,p2.y,0,p3.y), + bp(0,p0.x,1/6,p1.x,2/3,p2.x,1/6,p3.x), bp(0,p0.y,1/6,p1.y,2/3,p2.y,1/6,p3.y)); + }; + let b0 = points[0], b1 = points[0], b2 = points[0], b3 = points[1]; + drawSeg(b0, b1, b2, b3); + for (let i = 2; i < points.length; i++) { b0 = b1; b1 = b2; b2 = b3; b3 = points[i]; drawSeg(b0, b1, b2, b3); } + b0 = b1; b1 = b2; b2 = b3; drawSeg(b0, b1, b2, b3); + b0 = b1; b1 = b2; drawSeg(b0, b1, b2, b3); + }, + + _drawHermiteCanvas(ctx, points, tangents) { + if (tangents.length < 1 || (points.length !== tangents.length && points.length !== tangents.length + 2)) return; + const quad = points.length !== tangents.length; + let g = points[0], h = points[1], i = tangents[0], j = i, k = 1; + let prevCp2x, prevCp2y; + if (quad) { ctx.quadraticCurveTo(h.x - i.x * 2/3, h.y - i.y * 2/3, h.x, h.y); g = points[1]; k = 2; } + if (tangents.length > 1) { + j = tangents[1]; h = points[k]; k++; + prevCp2x = h.x - j.x; prevCp2y = h.y - j.y; + ctx.bezierCurveTo(g.x + i.x, g.y + i.y, prevCp2x, prevCp2y, h.x, h.y); + for (let idx = 2; idx < tangents.length; idx++, k++) { + const prevH = h; h = points[k]; j = tangents[idx]; + const rcp1x = 2 * prevH.x - prevCp2x, rcp1y = 2 * prevH.y - prevCp2y; + prevCp2x = h.x - j.x; prevCp2y = h.y - j.y; + ctx.bezierCurveTo(rcp1x, rcp1y, prevCp2x, prevCp2y, h.x, h.y); + } + } + if (quad) { const last = points[k]; ctx.quadraticCurveTo(h.x + j.x * 2/3, h.y + j.y * 2/3, last.x, last.y); } + } +}; + +export { Interpolation }; diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/editors/point_editor_canvas.js b/.disabled/comfyui-kjnodes@nightly/web/js/editors/point_editor_canvas.js new file mode 100644 index 0000000000000000000000000000000000000000..181c38596e8b425c19f1cb682a415b5eb01582ae --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/editors/point_editor_canvas.js @@ -0,0 +1,370 @@ +import { chainCallback, rectHitTest, cursorForBboxMode } from '../utility.js'; +import { BaseEditorCanvas, createEditorStylesheet } from './editor_base.js'; +const { app } = window.comfyAPI.app; + +createEditorStylesheet('kj-pointseditor-stylesheet', 'points-editor'); + +app.registerExtension({ + name: 'KJNodes.PointEditor', + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData?.name === 'PointsEditor') { + chainCallback(nodeType.prototype, "onNodeCreated", function () { + BaseEditorCanvas.setupNode(this, nodeData, { + editorClass: PointsEditor, + editorKey: 'pointsEditor', + heightKey: 'pointsEditorHeight', + className: 'points-editor', + menuItems: { + "Load Image": { action: (ed) => ed.openImageFilePicker() }, + "Clear Image": { action: (ed) => ed.clearBackgroundImage() }, + }, + hiddenWidgets: ["coordinates", "neg_coordinates", "bboxes"], + initialSize: [550, 550], + extraProperties: [ + ["points", this.constructor.type, "string"], + ["neg_points", this.constructor.type, "string"], + ], + }); + }); + } + } +}); + +class PointsEditor extends BaseEditorCanvas { + constructor(context, reset = false) { + super(context, reset); + this.initEditorPreamble('pointsEditor', 'points-editor'); + + this.pos_coordWidget = this.findWidget("coordinates"); + this.neg_coordWidget = this.findWidget("neg_coordinates"); + this.pointsStoreWidget = this.findWidget("points_store"); + this.widthWidget = this.findWidget("width"); + this.heightWidget = this.findWidget("height"); + this.bboxStoreWidget = this.findWidget("bbox_store"); + this.bboxWidget = this.findWidget("bboxes"); + + this.setupSizeCallbacks(); + this.pointsStoreWidget.callback = () => { + try { + const parsed = JSON.parse(this.pointsStoreWidget.value); + this.points = parsed.positive || []; + this.neg_points = parsed.negative || []; + } catch (e) { console.error("Error parsing points data:", e); } + this.render(); + this.updateData(); + }; + this.bboxStoreWidget.callback = () => { + try { this.bbox = JSON.parse(this.bboxStoreWidget.value); } + catch (e) { console.error("Error parsing bbox data:", e); } + this.render(); + this.updateData(); + }; + + this.initDisplaySize(); + this.points = []; + this.neg_points = []; + this.bbox = [{}]; + this.drawing = false; + this.selectedIndex = -1; + this.pointRadius = Math.max(4, Math.log(Math.max(1, Math.min(this.coordWidth, this.coordHeight))) * 4); + + if (!reset && this.pointsStoreWidget.value !== "") { + try { + const parsed = JSON.parse(this.pointsStoreWidget.value); + this.points = parsed.positive || []; + this.neg_points = parsed.negative || []; + this.bbox = JSON.parse(this.bboxStoreWidget.value); + } catch (e) { + console.error("Error parsing stored points:", e); + this.points = [{ x: this.coordWidth / 2, y: this.coordHeight / 2 }]; + this.neg_points = []; + this.bbox = [{}]; + } + } else { + this.points = [{ x: this.coordWidth / 2, y: this.coordHeight / 2 }]; + this.neg_points = []; + this.pointsStoreWidget.value = JSON.stringify({ positive: this.points, negative: this.neg_points }); + this.bboxStoreWidget.value = JSON.stringify(this.bbox); + } + + this.initEditor('pointsEditor', 'pointsEditorHeight', 310); + this.updateData(); + this.refreshBackgroundImage(); + } + + onDataChanged() { this.updateData(); } + + onCoordSpaceResized(oldWidth, oldHeight) { + const sx = this.coordWidth / oldWidth, sy = this.coordHeight / oldHeight; + const clampPt = (p) => { p.x = Math.max(0, Math.min(this.coordWidth, p.x * sx)); p.y = Math.max(0, Math.min(this.coordHeight, p.y * sy)); }; + for (const p of this.points) clampPt(p); + for (const p of this.neg_points) clampPt(p); + for (const b of this.bbox) { + if (b.startX != null) { + b.startX = Math.max(0, Math.min(this.coordWidth, b.startX * sx)); + b.startY = Math.max(0, Math.min(this.coordHeight, b.startY * sy)); + b.endX = Math.max(0, Math.min(this.coordWidth, b.endX * sx)); + b.endY = Math.max(0, Math.min(this.coordHeight, b.endY * sy)); + } + } + this.pointRadius = Math.max(4, Math.log(Math.max(1, Math.min(this.coordWidth, this.coordHeight))) * 4); + } + + // ─── Hit Testing ─── + + findPointAt(x, y, pointsArray) { + // Convert pixel radius to coord space + const r = this.pointRadius / Math.min(this.scaleX, this.scaleY); + for (let i = pointsArray.length - 1; i >= 0; i--) { + const p = pointsArray[i]; + const dx = p.x - x, dy = p.y - y; + if (dx * dx + dy * dy <= r * r) return i; + } + return -1; + } + + normBbox() { + const b = this.bbox[0]; + if (!b || Object.keys(b).length === 0) return null; + return { + x1: Math.min(b.startX, b.endX), y1: Math.min(b.startY, b.endY), + x2: Math.max(b.startX, b.endX), y2: Math.max(b.startY, b.endY), + }; + } + + hitTestBbox(mx, my) { + const n = this.normBbox(); + if (!n) return null; + return rectHitTest(mx, my, n.x1, n.y1, n.x2, n.y2, 10 / Math.min(this.scaleX, this.scaleY)); + } + + // ─── Mouse Handlers ─── + + onMouseDown(e) { + const mouse = this.getLocalMouse(e); + const clamped = this.clamp(mouse.x, mouse.y); + + if (e.shiftKey && e.button === 2) { + this.neg_points.push({ x: clamped.x, y: clamped.y }); + this.dragType = 'negative'; this.dragIndex = this.neg_points.length - 1; + this.selectedIndex = this.dragIndex; + this.dragOffset = { x: 0, y: 0 }; + this.render(); this.updateData(); this.startDocumentDrag(e); return; + } + if (e.shiftKey && e.button === 0) { + this.points.push({ x: clamped.x, y: clamped.y }); + this.dragType = 'positive'; this.dragIndex = this.points.length - 1; + this.selectedIndex = this.dragIndex; + this.dragOffset = { x: 0, y: 0 }; + this.render(); this.updateData(); this.startDocumentDrag(e); return; + } + + if (e.button === 2) { + const posIdx = this.findPointAt(mouse.x, mouse.y, this.points); + if (posIdx >= 0) { this.points.splice(posIdx, 1); this.render(); this.updateData(); return; } + const negIdx = this.findPointAt(mouse.x, mouse.y, this.neg_points); + if (negIdx >= 0) { this.neg_points.splice(negIdx, 1); this.render(); this.updateData(); return; } + const bboxHit = this.hitTestBbox(mouse.x, mouse.y); + if (bboxHit) { this.bbox = [{}]; this.render(); this.updateData(); return; } + this.showContextMenu(e); + return; + } + + if (e.button !== 0) return; + + if (e.ctrlKey) { + this.drawing = true; + this.dragType = 'bbox-draw'; + this.bbox[0] = { startX: clamped.x, startY: clamped.y, endX: clamped.x, endY: clamped.y }; + this.render(); this.startDocumentDrag(e); return; + } + + const bboxHit = this.hitTestBbox(mouse.x, mouse.y); + if (bboxHit) { + const n = this.normBbox(); + this.bboxAtDragStart = { startX: n.x1, startY: n.y1, endX: n.x2, endY: n.y2 }; + this.dragStart = { x: mouse.x, y: mouse.y }; + this.dragType = bboxHit === "move" ? 'bbox-move' : bboxHit; + this.dragIndex = 0; + this.startDocumentDrag(e); return; + } + + const posIdx = this.findPointAt(mouse.x, mouse.y, this.points); + if (posIdx >= 0) { + this.dragType = 'positive'; this.dragIndex = posIdx; this.selectedIndex = posIdx; + this.dragOffset = { x: mouse.x - this.points[posIdx].x, y: mouse.y - this.points[posIdx].y }; + this.render(); this.startDocumentDrag(e); return; + } + + const negIdx = this.findPointAt(mouse.x, mouse.y, this.neg_points); + if (negIdx >= 0) { + this.dragType = 'negative'; this.dragIndex = negIdx; this.selectedIndex = negIdx; + this.dragOffset = { x: mouse.x - this.neg_points[negIdx].x, y: mouse.y - this.neg_points[negIdx].y }; + this.render(); this.startDocumentDrag(e); return; + } + } + + onMouseMove(e) { + const mouse = this.getLocalMouse(e); + const clamped = this.clamp(mouse.x, mouse.y); + + if (!this.drawing && this.dragIndex < 0 && !this.dragType) { + const bboxHit = this.hitTestBbox(mouse.x, mouse.y); + const bboxCursor = cursorForBboxMode(bboxHit); + if (bboxCursor) { this.canvas.style.cursor = bboxCursor; } + else if (this.findPointAt(mouse.x, mouse.y, this.points) >= 0 || + this.findPointAt(mouse.x, mouse.y, this.neg_points) >= 0) { this.canvas.style.cursor = "move"; } + else { this.canvas.style.cursor = "default"; } + return; + } + + if (this.dragType === 'bbox-draw') { + this.bbox[0].endX = clamped.x; this.bbox[0].endY = clamped.y; + this.render(); return; + } + + if (this.dragType === 'bbox-move' && this.bboxAtDragStart) { + const dx = mouse.x - this.dragStart.x, dy = mouse.y - this.dragStart.y; + const bs = this.bboxAtDragStart; + const bw = bs.endX - bs.startX, bh = bs.endY - bs.startY; + const nx = Math.max(0, Math.min(this.coordWidth - bw, bs.startX + dx)); + const ny = Math.max(0, Math.min(this.coordHeight - bh, bs.startY + dy)); + this.bbox[0] = { startX: nx, startY: ny, endX: nx + bw, endY: ny + bh }; + this.render(); return; + } + + if (this.dragType?.startsWith('resize-') && this.bboxAtDragStart) { + const bs = this.bboxAtDragStart; + const offX = this.dragStart.x - (this.dragType === 'resize-tl' || this.dragType === 'resize-bl' ? bs.startX : bs.endX); + const offY = this.dragStart.y - (this.dragType === 'resize-tl' || this.dragType === 'resize-tr' ? bs.startY : bs.endY); + const cx = Math.max(0, Math.min(this.coordWidth, mouse.x - offX)); + const cy = Math.max(0, Math.min(this.coordHeight, mouse.y - offY)); + if (this.dragType === 'resize-tl') this.bbox[0] = { startX: bs.endX, startY: bs.endY, endX: cx, endY: cy }; + else if (this.dragType === 'resize-tr') this.bbox[0] = { startX: bs.startX, startY: bs.endY, endX: cx, endY: cy }; + else if (this.dragType === 'resize-bl') this.bbox[0] = { startX: bs.endX, startY: bs.startY, endX: cx, endY: cy }; + else this.bbox[0] = { startX: bs.startX, startY: bs.startY, endX: cx, endY: cy }; + this.render(); return; + } + + if (this.dragType === 'positive' && this.dragIndex >= 0 && this.dragIndex < this.points.length) { + const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0; + const target = this.clamp(mouse.x - ox, mouse.y - oy); + this.points[this.dragIndex] = { x: target.x, y: target.y }; + this.render(); + } else if (this.dragType === 'negative' && this.dragIndex >= 0 && this.dragIndex < this.neg_points.length) { + const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0; + const target = this.clamp(mouse.x - ox, mouse.y - oy); + this.neg_points[this.dragIndex] = { x: target.x, y: target.y }; + this.render(); + } + } + + onMouseUp() { + if (this.drawing || this.dragType) { + this.drawing = false; + this.bboxAtDragStart = null; + this.dragStart = null; + this.endDrag(); + this.updateData(); + } + } + + // ─── Rendering ─── + + _render() { + const ctx = this.ctx; + this.beginRender(); + + // Bounding box + const nb = this.normBbox(); + if (nb) { + const tl = this.toCanvas(nb.x1, nb.y1), br = this.toCanvas(nb.x2, nb.y2); + const bw = br.x - tl.x, bh = br.y - tl.y; + ctx.fillStyle = 'rgba(70, 130, 180, 0.3)'; + ctx.fillRect(tl.x, tl.y, bw, bh); + ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)'; ctx.lineWidth = 4; + ctx.strokeRect(tl.x, tl.y, bw, bh); + ctx.strokeStyle = 'steelblue'; ctx.lineWidth = 2; + ctx.strokeRect(tl.x, tl.y, bw, bh); + // Center cross + const cx = (tl.x + br.x) / 2, cy = (tl.y + br.y) / 2; + ctx.strokeStyle = 'steelblue'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(cx - 5, cy); ctx.lineTo(cx + 5, cy); + ctx.moveTo(cx, cy - 5); ctx.lineTo(cx, cy + 5); ctx.stroke(); + // Corner handles + const hs = 5; + ctx.fillStyle = 'steelblue'; + for (const [hx, hy] of [[tl.x, tl.y], [br.x, tl.y], [tl.x, br.y], [br.x, br.y]]) { + ctx.fillRect(hx - hs, hy - hs, hs * 2, hs * 2); + } + } + + // Points + this._badgePositions = []; + this._drawPoints(ctx, this.points, '#139613', '#07f907', 'positive'); + // Negative points + this._drawPoints(ctx, this.neg_points, '#891616', '#f91111', 'negative'); + + this.endRender(); + } + + _drawPoints(ctx, points, color, selectedColor, type) { + const r = this.pointRadius; + + for (let i = 0; i < points.length; i++) { + const p = points[i]; + const cp = this.toCanvas(p.x, p.y); + const isSelected = (this.dragType === type && this.dragIndex === i); + // Outer circle + ctx.beginPath(); ctx.arc(cp.x, cp.y, r, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(100, 100, 100, 0.25)'; ctx.fill(); + ctx.strokeStyle = isSelected ? selectedColor : color; ctx.lineWidth = 2; ctx.stroke(); + // Center dot + ctx.beginPath(); ctx.arc(cp.x, cp.y, 1.5, 0, Math.PI * 2); + ctx.fillStyle = 'red'; ctx.fill(); + // Index badge + const label = i.toString(); + const badgeR = label.length > 1 ? 8 : 7; + const off = r * 0.7; + const candidates = [ + { x: cp.x + off, y: cp.y - off }, + { x: cp.x - off, y: cp.y - off }, + { x: cp.x + off, y: cp.y + off }, + { x: cp.x - off, y: cp.y + off }, + ]; + const valid = candidates.filter(c => c.x - badgeR >= 0 && c.x + badgeR <= this.width && c.y - badgeR >= 0 && c.y + badgeR <= this.height); + const pool = valid.length > 0 ? valid : candidates; + let badge = pool[0]; + const minDist = badgeR * 2.2; + for (const c of pool) { + const overlaps = this._badgePositions.some(b => Math.abs(c.x - b.x) < minDist && Math.abs(c.y - b.y) < minDist); + if (!overlaps) { badge = c; break; } + } + this._badgePositions.push(badge); + + ctx.font = 'bold 10px sans-serif'; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.beginPath(); ctx.arc(badge.x, badge.y, badgeR, 0, Math.PI * 2); + ctx.fillStyle = isSelected ? selectedColor : color; ctx.fill(); + ctx.fillStyle = '#fff'; + ctx.fillText(label, badge.x, badge.y + 0.5); + ctx.textAlign = 'start'; ctx.textBaseline = 'alphabetic'; + } + } + + // ─── Data ─── + + updateData() { + const combinedPoints = { positive: this.points || [], negative: this.neg_points || [] }; + this.pointsStoreWidget.value = JSON.stringify(combinedPoints); + this.pos_coordWidget.value = JSON.stringify(this.points || []); + this.neg_coordWidget.value = JSON.stringify(this.neg_points || []); + if (this.bbox.length !== 0) { + let bboxString = JSON.stringify(this.bbox); + this.bboxStoreWidget.value = bboxString; + this.bboxWidget.value = bboxString; + } + } + +} diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/editors/spline_editor_canvas.js b/.disabled/comfyui-kjnodes@nightly/web/js/editors/spline_editor_canvas.js new file mode 100644 index 0000000000000000000000000000000000000000..0ebb998fadd208efbf19bdd44fc84a4e30fa3e26 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/editors/spline_editor_canvas.js @@ -0,0 +1,708 @@ +import { chainCallback } from '../utility.js'; +import { BaseEditorCanvas, createEditorStylesheet } from './editor_base.js'; +import { Interpolation } from './interpolation.js'; +const { app } = window.comfyAPI.app; + +createEditorStylesheet('kj-splineeditor-stylesheet', 'spline-editor'); + +// ─── Hidden SVG for path sampling (singleton) ─── +let _sharedSampler = null; +let _samplerRefCount = 0; +class PathSampler { + constructor() { + const ns = 'http://www.w3.org/2000/svg'; + this._svg = document.createElementNS(ns, 'svg'); + this._svg.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;'; + this._svg.setAttribute('aria-hidden', 'true'); + document.body.appendChild(this._svg); + this._path = document.createElementNS(ns, 'path'); + this._svg.appendChild(this._path); + } + static acquire() { + if (_sharedSampler) { _samplerRefCount++; return _sharedSampler; } + _sharedSampler = new PathSampler(); + _samplerRefCount = 1; + return _sharedSampler; + } + setPath(d) { this._path.setAttribute('d', d); } + getTotalLength() { return this._path.getTotalLength(); } + getPointAtLength(len) { return this._path.getPointAtLength(len); } + release() { + _samplerRefCount--; + if (_samplerRefCount <= 0 && this._svg && this._svg.parentNode) { + this._svg.parentNode.removeChild(this._svg); + _sharedSampler = null; + } + } + findPointAtX(targetX, pathLength) { + let low = 0, high = pathLength, bestPoint = this.getPointAtLength(0); + const epsilon = 0.5; + while (high - low > epsilon) { + const mid = (low + high) / 2, point = this.getPointAtLength(mid); + if (Math.abs(point.x - targetX) < Math.abs(bestPoint.x - targetX)) bestPoint = point; + if (Math.abs(point.x - targetX) < 0.5) return point; + if (point.x < targetX) low = mid; else high = mid; + } + return bestPoint; + } +} + +// ─── Extension Registration ─── +app.registerExtension({ + name: 'KJNodes.SplineEditor', + + init() { + app.ui.settings.addSetting({ + id: "KJNodes.splineEditor.showControlLines", + name: "Show control lines", + category: ["KJNodes", "Editors", "Show control lines"], + tooltip: "Display straight lines between control points", + type: "boolean", + defaultValue: false, + }); + app.ui.settings.addSetting({ + id: "KJNodes.splineEditor.showSamplePoints", + name: "Show sample points", + category: ["KJNodes", "Editors", "Show sample points"], + tooltip: "Display the sampled output points as red dots", + type: "boolean", + defaultValue: false, + }); + app.ui.settings.addSetting({ + id: "KJNodes.splineEditor.showArrows", + name: "Show direction arrows", + category: ["KJNodes", "Editors", "Show direction arrows"], + tooltip: "Display chevron arrows on control points showing curve direction", + type: "boolean", + defaultValue: true, + }); + app.ui.settings.addSetting({ + id: "KJNodes.editors.embedBackgroundImage", + name: "Embed background image in workflow", + category: ["KJNodes", "Editors", "Embed background image"], + tooltip: "When enabled, editor background images are embedded as base64 in the workflow file (portable, larger files). When disabled, images are stored as temp files on the server (small workflows, survives refresh, but not portable).", + type: "boolean", + defaultValue: false, + }); + }, + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData?.name === 'SplineEditor') { + chainCallback(nodeType.prototype, "onNodeCreated", function () { + BaseEditorCanvas.setupNode(this, nodeData, { + editorClass: SplineEditor, + editorKey: 'splineEditor', + heightKey: 'splineEditorHeight', + className: 'spline-editor', + menuClassName: 'spline-editor-context-menu', + menuItems: { + "Display control lines": { toggle: (ed) => ed.drawHandles, action: (ed) => { ed.drawHandles = !ed.drawHandles; app.ui.settings.setSettingValue("KJNodes.splineEditor.showControlLines", ed.drawHandles); ed.render(); } }, + "Display sample points": { toggle: (ed) => ed.drawSamplePoints, action: (ed) => { ed.drawSamplePoints = !ed.drawSamplePoints; app.ui.settings.setSettingValue("KJNodes.splineEditor.showSamplePoints", ed.drawSamplePoints); ed.updatePath(); } }, + "Display arrows": { toggle: (ed) => ed.showChevrons, action: (ed) => { ed.showChevrons = !ed.showChevrons; app.ui.settings.setSettingValue("KJNodes.splineEditor.showArrows", ed.showChevrons); ed.render(); } }, + "Background image": { action: (ed) => ed.openImageFilePicker() }, + "Invert point order": { action: (ed) => { ed.splines[ed.activeSplineIndex].points.reverse(); ed.render(); ed.updatePath(); } }, + "Clear Image": { action: (ed) => { ed.clearBackgroundImage(); ed.drawRuler = true; } }, + "Add new spline": { action: (ed) => { const idx = ed.splines.length; ed.splines.push({ points: [{ x: 0, y: ed.coordHeight }, { x: ed.coordWidth / 2, y: ed.coordHeight / 2 }, { x: ed.coordWidth, y: 0 }], color: ed.getSplineColor(idx), name: `Spline ${idx + 1}` }); ed.activeSplineIndex = idx; ed.render(); ed.updatePath(); } }, + "Add new single point": { action: (ed) => { const idx = ed.splines.length; ed.splines.push({ points: [{ x: ed.lastContextMenuPos.x, y: ed.lastContextMenuPos.y }], color: ed.getSplineColor(idx), name: `Spline ${idx + 1}`, isSinglePoint: true }); ed.activeSplineIndex = idx; ed.render(); ed.updatePath(); } }, + "Delete current spline": { action: (ed) => { if (ed.splines.length > 1) { ed.splines.splice(ed.activeSplineIndex, 1); ed.activeSplineIndex = Math.min(ed.activeSplineIndex, ed.splines.length - 1); ed.render(); ed.updatePath(); } } }, + "Next spline": { action: (ed) => { ed.activeSplineIndex = (ed.activeSplineIndex + 1) % ed.splines.length; ed.render(); ed.updatePath(); } }, + }, + hiddenWidgets: ["coordinates"], + initialSize: [550, 1000], + extraProperties: [ + ["points", this.constructor.type, "string"], + ], + }); + }); + } + } +}); + +// ─── SplineEditor class ─── +class SplineEditor extends BaseEditorCanvas { + constructor(context, reset = false) { + super(context, reset); + this.initEditorPreamble('splineEditor', 'spline-editor'); + + this.sampler = PathSampler.acquire(); + this.drawSamplePoints = app.ui.settings.getSettingValue("KJNodes.splineEditor.showSamplePoints") ?? false; + this.drawHandles = app.ui.settings.getSettingValue("KJNodes.splineEditor.showControlLines") ?? false; + this.showChevrons = app.ui.settings.getSettingValue("KJNodes.splineEditor.showArrows") ?? true; + this.drawRuler = true; + + this.coordWidget = this.findWidget("coordinates"); + this.interpolationWidget = this.findWidget("interpolation"); + this.pointsWidget = this.findWidget("points_to_sample"); + this.pointsStoreWidget = this.findWidget("points_store"); + this.tensionWidget = this.findWidget("tension"); + this.samplingMethodWidget = this.findWidget("sampling_method"); + this.widthWidget = this.findWidget("mask_width"); + this.heightWidget = this.findWidget("mask_height"); + + this.interpolationWidget.callback = () => this.updatePath(true); + this.samplingMethodWidget.callback = () => { + if (this.samplingMethod === "controlpoints") this.drawSamplePoints = true; + else this.drawSamplePoints = false; + if (this.samplingMethod === "path" || this.samplingMethod === "speed") this.showChevrons = true; + this.updatePath(true); + }; + this.tensionWidget.callback = () => this.updatePath(true); + this.pointsWidget.callback = () => this.updatePath(true); + this.setupSizeCallbacks(); + this.pointsStoreWidget.callback = () => { + this.parseSplineData(); + this.render(); this.updatePath(true); + }; + + this.initDisplaySize(); + this.splines = []; + this.activeSplineIndex = 0; + this.hoverSplineIndex = -1; + this.hoverIndex = -1; + this.sampledCoords = null; + this.lastContextMenuPos = { x: this.coordWidth / 2, y: this.coordHeight / 2 }; + + if (!reset && this.pointsStoreWidget.value !== "") { + this.parseSplineData(); + } else { + this.initializeDefaultSplines(); + this.pointsStoreWidget.value = JSON.stringify(this.splines); + } + + this._onKeyUp = (e) => { + if (e.key === 'Control' && this.subdividePreview) { this.subdividePreview = null; this.render(); } + }; + document.addEventListener('keyup', this._onKeyUp); + + this.initEditor('splineEditor', 'splineEditorHeight', 460); + this.updatePath(); + this.refreshBackgroundImage(); + } + + // ─── Widget value getters ─── + get interpolation() { return this.interpolationWidget.value; } + get tension() { return this.tensionWidget.value; } + get points_to_sample() { return this.pointsWidget.value; } + get samplingMethod() { return this.samplingMethodWidget.value; } + + // ─── Base class hooks ─── + + destroy() { + super.destroy(); + if (this.sampler) this.sampler.release(); + } + + onDataChanged() { this.updatePath(true); } + + onImageResize() { this.drawRuler = false; } + + onCoordSpaceResized(oldWidth, oldHeight) { + const sx = this.coordWidth / oldWidth, sy = this.coordHeight / oldHeight; + const cw = this.coordWidth, ch = this.coordHeight; + const clamp = (v, max) => Math.max(0, Math.min(max, v)); + for (const spline of this.splines) { + for (const p of spline.points) { + p.x = clamp(p.x * sx, cw); p.y = clamp(p.y * sy, ch); + if (p.h1x !== undefined) { p.h1x = clamp(p.h1x * sx, cw); p.h1y = clamp(p.h1y * sy, ch); } + if (p.h2x !== undefined) { p.h2x = clamp(p.h2x * sx, cw); p.h2y = clamp(p.h2y * sy, ch); } + } + } + } + + // ─── Spline Helpers ─── + + parseSplineData() { + try { + const parsed = JSON.parse(this.pointsStoreWidget.value); + if (Array.isArray(parsed) && parsed.length > 0 && parsed[0].hasOwnProperty('points')) { + this.splines = parsed; + } else { + this.splines = [{ points: parsed, color: "#1f77b4", name: "Spline 1" }]; + } + } catch (e) { + console.error("Error parsing spline data:", e); + this.initializeDefaultSplines(); + } + if (this.activeSplineIndex >= this.splines.length) { + this.activeSplineIndex = Math.max(0, this.splines.length - 1); + } + } + + initializeDefaultSplines() { + this.splines = [{ + points: [ + { x: 0, y: this.coordHeight }, + { x: this.coordWidth / 5 * 2, y: 50 + Math.random() * (this.coordHeight - 100) }, + { x: this.coordWidth, y: 0 } + ], + color: this.getSplineColor(0), + name: "Spline 1" + }]; + } + + getSplineColor(index) { + const colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]; + return colors[index % colors.length]; + } + + // ─── Hit Testing ─── + + findPointAt(x, y) { + const activePoints = this.splines[this.activeSplineIndex]?.points; + if (!activePoints) return -1; + const r = 12 / Math.min(this.scaleX, this.scaleY); + for (let i = activePoints.length - 1; i >= 0; i--) { + const dx = activePoints[i].x - x, dy = activePoints[i].y - y; + if (dx * dx + dy * dy <= r * r) return i; + } + return -1; + } + + findHandleAt(x, y) { + if (this.interpolation !== 'bezier') return null; + const activePoints = this.splines[this.activeSplineIndex]?.points; + if (!activePoints) return null; + const r = 8 / Math.min(this.scaleX, this.scaleY); + for (let i = activePoints.length - 1; i >= 0; i--) { + const p = activePoints[i]; + if (i > 0 && p.h1x !== undefined) { const dx = p.h1x - x, dy = p.h1y - y; if (dx * dx + dy * dy <= r * r) return { index: i, type: 'h1' }; } + if (i < activePoints.length - 1 && p.h2x !== undefined) { const dx = p.h2x - x, dy = p.h2y - y; if (dx * dx + dy * dy <= r * r) return { index: i, type: 'h2' }; } + } + return null; + } + + findSplineAt(x, y) { + const threshold = 15 / Math.min(this.scaleX, this.scaleY); + let bestDist = Infinity, bestIdx = -1; + for (let si = 0; si < this.splines.length; si++) { + const spline = this.splines[si]; + if (spline.isSinglePoint || (spline.points && spline.points.length === 1)) { + const p = spline.points[0], d = Math.sqrt((p.x - x) ** 2 + (p.y - y) ** 2); + if (d < threshold && d < bestDist) { bestDist = d; bestIdx = si; } + continue; + } + const pathD = Interpolation.buildPathD(spline.points, this.interpolation, this.tension); + this.sampler.setPath(pathD); + const len = this.sampler.getTotalLength(); + const steps = Math.min(200, Math.max(50, Math.round(len / 3))); + for (let i = 0; i <= steps; i++) { + const pt = this.sampler.getPointAtLength(len * i / steps); + const d = Math.sqrt((pt.x - x) ** 2 + (pt.y - y) ** 2); + if (d < threshold && d < bestDist) { bestDist = d; bestIdx = si; } + } + } + return bestIdx; + } + + findClosestPoints(points, clickedPoint) { + if (points.length < 2) return null; + let distances = points.map((point, idx) => { + const dx = clickedPoint.x - point.x, dy = clickedPoint.y - point.y; + return { index: idx, distance: Math.sqrt(dx * dx + dy * dy) }; + }); + distances.sort((a, b) => a.distance - b.distance); + let i1 = distances[0].index, i2 = distances[1].index; + if (i1 > i2) [i1, i2] = [i2, i1]; + return { point1Index: i1, point2Index: i2 }; + } + + // ─── Mouse Handlers ─── + + onMouseDown(e) { + const mouse = this.getLocalMouse(e); + const clamped = this.clamp(mouse.x, mouse.y); + const activeSpline = this.splines[this.activeSplineIndex]; + const activePoints = activeSpline?.points; + + if (e.shiftKey && e.button === 0 && activePoints) { + activePoints.push({ x: clamped.x, y: clamped.y }); + this.render(); this.updatePath(); return; + } + if (e.ctrlKey && e.button === 0 && activePoints && activePoints.length >= 2) { + const closest = this.findClosestPoints(activePoints, clamped); + if (closest) { + const p1 = activePoints[closest.point1Index], p2 = activePoints[closest.point2Index]; + activePoints.splice(closest.point2Index, 0, { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 }); + this.render(); this.updatePath(); + } + return; + } + + if (e.button === 2) { + const ptIdx = this.findPointAt(mouse.x, mouse.y); + if (activePoints && ptIdx > 0 && ptIdx < activePoints.length - 1) { + activePoints.splice(ptIdx, 1); this.render(); this.updatePath(); return; + } + this.lastContextMenuPos = { x: clamped.x, y: clamped.y }; + this.showContextMenu(e); + return; + } + + if (e.button !== 0) return; + + // Bezier handle drag + const handle = this.findHandleAt(mouse.x, mouse.y); + if (handle && activePoints) { + this.dragIndex = handle.index; this.dragType = handle.type; + const p = activePoints[handle.index]; + const hx = handle.type === 'h1' ? p.h1x : p.h2x, hy = handle.type === 'h1' ? p.h1y : p.h2y; + this.dragOffset = { x: mouse.x - hx, y: mouse.y - hy }; + this.render(); this.startDocumentDrag(e); return; + } + + // Point drag + const ptIdx = this.findPointAt(mouse.x, mouse.y); + if (ptIdx >= 0) { + this.dragIndex = ptIdx; this.dragType = 'point'; this.hoverIndex = ptIdx; + const p = activePoints[ptIdx]; + this.dragOffset = { x: mouse.x - p.x, y: mouse.y - p.y }; + this.render(); this.startDocumentDrag(e); return; + } + + // Spline selection + const splineIdx = this.findSplineAt(mouse.x, mouse.y); + if (splineIdx >= 0 && splineIdx !== this.activeSplineIndex) { + this.activeSplineIndex = splineIdx; this.render(); this.updatePath(); return; + } + } + + onMouseMove(e) { + const mouse = this.getLocalMouse(e); + const clamped = this.clamp(mouse.x, mouse.y); + + // Bezier handle drag + if ((this.dragType === 'h1' || this.dragType === 'h2') && this.dragIndex >= 0) { + const activePoints = this.splines[this.activeSplineIndex]?.points; + if (activePoints && this.dragIndex < activePoints.length) { + const p = activePoints[this.dragIndex]; + const clampH = (hx, hy) => ({ x: Math.max(0, Math.min(this.coordWidth, hx)), y: Math.max(0, Math.min(this.coordHeight, hy)) }); + const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0; + const prevH1x = p.h1x, prevH1y = p.h1y, prevH2x = p.h2x, prevH2y = p.h2y; + if (this.dragType === 'h1') { + const c = clampH(mouse.x - ox, mouse.y - oy); + p.h1x = c.x; p.h1y = c.y; + if (!e.altKey) { const dx = p.x - p.h1x, dy = p.y - p.h1y; const mc = clampH(p.x + dx, p.y + dy); p.h2x = mc.x; p.h2y = mc.y; } + } else { + const c = clampH(mouse.x - ox, mouse.y - oy); + p.h2x = c.x; p.h2y = c.y; + if (!e.altKey) { const dx = p.x - p.h2x, dy = p.y - p.h2y; const mc = clampH(p.x + dx, p.y + dy); p.h1x = mc.x; p.h1y = mc.y; } + } + if (p.h1x === prevH1x && p.h1y === prevH1y && p.h2x === prevH2x && p.h2y === prevH2y) return; + this.render(); + } + return; + } + + // Point drag + if (this.dragType === 'point' && this.dragIndex >= 0) { + const activePoints = this.splines[this.activeSplineIndex]?.points; + if (activePoints && this.dragIndex < activePoints.length) { + const p = activePoints[this.dragIndex]; + const ox = this.dragOffset?.x || 0, oy = this.dragOffset?.y || 0; + const target = this.clamp(mouse.x - ox, mouse.y - oy); + if (target.x === p.x && target.y === p.y) return; + const dx = target.x - p.x, dy = target.y - p.y; + if (this.interpolation === 'bezier' && p.h1x !== undefined) { + p.h1x += dx; p.h1y += dy; p.h2x += dx; p.h2y += dy; + } + p.x = target.x; p.y = target.y; + this.render(); + } + return; + } + + // Hover detection + if (!this.dragType) { + const ptIdx = this.findPointAt(mouse.x, mouse.y); + const activePoints = this.splines[this.activeSplineIndex]?.points; + + // Ctrl preview + if (e.ctrlKey && activePoints && activePoints.length >= 2) { + const closest = this.findClosestPoints(activePoints, clamped); + if (closest) { + const p1 = activePoints[closest.point1Index], p2 = activePoints[closest.point2Index]; + this.subdividePreview = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 }; + this.canvas.style.cursor = 'copy'; this.render(); return; + } + } else if (this.subdividePreview) { this.subdividePreview = null; this.render(); } + + // Handle hover + const handleHit = this.findHandleAt(mouse.x, mouse.y); + if (handleHit) { this.canvas.style.cursor = 'crosshair'; if (ptIdx !== this.hoverIndex) { this.hoverIndex = ptIdx; this.render(); } return; } + + if (ptIdx !== this.hoverIndex) { + this.hoverIndex = ptIdx; + this.canvas.style.cursor = ptIdx >= 0 ? 'move' : 'default'; + this.render(); + } + + // Spline hover + if (ptIdx < 0 && this.splines.length > 1) { + const splineIdx = this.findSplineAt(mouse.x, mouse.y); + const newSplineHover = splineIdx >= 0 && splineIdx !== this.activeSplineIndex ? splineIdx : -1; + if (newSplineHover !== this.hoverSplineIndex) { + this.hoverSplineIndex = newSplineHover; + this.canvas.style.cursor = newSplineHover >= 0 ? 'pointer' : 'default'; + this.render(); + } + } else if (this.hoverSplineIndex >= 0) { this.hoverSplineIndex = -1; this.render(); } + } + } + + onMouseUp() { + if (this.dragType) { + this.endDrag(); + this.updatePath(); + } + } + + // ─── Path Building & Sampling ─── + + samplePoints(splineIndex, numSamples, samplingMethod) { + const spline = this.splines[splineIndex]; + if (!spline || !spline.points || spline.points.length < 2) return []; + if (spline.isSinglePoint) { + const point = spline.points[0]; + return Array(numSamples).fill().map(() => ({ x: point.x, y: point.y })); + } + if (numSamples < 2) { + const p = spline.points[0]; + return [{ x: p.x, y: p.y }]; + } + const pathD = Interpolation.buildPathD(spline.points, this.interpolation, this.tension); + if (!pathD) return []; + + this.sampler.setPath(pathD); + const pathLength = this.sampler.getTotalLength(); + const points = []; + + if (samplingMethod === "speed") { + if (pathLength < 0.001) return [{ x: spline.points[0].x, y: spline.points[0].y }]; + const controlPoints = spline.points; + // Pair each control point with its path position, then sort together + const cpWithPos = controlPoints.map(cp => { + let bestDist = Infinity, bestPos = 0; + for (let pos = 0; pos <= pathLength; pos += pathLength / 100) { + const pt = this.sampler.getPointAtLength(pos); + const dist = Math.sqrt((pt.x - cp.x) ** 2 + (pt.y - cp.y) ** 2); + if (dist < bestDist) { bestDist = dist; bestPos = pos; } + } + return { cp, pos: bestPos }; + }); + cpWithPos.sort((a, b) => a.pos - b.pos); + const pathPositions = cpWithPos.map(c => c.pos); + + const densities = []; + let totalWeight = 0; + for (let i = 0; i < cpWithPos.length - 1; i++) { + const segLength = pathPositions[i + 1] - pathPositions[i]; + const d = 1 / Math.max(segLength, 0.0001); + densities.push(d); + totalWeight += d; + } + const cumulativeWeights = []; + let cum = 0; + for (let i = 0; i < densities.length; i++) { + cum += densities[i] / totalWeight; + cumulativeWeights.push(cum); + } + const mapToPath = (t) => { + if (t === 0) return 0; if (t === 1) return pathLength; + let segIdx = cumulativeWeights.length - 1; + for (let i = 0; i < cumulativeWeights.length; i++) { if (t <= cumulativeWeights[i]) { segIdx = i; break; } } + const segStart = segIdx > 0 ? cumulativeWeights[segIdx - 1] : 0; + const segT = (t - segStart) / (cumulativeWeights[segIdx] - segStart); + return pathPositions[segIdx] + segT * (pathPositions[segIdx + 1] - pathPositions[segIdx]); + }; + for (let i = 0; i < numSamples; i++) { + const pt = this.sampler.getPointAtLength(mapToPath(i / (numSamples - 1))); + points.push({ x: pt.x, y: pt.y }); + } + return points; + } + + for (let i = 0; i < numSamples; i++) { + let point; + if (samplingMethod === "time") { + point = this.sampler.findPointAtX((this.coordWidth / (numSamples - 1)) * i, pathLength); + } else { + point = this.sampler.getPointAtLength((pathLength / (numSamples - 1)) * i); + } + points.push({ x: point.x, y: point.y }); + } + if (points.length > 0 && spline.points.length > 1) { + points[points.length - 1].y = spline.points[spline.points.length - 1].y; + } + return points; + } + + updatePath(allDirty = false) { + if (!this.splines || this.splines.length === 0) return; + + // Rebuild cache when spline count changes or full refresh requested + if (!this._sampledCache || this._sampledCache.length !== this.splines.length || allDirty) { + this._sampledCache = new Array(this.splines.length).fill(null); + } + + const method = this.samplingMethod; + const useControlPoints = method === "controlpoints"; + for (let i = 0; i < this.splines.length; i++) { + if (useControlPoints) { + this._sampledCache[i] = this.splines[i].points; + } else if (i === this.activeSplineIndex || !this._sampledCache[i]) { + this._sampledCache[i] = this.samplePoints(i, this.points_to_sample, method); + } + } + this.sampledCoords = this._sampledCache[this.activeSplineIndex] || []; + this.pointsStoreWidget.value = JSON.stringify(this.splines); + if (this.coordWidget) this.coordWidget.value = JSON.stringify(this._sampledCache); + this.render(); + } + + // ─── Rendering ─── + + _render() { + const ctx = this.ctx; + const h = this.coordHeight; + this.beginRender(); + + // Ruler lines + if (this.drawRuler && !this.bgImage) { + ctx.strokeStyle = 'rgba(128,128,128,0.3)'; ctx.lineWidth = 1; + for (let y = 64; y < h; y += 64) { + const cy = y * this.scaleY; + ctx.beginPath(); ctx.moveTo(0, cy); ctx.lineTo(this.width, cy); ctx.stroke(); + } + } + + const tc = (x, y) => this.toCanvas(x, y); + + // Draw all splines — use scale transform for curves, toCanvas for discrete elements + for (let si = 0; si < this.splines.length; si++) { + const spline = this.splines[si]; + const isActive = si === this.activeSplineIndex, isHover = si === this.hoverSplineIndex; + + if (spline.isSinglePoint || (spline.points && spline.points.length === 1)) { + const cp = tc(spline.points[0].x, spline.points[0].y), sz = isActive ? 8 : 6; + ctx.fillStyle = spline.color; ctx.fillRect(cp.x - sz, cp.y - sz, sz * 2, sz * 2); + ctx.strokeStyle = 'black'; ctx.lineWidth = 2; ctx.strokeRect(cp.x - sz, cp.y - sz, sz * 2, sz * 2); + continue; + } + if (spline.points.length < 2) continue; + + // Build path once, stroke twice (outline + color) to avoid recomputing interpolation + const pathD = Interpolation.buildPathD(spline.points, this.interpolation, this.tension); + const curvePath = new Path2D(pathD); + ctx.save(); ctx.scale(this.scaleX, this.scaleY); + ctx.lineWidth = (isActive ? 5 : isHover ? 4 : 3.5) / Math.min(this.scaleX, this.scaleY); ctx.strokeStyle = 'black'; + ctx.stroke(curvePath); + ctx.lineWidth = (isActive ? 3 : isHover ? 2 : 1.5) / Math.min(this.scaleX, this.scaleY); ctx.strokeStyle = spline.color; + ctx.stroke(curvePath); + ctx.restore(); + } + + const activeSpline = this.splines[this.activeSplineIndex]; + + // Handle lines + if (this.drawHandles) { + const activePoints = this.splines[this.activeSplineIndex]?.points; + if (activePoints && activePoints.length >= 2) { + ctx.strokeStyle = '#ff7f0e'; ctx.lineWidth = 1; ctx.beginPath(); + const c0 = tc(activePoints[0].x, activePoints[0].y); + ctx.moveTo(c0.x, c0.y); + for (let i = 1; i < activePoints.length; i++) { const ci = tc(activePoints[i].x, activePoints[i].y); ctx.lineTo(ci.x, ci.y); } + ctx.stroke(); + } + } + + // Control points for active spline + if (activeSpline && activeSpline.points && !activeSpline.isSinglePoint) { + const dotRadius = 12; + for (let i = 0; i < activeSpline.points.length; i++) { + const p = activeSpline.points[i]; + const cp = tc(p.x, p.y); + const isHovered = this.hoverIndex === i; + ctx.fillStyle = 'rgba(100, 100, 100, 0.3)'; + ctx.strokeStyle = isHovered ? '#ff7f0e' : '#1f77b4'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.arc(cp.x, cp.y, dotRadius, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); + + // Chevron + const isEndpoint = i === 0 || i === activeSpline.points.length - 1; + const showChevron = this.showChevrons && ( + (this.samplingMethod === 'path' || this.samplingMethod === 'speed') + || (this.samplingMethod === 'time' && isEndpoint)); + + if (showChevron && activeSpline.points.length > 1) { + let angle = 0; + if (i > 0 && i < activeSpline.points.length - 1) { const prev = activeSpline.points[i-1], next = activeSpline.points[i+1]; angle = Math.atan2((next.y - prev.y) * this.scaleY, (next.x - prev.x) * this.scaleX); } + else if (i === 0) { const next = activeSpline.points[1]; angle = Math.atan2((next.y - p.y) * this.scaleY, (next.x - p.x) * this.scaleX); } + else { const prev = activeSpline.points[i-1]; angle = Math.atan2((p.y - prev.y) * this.scaleY, (p.x - prev.x) * this.scaleX); } + ctx.save(); + ctx.translate(cp.x, cp.y); + ctx.rotate(angle); + ctx.strokeStyle = isHovered ? '#fff' : 'rgba(255,255,255,0.7)'; + ctx.lineWidth = 2.5; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; + ctx.beginPath(); + ctx.moveTo(-dotRadius * 0.2, -dotRadius * 0.35); + ctx.lineTo(dotRadius * 0.3, 0); + ctx.lineTo(-dotRadius * 0.2, dotRadius * 0.35); + ctx.stroke(); + ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; + ctx.restore(); + } + + if (isHovered) { + ctx.font = '11px monospace'; + const label = `${i}: (${Math.round(p.x)}, ${Math.round(p.y)})`; + ctx.strokeStyle = '#000'; ctx.lineWidth = 3; ctx.strokeText(label, cp.x + dotRadius + 5, cp.y - 5); + ctx.fillStyle = '#fff'; ctx.fillText(label, cp.x + dotRadius + 5, cp.y - 5); + } + } + } + + // Bezier handles + if (this.interpolation === 'bezier' && activeSpline && activeSpline.points && !activeSpline.isSinglePoint) { + const pts = activeSpline.points; + Interpolation.ensureBezierHandles(pts); + const hr = 5; + for (let i = 0; i < pts.length; i++) { + const p = pts[i]; + const cp = tc(p.x, p.y); + if (i > 0 && p.h1x !== undefined) { + const h1 = tc(p.h1x, p.h1y); + ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(cp.x, cp.y); ctx.lineTo(h1.x, h1.y); ctx.stroke(); + ctx.fillStyle = (this.dragType === 'h1' && this.dragIndex === i) ? '#fff' : 'rgba(255,255,255,0.8)'; + ctx.strokeStyle = '#1f77b4'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.arc(h1.x, h1.y, hr, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); + } + if (i < pts.length - 1 && p.h2x !== undefined) { + const h2 = tc(p.h2x, p.h2y); + ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(cp.x, cp.y); ctx.lineTo(h2.x, h2.y); ctx.stroke(); + ctx.fillStyle = (this.dragType === 'h2' && this.dragIndex === i) ? '#fff' : 'rgba(255,255,255,0.8)'; + ctx.strokeStyle = '#ff7f0e'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.arc(h2.x, h2.y, hr, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); + } + } + } + + // Sample points + if (this.drawSamplePoints && this.sampledCoords) { + ctx.fillStyle = 'red'; ctx.strokeStyle = 'black'; ctx.lineWidth = 1; + for (const pt of this.sampledCoords) { const cp = tc(pt.x, pt.y); ctx.beginPath(); ctx.arc(cp.x, cp.y, 5, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); } + } + + // Subdivide preview + if (this.subdividePreview) { + const sp = tc(this.subdividePreview.x, this.subdividePreview.y); + ctx.beginPath(); ctx.arc(sp.x, sp.y, 10, 0, Math.PI * 2); + ctx.strokeStyle = 'rgba(0,255,0,0.3)'; ctx.lineWidth = 4; ctx.stroke(); + ctx.beginPath(); ctx.arc(sp.x, sp.y, 8, 0, Math.PI * 2); + ctx.strokeStyle = '#0f0'; ctx.lineWidth = 2; ctx.stroke(); + } + + this.endRender(); + } + +} diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/fast_preview.js b/.disabled/comfyui-kjnodes@nightly/web/js/fast_preview.js new file mode 100644 index 0000000000000000000000000000000000000000..62134fadf6683abb1bfd96234f1c7bbe7cf06b0b --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/fast_preview.js @@ -0,0 +1,31 @@ +import { chainCallback } from './utility.js'; +const { app } = window.comfyAPI.app; +const { api } = window.comfyAPI.api; + +app.registerExtension({ + name: 'KJNodes.FastPreview', + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData?.name === 'FastPreview') { + chainCallback(nodeType.prototype, "onNodeCreated", function () { + + this.setSize([550, 550]); + + const nodeRef = this; + api.addEventListener("b_preview_with_metadata", function (event) { + const { blob, nodeId, displayNodeId } = event.detail; + const targetId = String(displayNodeId || nodeId); + if (targetId !== String(nodeRef.id)) return; + + const img = new Image(); + img.onload = () => { + nodeRef.imgs = [img]; + nodeRef.setDirtyCanvas(true); + }; + img.src = URL.createObjectURL(blob); + }); + + }); + } + } +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/fillconnect.js b/.disabled/comfyui-kjnodes@nightly/web/js/fillconnect.js new file mode 100644 index 0000000000000000000000000000000000000000..1d1398c0ca312c2527bccf3335152f5ec17b2e53 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/fillconnect.js @@ -0,0 +1,218 @@ +const { app } = window.comfyAPI.app; +import { getSlotPos } from "./utility.js"; + +/** + * Check type compatibility. Returns a match tier: + * 2 = exact single-type match, 1 = multi-type or wildcard match, -1 = incompatible + */ +function typeMatchTier(outType, inType) { + if (!LiteGraph.isValidConnection(outType, inType)) return -1; + if (typeof outType === "string" && typeof inType === "string" + && !outType.includes(",") && !inType.includes(",") + && outType.toUpperCase() === inType.toUpperCase()) return 2; + return 1; +} + + +/** + * Order selected nodes for connection. + * Respects existing links between them (topological sort), + * then inserts unconnected nodes by spatial position (left-to-right, top-to-bottom). + */ +function orderNodes(nodes, graph) { + const selectedIds = new Set(nodes.map(n => n.id)); + const nodeById = new Map(nodes.map(n => [n.id, n])); + + const outEdges = new Map(); + const inDegree = new Map(); + for (const n of nodes) { + outEdges.set(n.id, new Set()); + inDegree.set(n.id, 0); + } + + for (const node of nodes) { + for (const out of (node.outputs || [])) { + for (const linkId of (out.links || [])) { + const link = graph.getLink(linkId); + if (link && selectedIds.has(link.target_id) && link.target_id !== node.id) { + if (!outEdges.get(node.id).has(link.target_id)) { + outEdges.get(node.id).add(link.target_id); + inDegree.set(link.target_id, inDegree.get(link.target_id) + 1); + } + } + } + } + } + + const bySpatial = (a, b) => a.pos[0] - b.pos[0] || a.pos[1] - b.pos[1]; + const queue = nodes.filter(n => inDegree.get(n.id) === 0); + queue.sort(bySpatial); + + const ordered = []; + while (queue.length > 0) { + const node = queue.shift(); + ordered.push(node); + for (const targetId of outEdges.get(node.id)) { + const deg = inDegree.get(targetId) - 1; + inDegree.set(targetId, deg); + if (deg === 0 && nodeById.has(targetId)) { + queue.push(nodeById.get(targetId)); + queue.sort(bySpatial); + } + } + } + + // Cycle fallback: append remaining by position + if (ordered.length < nodes.length) { + const inOrdered = new Set(ordered.map(n => n.id)); + const remaining = nodes.filter(n => !inOrdered.has(n.id)); + remaining.sort(bySpatial); + ordered.push(...remaining); + } + + return ordered; +} + +/** + * Collect all candidate connections and assign globally by closest 2D distance. + * Each input and output is used at most once per invocation. + */ +function planConnections(ordered) { + // Collect all candidates globally across all target nodes + const candidates = []; + + for (let b = 1; b < ordered.length; b++) { + const nodeB = ordered[b]; + if (!nodeB.inputs) continue; + + for (let inIdx = 0; inIdx < nodeB.inputs.length; inIdx++) { + const inp = nodeB.inputs[inIdx]; + if (inp.link != null) continue; + + const inPos = getSlotPos(nodeB, true, inIdx); + const inputCandidates = []; + let hasExact = false; + + for (let a = b - 1; a >= 0; a--) { + const nodeA = ordered[a]; + if (!nodeA.outputs) continue; + + for (let outIdx = 0; outIdx < nodeA.outputs.length; outIdx++) { + const tier = typeMatchTier(nodeA.outputs[outIdx].type, inp.type); + if (tier < 0) continue; + if (tier === 2) hasExact = true; + + const outPos = getSlotPos(nodeA, false, outIdx); + const dx = outPos[0] - inPos[0]; + const dy = outPos[1] - inPos[1]; + inputCandidates.push({ + targetNode: nodeB, + inIdx, + sourceNode: nodeA, + outIdx, + tier, + dist: dx * dx + dy * dy, + }); + } + } + + for (const c of inputCandidates) { + c.hasExact = hasExact; + } + candidates.push(...inputCandidates); + } + } + + // Filter out non-exact matches for inputs that have an exact candidate + const filtered = candidates.filter(c => c.tier === 2 || !c.hasExact); + + // Sort globally: higher tier first, then closest pair + filtered.sort((x, y) => (y.tier - x.tier) || (x.dist - y.dist)); + + // Greedy global assignment — closest pairs first + const planned = []; + const usedInputs = new Set(); + const usedOutputs = new Set(); + + for (const c of filtered) { + const inKey = `${c.targetNode.id}:${c.inIdx}`; + if (usedInputs.has(inKey)) continue; + const outKey = `${c.sourceNode.id}:${c.outIdx}`; + if (usedOutputs.has(outKey)) continue; + + planned.push({ + sourceNode: c.sourceNode, + outIdx: c.outIdx, + targetNode: c.targetNode, + inIdx: c.inIdx, + }); + usedInputs.add(inKey); + usedOutputs.add(outKey); + } + + return planned; +} + +function connectPlanned(planned, graph) { + for (const p of planned) { + p.sourceNode.connect(p.outIdx, p.targetNode, p.inIdx); + } + graph.change(); +} + +function fillConnectSelected() { + if (!app.ui.settings.getSettingValue("KJNodes.fillConnectEnabled")) return; + + const canvas = app.canvas; + const graph = canvas.graph; + const nodes = Object.values(canvas.selected_nodes || {}); + if (nodes.length < 2) return; + + const ordered = orderNodes(nodes, graph); + const planned = planConnections(ordered); + + if (planned.length > 0) { + connectPlanned(planned, graph); + } + + if (app.extensionManager?.toast) { + app.extensionManager.toast.add({ + severity: planned.length > 0 ? "info" : "warn", + summary: planned.length > 0 + ? `Connected ${planned.length} link${planned.length > 1 ? "s" : ""}` + : "No compatible connections found", + life: 2000, + }); + } +} + +app.registerExtension({ + name: "KJNodes.FillConnect", + + settings: [ + { + id: "KJNodes.fillConnectEnabled", + name: "Enable Fill-Connect hotkey", + category: ["KJNodes", "Fill-Connect"], + tooltip: "Fill-connect selected nodes by compatible types", + type: "boolean", + defaultValue: true, + }, + ], + + commands: [ + { + id: "KJNodes.fillConnectSelected", + label: "Fill-Connect Selected Nodes", + function: fillConnectSelected, + }, + ], + + keybindings: [ + { + commandId: "KJNodes.fillConnectSelected", + combo: { key: "f" }, + targetElementId: "graph-canvas", + }, + ], +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/help_popup.js b/.disabled/comfyui-kjnodes@nightly/web/js/help_popup.js new file mode 100644 index 0000000000000000000000000000000000000000..b481f84d6c46917445db2ba03c258ae1f80bfcc9 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/help_popup.js @@ -0,0 +1,468 @@ +const { app } = window.comfyAPI.app; + +// code based on mtb nodes by Mel Massadian https://github.com/melMass/comfy_mtb/ +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) + } + }) +} + +loadScript('kjweb_async/marked.min.js').catch((e) => { + console.error(e) +}) +loadScript('kjweb_async/purify.min.js').catch((e) => { + console.error(e) +}) + +const categories = ["KJNodes", "SUPIR", "VoiceCraft", "Marigold", "IC-Light", "WanVideoWrapper"]; +const nodeDescriptions = new Map(); + +function isHelpPopupEnabled() { + return app.ui.settings.getSettingValue("KJNodes.helpPopup") !== false; +} + +app.registerExtension({ + name: "KJNodes.HelpPopup", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (!isHelpPopupEnabled()) return; + try { + categories.forEach(category => { + if (nodeData?.category?.startsWith(category)) { + if (nodeData.description) { + nodeDescriptions.set(nodeData.name, nodeData.description); + } + addDocumentation(nodeData, nodeType); + } + else return + }); + } catch (error) { + console.error("Error in registering KJNodes.HelpPopup", error); + } + }, + nodeCreated(node) { + if (!isHelpPopupEnabled()) return; + const description = nodeDescriptions.get(node.type) || nodeDescriptions.get(node.comfyClass); + if (!description) return; + node._kjHelpDescription = description; + }, + setup() { + if (!isHelpPopupEnabled()) return; + setupHelpObserver(); + }, +}); + +const create_documentation_stylesheet = () => { + const tag = 'kj-documentation-stylesheet' + + let styleTag = document.getElementById(tag) + + if (!styleTag) { + styleTag = document.createElement('style') + styleTag.type = 'text/css' + styleTag.id = tag + styleTag.innerHTML = ` + .kj-documentation-popup { + background: var(--comfy-menu-bg); + position: absolute; + color: var(--fg-color); + font: 12px monospace; + line-height: 1.5em; + padding: 10px; + border-radius: 10px; + border-style: solid; + border-width: medium; + border-color: var(--border-color); + z-index: 5; + overflow: hidden; + } + .content-wrapper { + overflow: auto; + max-height: 100%; + /* Scrollbar styling for Chrome */ + &::-webkit-scrollbar { + width: 6px; + } + &::-webkit-scrollbar-track { + background: var(--bg-color); + } + &::-webkit-scrollbar-thumb { + background-color: var(--fg-color); + border-radius: 6px; + border: 3px solid var(--bg-color); + } + + /* Scrollbar styling for Firefox */ + scrollbar-width: thin; + scrollbar-color: var(--fg-color) var(--bg-color); + a { + color: yellow; + } + a:visited { + color: orange; + } + a:hover { + color: red; + } + } + ` + document.head.appendChild(styleTag) + } + } + +/** + * Creates the documentation popup DOM and wires up resize/close interactions. + * Returns { docElement, contentWrapper }. + * @param {string} description - Markdown description text + * @param {AbortSignal} signal - Signal to clean up event listeners + * @param {() => void} onClose - Called when the close button is clicked + * @param {{ scaleResize: boolean }} opts - If scaleResize is true, resize deltas are divided by canvas scale + */ +function createDocPopup(description, signal, onClose, opts = {}) { + create_documentation_stylesheet() + + const docElement = document.createElement('div') + const contentWrapper = document.createElement('div') + docElement.appendChild(contentWrapper) + + contentWrapper.classList.add('content-wrapper') + docElement.classList.add('kj-documentation-popup') + // Try ComfyUI's built-in markdown renderer first (available after frontend PR #10700) + if (app.extensionManager?.renderMarkdownToHtml) { + contentWrapper.innerHTML = app.extensionManager.renderMarkdownToHtml(description) + } else if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') { + contentWrapper.innerHTML = DOMPurify.sanitize(marked.parse(description)) + } else { + // Fallback: convert markdown links to
    tags, auto-link bare URLs, preserve line breaks + const escaped = description + .replace(/&/g, '&').replace(//g, '>') + .replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '$1') + .replace(/(^|[^"'])(https?:\/\/[^\s<]+)/g, '$1$2') + .replace(/\n/g, '
    ') + contentWrapper.innerHTML = escaped + } + + // resize handle + const resizeHandle = document.createElement('div') + resizeHandle.style.width = '0' + resizeHandle.style.height = '0' + resizeHandle.style.position = 'absolute' + resizeHandle.style.bottom = '0' + resizeHandle.style.right = '0' + resizeHandle.style.cursor = 'se-resize' + const borderColor = getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim() + resizeHandle.style.borderTop = '10px solid transparent' + resizeHandle.style.borderLeft = '10px solid transparent' + resizeHandle.style.borderBottom = `10px solid ${borderColor}` + resizeHandle.style.borderRight = `10px solid ${borderColor}` + docElement.appendChild(resizeHandle) + + let isResizing = false + let startX, startY, startWidth, startHeight + resizeHandle.addEventListener('mousedown', (e) => { + e.preventDefault() + e.stopPropagation() + isResizing = true + startX = e.clientX + startY = e.clientY + startWidth = parseInt(document.defaultView.getComputedStyle(docElement).width, 10) + startHeight = parseInt(document.defaultView.getComputedStyle(docElement).height, 10) + }, { signal }) + + document.addEventListener('mousemove', (e) => { + if (!isResizing) return + const scaleFactor = opts.scaleResize ? app.canvas.ds.scale : 1 + const newWidth = startWidth + (e.clientX - startX) / scaleFactor + const newHeight = startHeight + (e.clientY - startY) / scaleFactor + docElement.style.width = `${newWidth}px` + docElement.style.height = `${newHeight}px` + }, { signal }) + + document.addEventListener('mouseup', () => { + isResizing = false + }, { signal }) + + // close button + const closeButton = document.createElement('div') + closeButton.textContent = '❌' + closeButton.style.position = 'absolute' + closeButton.style.top = '0' + closeButton.style.right = '0' + closeButton.style.cursor = 'pointer' + closeButton.style.padding = '5px' + closeButton.style.color = 'red' + closeButton.style.fontSize = '12px' + docElement.appendChild(closeButton) + + closeButton.addEventListener('mousedown', (e) => { + e.stopPropagation() + onClose() + }, { signal }) + + document.body.appendChild(docElement) + return { docElement, contentWrapper } +} + +// ─── Legacy canvas mode (onDrawForeground) ─── + +/** Add documentation widget to the selected node (legacy canvas rendering) */ +export const addDocumentation = ( + nodeData, + nodeType, + opts = { icon_size: 14, icon_margin: 4 },) => { + + opts = opts || {} + const iconSize = opts.icon_size ? opts.icon_size : 14 + const iconMargin = opts.icon_margin ? opts.icon_margin : 4 + let docElement = null + let contentWrapper = null + + if (!nodeData.description) { + return + } + + const drawFg = nodeType.prototype.onDrawForeground + nodeType.prototype.onDrawForeground = function (ctx) { + const r = drawFg ? drawFg.apply(this, arguments) : undefined + if (this.flags.collapsed) return r + + const x = this.size[0] - iconSize - iconMargin + + // create the popup + if (this.show_doc && docElement === null) { + const popup = createDocPopup( + nodeData.description, + this.docCtrl.signal, + () => { + this.show_doc = !this.show_doc + docElement.parentNode.removeChild(docElement) + docElement = null + contentWrapper = null + }, + { scaleResize: true } + ) + docElement = popup.docElement + contentWrapper = popup.contentWrapper + } + // close the popup + else if (!this.show_doc && docElement !== null) { + docElement.parentNode.removeChild(docElement) + docElement = null + } + // update position of the popup + if (this.show_doc && docElement !== null) { + const rect = ctx.canvas.getBoundingClientRect() + const scaleX = rect.width / ctx.canvas.width + const scaleY = rect.height / ctx.canvas.height + + const transform = new DOMMatrix() + .scaleSelf(scaleX, scaleY) + .multiplySelf(ctx.getTransform()) + .translateSelf(this.size[0] * scaleX * Math.max(1.0,window.devicePixelRatio) , 0) + .translateSelf(10, -32) + + const scale = new DOMMatrix() + .scaleSelf(transform.a, transform.d); + const bcr = app.canvas.canvas.getBoundingClientRect() + + const styleObject = { + transformOrigin: '0 0', + transform: scale, + left: `${transform.a + bcr.x + transform.e}px`, + top: `${transform.d + bcr.y + transform.f}px`, + }; + Object.assign(docElement.style, styleObject); + } + + ctx.save() + ctx.translate(x - 2, iconSize - 34) + ctx.scale(iconSize / 32, iconSize / 32) + ctx.strokeStyle = 'rgba(255,255,255,0.3)' + ctx.lineCap = 'round' + ctx.lineJoin = 'round' + ctx.lineWidth = 2.4 + ctx.font = 'bold 36px monospace' + ctx.fillStyle = 'orange'; + ctx.fillText('?', 0, 24) + ctx.restore() + return r + } + + // handle clicking of the icon + const mouseDown = nodeType.prototype.onMouseDown + nodeType.prototype.onMouseDown = function (e, localPos, canvas) { + const r = mouseDown ? mouseDown.apply(this, arguments) : undefined + const iconX = this.size[0] - iconSize - iconMargin + const iconY = iconSize - 34 + if ( + localPos[0] > iconX && + localPos[0] < iconX + iconSize && + localPos[1] > iconY && + localPos[1] < iconY + iconSize + ) { + if (this.show_doc === undefined) { + this.show_doc = true + } else { + this.show_doc = !this.show_doc + } + if (this.show_doc) { + this.docCtrl = new AbortController() + } else { + this.docCtrl.abort() + } + return true; + } + return r; + } + + const onRem = nodeType.prototype.onRemoved + nodeType.prototype.onRemoved = function () { + const r = onRem ? onRem.apply(this, []) : undefined + if (docElement) { + docElement.remove() + docElement = null + contentWrapper = null + } + return r + } +} + +// ─── Vue nodes mode (DOM injection via MutationObserver) ─── + +/** Per-node popup state, keyed by node ID */ +const popupState = new Map() + +function getNodeById(nodeId) { + return app.graph?.getNodeById(nodeId) +} + +function closeNodePopup(nodeId) { + const state = popupState.get(nodeId) + if (!state) return + if (state.docElement) { + state.docElement.remove() + } + if (state.abortCtrl) { + state.abortCtrl.abort() + } + if (state.animFrame) { + cancelAnimationFrame(state.animFrame) + } + popupState.delete(nodeId) +} + +function openNodePopup(nodeId, description) { + closeNodePopup(nodeId) + const state = popupState.get(nodeId) || {} + popupState.set(nodeId, state) + + state.abortCtrl = new AbortController() + const popup = createDocPopup( + description, + state.abortCtrl.signal, + () => closeNodePopup(nodeId), + { scaleResize: false } + ) + state.docElement = popup.docElement + + function updatePosition() { + if (!state.docElement || !state.docElement.parentNode) return + const nodeEl = document.querySelector(`[data-node-id="${nodeId}"]`) + if (nodeEl) { + const rect = nodeEl.getBoundingClientRect() + state.docElement.style.left = `${rect.right + 10}px` + state.docElement.style.top = `${rect.top}px` + } + state.animFrame = requestAnimationFrame(updatePosition) + } + state.animFrame = requestAnimationFrame(updatePosition) +} + +/** Try to inject a "?" button into a Vue node header */ +function tryInjectHelpButton(header) { + if (header.querySelector('.kj-help-btn')) return + + const nodeEl = header.closest('[data-node-id]') + if (!nodeEl) return + const nodeId = nodeEl.dataset.nodeId + const node = getNodeById(nodeId) + if (!node) return + + const description = node._kjHelpDescription + if (!description) return + + const flexContainer = header.querySelector(':scope > div') + if (!flexContainer) return + + const helpBtn = document.createElement('span') + helpBtn.className = 'kj-help-btn' + helpBtn.textContent = '?' + helpBtn.style.cssText = ` + color: orange; + font-weight: bold; + font-size: 14px; + cursor: pointer; + flex-shrink: 0; + padding: 0 4px; + line-height: 1; + user-select: none; + ` + helpBtn.title = 'Show help' + helpBtn.addEventListener('click', (e) => { + e.stopPropagation() + const state = popupState.get(nodeId) + if (state?.docElement) { + closeNodePopup(nodeId) + } else { + openNodePopup(nodeId, description) + } + }) + flexContainer.appendChild(helpBtn) +} + +/** Observe the DOM for Vue node headers appearing and inject help buttons */ +function setupHelpObserver() { + // Inject into any headers already in the DOM + document.querySelectorAll('.lg-node-header').forEach(tryInjectHelpButton) + + let pending = false + const observer = new MutationObserver(() => { + if (pending) return + pending = true + requestAnimationFrame(() => { + pending = false + document.querySelectorAll('.lg-node-header:not(:has(.kj-help-btn))').forEach(tryInjectHelpButton) + }) + }) + observer.observe(document.body, { childList: true, subtree: true }) +} diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/jsnodes.js b/.disabled/comfyui-kjnodes@nightly/web/js/jsnodes.js new file mode 100644 index 0000000000000000000000000000000000000000..a2cceb3007e12a76492a8b7a83ea0596fae65214 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/jsnodes.js @@ -0,0 +1,402 @@ +const { app } = window.comfyAPI.app; +const { applyTextReplacements } = window.comfyAPI.utils; + +app.registerExtension({ + name: "KJNodes.jsnodes", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if(!nodeData?.category?.startsWith("KJNodes")) { + return; + } + switch (nodeData.name) { + case "ConditioningMultiCombine": + nodeType.prototype.onNodeCreated = function () { + this._type = "CONDITIONING" + this.inputs_offset = nodeData.name.includes("selective")?1:0 + this.addWidget("button", "Update inputs", null, () => { + if (!this.inputs) { + this.inputs = []; + } + const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"]; + const num_inputs = this.inputs.filter(input => input.type === this._type).length + if(target_number_of_inputs===num_inputs)return; // already set, do nothing + + if(target_number_of_inputs < num_inputs){ + const inputs_to_remove = num_inputs - target_number_of_inputs; + for(let i = 0; i < inputs_to_remove; i++) { + this.removeInput(this.inputs.length - 1); + } + } + else{ + for(let i = num_inputs+1; i <= target_number_of_inputs; ++i) + this.addInput(`conditioning_${i}`, this._type) + } + }); + } + break; + case "ImageBatchMulti": + case "ImageAddMulti": + case "ImageConcatMulti": + case "CrossFadeImagesMulti": + case "TransitionImagesMulti": + nodeType.prototype.onNodeCreated = function () { + this._type = "IMAGE" + this.addWidget("button", "Update inputs", null, () => { + if (!this.inputs) { + this.inputs = []; + } + const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"]; + const num_inputs = this.inputs.filter(input => input.type === this._type).length + if(target_number_of_inputs===num_inputs)return; // already set, do nothing + + if(target_number_of_inputs < num_inputs){ + const inputs_to_remove = num_inputs - target_number_of_inputs; + for(let i = 0; i < inputs_to_remove; i++) { + this.removeInput(this.inputs.length - 1); + } + } + else{ + for(let i = num_inputs+1; i <= target_number_of_inputs; ++i) + this.addInput(`image_${i}`, this._type, {shape: 7}); + } + + }); + } + break; + case "MaskBatchMulti": + nodeType.prototype.onNodeCreated = function () { + this._type = "MASK" + this.addWidget("button", "Update inputs", null, () => { + if (!this.inputs) { + this.inputs = []; + } + const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"]; + const num_inputs = this.inputs.filter(input => input.type === this._type).length + if(target_number_of_inputs===num_inputs)return; // already set, do nothing + + if(target_number_of_inputs < num_inputs){ + const inputs_to_remove = num_inputs - target_number_of_inputs; + for(let i = 0; i < inputs_to_remove; i++) { + this.removeInput(this.inputs.length - 1); + } + } + else{ + for(let i = num_inputs+1; i <= target_number_of_inputs; ++i) + this.addInput(`mask_${i}`, this._type) + } + }); + } + break; + + case "FluxBlockLoraSelect": + case "HunyuanVideoBlockLoraSelect": + case "Wan21BlockLoraSelect": + case "LTX2BlockLoraSelect": + nodeType.prototype.onNodeCreated = function () { + this.addWidget("button", "Set all", null, () => { + const userInput = prompt("Enter the values to set for widgets (e.g., s0,1,2-7=2.0, d0,1,2-7=2.0, or 1.0):", ""); + if (userInput) { + const regex = /([sd])?(\d+(?:,\d+|-?\d+)*?)?=(\d+(\.\d+)?)/; + const match = userInput.match(regex); + if (match) { + const type = match[1]; + const indicesPart = match[2]; + const value = parseFloat(match[3]); + + let targetWidgets = []; + if (type === 's') { + targetWidgets = this.widgets.filter(widget => widget.name.includes("single")); + } else if (type === 'd') { + targetWidgets = this.widgets.filter(widget => widget.name.includes("double")); + } else { + targetWidgets = this.widgets; // No type specified, all widgets + } + + if (indicesPart) { + const indices = indicesPart.split(',').flatMap(part => { + if (part.includes('-')) { + const [start, end] = part.split('-').map(Number); + return Array.from({ length: end - start + 1 }, (_, i) => start + i); + } + return Number(part); + }); + + for (const index of indices) { + if (index < targetWidgets.length) { + targetWidgets[index].value = value; + } + } + } else { + // No indices provided, set value for all target widgets + for (const widget of targetWidgets) { + widget.value = value; + } + } + } else if (!isNaN(parseFloat(userInput))) { + // Single value provided, set it for all widgets + const value = parseFloat(userInput); + for (const widget of this.widgets) { + widget.value = value; + } + } else { + alert("Invalid input format. Please use the format s0,1,2-7=2.0, d0,1,2-7=2.0, or 1.0"); + } + } else { + alert("Invalid input. Please enter a value."); + } + }); + }; + break; + + case "GetMaskSizeAndCount": + const onGetMaskSizeConnectInput = nodeType.prototype.onConnectInput; + nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) { + const v = onGetMaskSizeConnectInput? onGetMaskSizeConnectInput.apply(this, arguments): undefined + this.outputs[1]["label"] = "width" + this.outputs[2]["label"] = "height" + this.outputs[3]["label"] = "count" + return v; + } + const onGetMaskSizeExecuted = nodeType.prototype.onAfterExecuteNode; + nodeType.prototype.onExecuted = function(message) { + const r = onGetMaskSizeExecuted? onGetMaskSizeExecuted.apply(this,arguments): undefined + let values = message["text"].toString().split('x').map(Number); + this.outputs[1]["label"] = values[1] + " width" + this.outputs[2]["label"] = values[2] + " height" + this.outputs[3]["label"] = values[0] + " count" + return r + } + break; + + case "GetImageSizeAndCount": + const onGetImageSizeConnectInput = nodeType.prototype.onConnectInput; + nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) { + console.log(this) + const v = onGetImageSizeConnectInput? onGetImageSizeConnectInput.apply(this, arguments): undefined + //console.log(this) + this.outputs[1]["label"] = "width" + this.outputs[2]["label"] = "height" + this.outputs[3]["label"] = "count" + return v; + } + //const onGetImageSizeExecuted = nodeType.prototype.onExecuted; + const onGetImageSizeExecuted = nodeType.prototype.onAfterExecuteNode; + nodeType.prototype.onExecuted = function(message) { + console.log(this) + const r = onGetImageSizeExecuted? onGetImageSizeExecuted.apply(this,arguments): undefined + let values = message["text"].toString().split('x').map(Number); + console.log(values) + this.outputs[1]["label"] = values[1] + " width" + this.outputs[2]["label"] = values[2] + " height" + this.outputs[3]["label"] = values[0] + " count" + return r + } + break; + + case "GetLatentSizeAndCount": + const onGetLatentConnectInput = nodeType.prototype.onConnectInput; + nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) { + console.log(this) + const v = onGetLatentConnectInput? onGetLatentConnectInput.apply(this, arguments): undefined + //console.log(this) + this.outputs[1]["label"] = "batch_size" + this.outputs[2]["label"] = "channels" + this.outputs[3]["label"] = "frames" + this.outputs[4]["label"] = "height" + this.outputs[5]["label"] = "width" + return v; + } + //const onGetImageSizeExecuted = nodeType.prototype.onExecuted; + const onGetLatentSizeExecuted = nodeType.prototype.onAfterExecuteNode; + nodeType.prototype.onExecuted = function(message) { + console.log(this) + const r = onGetLatentSizeExecuted? onGetLatentSizeExecuted.apply(this,arguments): undefined + let values = message["text"].toString().split('x').map(Number); + console.log(values) + this.outputs[1]["label"] = values[0] + " batch" + this.outputs[2]["label"] = values[1] + " channels" + this.outputs[3]["label"] = values[2] + " frames" + this.outputs[4]["label"] = values[3] + " height" + this.outputs[5]["label"] = values[4] + " width" + return r + } + break; + + case "PreviewAnimation": + const onPreviewAnimationConnectInput = nodeType.prototype.onConnectInput; + nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) { + const v = onPreviewAnimationConnectInput? onPreviewAnimationConnectInput.apply(this, arguments): undefined + this.title = "Preview Animation" + return v; + } + const onPreviewAnimationExecuted = nodeType.prototype.onAfterExecuteNode; + nodeType.prototype.onExecuted = function(message) { + const r = onPreviewAnimationExecuted? onPreviewAnimationExecuted.apply(this,arguments): undefined + let values = message["text"].toString(); + this.title = "Preview Animation " + values + return r + } + break; + + case "VRAM_Debug": + const onVRAM_DebugConnectInput = nodeType.prototype.onConnectInput; + nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) { + const v = onVRAM_DebugConnectInput? onVRAM_DebugConnectInput.apply(this, arguments): undefined + this.outputs[3]["label"] = "freemem_before" + this.outputs[4]["label"] = "freemem_after" + return v; + } + const onVRAM_DebugExecuted = nodeType.prototype.onAfterExecuteNode; + nodeType.prototype.onExecuted = function(message) { + const r = onVRAM_DebugExecuted? onVRAM_DebugExecuted.apply(this,arguments): undefined + let values = message["text"].toString().split('x'); + this.outputs[3]["label"] = values[0] + " freemem_before" + this.outputs[4]["label"] = values[1] + " freemem_after" + return r + } + break; + + case "JoinStringMulti": + const originalOnNodeCreated = nodeType.prototype.onNodeCreated || function() {}; + nodeType.prototype.onNodeCreated = function () { + originalOnNodeCreated.apply(this, arguments); + + this._type = "STRING"; + this.addWidget("button", "Update inputs", null, () => { + if (!this.inputs) { + this.inputs = []; + } + const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"]; + const num_inputs = this.inputs.filter(input => input.name && input.name.toLowerCase().includes("string_")).length + if (target_number_of_inputs === num_inputs) return; // already set, do nothing + + if(target_number_of_inputs < num_inputs){ + const inputs_to_remove = num_inputs - target_number_of_inputs; + for(let i = 0; i < inputs_to_remove; i++) { + this.removeInput(this.inputs.length - 1); + } + } + else{ + for(let i = num_inputs+1; i <= target_number_of_inputs; ++i) + this.addInput(`string_${i}`, this._type, {shape: 7}); + } + }); + } + break; + case "SoundReactive": + nodeType.prototype.onNodeCreated = function () { + let audioContext; + let microphoneStream; + let animationFrameId; + let analyser; + let dataArray; + let startRangeHz; + let endRangeHz; + let smoothingFactor = 0.5; + let smoothedSoundLevel = 0; + + // Function to update the widget value in real-time + const updateWidgetValueInRealTime = () => { + // Ensure analyser and dataArray are defined before using them + if (analyser && dataArray) { + analyser.getByteFrequencyData(dataArray); + + const startRangeHzWidget = this.widgets.find(w => w.name === "start_range_hz"); + if (startRangeHzWidget) startRangeHz = startRangeHzWidget.value; + const endRangeHzWidget = this.widgets.find(w => w.name === "end_range_hz"); + if (endRangeHzWidget) endRangeHz = endRangeHzWidget.value; + const smoothingFactorWidget = this.widgets.find(w => w.name === "smoothing_factor"); + if (smoothingFactorWidget) smoothingFactor = smoothingFactorWidget.value; + + // Calculate frequency bin width (frequency resolution) + const frequencyBinWidth = audioContext.sampleRate / analyser.fftSize; + // Convert the widget values from Hz to indices + const startRangeIndex = Math.floor(startRangeHz / frequencyBinWidth); + const endRangeIndex = Math.floor(endRangeHz / frequencyBinWidth); + + // Function to calculate the average value for a frequency range + const calculateAverage = (start, end) => { + const sum = dataArray.slice(start, end).reduce((acc, val) => acc + val, 0); + const average = sum / (end - start); + + // Apply exponential moving average smoothing + smoothedSoundLevel = (average * (1 - smoothingFactor)) + (smoothedSoundLevel * smoothingFactor); + return smoothedSoundLevel; + }; + // Calculate the average levels for each frequency range + const soundLevel = calculateAverage(startRangeIndex, endRangeIndex); + + // Update the widget values + + const lowLevelWidget = this.widgets.find(w => w.name === "sound_level"); + if (lowLevelWidget) lowLevelWidget.value = soundLevel; + + animationFrameId = requestAnimationFrame(updateWidgetValueInRealTime); + } + }; + + // Function to start capturing audio from the microphone + const startMicrophoneCapture = () => { + // Only create the audio context and analyser once + if (!audioContext) { + audioContext = new (window.AudioContext || window.webkitAudioContext)(); + // Access the sample rate of the audio context + console.log(`Sample rate: ${audioContext.sampleRate}Hz`); + analyser = audioContext.createAnalyser(); + analyser.fftSize = 2048; + dataArray = new Uint8Array(analyser.frequencyBinCount); + // Get the range values from widgets (assumed to be in Hz) + const lowRangeWidget = this.widgets.find(w => w.name === "low_range_hz"); + if (lowRangeWidget) startRangeHz = lowRangeWidget.value; + + const midRangeWidget = this.widgets.find(w => w.name === "mid_range_hz"); + if (midRangeWidget) endRangeHz = midRangeWidget.value; + } + + navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { + microphoneStream = stream; + const microphone = audioContext.createMediaStreamSource(stream); + microphone.connect(analyser); + updateWidgetValueInRealTime(); + }).catch(error => { + console.error('Access to microphone was denied or an error occurred:', error); + }); + }; + + // Function to stop capturing audio from the microphone + const stopMicrophoneCapture = () => { + if (animationFrameId) { + cancelAnimationFrame(animationFrameId); + } + if (microphoneStream) { + microphoneStream.getTracks().forEach(track => track.stop()); + } + if (audioContext) { + audioContext.close(); + // Reset audioContext to ensure it can be created again when starting + audioContext = null; + } + }; + + // Add start button + this.addWidget("button", "Start mic capture", null, startMicrophoneCapture); + + // Add stop button + this.addWidget("button", "Stop mic capture", null, stopMicrophoneCapture); + }; + break; + case "SaveImageKJ": + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0; + const widget = this.widgets.find((w) => w.name === "filename_prefix"); + widget.serializeValue = () => { + return applyTextReplacements(app, widget.value); + }; + return r; + }; + break; + + } + + }, +}); \ No newline at end of file diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/nodeswap.js b/.disabled/comfyui-kjnodes@nightly/web/js/nodeswap.js new file mode 100644 index 0000000000000000000000000000000000000000..b7d9a36e6257c9680bbd8a9d060623367ae659a5 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/nodeswap.js @@ -0,0 +1,404 @@ +const { app } = window.comfyAPI.app; +import { typesCompatible, clientToCanvas, getNodeAtPoint } from "./utility.js"; + +let swapTargetNode = null; +let swapDraggedNode = null; +let swapDragStartPos = null; +let swapAnimating = false; +let swapHasMoved = false; +let swapKeyDown = false; + +/** Find the topmost node whose bounding box overlaps with draggedNode */ +function getOverlappingNode(graph, draggedNode) { + const ax = draggedNode.pos[0]; + const ay = draggedNode.pos[1]; + const aw = draggedNode.size[0] || 100; + const ah = draggedNode.size[1] || 60; + + for (let i = graph._nodes.length - 1; i >= 0; i--) { + const n = graph._nodes[i]; + if (n === draggedNode) continue; + const bx = n.pos[0]; + const by = n.pos[1]; + if (ax < bx + (n.size[0] || 100) && ax + aw > bx && + ay < by + (n.size[1] || 60) && ay + ah > by) { + return n; + } + } + return null; +} + + +function startHighlightAnim(lgCanvas) { + if (swapAnimating) return; + swapAnimating = true; + + function tick() { + if (!swapTargetNode) { + swapAnimating = false; + return; + } + lgCanvas.setDirty(false, true); + requestAnimationFrame(tick); + } + requestAnimationFrame(tick); +} + +function clearSwapState() { + swapTargetNode = null; + swapDraggedNode = null; + swapDragStartPos = null; + swapHasMoved = false; +} + +function snapshotConnections(graph, node) { + const inputs = []; + for (let i = 0; i < (node.inputs?.length ?? 0); i++) { + const inp = node.inputs[i]; + if (inp.link == null) continue; + const link = graph.getLink(inp.link); + if (!link) continue; + inputs.push({ + slotIndex: i, + type: inp.type, + originNodeId: link.origin_id, + originSlot: link.origin_slot, + }); + } + + const outputs = []; + for (let o = 0; o < (node.outputs?.length ?? 0); o++) { + const out = node.outputs[o]; + if (!out.links?.length) continue; + const targets = out.links + .map((linkId) => graph.getLink(linkId)) + .filter(Boolean) + .map((link) => ({ targetNodeId: link.target_id, targetSlot: link.target_slot })); + if (targets.length > 0) { + outputs.push({ slotIndex: o, type: out.type, targets }); + } + } + + return { inputs, outputs }; +} + +function disconnectAll(node) { + if (node.inputs) { + for (let i = node.inputs.length - 1; i >= 0; i--) { + if (node.inputs[i].link != null) node.disconnectInput(i); + } + } + if (node.outputs) { + for (let o = node.outputs.length - 1; o >= 0; o--) { + if (node.outputs[o].links?.length) node.disconnectOutput(o); + } + } +} + +// Find a compatible slot on node, preferring sameIndex. Returns -1 if none found. +// For inputs, isAvailable checks link == null and usedInputs; for outputs, always true. +function findCompatibleSlot(slots, type, sameIndex, isAvailable) { + if (!slots) return -1; + if (sameIndex < slots.length && isAvailable(sameIndex) && typesCompatible(type, slots[sameIndex].type)) { + return sameIndex; + } + for (let s = 0; s < slots.length; s++) { + if (isAvailable(s) && typesCompatible(type, slots[s].type)) return s; + } + return -1; +} + +// Reconnect external connections from a snapshot onto newNode. +// Tries same-slot first, then scans for a compatible free slot by type. +function reconnectExternal(graph, snapshot, newNode, otherNodeId) { + const usedInputs = new Set(); + for (const inp of snapshot.inputs) { + if (inp.originNodeId === otherNodeId) continue; + const originNode = graph.getNodeById(inp.originNodeId); + if (!originNode) continue; + const slot = findCompatibleSlot( + newNode.inputs, inp.type, inp.slotIndex, + (s) => !usedInputs.has(s) && newNode.inputs[s].link == null, + ); + if (slot === -1) continue; + originNode.connect(inp.originSlot, newNode, slot); + usedInputs.add(slot); + } + + for (const out of snapshot.outputs) { + const bestSlot = findCompatibleSlot( + newNode.outputs, out.type, out.slotIndex, + () => true, + ); + if (bestSlot === -1) continue; + for (const tgt of out.targets) { + if (tgt.targetNodeId === otherNodeId) continue; + const targetNode = graph.getNodeById(tgt.targetNodeId); + if (!targetNode) continue; + newNode.connect(bestSlot, targetNode, tgt.targetSlot); + } + } +} + +// Reconnect links that were between the two swapped nodes in one direction. +// A→B becomes B→A, if slot types are compatible. +function reconnectInternalOneDirection(snap, fromNodeId, srcNode, dstNode) { + for (const out of snap.outputs) { + for (const tgt of out.targets) { + if (tgt.targetNodeId !== fromNodeId) continue; + if (!srcNode.outputs || out.slotIndex >= srcNode.outputs.length) continue; + if (!dstNode.inputs || tgt.targetSlot >= dstNode.inputs.length) continue; + if (!typesCompatible(srcNode.outputs[out.slotIndex].type, dstNode.inputs[tgt.targetSlot].type)) continue; + srcNode.connect(out.slotIndex, dstNode, tgt.targetSlot); + } + } +} + +function getNodeElement(nodeId) { + return document.querySelector(`[data-node-id="${nodeId}"]`); +} + +function animateSwapVue(nodeA, toA, nodeB, toB, duration) { + const elA = getNodeElement(nodeA.id); + const elB = getNodeElement(nodeB.id); + const transition = `transform ${duration}ms cubic-bezier(0.65, 0, 0.35, 1)`; + + if (elA) elA.style.transition = transition; + if (elB) elB.style.transition = transition; + + nodeA.pos = [toA[0], toA[1]]; + nodeB.pos = [toB[0], toB[1]]; + app.canvas.setDirty(true, true); + + setTimeout(() => { + if (elA) elA.style.transition = ""; + if (elB) elB.style.transition = ""; + }, duration + 16); +} + +function animateSwapCanvas(nodeA, fromA, toA, nodeB, fromB, toB, duration) { + const start = performance.now(); + + function ease(t) { + return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; + } + + function frame(now) { + const t = Math.min((now - start) / duration, 1); + const e = ease(t); + nodeA.pos = [ + fromA[0] + (toA[0] - fromA[0]) * e, + fromA[1] + (toA[1] - fromA[1]) * e, + ]; + nodeB.pos = [ + fromB[0] + (toB[0] - fromB[0]) * e, + fromB[1] + (toB[1] - fromB[1]) * e, + ]; + app.canvas.setDirty(true, true); + if (t < 1) requestAnimationFrame(frame); + } + + requestAnimationFrame(frame); +} + +function executeNodeSwap(canvas, nodeA, nodeB, originalPosA) { + const graph = canvas.graph || app.graph; + + const snapA = snapshotConnections(graph, nodeA); + const snapB = snapshotConnections(graph, nodeB); + + const posA = originalPosA || [nodeA.pos[0], nodeA.pos[1]]; + const posB = [nodeB.pos[0], nodeB.pos[1]]; + + disconnectAll(nodeA); + disconnectAll(nodeB); + + reconnectExternal(graph, snapA, nodeB, nodeA.id); + reconnectExternal(graph, snapB, nodeA, nodeB.id); + + reconnectInternalOneDirection(snapA, nodeB.id, nodeB, nodeA); + reconnectInternalOneDirection(snapB, nodeA.id, nodeA, nodeB); + + if (LiteGraph.vueNodesMode) { + animateSwapVue(nodeA, posB, nodeB, posA, 200); + } else { + animateSwapCanvas(nodeA, [nodeA.pos[0], nodeA.pos[1]], posB, + nodeB, [nodeB.pos[0], nodeB.pos[1]], posA, 200); + } + + graph.change(); + canvas.setDirty(true, true); +} + +app.registerExtension({ + name: "KJNodes.NodeSwap", + + settings: [ + { + id: "KJNodes.nodeSwapEnabled", + name: "Enable node swap on drag", + category: ["KJNodes", "Node Swap", "Enable"], + tooltip: "Hold swap key (default: S, rebindable in Keybindings) and drag a node onto another to swap their positions and reconnect links", + type: "boolean", + defaultValue: true, + }, + ], + commands: [ + { + id: "KJNodes.ToggleNodeSwap", + label: "Toggle node swap on drag", + active: () => app.ui.settings.getSettingValue("KJNodes.nodeSwapEnabled"), + function: () => { + const cur = app.ui.settings.getSettingValue("KJNodes.nodeSwapEnabled"); + app.ui.settings.setSettingValue("KJNodes.nodeSwapEnabled", !cur); + }, + }, + { + id: "KJNodes.NodeSwapMode", + label: "Node swap mode (hold to activate)", + active: () => swapKeyDown, + function: () => { + swapKeyDown = true; + // If already dragging a node, check for overlap immediately + // (handles case where node is already on top of another when key is pressed) + if (swapDraggedNode) { + const graph = app.canvas?.graph || app.graph; + if (graph) { + swapTargetNode = getOverlappingNode(graph, swapDraggedNode); + if (swapTargetNode) startHighlightAnim(app.canvas); + } + } + }, + }, + ], + keybindings: [ + { + commandId: "KJNodes.NodeSwapMode", + combo: { key: "s" }, + targetElementId: "graph-canvas", + }, + ], + + async setup() { + await new Promise((resolve) => { + function check() { + if (app.canvas) return resolve(); + requestAnimationFrame(check); + } + check(); + }); + + const lgCanvas = app.canvas; + const canvasEl = lgCanvas.canvas; + + // The command system handles keydown (sets swapKeyDown = true). + // Any keyup clears it since the user must hold the key. + document.addEventListener("keyup", () => { + if (swapKeyDown) { + swapKeyDown = false; + if (swapTargetNode) { + swapTargetNode = null; + lgCanvas.setDirty(false, true); + } + } + }); + + // Pointermove/pointerup handlers — only attached while pointer is down. + function onPointerMove() { + swapHasMoved = true; + + if (!swapKeyDown) { + if (swapTargetNode) { + swapTargetNode = null; + lgCanvas.setDirty(false, true); + } + return; + } + + if (!swapDraggedNode) return; + + const graph = lgCanvas.graph || app.graph; + if (!graph) return; + + const prev = swapTargetNode; + swapTargetNode = getOverlappingNode(graph, swapDraggedNode); + + if (swapTargetNode && !prev) { + startHighlightAnim(lgCanvas); + } + } + + function onPointerUp(e) { + if (e.button !== 0) return; + + document.removeEventListener("pointermove", onPointerMove); + document.removeEventListener("pointerup", onPointerUp, true); + + const targetNode = swapTargetNode; + const draggedNode = swapDraggedNode; + const startPos = swapDragStartPos; + const hasMoved = swapHasMoved; + clearSwapState(); + + if (!hasMoved || !targetNode || !draggedNode || !swapKeyDown) return; + + if (!targetNode.flags?.pinned && !draggedNode.flags?.pinned) { + executeNodeSwap(lgCanvas, draggedNode, targetNode, startPos); + } + } + + // Record clicked node and its original position. + // Listen on document to catch events from both the canvas and Vue node overlays. + const graphContainer = canvasEl.closest(".graph-canvas-container") || canvasEl.parentElement; + document.addEventListener("pointerdown", (e) => { + if (e.button !== 0) return; + if (!app.ui.settings.getSettingValue("KJNodes.nodeSwapEnabled")) return; + if (!graphContainer?.contains(e.target)) return; + + swapHasMoved = false; + + const graph = lgCanvas.graph || app.graph; + if (!graph) return; + + const [cx, cy] = clientToCanvas(lgCanvas, e.clientX, e.clientY); + const node = getNodeAtPoint(graph, cx, cy); + + if (node && (node.inputs || node.outputs)) { + swapDraggedNode = node; + swapDragStartPos = [node.pos[0], node.pos[1]]; + document.addEventListener("pointermove", onPointerMove); + document.addEventListener("pointerup", onPointerUp, true); + } + }, true); + + // Draw pulsing glow outline on the swap target node + const origOnDrawBg = lgCanvas.onDrawBackground; + lgCanvas.onDrawBackground = function (ctx, ...args) { + origOnDrawBg?.call(this, ctx, ...args); + + const target = swapTargetNode; + if (!target) return; + + const [x, y] = target.pos; + const w = target.size[0] || 100; + const h = target.size[1] || 60; + const titleH = LiteGraph.NODE_TITLE_HEIGHT || 20; + const pulse = 0.5 + 0.3 * Math.sin(Date.now() / 200); + const isPinned = target.flags?.pinned; + const color = isPinned ? "255, 80, 80" : "100, 200, 255"; + const pad = 5; + + ctx.save(); + ctx.strokeStyle = `rgba(${color}, ${pulse})`; + ctx.lineWidth = 3; + ctx.shadowColor = `rgba(${color}, 0.8)`; + ctx.shadowBlur = 15; + ctx.beginPath(); + ctx.roundRect(x - pad, y - titleH - pad, w + pad * 2, h + titleH + pad * 2, 8); + ctx.stroke(); + ctx.fillStyle = `rgba(${color}, ${isPinned ? 0.08 : 0.05})`; + ctx.fill(); + ctx.restore(); + }; + }, +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/performance.js b/.disabled/comfyui-kjnodes@nightly/web/js/performance.js new file mode 100644 index 0000000000000000000000000000000000000000..c80b39bd671a1df1875ae5aca2e32456350077c2 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/performance.js @@ -0,0 +1,286 @@ +const { app } = window.comfyAPI.app; + +const _savedRoundRadius = typeof LiteGraph !== "undefined" ? LiteGraph.ROUND_RADIUS : 8; + +function getSetting(id, fallback) { + return app.ui.settings.getSettingValue(id) ?? fallback; +} + +function toggleSetting(id) { + const cur = app.ui.settings.getSettingValue(id); + app.ui.settings.setSettingValue(id, !cur); +} + +app.registerExtension({ + name: "KJNodes.Performance", + + commands: [ + { + id: "KJNodes.perf.toggleSingleCanvasPan", + label: "Single-canvas mode during pan", + menubarLabel: "Single-canvas mode during pan", + function: () => toggleSetting("KJNodes.perf.singleCanvasPan"), + active: () => getSetting("KJNodes.perf.singleCanvasPan", false), + }, + { + id: "KJNodes.perf.toggleDisableShadows", + label: "Disable node shadows", + menubarLabel: "Disable node shadows", + function: () => toggleSetting("KJNodes.perf.disableShadows"), + active: () => getSetting("KJNodes.perf.disableShadows", false), + }, + { + id: "KJNodes.perf.toggleDisableConnectionBorders", + label: "Disable connection borders", + menubarLabel: "Disable connection borders", + function: () => toggleSetting("KJNodes.perf.disableConnectionBorders"), + active: () => getSetting("KJNodes.perf.disableConnectionBorders", false), + }, + { + id: "KJNodes.perf.toggleDisableRoundedCorners", + label: "Disable rounded corners", + menubarLabel: "Disable rounded corners", + function: () => toggleSetting("KJNodes.perf.disableRoundedCorners"), + active: () => getSetting("KJNodes.perf.disableRoundedCorners", false), + }, + { + id: "KJNodes.perf.toggleThrottleRenderInfo", + label: "Throttle info overlay", + menubarLabel: "Throttle info overlay", + function: () => toggleSetting("KJNodes.perf.throttleRenderInfo"), + active: () => getSetting("KJNodes.perf.throttleRenderInfo", false), + }, + ], + + menuCommands: [ + { + path: ["KJNodes", "Performance"], + commands: [ + "KJNodes.perf.toggleSingleCanvasPan", + "KJNodes.perf.toggleDisableShadows", + "KJNodes.perf.toggleDisableConnectionBorders", + "KJNodes.perf.toggleDisableRoundedCorners", + "KJNodes.perf.toggleThrottleRenderInfo", + ], + }, + ], + + settings: [ + { + id: "KJNodes.perf.singleCanvasPan", + name: "Single-canvas mode during pan", + category: ["KJNodes", "Performance", "Single-canvas mode during pan"], + tooltip: "Eliminates the expensive bgcanvas-to-canvas copy during panning. Significant improvement without hardware acceleration.", + type: "boolean", + defaultValue: false, + onChange: (value) => { + const canvas = app.canvas; + if (!canvas) return; + if (value) { + installSingleCanvasPan(canvas); + } else { + uninstallSingleCanvasPan(canvas); + } + }, + }, + { + id: "KJNodes.perf.disableShadows", + name: "Disable node shadows", + category: ["KJNodes", "Performance", "Disable node shadows"], + tooltip: "Disable shadow rendering on nodes for better performance without hardware acceleration.", + type: "boolean", + defaultValue: false, + onChange: (value) => { + if (app.canvas) { + app.canvas.render_shadows = !value; + app.canvas.setDirty(true, true); + } + }, + }, + { + id: "KJNodes.perf.disableConnectionBorders", + name: "Disable connection borders", + category: ["KJNodes", "Performance", "Disable connection borders"], + tooltip: "Disable the outer border stroke on connection lines. Each link draws two strokes instead of one when enabled.", + type: "boolean", + defaultValue: false, + onChange: (value) => { + if (app.canvas) { + app.canvas.render_connections_border = !value; + app.canvas.setDirty(true, true); + } + }, + }, + { + id: "KJNodes.perf.disableRoundedCorners", + name: "Disable rounded corners", + category: ["KJNodes", "Performance", "Disable rounded corners"], + tooltip: "Use square corners on nodes instead of rounded. Avoids roundRect calls in software rendering.", + type: "boolean", + defaultValue: false, + onChange: (value) => { + if (typeof LiteGraph !== "undefined") { + LiteGraph.ROUND_RADIUS = value ? 0 : _savedRoundRadius; + app.canvas?.setDirty(true, true); + } + }, + }, + { + id: "KJNodes.perf.throttleRenderInfo", + name: "Throttle info overlay", + category: ["KJNodes", "Performance", "Throttle info overlay"], + tooltip: "Cache the FPS/info text overlay and only re-render it a few times per second. Saves ~20ms per frame in software rendering.", + type: "boolean", + defaultValue: false, + onChange: (value) => { + const canvas = app.canvas; + if (!canvas) return; + if (value) { + installThrottleRenderInfo(canvas); + } else { + uninstallThrottleRenderInfo(canvas); + } + }, + }, + ], + + setup() { + const canvas = app.canvas; + if (!canvas) return; + + if (getSetting("KJNodes.perf.singleCanvasPan", false)) { + installSingleCanvasPan(canvas); + } + if (getSetting("KJNodes.perf.disableShadows", false)) { + canvas.render_shadows = false; + } + if (getSetting("KJNodes.perf.disableConnectionBorders", false)) { + canvas.render_connections_border = false; + } + if (getSetting("KJNodes.perf.disableRoundedCorners", false)) { + LiteGraph.ROUND_RADIUS = 0; + } + if (getSetting("KJNodes.perf.throttleRenderInfo", false)) { + installThrottleRenderInfo(canvas); + } + }, +}); + +// ── Single-canvas mode during pan ─────────────────────────────────────────── + +let _origDraw = null; +let _panInstalledOn = null; + +function installSingleCanvasPan(canvas) { + if (_origDraw && _panInstalledOn === canvas) return; + if (_origDraw && _panInstalledOn !== canvas) { + // Canvas was replaced — discard stale reference + _origDraw = null; + } + _panInstalledOn = canvas; + _origDraw = canvas.draw; + let panning = false; + let savedBgCanvas = null; + let savedBgCtx = null; + + canvas.draw = function (force_canvas, force_bgcanvas) { + if (this.dragging_canvas) { + if (!panning) { + // Flush any pending bg redraw before aliasing to avoid a stale-frame flash + if (this.dirty_bgcanvas) { + _origDraw.call(this, false, true); + } + savedBgCanvas = this.bgcanvas; + savedBgCtx = this.bgctx; + panning = true; + this.bgcanvas = this.canvas; + this.bgctx = this.ctx; + } + } else if (panning) { + panning = false; + this.bgcanvas = savedBgCanvas; + this.bgctx = savedBgCtx; + this.dirty_bgcanvas = true; + this.dirty_canvas = true; + } + _origDraw.call(this, force_canvas, force_bgcanvas); + }; +} + +function uninstallSingleCanvasPan(canvas) { + if (!_origDraw) return; + if (_panInstalledOn === canvas) { + canvas.draw = _origDraw; + } + _origDraw = null; + _panInstalledOn = null; + canvas.dirty_bgcanvas = true; + canvas.dirty_canvas = true; +} + +// ── Throttle renderInfo ───────────────────────────────────────────────────── + +let _origRenderInfo = null; +let _infoCanvas = null; +let _infoInstalledOn = null; + +function installThrottleRenderInfo(canvas) { + if (_origRenderInfo && _infoInstalledOn === canvas) return; + if (_origRenderInfo && _infoInstalledOn !== canvas) { + _origRenderInfo = null; + _infoCanvas = null; + } + _infoInstalledOn = canvas; + _origRenderInfo = canvas.renderInfo; + _infoCanvas = document.createElement("canvas"); + let infoCtx = _infoCanvas.getContext("2d"); + let lastInfoTime = 0; + let cachedDpr = 0; + let _infoDrawX = 10; + let _infoDrawY = 0; + + canvas.renderInfo = function (ctx, x, y) { + const dpr = window.devicePixelRatio || 1; + + // Resize offscreen canvas if DPR changed + if (dpr !== cachedDpr) { + cachedDpr = dpr; + _infoCanvas.width = Math.ceil(200 * dpr); + _infoCanvas.height = Math.ceil(100 * dpr); + infoCtx = _infoCanvas.getContext("2d"); + infoCtx.scale(dpr, dpr); + lastInfoTime = 0; + } + + const now = performance.now(); + if (now - lastInfoTime > 250) { + lastInfoTime = now; + infoCtx.clearRect(0, 0, 200, 100); + // Render with the same x/y the original would use, but offset + // into offscreen canvas coordinates + const origX = x || 10; + const lineHeight = 13; + const lineCount = (this.graph ? 5 : 1) + (this.info_text ? 1 : 0); + const origY = y || (this.canvas.height / dpr - (lineCount + 1) * lineHeight); + // Store the computed position for blitting + _infoDrawX = origX; + _infoDrawY = origY; + // Draw into offscreen at (1, 1), text flows from there + _origRenderInfo.call(this, infoCtx, 1, 1); + } + + // Blit cached text at the original position + ctx.drawImage(_infoCanvas, _infoDrawX - 1, _infoDrawY - 1, 200, 100); + }; +} + +function uninstallThrottleRenderInfo(canvas) { + if (!_origRenderInfo) return; + if (_infoInstalledOn === canvas) { + canvas.renderInfo = _origRenderInfo; + } + _origRenderInfo = null; + _infoCanvas = null; + _infoInstalledOn = null; + canvas.setDirty(true, true); +} diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/play_sound.js b/.disabled/comfyui-kjnodes@nightly/web/js/play_sound.js new file mode 100644 index 0000000000000000000000000000000000000000..6b78000af63750a566c4503ac37cecfbb9c5c889 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/play_sound.js @@ -0,0 +1,94 @@ +const { app } = window.comfyAPI.app; +const { api } = window.comfyAPI.api; + +app.registerExtension({ + name: "KJNodes.PlaySound", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "PlaySoundKJ") return; + + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (output) { + onExecuted?.call(this, output); + + const audios = output?.audio; + if (!audios?.length) return; + + const modeWidget = this.widgets?.find(w => w.name === "mode"); + const volumeWidget = this.widgets?.find(w => w.name === "volume"); + const durationWidget = this.widgets?.find(w => w.name === "duration"); + const mode = modeWidget?.value ?? "always"; + const volume = volumeWidget?.value ?? 0.5; + const duration = durationWidget?.value ?? 0; + + // on_change: skip if audio content hasn't changed + if (mode === "on_change") { + const audioHash = output?.audio_hash?.[0]; + if (audioHash != null && this._kjLastAudioHash === audioHash) return; + this._kjLastAudioHash = audioHash; + } + + // Clean up previous state + if (this._kjStatusListener) { + api.removeEventListener("status", this._kjStatusListener); + this._kjStatusListener = null; + } + clearTimeout(this._kjQueueDebounce); + this._kjPendingAudio = null; + + if (this._kjPlayingAudio) { + this._kjPlayingAudio.pause(); + this._kjPlayingAudio = null; + } + if (this._kjPlayTimer != null) { + clearTimeout(this._kjPlayTimer); + this._kjPlayTimer = null; + } + + const startPlayback = () => { + const { filename, subfolder, type } = audios[0]; + const params = new URLSearchParams({ + filename: filename ?? "", + subfolder: subfolder ?? "", + type: type ?? "temp", + }); + const url = api.apiURL(`/view?${params.toString()}`); + const audio = new Audio(url); + audio.volume = Math.max(0, Math.min(1, volume)); + audio.play().catch(() => {}); + this._kjPlayingAudio = audio; + if (duration > 0) { + this._kjPlayTimer = setTimeout(() => { + audio.pause(); + this._kjPlayingAudio = null; + this._kjPlayTimer = null; + }, duration * 1000); + } + }; + + if (mode === "on_empty_queue") { + this._kjPendingAudio = startPlayback; + this._kjStatusListener = ({ detail }) => { + const remaining = detail?.exec_info?.queue_remaining ?? 0; + if (remaining === 0) { + // Debounce: confirm queue is truly empty + // (status can briefly show 0 between dispatches) + clearTimeout(this._kjQueueDebounce); + this._kjQueueDebounce = setTimeout(() => { + if (this._kjPendingAudio) { + this._kjPendingAudio(); + this._kjPendingAudio = null; + } + api.removeEventListener("status", this._kjStatusListener); + this._kjStatusListener = null; + }, 1000); + } else { + clearTimeout(this._kjQueueDebounce); + } + }; + api.addEventListener("status", this._kjStatusListener); + } else { + startPlayback(); + } + }; + }, +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/screencap_stream.js b/.disabled/comfyui-kjnodes@nightly/web/js/screencap_stream.js new file mode 100644 index 0000000000000000000000000000000000000000..9ff010e2e28e334881e84fac2db70dcc6f8fff4e --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/screencap_stream.js @@ -0,0 +1,500 @@ +import { addMiddleClickPan, addWheelPassthrough } from "./utility.js"; +const { app } = window.comfyAPI.app; + +app.registerExtension({ + name: "KJNodes.ScreencapStream", + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "ScreencapStream") return; + + nodeType.prototype.onNodeCreated = function () { + const node = this; + const frameWidget = this.widgets.find(w => w.name === "frame_data"); + frameWidget.computeSize = () => [0, -4]; + + // --- State --- + let stream = null; + let crop = null; // { x, y, w, h } in video pixel coords, or null + let previewVisible = true; + let previewInterval = null; + let bitmapInterval = null; + let cachedBitmap = null; // downscaled ImageBitmap for preview + let bitmapPending = false; + let drag = null; + let drawPending = false; + let cachedLayout = null; + let layoutDirty = true; + let updatingFromCrop = false; + let captureStartTime = null; + let timerInterval = null; + + const EDGE = 8; + // separate canvases to avoid conflicts between preview and serialization + const serializeCanvas = document.createElement("canvas"); + const serializeCtx = serializeCanvas.getContext("2d"); + + // --- DOM elements --- + const video = document.createElement("video"); + video.autoplay = true; + video.muted = true; + video.style.cssText = "position:absolute;width:1px;height:1px;opacity:0;pointer-events:none;overflow:hidden;"; + + const container = document.createElement("div"); + container.style.cssText = "width:100%;height:100%;background:#000;border-radius:4px;overflow:hidden;position:relative;"; + container.appendChild(video); + + const overlay = document.createElement("canvas"); + overlay.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;cursor:crosshair;"; + container.appendChild(overlay); + const overlayCtx = overlay.getContext("2d"); + + addMiddleClickPan(container); + addWheelPassthrough(container); + + // --- Widget references --- + const cropWWidget = node.widgets.find(w => w.name === "crop_width"); + const cropHWidget = node.widgets.find(w => w.name === "crop_height"); + const PREVIEW_MAX_RES = 960; // preview-only cap for performance + + // --- Layout --- + function invalidateLayout() { layoutDirty = true; } + + function getLayout() { + if (!layoutDirty && cachedLayout) return cachedLayout; + const oRect = overlay.getBoundingClientRect(); + const vw = video.videoWidth, vh = video.videoHeight; + if (!vw || !vh || !oRect.width || !oRect.height) { cachedLayout = null; return null; } + const scale = Math.min(oRect.width / vw, oRect.height / vh); + cachedLayout = { + scale, vw, vh, + offX: (oRect.width - vw * scale) / 2, + offY: (oRect.height - vh * scale) / 2, + }; + layoutDirty = false; + return cachedLayout; + } + + function toVideoCoords(cx, cy) { + const L = getLayout(); + if (!L) return { x: 0, y: 0 }; + return { + x: Math.round(Math.max(0, Math.min(L.vw, (cx - L.offX) / L.scale))), + y: Math.round(Math.max(0, Math.min(L.vh, (cy - L.offY) / L.scale))), + }; + } + + function pointerToLocal(e) { + const r = overlay.getBoundingClientRect(); + return { x: e.clientX - r.left, y: e.clientY - r.top }; + } + + // --- Output dimensions --- + // Single source of truth for what the output size will be. + function getOutputDimensions() { + const vw = video.videoWidth, vh = video.videoHeight; + if (!vw || !vh) return null; + const sw = crop ? crop.w : vw; + const sh = crop ? crop.h : vh; + return { w: sw, h: sh }; + } + + function updateSizeWidgets() { + updatingFromCrop = true; + const dims = getOutputDimensions(); + if (dims) { + cropWWidget.value = dims.w; + cropHWidget.value = dims.h; + // clamp max to full capture dimensions + if (cropWWidget.options) cropWWidget.options.max = video.videoWidth || dims.w; + if (cropHWidget.options) cropHWidget.options.max = video.videoHeight || dims.h; + } + app.graph.setDirtyCanvas(true); + updatingFromCrop = false; + } + + function updateCropFromWidgets() { + if (updatingFromCrop || !video.videoWidth || !crop) return; + const newW = Math.min(cropWWidget.value, video.videoWidth); + const newH = Math.min(cropHWidget.value, video.videoHeight); + if (newW <= 0 || newH <= 0) return; + const cx = crop.x + crop.w / 2; + const cy = crop.y + crop.h / 2; + let x = Math.round(cx - newW / 2); + let y = Math.round(cy - newH / 2); + x = Math.max(0, Math.min(x, video.videoWidth - newW)); + y = Math.max(0, Math.min(y, video.videoHeight - newH)); + crop = { x, y, w: newW, h: newH }; + drawOverlay(); + } + + function clearCrop() { + if (video.videoWidth && video.videoHeight) { + crop = { x: 0, y: 0, w: video.videoWidth, h: video.videoHeight }; + } else { + crop = null; + } + drawOverlay(); + updateSizeWidgets(); + } + + // --- Cached bitmap --- + // Updated every 500ms for preview display. + // Downscaled to PREVIEW_MAX_RES for performance. + async function updateCachedBitmap() { + if (bitmapPending || !stream || !video.videoWidth) return; + bitmapPending = true; + try { + const vw = video.videoWidth, vh = video.videoHeight; + if (vw <= 0 || vh <= 0) { bitmapPending = false; return; } + // always full frame for preview — crop is drawn as overlay + let outW = vw, outH = vh; + if (Math.max(vw, vh) > PREVIEW_MAX_RES) { + const s = PREVIEW_MAX_RES / Math.max(vw, vh); + outW = Math.round(vw * s); + outH = Math.round(vh * s); + } + const bmp = await createImageBitmap(video, { + resizeWidth: outW, + resizeHeight: outH, + resizeQuality: "medium", + }); + if (cachedBitmap) cachedBitmap.close(); + cachedBitmap = bmp; + } catch { /* frame not ready */ } + bitmapPending = false; + } + + function startBitmapLoop() { + stopBitmapLoop(); + bitmapInterval = setInterval(updateCachedBitmap, 500); + } + function stopBitmapLoop() { + if (bitmapInterval) { clearInterval(bitmapInterval); bitmapInterval = null; } + } + + // --- Preview drawing --- + function drawOverlay() { + if (drawPending) return; + drawPending = true; + requestAnimationFrame(() => { + drawPending = false; + renderOverlay(); + }); + } + + function renderOverlay() { + const r = overlay.getBoundingClientRect(); + const w = Math.round(r.width), h = Math.round(r.height); + if (overlay.width !== w || overlay.height !== h) { + overlay.width = w; overlay.height = h; + invalidateLayout(); + } + overlayCtx.clearRect(0, 0, w, h); + if (!previewVisible) return; + const L = getLayout(); + if (!L) return; + + // draw from cached bitmap if available, else raw video + const src = cachedBitmap || video; + overlayCtx.drawImage(src, L.offX, L.offY, L.vw * L.scale, L.vh * L.scale); + + if (!crop) return; + + const rx = L.offX + crop.x * L.scale; + const ry = L.offY + crop.y * L.scale; + const rw = crop.w * L.scale; + const rh = crop.h * L.scale; + + // darken outside crop + overlayCtx.fillStyle = "rgba(0,0,0,0.5)"; + overlayCtx.fillRect(0, 0, w, ry); + overlayCtx.fillRect(0, ry + rh, w, h - ry - rh); + overlayCtx.fillRect(0, ry, rx, rh); + overlayCtx.fillRect(rx + rw, ry, w - rx - rw, rh); + + overlayCtx.strokeStyle = "#fff"; + overlayCtx.lineWidth = 1.5; + overlayCtx.setLineDash([4, 3]); + overlayCtx.strokeRect(rx, ry, rw, rh); + overlayCtx.setLineDash([]); + } + + function startPreviewLoop() { + stopPreviewLoop(); + previewInterval = setInterval(() => drawOverlay(), 100); + } + function stopPreviewLoop() { + if (previewInterval) { clearInterval(previewInterval); previewInterval = null; } + } + + // --- Hit testing --- + function hitTest(lx, ly) { + if (!crop) return "draw"; + const L = getLayout(); + if (!L) return "draw"; + const rx = L.offX + crop.x * L.scale; + const ry = L.offY + crop.y * L.scale; + const rw = crop.w * L.scale; + const rh = crop.h * L.scale; + + const nearL = Math.abs(lx - rx) < EDGE; + const nearR = Math.abs(lx - (rx + rw)) < EDGE; + const nearT = Math.abs(ly - ry) < EDGE; + const nearB = Math.abs(ly - (ry + rh)) < EDGE; + const inX = lx > rx - EDGE && lx < rx + rw + EDGE; + const inY = ly > ry - EDGE && ly < ry + rh + EDGE; + + if (nearT && nearL && inX && inY) return "nw"; + if (nearT && nearR && inX && inY) return "ne"; + if (nearB && nearL && inX && inY) return "sw"; + if (nearB && nearR && inX && inY) return "se"; + if (nearT && inX) return "n"; + if (nearB && inX) return "s"; + if (nearL && inY) return "w"; + if (nearR && inY) return "e"; + if (lx > rx && lx < rx + rw && ly > ry && ly < ry + rh) return "move"; + return "draw"; + } + + const cursorMap = { + nw: "nwse-resize", se: "nwse-resize", + ne: "nesw-resize", sw: "nesw-resize", + n: "ns-resize", s: "ns-resize", + w: "ew-resize", e: "ew-resize", + move: "grab", draw: "crosshair", + }; + + // --- Widget callbacks --- + const origWCb = cropWWidget.callback; + const origHCb = cropHWidget.callback; + cropWWidget.callback = function() { origWCb?.apply(this, arguments); updateCropFromWidgets(); }; + cropHWidget.callback = function() { origHCb?.apply(this, arguments); updateCropFromWidgets(); }; + + // --- Pointer events --- + overlay.addEventListener("pointermove", (e) => { + if (drag) { + e.stopPropagation(); + e.preventDefault(); + const p = pointerToLocal(e); + const v = toVideoCoords(p.x, p.y); + const dx = v.x - drag.startVX; + const dy = v.y - drag.startVY; + const o = drag.origCrop; + const maxW = video.videoWidth, maxH = video.videoHeight; + + if (drag.type === "draw") { + let w = Math.abs(v.x - drag.startVX); + let h = Math.abs(v.y - drag.startVY); + if (e.shiftKey && w > 0 && h > 0) { + const aspect = drag.aspect || w / h; + drag.aspect = aspect; + if (w / h > aspect) w = Math.round(h * aspect); + else h = Math.round(w / aspect); + } else { + drag.aspect = null; + } + crop = { + x: v.x < drag.startVX ? drag.startVX - w : drag.startVX, + y: v.y < drag.startVY ? drag.startVY - h : drag.startVY, + w, h, + }; + } else if (drag.type === "move") { + let nx = o.x + dx, ny = o.y + dy; + nx = Math.max(0, Math.min(maxW - o.w, nx)); + ny = Math.max(0, Math.min(maxH - o.h, ny)); + crop = { x: nx, y: ny, w: o.w, h: o.h }; + } else { + let { x, y, w, h } = { ...o }; + if (drag.type.includes("w")) { x = o.x + dx; w = o.w - dx; } + if (drag.type.includes("e")) { w = o.w + dx; } + if (drag.type.includes("n")) { y = o.y + dy; h = o.h - dy; } + if (drag.type.includes("s")) { h = o.h + dy; } + if (w < 0) { x += w; w = -w; } + if (h < 0) { y += h; h = -h; } + if (e.shiftKey && o.w > 0 && o.h > 0 && w > 0 && h > 0) { + const aspect = o.w / o.h; + if (drag.type.length === 2) { + if (w / h > aspect) w = Math.round(h * aspect); + else h = Math.round(w / aspect); + if (drag.type.includes("w")) x = o.x + o.w - w; + if (drag.type.includes("n")) y = o.y + o.h - h; + } else if (drag.type === "n" || drag.type === "s") { + w = Math.round(h * aspect); + x = o.x + Math.round((o.w - w) / 2); + } else { + h = Math.round(w / aspect); + y = o.y + Math.round((o.h - h) / 2); + } + } + x = Math.max(0, x); y = Math.max(0, y); + w = Math.min(w, maxW - x); h = Math.min(h, maxH - y); + crop = { x, y, w, h }; + } + drawOverlay(); + updateSizeWidgets(); + return; + } + if (!previewVisible || !stream) return; + const p = pointerToLocal(e); + overlay.style.cursor = cursorMap[hitTest(p.x, p.y)]; + }); + + overlay.addEventListener("pointerdown", (e) => { + if (!previewVisible || !stream) return; + e.stopPropagation(); + e.preventDefault(); + overlay.setPointerCapture(e.pointerId); + const p = pointerToLocal(e); + const type = hitTest(p.x, p.y); + const v = toVideoCoords(p.x, p.y); + drag = { + type, + startVX: v.x, startVY: v.y, + origCrop: crop ? { ...crop } : null, + }; + if (type === "move") overlay.style.cursor = "grabbing"; + }); + + overlay.addEventListener("pointerup", (e) => { + if (!drag) return; + e.stopPropagation(); + if (drag.type === "move") overlay.style.cursor = "grab"; + drag = null; + if (crop && (crop.w < 5 || crop.h < 5)) { + crop = { x: 0, y: 0, w: video.videoWidth, h: video.videoHeight }; + } + drawOverlay(); + updateSizeWidgets(); + }); + + overlay.addEventListener("dblclick", (e) => { + e.stopPropagation(); + e.preventDefault(); + clearCrop(); + }); + + overlay.addEventListener("contextmenu", (e) => { + e.stopPropagation(); + e.preventDefault(); + clearCrop(); + }); + + // --- Resize observer --- + const resizeObs = new ResizeObserver(() => { invalidateLayout(); drawOverlay(); }); + resizeObs.observe(container); + + // --- Timer --- + function formatElapsed(ms) { + const s = Math.floor(ms / 1000); + const m = Math.floor(s / 60); + const h = Math.floor(m / 60); + const pad = (n) => String(n).padStart(2, "0"); + if (h > 0) return `${h}:${pad(m % 60)}:${pad(s % 60)}`; + return `${m}:${pad(s % 60)}`; + } + + function updateBtnTimer() { + if (!captureStartTime || !btnWidget) return; + const elapsed = formatElapsed(Date.now() - captureStartTime); + btnWidget.name = `\uD83D\uDD34 ${elapsed} - Stop capture`; + app.graph.setDirtyCanvas(true); + } + + function startTimer() { + captureStartTime = Date.now(); + timerInterval = setInterval(updateBtnTimer, 1000); + updateBtnTimer(); + } + + function stopTimer() { + if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } + captureStartTime = null; + } + + // --- Stream management --- + let btnWidget = null; + + function stopStream() { + stopPreviewLoop(); + stopBitmapLoop(); + stopTimer(); + if (cachedBitmap) { cachedBitmap.close(); cachedBitmap = null; } + if (stream) stream.getTracks().forEach(t => t.stop()); + stream = null; + crop = null; + video.srcObject = null; + if (btnWidget) btnWidget.name = "Start capture"; + app.graph.setDirtyCanvas(true); + } + + btnWidget = this.addWidget("button", "Start capture", null, async () => { + if (stream) { stopStream(); return; } + try { + // capture at native resolution — browser constraints + // cause green tint. Preview is downscaled via + // createImageBitmap, output goes to Python at full res. + stream = await navigator.mediaDevices.getDisplayMedia({ + video: { frameRate: { ideal: 5, max: 10 } }, + }); + video.srcObject = stream; + startTimer(); + const track = stream.getVideoTracks()[0]; + track.addEventListener("ended", stopStream); + video.addEventListener("loadedmetadata", () => { + crop = { x: 0, y: 0, w: video.videoWidth, h: video.videoHeight }; + invalidateLayout(); + updateSizeWidgets(); + startBitmapLoop(); + if (previewVisible) startPreviewLoop(); + }, { once: true }); + } catch { /* user cancelled */ } + }); + + // --- DOM widget --- + this.addDOMWidget("preview", "ScreencapPreview", container, { + serialize: false, + hideOnZoom: false, + getMinHeight: () => 200, + }); + + const previewBtn = this.addWidget("button", "Hide preview", null, () => { + previewVisible = !previewVisible; + previewBtn.name = previewVisible ? "Hide preview" : "Show preview"; + if (previewVisible && stream) { + invalidateLayout(); + startBitmapLoop(); + startPreviewLoop(); + } else { + stopPreviewLoop(); + stopBitmapLoop(); + overlayCtx.clearRect(0, 0, overlay.width, overlay.height); + } + app.graph.setDirtyCanvas(true); + }); + + // --- Frame serialization --- + // Always send full crop resolution to Python. + // Python handles downscaling with Lanczos for better quality. + frameWidget.serializeValue = () => { + if (!stream || !video.videoWidth) return ""; + const vw = video.videoWidth, vh = video.videoHeight; + const sx = crop ? Math.min(crop.x, vw) : 0; + const sy = crop ? Math.min(crop.y, vh) : 0; + const sw = crop ? Math.min(crop.w, vw - sx) : vw; + const sh = crop ? Math.min(crop.h, vh - sy) : vh; + if (sw <= 0 || sh <= 0) return ""; + serializeCanvas.width = sw; + serializeCanvas.height = sh; + serializeCtx.drawImage(video, sx, sy, sw, sh, 0, 0, sw, sh); + return serializeCanvas.toDataURL("image/png"); + }; + + // --- Cleanup --- + const origOnRemoved = this.onRemoved; + this.onRemoved = function () { + stopStream(); + resizeObs.disconnect(); + origOnRemoved?.apply(this, arguments); + }; + }; + }, +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/setgetnodes.js b/.disabled/comfyui-kjnodes@nightly/web/js/setgetnodes.js new file mode 100644 index 0000000000000000000000000000000000000000..692b4d70934034fa06e3ce4f10f2bc5342e678d8 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/setgetnodes.js @@ -0,0 +1,1544 @@ +const { app } = window.comfyAPI.app; + +// originally based on diffus3's SetGet: https://github.com/diffus3/ComfyUI-extensions + +// Nodes that allow you to hide connections for cleaner graphs + +let _typeColorMap; +function setColorAndBgColor(node, type) { + if (!_typeColorMap) { + _typeColorMap = { + "DEFAULT": LGraphCanvas.node_colors.gray, + "MODEL": LGraphCanvas.node_colors.blue, + "LATENT": LGraphCanvas.node_colors.purple, + "VAE": LGraphCanvas.node_colors.red, + "WANVAE": LGraphCanvas.node_colors.red, + "CONDITIONING": LGraphCanvas.node_colors.brown, + "IMAGE": LGraphCanvas.node_colors.pale_blue, + "CLIP": LGraphCanvas.node_colors.yellow, + "FLOAT": LGraphCanvas.node_colors.green, + "MASK": { color: "#1c5715", bgcolor: "#1f401b"}, + "INT": { color: "#1b4669", bgcolor: "#29699c"}, + "CONTROL_NET": { color: "#156653", bgcolor: "#1c453b"}, + "NOISE": { color: "#2e2e2e", bgcolor: "#242121"}, + "GUIDER": { color: "#3c7878", bgcolor: "#1c453b"}, + "SAMPLER": { color: "#614a4a", bgcolor: "#3b2c2c"}, + "SIGMAS": { color: "#485248", bgcolor: "#272e27"}, + }; + } + const colors = _typeColorMap[type] || LGraphCanvas.node_colors?.gray; + if (colors) { + node.color = colors.color; + node.bgcolor = colors.bgcolor; + } +} +function getDisablePrefix() { + return app.ui.settings.getSettingValue("KJNodes.disablePrefix") ?? false; +} +function prefixedTitle(prefix, name) { + return (getDisablePrefix() ? "" : prefix + "_") + name; +} +function autoColor(node, type) { + if (!app.ui.settings.getSettingValue("KJNodes.nodeAutoColor")) return; + if (type === '*') { node.color = null; node.bgcolor = null; } + else setColorAndBgColor(node, type); +} +function addNodeToSelectedOrCursor(nodeType, side) { + const selected = Object.values(app.canvas.selected_nodes || {}); + if (selected.length > 0) { + for (const n of selected) window.kjNodes.addNode(nodeType, n, { side, offset: 30 }); + } else { + const canvas = app.canvas, graph = canvas.graph || app.graph; + const node = LiteGraph.createNode(nodeType); + if (!node) return; + node.pos = [canvas.graph_mouse[0], canvas.graph_mouse[1]]; + graph.add(node); + canvas.selectNode(node, false); + canvas.setDirty(true, true); + } +} +// Temporary map for paste rename coordination between Set and Get nodes. +// Key: old name, Value: new name. Cleared via setTimeout(0) after each paste cycle. +// This works because both onConfigure calls (Set + Get) fire synchronously within +// the same paste operation, before the timeout clears the entry. +const _pasteRenameMap = new Map(); + +let _forceShowAllLinks = false; + +function getShowLinksMode() { + if (_forceShowAllLinks) return "always"; + return app.ui.settings.getSettingValue("KJNodes.showSetGetLinks") ?? "never"; +} +const LGraphNode = LiteGraph.LGraphNode + +// Cross-graph traversal utilities with lexical scoping for subgraph support. +// Set nodes propagate downward: a Set in a parent graph is visible to all descendant subgraphs. +// Get nodes look upward: a Get searches its own graph first, then parent, then grandparent, etc. +// Duplicate names are allowed across unrelated (sibling) subgraphs. + +function findRootGraph(graph) { + if (!graph) return null; + return graph.rootGraph || graph; +} + +// Find which SubgraphNode in parentGraph wraps the given subgraph +function findSubgraphNodeFor(parentGraph, innerNode) { + if (!parentGraph?._nodes || !innerNode?.graph) return null; + for (const n of parentGraph._nodes) { + if (n.subgraph && n.subgraph === innerNode.graph) return n; + } + return null; +} + +// Walk from a subgraph up to root, returning [graph, parent, grandparent, ..., root] +function getGraphAncestors(graph) { + if (!graph) return []; + const root = findRootGraph(graph); + if (!root || graph === root) return [root]; + + const chain = [graph]; + const visited = new Set([graph]); + let current = graph; + // Walk up: find which SubgraphNode wraps current, then get its parent graph + while (current !== root) { + let found = false; + // Search root nodes + for (const n of root._nodes) { + if (n.subgraph === current) { + chain.push(root); + current = root; + found = true; + break; + } + } + if (found) break; + // Search sibling subgraphs (for nested subgraphs) + const subgraphs = root._subgraphs || root.subgraphs; + if (subgraphs) { + for (const sg of subgraphs.values()) { + if (sg === current || !sg._nodes) continue; + for (const n of sg._nodes) { + if (n.subgraph === current) { + if (visited.has(sg)) { found = false; break; } + visited.add(sg); + chain.push(sg); + current = sg; + found = true; + break; + } + } + if (found) break; + } + } + if (!found) { + // Can't find parent, add root as fallback + if (!chain.includes(root)) chain.push(root); + break; + } + } + return chain; +} + +// Get all descendant subgraphs of a graph (children, grandchildren, etc.) +function getGraphDescendants(graph, _visited) { + if (!graph?._nodes) return []; + const visited = _visited || new Set(); + if (visited.has(graph)) return []; + visited.add(graph); + const descendants = []; + for (const n of graph._nodes) { + if (n.subgraph && !visited.has(n.subgraph)) { + descendants.push(n.subgraph); + descendants.push(...getGraphDescendants(n.subgraph, visited)); + } + } + return descendants; +} + +// Collect nodes of a type from specific graphs +function collectNodesOfType(graphs, type) { + const results = []; + for (const g of graphs) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type === type) results.push({ node, graph: g }); + } + } + return results; +} + +// Find all nodes of type across ALL graphs (root + all subgraphs). Used for global operations. +function findAllNodesOfType(graph, type) { + const root = findRootGraph(graph); + if (!root) return []; + const allGraphs = [root]; + const subgraphs = root._subgraphs || root.subgraphs; + if (subgraphs) { + for (const sg of subgraphs.values()) allGraphs.push(sg); + } + return collectNodesOfType(allGraphs, type); +} + +// Scoped setter lookup: search current graph, then ancestors (look up). +function findSetterByName(graph, name) { + if (!name) return null; + for (const g of getGraphAncestors(graph)) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type === 'SetNode' && node.widgets[0].value === name) { + return { node, graph: g }; + } + } + } + return null; +} + +// Scoped getter lookup: search current graph + descendants (propagate down). +function findGettersByName(graph, name) { + if (!name) return []; + const graphs = [graph, ...getGraphDescendants(graph)]; + return collectNodesOfType(graphs, 'GetNode') + .filter(entry => entry.node.widgets[0].value === name); +} + +// Get all visible SetNode names for a GetNode's combo dropdown. +// Shows names from current graph + ancestors (what's in scope). +// Also builds a source map for getOptionLabel. This module-level variable is safe +// because the values getter and getOptionLabel run in the same synchronous render pass. +let _setNameSourceMap = new Map(); + +function getVisibleSetNames(graph, filterType) { + const sourceMap = new Map(); + const ancestors = getGraphAncestors(graph); + const entries = collectNodesOfType(ancestors, 'SetNode'); + for (const e of entries) { + const name = e.node.widgets[0].value; + if (!name) continue; + if (filterType && filterType !== '*') { + const setType = e.node.inputs[0]?.type; + if (setType && setType !== '*') { + const filterTypes = String(filterType).split(","); + if (!filterTypes.some(ft => ft === setType || setType.split(",").includes(ft))) continue; + } + } + if (!sourceMap.has(name)) { + sourceMap.set(name, e.graph === graph ? "local" : "parent"); + } + } + _setNameSourceMap = sourceMap; + return [...sourceMap.keys()].sort(); +} + +// Exposed globally for use in contextmenu.js +window.kjNodes = window.kjNodes || {}; +window.kjNodes.convertOutputsToSetGet = convertOutputsToSetGet; +window.kjNodes.snapshotSelectedNodes = snapshotSelectedNodes; +function convertOutputsToSetGet(graph, node) { + if (!graph || !node) return; + for (let slotIdx = 0; slotIdx < node.outputs.length; slotIdx++) { + const output = node.outputs[slotIdx]; + if (!output.links || output.links.length === 0) continue; + + const linkType = output.type || "*"; + const linkName = output.name || linkType; + + // Collect targets and link IDs to remove, skipping existing Set/Get nodes + const targets = []; + const linksToRemove = []; + for (const linkId of [...output.links]) { + const link = getLink(graph, linkId); + if (link) { + const targetNode = graph.getNodeById(link.target_id); + if (targetNode && targetNode.type !== 'SetNode' && targetNode.type !== 'GetNode') { + targets.push({ targetId: link.target_id, targetSlot: link.target_slot }); + linksToRemove.push(linkId); + } + } + } + if (targets.length === 0) continue; + + // Create Set node + const setNode = LiteGraph.createNode("SetNode"); + if (!setNode) continue; + setNode.pos = [ + node.pos[0] + node.size[0] + 30, + node.pos[1] + slotIdx * 60 + ]; + graph.add(setNode); + setNode.flags.collapsed = true; + + for (const linkId of linksToRemove) graph.removeLink(linkId); + + // Connect source → Set node input + node.connect(slotIdx, setNode, 0); + + // Set the name widget + setNode.widgets[0].value = linkName; + setNode.title = prefixedTitle("Set", linkName); + setNode.validateName(graph); + const finalName = setNode.widgets[0].value; + setNode.properties.previousName = finalName; + + // Create a Get node for each target + for (const target of targets) { + const targetNode = graph.getNodeById(target.targetId); + if (!targetNode) continue; + + const getNode = LiteGraph.createNode("GetNode"); + if (!getNode) continue; + getNode.pos = [ + targetNode.pos[0] - getNode.size[0] - 30, + targetNode.pos[1] + ]; + graph.add(getNode); + getNode.flags.collapsed = true; + + getNode.widgets[0].value = finalName; + getNode.onRename(); + + getNode.connect(0, targetNode, target.targetSlot); + } + } + app.canvas.setDirty(true, true); +} + +// Snapshot selection immediately (before right-click changes it) +function snapshotSelectedNodes(node, typeFilter) { + const selected = Object.values(app.canvas.selected_nodes || {}); + // Always include the right-clicked node, even if selection state is inconsistent + const nodeSet = new Set(selected); + nodeSet.add(node); + let nodes = [...nodeSet]; + if (typeFilter) nodes = nodes.filter(n => n.type === typeFilter); + return nodes; +} + +// Tracks nodes flagged with has_errors so they can be cleared on the next alert. +// Always cleared before repopulating, so it only holds nodes from the most recent alert. +const _errorNodes = new Set(); +function showAlert(message, nodes) { + const nodeList = nodes ? (Array.isArray(nodes) ? nodes : [nodes]) : []; + const nodeInfo = nodeList.map(n => + `${n.title || n.type} [${Math.round(n.pos[0])}, ${Math.round(n.pos[1])}]` + ).join(', '); + if (nodeList.length) { + // Clear previous error flags + for (const n of _errorNodes) n.has_errors = false; + _errorNodes.clear(); + setTimeout(() => { + for (const n of nodeList) { + n.has_errors = true; + _errorNodes.add(n); + } + app.canvas?.setDirty(true, true); + }, 100); + } + app.extensionManager.toast.add({ + severity: 'warn', + summary: "KJ Set/Get", + detail: nodeInfo ? `${message} — ${nodeInfo}` : message, + life: 5000, + }); +} +function convertAllSetGetToLinks(graph) { + if (!graph) return; + const rootGraph = findRootGraph(graph); + + // First pass: handle cross-graph pairs (must run before same-graph + // because converting cross-graph creates real links that replace + // the Set/Get, and same-graph pass would miss the removed nodes) + const allSetEntries = findAllNodesOfType(rootGraph, 'SetNode'); + for (const { node: setNode, graph: setGraph } of [...allSetEntries]) { + const name = setNode.widgets[0].value; + if (!name) continue; + const allGetEntries = findGettersByName(rootGraph, name); + const crossGraphGetters = allGetEntries.filter(e => e.graph !== setGraph); + if (crossGraphGetters.length > 0) { + convertCrossGraphSetGet(setNode, setGraph, crossGraphGetters); + } + } + + // Second pass: handle remaining same-graph pairs + for (const { node: setNode, graph: g } of [...findAllNodesOfType(rootGraph, 'SetNode')]) { + convertSetGetToLinks(g, setNode); + } +} + +// Compat shim: older frontends may lack graph.getLink(), and _links may be a Map or +// plain object depending on the litegraph version. The == null check catches both null +// and undefined intentionally. +function getLink(graph, linkId) { + if (linkId == null) return null; + if (graph.getLink) return graph.getLink(linkId); + return graph._links instanceof Map ? graph._links.get(linkId) : graph._links?.[linkId] ?? null; +} + +// Collect {targetId, targetSlot} from an output slot's links +function collectOutputConnections(graph, output) { + const connections = []; + if (output?.links) { + for (const linkId of [...output.links]) { + const link = getLink(graph, linkId); + if (link) connections.push({ targetId: link.target_id, targetSlot: link.target_slot }); + } + } + return connections; +} + +function convertCrossGraphSetGet(setNode, setGraph, crossGraphGetters) { + // Find what's connected to the SetNode's input + const setInput = setNode.inputs[0]; + if (setInput.link == null) return; + const sourceLink = getLink(setGraph, setInput.link); + if (!sourceLink) return; + const sourceNode = setGraph.getNodeById(sourceLink.origin_id); + if (!sourceNode) return; + const sourceSlot = sourceLink.origin_slot; + const linkType = setNode.inputs[0].type || '*'; + + for (const { node: getter, graph: getterGraph } of crossGraphGetters) { + // Collect getter's downstream connections before removing it + const connections = collectOutputConnections(getterGraph, getter.outputs[0]); + if (connections.length === 0) { + getterGraph.remove(getter); + continue; + } + + // Determine direction and create SubgraphInput or SubgraphOutput + const rootGraph = findRootGraph(setGraph); + const sgNodeForGetter = findSubgraphNodeFor(rootGraph, getter); + const sgNodeForSetter = findSubgraphNodeFor(rootGraph, setNode); + + if (sgNodeForGetter && setGraph === rootGraph) { + // Set in root, Get in subgraph → create SubgraphInput + const subgraph = sgNodeForGetter.subgraph; + const inputName = setNode.widgets[0].value || linkType; + const newInput = subgraph.addInput(inputName, linkType); + const inputIndex = subgraph.inputs.indexOf(newInput); + + // Connect source → SubgraphNode's new input in root graph + sourceNode.connect(sourceSlot, sgNodeForGetter, inputIndex); + + // Inside subgraph: connect SubgraphInput slot → getter's targets + for (const conn of connections) { + if (conn.targetId === subgraph.outputNode?.id) { + // GetNode fed a SubgraphOutput — bypass it and connect source directly in parent graph. + const sgNodeOutput = sgNodeForGetter.outputs[conn.targetSlot]; + if (sgNodeOutput?.links) { + for (const parentLinkId of [...sgNodeOutput.links]) { + const parentLink = getLink(rootGraph, parentLinkId); + if (parentLink) { + const parentTarget = rootGraph.getNodeById(parentLink.target_id); + if (parentTarget) { + sourceNode.connect(sourceSlot, parentTarget, parentLink.target_slot); + } + } + } + } + // Remove the now-unnecessary SubgraphOutput + const sgOutput = subgraph.outputs[conn.targetSlot]; + if (sgOutput) { + subgraph.removeOutput(sgOutput); + } + } else { + const targetNode = getterGraph.getNodeById(conn.targetId); + if (targetNode) { + newInput.connect(targetNode.inputs[conn.targetSlot], targetNode); + } + } + } + + // If no connections used the SubgraphInput, remove it + if (newInput.linkIds.length === 0) { + subgraph.removeInput(newInput); + } + + getterGraph.remove(getter); + + } else if (sgNodeForSetter && getterGraph === rootGraph) { + // Set in subgraph, Get in root → create SubgraphOutput + const subgraph = sgNodeForSetter.subgraph; + const outputName = setNode.widgets[0].value || linkType; + const newOutput = subgraph.addOutput(outputName, linkType); + const outputIndex = subgraph.outputs.indexOf(newOutput); + + // Inside subgraph: connect source output → SubgraphOutput slot + newOutput.connect(sourceNode.outputs[sourceSlot], sourceNode); + + // In root graph: connect SubgraphNode's new output → getter's targets + for (const conn of connections) { + const targetNode = getterGraph.getNodeById(conn.targetId); + if (targetNode) { + sgNodeForSetter.connect(outputIndex, targetNode, conn.targetSlot); + } + } + + getterGraph.remove(getter); + + } else { + // Both in different subgraphs (sibling) — would need both input and output + // Skip for now, too complex + console.warn(`KJNodes: Cannot convert cross-graph Set/Get "${setNode.widgets[0].value}" between sibling subgraphs`); + } + } + + // Remove SetNode if all its getters have been handled (check if any same-graph getters remain) + const remainingGetters = setGraph._nodes.filter( + n => n.type === 'GetNode' && n.widgets[0].value === setNode.widgets[0].value + ); + if (remainingGetters.length === 0) { + setGraph.remove(setNode); + } +} + +function convertSetGetToLinks(graph, setNode) { + if (!graph || !setNode) return; + + const name = setNode.widgets[0].value; + let sameGraphGetters = []; + if (name) { + const allGetters = findGettersByName(graph, name); + const crossGetters = []; + for (const entry of allGetters) { + if (entry.graph === graph) sameGraphGetters.push(entry.node); + else crossGetters.push(entry); + } + if (crossGetters.length > 0) { + convertCrossGraphSetGet(setNode, graph, crossGetters); + } + } + + // Find the source connected to the Set node's input + const setInput = setNode.inputs[0]; + if (setInput.link == null) return; + const sourceLink = getLink(graph, setInput.link); + if (!sourceLink) return; + const sourceNode = graph.getNodeById(sourceLink.origin_id); + if (!sourceNode) return; + const sourceSlot = sourceLink.origin_slot; + + // Collect all consumer connections from Get nodes and SetNode's own output passthrough + const connections = []; + for (const getter of sameGraphGetters) { + connections.push(...collectOutputConnections(graph, getter.outputs[0])); + } + connections.push(...collectOutputConnections(graph, setNode.outputs[0])); + + // Remove all Get nodes (this also removes their links) + for (const getter of sameGraphGetters) { + graph.remove(getter); + } + // Remove the Set node + graph.remove(setNode); + + // Create direct links from source to each consumer + for (const conn of connections) { + const targetNode = graph.getNodeById(conn.targetId); + if (targetNode) { + sourceNode.connect(sourceSlot, targetNode, conn.targetSlot); + } + } + + app.canvas?.setDirty(true, true); +} + +// region SetNode +app.registerExtension({ + name: "KJNodes.SetNode", + registerCustomNodes() { + class SetNode extends LGraphNode { + static title = "Set"; + static category = "KJNodes"; + serialize_widgets = true; + drawConnection = false; + slotColor = "#FFF"; + canvas = app.canvas; + + constructor(title) { + super(title) + if (!this.properties) { + this.properties = { + "previousName": "" + }; + } + this.properties["Node name for S&R"] = "SetNode"; + this.properties["aux_id"] = "kijai/ComfyUI-KJNodes"; + this.isVirtualNode = true; // This node is purely frontend and does not impact the resulting prompt so should not be serialized + + this.addWidget( + "text", + "Constant", + '', + () => { + if (!this.graph || app.configuringGraph) return; + this.validateName(this.graph); + if (this.widgets[0].value !== '') { + this.title = prefixedTitle("Set", this.widgets[0].value); + } + this.update(); + this.properties.previousName = this.widgets[0].value; + }, + {} + ) + + this.addInput("*", "*"); + this.addOutput("*", '*'); + } + + onConnectionsChange( + slotType, + slot, + isChangeConnect, + link_info + ) { + // During graph load, slots are restored by configure — skip side effects + if (app.configuringGraph) return; + //On Disconnect + if (slotType === LiteGraph.INPUT && !isChangeConnect) { + const outputConnected = this.outputs[0]?.links?.length > 0; + if (outputConnected) { + this.inputs[slot].type = this.outputs[0].type; + this.inputs[slot].name = this.outputs[0].name; + } else { + this.inputs[slot].type = '*'; + this.inputs[slot].name = '*'; + this.outputs[0].type = '*'; + this.outputs[0].name = '*'; + this.title = "Set"; + this.color = null; + this.bgcolor = null; + } + this.update(); + } + if (slotType === LiteGraph.OUTPUT && !isChangeConnect) { + if (this.outputs && this.outputs[slot]) { + // Keep type if input has a real connection + const inputConnected = this.inputs[0]?.link != null; + if (inputConnected) { + this.outputs[slot].type = this.inputs[0].type; + this.outputs[slot].name = this.inputs[0].name; + } else { + this.inputs[0].type = '*'; + this.inputs[0].name = '*'; + this.outputs[slot].type = '*'; + this.outputs[slot].name = '*'; + this.color = null; + this.bgcolor = null; + } + } + } + //On Connect + if (link_info && this.graph && slotType === LiteGraph.INPUT && isChangeConnect) { + const resolve = link_info.resolve(this.graph) + const resolvedSlot = resolve?.subgraphInput ?? resolve?.output; + const type = resolvedSlot?.type; + if (type) { + if (this.title === "Set"){ + this.title = prefixedTitle("Set", type); + } + if (this.widgets[0].value === '' || this.widgets[0].value === '*'){ + // Determine the initial widget value based on naming setting + const namingMode = app.ui.settings.getSettingValue("KJNodes.setGetNaming") ?? "empty"; + if (namingMode !== "empty") { + const link = getLink(this.graph, this.inputs[0]?.link); + const sourceNode = link ? this.graph.getNodeById(link.origin_id) : null; + const slotName = sourceNode?.outputs?.[link?.origin_slot]?.name || type; + switch (namingMode) { + case "slot name": this.widgets[0].value = slotName; break; + case "slot name (lowercase)": this.widgets[0].value = slotName.toLowerCase(); break; + case "slot name (UPPERCASE)": this.widgets[0].value = slotName.toUpperCase(); break; + } + } + } + + this.validateName(this.graph); + this.properties.previousName = this.widgets[0].value; + this.inputs[0].type = type; + this.inputs[0].name = type; + this.outputs[0].type = type; + this.outputs[0].name = type; + + autoColor(this, type); + } else { + showAlert(`node ${this.title} input undefined.`, this) + } + } + if (link_info && this.graph && slotType === LiteGraph.OUTPUT && isChangeConnect) { + const inputType = this.inputs[0]?.type; + if (inputType && inputType !== '*') { + this.outputs[0].type = inputType; + this.outputs[0].name = inputType; + } else { + const resolve = link_info.resolve(this.graph); + const type = resolve?.input?.type; + if (type && type !== '*') { + this.inputs[0].type = type; + this.inputs[0].name = type; + this.outputs[0].type = type; + this.outputs[0].name = type; + autoColor(this, type); + } + } + } + + //Update either way + this.update(); + } + + // Returns true if the name was changed + validateName(graph, sameGraphOnly) { + let widgetValue = this.widgets[0].value; + + if (widgetValue !== '') { + let tries = 0; + const existingValues = new Set(); + + // sameGraphOnly: only check the immediate graph (for paste/clone) + // otherwise check full scope (own graph + ancestors) + const scopeGraphs = sameGraphOnly ? [graph] : getGraphAncestors(graph); + const scopedSetNodes = collectNodesOfType(scopeGraphs, 'SetNode'); + scopedSetNodes.forEach(entry => { + if (entry.node !== this) { + existingValues.add(entry.node.widgets[0].value); + } + }); + + const originalValue = widgetValue; + // Only strip _N suffix during paste to avoid FOO_0_1_2 accumulation. + // For manual renames, keep the full name as base (user may intend FOO_3). + const baseName = this._justAdded ? widgetValue.replace(/_\d+$/, '') : widgetValue; + while (existingValues.has(widgetValue)) { + widgetValue = baseName + "_" + tries; + tries++; + } + + this.widgets[0].value = widgetValue; + this.title = prefixedTitle("Set", widgetValue); + return widgetValue !== originalValue; + } + return false; + } + + clone() { + const cloned = super.clone(); + cloned.inputs[0].name = '*'; + cloned.inputs[0].type = '*'; + cloned.properties.previousName = ''; + cloned.size = cloned.computeSize(); + return cloned; + } + + onAdded() { + this._justAdded = true; + } + + onConfigure() { + // Only run paste logic when actually pasting, not during workflow load + if (this._justAdded && this.graph && !app.configuringGraph) { + const oldName = this.widgets[0].value; + this.validateName(this.graph, true); + this._justAdded = false; + const newName = this.widgets[0].value; + if (newName !== oldName) { + _pasteRenameMap.set(oldName, newName); + // Clear the map after this paste cycle + setTimeout(() => _pasteRenameMap.delete(oldName), 0); + } + // Reset type and color on paste — nothing is connected yet + if (this.inputs[0]?.link == null) { + this.inputs[0].type = '*'; + this.inputs[0].name = '*'; + this.outputs[0].type = '*'; + this.outputs[0].name = '*'; + this.color = null; + this.bgcolor = null; + } + } + this._justAdded = false; + } + + update() { + if (!this.graph) return; + + const getters = this.findGetters(this.graph); + getters.forEach(getter => { + getter.setType(this.inputs[0].type); + }); + + if (this.widgets[0].value && this.properties.previousName) { + const gettersWithPreviousName = this.findGetters(this.graph, true); + gettersWithPreviousName.forEach(getter => { + getter.setName(this.widgets[0].value); + }); + } + app.canvas?.setDirty(true, true); + } + + findGetters(graph, checkForPreviousName) { + const name = checkForPreviousName ? this.properties.previousName : this.widgets[0].value; + if (!name || name === '') return []; + // Scoped: searches own graph + descendant subgraphs + return findGettersByName(graph, name).map(entry => entry.node); + } + + getExtraMenuOptions(_, options) { + options.unshift( + { + content: this.drawConnection ? "Hide connections" : "Show connections", + callback: () => { + this.drawConnection = !this.drawConnection; + const linkType = this.inputs[0].type; + this.slotColor = this.canvas.default_connection_color_byType[linkType]; + this.canvas.setDirty(true, true); + }, + }, + { + content: "Hide all connections", + callback: () => { + for (const n of this.graph._nodes) { + if (n.type === "GetNode" || n.type === "SetNode") n.drawConnection = false; + } + this.canvas.setDirty(true, true); + }, + + }, + ); + options.unshift({ + content: "Convert to links", + callback: () => { + const graph = this.graph; + for (const n of snapshotSelectedNodes(this, 'SetNode')) convertSetGetToLinks(graph, n); + }, + }); + options.unshift({ + content: "Add paired GetNode", + callback: () => { + const graph = this.graph; + const getNode = LiteGraph.createNode("GetNode"); + if (!getNode) return; + getNode.pos = [this.pos[0] + this.size[0] + 30, this.pos[1]]; + graph.add(getNode); + // Set the widget value to match — this drives type, color, and connection + const name = this.widgets[0].value; + if (getNode.widgets?.[0]) { + getNode.widgets[0].value = name; + } + getNode.onRename?.(); + app.canvas.selectNode(getNode, false); + app.canvas.setDirty(true, true); + }, + }); + // Dynamically add a submenu for all getters + const allGettersForMenu = this.findGetters(this.graph); + if (allGettersForMenu.length) { + let gettersSubmenu = allGettersForMenu.map(getter => { + const sameGraph = getter.graph === this.graph; + const sgNode = !sameGraph ? findSubgraphNodeFor(this.graph, getter) : null; + const label = sameGraph + ? `${getter.title} id: ${getter.id}` + : `${getter.title} (in subgraph${sgNode ? ': ' + (sgNode.title || sgNode.type) : ''})`; + return { + content: label, + callback: () => { + if (sameGraph) { + this.canvas.centerOnNode(getter); + this.canvas.selectNode(getter, false); + } else if (sgNode) { + this.canvas.openSubgraph(sgNode.subgraph, sgNode); + // Center on the getter after entering the subgraph + setTimeout(() => { + this.canvas.centerOnNode(getter); + this.canvas.selectNode(getter, false); + }, 0); + } + this.canvas.setDirty(true, true); + }, + }; + }); + + options.unshift({ + content: "Getters", + has_submenu: true, + submenu: { + title: "GetNodes", + options: gettersSubmenu, + } + }); + } + } + } + + LiteGraph.registerNodeType("SetNode", SetNode); + }, +}); + +// region GetNode +app.registerExtension({ + name: "KJNodes.GetNode", + registerCustomNodes() { + class GetNode extends LGraphNode { + static title = "Get"; + static category = "KJNodes"; + serialize_widgets = true; + drawConnection = false; + currentSetter = null; + canvas = app.canvas; + + constructor(title) { + super(title) + if (!this.properties) { + this.properties = {}; + } + this.properties["Node name for S&R"] = "GetNode"; + this.properties["aux_id"] = "kijai/ComfyUI-KJNodes"; + this.isVirtualNode = true; // This node is purely frontend and does not impact the resulting prompt so should not be serialized + const comboOptions = { + getOptionLabel: (value) => { + if (!value) return ""; + const source = _setNameSourceMap.get(value); + if (!source || source === "local") return value; + return `${value} (${source})`; + }, + }; + Object.defineProperty(comboOptions, 'values', { + get: () => { + if (!this.graph) return []; + let filterType = null; + if (app.ui.settings.getSettingValue("KJNodes.filterGetNodeOptions") !== false + && this.outputs[0]?.links?.length) { + const linkId = this.outputs[0].links[0]; + const link = getLink(this.graph, linkId); + if (link) { + const targetNode = this.graph.getNodeById(link.target_id); + filterType = targetNode?.inputs?.[link.target_slot]?.type || null; + } + } + return getVisibleSetNames(this.graph, filterType); + }, + enumerable: true, + configurable: true + }); + this.addWidget("combo", "Constant", "", () => { if (!app.configuringGraph) this.onRename(); }, comboOptions) + this.addOutput("*", '*'); + } + + onConnectionsChange() { + if (app.configuringGraph) return; + this.validateLinks(); + } + + setName(name) { + this.widgets[0].value = name; + this.onRename(); + this.serialize(); + } + + onRename() { + const setter = this.findSetter(this.graph); + if (setter) { + this.setType(setter.inputs[0].type); + this.title = prefixedTitle("Get", setter.widgets[0].value); + } else { + this.setType('*'); + const name = this.widgets[0].value; + this.title = name ? prefixedTitle("Get", name) : "Get"; + } + app.canvas?.setDirty(true, true); + } + + clone() { + const cloned = super.clone(); + cloned.size = cloned.computeSize(); + return cloned; + } + + validateLinks() { + if (this.outputs[0].type !== '*' && this.outputs[0].links && this.graph) { + this.outputs[0].links.filter(linkId => { + const link = getLink(this.graph, linkId); + if (!link || !link.type) return false; + if (link.type === '*') return false; + const targetNode = this.graph.getNodeById(link.target_id); + const targetType = targetNode?.inputs?.[link.target_slot]?.type; + if (targetType === '*') return false; + if (targetType) { + const targetTypes = String(targetType).split(","); + if (targetTypes.includes(this.outputs[0].type)) return false; + } + return !link.type.split(",").includes(this.outputs[0].type); + }).forEach(linkId => { + this.graph.removeLink(linkId); + }); + } + } + + setType(type) { + this.outputs[0].name = type; + this.outputs[0].type = type; + this.validateLinks(); + autoColor(this, type); + } + + findSetter(graph) { + const name = this.widgets[0].value; + // Scoped: searches own graph first, then ancestors + const result = findSetterByName(graph, name); + return result ? result.node : undefined; + } + + goToSetter() { + if (!this.currentSetter) return; + const setterGraph = this.currentSetter.graph; + if (setterGraph && setterGraph !== this.graph) { + this.canvas.setGraph(setterGraph); + setTimeout(() => { + this.canvas.centerOnNode(this.currentSetter); + this.canvas.selectNode(this.currentSetter, false); + this.canvas.setDirty(true, true); + }, 0); + } else { + this.canvas.centerOnNode(this.currentSetter); + this.canvas.selectNode(this.currentSetter, false); + } + } + + onAdded() { + this._justAdded = true; + } + + onConfigure() { + if (this._justAdded && !app.configuringGraph) { + const name = this.widgets[0].value; + if (name) { + // Check if our paired SetNode was renamed during this paste + const newName = _pasteRenameMap.get(name); + if (newName) { + this.widgets[0].value = newName; + } + // Restore type/color from setter after paste + setTimeout(() => this.onRename(), 0); + } + } + this._justAdded = false; + } + + getInputLink(slot) { + // Same-graph: standard resolveOutput path. + // Cross-graph: handled by resolveVirtualOutput. + const name = this.widgets[0].value; + if (!name || name === '') return null; + const setter = this.graph?._nodes?.find( + n => n.type === 'SetNode' && n.widgets[0].value === name + ); + if (setter) { + const slotInfo = setter.inputs[slot]; + if (!slotInfo || slotInfo.link == null) return null; + return getLink(this.graph, slotInfo.link); + } + // Scoped lookup: no setter found in own graph or ancestors + if (name && !findSetterByName(this.graph, name)) { + showAlert("No SetNode found for " + name + "(" + this.type + ")", this); + } + return null; + } + + resolveVirtualOutput(slot) { + const name = this.widgets[0].value; + // Scoped lookup: own graph first, then ancestors + const result = findSetterByName(this.graph, name); + if (!result) return undefined; + + // Same graph — let the standard getInputLink path handle it + if (result.graph === this.graph) return undefined; + + // Warn if multiple SetNodes with this name exist in scope + const scopeGraphs = getGraphAncestors(this.graph); + const scopedSetters = collectNodesOfType(scopeGraphs, 'SetNode') + .filter(e => e.node.widgets[0].value === name); + if (scopedSetters.length > 1) { + showAlert(`Multiple SetNodes named "${name}" found in scope. Rename duplicates or use "Convert to links" to resolve`, [this, ...scopedSetters.map(e => e.node)]); + return undefined; + } + + const { node: setter, graph: setterGraph } = result; + const slotInfo = setter.inputs[slot]; + if (!slotInfo || slotInfo.link == null) return undefined; + + const link = getLink(setterGraph, slotInfo.link); + if (!link) return undefined; + + const sourceNode = setterGraph.getNodeById(link.origin_id); + if (!sourceNode) return undefined; + + return { node: sourceNode, slot: link.origin_slot }; + } + getExtraMenuOptions(_, options) { + this.currentSetter = this.findSetter(this.graph) + if (!this.currentSetter) return + const sameGraph = this.currentSetter.graph === this.graph; + if (sameGraph) { + let menuEntry = this.drawConnection ? "Hide connections" : "Show connections"; + options.unshift( + { + content: "Convert to links", + callback: () => { + const graph = this.graph; + const setters = new Set(snapshotSelectedNodes(this, 'GetNode') + .map(n => n.findSetter?.(graph)).filter(Boolean)); + for (const s of setters) convertSetGetToLinks(graph, s); + }, + }, + { + content: "Go to setter", + callback: () => { + this.goToSetter(); + }, + }, + { + content: menuEntry, + callback: () => { + if (!this.currentSetter) return; + const linkType = this.currentSetter.inputs[0].type; + // Toggle on the SetNode so the canvas-level hook draws it + this.currentSetter.drawConnection = !this.currentSetter.drawConnection; + this.currentSetter.slotColor = this.canvas.default_connection_color_byType[linkType]; + this.drawConnection = this.currentSetter.drawConnection; + this.canvas.setDirty(true, true); + }, + }, + ); + } else { + // Cross-graph setter — navigate to its graph + const setterGraph = this.currentSetter.graph; + const isRoot = setterGraph === findRootGraph(this.graph); + options.unshift( + { + content: `Go to setter (in ${isRoot ? 'parent graph' : 'subgraph'})`, + callback: () => { + const canvas = this.canvas; + canvas.setGraph(setterGraph); + setTimeout(() => { + canvas.centerOnNode(this.currentSetter); + canvas.selectNode(this.currentSetter, false); + canvas.setDirty(true, true); + }, 0); + }, + }, + ); + } + } + } + + LiteGraph.registerNodeType("GetNode", GetNode); + }, +}); + +// region UI: commands, keybindings, canvas menu, draw hook, settings +app.registerExtension({ + name: "KJNodes.SetGetUI", + settings: [ + { + id: "KJNodes.setGetNaming", + name: "Default SetNode widget value", + category: ["KJNodes", "Set & Get", "Default SetNode widget value"], + tooltip: "Initial Constant value when a Set node is first connected to a slot", + type: "combo", + options: ["empty", "slot name", "slot name (lowercase)", "slot name (UPPERCASE)"], + defaultValue: "empty", + }, + { + id: "KJNodes.showSetGetLinks", + name: "Show links", + category: ["KJNodes", "Set & Get", "Show links"], + tooltip: "When to show virtual links between Set/Get pairs", + type: "combo", + options: ["never", "selected", "always"], + defaultValue: "never", + onChange: () => app.canvas?.setDirty(true, true), + }, + ], + commands: [ + { + id: "KJNodes.AddSetNodeToSelected", + label: "Add Set node to selected / at cursor", + function: () => addNodeToSelectedOrCursor("SetNode", "right"), + }, + { + id: "KJNodes.AddGetNodeAtCursor", + label: "Add Get node to selected / at cursor", + function: () => addNodeToSelectedOrCursor("GetNode", "left"), + }, + { + id: "KJNodes.ToggleForceShowSetGetLinks", + label: "Toggle force-show all Set/Get connections", + function: () => { + _forceShowAllLinks = !_forceShowAllLinks; + app.canvas.setDirty(true, true); + }, + }, + ], + keybindings: [ + { + commandId: "KJNodes.AddSetNodeToSelected", + combo: { key: "s", ctrl: true, shift: true }, + targetElementId: "graph-canvas", + }, + { + commandId: "KJNodes.AddGetNodeAtCursor", + combo: { key: "g", ctrl: true, shift: true }, + targetElementId: "graph-canvas", + }, + { + commandId: "KJNodes.ToggleForceShowSetGetLinks", + combo: { key: "l", ctrl: true, shift: true }, + targetElementId: "graph-canvas", + }, + ], + getCanvasMenuItems() { + return [ + { + content: "KJNodes", + has_submenu: true, + submenu: { + options: [ + { + content: "Convert outputs on all selected nodes to Set/Get", + callback: () => { + const selected = Object.values(app.canvas.selected_nodes || {}); + if (selected.length === 0) return; + for (const n of selected) convertOutputsToSetGet(app.graph, n); + }, + }, + { + content: "Convert selected Set/Get to links", + callback: () => { + const graph = app.graph; + const selected = Object.values(app.canvas.selected_nodes || {}); + const setNodes = selected.filter(n => n.type === 'SetNode'); + const getNodes = selected.filter(n => n.type === 'GetNode'); + for (const n of setNodes) convertSetGetToLinks(graph, n); + const setters = new Set(getNodes.map(n => n.findSetter?.(graph)).filter(Boolean)); + for (const s of setters) convertSetGetToLinks(graph, s); + }, + }, + ], + }, + }, + ]; + }, + setup() { + // Double-click GetNode to jump to its SetNode (works in both legacy and Vue modes) + document.addEventListener("dblclick", (e) => { + // Don't interfere when a ContextMenu (e.g. combo dropdown) is open + if (document.querySelector(".litecontextmenu")) return; + const canvas = app.canvas; + if (!canvas) return; + const selected = Object.values(canvas.selected_nodes || {}); + if (selected.length !== 1) return; + const node = selected[0]; + if (node.type === "GetNode") { + node.currentSetter = node.findSetter(node.graph); + if (node.currentSetter) node.goToSetter(); + } + }); + // Suppress title rename on collapsed GetNodes so double-click navigates instead + document.addEventListener("litegraph:canvas", (e) => { + if (e.detail?.subType !== 'node-double-click') return; + const node = e.detail.node; + if (node?.type === "GetNode" && node.flags?.collapsed) { + e.stopImmediatePropagation(); + } + }); + + // Monkey-patch: no extension hook exists for filtering visible nodes. + // Keep Set/Get nodes with visible virtual connections in the visible set + // even when offscreen, so the link lines don't get clipped. + const originalComputeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes; + LGraphCanvas.prototype.computeVisibleNodes = function () { + const visible = originalComputeVisibleNodes.apply(this, arguments); + for (const node of this.graph._nodes) { + if ((node.type === "SetNode" || node.type === "GetNode") && node.drawConnection && !visible.includes(node)) { + visible.push(node); + } + } + return visible; + }; + + // Monkey-patch: no extension hook exists for custom canvas drawing. + // Draws virtual links between Set/Get pairs. + // Handles per-node "Show connections", "selected" mode, and "always" mode. + const origCanvasOnDrawBackground = app.canvas.onDrawBackground; + app.canvas.onDrawBackground = function(ctx, visibleArea) { + origCanvasOnDrawBackground?.call(this, ctx, visibleArea); + + const graph = this.graph || app.graph; + if (!graph?._nodes) return; + const mode = getShowLinksMode(); + + // Build set of selected Set/Get names for "selected" mode + let selectedNames = null; + if (mode === "selected") { + const sel = Object.values(this.selected_nodes || {}); + if (!sel.length) { + // No selection — still honor per-node drawConnection + if (!graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return; + } else { + selectedNames = new Set(); + for (const n of sel) { + if (n.type === 'SetNode' || n.type === 'GetNode') { + selectedNames.add(n.widgets?.[0]?.value ?? n.title); + } + } + if (!selectedNames.size && !graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return; + } + } else if (mode === "never") { + if (!graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return; + } + + // Collect all GetNodes once across current graph + descendants, grouped by name. + // This avoids re-discovering descendant graphs and re-scanning nodes per SetNode. + const gettersByName = new Map(); + const scopeGraphs = [graph, ...getGraphDescendants(graph)]; + for (const g of scopeGraphs) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type !== 'GetNode') continue; + const n = node.widgets?.[0]?.value; + if (!n) continue; + let list = gettersByName.get(n); + if (!list) { list = []; gettersByName.set(n, list); } + list.push(node); + } + } + + for (const setNode of graph._nodes) { + if (setNode.type !== 'SetNode') continue; + const name = setNode.widgets?.[0]?.value ?? setNode.title; + const showByMode = mode === "always" || (mode === "selected" && selectedNames?.has(name)); + if (!showByMode && !setNode.drawConnection) continue; + + const allGetters = gettersByName.get(name) || []; + const drawTargets = []; + const seenSubgraphs = new Set(); + for (const getter of allGetters) { + if (getter.graph === graph) { + drawTargets.push(getter); + } else { + const sgNode = findSubgraphNodeFor(graph, getter); + if (sgNode && !seenSubgraphs.has(sgNode)) { + seenSubgraphs.add(sgNode); + drawTargets.push(sgNode); + } + } + } + if (!drawTargets.length) continue; + + const linkType = setNode.inputs[0]?.type; + const slotColor = app.canvas.default_connection_color_byType?.[linkType] + || LGraphCanvas.link_type_colors?.[linkType] + || setNode.bgcolor + || (setNode.slotColor !== "#FFF" ? setNode.slotColor : null) || "#AAA"; + + const startPos = setNode.getConnectionPos(false, 0); + + for (const target of drawTargets) { + const endPos = target.getConnectionPos(true, 0); + const highlighted = setNode.is_selected || target.is_selected; + const color = highlighted ? "#FFF" : slotColor; + app.canvas.renderLink( + ctx, + startPos, + endPos, + null, + false, + null, + color, + LiteGraph.RIGHT, + LiteGraph.LEFT + ); + } + } + }; + + app.ui.settings.addSetting({ + id: "KJNodes.filterGetNodeOptions", + name: "Filter Get node options by type", + category: ["KJNodes", "Set & Get", "Filter Get node options by type"], + tooltip: "When a Get node is connected, only show Set nodes with compatible types in the dropdown", + type: "boolean", + defaultValue: true, + }); + app.ui.settings.addSetting({ + id: "KJNodes.convertAllSetGet", + name: "Convert ALL Set/Get to links", + category: ["KJNodes", "Set & Get", "Convert ALL Set/Get to links"], + tooltip: "Replaces all Set/Get node pairs with direct links, including across subgraph boundaries (irreversible)", + type: () => { + const btn = document.createElement("button"); + btn.textContent = "Convert ALL Set/Get to links"; + btn.style.cssText = "padding: 6px 12px; cursor: pointer;"; + btn.onclick = () => { + if (confirm("This will replace ALL Set/Get pairs with direct links. This is irreversible. Continue?")) { + convertAllSetGetToLinks(app.graph); + app.canvas?.setDirty(true, true); + app.extensionManager.toast.add({ + severity: 'info', + summary: "KJ Set/Get", + detail: "All Set/Get nodes converted to direct links", + life: 3000, + }); + } + }; + return btn; + }, + defaultValue: false, + }); + } +}); + +// Temporary backwards-compat patch: makes cross-subgraph Set/Get work on frontends +// that don't natively support resolveVirtualOutput. Remove when no longer needed. +app.registerExtension({ + name: "KJNodes.CrossGraphSetGet", + setup() { + let patched = false; + + const originalGraphToPrompt = app.graphToPrompt.bind(app); + app.graphToPrompt = async function(...args) { + if (!patched) { + try { + const subgraphNode = app.graph._nodes.find(n => typeof n.getInnerNodes === 'function'); + if (subgraphNode) { + const tempMap = new Map(); + const dtos = subgraphNode.getInnerNodes(tempMap, []); + if (dtos.length > 0) { + const proto = Object.getPrototypeOf(dtos[0]); + const DtoClass = proto.constructor; + const nativeSource = proto.resolveOutput.toString(); + const hasNativeSupport = nativeSource.includes('resolveVirtualOutput'); + console.log(`[KJNodes] Cross-graph Set/Get: frontend native support ${hasNativeSupport ? 'detected, skipping patch' : 'not found, applying patch'}`); + if (!hasNativeSupport) { + const origResolveOutput = proto.resolveOutput; + proto.resolveOutput = function(slot, type, visited) { + if (typeof this.node?.resolveVirtualOutput === 'function') { + const virtualSource = this.node.resolveVirtualOutput(slot); + if (virtualSource) { + const inputNodeDto = [...this.nodesByExecutionId.values()] + .find(dto => dto instanceof DtoClass && dto.node === virtualSource.node); + if (inputNodeDto) { + return inputNodeDto.resolveOutput(virtualSource.slot, type, visited); + } + throw new Error(`KJNodes: No DTO found for cross-graph source node [${virtualSource.node.id}]`); + } + } + return origResolveOutput.call(this, slot, type, visited); + }; + } + patched = true; + } + } + } catch (e) { + console.warn('[KJNodes] Failed to probe ExecutableNodeDTO for cross-graph patch:', e); + } + } + return originalGraphToPrompt(...args); + }; + } +}); + +// Monkey-patch: no hook exists to extend the link context menu. +// Appends a "Convert to Set/Get" entry by counting DOM menus before/after +// the original call to find the newly created one. Fragile but unavoidable. +app.registerExtension({ + name: "KJNodes.LinkToSetGet", + setup() { + const originalShowLinkMenu = LGraphCanvas.prototype.showLinkMenu; + LGraphCanvas.prototype.showLinkMenu = function(segment, e) { + const menusBefore = document.querySelectorAll(".litecontextmenu").length; + const result = originalShowLinkMenu.call(this, segment, e); + + const graph = this.graph; + if (!graph) return result; + + // Get the full link object to access target info + const link = getLink(graph, segment.id); + if (!link || link.origin_id == null || link.target_id == null) return result; + + // Find the newly created context menu + const menus = document.querySelectorAll(".litecontextmenu"); + if (menus.length <= menusBefore) return result; + const lastMenu = menus[menus.length - 1]; + if (!lastMenu) return result; + + const entries = lastMenu.querySelector(".litemenu-entry")?.parentElement; + if (!entries) return result; + + // Create separator + const separator = document.createElement("div"); + separator.className = "litemenu-entry separator"; + entries.appendChild(separator); + + // Create menu entry + const menuItem = document.createElement("div"); + menuItem.className = "litemenu-entry submenu"; + menuItem.textContent = "Convert to Set/Get"; + entries.appendChild(menuItem); + + const canvas = this; + menuItem.addEventListener("click", function() { + // Close menu + lastMenu.remove(); + + const originNode = graph.getNodeById(link.origin_id); + const targetNode = graph.getNodeById(link.target_id); + if (!originNode || !targetNode) return; + + const outputSlot = originNode.outputs[link.origin_slot]; + const linkType = outputSlot?.type || "*"; + const linkName = outputSlot?.name || linkType; + + // Create Set node near the source + const setNode = LiteGraph.createNode("SetNode"); + if (!setNode) return; + setNode.pos = [ + originNode.pos[0] + originNode.size[0] + 30, + originNode.pos[1] + ]; + graph.add(setNode); + + // Create Get node near the target + const getNode = LiteGraph.createNode("GetNode"); + if (!getNode) return; + graph.add(getNode); + getNode.pos = [ + targetNode.pos[0] - getNode.size[0] - 30, + targetNode.pos[1] + ]; + + // Remove the original link + graph.removeLink(link.id); + + // Connect source -> Set node input + originNode.connect(link.origin_slot, setNode, 0); + + // Set the name widget on the Set node + setNode.widgets[0].value = linkName; + setNode.title = prefixedTitle("Set", linkName); + setNode.validateName(graph); + setNode.properties.previousName = setNode.widgets[0].value; + + // Update Get node to match + const finalName = setNode.widgets[0].value; + getNode.widgets[0].value = finalName; + getNode.onRename(); + + // Connect Get node output -> target node input + getNode.connect(0, targetNode, link.target_slot); + + canvas.setDirty(true, true); + }); + + return result; + }; + } +}); diff --git a/.disabled/comfyui-kjnodes@nightly/web/js/utility.js b/.disabled/comfyui-kjnodes@nightly/web/js/utility.js new file mode 100644 index 0000000000000000000000000000000000000000..5df65e4b2e60c510bcbaf44bd4e4dcedadfd2587 --- /dev/null +++ b/.disabled/comfyui-kjnodes@nightly/web/js/utility.js @@ -0,0 +1,230 @@ +const { app } = window.comfyAPI.app; + +// ─── General-purpose helpers shared across KJNodes JS ─── + +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 +} + +export function chainCallback(object, property, callback) { + if (object == undefined) { + console.error("Tried to add callback to non-existant object") + return; + } + if (property in object) { + const callback_orig = object[property] + object[property] = function () { + const r = callback_orig.apply(this, arguments); + callback.apply(this, arguments); + return r + }; + } else { + object[property] = callback; + } +} + +export function hideWidgetForGood(node, widget, suffix = '') { + widget.origType = widget.type + widget.origComputeSize = widget.computeSize + widget.origSerializeValue = widget.serializeValue + widget.computeSize = () => [0, -4] + widget.type = "converted-widget" + suffix + if (widget.linkedWidgets) { + for (const w of widget.linkedWidgets) { + hideWidgetForGood(node, w, ':' + widget.name) + } + } +} + +// ─── Graph coordinate helpers ─── + +export function clientToCanvas(lgCanvas, clientX, clientY) { + const rect = lgCanvas.canvas.getBoundingClientRect(); + return [ + (clientX - rect.left) / lgCanvas.ds.scale - lgCanvas.ds.offset[0], + (clientY - rect.top) / lgCanvas.ds.scale - lgCanvas.ds.offset[1], + ]; +} + +export function getNodeAtPoint(graph, cx, cy) { + for (let i = graph._nodes.length - 1; i >= 0; i--) { + if (graph._nodes[i].isPointInside(cx, cy)) return graph._nodes[i]; + } + return null; +} + +export function typesCompatible(a, b) { + if (a === "*" || b === "*") return true; + if (a === b) return true; + if (typeof a === "string" && typeof b === "string" && a.toUpperCase() === b.toUpperCase()) return true; + return false; +} + +// ─── Slot position helper ─── +// Uses modern API (DOM-registered positions in Vue mode) with legacy fallback +export function getSlotPos(node, isInput, slotIdx) { + if (isInput && node.getInputPos) return node.getInputPos(slotIdx); + if (!isInput && node.getOutputPos) return node.getOutputPos(slotIdx); + const out = [0, 0]; + node.getConnectionPos(isInput, slotIdx, out); + return out; +} + +// ─── Middle-click pan passthrough for DOM widgets ─── +// Allows panning the LiteGraph canvas via middle-click drag on any DOM element +export function addMiddleClickPan(element) { + const onMouseDown = (e) => { + if (e.button !== 1) return; + e.preventDefault(); + const ds = app.canvas?.ds; + if (!ds) return; + const startX = e.clientX, startY = e.clientY; + const startOffsetX = ds.offset[0], startOffsetY = ds.offset[1]; + const onMove = (me) => { + ds.offset[0] = startOffsetX + (me.clientX - startX); + ds.offset[1] = startOffsetY + (me.clientY - startY); + app.canvas.setDirty(true, true); + }; + const onUp = () => { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onUp); + }; + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onUp); + }; + element.addEventListener('mousedown', onMouseDown); + return () => element.removeEventListener('mousedown', onMouseDown); +} + +// ─── Resolve preview image/video from a connected source node ─── +// Walks the graph link to find what's connected to node.inputs[inputSlot] +// and returns { url, isVideo, videoEl } or null +export function resolveSourcePreview(node, inputSlot) { + if (!node.graph) return null; + const input = node.inputs?.[inputSlot]; + if (!input || input.link == null) return null; + const link = node.graph.links?.[input.link] ?? node.graph.links?.get?.(input.link); + if (!link) return null; + const srcNode = node.graph.getNodeById(link.origin_id); + if (!srcNode) return null; + + // Check for VHS-style video preview widget + const vpWidget = srcNode.widgets?.find((w) => w.name === "videopreview"); + if (vpWidget?.videoEl?.src) { + return { isVideo: true, videoEl: vpWidget.videoEl }; + } + + // Look for a LoadImage "image" widget or LoadVideo "video" widget + const w = srcNode.widgets?.find((w) => w.name === "image" || w.name === "video"); + if (w?.value) { + let subfolder = "", fname = w.value; + const lastSlash = fname.lastIndexOf("/"); + if (lastSlash >= 0) { subfolder = fname.substring(0, lastSlash); fname = fname.substring(lastSlash + 1); } + const isVideo = w.name === "video"; + const url = `/view?filename=${encodeURIComponent(fname)}&type=input&subfolder=${encodeURIComponent(subfolder)}`; + return { url, isVideo }; + } + + // Fallback: check node.imgs (set after execution) + if (srcNode.imgs?.length > 0 && srcNode.imgs[0].src) { + return { url: srcNode.imgs[0].src, isVideo: false }; + } + return null; +} + +// ─── Source input watcher ─── +// Watches a named IMAGE input for connection changes and source widget changes. +// Calls onChange(sources) when connections change or the source node's image/video widget changes. +// sources: array of { url, isVideo, videoEl } per connected IMAGE input matching inputName (or all if inputName is null). +// Returns a cleanup function. +export function watchImageInputs(node, inputName, onChange) { + let watchedWidgets = []; + + function unwatchWidgets() { + for (const { widget, origCb } of watchedWidgets) widget.callback = origCb; + watchedWidgets = []; + } + + function resolve() { + if (!node.inputs) return []; + const slots = inputName + ? node.inputs.map((inp, i) => inp.name === inputName ? i : -1).filter(i => i >= 0) + : node.inputs.map((inp, i) => inp.type === "IMAGE" ? i : -1).filter(i => i >= 0); + return slots.map(i => resolveSourcePreview(node, i)).filter(s => s !== null); + } + + function watch() { + unwatchWidgets(); + if (!node.inputs || !node.graph) return; + const slots = inputName + ? node.inputs.map((inp, i) => inp.name === inputName ? i : -1).filter(i => i >= 0) + : node.inputs.map((inp, i) => inp.type === "IMAGE" ? i : -1).filter(i => i >= 0); + for (const slotIdx of slots) { + const input = node.inputs[slotIdx]; + if (!input || input.link == null) continue; + const link = node.graph.links?.[input.link] ?? node.graph.links?.get?.(input.link); + if (!link) continue; + const srcNode = node.graph.getNodeById(link.origin_id); + if (!srcNode) continue; + const w = srcNode.widgets?.find(w => w.name === "image" || w.name === "video"); + if (!w) continue; + const origCb = w.callback; + w.callback = function (...args) { + if (origCb) origCb.apply(this, args); + setTimeout(() => onChange(resolve()), 100); + }; + watchedWidgets.push({ widget: w, origCb }); + } + } + + chainCallback(node, "onConnectionsChange", function () { + setTimeout(() => { + watch(); + onChange(resolve()); + }, 100); + }); + + chainCallback(node, "onRemoved", unwatchWidgets); + + return unwatchWidgets; +} + +// ─── Bounding box hit test ─── +// Tests whether (mx, my) hits a corner handle or the interior of a rect defined by (x1, y1)–(x2, y2). +// Returns "resize-tl", "resize-tr", "resize-bl", "resize-br", "move", or null. +export function rectHitTest(mx, my, x1, y1, x2, y2, radius) { + const hit = (cx, cy) => Math.abs(mx - cx) < radius && Math.abs(my - cy) < radius; + if (hit(x1, y1)) return "resize-tl"; + if (hit(x2, y1)) return "resize-tr"; + if (hit(x1, y2)) return "resize-bl"; + if (hit(x2, y2)) return "resize-br"; + if (mx >= x1 && mx <= x2 && my >= y1 && my <= y2) return "move"; + return null; +} + +// Returns the appropriate CSS cursor for a bbox hit mode string. +export function cursorForBboxMode(mode) { + if (mode === "move") return "move"; + if (mode === "resize-tl" || mode === "resize-br") return "nwse-resize"; + if (mode === "resize-tr" || mode === "resize-bl") return "nesw-resize"; + return null; +} + +// ─── Wheel zoom passthrough for DOM widgets ─── +// Re-dispatches wheel events to the LiteGraph canvas for zoom +export function addWheelPassthrough(element) { + element.addEventListener("wheel", (e) => { + const gc = document.getElementById("graph-canvas"); + if (gc) { + gc.dispatchEvent(new WheelEvent(e.type, e)); + e.preventDefault(); + } + }, { passive: false }); +} + diff --git a/ComfyUI-Crystools/.editorconfig b/ComfyUI-Crystools/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..0fcf04f21ded11b05867a2612a67c79fdeada051 --- /dev/null +++ b/ComfyUI-Crystools/.editorconfig @@ -0,0 +1,20 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org + +root = true + +[*] +# Change these settings to your own preference +indent_style = space +indent_size = 2 +max_line_length = 120 + +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +max_line_length = off +trim_trailing_whitespace = false diff --git a/ComfyUI-Crystools/.eslintrc.cjs b/ComfyUI-Crystools/.eslintrc.cjs new file mode 100644 index 0000000000000000000000000000000000000000..f9cb51578788e3d2bc3bf061479860afe0b79cb1 --- /dev/null +++ b/ComfyUI-Crystools/.eslintrc.cjs @@ -0,0 +1,164 @@ +module.exports = { + root: true, + env: { browser: true, es2020: true }, + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + 'plugin:@typescript-eslint/recommended-type-checked', + 'plugin:@typescript-eslint/stylistic-type-checked' + ], + parser: '@typescript-eslint/parser', + plugins: ['@typescript-eslint', 'import'], + parserOptions: { + // tsconfigRootDir: __dirname, + sourceType: 'module', + ecmaVersion: 'latest', + ecmaFeatures: { + // experimentalObjectRestSpread: true, + modules: true, + legacyDecorators: true + }, + project: ['./tsconfig.json'], + }, + rules: { + // 'import/extensions': [ + // 'error', + // "ignorePackages", + // { + // "js": "always", + // "ts": "never" + // } + // ], + 'import/no-unresolved': ['off'], + 'class-methods-use-this': ['off'], + 'radix': ['off'], + 'import/prefer-default-export': ['off'], + 'implicit-arrow-linebreak': ['off'], + 'no-trailing-spaces': [ + 'error', { + 'skipBlankLines': true, + 'ignoreComments': true, + }, + ], + 'max-len': [ + 'error', { + 'code': 120, + }, + ], + 'prefer-rest-params': ['off'], + + 'import/no-extraneous-dependencies': [ + 'error', { + 'devDependencies': ['**/__tests__/*.ts', '**/__mocks__/*.ts'], + }, + ], + + 'one-var': ['off'], + + // false positive https://github.com/typescript-eslint/typescript-eslint/issues/2483 + 'no-shadow': 'off', + 'object-curly-newline': ["error", { + "ObjectExpression": { "multiline": true, "minProperties": 8 }, + "ObjectPattern": { "multiline": true, "minProperties": 8 }, + "ImportDeclaration": {"multiline": true, "minProperties": 8 }, + "ExportDeclaration": { "multiline": true, "minProperties": 8 } + }], + "@typescript-eslint/explicit-function-return-type": 'error', + '@typescript-eslint/triple-slash-reference': 'off', + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/no-unsafe-argument': 'off', + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/prefer-nullish-coalescing': 'off', + '@typescript-eslint/consistent-type-definitions': 'off', + '@typescript-eslint/no-unused-expressions': [ + 'error', + { + 'allowShortCircuit': true, + 'allowTernary': true, + }, + ], + '@typescript-eslint/no-use-before-define': ['off'], + '@typescript-eslint/no-unused-vars': [ + 'error', + {'argsIgnorePattern': '^_'}, + ], + '@typescript-eslint/explicit-module-boundary-types': [ + 'off', { + allowArgumentsExplicitlyTypedAsAny: true, + }, + ], + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/ban-ts-comment': [ + 'off', + {'ts-expect-error': 'allow-with-description'}, + ], + '@typescript-eslint/no-empty-function': [ + 'error', + { + 'allow': [ + 'methods', + 'asyncMethods', + ], + }, + ], + + 'lines-between-class-members': 'off', + '@typescript-eslint/lines-between-class-members': 'off', + + 'curly': ['error', 'multi-line', 'consistent'], + 'no-unused-vars': 'off', + 'jest/no-test-prefixes': 'off', + 'jest/no-focused-tests': 'off', + 'comma-dangle': ['error', 'only-multiline'], + 'linebreak-style': ['error', 'unix'], + 'quotes': ['error', 'single'], + 'semi': ['error', 'always'], + 'eqeqeq': ['error', 'always'], + 'complexity': [ + 'error', { + max: 8, + }, + ], + 'block-scoped-var': 'error', + 'no-else-return': [ + 'error', { + allowElseIf: true, + }, + ], + 'no-debugger': 'off', + 'no-eval': 'error', + 'no-lone-blocks': 'error', + 'no-multi-spaces': 'error', + 'no-useless-return': 'error', + 'no-var': 'error', + 'no-console': [ + // 'error', { + // allow: ['warn', 'error'], + // }, + 'off', + ], + 'no-throw-literal': 'error', + 'newline-per-chained-call': [ + 'error', { + ignoreChainWithDepth: 4, + }, + ], + 'no-extra-boolean-cast': [ + 'error', { + enforceForLogicalOperands: true, + }, + ], + 'no-fallthrough': 'error', + 'no-use-before-define': 'off', + 'no-case-declarations': 'off', + }, + ignorePatterns: [ + 'node_modules', + 'web/**/*.d.ts', + 'web/**/*.js' + ], + globals: {}, +} diff --git a/ComfyUI-Crystools/.github/ISSUE_TEMPLATE/bug_report.md b/ComfyUI-Crystools/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..68027caf8e00fbe74a37c9f243a2496634b7aa08 --- /dev/null +++ b/ComfyUI-Crystools/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,47 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +__Please attach a workflow file to make it easier for others to reproduce the error!__ + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Error in console:** +If applicable, add the error message from the console. + +**Versions:** +Copy the output of the console (4 parts), like this: +``` +** Python version: 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)] +``` +``` +Total VRAM 12287 MB, total RAM 130996 MB +Set vram state to: NORMAL_VRAM +``` +``` +[Crystools INFO] Crystools version: 1.9.2 +[Crystools INFO] CPU: AMD Ryzen 9 5950X 16-Core Processor - Arch: AMD64 - OS: Windows 10 +[Crystools INFO] GPU/s: +[Crystools INFO] 0) NVIDIA GeForce RTX 3080 Ti +[Crystools INFO] NVIDIA Driver: 546.33 +``` +``` +### Loading: ComfyUI-Manager (V1.25.3) +### ComfyUI Revision: 1886 [6a10640f] | Released on '2024-01-08' +``` + +**Additional context** +Add any other context about the problem here. diff --git a/ComfyUI-Crystools/.github/ISSUE_TEMPLATE/feature_request.md b/ComfyUI-Crystools/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..72718d5aa63a292159351ae852c305fec1880a93 --- /dev/null +++ b/ComfyUI-Crystools/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/ComfyUI-Crystools/.github/workflows/publish.yml b/ComfyUI-Crystools/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..3f8fa2459b9ddcad50dd3115491c015ffb1400cb --- /dev/null +++ b/ComfyUI-Crystools/.github/workflows/publish.yml @@ -0,0 +1,24 @@ +name: Publish to Comfy registry +on: + workflow_dispatch: + push: + branches: + - main + paths: + - "pyproject.toml" + +permissions: + issues: write + +jobs: + publish-node: + name: Publish Custom Node to registry + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'crystian' }} + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Publish Custom Node + uses: Comfy-Org/publish-node-action@v1 + with: + personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} diff --git a/ComfyUI-Crystools/.gitignore b/ComfyUI-Crystools/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c5ba16f06e812f93872b4fb863cf2bdecfa5c84a --- /dev/null +++ b/ComfyUI-Crystools/.gitignore @@ -0,0 +1,156 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ +*.pyc + +.idea +/node_modules +/node.zip diff --git a/ComfyUI-Crystools/.others/ComfyUI.run.xml b/ComfyUI-Crystools/.others/ComfyUI.run.xml new file mode 100644 index 0000000000000000000000000000000000000000..cf00e2750e6fc7b723b204a043fc7754600f9e30 --- /dev/null +++ b/ComfyUI-Crystools/.others/ComfyUI.run.xml @@ -0,0 +1,25 @@ + + + + + \ No newline at end of file diff --git a/ComfyUI-Crystools/.others/lint.run.xml b/ComfyUI-Crystools/.others/lint.run.xml new file mode 100644 index 0000000000000000000000000000000000000000..ab127c9f140d7d18882692ea33d7f9d5c60d3b80 --- /dev/null +++ b/ComfyUI-Crystools/.others/lint.run.xml @@ -0,0 +1,12 @@ + + + + + +