This commit is contained in:
pythongosssss 2024-02-18 17:18:40 +00:00
parent d293e5d067
commit b823baf2be
7 changed files with 473 additions and 32 deletions

View File

@ -2,6 +2,8 @@ import json
import os
import re
import uuid
import glob
import shutil
from aiohttp import web
from comfy.cli_args import args
from folder_paths import user_directory
@ -108,33 +110,85 @@ class UserManager():
user_id = self.add_user(username)
return web.json_response(user_id)
@routes.get("/userdata/{file}")
async def getuserdata(request):
file = request.match_info.get("file", None)
if not file:
@routes.get("/userdata")
async def listuserdata(request):
directory = request.rel_url.query.get('dir', '')
if not directory:
return web.Response(status=400)
path = self.get_request_user_filepath(request, file)
path = self.get_request_user_filepath(request, directory)
if not path:
return web.Response(status=403)
if not os.path.exists(path):
return web.Response(status=404)
return web.FileResponse(path)
recurse = request.rel_url.query.get('recurse', '').lower() == "true"
results = glob.glob(os.path.join(
glob.escape(path), '**/*'), recursive=recurse)
results = [os.path.relpath(x, path) for x in results if os.path.isfile(x)]
split_path = request.rel_url.query.get('split', '').lower() == "true"
if split_path:
results = [x.split(os.sep) for x in results]
@routes.post("/userdata/{file}")
async def post_userdata(request):
file = request.match_info.get("file", None)
return web.json_response(results)
def get_user_data_path(request, check_exists = False, param = "file"):
file = request.match_info.get(param, None)
if not file:
return web.Response(status=400)
path = self.get_request_user_filepath(request, file)
if not path:
return web.Response(status=403)
if check_exists and not os.path.exists(path):
return web.Response(status=404)
return path
@routes.get("/userdata/{file}")
async def getuserdata(request):
path = get_user_data_path(request, check_exists=True)
if not isinstance(path, str):
return path
return web.FileResponse(path)
@routes.post("/userdata/{file}")
async def post_userdata(request):
path = get_user_data_path(request)
if not isinstance(path, str):
return path
body = await request.read()
with open(path, "wb") as f:
f.write(body)
return web.Response(status=200)
@routes.delete("/userdata/{file}")
async def delete_userdata(request):
path = get_user_data_path(request, check_exists=True)
if not isinstance(path, str):
return path
os.remove(path)
return web.Response(status=204)
@routes.post("/userdata/{file}/move/{dest}")
async def move_userdata(request):
source = get_user_data_path(request, check_exists=True)
if not isinstance(source, str):
return source
dest = get_user_data_path(request, check_exists=True, param="dest")
if not isinstance(source, str):
return dest
print(f"moving '{source}' -> '{dest}'")
shutil.move(source, dest)
return web.Response(status=204)

View File

@ -327,7 +327,7 @@ class ComfyApi extends EventTarget {
/**
* Gets user configuration data and where data should be stored
* @returns { Promise<{ storage: "server" | "browser", users?: Promise<string, unknown>, migrated?: boolean }> }
* @returns { Promise<{ storage: "server" | "browser", users?: Promise<string, unknown>, migrated?: boolean }> }
*/
async getUserConfig() {
return (await this.fetchApi("/users")).json();
@ -335,7 +335,7 @@ class ComfyApi extends EventTarget {
/**
* Creates a new user
* @param { string } username
* @param { string } username
* @returns The fetch response
*/
createUser(username) {
@ -394,7 +394,7 @@ class ComfyApi extends EventTarget {
* Gets a user data file for the current user
* @param { string } file The name of the userdata file to load
* @param { RequestInit } [options]
* @returns { Promise<unknown> } The fetch response object
* @returns { Promise<Response> } The fetch response object
*/
async getUserData(file, options) {
return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options);
@ -412,11 +412,55 @@ class ComfyApi extends EventTarget {
method: "POST",
body: options?.stringify ? JSON.stringify(data) : data,
...options,
});
});
if (resp.status !== 200) {
throw new Error(`Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`);
}
}
/**
* Deletes a user data file for the current user
* @param { string } file The name of the userdata file to delete
*/
async deleteUserData(file) {
const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {
method: "DELETE",
});
if (resp.status !== 204) {
throw new Error(`Error removing user data file '${file}': ${resp.status} ${(resp).statusText}`);
}
}
/**
* @overload
* Lists user data files for the current user
* @param { string } dir The directory in which to list files
* @param { boolean } [recurse] If the listing should be recursive
* @param { true } [split] If the paths should be split based on the os path separator
* @returns { Promise<string[][]>> } The list of split file paths
*/
/**
* @overload
* Lists user data files for the current user
* @param { string } dir The directory in which to list files
* @param { boolean } [recurse] If the listing should be recursive
* @param { false | undefined } [split] If the paths should be split based on the os path separator
* @returns { Promise<string[]>> } The list of files
*/
async listUserData(dir, recurse, split) {
const resp = await this.fetchApi(
`/userdata?${new URLSearchParams({
recurse,
dir,
split,
})}`
);
if (resp.status === 404) return [];
if (resp.status !== 200) {
throw new Error(`Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`);
}
return resp.json();
}
}
export const api = new ComfyApi();

