Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .disabled/comfyui-kjnodes@nightly/__pycache__/__init__.cpython-310.pycAdded
- .disabled/comfyui-kjnodes@nightly/kjweb_async/marked.min.jsAdded+6
- .disabled/comfyui-kjnodes@nightly/kjweb_async/purify.min.jsAdded+3
- .disabled/comfyui-kjnodes@nightly/nodes/__pycache__/model_optimization_nodes.cpython-310.pycAdded
- .disabled/comfyui-kjnodes@nightly/nodes/__pycache__/nodes.cpython-310.pycAdded
- .disabled/comfyui-kjnodes@nightly/nodes/__pycache__/sharpen_nodes.cpython-310.pycAdded
- .disabled/comfyui-kjnodes@nightly/nodes/nodes.pyAdded
- .disabled/comfyui-kjnodes@nightly/nodes/sharpen_nodes.pyAdded+259
- .disabled/comfyui-kjnodes@nightly/utility/__pycache__/utility.cpython-310.pycAdded
- .disabled/comfyui-kjnodes@nightly/utility/fluid.pyAdded+67
- .disabled/comfyui-kjnodes@nightly/utility/magictex.pyAdded+95
- .disabled/comfyui-kjnodes@nightly/utility/numerical.pyAdded+25
- .disabled/comfyui-kjnodes@nightly/utility/utility.pyAdded+88
- .disabled/comfyui-kjnodes@nightly/web/js/appearance.jsAdded+23
- .disabled/comfyui-kjnodes@nightly/web/js/canvas_background.jsAdded+476
- .disabled/comfyui-kjnodes@nightly/web/js/contextmenu.jsAdded+256
- .disabled/comfyui-kjnodes@nightly/web/js/editors/editor_base.jsAdded+707
- .disabled/comfyui-kjnodes@nightly/web/js/editors/interpolation.jsAdded+211
- .disabled/comfyui-kjnodes@nightly/web/js/editors/point_editor_canvas.jsAdded+370
- .disabled/comfyui-kjnodes@nightly/web/js/editors/spline_editor_canvas.jsAdded+708
- .disabled/comfyui-kjnodes@nightly/web/js/fast_preview.jsAdded+31
- .disabled/comfyui-kjnodes@nightly/web/js/fillconnect.jsAdded+218
- .disabled/comfyui-kjnodes@nightly/web/js/help_popup.jsAdded+468
- .disabled/comfyui-kjnodes@nightly/web/js/jsnodes.jsAdded+402
- .disabled/comfyui-kjnodes@nightly/web/js/nodeswap.jsAdded+404
- .disabled/comfyui-kjnodes@nightly/web/js/performance.jsAdded+286
- .disabled/comfyui-kjnodes@nightly/web/js/play_sound.jsAdded+94
- .disabled/comfyui-kjnodes@nightly/web/js/screencap_stream.jsAdded+500
- .disabled/comfyui-kjnodes@nightly/web/js/setgetnodes.jsAdded+1544
- .disabled/comfyui-kjnodes@nightly/web/js/utility.jsAdded+230
- ComfyUI-Crystools/.editorconfigAdded+20
- ComfyUI-Crystools/.eslintrc.cjsAdded+164
- ComfyUI-Crystools/.github/ISSUE_TEMPLATE/bug_report.mdAdded+47
- ComfyUI-Crystools/.github/ISSUE_TEMPLATE/feature_request.mdAdded+20
- ComfyUI-Crystools/.github/workflows/publish.ymlAdded+24
- ComfyUI-Crystools/.gitignoreAdded+156
- ComfyUI-Crystools/.others/ComfyUI.run.xmlAdded+25
- ComfyUI-Crystools/.others/lint.run.xmlAdded+12
- ComfyUI-Crystools/.others/pre-commitAdded+33
- ComfyUI-Crystools/.others/typescript.run.xmlAdded+12
- ComfyUI-Crystools/.others/version.pyAdded+60
- ComfyUI-Crystools/LICENSEAdded+21
- ComfyUI-Crystools/README.mdAdded+672
- ComfyUI-Crystools/__init__.pyAdded+108
- ComfyUI-Crystools/core/__init__.pyAdded+6
- ComfyUI-Crystools/core/__pycache__/__init__.cpython-310.pycAdded
- ComfyUI-Crystools/core/__pycache__/common.cpython-310.pycAdded
- ComfyUI-Crystools/core/__pycache__/config.cpython-310.pycAdded
- ComfyUI-Crystools/core/__pycache__/keys.cpython-310.pycAdded
- ComfyUI-Crystools/core/__pycache__/logger.cpython-310.pycAdded
123456/**
* 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.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(/\\\|/g,"|");return n}function x(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s;){const i=e.charAt(s-r-1);if(i!==t||n){if(i===t||!n)break;r++}else r++}return e.slice(0,s-r)}function b(e,t,n,s){const r=t.href,i=t.title?c(t.title):null,l=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:r,title:i,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:r,title:i,text:c(l)}}class w{options;rules;lexer;constructor(t){this.options=t||e.defaults}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)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<r.items.length;e++)if(this.lexer.state.top=!1,r.items[e].tokens=this.lexer.blockTokens(r.items[e].text,[]),!r.loose){const t=r.items[e].tokens.filter((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<r.items.length;e++)r.items[e].loose=!0;return r}}html(e){const t=this.rules.block.html.exec(e);if(t){return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$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&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/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)){if(!/>$/.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<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return-1}(t[2],"()");if(e>-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(n)&&(n=this.options.pedantic&&!/>$/.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=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,I=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\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","</?(?:tag)(?: +|\\n|/?>)|<(?: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","</?(?:tag)(?: +|\\n|/?>)|<(?: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","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex()},P={...q,html:k("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\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:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\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:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\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]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:f},V={...K,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",F).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",F).getRegex()},W={...K,escape:k(Q).replace("])","~|])").getRegex(),url:k(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Y={...W,br:k(v).replace("{2,}","*").getRegex(),text:k(W.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ee={normal:q,gfm:L,pedantic:P},te={normal:K,gfm:W,breaks:Y,pedantic:V};class ne{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||e.defaults,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:ee.normal,inline:te.normal};this.options.pedantic?(n.block=ee.pedantic,n.inline=te.pedantic):this.options.gfm&&(n.block=ee.gfm,this.options.breaks?n.inline=te.breaks:n.inline=te.gfm),this.tokenizer.rules=n}static get rules(){return{block:ee,inline:te}}static lex(e,t){return new ne(t).lex(e)}static lexInline(e,t){return new ne(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){let n,s,r,i;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>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?'<pre><code class="language-'+c(s)+'">'+(n?e:c(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:c(e,!0))+"</code></pre>\n"}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}html(e,t){return e}heading(e,t,n){return`<h${t}>${e}</h${t}>\n`}hr(){return"<hr>\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+s+">\n"}listitem(e,t,n){return`<li>${e}</li>\n`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>\n`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return`<tr>\n${e}</tr>\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){const s=g(e);if(null===s)return n;let r='<a href="'+(e=s)+'"';return t&&(r+=' title="'+t+'"'),r+=">"+n+"</a>",r}image(e,t,n){const s=g(e);if(null===s)return n;let r=`<img src="${e=s}" alt="${n}"`;return t&&(r+=` title="${t}"`),r+=">",r}text(e){return e}}class re{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}class ie{options;renderer;textRenderer;constructor(t){this.options=t||e.defaults,this.options.renderer=this.options.renderer||new se,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new re}static parse(e,t){return new ie(t).parse(e)}static parseInline(e,t){return new ie(t).parseInline(e)}parse(e,t=!0){let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=r,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}switch(r.type){case"space":continue;case"hr":n+=this.renderer.hr();continue;case"heading":{const e=r;n+=this.renderer.heading(this.parseInline(e.tokens),e.depth,p(this.parseInline(e.tokens,this.textRenderer)));continue}case"code":{const e=r;n+=this.renderer.code(e.text,e.lang,!!e.escaped);continue}case"table":{const e=r;let t="",s="";for(let t=0;t<e.header.length;t++)s+=this.renderer.tablecell(this.parseInline(e.header[t].tokens),{header:!0,align:e.align[t]});t+=this.renderer.tablerow(s);let i="";for(let t=0;t<e.rows.length;t++){const n=e.rows[t];s="";for(let t=0;t<n.length;t++)s+=this.renderer.tablecell(this.parseInline(n[t].tokens),{header:!1,align:e.align[t]});i+=this.renderer.tablerow(s)}n+=this.renderer.table(t,i);continue}case"blockquote":{const e=r,t=this.parse(e.tokens);n+=this.renderer.blockquote(t);continue}case"list":{const e=r,t=e.ordered,s=e.start,i=e.loose;let l="";for(let t=0;t<e.items.length;t++){const n=e.items[t],s=n.checked,r=n.task;let o="";if(n.task){const e=this.renderer.checkbox(!!s);i?n.tokens.length>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<e.length&&"text"===e[s+1].type;)i=e[++s],l+="\n"+(i.tokens?this.parseInline(i.tokens):i.text);n+=t?this.renderer.paragraph(l):l;continue}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=this.options.extensions.renderers[r.type].call({parser:this},r);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=e||"";continue}}switch(r.type){case"escape":{const e=r;n+=t.text(e.text);break}case"html":{const e=r;n+=t.html(e.text);break}case"link":{const e=r;n+=t.link(e.href,e.title,this.parseInline(e.tokens,t));break}case"image":{const e=r;n+=t.image(e.href,e.title,e.text);break}case"strong":{const e=r;n+=t.strong(this.parseInline(e.tokens,t));break}case"em":{const e=r;n+=t.em(this.parseInline(e.tokens,t));break}case"codespan":{const e=r;n+=t.codespan(e.text);break}case"br":n+=t.br();break;case"del":{const e=r;n+=t.del(this.parseInline(e.tokens,t));break}case"text":{const e=r;n+=t.text(e.text);break}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}class le{options;constructor(t){this.options=t||e.defaults}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}}class oe{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.#e(ne.lex,ie.parse);parseInline=this.#e(ne.lexInline,ie.parseInline);Parser=ie;Renderer=se;TextRenderer=re;Lexer=ne;Tokenizer=w;Hooks=le;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(const s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{const e=s;for(const s of e.header)n=n.concat(this.walkTokens(s.tokens,t));for(const s of e.rows)for(const e of s)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=s;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((s=>{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="<p>An error occurred:</p><pre>"+c(n.message+"",!0)+"</pre>";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}));123/*! @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;n<e;n++)t[n]=arguments[n];return s(N,t)});var N;function b(e){return function(t){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return c(e,t,o)}}function S(e,o){let r=arguments.length>2&&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<e.length;t++){E(e,t)||(e[t]=null)}return e}function w(t){const n=l(null);for(const[o,r]of e(t)){E(t,o)&&(Array.isArray(r)?n[o]=R(r):r&&"object"==typeof r&&r.constructor===Object?n[o]=w(r):n[o]=r)}return n}function L(e,t){for(;null!==e;){const n=r(e,t);if(n){if(n.get)return b(n.get);if("function"==typeof n.value)return b(n.value)}e=o(e)}return function(){return null}}const D=i(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),C=i(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),O=i(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),x=i(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),v=i(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),k=i(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),M=i(["#text"]),I=i(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),U=i(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),P=i(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),F=i(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),H=a(/\{\{[\w\W]*|[\w\W]*\}\}/gm),z=a(/<%[\w\W]*|[\w\W]*%>/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="<remove></remove>"+e;else{const t=h(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===tt&&Ze===Ve&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");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="<!DOCTYPE "+n.ownerDocument.doctype.name+">\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.map123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259import 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 out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import 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, pressure1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""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 c12345678910111213141516171819202122232425from 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import 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_list1234567891011121314151617181920212223const { 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;
}
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476const { 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;
};
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256const { 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;
};
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707import { 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) {}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211// ─── 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 };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370import { 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;
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708import { 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();
}
}12345678910111213141516171819202122232425262728293031import { 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);
});
});
}
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218const { 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",
},
],
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468const { 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 <a> tags, auto-link bare URLs, preserve line breaks
const escaped = description
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
.replace(/(^|[^"'])(https?:\/\/[^\s<]+)/g, '$1<a href="$2" target="_blank">$2</a>')
.replace(/\n/g, '<br>')
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 })
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402const { 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;
}
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404const { 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();
};
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286const { 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);
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394const { 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();
}
};
},
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500import { 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);
};
};
},
});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544const { 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;
};
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230const { 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 });
}
1234567891011121314151617181920# 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 = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164module.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: {},
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647---
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.1234567891011121314151617181920---
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.123456789101112131415161718192021222324name: 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 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156# 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.zip12345678910111213141516171819202122232425<component name="ProjectRunConfigurationManager">
<configuration default="false" name="ComfyUI" type="PythonConfigurationType" factoryName="Python">
<module name="ComfyUI" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
<env name="CRYSTOOLS_LOGLEVEL" value="10" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="X:\comfy\ComfyUI" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/main.py" />
<option name="PARAMETERS" value="--extra-model-paths-config ..\extra_model_paths.yaml --output-directory ..\..\comfyUI.output --input-directory ..\..\comfyUI.input --disable-auto-launch --preview-size 1024 --front-end-version aComfy-Org/ComfyUI_frontend@latest" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>123456789101112<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lint" type="js.build_tools.npm">
<package-json value="$PROJECT_DIR$/custom_nodes/comfyui-crystools/package.json" />
<command value="run" />
<scripts>
<script value="lint" />
</scripts>
<node-interpreter value="project" />
<envs />
<method v="2" />
</configuration>
</component>123456789101112131415161718192021222324252627282930313233#!/bin/bash
# REMEMBER TO COPY THIS FILE INTO .git/hooks/pre-commit
cd ../comfy/ComfyUI
rm ./custom_nodes/comfyui-crystools/web/*.js -f
LOCAL_COMMAND="npm --prefix ./custom_nodes/comfyui-crystools run validate"
OUTPUT=$($LOCAL_COMMAND 2>&1)
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
echo "Validate ok"
cd ../../comfyui-crystools
else
echo "Validate KO!"
echo $OUTPUT
exit 1
fi
LOCAL_COMMAND="python .others/version.py"
OUTPUT=$($LOCAL_COMMAND 2>&1)
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
echo "Version changed"
else
echo "Can't change the version! check the .other/version.py"
echo $OUTPUT
exit 1
fi
git add version pyproject.toml __init__.py core/version.py web/*.js123456789101112<component name="ProjectRunConfigurationManager">
<configuration default="false" name="typescript" type="js.build_tools.npm">
<package-json value="$PROJECT_DIR$/package.json" />
<command value="run" />
<scripts>
<script value="start" />
</scripts>
<node-interpreter value="W:/!Workstation/nodejs/node" />
<envs />
<method v="2" />
</configuration>
</component>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import os
print("-- Setting up the version --")
versionLabel = "@version:"
version_file = os.path.join(os.path.dirname(__file__), "../version")
with open(version_file, "r") as f:
version = f.read().strip()
if version is None or version == "":
raise RuntimeError(f"File without version: {version_file}")
print(f"Version to set: {version}")
# modify the __init__.py file with @version
file1 = os.path.join(os.path.dirname(__file__), "../__init__.py")
print(f"> File1: {file1}")
file1VersionFound = False
# lines = None
with open(file1, "r") as f:
lines = f.readlines()
for line in lines:
if versionLabel in line:
file1VersionFound = True
lines[lines.index(line)] = f"{versionLabel} {version}\n"
if not file1VersionFound:
raise RuntimeError(f"Version label not found in file: {file1}")
with open(file1, "w") as f2:
f2.writelines(lines)
file2 = os.path.join(os.path.dirname(__file__), "../core/version.py")
print(f"> File2 {file2}")
with open(file2, "w") as f2:
f2.writelines([f"version = \"{version}\"\n"])
# modify pyproject.toml file with @version
file3 = os.path.join(os.path.dirname(__file__), "../pyproject.toml")
print(f"> File3: {file3}")
file3VersionFound = False
# lines = None
with open(file3, "r") as f:
lines = f.readlines()
for line in lines:
if "version = " in line:
file3VersionFound = True
lines[lines.index(line)] = f"version = \"{version}\"\n"
if not file3VersionFound:
raise RuntimeError(f"Version label not found in file: {file3}")
with open(file3, "w") as f3:
f3.writelines(lines)123456789101112131415161718192021MIT License
Copyright (c) 2023 Crystian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672# comfyui-crystools [](https://paypal.me/crystian77) <a src="https://colab.research.google.com/assets/colab-badge.svg" href="https://colab.research.google.com/drive/1xiTiPmZkcIqNOsLQPO1UNCdJZqgK3U5k?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"></a>
**_🪛 A powerful set of tools for your belt when you work with ComfyUI 🪛_**
With this suit, you can see the resources monitor, progress bar & time elapsed, metadata and compare between two images, compare between two JSONs, show any value to console/display, pipes, and more!
This provides better nodes to load/save images, previews, etc, and see "hidden" data without loading a new workflow.

# Table of contents
- [General](#general)
- [Metadata](#metadata)
- [Debugger](#debugger)
- [Image](#image)
- [Pipe](#pipe)
- [Utils](#utils)
- [Primitives](#primitives)
- [List](#list)
- [Switch](#switch)
- Others: [About](#about), [To do](#to-do), [Changelog](#changelog), [Installation](#installation), [Use](#use)
---
## General
### Resources monitor
**🎉Finally, you can see the resources used by ComfyUI (CPU, GPU, RAM, VRAM, GPU Temp and space) on the menu in real-time!**
Horizontal:

Vertical:

Now you can identify the bottlenecks in your workflow and know when it's time to restart the server, unload models or even close some tabs!
You can configure the refresh rate which resources to show:

> **Notes:**
> - The GPU data is only available when you use CUDA (only NVIDIA cards, sorry AMD users).
> - This extension needs ComfyUI 1915 (or higher).
> - The cost of the monitor is low (0.1 to 0.5% of utilization), you can disable it from settings (`Refres rate` to `0`).
> - Data comes from these libraries:
> - [psutil](https://pypi.org/project/psutil/)
> - [torch](https://pytorch.org/)
> - [pynvml](https://pypi.org/project/pynvml/) (official NVIDIA library)
### Progress bar
You can see the progress of your workflow with a progress bar on the menu!

https://github.com/crystian/comfyui-crystools/assets/3886806/35cc1257-2199-4b85-936e-2e31d892959c
Additionally, it shows the time elapsed at the end of the workflow, and you can `click` on it to see the **current working node.**
> **Notes:**
> - If you don't want to see it, you can turn it off from settings (`Show progress bar in menu`)
## Metadata
### Node: Metadata extractor
This node is used to extract the metadata from the image and handle it as a JSON source for other nodes.
You can see **all information**, even metadata from other sources (like Photoshop, see sample).
The input comes from the [load image with metadata](#node-load-image-with-metadata) or [preview from image](#node-preview-from-image) nodes (and others in the future).

**Sample:** [metadata-extractor.json](./samples/metadata-extractor.json)
><details>
> <summary>Other metadata sample (photoshop)</summary>
>
> With metadata from Photoshop

></details>
><details>
> <summary><i>Parameters</i></summary>
>
> - input:
> - metadata_raw: The metadata raw from the image or preview node
> - Output:
> - prompt: The prompt used to produce the image.
> - workflow: The workflow used to produce the image (all information about nodes, values, etc).
> - file info: The file info of the image/metadata (resolution, size, etc) is human readable.
> - raw to JSON: The entire metadata is raw but formatted/readable.
> - raw to property: The entire metadata is raw in "properties" format.
> - raw to csv: The entire metadata is raw in "csv" format.
></details>
<br />
### Node: Metadata comparator
This node is so useful for comparing two metadata and seeing the differences (**the main reason why I created this extension!**)
You can compare 3 inputs: "Prompt", "Workflow" and "Fileinfo"
There are three potential "outputs": `values_changed`, `dictionary_item_added`, and `dictionary_item_removed` (in this order of priority).

**Sample:** [metadata-comparator.json](./samples/metadata-comparator.json)
**Notes:**
- I use [DeepDiff](https://pypi.org/project/deepdiff) for that. For more info check the link.
- If you want to compare two JSONs, you can use the [JSON comparator](#node-JSON-comparator) node.
><details>
> <summary><i>Parameters</i></summary>
>
> - options:
> - what: What to compare, you can choose between "Prompt", "Workflow" and "Fileinfo"
> - input:
> - metadata_raw_old: The metadata raw to start comparing
> - metadata_raw_new: The metadata raw to compare
> - Output:
> - diff: This is the same output you can see in the display of the node; you can use it on other nodes.
></details>
<br />
---
## Debugger
### Node: Show Metadata
With this node, you will be able to see the JSON produced from your entire prompt and workflow so that you can know all the values (and more) of your prompt quickly without opening the file (PNG or JSON).

**Sample:** [debugger-metadata.json](./samples/debugger-metadata.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Options:
> - Active: Enable/disable the node
> - Parsed: Show the parsed JSON or plain text
> - What: Show the prompt or workflow (prompt are values to produce the image, and workflow is the entire workflow of ComfyUI)
></details>
<br />
### Node: Show any
You can see on the console or display any text or data from the nodes. Connect it to what you want to inspect, and you will see it.

**Sample:** [debugger-any.json](./samples/debugger-any.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - any_value: Any value to show, which can be a string, number, etc.
> - Options:
> - Console: Enable/disable write to console
> - Display: Enable/disable write on this node
> - Prefix: Prefix to console
></details>
<br />
### Node: Show any to JSON
It is the same as the previous one, but it formatted the value to JSON (only display).

**Sample:** [debugger-json.json](./samples/debugger-json.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - any_value: Any value to try to convert to JSON
> - Output:
> - string: The same string is shown on the display
></details>
<br />
---
## Image
### Node: Load image with metadata
This node is the same as the default one, but it adds three features: Prompt, Metadata, and supports **subfolders** of the "input" folder.

**Sample:** [image-load.json](./samples/image-load.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - image: Read the images from the input folder (and subfolder) (you can drop the image here or even paste an image from the clipboard)
> - Output:
> - Image/Mask: The same as the default node
> - Prompt: The prompt used to produce the image (not the workflow)
> - Metadata RAW: The metadata raw of the image (full workflow) as string
></details>
**Note:** The subfolders support inspired on: [comfyui-imagesubfolders](https://github.com/catscandrive/comfyui-imagesubfolders)
<br />
### Node: Save image with extra metadata
This node is the same as the default one, but it adds two features: Save the workflow in the png or not, and you can add any piece of metadata (as JSON).
This saves custom data on the image, so you can share it with others, and they can see the workflow and metadata (see [preview from metadata](#node-preview-from-metadata)), even your custom data.
It can be any type of information that supports text and JSON.

**Sample:** [image-save.json](./samples/image-save.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - options:
> - with_workflow: If you want to save into the image workflow (special to share the workflow with others)
> - Input:
> - image: The image to save (same as the default node)
> - Output:
> - Metadata RAW: The metadata raw of the image (full workflow) as string
></details>
**Note:** The data is saved as special "exif" (as ComfyUI does) in the png file; you can read it with [Load image with metadata](#node-load-image-with-metadata).
> **Important:**
> - If you want to save your workflow with a particular name and your data as creator, you need to use the [ComfyUI-Crystools-save](https://github.com/crystian/ComfyUI-Crystools-save) extension; try it!

<br />
### Node: Preview from image
This node is used to preview the image with the **current prompt** and additional features.

**Feature:** It supports cache (shows as "CACHED") (not permanent yet!), so you can disconnect the node and still see the image and data, so you can use it to compare with others!

As you can see the seed, steps, and cfg were changed
**Sample:** [image-preview-image.json](./samples/image-preview-image.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - image: Any kind of image link
> - Output:
> - Metadata RAW: The metadata raw of the image and full workflow.
> - You can use it to **compare with others** (see [metadata comparator](#node-metadata-comparator))
> - The file info like filename, resolution, datetime and size with **the current prompt, not the original one!** (see important note)
></details>
> **Important:**
> - If you want to read the metadata of the image, you need to use the [load image with metadata](#node-load-image-with-metadata) and use the output "metadata RAW" not the image link.
> - To do a preview, it is necessary to save it first on the temporal folder, and the data shown is from the temporal image, **not the original one** even **the prompt!**
<br />
### Node: Preview from metadata
This node is used to preview the image from the metadata and shows additional data (all around this one).
It supports the same features as [preview from image](#node-preview-from-image) (cache, metadata raw, etc.). But the important difference is you see **real data from the image** (not the temporal one or the current prompt).

**Sample:** [image-preview-metadata.json](./samples/image-preview-metadata.json)
<br />
### Node: Show resolution
This node is used to show the resolution of an image.
> Can be used with any image link.

**Sample:** [image-resolution.json](./samples/image-resolution.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - image: Any kind of image link
> - Output:
> - Width: The width of the image
> - Height: The height of the image
></details>
<br />
---
## Pipe
### Nodes: Pipe to/edit any, Pipe from any
This powerful set of nodes is used to better organize your pipes.
The "Pipe to/edit any" node is used to encapsulate multiple links into a single one. It includes support for editing and easily adding the modified content back to the same pipe number.
The "Pipe from any" node is used to extract the content of a pipe.
Typical example:

With pipes:

**Sample:** [pipe-1.json](./samples/pipe-1.json)
Editing pipes:

**Sample:** [pipe-2.json](./samples/pipe-2.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - CPipeAny: This is the type of this pipe you can use to edit (see the sample)
> - any_*: 6 possible inputs to use
> - Output:
> - CPipeAny: You can continue the pipe with this output; you can use it to bifurcate the pipe (see the sample)
></details>
>**Important:**
> - Please note that it supports "any," meaning it does not validate (not yet!) the correspondence of input nodes with the output ones. When creating the link, it is recommended to link consciously number by number.
> - "RecursionError" It's crucial to note that the flow of links **must be in the same direction**, and they cannot be mixed with other flows that use the result of this one. Otherwise, this may lead to recursion and block the server (you need to restart it!)
><details>
> <summary><i>Bad example with "RecursionError: maximum recursion depth exceeded"</i></summary>
>
> If you see something like this on your console, you need to check your pipes. That is bad sample of pipes, you can't mix the flows.

></details>
<br />
---
## Utils
Some useful nodes to use in your workflow.
### Node: JSON comparator
This node is so useful to compare two JSONs and see the differences.

**Sample:** [utils-json-comparator.json](./samples/utils-json-comparator.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - input:
> - json_old: The first JSON to start compare
> - json_new: The JSON to compare
> - Output:
> - diff: A new JSON with the differences
></details>
**Notes:**
As you can see, it is the same as the [metadata comparator](#node-metadata-comparator) but with JSONs.
The other is intentionally simple to compare two images metadata; this is more generic.
The main difference is that you can compare any JSON, not only metadata.
<br />
### Node: Stats system
This node is used to show the system stats (RAM, VRAM, and Space).
It **should** connect as a pipe.

**Sample:** [utils-stats.json](./samples/utils-stats.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - input:
> - latent: The latent to use to measure the stats
> - Output:
> - latent: Return the same latent to continue the pipe
></details>
**Notes:** The original is in [WAS](https://github.com/WASasquatch/was-node-suite-comfyui), I only show it on the display.
<br />
---
## Primitives
### Nodes: Primitive boolean, Primitive integer, Primitive float, Primitive string, Primitive string multiline
A set of nodes with primitive values to use in your prompts.

<br />
---
## List
A set of nodes with a list of values (any or strings/texts) for any proposal (news nodes to use it coming soon!).
> **Important:** You can use other nodes like "Show any" to see the values of the list
### Node: List of strings
**Feature:** You can concatenate them.

**Sample:** [list-strings.json](./samples/list-strings.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - string_*: 8 possible inputs to use
> - delimiter: Use to concatenate the values on the output
> - Output:
> - concatenated: A string with all values concatenated
> - list_string: The list of strings (only with values)
></details>
<br />
### Node: List of any
You can concatenate any value (it will try to convert it to a string and show the value), so it is util to see several values at the same time.

**Sample:** [list-any.json](./samples/list-any.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - any_*: 8 possible inputs to use
> - Output:
> - list_any: The list of any elements (only with values)
></details>
<br />
---
## Switch
A set of nodes to switch between flows.
All switches are boolean; you can switch between flows by simply changing the value of the switch.
You have predefined switches (string, latent, image, conditioning) but you can use "Switch any" for any value/type.

**Sample:** [switch.json](./samples/switch.json)
<br />
---
## About
**Notes from the author:**
- This is my first project in python ¯\\_(ツ)_/¯ (PR are welcome!)
- I'm a software engineer but in other languages (web technologies)
- My Instagram is: https://www.instagram.com/crystian.ia I'll publish my works on it, so consider following me for news! :)
- I'm not a native English speaker, so sorry for my English :P
---
## To do
- [ ] Several unit tests
- [ ] Add permanent cache for preview/metadata image (to survive to F5! or restart the server)
---
## Changelog
### Crystools
### 1.27.0 (17/08/2025)
- revert the lower case on name, cannot change on registry ¯\_(ツ)_/¯
- zluda check removed, it is not necessary anymore
### 1.25.3 (27/07/2025)
- change the name to lower case
### 1.25.1 (02/06/2025)
- fix issues with switches on settings menu
- node: "Switch from any" added
- load image with metadata: filtered (exclude hidden folders an typically metadata files)
- other fixes
### 1.24.0 (02/06/2025)
- PRs by community merged
- Improved VRAM usage/readout
- HDD error handling
- Lazy switches
### 1.23.0 (02/06/2025)
- Jetson support added by @johnnynunez
- some ui fixes
### 1.20.0 (21/10/2024)
- BETA of JSON file reader and extractor, to allow you to read your own JSON files and extract the values to use in your workflow
### 1.19.0 (06/10/2024)
- HORIZONTAL UI! New version is ready! 🎉
### 1.18.0 (21/09/2024)
- HORIZONTAL UI! 🎉
- Configurable size of monitors on settings menu
### 1.17.0 (21/09/2024)
- Settings menu reorganized
- Preparing for horizontal UI
- Update from ComfyUI (typescript and new features)
### 1.16.0 (31/07/2024)
- Rollback of AMD support by manager does not support other repository parameter (https://test.pypi.org/simple by pyrsmi)
### 1.15.0 (21/07/2024)
- AMD Branch merged to the main branch, should work for AMD users on **Linux**
### 1.14.0 (15/07/2024)
- Tried to use AMD info, but it breaks installation on windows, so I removed it ¯\_(ツ)_/¯
- AMD Branch added, if you use AMD and Linux, you can try it (not tested for me)
### 1.13.0 (01/07/2024)
- Integrate with new ecosystem of ComfyUI
- Webp support added on load image with metadata node
### 1.12.0 (27/03/2024)
- GPU Temperature added
### 1.10.0 (17/01/2024)
- Multi-gpu added
### 1.9.2 (15/01/2024)
- Big refactor on hardwareInfo and monitor.ts, gpu was separated on another file, preparing for multi-gpu support
### 1.8.0 (14/01/2024) - internal
- HDD monitor selector on settings
### 1.7.0 (11/01/2024) - internal
- Typescript added!
### 1.6.0 (11/01/2024)
- Fix issue [#7](https://github.com/crystian/comfyui-crystools/issues/7) to the thread deadlock on concurrency
### 1.5.0 (10/01/2024)
- Improvements on the resources monitor and how handle the threads
- Some fixes
### 1.3.0 (08/01/2024)
- Added in general Resources monitor (CPU, GPU, RAM, VRAM, and space)
- Added this icon to identify this set of tools: 🪛
### 1.2.0 (05/01/2024)
- progress bar added
### 1.1.0 (29/12/2023)
- Node added: "Save image with extra metadata"
- Support to **read** Jpeg metadata added (not save)
### 1.0.0 (26/12/2023)
- First release
### Crystools-save - DEPRECATED (01/06/2025)
### 1.1.0 (07/01/2024)
- Labeling updated according to the new version of Crystools (this project)
### 1.0.0 (29/12/2023)
- Created another extension to save the info about the author on workflow: [ComfyUI-Crystools-save](https://github.com/crystian/ComfyUI-Crystools-save)
---
## Installation
### Install from GitHub
1. Install [ComfyUi](https://github.com/comfyanonymous/ComfyUI).
2. Clone this repo into `custom_nodes`:
```
cd ComfyUI/custom_nodes
git clone https://github.com/crystian/comfyui-crystools.git
cd comfyui-crystools
pip install -r requirements.txt
```
3. Start up ComfyUI.
#### For AMD users
If you are an AMD user with Linux, you can try the AMD branch:
**ATTENTION:** Don't install with the manager, you need to install manually:
```
cd ComfyUI/custom_nodes
git clone -b AMD https://github.com/crystian/comfyui-crystools.git
cd comfyui-crystools
pip install -r requirements.txt
```
### Install from manager
Search for `crystools` in the [manager](https://github.com/ltdrdata/ComfyUI-Manager.git) and install it.
### Using on Google Colab
You can use it on Google Colab, but you need to install it manually:
[Google Colab](https://colab.research.google.com/drive/1xiTiPmZkcIqNOsLQPO1UNCdJZqgK3U5k?usp=sharing)
* Run the first cell to install ComfyUI and launch the server
* After it finishes, use the link to open the a new tab, looking a line like this:
```
This is the URL to access ComfyUI: https://identifying-complications-fw-some.trycloudflare.com
```
---
## Use
You can use it as any other node, just using the menu in the category `crystools` or double clicking on the canvas (I recommended using the "oo" to fast filter), all nodes were post fixing with `[Crystools]`.


If for some reason you need to see the logs, you can define the environment variable `CRYSTOOLS_LOGLEVEL` and set the [value](https://docs.python.org/es/3/howto/logging.html).
---
Made with ❤️ by Crystian.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""
@author: Crystian
@title: Crystools
@nickname: Crystools
@version: 1.27.4
@project: "https://github.com/crystian/comfyui-crystools",
@description: Plugins for multiples uses, mainly for debugging, you need them! IG: https://www.instagram.com/crystian.ia
"""
from .core import version, logger
logger.info(f'Crystools version: {version}')
from .nodes._names import CLASSES
from .nodes.primitive import CBoolean, CText, CTextML, CInteger, CFloat
from .nodes.switch import CSwitchBooleanAny, CSwitchBooleanLatent, CSwitchBooleanConditioning, CSwitchBooleanImage, \
CSwitchBooleanString, CSwitchBooleanMask, CSwitchFromAny
from .nodes.debugger import CConsoleAny, CConsoleAnyToJson
from .nodes.image import CImagePreviewFromImage, CImageLoadWithMetadata, CImageGetResolution, CImagePreviewFromMetadata, \
CImageSaveWithExtraMetadata
from .nodes.list import CListAny, CListString
from .nodes.pipe import CPipeToAny, CPipeFromAny
from .nodes.utils import CUtilsCompareJsons, CUtilsStatSystem
from .nodes.metadata import CMetadataExtractor, CMetadataCompare
from .nodes.parameters import CJsonFile, CJsonExtractor
from .server import *
from .general import *
NODE_CLASS_MAPPINGS = {
CLASSES.CBOOLEAN_NAME.value: CBoolean,
CLASSES.CTEXT_NAME.value: CText,
CLASSES.CTEXTML_NAME.value: CTextML,
CLASSES.CINTEGER_NAME.value: CInteger,
CLASSES.CFLOAT_NAME.value: CFloat,
CLASSES.CDEBUGGER_CONSOLE_ANY_NAME.value: CConsoleAny,
CLASSES.CDEBUGGER_CONSOLE_ANY_TO_JSON_NAME.value: CConsoleAnyToJson,
CLASSES.CLIST_ANY_NAME.value: CListAny,
CLASSES.CLIST_STRING_NAME.value: CListString,
CLASSES.CSWITCH_FROM_ANY_NAME.value: CSwitchFromAny,
CLASSES.CSWITCH_ANY_NAME.value: CSwitchBooleanAny,
CLASSES.CSWITCH_LATENT_NAME.value: CSwitchBooleanLatent,
CLASSES.CSWITCH_CONDITIONING_NAME.value: CSwitchBooleanConditioning,
CLASSES.CSWITCH_IMAGE_NAME.value: CSwitchBooleanImage,
CLASSES.CSWITCH_MASK_NAME.value: CSwitchBooleanMask,
CLASSES.CSWITCH_STRING_NAME.value: CSwitchBooleanString,
CLASSES.CPIPE_TO_ANY_NAME.value: CPipeToAny,
CLASSES.CPIPE_FROM_ANY_NAME.value: CPipeFromAny,
CLASSES.CIMAGE_LOAD_METADATA_NAME.value: CImageLoadWithMetadata,
CLASSES.CIMAGE_GET_RESOLUTION_NAME.value: CImageGetResolution,
CLASSES.CIMAGE_PREVIEW_IMAGE_NAME.value: CImagePreviewFromImage,
CLASSES.CIMAGE_PREVIEW_METADATA_NAME.value: CImagePreviewFromMetadata,
CLASSES.CIMAGE_SAVE_METADATA_NAME.value: CImageSaveWithExtraMetadata,
CLASSES.CMETADATA_EXTRACTOR_NAME.value: CMetadataExtractor,
CLASSES.CMETADATA_COMPARATOR_NAME.value: CMetadataCompare,
CLASSES.CUTILS_JSON_COMPARATOR_NAME.value: CUtilsCompareJsons,
CLASSES.CUTILS_STAT_SYSTEM_NAME.value: CUtilsStatSystem,
CLASSES.CJSONFILE_NAME.value: CJsonFile,
CLASSES.CJSONEXTRACTOR_NAME.value: CJsonExtractor,
}
NODE_DISPLAY_NAME_MAPPINGS = {
CLASSES.CBOOLEAN_NAME.value: CLASSES.CBOOLEAN_DESC.value,
CLASSES.CTEXT_NAME.value: CLASSES.CTEXT_DESC.value,
CLASSES.CTEXTML_NAME.value: CLASSES.CTEXTML_DESC.value,
CLASSES.CINTEGER_NAME.value: CLASSES.CINTEGER_DESC.value,
CLASSES.CFLOAT_NAME.value: CLASSES.CFLOAT_DESC.value,
CLASSES.CDEBUGGER_CONSOLE_ANY_NAME.value: CLASSES.CDEBUGGER_ANY_DESC.value,
CLASSES.CDEBUGGER_CONSOLE_ANY_TO_JSON_NAME.value: CLASSES.CDEBUGGER_CONSOLE_ANY_TO_JSON_DESC.value,
CLASSES.CLIST_ANY_NAME.value: CLASSES.CLIST_ANY_DESC.value,
CLASSES.CLIST_STRING_NAME.value: CLASSES.CLIST_STRING_DESC.value,
CLASSES.CSWITCH_FROM_ANY_NAME.value: CLASSES.CSWITCH_FROM_ANY_DESC.value,
CLASSES.CSWITCH_ANY_NAME.value: CLASSES.CSWITCH_ANY_DESC.value,
CLASSES.CSWITCH_LATENT_NAME.value: CLASSES.CSWITCH_LATENT_DESC.value,
CLASSES.CSWITCH_CONDITIONING_NAME.value: CLASSES.CSWITCH_CONDITIONING_DESC.value,
CLASSES.CSWITCH_IMAGE_NAME.value: CLASSES.CSWITCH_IMAGE_DESC.value,
CLASSES.CSWITCH_MASK_NAME.value: CLASSES.CSWITCH_MASK_DESC.value,
CLASSES.CSWITCH_STRING_NAME.value: CLASSES.CSWITCH_STRING_DESC.value,
CLASSES.CPIPE_TO_ANY_NAME.value: CLASSES.CPIPE_TO_ANY_DESC.value,
CLASSES.CPIPE_FROM_ANY_NAME.value: CLASSES.CPIPE_FROM_ANY_DESC.value,
CLASSES.CIMAGE_LOAD_METADATA_NAME.value: CLASSES.CIMAGE_LOAD_METADATA_DESC.value,
CLASSES.CIMAGE_GET_RESOLUTION_NAME.value: CLASSES.CIMAGE_GET_RESOLUTION_DESC.value,
CLASSES.CIMAGE_PREVIEW_IMAGE_NAME.value: CLASSES.CIMAGE_PREVIEW_IMAGE_DESC.value,
CLASSES.CIMAGE_PREVIEW_METADATA_NAME.value: CLASSES.CIMAGE_PREVIEW_METADATA_DESC.value,
CLASSES.CIMAGE_SAVE_METADATA_NAME.value: CLASSES.CIMAGE_SAVE_METADATA_DESC.value,
CLASSES.CMETADATA_EXTRACTOR_NAME.value: CLASSES.CMETADATA_EXTRACTOR_DESC.value,
CLASSES.CMETADATA_COMPARATOR_NAME.value: CLASSES.CMETADATA_COMPARATOR_DESC.value,
CLASSES.CUTILS_JSON_COMPARATOR_NAME.value: CLASSES.CUTILS_JSON_COMPARATOR_DESC.value,
CLASSES.CUTILS_STAT_SYSTEM_NAME.value: CLASSES.CUTILS_STAT_SYSTEM_DESC.value,
CLASSES.CJSONFILE_NAME.value: CLASSES.CJSONFILE_DESC.value,
CLASSES.CJSONEXTRACTOR_NAME.value: CLASSES.CJSONEXTRACTOR_DESC.value,
}
WEB_DIRECTORY = "./web"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]123456from .logger import *
from .keys import *
from .types import *
from .config import *
from .common import *
from .version import *.disabled/comfyui-kjnodes@nightly/__pycache__/__init__.cpython-310.pycAdded
.disabled/comfyui-kjnodes@nightly/kjweb_async/marked.min.jsAdded+6
.disabled/comfyui-kjnodes@nightly/kjweb_async/purify.min.jsAdded+3
.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/model_optimization_nodes.cpython-310.pycAdded
.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/nodes.cpython-310.pycAdded
.disabled/comfyui-kjnodes@nightly/nodes/__pycache__/sharpen_nodes.cpython-310.pycAdded
.disabled/comfyui-kjnodes@nightly/nodes/nodes.pyAdded
.disabled/comfyui-kjnodes@nightly/nodes/sharpen_nodes.pyAdded+259
.disabled/comfyui-kjnodes@nightly/utility/__pycache__/utility.cpython-310.pycAdded
.disabled/comfyui-kjnodes@nightly/utility/fluid.pyAdded+67
.disabled/comfyui-kjnodes@nightly/utility/magictex.pyAdded+95
.disabled/comfyui-kjnodes@nightly/utility/numerical.pyAdded+25
.disabled/comfyui-kjnodes@nightly/utility/utility.pyAdded+88
.disabled/comfyui-kjnodes@nightly/web/js/appearance.jsAdded+23
.disabled/comfyui-kjnodes@nightly/web/js/canvas_background.jsAdded+476
.disabled/comfyui-kjnodes@nightly/web/js/contextmenu.jsAdded+256
.disabled/comfyui-kjnodes@nightly/web/js/editors/editor_base.jsAdded+707
.disabled/comfyui-kjnodes@nightly/web/js/editors/interpolation.jsAdded+211
.disabled/comfyui-kjnodes@nightly/web/js/editors/point_editor_canvas.jsAdded+370
.disabled/comfyui-kjnodes@nightly/web/js/editors/spline_editor_canvas.jsAdded+708
.disabled/comfyui-kjnodes@nightly/web/js/fast_preview.jsAdded+31
.disabled/comfyui-kjnodes@nightly/web/js/fillconnect.jsAdded+218
.disabled/comfyui-kjnodes@nightly/web/js/help_popup.jsAdded+468
.disabled/comfyui-kjnodes@nightly/web/js/jsnodes.jsAdded+402
.disabled/comfyui-kjnodes@nightly/web/js/nodeswap.jsAdded+404
.disabled/comfyui-kjnodes@nightly/web/js/performance.jsAdded+286
.disabled/comfyui-kjnodes@nightly/web/js/play_sound.jsAdded+94
.disabled/comfyui-kjnodes@nightly/web/js/screencap_stream.jsAdded+500
.disabled/comfyui-kjnodes@nightly/web/js/setgetnodes.jsAdded+1544
.disabled/comfyui-kjnodes@nightly/web/js/utility.jsAdded+230
ComfyUI-Crystools/.editorconfigAdded+20
ComfyUI-Crystools/.eslintrc.cjsAdded+164
ComfyUI-Crystools/.github/ISSUE_TEMPLATE/bug_report.mdAdded+47
ComfyUI-Crystools/.github/ISSUE_TEMPLATE/feature_request.mdAdded+20
ComfyUI-Crystools/.github/workflows/publish.ymlAdded+24
ComfyUI-Crystools/.gitignoreAdded+156
ComfyUI-Crystools/.others/ComfyUI.run.xmlAdded+25
ComfyUI-Crystools/.others/lint.run.xmlAdded+12
ComfyUI-Crystools/.others/pre-commitAdded+33
ComfyUI-Crystools/.others/typescript.run.xmlAdded+12
ComfyUI-Crystools/.others/version.pyAdded+60
ComfyUI-Crystools/LICENSEAdded+21
ComfyUI-Crystools/README.mdAdded+672
ComfyUI-Crystools/__init__.pyAdded+108
ComfyUI-Crystools/core/__init__.pyAdded+6
ComfyUI-Crystools/core/__pycache__/__init__.cpython-310.pycAdded
ComfyUI-Crystools/core/__pycache__/common.cpython-310.pycAdded
ComfyUI-Crystools/core/__pycache__/config.cpython-310.pycAdded
ComfyUI-Crystools/core/__pycache__/keys.cpython-310.pycAdded
ComfyUI-Crystools/core/__pycache__/logger.cpython-310.pycAdded