Files

1956 lines
78 KiB
JavaScript

import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
import { api } from "../../scripts/api.js";
import { setPromptTextLocked } from "./prompt_text_lock.js";
let promptInputMaskPatched = false;
const AUTO_SELECT_MODEL_OPTION = "Default (auto-select)";
const preferredModelSettingOptions = [AUTO_SELECT_MODEL_OPTION];
const preferredModelBaseTooltip = "Select the preferred model for all modes (text and vision). Leave blank to auto-select.";
function normalizePreferredModelSettingValue(value) {
return value === AUTO_SELECT_MODEL_OPTION || value == null ? "" : String(value);
}
function updatePreferredModelSettingDefinition(definition, models, tooltip) {
preferredModelSettingOptions.splice(0, preferredModelSettingOptions.length, AUTO_SELECT_MODEL_OPTION, ...models);
definition.options = preferredModelSettingOptions;
definition.tooltip = tooltip || preferredModelBaseTooltip;
const registeredDefinition = app?.ui?.settings?.settingsLookup?.[definition.id];
if (registeredDefinition) {
registeredDefinition.options = preferredModelSettingOptions;
registeredDefinition.tooltip = definition.tooltip;
}
const currentValue = app?.ui?.settings?.getSettingValue?.(definition.id);
if (currentValue === "") {
app.ui.settings.setSettingValue(definition.id, AUTO_SELECT_MODEL_OPTION);
}
}
async function refreshPreferredModelOptions(definition) {
try {
const response = await api.fetchApi("/prompt-manager/available-models");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const models = Array.isArray(data?.models)
? data.models.filter(model => typeof model === "string" && model.trim())
: [];
const tooltipParts = [preferredModelBaseTooltip];
const status = typeof data?.status === "string" ? data.status.trim() : "";
if (status && !status.toLowerCase().startsWith("error:")) {
tooltipParts.push(status);
}
updatePreferredModelSettingDefinition(definition, models, tooltipParts.join("\n"));
} catch (error) {
console.error("[PromptManager] Error loading preferred model options:", error);
updatePreferredModelSettingDefinition(definition, [], preferredModelBaseTooltip);
}
}
const nativeModelSettingOptions = [AUTO_SELECT_MODEL_OPTION];
// The native engine's text encoders, shown by file name alone in the
// setting. The Prompt Generator's list follows the same folder: its
// definition for new nodes, and the nodes already on the canvas.
async function refreshNativeModelOptions(definition) {
let models = [];
try {
const response = await api.fetchApi("/prompt-manager/native-models");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
models = (await response.json())?.models ?? [];
} catch (error) {
console.error("[PromptManager] Error loading native model options:", error);
}
const choices = models.map(value => ({ text: value.split(/[\\/]/).pop().replace(/\.safetensors$/i, ""), value }));
nativeModelSettingOptions.splice(0, nativeModelSettingOptions.length, AUTO_SELECT_MODEL_OPTION, ...choices);
definition.options = nativeModelSettingOptions;
const registeredDefinition = app?.ui?.settings?.settingsLookup?.[definition.id];
if (registeredDefinition) registeredDefinition.options = nativeModelSettingOptions;
const values = ["(use default)", ...models];
const spec = globalThis.LiteGraph?.registered_node_types?.PromptGenerator?.nodeData?.input?.optional?.text_encoder;
if (Array.isArray(spec)) spec[0] = values;
for (const node of app.graph?._nodes ?? []) {
const widget = node.type === "PromptGenerator" ? node.widgets?.find(w => w.name === "text_encoder") : null;
if (!widget?.options) continue;
widget.options.values = values;
node._pg?.card.refresh();
}
}
function isTruthyInputFlag(value) {
return value === true || value === 1 || value === "1" || value === "true";
}
function attachPromptInputMaskShim() {
if (promptInputMaskPatched) return;
if (!app || typeof app.graphToPrompt !== "function") return;
promptInputMaskPatched = true;
const originalGraphToPrompt = app.graphToPrompt.bind(app);
app.graphToPrompt = async function (...args) {
const result = await originalGraphToPrompt(...args);
const promptData = result && typeof result === "object"
? (result.output && typeof result.output === "object"
? result.output
: (result.prompt && typeof result.prompt === "object" ? result.prompt : null))
: null;
if (!promptData) return result;
for (const nodeId of Object.keys(promptData)) {
const nodePayload = promptData[nodeId];
if (!nodePayload || typeof nodePayload !== "object") continue;
const classType = String(nodePayload.class_type || nodePayload.type || "");
if (classType !== "PromptManager") continue;
const inputs = nodePayload.inputs;
if (!inputs || typeof inputs !== "object") continue;
const useExternal = isTruthyInputFlag(inputs.use_external);
if (!useExternal && Object.prototype.hasOwnProperty.call(inputs, "llm_input")) {
delete inputs.llm_input;
}
}
return result;
};
}
const preferredModelSetting = {
id: "PromptManager.PreferredModel",
category: ["Prompt Manager", "1. Model Preferences", "Preferred Model"],
name: "Preferred Llama Model",
tooltip: preferredModelBaseTooltip,
type: "combo",
options: preferredModelSettingOptions,
defaultValue: AUTO_SELECT_MODEL_OPTION,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_model", value: normalizePreferredModelSettingValue(value) })
}).catch(error => {
console.error("[PromptManager] Error saving preferred model preference:", error);
});
}
};
const preferredNativeModelSetting = {
id: "PromptManager.PreferredNativeModel",
category: ["Prompt Manager", "1. Model Preferences", "Preferred Native Model"],
name: "Preferred Native Model",
tooltip: "The text encoder the Prompt Generator's native engine uses when its model is '(use default)'. Auto-select takes the first one in the native model folder.",
type: "combo",
options: nativeModelSettingOptions,
defaultValue: AUTO_SELECT_MODEL_OPTION,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_native_model", value: normalizePreferredModelSettingValue(value) })
}).catch(error => {
console.error("[PromptManager] Error saving preferred native model preference:", error);
});
}
};
app.registerExtension({
name: "PromptManager",
settings: [
preferredModelSetting,
preferredNativeModelSetting,
{
id: "PromptManager.HideDownloadableModels",
category: ["Prompt Manager", "1. Model Preferences", "Hide Downloadable Models"],
name: "Hide downloadable built-in models",
tooltip: "When enabled, Prompt Generator dropdowns only show locally available models instead of also listing the built-in HuggingFace download options.",
type: "boolean",
defaultValue: false,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "hide_downloadable_models", value: value })
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving hide-downloadable-models preference:", error);
});
}
},
{
id: "PromptManager.NativeModelFolder",
category: ["Prompt Manager", "1. Model Preferences", "Native Model Folder"],
name: "Native model folder",
tooltip: "Folder in models/text_encoders whose .safetensors the Prompt Generator's native engine lists (any letter case). Default: LLM",
type: "text",
defaultValue: "LLM",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "native_model_folder", value: value })
}).then(() => refreshNativeModelOptions(preferredNativeModelSetting)).catch(error => {
console.error("[PromptManager] Error saving native model folder preference:", error);
});
}
},
{
id: "PromptManager.LlamaPath",
category: ["Prompt Manager", "2. Llama Preferences", "Custom Llama Path"],
name: "Custom Llama Path",
tooltip: "Path to custom Llama installation (Can leave empty if it's defined in your system Path)",
type: "text",
defaultValue: "",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_path", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Llama path preference:", error);
});
}
},
{
id: "PromptManager.ModelPath",
category: ["Prompt Manager", "2. Llama Preferences", "Custom Model Path"],
name: "Custom Model Path",
tooltip: "Path to custom model location (If emtpty, defaults to the models/gguf folder)",
type: "text",
defaultValue: "",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_model_path", value: value })
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving Model path preference:", error);
});
}
},
{
id: "PromptManager.Port",
category: ["Prompt Manager", "2. Llama Preferences", "Port"],
name: "Port",
tooltip: "Port number for the Llama server (default 8080)",
type: "text",
defaultValue: "8080",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_port", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Port preference:", error);
});
}
},
{
id: "PromptManager.CloseLlama",
category: ["Prompt Manager", "3. Exit Preferences", "Close Llama on Exit"],
name: "Close Llama on Exit",
tooltip: "If enabled, will close Llama when ComfyUI exits",
type: "boolean",
defaultValue: true,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "close_llama_on_exit", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Close Llama preference:", error);
});
}
},
{
id: "PromptManager.WarnUnsavedChanges",
category: ["Prompt Manager", "4. Advanced Preferences", "Warn Unsaved Changes"],
name: "Warn about unsaved prompt changes",
tooltip: "Show a warning when switching prompts if the current prompt's text has unsaved changes.",
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.DefaultHideNSFW",
category: ["Prompt Manager", "4. Advanced Preferences", "Hide NSFW by Default"],
name: "Hide NSFW prompts by default",
tooltip: "When enabled, NSFW categories and prompts are hidden in the prompt browser on startup. Can be toggled per session.",
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.EnableThumbnailPreview",
category: ["Prompt Manager", "4. Advanced Preferences", "Enable Thumbnail Hover Preview"],
name: "Enable thumbnail hover preview",
tooltip: "When enabled, hovering over thumbnails in the prompt browser shows a larger preview after a short delay.",
type: "boolean",
defaultValue: false
},
{
id: "PromptManager.CompactPromptBrowser",
category: ["Prompt Manager", "4. Advanced Preferences", "Compact Prompt Browser"],
name: "Use compact prompt browser",
tooltip: "When enabled, the prompt browser dialog uses the smaller legacy size. When disabled (default), it is enlarged to show more thumbnails.",
type: "boolean",
defaultValue: false
},
{
id: "PromptManager.ThumbnailCheckpoint",
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Checkpoint"],
name: "Checkpoint for thumbnail generation",
tooltip: "The checkpoint model used when generating thumbnails via right-click menu. Can also be changed from the prompt context menu.",
type: "text",
defaultValue: ""
},
{
id: "PromptManager.ThumbnailRenderSteps",
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Steps"],
name: "Thumbnail generation steps (per family overrides)",
tooltip: "JSON map of model family -> step count used for thumbnail generation, e.g. {\"sdxl\": 12}. Set from the gear icon in the prompt browser (Steps row). Leave empty to use the hardcoded per-family defaults, or use the Reset button in the picker to revert a family.",
type: "text",
defaultValue: ""
},
{
id: "PromptManager.ThumbnailComposerSeed",
category: ["Prompt Manager", "4. Advanced Preferences", "Composer Thumbnail Seed"],
name: "Static seed for Prompt Composer thumbnail generation",
tooltip: "Seed used by Thumbnail Generator for Prompt Composer Manager categories. Set to 0 to use random seeds instead.",
type: "number",
defaultValue: 42,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "thumbnail_composer_seed", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving composer thumbnail seed preference:", error);
});
}
},
{
id: "PromptManager.LLMBackend",
category: ["Prompt Manager", "5. Ollama Settings", "LLM Backend"],
name: "LLM Backend",
tooltip: "Choose the LLM backend: llama.cpp (local server, default) or Ollama",
type: "combo",
options: ["llama.cpp", "ollama"],
defaultValue: "llama.cpp",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "llm_backend", value: value })
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving LLM backend preference:", error);
});
}
},
{
id: "PromptManager.OllamaUrl",
category: ["Prompt Manager", "5. Ollama Settings", "Ollama URL"],
name: "Ollama URL",
tooltip: "URL of the Ollama server (default: http://127.0.0.1:11434)",
type: "text",
defaultValue: "http://127.0.0.1:11434",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_url", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Ollama URL preference:", error);
});
}
},
{
id: "PromptManager.OllamaKeepAlive",
category: ["Prompt Manager", "5. Ollama Settings", "Keep Alive Duration"],
name: "Keep Alive Duration",
tooltip: "How long Ollama keeps the model loaded in memory after a request. Examples: '5m' (5 minutes), '30m', '1h', '0' (unload immediately), '-1' (keep forever). Default: 5m",
type: "text",
defaultValue: "5m",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_keep_alive", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving Ollama keep alive preference:", error);
});
}
}
],
async setup() {
// Load settings from ComfyUI and sync to Python cache
try {
// Sync current values to Python cache first
const preferredModel = normalizePreferredModelSettingValue(app.ui.settings.getSettingValue("PromptManager.PreferredModel"));
const hideDownloadableModels = app.ui.settings.getSettingValue("PromptManager.HideDownloadableModels");
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath");
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath");
const port = app.ui.settings.getSettingValue("PromptManager.Port");
const CloseLlama = app.ui.settings.getSettingValue("PromptManager.CloseLlama");
const llmBackend = app.ui.settings.getSettingValue("PromptManager.LLMBackend");
const ollamaUrl = app.ui.settings.getSettingValue("PromptManager.OllamaUrl");
const ollamaKeepAlive = app.ui.settings.getSettingValue("PromptManager.OllamaKeepAlive");
console.log("[PromptManager] Syncing preferences:", { preferredModel, hideDownloadableModels, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_model", value: preferredModel })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "hide_downloadable_models", value: hideDownloadableModels === true })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_path", value: llamaPath })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_model_path", value: modelPath })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_port", value: port })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "close_llama_on_exit", value: CloseLlama })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "llm_backend", value: llmBackend })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_url", value: ollamaUrl })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_keep_alive", value: ollamaKeepAlive })
});
const nativeFolder = app.ui.settings.getSettingValue("PromptManager.NativeModelFolder") || "LLM";
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "native_model_folder", value: nativeFolder })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_native_model", value: normalizePreferredModelSettingValue(app.ui.settings.getSettingValue("PromptManager.PreferredNativeModel")) })
});
await refreshNativeModelOptions(preferredNativeModelSetting);
await refreshPreferredModelOptions(preferredModelSetting);
} catch (error) {
console.error("[PromptManager] Error syncing preferences:", error);
await refreshPreferredModelOptions(preferredModelSetting);
await refreshNativeModelOptions(preferredNativeModelSetting);
}
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PromptManager") {
attachPromptInputMaskShim();
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
const node = this;
node.prompts = {};
// Set initial size to be square (400x400)
this.setSize([400, 400]);
// Change widget labels
const promptTextWidget = this.widgets.find(w => w.name === "text");
if (promptTextWidget) {
promptTextWidget.label = "prompt";
}
const promptNameWidget = this.widgets.find(w => w.name === "name");
if (promptNameWidget) {
promptNameWidget.label = "name";
}
const useExternalWidget = this.widgets.find(w => w.name === "use_external");
if (useExternalWidget) {
useExternalWidget.label = "use llm input";
}
// Make text widget scrollable even when read-only
if (promptTextWidget && promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
}
// Listen for text updates from backend (when connected inputs change or toggle changes)
api.addEventListener("prompt-manager-update-text", (event) => {
if (String(event.detail.node_id) === String(this.id)) {
if (promptTextWidget) {
const useExternal = event.detail.use_external || false;
const llmInput = event.detail.llm_input || "";
if (useExternal && llmInput) {
// When using external, display the LLM input text (read-only, ghosted)
promptTextWidget.value = llmInput;
setPromptTextLocked(promptTextWidget, true);
} else {
setPromptTextLocked(promptTextWidget, false);
}
this.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
}
});
// IMPORTANT: Add DOM widgets SYNCHRONOUSLY during node creation
// to ensure proper positioning and rendering within the node bounds
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
// Load prompts asynchronously (data only, not widgets)
loadPrompts(node).then(() => {
filterPromptDropdown(node, { preserveDanglingSelection: true });
// Ensure height is sufficient after data is loaded
setTimeout(() => {
const computedSize = node.computeSize();
const minHeight = Math.max(400, computedSize[1] + 20);
if (node.size[1] < minHeight) {
node.setSize([Math.max(400, node.size[0]), minHeight]);
}
app.graph.setDirtyCanvas(true, true);
}, 100);
});
return result;
};
// Handle node reconfiguration when ComfyUI refreshes
const onConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function(info) {
const result = onConfigure?.apply(this, arguments);
const node = this;
// Mark workflow restore so async onNodeCreated load does not coerce selection.
node._configuredFromWorkflow = true;
node._restoringFromWorkflow = true;
// Reload prompts from server and reapply filtering
setTimeout(() => {
loadPrompts(node).then(() => {
try {
filterPromptDropdown(node, { preserveDanglingSelection: true });
// Reattach button bar if needed
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
}
} finally {
node._restoringFromWorkflow = false;
}
});
}, 100);
return result;
};
// Draw red NSFW badge at the top of the node when NSFW content is selected
const onDrawForeground = nodeType.prototype.onDrawForeground;
nodeType.prototype.onDrawForeground = function(ctx) {
if (onDrawForeground) onDrawForeground.apply(this, arguments);
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
if (hideNSFW || !this.prompts) return;
const categoryWidget = this.widgets?.find(w => w.name === "category");
const promptWidget = this.widgets?.find(w => w.name === "name");
if (!categoryWidget || !promptWidget) return;
const category = categoryWidget.value;
const promptName = promptWidget.value;
const catIsNSFW = this.prompts[category]?.["__meta__"]?.nsfw === true;
const promptIsNSFW = this.prompts[category]?.[promptName]?.nsfw === true;
if (catIsNSFW || promptIsNSFW) {
ctx.save();
// Draw red "NSFW" badge at top-right of node
const text = "NSFW";
ctx.font = "bold 8px sans-serif";
const textWidth = ctx.measureText(text).width;
const badgeW = textWidth + 8;
const badgeH = 12;
const badgeX = this.size[0] - badgeW - 4;
const badgeY = -LiteGraph.NODE_TITLE_HEIGHT + (LiteGraph.NODE_TITLE_HEIGHT - badgeH) / 2;
// Badge background
ctx.fillStyle = "rgba(204, 50, 50, 0.85)";
ctx.beginPath();
if (ctx.roundRect) {
ctx.roundRect(badgeX, badgeY, badgeW, badgeH, 2);
} else {
ctx.rect(badgeX, badgeY, badgeW, badgeH);
}
ctx.fill();
// Badge text
ctx.fillStyle = "#fff";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, badgeX + badgeW / 2, badgeY + badgeH / 2);
ctx.restore();
}
};
// Enforce minimum node width
const onResize = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResize ? onResize.apply(this, arguments) : size;
};
}
}
});
async function loadPrompts(node) {
try {
const response = await fetch("/prompt-manager/get-prompts");
const data = await response.json();
node.prompts = data;
return data;
} catch (error) {
console.error("[PromptManager] Error loading prompts:", error);
return {};
}
}
/**
* Check if there are unsaved changes in the prompt
*/
function hasUnsavedChanges(node) {
// New unsaved prompt always has unsaved changes
if (node.isNewUnsavedPrompt) {
return true;
}
// For basic PromptManager, check if text differs from saved
const textWidget = node.widgets?.find(w => w.name === "text");
const categoryWidget = node.widgets?.find(w => w.name === "category");
const promptWidget = node.widgets?.find(w => w.name === "name");
if (!textWidget || !categoryWidget || !promptWidget) {
return false;
}
const currentText = textWidget.value || "";
const category = categoryWidget.value;
const promptName = promptWidget.value;
// If no saved prompt exists, no unsaved changes (unless it's a new prompt)
if (!node.prompts || !node.prompts[category] || !node.prompts[category][promptName]) {
return false;
}
const savedPrompt = node.prompts[category][promptName];
const savedText = savedPrompt?.prompt || "";
return currentText !== savedText;
}
function filterPromptDropdown(node, options = {}) {
const preserveDanglingSelection = options?.preserveDanglingSelection === true;
// Filter name dropdown to only show prompts from current category
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
if (categoryWidget && promptWidget) {
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
// Filter NSFW categories from the category dropdown
if (node.prompts) {
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
const currentCategoryValue = String(categoryWidget.value || "");
if (hideNSFW) {
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
}
let categoryOptions = categories.length > 0 ? [...categories] : ["Default"];
if (preserveDanglingSelection && currentCategoryValue && !categoryOptions.includes(currentCategoryValue)) {
categoryOptions = [currentCategoryValue, ...categoryOptions];
}
categoryWidget.options.values = categoryOptions;
// If current category is now hidden, switch only when we are not preserving
// workflow-restored dangling selections.
if (!categoryOptions.includes(categoryWidget.value) && categories.length > 0) {
categoryWidget.value = categories[0];
}
}
const currentCategory = categoryWidget.value;
if (node.prompts[currentCategory]) {
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
const catIsNSFW = node.prompts[currentCategory]?.["__meta__"]?.nsfw === true;
if (catIsNSFW) {
promptNames = [];
} else {
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
}
}
const currentPromptValue = String(promptWidget.value || "");
if (preserveDanglingSelection && currentPromptValue && !promptNames.includes(currentPromptValue)) {
promptNames = [currentPromptValue, ...promptNames];
}
if (promptNames.length === 0) {
promptNames.push("");
}
promptWidget.options.values = promptNames;
}
}
}
function addButtonBar(node) {
if (node.buttonBarAttached) {
return;
}
const textWidget = node.widgets.find(w => w.name === "text");
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
// Create button container with proper styling for DOM widget
const buttonContainer = document.createElement("div");
buttonContainer.style.display = "flex";
buttonContainer.style.gap = "4px";
buttonContainer.style.padding = "2px 4px 4px 4px";
buttonContainer.style.flexWrap = "nowrap";
buttonContainer.style.marginTop = "-10px";
buttonContainer.style.width = "100%";
buttonContainer.style.boxSizing = "border-box";
buttonContainer.style.position = "relative";
// Save Prompt button with category selection
const savePromptBtn = createButton("Save Prompt", async () => {
const categories = Object.keys(node.prompts || {}).sort((a, b) => a.localeCompare(b));
const currentCategory = categoryWidget.value;
const result = await showPromptWithCategory(
"Save Prompt",
"Enter prompt name:",
promptWidget.value || "New Prompt",
categories,
currentCategory
);
if (result && result.name && result.name.trim()) {
const promptName = result.name.trim();
const targetCategory = result.category;
const promptText = textWidget.value;
if (!promptText || !promptText.trim()) {
await showInfo("Empty Prompt", "Prompt text cannot be empty");
return;
}
// Case-insensitive check for existing prompt
let existingPromptName = null;
if (node.prompts[targetCategory]) {
const existingNames = Object.keys(node.prompts[targetCategory]).filter(k => k !== '__meta__');
existingPromptName = existingNames.find(name => name.toLowerCase() === promptName.toLowerCase());
}
// Ask for confirmation before overwriting existing prompt
if (existingPromptName) {
const confirmed = await showConfirm(
"Overwrite Prompt",
`Prompt "${existingPromptName}" already exists in category "${targetCategory}". Do you want to overwrite it?`,
"Overwrite",
"#f80"
);
if (!confirmed) {
return;
}
}
await savePrompt(node, targetCategory, promptName, promptText.trim());
// Clear new prompt flag since it's now saved
node.isNewUnsavedPrompt = false;
node.newPromptCategory = null;
node.newPromptName = null;
// Update UI to show the saved prompt
categoryWidget.value = targetCategory;
filterPromptDropdown(node);
promptWidget.value = promptName;
}
});
// New Prompt button - simply clears fields for a fresh start
const newPromptBtn = createButton("New Prompt", async () => {
// Check for unsaved changes before creating new prompt
const hasUnsaved = hasUnsavedChanges(node);
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.WarnUnsavedChanges");
if (hasUnsaved && warnEnabled) {
const confirmed = await showConfirm(
"Unsaved Changes",
"You have unsaved changes to the current prompt. Do you want to discard them and start fresh?",
"Discard & Continue",
"#f80"
);
if (!confirmed) {
return;
}
}
// Keep the current category, just clear the prompt selection and content
const currentCategory = categoryWidget.value;
// Clear prompt selection (set to empty/placeholder)
promptWidget.value = "";
textWidget.value = "";
// Update previous values for cancel/revert
node._previousCategory = currentCategory;
node._previousPrompt = "";
// Mark as new unsaved prompt state
node.isNewUnsavedPrompt = true;
node.newPromptCategory = currentCategory;
node.newPromptName = null;
// Clear the last saved state since this is a brand new prompt
node.lastSavedState = null;
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
});
// More dropdown button
const moreBtn = createDropdownButton("More ▼", [
{
label: "New Category",
action: async () => {
const categoryName = await showTextPrompt("New Category", "Enter new category name:");
if (categoryName && categoryName.trim()) {
let existingCategoryName = null;
if (node.prompts) {
const existingCategories = Object.keys(node.prompts);
existingCategoryName = existingCategories.find(cat => cat.toLowerCase() === categoryName.trim().toLowerCase());
}
if (existingCategoryName) {
await showInfo(
"Category Exists",
`Category already exists as "${existingCategoryName}".`
);
return;
}
await createCategory(node, categoryName.trim());
}
}
},
{
label: "Delete Category",
action: async () => {
if (await showConfirm("Delete Category", `Are you sure you want to delete category "${categoryWidget.value}" and all its prompts?`)) {
await deleteCategory(node, categoryWidget.value);
}
}
},
{
label: "Delete Prompt",
action: async () => {
if (await showConfirm("Delete Prompt", `Are you sure you want to delete prompt "${promptWidget.value}"?`)) {
await deletePrompt(node, categoryWidget.value, promptWidget.value);
}
}
},
{ divider: true },
{
label: "Export JSON",
action: async () => {
await exportPromptsJSON(node);
}
},
{
label: "Import JSON",
action: async () => {
await importPromptsJSON(node, "merge");
}
},
{
label: "Replace JSON",
action: async () => {
await importPromptsJSON(node, "replace");
}
}
]);
buttonContainer.appendChild(savePromptBtn);
buttonContainer.appendChild(newPromptBtn);
buttonContainer.appendChild(moreBtn);
// Add button bar to node with proper options to avoid clipping issues
const htmlWidget = node.addDOMWidget("buttons", "div", buttonContainer, {
hideOnZoom: true,
serialize: false
});
htmlWidget.computeSize = function(width) {
return [width, 36];
};
// Nodes 2.0 stretches DOM widgets that expose computeLayoutSize; keep this row fixed-height.
htmlWidget.computeLayoutSize = undefined;
node.buttonBarAttached = true;
}
function setupCategoryChangeHandler(node) {
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
const textWidget = node.widgets.find(w => w.name === "text");
const useExternalWidget = node.widgets.find(w => w.name === "use_external");
if (!categoryWidget || !promptWidget || !textWidget) return;
const originalCallback = categoryWidget.callback;
// Update prompt dropdown when category changes
categoryWidget.callback = async function(value) {
if (node._restoringFromWorkflow) {
if (originalCallback) {
originalCallback.apply(this, arguments);
}
return;
}
if (originalCallback) {
originalCallback.apply(this, arguments);
}
// Reload prompts from server to get latest changes from other tabs
await loadPrompts(node);
const category = value;
if (node.prompts && node.prompts[category]) {
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
}
promptWidget.options.values = promptNames;
// Only update the text widget if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (promptNames.length > 0) {
promptWidget.value = promptNames[0];
if (!useExternal) {
const promptData = node.prompts[category][promptNames[0]];
textWidget.value = promptData?.prompt || "";
}
} else {
promptWidget.value = "";
if (!useExternal) {
textWidget.value = "";
}
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
};
const originalPromptCallback = promptWidget.callback;
// Update text widget when prompt selection changes
promptWidget.callback = async function(value) {
if (node._restoringFromWorkflow) {
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
return;
}
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
// Reload prompts from server to get latest changes from other tabs
await loadPrompts(node);
const category = categoryWidget.value;
// Update prompt dropdown options in case prompts were deleted/added in another tab
if (node.prompts && node.prompts[category]) {
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
let promptNames = Object.keys(node.prompts[category]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
promptNames = promptNames.filter(name => !node.prompts[category][name]?.nsfw);
}
promptWidget.options.values = promptNames.length > 0 ? promptNames : [""];
// Check if selected prompt still exists after reload
if (!promptNames.includes(value)) {
// Prompt was deleted in another tab, switch to first available
value = promptNames.length > 0 ? promptNames[0] : "";
promptWidget.value = value;
}
}
// Only update text if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (!useExternal) {
if (node.prompts && node.prompts[category] && node.prompts[category][value]) {
const promptData = node.prompts[category][value];
textWidget.value = promptData?.prompt || "";
}
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
};
// Prevent ComfyUI from setting all prompts instead of filtered category prompts
Object.defineProperty(promptWidget.options, 'values', {
get: function() {
return this._values;
},
set: function(newValues) {
this._values = newValues;
// Re-filter if ComfyUI tries to set the master list of all prompts
if (node.prompts && categoryWidget && newValues && newValues.length > 0) {
const currentCategory = categoryWidget.value;
if (node.prompts[currentCategory]) {
const categoryPrompts = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__');
const hasOtherCategoryPrompts = newValues.some(val =>
val !== "" && !categoryPrompts.includes(val)
);
if (hasOtherCategoryPrompts) {
setTimeout(() => {
filterPromptDropdown(node, { preserveDanglingSelection: node._restoringFromWorkflow === true });
}, 50);
}
}
}
},
enumerable: true,
configurable: true
});
promptWidget.options._values = promptWidget.options.values || [];
}
function setupUseExternalToggleHandler(node) {
const textWidget = node.widgets?.find(w => w.name === "text");
const useExternalWidget = node.widgets?.find(w => w.name === "use_external");
const categoryWidget = node.widgets?.find(w => w.name === "category");
const promptWidget = node.widgets?.find(w => w.name === "name");
if (!textWidget || !useExternalWidget) return;
// Apply initial state on load/reload
const applyToggleState = (value) => {
const llmInputConnection = node.inputs?.find(inp => inp.name === "llm_input");
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
if (value && isLlmConnected) {
// Using LLM and it's connected - make text widget read-only (ghosted)
setPromptTextLocked(textWidget, true);
// Try to show LLM value if available
const graph = app.graph;
const link = graph.links[llmInputConnection.link];
if (link) {
const originNode = graph.getNodeById(link.origin_id);
if (originNode) {
// Try to get the output value from the origin node
const outputData = originNode.getOutputData?.(link.origin_slot);
if (outputData !== undefined) {
textWidget.value = outputData;
} else if (originNode.widgets) {
// Fallback: try to find widget with matching output
const outputWidget = originNode.widgets.find(w => w.name === "text" || w.name === "STRING");
if (outputWidget) {
textWidget.value = outputWidget.value;
}
}
}
}
} else {
// Using internal text - enable widget but keep current text (which may be LLM output)
setPromptTextLocked(textWidget, false);
}
};
// Apply initial state when the handler is set up
applyToggleState(useExternalWidget.value);
const originalCallback = useExternalWidget.callback;
useExternalWidget.callback = function(value) {
// Check if llm_input is connected
const llmInputConnection = node.inputs?.find(inp => inp.name === "llm_input");
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
// Prevent turning on if nothing is connected
if (value && !isLlmConnected) {
useExternalWidget.value = false;
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
return;
}
if (originalCallback) {
originalCallback.apply(this, arguments);
}
applyToggleState(value);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
};
}
function createButton(text, callback) {
const button = document.createElement("button");
button.textContent = text;
button.style.flex = "1";
button.style.minWidth = "80px";
button.style.padding = "6px 8px";
button.style.cursor = "pointer";
button.style.backgroundColor = "#222";
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "13px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.overflow = "hidden";
button.style.textOverflow = "ellipsis";
button.style.lineHeight = "normal";
button.style.textAlign = "center";
button.style.height = "28px";
button.style.display = "flex";
button.style.alignItems = "center";
button.style.justifyContent = "center";
button.onclick = callback;
return button;
}
function createDropdownButton(text, items) {
const container = document.createElement("div");
container.style.position = "relative";
container.style.flex = "1";
container.style.minWidth = "80px";
const button = document.createElement("button");
button.textContent = text;
button.style.width = "100%";
button.style.padding = "6px 8px";
button.style.cursor = "pointer";
button.style.backgroundColor = "#222";
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "13px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.height = "28px";
button.style.display = "flex";
button.style.alignItems = "center";
button.style.justifyContent = "center";
// Create dropdown and append to body to escape stacking context issues
const dropdown = document.createElement("div");
dropdown.style.cssText = `
position: fixed;
background: #2a2a2a;
border: 1px solid #555;
border-radius: 6px;
z-index: 999999;
display: none;
box-shadow: 0 4px 12px rgba(0,0,0,0.5);
min-width: 140px;
`;
document.body.appendChild(dropdown);
items.forEach(item => {
if (item.divider) {
const divider = document.createElement("div");
divider.style.cssText = "height: 1px; background: #444; margin: 4px 0;";
dropdown.appendChild(divider);
} else {
const menuItem = document.createElement("div");
menuItem.textContent = item.label;
menuItem.style.cssText = `
padding: 8px 12px;
cursor: pointer;
font-size: 13px;
color: #fff;
white-space: nowrap;
`;
menuItem.addEventListener("mouseenter", () => {
menuItem.style.backgroundColor = "#4a4a4a";
});
menuItem.addEventListener("mouseleave", () => {
menuItem.style.backgroundColor = "transparent";
});
menuItem.addEventListener("click", (e) => {
e.stopPropagation();
dropdown.style.display = "none";
item.action();
});
dropdown.appendChild(menuItem);
}
});
button.addEventListener("click", (e) => {
e.stopPropagation();
const isVisible = dropdown.style.display === "block";
if (isVisible) {
dropdown.style.display = "none";
} else {
// Position dropdown below the button
const rect = button.getBoundingClientRect();
dropdown.style.left = rect.left + "px";
dropdown.style.top = (rect.bottom + 2) + "px";
dropdown.style.display = "block";
}
});
// Close dropdown when clicking elsewhere
document.addEventListener("click", (e) => {
if (!dropdown.contains(e.target) && e.target !== button) {
dropdown.style.display = "none";
}
});
container.appendChild(button);
return container;
}
function showPromptWithCategory(title, message, defaultName, categories, defaultCategory) {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 320px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
// Build category options
const categoryOptions = categories.map(cat =>
`<option value="${cat}" ${cat === defaultCategory ? 'selected' : ''}>${cat}</option>`
).join('');
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 6px; color: #aaa; font-size: 14px;">Category:</div>
<select style="width: 100%; padding: 8px; margin-bottom: 12px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px;">
${categoryOptions}
</select>
<div style="margin-bottom: 6px; color: #aaa; font-size: 14px;">${message}</div>
<input type="text" value="${defaultName}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px; box-sizing: border-box;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
</div>
`;
const selectEl = dialog.querySelector("select");
const input = dialog.querySelector("input");
const okBtn = dialog.querySelector(".ok-btn");
const cancelBtn = dialog.querySelector(".cancel-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
const handleOk = () => {
resolve({ name: input.value, category: selectEl.value });
cleanup();
};
const handleCancel = () => {
resolve(null);
cleanup();
};
okBtn.onclick = handleOk;
cancelBtn.onclick = handleCancel;
overlay.onclick = handleCancel;
input.onkeydown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
handleOk();
} else if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
handleCancel();
}
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
input.focus();
input.select();
});
}
async function exportPromptsJSON(node) {
try {
const response = await fetch("/prompt-manager/get-prompts");
const data = await response.json();
const jsonStr = JSON.stringify(data, null, 2);
const blob = new Blob([jsonStr], { type: "application/json" });
// Try File System Access API first (works on localhost and https)
if (window.showSaveFilePicker) {
try {
const handle = await window.showSaveFilePicker({
suggestedName: "prompt_manager_data.json",
types: [{
description: "JSON Files",
accept: { "application/json": [".json"] }
}]
});
const writable = await handle.createWritable();
await writable.write(blob);
await writable.close();
await showInfo("Export Complete", "Prompts exported successfully!");
return;
} catch (err) {
// User cancelled the dialog
if (err.name === "AbortError") {
return;
}
// Fall back to download method if API fails
console.log("[PromptManager] Save picker failed, falling back to download:", err);
}
}
// Fallback: Prompt user for filename, then download
const filename = await showTextPrompt(
"Export Prompts",
"Enter filename for export:",
"prompt_manager_data.json"
);
if (!filename) {
return; // User cancelled
}
const finalFilename = filename.endsWith(".json") ? filename : filename + ".json";
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = finalFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
await showInfo("Export Complete", "Prompts exported successfully!");
} catch (error) {
console.error("[PromptManager] Error exporting prompts:", error);
await showInfo("Error", "Failed to export prompts");
}
}
async function importPromptsJSON(node, importMode = "merge") {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) {
resolve(false);
return;
}
try {
const text = await file.text();
const importedData = JSON.parse(text);
// Validate structure
if (typeof importedData !== 'object' || Array.isArray(importedData)) {
await showInfo("Error", "Invalid JSON structure. Expected an object with categories.");
resolve(false);
return;
}
// Send to backend
const response = await fetch("/prompt-manager/import-prompts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
data: importedData,
mode: importMode
})
});
const result = await response.json();
if (result.success) {
node.prompts = result.prompts;
updateDropdowns(node);
// Refresh the current prompt text
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
const textWidget = node.widgets.find(w => w.name === "text");
if (categoryWidget && promptWidget && textWidget) {
const category = categoryWidget.value;
const promptName = promptWidget.value;
if (node.prompts[category] && node.prompts[category][promptName]) {
textWidget.value = node.prompts[category][promptName].prompt || "";
}
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
await showInfo(importMode === "replace" ? "Replace Complete" : "Import Complete", importMode === "replace" ? "Successfully replaced prompts!" : "Successfully imported prompts!");
resolve(true);
} else {
await showInfo("Error", result.error || (importMode === "replace" ? "Failed to replace prompts" : "Failed to import prompts"));
resolve(false);
}
} catch (error) {
console.error("[PromptManager] Error importing prompts:", error);
await showInfo("Error", "Failed to parse JSON file");
resolve(false);
}
};
input.click();
});
}
function showImportOptions() {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 320px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">Import Prompts</div>
<div style="margin-bottom: 20px; color: #ccc;">How do you want to import?<br><br>
<strong>Merge:</strong> Keep existing prompts, add/update from import<br>
<strong>Replace:</strong> Delete all existing, use import only
</div>
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="replace-btn" style="padding: 8px 16px; background: #c00; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Replace</button>
<button class="merge-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Merge</button>
</div>
`;
const mergeBtn = dialog.querySelector(".merge-btn");
const replaceBtn = dialog.querySelector(".replace-btn");
const cancelBtn = dialog.querySelector(".cancel-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
mergeBtn.onclick = () => {
resolve("merge");
cleanup();
};
replaceBtn.onclick = () => {
resolve("replace");
cleanup();
};
cancelBtn.onclick = () => {
resolve(null);
cleanup();
};
overlay.onclick = () => {
resolve(null);
cleanup();
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
mergeBtn.focus();
});
}
function showTextPrompt(title, message, defaultValue = "") {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 300px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 10px; color: #ccc;">${message}</div>
<input type="text" value="${defaultValue}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
</div>
`;
const input = dialog.querySelector("input");
const okBtn = dialog.querySelector(".ok-btn");
const cancelBtn = dialog.querySelector(".cancel-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
const handleOk = () => {
resolve(input.value);
cleanup();
};
const handleCancel = () => {
resolve(null);
cleanup();
};
okBtn.onclick = handleOk;
cancelBtn.onclick = handleCancel;
overlay.onclick = handleCancel;
input.onkeydown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
handleOk();
} else if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
handleCancel();
}
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
input.focus();
input.select();
});
}
function showConfirm(title, message, confirmText = "Delete", confirmColor = "#c00") {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 300px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 20px; color: #ccc;">${message}</div>
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: ${confirmColor}; color: #fff; border: none; border-radius: 4px; cursor: pointer;">${confirmText}</button>
</div>
`;
const okBtn = dialog.querySelector(".ok-btn");
const cancelBtn = dialog.querySelector(".cancel-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
okBtn.onclick = () => {
resolve(true);
cleanup();
};
cancelBtn.onclick = () => {
resolve(false);
cleanup();
};
overlay.onclick = () => {
resolve(false);
cleanup();
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
okBtn.focus();
});
}
function showInfo(title, message) {
return new Promise((resolve) => {
const dialog = document.createElement("div");
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #222;
border: 2px solid #444;
border-radius: 8px;
padding: 20px;
z-index: 10000;
min-width: 300px;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
`;
const overlay = document.createElement("div");
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 9999;
`;
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 20px; color: #ccc;">${message}</div>
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
</div>
`;
const okBtn = dialog.querySelector(".ok-btn");
const cleanup = () => {
document.body.removeChild(overlay);
document.body.removeChild(dialog);
};
okBtn.onclick = () => {
resolve(true);
cleanup();
};
overlay.onclick = () => {
resolve(true);
cleanup();
};
document.body.appendChild(overlay);
document.body.appendChild(dialog);
okBtn.focus();
});
}
function updateDropdowns(node) {
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
const textWidget = node.widgets.find(w => w.name === "text");
if (!categoryWidget || !promptWidget || !textWidget) return;
// Update category dropdown (sorted alphabetically)
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
}
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
if (!node.prompts[categoryWidget.value] && categories.length > 0) {
categoryWidget.value = categories[0];
}
// Update prompt dropdown for current category (sorted alphabetically)
const currentCategory = categoryWidget.value;
if (node.prompts[currentCategory]) {
let promptNames = Object.keys(node.prompts[currentCategory]).filter(k => k !== '__meta__').sort((a, b) => a.localeCompare(b));
if (hideNSFW) {
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
}
if (promptNames.length === 0) {
promptNames.push("");
}
promptWidget.options.values = promptNames;
if (!node.prompts[currentCategory][promptWidget.value] && promptNames.length > 0) {
promptWidget.value = promptNames[0];
}
if (promptWidget.value && node.prompts[currentCategory][promptWidget.value]) {
const promptData = node.prompts[currentCategory][promptWidget.value];
textWidget.value = promptData?.prompt || "";
} else {
textWidget.value = "";
}
} else {
promptWidget.options.values = [""];
promptWidget.value = "";
textWidget.value = "";
}
}
async function createCategory(node, categoryName) {
try {
const response = await fetch("/prompt-manager/save-category", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category_name: categoryName })
});
const data = await response.json();
if (data.success) {
node.prompts = data.prompts;
// Select the newly created category
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
const textWidget = node.widgets.find(w => w.name === "text");
if (categoryWidget) {
categoryWidget.value = categoryName;
}
if (promptWidget) {
promptWidget.value = "";
}
if (textWidget) {
textWidget.value = "";
}
updateDropdowns(node);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
await showInfo("Error", data.error);
}
} catch (error) {
console.error("[PromptManager] Error creating category:", error);
await showInfo("Error", "Error creating category");
}
}
async function savePrompt(node, category, name, text) {
try {
const response = await fetch("/prompt-manager/save-prompt", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category: category,
name: name,
text: text
})
});
const data = await response.json();
if (data.success) {
node.prompts = data.prompts;
updateDropdowns(node);
// Select the newly saved prompt
const promptWidget = node.widgets.find(w => w.name === "name");
if (promptWidget) {
promptWidget.value = name;
updateDropdowns(node);
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
await showInfo("Error", data.error || "Failed to save prompt");
}
} catch (error) {
console.error("[PromptManager] Error saving prompt:", error);
await showInfo("Error", "Failed to save prompt");
}
}
async function deleteCategory(node, category) {
try {
const response = await fetch("/prompt-manager/delete-category", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category: category })
});
const data = await response.json();
if (data.success) {
node.prompts = data.prompts;
updateDropdowns(node);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
await showInfo("Error", data.error || "Failed to delete category");
}
} catch (error) {
console.error("[PromptManager] Error deleting category:", error);
await showInfo("Error", "Failed to delete category");
}
}
async function deletePrompt(node, category, name) {
try {
const response = await fetch("/prompt-manager/delete-prompt", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category: category,
name: name
})
});
const data = await response.json();
if (data.success) {
node.prompts = data.prompts;
updateDropdowns(node);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
} else {
await showInfo("Error", data.error || "Failed to delete prompt");
}
} catch (error) {
console.error("[PromptManager] Error deleting prompt:", error);
await showInfo("Error", "Failed to delete prompt");
}
}
console.log("[PromptManager] Extension loaded");