View File

@ -1730,7 +1730,7 @@ export class ComfyApp {
* @param {*} graphData A serialized graph object
* @param { boolean } clean If the graph state, e.g. images, should be cleared
*/
async loadGraphData(graphData, clean = true) {
async loadGraphData(graphData, clean = true, keepOld = false) {
if (clean !== false) {
this.clean();
}
@ -1765,7 +1765,7 @@ export class ComfyApp {
}
try {
this.graph.configure(graphData);
this.graph.configure(graphData, keepOld);
} catch (error) {
let errorHint = [];
// Try extracting filename to see if it was caused by an extension script

View File

@ -83,7 +83,7 @@ export class ComfyButton {
}
}
updateIcon = () => (this.iconElement.className = `mdi mdi-${this.icon}${this.iconSize ? " mdi-" + this.iconSize : ""}`);
updateIcon = () => (this.iconElement.className = `mdi mdi-${this.icon}${this.iconSize ? " mdi-" + this.iconSize + "px" : ""}`);
updateClasses = () => {
const internalClasses = [];
if (this.hidden) {
@ -92,10 +92,12 @@ export class ComfyButton {
if (!this.enabled) {
internalClasses.push("disabled");
}
if (this.#popupOpen) {
internalClasses.push("popup-open");
} else {
internalClasses.push("popup-closed");
if (this.popup) {
if (this.#popupOpen) {
internalClasses.push("popup-open");
} else {
internalClasses.push("popup-closed");
}
}
applyClasses(this.element, this.classList, ...internalClasses);
};

View File

@ -38,7 +38,7 @@ export class ComfyAppMenu {
});
this.logo = $el("h1.comfyui-logo.sm-hide", { title: "ComfyUI" }, "ComfyUI");
this.workflows = new ComfyWorkflowsMenu();
this.workflows = new ComfyWorkflowsMenu(app);
this.element = $el("nav.comfyui-menu", { parent: document.body }, [
this.logo,
this.workflows.element,

View File

@ -17,6 +17,9 @@
.hidden {
display: none !important;
}
.mdi.rotate270::before {
transform: rotate(270deg);
}
/* Generic */
.comfyui-button {
@ -294,8 +297,8 @@
}
.comfyui-workflows-popup {
width: 100%;
max-width: 350px;
font-family: Arial, Helvetica, sans-serif;
font-size: 0.8em;
padding: 10px;
overflow: auto;
background-color: var(--border-color);
@ -304,6 +307,101 @@
border-bottom-left-radius: 4px;
}
.comfyui-workflows-actions {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
.comfyui-workflows-actions .comfyui-button {
background: var(--comfy-input-bg);
color: var(--input-text);
}
.comfyui-workflows-actions .comfyui-button:not(:disabled):hover {
background: var(--primary-bg);
color: var(--primary-fg);
}
.comfyui-workflows-favorites {
border-bottom: 1px solid var(--comfy-input-bg);
padding-bottom: 5px;
}
.comfyui-workflows-favorites:empty {
display: none;
}
.comfyui-workflows-tree {
padding: 0;
padding-top: 5px;
margin-bottom: 0;
margin: 0;
}
.comfyui-workflows-tree>ul {
padding: 0;
}
.comfyui-workflows-tree>ul ul {
margin: 0;
padding: 0 0 0 30px;
}
.comfyui-workflows-tree .closed>ul {
display: none;
}
.comfyui-workflows-tree li,
.comfyui-workflows-tree-file {
--item-height: 31px;
list-style-type: none;
height: var(--item-height);
display: flex;
align-items: center;
gap: 5px;
cursor: pointer;
user-select: none;
}
.comfyui-workflows-tree li:hover::before,
.comfyui-workflows-tree-file:hover::before {
content: "";
position: absolute;
width: 100%;
left: 0;
height: var(--item-height);
background-color: var(--comfy-input-bg);
z-index: -1;
}
.comfyui-workflows-tree-file span {
flex: auto;
}
.comfyui-workflows-tree-file span+.comfyui-workflows-file-action {
margin-left: 10px;
}
.comfyui-workflows-tree-file .comfyui-workflows-file-action {
opacity: 0;
background-color: transparent;
color: var(--fg-color);
padding: 2px 4px;
}
.comfyui-workflows-tree-file .comfyui-workflows-file-action:hover {
background-color: var(--primary-bg);
color: var(--primary-fg);
}
.comfyui-workflows-tree-file:hover .comfyui-workflows-file-action {
opacity: 1;
}
.comfyui-workflows-tree-file>.mdi-star {
color: orange
}
/* View List */
.comfyui-view-list-popup {
padding: 10px;

View File

@ -3,6 +3,7 @@
import { ComfyButton } from "../components/button.js";
import { prop } from "../../utils.js";
import { $el } from "../../ui.js";
import { api } from "../../api.js";
import { ComfyPopup } from "../components/popup.js";
export class ComfyWorkflowsMenu {
@ -16,7 +17,7 @@ export class ComfyWorkflowsMenu {
this.popup.open = open;
}
constructor() {
constructor(app) {
const classList = {
"comfyui-workflows-button": true,
"comfyui-button": true,
@ -30,10 +31,8 @@ export class ComfyWorkflowsMenu {
this.element.append(this.button.element);
this.popup = new ComfyPopup(
{ target: this.element, classList: "comfyui-workflows-popup" },
new ComfyWorkflowsPopup().element
);
this.popup = new ComfyPopup({ target: this.element, classList: "comfyui-workflows-popup" });
this.popup.children = [new ComfyWorkflowsContent(app, this.popup).element];
this.popup.addEventListener("change", () => {
this.button.icon = "chevron-" + (this.popup.open ? "up" : "down");
});
@ -50,11 +49,255 @@ export class ComfyWorkflowsMenu {
}
}
export class ComfyWorkflowsPopup {
export class ComfyWorkflowsContent {
#fileLookup = {};
element = $el("div.comfyui-workflows-panel");
/** @type {Set<string>} */
favorites;
constructor() {
this.element.append(new ComfyButton({ content: "New Workflow" }).element);
this.element.append(new ComfyButton({ content: "Default Workflow" }).element);
constructor(app, popup) {
this.app = app;
this.popup = popup;
this.actions = $el("div.comfyui-workflows-actions", [
new ComfyButton({ content: "New Workflow", icon: "plus" }).element,
new ComfyButton({ content: "Load Default" }).element,
]);
this.load();
}
async loadWorkflowsInfo() {
const resp = await api.getUserData("workflows/.index.json");
let info;
if (resp.status === 200) {
info = await resp.json();
}
this.favorites = new Set(info?.favorites ?? []);
}
async storeWorkflowsInfo() {
await api.storeUserData("workflows/.index.json", {
favorites: [...this.favorites.values()],
});
}
async load() {
const tree = await this.createTreeElement();
this.updateFavoritesElement();
this.element.replaceChildren(this.actions, this.favoritesElement, tree);
}
updateFavoritesElement() {
const favorites = [...this.favorites.values()];
const current = this.favoritesElement;
this.favoritesElement = $el(
"div.comfyui-workflows-favorites",
favorites.map((f) => {
const entry = this.#fileLookup[f];
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;
})
);
if (current) {
current.replaceWith(this.favoritesElement);
}
}
async createTreeElement() {
await this.loadWorkflowsInfo();
const workflows = await api.listUserData("workflows", true, true);
const nodes = {};
const rootNode = $el("ul.comfyui-workflows-tree");
for (const pathParts of workflows) {
let currentPath = "";
let currentRoot = rootNode;
for (let i = 0; i < pathParts.length; i++) {
const part = 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 === pathParts.length - 1;
let nodeElement;
if (leaf) {
const fileNode = new FileNode(this, currentPath, part);
nodeElement = fileNode.element;
this.#fileLookup[currentPath] = fileNode;
} else {
nodeElement = $el("li", [$el("i.mdi.mdi-18px.mdi-folder"), $el("span", part)]);
}
parentNode.append(nodeElement);
}
nodes[currentPath] = parentNode;
currentRoot = parentNode;
}
}
return rootNode;
}
}
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();
}
// 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 loadWorkflow = async (e, insert) => {
e.stopImmediatePropagation();
const resp = await api.getUserData(fileName);
if (resp.status !== 200) {
alert(`Error storing user data file '${fileName}': ${resp.status} ${resp.statusText}`);
return;
}
const data = await resp.json();
// TODO: fix insert, LiteGraph has a dont clear parameter but it doesnt fix duplicate ids
await this.parent.app.loadGraphData(data, !insert, insert);
this.parent.popup.open = false;
};
const name = this.part.replace(/\.json$/, "");
this.element = $el(
tagName + ".comfyui-workflows-tree-file",
{
onclick: (e) => loadWorkflow(e, false),
},
[
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: (e) => loadWorkflow(e, true),
// }).element,
new ComfyButton({
icon: "pencil",
tooltip: "Rename this workflow",
classList: "comfyui-button comfyui-workflows-file-action",
iconSize: 18,
action: (e) => {
e.stopImmediatePropagation();
const newName = prompt("Enter new name", name);
if (newName) {
// Rename file
}
},
}).element,
this.favoriteButton.element,
deleteButton.element,
]
);
this.updateFavorite();
}
}