From a3fe94513fdb071049d9de1e42ec096dd197c18f Mon Sep 17 00:00:00 2001 From: pythongosssss <125205205+pythongosssss@users.noreply.github.com> Date: Wed, 6 Mar 2024 21:12:47 +0000 Subject: [PATCH] wip --- app/user_manager.py | 6 +- web/scripts/app.js | 2 +- web/scripts/changeTracker.js | 2 +- web/scripts/ui.js | 4 +- web/scripts/ui/components/button.js | 38 ++- web/scripts/ui/menu/index.js | 4 +- web/scripts/ui/menu/menu.css | 14 +- web/scripts/ui/menu/v3.js | 8 - web/scripts/ui/menu/workflows.js | 458 +++++++++++++--------------- web/scripts/workflows.js | 152 ++++++--- 10 files changed, 382 insertions(+), 306 deletions(-) delete mode 100644 web/scripts/ui/menu/v3.js diff --git a/app/user_manager.py b/app/user_manager.py index 106f2e2bc..53dff18b7 100644 --- a/app/user_manager.py +++ b/app/user_manager.py @@ -171,7 +171,8 @@ class UserManager(): with open(path, "wb") as f: f.write(body) - return web.Response(status=200) + resp = os.path.relpath(path, self.get_request_user_filepath(request, None)) + return web.json_response(resp) @routes.delete("/userdata/{file}") async def delete_userdata(request): @@ -200,4 +201,5 @@ class UserManager(): print(f"moving '{source}' -> '{dest}'") shutil.move(source, dest) - return web.Response(status=204) + resp = os.path.relpath(dest, self.get_request_user_filepath(request, None)) + return web.json_response(resp) diff --git a/web/scripts/app.js b/web/scripts/app.js index aff255a4b..7b22b08ee 100644 --- a/web/scripts/app.js +++ b/web/scripts/app.js @@ -1733,7 +1733,7 @@ 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 { import("./workflows.js").ComfyWorkflow | null } name The workflow + * @param { import("./workflows.js").ComfyWorkflowInstance | null } name The workflow */ async loadGraphData(graphData, clean = true, workflow = null) { if (clean !== false) { diff --git a/web/scripts/changeTracker.js b/web/scripts/changeTracker.js index a9e298b81..87925eb21 100644 --- a/web/scripts/changeTracker.js +++ b/web/scripts/changeTracker.js @@ -10,7 +10,7 @@ export class ChangeTracker { redo = []; activeState = null; isOurLoad = false; - /** @type { import("./workflows").ComfyWorkflow } */ + /** @type { import("./workflows").ComfyWorkflowInstance } */ workflow; ds; diff --git a/web/scripts/ui.js b/web/scripts/ui.js index d7df3eed0..8e28fa786 100644 --- a/web/scripts/ui.js +++ b/web/scripts/ui.js @@ -59,7 +59,7 @@ export function $el(tag, propsOrChildren, children) { Object.assign(element, propsOrChildren); if (children) { - element.append(...(children instanceof Array ? children : [children])); + element.append(...(children instanceof Array ? children.filter(Boolean) : [children])); } if (parent) { @@ -374,6 +374,8 @@ export class ComfyUI { }, }); + this.loadFile = () => fileInput.click(); + const autoQueueModeEl = toggleSwitch( "autoQueueMode", [ diff --git a/web/scripts/ui/components/button.js b/web/scripts/ui/components/button.js index 15020b8aa..25e5aeebd 100644 --- a/web/scripts/ui/components/button.js +++ b/web/scripts/ui/components/button.js @@ -7,6 +7,7 @@ import { prop } from "../../utils.js"; /** * @typedef {{ * icon?: string; + * overIcon?: string; * iconSize?: number; * content?: string | HTMLElement; * tooltip?: string; @@ -20,6 +21,7 @@ import { prop } from "../../utils.js"; export class ComfyButton { #over = 0; #popupOpen = false; + isOver = false; iconElement = $el("i.mdi"); contentElement = $el("span"); /** @@ -30,10 +32,40 @@ export class ComfyButton { /** * @param {ComfyButtonProps} opts */ - constructor({ icon, iconSize, content, tooltip, action, classList = "comfyui-button", visibilitySetting, app, enabled = true }) { - this.element = $el("button", [this.iconElement, this.contentElement]); + constructor({ + icon, + overIcon, + iconSize, + content, + tooltip, + action, + classList = "comfyui-button", + visibilitySetting, + app, + enabled = true, + }) { + this.element = $el("button", { + onmouseenter: () => { + this.isOver = true; + if(this.overIcon) { + this.updateIcon(); + } + }, + onmouseleave: () => { + this.isOver = false; + if(this.overIcon) { + this.updateIcon(); + } + } + + }, [this.iconElement, this.contentElement]); this.icon = prop(this, "icon", icon, toggleElement(this.iconElement, { onShow: this.updateIcon })); + this.overIcon = prop(this, "overIcon", overIcon, () => { + if(this.isOver) { + this.updateIcon(); + } + }); this.iconSize = prop(this, "iconSize", iconSize, this.updateIcon); this.content = prop( this, @@ -83,7 +115,7 @@ export class ComfyButton { } } - updateIcon = () => (this.iconElement.className = `mdi mdi-${this.icon}${this.iconSize ? " mdi-" + this.iconSize + "px" : ""}`); + updateIcon = () => (this.iconElement.className = `mdi mdi-${(this.isOver && this.overIcon) || this.icon}${this.iconSize ? " mdi-" + this.iconSize + "px" : ""}`); updateClasses = () => { const internalClasses = []; if (this.hidden) { diff --git a/web/scripts/ui/menu/index.js b/web/scripts/ui/menu/index.js index b22e1b204..2f352bfee 100644 --- a/web/scripts/ui/menu/index.js +++ b/web/scripts/ui/menu/index.js @@ -32,7 +32,7 @@ export class ComfyAppMenu { new ComfyButton({ icon: "content-save", tooltip: "Save the current workflow", - action: () => this.workflows.save(), + action: () => app.workflowManager.activeWorkflow.save(), content: t, }); @@ -50,7 +50,7 @@ export class ComfyAppMenu { icon: "content-save-edit", content: "Save As", tooltip: "Save the current graph as a new workflow", - action: () => this.workflows.save(true), + action: () => app.workflowManager.activeWorkflow.save(true), }), new ComfyButton({ icon: "download", diff --git a/web/scripts/ui/menu/menu.css b/web/scripts/ui/menu/menu.css index 88800e6db..b2aaf1141 100644 --- a/web/scripts/ui/menu/menu.css +++ b/web/scripts/ui/menu/menu.css @@ -37,12 +37,12 @@ opacity: 0.5; cursor: not-allowed; } -.primary .comfyui-button { +.primary .comfyui-button, .primary.comfyui-button { background-color: var(--primary-bg) !important; color: var(--primary-fg) !important; } -.primary .comfyui-button:not(:disabled):hover { +.primary .comfyui-button:not(:disabled):hover, .primary.comfyui-button:not(:disabled):hover { background-color: var(--primary-hover-bg) !important; color: var(--primary-hover-fg) !important; } @@ -433,9 +433,17 @@ opacity: 1; } -.comfyui-workflows-tree-file>.mdi-star { +.comfyui-workflows-tree-file .comfyui-workflows-file-action-primary { + background-color: transparent; + color: var(--fg-color); + padding: 2px 4px; + margin: 0 -4px; +} + +.comfyui-workflows-file-action-favorite .mdi-star { color: orange } + /* View List */ .comfyui-view-list-popup { padding: 10px; diff --git a/web/scripts/ui/menu/v3.js b/web/scripts/ui/menu/v3.js deleted file mode 100644 index 3df3ecc72..000000000 --- a/web/scripts/ui/menu/v3.js +++ /dev/null @@ -1,8 +0,0 @@ -class ComfyMenu extends HTMLElement { - constructor() { - super(); - this.classList.add("test"); - } -} - -customElements.define("comfyui-menu", ComfyMenu); diff --git a/web/scripts/ui/menu/workflows.js b/web/scripts/ui/menu/workflows.js index b19b90ce5..44f5bfc9a 100644 --- a/web/scripts/ui/menu/workflows.js +++ b/web/scripts/ui/menu/workflows.js @@ -25,11 +25,19 @@ export class ComfyWorkflowsMenu { constructor(app) { this.app = app; - app.workflowManager.addEventListener("change", () => { + const updateActive = () => { const active = app.workflowManager.activeWorkflow; this.button.tooltip = active.path; this.workflowLabel.textContent = active.name; this.unsaved = active.unsaved; + }; + + app.workflowManager.addEventListener("changeWorkflow", updateActive); + app.workflowManager.addEventListener("rename", updateActive); + app.workflowManager.addEventListener("delete", updateActive); + + app.workflowManager.addEventListener("save", () => { + this.unsaved = app.workflowManager.activeWorkflow.unsaved; }); api.addEventListener("graphChanged", () => { @@ -41,7 +49,7 @@ export class ComfyWorkflowsMenu { "comfyui-button": true, unsaved: getStorageValue("Comfy.PreviousWorkflowUnsaved") === "true", }; - this.workflowLabel = $el("span.comfyui-workflows-label", "Unsaved workflow"); + this.workflowLabel = $el("span.comfyui-workflows-label", ""); this.button = new ComfyButton({ content: $el("div.comfyui-workflows-button-inner", [$el("i.mdi.mdi-graph"), this.workflowLabel]), icon: "chevron-down", @@ -68,6 +76,8 @@ export class ComfyWorkflowsMenu { export class ComfyWorkflowsContent { element = $el("div.comfyui-workflows-panel"); + treeState = {}; + treeFiles = {}; /** * @param {import("../../app.js").ComfyApp} app @@ -78,29 +88,36 @@ export class ComfyWorkflowsContent { this.popup = popup; this.actions = $el("div.comfyui-workflows-actions", [ new ComfyButton({ - content: "New Workflow", - icon: "plus", + content: "Default", + icon: "file-code", + iconSize: 18, + classList: "comfyui-button primary", + action: () => { + popup.open = false; + app.loadGraphData(); + }, + }).element, + new ComfyButton({ + content: "Browse", + icon: "folder", + iconSize: 18, + action: () => { + popup.open = false; + app.ui.loadFile(); + }, + }).element, + new ComfyButton({ + content: "Blank", + icon: "plus-thick", + iconSize: 18, action: () => { app.workflowManager.setWorkflow(null); app.clean(); app.graph.clear(); + app.workflowManager.activeWorkflow.track(); popup.open = false; }, }).element, - new ComfyButton({ - content: "Load JSON", - action: () => { - popup.open = false; - app.loadGraphData(); - }, - }).element, - new ComfyButton({ - content: "Load Default", - action: () => { - popup.open = false; - app.loadGraphData(); - }, - }).element, ]); this.spinner = createSpinner(); @@ -108,22 +125,42 @@ export class ComfyWorkflowsContent { this.popup.addEventListener("open", () => this.load()); this.popup.addEventListener("close", () => this.element.replaceChildren(this.actions, this.spinner)); + + this.app.workflowManager.addEventListener("favorite", (e) => { + const workflow = e["detail"]; + const button = this.treeFiles[workflow.path]?.primaryButton; + if (!button) return; // Can happen when a workflow is renamed + button.icon = this.#getFavoriteIcon(workflow); + button.overIcon = this.#getFavoriteOverIcon(workflow); + this.updateFavorites(); + }); + + this.app.workflowManager.addEventListener("open", (e) => { + this.updateOpen(); + }); + this.app.workflowManager.addEventListener("close", (e) => { + this.updateOpen(); + }); + this.app.workflowManager.addEventListener("rename", (e) => { + this.load(); + }); } async load() { + await this.app.workflowManager.loadWorkflows(); this.updateTree(); this.updateFavorites(); - this.updateOpenWorkflows(); + this.updateOpen(); this.element.replaceChildren(this.actions, this.openElement, this.favoritesElement, this.treeElement); } - updateOpenWorkflows() { + updateOpen() { const current = this.openElement; this.openElement = $el("div.comfyui-workflows-open", [ $el("h3", "Open Workflows"), ...this.app.workflowManager.openWorkflows.map((w) => { - const wrapper = new WorkflowElement(w, { + const wrapper = new WorkflowElement(this, w, { buttons: [], }); @@ -141,27 +178,8 @@ export class ComfyWorkflowsContent { this.favoritesElement = $el( "div.comfyui-workflows-favorites", favorites - .map((f) => { - return $el("span", f.path); - // const entry = this.#fileLookup[f]; - // if (!entry) return null; - // const res = new FileNode( - // this, - // entry.path, - // entry.part, - // "div", - // (f) => { - // entry.isFavorite = f; - // entry.updateFavorite(); - // this.updateFavoritesElement(); - // }, - // () => { - // res.element.remove(); - // entry.remove(); - // return false; - // } - // ); - // return res.element; + .map((w) => { + return this.#getWorkflowElement(w).element; }) .filter(Boolean) ); @@ -171,9 +189,9 @@ export class ComfyWorkflowsContent { updateTree() { const current = this.treeElement; - const flat = {}; const nodes = {}; + this.treeFiles = {}; this.treeElement = $el("ul.comfyui-workflows-tree"); for (const workflow of this.app.workflowManager.workflows) { @@ -183,33 +201,8 @@ export class ComfyWorkflowsContent { let currentRoot = this.treeElement; for (let i = 0; i < workflow.pathParts.length; i++) { - const part = workflow.pathParts[i]; - currentPath += (currentPath ? "\\" : "") + part; - let parentNode = nodes[currentPath]; - - // Create a new parent node if it doesn't exist - if (!parentNode) { - parentNode = $el("ul.closed", { - $: (el) => { - el.onclick = (e) => { - el.classList.toggle("closed"); - e.stopImmediatePropagation(); - }; - }, - }); - currentRoot.append(parentNode); - - // Create a node for the current part and an inner UL for its children if it isnt a leaf node - const leaf = i === workflow.pathParts.length - 1; - let nodeElement; - if (leaf) { - const fileNode = new WorkflowElement(workflow, { buttons: [] }); - nodeElement = fileNode.element; - } else { - nodeElement = $el("li", [$el("i.mdi.mdi-18px.mdi-folder"), $el("span", part)]); - } - parentNode.append(nodeElement); - } + currentPath += (currentPath ? "\\" : "") + workflow.pathParts[i]; + const parentNode = nodes[currentPath] ?? this.#createNode(currentPath, workflow, i, currentRoot); nodes[currentPath] = parentNode; currentRoot = parentNode; @@ -218,190 +211,175 @@ export class ComfyWorkflowsContent { current?.replaceWith(this.treeElement); } + + #expandNode(el, workflow, thisPath, i) { + const expanded = !el.classList.toggle("closed"); + if (expanded) { + let c = ""; + for (let j = 0; j <= i; j++) { + c += (c ? "\\" : "") + workflow.pathParts[j]; + this.treeState[c] = true; + } + } else { + let c = thisPath; + for (let j = i + 1; j < workflow.pathParts.length; j++) { + c += (c ? "\\" : "") + workflow.pathParts[j]; + delete this.treeState[c]; + } + delete this.treeState[thisPath]; + } + } + + /** @param {ComfyWorkflow} workflow */ + #getFavoriteIcon(workflow) { + return workflow.isFavorite ? "star" : "file-outline"; + } + + /** @param {ComfyWorkflow} workflow */ + #getFavoriteOverIcon(workflow) { + return workflow.isFavorite ? "star-off" : "star-outline"; + } + + /** @param {ComfyWorkflow} workflow */ + #getFavoriteButton(workflow, primary) { + return new ComfyButton({ + icon: this.#getFavoriteIcon(workflow), + overIcon: this.#getFavoriteOverIcon(workflow), + iconSize: 18, + classList: "comfyui-button comfyui-workflows-file-action-favorite" + (primary ? " comfyui-workflows-file-action-primary" : ""), + action: (e) => { + e.stopImmediatePropagation(); + workflow.favorite(!workflow.isFavorite); + }, + }); + } + + /** @param {ComfyWorkflow} workflow */ + #getDeleteButton(workflow) { + const deleteButton = new ComfyButton({ + icon: "delete", + tooltip: "Delete this workflow", + classList: "comfyui-button comfyui-workflows-file-action", + iconSize: 18, + action: async (e, btn) => { + e.stopImmediatePropagation(); + + if (btn.icon === "delete-empty") { + btn.enabled = false; + await workflow.delete(); + await this.load(); + } else { + btn.icon = "delete-empty"; + btn.element.style.background = "red"; + } + }, + }); + deleteButton.element.addEventListener("mouseleave", () => { + deleteButton.icon = "delete"; + deleteButton.element.style.removeProperty("background"); + }); + return deleteButton; + } + + /** @param {ComfyWorkflow} workflow */ + #getInsertButton(workflow) { + return new ComfyButton({ + icon: "file-move-outline", + iconSize: 18, + tooltip: "Insert this workflow into the current workflow", + classList: "comfyui-button comfyui-workflows-file-action", + action: (e) => { + if (!this.app.shiftDown) { + this.popup.open = false; + } + e.stopImmediatePropagation(); + if (!this.app.shiftDown) { + this.popup.open = false; + } + workflow.insert(); + }, + }); + } + + /** @param {ComfyWorkflow} workflow */ + #getRenameButton(workflow) { + return new ComfyButton({ + icon: "pencil", + tooltip: "Rename this workflow", + classList: "comfyui-button comfyui-workflows-file-action", + iconSize: 18, + action: async (e) => { + e.stopImmediatePropagation(); + const newName = prompt("Enter new name", workflow.path); + if (newName) { + await workflow.rename(newName); + } + }, + }); + } + + /** @param {ComfyWorkflow} workflow */ + #getWorkflowElement(workflow) { + return new WorkflowElement(this, workflow, { + primaryButton: this.#getFavoriteButton(workflow, true), + buttons: [this.#getInsertButton(workflow), this.#getRenameButton(workflow), this.#getDeleteButton(workflow)], + }); + } + + /** @param {ComfyWorkflow} workflow */ + #createLeafNode(workflow) { + const fileNode = this.#getWorkflowElement(workflow); + this.treeFiles[workflow.path] = fileNode; + return fileNode; + } + + #createNode(currentPath, workflow, i, currentRoot) { + const part = workflow.pathParts[i]; + + const parentNode = $el("ul" + (this.treeState[currentPath] ? "" : ".closed"), { + $: (el) => { + el.onclick = (e) => { + this.#expandNode(el, workflow, currentPath, i); + e.stopImmediatePropagation(); + }; + }, + }); + currentRoot.append(parentNode); + + // Create a node for the current part and an inner UL for its children if it isnt a leaf node + const leaf = i === workflow.pathParts.length - 1; + let nodeElement; + if (leaf) { + nodeElement = this.#createLeafNode(workflow).element; + } else { + nodeElement = $el("li", [$el("i.mdi.mdi-18px.mdi-folder"), $el("span", part)]); + } + parentNode.append(nodeElement); + return parentNode; + } } class WorkflowElement { /** + * @param { ComfyWorkflowsContent } parent * @param { ComfyWorkflow } workflow */ - constructor(workflow, { tagName = "li", buttons }) { + constructor(parent, workflow, { tagName = "li", primaryButton, buttons }) { + this.parent = parent; this.workflow = workflow; + this.primaryButton = primaryButton; this.buttons = buttons; this.element = $el( tagName + ".comfyui-workflows-tree-file", { - onclick: workflow.load, + onclick: () => { + workflow.load(); + this.parent.popup.open = false; + }, title: this.workflow.path, }, - [$el("span", workflow.name)] + [this.primaryButton?.element, $el("span", workflow.name), ...buttons.map((b) => b.element)] ); } } - -// class FileNode { -// constructor(parent, path, part, tagName = "li", onFavorite = null, onRemove = null) { -// this.parent = parent; -// this.path = path; -// this.part = part; -// this.createFileElement(tagName); -// this.onFavorite = onFavorite; -// this.onRemove = onRemove; -// } - -// updateFavorite() { -// if (this.onFavorite?.(this.isFavorite) === false) return; -// if (this.isFavorite) { -// this.parent.favorites.add(this.path); -// this.favoriteButton.icon = "star"; -// this.favoriteButton.tooltip = "Unfavorite this workflow"; -// this.nodeIcon.classList.remove("mdi-file-outline"); -// this.nodeIcon.classList.add("mdi-star"); -// } else { -// this.parent.favorites.delete(this.path); -// this.favoriteButton.icon = "star-outline"; -// this.favoriteButton.tooltip = "Favorite this workflow"; -// this.nodeIcon.classList.add("mdi-file-outline"); -// this.nodeIcon.classList.remove("mdi-star"); -// } -// } - -// remove() { -// if (this.onRemove?.() === false) return; - -// const folderNode = this.element.parentElement.parentElement; -// if (folderNode.querySelectorAll("ul").length === 1) { -// folderNode.remove(); -// } else { -// this.element.parentElement.remove(); -// } -// } - -// createFileElement(tagName) { -// const fileName = `workflows\\${this.path}`; - -// this.isFavorite = this.parent.favorites.has(this.path); -// this.nodeIcon = $el("i.mdi.mdi-18px"); -// this.favoriteButton = new ComfyButton({ -// icon: this.isFavorite ? "star" : "star-outline", -// classList: "comfyui-button comfyui-workflows-file-action comfyui-workflows-file-action-favorite", -// iconSize: 18, -// action: async (e) => { -// e.stopImmediatePropagation(); -// this.isFavorite = !this.isFavorite; -// this.updateFavorite(); -// this.parent.updateFavoritesElement(); -// await this.parent.storeWorkflowsInfo(); -// }, -// }); - -// const deleteButton = new ComfyButton({ -// icon: "delete", -// tooltip: "Delete this workflow", -// classList: "comfyui-button comfyui-workflows-file-action", -// iconSize: 18, -// action: async (e, btn) => { -// e.stopImmediatePropagation(); - -// if (btn.icon === "delete-empty") { -// btn.enabled = false; -// if (this.isFavorite) { -// this.parent.favorites.delete(this.path); -// await this.parent.storeWorkflowsInfo(); -// } -// if (this.parent.app.currentWorkflow === this.path) { -// this.parent.app.currentWorkflow = null; -// } -// await api.deleteUserData(fileName); -// this.remove(); -// } else { -// btn.icon = "delete-empty"; -// btn.element.style.background = "red"; -// } -// }, -// }); -// deleteButton.element.addEventListener("mouseleave", () => { -// deleteButton.icon = "delete"; -// deleteButton.element.style.removeProperty("background"); -// }); - -// const getWorkflow = async (e) => { -// e.stopImmediatePropagation(); -// const resp = await api.getUserData(fileName); -// if (resp.status !== 200) { -// alert(`Error loading user data file '${fileName}': ${resp.status} ${resp.statusText}`); -// return; -// } -// return await resp.json(); -// }; - -// const loadWorkflow = async (e) => { -// const data = await getWorkflow(e); -// await this.parent.app.loadGraphData(data, true, this.path); -// this.parent.popup.open = false; -// }; - -// const insertWorkflow = async (e) => { -// const data = await getWorkflow(e); -// const old = localStorage.getItem("litegrapheditor_clipboard"); -// const graph = new LGraph(data); -// const canvas = new LGraphCanvas(null, graph, { skip_events: true, skip_render: true }); -// canvas.selectNodes(); -// canvas.copyToClipboard(); -// this.parent.app.canvas.pasteFromClipboard(); -// localStorage.setItem("litegrapheditor_clipboard", old); -// }; - -// const name = trimJsonExt(this.part); -// this.element = $el( -// tagName + ".comfyui-workflows-tree-file", -// { -// onclick: loadWorkflow, -// title: this.path, -// }, -// [ -// this.nodeIcon, -// $el("span", name), -// new ComfyButton({ -// icon: "file-move-outline", -// tooltip: "Insert this workflow into the current view", -// classList: "comfyui-button comfyui-workflows-file-action", -// iconSize: 18, -// action: insertWorkflow, -// }).element, -// new ComfyButton({ -// icon: "pencil", -// tooltip: "Rename this workflow", -// classList: "comfyui-button comfyui-workflows-file-action", -// iconSize: 18, -// action: async (e) => { -// e.stopImmediatePropagation(); -// const newName = prompt("Enter new name", trimJsonExt(this.path)); -// if (newName) { -// // Rename file -// try { -// const res = await api.moveUserData("workflows/" + this.path, "workflows/" + newName); - -// if (res.status === 409) { -// if (!confirm(`Workflow '${newName}' already exists, do you want to overwrite it?`)) return; -// await api.moveUserData("workflows/" + this.path, "workflows/" + newName, { overwrite: true }); -// } - -// if (this.parent.app.currentWorkflow === this.path) { -// this.parent.app.currentWorkflow = newName; -// } - -// await this.parent.load(); -// } catch (error) { -// alert(error.message ?? error); -// } -// } -// }, -// }).element, -// this.favoriteButton.element, -// deleteButton.element, -// ] -// ); -// this.updateFavorite(); -// } -// } diff --git a/web/scripts/workflows.js b/web/scripts/workflows.js index 59b0a6f92..d95016c8f 100644 --- a/web/scripts/workflows.js +++ b/web/scripts/workflows.js @@ -4,9 +4,19 @@ import { api } from "./api.js"; import { ChangeTracker } from "./changeTracker.js"; import { getStorageValue, setStorageValue } from "./utils.js"; +function appendJson(path) { + if (!path.toLowerCase().endsWith(".json")) { + path += ".json"; + } + return path; +} + export class ComfyWorkflowManager extends EventTarget { #unsavedCount = 0; + /** @type {Record} */ + workflowLookup = {}; + /** @type {Array} */ workflows = []; /** @type {Array} */ @@ -38,7 +48,12 @@ export class ComfyWorkflowManager extends EventTarget { } const workflows = (await api.listUserData("workflows", true, true)).map((w) => { - return new ComfyWorkflow(this, w[0], w.slice(1), favorites.has(w[0])); + let workflow = this.workflowLookup[w[0]]; + if (!workflow) { + workflow = new ComfyWorkflow(this, w[0], w.slice(1), favorites.has(w[0])); + this.workflowLookup[workflow.path] = workflow; + } + return workflow; }); this.workflows = workflows; @@ -50,7 +65,7 @@ export class ComfyWorkflowManager extends EventTarget { async saveWorkflowMetadata() { await api.storeUserData("workflows/.index.json", { - favorites: [...this.workflows.filter((w) => w.isFavorite).map((w) => w.name)], + favorites: [...this.workflows.filter((w) => w.isFavorite).map((w) => w.path)], }); } @@ -63,7 +78,7 @@ export class ComfyWorkflowManager extends EventTarget { const found = this.workflows.find((w) => w.path === workflow); if (found) { workflow = found; - workflow.unsaved = !workflow || (getStorageValue("Comfy.PreviousWorkflowUnsaved") === "true"); + workflow.unsaved = !workflow || getStorageValue("Comfy.PreviousWorkflowUnsaved") === "true"; } } @@ -82,7 +97,7 @@ export class ComfyWorkflowManager extends EventTarget { } setStorageValue("Comfy.PreviousWorkflow", this.activeWorkflow.path ?? ""); - this.dispatchEvent(new CustomEvent("change")); + this.dispatchEvent(new CustomEvent("changeWorkflow")); } } @@ -136,9 +151,7 @@ export class ComfyWorkflow { constructor(manager, path, pathParts, isFavorite) { this.manager = manager; if (pathParts) { - this.#path = path; - this.#pathParts = pathParts; - this.#name = pathParts[pathParts.length - 1].replace(/\.json$/, ""); + this.#updatePath(path, pathParts); this.#isFavorite = isFavorite; } else { this.#name = path; @@ -146,16 +159,36 @@ export class ComfyWorkflow { } } + /** + * @param {string} path + * @param {string[]} [pathParts] + */ + #updatePath(path, pathParts) { + this.#path = path; + + if (!pathParts) { + if (!path.includes("\\")) { + pathParts = path.split("/"); + } else { + pathParts = path.split("\\"); + } + } + + this.#pathParts = pathParts; + this.#name = pathParts[pathParts.length - 1].replace(/\.json$/, ""); + } + async getWorkflowData() { const resp = await api.getUserData("workflows/" + this.path); if (resp.status !== 200) { - alert(`Error loading user data file '${this.path}': ${resp.status} ${resp.statusText}`); + alert(`Error loading workflow file '${this.path}': ${resp.status} ${resp.statusText}`); return; } return await resp.json(); } load = async () => { + debugger; if (this.isOpen) { await this.manager.app.loadGraphData(this.changeTracker.activeState, true, this); } else { @@ -165,8 +198,8 @@ export class ComfyWorkflow { } }; - async save() { - if (!this.path) { + async save(saveAs = false) { + if (!this.path || saveAs) { await this.#save(null, false); } else { await this.#save(this.path, true); @@ -178,11 +211,12 @@ export class ComfyWorkflow { */ async favorite(value) { try { - await this.manager.saveWorkflowMetadata(); + if (this.#isFavorite === value) return; this.#isFavorite = value; + await this.manager.saveWorkflowMetadata(); this.manager.dispatchEvent(new CustomEvent("favorite", { detail: this })); } catch (error) { - alert("Error favoriting workflow " + this.name + "\n" + (error.message ?? error)); + alert("Error favoriting workflow " + this.path + "\n" + (error.message ?? error)); } } @@ -190,15 +224,29 @@ export class ComfyWorkflow { * @param {string} path */ async rename(path) { - let res = await api.moveUserData("workflows/" + this.path, "workflows/" + path); + path = appendJson(path); + let resp = await api.moveUserData("workflows/" + this.path, "workflows/" + path); - if (res.status === 409) { - if (!confirm(`Workflow '${path}' already exists, do you want to overwrite it?`)) return res; - res = await api.moveUserData("workflows/" + this.path, "workflows/" + path, { overwrite: true }); + if (resp.status === 409) { + if (!confirm(`Workflow '${path}' already exists, do you want to overwrite it?`)) return resp; + resp = await api.moveUserData("workflows/" + this.path, "workflows/" + path, { overwrite: true }); } - this.#updatePath(path); - return res; + if (resp.status !== 200) { + alert(`Error renaming workflow file '${this.path}': ${resp.status} ${resp.statusText}`); + return; + } + + const isFav = this.isFavorite; + if (isFav) { + await this.favorite(false); + } + path = (await resp.json()).substring("workflows/".length); + this.#updatePath(path, null); + if (isFav) { + await this.favorite(true); + } + this.manager.dispatchEvent(new CustomEvent("rename", { detail: this })); } async insert() { @@ -215,11 +263,21 @@ export class ComfyWorkflow { } async delete() { - if (this.isFavorite) { - await this.favorite(false); + // TODO: fix delete of current workflow - should mark workflow as unsaved and when saving use old name by default + + try { + if (this.isFavorite) { + await this.favorite(false); + } + await api.deleteUserData("workflows/" + this.path); + this.unsaved = true; + this.#path = null; + this.#pathParts = null; + this.manager.workflows.splice(this.manager.workflows.indexOf(this), 1); + this.manager.dispatchEvent(new CustomEvent("delete", { detail: this })); + } catch (error) { + alert(`Error deleting workflow: ${error.message || error}`); } - await api.deleteUserData(this.path); - this.manager.dispatchEvent(new CustomEvent("delete", { detail: this })); } track() { @@ -230,44 +288,48 @@ export class ComfyWorkflow { } } - /** - * @param {string} path - */ - #updatePath(path) { - this.#path = path; - if (!path.includes("\\")) { - this.#pathParts = path.split("/"); - } else { - this.#pathParts = path.split("\\"); - } - this.manager.dispatchEvent(new CustomEvent("rename", { detail: this })); - } - /** * @param {string|null} path * @param {boolean} overwrite */ async #save(path, overwrite) { if (!path) { - path = prompt("Save workflow as:", this.path ?? "workflow"); + path = prompt("Save workflow as:", this.path ?? this.name ?? "workflow"); if (!path) return; } - if (!path.toLowerCase().endsWith(".json")) { - path += ".json"; - } + path = appendJson(path); const p = await this.manager.app.graphToPrompt(); const json = JSON.stringify(p.workflow, null, 2); - const res = await api.storeUserData("workflows/" + path, json, { stringify: false, throwOnError: false, overwrite }); - if (res.status === 409) { + let resp = await api.storeUserData("workflows/" + path, json, { stringify: false, throwOnError: false, overwrite }); + if (resp.status === 409) { if (!confirm(`Workflow '${path}' already exists, do you want to overwrite it?`)) return; - await api.storeUserData("workflows/" + path, json, { stringify: false }); - this.#updatePath(path); - } else if (path === this.path && this.isOpen) { + resp = await api.storeUserData("workflows/" + path, json, { stringify: false }); + } + + if (resp.status !== 200) { + alert(`Error saving workflow '${this.path}': ${resp.status} ${resp.statusText}`); + return; + } + + path = (await resp.json()).substring("workflows/".length); + + if (!this.path) { + // Saved new workflow, patch this instance + this.#updatePath(path, null); + await this.manager.loadWorkflows(); + this.manager.dispatchEvent(new CustomEvent("rename", { detail: this })); + this.unsaved = false; + } else if (path !== this.path) { + // Saved as, open the new copy + await this.manager.loadWorkflows(); + const workflow = this.manager.workflowLookup[path]; + await workflow.load(); + } else { + // Normal save this.unsaved = false; this.manager.dispatchEvent(new CustomEvent("save", { detail: this })); } } } -