FizzleDorf

widgets.js

Mar 26th, 2023
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.30 KB | None | 0 0
  1. import { ComfyWidgets, addSeedControlWidget } from "/scripts/widgets.js";
  2. import { app } from "/scripts/app.js";
  3.  
  4. const CONVERTED_TYPE = "converted-widget";
  5. const VALID_TYPES = ["STRING", "combo", "number", "select"];
  6.  
  7. function isConvertableWidget(widget, config) {
  8. return VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0]);
  9. }
  10.  
  11. function hideWidget(node, widget, suffix = "") {
  12. widget.origType = widget.type;
  13. widget.origComputeSize = widget.computeSize;
  14. widget.origSerializeValue = widget.serializeValue;
  15. widget.computeSize = () => [0, -4]; // -4 is due to the gap litegraph adds between widgets automatically
  16. widget.type = CONVERTED_TYPE + suffix;
  17. widget.serializeValue = () => {
  18. // Prevent serializing the widget if we have no input linked
  19. const { link } = node.inputs.find((i) => i.widget?.name === widget.name);
  20. if (link == null) {
  21. return undefined;
  22. }
  23. return widget.value;
  24. };
  25.  
  26. // Hide any linked widgets, e.g. seed+seedControl
  27. if (widget.linkedWidgets) {
  28. for (const w of widget.linkedWidgets) {
  29. hideWidget(node, w, ":" + widget.name);
  30. }
  31. }
  32. }
  33.  
  34. function showWidget(widget) {
  35. widget.type = widget.origType;
  36. widget.computeSize = widget.origComputeSize;
  37. widget.serializeValue = widget.origSerializeValue;
  38.  
  39. delete widget.origType;
  40. delete widget.origComputeSize;
  41. delete widget.origSerializeValue;
  42.  
  43. // Hide any linked widgets, e.g. seed+seedControl
  44. if (widget.linkedWidgets) {
  45. for (const w of widget.linkedWidgets) {
  46. showWidget(w);
  47. }
  48. }
  49. }
  50.  
  51. function convertToInput(node, widget, config) {
  52. hideWidget(node, widget);
  53.  
  54. const { linkType } = getWidgetType(config);
  55.  
  56. // Add input and store widget config for creating on primitive node
  57. const sz = node.size;
  58. node.addInput(widget.name, linkType, {
  59. widget: { name: widget.name, config },
  60. });
  61.  
  62. // Restore original size but grow if needed
  63. node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]);
  64. }
  65.  
  66. function convertToWidget(node, widget) {
  67. showWidget(widget);
  68. const sz = node.size;
  69. node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name));
  70.  
  71. // Restore original size but grow if needed
  72. node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]);
  73. }
  74.  
  75. function getWidgetType(config) {
  76. // Special handling for COMBO so we restrict links based on the entries
  77. let type = config[0];
  78. let linkType = type;
  79. if (type instanceof Array) {
  80. type = "COMBO";
  81. linkType = linkType.join(",");
  82. }
  83. return { type, linkType };
  84. }
  85.  
  86. app.registerExtension({
  87. name: "Comfy.WidgetInputs",
  88. async beforeRegisterNodeDef(nodeType, nodeData, app) {
  89. // Add menu options to conver to/from widgets
  90. const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
  91. nodeType.prototype.getExtraMenuOptions = function (_, options) {
  92. const r = origGetExtraMenuOptions ? origGetExtraMenuOptions.apply(this, arguments) : undefined;
  93.  
  94. if (this.widgets) {
  95. let toInput = [];
  96. let toWidget = [];
  97. for (const w of this.widgets) {
  98. if (w.type === CONVERTED_TYPE) {
  99. toWidget.push({
  100. content: `Convert ${w.name} to widget`,
  101. callback: () => convertToWidget(this, w),
  102. });
  103. } else {
  104. const config = nodeData?.input?.required[w.name] || [w.type, w.options || {}];
  105. if (isConvertableWidget(w, config)) {
  106. toInput.push({
  107. content: `Convert ${w.name} to input`,
  108. callback: () => convertToInput(this, w, config),
  109. });
  110. }
  111. }
  112. }
  113. if (toInput.length) {
  114. options.push(...toInput, null);
  115. }
  116.  
  117. if (toWidget.length) {
  118. options.push(...toWidget, null);
  119. }
  120. }
  121.  
  122. return r;
  123. };
  124.  
  125. // On initial configure of nodes hide all converted widgets
  126. const origOnConfigure = nodeType.prototype.onConfigure;
  127. nodeType.prototype.onConfigure = function () {
  128. const r = origOnConfigure ? origOnConfigure.apply(this, arguments) : undefined;
  129.  
  130. if (this.inputs) {
  131. for (const input of this.inputs) {
  132. if (input.widget) {
  133. const w = this.widgets.find((w) => w.name === input.widget.name);
  134. if (w) {
  135. hideWidget(this, w);
  136. } else {
  137. convertToWidget(this, input)
  138. }
  139. }
  140. }
  141. }
  142.  
  143. return r;
  144. };
  145.  
  146. function isNodeAtPos(pos) {
  147. for (const n of app.graph._nodes) {
  148. if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) {
  149. return true;
  150. }
  151. }
  152. return false;
  153. }
  154.  
  155. // Double click a widget input to automatically attach a primitive
  156. const origOnInputDblClick = nodeType.prototype.onInputDblClick;
  157. const ignoreDblClick = Symbol();
  158. nodeType.prototype.onInputDblClick = function (slot) {
  159. const r = origOnInputDblClick ? origOnInputDblClick.apply(this, arguments) : undefined;
  160.  
  161. const input = this.inputs[slot];
  162. if (input.widget && !input[ignoreDblClick]) {
  163. const node = LiteGraph.createNode("PrimitiveNode");
  164. app.graph.add(node);
  165.  
  166. // Calculate a position that wont directly overlap another node
  167. const pos = [this.pos[0] - node.size[0] - 30, this.pos[1]];
  168. while (isNodeAtPos(pos)) {
  169. pos[1] += LiteGraph.NODE_TITLE_HEIGHT;
  170. }
  171.  
  172. node.pos = pos;
  173. node.connect(0, this, slot);
  174. node.title = input.name;
  175.  
  176. // Prevent adding duplicates due to triple clicking
  177. input[ignoreDblClick] = true;
  178. setTimeout(() => {
  179. delete input[ignoreDblClick];
  180. }, 300);
  181. }
  182.  
  183. return r;
  184. };
  185. },
  186. registerCustomNodes() {
  187. class PrimitiveNode {
  188. constructor() {
  189. this.addOutput("connect to widget input", "*");
  190. this.serialize_widgets = true;
  191. this.isVirtualNode = true;
  192. }
  193.  
  194. applyToGraph() {
  195. if (!this.outputs[0].links?.length) return;
  196.  
  197. // For each output link copy our value over the original widget value
  198. for (const l of this.outputs[0].links) {
  199. const linkInfo = app.graph.links[l];
  200. const node = this.graph.getNodeById(linkInfo.target_id);
  201. const input = node.inputs[linkInfo.target_slot];
  202. const widgetName = input.widget.name;
  203. if (widgetName) {
  204. const widget = node.widgets.find((w) => w.name === widgetName);
  205. if (widget) {
  206. widget.value = this.widgets[0].value;
  207. if (widget.callback) {
  208. widget.callback(widget.value, app.canvas, node, app.canvas.graph_mouse, {});
  209. }
  210. }
  211. }
  212. }
  213. }
  214.  
  215. onConnectionsChange(_, index, connected) {
  216. if (connected) {
  217. if (this.outputs[0].links?.length) {
  218. if (!this.widgets?.length) {
  219. this.#onFirstConnection();
  220. }
  221. if (!this.widgets?.length && this.outputs[0].widget) {
  222. // On first load it often cant recreate the widget as the other node doesnt exist yet
  223. // Manually recreate it from the output info
  224. this.#createWidget(this.outputs[0].widget.config);
  225. }
  226. }
  227. } else if (!this.outputs[0].links?.length) {
  228. this.#onLastDisconnect();
  229. }
  230. }
  231.  
  232. onConnectOutput(slot, type, input, target_node, target_slot) {
  233. // Fires before the link is made allowing us to reject it if it isn't valid
  234.  
  235. // No widget, we cant connect
  236. if (!input.widget) return false;
  237.  
  238. if (this.outputs[slot].links?.length) {
  239. return this.#isValidConnection(input);
  240. }
  241. }
  242.  
  243. #onFirstConnection() {
  244. // First connection can fire before the graph is ready on initial load so random things can be missing
  245. const linkId = this.outputs[0].links[0];
  246. const link = this.graph.links[linkId];
  247. if (!link) return;
  248.  
  249. const theirNode = this.graph.getNodeById(link.target_id);
  250. if (!theirNode || !theirNode.inputs) return;
  251.  
  252. const input = theirNode.inputs[link.target_slot];
  253. if (!input) return;
  254.  
  255. const widget = input.widget;
  256. const { type, linkType } = getWidgetType(widget.config);
  257.  
  258. // Update our output to restrict to the widget type
  259. this.outputs[0].type = linkType;
  260. this.outputs[0].name = type;
  261. this.outputs[0].widget = widget;
  262.  
  263. this.#createWidget(widget.config, theirNode, widget.name);
  264. }
  265.  
  266. #createWidget(inputData, node, widgetName) {
  267. let type = inputData[0];
  268.  
  269. if (type instanceof Array) {
  270. type = "COMBO";
  271. }
  272.  
  273. let widget;
  274. if (type in ComfyWidgets) {
  275. widget = (ComfyWidgets[type](this, "value", inputData, app) || {}).widget;
  276. } else {
  277. widget = this.addWidget(type, "value", null, () => {}, {});
  278. }
  279.  
  280. if (node?.widgets && widget) {
  281. const theirWidget = node.widgets.find((w) => w.name === widgetName);
  282. if (theirWidget) {
  283. widget.value = theirWidget.value;
  284. }
  285. }
  286.  
  287. if (widget.type === "number") {
  288. addSeedControlWidget(this, widget, "fixedSeed");
  289. }
  290.  
  291. // When our value changes, update other widgets to reflect our changes
  292. // e.g. so LoadImage shows correct image
  293. const callback = widget.callback;
  294. const self = this;
  295. widget.callback = function () {
  296. const r = callback ? callback.apply(this, arguments) : undefined;
  297. self.applyToGraph();
  298. return r;
  299. };
  300.  
  301. // Grow our node if required
  302. const sz = this.computeSize();
  303. if (this.size[0] < sz[0]) {
  304. this.size[0] = sz[0];
  305. }
  306. if (this.size[1] < sz[1]) {
  307. this.size[1] = sz[1];
  308. }
  309.  
  310. requestAnimationFrame(() => {
  311. if (this.onResize) {
  312. this.onResize(this.size);
  313. }
  314. });
  315. }
  316.  
  317. #isValidConnection(input) {
  318. // Only allow connections where the configs match
  319. const config1 = this.outputs[0].widget.config;
  320. const config2 = input.widget.config;
  321.  
  322. if (config1[0] !== config2[0]) return false;
  323.  
  324. for (const k in config1[1]) {
  325. if (k !== "default") {
  326. if (config1[1][k] !== config2[1][k]) {
  327. return false;
  328. }
  329. }
  330. }
  331.  
  332. return true;
  333. }
  334.  
  335. #onLastDisconnect() {
  336. // We cant remove + re-add the output here as if you drag a link over the same link
  337. // it removes, then re-adds, causing it to break
  338. this.outputs[0].type = "*";
  339. this.outputs[0].name = "connect to widget input";
  340. delete this.outputs[0].widget;
  341.  
  342. if (this.widgets) {
  343. // Allow widgets to cleanup
  344. for (const w of this.widgets) {
  345. if (w.onRemove) {
  346. w.onRemove();
  347. }
  348. }
  349. this.widgets.length = 0;
  350. }
  351. }
  352. }
  353.  
  354. LiteGraph.registerNodeType(
  355. "PrimitiveNode",
  356. Object.assign(PrimitiveNode, {
  357. title: "Primitive",
  358. })
  359. );
  360. PrimitiveNode.category = "utils";
  361. },
  362. });
  363.  
Advertisement
Add Comment
Please, Sign In to add comment