fix session storage

implement renaming
This commit is contained in:
pythongosssss 2024-02-27 20:24:40 +00:00
parent 114369c853
commit 19c3eb8f57
9 changed files with 88 additions and 23 deletions

View File

@ -189,10 +189,14 @@ class UserManager():
if not isinstance(source, str): if not isinstance(source, str):
return source return source
dest = get_user_data_path(request, check_exists=True, param="dest") dest = get_user_data_path(request, check_exists=False, param="dest")
if not isinstance(source, str): if not isinstance(source, str):
return dest return dest
overwrite = request.query["overwrite"] != "false"
if not overwrite and os.path.exists(dest):
return web.Response(status=409)
print(f"moving '{source}' -> '{dest}'") print(f"moving '{source}' -> '{dest}'")
shutil.move(source, dest) shutil.move(source, dest)

View File

@ -4,7 +4,7 @@
"paths": { "paths": {
"/*": ["./*"] "/*": ["./*"]
}, },
"lib": ["DOM", "ES2022"], "lib": ["DOM", "ES2022", "DOM.Iterable"],
"target": "ES2015", "target": "ES2015",
"module": "es2020" "module": "es2020"
}, },

View File

@ -407,7 +407,7 @@ class ComfyApi extends EventTarget {
* @param { RequestInit & { overwrite?: boolean, stringify?: boolean, throwOnError?: boolean } } [options] * @param { RequestInit & { overwrite?: boolean, stringify?: boolean, throwOnError?: boolean } } [options]
* @returns { Promise<Response> } * @returns { Promise<Response> }
*/ */
async storeUserData(file, data, options = { overwrite: true, stringify: true, throwOnError: true }) { async storeUserData(file, data, options = { overwrite: false, stringify: true, throwOnError: true }) {
const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}?overwrite=${options?.overwrite}`, { const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}?overwrite=${options?.overwrite}`, {
method: "POST", method: "POST",
body: options?.stringify ? JSON.stringify(data) : data, body: options?.stringify ? JSON.stringify(data) : data,
@ -432,6 +432,18 @@ class ComfyApi extends EventTarget {
} }
} }
/**
* Move a user data file for the current user
* @param { string } source The userdata file to move
* @param { string } dest The destination for the file
*/
async moveUserData(source, dest, options = { overwrite: false }) {
const resp = await this.fetchApi(`/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options?.overwrite}`, {
method: "POST",
});
return resp;
}
/** /**
* @overload * @overload
* Lists user data files for the current user * Lists user data files for the current user

View File

@ -5,9 +5,10 @@ import { api } from "./api.js";
import { defaultGraph } from "./defaultGraph.js"; import { defaultGraph } from "./defaultGraph.js";
import { getPngMetadata, getWebpMetadata, importA1111, getLatentMetadata } from "./pnginfo.js"; import { getPngMetadata, getWebpMetadata, importA1111, getLatentMetadata } from "./pnginfo.js";
import { addDomClippingSetting } from "./domWidget.js"; import { addDomClippingSetting } from "./domWidget.js";
import { createImageHost, calculateImageGrid } from "./ui/imagePreview.js" import { createImageHost, calculateImageGrid } from "./ui/imagePreview.js";
import { ComfyAppMenu } from "./ui/menu/index.js" import { ComfyAppMenu } from "./ui/menu/index.js";
export const ANIM_PREVIEW_WIDGET = "$$comfy_animation_preview" import { getStorageValue, setStorageValue } from "./utils.js";
export const ANIM_PREVIEW_WIDGET = "$$comfy_animation_preview";
function sanitizeNodeName(string) { function sanitizeNodeName(string) {
let entityMap = { let entityMap = {
@ -61,6 +62,7 @@ export class ComfyApp {
set currentWorkflow(value) { set currentWorkflow(value) {
this.#currentWorkflow = value ?? null; this.#currentWorkflow = value ?? null;
api.dispatchEvent(new CustomEvent("workflowChanged", { detail: value ?? null })); api.dispatchEvent(new CustomEvent("workflowChanged", { detail: value ?? null }));
setStorageValue("Comfy.LastWorkflow", value ?? "");
} }
/** /**
@ -1526,7 +1528,7 @@ export class ComfyApp {
const loadWorkflow = async (json) => { const loadWorkflow = async (json) => {
if (json) { if (json) {
const workflow = JSON.parse(json); const workflow = JSON.parse(json);
const workflowName = localStorage.getItem("Comfy.LastWorkflow"); const workflowName = getStorageValue("Comfy.LastWorkflow");
await this.loadGraphData(workflow, true, workflowName); await this.loadGraphData(workflow, true, workflowName);
return true; return true;
} }
@ -1775,7 +1777,6 @@ export class ComfyApp {
} }
this.currentWorkflow = name; this.currentWorkflow = name;
localStorage.setItem("Comfy.LastWorkflow", name ?? "");
const missingNodeTypes = []; const missingNodeTypes = [];
await this.#invokeExtensionsAsync("beforeConfigureGraph", graphData, missingNodeTypes); await this.#invokeExtensionsAsync("beforeConfigureGraph", graphData, missingNodeTypes);

View File

@ -1,8 +1,7 @@
// @ts-check // @ts-check
import { $el } from "../../ui.js"; import { $el } from "../../ui.js";
import { api } from "../../api.js"; import { downloadBlob } from "../../utils.js";
import { addStylesheet, downloadBlob } from "../../utils.js";
import { ComfyButton } from "../components/button.js"; import { ComfyButton } from "../components/button.js";
import { ComfyButtonGroup } from "../components/buttonGroup.js"; import { ComfyButtonGroup } from "../components/buttonGroup.js";
import { ComfySplitButton } from "../components/splitButton.js"; import { ComfySplitButton } from "../components/splitButton.js";
@ -12,8 +11,6 @@ import { ComfyWorkflowsMenu } from "./workflows.js";
import { ComfyViewQueueButton } from "./viewQueue.js"; import { ComfyViewQueueButton } from "./viewQueue.js";
import { getInteruptButton } from "./interruptButton.js"; import { getInteruptButton } from "./interruptButton.js";
addStylesheet("menu.css", import.meta.url);
const collapseOnMobile = (t) => { const collapseOnMobile = (t) => {
(t.element ?? t).classList.add("comfyui-menu-mobile-collapse"); (t.element ?? t).classList.add("comfyui-menu-mobile-collapse");
return t; return t;
@ -40,7 +37,7 @@ export class ComfyAppMenu {
}); });
this.logo = $el("h1.comfyui-logo.sm-hide", { title: "ComfyUI" }, "ComfyUI"); this.logo = $el("h1.comfyui-logo.sm-hide", { title: "ComfyUI" }, "ComfyUI");
this.element = $el("nav.comfyui-menu", { parent: document.body }, [ this.element = $el("nav.comfyui-menu", { style: { display: "none" }, parent: document.body }, [
this.logo, this.logo,
this.workflows.element, this.workflows.element,
new ComfySplitButton( new ComfySplitButton(
@ -128,6 +125,22 @@ export class ComfyAppMenu {
}) })
).element, ).element,
]); ]);
app.ui.settings.addSetting({
id: "Comfy.UseNewMenu",
defaultValue: false,
name: "[Beta] Use new menu and workflow management",
type: "boolean",
onChange: async (v) => {
if (v) {
app.ui.menuContainer.style.display = "none";
this.element.style.removeProperty("display");
} else {
app.ui.menuContainer.style.removeProperty("display");
this.element.style.display = "none";
}
},
});
} }
/** /**

View File

@ -299,6 +299,7 @@
direction: rtl; direction: rtl;
flex: auto; flex: auto;
position: relative; position: relative;
width: 120px;
} }
.comfyui-workflows-button.unsaved .comfyui-workflows-label { .comfyui-workflows-button.unsaved .comfyui-workflows-label {

View File

@ -1,7 +1,7 @@
// @ts-check // @ts-check
import { ComfyButton } from "../components/button.js"; import { ComfyButton } from "../components/button.js";
import { prop } from "../../utils.js"; import { prop, getStorageValue, setStorageValue } from "../../utils.js";
import { $el } from "../../ui.js"; import { $el } from "../../ui.js";
import { api } from "../../api.js"; import { api } from "../../api.js";
import { ComfyPopup } from "../components/popup.js"; import { ComfyPopup } from "../components/popup.js";
@ -29,7 +29,7 @@ export class ComfyWorkflowsMenu {
let first = true; let first = true;
api.addEventListener("workflowChanged", ({ detail }) => { api.addEventListener("workflowChanged", ({ detail }) => {
if (detail) { if (detail) {
this.unsaved = first ? localStorage.getItem("Comfy.LastWorkflowUnsaved") === "true" : false; this.unsaved = first ? getStorageValue("Comfy.LastWorkflowUnsaved") === "true" : false;
this.currentWorkflow = detail; this.currentWorkflow = detail;
} else { } else {
this.unsaved = true; this.unsaved = true;
@ -73,7 +73,7 @@ export class ComfyWorkflowsMenu {
classList.unsaved = v; classList.unsaved = v;
this.button.classList = classList; this.button.classList = classList;
if (!first) { if (!first) {
localStorage.setItem("Comfy.LastWorkflowUnsaved", v); setStorageValue("Comfy.LastWorkflowUnsaved", v);
} }
}); });
this.currentWorkflow = prop(this, "currentWorkflow", "", () => { this.currentWorkflow = prop(this, "currentWorkflow", "", () => {
@ -83,7 +83,7 @@ export class ComfyWorkflowsMenu {
save(saveAs) { save(saveAs) {
if (!saveAs && this.app.currentWorkflow) { if (!saveAs && this.app.currentWorkflow) {
this.#saveWorkflow(this.app.currentWorkflow); this.#saveWorkflow(trimJsonExt(this.app.currentWorkflow));
} else { } else {
this.#saveWorkflow(); this.#saveWorkflow();
} }
@ -108,12 +108,11 @@ export class ComfyWorkflowsMenu {
const res = await api.storeUserData("workflows/" + filename, json, { stringify: false, throwOnError: false, overwrite }); const res = await api.storeUserData("workflows/" + filename, json, { stringify: false, throwOnError: false, overwrite });
if (res.status === 409) { if (res.status === 409) {
if (!confirm(`Workflow '${filename}' already exists, do you want to overwrite it?`)) return; 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; this.unsaved = false;
this.app.currentWorkflow = filename; this.app.currentWorkflow = filename;
localStorage.setItem("Comfy.LastWorkflow", filename);
} }
} }
@ -330,6 +329,9 @@ class FileNode {
this.parent.favorites.delete(this.path); this.parent.favorites.delete(this.path);
await this.parent.storeWorkflowsInfo(); await this.parent.storeWorkflowsInfo();
} }
if (this.parent.app.currentWorkflow === this.path) {
this.parent.app.currentWorkflow = null;
}
await api.deleteUserData(fileName); await api.deleteUserData(fileName);
this.remove(); this.remove();
} else { } else {
@ -392,11 +394,27 @@ class FileNode {
tooltip: "Rename this workflow", tooltip: "Rename this workflow",
classList: "comfyui-button comfyui-workflows-file-action", classList: "comfyui-button comfyui-workflows-file-action",
iconSize: 18, iconSize: 18,
action: (e) => { action: async (e) => {
e.stopImmediatePropagation(); e.stopImmediatePropagation();
const newName = prompt("Enter new name", name); const newName = prompt("Enter new name", trimJsonExt(this.path));
if (newName) { if (newName) {
// Rename file // 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, }).element,

View File

@ -1,4 +1,5 @@
import { $el } from "./ui.js"; import { $el } from "./ui.js";
import { api } from "./api.js";
// Simple date formatter // Simple date formatter
const parts = { const parts = {
@ -88,8 +89,8 @@ export async function addStylesheet(urlOrFile, relativeTo) {
} }
/** /**
* @param { string } filename * @param { string } filename
* @param { Blob } blob * @param { Blob } blob
*/ */
export function downloadBlob(filename, blob) { export function downloadBlob(filename, blob) {
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
@ -126,4 +127,17 @@ export function prop(target, name, defaultValue, onChanged) {
}, },
}); });
return defaultValue; return defaultValue;
}
export function getStorageValue(id) {
const clientId = api.clientId ?? api.initialClientId;
return (clientId && sessionStorage.getItem(`${id}:${clientId}`)) ?? localStorage.getItem(id);
}
export function setStorageValue(id, value) {
const clientId = api.clientId ?? api.initialClientId;
if (clientId) {
sessionStorage.setItem(`${id}:${clientId}`, value);
}
localStorage.setItem(id, value);
} }

View File

@ -1,3 +1,5 @@
@import url("scripts/ui/menu/menu.css");
:root { :root {
--fg-color: #000; --fg-color: #000;
--bg-color: #fff; --bg-color: #fff;