mirror of
https://git.datalinker.icu/comfyanonymous/ComfyUI
synced 2026-11-20 23:07:04 +08:00
temp
This commit is contained in:
parent
19c3eb8f57
commit
60ad4f9abc
@ -142,6 +142,7 @@ export class GroupNodeConfig {
|
||||
this.inputCount = 0;
|
||||
this.oldToNewOutputMap = {};
|
||||
this.newToOldOutputMap = {};
|
||||
this.newToOldInputMap = {};
|
||||
this.oldToNewInputMap = {};
|
||||
this.oldToNewWidgetMap = {};
|
||||
this.newToOldWidgetMap = {};
|
||||
@ -438,6 +439,8 @@ export class GroupNodeConfig {
|
||||
|
||||
this.nodeDef.input.required[name] = config;
|
||||
inputMap[i] = this.inputCount++;
|
||||
|
||||
this.newToOldInputMap[name] = [node.index, inputName];
|
||||
}
|
||||
}
|
||||
|
||||
@ -647,44 +650,41 @@ export class GroupNodeHandler {
|
||||
};
|
||||
|
||||
this.node.updateLink = (link) => {
|
||||
// Replace the group node reference with the internal node
|
||||
link = { ...link };
|
||||
const output = this.groupData.newToOldOutputMap[link.origin_slot];
|
||||
let innerNode = this.innerNodes[output.node.index];
|
||||
let l;
|
||||
while (innerNode?.type === "Reroute") {
|
||||
l = innerNode.getInputLink(0);
|
||||
innerNode = innerNode.getInputNode(0);
|
||||
}
|
||||
|
||||
if (!innerNode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (l && GroupNodeHandler.isGroupNode(innerNode)) {
|
||||
return innerNode.updateLink(l);
|
||||
}
|
||||
|
||||
link.origin_id = innerNode.id;
|
||||
link.origin_slot = l?.origin_slot ?? output.slot;
|
||||
return link;
|
||||
// // Replace the group node reference with the internal node
|
||||
// link = { ...link };
|
||||
// const output = this.groupData.newToOldOutputMap[link.origin_slot];
|
||||
// let innerNode = this.innerNodes[output.node.index];
|
||||
// let l;
|
||||
// while (innerNode?.type === "Reroute") {
|
||||
// l = innerNode.getInputLink(0);
|
||||
// innerNode = innerNode.getInputNode(0);
|
||||
// }
|
||||
// if (!innerNode) {
|
||||
// return null;
|
||||
// }
|
||||
// if (l && GroupNodeHandler.isGroupNode(innerNode)) {
|
||||
// return innerNode.updateLink(l);
|
||||
// }
|
||||
// link.origin_id = innerNode.id;
|
||||
// link.origin_slot = l?.origin_slot ?? output.slot;
|
||||
// return link;
|
||||
};
|
||||
|
||||
this.node.getInnerNodes = () => {
|
||||
if (!this.innerNodes) {
|
||||
this.node.setInnerNodes(
|
||||
this.groupData.nodeData.nodes.map((n, i) => {
|
||||
const innerNode = LiteGraph.createNode(n.type);
|
||||
innerNode.configure(n);
|
||||
innerNode.id = `${this.node.id}:${i}`;
|
||||
return innerNode;
|
||||
})
|
||||
);
|
||||
}
|
||||
// if (!this.innerNodes) {
|
||||
// this.node.setInnerNodes(
|
||||
// this.groupData.nodeData.nodes.map((n, i) => {
|
||||
// const innerNode = LiteGraph.createNode(n.type);
|
||||
// innerNode.configure(n);
|
||||
// innerNode.id = `${this.node.id}:${i}`;
|
||||
// return innerNode;
|
||||
// })
|
||||
// );
|
||||
// }
|
||||
|
||||
this.updateInnerWidgets();
|
||||
// this.updateInnerWidgets();
|
||||
|
||||
return this.innerNodes;
|
||||
return [this.node];
|
||||
};
|
||||
|
||||
this.node.recreate = async () => {
|
||||
@ -884,7 +884,7 @@ export class GroupNodeHandler {
|
||||
const r = onDrawForeground?.apply?.(this, arguments);
|
||||
if (+app.runningNodeId === this.id && this.runningInternalNodeId !== null) {
|
||||
const n = groupData.nodes[this.runningInternalNodeId];
|
||||
if(!n) return;
|
||||
if (!n) return;
|
||||
const message = `Running ${n.title || n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`;
|
||||
ctx.save();
|
||||
ctx.font = "12px sans-serif";
|
||||
@ -1252,6 +1252,66 @@ const ext = {
|
||||
name: id,
|
||||
setup() {
|
||||
addConvertToGroupOptions();
|
||||
|
||||
const graphToPrompt = app.graphToPrompt;
|
||||
app.graphToPrompt = async function () {
|
||||
const graph = arguments[0] ?? app.graph;
|
||||
const prompt = await graphToPrompt.apply(this, [graph, false]);
|
||||
|
||||
for (const nodeId in prompt.output) {
|
||||
const node = graph.getNodeById(nodeId);
|
||||
if (GroupNodeHandler.isGroupNode(node)) {
|
||||
const groupData = GroupNodeHandler.getGroupData(node);
|
||||
const innerGraph = new LGraph();
|
||||
const canvas = new LGraphCanvas(null, innerGraph, { skip_events: true, skip_render: true });
|
||||
|
||||
const old = localStorage.getItem("litegrapheditor_clipboard");
|
||||
localStorage.setItem("litegrapheditor_clipboard", JSON.stringify(groupData.nodeData));
|
||||
canvas.pasteFromClipboard();
|
||||
localStorage.setItem("litegrapheditor_clipboard", old);
|
||||
|
||||
// Add internal nodes to output
|
||||
const innerPrompt = await app.graphToPrompt(innerGraph, false);
|
||||
for (const innerNodeId in innerPrompt.output) {
|
||||
const p = (prompt.output[`${nodeId}:${innerNodeId}`] = innerPrompt.output[innerNodeId]);
|
||||
if (!p.inputs) continue;
|
||||
for (const inputId in p.inputs) {
|
||||
const input = p.inputs[inputId];
|
||||
if (input instanceof Array) {
|
||||
// Rewrite IDs
|
||||
p.inputs[inputId][0] = `${nodeId}:${input[0]}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const inputId in prompt.output[nodeId].inputs ?? {}) {
|
||||
const input = prompt.output[nodeId].inputs[inputId];
|
||||
if (!(input instanceof Array)) continue;
|
||||
const mapping = groupData.newToOldInputMap[inputId];
|
||||
const toSlot = groupData.nodeData.nodes[mapping[0]].inputs.findIndex((inp) => inp.name === mapping[1]);
|
||||
debugger;
|
||||
const toNode = `${nodeId}:${mapping[0]}`;
|
||||
prompt.output[toNode].inputs ??= {};
|
||||
prompt.output[toNode].inputs[toSlot] = input;
|
||||
}
|
||||
|
||||
for (let i = 0; i < node.outputs?.length; i++) {
|
||||
const output = node.outputs[i];
|
||||
if (!output.links) continue;
|
||||
for (const linkId of output.links) {
|
||||
const link = graph.links[linkId];
|
||||
const targetNode = graph.getNodeById(link.target_id);
|
||||
const input = (prompt.output[link.target_id].inputs ??= {});
|
||||
const mapping = groupData.newToOldOutputMap[i];
|
||||
input[targetNode.inputs[link.target_slot].name] = [`${nodeId}:${mapping.node.index + 1}`, mapping.slot];
|
||||
}
|
||||
}
|
||||
delete prompt.output[nodeId];
|
||||
}
|
||||
}
|
||||
|
||||
return prompt;
|
||||
};
|
||||
},
|
||||
async beforeConfigureGraph(graphData, missingNodeTypes) {
|
||||
const nodes = graphData?.extra?.groupNodes;
|
||||
@ -1275,7 +1335,7 @@ const ext = {
|
||||
if (nodes) {
|
||||
await GroupNodeConfig.registerFromWorkflow(nodes, {});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
app.registerExtension(ext);
|
||||
|
||||
@ -1,177 +0,0 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js"
|
||||
|
||||
const MAX_HISTORY = 50;
|
||||
|
||||
let undo = [];
|
||||
let redo = [];
|
||||
let activeState = null;
|
||||
let isOurLoad = false;
|
||||
function checkState() {
|
||||
const currentState = app.graph.serialize();
|
||||
if (!graphEqual(activeState, currentState)) {
|
||||
undo.push(activeState);
|
||||
if (undo.length > MAX_HISTORY) {
|
||||
undo.shift();
|
||||
}
|
||||
activeState = clone(currentState);
|
||||
redo.length = 0;
|
||||
api.dispatchEvent(new CustomEvent("graphChanged", { detail: activeState }));
|
||||
}
|
||||
}
|
||||
|
||||
const loadGraphData = app.loadGraphData;
|
||||
app.loadGraphData = async function () {
|
||||
const v = await loadGraphData.apply(this, arguments);
|
||||
if (isOurLoad) {
|
||||
isOurLoad = false;
|
||||
} else {
|
||||
checkState();
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
function clone(obj) {
|
||||
try {
|
||||
if (typeof structuredClone !== "undefined") {
|
||||
return structuredClone(obj);
|
||||
}
|
||||
} catch (error) {
|
||||
// structuredClone is stricter than using JSON.parse/stringify so fallback to that
|
||||
}
|
||||
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
|
||||
function graphEqual(a, b, root = true) {
|
||||
if (a === b) return true;
|
||||
|
||||
if (typeof a == "object" && a && typeof b == "object" && b) {
|
||||
const keys = Object.getOwnPropertyNames(a);
|
||||
|
||||
if (keys.length != Object.getOwnPropertyNames(b).length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const key of keys) {
|
||||
let av = a[key];
|
||||
let bv = b[key];
|
||||
if (root && key === "nodes") {
|
||||
// Nodes need to be sorted as the order changes when selecting nodes
|
||||
av = [...av].sort((a, b) => a.id - b.id);
|
||||
bv = [...bv].sort((a, b) => a.id - b.id);
|
||||
}
|
||||
if (!graphEqual(av, bv, false)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const undoRedo = async (e) => {
|
||||
const updateState = async (source, target) => {
|
||||
const prevState = source.pop();
|
||||
if (prevState) {
|
||||
target.push(activeState);
|
||||
isOurLoad = true;
|
||||
await app.loadGraphData(prevState, false);
|
||||
activeState = prevState;
|
||||
}
|
||||
}
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
if (e.key === "y") {
|
||||
updateState(redo, undo);
|
||||
return true;
|
||||
} else if (e.key === "z") {
|
||||
updateState(undo, redo);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const bindInput = (activeEl) => {
|
||||
if (activeEl && activeEl.tagName !== "CANVAS" && activeEl.tagName !== "BODY") {
|
||||
for (const evt of ["change", "input", "blur"]) {
|
||||
if (`on${evt}` in activeEl) {
|
||||
const listener = () => {
|
||||
checkState();
|
||||
activeEl.removeEventListener(evt, listener);
|
||||
};
|
||||
activeEl.addEventListener(evt, listener);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let keyIgnored = false;
|
||||
window.addEventListener(
|
||||
"keydown",
|
||||
(e) => {
|
||||
requestAnimationFrame(async () => {
|
||||
let activeEl;
|
||||
// If we are auto queue in change mode then we do want to trigger on inputs
|
||||
if (!app.ui.autoQueueEnabled || app.ui.autoQueueMode === "instant") {
|
||||
activeEl = document.activeElement;
|
||||
if (activeEl?.tagName === "INPUT" || activeEl?.type === "textarea") {
|
||||
// Ignore events on inputs, they have their native history
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
keyIgnored = e.key === "Control" || e.key === "Shift" || e.key === "Alt" || e.key === "Meta";
|
||||
if (keyIgnored) return;
|
||||
|
||||
// Check if this is a ctrl+z ctrl+y
|
||||
if (await undoRedo(e)) return;
|
||||
|
||||
// If our active element is some type of input then handle changes after they're done
|
||||
if (bindInput(activeEl)) return;
|
||||
checkState();
|
||||
});
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
window.addEventListener("keyup", (e) => {
|
||||
if (keyIgnored) {
|
||||
keyIgnored = false;
|
||||
checkState();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle clicking DOM elements (e.g. widgets)
|
||||
window.addEventListener("mouseup", () => {
|
||||
checkState();
|
||||
});
|
||||
|
||||
// Handle prompt queue event for dynamic widget changes
|
||||
api.addEventListener("promptQueued", () => {
|
||||
checkState();
|
||||
});
|
||||
|
||||
// Handle litegraph clicks
|
||||
const processMouseUp = LGraphCanvas.prototype.processMouseUp;
|
||||
LGraphCanvas.prototype.processMouseUp = function (e) {
|
||||
const v = processMouseUp.apply(this, arguments);
|
||||
checkState();
|
||||
return v;
|
||||
};
|
||||
const processMouseDown = LGraphCanvas.prototype.processMouseDown;
|
||||
LGraphCanvas.prototype.processMouseDown = function (e) {
|
||||
const v = processMouseDown.apply(this, arguments);
|
||||
checkState();
|
||||
return v;
|
||||
};
|
||||
|
||||
// Handle litegraph context menu for COMBO widgets
|
||||
const close = LiteGraph.ContextMenu.prototype.close;
|
||||
LiteGraph.ContextMenu.prototype.close = function(e) {
|
||||
const v = close.apply(this, arguments);
|
||||
checkState();
|
||||
return v;
|
||||
}
|
||||
@ -407,7 +407,7 @@ class ComfyApi extends EventTarget {
|
||||
* @param { RequestInit & { overwrite?: boolean, stringify?: boolean, throwOnError?: boolean } } [options]
|
||||
* @returns { Promise<Response> }
|
||||
*/
|
||||
async storeUserData(file, data, options = { overwrite: false, stringify: true, throwOnError: true }) {
|
||||
async storeUserData(file, data, options = { overwrite: true, stringify: true, throwOnError: true }) {
|
||||
const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}?overwrite=${options?.overwrite}`, {
|
||||
method: "POST",
|
||||
body: options?.stringify ? JSON.stringify(data) : data,
|
||||
|
||||
@ -8,6 +8,7 @@ import { addDomClippingSetting } from "./domWidget.js";
|
||||
import { createImageHost, calculateImageGrid } from "./ui/imagePreview.js";
|
||||
import { ComfyAppMenu } from "./ui/menu/index.js";
|
||||
import { getStorageValue, setStorageValue } from "./utils.js";
|
||||
import { ComfyWorkflow } from "./workflows.js";
|
||||
export const ANIM_PREVIEW_WIDGET = "$$comfy_animation_preview";
|
||||
|
||||
function sanitizeNodeName(string) {
|
||||
@ -41,30 +42,6 @@ export class ComfyApp {
|
||||
*/
|
||||
#processingQueue = false;
|
||||
|
||||
/** The name of the current workflow
|
||||
* @type { string | null }
|
||||
*/
|
||||
#currentWorkflow = null;
|
||||
|
||||
/**
|
||||
* Content Clipboard
|
||||
* @type {serialized node object}
|
||||
*/
|
||||
static clipspace = null;
|
||||
static clipspace_invalidate_handler = null;
|
||||
static open_maskeditor = null;
|
||||
static clipspace_return_node = null;
|
||||
|
||||
get currentWorkflow() {
|
||||
return this.#currentWorkflow;
|
||||
}
|
||||
|
||||
set currentWorkflow(value) {
|
||||
this.#currentWorkflow = value ?? null;
|
||||
api.dispatchEvent(new CustomEvent("workflowChanged", { detail: value ?? null }));
|
||||
setStorageValue("Comfy.LastWorkflow", value ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Content Clipboard
|
||||
* @type {serialized node object}
|
||||
@ -77,6 +54,7 @@ export class ComfyApp {
|
||||
constructor() {
|
||||
this.ui = new ComfyUI(this);
|
||||
this.logging = new ComfyLogging(this);
|
||||
ComfyWorkflow.init(this);
|
||||
new ComfyAppMenu(this);
|
||||
|
||||
/**
|
||||
@ -1755,9 +1733,9 @@ export class ComfyApp {
|
||||
* Populates the graph with the specified workflow data
|
||||
* @param {*} graphData A serialized graph object
|
||||
* @param { boolean } clean If the graph state, e.g. images, should be cleared
|
||||
* @param { string } name The name of the workflow
|
||||
* @param { import("./workflows.js").ComfyWorkflow | string | null } name The workflow
|
||||
*/
|
||||
async loadGraphData(graphData, clean = true, name = null) {
|
||||
async loadGraphData(graphData, clean = true, workflow = null) {
|
||||
if (clean !== false) {
|
||||
this.clean();
|
||||
}
|
||||
@ -1776,7 +1754,11 @@ export class ComfyApp {
|
||||
graphData = structuredClone(graphData);
|
||||
}
|
||||
|
||||
this.currentWorkflow = name;
|
||||
if (workflow) {
|
||||
ComfyWorkflow.changeWorkflow(workflow);
|
||||
} else {
|
||||
ComfyWorkflow.newWorkflow();
|
||||
}
|
||||
|
||||
const missingNodeTypes = [];
|
||||
await this.#invokeExtensionsAsync("beforeConfigureGraph", graphData, missingNodeTypes);
|
||||
@ -1888,8 +1870,8 @@ export class ComfyApp {
|
||||
* Converts the current graph workflow for sending to the API
|
||||
* @returns The workflow and node links
|
||||
*/
|
||||
async graphToPrompt() {
|
||||
for (const outerNode of this.graph.computeExecutionOrder(false)) {
|
||||
async graphToPrompt(graph = this.graph, clean = true) {
|
||||
for (const outerNode of graph.computeExecutionOrder(false)) {
|
||||
if (outerNode.widgets) {
|
||||
for (const widget of outerNode.widgets) {
|
||||
// Allow widgets to run callbacks before a prompt has been queued
|
||||
@ -1909,10 +1891,10 @@ export class ComfyApp {
|
||||
}
|
||||
}
|
||||
|
||||
const workflow = this.graph.serialize();
|
||||
const workflow = graph.serialize();
|
||||
const output = {};
|
||||
// Process nodes in order of execution
|
||||
for (const outerNode of this.graph.computeExecutionOrder(false)) {
|
||||
for (const outerNode of graph.computeExecutionOrder(false)) {
|
||||
const skipNode = outerNode.mode === 2 || outerNode.mode === 4;
|
||||
const innerNodes = (!skipNode && outerNode.getInnerNodes) ? outerNode.getInnerNodes() : [outerNode];
|
||||
for (const node of innerNodes) {
|
||||
@ -2004,13 +1986,14 @@ export class ComfyApp {
|
||||
}
|
||||
|
||||
// Remove inputs connected to removed nodes
|
||||
|
||||
for (const o in output) {
|
||||
for (const i in output[o].inputs) {
|
||||
if (Array.isArray(output[o].inputs[i])
|
||||
&& output[o].inputs[i].length === 2
|
||||
&& !output[output[o].inputs[i][0]]) {
|
||||
delete output[o].inputs[i];
|
||||
if(clean) {
|
||||
for (const o in output) {
|
||||
for (const i in output[o].inputs) {
|
||||
if (Array.isArray(output[o].inputs[i])
|
||||
&& output[o].inputs[i].length === 2
|
||||
&& !output[output[o].inputs[i][0]]) {
|
||||
delete output[o].inputs[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -299,7 +299,7 @@
|
||||
direction: rtl;
|
||||
flex: auto;
|
||||
position: relative;
|
||||
width: 120px;
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.comfyui-workflows-button.unsaved .comfyui-workflows-label {
|
||||
@ -353,9 +353,10 @@
|
||||
color: var(--primary-fg);
|
||||
}
|
||||
|
||||
.comfyui-workflows-favorites {
|
||||
.comfyui-workflows-favorites, .comfyui-workflows-open {
|
||||
border-bottom: 1px solid var(--comfy-input-bg);
|
||||
padding-bottom: 5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.comfyui-workflows-favorites:empty {
|
||||
@ -364,7 +365,6 @@
|
||||
|
||||
.comfyui-workflows-tree {
|
||||
padding: 0;
|
||||
padding-top: 5px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
|
||||
8
web/scripts/ui/menu/v3.js
Normal file
8
web/scripts/ui/menu/v3.js
Normal file
@ -0,0 +1,8 @@
|
||||
class ComfyMenu extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.classList.add("test");
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("comfyui-menu", ComfyMenu);
|
||||
@ -6,6 +6,24 @@ import { $el } from "../../ui.js";
|
||||
import { api } from "../../api.js";
|
||||
import { ComfyPopup } from "../components/popup.js";
|
||||
import { createSpinner } from "../spinner.js";
|
||||
import { ComfyWorkflow } from "../../workflows.js";
|
||||
|
||||
function reactive(html) {
|
||||
|
||||
}
|
||||
|
||||
reactive(`
|
||||
<div>
|
||||
<header>
|
||||
<comfy-button icon="plus" text="New Workflow" onclick="newWorkflow" />
|
||||
</header>
|
||||
<section>
|
||||
<h3>Open Workflows</h3>
|
||||
<div $if="hasWorkflows">
|
||||
</section>
|
||||
</div>
|
||||
`)
|
||||
|
||||
|
||||
function trimJsonExt(name) {
|
||||
return name.replace(/\.json$/, "");
|
||||
@ -27,17 +45,18 @@ export class ComfyWorkflowsMenu {
|
||||
|
||||
let ignoreChange = false;
|
||||
let first = true;
|
||||
api.addEventListener("workflowChanged", ({ detail }) => {
|
||||
if (detail) {
|
||||
this.unsaved = first ? getStorageValue("Comfy.LastWorkflowUnsaved") === "true" : false;
|
||||
this.currentWorkflow = detail;
|
||||
} else {
|
||||
this.unsaved = true;
|
||||
this.currentWorkflow = "Unsaved workflow";
|
||||
}
|
||||
first = false;
|
||||
ignoreChange = true;
|
||||
setTimeout(() => (ignoreChange = false), 5);
|
||||
api.addEventListener("workflowsChanged", ({ detail }) => {
|
||||
this.currentWorkflow = ComfyWorkflow.activeWorkflow.displayName;
|
||||
console.log(detail);
|
||||
// if (detail) {
|
||||
// this.unsaved = first ? getStorageValue("Comfy.LastWorkflowUnsaved") === "true" : false;
|
||||
// } else {
|
||||
// this.unsaved = true;
|
||||
// }
|
||||
// first = false;
|
||||
// ignoreChange = true;
|
||||
// setTimeout(() => (ignoreChange = false), 5);
|
||||
// this.content.updateOpenElement();
|
||||
});
|
||||
|
||||
api.addEventListener("graphChanged", () => {
|
||||
@ -63,7 +82,8 @@ export class ComfyWorkflowsMenu {
|
||||
this.element.append(this.button.element);
|
||||
|
||||
this.popup = new ComfyPopup({ target: this.element, classList: "comfyui-workflows-popup" });
|
||||
this.popup.children = [new ComfyWorkflowsContent(app, this.popup).element];
|
||||
this.content = new ComfyWorkflowsContent(app, this.popup);
|
||||
this.popup.children = [this.content.element];
|
||||
this.popup.addEventListener("change", () => {
|
||||
this.button.icon = "chevron-" + (this.popup.open ? "up" : "down");
|
||||
});
|
||||
@ -108,7 +128,7 @@ export class ComfyWorkflowsMenu {
|
||||
const res = await api.storeUserData("workflows/" + filename, json, { stringify: false, throwOnError: false, overwrite });
|
||||
if (res.status === 409) {
|
||||
if (!confirm(`Workflow '${filename}' already exists, do you want to overwrite it?`)) return;
|
||||
await api.storeUserData("workflows/" + filename, json, { stringify: false, });
|
||||
await api.storeUserData("workflows/" + filename, json, { stringify: false });
|
||||
}
|
||||
|
||||
this.unsaved = false;
|
||||
@ -170,12 +190,43 @@ export class ComfyWorkflowsContent {
|
||||
async load() {
|
||||
const tree = await this.createTreeElement();
|
||||
this.updateFavoritesElement();
|
||||
this.element.replaceChildren(this.actions, this.favoritesElement, tree);
|
||||
this.updateOpenElement();
|
||||
this.element.replaceChildren(this.actions, this.openElement, this.favoritesElement, tree);
|
||||
}
|
||||
|
||||
updateOpenElement() {
|
||||
const current = this.openElement;
|
||||
|
||||
this.openElement = $el(
|
||||
"div.comfyui-workflows-open",
|
||||
[$el("h3", "Open Workflows"), ...ComfyWorkflow.openWorkflows.map((w) => {
|
||||
const res = new FileNode(
|
||||
this,
|
||||
w.displayName,
|
||||
w.displayName,
|
||||
"div",
|
||||
(f) => {
|
||||
// entry.isFavorite = f;
|
||||
// entry.updateFavorite();
|
||||
// this.updateFavoritesElement();
|
||||
},
|
||||
() => {
|
||||
// res.element.remove();
|
||||
// entry.remove();
|
||||
return false;
|
||||
}
|
||||
);
|
||||
return res.element;
|
||||
})]
|
||||
);
|
||||
|
||||
if (current) {
|
||||
current.replaceWith(this.openElement);
|
||||
}
|
||||
}
|
||||
|
||||
updateFavoritesElement() {
|
||||
const favorites = [...this.favorites.values()];
|
||||
|
||||
const current = this.favoritesElement;
|
||||
|
||||
this.favoritesElement = $el(
|
||||
|
||||
@ -26,6 +26,19 @@ function formatDate(text, date) {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function clone(obj) {
|
||||
try {
|
||||
if (typeof structuredClone !== "undefined") {
|
||||
return structuredClone(obj);
|
||||
}
|
||||
} catch (error) {
|
||||
// structuredClone is stricter than using JSON.parse/stringify so fallback to that
|
||||
}
|
||||
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
|
||||
export function applyTextReplacements(app, value) {
|
||||
return value.replace(/%([^%]+)%/g, function (match, text) {
|
||||
const split = text.split(".");
|
||||
@ -140,4 +153,155 @@ export function setStorageValue(id, value) {
|
||||
sessionStorage.setItem(`${id}:${clientId}`, value);
|
||||
}
|
||||
localStorage.setItem(id, value);
|
||||
}
|
||||
|
||||
export class tmpl {
|
||||
static #subs = Symbol();
|
||||
|
||||
constructor(template, components) {
|
||||
this.template = template;
|
||||
this.components = components;
|
||||
}
|
||||
|
||||
build = (context) => {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.innerHTML = this.template;
|
||||
|
||||
for (const el of wrapper.children) {
|
||||
this.#build(el, context);
|
||||
}
|
||||
|
||||
return wrapper.children;
|
||||
};
|
||||
|
||||
#build = (el, ctx) => {
|
||||
if (this.#loop(el, ctx)) return;
|
||||
|
||||
tmpl.#if(el, ctx);
|
||||
tmpl.#text(el, ctx);
|
||||
|
||||
for (const child of el.children) {
|
||||
this.#build(child, ctx);
|
||||
}
|
||||
};
|
||||
|
||||
#loop = (el, ctx) => {
|
||||
const attr = el.getAttribute(":each");
|
||||
if (attr) {
|
||||
const id = el.getAttribute(":tmpl");
|
||||
el.removeAttribute(":each");
|
||||
el.removeAttribute(":tmpl");
|
||||
|
||||
if (!id || !this.components[id]) {
|
||||
console.warn("Missing template: " + id, el);
|
||||
return false;
|
||||
}
|
||||
|
||||
tmpl.#bind(ctx[attr], (v) => {
|
||||
if (v == null) {
|
||||
v = [];
|
||||
} else if (!(v instanceof Array)) {
|
||||
if (typeof v === "object") {
|
||||
v = Object.entries(v);
|
||||
} else {
|
||||
v = [v];
|
||||
}
|
||||
}
|
||||
|
||||
const res = v.flatMap((item, index, array) => {
|
||||
const parent = el.cloneNode(true);
|
||||
const children = this.components[id]({ item, index, array }, ctx, this);
|
||||
parent.replaceChildren(...children);
|
||||
return parent;
|
||||
});
|
||||
el.replaceWith(...res);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
static rx(value, onChange, immediate = true) {
|
||||
let v = value;
|
||||
const subs = [];
|
||||
if (onChange) {
|
||||
subs.push(onChange);
|
||||
if (immediate) {
|
||||
onChange(v);
|
||||
}
|
||||
}
|
||||
return {
|
||||
get value() {
|
||||
return v;
|
||||
},
|
||||
set value(value) {
|
||||
let old = v;
|
||||
v = value;
|
||||
for (const sub of subs) {
|
||||
sub(v, old);
|
||||
}
|
||||
},
|
||||
[tmpl.#subs]: subs,
|
||||
};
|
||||
}
|
||||
|
||||
static watch(rx, cb) {
|
||||
const subs = rx[tmpl.#subs];
|
||||
if (!subs) throw new Error("Attempt to watch non-reactive object");
|
||||
subs.push(cb);
|
||||
return () => subs.splice(subs.indexOf(cb), 1);
|
||||
}
|
||||
|
||||
static #isReactive(value) {
|
||||
return !!value?.[tmpl.#subs];
|
||||
}
|
||||
|
||||
static #unwrap(value) {
|
||||
return tmpl.#isReactive(value) ? value.value : value;
|
||||
}
|
||||
|
||||
static #bind(value, check) {
|
||||
if (tmpl.#isReactive(value)) {
|
||||
tmpl.watch(value, check);
|
||||
value = tmpl.#unwrap(value);
|
||||
}
|
||||
check(value);
|
||||
}
|
||||
|
||||
static #if(el, ctx) {
|
||||
let visibilityAttr = el.getAttribute(":if");
|
||||
let negate = false;
|
||||
|
||||
if (visibilityAttr) {
|
||||
el.removeAttribute(":if");
|
||||
} else {
|
||||
visibilityAttr = el.getAttribute(":if!");
|
||||
if (visibilityAttr) {
|
||||
el.removeAttribute(":if!");
|
||||
negate = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (visibilityAttr) {
|
||||
el.removeAttribute(visibilityAttr);
|
||||
tmpl.#bind(ctx[visibilityAttr], (v) => {
|
||||
if (negate) {
|
||||
v = !v;
|
||||
}
|
||||
if (v) {
|
||||
el.style.display = "none";
|
||||
} else {
|
||||
el.style.removeProperty("display");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
static #text(el, ctx) {
|
||||
const attr = el.getAttribute(":text");
|
||||
if (attr) {
|
||||
el.removeAttribute(":text");
|
||||
tmpl.#bind(ctx[attr], (v) => (el.textContent = v));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,3 +1,283 @@
|
||||
export class ComfyWorkflows {
|
||||
|
||||
}
|
||||
// @ts-check
|
||||
|
||||
import { api } from "./api.js";
|
||||
import { clone } from "./utils.js";
|
||||
|
||||
export class ComfyWorkflow {
|
||||
/** @type { Array<ComfyWorkflow> } */
|
||||
static openWorkflows = [];
|
||||
/** @type {import("./app.js").ComfyApp} */
|
||||
static app;
|
||||
static unsavedCount = 0;
|
||||
|
||||
unsaved = false;
|
||||
/** @type { string | null } */
|
||||
name = null;
|
||||
/** @type { ChangeTracker } */
|
||||
changeTracker;
|
||||
/** @type { string | null } */
|
||||
tempName = null;
|
||||
|
||||
get displayName() {
|
||||
return this.name ?? this.tempName;
|
||||
}
|
||||
|
||||
static get activeWorkflow() {
|
||||
return this.openWorkflows[0];
|
||||
}
|
||||
|
||||
static get changeTracker() {
|
||||
return this.activeWorkflow.changeTracker;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} [name]
|
||||
*/
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
if (!name) {
|
||||
this.tempName = "Unsaved workflow";
|
||||
if (ComfyWorkflow.unsavedCount++) {
|
||||
this.tempName += ` (${ComfyWorkflow.unsavedCount})`;
|
||||
}
|
||||
}
|
||||
this.changeTracker = new ChangeTracker(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("./app.js").ComfyApp} app
|
||||
*/
|
||||
static init(app) {
|
||||
ComfyWorkflow.app = app;
|
||||
ChangeTracker.init(app);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param { Partial<ComfyWorkflow> } opts
|
||||
* @returns
|
||||
*/
|
||||
static newWorkflow(opts = {}) {
|
||||
const workflow = new ComfyWorkflow(opts?.name);
|
||||
Object.assign(workflow, opts);
|
||||
ComfyWorkflow.openWorkflows.unshift(workflow);
|
||||
ComfyWorkflow.#workflowsChanged();
|
||||
return workflow;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param { ComfyWorkflow | string } workflow
|
||||
*/
|
||||
static changeWorkflow(workflow) {
|
||||
let index;
|
||||
if (typeof workflow === "string") {
|
||||
index = this.openWorkflows.findIndex((w) => w.name === workflow);
|
||||
if (index === -1) {
|
||||
const r = ComfyWorkflow.newWorkflow({ name: workflow });
|
||||
return r;
|
||||
} else {
|
||||
workflow = this.openWorkflows[index];
|
||||
}
|
||||
} else {
|
||||
index = this.openWorkflows.indexOf(workflow);
|
||||
}
|
||||
if (index !== -1) {
|
||||
this.openWorkflows.splice(index, 1);
|
||||
}
|
||||
this.openWorkflows.unshift(workflow);
|
||||
this.#workflowsChanged();
|
||||
return workflow;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param { ComfyWorkflow } workflow
|
||||
*/
|
||||
static closeWorkflow(workflow) {
|
||||
const index = this.openWorkflows.indexOf(workflow);
|
||||
if (index !== -1) {
|
||||
this.openWorkflows.splice(index, 1);
|
||||
}
|
||||
ComfyWorkflow.#workflowsChanged();
|
||||
}
|
||||
|
||||
static #workflowsChanged() {
|
||||
console.log("workflowsChanged", this.activeWorkflow?.name, this.openWorkflows.length);
|
||||
api.dispatchEvent(new CustomEvent("workflowsChanged", { detail: this.activeWorkflow }));
|
||||
}
|
||||
}
|
||||
|
||||
export class ChangeTracker {
|
||||
static MAX_HISTORY = 50;
|
||||
|
||||
undo = [];
|
||||
redo = [];
|
||||
activeState = null;
|
||||
isOurLoad = false;
|
||||
/** @type { ComfyWorkflow } */
|
||||
workflow;
|
||||
|
||||
constructor(workflow) {
|
||||
this.workflow = workflow;
|
||||
}
|
||||
|
||||
checkState() {
|
||||
const currentState = ComfyWorkflow.app.graph.serialize();
|
||||
if (!ChangeTracker.graphEqual(this.activeState, currentState)) {
|
||||
this.undo.push(this.activeState);
|
||||
if (this.undo.length > ChangeTracker.MAX_HISTORY) {
|
||||
this.undo.shift();
|
||||
}
|
||||
this.activeState = clone(currentState);
|
||||
this.redo.length = 0;
|
||||
this.workflow.unsaved = true;
|
||||
api.dispatchEvent(new CustomEvent("graphChanged", { detail: this.activeState }));
|
||||
}
|
||||
}
|
||||
|
||||
async updateState(source, target) {
|
||||
const prevState = source.pop();
|
||||
if (prevState) {
|
||||
target.push(this.activeState);
|
||||
this.isOurLoad = true;
|
||||
await ComfyWorkflow.app.loadGraphData(prevState, false, this.workflow);
|
||||
this.activeState = prevState;
|
||||
}
|
||||
}
|
||||
|
||||
async undoRedo(e) {
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
if (e.key === "y") {
|
||||
this.updateState(this.redo, this.undo);
|
||||
return true;
|
||||
} else if (e.key === "z") {
|
||||
this.updateState(this.undo, this.redo);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static init(app) {
|
||||
const loadGraphData = app.loadGraphData;
|
||||
app.loadGraphData = async function () {
|
||||
const v = await loadGraphData.apply(this, arguments);
|
||||
if (ComfyWorkflow.changeTracker.isOurLoad) {
|
||||
ComfyWorkflow.changeTracker.isOurLoad = false;
|
||||
} else {
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
let keyIgnored = false;
|
||||
window.addEventListener(
|
||||
"keydown",
|
||||
(e) => {
|
||||
requestAnimationFrame(async () => {
|
||||
let activeEl;
|
||||
// If we are auto queue in change mode then we do want to trigger on inputs
|
||||
if (!app.ui.autoQueueEnabled || app.ui.autoQueueMode === "instant") {
|
||||
activeEl = document.activeElement;
|
||||
if (activeEl?.tagName === "INPUT" || activeEl?.["type"] === "textarea") {
|
||||
// Ignore events on inputs, they have their native history
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
keyIgnored = e.key === "Control" || e.key === "Shift" || e.key === "Alt" || e.key === "Meta";
|
||||
if (keyIgnored) return;
|
||||
|
||||
// Check if this is a ctrl+z ctrl+y
|
||||
if (await ComfyWorkflow.changeTracker.undoRedo(e)) return;
|
||||
|
||||
// If our active element is some type of input then handle changes after they're done
|
||||
if (ChangeTracker.bindInput(activeEl)) return;
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
});
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
window.addEventListener("keyup", (e) => {
|
||||
if (keyIgnored) {
|
||||
keyIgnored = false;
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle clicking DOM elements (e.g. widgets)
|
||||
window.addEventListener("mouseup", () => {
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
});
|
||||
|
||||
// Handle prompt queue event for dynamic widget changes
|
||||
api.addEventListener("promptQueued", () => {
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
});
|
||||
|
||||
// Handle litegraph clicks
|
||||
const processMouseUp = LGraphCanvas.prototype.processMouseUp;
|
||||
LGraphCanvas.prototype.processMouseUp = function (e) {
|
||||
const v = processMouseUp.apply(this, arguments);
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
return v;
|
||||
};
|
||||
const processMouseDown = LGraphCanvas.prototype.processMouseDown;
|
||||
LGraphCanvas.prototype.processMouseDown = function (e) {
|
||||
const v = processMouseDown.apply(this, arguments);
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
return v;
|
||||
};
|
||||
|
||||
// Handle litegraph context menu for COMBO widgets
|
||||
const close = LiteGraph.ContextMenu.prototype.close;
|
||||
LiteGraph.ContextMenu.prototype.close = function (e) {
|
||||
const v = close.apply(this, arguments);
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
return v;
|
||||
};
|
||||
}
|
||||
|
||||
static bindInput(activeEl) {
|
||||
if (activeEl && activeEl.tagName !== "CANVAS" && activeEl.tagName !== "BODY") {
|
||||
for (const evt of ["change", "input", "blur"]) {
|
||||
if (`on${evt}` in activeEl) {
|
||||
const listener = () => {
|
||||
ComfyWorkflow.changeTracker.checkState();
|
||||
activeEl.removeEventListener(evt, listener);
|
||||
};
|
||||
activeEl.addEventListener(evt, listener);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static graphEqual(a, b, root = true) {
|
||||
if (a === b) return true;
|
||||
|
||||
if (typeof a == "object" && a && typeof b == "object" && b) {
|
||||
const keys = Object.getOwnPropertyNames(a);
|
||||
|
||||
if (keys.length != Object.getOwnPropertyNames(b).length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const key of keys) {
|
||||
let av = a[key];
|
||||
let bv = b[key];
|
||||
if (root && key === "nodes") {
|
||||
// Nodes need to be sorted as the order changes when selecting nodes
|
||||
av = [...av].sort((a, b) => a.id - b.id);
|
||||
bv = [...bv].sort((a, b) => a.id - b.id);
|
||||
}
|
||||
if (!ChangeTracker.graphEqual(av, bv, false)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user